Plugins: Add exercise signature see BT#17896

pull/3588/head
Julio Montoya 6 years ago
parent fc0059fc2c
commit 7816eda91c
  1. 521
      app/Resources/public/assets/signature_pad/signature_pad.umd.js
  2. 5
      main/exercise/exercise.class.php
  3. 29
      main/exercise/result.php
  4. 39
      main/inc/ajax/exercise.ajax.php
  5. 20
      main/inc/lib/exercise.lib.php
  6. 4
      main/inc/lib/extra_field.lib.php
  7. 20
      main/template/default/exercise/partials/result_exercise.tpl
  8. 98
      main/template/default/exercise/result.tpl
  9. 1
      plugin/exercise_signature/README.md
  10. 1
      plugin/exercise_signature/index.php
  11. 9
      plugin/exercise_signature/install.php
  12. 10
      plugin/exercise_signature/lang/english.php
  13. 10
      plugin/exercise_signature/lang/french.php
  14. 10
      plugin/exercise_signature/lang/spanish.php
  15. 171
      plugin/exercise_signature/lib/ExerciseSignature.php
  16. 5
      plugin/exercise_signature/plugin.php
  17. 9
      plugin/exercise_signature/uninstall.php
  18. 1
      src/Chamilo/CoreBundle/Entity/ExtraField.php

@ -0,0 +1,521 @@
/*!
* Signature Pad v3.0.0-beta.3 | https://github.com/szimek/signature_pad
* (c) 2018 Szymon Nowak | Released under the MIT license
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.SignaturePad = factory());
}(this, (function () { 'use strict';
var Point = (function () {
function Point(x, y, time) {
this.x = x;
this.y = y;
this.time = time || Date.now();
}
Point.prototype.distanceTo = function (start) {
return Math.sqrt(Math.pow(this.x - start.x, 2) + Math.pow(this.y - start.y, 2));
};
Point.prototype.equals = function (other) {
return this.x === other.x && this.y === other.y && this.time === other.time;
};
Point.prototype.velocityFrom = function (start) {
return (this.time !== start.time) ? this.distanceTo(start) / (this.time - start.time) : 0;
};
return Point;
}());
var Bezier = (function () {
function Bezier(startPoint, control2, control1, endPoint, startWidth, endWidth) {
this.startPoint = startPoint;
this.control2 = control2;
this.control1 = control1;
this.endPoint = endPoint;
this.startWidth = startWidth;
this.endWidth = endWidth;
}
Bezier.fromPoints = function (points, widths) {
var c2 = this.calculateControlPoints(points[0], points[1], points[2]).c2;
var c3 = this.calculateControlPoints(points[1], points[2], points[3]).c1;
return new Bezier(points[1], c2, c3, points[2], widths.start, widths.end);
};
Bezier.calculateControlPoints = function (s1, s2, s3) {
var dx1 = s1.x - s2.x;
var dy1 = s1.y - s2.y;
var dx2 = s2.x - s3.x;
var dy2 = s2.y - s3.y;
var m1 = { x: (s1.x + s2.x) / 2.0, y: (s1.y + s2.y) / 2.0 };
var m2 = { x: (s2.x + s3.x) / 2.0, y: (s2.y + s3.y) / 2.0 };
var l1 = Math.sqrt((dx1 * dx1) + (dy1 * dy1));
var l2 = Math.sqrt((dx2 * dx2) + (dy2 * dy2));
var dxm = (m1.x - m2.x);
var dym = (m1.y - m2.y);
var k = l2 / (l1 + l2);
var cm = { x: m2.x + (dxm * k), y: m2.y + (dym * k) };
var tx = s2.x - cm.x;
var ty = s2.y - cm.y;
return {
c1: new Point(m1.x + tx, m1.y + ty),
c2: new Point(m2.x + tx, m2.y + ty)
};
};
Bezier.prototype.length = function () {
var steps = 10;
var length = 0;
var px;
var py;
for (var i = 0; i <= steps; i += 1) {
var t = i / steps;
var cx = this.point(t, this.startPoint.x, this.control1.x, this.control2.x, this.endPoint.x);
var cy = this.point(t, this.startPoint.y, this.control1.y, this.control2.y, this.endPoint.y);
if (i > 0) {
var xdiff = cx - px;
var ydiff = cy - py;
length += Math.sqrt((xdiff * xdiff) + (ydiff * ydiff));
}
px = cx;
py = cy;
}
return length;
};
Bezier.prototype.point = function (t, start, c1, c2, end) {
return (start * (1.0 - t) * (1.0 - t) * (1.0 - t))
+ (3.0 * c1 * (1.0 - t) * (1.0 - t) * t)
+ (3.0 * c2 * (1.0 - t) * t * t)
+ (end * t * t * t);
};
return Bezier;
}());
function throttle(fn, wait) {
if (wait === void 0) { wait = 250; }
var previous = 0;
var timeout = null;
var result;
var storedContext;
var storedArgs;
var later = function () {
previous = Date.now();
timeout = null;
result = fn.apply(storedContext, storedArgs);
if (!timeout) {
storedContext = null;
storedArgs = [];
}
};
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var now = Date.now();
var remaining = wait - (now - previous);
storedContext = this;
storedArgs = args;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = fn.apply(storedContext, storedArgs);
if (!timeout) {
storedContext = null;
storedArgs = [];
}
}
else if (!timeout) {
timeout = window.setTimeout(later, remaining);
}
return result;
};
}
var SignaturePad = (function () {
function SignaturePad(canvas, options) {
if (options === void 0) { options = {}; }
var _this = this;
this.canvas = canvas;
this.options = options;
this._handleMouseDown = function (event) {
if (event.which === 1) {
_this._mouseButtonDown = true;
_this._strokeBegin(event);
}
};
this._handleMouseMove = function (event) {
if (_this._mouseButtonDown) {
_this._strokeMoveUpdate(event);
}
};
this._handleMouseUp = function (event) {
if (event.which === 1 && _this._mouseButtonDown) {
_this._mouseButtonDown = false;
_this._strokeEnd(event);
}
};
this._handleTouchStart = function (event) {
event.preventDefault();
if (event.targetTouches.length === 1) {
var touch = event.changedTouches[0];
_this._strokeBegin(touch);
}
};
this._handleTouchMove = function (event) {
event.preventDefault();
var touch = event.targetTouches[0];
_this._strokeMoveUpdate(touch);
};
this._handleTouchEnd = function (event) {
var wasCanvasTouched = event.target === _this.canvas;
if (wasCanvasTouched) {
event.preventDefault();
var touch = event.changedTouches[0];
_this._strokeEnd(touch);
}
};
this.velocityFilterWeight = options.velocityFilterWeight || 0.7;
this.minWidth = options.minWidth || 0.5;
this.maxWidth = options.maxWidth || 2.5;
this.throttle = ('throttle' in options ? options.throttle : 16);
this.minDistance = ('minDistance' in options ? options.minDistance : 5);
if (this.throttle) {
this._strokeMoveUpdate = throttle(SignaturePad.prototype._strokeUpdate, this.throttle);
}
else {
this._strokeMoveUpdate = SignaturePad.prototype._strokeUpdate;
}
this.dotSize = options.dotSize || function () {
return (this.minWidth + this.maxWidth) / 2;
};
this.penColor = options.penColor || 'black';
this.backgroundColor = options.backgroundColor || 'rgba(0,0,0,0)';
this.onBegin = options.onBegin;
this.onEnd = options.onEnd;
this._ctx = canvas.getContext('2d');
this.clear();
this.on();
}
SignaturePad.prototype.clear = function () {
var ctx = this._ctx;
var canvas = this.canvas;
ctx.fillStyle = this.backgroundColor;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(0, 0, canvas.width, canvas.height);
this._data = [];
this._reset();
this._isEmpty = true;
};
SignaturePad.prototype.fromDataURL = function (dataUrl, options, callback) {
var _this = this;
if (options === void 0) { options = {}; }
var image = new Image();
var ratio = options.ratio || window.devicePixelRatio || 1;
var width = options.width || (this.canvas.width / ratio);
var height = options.height || (this.canvas.height / ratio);
this._reset();
image.onload = function () {
_this._ctx.drawImage(image, 0, 0, width, height);
if (callback) {
callback();
}
};
image.onerror = function (error) {
if (callback) {
callback(error);
}
};
image.src = dataUrl;
this._isEmpty = false;
};
SignaturePad.prototype.toDataURL = function (type, encoderOptions) {
if (type === void 0) { type = 'image/png'; }
switch (type) {
case 'image/svg+xml':
return this._toSVG();
default:
return this.canvas.toDataURL(type, encoderOptions);
}
};
SignaturePad.prototype.on = function () {
this.canvas.style.touchAction = 'none';
this.canvas.style.msTouchAction = 'none';
if (window.PointerEvent) {
this._handlePointerEvents();
}
else {
this._handleMouseEvents();
if ('ontouchstart' in window) {
this._handleTouchEvents();
}
}
};
SignaturePad.prototype.off = function () {
this.canvas.style.touchAction = 'auto';
this.canvas.style.msTouchAction = 'auto';
this.canvas.removeEventListener('pointerdown', this._handleMouseDown);
this.canvas.removeEventListener('pointermove', this._handleMouseMove);
document.removeEventListener('pointerup', this._handleMouseUp);
this.canvas.removeEventListener('mousedown', this._handleMouseDown);
this.canvas.removeEventListener('mousemove', this._handleMouseMove);
document.removeEventListener('mouseup', this._handleMouseUp);
this.canvas.removeEventListener('touchstart', this._handleTouchStart);
this.canvas.removeEventListener('touchmove', this._handleTouchMove);
this.canvas.removeEventListener('touchend', this._handleTouchEnd);
};
SignaturePad.prototype.isEmpty = function () {
return this._isEmpty;
};
SignaturePad.prototype.fromData = function (pointGroups) {
var _this = this;
this.clear();
this._fromData(pointGroups, function (_a) {
var color = _a.color, curve = _a.curve;
return _this._drawCurve({ color: color, curve: curve });
}, function (_a) {
var color = _a.color, point = _a.point;
return _this._drawDot({ color: color, point: point });
});
this._data = pointGroups;
};
SignaturePad.prototype.toData = function () {
return this._data;
};
SignaturePad.prototype._strokeBegin = function (event) {
var newPointGroup = {
color: this.penColor,
points: []
};
this._data.push(newPointGroup);
this._reset();
this._strokeUpdate(event);
if (typeof this.onBegin === 'function') {
this.onBegin(event);
}
};
SignaturePad.prototype._strokeUpdate = function (event) {
var x = event.clientX;
var y = event.clientY;
var point = this._createPoint(x, y);
var lastPointGroup = this._data[this._data.length - 1];
var lastPoints = lastPointGroup.points;
var lastPoint = lastPoints.length > 0 && lastPoints[lastPoints.length - 1];
var isLastPointTooClose = lastPoint ? point.distanceTo(lastPoint) <= this.minDistance : false;
var color = lastPointGroup.color;
if (!lastPoint || !(lastPoint && isLastPointTooClose)) {
var curve = this._addPoint(point);
if (!lastPoint) {
this._drawDot({ color: color, point: point });
}
else if (curve) {
this._drawCurve({ color: color, curve: curve });
}
lastPoints.push({
time: point.time,
x: point.x,
y: point.y
});
}
};
SignaturePad.prototype._strokeEnd = function (event) {
this._strokeUpdate(event);
if (typeof this.onEnd === 'function') {
this.onEnd(event);
}
};
SignaturePad.prototype._handlePointerEvents = function () {
this._mouseButtonDown = false;
this.canvas.addEventListener('pointerdown', this._handleMouseDown);
this.canvas.addEventListener('pointermove', this._handleMouseMove);
document.addEventListener('pointerup', this._handleMouseUp);
};
SignaturePad.prototype._handleMouseEvents = function () {
this._mouseButtonDown = false;
this.canvas.addEventListener('mousedown', this._handleMouseDown);
this.canvas.addEventListener('mousemove', this._handleMouseMove);
document.addEventListener('mouseup', this._handleMouseUp);
};
SignaturePad.prototype._handleTouchEvents = function () {
this.canvas.addEventListener('touchstart', this._handleTouchStart);
this.canvas.addEventListener('touchmove', this._handleTouchMove);
this.canvas.addEventListener('touchend', this._handleTouchEnd);
};
SignaturePad.prototype._reset = function () {
this._lastPoints = [];
this._lastVelocity = 0;
this._lastWidth = (this.minWidth + this.maxWidth) / 2;
this._ctx.fillStyle = this.penColor;
};
SignaturePad.prototype._createPoint = function (x, y) {
var rect = this.canvas.getBoundingClientRect();
return new Point(x - rect.left, y - rect.top, new Date().getTime());
};
SignaturePad.prototype._addPoint = function (point) {
var _lastPoints = this._lastPoints;
_lastPoints.push(point);
if (_lastPoints.length > 2) {
if (_lastPoints.length === 3) {
_lastPoints.unshift(_lastPoints[0]);
}
var widths = this._calculateCurveWidths(_lastPoints[1], _lastPoints[2]);
var curve = Bezier.fromPoints(_lastPoints, widths);
_lastPoints.shift();
return curve;
}
return null;
};
SignaturePad.prototype._calculateCurveWidths = function (startPoint, endPoint) {
var velocity = (this.velocityFilterWeight * endPoint.velocityFrom(startPoint))
+ ((1 - this.velocityFilterWeight) * this._lastVelocity);
var newWidth = this._strokeWidth(velocity);
var widths = {
end: newWidth,
start: this._lastWidth
};
this._lastVelocity = velocity;
this._lastWidth = newWidth;
return widths;
};
SignaturePad.prototype._strokeWidth = function (velocity) {
return Math.max(this.maxWidth / (velocity + 1), this.minWidth);
};
SignaturePad.prototype._drawCurveSegment = function (x, y, width) {
var ctx = this._ctx;
ctx.moveTo(x, y);
ctx.arc(x, y, width, 0, 2 * Math.PI, false);
this._isEmpty = false;
};
SignaturePad.prototype._drawCurve = function (_a) {
var color = _a.color, curve = _a.curve;
var ctx = this._ctx;
var widthDelta = curve.endWidth - curve.startWidth;
var drawSteps = Math.floor(curve.length()) * 2;
ctx.beginPath();
ctx.fillStyle = color;
for (var i = 0; i < drawSteps; i += 1) {
var t = i / drawSteps;
var tt = t * t;
var ttt = tt * t;
var u = 1 - t;
var uu = u * u;
var uuu = uu * u;
var x = uuu * curve.startPoint.x;
x += 3 * uu * t * curve.control1.x;
x += 3 * u * tt * curve.control2.x;
x += ttt * curve.endPoint.x;
var y = uuu * curve.startPoint.y;
y += 3 * uu * t * curve.control1.y;
y += 3 * u * tt * curve.control2.y;
y += ttt * curve.endPoint.y;
var width = curve.startWidth + (ttt * widthDelta);
this._drawCurveSegment(x, y, width);
}
ctx.closePath();
ctx.fill();
};
SignaturePad.prototype._drawDot = function (_a) {
var color = _a.color, point = _a.point;
var ctx = this._ctx;
var width = typeof this.dotSize === 'function' ? this.dotSize() : this.dotSize;
ctx.beginPath();
this._drawCurveSegment(point.x, point.y, width);
ctx.closePath();
ctx.fillStyle = color;
ctx.fill();
};
SignaturePad.prototype._fromData = function (pointGroups, drawCurve, drawDot) {
for (var _i = 0, pointGroups_1 = pointGroups; _i < pointGroups_1.length; _i++) {
var group = pointGroups_1[_i];
var color = group.color, points = group.points;
if (points.length > 1) {
for (var j = 0; j < points.length; j += 1) {
var basicPoint = points[j];
var point = new Point(basicPoint.x, basicPoint.y, basicPoint.time);
this.penColor = color;
if (j === 0) {
this._reset();
}
var curve = this._addPoint(point);
if (curve) {
drawCurve({ color: color, curve: curve });
}
}
}
else {
this._reset();
drawDot({
color: color,
point: points[0]
});
}
}
};
SignaturePad.prototype._toSVG = function () {
var _this = this;
var pointGroups = this._data;
var ratio = Math.max(window.devicePixelRatio || 1, 1);
var minX = 0;
var minY = 0;
var maxX = this.canvas.width / ratio;
var maxY = this.canvas.height / ratio;
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width', this.canvas.width.toString());
svg.setAttribute('height', this.canvas.height.toString());
this._fromData(pointGroups, function (_a) {
var color = _a.color, curve = _a.curve;
var path = document.createElement('path');
if (!isNaN(curve.control1.x) &&
!isNaN(curve.control1.y) &&
!isNaN(curve.control2.x) &&
!isNaN(curve.control2.y)) {
var attr = "M " + curve.startPoint.x.toFixed(3) + "," + curve.startPoint.y.toFixed(3) + " "
+ ("C " + curve.control1.x.toFixed(3) + "," + curve.control1.y.toFixed(3) + " ")
+ (curve.control2.x.toFixed(3) + "," + curve.control2.y.toFixed(3) + " ")
+ (curve.endPoint.x.toFixed(3) + "," + curve.endPoint.y.toFixed(3));
path.setAttribute('d', attr);
path.setAttribute('stroke-width', (curve.endWidth * 2.25).toFixed(3));
path.setAttribute('stroke', color);
path.setAttribute('fill', 'none');
path.setAttribute('stroke-linecap', 'round');
svg.appendChild(path);
}
}, function (_a) {
var color = _a.color, point = _a.point;
var circle = document.createElement('circle');
var dotSize = typeof _this.dotSize === 'function' ? _this.dotSize() : _this.dotSize;
circle.setAttribute('r', dotSize.toString());
circle.setAttribute('cx', point.x.toString());
circle.setAttribute('cy', point.y.toString());
circle.setAttribute('fill', color);
svg.appendChild(circle);
});
var prefix = 'data:image/svg+xml;base64,';
var header = '<svg'
+ ' xmlns="http://www.w3.org/2000/svg"'
+ ' xmlns:xlink="http://www.w3.org/1999/xlink"'
+ (" viewBox=\"" + minX + " " + minY + " " + maxX + " " + maxY + "\"")
+ (" width=\"" + maxX + "\"")
+ (" height=\"" + maxY + "\"")
+ '>';
var body = svg.innerHTML;
if (body === undefined) {
var dummy = document.createElement('dummy');
var nodes = svg.childNodes;
dummy.innerHTML = '';
for (var i = 0; i < nodes.length; i += 1) {
dummy.appendChild(nodes[i].cloneNode(true));
}
body = dummy.innerHTML;
}
var footer = '</svg>';
var data = header + body + footer;
return prefix + btoa(data);
};
return SignaturePad;
}());
return SignaturePad;
})));

@ -6197,13 +6197,15 @@ class Exercise
* @param array $user_data result of api_get_user_info()
* @param array $trackExerciseInfo result of get_stat_track_exercise_info
* @param bool $saveUserResult
* @param bool $allowSignature
*
* @return string
*/
public function showExerciseResultHeader(
$user_data,
$trackExerciseInfo,
$saveUserResult
$saveUserResult,
$allowSignature = false
) {
if (api_get_configuration_value('hide_user_info_in_quiz_result')) {
return '';
@ -6303,6 +6305,7 @@ class Exercise
$tpl = new Template(null, false, false, false, false, false, false);
$tpl->assign('data', $data);
$tpl->assign('allow_signature', $allowSignature);
$layoutTemplate = $tpl->get_template('exercise/partials/result_exercise.tpl');
return $tpl->fetch($layoutTemplate);

@ -36,7 +36,7 @@ if (empty($track_exercise_info)) {
}
$exercise_id = $track_exercise_info['exe_exo_id'];
$student_id = $track_exercise_info['exe_user_id'];
$student_id = (int) $track_exercise_info['exe_user_id'];
$current_user_id = api_get_user_id();
$objExercise = new Exercise();
@ -55,9 +55,25 @@ if (!$is_allowedToEdit) {
}
}
$allowSignature = false;
if ($student_id === $current_user_id && 'true' === api_get_plugin_setting('exercise_signature', 'tool_enable')) {
$extraFieldValue = new ExtraFieldValue('exercise');
$result = $extraFieldValue->get_values_by_handler_and_field_variable($exercise_id, 'signature_activated');
if ($result && isset($result['value']) && 1 === (int) $result['value']) {
// Check if signature exists.
$signature = ExerciseSignaturePlugin::getSignature($current_user_id, $track_exercise_info);
if (false === $signature) {
$allowSignature = true;
}
}
}
$htmlHeadXtra[] = '<link rel="stylesheet" href="'.api_get_path(WEB_LIBRARY_JS_PATH).'hotspot/css/hotspot.css">';
$htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_JS_PATH).'hotspot/js/hotspot.js"></script>';
$htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_JS_PATH).'annotation/js/annotation.js"></script>';
if ($allowSignature) {
$htmlHeadXtra[] = api_get_asset('signature_pad/signature_pad.umd.js');
}
if (!empty($objExercise->getResultAccess())) {
$htmlHeadXtra[] = api_get_css(api_get_path(WEB_LIBRARY_PATH).'javascript/epiclock/renderers/minute/epiclock.minute.css');
@ -78,7 +94,7 @@ if ($show_headers) {
body { background: none;}
</style>';
if ($origin == 'mobileapp') {
if ($origin === 'mobileapp') {
echo '<div class="actions">';
echo '<a href="javascript:window.history.go(-1);">'.
Display::return_icon('back.png', get_lang('GoBackToQuestionList'), [], 32).'</a>';
@ -94,15 +110,16 @@ ExerciseLib::displayQuestionListByAttempt(
$objExercise,
$id,
false,
$message
$message,
$allowSignature
);
$pageContent = ob_get_contents();
ob_end_clean();
$template = new Template('', $show_headers, $show_headers);
$template->assign('page_content', $pageContent);
$layout = $template->fetch(
$template->get_template('exercise/result.tpl')
);
$template->assign('allow_signature', $allowSignature);
$template->assign('exe_id', $id);
$layout = $template->fetch($template->get_template('exercise/result.tpl'));
$template->assign('content', $layout);
$template->display_one_col_template();

@ -1,32 +1,24 @@
<?php
/* For licensing terms, see /license.txt */
use Chamilo\CoreBundle\Entity\TrackEExerciseConfirmation;
use ChamiloSession as Session;
/**
* Responses to AJAX calls.
*/
require_once __DIR__.'/../global.inc.php';
$debug = false;
// Check if the user has access to the contextual course/session
api_protect_course_script(true);
$action = $_REQUEST['a'];
if ($debug) {
error_log('-----------------------------------------------------');
error_log("$action ajax call");
error_log('-----------------------------------------------------');
}
$course_id = api_get_course_int_id();
$session_id = isset($_REQUEST['session_id']) ? (int) $_REQUEST['session_id'] : api_get_session_id();
$course_code = isset($_REQUEST['cidReq']) ? $_REQUEST['cidReq'] : api_get_course_id();
$currentUserId = api_get_user_id();
$exeId = isset($_REQUEST['exe_id']) ? $_REQUEST['exe_id'] : 0;
switch ($action) {
case 'update_duration':
$exeId = isset($_REQUEST['exe_id']) ? $_REQUEST['exe_id'] : 0;
if (Session::read('login_as')) {
if ($debug) {
@ -70,7 +62,6 @@ switch ($action) {
$now = $nowObject->getTimestamp();
$exerciseId = $attempt->getExeExoId();
$userId = $attempt->getExeUserId();
$currentUserId = api_get_user_id();
if ($userId != $currentUserId) {
if ($debug) {
@ -356,7 +347,6 @@ switch ($action) {
case 'add_question_to_reminder':
/** @var Exercise $objExercise */
$objExercise = Session::read('objExercise');
$exeId = isset($_REQUEST['exe_id']) ? $_REQUEST['exe_id'] : 0;
if (empty($objExercise) || empty($exeId)) {
echo 0;
@ -413,9 +403,6 @@ switch ($action) {
$learnpath_id = isset($_REQUEST['learnpath_id']) ? (int) $_REQUEST['learnpath_id'] : 0;
$learnpath_item_id = isset($_REQUEST['learnpath_item_id']) ? (int) $_REQUEST['learnpath_item_id'] : 0;
// Attempt id.
$exeId = isset($_REQUEST['exe_id']) ? (int) $_REQUEST['exe_id'] : 0;
if ($debug) {
error_log("exe_id = $exeId");
error_log("type = $type");
@ -910,6 +897,26 @@ switch ($action) {
echo Display::return_message($exception->getMessage(), 'error');
}
break;
case 'sign_attempt':
api_block_anonymous_users();
if ('true' !== api_get_plugin_setting('exercise_signature', 'tool_enable')) {
exit;
}
$file = isset($_REQUEST['file']) ? $_REQUEST['file'] : '';
if (empty($exeId) || empty($file)) {
echo 0;
exit;
}
$track = ExerciseLib::get_exercise_track_exercise_info($exeId);
if ($track) {
$result = ExerciseSignaturePlugin::saveSignature($currentUserId, $track, $file);
if ($result) {
echo 1;
exit;
}
}
echo 0;
break;
default:
echo '';

@ -2847,6 +2847,7 @@ HOTSPOT;
* @param string $decimalSeparator
* @param string $thousandSeparator
* @param bool $roundValues This option rounds the float values into a int using ceil()
* @param bool $removeEmptyDecimals
*
* @return string an html with the score modified
*/
@ -2859,12 +2860,16 @@ HOTSPOT;
$hidePercentageSign = false,
$decimalSeparator = '.',
$thousandSeparator = ',',
$roundValues = false
$roundValues = false,
$removeEmptyDecimals = false
) {
if (is_null($score) && is_null($weight)) {
return '-';
}
$decimalSeparator = empty($decimalSeparator) ? '.' : $decimalSeparator;
$thousandSeparator = empty($thousandSeparator) ? ',' : $thousandSeparator;
if ($use_platform_settings) {
$result = self::convertScoreToPlatformSetting($score, $weight);
$score = $result['score'];
@ -2872,6 +2877,7 @@ HOTSPOT;
}
$percentage = (100 * $score) / ($weight != 0 ? $weight : 1);
// Formats values
$percentage = float_format($percentage, 1);
$score = float_format($score, 1);
@ -2920,6 +2926,11 @@ HOTSPOT;
$html = $percentage.$percentageSign;
}
} else {
/*if ($removeEmptyDecimals) {
if (ScoreDisplay::hasEmptyDecimals($weight)) {
$weight = round($weight);
}
}*/
$html = $score.' / '.$weight;
}
@ -4422,12 +4433,14 @@ EOT;
* @param int $exeId
* @param bool $save_user_result save users results (true) or just show the results (false)
* @param string $remainingMessage
* @param bool $allowSignature
*/
public static function displayQuestionListByAttempt(
$objExercise,
$exeId,
$save_user_result = false,
$remainingMessage = ''
$remainingMessage = '',
$allowSignature = false
) {
$origin = api_get_origin();
$courseId = api_get_course_int_id();
@ -4582,7 +4595,8 @@ EOT;
echo $objExercise->showExerciseResultHeader(
$studentInfo,
$exercise_stat_info,
$save_user_result
$save_user_result,
$allowSignature
);
}

@ -156,6 +156,9 @@ class ExtraField extends Model
case 'forum_post':
$this->extraFieldType = EntityExtraField::FORUM_POST_TYPE;
break;
case 'track_exercise':
$this->extraFieldType = EntityExtraField::TRACK_EXERCISE_FIELD_TYPE;
break;
}
$this->pageUrl = 'extra_fields.php?type='.$this->type;
@ -185,6 +188,7 @@ class ExtraField extends Model
'forum_category',
'forum_post',
'exercise',
'track_exercise',
];
if (api_get_configuration_value('allow_scheduled_announcements')) {

@ -43,10 +43,17 @@
<i class="fa fa-fw fa-laptop" aria-hidden="true"></i> {{ data.ip }}
</div>
{% endif %}
</div>
<hr>
{% if allow_signature %}
<div class="list-data ip">
<span class="item"></span>
<a id="sign" class="btn btn-primary" href="javascript:void(0)">
<em class="fa fa-pencil"></em> {{ 'Sign'| get_plugin_lang('ExerciseSignaturePlugin') }}
</a>
</div>
{% endif %}
</div>
<hr />
<div id="quiz_saved_answers_container">
{% if data.number_of_answers_saved != data.number_of_answers %}
<span class="label label-warning">
@ -65,7 +72,11 @@
<div class="col-sm-12">
<div class="checkbox">
<label>
<input type="checkbox" name="quiz_confirm_saved_answers_check" {% if not enable_form %}disabled{% endif %} {% if data.track_confirmation.confirmed %}checked{% endif %}>
<input
type="checkbox"
name="quiz_confirm_saved_answers_check"
{% if not enable_form %}disabled{% endif %} {% if data.track_confirmation.confirmed %}checked{% endif %}
>
{{ 'QuizConfirmSavedAnswers'|get_lang }}
</label>
</div>
@ -95,7 +106,6 @@
{% if 'quiz_confirm_saved_answers'|api_get_configuration_value %}
{% set enable_form = data.track_confirmation.updatedAt is empty and data.track_confirmation.userId == _u.id %}
{% if enable_form %}
<script>
$(function () {

@ -1,7 +1,101 @@
{# Displayed from exercise_result.php #}
{{ page_top }}
{{ page_content }}
{{ page_bottom }}
{% if allow_signature %}
<div id="sign_popup" style="display: none">
<div id="signature_area" class="well">
<canvas width="400px"></canvas>
</div>
<span class="loading" style="display: none"><i class="fas fa-spinner"></i></span>
<span id="save_controls">
<button id="sign_popup_save" class="btn btn-primary" type="submit">
<em class="fa fa-save"></em> {{ 'Save'|get_lang }}
</button>
<button id="sign_popup_clean" class="btn btn-default" type="submit">
<em class="fa fa-eraser"></em> {{ 'Clean'|get_lang }}
</button>
</span>
<span id="close_controls" style="display: none">
<span id="sign_results"></span>
<hr />
<button id="sign_popup_close" class="btn btn-default" type="submit">
{{ 'Close'|get_lang }}
</button>
</span>
</div>
<script>
var canvas = document.querySelector("canvas");
var signaturePad = new SignaturePad(canvas);
var dataURL = signaturePad.toDataURL("image/jpeg");
var url = "{{ _p.web_ajax }}exercise.ajax.php?{{ _p.web_cid_query }}";
var exeId = "{{ exe_id }}";
$(function() {
$("#sign_popup_close").on("click", function() {
$("#sign_popup").dialog("close");
$('#loading').hide();
$('#save_controls').show();
$('#close_controls').hide();
$('#signature_area').show();
});
$("#sign_popup_clean").on("click", function() {
signaturePad.clear();
});
$("#sign_popup_save").on("click", function() {
if (signaturePad.isEmpty()) {
alert('{{ 'ProvideASignatureFirst'| get_plugin_lang('ExerciseSignaturePlugin') }}');
return false;
}
var dataURL = signaturePad.toDataURL("image/jpeg");
$.ajax({
contentType: "application/x-www-form-urlencoded",
beforeSend: function(result) {
$('#loading').show();
},
type: "POST",
url: url,
data: "a=sign_attempt&exe_id="+exeId+"&file="+dataURL,
success: function(data) {
$('#loading').hide();
$('#save_controls').hide();
$('#close_controls').show();
$('#signature_area').hide();
signaturePad.clear();
if (1 == data) {
$('#sign_results').html('{{ 'Saved' | get_lang }}');
$('#sign').hide();
//$('#sign').html('{{ 'SignatureSaved' | get_lang }}');
} else {
$('#sign_results').html('{{ 'Error' | get_lang }}');
}
$('#close_controls').show();
},
});
});
$("#sign").on("click", function() {
$("#sign_popup").dialog({
autoOpen: false,
width: 500,
height: 'auto',
//position: { my: 'left top', at: 'right top'}, //of: $target
close: function(){
//$("div#"+div_show_id).remove();
//$("div#"+div_content_id).remove();
}
});
$("#sign_popup").dialog("open");
});
});
</script>
{% endif %}

@ -0,0 +1 @@
Students can sign exercise results.

@ -0,0 +1,9 @@
<?php
/* For license terms, see /license.txt */
if (!api_is_platform_admin()) {
die('You must have admin permissions to install plugins');
}
ExerciseSignaturePlugin::create()->install();

@ -0,0 +1,10 @@
<?php
/* License: see /license.txt */
// Needed in order to show the plugin title
$strings['plugin_title'] = "Exercise signature";
$strings['plugin_comment'] = "";
$strings['tool_enable'] = 'Tool enabled';
$strings['ProvideASignatureFirst'] = 'Please provide a signature first';
$strings['Sign'] = 'Sign';

@ -0,0 +1,10 @@
<?php
/* License: see /license.txt */
// Needed in order to show the plugin title
$strings['plugin_title'] = "Exercice signature";
$strings['plugin_comment'] = "";
$strings['tool_enable'] = 'Activer le plugin';
$strings['Sign'] = 'Signer';
$strings['ProvideASignatureFirst'] = "Veuillez d'abord fournir une signature";

@ -0,0 +1,10 @@
<?php
/* License: see /license.txt */
// Needed in order to show the plugin title
$strings['plugin_title'] = "Exercise signature";
$strings['plugin_comment'] = "";
$strings['tool_enable'] = 'Activar plugin';
$strings['Sign'] = 'Firmar';
$strings['ProvideASignatureFirst'] = "Primero ingrese una firma";

@ -0,0 +1,171 @@
<?php
/* For licensing terms, see /license.txt */
class ExerciseSignaturePlugin extends Plugin
{
public function __construct()
{
parent::__construct(
'0.1',
'Julio Montoya',
[
'tool_enable' => 'boolean',
]
);
$this->isAdminPlugin = true;
}
/**
* @return $this
*/
public static function create()
{
static $instance = null;
return $instance ? $instance : $instance = new self();
}
public static function saveSignature($userId, $trackInfo, $file)
{
if (false === self::validateSignatureAccess($userId, $trackInfo)) {
return false;
}
$signature = self::getSignature($userId, $trackInfo);
if (false !== $signature) {
return false;
}
if (empty($file)) {
return false;
}
$params = [
'item_id' => $trackInfo['exe_id'],
'extra_signature' => $file,
];
$extraFieldValue = new ExtraFieldValue('track_exercise');
$extraFieldValue->saveFieldValues(
$params,
true
);
$signature = self::getSignature($userId, $trackInfo);
if (false !== $signature) {
return true;
}
return true;
}
public static function validateSignatureAccess($userId, $trackInfo)
{
$userId = (int) $userId;
if (isset($trackInfo['exe_id']) && isset($trackInfo['exe_user_id']) &&
!empty($trackInfo['exe_id']) && !empty($trackInfo['exe_user_id']) &&
$trackInfo['status'] !== 'incomplete'
) {
if ($userId === (int) $trackInfo['exe_user_id']) {
return true;
}
}
return false;
}
public static function getSignature($userId, $trackInfo)
{
if (false === self::validateSignatureAccess($userId, $trackInfo)) {
return false;
}
$extraFieldValue = new ExtraFieldValue('track_exercise');
$result = $extraFieldValue->get_values_by_handler_and_field_variable($trackInfo['exe_id'], 'signature');
if ($result && isset($result['value']) && !empty($result['value'])) {
return $result['value'];
}
return false;
}
/**
* Get the plugin Name.
*
* @return string
*/
public function get_name()
{
return 'exercise_signature';
}
/**
* Creates this plugin's related tables in the internal database.
* Installs course fields in all courses.
*/
public function install()
{
$extraField = new ExtraField('track_exercise');
$extraFieldHandler = $extraField->get_handler_field_info_by_field_variable('signature_activated');
$exists = $extraFieldHandler !== false;
if (!$exists) {
$extraField->save(
[
'field_type' => 13, // checkbox yes/no
'variable' => 'signature_activated',
'display_text' => get_plugin_lang('SignatureActivated', 'ExerciseSignaturePlugin'),
'default_value' => null,
'field_order' => null,
'visible_to_self' => 1,
'changeable' => 1,
'filter' => null,
]
);
}
$extraField = new ExtraField('exercise');
$extraFieldHandler = $extraField->get_handler_field_info_by_field_variable('signature');
$exists = $extraFieldHandler !== false;
if (!$exists) {
$extraField->save(
[
'field_type' => 2, // textarea
'variable' => 'signature',
'display_text' => get_plugin_lang('Signature', 'ExerciseSignaturePlugin'),
'default_value' => null,
'field_order' => null,
'visible_to_self' => 1,
'changeable' => 1,
'filter' => null,
]
);
}
$table = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
$sql = "ALTER TABLE $table MODIFY COLUMN value LONGTEXT null;";
Database::query($sql);
}
/**
* Drops this plugins' related tables from the internal database.
* Uninstalls course fields in all courses().
*/
public function uninstall()
{
$extraField = new ExtraField('track_exercise');
$fieldInfo = $extraField->get_handler_field_info_by_field_variable('signature_activated');
if ($fieldInfo) {
$extraField->delete($fieldInfo['id']);
}
$extraField = new ExtraField('exercise');
$fieldInfo = $extraField->get_handler_field_info_by_field_variable('signature');
if ($fieldInfo) {
$extraField->delete($fieldInfo['id']);
}
}
}

@ -0,0 +1,5 @@
<?php
/* For license terms, see /license.txt */
$plugin_info = ExerciseSignaturePlugin::create()->get_info();

@ -0,0 +1,9 @@
<?php
/* For license terms, see /license.txt */
if (!api_is_platform_admin()) {
die('You must have admin permissions to uninstall plugins');
}
ExerciseSignaturePlugin::create()->uninstall();

@ -36,6 +36,7 @@ class ExtraField extends BaseAttribute
const FORUM_CATEGORY_TYPE = 15;
const FORUM_POST_TYPE = 16;
const EXERCISE_FIELD_TYPE = 17;
const TRACK_EXERCISE_FIELD_TYPE = 18;
/**
* @var int

Loading…
Cancel
Save