Compare commits

..

60 commits

Author SHA1 Message Date
Mark Nelson
be34b27ff9 Fixed size of 'Changed' in CHANGES.md 2020-11-26 23:31:42 +08:00
Mark Nelson
2253884856 Bumped version 2020-11-26 23:00:04 +08:00
Mark Nelson
e5059a63f4 Update CHANGES.md (#390) 2020-11-26 22:11:28 +08:00
uvigo-atic
13a1012ffb Added username to userfield form element (#390) 2020-11-26 22:11:19 +08:00
Mark Nelson
24ac8add66 Updated CHANGES.md (#276) 2020-11-26 21:43:02 +08:00
Mark Nelson
98a2c53463 Update 'emailteachers_help' and 'emailothers_help' language strings (#276) 2020-11-26 21:35:44 +08:00
Mark Nelson
69817ce07a Do not email out certificates with no elements (#276) 2020-11-26 21:13:43 +08:00
Mark Nelson
b56c13b67b Use null coalescing operator in element factory 2020-11-26 18:22:52 +08:00
Mark Nelson
90241238fb Update 'emailstudents_help' language string (#276) 2020-11-26 17:55:54 +08:00
Mark Nelson
5034faa2e4 Bump .travis.yml to use v3 of moodle-plugin-ci 2020-11-09 16:29:14 +01:00
Mark Nelson
0f6282a1b1 Update repo used by Travis 2020-11-09 16:28:54 +01:00
Mark Nelson
7e9de4aada Update CHANGES.md 2020-11-04 19:32:50 +01:00
Brendan Heywood
42d3b3a50e PDFs should be inline not attachments #153 2020-11-04 19:16:22 +01:00
Mark Nelson
c9b83759bc Add CSS class for mobile app (#378) 2020-10-12 13:36:33 +02:00
Mark Nelson
f1a55ce6db Removed multiple empty lines 2020-09-20 16:00:55 +02:00
Mark Nelson
d0e75bb6fc Updated CHANGES.md 2020-09-20 15:55:05 +02:00
Mark Nelson
2b210b4bb8 Fixed issue with PDF being generated without a name (#333) 2020-09-20 15:41:05 +02:00
Mark Nelson
4765c11a46 Fixed exception loading template image that has no image selected (#369) 2020-09-20 14:58:18 +02:00
Mark Nelson
03d56eddae Do not email those who can manage the certificate (#376) 2020-09-20 14:29:31 +02:00
Guillermo Gomez
d37bfab4cd Implement get_objectid_mapping (#374) 2020-09-20 14:17:08 +02:00
Mark Nelson
d8f275d588 Updated CHANGES.md 2020-08-08 19:38:57 +02:00
Mark Nelson
616bc4f43b Changed 'enrollment' to 'enrolment' to conform to Moodle core (#328)
Also minor changes like ordering strings alphabetically and adding
full-stops.
2020-08-08 19:36:17 +02:00
Sergey Evstegneiev
b3433e598c Adding enrollment start & end date options (#328) 2020-08-08 19:35:50 +02:00
Mark Nelson
05ba53ad3a Fix stale file warning 2020-08-08 18:11:04 +02:00
Mark Nelson
545ed8bbbd Ignore multiple certificate codes (#363) 2020-08-08 15:53:00 +02:00
Mark Nelson
2697ba9fb5 Remove trailing spaces 2020-08-08 15:47:00 +02:00
Thong Bui
4447e2ac6f Fix get position when browser shrinking (#343) 2020-08-08 15:28:28 +02:00
Mark Nelson
4a85da7297 Updated CHANGES.md 2020-06-28 18:37:50 +02:00
Mark Nelson
112a027849 Mark certificates as viewed in mobile app (#342) 2020-05-30 13:10:18 +02:00
Mark Nelson
feb3bac856 Refactor element_helper::get_grade_items() to be nicer to read 2020-05-08 21:24:10 +02:00
Mark Nelson
88d0449d62 Fix docs in Grade element name 2020-05-08 17:50:36 +02:00
Mark Nelson
ba0bfd3a7e The Grade item name element works with all grade items (#346) 2020-05-08 17:27:46 +02:00
Mark Nelson
8d3d78307f Extend unit test (#329) 2020-05-08 17:23:14 +02:00
Mark Nelson
6ba2efa3b0 Add the ability to select Outcomes in the Grade element (#329) 2020-05-08 17:23:08 +02:00
Mark Nelson
a7d372a26a Removed 'exampledata' string 2020-05-08 16:57:28 +02:00
Mark Nelson
14e480f7e9 Bumped version 2020-03-17 00:21:51 +01:00
Mark Nelson
a379c93dd7 Fixed broken logic (#298) 2020-03-16 17:52:19 +01:00
Mark Nelson
185389b983 Loading templates copies system images to the course (#298)
Before it would just reference the system images. However, this meant
backup/restore was broken as it did not include the images the template
was using.
2020-03-15 19:53:05 +01:00
Mark Nelson
3dc83cb306 Updated CHANGES.md 2020-03-12 14:54:58 +01:00
Mark Nelson
a2c30e3667 Added extra Behat steps for new elements (#309) 2020-03-11 14:18:42 +01:00
Mark Nelson
ad7d4099b4 Avoid use of old array syntax (#331) 2020-03-10 17:41:30 +01:00
Sergey
1c9f4786fb Fix of showing names of custom user fields (#326)
Show normal human-readable name of custom user profile fields instead of internal shortname
2020-03-09 14:57:35 +01:00
Mark Nelson
2f8bb1eb29 Do not allow '0' as a value for width or height in QR code (#321) 2020-03-09 14:53:11 +01:00
Mark Nelson
01bfe2f660 Fix foreign key violation (#331) 2020-03-09 14:32:10 +01:00
Mark Nelson
28a8b99f31 Bumped version 2020-02-01 16:00:06 +01:00
Mark Nelson
9810b48b25 Updated CHANGES.md 2020-02-01 15:55:22 +01:00
Mark Nelson
28b2210b19 Fixed typo in Behat file name 2020-02-01 15:48:42 +01:00
Mark Nelson
62639d1754 Re-add code column (#264) 2020-02-01 15:48:08 +01:00
mwithheld
e7352bf715 Do not fail if multiple certificate issues (#304)
Fix another location of this problem.
2019-12-16 16:18:24 +01:00
mwithheld
b28877f5ee Do not fail if multiple certificate issues (#295)
Ignore multiple matches for a user-customcert combo in the customcert_issues table.
In our case, the scheduled task died when:
$issueid = $DB->get_field('customcert_issues', 'id', array('userid' => $enroluser->id, 'customcertid' => $customcert->id));
returned 2 rows, which shouldn't happen, but did anyway.

This means in rare circumstances (i.e. the race condition) the user may get multiple certificates (e.g. one via the UI, one by email) but that is better than not getting one at all and the whole job dying.
2019-12-16 16:18:12 +01:00
Mark Nelson
bc2fe29354 Changed references to old github name 2019-12-16 15:11:36 +01:00
Arnaud Trouvé
74f1cd732d Add userfullname variable for email subject (#316) 2019-12-16 15:01:52 +01:00
Mark Nelson
9d97d7e6fb Bumped version 2019-06-17 17:08:06 +08:00
Mark Nelson
bd91807fe2 Updated CHANGES.md 2019-06-17 14:40:59 +08:00
Mark Nelson
88ef8f25fa Add ability to specify the current date for date related elements (#289) 2019-06-17 13:34:56 +08:00
Mark Nelson
c420d3b943 String improvements for date range element
Also added a help button to reduce the wall
of text.
2019-06-17 12:42:04 +08:00
Mark Nelson
5a6993009b Fixed PHPDoc reference to edit_element_form 2019-06-17 12:16:05 +08:00
Mark Nelson
08b10ebdad Use negative numbers for constants in date range element
The reason being that we may have a module that has
an id matching one of these values.
2019-06-17 11:30:58 +08:00
Mark Nelson
1511c079ab Specify OS in travis 2019-05-29 00:19:47 +08:00
Mark Nelson
a26d58bf33 Fix complaints found by local_moodlecheck 2019-05-29 00:13:17 +08:00
205 changed files with 14168 additions and 5618 deletions

52
.travis.yml Normal file
View file

@ -0,0 +1,52 @@
language: php
# For javascript behat tests we need sudo
sudo: true
dist: trusty
cache:
directories:
- $HOME/.composer/cache
- $HOME/.npm
php:
- 7.0
- 7.2
addons:
firefox: 47.0.1
postgresql: 9.4
apt:
packages:
- openjdk-8-jre-headless
env:
global:
- MOODLE_BRANCH=MOODLE_36_STABLE
- IGNORE_NAMES=mobile_*.mustache # Mobile mustache has specific syntax, ignore their templates
matrix:
- DB=pgsql
- DB=mysqli
before_install:
- phpenv config-rm xdebug.ini
- nvm install 8.9
- nvm use 8.9
- cd ../..
- composer create-project -n --no-dev --prefer-dist moodlehq/moodle-plugin-ci ci ^3
- export PATH="$(cd ci/bin; pwd):$(cd ci/vendor/bin; pwd):$PATH"
install:
- moodle-plugin-ci install
script:
- moodle-plugin-ci phplint
# - moodle-plugin-ci phpcpd # subplugins often have similar code and cause "duplicated code" errors
# - moodle-plugin-ci phpmd # too much noise from this check, maybe, some day...
- moodle-plugin-ci codechecker
- moodle-plugin-ci validate
- moodle-plugin-ci savepoints
- moodle-plugin-ci mustache
- moodle-plugin-ci grunt -t stylelint:css -t js
- moodle-plugin-ci phpunit
- moodle-plugin-ci behat

264
CHANGES.md Normal file
View file

@ -0,0 +1,264 @@
# Changelog
All notable changes to this project will be documented in this file.
Note - All hash comments refer to the issue number. Eg. #169 refers to https://github.com/mdjnelson/moodle-mod_customcert/issues/169.
## [3.6.7] - 2020-11-26
### Added
- Added ability to select outcomes in the Grade element (#329).
- The Grade Item Name element now works with all grade items, whereas before it was just activities (#346).
- Added enrolment start and end dates to the date element (#328).
- Added username to userfield form element (#390).
### Changed
- Removed unnecessary and confusing 'exampledata' string.
- Do not email those who can manage the certificate (#376).
- Do not force the PDF to be downloaded, instead send the file inline to the browser (#153).
- Updated the 'emailstudents_help', 'emailteachers_help' and 'emailothers_help' strings to warn users about prematurely emailing the certificate (#276).
- Do not email out certificates that contain no elements (#276).
### Fixed
- Certificates now get marked as viewed via the mobile app (#342).
- Fix repositioning elements page when resizing the browser (#343).
- Prevent error when duplicate issues exist when using the code element (#363).
- Implemented get_objectid_mapping for the course_module_viewed.php event to avoid warning (#374).
- Fixed exception being thrown when loading a template that has an image element but no image selected (#369).
- Fixed issue with PDF being generated without a name (#333).
## [3.6.6] - 2020-03-12
### Added
- Added extra Behat steps for new elements (#309).
### Changed
- When copying a site template the site images are also copied to the course context and then those copied images are used.
Before, the elements would simply point to the site images. However, this meant when performing a backup/restore the
images were not stored in the backup file (#298).
### Fixed
- Fixed the displaying of names of a custom user field (#326).
- Do not allow '0' as a value for width or height in QR code (#321).
## [3.6.5] - 2020-03-09
### Fixed
- Fixed foreign key violation (#331).
## [3.6.4] - 2020-02-01
### Added
- Re-added 'code' column to user report (#264).
- Add 'userfullname' variable for email subject (#316).
### Fixed
- Do not fail if multiple certificate issues (#304) and (#295).
## [3.6.3] - 2019-06-17
### Added
- Added ability to specify the current date for date related elements (#289).
### Changed
- String improvements for the 'Date range' element.
### Fixed
- Use negative numbers for constants in the 'Date range' element. The reason being that we may have a module
that has an id matching one of these positive values. Sites which are using the 'Date range' element (sites
which are **not** using this element do **not** have to do anything) will need to re-edit each element, select
the date item again and save. An upgrade step was not created because it is impossible to tell if the site does
actually want the constant or if they actually want the date for the module.
## [3.6.2] - 2019-05-28
### Changed
- Always send emails from the 'noreplyuser' (#165).
### Added
- Added QR code element (#146).
- Added Date range element (#185).
- Added the number of certificates issued above the report (#266).
- Added new capability to control who can be issued a certificate (#270).
### Fixed
- Failures when running unit tests for multiple activities (#282).
- Check that a certificate is valid before downloading on 'My certificates' page (#269).
## [3.6.1] - 2018-12-31
### Changed
- Make it clear what element values are just an example when previewing the PDF (#144).
### Fixed
- Missing implementation for privacy provider (#260).
- Use course module context when calling format_string/text (#200).
- Exception being thrown when adding the 'teachername' element to site template (#261).
## [3.5.5] - 2018-12-20
### Added
- GDPR: Add support for removal of users from a context (see MDL-62560) (#252).
- Images can be made transparent (#186).
- Set default values of activity instance settings (#180).
- Allow element plugins to control if they can be added to a certificate (#225).
- Allow element plugins to have their own admin settings (#213).
- Added plaintext language variants for email bodies (#231).
- Added possibility to selectively disable activity instance settings (#179).
### Changed
- Allow verification of deleted users (#159).
- The 'element' field in the 'customcert_elements' table has been changed from a Text field to varchar(255) (#241).
- The 'Completion date' option in the 'date' element is only displayed when completion is enabled (#160).
- Instead of assuming 2 decimal points for percentages, we now make use of the decimal value setting, which the
function `grade_format_gradevalue` does by default if no decimal value is passed.
### Fixed
- Issue with scales not displaying correctly (#242).
- The report now respects the setting 'Show user identity' (#224).
- Removed incorrect course reset logic (#223).
- Description strings referring to the wrong setting (#254).
## [3.5.4] - 2018-07-13
### Fixed
- Use custom fonts if present (#211).
- Fix broken SQL on Oracle in the email certificate task (#187).
- Fixed exception when clicking 'Add page' when template has not been saved (#154).
- Only email teachers who are enrolled within the course (#176).
- Only display teachers who are enrolled within the course in the dropdown (#171).
### Changed
- Multiple UX improvements to both the browser and mobile views (#207).
- One big change here is combining the report and activity view page into one.
- Allow short dates with leading zeros (#210).
## [3.5.3] - 2018-06-26
### Fixed
- Respect filters in the 'My certificates' and 'Verify certificate' pages (#197).
- Fixed reference to 'mod/certificate' capability.
### Changed
- Multiple UX improvements to both the browser and mobile views (#203).
## [3.5.2] - 2018-06-07
### Fixed
- Hotfix to prevent misalignment of 'text' elements after last release (#196).
## [3.5.1] - 2018-06-06
### Added
- Mobile app support (#70).
```
This allows students to view the activity and download
their certificate. It also allows teachers to view the
list of issued certificates, with the ability to revoke
any.
This is for the soon-to-be released Moodle Mobile v3.5.0
(not to be confused with your Moodle site version) and
will not work on Mobile versions earlier than this.
If you are running a Moodle site on version 3.4 or below
you will need to install the local_mobile plugin in order
for this to work.
If you are running a Moodle site on version 3.0 or below
then you will need to upgrade.
```
- More font sizes (#148).
- Added new download icon.
```
This was done because the core 'import' icon was mapped
to the Font Awesome icon 'fa-level-up' which did not look
appropriate. So, a new icon was added and that was mapped
to the 'fa-download' icon.
```
### Fixed
- No longer display the 'action' column and user picture URL when downloading the user report (#192).
- Elements no longer ignore filters (#170).
## [3.4.1] - 2018-05-17
### Added
- GDPR Compliance (#189).
### Fixed
- Race condition on certificate issues in scheduled task (#173).
- Ensure we backup the 'verifyany' setting (#169).
- Fixed encoding content links used by restore (#166).
## [3.3.9] - 2017-11-13
### Added
- Added capability ```mod/customcert:verifyallcertificates``` that provides a user with the ability to verify any certificate
on the site by simply visiting the ```mod/customcert/verify_certificate.php``` page, rather than having to go to the
verification link for each certificate.
- Added site setting ```customcert/verifyallcertificates``` which when enabled allows any person (including users not logged in)
to be able to verify any certificate on the site, rather than having to go to the verification link for each certificate.
However, this only applies to certificates where ```Allow anyone to verify a certificate``` has been set to ```Yes``` in the
certificate settings.
- You can now display the grade and date of all grade items, not just the course and course activities.
- Text has been added above the ```My certificates``` list to explain that it contains certificates that have been issued to
avoid confusion as to why certificates may not be appearing.
### Changed
- The course full name is now used in emails.
### Fixed
- Added missing string used in course reset.
## [3.3.8] - 2017-09-04
### Added
- New digital signature element (uses existing functionality in the TCPDF library).
- Ability to duplicate site templates via the manage templates page.
- Ability to delete issued certificates for individual users on the course report page.
### Changed
- Removed usage of magic getter and abuse of ```$this->element```. The variable ```$this->element``` will still be
accessible by any third-party element plugins, though this is discouraged and the appropriate ```get_xxx()```
method should be used instead. Using ```$this->element``` in ```definition_after_data()``` will no longer work.
Please explicitly set the value of any custom fields you have in the form.
### Fixed
- Added missing ```confirm_sesskey()``` checks.
- Minor bug fixes.
## [3.3.7] - 2017-08-11
### Added
- Added much needed Behat test coverage.
### Changed
- Minor language string changes.
- Made changes to the UI when editing a certificate.
- Moved the 'Add element' submit button below the list of elements.
- Added icon next to the 'Delete page' link.
- Changed the 'Add page' button to a link, added an icon and moved it's location to the right.
- Do not make all submit buttons primary. MDL-59740 needs to be applied to your Moodle install in order to notice the change.
### Fixed
- Issue where the date an activity was graded was not displaying at all.
## [3.3.6] - 2017-08-05
### Changed
- Renamed the column 'size' in the table 'customcert_elements' to 'fontsize' due to 'size' being a reserved word in Oracle.

57
ajax.php Normal file
View file

@ -0,0 +1,57 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Handles AJAX requests for the customcert module.
*
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once(__DIR__ . '/../../config.php');
if (!defined('AJAX_SCRIPT')) {
define('AJAX_SCRIPT', true);
}
$tid = required_param('tid', PARAM_INT);
$values = required_param('values', PARAM_RAW);
$values = json_decode($values);
// Make sure the template exists.
$template = $DB->get_record('customcert_templates', array('id' => $tid), '*', MUST_EXIST);
// Set the template.
$template = new \mod_customcert\template($template);
// Perform checks.
if ($cm = $template->get_cm()) {
$courseid = $cm->course;
require_login($courseid, false, $cm);
} else {
require_login();
}
// Make sure the user has the required capabilities.
$template->require_manage();
// Loop through the data.
foreach ($values as $value) {
$element = new stdClass();
$element->id = $value->id;
$element->posx = $value->posx;
$element->posy = $value->posy;
$DB->update_record('customcert_elements', $element);
}

1
amd/build/dialogue.min.js vendored Normal file
View file

@ -0,0 +1 @@
define(["core/yui"],function(a){var b=function(b,c,d,e,f){this.yuiDialogue=null;var g=this;"undefined"==typeof f&&(f=!1),a.use("moodle-core-notification","timers",function(){var h="480px";f&&(h="800px"),g.yuiDialogue=new M.core.dialogue({headerContent:b,bodyContent:c,draggable:!0,visible:!1,center:!0,modal:!0,width:h}),g.yuiDialogue.after("visibleChange",function(b){b.newVal?"undefined"!=typeof d&&a.soon(function(){d(g),g.yuiDialogue.centerDialogue()}):"undefined"!=typeof e&&a.soon(function(){e(g)})}),g.yuiDialogue.show()})};return b.prototype.close=function(){this.yuiDialogue.hide(),this.yuiDialogue.destroy()},b.prototype.getContent=function(){return this.yuiDialogue.bodyNode.getDOMNode()},b});

1
amd/build/rearrange-area.min.js vendored Normal file
View file

@ -0,0 +1 @@
define(["jquery","core/yui","core/fragment","mod_customcert/dialogue","core/notification","core/str","core/templates","core/ajax"],function(a,b,c,d,e,f,g,h){var i=function(b){this._node=a(b),this._setEvents()};return i.prototype.CUSTOMCERT_REF_POINT_TOPLEFT=0,i.prototype.CUSTOMCERT_REF_POINT_TOPCENTER=1,i.prototype.CUSTOMCERT_REF_POINT_TOPRIGHT=2,i.prototype.PIXELSINMM=3.779527559055,i.prototype._setEvents=function(){this._node.on("click",".element",this._editElement.bind(this))},i.prototype._editElement=function(a){var g=a.currentTarget.id.substr(8),h=this._node.attr("data-contextid"),i={elementid:g};c.loadFragment("mod_customcert","editelement",h,i).done(function(a,c){f.get_string("editelement","mod_customcert").done(function(e){b.use("moodle-core-formchangechecker",function(){new d(e,"<div id='elementcontent'></div>",this._editElementDialogueConfig.bind(this,g,a,c),(void 0),(!0))}.bind(this))}.bind(this))}.bind(this)).fail(e.exception)},i.prototype._editElementDialogueConfig=function(b,c,d,f){g.replaceNode("#elementcontent",c,d),this._setPositionInForm(b);var h=a(f.getContent());h.on("click","#id_submitbutton",function(c){M.core_formchangechecker.reset_form_dirty_state(),this._saveElement(b).then(function(){this._getElementHTML(b).done(function(c){var d=this._node.find("#element-"+b),e=parseInt(a("#id_refpoint").val()),g="";e==this.CUSTOMCERT_REF_POINT_TOPLEFT?g="refpoint-left":e==this.CUSTOMCERT_REF_POINT_TOPCENTER?g="refpoint-center":e==this.CUSTOMCERT_REF_POINT_TOPRIGHT&&(g="refpoint-right"),d.empty().append(c),d.removeClass(),d.addClass("element "+g),d.attr("data-refpoint",e);var h=a("#editelementform #id_posx").val(),i=a("#editelementform #id_posy").val();this._setPosition(b,e,h,i),f.close()}.bind(this))}.bind(this)).fail(e.exception),c.preventDefault()}.bind(this)),h.on("click","#id_cancel",function(a){f.close(),a.preventDefault()})},i.prototype._setPosition=function(a,c,d,e){var f=b.one("#element-"+a);d=b.one("#pdf").getX()+d*this.PIXELSINMM,e=b.one("#pdf").getY()+e*this.PIXELSINMM;var g=parseFloat(f.getComputedStyle("width")),h=f.width*this.PIXELSINMM;switch(h&&g>h&&(g=h),c){case this.CUSTOMCERT_REF_POINT_TOPCENTER:d-=g/2;break;case this.CUSTOMCERT_REF_POINT_TOPRIGHT:d=d-g+2}f.setX(d),f.setY(e)},i.prototype._setPositionInForm=function(c){var d=a("#editelementform #id_posx"),e=a("#editelementform #id_posy");if(d.length&&e.length){var f=b.one("#element-"+c),g=f.getX()-b.one("#pdf").getX(),h=f.getY()-b.one("#pdf").getY(),i=parseInt(f.getData("refpoint")),j=parseFloat(f.getComputedStyle("width"));switch(i){case this.CUSTOMCERT_REF_POINT_TOPCENTER:g+=j/2;break;case this.CUSTOMCERT_REF_POINT_TOPRIGHT:g+=j}g=Math.round(parseFloat(g/this.PIXELSINMM)),h=Math.round(parseFloat(h/this.PIXELSINMM)),d.val(g),e.val(h)}},i.prototype._getElementHTML=function(a){var b=this._node.attr("data-templateid"),c=h.call([{methodname:"mod_customcert_get_element_html",args:{templateid:b,elementid:a}}]);return c[0]},i.prototype._saveElement=function(b){var c=this._node.attr("data-templateid"),d=a("#editelementform").serializeArray(),e=h.call([{methodname:"mod_customcert_save_element",args:{templateid:c,elementid:b,values:d}}]);return e[0]},{init:function(a){new i(a)}}});

102
amd/src/dialogue.js Normal file
View file

@ -0,0 +1,102 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Wrapper for the YUI M.core.notification class. Allows us to
* use the YUI version in AMD code until it is replaced.
*
* @module mod_customcert/dialogue
* @package mod_customcert
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
define(['core/yui'], function(Y) {
/**
* Constructor
*
* @param {String} title Title for the window.
* @param {String} content The content for the window.
* @param {function} afterShow Callback executed after the window is opened.
* @param {function} afterHide Callback executed after the window is closed.
* @param {Boolean} wide Specify we want an extra wide dialogue (the size is standard, but wider than the default).
*/
var dialogue = function(title, content, afterShow, afterHide, wide) {
this.yuiDialogue = null;
var parent = this;
// Default for wide is false.
if (typeof wide == 'undefined') {
wide = false;
}
Y.use('moodle-core-notification', 'timers', function() {
var width = '480px';
if (wide) {
width = '800px';
}
parent.yuiDialogue = new M.core.dialogue({
headerContent: title,
bodyContent: content,
draggable: true,
visible: false,
center: true,
modal: true,
width: width
});
parent.yuiDialogue.after('visibleChange', function(e) {
if (e.newVal) {
// Delay the callback call to the next tick, otherwise it can happen that it is
// executed before the dialogue constructor returns.
if ((typeof afterShow !== 'undefined')) {
Y.soon(function() {
afterShow(parent);
parent.yuiDialogue.centerDialogue();
});
}
} else {
if ((typeof afterHide !== 'undefined')) {
Y.soon(function() {
afterHide(parent);
});
}
}
});
parent.yuiDialogue.show();
});
};
/**
* Close this window.
*/
dialogue.prototype.close = function() {
this.yuiDialogue.hide();
this.yuiDialogue.destroy();
};
/**
* Get content.
*
* @returns {HTMLElement}
*/
dialogue.prototype.getContent = function() {
return this.yuiDialogue.bodyNode.getDOMNode();
};
return dialogue;
});

213
amd/src/rearrange-area.js Normal file
View file

@ -0,0 +1,213 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* AMD module used when rearranging a custom certificate.
*
* @module mod_customcert/rearrange-area
* @package mod_customcert
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
define(['jquery', 'core/yui', 'core/fragment', 'mod_customcert/dialogue', 'core/notification',
'core/str', 'core/templates', 'core/ajax'],
function($, Y, fragment, Dialogue, notification, str, template, ajax) {
/**
* RearrangeArea class.
*
* @param {String} selector The rearrange PDF selector
*/
var RearrangeArea = function(selector) {
this._node = $(selector);
this._setEvents();
};
RearrangeArea.prototype.CUSTOMCERT_REF_POINT_TOPLEFT = 0;
RearrangeArea.prototype.CUSTOMCERT_REF_POINT_TOPCENTER = 1;
RearrangeArea.prototype.CUSTOMCERT_REF_POINT_TOPRIGHT = 2;
RearrangeArea.prototype.PIXELSINMM = 3.779527559055;
RearrangeArea.prototype._setEvents = function() {
this._node.on('click', '.element', this._editElement.bind(this));
};
RearrangeArea.prototype._editElement = function(event) {
var elementid = event.currentTarget.id.substr(8);
var contextid = this._node.attr('data-contextid');
var params = {
'elementid': elementid
};
fragment.loadFragment('mod_customcert', 'editelement', contextid, params).done(function(html, js) {
str.get_string('editelement', 'mod_customcert').done(function(title) {
Y.use('moodle-core-formchangechecker', function() {
new Dialogue(
title,
'<div id=\'elementcontent\'></div>',
this._editElementDialogueConfig.bind(this, elementid, html, js),
undefined,
true
);
}.bind(this));
}.bind(this));
}.bind(this)).fail(notification.exception);
};
RearrangeArea.prototype._editElementDialogueConfig = function(elementid, html, js, popup) {
// Place the content in the dialogue.
template.replaceNode('#elementcontent', html, js);
// We may have dragged the element changing it's position.
// Ensure the form has the current up-to-date location.
this._setPositionInForm(elementid);
// Add events for when we save, close and cancel the page.
var body = $(popup.getContent());
body.on('click', '#id_submitbutton', function(e) {
// Do not want to ask the user if they wish to stay on page after saving.
M.core_formchangechecker.reset_form_dirty_state();
// Save the data.
this._saveElement(elementid).then(function() {
// Update the DOM to reflect the adjusted value.
this._getElementHTML(elementid).done(function(html) {
var elementNode = this._node.find('#element-' + elementid);
var refpoint = parseInt($('#id_refpoint').val());
var refpointClass = '';
if (refpoint == this.CUSTOMCERT_REF_POINT_TOPLEFT) {
refpointClass = 'refpoint-left';
} else if (refpoint == this.CUSTOMCERT_REF_POINT_TOPCENTER) {
refpointClass = 'refpoint-center';
} else if (refpoint == this.CUSTOMCERT_REF_POINT_TOPRIGHT) {
refpointClass = 'refpoint-right';
}
elementNode.empty().append(html);
// Update the ref point.
elementNode.removeClass();
elementNode.addClass('element ' + refpointClass);
elementNode.attr('data-refpoint', refpoint);
// Move the element.
var posx = $('#editelementform #id_posx').val();
var posy = $('#editelementform #id_posy').val();
this._setPosition(elementid, refpoint, posx, posy);
// All done.
popup.close();
}.bind(this));
}.bind(this)).fail(notification.exception);
e.preventDefault();
}.bind(this));
body.on('click', '#id_cancel', function(e) {
popup.close();
e.preventDefault();
});
};
RearrangeArea.prototype._setPosition = function(elementid, refpoint, posx, posy) {
var element = Y.one('#element-' + elementid);
posx = Y.one('#pdf').getX() + posx * this.PIXELSINMM;
posy = Y.one('#pdf').getY() + posy * this.PIXELSINMM;
var nodewidth = parseFloat(element.getComputedStyle('width'));
var maxwidth = element.width * this.PIXELSINMM;
if (maxwidth && (nodewidth > maxwidth)) {
nodewidth = maxwidth;
}
switch (refpoint) {
case this.CUSTOMCERT_REF_POINT_TOPCENTER:
posx -= nodewidth / 2;
break;
case this.CUSTOMCERT_REF_POINT_TOPRIGHT:
posx = posx - nodewidth + 2;
break;
}
element.setX(posx);
element.setY(posy);
};
RearrangeArea.prototype._setPositionInForm = function(elementid) {
var posxelement = $('#editelementform #id_posx');
var posyelement = $('#editelementform #id_posy');
if (posxelement.length && posyelement.length) {
var element = Y.one('#element-' + elementid);
var posx = element.getX() - Y.one('#pdf').getX();
var posy = element.getY() - Y.one('#pdf').getY();
var refpoint = parseInt(element.getData('refpoint'));
var nodewidth = parseFloat(element.getComputedStyle('width'));
switch (refpoint) {
case this.CUSTOMCERT_REF_POINT_TOPCENTER:
posx += nodewidth / 2;
break;
case this.CUSTOMCERT_REF_POINT_TOPRIGHT:
posx += nodewidth;
break;
}
posx = Math.round(parseFloat(posx / this.PIXELSINMM));
posy = Math.round(parseFloat(posy / this.PIXELSINMM));
posxelement.val(posx);
posyelement.val(posy);
}
};
RearrangeArea.prototype._getElementHTML = function(elementid) {
// Get the variables we need.
var templateid = this._node.attr('data-templateid');
// Call the web service to get the updated element.
var promises = ajax.call([{
methodname: 'mod_customcert_get_element_html',
args: {
templateid: templateid,
elementid: elementid
}
}]);
// Return the promise.
return promises[0];
};
RearrangeArea.prototype._saveElement = function(elementid) {
// Get the variables we need.
var templateid = this._node.attr('data-templateid');
var inputs = $('#editelementform').serializeArray();
// Call the web service to save the element.
var promises = ajax.call([{
methodname: 'mod_customcert_save_element',
args: {
templateid: templateid,
elementid: elementid,
values: inputs
}
}]);
// Return the promise.
return promises[0];
};
return {
init: function(selector) {
new RearrangeArea(selector);
}
};
}
);

View file

@ -1,5 +1,5 @@
<?php
// This file is part of the htmlcert module for Moodle - http://moodle.org/
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@ -17,23 +17,23 @@
/**
* This file contains the backup tasks that provides all the settings and steps to perform a backup of the activity.
*
* @package mod_htmlcert
* @copyright 2013 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
require_once($CFG->dirroot . '/mod/htmlcert/backup/moodle2/backup_htmlcert_stepslib.php');
require_once($CFG->dirroot . '/mod/customcert/backup/moodle2/backup_customcert_stepslib.php');
/**
* Handles creating tasks to peform in order to create the backup.
*
* @package mod_htmlcert
* @copyright 2013 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class backup_htmlcert_activity_task extends backup_activity_task {
class backup_customcert_activity_task extends backup_activity_task {
/**
* Define particular settings this activity can have.
@ -46,8 +46,8 @@ class backup_htmlcert_activity_task extends backup_activity_task {
* Define particular steps this activity can have.
*/
protected function define_my_steps() {
// The htmlcert only has one structure step.
$this->add_step(new backup_htmlcert_activity_structure_step('htmlcert_structure', 'htmlcert.xml'));
// The customcert only has one structure step.
$this->add_step(new backup_customcert_activity_structure_step('customcert_structure', 'customcert.xml'));
}
/**
@ -56,18 +56,18 @@ class backup_htmlcert_activity_task extends backup_activity_task {
* @param string $content
* @return mixed|string
*/
public static function encode_content_links($content) {
static public function encode_content_links($content) {
global $CFG;
$base = preg_quote($CFG->wwwroot, "/");
// Link to the list of htmlcerts.
$search = "/(".$base."\/mod\/htmlcert\/index.php\?id\=)([0-9]+)/";
$content = preg_replace($search, '$@HTMLCERTINDEX*$2@$', $content);
// Link to the list of customcerts.
$search = "/(".$base."\/mod\/customcert\/index.php\?id\=)([0-9]+)/";
$content = preg_replace($search, '$@CUSTOMCERTINDEX*$2@$', $content);
// Link to htmlcert view by moduleid.
$search = "/(".$base."\/mod\/htmlcert\/view.php\?id\=)([0-9]+)/";
$content = preg_replace($search, '$@HTMLCERTVIEWBYID*$2@$', $content);
// Link to customcert view by moduleid.
$search = "/(".$base."\/mod\/customcert\/view.php\?id\=)([0-9]+)/";
$content = preg_replace($search, '$@CUSTOMCERTVIEWBYID*$2@$', $content);
return $content;
}

View file

@ -0,0 +1,104 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Define all the backup steps that will be used by the backup_customcert_activity_task.
*
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
/**
* Define the complete customcert structure for backup, with file and id annotations.
*
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class backup_customcert_activity_structure_step extends backup_activity_structure_step {
/**
* Define the structure of the backup file.
*
* @return backup_nested_element
*/
protected function define_structure() {
// The instance.
$customcert = new backup_nested_element('customcert', array('id'), array(
'templateid', 'name', 'intro', 'introformat', 'requiredtime', 'verifyany', 'emailstudents',
'emailteachers', 'emailothers', 'protection', 'timecreated', 'timemodified'));
// The template.
$template = new backup_nested_element('template', array('id'), array(
'name', 'contextid', 'timecreated', 'timemodified'));
// The pages.
$pages = new backup_nested_element('pages');
$page = new backup_nested_element('page', array('id'), array(
'templateid', 'width', 'height', 'leftmargin', 'rightmargin',
'sequence', 'timecreated', 'timemodified'));
// The elements.
$element = new backup_nested_element('element', array('id'), array(
'pageid', 'name', 'element', 'data', 'font', 'fontsize',
'colour', 'posx', 'posy', 'width', 'refpoint', 'sequence',
'timecreated', 'timemodified'));
// The issues.
$issues = new backup_nested_element('issues');
$issue = new backup_nested_element('issue', array('id'), array(
'customcertid', 'userid', 'timecreated', 'emailed', 'code'));
// Build the tree.
$customcert->add_child($issues);
$issues->add_child($issue);
$customcert->add_child($template);
$template->add_child($pages);
$pages->add_child($page);
$page->add_child($element);
// Define sources.
$customcert->set_source_table('customcert', array('id' => backup::VAR_ACTIVITYID));
// Define template source.
$template->set_source_table('customcert_templates', array('contextid' => backup::VAR_CONTEXTID));
// Define page source.
$page->set_source_table('customcert_pages', array('templateid' => backup::VAR_PARENTID));
// Define element source, each element belongs to a page.
$element->set_source_table('customcert_elements', array('pageid' => backup::VAR_PARENTID));
// If we are including user info then save the issues.
if ($this->get_setting_value('userinfo')) {
$issue->set_source_table('customcert_issues', array('customcertid' => backup::VAR_ACTIVITYID));
}
// Annotate the user id's where required.
$issue->annotate_ids('user', 'userid');
// Define file annotations.
$customcert->annotate_files('mod_customcert', 'intro', null);
$customcert->annotate_files('mod_customcert', 'image', null, context_course::instance($this->get_courseid())->id);
// Return the root element (customcert), wrapped into standard activity structure.
return $this->prepare_activity_structure($customcert);
}
}

View file

@ -1,83 +0,0 @@
<?php
// This file is part of the htmlcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Define all the backup steps that will be used by the backup_htmlcert_activity_task.
*
* @package mod_htmlcert
* @copyright 2013 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
/**
* Define the complete htmlcert structure for backup, with file and id annotations.
*
* @package mod_htmlcert
* @copyright 2013 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class backup_htmlcert_activity_structure_step extends backup_activity_structure_step {
/**
* Define the structure of the backup file.
*
* @return backup_nested_element
*/
protected function define_structure() {
// The instance.
$htmlcert = new backup_nested_element('htmlcert', array('id'), array(
'templateid', 'name', 'intro', 'introformat', 'requiredtime', 'verifyany', 'emailstudents',
'emailteachers', 'emailothers', 'protection', 'timecreated', 'timemodified'));
// The template.
$template = new backup_nested_element('template', array('id'), array(
'name', 'html', 'contextid', 'timecreated', 'timemodified'));
// The issues.
$issues = new backup_nested_element('issues');
$issue = new backup_nested_element('issue', array('id'), array(
'htmlcertid', 'userid', 'timecreated', 'emailed', 'code'));
// Build the tree.
$htmlcert->add_child($issues);
$issues->add_child($issue);
$htmlcert->add_child($template);
// Define sources.
$htmlcert->set_source_table('htmlcert', array('id' => backup::VAR_ACTIVITYID));
// Define template source.
$template->set_source_table('htmlcert_templates', array('contextid' => backup::VAR_CONTEXTID));
// If we are including user info then save the issues.
if ($this->get_setting_value('userinfo')) {
$issue->set_source_table('htmlcert_issues', array('htmlcertid' => backup::VAR_ACTIVITYID));
}
// Annotate the user id's where required.
$issue->annotate_ids('user', 'userid');
// Define file annotations.
$htmlcert->annotate_files('mod_htmlcert', 'intro', null);
$htmlcert->annotate_files('mod_htmlcert', 'image', null, context_course::instance($this->get_courseid())->id);
// Return the root element (htmlcert), wrapped into standard activity structure.
return $this->prepare_activity_structure($htmlcert);
}
}

View file

@ -0,0 +1,121 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Define all the restore steps that will be used by the restore_customcert_activity_task.
*
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
require_once($CFG->dirroot . '/mod/customcert/backup/moodle2/restore_customcert_stepslib.php');
/**
* The class definition for assigning tasks that provide the settings and steps to perform a restore of the activity.
*
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class restore_customcert_activity_task extends restore_activity_task {
/**
* Define particular settings this activity can have.
*/
protected function define_my_settings() {
// No particular settings for this activity.
}
/**
* Define particular steps this activity can have.
*/
protected function define_my_steps() {
// The customcert only has one structure step.
$this->add_step(new restore_customcert_activity_structure_step('customcert_structure', 'customcert.xml'));
}
/**
* Define the contents in the activity that must be processed by the link decoder.
*/
static public function define_decode_contents() {
$contents = array();
$contents[] = new restore_decode_content('customcert', array('intro'), 'customcert');
return $contents;
}
/**
* Define the decoding rules for links belonging to the activity to be executed by the link decoder.
*/
static public function define_decode_rules() {
$rules = array();
$rules[] = new restore_decode_rule('CUSTOMCERTVIEWBYID', '/mod/customcert/view.php?id=$1', 'course_module');
$rules[] = new restore_decode_rule('CUSTOMCERTINDEX', '/mod/customcert/index.php?id=$1', 'course');
return $rules;
}
/**
* Define the restore log rules that will be applied by the {@link restore_logs_processor} when restoring
* customcert logs. It must return one array of {@link restore_log_rule} objects.
*
* @return array the restore log rules
*/
static public function define_restore_log_rules() {
$rules = array();
$rules[] = new restore_log_rule('customcert', 'add', 'view.php?id={course_module}', '{customcert}');
$rules[] = new restore_log_rule('customcert', 'update', 'view.php?id={course_module}', '{customcert}');
$rules[] = new restore_log_rule('customcert', 'view', 'view.php?id={course_module}', '{customcert}');
$rules[] = new restore_log_rule('customcert', 'received', 'view.php?id={course_module}', '{customcert}');
$rules[] = new restore_log_rule('customcert', 'view report', 'view.php?id={course_module}', '{customcert}');
return $rules;
}
/**
* This function is called after all the activities in the backup have been restored. This allows us to get
* the new course module ids, as they may have been restored after the customcert module, meaning no id
* was available at the time.
*/
public function after_restore() {
global $DB;
// Get the customcert elements.
$sql = "SELECT e.*
FROM {customcert_elements} e
INNER JOIN {customcert_pages} p
ON e.pageid = p.id
INNER JOIN {customcert} c
ON p.templateid = c.templateid
WHERE c.id = :customcertid";
if ($elements = $DB->get_records_sql($sql, array('customcertid' => $this->get_activityid()))) {
// Go through the elements for the certificate.
foreach ($elements as $e) {
// Get an instance of the element class.
if ($e = \mod_customcert\element_factory::get_element_instance($e)) {
$e->after_restore($this);
}
}
}
}
}

View file

@ -0,0 +1,179 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Define all the restore steps that will be used by the restore_customcert_activity_task.
*
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
/**
* Define the complete customcert structure for restore, with file and id annotations.
*
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class restore_customcert_activity_structure_step extends restore_activity_structure_step {
/**
* Define the different items to restore.
*
* @return array the restore paths
*/
protected function define_structure() {
// The array used to store the path to the items we want to restore.
$paths = array();
// The customcert instance.
$paths[] = new restore_path_element('customcert', '/activity/customcert');
// The templates.
$paths[] = new restore_path_element('customcert_template', '/activity/customcert/template');
// The pages.
$paths[] = new restore_path_element('customcert_page', '/activity/customcert/template/pages/page');
// The elements.
$paths[] = new restore_path_element('customcert_element', '/activity/customcert/template/pages/page/element');
// Check if we want the issues as well.
if ($this->get_setting_value('userinfo')) {
$paths[] = new restore_path_element('customcert_issue', '/activity/customcert/issues/issue');
}
// Return the paths wrapped into standard activity structure.
return $this->prepare_activity_structure($paths);
}
/**
* Handles restoring the customcert activity.
*
* @param stdClass $data the customcert data
*/
protected function process_customcert($data) {
global $DB;
$data = (object) $data;
$data->course = $this->get_courseid();
$data->timecreated = $this->apply_date_offset($data->timecreated);
$data->timemodified = $this->apply_date_offset($data->timemodified);
// Insert the customcert record.
$newitemid = $DB->insert_record('customcert', $data);
// Immediately after inserting record call this.
$this->apply_activity_instance($newitemid);
}
/**
* Handles restoring a customcert page.
*
* @param stdClass $data the customcert data
*/
protected function process_customcert_template($data) {
global $DB;
$data = (object) $data;
$oldid = $data->id;
$data->contextid = $this->task->get_contextid();
$data->timecreated = $this->apply_date_offset($data->timecreated);
$data->timemodified = $this->apply_date_offset($data->timemodified);
$newitemid = $DB->insert_record('customcert_templates', $data);
$this->set_mapping('customcert_template', $oldid, $newitemid);
// Update the template id for the customcert.
$customcert = new stdClass();
$customcert->id = $this->get_new_parentid('customcert');
$customcert->templateid = $newitemid;
$DB->update_record('customcert', $customcert);
}
/**
* Handles restoring a customcert template.
*
* @param stdClass $data the customcert data
*/
protected function process_customcert_page($data) {
global $DB;
$data = (object) $data;
$oldid = $data->id;
$data->templateid = $this->get_new_parentid('customcert_template');
$data->timecreated = $this->apply_date_offset($data->timecreated);
$data->timemodified = $this->apply_date_offset($data->timemodified);
$newitemid = $DB->insert_record('customcert_pages', $data);
$this->set_mapping('customcert_page', $oldid, $newitemid);
}
/**
* Handles restoring a customcert element.
*
* @param stdclass $data the customcert data
*/
protected function process_customcert_element($data) {
global $DB;
$data = (object) $data;
$oldid = $data->id;
$data->pageid = $this->get_new_parentid('customcert_page');
$data->timecreated = $this->apply_date_offset($data->timecreated);
$data->timemodified = $this->apply_date_offset($data->timemodified);
$newitemid = $DB->insert_record('customcert_elements', $data);
$this->set_mapping('customcert_element', $oldid, $newitemid);
}
/**
* Handles restoring a customcert issue.
*
* @param stdClass $data the customcert data
*/
protected function process_customcert_issue($data) {
global $DB;
$data = (object) $data;
$oldid = $data->id;
$data->customcertid = $this->get_new_parentid('customcert');
$data->timecreated = $this->apply_date_offset($data->timecreated);
$newitemid = $DB->insert_record('customcert_issues', $data);
$this->set_mapping('customcert_issue', $oldid, $newitemid);
}
/**
* Called immediately after all the other restore functions.
*/
protected function after_execute() {
parent::after_execute();
// Add the files.
$this->add_related_files('mod_customcert', 'intro', null);
// Note - we can't use get_old_contextid() as it refers to the module context.
$this->add_related_files('mod_customcert', 'image', null, $this->get_task()->get_info()->original_course_contextid);
}
}

View file

@ -1,103 +0,0 @@
<?php
// This file is part of the htmlcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Define all the restore steps that will be used by the restore_htmlcert_activity_task.
*
* @package mod_htmlcert
* @copyright 2013 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
require_once($CFG->dirroot . '/mod/htmlcert/backup/moodle2/restore_htmlcert_stepslib.php');
/**
* The class definition for assigning tasks that provide the settings and steps to perform a restore of the activity.
*
* @package mod_htmlcert
* @copyright 2013 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class restore_htmlcert_activity_task extends restore_activity_task {
/**
* Define particular settings this activity can have.
*/
protected function define_my_settings() {
// No particular settings for this activity.
}
/**
* Define particular steps this activity can have.
*/
protected function define_my_steps() {
// The htmlcert only has one structure step.
$this->add_step(new restore_htmlcert_activity_structure_step('htmlcert_structure', 'htmlcert.xml'));
}
/**
* Define the contents in the activity that must be processed by the link decoder.
*/
public static function define_decode_contents() {
$contents = array();
$contents[] = new restore_decode_content('htmlcert', array('intro'), 'htmlcert');
return $contents;
}
/**
* Define the decoding rules for links belonging to the activity to be executed by the link decoder.
*/
public static function define_decode_rules() {
$rules = array();
$rules[] = new restore_decode_rule('HTMLCERTVIEWBYID', '/mod/htmlcert/view.php?id=$1', 'course_module');
$rules[] = new restore_decode_rule('HTMLCERTINDEX', '/mod/htmlcert/index.php?id=$1', 'course');
return $rules;
}
/**
* Define the restore log rules that will be applied by the {@see restore_logs_processor} when restoring
* htmlcert logs. It must return one array of {@see restore_log_rule} objects.
*
* @return array the restore log rules
*/
public static function define_restore_log_rules() {
$rules = array();
$rules[] = new restore_log_rule('htmlcert', 'add', 'view.php?id={course_module}', '{htmlcert}');
$rules[] = new restore_log_rule('htmlcert', 'update', 'view.php?id={course_module}', '{htmlcert}');
$rules[] = new restore_log_rule('htmlcert', 'view', 'view.php?id={course_module}', '{htmlcert}');
$rules[] = new restore_log_rule('htmlcert', 'received', 'view.php?id={course_module}', '{htmlcert}');
$rules[] = new restore_log_rule('htmlcert', 'view report', 'view.php?id={course_module}', '{htmlcert}');
return $rules;
}
/**
* This function is called after all the activities in the backup have been restored. This allows us to get
* the new course module ids, as they may have been restored after the htmlcert module, meaning no id
* was available at the time.
*/
public function after_restore() {
global $DB;
}
}

View file

@ -1,136 +0,0 @@
<?php
// This file is part of the htmlcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Define all the restore steps that will be used by the restore_htmlcert_activity_task.
*
* @package mod_htmlcert
* @copyright 2013 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
/**
* Define the complete htmlcert structure for restore, with file and id annotations.
*
* @package mod_htmlcert
* @copyright 2013 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class restore_htmlcert_activity_structure_step extends restore_activity_structure_step {
/**
* Define the different items to restore.
*
* @return array the restore paths
*/
protected function define_structure() {
// The array used to store the path to the items we want to restore.
$paths = array();
// The htmlcert instance.
$paths[] = new restore_path_element('htmlcert', '/activity/htmlcert');
// The templates.
$paths[] = new restore_path_element('htmlcert_template', '/activity/htmlcert/template');
// Check if we want the issues as well.
if ($this->get_setting_value('userinfo')) {
$paths[] = new restore_path_element('htmlcert_issue', '/activity/htmlcert/issues/issue');
}
// Return the paths wrapped into standard activity structure.
return $this->prepare_activity_structure($paths);
}
/**
* Handles restoring the htmlcert activity.
*
* @param stdClass $data the htmlcert data
*/
protected function process_htmlcert($data) {
global $DB;
$data = (object) $data;
$data->course = $this->get_courseid();
$data->timecreated = $this->apply_date_offset($data->timecreated);
$data->timemodified = $this->apply_date_offset($data->timemodified);
// Insert the htmlcert record.
$newitemid = $DB->insert_record('htmlcert', $data);
// Immediately after inserting record call this.
$this->apply_activity_instance($newitemid);
}
/**
* Handles restoring a htmlcert templage.
*
* @param stdClass $data the htmlcert data
*/
protected function process_htmlcert_template($data) {
global $DB;
$data = (object) $data;
$oldid = $data->id;
$data->contextid = $this->task->get_contextid();
$data->timecreated = $this->apply_date_offset($data->timecreated);
$data->timemodified = $this->apply_date_offset($data->timemodified);
$newitemid = $DB->insert_record('htmlcert_templates', $data);
$this->set_mapping('htmlcert_template', $oldid, $newitemid);
// Update the template id for the htmlcert.
$htmlcert = new stdClass();
$htmlcert->id = $this->get_new_parentid('htmlcert');
$htmlcert->templateid = $newitemid;
$DB->update_record('htmlcert', $htmlcert);
}
/**
* Handles restoring a htmlcert issue.
*
* @param stdClass $data the htmlcert data
*/
protected function process_htmlcert_issue($data) {
global $DB;
$data = (object) $data;
$oldid = $data->id;
$data->htmlcertid = $this->get_new_parentid('htmlcert');
$data->timecreated = $this->apply_date_offset($data->timecreated);
$data->userid = $this->get_mappingid('user', $data->userid);
$newitemid = $DB->insert_record('htmlcert_issues', $data);
$this->set_mapping('htmlcert_issue', $oldid, $newitemid);
}
/**
* Called immediately after all the other restore functions.
*/
protected function after_execute() {
parent::after_execute();
// Add the files.
$this->add_related_files('mod_htmlcert', 'intro', null);
// Note - we can't use get_old_contextid() as it refers to the module context.
$this->add_related_files('mod_htmlcert', 'image', null, $this->get_task()->get_info()->original_course_contextid);
}
}

View file

@ -1,5 +1,5 @@
<?php
// This file is part of the htmlcert module for Moodle - http://moodle.org/
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@ -17,12 +17,12 @@
/**
* Creates an upload form on the settings page.
*
* @package mod_htmlcert
* @copyright 2013 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert;
namespace mod_customcert;
defined('MOODLE_INTERNAL') || die();
@ -31,8 +31,8 @@ require_once($CFG->libdir.'/adminlib.php');
/**
* Class extends admin setting class to allow/process an uploaded file
*
* @package mod_htmlcert
* @copyright 2013 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class admin_setting_link extends \admin_setting_configtext {
@ -80,4 +80,4 @@ class admin_setting_link extends \admin_setting_configtext {
return format_admin_setting($this, $this->visiblename,
\html_writer::link($this->link, $this->linkname), $this->description, true, '', null, $query);
}
}
}

View file

@ -1,5 +1,5 @@
<?php
// This file is part of the htmlcert module for Moodle - http://moodle.org/
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@ -15,14 +15,14 @@
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Provides functionality needed by htmlcert activities.
* Provides functionality needed by customcert activities.
*
* @package mod_htmlcert
* @copyright 2016 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert;
namespace mod_customcert;
defined('MOODLE_INTERNAL') || die();
@ -31,22 +31,12 @@ defined('MOODLE_INTERNAL') || die();
*
* Helper functionality for certificates.
*
* @package mod_htmlcert
* @copyright 2016 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class certificate {
/**
* Send the file inline to the browser.
*/
const DELIVERY_OPTION_INLINE = 'I';
/**
* Send to the browser and force a file download
*/
const DELIVERY_OPTION_DOWNLOAD = 'D';
/**
* @var string the print protection variable
*/
@ -64,12 +54,12 @@ class certificate {
/**
* @var int the number of issues that will be displayed on each page in the report
* If you want to display all htmlcerts on a page set this to 0.
* If you want to display all customcerts on a page set this to 0.
*/
const HTMLCERT_PER_PAGE = '50';
const CUSTOMCERT_PER_PAGE = '50';
/**
* Handles setting the protection field for the htmlcert
* Handles setting the protection field for the customcert
*
* @param \stdClass $data
* @return string the value to insert into the protection field
@ -92,7 +82,7 @@ class certificate {
}
/**
* Handles uploading an image for the htmlcert module.
* Handles uploading an image for the customcert module.
*
* @param int $draftitemid the draft area containing the files
* @param int $contextid the context we are storing this image in
@ -103,7 +93,69 @@ class certificate {
// Save the file if it exists that is currently in the draft area.
require_once($CFG->dirroot . '/lib/filelib.php');
file_save_draft_area_files($draftitemid, $contextid, 'mod_htmlcert', $filearea, 0);
file_save_draft_area_files($draftitemid, $contextid, 'mod_customcert', $filearea, 0);
}
/**
* Return the list of possible fonts to use.
*/
public static function get_fonts() {
global $CFG;
require_once($CFG->libdir . '/pdflib.php');
$arrfonts = [];
$pdf = new \pdf();
$fontfamilies = $pdf->get_font_families();
foreach ($fontfamilies as $fontfamily => $fontstyles) {
foreach ($fontstyles as $fontstyle) {
$fontstyle = strtolower($fontstyle);
if ($fontstyle == 'r') {
$filenamewoextension = $fontfamily;
} else {
$filenamewoextension = $fontfamily . $fontstyle;
}
$fullpath = \TCPDF_FONTS::_getfontpath() . $filenamewoextension;
// Set the name of the font to null, the include next should then set this
// value, if it is not set then the file does not include the necessary data.
$name = null;
// Some files include a display name, the include next should then set this
// value if it is present, if not then $name is used to create the display name.
$displayname = null;
// Some of the TCPDF files include files that are not present, so we have to
// suppress warnings, this is the TCPDF libraries fault, grrr.
@include($fullpath . '.php');
// If no $name variable in file, skip it.
if (is_null($name)) {
continue;
}
// Check if there is no display name to use.
if (is_null($displayname)) {
// Format the font name, so "FontName-Style" becomes "Font Name - Style".
$displayname = preg_replace("/([a-z])([A-Z])/", "$1 $2", $name);
$displayname = preg_replace("/([a-zA-Z])-([a-zA-Z])/", "$1 - $2", $displayname);
}
$arrfonts[$filenamewoextension] = $displayname;
}
}
ksort($arrfonts);
return $arrfonts;
}
/**
* Return the list of possible font sizes to use.
*/
public static function get_font_sizes() {
// Array to store the sizes.
$sizes = array();
for ($i = 1; $i <= 200; $i++) {
$sizes[$i] = $i;
}
return $sizes;
}
/**
@ -113,7 +165,7 @@ class certificate {
* @param int $userid
* @return int the total time spent in seconds
*/
public static function get_course_time(int $courseid, int $userid = 0): int {
public static function get_course_time($courseid, $userid = 0) {
global $CFG, $DB, $USER;
if (empty($userid)) {
@ -165,7 +217,7 @@ class certificate {
$totaltime = 0;
}
$delay = $log->$timefield - $lasthit;
if ($delay > $CFG->sessiontimeout) {
if ($delay > ($CFG->sessiontimeout * 60)) {
// The difference between the last log and the current log is more than
// the timeout Register session value so that we have found a session!
$login = $log->$timefield;
@ -183,9 +235,9 @@ class certificate {
}
/**
* Returns a list of issued htmlcerts.
* Returns a list of issued customcerts.
*
* @param int $htmlcertid
* @param int $customcertid
* @param bool $groupmode are we in group mode
* @param \stdClass $cm the course module
* @param int $limitfrom
@ -193,7 +245,7 @@ class certificate {
* @param string $sort
* @return array the users
*/
public static function get_issues($htmlcertid, $groupmode, $cm, $limitfrom, $limitnum, $sort = '') {
public static function get_issues($customcertid, $groupmode, $cm, $limitfrom, $limitnum, $sort = '') {
global $DB;
// Get the conditional SQL.
@ -204,26 +256,18 @@ class certificate {
return array();
}
// Add the conditional SQL and the htmlcertid to form all used parameters.
$allparams = $conditionsparams + array('htmlcertid' => $htmlcertid);
// Add the conditional SQL and the customcertid to form all used parameters.
$allparams = $conditionsparams + array('customcertid' => $customcertid);
// Return the issues.
$context = \context_module::instance($cm->id);
$extrafields = \core_user\fields::for_identity($context)->get_required_fields();
$ufields = \core_user\fields::for_userpic()->including(...$extrafields);
[
'selects' => $userfieldsselects,
'joins' => $userfieldsjoin,
'params' => $userfieldsparams
] = (array) $ufields->get_sql('u', true);
$allparams = array_merge($allparams, $userfieldsparams);
$sql = "SELECT ci.id as issueid, ci.code, ci.timecreated $userfieldsselects
$extrafields = get_extra_user_fields(\context_module::instance($cm->id));
$ufields = \user_picture::fields('u', $extrafields);
$sql = "SELECT $ufields, ci.id as issueid, ci.code, ci.timecreated
FROM {user} u
INNER JOIN {htmlcert_issues} ci ON u.id = ci.userid
$userfieldsjoin
INNER JOIN {customcert_issues} ci
ON u.id = ci.userid
WHERE u.deleted = 0
AND ci.htmlcertid = :htmlcertid
AND ci.customcertid = :customcertid
$conditionssql";
if ($sort) {
$sql .= "ORDER BY " . $sort;
@ -235,14 +279,14 @@ class certificate {
}
/**
* Returns the total number of issues for a given htmlcert.
* Returns the total number of issues for a given customcert.
*
* @param int $htmlcertid
* @param int $customcertid
* @param \stdClass $cm the course module
* @param bool $groupmode the group mode
* @return int the number of issues
*/
public static function get_number_of_issues($htmlcertid, $cm, $groupmode) {
public static function get_number_of_issues($customcertid, $cm, $groupmode) {
global $DB;
// Get the conditional SQL.
@ -253,16 +297,16 @@ class certificate {
return 0;
}
// Add the conditional SQL and the htmlcertid to form all used parameters.
$allparams = $conditionsparams + array('htmlcertid' => $htmlcertid);
// Add the conditional SQL and the customcertid to form all used parameters.
$allparams = $conditionsparams + array('customcertid' => $customcertid);
// Return the number of issues.
$sql = "SELECT COUNT(u.id) as count
FROM {user} u
INNER JOIN {htmlcert_issues} ci
INNER JOIN {customcert_issues} ci
ON u.id = ci.userid
WHERE u.deleted = 0
AND ci.htmlcertid = :htmlcertid
AND ci.customcertid = :customcertid
$conditionssql";
return $DB->count_records_sql($sql, $allparams);
}
@ -277,13 +321,13 @@ class certificate {
public static function get_conditional_issues_sql($cm, $groupmode) {
global $DB, $USER;
// Get all users that can manage this htmlcert to exclude them from the report.
// Get all users that can manage this customcert to exclude them from the report.
$context = \context_module::instance($cm->id);
$conditionssql = '';
$conditionsparams = array();
// Get all users that can manage this certificate to exclude them from the report.
$certmanagers = array_keys(get_users_by_capability($context, 'mod/htmlcert:manage', 'u.id'));
$certmanagers = array_keys(get_users_by_capability($context, 'mod/customcert:manage', 'u.id'));
$certmanagers = array_merge($certmanagers, array_keys(get_admins()));
list($sql, $params) = $DB->get_in_or_equal($certmanagers, SQL_PARAMS_NAMED, 'cert');
$conditionssql .= "AND NOT u.id $sql \n";
@ -340,9 +384,9 @@ class certificate {
global $DB;
$sql = "SELECT COUNT(*)
FROM {htmlcert} c
INNER JOIN {htmlcert_issues} ci
ON c.id = ci.htmlcertid
FROM {customcert} c
INNER JOIN {customcert_issues} ci
ON c.id = ci.customcertid
WHERE ci.userid = :userid";
return $DB->count_records_sql($sql, array('userid' => $userid));
}
@ -364,9 +408,9 @@ class certificate {
}
$sql = "SELECT c.id, c.name, co.fullname as coursename, ci.code, ci.timecreated
FROM {htmlcert} c
INNER JOIN {htmlcert_issues} ci
ON c.id = ci.htmlcertid
FROM {customcert} c
INNER JOIN {customcert_issues} ci
ON c.id = ci.customcertid
INNER JOIN {course} co
ON c.course = co.id
WHERE ci.userid = :userid
@ -386,13 +430,13 @@ class certificate {
$issue = new \stdClass();
$issue->userid = $userid;
$issue->htmlcertid = $certificateid;
$issue->customcertid = $certificateid;
$issue->code = self::generate_code();
$issue->emailed = 0;
$issue->timecreated = time();
// Insert the record into the database.
return $DB->insert_record('htmlcert_issues', $issue);
return $DB->insert_record('customcert_issues', $issue);
}
/**
@ -406,7 +450,7 @@ class certificate {
$uniquecodefound = false;
$code = random_string(10);
while (!$uniquecodefound) {
if (!$DB->record_exists('htmlcert_issues', array('code' => $code))) {
if (!$DB->record_exists('customcert_issues', array('code' => $code))) {
$uniquecodefound = true;
} else {
$code = random_string(10);

View file

@ -0,0 +1,98 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the form for handling editing a customcert element.
*
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_customcert;
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
require_once($CFG->dirroot . '/course/moodleform_mod.php');
require_once($CFG->dirroot . '/mod/customcert/includes/colourpicker.php');
\MoodleQuickForm::registerElementType('customcert_colourpicker',
$CFG->dirroot . '/mod/customcert/includes/colourpicker.php', 'MoodleQuickForm_customcert_colourpicker');
/**
* The form for handling editing a customcert element.
*
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class edit_element_form extends \moodleform {
/**
* @var \mod_customcert\element The element object.
*/
protected $element;
/**
* Form definition.
*/
public function definition() {
$mform =& $this->_form;
$mform->updateAttributes(array('id' => 'editelementform'));
$element = $this->_customdata['element'];
// Add the field for the name of the element, this is required for all elements.
$mform->addElement('text', 'name', get_string('elementname', 'customcert'), 'maxlength="255"');
$mform->setType('name', PARAM_TEXT);
$mform->setDefault('name', get_string('pluginname', 'customcertelement_' . $element->element));
$mform->addRule('name', get_string('required'), 'required', null, 'client');
$mform->addHelpButton('name', 'elementname', 'customcert');
$this->element = \mod_customcert\element_factory::get_element_instance($element);
$this->element->set_edit_element_form($this);
$this->element->render_form_elements($mform);
$this->add_action_buttons(true);
}
/**
* Fill in the current page data for this customcert.
*/
public function definition_after_data() {
$this->element->definition_after_data($this->_form);
}
/**
* Validation.
*
* @param array $data
* @param array $files
* @return array the errors that were found
*/
public function validation($data, $files) {
$errors = array();
if (\core_text::strlen($data['name']) > 255) {
$errors['name'] = get_string('nametoolong', 'customcert');
}
$errors += $this->element->validate_form_elements($data, $files);
return $errors;
}
}

View file

@ -1,5 +1,5 @@
<?php
// This file is part of the htmlcert module for Moodle - http://moodle.org/
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@ -15,24 +15,28 @@
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the form for handling the layout of the htmlcert instance.
* This file contains the form for handling the layout of the customcert instance.
*
* @package mod_htmlcert
* @copyright 2013 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert;
namespace mod_customcert;
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
require_once($CFG->dirroot . '/course/moodleform_mod.php');
require_once($CFG->dirroot . '/mod/customcert/includes/colourpicker.php');
\MoodleQuickForm::registerElementType('customcert_colourpicker',
$CFG->dirroot . '/mod/customcert/includes/colourpicker.php', 'MoodleQuickForm_customcert_colourpicker');
/**
* The form for handling the layout of the htmlcert instance.
* The form for handling the layout of the customcert instance.
*
* @package mod_htmlcert
* @copyright 2013 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class edit_form extends \moodleform {
@ -42,6 +46,11 @@ class edit_form extends \moodleform {
*/
protected $tid = null;
/**
* @var int The total number of pages for this cert.
*/
protected $numpages = 1;
/**
* Form definition.
*/
@ -50,26 +59,82 @@ class edit_form extends \moodleform {
$mform =& $this->_form;
$mform->addElement('text', 'name', get_string('name', 'htmlcert'), 'maxlength="255"');
$mform->addElement('text', 'name', get_string('name', 'customcert'), 'maxlength="255"');
$mform->setType('name', PARAM_TEXT);
$mform->addRule('name', null, 'required');
$mform->addElement('textarea', 'html', get_string('html', 'htmlcert'));
$mform->setType('html', PARAM_RAW);
// Get the number of pages for this module.
if (isset($this->_customdata['tid'])) {
$this->tid = $this->_customdata['tid'];
if ($pages = $DB->get_records('customcert_pages', array('templateid' => $this->tid), 'sequence')) {
$this->numpages = count($pages);
foreach ($pages as $p) {
$this->add_customcert_page_elements($p);
}
}
} else { // Add a new template.
// Create a 'fake' page to display the elements on - not yet saved in the DB.
$page = new \stdClass();
$page->id = 0;
$page->sequence = 1;
$this->add_customcert_page_elements($page);
}
// Link to add another page, only display it when the template has been created.
if (isset($this->_customdata['tid'])) {
$addpagelink = new \moodle_url('/mod/customcert/edit.php',
array(
'tid' => $this->tid,
'aid' => 1,
'action' => 'addpage',
'sesskey' => sesskey()
)
);
$icon = $OUTPUT->pix_icon('t/switch_plus', get_string('addcertpage', 'customcert'));
$addpagehtml = \html_writer::link($addpagelink, $icon . get_string('addcertpage', 'customcert'));
$mform->addElement('html', \html_writer::tag('div', $addpagehtml, array('class' => 'addpage')));
}
// Add the submit buttons.
$group = array();
$group[] = $mform->createElement('submit', 'submitbtn', get_string('savechanges'));
$group[] = $mform->createElement('submit', 'previewbtn', get_string('savechangespreview', 'htmlcert'), array(), false);
$group[] = $mform->createElement('submit', 'previewbtn', get_string('savechangespreview', 'customcert'), array(), false);
$mform->addElement('group', 'submitbtngroup', '', $group, '', false);
$mform->addElement('hidden', 'tid');
$mform->setType('tid', PARAM_INT);
$mform->setDefault('tid', $this->tid);
}
/**
* Fill in the current page data for this htmlcert.
* Fill in the current page data for this customcert.
*/
public function definition_after_data() {
global $DB;
$mform = $this->_form;
// Check that we are updating a current customcert.
if ($this->tid) {
// Get the pages for this customcert.
if ($pages = $DB->get_records('customcert_pages', array('templateid' => $this->tid))) {
// Loop through the pages.
foreach ($pages as $p) {
// Set the width.
$element = $mform->getElement('pagewidth_' . $p->id);
$element->setValue($p->width);
// Set the height.
$element = $mform->getElement('pageheight_' . $p->id);
$element->setValue($p->height);
// Set the left margin.
$element = $mform->getElement('pageleftmargin_' . $p->id);
$element->setValue($p->leftmargin);
// Set the right margin.
$element = $mform->getElement('pagerightmargin_' . $p->id);
$element->setValue($p->rightmargin);
}
}
}
}
/**
@ -83,7 +148,39 @@ class edit_form extends \moodleform {
$errors = parent::validation($data, $files);
if (\core_text::strlen($data['name']) > 255) {
$errors['name'] = get_string('nametoolong', 'htmlcert');
$errors['name'] = get_string('nametoolong', 'customcert');
}
// Go through the data and check any width, height or margin values.
foreach ($data as $key => $value) {
if (strpos($key, 'pagewidth_') !== false) {
$page = str_replace('pagewidth_', '', $key);
$widthid = 'pagewidth_' . $page;
// Validate that the width is a valid value.
if ((!isset($data[$widthid])) || (!is_numeric($data[$widthid])) || ($data[$widthid] <= 0)) {
$errors[$widthid] = get_string('invalidwidth', 'customcert');
}
}
if (strpos($key, 'pageheight_') !== false) {
$page = str_replace('pageheight_', '', $key);
$heightid = 'pageheight_' . $page;
// Validate that the height is a valid value.
if ((!isset($data[$heightid])) || (!is_numeric($data[$heightid])) || ($data[$heightid] <= 0)) {
$errors[$heightid] = get_string('invalidheight', 'customcert');
}
}
if (strpos($key, 'pageleftmargin_') !== false) {
// Validate that the left margin is a valid value.
if (isset($data[$key]) && ($data[$key] < 0)) {
$errors[$key] = get_string('invalidmargin', 'customcert');
}
}
if (strpos($key, 'pagerightmargin_') !== false) {
// Validate that the right margin is a valid value.
if (isset($data[$key]) && ($data[$key] < 0)) {
$errors[$key] = get_string('invalidmargin', 'customcert');
}
}
}
return $errors;
@ -92,28 +189,126 @@ class edit_form extends \moodleform {
/**
* Adds the page elements to the form.
*
* @param \stdClass $page the htmlcert page
* @param \stdClass $page the customcert page
*/
protected function add_htmlcert_page_elements($page) {
protected function add_customcert_page_elements($page) {
global $DB, $OUTPUT;
// Create the form object.
$mform =& $this->_form;
$editlink = '/mod/htmlcert/edit.php';
if ($this->numpages > 1) {
$mform->addElement('header', 'page_' . $page->id, get_string('page', 'customcert', $page->sequence));
}
$editlink = '/mod/customcert/edit.php';
$editlinkparams = array('tid' => $this->tid, 'sesskey' => sesskey());
$editelementlink = '/mod/customcert/edit_element.php';
$editelementlinkparams = array('tid' => $this->tid, 'sesskey' => sesskey());
$mform->addElement('text', 'pagewidth', get_string('width', 'htmlcert'));
$mform->setType('pagewidth', PARAM_INT);
$mform->setDefault('pagewidth', '210');
$mform->addRule('pagewidth', null, 'required', null, 'client');
$mform->addHelpButton('pagewidth', 'width', 'htmlcert');
// Place the ordering arrows.
// Only display the move up arrow if it is not the first.
if ($page->sequence > 1) {
$url = new \moodle_url($editlink, $editlinkparams + array('action' => 'pmoveup', 'aid' => $page->id));
$mform->addElement('html', $OUTPUT->action_icon($url, new \pix_icon('t/up', get_string('moveup'))));
}
// Only display the move down arrow if it is not the last.
if ($page->sequence < $this->numpages) {
$url = new \moodle_url($editlink, $editlinkparams + array('action' => 'pmovedown', 'aid' => $page->id));
$mform->addElement('html', $OUTPUT->action_icon($url, new \pix_icon('t/down', get_string('movedown'))));
}
$mform->addElement('text', 'pageheight', get_string('height', 'htmlcert'));
$mform->setType('pageheight', PARAM_INT);
$mform->setDefault('pageheight', '297');
$mform->addRule('pageheight', null, 'required', null, 'client');
$mform->addHelpButton('pageheight', 'height', 'htmlcert');
$mform->addElement('text', 'pagewidth_' . $page->id, get_string('width', 'customcert'));
$mform->setType('pagewidth_' . $page->id, PARAM_INT);
$mform->setDefault('pagewidth_' . $page->id, '210');
$mform->addRule('pagewidth_' . $page->id, null, 'required', null, 'client');
$mform->addHelpButton('pagewidth_' . $page->id, 'width', 'customcert');
$mform->addElement('text', 'pageheight_' . $page->id, get_string('height', 'customcert'));
$mform->setType('pageheight_' . $page->id, PARAM_INT);
$mform->setDefault('pageheight_' . $page->id, '297');
$mform->addRule('pageheight_' . $page->id, null, 'required', null, 'client');
$mform->addHelpButton('pageheight_' . $page->id, 'height', 'customcert');
$mform->addElement('text', 'pageleftmargin_' . $page->id, get_string('leftmargin', 'customcert'));
$mform->setType('pageleftmargin_' . $page->id, PARAM_INT);
$mform->setDefault('pageleftmargin_' . $page->id, 0);
$mform->addHelpButton('pageleftmargin_' . $page->id, 'leftmargin', 'customcert');
$mform->addElement('text', 'pagerightmargin_' . $page->id, get_string('rightmargin', 'customcert'));
$mform->setType('pagerightmargin_' . $page->id, PARAM_INT);
$mform->setDefault('pagerightmargin_' . $page->id, 0);
$mform->addHelpButton('pagerightmargin_' . $page->id, 'rightmargin', 'customcert');
// Check if there are elements to add.
if ($elements = $DB->get_records('customcert_elements', array('pageid' => $page->id), 'sequence ASC')) {
// Get the total number of elements.
$numelements = count($elements);
// Create a table to display these elements.
$table = new \html_table();
$table->attributes = array('class' => 'generaltable elementstable');
$table->head = array(get_string('name', 'customcert'), get_string('type', 'customcert'), '');
$table->align = array('left', 'left', 'left');
// Loop through and add the elements to the table.
foreach ($elements as $element) {
$elementname = new \core\output\inplace_editable('mod_customcert', 'elementname', $element->id,
true, format_string($element->name), $element->name);
$row = new \html_table_row();
$row->cells[] = $OUTPUT->render($elementname);
$row->cells[] = $element->element;
// Link to edit this element.
$link = new \moodle_url($editelementlink, $editelementlinkparams + array('id' => $element->id,
'action' => 'edit'));
$icons = $OUTPUT->action_icon($link, new \pix_icon('t/edit', get_string('edit')), null,
array('class' => 'action-icon edit-icon'));
// Link to delete the element.
$link = new \moodle_url($editlink, $editlinkparams + array('action' => 'deleteelement',
'aid' => $element->id));
$icons .= $OUTPUT->action_icon($link, new \pix_icon('t/delete', get_string('delete')), null,
array('class' => 'action-icon delete-icon'));
// Now display any moving arrows if they are needed.
if ($numelements > 1) {
// Only display the move up arrow if it is not the first.
$moveicons = '';
if ($element->sequence > 1) {
$url = new \moodle_url($editlink, $editlinkparams + array('action' => 'emoveup',
'aid' => $element->id));
$moveicons .= $OUTPUT->action_icon($url, new \pix_icon('t/up', get_string('moveup')));
}
// Only display the move down arrow if it is not the last.
if ($element->sequence < $numelements) {
$url = new \moodle_url($editlink, $editlinkparams + array('action' => 'emovedown',
'aid' => $element->id));
$moveicons .= $OUTPUT->action_icon($url, new \pix_icon('t/down', get_string('movedown')));
}
$icons .= $moveicons;
}
$row->cells[] = $icons;
$table->data[] = $row;
}
// Create link to order the elements.
$link = \html_writer::link(new \moodle_url('/mod/customcert/rearrange.php', array('pid' => $page->id)),
get_string('rearrangeelements', 'customcert'));
// Add the table to the form.
$mform->addElement('static', 'elements_' . $page->id, get_string('elements', 'customcert'), \html_writer::table($table)
. \html_writer::tag( 'div', $link));
$mform->addHelpButton('elements_' . $page->id, 'elements', 'customcert');
}
$group = array();
$group[] = $mform->createElement('select', 'element_' . $page->id, '', element_helper::get_available_element_types());
$group[] = $mform->createElement('submit', 'addelement_' . $page->id, get_string('addelement', 'customcert'),
array(), false);
$mform->addElement('group', 'elementgroup', '', $group, '', false);
// Add option to delete this page if there is more than one page.
if ($this->numpages > 1) {
// Link to delete the page.
$deletelink = new \moodle_url($editlink, $editlinkparams + array('action' => 'deletepage', 'aid' => $page->id));
$icon = $OUTPUT->pix_icon('t/delete', get_string('deletecertpage', 'customcert'));
$deletepagehtml = \html_writer::link($deletelink, $icon . get_string('deletecertpage', 'customcert'));
$mform->addElement('html', \html_writer::tag('div', $deletepagehtml, array('class' => 'deletebutton')));
}
}
}

453
classes/element.php Normal file
View file

@ -0,0 +1,453 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* The base class for the customcert elements.
*
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_customcert;
defined('MOODLE_INTERNAL') || die();
/**
* Class element
*
* All customcert element plugins are based on this class.
*
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class element {
/**
* @var \stdClass $element The data for the element we are adding - do not use, kept for legacy reasons.
*/
protected $element;
/**
* @var int The id.
*/
protected $id;
/**
* @var int The page id.
*/
protected $pageid;
/**
* @var string The name.
*/
protected $name;
/**
* @var mixed The data.
*/
protected $data;
/**
* @var string The font name.
*/
protected $font;
/**
* @var int The font size.
*/
protected $fontsize;
/**
* @var string The font colour.
*/
protected $colour;
/**
* @var int The position x.
*/
protected $posx;
/**
* @var int The position y.
*/
protected $posy;
/**
* @var int The width.
*/
protected $width;
/**
* @var int The refpoint.
*/
protected $refpoint;
/**
* @var bool $showposxy Show position XY form elements?
*/
protected $showposxy;
/**
* @var edit_element_form Element edit form instance.
*/
private $editelementform;
/**
* Constructor.
*
* @param \stdClass $element the element data
*/
public function __construct($element) {
$showposxy = get_config('customcert', 'showposxy');
// Keeping this for legacy reasons so we do not break third-party elements.
$this->element = clone($element);
$this->id = $element->id;
$this->pageid = $element->pageid;
$this->name = $element->name;
$this->data = $element->data;
$this->font = $element->font;
$this->fontsize = $element->fontsize;
$this->colour = $element->colour;
$this->posx = $element->posx;
$this->posy = $element->posy;
$this->width = $element->width;
$this->refpoint = $element->refpoint;
$this->showposxy = isset($showposxy) && $showposxy;
}
/**
* Returns the id.
*
* @return int
*/
public function get_id() {
return $this->id;
}
/**
* Returns the page id.
*
* @return int
*/
public function get_pageid() {
return $this->pageid;
}
/**
* Returns the name.
*
* @return int
*/
public function get_name() {
return $this->name;
}
/**
* Returns the data.
*
* @return mixed
*/
public function get_data() {
return $this->data;
}
/**
* Returns the font name.
*
* @return string
*/
public function get_font() {
return $this->font;
}
/**
* Returns the font size.
*
* @return int
*/
public function get_fontsize() {
return $this->fontsize;
}
/**
* Returns the font colour.
*
* @return string
*/
public function get_colour() {
return $this->colour;
}
/**
* Returns the position x.
*
* @return int
*/
public function get_posx() {
return $this->posx;
}
/**
* Returns the position y.
*
* @return int
*/
public function get_posy() {
return $this->posy;
}
/**
* Returns the width.
*
* @return int
*/
public function get_width() {
return $this->width;
}
/**
* Returns the refpoint.
*
* @return int
*/
public function get_refpoint() {
return $this->refpoint;
}
/**
* This function renders the form elements when adding a customcert element.
* Can be overridden if more functionality is needed.
*
* @param \MoodleQuickForm $mform the edit_form instance.
*/
public function render_form_elements($mform) {
// Render the common elements.
element_helper::render_form_element_font($mform);
element_helper::render_form_element_colour($mform);
if ($this->showposxy) {
element_helper::render_form_element_position($mform);
}
element_helper::render_form_element_width($mform);
element_helper::render_form_element_refpoint($mform);
}
/**
* Sets the data on the form when editing an element.
* Can be overridden if more functionality is needed.
*
* @param edit_element_form $mform the edit_form instance
*/
public function definition_after_data($mform) {
// Loop through the properties of the element and set the values
// of the corresponding form element, if it exists.
$properties = [
'name' => $this->name,
'font' => $this->font,
'fontsize' => $this->fontsize,
'colour' => $this->colour,
'posx' => $this->posx,
'posy' => $this->posy,
'width' => $this->width,
'refpoint' => $this->refpoint
];
foreach ($properties as $property => $value) {
if (!is_null($value) && $mform->elementExists($property)) {
$element = $mform->getElement($property);
$element->setValue($value);
}
}
}
/**
* Performs validation on the element values.
* Can be overridden if more functionality is needed.
*
* @param array $data the submitted data
* @param array $files the submitted files
* @return array the validation errors
*/
public function validate_form_elements($data, $files) {
// Array to return the errors.
$errors = array();
// Common validation methods.
$errors += element_helper::validate_form_element_colour($data);
if ($this->showposxy) {
$errors += element_helper::validate_form_element_position($data);
}
$errors += element_helper::validate_form_element_width($data);
return $errors;
}
/**
* Handles saving the form elements created by this element.
* Can be overridden if more functionality is needed.
*
* @param \stdClass $data the form data
* @return bool true of success, false otherwise.
*/
public function save_form_elements($data) {
global $DB;
// Get the data from the form.
$element = new \stdClass();
$element->name = $data->name;
$element->data = $this->save_unique_data($data);
$element->font = (isset($data->font)) ? $data->font : null;
$element->fontsize = (isset($data->fontsize)) ? $data->fontsize : null;
$element->colour = (isset($data->colour)) ? $data->colour : null;
if ($this->showposxy) {
$element->posx = (isset($data->posx)) ? $data->posx : null;
$element->posy = (isset($data->posy)) ? $data->posy : null;
}
$element->width = (isset($data->width)) ? $data->width : null;
$element->refpoint = (isset($data->refpoint)) ? $data->refpoint : null;
$element->timemodified = time();
// Check if we are updating, or inserting a new element.
if (!empty($this->id)) { // Must be updating a record in the database.
$element->id = $this->id;
return $DB->update_record('customcert_elements', $element);
} else { // Must be adding a new one.
$element->element = $data->element;
$element->pageid = $data->pageid;
$element->sequence = \mod_customcert\element_helper::get_element_sequence($element->pageid);
$element->timecreated = time();
return $DB->insert_record('customcert_elements', $element, false);
}
}
/**
* This will handle how form data will be saved into the data column in the
* customcert_elements table.
* Can be overridden if more functionality is needed.
*
* @param \stdClass $data the form data
* @return string the unique data to save
*/
public function save_unique_data($data) {
return '';
}
/**
* This handles copying data from another element of the same type.
* Can be overridden if more functionality is needed.
*
* @param \stdClass $data the form data
* @return bool returns true if the data was copied successfully, false otherwise
*/
public function copy_element($data) {
return true;
}
/**
* This defines if an element plugin can be added to a certificate.
* Can be overridden if an element plugin wants to take over the control.
*
* @return bool returns true if the element can be added, false otherwise
*/
public static function can_add() {
return true;
}
/**
* Handles rendering the element on the pdf.
*
* Must be overridden.
*
* @param \pdf $pdf the pdf object
* @param bool $preview true if it is a preview, false otherwise
* @param \stdClass $user the user we are rendering this for
*/
public abstract function render($pdf, $preview, $user);
/**
* Render the element in html.
*
* Must be overridden.
*
* This function is used to render the element when we are using the
* drag and drop interface to position it.
*
* @return string the html
*/
public abstract function render_html();
/**
* Handles deleting any data this element may have introduced.
* Can be overridden if more functionality is needed.
*
* @return bool success return true if deletion success, false otherwise
*/
public function delete() {
global $DB;
return $DB->delete_records('customcert_elements', array('id' => $this->id));
}
/**
* This function is responsible for handling the restoration process of the element.
*
* For example, the function may save data that is related to another course module, this
* data will need to be updated if we are restoring the course as the course module id will
* be different in the new course.
*
* @param \restore_customcert_activity_task $restore
*/
public function after_restore($restore) {
}
/**
* Magic getter for read only access.
*
* @param string $name
*/
public function __get($name) {
debugging('Please call the appropriate get_* function instead of relying on magic getters', DEBUG_DEVELOPER);
if (property_exists($this->element, $name)) {
return $this->element->$name;
}
}
/**
* Set edit form instance for the custom cert element.
*
* @param \mod_customcert\edit_element_form $editelementform
*/
public function set_edit_element_form(edit_element_form $editelementform) {
$this->editelementform = $editelementform;
}
/**
* Get edit form instance for the custom cert element.
*
* @return \mod_customcert\edit_element_form
*/
public function get_edit_element_form() {
if (empty($this->editelementform)) {
throw new \coding_exception('Edit element form instance is not set.');
}
return $this->editelementform;
}
}

View file

@ -0,0 +1,70 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Contains the factory class responsible for creating custom certificate instances.
*
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_customcert;
defined('MOODLE_INTERNAL') || die();
/**
* The factory class responsible for creating custom certificate instances.
*
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class element_factory {
/**
* Returns an instance of the element class.
*
* @param \stdClass $element the element
* @return \mod_customcert\element|bool returns the instance of the element class, or false if element
* class does not exists.
*/
public static function get_element_instance($element) {
// Get the class name.
$classname = '\\customcertelement_' . $element->element . '\\element';
$data = new \stdClass();
$data->id = $element->id ?? null;
$data->pageid = $element->pageid ?? null;
$data->name = $element->name ?? get_string('pluginname', 'customcertelement_' . $element->element);
$data->element = $element->element;
$data->data = $element->data ?? null;
$data->font = $element->font ?? null;
$data->fontsize = $element->fontsize ?? null;
$data->colour = $element->colour ?? null;
$data->posx = $element->posx ?? null;
$data->posy = $element->posy ?? null;
$data->width = $element->width ?? null;
$data->refpoint = $element->refpoint ?? null;
// Ensure the necessary class exists.
if (class_exists($classname)) {
return new $classname($data);
}
return false;
}
}

609
classes/element_helper.php Normal file
View file

@ -0,0 +1,609 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Provides useful functions related to elements.
*
* @package mod_customcert
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_customcert;
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir . '/grade/constants.php');
require_once($CFG->dirroot . '/grade/lib.php');
require_once($CFG->dirroot . '/grade/querylib.php');
/**
* Class helper.
*
* Provides useful functions related to elements.
*
* @package mod_customcert
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class element_helper {
/**
* @var int the top-left of element
*/
const CUSTOMCERT_REF_POINT_TOPLEFT = 0;
/**
* @var int the top-center of element
*/
const CUSTOMCERT_REF_POINT_TOPCENTER = 1;
/**
* @var int the top-left of element
*/
const CUSTOMCERT_REF_POINT_TOPRIGHT = 2;
/**
* Common behaviour for rendering specified content on the pdf.
*
* @param \pdf $pdf the pdf object
* @param \mod_customcert\element $element the customcert element
* @param string $content the content to render
*/
public static function render_content($pdf, $element, $content) {
list($font, $attr) = self::get_font($element);
$pdf->setFont($font, $attr, $element->get_fontsize());
$fontcolour = \TCPDF_COLORS::convertHTMLColorToDec($element->get_colour(), $fontcolour);
$pdf->SetTextColor($fontcolour['R'], $fontcolour['G'], $fontcolour['B']);
$x = $element->get_posx();
$y = $element->get_posy();
$w = $element->get_width();
$refpoint = $element->get_refpoint();
$actualwidth = $pdf->GetStringWidth($content);
if ($w and $w < $actualwidth) {
$actualwidth = $w;
}
switch ($refpoint) {
case self::CUSTOMCERT_REF_POINT_TOPRIGHT:
$x = $element->get_posx() - $actualwidth;
if ($x < 0) {
$x = 0;
$w = $element->get_posx();
} else {
$w = $actualwidth;
}
break;
case self::CUSTOMCERT_REF_POINT_TOPCENTER:
$x = $element->get_posx() - $actualwidth / 2;
if ($x < 0) {
$x = 0;
$w = $element->get_posx() * 2;
} else {
$w = $actualwidth;
}
break;
}
if ($w) {
$w += 0.0001;
}
$pdf->setCellPaddings(0, 0, 0, 0);
$pdf->writeHTMLCell($w, 0, $x, $y, $content, 0, 0, false, true);
}
/**
* Common behaviour for rendering specified content on the drag and drop page.
*
* @param \mod_customcert\element $element the customcert element
* @param string $content the content to render
* @return string the html
*/
public static function render_html_content($element, $content) {
list($font, $attr) = self::get_font($element);
$fontstyle = 'font-family: ' . $font;
if (strpos($attr, 'B') !== false) {
$fontstyle .= '; font-weight: bold';
}
if (strpos($attr, 'I') !== false) {
$fontstyle .= '; font-style: italic';
}
$style = $fontstyle . '; color: ' . $element->get_colour() . '; font-size: ' . $element->get_fontsize() . 'pt;';
if ($element->get_width()) {
$style .= ' width: ' . $element->get_width() . 'mm';
}
return \html_writer::div($content, '', array('style' => $style));
}
/**
* Helper function to render the font elements.
*
* @param \MoodleQuickForm $mform the edit_form instance.
*/
public static function render_form_element_font($mform) {
$mform->addElement('select', 'font', get_string('font', 'customcert'), \mod_customcert\certificate::get_fonts());
$mform->setType('font', PARAM_TEXT);
$mform->setDefault('font', 'times');
$mform->addHelpButton('font', 'font', 'customcert');
$mform->addElement('select', 'fontsize', get_string('fontsize', 'customcert'),
\mod_customcert\certificate::get_font_sizes());
$mform->setType('fontsize', PARAM_INT);
$mform->setDefault('fontsize', 12);
$mform->addHelpButton('fontsize', 'fontsize', 'customcert');
}
/**
* Helper function to render the colour elements.
*
* @param \MoodleQuickForm $mform the edit_form instance.
*/
public static function render_form_element_colour($mform) {
$mform->addElement('customcert_colourpicker', 'colour', get_string('fontcolour', 'customcert'));
$mform->setType('colour', PARAM_RAW); // Need to validate that this is a valid colour.
$mform->setDefault('colour', '#000000');
$mform->addHelpButton('colour', 'fontcolour', 'customcert');
}
/**
* Helper function to render the position elements.
*
* @param \MoodleQuickForm $mform the edit_form instance.
*/
public static function render_form_element_position($mform) {
$mform->addElement('text', 'posx', get_string('posx', 'customcert'), array('size' => 10));
$mform->setType('posx', PARAM_INT);
$mform->setDefault('posx', 0);
$mform->addHelpButton('posx', 'posx', 'customcert');
$mform->addElement('text', 'posy', get_string('posy', 'customcert'), array('size' => 10));
$mform->setType('posy', PARAM_INT);
$mform->setDefault('posy', 0);
$mform->addHelpButton('posy', 'posy', 'customcert');
}
/**
* Helper function to render the width element.
*
* @param \MoodleQuickForm $mform the edit_form instance.
*/
public static function render_form_element_width($mform) {
$mform->addElement('text', 'width', get_string('elementwidth', 'customcert'), array('size' => 10));
$mform->setType('width', PARAM_INT);
$mform->setDefault('width', 0);
$mform->addHelpButton('width', 'elementwidth', 'customcert');
}
/**
* Helper function to render the refpoint element.
*
* @param \MoodleQuickForm $mform the edit_form instance.
*/
public static function render_form_element_refpoint($mform) {
$refpointoptions = array();
$refpointoptions[self::CUSTOMCERT_REF_POINT_TOPLEFT] = get_string('topleft', 'customcert');
$refpointoptions[self::CUSTOMCERT_REF_POINT_TOPCENTER] = get_string('topcenter', 'customcert');
$refpointoptions[self::CUSTOMCERT_REF_POINT_TOPRIGHT] = get_string('topright', 'customcert');
$mform->addElement('select', 'refpoint', get_string('refpoint', 'customcert'), $refpointoptions);
$mform->setType('refpoint', PARAM_INT);
$mform->setDefault('refpoint', self::CUSTOMCERT_REF_POINT_TOPCENTER);
$mform->addHelpButton('refpoint', 'refpoint', 'customcert');
}
/**
* Helper function to performs validation on the colour element.
*
* @param array $data the submitted data
* @return array the validation errors
*/
public static function validate_form_element_colour($data) {
$errors = array();
// Validate the colour.
if (!self::validate_colour($data['colour'])) {
$errors['colour'] = get_string('invalidcolour', 'customcert');
}
return $errors;
}
/**
* Helper function to performs validation on the position elements.
*
* @param array $data the submitted data
* @return array the validation errors
*/
public static function validate_form_element_position($data) {
$errors = array();
// Check if posx is not set, or not numeric or less than 0.
if ((!isset($data['posx'])) || (!is_numeric($data['posx'])) || ($data['posx'] < 0)) {
$errors['posx'] = get_string('invalidposition', 'customcert', 'X');
}
// Check if posy is not set, or not numeric or less than 0.
if ((!isset($data['posy'])) || (!is_numeric($data['posy'])) || ($data['posy'] < 0)) {
$errors['posy'] = get_string('invalidposition', 'customcert', 'Y');
}
return $errors;
}
/**
* Helper function to perform validation on the width element.
*
* @param array $data the submitted data
* @return array the validation errors
*/
public static function validate_form_element_width($data) {
$errors = array();
// Check if width is less than 0.
if (isset($data['width']) && $data['width'] < 0) {
$errors['width'] = get_string('invalidelementwidth', 'customcert');
}
return $errors;
}
/**
* Returns the font used for this element.
*
* @param \mod_customcert\element $element the customcert element
* @return array the font and font attributes
*/
public static function get_font($element) {
// Variable for the font.
$font = $element->get_font();
// Get the last two characters of the font name.
$fontlength = strlen($font);
$lastchar = $font[$fontlength - 1];
$secondlastchar = $font[$fontlength - 2];
// The attributes of the font.
$attr = '';
// Check if the last character is 'i'.
if ($lastchar == 'i') {
// Remove the 'i' from the font name.
$font = substr($font, 0, -1);
// Check if the second last char is b.
if ($secondlastchar == 'b') {
// Remove the 'b' from the font name.
$font = substr($font, 0, -1);
$attr .= 'B';
}
$attr .= 'I';
} else if ($lastchar == 'b') {
// Remove the 'b' from the font name.
$font = substr($font, 0, -1);
$attr .= 'B';
}
return array($font, $attr);
}
/**
* Validates the colour selected.
*
* @param string $colour
* @return bool returns true if the colour is valid, false otherwise
*/
public static function validate_colour($colour) {
// List of valid HTML colour names.
$colournames = array(
'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
'lime', 'limegreen', 'linen', 'magenta', 'maroon',
'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
'whitesmoke', 'yellow', 'yellowgreen'
);
if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $colour)) {
return true;
} else if (in_array(strtolower($colour), $colournames)) {
return true;
}
return false;
}
/**
* Helper function that returns the sequence on a specified customcert page for a
* newly created element.
*
* @param int $pageid the id of the page we are adding this element to
* @return int the element number
*/
public static function get_element_sequence($pageid) {
global $DB;
// Set the sequence of the element we are creating.
$sequence = 1;
// Check if there already elements that exist, if so, overwrite value.
$sql = "SELECT MAX(sequence) as maxsequence
FROM {customcert_elements}
WHERE pageid = :id";
// Get the current max sequence on this page and add 1 to get the new sequence.
if ($maxseq = $DB->get_record_sql($sql, array('id' => $pageid))) {
$sequence = $maxseq->maxsequence + 1;
}
return $sequence;
}
/**
* Helper function that returns the course id for this element.
*
* @param int $elementid The element id
* @return int The course id
*/
public static function get_courseid($elementid) {
global $DB, $SITE;
$sql = "SELECT course
FROM {customcert} c
INNER JOIN {customcert_pages} cp
ON c.templateid = cp.templateid
INNER JOIN {customcert_elements} ce
ON cp.id = ce.pageid
WHERE ce.id = :elementid";
// Check if there is a course associated with this element.
if ($course = $DB->get_record_sql($sql, array('elementid' => $elementid))) {
return $course->course;
} else { // Must be in a site template.
return $SITE->id;
}
}
/**
* Helper function that returns the context for this element.
*
* @param int $elementid The element id
* @return \context The context
*/
public static function get_context(int $elementid) : \context {
global $DB;
$sql = "SELECT ct.contextid
FROM {customcert_templates} ct
INNER JOIN {customcert_pages} cp
ON ct.id = cp.templateid
INNER JOIN {customcert_elements} ce
ON cp.id = ce.pageid
WHERE ce.id = :elementid";
$contextid = $DB->get_field_sql($sql, array('elementid' => $elementid), MUST_EXIST);
return \context::instance_by_id($contextid);
}
/**
* Return the list of possible elements to add.
*
* @return array the list of element types that can be used.
*/
public static function get_available_element_types() {
global $CFG;
// Array to store the element types.
$options = array();
// Check that the directory exists.
$elementdir = "$CFG->dirroot/mod/customcert/element";
if (file_exists($elementdir)) {
// Get directory contents.
$elementfolders = new \DirectoryIterator($elementdir);
// Loop through the elements folder.
foreach ($elementfolders as $elementfolder) {
// If it is not a directory or it is '.' or '..', skip it.
if (!$elementfolder->isDir() || $elementfolder->isDot()) {
continue;
}
// Check that the standard class exists, if not we do
// not want to display it as an option as it will not work.
$foldername = $elementfolder->getFilename();
// Get the class name.
$classname = '\\customcertelement_' . $foldername . '\\element';
// Ensure the necessary class exists.
if (class_exists($classname)) {
// Additionally, check if the user is allowed to add the element at all.
if ($classname::can_add()) {
$component = "customcertelement_{$foldername}";
$options[$foldername] = get_string('pluginname', $component);
}
}
}
}
\core_collator::asort($options);
return $options;
}
/**
* Helper function to return all the grades items for a given course.
*
* @param \stdClass $course The course we want to return the grade items for
* @return array the array of gradeable items in the course
*/
public static function get_grade_items($course) {
// Array to store the grade items.
$arrgradeitems = array();
// Get other non-module related grade items.
if ($gradeitems = \grade_item::fetch_all(['courseid' => $course->id])) {
foreach ($gradeitems as $gi) {
if ($gi->is_course_item()) {
continue; // Skipping for legacy reasons - this was added to individual elements.
}
if ($gi->is_external_item()) {
$cm = get_coursemodule_from_instance($gi->itemmodule, $gi->iteminstance, $course->id);
$modcontext = \context_module::instance($cm->id);
$modname = format_string($cm->name, true, array('context' => $modcontext));
}
if ($gi->is_external_item() && !$gi->is_outcome_item()) {
// Due to legacy reasons we are storing the course module ID here rather than the grade item id.
// If we were to change we would need to provide upgrade steps to convert cm->id to gi->id.
$arrgradeitems[$cm->id] = get_string('activity', 'mod_customcert') . ' : ' . $gi->get_name();
} else if ($gi->is_external_item() && $gi->is_outcome_item()) {
// Get the name of the activity.
$optionname = get_string('gradeoutcome', 'mod_customcert') . ' : ' . $modname . " - " . $gi->get_name();
$arrgradeitems['gradeitem:' . $gi->id] = $optionname;
} else {
$arrgradeitems['gradeitem:' . $gi->id] = get_string('gradeitem', 'grades') . ' : ' . $gi->get_name(true);
}
}
// Alphabetise this.
asort($arrgradeitems);
}
return $arrgradeitems;
}
/**
* Helper function to return the grade information for a course for a specified user.
*
* @param int $courseid
* @param int $gradeformat
* @param int $userid
* @return grade_information|bool the grade information, or false if there is none.
*/
public static function get_course_grade_info($courseid, $gradeformat, $userid) {
$courseitem = \grade_item::fetch_course_item($courseid);
if (!$courseitem) {
return false;
}
$grade = new \grade_grade(array('itemid' => $courseitem->id, 'userid' => $userid));
return new grade_information(
$courseitem->get_name(),
$grade->finalgrade,
grade_format_gradevalue($grade->finalgrade, $courseitem, true, $gradeformat),
$grade->get_dategraded()
);
}
/**
* Helper function to return the grade information for a module for a specified user.
*
* @param int $cmid
* @param int $gradeformat
* @param int $userid
* @return grade_information|bool the grade information, or false if there is none.
*/
public static function get_mod_grade_info($cmid, $gradeformat, $userid) {
global $DB;
if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
return false;
}
if (!$module = $DB->get_record('modules', array('id' => $cm->module))) {
return false;
}
$params = [
'itemtype' => 'mod',
'itemmodule' => $module->name,
'iteminstance' => $cm->instance,
'courseid' => $cm->course,
'itemnumber' => 0
];
$gradeitem = \grade_item::fetch($params);
if (empty($gradeitem)) {
return false;
}
$grade = grade_get_grades(
$cm->course,
'mod',
$module->name,
$cm->instance,
$userid
);
if (!isset($grade->items[0]->grades[$userid])) {
return false;
}
$gradebookgrade = $grade->items[0]->grades[$userid];
$dategraded = null;
if (!empty($gradebookgrade->dategraded)) {
$dategraded = $gradebookgrade->dategraded;
}
$displaygrade = grade_format_gradevalue($gradebookgrade->grade, $gradeitem, true, $gradeformat);
return new grade_information(
$gradeitem->get_name(),
$gradebookgrade->grade,
$displaygrade,
$dategraded
);
}
/**
* Helper function to return the grade information for a grade item for a specified user.
*
* @param int $gradeitemid
* @param int $gradeformat
* @param int $userid
* @return grade_information|bool the grade information, or false if there is none.
*/
public static function get_grade_item_info($gradeitemid, $gradeformat, $userid) {
if (!$gradeitem = \grade_item::fetch(['id' => $gradeitemid])) {
return false;
}
$grade = new \grade_grade(array('itemid' => $gradeitem->id, 'userid' => $userid));
return new grade_information(
$gradeitem->get_name(),
$grade->finalgrade,
grade_format_gradevalue($grade->finalgrade, $gradeitem, true, $gradeformat),
$grade->get_dategraded()
);
}
}

View file

@ -17,20 +17,20 @@
/**
* Contains the course module instance list viewed event class.
*
* @package mod_htmlcert
* @copyright 2017 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert\event;
namespace mod_customcert\event;
defined('MOODLE_INTERNAL') || die();
/**
* The course module instance list viewed event class.
*
* @package mod_htmlcert
* @copyright 2017 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class course_module_instance_list_viewed extends \core\event\course_module_instance_list_viewed {

View file

@ -17,20 +17,20 @@
/**
* Contains the course module viewed event class.
*
* @package mod_htmlcert
* @copyright 2017 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert\event;
namespace mod_customcert\event;
defined('MOODLE_INTERNAL') || die();
/**
* The course module viewed event class.
*
* @package mod_htmlcert
* @copyright 2017 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class course_module_viewed extends \core\event\course_module_viewed {
@ -39,24 +39,14 @@ class course_module_viewed extends \core\event\course_module_viewed {
* Initialises the event.
*/
protected function init() {
$this->data['objecttable'] = 'htmlcert';
$this->data['objecttable'] = 'customcert';
parent::init();
}
/**
* {@inheritdoc}
*
* @return string[]
*/
public static function get_objectid_mapping() {
return array('db' => 'htmlcert', 'restore' => 'htmlcert');
return array('db' => 'customcert', 'restore' => 'customcert');
}
/**
* {@inheritdoc}
*
* @return bool
*/
public static function get_other_mapping() {
// No need to map.
return false;

View file

@ -17,11 +17,11 @@
/**
* This is the external API for this tool.
*
* @package mod_htmlcert
* @copyright 2016 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert;
namespace mod_customcert;
defined('MOODLE_INTERNAL') || die();
require_once("$CFG->libdir/externallib.php");
@ -29,10 +29,152 @@ require_once("$CFG->libdir/externallib.php");
/**
* This is the external API for this tool.
*
* @copyright 2016 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class external extends \external_api {
/**
* Returns the save_element() parameters.
*
* @return \external_function_parameters
*/
public static function save_element_parameters() {
return new \external_function_parameters(
array(
'templateid' => new \external_value(PARAM_INT, 'The template id'),
'elementid' => new \external_value(PARAM_INT, 'The element id'),
'values' => new \external_multiple_structure(
new \external_single_structure(
array(
'name' => new \external_value(PARAM_ALPHANUMEXT, 'The field to update'),
'value' => new \external_value(PARAM_RAW, 'The value of the field'),
)
)
)
)
);
}
/**
* Handles saving element data.
*
* @param int $templateid The template id.
* @param int $elementid The element id.
* @param array $values The values to save
* @return array
*/
public static function save_element($templateid, $elementid, $values) {
global $DB;
$params = array(
'templateid' => $templateid,
'elementid' => $elementid,
'values' => $values
);
self::validate_parameters(self::save_element_parameters(), $params);
$template = $DB->get_record('customcert_templates', array('id' => $templateid), '*', MUST_EXIST);
$element = $DB->get_record('customcert_elements', array('id' => $elementid), '*', MUST_EXIST);
// Set the template.
$template = new \mod_customcert\template($template);
// Perform checks.
if ($cm = $template->get_cm()) {
self::validate_context(\context_module::instance($cm->id));
} else {
self::validate_context(\context_system::instance());
}
// Make sure the user has the required capabilities.
$template->require_manage();
// Set the values we are going to save.
$data = new \stdClass();
$data->id = $element->id;
$data->name = $element->name;
foreach ($values as $value) {
$field = $value['name'];
$data->$field = $value['value'];
}
// Get an instance of the element class.
if ($e = \mod_customcert\element_factory::get_element_instance($element)) {
return $e->save_form_elements($data);
}
return false;
}
/**
* Returns the save_element result value.
*
* @return \external_value
*/
public static function save_element_returns() {
return new \external_value(PARAM_BOOL, 'True if successful, false otherwise');
}
/**
* Returns get_element() parameters.
*
* @return \external_function_parameters
*/
public static function get_element_html_parameters() {
return new \external_function_parameters(
array(
'templateid' => new \external_value(PARAM_INT, 'The template id'),
'elementid' => new \external_value(PARAM_INT, 'The element id'),
)
);
}
/**
* Handles return the element's HTML.
*
* @param int $templateid The template id
* @param int $elementid The element id.
* @return string
*/
public static function get_element_html($templateid, $elementid) {
global $DB;
$params = array(
'templateid' => $templateid,
'elementid' => $elementid
);
self::validate_parameters(self::get_element_html_parameters(), $params);
$template = $DB->get_record('customcert_templates', array('id' => $templateid), '*', MUST_EXIST);
$element = $DB->get_record('customcert_elements', array('id' => $elementid), '*', MUST_EXIST);
// Set the template.
$template = new \mod_customcert\template($template);
// Perform checks.
if ($cm = $template->get_cm()) {
self::validate_context(\context_module::instance($cm->id));
} else {
self::validate_context(\context_system::instance());
}
// Get an instance of the element class.
if ($e = \mod_customcert\element_factory::get_element_instance($element)) {
return $e->render_html();
}
return '';
}
/**
* Returns the get_element result value.
*
* @return \external_value
*/
public static function get_element_html_returns() {
return new \external_value(PARAM_RAW, 'The HTML');
}
/**
* Returns the delete_issue() parameters.
*
@ -48,7 +190,7 @@ class external extends \external_api {
}
/**
* Handles deleting a htmlcert issue.
* Handles deleting a customcert issue.
*
* @param int $certificateid The certificate id.
* @param int $issueid The issue id.
@ -63,18 +205,18 @@ class external extends \external_api {
];
self::validate_parameters(self::delete_issue_parameters(), $params);
$certificate = $DB->get_record('htmlcert', ['id' => $certificateid], '*', MUST_EXIST);
$issue = $DB->get_record('htmlcert_issues', ['id' => $issueid, 'htmlcertid' => $certificateid], '*', MUST_EXIST);
$certificate = $DB->get_record('customcert', ['id' => $certificateid], '*', MUST_EXIST);
$issue = $DB->get_record('customcert_issues', ['id' => $issueid, 'customcertid' => $certificateid], '*', MUST_EXIST);
$cm = get_coursemodule_from_instance('htmlcert', $certificate->id, 0, false, MUST_EXIST);
$cm = get_coursemodule_from_instance('customcert', $certificate->id, 0, false, MUST_EXIST);
// Make sure the user has the required capabilities.
$context = \context_module::instance($cm->id);
self::validate_context($context);
require_capability('mod/htmlcert:manage', $context);
require_capability('mod/customcert:manage', $context);
// Delete the issue.
return $DB->delete_records('htmlcert_issues', ['id' => $issue->id]);
return $DB->delete_records('customcert_issues', ['id' => $issue->id]);
}
/**

View file

@ -1,5 +1,5 @@
<?php
// This file is part of the htmlcert module for Moodle - http://moodle.org/
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@ -17,19 +17,19 @@
/**
* Contains the class that provides a grade object to be used by elements for display purposes.
*
* @package mod_htmlcert
* @copyright 2017 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert;
namespace mod_customcert;
defined('MOODLE_INTERNAL') || die();
/**
* The class that provides a grade object to be used by elements for display purposes.
*
* @package mod_htmlcert
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/

View file

@ -1,64 +0,0 @@
<?php
// This file is part of the htmlcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Provides helper functionality.
*
* @package mod_htmlcert
* @copyright 2021 Mark Nelson <mdjnelson@gmail.com>, Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert;
use core_user\fields;
defined('MOODLE_INTERNAL') || die();
/**
* Class helper.
*
* Helper functionality for this module.
*
* @package mod_htmlcert
* @copyright 2021 Mark Nelson <mdjnelson@gmail.com>, Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class helper {
/**
* A centralised location for the all name fields.
*
* Returns a sql string snippet.
*
* @param string $tableprefix table query prefix to use in front of each field.
* @return string All name fields.
*/
public static function get_all_user_name_fields(string $tableprefix = ''): string {
$alternatenames = [];
foreach (fields::get_name_fields() as $field) {
$alternatenames[$field] = $field;
}
if ($tableprefix) {
foreach ($alternatenames as $key => $altname) {
$alternatenames[$key] = $tableprefix . '.' . $altname;
}
}
return implode(',', $alternatenames);
}
}

View file

@ -1,5 +1,5 @@
<?php
// This file is part of the htmlcert module for Moodle - http://moodle.org/
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@ -15,23 +15,23 @@
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the form for loading htmlcert templates.
* This file contains the form for loading customcert templates.
*
* @package mod_htmlcert
* @copyright 2013 Mark Nelson <markn@moodle.com>, Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert;
namespace mod_customcert;
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
require_once($CFG->libdir . '/formslib.php');
/**
* The form for loading htmlcert templates.
* The form for loading customcert templates.
*
* @package mod_htmlcert
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
@ -47,30 +47,26 @@ class load_template_form extends \moodleform {
// Get the context.
$context = $this->_customdata['context'];
$syscontext = \context_system::instance();
$mform->addElement('header', 'loadtemplateheader', get_string('loadtemplate', 'htmlcert'));
$mform->addElement('header', 'loadtemplateheader', get_string('loadtemplate', 'customcert'));
// Display a link to the manage templates page.
if ($context->contextlevel != CONTEXT_SYSTEM && has_capability('mod/htmlcert:manage', $syscontext)) {
$link = \html_writer::link(new \moodle_url('/mod/htmlcert/manage_templates.php'),
get_string('managetemplates', 'htmlcert'));
if ($context->contextlevel != CONTEXT_SYSTEM && has_capability('mod/customcert:manage', \context_system::instance())) {
$link = \html_writer::link(new \moodle_url('/mod/customcert/manage_templates.php'),
get_string('managetemplates', 'customcert'));
$mform->addElement('static', 'managetemplates', '', $link);
}
$arrtemplates = $DB->get_records_menu('htmlcert_templates', ['contextid' => $syscontext->id], 'name ASC', 'id, name');
if ($arrtemplates) {
$templates = [];
foreach ($arrtemplates as $key => $template) {
$templates[$key] = format_string($template, true, ['context' => $context]);
}
$templates = $DB->get_records_menu('customcert_templates',
array('contextid' => \context_system::instance()->id), 'name ASC', 'id, name');
if ($templates) {
$group = array();
$group[] = $mform->createElement('select', 'ltid', '', $templates);
$group[] = $mform->createElement('submit', 'loadtemplatesubmit', get_string('load', 'htmlcert'));
$group[] = $mform->createElement('submit', 'loadtemplatesubmit', get_string('load', 'customcert'));
$mform->addElement('group', 'loadtemplategroup', '', $group, '', false);
$mform->setType('ltid', PARAM_INT);
} else {
$msg = \html_writer::tag('div', get_string('notemplates', 'htmlcert'), array('class' => 'alert'));
$msg = \html_writer::tag('div', get_string('notemplates', 'customcert'), array('class' => 'alert'));
$mform->addElement('static', 'notemplates', '', $msg);
}
}

View file

@ -17,12 +17,12 @@
/**
* The table that displays the templates in a given context.
*
* @package mod_htmlcert
* @copyright 2017 Mark Nelson <markn@moodle.com>, Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert;
namespace mod_customcert;
defined('MOODLE_INTERNAL') || die;
@ -33,8 +33,8 @@ require_once($CFG->libdir . '/tablelib.php');
/**
* Class for the table that displays the templates in a given context.
*
* @package mod_htmlcert
* @copyright 2017 Mark Nelson <markn@moodle.com>, Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class manage_templates_table extends \table_sql {
@ -50,7 +50,7 @@ class manage_templates_table extends \table_sql {
* @param \context $context
*/
public function __construct($context) {
parent::__construct('mod_htmlcert_manage_templates_table');
parent::__construct('mod_customcert_manage_templates_table');
$columns = [
'name',
@ -77,7 +77,7 @@ class manage_templates_table extends \table_sql {
* @return string
*/
public function col_name($template) {
return format_string($template->name, true, ['context' => $this->context]);
return $template->name;
}
/**
@ -90,11 +90,11 @@ class manage_templates_table extends \table_sql {
global $OUTPUT;
// Link to edit the template.
$editlink = new \moodle_url('/mod/htmlcert/edit.php', array('tid' => $template->id));
$editlink = new \moodle_url('/mod/customcert/edit.php', array('tid' => $template->id));
$editicon = $OUTPUT->action_icon($editlink, new \pix_icon('t/edit', get_string('edit')));
// Link to duplicate the template.
$duplicatelink = new \moodle_url('/mod/htmlcert/manage_templates.php',
$duplicatelink = new \moodle_url('/mod/customcert/manage_templates.php',
array(
'tid' => $template->id,
'action' => 'duplicate',
@ -105,7 +105,7 @@ class manage_templates_table extends \table_sql {
array('class' => 'action-icon duplicate-icon'));
// Link to delete the template.
$deletelink = new \moodle_url('/mod/htmlcert/manage_templates.php',
$deletelink = new \moodle_url('/mod/customcert/manage_templates.php',
array(
'tid' => $template->id,
'action' => 'delete',
@ -127,11 +127,11 @@ class manage_templates_table extends \table_sql {
public function query_db($pagesize, $useinitialsbar = true) {
global $DB;
$total = $DB->count_records('htmlcert_templates', array('contextid' => $this->context->id));
$total = $DB->count_records('customcert_templates', array('contextid' => $this->context->id));
$this->pagesize($pagesize, $total);
$this->rawdata = $DB->get_records('htmlcert_templates', array('contextid' => $this->context->id),
$this->rawdata = $DB->get_records('customcert_templates', array('contextid' => $this->context->id),
$this->get_sql_sort(), '*', $this->get_page_start(), $this->get_page_size());
// Set initial bars.

View file

@ -17,12 +17,12 @@
/**
* The report that displays the certificates the user has throughout the site.
*
* @package mod_htmlcert
* @copyright 2016 Mark Nelson <markn@moodle.com>, 2022 Kumi Systems e.U. <office@kumi.systems>
* @package mod_customcert
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert;
namespace mod_customcert;
defined('MOODLE_INTERNAL') || die;
@ -33,8 +33,8 @@ require_once($CFG->libdir . '/tablelib.php');
/**
* Class for the report that displays the certificates the user has throughout the site.
*
* @package mod_htmlcert
* @copyright 2016 Mark Nelson <markn@moodle.com>, 2022 Kumi Systems e.U. <office@kumi.systems>
* @package mod_customcert
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class my_certificates_table extends \table_sql {
@ -51,7 +51,7 @@ class my_certificates_table extends \table_sql {
* @param string|null $download The file type, null if we are not downloading
*/
public function __construct($userid, $download = null) {
parent::__construct('mod_htmlcert_report_table');
parent::__construct('mod_customcert_report_table');
$columns = array(
'name',
@ -62,13 +62,13 @@ class my_certificates_table extends \table_sql {
$headers = array(
get_string('name'),
get_string('course'),
get_string('receiveddate', 'htmlcert'),
get_string('code', 'htmlcert')
get_string('receiveddate', 'customcert'),
get_string('code', 'customcert')
);
// Check if we were passed a filename, which means we want to download it.
if ($download) {
$this->is_downloading($download, 'htmlcert-report');
$this->is_downloading($download, 'customcert-report');
}
if (!$this->is_downloading()) {
@ -94,7 +94,7 @@ class my_certificates_table extends \table_sql {
* @return string
*/
public function col_name($certificate) {
$cm = get_coursemodule_from_instance('htmlcert', $certificate->id);
$cm = get_coursemodule_from_instance('customcert', $certificate->id);
$context = \context_module::instance($cm->id);
return format_string($certificate->name, true, ['context' => $context]);
@ -107,7 +107,7 @@ class my_certificates_table extends \table_sql {
* @return string
*/
public function col_coursename($certificate) {
$cm = get_coursemodule_from_instance('htmlcert', $certificate->id);
$cm = get_coursemodule_from_instance('customcert', $certificate->id);
$context = \context_module::instance($cm->id);
return format_string($certificate->coursename, true, ['context' => $context]);
@ -142,13 +142,13 @@ class my_certificates_table extends \table_sql {
public function col_download($certificate) {
global $OUTPUT;
$icon = new \pix_icon('download', get_string('download'), 'htmlcert');
$link = new \moodle_url('/mod/htmlcert/my_certificates.php',
$icon = new \pix_icon('download', get_string('download'), 'customcert');
$link = new \moodle_url('/mod/customcert/my_certificates.php',
array('userid' => $this->userid,
'certificateid' => $certificate->id,
'downloadcert' => '1'));
return $OUTPUT->action_link($link, '', new \popup_action('click', $link), null, $icon);
return $OUTPUT->action_link($link, '', null, null, $icon);
}
/**

View file

@ -17,23 +17,23 @@
/**
* Email certificate as html renderer.
*
* @package mod_htmlcert
* @copyright 2017 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert\output\email;
namespace mod_customcert\output\email;
defined('MOODLE_INTERNAL') || die();
/**
* Email certificate as html renderer.
*
* @package mod_htmlcert
* @copyright 2017 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class renderer extends \mod_htmlcert\output\renderer {
class renderer extends \mod_customcert\output\renderer {
/**
* The template name for this renderer.

View file

@ -17,23 +17,23 @@
/**
* Email certificate as text renderer.
*
* @package mod_htmlcert
* @copyright 2017 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert\output\email;
namespace mod_customcert\output\email;
defined('MOODLE_INTERNAL') || die();
/**
* Email certificate as text renderer.
*
* @package mod_htmlcert
* @copyright 2017 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class renderer_textemail extends \mod_htmlcert\output\renderer {
class renderer_textemail extends \mod_customcert\output\renderer {
/**
* The template name for this renderer.

View file

@ -17,12 +17,12 @@
/**
* Email certificate renderable.
*
* @package mod_htmlcert
* @copyright 2017 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert\output;
namespace mod_customcert\output;
defined('MOODLE_INTERNAL') || die();
@ -100,17 +100,17 @@ class email_certificate implements \renderable, \templatable {
$info->coursefullname = $this->coursefullname;
if ($this->isstudent) {
$data->emailgreeting = get_string('emailstudentgreeting', 'htmlcert', $this->userfullname);
$data->emailbody = get_string('emailstudentbody', 'htmlcert', $info);
$data->emailbodyplaintext = get_string('emailstudentbodyplaintext', 'htmlcert', $info);
$data->emailcertificatelink = new \moodle_url('/mod/htmlcert/view.php', array('id' => $this->cmid));
$data->emailcertificatetext = get_string('emailstudentcertificatelinktext', 'htmlcert');
$data->emailgreeting = get_string('emailstudentgreeting', 'customcert', $this->userfullname);
$data->emailbody = get_string('emailstudentbody', 'customcert', $info);
$data->emailbodyplaintext = get_string('emailstudentbodyplaintext', 'customcert', $info);
$data->emailcertificatelink = new \moodle_url('/mod/customcert/view.php', array('id' => $this->cmid));
$data->emailcertificatetext = get_string('emailstudentcertificatelinktext', 'customcert');
} else {
$data->emailgreeting = get_string('emailnonstudentgreeting', 'htmlcert');
$data->emailbody = get_string('emailnonstudentbody', 'htmlcert', $info);
$data->emailbodyplaintext = get_string('emailnonstudentbodyplaintext', 'htmlcert', $info);
$data->emailcertificatelink = new \moodle_url('/mod/htmlcert/view.php', array('id' => $this->cmid));
$data->emailcertificatetext = get_string('emailnonstudentcertificatelinktext', 'htmlcert');
$data->emailgreeting = get_string('emailnonstudentgreeting', 'customcert');
$data->emailbody = get_string('emailnonstudentbody', 'customcert', $info);
$data->emailbodyplaintext = get_string('emailnonstudentbodyplaintext', 'customcert', $info);
$data->emailcertificatelink = new \moodle_url('/mod/customcert/view.php', array('id' => $this->cmid));
$data->emailcertificatetext = get_string('emailnonstudentcertificatelinktext', 'customcert');
}
return $data;

View file

@ -17,12 +17,12 @@
/**
* Contains the mobile output class for the custom certificate.
*
* @package mod_htmlcert
* @copyright 2018 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert\output;
namespace mod_customcert\output;
defined('MOODLE_INTERNAL') || die();
@ -44,40 +44,39 @@ class mobile {
global $OUTPUT, $DB, $USER;
$args = (object) $args;
$versionname = $args->appversioncode >= 3950 ? 'latest' : 'ionic3';
$cmid = $args->cmid;
$groupid = empty($args->group) ? 0 : (int) $args->group; // By default, group 0.
$groupid = empty($args->group) ? 0 : $args->group; // By default, group 0.
// Capabilities check.
$cm = get_coursemodule_from_id('htmlcert', $cmid);
$cm = get_coursemodule_from_id('customcert', $cmid);
$context = \context_module::instance($cm->id);
self::require_capability($cm, $context, 'mod/htmlcert:view');
self::require_capability($cm, $context, 'mod/customcert:view');
// Set some variables we are going to be using.
$certificate = $DB->get_record('htmlcert', ['id' => $cm->instance], '*', MUST_EXIST);
$certificate = $DB->get_record('customcert', ['id' => $cm->instance], '*', MUST_EXIST);
$certificate->name = format_string($certificate->name);
list($certificate->intro, $certificate->introformat) = external_format_text($certificate->intro,
$certificate->introformat, $context->id, 'mod_htmlcert', 'intro');
$certificate->introformat, $context->id, 'mod_customcert', 'intro');
// Get any issues this person may have.
$issue = false;
if ($issues = $DB->get_records('htmlcert_issues', ['userid' => $USER->id, 'htmlcertid' => $certificate->id],
if ($issues = $DB->get_records('customcert_issues', ['userid' => $USER->id, 'customcertid' => $certificate->id],
'timecreated DESC')) {
$issue = reset($issues);
}
$requiredtimemet = true;
$canmanage = has_capability('mod/htmlcert:manage', $context);
$canmanage = has_capability('mod/customcert:manage', $context);
if ($certificate->requiredtime && !$canmanage) {
if (\mod_htmlcert\certificate::get_course_time($certificate->course) < ($certificate->requiredtime * 60)) {
if (\mod_customcert\certificate::get_course_time($certificate->course) < ($certificate->requiredtime * 60)) {
$requiredtimemet = false;
}
}
$fileurl = "";
if ($requiredtimemet) {
$fileurl = new \moodle_url('/mod/htmlcert/mobile/pluginfile.php', ['certificateid' => $certificate->id,
$fileurl = new \moodle_url('/mod/customcert/mobile/pluginfile.php', ['certificateid' => $certificate->id,
'userid' => $USER->id]);
$fileurl = $fileurl->out(true);
}
@ -85,7 +84,7 @@ class mobile {
$showreport = false;
$groups = [];
$recipients = [];
if (has_capability('mod/htmlcert:viewreport', $context)) {
if (has_capability('mod/customcert:viewreport', $context)) {
$showreport = true;
// Get the groups (if any) to display - also sets active group.
@ -95,10 +94,10 @@ class mobile {
$groupmode = 'aag';
}
$recipients = \mod_htmlcert\certificate::get_issues($certificate->id, $groupmode, $cm, 0, 0);
$recipients = \mod_customcert\certificate::get_issues($certificate->id, $groupmode, $cm, 0, 0);
foreach ($recipients as $recipient) {
$recipient->displayname = fullname($recipient);
$recipient->fileurl = new \moodle_url('/mod/htmlcert/mobile/pluginfile.php', ['certificateid' => $certificate->id,
$recipient->fileurl = new \moodle_url('/mod/customcert/mobile/pluginfile.php', ['certificateid' => $certificate->id,
'userid' => $recipient->id]);
}
}
@ -115,7 +114,6 @@ class mobile {
'showreport' => $showreport,
'hasrecipients' => !empty($recipients),
'recipients' => array_values($recipients),
'numrecipients' => count($recipients),
'currenttimestamp' => time()
];
@ -123,13 +121,11 @@ class mobile {
'templates' => [
[
'id' => 'main',
'html' => $OUTPUT->render_from_template("mod_htmlcert/mobile_view_activity_page_$versionname", $data),
'html' => $OUTPUT->render_from_template('mod_customcert/mobile_view_activity_page', $data),
],
],
'javascript' => '',
'otherdata' => [
'group' => $groupid,
]
'otherdata' => ''
];
}

View file

@ -17,12 +17,12 @@
/**
* Contains renderer class.
*
* @package mod_htmlcert
* @copyright 2017 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert\output;
namespace mod_customcert\output;
defined('MOODLE_INTERNAL') || die();
@ -31,8 +31,8 @@ use plugin_renderer_base;
/**
* Renderer class.
*
* @package mod_htmlcert
* @copyright 2017 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class renderer extends plugin_renderer_base {
@ -42,12 +42,12 @@ class renderer extends plugin_renderer_base {
*
* Defer to template.
*
* @param \mod_htmlcert\output\verify_certificate_results $page
* @param \mod_customcert\output\verify_certificate_results $page
* @return string html for the page
*/
public function render_verify_certificate_results(verify_certificate_results $page) {
$data = $page->export_for_template($this);
return parent::render_from_template('mod_htmlcert/verify_certificate_results', $data);
return parent::render_from_template('mod_customcert/verify_certificate_results', $data);
}
/**
@ -58,6 +58,6 @@ class renderer extends plugin_renderer_base {
*/
public function render_email_certificate(email_certificate $certificate) {
$data = $certificate->export_for_template($this);
return $this->render_from_template('mod_htmlcert/' . $this->get_template_name(), $data);
return $this->render_from_template('mod_customcert/' . $this->get_template_name(), $data);
}
}

View file

@ -17,12 +17,12 @@
/**
* Contains class used to prepare a verification result for display.
*
* @package mod_htmlcert
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert\output;
namespace mod_customcert\output;
defined('MOODLE_INTERNAL') || die();
@ -32,7 +32,7 @@ use templatable;
/**
* Class to prepare a verification result for display.
*
* @package mod_htmlcert
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
@ -69,7 +69,7 @@ class verify_certificate_result implements templatable, renderable {
* @param \stdClass $result
*/
public function __construct($result) {
$cm = get_coursemodule_from_instance('htmlcert', $result->certificateid);
$cm = get_coursemodule_from_instance('customcert', $result->certificateid);
$context = \context_module::instance($cm->id);
$this->userprofileurl = new \moodle_url('/user/view.php', array('id' => $result->userid,

View file

@ -17,12 +17,12 @@
/**
* Contains class used to prepare verification results for display.
*
* @package mod_htmlcert
* @copyright 2017 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert\output;
namespace mod_customcert\output;
defined('MOODLE_INTERNAL') || die();
@ -32,8 +32,8 @@ use templatable;
/**
* Class to prepare verification results for display.
*
* @package mod_htmlcert
* @copyright 2017 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class verify_certificate_results implements templatable, renderable {
@ -61,9 +61,9 @@ class verify_certificate_results implements templatable, renderable {
public function __construct($result) {
$this->success = $result->success;
if ($this->success) {
$this->message = get_string('verified', 'htmlcert');
$this->message = get_string('verified', 'customcert');
} else {
$this->message = get_string('notverified', 'htmlcert');
$this->message = get_string('notverified', 'customcert');
}
$this->issues = $result->issues;
}

View file

@ -1,5 +1,5 @@
<?php
// This file is part of the htmlcert module for Moodle - http://moodle.org/
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@ -17,12 +17,12 @@
/**
* Provides useful functions related to setting up the page.
*
* @package mod_htmlcert
* @copyright 2016 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert;
namespace mod_customcert;
defined('MOODLE_INTERNAL') || die();
@ -31,8 +31,8 @@ defined('MOODLE_INTERNAL') || die();
*
* Provides useful functions.
*
* @package mod_htmlcert
* @copyright 2016 Mark Nelson <markn@moodle.com>, Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class page_helper {
@ -56,7 +56,7 @@ class page_helper {
$PAGE->set_pagelayout('admin');
$PAGE->set_heading($SITE->fullname);
$urloverride = new \moodle_url('/admin/settings.php?section=modsettinghtmlcert');
$urloverride = new \moodle_url('/admin/settings.php?section=modsettingcustomcert');
\navigation_node::override_active_url($urloverride);
} else {
$PAGE->set_heading(format_string($COURSE->fullname));

View file

@ -0,0 +1,87 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Subplugin info class.
*
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_customcert\plugininfo;
use core\plugininfo\base;
defined('MOODLE_INTERNAL') || die();
/**
* Subplugin info class.
*
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class customcertelement extends base {
/**
* Do not allow users to uninstall these plugins as it could cause customcerts to break.
*
* @return bool
*/
public function is_uninstall_allowed() {
return false;
}
/**
* Loads plugin settings to the settings tree.
*
* @param \part_of_admin_tree $adminroot
* @param string $parentnodename
* @param bool $hassiteconfig whether the current user has moodle/site:config capability
*/
public function load_settings(\part_of_admin_tree $adminroot, $parentnodename, $hassiteconfig) {
global $CFG, $USER, $DB, $OUTPUT, $PAGE;
$ADMIN = $adminroot;
$plugininfo = $this;
if (!$this->is_installed_and_upgraded()) {
return;
}
if (!$hassiteconfig or !file_exists($this->full_path('settings.php'))) {
return;
}
$section = $this->get_settings_section_name();
$settings = new \admin_settingpage($section, $this->displayname, 'moodle/site:config', false);
include($this->full_path('settings.php'));
$ADMIN->add($parentnodename, $settings);
}
/**
* Get the settings section name.
*
* @return null|string the settings section name.
*/
public function get_settings_section_name() {
if (file_exists($this->full_path('settings.php'))) {
return 'customcertelement_' . $this->name;
} else {
return null;
}
}
}

View file

@ -15,13 +15,13 @@
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Privacy Subsystem implementation for mod_htmlcert.
* Privacy Subsystem implementation for mod_customcert.
*
* @package mod_htmlcert
* @copyright 2018 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert\privacy;
namespace mod_customcert\privacy;
use core_privacy\local\metadata\collection;
use core_privacy\local\request\approved_contextlist;
@ -35,7 +35,7 @@ use core_privacy\local\request\writer;
defined('MOODLE_INTERNAL') || die();
/**
* Privacy Subsystem implementation for mod_htmlcert.
* Privacy Subsystem implementation for mod_customcert.
*
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
@ -53,15 +53,15 @@ class provider implements
*/
public static function get_metadata(collection $items) : collection {
$items->add_database_table(
'htmlcert_issues',
'customcert_issues',
[
'userid' => 'privacy:metadata:htmlcert_issues:userid',
'htmlcertid' => 'privacy:metadata:htmlcert_issues:htmlcertid',
'code' => 'privacy:metadata:htmlcert_issues:code',
'emailed' => 'privacy:metadata:htmlcert_issues:emailed',
'timecreated' => 'privacy:metadata:htmlcert_issues:timecreated',
'userid' => 'privacy:metadata:customcert_issues:userid',
'customcertid' => 'privacy:metadata:customcert_issues:customcertid',
'code' => 'privacy:metadata:customcert_issues:code',
'emailed' => 'privacy:metadata:customcert_issues:emailed',
'timecreated' => 'privacy:metadata:customcert_issues:timecreated',
],
'privacy:metadata:htmlcert_issues'
'privacy:metadata:customcert_issues'
);
return $items;
@ -82,14 +82,14 @@ class provider implements
INNER JOIN {modules} m
ON m.id = cm.module
AND m.name = :modulename
INNER JOIN {htmlcert} htmlcert
ON htmlcert.id = cm.instance
INNER JOIN {htmlcert_issues} htmlcertissues
ON htmlcertissues.htmlcertid = htmlcert.id
WHERE htmlcertissues.userid = :userid";
INNER JOIN {customcert} customcert
ON customcert.id = cm.instance
INNER JOIN {customcert_issues} customcertissues
ON customcertissues.customcertid = customcert.id
WHERE customcertissues.userid = :userid";
$params = [
'modulename' => 'htmlcert',
'modulename' => 'customcert',
'contextlevel' => CONTEXT_MODULE,
'userid' => $userid,
];
@ -112,19 +112,19 @@ class provider implements
}
// Fetch all users who have a custom certificate.
$sql = "SELECT htmlcertissues.userid
$sql = "SELECT customcertissues.userid
FROM {course_modules} cm
JOIN {modules} m
ON m.id = cm.module AND m.name = :modname
JOIN {htmlcert} htmlcert
ON htmlcert.id = cm.instance
JOIN {htmlcert_issues} htmlcertissues
ON htmlcertissues.htmlcertid = htmlcert.id
JOIN {customcert} customcert
ON customcert.id = cm.instance
JOIN {customcert_issues} customcertissues
ON customcertissues.customcertid = customcert.id
WHERE cm.id = :cmid";
$params = [
'cmid' => $context->instanceid,
'modname' => 'htmlcert',
'modname' => 'customcert',
];
$userlist->add_from_sql('userid', $sql, $params);
@ -152,22 +152,22 @@ class provider implements
$user = $contextlist->get_user();
// Get all the htmlcert activities associated with the above course modules.
$htmlcertidstocmids = self::get_htmlcert_ids_to_cmids_from_cmids($cmids);
// Get all the customcert activities associated with the above course modules.
$customcertidstocmids = self::get_customcert_ids_to_cmids_from_cmids($cmids);
list($insql, $inparams) = $DB->get_in_or_equal(array_keys($htmlcertidstocmids), SQL_PARAMS_NAMED);
list($insql, $inparams) = $DB->get_in_or_equal(array_keys($customcertidstocmids), SQL_PARAMS_NAMED);
$params = array_merge($inparams, ['userid' => $user->id]);
$recordset = $DB->get_recordset_select('htmlcert_issues', "htmlcertid $insql AND userid = :userid",
$recordset = $DB->get_recordset_select('customcert_issues', "customcertid $insql AND userid = :userid",
$params, 'timecreated, id ASC');
self::recordset_loop_and_export($recordset, 'htmlcertid', [], function($carry, $record) {
self::recordset_loop_and_export($recordset, 'customcertid', [], function($carry, $record) {
$carry[] = [
'code' => $record->code,
'emailed' => transform::yesno($record->emailed),
'timecreated' => transform::datetime($record->timecreated)
];
return $carry;
}, function($htmlcertid, $data) use ($user, $htmlcertidstocmids) {
$context = \context_module::instance($htmlcertidstocmids[$htmlcertid]);
}, function($customcertid, $data) use ($user, $customcertidstocmids) {
$context = \context_module::instance($customcertidstocmids[$customcertid]);
$contextdata = helper::get_context_data($context, $user);
$finaldata = (object) array_merge((array) $contextdata, ['issues' => $data]);
helper::export_context_files($context, $user);
@ -187,11 +187,11 @@ class provider implements
return;
}
if (!$cm = get_coursemodule_from_id('htmlcert', $context->instanceid)) {
if (!$cm = get_coursemodule_from_id('customcert', $context->instanceid)) {
return;
}
$DB->delete_records('htmlcert_issues', ['htmlcertid' => $cm->instance]);
$DB->delete_records('customcert_issues', ['customcertid' => $cm->instance]);
}
/**
@ -212,7 +212,7 @@ class provider implements
continue;
}
$instanceid = $DB->get_field('course_modules', 'instance', ['id' => $context->instanceid], MUST_EXIST);
$DB->delete_records('htmlcert_issues', ['htmlcertid' => $instanceid, 'userid' => $userid]);
$DB->delete_records('customcert_issues', ['customcertid' => $instanceid, 'userid' => $userid]);
}
}
@ -229,39 +229,39 @@ class provider implements
return;
}
$cm = get_coursemodule_from_id('htmlcert', $context->instanceid);
$cm = get_coursemodule_from_id('customcert', $context->instanceid);
if (!$cm) {
// Only htmlcert module will be handled.
// Only customcert module will be handled.
return;
}
$userids = $userlist->get_userids();
list($usersql, $userparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
$select = "htmlcertid = :htmlcertid AND userid $usersql";
$params = ['htmlcertid' => $cm->instance] + $userparams;
$DB->delete_records_select('htmlcert_issues', $select, $params);
$select = "customcertid = :customcertid AND userid $usersql";
$params = ['customcertid' => $cm->instance] + $userparams;
$DB->delete_records_select('customcert_issues', $select, $params);
}
/**
* Return a list of htmlcert IDs mapped to their course module ID.
* Return a list of Customcert IDs mapped to their course module ID.
*
* @param array $cmids The course module IDs.
* @return array In the form of [$htmlcertid => $cmid].
* @return array In the form of [$customcertid => $cmid].
*/
protected static function get_htmlcert_ids_to_cmids_from_cmids(array $cmids) {
protected static function get_customcert_ids_to_cmids_from_cmids(array $cmids) {
global $DB;
list($insql, $inparams) = $DB->get_in_or_equal($cmids, SQL_PARAMS_NAMED);
$sql = "SELECT htmlcert.id, cm.id AS cmid
FROM {htmlcert} htmlcert
$sql = "SELECT customcert.id, cm.id AS cmid
FROM {customcert} customcert
JOIN {modules} m
ON m.name = :modulename
JOIN {course_modules} cm
ON cm.instance = htmlcert.id
ON cm.instance = customcert.id
AND cm.module = m.id
WHERE cm.id $insql";
$params = array_merge($inparams, ['modulename' => 'htmlcert']);
$params = array_merge($inparams, ['modulename' => 'customcert']);
return $DB->get_records_sql_menu($sql, $params);
}

View file

@ -17,12 +17,12 @@
/**
* The report that displays issued certificates.
*
* @package mod_htmlcert
* @copyright 2016 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert;
namespace mod_customcert;
defined('MOODLE_INTERNAL') || die;
@ -33,16 +33,16 @@ require_once($CFG->libdir . '/tablelib.php');
/**
* Class for the report that displays issued certificates.
*
* @package mod_htmlcert
* @copyright 2016 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class report_table extends \table_sql {
/**
* @var int $htmlcertid The custom certificate id
* @var int $customcertid The custom certificate id
*/
protected $htmlcertid;
protected $customcertid;
/**
* @var \stdClass $cm The course module.
@ -57,16 +57,16 @@ class report_table extends \table_sql {
/**
* Sets up the table.
*
* @param int $htmlcertid
* @param int $customcertid
* @param \stdClass $cm the course module
* @param bool $groupmode are we in group mode?
* @param string|null $download The file type, null if we are not downloading
*/
public function __construct($htmlcertid, $cm, $groupmode, $download = null) {
parent::__construct('mod_htmlcert_report_table');
public function __construct($customcertid, $cm, $groupmode, $download = null) {
parent::__construct('mod_customcert_report_table');
$context = \context_module::instance($cm->id);
$extrafields = \core_user\fields::for_identity($context)->get_required_fields();
$extrafields = get_extra_user_fields($context);
$columns = [];
$columns[] = 'fullname';
@ -79,14 +79,14 @@ class report_table extends \table_sql {
$headers = [];
$headers[] = get_string('fullname');
foreach ($extrafields as $extrafield) {
$headers[] = \core_user\fields::get_display_name($extrafield);
$headers[] = get_user_field_name($extrafield);
}
$headers[] = get_string('receiveddate', 'htmlcert');
$headers[] = get_string('code', 'htmlcert');
$headers[] = get_string('receiveddate', 'customcert');
$headers[] = get_string('code', 'customcert');
// Check if we were passed a filename, which means we want to download it.
if ($download) {
$this->is_downloading($download, 'htmlcert-report');
$this->is_downloading($download, 'customcert-report');
}
if (!$this->is_downloading()) {
@ -94,7 +94,7 @@ class report_table extends \table_sql {
$headers[] = get_string('file');
}
if (!$this->is_downloading() && has_capability('mod/htmlcert:manage', $context)) {
if (!$this->is_downloading() && has_capability('mod/customcert:manage', $context)) {
$columns[] = 'actions';
$headers[] = '';
}
@ -107,7 +107,7 @@ class report_table extends \table_sql {
$this->no_sorting('download');
$this->is_downloadable(true);
$this->htmlcertid = $htmlcertid;
$this->customcertid = $customcertid;
$this->cm = $cm;
$this->groupmode = $groupmode;
}
@ -157,8 +157,8 @@ class report_table extends \table_sql {
public function col_download($user) {
global $OUTPUT;
$icon = new \pix_icon('download', get_string('download'), 'htmlcert');
$link = new \moodle_url('/mod/htmlcert/view.php',
$icon = new \pix_icon('download', get_string('download'), 'customcert');
$link = new \moodle_url('/mod/customcert/view.php',
[
'id' => $this->cm->id,
'downloadissue' => $user->id
@ -178,7 +178,7 @@ class report_table extends \table_sql {
global $OUTPUT;
$icon = new \pix_icon('i/delete', get_string('delete'));
$link = new \moodle_url('/mod/htmlcert/view.php',
$link = new \moodle_url('/mod/customcert/view.php',
[
'id' => $this->cm->id,
'deleteissue' => $user->issueid,
@ -196,11 +196,11 @@ class report_table extends \table_sql {
* @param bool $useinitialsbar do you want to use the initials bar.
*/
public function query_db($pagesize, $useinitialsbar = true) {
$total = \mod_htmlcert\certificate::get_number_of_issues($this->htmlcertid, $this->cm, $this->groupmode);
$total = \mod_customcert\certificate::get_number_of_issues($this->customcertid, $this->cm, $this->groupmode);
$this->pagesize($pagesize, $total);
$this->rawdata = \mod_htmlcert\certificate::get_issues($this->htmlcertid, $this->groupmode, $this->cm,
$this->rawdata = \mod_customcert\certificate::get_issues($this->customcertid, $this->groupmode, $this->cm,
$this->get_page_start(), $this->get_page_size(), $this->get_sql_sort());
// Set initial bars.
@ -214,7 +214,7 @@ class report_table extends \table_sql {
*/
public function download() {
\core\session\manager::write_close();
$total = \mod_htmlcert\certificate::get_number_of_issues($this->htmlcertid, $this->cm, $this->groupmode);
$total = \mod_customcert\certificate::get_number_of_issues($this->customcertid, $this->cm, $this->groupmode);
$this->out($total, false);
exit;
}

View file

@ -1,5 +1,5 @@
<?php
// This file is part of the htmlcert module for Moodle - http://moodle.org/
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@ -15,22 +15,22 @@
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Search area for mod_htmlcert activities.
* Search area for mod_customcert activities.
*
* @package mod_htmlcert
* @copyright 2016 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert\search;
namespace mod_customcert\search;
defined('MOODLE_INTERNAL') || die();
/**
* Search area for mod_htmlcert activities.
* Search area for mod_customcert activities.
*
* @package mod_htmlcert
* @copyright 2016 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class activity extends \core_search\base_activity {

View file

@ -17,21 +17,19 @@
/**
* A scheduled task for emailing certificates.
*
* @package mod_htmlcert
* @copyright 2017 Mark Nelson <markn@moodle.com>, 2021 Kumi Systems e.U. <office@kumi.systems>
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert\task;
use mod_htmlcert\helper;
namespace mod_customcert\task;
defined('MOODLE_INTERNAL') || die();
/**
* A scheduled task for emailing certificates.
*
* @package mod_htmlcert
* @copyright 2017 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class email_certificate_task extends \core\task\scheduled_task {
@ -42,7 +40,7 @@ class email_certificate_task extends \core\task\scheduled_task {
* @return string
*/
public function get_name() {
return get_string('taskemailcertificate', 'htmlcert');
return get_string('taskemailcertificate', 'customcert');
}
/**
@ -55,29 +53,36 @@ class email_certificate_task extends \core\task\scheduled_task {
$emailotherslengthsql = $DB->sql_length('c.emailothers');
$sql = "SELECT c.*, ct.id as templateid, ct.name as templatename, ct.contextid, co.id as courseid,
co.fullname as coursefullname, co.shortname as courseshortname
FROM {htmlcert} c
JOIN {htmlcert_templates} ct
FROM {customcert} c
JOIN {customcert_templates} ct
ON c.templateid = ct.id
JOIN {course} co
ON c.course = co.id
WHERE (c.emailstudents = :emailstudents
OR c.emailteachers = :emailteachers
OR $emailotherslengthsql >= 3)";
if (!$htmlcerts = $DB->get_records_sql($sql, array('emailstudents' => 1, 'emailteachers' => 1))) {
if (!$customcerts = $DB->get_records_sql($sql, array('emailstudents' => 1, 'emailteachers' => 1))) {
return;
}
// The renderers used for sending emails.
$htmlrenderer = $PAGE->get_renderer('mod_htmlcert', 'email', 'htmlemail');
$textrenderer = $PAGE->get_renderer('mod_htmlcert', 'email', 'textemail');
$htmlrenderer = $PAGE->get_renderer('mod_customcert', 'email', 'htmlemail');
$textrenderer = $PAGE->get_renderer('mod_customcert', 'email', 'textemail');
foreach ($customcerts as $customcert) {
// Do not process an empty certificate.
$sql = "SELECT ce.*
FROM {customcert_elements} ce
JOIN {customcert_pages} cp
ON cp.id = ce.pageid
JOIN {customcert_templates} ct
ON ct.id = cp.templateid
WHERE ct.contextid = :contextid";
if (!$DB->record_exists_sql($sql, ['contextid' => $customcert->contextid])) {
continue;
}
// Get the context.
$context = \context::instance_by_id($htmlcert->contextid);
// Set the $PAGE context - this ensure settings, such as language, are kept and don't default to the site settings.
$PAGE->set_context($context);
$context = \context::instance_by_id($customcert->contextid);
// Get the person we are going to send this email on behalf of.
$userfrom = \core_user::get_noreply_user();
@ -85,9 +90,9 @@ class email_certificate_task extends \core\task\scheduled_task {
// Store teachers for later.
$teachers = get_enrolled_users($context, 'moodle/course:update');
$courseshortname = format_string($htmlcert->courseshortname, true, array('context' => $context));
$coursefullname = format_string($htmlcert->coursefullname, true, array('context' => $context));
$certificatename = format_string($htmlcert->name, true, array('context' => $context));
$courseshortname = format_string($customcert->courseshortname, true, array('context' => $context));
$coursefullname = format_string($customcert->coursefullname, true, array('context' => $context));
$certificatename = format_string($customcert->name, true, array('context' => $context));
// Used to create the email subject.
$info = new \stdClass;
@ -97,16 +102,16 @@ class email_certificate_task extends \core\task\scheduled_task {
$info->certificatename = $certificatename;
// Get a list of all the issues.
$userfields = helper::get_all_user_name_fields('u');
$userfields = get_all_user_name_fields(true, 'u');
$sql = "SELECT u.id, u.username, $userfields, u.email, ci.id as issueid, ci.emailed
FROM {htmlcert_issues} ci
JOIN {user} u
FROM {customcert_issues} ci
JOIN {user} u
ON ci.userid = u.id
WHERE ci.htmlcertid = :htmlcertid";
$issuedusers = $DB->get_records_sql($sql, array('htmlcertid' => $htmlcert->id));
WHERE ci.customcertid = :customcertid";
$issuedusers = $DB->get_records_sql($sql, array('customcertid' => $customcert->id));
// Now, get a list of users who can access the certificate but have not yet.
$enrolledusers = get_enrolled_users(\context_course::instance($htmlcert->courseid), 'mod/htmlcert:view');
$enrolledusers = get_enrolled_users(\context_course::instance($customcert->courseid), 'mod/customcert:view');
foreach ($enrolledusers as $enroluser) {
// Check if the user has already been issued.
if (in_array($enroluser->id, array_keys((array) $issuedusers))) {
@ -114,35 +119,35 @@ class email_certificate_task extends \core\task\scheduled_task {
}
// Now check if the certificate is not visible to the current user.
$cm = get_fast_modinfo($htmlcert->courseid, $enroluser->id)->instances['htmlcert'][$htmlcert->id];
$cm = get_fast_modinfo($customcert->courseid, $enroluser->id)->instances['customcert'][$customcert->id];
if (!$cm->uservisible) {
continue;
}
// Don't want to email those with the capability to manage the certificate.
if (has_capability('mod/htmlcert:manage', $context, $enroluser->id)) {
if (has_capability('mod/customcert:manage', $context, $enroluser->id)) {
continue;
}
// Only email those with the capability to receive the certificate.
if (!has_capability('mod/htmlcert:receiveissue', $context, $enroluser->id)) {
if (!has_capability('mod/customcert:receiveissue', $context, $enroluser->id)) {
continue;
}
// Check that they have passed the required time.
if (!empty($htmlcert->requiredtime)) {
if (\mod_htmlcert\certificate::get_course_time($htmlcert->courseid,
$enroluser->id) < ($htmlcert->requiredtime * 60)) {
if (!empty($customcert->requiredtime)) {
if (\mod_customcert\certificate::get_course_time($customcert->courseid,
$enroluser->id) < ($customcert->requiredtime * 60)) {
continue;
}
}
// Ensure the cert hasn't already been issued, e.g via the UI (view.php) - a race condition.
$issueid = $DB->get_field('htmlcert_issues', 'id',
array('userid' => $enroluser->id, 'htmlcertid' => $htmlcert->id), IGNORE_MULTIPLE);
$issueid = $DB->get_field('customcert_issues', 'id',
array('userid' => $enroluser->id, 'customcertid' => $customcert->id), IGNORE_MULTIPLE);
if (empty($issueid)) {
// Ok, issue them the certificate.
$issueid = \mod_htmlcert\certificate::issue_certificate($htmlcert->id, $enroluser->id);
$issueid = \mod_customcert\certificate::issue_certificate($customcert->id, $enroluser->id);
}
// Add them to the array so we email them.
@ -171,18 +176,15 @@ class email_certificate_task extends \core\task\scheduled_task {
// Now, email the people we need to.
foreach ($issuedusers as $user) {
// Set up the user.
cron_setup_user($user);
$userfullname = fullname($user);
$info->userfullname = $userfullname;
// Now, get the PDF.
$template = new \stdClass();
$template->id = $htmlcert->templateid;
$template->name = $htmlcert->templatename;
$template->contextid = $htmlcert->contextid;
$template = new \mod_htmlcert\template($template);
$template->id = $customcert->templateid;
$template->name = $customcert->templatename;
$template->contextid = $customcert->contextid;
$template = new \mod_customcert\template($template);
$filecontents = $template->generate_pdf(false, $user->id, true);
// Set the name of the file we are going to send.
@ -196,55 +198,53 @@ class email_certificate_task extends \core\task\scheduled_task {
$tempfile = $tempdir . '/' . md5(microtime() . $user->id) . '.pdf';
file_put_contents($tempfile, $filecontents);
if ($htmlcert->emailstudents) {
$renderable = new \mod_htmlcert\output\email_certificate(true, $userfullname, $courseshortname,
$coursefullname, $certificatename, $htmlcert->contextid);
if ($customcert->emailstudents) {
$renderable = new \mod_customcert\output\email_certificate(true, $userfullname, $courseshortname,
$coursefullname, $certificatename, $customcert->contextid);
$subject = get_string('emailstudentsubject', 'htmlcert', $info);
$subject = get_string('emailstudentsubject', 'customcert', $info);
$message = $textrenderer->render($renderable);
$messagehtml = $htmlrenderer->render($renderable);
email_to_user($user, fullname($userfrom), html_entity_decode($subject), $message, $messagehtml,
$tempfile, $filename);
email_to_user($user, fullname($userfrom), $subject, $message, $messagehtml, $tempfile, $filename);
}
if ($htmlcert->emailteachers) {
$renderable = new \mod_htmlcert\output\email_certificate(false, $userfullname, $courseshortname,
$coursefullname, $certificatename, $htmlcert->contextid);
if ($customcert->emailteachers) {
$renderable = new \mod_customcert\output\email_certificate(false, $userfullname, $courseshortname,
$coursefullname, $certificatename, $customcert->contextid);
$subject = get_string('emailnonstudentsubject', 'htmlcert', $info);
$subject = get_string('emailnonstudentsubject', 'customcert', $info);
$message = $textrenderer->render($renderable);
$messagehtml = $htmlrenderer->render($renderable);
foreach ($teachers as $teacher) {
email_to_user($teacher, fullname($userfrom), html_entity_decode($subject), $message, $messagehtml,
$tempfile, $filename);
email_to_user($teacher, fullname($userfrom), $subject, $message, $messagehtml, $tempfile,
$filename);
}
}
if (!empty($htmlcert->emailothers)) {
$others = explode(',', $htmlcert->emailothers);
if (!empty($customcert->emailothers)) {
$others = explode(',', $customcert->emailothers);
foreach ($others as $email) {
$email = trim($email);
if (validate_email($email)) {
$renderable = new \mod_htmlcert\output\email_certificate(false, $userfullname,
$courseshortname, $coursefullname, $certificatename, $htmlcert->contextid);
$renderable = new \mod_customcert\output\email_certificate(false, $userfullname,
$courseshortname, $coursefullname, $certificatename, $customcert->contextid);
$subject = get_string('emailnonstudentsubject', 'htmlcert', $info);
$subject = get_string('emailnonstudentsubject', 'customcert', $info);
$message = $textrenderer->render($renderable);
$messagehtml = $htmlrenderer->render($renderable);
$emailuser = new \stdClass();
$emailuser->id = -1;
$emailuser->email = $email;
email_to_user($emailuser, fullname($userfrom), html_entity_decode($subject), $message,
$messagehtml, $tempfile, $filename);
email_to_user($emailuser, fullname($userfrom), $subject, $message, $messagehtml, $tempfile,
$filename);
}
}
}
// Set the field so that it is emailed.
$DB->set_field('htmlcert_issues', 'emailed', 1, array('id' => $user->issueid));
$DB->set_field('customcert_issues', 'emailed', 1, array('id' => $user->issueid));
}
}
}
}

View file

@ -15,27 +15,22 @@
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Class represents a htmlcert template.
* Class represents a customcert template.
*
* @package mod_htmlcert
* @copyright 2016 Mark Nelson <markn@moodle.com>, 2021-2022 Kumi Systems e.U. <office@kumi.systems>
* @package mod_customcert
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert;
require_once(__DIR__ . "/../vendor/autoload.php");
require_once($CFG->dirroot.'/user/profile/lib.php');
use mikehaertl\wkhtmlto\Pdf;
namespace mod_customcert;
defined('MOODLE_INTERNAL') || die();
/**
* Class represents a htmlcert template.
* Class represents a customcert template.
*
* @package mod_htmlcert
* @copyright 2016 Mark Nelson <markn@moodle.com>, 2021-2022 Kumi Systems e.U. <office@kumi.systems>
* @package mod_customcert
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class template {
@ -55,8 +50,6 @@ class template {
*/
protected $contextid;
protected $html;
/**
* The constructor.
*
@ -66,7 +59,6 @@ class template {
$this->id = $template->id;
$this->name = $template->name;
$this->contextid = $template->contextid;
$this->html = $template->html;
}
/**
@ -80,10 +72,74 @@ class template {
$savedata = new \stdClass();
$savedata->id = $this->id;
$savedata->name = $data->name;
$savedata->html = $data->html ?: $this->html;
$savedata->timemodified = time();
$DB->update_record('htmlcert_templates', $savedata);
$DB->update_record('customcert_templates', $savedata);
}
/**
* Handles adding another page to the template.
*
* @return int the id of the page
*/
public function add_page() {
global $DB;
// Set the page number to 1 to begin with.
$sequence = 1;
// Get the max page number.
$sql = "SELECT MAX(sequence) as maxpage
FROM {customcert_pages} cp
WHERE cp.templateid = :templateid";
if ($maxpage = $DB->get_record_sql($sql, array('templateid' => $this->id))) {
$sequence = $maxpage->maxpage + 1;
}
// New page creation.
$page = new \stdClass();
$page->templateid = $this->id;
$page->width = '210';
$page->height = '297';
$page->sequence = $sequence;
$page->timecreated = time();
$page->timemodified = $page->timecreated;
// Insert the page.
return $DB->insert_record('customcert_pages', $page);
}
/**
* Handles saving page data.
*
* @param \stdClass $data the template data
*/
public function save_page($data) {
global $DB;
// Set the time to a variable.
$time = time();
// Get the existing pages and save the page data.
if ($pages = $DB->get_records('customcert_pages', array('templateid' => $data->tid))) {
// Loop through existing pages.
foreach ($pages as $page) {
// Get the name of the fields we want from the form.
$width = 'pagewidth_' . $page->id;
$height = 'pageheight_' . $page->id;
$leftmargin = 'pageleftmargin_' . $page->id;
$rightmargin = 'pagerightmargin_' . $page->id;
// Create the page data to update the DB with.
$p = new \stdClass();
$p->id = $page->id;
$p->width = $data->$width;
$p->height = $data->$height;
$p->leftmargin = $data->$leftmargin;
$p->rightmargin = $data->$rightmargin;
$p->timemodified = $time;
// Update the page.
$DB->update_record('customcert_pages', $p);
}
}
}
/**
@ -94,13 +150,101 @@ class template {
public function delete() {
global $DB;
if (!$DB->delete_records('htmlcert_templates', array('id' => $this->id))) {
// Delete the elements.
$sql = "SELECT e.*
FROM {customcert_elements} e
INNER JOIN {customcert_pages} p
ON e.pageid = p.id
WHERE p.templateid = :templateid";
if ($elements = $DB->get_records_sql($sql, array('templateid' => $this->id))) {
foreach ($elements as $element) {
// Get an instance of the element class.
if ($e = \mod_customcert\element_factory::get_element_instance($element)) {
$e->delete();
} else {
// The plugin files are missing, so just remove the entry from the DB.
$DB->delete_records('customcert_elements', array('id' => $element->id));
}
}
}
// Delete the pages.
if (!$DB->delete_records('customcert_pages', array('templateid' => $this->id))) {
return false;
}
// Now, finally delete the actual template.
if (!$DB->delete_records('customcert_templates', array('id' => $this->id))) {
return false;
}
return true;
}
/**
* Handles deleting a page from the template.
*
* @param int $pageid the template page
*/
public function delete_page($pageid) {
global $DB;
// Get the page.
$page = $DB->get_record('customcert_pages', array('id' => $pageid), '*', MUST_EXIST);
// Delete this page.
$DB->delete_records('customcert_pages', array('id' => $page->id));
// The element may have some extra tasks it needs to complete to completely delete itself.
if ($elements = $DB->get_records('customcert_elements', array('pageid' => $page->id))) {
foreach ($elements as $element) {
// Get an instance of the element class.
if ($e = \mod_customcert\element_factory::get_element_instance($element)) {
$e->delete();
} else {
// The plugin files are missing, so just remove the entry from the DB.
$DB->delete_records('customcert_elements', array('id' => $element->id));
}
}
}
// Now we want to decrease the page number values of
// the pages that are greater than the page we deleted.
$sql = "UPDATE {customcert_pages}
SET sequence = sequence - 1
WHERE templateid = :templateid
AND sequence > :sequence";
$DB->execute($sql, array('templateid' => $this->id, 'sequence' => $page->sequence));
}
/**
* Handles deleting an element from the template.
*
* @param int $elementid the template page
*/
public function delete_element($elementid) {
global $DB;
// Ensure element exists and delete it.
$element = $DB->get_record('customcert_elements', array('id' => $elementid), '*', MUST_EXIST);
// Get an instance of the element class.
if ($e = \mod_customcert\element_factory::get_element_instance($element)) {
$e->delete();
} else {
// The plugin files are missing, so just remove the entry from the DB.
$DB->delete_records('customcert_elements', array('id' => $elementid));
}
// Now we want to decrease the sequence numbers of the elements
// that are greater than the element we deleted.
$sql = "UPDATE {customcert_elements}
SET sequence = sequence - 1
WHERE pageid = :pageid
AND sequence > :sequence";
$DB->execute($sql, array('pageid' => $element->pageid, 'sequence' => $element->sequence));
}
/**
* Generate the PDF for the template.
*
@ -109,8 +253,8 @@ class template {
* @param bool $return Do we want to return the contents of the PDF?
* @return string|void Can return the PDF in string format if specified.
*/
public function generate_pdf(bool $preview = false, int $userid = null, bool $return = false) {
global $CFG, $DB, $USER, $SITE;
public function generate_pdf($preview = false, $userid = null, $return = false) {
global $CFG, $DB, $USER;
if (empty($userid)) {
$user = $USER;
@ -118,72 +262,65 @@ class template {
$user = \core_user::get_user($userid);
}
profile_load_data($user);
require_once($CFG->libdir . '/pdflib.php');
$htmlcert = $DB->get_record('htmlcert', ['templateid' => $this->id]);
// Get the pages for the template, there should always be at least one page for each template.
if ($pages = $DB->get_records('customcert_pages', array('templateid' => $this->id), 'sequence ASC')) {
// Create the pdf object.
$pdf = new \pdf();
$pdf = new Pdf(array(
"disable-smart-shrinking",
"margin-bottom" => "0",
"margin-right" => "0",
"margin-left" => "0",
"margin-top" => "0"
));
$html = $this->html;
$context = \context_user::instance($user->id);
$fs = get_file_storage();
$files = $fs->get_area_files($context->id, 'user', 'icon', 0);
$file = null;
$content = "";
foreach ($files as $filefound) {
if (!$filefound->is_directory()) {
$file = $filefound;
break;
// If the template belongs to a certificate then we need to check what permissions we set for it.
if ($protection = $DB->get_field('customcert', 'protection', array('templateid' => $this->id))) {
if (!empty($protection)) {
$protection = explode(', ', $protection);
$pdf->SetProtection($protection);
}
}
}
if ($file) {
$location = make_request_directory() . '/target';
$content = $file->get_content();
}
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetTitle($this->name);
$pdf->SetAutoPageBreak(true, 0);
// Remove full-stop at the end, if it exists, to avoid "..pdf" being created and being filtered by clean_filename.
$filename = rtrim($this->name, '.');
$html = str_replace("__PROFILEPIC__", 'data: ' . mime_content_type($file) . ';base64,' . $content, $html);
// This is the logic the TCPDF library uses when processing the name. This makes names
// such as 'الشهادة' become empty, so set a default name in these cases.
$filename = preg_replace('/[\s]+/', '_', $filename);
$filename = preg_replace('/[^a-zA-Z0-9_\.-]/', '', $filename);
$html = str_replace("__NAME__", $user->firstname . " " . $user->lastname, $html);
if (empty($filename)) {
$filename = get_string('certificate', 'customcert');
}
if ($preview) {
$code = \mod_htmlcert\certificate::generate_code();
} else {
$issue = $DB->get_record('htmlcert_issues', array('userid' => $user->id, 'htmlcertid' => $htmlcert->id),
'*', IGNORE_MULTIPLE);
$code = $issue->code;
}
$filename = clean_filename($filename . '.pdf');
// Loop through the pages and display their content.
foreach ($pages as $page) {
// Add the page to the PDF.
if ($page->width > $page->height) {
$orientation = 'L';
} else {
$orientation = 'P';
}
$pdf->AddPage($orientation, array($page->width, $page->height));
$pdf->SetMargins($page->leftmargin, 0, $page->rightmargin);
// Get the elements for the page.
if ($elements = $DB->get_records('customcert_elements', array('pageid' => $page->id), 'sequence ASC')) {
// Loop through and display.
foreach ($elements as $element) {
// Get an instance of the element class.
if ($e = \mod_customcert\element_factory::get_element_instance($element)) {
$e->render($pdf, $preview, $user);
}
}
}
}
$html = str_replace("__CERTNUM__", $code, $html);
if ($return) {
return $pdf->Output('', 'S');
}
$courseid = $htmlcert->course ?: $SITE->id;
$course = get_course($courseid);
$coursename = $course->fullname;
$html = str_replace("__COURSE__", $coursename, $html);
$date = $issue->timecreated;
$html = str_replace("__DATE__", userdate($date, '%B %d, %Y'), $html);
$html = str_replace("__PIN__", $user->username, $html);
$pdf->addPage($html);
$pdf->send();
die($pdf->getError());
if ($return) {
return $pdf->toString();
$pdf->Output($filename, 'I');
}
}
@ -195,10 +332,78 @@ class template {
public function copy_to_template($copytotemplateid) {
global $DB;
$copytotemplate = $DB->get_record('htmlcert_templates', array('id' => $copytotemplateid));
$copytotemplate->html = $this->html;
$DB->update_record('htmlcert_templates', $copytotemplate);
// Get the pages for the template, there should always be at least one page for each template.
if ($templatepages = $DB->get_records('customcert_pages', array('templateid' => $this->id))) {
// Loop through the pages.
foreach ($templatepages as $templatepage) {
$page = clone($templatepage);
$page->templateid = $copytotemplateid;
$page->timecreated = time();
$page->timemodified = $page->timecreated;
// Insert into the database.
$page->id = $DB->insert_record('customcert_pages', $page);
// Now go through the elements we want to load.
if ($templateelements = $DB->get_records('customcert_elements', array('pageid' => $templatepage->id))) {
foreach ($templateelements as $templateelement) {
$element = clone($templateelement);
$element->pageid = $page->id;
$element->timecreated = time();
$element->timemodified = $element->timecreated;
// Ok, now we want to insert this into the database.
$element->id = $DB->insert_record('customcert_elements', $element);
// Load any other information the element may need to for the template.
if ($e = \mod_customcert\element_factory::get_element_instance($element)) {
if (!$e->copy_element($templateelement)) {
// Failed to copy - delete the element.
$e->delete();
}
}
}
}
}
}
}
/**
* Handles moving an item on a template.
*
* @param string $itemname the item we are moving
* @param int $itemid the id of the item
* @param string $direction the direction
*/
public function move_item($itemname, $itemid, $direction) {
global $DB;
$table = 'customcert_';
if ($itemname == 'page') {
$table .= 'pages';
} else { // Must be an element.
$table .= 'elements';
}
if ($moveitem = $DB->get_record($table, array('id' => $itemid))) {
// Check which direction we are going.
if ($direction == 'up') {
$sequence = $moveitem->sequence - 1;
} else { // Must be down.
$sequence = $moveitem->sequence + 1;
}
// Get the item we will be swapping with. Make sure it is related to the same template (if it's
// a page) or the same page (if it's an element).
if ($itemname == 'page') {
$params = array('templateid' => $moveitem->templateid);
} else { // Must be an element.
$params = array('pageid' => $moveitem->pageid);
}
$swapitem = $DB->get_record($table, $params + array('sequence' => $sequence));
}
// Check that there is an item to move, and an item to swap it with.
if ($moveitem && !empty($swapitem)) {
$DB->set_field($table, 'sequence', $swapitem->sequence, array('id' => $moveitem->id));
$DB->set_field($table, 'sequence', $moveitem->sequence, array('id' => $swapitem->id));
}
}
/**
@ -219,10 +424,6 @@ class template {
return $this->name;
}
public function get_html() {
return $this->html;
}
/**
* Returns the context id.
*
@ -249,7 +450,7 @@ class template {
public function get_cm() {
$context = $this->get_context();
if ($context->contextlevel === CONTEXT_MODULE) {
return get_coursemodule_from_id('htmlcert', $context->instanceid, 0, false, MUST_EXIST);
return get_coursemodule_from_id('customcert', $context->instanceid, 0, false, MUST_EXIST);
}
return null;
@ -261,7 +462,7 @@ class template {
* @throws \required_capability_exception if the user does not have the necessary capabilities (ie. Fred)
*/
public function require_manage() {
require_capability('mod/htmlcert:manage', $this->get_context());
require_capability('mod/customcert:manage', $this->get_context());
}
/**
@ -269,7 +470,7 @@ class template {
*
* @param string $templatename the name of the template
* @param int $contextid the context id
* @return \mod_htmlcert\template the template object
* @return \mod_customcert\template the template object
*/
public static function create($templatename, $contextid) {
global $DB;
@ -279,8 +480,8 @@ class template {
$template->contextid = $contextid;
$template->timecreated = time();
$template->timemodified = $template->timecreated;
$template->id = $DB->insert_record('htmlcert_templates', $template);
$template->id = $DB->insert_record('customcert_templates', $template);
return new \mod_htmlcert\template($template);
return new \mod_customcert\template($template);
}
}

View file

@ -1,5 +1,5 @@
<?php
// This file is part of the htmlcert module for Moodle - http://moodle.org/
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@ -17,12 +17,12 @@
/**
* This file contains the class that handles uploading files.
*
* @package mod_htmlcert
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert;
namespace mod_customcert;
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
@ -31,7 +31,7 @@ require_once($CFG->libdir.'/formslib.php');
/**
* Handles uploading files.
*
* @package mod_htmlcert
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
@ -51,23 +51,23 @@ class upload_image_form extends \moodleform {
'maxbytes' => $CFG->maxbytes,
'subdirs' => 1,
'accepted_types' => 'image');
$mform->addElement('filemanager', 'htmlcertimage', get_string('uploadimage', 'htmlcert'), '',
$mform->addElement('filemanager', 'customcertimage', get_string('uploadimage', 'customcert'), '',
$this->filemanageroptions);
$this->add_action_buttons();
}
/**
* Fill in the current page data for this htmlcert.
* Fill in the current page data for this customcert.
*/
public function definition_after_data() {
$mform = $this->_form;
// Editing existing instance - copy existing files into draft area.
$draftitemid = file_get_submitted_draft_itemid('htmlcertimage');
file_prepare_draft_area($draftitemid, \context_system::instance()->id, 'mod_htmlcert', 'image', 0,
$draftitemid = file_get_submitted_draft_itemid('customcertimage');
file_prepare_draft_area($draftitemid, \context_system::instance()->id, 'mod_customcert', 'image', 0,
$this->filemanageroptions);
$element = $mform->getElement('htmlcertimage');
$element = $mform->getElement('customcertimage');
$element->setValue($draftitemid);
}
}

View file

@ -1,5 +1,5 @@
<?php
// This file is part of the htmlcert module for Moodle - http://moodle.org/
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@ -17,12 +17,12 @@
/**
* This files contains the form for verifying a certificate.
*
* @package mod_htmlcert
* @copyright 2017 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_htmlcert;
namespace mod_customcert;
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
@ -31,8 +31,8 @@ require_once($CFG->libdir . '/formslib.php');
/**
* The form for verifying a certificate.
*
* @package mod_htmlcert
* @copyright 2017 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class verify_certificate_form extends \moodleform {
@ -43,10 +43,10 @@ class verify_certificate_form extends \moodleform {
public function definition() {
$mform =& $this->_form;
$mform->addElement('text', 'code', get_string('code', 'htmlcert'));
$mform->addElement('text', 'code', get_string('code', 'customcert'));
$mform->setType('code', PARAM_ALPHANUM);
$mform->addElement('submit', 'verify', get_string('verify', 'htmlcert'));
$mform->addElement('submit', 'verify', get_string('verify', 'customcert'));
}
/**
@ -60,7 +60,7 @@ class verify_certificate_form extends \moodleform {
$errors = array();
if ($data['code'] === '') {
$errors['code'] = get_string('invalidcode', 'htmlcert');
$errors['code'] = get_string('invalidcode', 'customcert');
}
return $errors;

View file

@ -1,5 +1,10 @@
{
"name": "mdjnelson/moodle-mod_customcert",
"type": "moodle-mod",
"require": {
"mikehaertl/phpwkhtmltopdf": "^2.5"
"composer/installers": "~1.0"
},
"extra": {
"installer-name": "customcert"
}
}

160
composer.lock generated
View file

@ -1,160 +0,0 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "7f2a6587c80faa77c0f646f7f2ea6165",
"packages": [
{
"name": "mikehaertl/php-shellcommand",
"version": "1.6.4",
"source": {
"type": "git",
"url": "https://github.com/mikehaertl/php-shellcommand.git",
"reference": "3488d7803df1e8f1a343d3d0ca452d527ad8d5e5"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/mikehaertl/php-shellcommand/zipball/3488d7803df1e8f1a343d3d0ca452d527ad8d5e5",
"reference": "3488d7803df1e8f1a343d3d0ca452d527ad8d5e5",
"shasum": ""
},
"require": {
"php": ">= 5.3.0"
},
"require-dev": {
"phpunit/phpunit": ">4.0 <=9.4"
},
"type": "library",
"autoload": {
"psr-4": {
"mikehaertl\\shellcommand\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Härtl",
"email": "haertl.mike@gmail.com"
}
],
"description": "An object oriented interface to shell commands",
"keywords": [
"shell"
],
"support": {
"issues": "https://github.com/mikehaertl/php-shellcommand/issues",
"source": "https://github.com/mikehaertl/php-shellcommand/tree/1.6.4"
},
"time": "2021-03-17T06:54:33+00:00"
},
{
"name": "mikehaertl/php-tmpfile",
"version": "1.2.1",
"source": {
"type": "git",
"url": "https://github.com/mikehaertl/php-tmpfile.git",
"reference": "70a5b70b17bc0d9666388e6a551ecc93d0b40a10"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/mikehaertl/php-tmpfile/zipball/70a5b70b17bc0d9666388e6a551ecc93d0b40a10",
"reference": "70a5b70b17bc0d9666388e6a551ecc93d0b40a10",
"shasum": ""
},
"require-dev": {
"php": ">=5.3.0",
"phpunit/phpunit": ">4.0 <=9.4"
},
"type": "library",
"autoload": {
"psr-4": {
"mikehaertl\\tmp\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Härtl",
"email": "haertl.mike@gmail.com"
}
],
"description": "A convenience class for temporary files",
"keywords": [
"files"
],
"support": {
"issues": "https://github.com/mikehaertl/php-tmpfile/issues",
"source": "https://github.com/mikehaertl/php-tmpfile/tree/1.2.1"
},
"time": "2021-03-01T18:26:25+00:00"
},
{
"name": "mikehaertl/phpwkhtmltopdf",
"version": "2.5.0",
"source": {
"type": "git",
"url": "https://github.com/mikehaertl/phpwkhtmltopdf.git",
"reference": "17ee71341591415d942774eda2c98d8ba7ea9e90"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/mikehaertl/phpwkhtmltopdf/zipball/17ee71341591415d942774eda2c98d8ba7ea9e90",
"reference": "17ee71341591415d942774eda2c98d8ba7ea9e90",
"shasum": ""
},
"require": {
"mikehaertl/php-shellcommand": "^1.5.0",
"mikehaertl/php-tmpfile": "^1.2.1",
"php": ">=5.0.0"
},
"require-dev": {
"phpunit/phpunit": ">4.0 <9.4"
},
"type": "library",
"autoload": {
"psr-4": {
"mikehaertl\\wkhtmlto\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Haertl",
"email": "haertl.mike@gmail.com"
}
],
"description": "A slim PHP wrapper around wkhtmltopdf with an easy to use and clean OOP interface",
"homepage": "http://mikehaertl.github.com/phpwkhtmltopdf/",
"keywords": [
"pdf",
"wkhtmltoimage",
"wkhtmltopdf"
],
"support": {
"issues": "https://github.com/mikehaertl/phpwkhtmltopdf/issues",
"source": "https://github.com/mikehaertl/phpwkhtmltopdf/tree/2.5.0"
},
"time": "2021-03-01T19:41:06+00:00"
}
],
"packages-dev": [],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"prefer-stable": false,
"prefer-lowest": false,
"platform": [],
"platform-dev": [],
"plugin-api-version": "2.0.0"
}

View file

@ -1,5 +1,5 @@
<?php
// This file is part of the htmlcert module for Moodle - http://moodle.org/
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@ -15,10 +15,10 @@
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* htmlcert module capability definition
* Customcert module capability definition
*
* @package mod_htmlcert
* @copyright 2013 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
@ -26,7 +26,7 @@ defined('MOODLE_INTERNAL') || die();
$capabilities = array(
'mod/htmlcert:addinstance' => array(
'mod/customcert:addinstance' => array(
'riskbitmask' => RISK_XSS,
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
@ -37,7 +37,7 @@ $capabilities = array(
'clonepermissionsfrom' => 'moodle/course:manageactivities'
),
'mod/htmlcert:view' => array(
'mod/customcert:view' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
@ -49,7 +49,7 @@ $capabilities = array(
)
),
'mod/htmlcert:manage' => array(
'mod/customcert:manage' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
@ -60,7 +60,7 @@ $capabilities = array(
)
),
'mod/htmlcert:receiveissue' => array(
'mod/customcert:receiveissue' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'archetypes' => array(
@ -68,7 +68,7 @@ $capabilities = array(
)
),
'mod/htmlcert:viewreport' => array(
'mod/customcert:viewreport' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
@ -79,7 +79,7 @@ $capabilities = array(
)
),
'mod/htmlcert:viewallcertificates' => array(
'mod/customcert:viewallcertificates' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_SYSTEM,
'archetypes' => array(
@ -87,7 +87,7 @@ $capabilities = array(
)
),
'mod/htmlcert:verifycertificate' => array(
'mod/customcert:verifycertificate' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'archetypes' => array(
@ -97,7 +97,7 @@ $capabilities = array(
)
),
'mod/htmlcert:verifyallcertificates' => array(
'mod/customcert:verifyallcertificates' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_SYSTEM,
'archetypes' => array(
@ -105,7 +105,7 @@ $capabilities = array(
)
),
'mod/htmlcert:manageemailstudents' => array(
'mod/customcert:manageemailstudents' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'archetypes' => array(
@ -115,7 +115,7 @@ $capabilities = array(
'clonepermissionsfrom' => 'moodle/course:manageactivities'
),
'mod/htmlcert:manageemailteachers' => array(
'mod/customcert:manageemailteachers' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'archetypes' => array(
@ -125,7 +125,7 @@ $capabilities = array(
'clonepermissionsfrom' => 'moodle/course:manageactivities'
),
'mod/htmlcert:manageemailothers' => array(
'mod/customcert:manageemailothers' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'archetypes' => array(
@ -135,7 +135,7 @@ $capabilities = array(
'clonepermissionsfrom' => 'moodle/course:manageactivities'
),
'mod/htmlcert:manageverifyany' => array(
'mod/customcert:manageverifyany' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'archetypes' => array(
@ -145,7 +145,7 @@ $capabilities = array(
'clonepermissionsfrom' => 'moodle/course:manageactivities'
),
'mod/htmlcert:managerequiredtime' => array(
'mod/customcert:managerequiredtime' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'archetypes' => array(
@ -155,7 +155,7 @@ $capabilities = array(
'clonepermissionsfrom' => 'moodle/course:manageactivities'
),
'mod/htmlcert:manageprotection' => array(
'mod/customcert:manageprotection' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'archetypes' => array(

View file

@ -1,10 +1,10 @@
<?xml version="1.0" encoding="UTF-8" ?>
<XMLDB PATH="mod/htmlcert/db" VERSION="20170530" COMMENT="XMLDB file for Moodle mod/htmlcert"
<XMLDB PATH="mod/customcert/db" VERSION="20170530" COMMENT="XMLDB file for Moodle mod/customcert"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../../lib/xmldb/xmldb.xsd"
>
<TABLES>
<TABLE NAME="htmlcert" COMMENT="Defines htmlcerts">
<TABLE NAME="customcert" COMMENT="Defines customcerts">
<FIELDS>
<FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true"/>
<FIELD NAME="course" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
@ -14,7 +14,6 @@
<FIELD NAME="introformat" TYPE="int" LENGTH="4" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
<FIELD NAME="requiredtime" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
<FIELD NAME="verifyany" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
<FIELD NAME="deliveryoption" TYPE="char" LENGTH="255" NOTNULL="false" SEQUENCE="false"/>
<FIELD NAME="emailstudents" TYPE="int" LENGTH="1" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
<FIELD NAME="emailteachers" TYPE="int" LENGTH="1" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
<FIELD NAME="emailothers" TYPE="text" NOTNULL="false" SEQUENCE="false"/>
@ -23,36 +22,75 @@
<FIELD NAME="timemodified" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
</FIELDS>
<KEYS>
<KEY NAME="primary" TYPE="primary" FIELDS="id" COMMENT="Primary key for htmlcert"/>
<KEY NAME="template" TYPE="foreign" FIELDS="templateid" REFTABLE="htmlcert_templates" REFFIELDS="id"/>
<KEY NAME="primary" TYPE="primary" FIELDS="id" COMMENT="Primary key for customcert"/>
<KEY NAME="template" TYPE="foreign" FIELDS="templateid" REFTABLE="customcert_templates" REFFIELDS="id"/>
</KEYS>
</TABLE>
<TABLE NAME="htmlcert_templates" COMMENT="Stores each htmlcert template">
<TABLE NAME="customcert_templates" COMMENT="Stores each customcert template">
<FIELDS>
<FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true"/>
<FIELD NAME="name" TYPE="char" LENGTH="255" NOTNULL="false" SEQUENCE="false"/>
<FIELD NAME="html" TYPE="text" NOTNULL="false"/>
<FIELD NAME="contextid" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false" COMMENT="References contextid."/>
<FIELD NAME="timecreated" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
<FIELD NAME="timemodified" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
</FIELDS>
<KEYS>
<KEY NAME="primary" TYPE="primary" FIELDS="id" COMMENT="Primary key for htmlcert_template"/>
<KEY NAME="primary" TYPE="primary" FIELDS="id" COMMENT="Primary key for customcert_template"/>
<KEY NAME="contextid" TYPE="foreign" FIELDS="contextid" REFTABLE="context" REFFIELDS="id"/>
</KEYS>
</TABLE>
<TABLE NAME="htmlcert_issues" COMMENT="Stores each issue of a htmlcert">
<TABLE NAME="customcert_issues" COMMENT="Stores each issue of a customcert">
<FIELDS>
<FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true"/>
<FIELD NAME="userid" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
<FIELD NAME="htmlcertid" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
<FIELD NAME="customcertid" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
<FIELD NAME="code" TYPE="char" LENGTH="40" NOTNULL="false" SEQUENCE="false"/>
<FIELD NAME="emailed" TYPE="int" LENGTH="1" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
<FIELD NAME="timecreated" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
</FIELDS>
<KEYS>
<KEY NAME="primary" TYPE="primary" FIELDS="id" COMMENT="Primary key for htmlcert_issues"/>
<KEY NAME="htmlcert" TYPE="foreign" FIELDS="htmlcertid" REFTABLE="htmlcert" REFFIELDS="id"/>
<KEY NAME="primary" TYPE="primary" FIELDS="id" COMMENT="Primary key for customcert_issues"/>
<KEY NAME="customcert" TYPE="foreign" FIELDS="customcertid" REFTABLE="customcert" REFFIELDS="id"/>
</KEYS>
</TABLE>
<TABLE NAME="customcert_pages" COMMENT="Stores each page of a custom cert">
<FIELDS>
<FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true"/>
<FIELD NAME="templateid" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
<FIELD NAME="width" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
<FIELD NAME="height" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
<FIELD NAME="leftmargin" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
<FIELD NAME="rightmargin" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
<FIELD NAME="sequence" TYPE="int" LENGTH="10" NOTNULL="false" SEQUENCE="false"/>
<FIELD NAME="timecreated" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
<FIELD NAME="timemodified" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
</FIELDS>
<KEYS>
<KEY NAME="primary" TYPE="primary" FIELDS="id" COMMENT="Primary key for customcert_pages"/>
<KEY NAME="template" TYPE="foreign" FIELDS="templateid" REFTABLE="customcert_templates" REFFIELDS="id"/>
</KEYS>
</TABLE>
<TABLE NAME="customcert_elements" COMMENT="Stores the elements for a given page">
<FIELDS>
<FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true"/>
<FIELD NAME="pageid" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
<FIELD NAME="name" TYPE="char" LENGTH="255" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="element" TYPE="char" LENGTH="255" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="data" TYPE="text" LENGTH="big" NOTNULL="false" SEQUENCE="false"/>
<FIELD NAME="font" TYPE="char" LENGTH="255" NOTNULL="false" SEQUENCE="false"/>
<FIELD NAME="fontsize" TYPE="int" LENGTH="10" NOTNULL="false" SEQUENCE="false"/>
<FIELD NAME="colour" TYPE="char" LENGTH="50" NOTNULL="false" SEQUENCE="false"/>
<FIELD NAME="posx" TYPE="int" LENGTH="10" NOTNULL="false" SEQUENCE="false"/>
<FIELD NAME="posy" TYPE="int" LENGTH="10" NOTNULL="false" SEQUENCE="false"/>
<FIELD NAME="width" TYPE="int" LENGTH="10" NOTNULL="false" SEQUENCE="false"/>
<FIELD NAME="refpoint" TYPE="int" LENGTH="4" NOTNULL="false" SEQUENCE="false"/>
<FIELD NAME="sequence" TYPE="int" LENGTH="10" NOTNULL="false" SEQUENCE="false"/>
<FIELD NAME="timecreated" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
<FIELD NAME="timemodified" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false"/>
</FIELDS>
<KEYS>
<KEY NAME="primary" TYPE="primary" FIELDS="id" COMMENT="Primary key for customcert_elements"/>
<KEY NAME="page" TYPE="foreign" FIELDS="pageid" REFTABLE="customcert_pages" REFFIELDS="id"/>
</KEYS>
</TABLE>
</TABLES>

View file

@ -1,5 +1,5 @@
<?php
// This file is part of the htmlcert module for Moodle - http://moodle.org/
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@ -17,16 +17,16 @@
/**
* Definition of log events
*
* @package mod_htmlcert
* @copyright 2013 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$logs = array(
array('module' => 'htmlcert', 'action' => 'view', 'mtable' => 'htmlcert', 'field' => 'name'),
array('module' => 'htmlcert', 'action' => 'add', 'mtable' => 'htmlcert', 'field' => 'name'),
array('module' => 'htmlcert', 'action' => 'update', 'mtable' => 'htmlcert', 'field' => 'name'),
array('module' => 'htmlcert', 'action' => 'received', 'mtable' => 'htmlcert', 'field' => 'name'),
array('module' => 'customcert', 'action' => 'view', 'mtable' => 'customcert', 'field' => 'name'),
array('module' => 'customcert', 'action' => 'add', 'mtable' => 'customcert', 'field' => 'name'),
array('module' => 'customcert', 'action' => 'update', 'mtable' => 'customcert', 'field' => 'name'),
array('module' => 'customcert', 'action' => 'received', 'mtable' => 'customcert', 'field' => 'name'),
);

View file

@ -17,38 +17,38 @@
/**
* Defines mobile handlers.
*
* @package mod_htmlcert
* @copyright 2018 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$addons = [
'mod_htmlcert' => [ // Plugin identifier.
'mod_customcert' => [ // Plugin identifier.
'handlers' => [ // Different places where the plugin will display content.
'issueview' => [ // Handler unique name.
'displaydata' => [
'icon' => $CFG->wwwroot . '/mod/htmlcert/pix/icon.png',
'class' => 'core-course-module-htmlcert-handler',
'icon' => $CFG->wwwroot . '/mod/customcert/pix/icon.png',
'class' => 'core-course-module-customcert-handler',
],
'delegate' => 'CoreCourseModuleDelegate', // Delegate (where to display the link to the plugin).
'method' => 'mobile_view_activity', // Main function in \mod_htmlcert\output\mobile.
'method' => 'mobile_view_activity', // Main function in \mod_customcert\output\mobile.
'styles' => [
'url' => '/mod/htmlcert/mobile/styles.css',
'url' => '/mod/customcert/mobile/styles.css',
'version' => 1
]
]
],
'lang' => [ // Language strings that are used in all the handlers.
['deleteissueconfirm', 'htmlcert'],
['gethtmlcert', 'htmlcert'],
['listofissues', 'htmlcert'],
['deleteissueconfirm', 'customcert'],
['getcustomcert', 'customcert'],
['listofissues', 'customcert'],
['nothingtodisplay', 'moodle'],
['notissued', 'htmlcert'],
['pluginname', 'htmlcert'],
['receiveddate', 'htmlcert'],
['requiredtimenotmet', 'htmlcert'],
['notissued', 'customcert'],
['pluginname', 'customcert'],
['receiveddate', 'customcert'],
['requiredtimenotmet', 'customcert'],
['selectagroup', 'moodle']
]
]

View file

@ -15,18 +15,18 @@
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Web service for mod htmlcert.
* Web service for mod customcert.
*
* @package mod_htmlcert
* @copyright 2016 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$functions = array(
'mod_htmlcert_delete_issue' => array(
'classname' => 'mod_htmlcert\external',
'mod_customcert_delete_issue' => array(
'classname' => 'mod_customcert\external',
'methodname' => 'delete_issue',
'classpath' => '',
'description' => 'Delete an issue for a certificate',
@ -34,16 +34,16 @@ $functions = array(
'ajax' => true,
'services' => array(MOODLE_OFFICIAL_MOBILE_SERVICE)
),
'mod_htmlcert_save_element' => array(
'classname' => 'mod_htmlcert\external',
'mod_customcert_save_element' => array(
'classname' => 'mod_customcert\external',
'methodname' => 'save_element',
'classpath' => '',
'description' => 'Saves data for an element',
'type' => 'write',
'ajax' => true
),
'mod_htmlcert_get_element_html' => array(
'classname' => 'mod_htmlcert\external',
'mod_customcert_get_element_html' => array(
'classname' => 'mod_customcert\external',
'methodname' => 'get_element_html',
'classpath' => '',
'description' => 'Returns the HTML to display for an element',

27
db/subplugins.php Normal file
View file

@ -0,0 +1,27 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Definition of sub-plugins.
*
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$subplugins = array('customcertelement' => 'mod/customcert/element');

View file

@ -15,11 +15,11 @@
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Definition of htmlcert scheduled tasks.
* Definition of customcert scheduled tasks.
*
* @package mod_htmlcert
* @package mod_customcert
* @category task
* @copyright 2017 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
@ -27,7 +27,7 @@ defined('MOODLE_INTERNAL') || die();
$tasks = array(
array(
'classname' => 'mod_htmlcert\task\email_certificate_task',
'classname' => 'mod_customcert\task\email_certificate_task',
'blocking' => 0,
'minute' => '*',
'hour' => '*',

170
db/upgrade.php Normal file
View file

@ -0,0 +1,170 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Customcert module upgrade code.
*
* @package mod_customcert
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
/**
* Customcert module upgrade code.
*
* @param int $oldversion the version we are upgrading from
* @return bool always true
*/
function xmldb_customcert_upgrade($oldversion) {
global $DB;
$dbman = $DB->get_manager();
if ($oldversion < 2016120503) {
$table = new xmldb_table('customcert_templates');
$field = new xmldb_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'id');
$dbman->change_field_precision($table, $field);
// Savepoint reached.
upgrade_mod_savepoint(true, 2016120503, 'customcert');
}
if ($oldversion < 2016120505) {
$table = new xmldb_table('customcert');
$field = new xmldb_field('emailstudents', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'requiredtime');
// Conditionally launch add field.
if (!$dbman->field_exists($table, $field)) {
$dbman->add_field($table, $field);
}
$field = new xmldb_field('emailteachers', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'emailstudents');
// Conditionally launch add field.
if (!$dbman->field_exists($table, $field)) {
$dbman->add_field($table, $field);
}
$field = new xmldb_field('emailothers', XMLDB_TYPE_TEXT, null, null, null, null, null, 'emailteachers');
// Conditionally launch add field.
if (!$dbman->field_exists($table, $field)) {
$dbman->add_field($table, $field);
}
$table = new xmldb_table('customcert_issues');
$field = new xmldb_field('emailed', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'code');
// Conditionally launch add field.
if (!$dbman->field_exists($table, $field)) {
$dbman->add_field($table, $field);
}
// Savepoint reached.
upgrade_mod_savepoint(true, 2016120505, 'customcert');
}
if ($oldversion < 2017050501) {
// Remove any duplicate rows from customcert issue table.
// This SQL fetches the id of those records which have duplicate customcert issues.
// This doesn't return the first issue.
$fromclause = "FROM (
SELECT min(id) AS minid, userid, customcertid
FROM {customcert_issues}
GROUP BY userid, customcertid
) minid
JOIN {customcert_issues} ci
ON ci.userid = minid.userid
AND ci.customcertid = minid.customcertid
AND ci.id > minid.minid";
// Get the records themselves.
$getduplicatessql = "SELECT ci.id $fromclause ORDER BY minid";
if ($records = $DB->get_records_sql($getduplicatessql)) {
// Delete them.
$ids = implode(',', array_keys($records));
$DB->delete_records_select('customcert_issues', "id IN ($ids)");
}
// Savepoint reached.
upgrade_mod_savepoint(true, 2017050501, 'customcert');
}
if ($oldversion < 2017050502) {
// Add column for new 'verifycertificateanyone' setting.
$table = new xmldb_table('customcert');
$field = new xmldb_field('verifyany', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0',
'requiredtime');
// Conditionally launch add field.
if (!$dbman->field_exists($table, $field)) {
$dbman->add_field($table, $field);
}
// Savepoint reached.
upgrade_mod_savepoint(true, 2017050502, 'customcert');
}
if ($oldversion < 2017050506) {
$table = new xmldb_table('customcert_elements');
$field = new xmldb_field('size');
// Rename column as it is a reserved word in Oracle.
if ($dbman->field_exists($table, $field)) {
$field->set_attributes(XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'font');
$dbman->rename_field($table, $field, 'fontsize');
}
// Savepoint reached.
upgrade_mod_savepoint(true, 2017050506, 'customcert');
}
if ($oldversion < 2018051705) {
$table = new xmldb_table('customcert_elements');
$field = new xmldb_field('element', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'name');
// Alter the 'element' column to be characters, rather than text.
$dbman->change_field_type($table, $field);
// Savepoint reached.
upgrade_mod_savepoint(true, 2018051705, 'customcert');
}
if ($oldversion < 2018120305) {
$table = new xmldb_table('customcert');
$index = new xmldb_index('templateid', XMLDB_INDEX_UNIQUE, ['templateid']);
if ($dbman->index_exists($table, $index)) {
$dbman->drop_index($table, $index);
}
$key = new xmldb_key('templateid', XMLDB_KEY_FOREIGN, ['templateid'], 'customcert_templates', ['id']);
$dbman->add_key($table, $key);
$table = new xmldb_table('customcert_pages');
$index = new xmldb_index('templateid', XMLDB_INDEX_UNIQUE, ['templateid']);
if ($dbman->index_exists($table, $index)) {
$dbman->drop_index($table, $index);
}
$key = new xmldb_key('templateid', XMLDB_KEY_FOREIGN, ['templateid'], 'customcert_templates', ['id']);
$dbman->add_key($table, $key);
upgrade_mod_savepoint(true, 2018120305, 'customcert');
}
return true;
}

183
edit.php
View file

@ -1,5 +1,5 @@
<?php
// This file is part of the htmlcert module for Moodle - http://moodle.org/
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@ -15,10 +15,10 @@
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Edit the htmlcert settings.
* Edit the customcert settings.
*
* @package mod_htmlcert
* @copyright 2013 Mark Nelson <markn@moodle.com>, 2021 Klaus-Uwe Mitterer <kumitterer@kumi.systems>
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
@ -34,26 +34,26 @@ $confirm = optional_param('confirm', 0, PARAM_INT);
// Edit an existing template.
if ($tid) {
// Create the template object.
$template = $DB->get_record('htmlcert_templates', array('id' => $tid), '*', MUST_EXIST);
$template = new \mod_htmlcert\template($template);
$template = $DB->get_record('customcert_templates', array('id' => $tid), '*', MUST_EXIST);
$template = new \mod_customcert\template($template);
// Set the context.
$contextid = $template->get_contextid();
// Set the page url.
$pageurl = new moodle_url('/mod/htmlcert/edit.php', array('tid' => $tid));
$pageurl = new moodle_url('/mod/customcert/edit.php', array('tid' => $tid));
} else { // Adding a new template.
// Need to supply the contextid.
$contextid = required_param('contextid', PARAM_INT);
// Set the page url.
$pageurl = new moodle_url('/mod/htmlcert/edit.php', array('contextid' => $contextid));
$pageurl = new moodle_url('/mod/customcert/edit.php', array('contextid' => $contextid));
}
$context = context::instance_by_id($contextid);
if ($context->contextlevel == CONTEXT_MODULE) {
$cm = get_coursemodule_from_id('htmlcert', $context->instanceid, 0, false, MUST_EXIST);
$cm = get_coursemodule_from_id('customcert', $context->instanceid, 0, false, MUST_EXIST);
require_login($cm->course, false, $cm);
$htmlcert = $DB->get_record('htmlcert', ['id' => $cm->instance], '*', MUST_EXIST);
$title = $htmlcert->name;
$customcert = $DB->get_record('customcert', ['id' => $cm->instance], '*', MUST_EXIST);
$title = $customcert->name;
$heading = format_string($title);
} else {
require_login();
@ -61,40 +61,173 @@ if ($context->contextlevel == CONTEXT_MODULE) {
$heading = $title;
}
require_capability('mod/htmlcert:manage', $context);
require_capability('mod/customcert:manage', $context);
// Set up the page.
\mod_htmlcert\page_helper::page_setup($pageurl, $context, $title);
\mod_customcert\page_helper::page_setup($pageurl, $context, $title);
if ($context->contextlevel == CONTEXT_SYSTEM) {
// We are managing a template - add some navigation.
$PAGE->navbar->add(get_string('managetemplates', 'htmlcert'),
new moodle_url('/mod/htmlcert/manage_templates.php'));
$PAGE->navbar->add(get_string('managetemplates', 'customcert'),
new moodle_url('/mod/customcert/manage_templates.php'));
if (!$tid) {
$PAGE->navbar->add(get_string('edithtmlcert', 'htmlcert'));
$PAGE->navbar->add(get_string('editcustomcert', 'customcert'));
} else {
$PAGE->navbar->add(get_string('edithtmlcert', 'htmlcert'),
new moodle_url('/mod/htmlcert/edit.php', ['tid' => $tid]));
$PAGE->navbar->add(get_string('editcustomcert', 'customcert'),
new moodle_url('/mod/customcert/edit.php', ['tid' => $tid]));
}
}
// Flag to determine if we are deleting anything.
$deleting = false;
if ($tid) {
$mform = new \mod_htmlcert\edit_form($pageurl, array('tid' => $tid));
if ($action && confirm_sesskey()) {
switch ($action) {
case 'pmoveup' :
$template->move_item('page', $actionid, 'up');
break;
case 'pmovedown' :
$template->move_item('page', $actionid, 'down');
break;
case 'emoveup' :
$template->move_item('element', $actionid, 'up');
break;
case 'emovedown' :
$template->move_item('element', $actionid, 'down');
break;
case 'addpage' :
$template->add_page();
$url = new \moodle_url('/mod/customcert/edit.php', array('tid' => $tid));
redirect($url);
break;
case 'deletepage' :
if (!empty($confirm)) { // Check they have confirmed the deletion.
$template->delete_page($actionid);
$url = new \moodle_url('/mod/customcert/edit.php', array('tid' => $tid));
redirect($url);
} else {
// Set deletion flag to true.
$deleting = true;
// Create the message.
$message = get_string('deletepageconfirm', 'customcert');
// Create the link options.
$nourl = new moodle_url('/mod/customcert/edit.php', array('tid' => $tid));
$yesurl = new moodle_url('/mod/customcert/edit.php',
array(
'tid' => $tid,
'action' => 'deletepage',
'aid' => $actionid,
'confirm' => 1,
'sesskey' => sesskey()
)
);
}
break;
case 'deleteelement' :
if (!empty($confirm)) { // Check they have confirmed the deletion.
$template->delete_element($actionid);
} else {
// Set deletion flag to true.
$deleting = true;
// Create the message.
$message = get_string('deleteelementconfirm', 'customcert');
// Create the link options.
$nourl = new moodle_url('/mod/customcert/edit.php', array('tid' => $tid));
$yesurl = new moodle_url('/mod/customcert/edit.php',
array(
'tid' => $tid,
'action' => 'deleteelement',
'aid' => $actionid,
'confirm' => 1,
'sesskey' => sesskey()
)
);
}
break;
}
}
}
// Check if we are deleting either a page or an element.
if ($deleting) {
// Show a confirmation page.
$PAGE->navbar->add(get_string('deleteconfirm', 'customcert'));
echo $OUTPUT->header();
echo $OUTPUT->heading($heading);
echo $OUTPUT->confirm($message, $yesurl, $nourl);
echo $OUTPUT->footer();
exit();
}
if ($tid) {
$mform = new \mod_customcert\edit_form($pageurl, array('tid' => $tid));
// Set the name for the form.
$mform->set_data(array('name' => $template->get_name(), 'html' => ''));
$mform->set_data(array('name' => $template->get_name()));
} else {
$mform = new \mod_htmlcert\edit_form($pageurl);
$mform = new \mod_customcert\edit_form($pageurl);
}
if ($data = $mform->get_data()) {
// If there is no id, then we are creating a template.
if (!$tid) {
$template = \mod_htmlcert\template::create($data->name, $contextid);
$template = \mod_customcert\template::create($data->name, $contextid);
// Create a page for this template.
$pageid = $template->add_page();
// Associate all the data from the form to the newly created page.
$width = 'pagewidth_' . $pageid;
$height = 'pageheight_' . $pageid;
$leftmargin = 'pageleftmargin_' . $pageid;
$rightmargin = 'pagerightmargin_' . $pageid;
$rightmargin = 'pagerightmargin_' . $pageid;
$data->$width = $data->pagewidth_0;
$data->$height = $data->pageheight_0;
$data->$leftmargin = $data->pageleftmargin_0;
$data->$rightmargin = $data->pagerightmargin_0;
// We may also have clicked to add an element, so these need changing as well.
if (isset($data->element_0) && isset($data->addelement_0)) {
$element = 'element_' . $pageid;
$addelement = 'addelement_' . $pageid;
$data->$element = $data->element_0;
$data->$addelement = $data->addelement_0;
// Need to remove the temporary element and add element placeholders so we
// don't try add an element to the wrong page.
unset($data->element_0);
unset($data->addelement_0);
}
}
// Save any data for the template.
$template->save($data);
// Save any page data.
$template->save_page($data);
// Loop through the data.
foreach ($data as $key => $value) {
// Check if they chose to add an element to a page.
if (strpos($key, 'addelement_') !== false) {
// Get the page id.
$pageid = str_replace('addelement_', '', $key);
// Get the element.
$element = "element_" . $pageid;
$element = $data->$element;
// Create the URL to redirect to to add this element.
$params = array();
$params['tid'] = $template->get_id();
$params['action'] = 'add';
$params['element'] = $element;
$params['pageid'] = $pageid;
$url = new moodle_url('/mod/customcert/edit_element.php', $params);
redirect($url);
}
}
// Check if we want to preview this custom certificate.
if (!empty($data->previewbtn)) {
$template->generate_pdf(true);
@ -102,7 +235,7 @@ if ($data = $mform->get_data()) {
}
// Redirect to the editing page to show form with recent updates.
$url = new moodle_url('/mod/htmlcert/edit.php', array('tid' => $template->get_id()));
$url = new moodle_url('/mod/customcert/edit.php', array('tid' => $template->get_id()));
redirect($url);
}
@ -110,8 +243,8 @@ echo $OUTPUT->header();
echo $OUTPUT->heading($heading);
$mform->display();
if ($tid && $context->contextlevel == CONTEXT_MODULE) {
$loadtemplateurl = new moodle_url('/mod/htmlcert/load_template.php', array('tid' => $tid));
$loadtemplateform = new \mod_htmlcert\load_template_form($loadtemplateurl, array('context' => $context), 'post',
$loadtemplateurl = new moodle_url('/mod/customcert/load_template.php', array('tid' => $tid));
$loadtemplateform = new \mod_customcert\load_template_form($loadtemplateurl, array('context' => $context), 'post',
'', array('id' => 'loadtemplateform'));
$loadtemplateform->display();
}

108
edit_element.php Normal file
View file

@ -0,0 +1,108 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Edit a customcert element.
*
* @package mod_customcert
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once('../../config.php');
$tid = required_param('tid', PARAM_INT);
$action = required_param('action', PARAM_ALPHA);
$template = $DB->get_record('customcert_templates', array('id' => $tid), '*', MUST_EXIST);
// Set the template object.
$template = new \mod_customcert\template($template);
// Perform checks.
if ($cm = $template->get_cm()) {
require_login($cm->course, false, $cm);
} else {
require_login();
}
// Make sure the user has the required capabilities.
$template->require_manage();
if ($template->get_context()->contextlevel == CONTEXT_MODULE) {
$customcert = $DB->get_record('customcert', ['id' => $cm->instance], '*', MUST_EXIST);
$title = $customcert->name;
$heading = format_string($title);
} else {
$title = $SITE->fullname;
$heading = $title;
}
if ($action == 'edit') {
// The id of the element must be supplied if we are currently editing one.
$id = required_param('id', PARAM_INT);
$element = $DB->get_record('customcert_elements', array('id' => $id), '*', MUST_EXIST);
$pageurl = new moodle_url('/mod/customcert/edit_element.php', array('id' => $id, 'tid' => $tid, 'action' => $action));
} else { // Must be adding an element.
// We need to supply what element we want added to what page.
$pageid = required_param('pageid', PARAM_INT);
$element = new stdClass();
$element->element = required_param('element', PARAM_ALPHA);
$pageurl = new moodle_url('/mod/customcert/edit_element.php', array('tid' => $tid, 'element' => $element->element,
'pageid' => $pageid, 'action' => $action));
}
// Set up the page.
\mod_customcert\page_helper::page_setup($pageurl, $template->get_context(), $title);
// Additional page setup.
if ($template->get_context()->contextlevel == CONTEXT_SYSTEM) {
$PAGE->navbar->add(get_string('managetemplates', 'customcert'),
new moodle_url('/mod/customcert/manage_templates.php'));
}
$PAGE->navbar->add(get_string('editcustomcert', 'customcert'), new moodle_url('/mod/customcert/edit.php',
array('tid' => $tid)));
$PAGE->navbar->add(get_string('editelement', 'customcert'));
$mform = new \mod_customcert\edit_element_form($pageurl, array('element' => $element));
// Check if they cancelled.
if ($mform->is_cancelled()) {
$url = new moodle_url('/mod/customcert/edit.php', array('tid' => $tid));
redirect($url);
}
if ($data = $mform->get_data()) {
// Set the id, or page id depending on if we are editing an element, or adding a new one.
if ($action == 'edit') {
$data->id = $id;
} else {
$data->pageid = $pageid;
}
// Set the element variable.
$data->element = $element->element;
// Get an instance of the element class.
if ($e = \mod_customcert\element_factory::get_element_instance($data)) {
$e->save_form_elements($data);
}
$url = new moodle_url('/mod/customcert/edit.php', array('tid' => $tid));
redirect($url);
}
echo $OUTPUT->header();
echo $OUTPUT->heading($heading);
$mform->display();
echo $OUTPUT->footer();

View file

@ -0,0 +1,130 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the customcert element background image's core interaction API.
*
* @package customcertelement_bgimage
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customcertelement_bgimage;
defined('MOODLE_INTERNAL') || die();
/**
* The customcert element background image's core interaction API.
*
* @package customcertelement_bgimage
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class element extends \customcertelement_image\element {
/**
* This function renders the form elements when adding a customcert element.
*
* @param \MoodleQuickForm $mform the edit_form instance
*/
public function render_form_elements($mform) {
$mform->addElement('select', 'fileid', get_string('image', 'customcertelement_image'), self::get_images());
$mform->addElement('filemanager', 'customcertimage', get_string('uploadimage', 'customcert'), '',
$this->filemanageroptions);
}
/**
* Performs validation on the element values.
*
* @param array $data the submitted data
* @param array $files the submitted files
* @return array the validation errors
*/
public function validate_form_elements($data, $files) {
// Array to return the errors.
return array();
}
/**
* Handles rendering the element on the pdf.
*
* @param \pdf $pdf the pdf object
* @param bool $preview true if it is a preview, false otherwise
* @param \stdClass $user the user we are rendering this for
*/
public function render($pdf, $preview, $user) {
// If there is no element data, we have nothing to display.
if (empty($this->get_data())) {
return;
}
$imageinfo = json_decode($this->get_data());
// If there is no file, we have nothing to display.
if (empty($imageinfo->filename)) {
return;
}
if ($file = $this->get_file()) {
$location = make_request_directory() . '/target';
$file->copy_content_to($location);
// Set the image to the size of the PDF page.
$mimetype = $file->get_mimetype();
if ($mimetype == 'image/svg+xml') {
$pdf->ImageSVG($location, 0, 0, $pdf->getPageWidth(), $pdf->getPageHeight());
} else {
$pdf->Image($location, 0, 0, $pdf->getPageWidth(), $pdf->getPageHeight());
}
}
}
/**
* Render the element in html.
*
* This function is used to render the element when we are using the
* drag and drop interface to position it.
*
* @return string the html
*/
public function render_html() {
global $DB;
// If there is no element data, we have nothing to display.
if (empty($this->get_data())) {
return '';
}
$imageinfo = json_decode($this->get_data());
// If there is no file, we have nothing to display.
if (empty($imageinfo->filename)) {
return '';
}
if ($file = $this->get_file()) {
$url = \moodle_url::make_pluginfile_url($file->get_contextid(), 'mod_customcert', 'image', $file->get_itemid(),
$file->get_filepath(), $file->get_filename());
// Get the page we are rendering this on.
$page = $DB->get_record('customcert_pages', array('id' => $this->get_pageid()), '*', MUST_EXIST);
// Set the image to the size of the page.
$style = 'width: ' . $page->width . 'mm; height: ' . $page->height . 'mm';
return \html_writer::tag('img', '', array('src' => $url, 'style' => $style));
}
}
}

View file

@ -0,0 +1,46 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Privacy Subsystem implementation for customcertelement_bgimage.
*
* @package customcertelement_bgimage
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customcertelement_bgimage\privacy;
defined('MOODLE_INTERNAL') || die();
/**
* Privacy Subsystem for customcertelement_bgimage implementing null_provider.
*
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements \core_privacy\local\metadata\null_provider {
/**
* Get the language string identifier with the component's language
* file to explain why this plugin stores no data.
*
* @return string
*/
public static function get_reason() : string {
return 'privacy:metadata';
}
}

View file

@ -0,0 +1,66 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Customcert background image element upgrade code.
*
* @package customcertelement_bgimage
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
/**
* Customcert background image element upgrade code.
*
* @param int $oldversion the version we are upgrading from
* @return bool always true
*/
function xmldb_customcertelement_bgimage_upgrade($oldversion) {
global $DB;
if ($oldversion < 2016120501) {
// Go through each 'image' element and update the file stored information.
if ($images = $DB->get_records_select('customcert_elements', $DB->sql_compare_text('element') . ' = \'bgimage\'')) {
// Create a file storage instance we are going to use to create pathname hashes.
$fs = get_file_storage();
// Go through and update the details.
foreach ($images as $image) {
// Get the current data we have stored for this element.
$elementinfo = json_decode($image->data);
if ($file = $fs->get_file_by_hash($elementinfo->pathnamehash)) {
$arrtostore = array(
'contextid' => $file->get_contextid(),
'filearea' => $file->get_filearea(),
'itemid' => $file->get_itemid(),
'filepath' => $file->get_filepath(),
'filename' => $file->get_filename(),
'width' => (int) $elementinfo->width,
'height' => (int) $elementinfo->height
);
$arrtostore = json_encode($arrtostore);
$DB->set_field('customcert_elements', 'data', $arrtostore, array('id' => $image->id));
}
}
}
// Savepoint reached.
upgrade_plugin_savepoint(true, 2016120501, 'customcertelement', 'bgimage');
}
return true;
}

View file

@ -0,0 +1,26 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'customcertelement_bgimage', language 'en'.
*
* @package customcertelement_bgimage
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['pluginname'] = 'Background image';
$string['privacy:metadata'] = 'The Background image plugin does not store any personal data.';

View file

@ -0,0 +1,29 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the version information for the background image plugin.
*
* @package customcertelement_bgimage
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
$plugin->version = 2018120300; // The current module version (Date: YYYYMMDDXX).
$plugin->requires = 2018120300; // Requires this Moodle version (3.6).
$plugin->component = 'customcertelement_bgimage';

View file

@ -0,0 +1,126 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the customcert element border's core interaction API.
*
* @package customcertelement_border
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customcertelement_border;
defined('MOODLE_INTERNAL') || die();
/**
* The customcert element border's core interaction API.
*
* @package customcertelement_border
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class element extends \mod_customcert\element {
/**
* This function renders the form elements when adding a customcert element.
*
* @param \MoodleQuickForm $mform the edit_form instance
*/
public function render_form_elements($mform) {
// We want to define the width of the border.
$mform->addElement('text', 'width', get_string('width', 'customcertelement_border'), array('size' => 10));
$mform->setType('width', PARAM_INT);
$mform->addHelpButton('width', 'width', 'customcertelement_border');
// The only other thing to define is the colour we want the border to be.
\mod_customcert\element_helper::render_form_element_colour($mform);
}
/**
* Handles rendering the element on the pdf.
*
* @param \pdf $pdf the pdf object
* @param bool $preview true if it is a preview, false otherwise
* @param \stdClass $user the user we are rendering this for
*/
public function render($pdf, $preview, $user) {
$colour = \TCPDF_COLORS::convertHTMLColorToDec($this->get_colour(), $colour);
$pdf->SetLineStyle(array('width' => $this->get_data(), 'color' => $colour));
$pdf->Line(0, 0, $pdf->getPageWidth(), 0);
$pdf->Line($pdf->getPageWidth(), 0, $pdf->getPageWidth(), $pdf->getPageHeight());
$pdf->Line(0, $pdf->getPageHeight(), $pdf->getPageWidth(), $pdf->getPageHeight());
$pdf->Line(0, 0, 0, $pdf->getPageHeight());
}
/**
* Render the element in html.
*
* This function is used to render the element when we are using the
* drag and drop interface to position it.
*
* @return string the html
*/
public function render_html() {
return '';
}
/**
* Performs validation on the element values.
*
* @param array $data the submitted data
* @param array $files the submitted files
* @return array the validation errors
*/
public function validate_form_elements($data, $files) {
// Array to return the errors.
$errors = array();
// Check if width is not set, or not numeric or less than 0.
if ((!isset($data['width'])) || (!is_numeric($data['width'])) || ($data['width'] <= 0)) {
$errors['width'] = get_string('invalidwidth', 'customcertelement_border');
}
// Validate the colour.
$errors += \mod_customcert\element_helper::validate_form_element_colour($data);
return $errors;
}
/**
* Sets the data on the form when editing an element.
*
* @param \MoodleQuickForm $mform the edit_form instance
*/
public function definition_after_data($mform) {
if (!empty($this->get_data())) {
$element = $mform->getElement('width');
$element->setValue($this->get_data());
}
parent::definition_after_data($mform);
}
/**
* This will handle how form data will be saved into the data column in the
* customcert_elements table.
*
* @param \stdClass $data the form data
* @return string the json encoded array
*/
public function save_unique_data($data) {
return $data->width;
}
}

View file

@ -0,0 +1,46 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Privacy Subsystem implementation for customcertelement_border.
*
* @package customcertelement_border
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customcertelement_border\privacy;
defined('MOODLE_INTERNAL') || die();
/**
* Privacy Subsystem for customcertelement_border implementing null_provider.
*
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements \core_privacy\local\metadata\null_provider {
/**
* Get the language string identifier with the component's language
* file to explain why this plugin stores no data.
*
* @return string
*/
public static function get_reason() : string {
return 'privacy:metadata';
}
}

View file

@ -0,0 +1,29 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'customcertelement_border', language 'en'.
*
* @package customcertelement_border
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['pluginname'] = 'Border';
$string['privacy:metadata'] = 'The Border plugin does not store any personal data.';
$string['invalidwidth'] = 'The width has to be a valid number greater than 0.';
$string['width'] = 'Width';
$string['width_help'] = 'Width of the border in mm.';

View file

@ -0,0 +1,29 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the version information for the border plugin.
*
* @package customcertelement_border
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
$plugin->version = 2018120300; // The current module version (Date: YYYYMMDDXX).
$plugin->requires = 2018120300; // Requires this Moodle version (3.6).
$plugin->component = 'customcertelement_border';

View file

@ -0,0 +1,82 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the customcert element categoryname's core interaction API.
*
* @package customcertelement_categoryname
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customcertelement_categoryname;
defined('MOODLE_INTERNAL') || die();
/**
* The customcert element categoryname's core interaction API.
*
* @package customcertelement_categoryname
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class element extends \mod_customcert\element {
/**
* Handles rendering the element on the pdf.
*
* @param \pdf $pdf the pdf object
* @param bool $preview true if it is a preview, false otherwise
* @param \stdClass $user the user we are rendering this for
*/
public function render($pdf, $preview, $user) {
\mod_customcert\element_helper::render_content($pdf, $this, $this->get_category_name());
}
/**
* Render the element in html.
*
* This function is used to render the element when we are using the
* drag and drop interface to position it.
*
* @return string the html
*/
public function render_html() {
return \mod_customcert\element_helper::render_html_content($this, $this->get_category_name());
}
/**
* Helper function that returns the category name.
*
* @return string
*/
protected function get_category_name() : string {
global $DB, $SITE;
$courseid = \mod_customcert\element_helper::get_courseid($this->get_id());
$course = get_course($courseid);
$context = \mod_customcert\element_helper::get_context($this->get_id());
// Check that there is a course category available.
if (!empty($course->category)) {
$categoryname = $DB->get_field('course_categories', 'name', array('id' => $course->category), MUST_EXIST);
} else { // Must be in a site template.
$categoryname = $SITE->fullname;
}
return format_string($categoryname, true, ['context' => $context]);
}
}

View file

@ -0,0 +1,46 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Privacy Subsystem implementation for customcertelement_categoryname.
*
* @package customcertelement_categoryname
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customcertelement_categoryname\privacy;
defined('MOODLE_INTERNAL') || die();
/**
* Privacy Subsystem for customcertelement_categoryname implementing null_provider.
*
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements \core_privacy\local\metadata\null_provider {
/**
* Get the language string identifier with the component's language
* file to explain why this plugin stores no data.
*
* @return string
*/
public static function get_reason() : string {
return 'privacy:metadata';
}
}

View file

@ -0,0 +1,26 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'customcertelement_categoryname', language 'en'.
*
* @package customcertelement_categoryname
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['pluginname'] = 'Category name';
$string['privacy:metadata'] = 'The Category name plugin does not store any personal data.';

View file

@ -0,0 +1,29 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the version information for the categoryname plugin.
*
* @package customcertelement_categoryname
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
$plugin->version = 2018120300; // The current module version (Date: YYYYMMDDXX).
$plugin->requires = 2018120300; // Requires this Moodle version (3.6).
$plugin->component = 'customcertelement_categoryname';

View file

@ -0,0 +1,77 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the customcert element code's core interaction API.
*
* @package customcertelement_code
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customcertelement_code;
defined('MOODLE_INTERNAL') || die();
/**
* The customcert element code's core interaction API.
*
* @package customcertelement_code
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class element extends \mod_customcert\element {
/**
* Handles rendering the element on the pdf.
*
* @param \pdf $pdf the pdf object
* @param bool $preview true if it is a preview, false otherwise
* @param \stdClass $user the user we are rendering this for
*/
public function render($pdf, $preview, $user) {
global $DB;
if ($preview) {
$code = \mod_customcert\certificate::generate_code();
} else {
// Get the page.
$page = $DB->get_record('customcert_pages', array('id' => $this->get_pageid()), '*', MUST_EXIST);
// Get the customcert this page belongs to.
$customcert = $DB->get_record('customcert', array('templateid' => $page->templateid), '*', MUST_EXIST);
// Now we can get the issue for this user.
$issue = $DB->get_record('customcert_issues', array('userid' => $user->id, 'customcertid' => $customcert->id),
'*', IGNORE_MULTIPLE);
$code = $issue->code;
}
\mod_customcert\element_helper::render_content($pdf, $this, $code);
}
/**
* Render the element in html.
*
* This function is used to render the element when we are using the
* drag and drop interface to position it.
*
* @return string the html
*/
public function render_html() {
$code = \mod_customcert\certificate::generate_code();
return \mod_customcert\element_helper::render_html_content($this, $code);
}
}

View file

@ -0,0 +1,46 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Privacy Subsystem implementation for customcertelement_code.
*
* @package customcertelement_code
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customcertelement_code\privacy;
defined('MOODLE_INTERNAL') || die();
/**
* Privacy Subsystem for customcertelement_code implementing null_provider.
*
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements \core_privacy\local\metadata\null_provider {
/**
* Get the language string identifier with the component's language
* file to explain why this plugin stores no data.
*
* @return string
*/
public static function get_reason() : string {
return 'privacy:metadata';
}
}

View file

@ -0,0 +1,26 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'customcertelement_code', language 'en'.
*
* @package customcertelement_code
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['pluginname'] = 'Code';
$string['privacy:metadata'] = 'The Code plugin does not store any personal data.';

29
element/code/version.php Normal file
View file

@ -0,0 +1,29 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the version information for the code plugin.
*
* @package customcertelement_code
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
$plugin->version = 2018120300; // The current module version (Date: YYYYMMDDXX).
$plugin->requires = 2018120300; // Requires this Moodle version (3.6).
$plugin->component = 'customcertelement_code';

View file

@ -0,0 +1,73 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the customcert element coursename's core interaction API.
*
* @package customcertelement_coursename
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customcertelement_coursename;
defined('MOODLE_INTERNAL') || die();
/**
* The customcert element coursename's core interaction API.
*
* @package customcertelement_coursename
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class element extends \mod_customcert\element {
/**
* Handles rendering the element on the pdf.
*
* @param \pdf $pdf the pdf object
* @param bool $preview true if it is a preview, false otherwise
* @param \stdClass $user the user we are rendering this for
*/
public function render($pdf, $preview, $user) {
\mod_customcert\element_helper::render_content($pdf, $this, $this->get_course_name());
}
/**
* Render the element in html.
*
* This function is used to render the element when we are using the
* drag and drop interface to position it.
*
* @return string the html
*/
public function render_html() {
return \mod_customcert\element_helper::render_html_content($this, $this->get_course_name());
}
/**
* Helper function that returns the category name.
*
* @return string
*/
protected function get_course_name() : string {
$courseid = \mod_customcert\element_helper::get_courseid($this->get_id());
$course = get_course($courseid);
$context = \mod_customcert\element_helper::get_context($this->get_id());
return format_string($course->fullname, true, ['context' => $context]);
}
}

View file

@ -0,0 +1,46 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Privacy Subsystem implementation for customcertelement_coursename.
*
* @package customcertelement_coursename
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customcertelement_coursename\privacy;
defined('MOODLE_INTERNAL') || die();
/**
* Privacy Subsystem for customcertelement_coursename implementing null_provider.
*
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements \core_privacy\local\metadata\null_provider {
/**
* Get the language string identifier with the component's language
* file to explain why this plugin stores no data.
*
* @return string
*/
public static function get_reason() : string {
return 'privacy:metadata';
}
}

View file

@ -0,0 +1,26 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'customcertelement_coursename', language 'en'.
*
* @package customcertelement_coursename
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['pluginname'] = 'Course name';
$string['privacy:metadata'] = 'The Course name plugin does not store any personal data.';

View file

@ -0,0 +1,29 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the version information for the coursename plugin.
*
* @package customcertelement_coursename
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
$plugin->version = 2018120300; // The current module version (Date: YYYYMMDDXX).
$plugin->requires = 2018120300; // Requires this Moodle version (3.6).
$plugin->component = 'customcertelement_coursename';

View file

@ -0,0 +1,409 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the customcert element date's core interaction API.
*
* @package customcertelement_date
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customcertelement_date;
defined('MOODLE_INTERNAL') || die();
/**
* Date - Course grade date
*/
define('CUSTOMCERT_DATE_COURSE_GRADE', '0');
/**
* Date - Issue
*/
define('CUSTOMCERT_DATE_ISSUE', '-1');
/**
* Date - Completion
*/
define('CUSTOMCERT_DATE_COMPLETION', '-2');
/**
* Date - Course start
*/
define('CUSTOMCERT_DATE_COURSE_START', '-3');
/**
* Date - Course end
*/
define('CUSTOMCERT_DATE_COURSE_END', '-4');
/**
* Date - Current date
*/
define('CUSTOMCERT_DATE_CURRENT_DATE', '-5');
/**
* Date - Enrollment start
*/
define('CUSTOMCERT_DATE_ENROLMENT_START', '-6');
/**
* Date - Entrollment end
*/
define('CUSTOMCERT_DATE_ENROLMENT_END', '-7');
require_once($CFG->dirroot . '/lib/grade/constants.php');
/**
* The customcert element date's core interaction API.
*
* @package customcertelement_date
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class element extends \mod_customcert\element {
/**
* This function renders the form elements when adding a customcert element.
*
* @param \MoodleQuickForm $mform the edit_form instance
*/
public function render_form_elements($mform) {
global $CFG, $COURSE;
// Get the possible date options.
$dateoptions = array();
$dateoptions[CUSTOMCERT_DATE_ISSUE] = get_string('issueddate', 'customcertelement_date');
$dateoptions[CUSTOMCERT_DATE_CURRENT_DATE] = get_string('currentdate', 'customcertelement_date');
$completionenabled = $CFG->enablecompletion && ($COURSE->id == SITEID || $COURSE->enablecompletion);
if ($completionenabled) {
$dateoptions[CUSTOMCERT_DATE_COMPLETION] = get_string('completiondate', 'customcertelement_date');
}
$dateoptions[CUSTOMCERT_DATE_ENROLMENT_START] = get_string('enrolmentstartdate', 'customcertelement_date');
$dateoptions[CUSTOMCERT_DATE_ENROLMENT_END] = get_string('enrolmentenddate', 'customcertelement_date');
$dateoptions[CUSTOMCERT_DATE_COURSE_START] = get_string('coursestartdate', 'customcertelement_date');
$dateoptions[CUSTOMCERT_DATE_COURSE_END] = get_string('courseenddate', 'customcertelement_date');
$dateoptions[CUSTOMCERT_DATE_COURSE_GRADE] = get_string('coursegradedate', 'customcertelement_date');
$dateoptions = $dateoptions + \mod_customcert\element_helper::get_grade_items($COURSE);
$mform->addElement('select', 'dateitem', get_string('dateitem', 'customcertelement_date'), $dateoptions);
$mform->addHelpButton('dateitem', 'dateitem', 'customcertelement_date');
$mform->addElement('select', 'dateformat', get_string('dateformat', 'customcertelement_date'), self::get_date_formats());
$mform->addHelpButton('dateformat', 'dateformat', 'customcertelement_date');
parent::render_form_elements($mform);
}
/**
* This will handle how form data will be saved into the data column in the
* customcert_elements table.
*
* @param \stdClass $data the form data
* @return string the json encoded array
*/
public function save_unique_data($data) {
// Array of data we will be storing in the database.
$arrtostore = array(
'dateitem' => $data->dateitem,
'dateformat' => $data->dateformat
);
// Encode these variables before saving into the DB.
return json_encode($arrtostore);
}
/**
* Handles rendering the element on the pdf.
*
* @param \pdf $pdf the pdf object
* @param bool $preview true if it is a preview, false otherwise
* @param \stdClass $user the user we are rendering this for
*/
public function render($pdf, $preview, $user) {
global $DB;
// If there is no element data, we have nothing to display.
if (empty($this->get_data())) {
return;
}
$courseid = \mod_customcert\element_helper::get_courseid($this->id);
// Decode the information stored in the database.
$dateinfo = json_decode($this->get_data());
$dateitem = $dateinfo->dateitem;
$dateformat = $dateinfo->dateformat;
// If we are previewing this certificate then just show a demonstration date.
if ($preview) {
$date = time();
} else {
// Get the page.
$page = $DB->get_record('customcert_pages', array('id' => $this->get_pageid()), '*', MUST_EXIST);
// Get the customcert this page belongs to.
$customcert = $DB->get_record('customcert', array('templateid' => $page->templateid), '*', MUST_EXIST);
// Now we can get the issue for this user.
$issue = $DB->get_record('customcert_issues', array('userid' => $user->id, 'customcertid' => $customcert->id),
'*', IGNORE_MULTIPLE);
if ($dateitem == CUSTOMCERT_DATE_ISSUE) {
$date = $issue->timecreated;
} else if ($dateitem == CUSTOMCERT_DATE_CURRENT_DATE) {
$date = time();
} else if ($dateitem == CUSTOMCERT_DATE_COMPLETION) {
// Get the last completion date.
$sql = "SELECT MAX(c.timecompleted) as timecompleted
FROM {course_completions} c
WHERE c.userid = :userid
AND c.course = :courseid";
if ($timecompleted = $DB->get_record_sql($sql, array('userid' => $issue->userid, 'courseid' => $courseid))) {
if (!empty($timecompleted->timecompleted)) {
$date = $timecompleted->timecompleted;
}
}
} else if ($dateitem == CUSTOMCERT_DATE_ENROLMENT_START) {
// Get the enrolment start date.
$sql = "SELECT ue.timestart FROM {enrol} e JOIN {user_enrolments} ue ON ue.enrolid = e.id
WHERE e.courseid = :courseid
AND ue.userid = :userid";
if ($timestart = $DB->get_record_sql($sql, array('userid' => $issue->userid, 'courseid' => $courseid))) {
if (!empty($timestart->timestart)) {
$date = $timestart->timestart;
}
}
} else if ($dateitem == CUSTOMCERT_DATE_ENROLMENT_END) {
// Get the enrolment end date.
$sql = "SELECT ue.timeend FROM {enrol} e JOIN {user_enrolments} ue ON ue.enrolid = e.id
WHERE e.courseid = :courseid
AND ue.userid = :userid";
if ($timeend = $DB->get_record_sql($sql, array('userid' => $issue->userid, 'courseid' => $courseid))) {
if (!empty($timeend->timeend)) {
$date = $timeend->timeend;
}
}
} else if ($dateitem == CUSTOMCERT_DATE_COURSE_START) {
$date = $DB->get_field('course', 'startdate', array('id' => $courseid));
} else if ($dateitem == CUSTOMCERT_DATE_COURSE_END) {
$date = $DB->get_field('course', 'enddate', array('id' => $courseid));
} else {
if ($dateitem == CUSTOMCERT_DATE_COURSE_GRADE) {
$grade = \mod_customcert\element_helper::get_course_grade_info(
$courseid,
GRADE_DISPLAY_TYPE_DEFAULT,
$user->id
);
} else if (strpos($dateitem, 'gradeitem:') === 0) {
$gradeitemid = substr($dateitem, 10);
$grade = \mod_customcert\element_helper::get_grade_item_info(
$gradeitemid,
$dateitem,
$user->id
);
} else {
$grade = \mod_customcert\element_helper::get_mod_grade_info(
$dateitem,
GRADE_DISPLAY_TYPE_DEFAULT,
$user->id
);
}
if ($grade && !empty($grade->get_dategraded())) {
$date = $grade->get_dategraded();
}
}
}
// Ensure that a date has been set.
if (!empty($date)) {
\mod_customcert\element_helper::render_content($pdf, $this, $this->get_date_format_string($date, $dateformat));
}
}
/**
* Render the element in html.
*
* This function is used to render the element when we are using the
* drag and drop interface to position it.
*
* @return string the html
*/
public function render_html() {
// If there is no element data, we have nothing to display.
if (empty($this->get_data())) {
return;
}
// Decode the information stored in the database.
$dateinfo = json_decode($this->get_data());
$dateformat = $dateinfo->dateformat;
return \mod_customcert\element_helper::render_html_content($this, $this->get_date_format_string(time(), $dateformat));
}
/**
* Sets the data on the form when editing an element.
*
* @param \MoodleQuickForm $mform the edit_form instance
*/
public function definition_after_data($mform) {
// Set the item and format for this element.
if (!empty($this->get_data())) {
$dateinfo = json_decode($this->get_data());
$element = $mform->getElement('dateitem');
$element->setValue($dateinfo->dateitem);
$element = $mform->getElement('dateformat');
$element->setValue($dateinfo->dateformat);
}
parent::definition_after_data($mform);
}
/**
* This function is responsible for handling the restoration process of the element.
*
* We will want to update the course module the date element is pointing to as it will
* have changed in the course restore.
*
* @param \restore_customcert_activity_task $restore
*/
public function after_restore($restore) {
global $DB;
$dateinfo = json_decode($this->get_data());
if ($newitem = \restore_dbops::get_backup_ids_record($restore->get_restoreid(), 'course_module', $dateinfo->dateitem)) {
$dateinfo->dateitem = $newitem->newitemid;
$DB->set_field('customcert_elements', 'data', $this->save_unique_data($dateinfo), array('id' => $this->get_id()));
}
}
/**
* Helper function to return all the date formats.
*
* @return array the list of date formats
*/
public static function get_date_formats() {
// Hard-code date so users can see the difference between short dates with and without the leading zero.
// Eg. 06/07/18 vs 6/07/18.
$date = 1530849658;
$suffix = self::get_ordinal_number_suffix(userdate($date, '%d'));
$dateformats = [
1 => userdate($date, '%B %d, %Y'),
2 => userdate($date, '%B %d' . $suffix . ', %Y')
];
$strdateformats = [
'strftimedate',
'strftimedatefullshort',
'strftimedatefullshortwleadingzero',
'strftimedateshort',
'strftimedatetime',
'strftimedatetimeshort',
'strftimedatetimeshortwleadingzero',
'strftimedaydate',
'strftimedaydatetime',
'strftimedayshort',
'strftimedaytime',
'strftimemonthyear',
'strftimerecent',
'strftimerecentfull',
'strftimetime'
];
foreach ($strdateformats as $strdateformat) {
if ($strdateformat == 'strftimedatefullshortwleadingzero') {
$dateformats[$strdateformat] = userdate($date, get_string('strftimedatefullshort', 'langconfig'), 99, false);
} else if ($strdateformat == 'strftimedatetimeshortwleadingzero') {
$dateformats[$strdateformat] = userdate($date, get_string('strftimedatetimeshort', 'langconfig'), 99, false);
} else {
$dateformats[$strdateformat] = userdate($date, get_string($strdateformat, 'langconfig'));
}
}
return $dateformats;
}
/**
* Returns the date in a readable format.
*
* @param int $date
* @param string $dateformat
* @return string
*/
protected function get_date_format_string($date, $dateformat) {
// Keeping for backwards compatibility.
if (is_number($dateformat)) {
switch ($dateformat) {
case 1:
$certificatedate = userdate($date, '%B %d, %Y');
break;
case 2:
$suffix = self::get_ordinal_number_suffix(userdate($date, '%d'));
$certificatedate = userdate($date, '%B %d' . $suffix . ', %Y');
break;
case 3:
$certificatedate = userdate($date, '%d %B %Y');
break;
case 4:
$certificatedate = userdate($date, '%B %Y');
break;
default:
$certificatedate = userdate($date, get_string('strftimedate', 'langconfig'));
}
}
// Ok, so we must have been passed the actual format in the lang file.
if (!isset($certificatedate)) {
if ($dateformat == 'strftimedatefullshortwleadingzero') {
$certificatedate = userdate($date, get_string('strftimedatefullshort', 'langconfig'), 99, false);
} else if ($dateformat == 'strftimedatetimeshortwleadingzero') {
$certificatedate = userdate($date, get_string('strftimedatetimeshort', 'langconfig'), 99, false);
} else {
$certificatedate = userdate($date, get_string($dateformat, 'langconfig'));
}
}
return $certificatedate;
}
/**
* Helper function to return the suffix of the day of
* the month, eg 'st' if it is the 1st of the month.
*
* @param int $day the day of the month
* @return string the suffix.
*/
protected static function get_ordinal_number_suffix($day) {
if (!in_array(($day % 100), array(11, 12, 13))) {
switch ($day % 10) {
// Handle 1st, 2nd, 3rd.
case 1:
return get_string('numbersuffix_st_as_in_first', 'customcertelement_date');
case 2:
return get_string('numbersuffix_nd_as_in_second', 'customcertelement_date');
case 3:
return get_string('numbersuffix_rd_as_in_third', 'customcertelement_date');
}
}
return 'th';
}
}

View file

@ -0,0 +1,46 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Privacy Subsystem implementation for customcertelement_date.
*
* @package customcertelement_date
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customcertelement_date\privacy;
defined('MOODLE_INTERNAL') || die();
/**
* Privacy Subsystem for customcertelement_date implementing null_provider.
*
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements \core_privacy\local\metadata\null_provider {
/**
* Get the language string identifier with the component's language
* file to explain why this plugin stores no data.
*
* @return string
*/
public static function get_reason() : string {
return 'privacy:metadata';
}
}

View file

@ -0,0 +1,42 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'customcertelement_date', language 'en'.
*
* @package customcertelement_date
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['completiondate'] = 'Completion date';
$string['courseenddate'] = 'Course end date';
$string['coursegradedate'] = 'Course grade date';
$string['coursestartdate'] = 'Course start date';
$string['enrolmentenddate'] = 'Enrolment end date';
$string['enrolmentstartdate'] = 'Enrolment start date';
$string['currentdate'] = 'Current date';
$string['dateformat'] = 'Date format';
$string['dateformat_help'] = 'This is the format of the date that will be displayed';
$string['dateitem'] = 'Date item';
$string['dateitem_help'] = 'This will be the date that is printed on the certificate';
$string['issueddate'] = 'Issued date';
$string['pluginname'] = 'Date';
$string['privacy:metadata'] = 'The Date plugin does not store any personal data.';
$string['numbersuffix_nd_as_in_second'] = 'nd';
$string['numbersuffix_rd_as_in_third'] = 'rd';
$string['numbersuffix_st_as_in_first'] = 'st';
$string['userdateformat'] = 'User date format';

29
element/date/version.php Normal file
View file

@ -0,0 +1,29 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the version information for the date plugin.
*
* @package customcertelement_date
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
$plugin->version = 2018120301; // The current module version (Date: YYYYMMDDXX).
$plugin->requires = 2018120300; // Requires this Moodle version (3.6).
$plugin->component = 'customcertelement_date';

View file

@ -0,0 +1,731 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the customcert date range element.
*
* @package customcertelement_daterange
* @copyright 2018 Dmitrii Metelkin <dmitriim@catalyst-au.net>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customcertelement_daterange;
use \mod_customcert\element_helper;
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
require_once($CFG->dirroot . '/lib/grade/constants.php');
/**
* The customcert date range element.
*
* @package customcertelement_daterange
* @copyright 2018 Dmitrii Metelkin <dmitriim@catalyst-au.net>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class element extends \mod_customcert\element {
/**
* Max recurring period in seconds.
*/
const MAX_RECURRING_PERIOD = 31556926; // 12 months.
/**
* Current year placeholder string.
*/
const CURRENT_YEAR_PLACEHOLDER = '{{current_year}}';
/**
* First year in a date range placeholder string.
*/
const RANGE_FIRST_YEAR_PLACEHOLDER = '{{range_first_year}}';
/**
* Last year in a date range placeholder string.
*/
const RANGE_LAST_YEAR_PLACEHOLDER = '{{range_last_year}}';
/**
* First year in a date range placeholder string.
*/
const RECUR_RANGE_FIRST_YEAR_PLACEHOLDER = '{{recurring_range_first_year}}';
/**
* Last year in a date range placeholder string.
*/
const RECUR_RANGE_LAST_YEAR_PLACEHOLDER = '{{recurring_range_last_year}}';
/**
* A year in the user's date.
*/
const DATE_YEAR_PLACEHOLDER = '{{date_year}}';
/**
* Date - Issue
*/
const DATE_ISSUE = -1;
/**
* Date - Completion
*/
const DATE_COMPLETION = -2;
/**
* Date - Course start
*/
const DATE_COURSE_START = -3;
/**
* Date - Course end
*/
const DATE_COURSE_END = -4;
/**
* Date - Course grade date
*/
const DATE_COURSE_GRADE = -5;
/**
* Date - Course current date
*/
const DATE_CURRENT_DATE = -6;
/**
* This function renders the form elements when adding a customcert element.
*
* @param \MoodleQuickForm $mform the edit form instance
*/
public function render_form_elements($mform) {
global $COURSE;
// Get the possible date options.
$dateoptions = array();
$dateoptions[self::DATE_ISSUE] = get_string('issueddate', 'customcertelement_daterange');
$dateoptions[self::DATE_CURRENT_DATE] = get_string('currentdate', 'customcertelement_daterange');
$dateoptions[self::DATE_COMPLETION] = get_string('completiondate', 'customcertelement_daterange');
$dateoptions[self::DATE_COURSE_START] = get_string('coursestartdate', 'customcertelement_daterange');
$dateoptions[self::DATE_COURSE_END] = get_string('courseenddate', 'customcertelement_daterange');
$dateoptions[self::DATE_COURSE_GRADE] = get_string('coursegradedate', 'customcertelement_daterange');
$dateoptions = $dateoptions + element_helper::get_grade_items($COURSE);
$mform->addElement('select', 'dateitem', get_string('dateitem', 'customcertelement_daterange'), $dateoptions);
$mform->addHelpButton('dateitem', 'dateitem', 'customcertelement_daterange');
parent::render_form_elements($mform);
$mform->addElement('header', 'dateranges', get_string('dateranges', 'customcertelement_daterange'));
$mform->addElement('static', 'help', '', get_string('help', 'customcertelement_daterange'));
$mform->addElement('static', 'placeholders', '', get_string('placeholders', 'customcertelement_daterange'));
$mform->addElement('text', 'fallbackstring', get_string('fallbackstring', 'customcertelement_daterange'));
$mform->addHelpButton('fallbackstring', 'fallbackstring', 'customcertelement_daterange');
$mform->setType('fallbackstring', PARAM_NOTAGS);
if (empty($this->get_decoded_data()->dateranges)) {
$repeats = 1;
} else {
$repeats = count($this->get_decoded_data()->dateranges);
}
$ranges = [];
$ranges[] = $mform->createElement('html', '<hr>');
$ranges[] = $mform->createElement(
'date_selector',
'startdate',
get_string('start', 'customcertelement_daterange')
);
$ranges[] = $mform->createElement(
'date_selector',
'enddate',
get_string('end', 'customcertelement_daterange')
);
$ranges[] = $mform->createElement(
'checkbox',
'recurring',
get_string('recurring', 'customcertelement_daterange')
);
$ranges[] = $mform->createElement(
'text',
'datestring',
get_string('datestring', 'customcertelement_daterange'),
['class' => 'datestring']
);
$ranges[] = $mform->createElement(
'advcheckbox',
'rangedelete',
get_string('setdeleted', 'customcertelement_daterange'),
'',
[],
[0, 1]
);
$rangeoptions = array();
$rangeoptions['startdate']['type'] = PARAM_INT;
$rangeoptions['enddate']['type'] = PARAM_INT;
$rangeoptions['recurring']['type'] = PARAM_INT;
$rangeoptions['recurring']['helpbutton'] = ['recurring', 'customcertelement_daterange'];
$rangeoptions['datestring']['type'] = PARAM_NOTAGS;
$rangeoptions['rangedelete']['type'] = PARAM_BOOL;
$addstring = get_string('addrange', 'customcertelement_daterange');
$this->get_edit_element_form()->repeat_elements($ranges, $repeats, $rangeoptions, 'repeats', 'add', 1, $addstring, true);
}
/**
* A helper function to build consistent form element name.
*
* @param string $name
* @param string $num
*
* @return string
*/
protected function build_element_name($name, $num) {
return $name . '[' . $num . ']';
}
/**
* Get decoded data stored in DB.
*
* @return \stdClass
*/
protected function get_decoded_data() {
return json_decode($this->get_data());
}
/**
* Sets the data on the form when editing an element.
*
* @param \MoodleQuickForm $mform the edit form instance
*/
public function definition_after_data($mform) {
if (!empty($this->get_data()) && !$mform->isSubmitted()) {
$element = $mform->getElement('dateitem');
$element->setValue($this->get_decoded_data()->dateitem);
$element = $mform->getElement('fallbackstring');
$element->setValue($this->get_decoded_data()->fallbackstring);
foreach ($this->get_decoded_data()->dateranges as $key => $range) {
$mform->setDefault($this->build_element_name('startdate', $key), $range->startdate);
$mform->setDefault($this->build_element_name('enddate', $key), $range->enddate);
$mform->setDefault($this->build_element_name('datestring', $key), $range->datestring);
$mform->setDefault($this->build_element_name('recurring', $key), $range->recurring);
}
}
parent::definition_after_data($mform);
}
/**
* Performs validation on the element values.
*
* @param array $data the submitted data
* @param array $files the submitted files
* @return array the validation errors
*/
public function validate_form_elements($data, $files) {
$errors = parent::validate_form_elements($data, $files);
// Check if at least one range is set.
$error = get_string('error:atleastone', 'customcertelement_daterange');
for ($i = 0; $i < $data['repeats']; $i++) {
if (empty($data['rangedelete'][$i])) {
$error = '';
}
}
if (!empty($error)) {
$errors['help'] = $error;
}
// Check that datestring is set dataranges what aren't need to be deleted.
for ($i = 0; $i < $data['repeats']; $i++) {
// Skip elements that needs to be deleted.
if (!empty($data['rangedelete'][$i])) {
continue;
}
if (empty($data['datestring'][$i])) {
$name = $this->build_element_name('datestring', $i);
$errors[$name] = get_string('error:datestring', 'customcertelement_daterange');
}
// Check that end date is correctly set.
if ( $data['startdate'][$i] >= $data['enddate'][$i] ) {
$errors[$this->build_element_name('enddate', $i)] = get_string('error:enddate', 'customcertelement_daterange');
}
$rangeperiod = $data['enddate'][$i] - $data['startdate'][$i];
// Check that recurring dateranges are not longer than 12 months.
if (!empty($data['recurring'][$i]) && $rangeperiod >= self::MAX_RECURRING_PERIOD ) {
$errors[$this->build_element_name('enddate', $i)] = get_string('error:recurring', 'customcertelement_daterange');
}
}
return $errors;
}
/**
* This will handle how form data will be saved into the data column in the
* customcert_elements table.
*
* @param \stdClass $data the form data
* @return string the json encoded array
*/
public function save_unique_data($data) {
$arrtostore = array(
'dateitem' => $data->dateitem,
'fallbackstring' => $data->fallbackstring,
'dateranges' => [],
);
for ($i = 0; $i < $data->repeats; $i++) {
if (empty($data->rangedelete[$i])) {
$arrtostore['dateranges'][] = [
'startdate' => $data->startdate[$i],
'enddate' => $data->enddate[$i],
'datestring' => $data->datestring[$i],
'recurring' => !empty($data->recurring[$i]),
];
}
}
// Encode these variables before saving into the DB.
return json_encode($arrtostore);
}
/**
* Handles rendering the element on the pdf.
*
* @param \pdf $pdf the pdf object
* @param bool $preview true if it is a preview, false otherwise
* @param \stdClass $user the user we are rendering this for
*/
public function render($pdf, $preview, $user) {
global $DB;
// If there is no element data, we have nothing to display.
if (empty($this->get_data())) {
return;
}
$courseid = element_helper::get_courseid($this->id);
$dateitem = $this->get_decoded_data()->dateitem;
// If we are previewing this certificate then just show a demonstration date.
if ($preview) {
$date = time();
} else {
// Get the page.
$page = $DB->get_record('customcert_pages', array('id' => $this->get_pageid()), '*', MUST_EXIST);
// Get the customcert this page belongs to.
$customcert = $DB->get_record('customcert', array('templateid' => $page->templateid), '*', MUST_EXIST);
// Now we can get the issue for this user.
$issue = $DB->get_record('customcert_issues', array('userid' => $user->id, 'customcertid' => $customcert->id),
'*', MUST_EXIST);
switch ($dateitem) {
case self::DATE_ISSUE:
$date = $issue->timecreated;
break;
case self::DATE_CURRENT_DATE:
$date = time();
break;
case self::DATE_COMPLETION:
// Get the last completion date.
$sql = "SELECT MAX(c.timecompleted) as timecompleted
FROM {course_completions} c
WHERE c.userid = :userid
AND c.course = :courseid";
if ($timecompleted = $DB->get_record_sql($sql, array('userid' => $issue->userid, 'courseid' => $courseid))) {
if (!empty($timecompleted->timecompleted)) {
$date = $timecompleted->timecompleted;
}
}
break;
case self::DATE_COURSE_START:
$date = $DB->get_field('course', 'startdate', array('id' => $courseid));
break;
case self::DATE_COURSE_END:
$date = $DB->get_field('course', 'enddate', array('id' => $courseid));
break;
case self::DATE_COURSE_GRADE:
$grade = element_helper::get_course_grade_info(
$courseid,
GRADE_DISPLAY_TYPE_DEFAULT, $user->id
);
if ($grade && !empty($grade->get_dategraded())) {
$date = $grade->get_dategraded();
}
break;
default:
if (strpos($dateitem, 'gradeitem:') === 0) {
$gradeitemid = substr($dateitem, 10);
$grade = element_helper::get_grade_item_info(
$gradeitemid,
$dateitem,
$user->id
);
} else {
$grade = element_helper::get_mod_grade_info(
$dateitem,
GRADE_DISPLAY_TYPE_DEFAULT,
$user->id
);
}
if ($grade && !empty($grade->get_dategraded())) {
$date = $grade->get_dategraded();
}
break;
}
}
// Ensure that a date has been set.
if (!empty($date)) {
element_helper::render_content($pdf, $this, $this->get_daterange_string($date));
}
}
/**
* Get daterange string.
*
* @param int $date Unix stamp date.
*
* @return string
*/
protected function get_daterange_string($date) {
$matchedrange = null;
$outputstring = '';
$formatdata = [];
$formatdata['date'] = $date;
foreach ($this->get_decoded_data()->dateranges as $key => $range) {
if ($this->is_recurring_range($range)) {
if ($matchedrange = $this->get_matched_recurring_range($date, $range)) {
$outputstring = $matchedrange->datestring;
$formatdata['range'] = $range;
$formatdata['recurringrange'] = $matchedrange;
break;
}
} else {
if ($this->is_date_in_range($date, $range)) {
$outputstring = $range->datestring;
$formatdata['range'] = $range;
break;
}
}
}
if (empty($outputstring) && !empty($this->get_decoded_data()->fallbackstring)) {
$outputstring = $this->get_decoded_data()->fallbackstring;
}
return $this->format_date_string($outputstring, $formatdata);
}
/**
* Returns whether or not a range is recurring.
*
* @param \stdClass $range Range object.
*
* @return bool
*/
protected function is_recurring_range(\stdClass $range) {
return !empty($range->recurring);
}
/**
* Check if the provided date is in the date range.
*
* @param int $date Unix timestamp date to check.
* @param \stdClass $range Range object.
*
* @return bool
*/
protected function is_date_in_range($date, \stdClass $range) {
return ($date >= $range->startdate && $date <= $range->enddate);
}
/**
* Check if provided date is in the recurring date range.
*
* @param int $date Unix timestamp date to check.
* @param \stdClass $range Range object.
*
* @return bool
*/
protected function is_date_in_recurring_range($date, \stdClass $range) {
$intdate = $this->build_number_from_date($date);
$intstart = $this->build_number_from_date($range->startdate);
$intend = $this->build_number_from_date($range->enddate);
if (!$this->has_turn_of_the_year($range)) {
if ($intdate >= $intstart && $intdate <= $intend) {
return true;
}
} else {
if ($intdate >= $intstart && $intdate >= $intend) {
return true;
}
if ($intdate <= $intstart && $intdate <= $intend) {
return true;
}
}
return false;
}
/**
* Check if provided recurring range has a turn of the year.
*
* @param \stdClass $reccurringrange Range object.
*
* @return bool
*/
protected function has_turn_of_the_year(\stdClass $reccurringrange) {
return date('Y', $reccurringrange->startdate) != date('Y', $reccurringrange->enddate);
}
/**
* Check if provided date is in the start year of the recurring range with a turn of the year.
*
* @param int $date Unix timestamp date to check.
* @param \stdClass $range Range object.
*
* @return bool
*/
protected function in_start_year($date, \stdClass $range) {
$intdate = $this->build_number_from_date($date);
$intstart = $this->build_number_from_date($range->startdate);
$intend = $this->build_number_from_date($range->enddate);
return $intdate >= $intstart && $intdate >= $intend;
}
/**
* Check if provided date is in the end year of the recurring range with a turn of the year.
*
* @param int $date Unix timestamp date to check.
* @param \stdClass $range Range object.
*
* @return bool
*/
protected function in_end_year($date, \stdClass $range) {
$intdate = $this->build_number_from_date($date);
$intstart = $this->build_number_from_date($range->startdate);
$intend = $this->build_number_from_date($range->enddate);
return $intdate <= $intstart && $intdate <= $intend;
}
/**
* Return matched recurring date range.
*
* As recurring date ranges do not depend on the year,
* we will use a date's year to build a new matched recurring date range with
* start year and end year. This is required to replace placeholders like range_first_year and range_last_year.
*
* @param int $date Unix timestamp date to check.
* @param \stdClass $range Range object.
*
* @return \stdClass || null
*/
protected function get_matched_recurring_range($date, \stdClass $range) {
if (!$this->is_date_in_recurring_range($date, $range)) {
return null;
}
$matchedrage = clone $range;
if ($this->has_turn_of_the_year($matchedrage)) {
if ($this->in_start_year($date, $matchedrage)) {
$startyear = date('Y', $date);
$endyear = $startyear + 1;
$matchedrage->startdate = strtotime(date('d.m.', $matchedrage->startdate) . $startyear);
$matchedrage->enddate = strtotime(date('d.m.', $matchedrage->enddate) . $endyear);
return $matchedrage;
}
if ($this->in_end_year($date, $matchedrage)) {
$endyear = date('Y', $date);
$startyear = $endyear - 1;
$matchedrage->startdate = strtotime(date('d.m.', $matchedrage->startdate) . $startyear);
$matchedrage->enddate = strtotime(date('d.m.', $matchedrage->enddate) . $endyear);
return $matchedrage;
}
} else {
$matchedrage->startdate = strtotime(date('d.m.', $matchedrage->startdate) . date('Y', $date));
$matchedrage->enddate = strtotime(date('d.m.', $matchedrage->enddate) . date('Y', $date));
return $matchedrage;
}
return null;
}
/**
* Build number representation of the provided date.
*
* @param int $date Unix timestamp date to check.
*
* @return int
*/
protected function build_number_from_date($date) {
return (int)date('md', $date);
}
/**
* Format date string based on different types of placeholders.
*
* @param string $datestring The date string
* @param array $formatdata A list of format data.
*
* @return string
*/
protected function format_date_string($datestring, array $formatdata) {
foreach ($this->get_placeholders() as $search => $replace) {
$datestring = str_replace($search, $replace, $datestring);
}
if (!empty($formatdata['date'])) {
foreach ($this->get_date_placeholders($formatdata['date']) as $search => $replace) {
$datestring = str_replace($search, $replace, $datestring);
}
}
if (!empty($formatdata['range'])) {
foreach ($this->get_range_placeholders($formatdata['range']) as $search => $replace) {
$datestring = str_replace($search, $replace, $datestring);
}
}
if (!empty($formatdata['recurringrange'])) {
foreach ($this->get_recurring_range_placeholders($formatdata['recurringrange']) as $search => $replace) {
$datestring = str_replace($search, $replace, $datestring);
}
}
return $datestring;
}
/**
* Return a list of placeholders to replace in date string as search => $replace pairs.
*
* @return array
*/
protected function get_placeholders() {
return [
self::CURRENT_YEAR_PLACEHOLDER => date('Y', time()),
];
}
/**
* Return a list of user's date related placeholders to replace in date string as search => $replace pairs.
* @param int $date Unix timestamp date to check.
*
* @return array
*/
protected function get_date_placeholders($date) {
return [
self::DATE_YEAR_PLACEHOLDER => date('Y', $date),
];
}
/**
* Return a list of range related placeholders to replace in date string as search => $replace pairs.
*
* @param \stdClass $range
*
* @return array
*/
protected function get_range_placeholders(\stdClass $range) {
return [
self::RANGE_FIRST_YEAR_PLACEHOLDER => date('Y', $range->startdate),
self::RANGE_LAST_YEAR_PLACEHOLDER => date('Y', $range->enddate),
];
}
/**
* Return a list of recurring range s placeholders to replace in date string as search => $replace pairs.
*
* @param \stdClass $range
*
* @return array
*/
protected function get_recurring_range_placeholders(\stdClass $range) {
return [
self::RECUR_RANGE_FIRST_YEAR_PLACEHOLDER => date('Y', $range->startdate),
self::RECUR_RANGE_LAST_YEAR_PLACEHOLDER => date('Y', $range->enddate),
];
}
/**
* Render the element in html.
*
* This function is used to render the element when we are using the
* drag and drop interface to position it.
*
* @return string the html
*/
public function render_html() {
// If there is no element data, we have nothing to display.
if (empty($this->get_data())) {
return;
}
return element_helper::render_html_content($this, get_string('preview', 'customcertelement_daterange', $this->get_name()));
}
/**
* This function is responsible for handling the restoration process of the element.
*
* We will want to update the course module the date element is pointing to as it will
* have changed in the course restore.
*
* @param \restore_customcert_activity_task $restore
*/
public function after_restore($restore) {
global $DB;
$data = $this->get_decoded_data();
if ($newitem = \restore_dbops::get_backup_ids_record($restore->get_restoreid(), 'course_module', $data->dateitem)) {
$data->dateitem = $newitem->newitemid;
$DB->set_field('customcert_elements', 'data', $this->save_unique_data($data), array('id' => $this->get_id()));
}
}
}

View file

@ -0,0 +1,46 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Privacy Subsystem implementation for customcertelement_daterange.
*
* @package customcertelement_daterange
* @copyright 2018 Dmitrii Metelkin <dmitriim@catalyst-au.net>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customcertelement_daterange\privacy;
defined('MOODLE_INTERNAL') || die();
/**
* Privacy Subsystem for customcertelement_daterange implementing null_provider.
*
* @copyright 2018 Dmitrii Metelkin <dmitriim@catalyst-au.net>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements \core_privacy\local\metadata\null_provider {
/**
* Get the language string identifier with the component's language
* file to explain why this plugin stores no data.
*
* @return string
*/
public static function get_reason() : string {
return 'privacy:metadata';
}
}

View file

@ -0,0 +1,53 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'customcertelement_daterange', language 'en'.
*
* @package customcertelement_daterange
* @copyright 2018 Dmitrii Metelkin <dmitriim@catalyst-au.net>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
$string['addrange'] = 'Add another range';
$string['completiondate'] = 'Completion date';
$string['courseenddate'] = 'Course end date';
$string['coursegradedate'] = 'Course grade date';
$string['coursestartdate'] = 'Course start date';
$string['currentdate'] = 'Current date';
$string['dateitem'] = 'Date item';
$string['dateitem_help'] = 'This will be the date that is printed on the certificate';
$string['dateranges'] = 'Date ranges';
$string['datestring'] = 'String';
$string['end'] = 'End';
$string['error:atleastone'] = 'You must have at least one date range configured';
$string['error:datestring'] = 'You must provide string representation for the date range';
$string['error:enddate'] = 'End date must occur after the start date';
$string['error:recurring'] = 'Recurring range must not be longer than 12 months';
$string['fallbackstring'] = 'Fallback string';
$string['fallbackstring_help'] = 'This string will be displayed if no date range applies to a date. If the fallback string is not set, then there will be no output at all.';
$string['help'] = 'Configure a string representation for your date ranges.<br /><br />If your ranges overlap the first matched date range will be applied.';
$string['issueddate'] = 'Issued date';
$string['placeholders'] = 'The following placeholders can be used in the string representation or fallback string. <br/><br /> {{range_first_year}} - first year of the matched range,<br/> {{range_last_year}} - last year of the matched range,<br/> {{recurring_range_first_year}} - first year of the matched recurring period,<br/> {{recurring_range_last_year}} - last year of the matched recurring period,<br/> {{current_year}} - the current year,<br/> {{date_year}} - a year of the users\'s date.';
$string['pluginname'] = 'Date range';
$string['preview'] = 'Preview {$a}';
$string['privacy:metadata'] = 'The Date range plugin does not store any personal data.';
$string['recurring'] = 'Recurring';
$string['recurring_help'] = 'If you mark a date range as recurring then the configured year will not be considered.';
$string['setdeleted'] = 'Delete';
$string['start'] = 'Start';

View file

@ -0,0 +1,248 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Test datarange element.
*
* @package customcertelement_daterange
* @copyright 2018 Dmitrii Metelkin <dmitriim@catalyst-au.net>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/mod/customcert/element/daterange/tests/fixtures/fake_datarange_element.php');
/**
* Test datarange element.
*
* @package customcertelement_daterange
* @copyright 2018 Dmitrii Metelkin <dmitriim@catalyst-au.net>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class customcertelement_daterange_element_test extends advanced_testcase {
/**
* Helper function to build element data.
*
* @param stdClass $data Element data.
*
* @return object
*/
protected function build_element_data(stdClass $data) {
return (object) [
'id' => 1,
'pageid' => 1,
'name' => 'Test',
'data' => json_encode($data),
'font' => 'Font',
'fontsize' => 1,
'colour' => '#EEE',
'posx' => 0,
'posy' => 0,
'width' => 100,
'refpoint' => 1
];
}
/**
* Helper function to build datarange data.
*
* @param array $dataranges A list of dataranges.
* @param string $fallbackstring Fall back string.
*
* @return object
*/
protected function build_datarange_data(array $dataranges, $fallbackstring = '') {
return (object) [
'dateitem' => 1,
'fallbackstring' => $fallbackstring,
'numranges' => count($dataranges),
'dateranges' => $dataranges,
];
}
/**
* A helper function to get datarange element for testing.
*
* @param array $dataranges A list of dataranges.
* @param string $fallbackstring Fall back strin
*
* @return \fake_datarange_element
*/
protected function get_datarange_element(array $dataranges, $fallbackstring = '') {
$datarangedata = $this->build_datarange_data($dataranges, $fallbackstring);
$elementdata = $this->build_element_data($datarangedata);
return new fake_datarange_element($elementdata);
}
/**
* Data provider for test_get_daterange_string_for_recurring_ranges.
* @return array
*/
public function get_test_get_daterange_string_for_recurring_ranges_data_provider() {
return [
['1.11.2016', 'WS 2016/2017'],
['1.11.2017', 'WS 2017/2018'],
['1.11.2018', 'WS 2018/2019'],
['1.11.2019', 'WS 2019/2020'],
['1.02.2017', 'WS 2016/2017'],
['1.02.2018', 'WS 2017/2018'],
['1.02.2019', 'WS 2018/2019'],
['1.02.2020', 'WS 2019/2020'],
['1.05.2016', 'SS 2016'],
['1.05.2017', 'SS 2017'],
['1.05.2018', 'SS 2018'],
['1.05.2019', 'SS 2019'],
];
}
/**
* Test get correct strings for recurring ranges.
*
* @dataProvider get_test_get_daterange_string_for_recurring_ranges_data_provider
*
* @param string $date Date to test.
* @param string $expected Expected result.
*/
public function test_get_daterange_string_for_recurring_ranges($date, $expected) {
$dateranges = [
(object)[
'startdate' => strtotime('01.04.2017'),
'enddate' => strtotime('30.09.2017'),
'datestring' => 'SS {{date_year}}',
'recurring' => true,
],
(object)[
'startdate' => strtotime('01.10.2017'),
'enddate' => strtotime('31.03.2018'),
'datestring' => 'WS {{recurring_range_first_year}}/{{recurring_range_last_year}}',
'recurring' => true,
],
];
$element = $this->get_datarange_element($dateranges);
$date = strtotime($date);
$this->assertEquals($expected, $element->get_daterange_string($date));
}
/**
* Test that first found element matched.
*/
public function test_that_first_matched_range_applied_first() {
$dateranges = [
(object)[
'startdate' => strtotime('01.04.2017'),
'enddate' => strtotime('30.09.2017'),
'datestring' => 'First range',
'recurring' => false,
],
(object)[
'startdate' => strtotime('01.05.2017'),
'enddate' => strtotime('01.07.2018'),
'datestring' => 'Second range',
'recurring' => false,
],
];
$element = $this->get_datarange_element($dateranges);
$date = strtotime('1.06.2017');
$this->assertEquals('First range', $element->get_daterange_string($date));
}
/**
* Test that placeholders correctly applied to matched range and fall back string.
*/
public function test_placeholders_and_fall_back_string() {
$dateranges = [
(object)[
'startdate' => strtotime('01.04.2017'),
'enddate' => strtotime('30.09.2018'),
'datestring' => '{{current_year}} - {{range_first_year}} - {{range_last_year}} - {{date_year}}',
'recurring' => false,
],
];
$fallbackstring = '{{current_year}} - {{range_first_year}} - {{range_last_year}} - {{date_year}}';
$element = $this->get_datarange_element($dateranges, $fallbackstring);
$date = strtotime('1.01.2000');
$expected = date('Y', time()) . ' - {{range_first_year}} - {{range_last_year}} - 2000';
$this->assertEquals($expected, $element->get_daterange_string($date));
$date = strtotime('1.07.2017');
$expected = date('Y', time()) . ' - 2017 - 2018 - 2017';
$this->assertEquals($expected, $element->get_daterange_string($date));
}
/**
* Test that nothing will be displayed if not matched and empty fall back string.
*/
public function test_nothing_will_be_displayed_if_empty_fallback_string() {
$dateranges = [
(object)[
'startdate' => strtotime('01.04.2017'),
'enddate' => strtotime('30.09.2018'),
'datestring' => '{{current_year}} - {{range_first_year}} - {{range_last_year}} - {{date_year}}',
'recurring' => false,
],
];
$fallbackstring = '';
$element = $this->get_datarange_element($dateranges, $fallbackstring);
$date = strtotime('1.07.2011');
$this->assertEquals($fallbackstring, $element->get_daterange_string($date));
}
/**
* Test that display recurring_range_first_year and recurring_range_last_year placeholders.
*/
public function test_recurring_range_first_year_and_recurring_range_last_year_placeholders() {
$datestring = '{{range_first_year}}-{{range_last_year}}-{{recurring_range_first_year}}-{{recurring_range_last_year}}';
$dateranges = [
(object) [
'startdate' => strtotime('01.04.2017'),
'enddate' => strtotime('30.09.2017'),
'datestring' => $datestring,
'recurring' => true,
],
(object)[
'startdate' => strtotime('01.10.2017'),
'enddate' => strtotime('31.03.2018'),
'datestring' => $datestring,
'recurring' => true,
],
];
$element = $this->get_datarange_element($dateranges);
$date = strtotime('1.05.2020');
$this->assertEquals('2017-2017-2020-2020', $element->get_daterange_string($date));
$date = strtotime('1.05.2024');
$this->assertEquals('2017-2017-2024-2024', $element->get_daterange_string($date));
$date = strtotime('1.02.2020');
$this->assertEquals('2017-2018-2019-2020', $element->get_daterange_string($date));
$date = strtotime('1.02.2024');
$this->assertEquals('2017-2018-2023-2024', $element->get_daterange_string($date));
}
}

View file

@ -0,0 +1,47 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Fake datarange element for testing.
*
* @package customcertelement_daterange
* @copyright 2018 Dmitrii Metelkin <dmitriim@catalyst-au.net>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**
* Fake datarange element for testing.
*
* @package customcertelement_daterange
* @copyright 2018 Dmitrii Metelkin <dmitriim@catalyst-au.net>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class fake_datarange_element extends \customcertelement_daterange\element {
/**
* Override protected method for testing.
*
* @param int $date
*
* @return string
*/
public function get_daterange_string($date) {
$result = parent::get_daterange_string($date);
return $result;
}
}

View file

@ -0,0 +1,29 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the version information for the date plugin.
*
* @package customcertelement_daterange
* @copyright 2018 Dmitrii Metelkin <dmitriim@catalyst-au.net>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
$plugin->version = 2018120300; // The current module version (Date: YYYYMMDDXX).
$plugin->requires = 2018120300; // Requires this Moodle version (3.6).
$plugin->component = 'customcertelement_daterange';

View file

@ -0,0 +1,338 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the customcert element digitial signature's core interaction API.
*
* @package customcertelement_digitalsignature
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customcertelement_digitalsignature;
defined('MOODLE_INTERNAL') || die();
/**
* The customcert element digital signature's core interaction API.
*
* @package customcertelement_digitalsignature
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class element extends \customcertelement_image\element {
/**
* @var array The file manager options for the certificate.
*/
protected $signaturefilemanageroptions = array();
/**
* Constructor.
*
* @param \stdClass $element the element data
*/
public function __construct($element) {
global $COURSE;
$this->signaturefilemanageroptions = [
'maxbytes' => $COURSE->maxbytes,
'subdirs' => 1,
'accepted_types' => ['.crt']
];
parent::__construct($element);
}
/**
* This function renders the form elements when adding a customcert element.
*
* @param \MoodleQuickForm $mform the edit_form instance
*/
public function render_form_elements($mform) {
$mform->addElement('select', 'fileid', get_string('image', 'customcertelement_image'), self::get_images());
$mform->addElement('select', 'signaturefileid', get_string('digitalsignature', 'customcertelement_digitalsignature'),
self::get_signatures());
$mform->addElement('text', 'signaturename', get_string('signaturename', 'customcertelement_digitalsignature'));
$mform->setType('signaturename', PARAM_TEXT);
$mform->setDefault('signaturename', '');
$mform->addElement('passwordunmask', 'signaturepassword',
get_string('signaturepassword', 'customcertelement_digitalsignature'));
$mform->setType('signaturepassword', PARAM_TEXT);
$mform->setDefault('signaturepassword', '');
$mform->addElement('text', 'signaturelocation', get_string('signaturelocation', 'customcertelement_digitalsignature'));
$mform->setType('signaturelocation', PARAM_TEXT);
$mform->setDefault('signaturelocation', '');
$mform->addElement('text', 'signaturereason', get_string('signaturereason', 'customcertelement_digitalsignature'));
$mform->setType('signaturereason', PARAM_TEXT);
$mform->setDefault('signaturereason', '');
$mform->addElement('text', 'signaturecontactinfo',
get_string('signaturecontactinfo', 'customcertelement_digitalsignature'));
$mform->setType('signaturecontactinfo', PARAM_TEXT);
$mform->setDefault('signaturecontactinfo', '');
$mform->addElement('text', 'width', get_string('width', 'customcertelement_image'), array('size' => 10));
$mform->setType('width', PARAM_INT);
$mform->setDefault('width', 0);
$mform->addHelpButton('width', 'width', 'customcertelement_image');
$mform->addElement('text', 'height', get_string('height', 'customcertelement_image'), array('size' => 10));
$mform->setType('height', PARAM_INT);
$mform->setDefault('height', 0);
$mform->addHelpButton('height', 'height', 'customcertelement_image');
if (get_config('customcert', 'showposxy')) {
\mod_customcert\element_helper::render_form_element_position($mform);
}
$mform->addElement('filemanager', 'customcertimage', get_string('uploadimage', 'customcert'), '',
$this->filemanageroptions);
$mform->addElement('filemanager', 'digitalsignature',
get_string('uploaddigitalsignature', 'customcertelement_digitalsignature'), '',
$this->signaturefilemanageroptions);
}
/**
* Handles saving the form elements created by this element.
* Can be overridden if more functionality is needed.
*
* @param \stdClass $data the form data
* @return bool true of success, false otherwise.
*/
public function save_form_elements($data) {
global $COURSE, $SITE;
// Set the context.
if ($COURSE->id == $SITE->id) {
$context = \context_system::instance();
} else {
$context = \context_course::instance($COURSE->id);
}
// Handle file uploads.
\mod_customcert\certificate::upload_files($data->customcertimage, $context->id);
// Handle file certificate uploads.
\mod_customcert\certificate::upload_files($data->digitalsignature, $context->id, 'signature');
return parent::save_form_elements($data);
}
/**
* This will handle how form data will be saved into the data column in the
* customcert_elements table.
*
* @param \stdClass $data the form data
* @return string the json encoded array
*/
public function save_unique_data($data) {
$arrtostore = [
'signaturename' => $data->signaturename,
'signaturepassword' => $data->signaturepassword,
'signaturelocation' => $data->signaturelocation,
'signaturereason' => $data->signaturereason,
'signaturecontactinfo' => $data->signaturecontactinfo,
'width' => !empty($data->width) ? (int) $data->width : 0,
'height' => !empty($data->height) ? (int) $data->height : 0
];
// Array of data we will be storing in the database.
$fs = get_file_storage();
if (!empty($data->fileid)) {
if ($file = $fs->get_file_by_id($data->fileid)) {
$arrtostore += [
'contextid' => $file->get_contextid(),
'filearea' => $file->get_filearea(),
'itemid' => $file->get_itemid(),
'filepath' => $file->get_filepath(),
'filename' => $file->get_filename(),
];
}
}
if (!empty($data->signaturefileid)) {
if ($signaturefile = $fs->get_file_by_id($data->signaturefileid)) {
$arrtostore += [
'signaturecontextid' => $signaturefile->get_contextid(),
'signaturefilearea' => $signaturefile->get_filearea(),
'signatureitemid' => $signaturefile->get_itemid(),
'signaturefilepath' => $signaturefile->get_filepath(),
'signaturefilename' => $signaturefile->get_filename()
];
}
}
return json_encode($arrtostore);
}
/**
* Handles rendering the element on the pdf.
*
* @param \pdf $pdf the pdf object
* @param bool $preview true if it is a preview, false otherwise
* @param \stdClass $user the user we are rendering this for
*/
public function render($pdf, $preview, $user) {
// If there is no element data, we have nothing to display.
if (empty($this->get_data())) {
return;
}
$imageinfo = json_decode($this->get_data());
// If there is no file, we have nothing to display.
if (empty($imageinfo->filename)) {
return;
}
// If there is no signature file, we have nothing to display.
if (empty($imageinfo->signaturefilename)) {
return;
}
if ($file = $this->get_file()) {
$location = make_request_directory() . '/target';
$file->copy_content_to($location);
$mimetype = $file->get_mimetype();
if ($mimetype == 'image/svg+xml') {
$pdf->ImageSVG($location, $this->get_posx(), $this->get_posy(), $imageinfo->width, $imageinfo->height);
} else {
$pdf->Image($location, $this->get_posx(), $this->get_posy(), $imageinfo->width, $imageinfo->height);
}
}
if ($signaturefile = $this->get_signature_file()) {
$location = make_request_directory() . '/target';
$signaturefile->copy_content_to($location);
$info = [
'Name' => $imageinfo->signaturename,
'Location' => $imageinfo->signaturelocation,
'Reason' => $imageinfo->signaturereason,
'ContactInfo' => $imageinfo->signaturecontactinfo
];
$pdf->setSignature('file://' . $location, '', $imageinfo->signaturepassword, '', 2, $info);
$pdf->setSignatureAppearance($this->get_posx(), $this->get_posy(), $imageinfo->width, $imageinfo->height);
}
}
/**
* Sets the data on the form when editing an element.
*
* @param \MoodleQuickForm $mform the edit_form instance
*/
public function definition_after_data($mform) {
global $COURSE, $SITE;
// Set the context.
if ($COURSE->id == $SITE->id) {
$context = \context_system::instance();
} else {
$context = \context_course::instance($COURSE->id);
}
if (!empty($this->get_data())) {
$imageinfo = json_decode($this->get_data());
$element = $mform->getElement('signaturename');
$element->setValue($imageinfo->signaturename);
$element = $mform->getElement('signaturepassword');
$element->setValue($imageinfo->signaturepassword);
$element = $mform->getElement('signaturelocation');
$element->setValue($imageinfo->signaturelocation);
$element = $mform->getElement('signaturereason');
$element->setValue($imageinfo->signaturereason);
$element = $mform->getElement('signaturecontactinfo');
$element->setValue($imageinfo->signaturecontactinfo);
if (!empty($imageinfo->signaturefilename)) {
if ($signaturefile = $this->get_signature_file()) {
$element = $mform->getElement('signaturefileid');
$element->setValue($signaturefile->get_id());
}
}
}
// Editing existing instance - copy existing files into draft area.
$draftitemid = file_get_submitted_draft_itemid('digitalsignature');
file_prepare_draft_area($draftitemid, $context->id, 'mod_customcert', 'signature', 0,
$this->signaturefilemanageroptions);
$element = $mform->getElement('digitalsignature');
$element->setValue($draftitemid);
parent::definition_after_data($mform);
}
/**
* Return the list of possible images to use.
*
* @return array the list of images that can be used
*/
public static function get_signatures() {
global $COURSE;
// Create file storage object.
$fs = get_file_storage();
// The array used to store the digital signatures.
$arrfiles = array();
// Loop through the files uploaded in the system context.
if ($files = $fs->get_area_files(\context_system::instance()->id, 'mod_customcert', 'signature', false,
'filename', false)) {
foreach ($files as $hash => $file) {
$arrfiles[$file->get_id()] = $file->get_filename();
}
}
// Loop through the files uploaded in the course context.
if ($files = $fs->get_area_files(\context_course::instance($COURSE->id)->id, 'mod_customcert', 'signature', false,
'filename', false)) {
foreach ($files as $hash => $file) {
$arrfiles[$file->get_id()] = $file->get_filename();
}
}
\core_collator::asort($arrfiles);
$arrfiles = array('0' => get_string('nosignature', 'customcertelement_digitalsignature')) + $arrfiles;
return $arrfiles;
}
/**
* Fetch stored file.
*
* @return \stored_file|bool stored_file instance if exists, false if not
*/
public function get_signature_file() {
$imageinfo = json_decode($this->get_data());
$fs = get_file_storage();
return $fs->get_file($imageinfo->signaturecontextid, 'mod_customcert', $imageinfo->signaturefilearea,
$imageinfo->signatureitemid, $imageinfo->signaturefilepath, $imageinfo->signaturefilename);
}
}

View file

@ -0,0 +1,46 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Privacy Subsystem implementation for customcertelement_digitalsignature.
*
* @package customcertelement_digitalsignature
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customcertelement_digitalsignature\privacy;
defined('MOODLE_INTERNAL') || die();
/**
* Privacy Subsystem for customcertelement_digitalsignature implementing null_provider.
*
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements \core_privacy\local\metadata\null_provider {
/**
* Get the language string identifier with the component's language
* file to explain why this plugin stores no data.
*
* @return string
*/
public static function get_reason() : string {
return 'privacy:metadata';
}
}

View file

@ -0,0 +1,34 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'customcertelement_digitalsignature', language 'en'.
*
* @package customcertelement_digitalsignature
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['digitalsignature'] = 'Digital signature';
$string['nosignature'] = 'No signature';
$string['pluginname'] = 'Digital signature';
$string['privacy:metadata'] = 'The Digital signature plugin does not store any personal data.';
$string['signaturename'] = 'Signature name';
$string['signaturepassword'] = 'Signature password';
$string['signaturelocation'] = 'Signature location';
$string['signaturereason'] = 'Signature reason';
$string['signaturecontactinfo'] = 'Signature contact info';
$string['uploaddigitalsignature'] = 'Upload digital signature';

View file

@ -0,0 +1,29 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the version information for the digital signature plugin.
*
* @package customcertelement_digitalsignature
* @copyright 2017 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
$plugin->version = 2018120300; // The current module version (Date: YYYYMMDDXX).
$plugin->requires = 2018120300; // Requires this Moodle version (3.6).
$plugin->component = 'customcertelement_digitalsignature';

View file

@ -0,0 +1,218 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the customcert element grade's core interaction API.
*
* @package customcertelement_grade
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customcertelement_grade;
defined('MOODLE_INTERNAL') || die();
/**
* Grade - Course
*/
define('CUSTOMCERT_GRADE_COURSE', '0');
/**
* The customcert element grade's core interaction API.
*
* @package customcertelement_grade
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class element extends \mod_customcert\element {
/**
* This function renders the form elements when adding a customcert element.
*
* @param \MoodleQuickForm $mform the edit_form instance
*/
public function render_form_elements($mform) {
global $COURSE;
// Get the grade items we can display.
$gradeitems = array();
$gradeitems[CUSTOMCERT_GRADE_COURSE] = get_string('coursegrade', 'customcertelement_grade');
$gradeitems = $gradeitems + \mod_customcert\element_helper::get_grade_items($COURSE);
// The grade items.
$mform->addElement('select', 'gradeitem', get_string('gradeitem', 'customcertelement_grade'), $gradeitems);
$mform->addHelpButton('gradeitem', 'gradeitem', 'customcertelement_grade');
// The grade format.
$mform->addElement('select', 'gradeformat', get_string('gradeformat', 'customcertelement_grade'),
self::get_grade_format_options());
$mform->setType('gradeformat', PARAM_INT);
$mform->addHelpButton('gradeformat', 'gradeformat', 'customcertelement_grade');
parent::render_form_elements($mform);
}
/**
* This will handle how form data will be saved into the data column in the
* customcert_elements table.
*
* @param \stdClass $data the form data.
* @return string the json encoded array
*/
public function save_unique_data($data) {
// Array of data we will be storing in the database.
$arrtostore = array(
'gradeitem' => $data->gradeitem,
'gradeformat' => $data->gradeformat
);
// Encode these variables before saving into the DB.
return json_encode($arrtostore);
}
/**
* Handles rendering the element on the pdf.
*
* @param \pdf $pdf the pdf object
* @param bool $preview true if it is a preview, false otherwise
* @param \stdClass $user the user we are rendering this for
*/
public function render($pdf, $preview, $user) {
// If there is no element data, we have nothing to display.
if (empty($this->get_data())) {
return;
}
$courseid = \mod_customcert\element_helper::get_courseid($this->id);
// Decode the information stored in the database.
$gradeinfo = json_decode($this->get_data());
$gradeitem = $gradeinfo->gradeitem;
$gradeformat = $gradeinfo->gradeformat;
// If we are previewing this certificate then just show a demonstration grade.
if ($preview) {
$courseitem = \grade_item::fetch_course_item($courseid);
$grade = grade_format_gradevalue('100', $courseitem, true, $gradeinfo->gradeformat);;
} else {
if ($gradeitem == CUSTOMCERT_GRADE_COURSE) {
$grade = \mod_customcert\element_helper::get_course_grade_info(
$courseid,
$gradeformat,
$user->id
);
} else if (strpos($gradeitem, 'gradeitem:') === 0) {
$gradeitemid = substr($gradeitem, 10);
$grade = \mod_customcert\element_helper::get_grade_item_info(
$gradeitemid,
$gradeformat,
$user->id
);
} else {
$grade = \mod_customcert\element_helper::get_mod_grade_info(
$gradeitem,
$gradeformat,
$user->id
);
}
if ($grade) {
$grade = $grade->get_displaygrade();
}
}
\mod_customcert\element_helper::render_content($pdf, $this, $grade);
}
/**
* Render the element in html.
*
* This function is used to render the element when we are using the
* drag and drop interface to position it.
*
* @return string the html
*/
public function render_html() {
global $COURSE;
// If there is no element data, we have nothing to display.
if (empty($this->get_data())) {
return;
}
// Decode the information stored in the database.
$gradeinfo = json_decode($this->get_data());
$courseitem = \grade_item::fetch_course_item($COURSE->id);
$grade = grade_format_gradevalue('100', $courseitem, true, $gradeinfo->gradeformat);
return \mod_customcert\element_helper::render_html_content($this, $grade);
}
/**
* Sets the data on the form when editing an element.
*
* @param \MoodleQuickForm $mform the edit_form instance
*/
public function definition_after_data($mform) {
// Set the item and format for this element.
if (!empty($this->get_data())) {
$gradeinfo = json_decode($this->get_data());
$element = $mform->getElement('gradeitem');
$element->setValue($gradeinfo->gradeitem);
$element = $mform->getElement('gradeformat');
$element->setValue($gradeinfo->gradeformat);
}
parent::definition_after_data($mform);
}
/**
* This function is responsible for handling the restoration process of the element.
*
* We will want to update the course module the grade element is pointing to as it will
* have changed in the course restore.
*
* @param \restore_customcert_activity_task $restore
*/
public function after_restore($restore) {
global $DB;
$gradeinfo = json_decode($this->get_data());
if ($newitem = \restore_dbops::get_backup_ids_record($restore->get_restoreid(), 'course_module', $gradeinfo->gradeitem)) {
$gradeinfo->gradeitem = $newitem->newitemid;
$DB->set_field('customcert_elements', 'data', $this->save_unique_data($gradeinfo), array('id' => $this->get_id()));
}
}
/**
* Helper function to return all the possible grade formats.
*
* @return array returns an array of grade formats
*/
public static function get_grade_format_options() {
$gradeformat = array();
$gradeformat[GRADE_DISPLAY_TYPE_REAL] = get_string('gradepoints', 'customcertelement_grade');
$gradeformat[GRADE_DISPLAY_TYPE_PERCENTAGE] = get_string('gradepercent', 'customcertelement_grade');
$gradeformat[GRADE_DISPLAY_TYPE_LETTER] = get_string('gradeletter', 'customcertelement_grade');
return $gradeformat;
}
}

View file

@ -0,0 +1,46 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Privacy Subsystem implementation for customcertelement_grade.
*
* @package customcertelement_grade
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customcertelement_grade\privacy;
defined('MOODLE_INTERNAL') || die();
/**
* Privacy Subsystem for customcertelement_grade implementing null_provider.
*
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements \core_privacy\local\metadata\null_provider {
/**
* Get the language string identifier with the component's language
* file to explain why this plugin stores no data.
*
* @return string
*/
public static function get_reason() : string {
return 'privacy:metadata';
}
}

View file

@ -0,0 +1,36 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'customcertelement_grade', language 'en'.
*
* @package customcertelement_grade
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['coursegrade'] = 'Course grade';
$string['gradeitem'] = 'Grade item';
$string['gradeitem_help'] = 'The grade item you wish to display the grade of.';
$string['gradeformat'] = 'Grade format';
$string['gradeformat_help'] = 'The format you wish to use when displaying the grade.';
$string['gradeitem'] = 'Grade item';
$string['gradepercent'] = 'Percentage';
$string['gradepoints'] = 'Points';
$string['gradeletter'] = 'Letter';
$string['pluginname'] = 'Grade';
$string['previewgrade'] = 'Preview grade';
$string['privacy:metadata'] = 'The Grade plugin does not store any personal data.';

29
element/grade/version.php Normal file
View file

@ -0,0 +1,29 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the version information for the grade plugin.
*
* @package customcertelement_grade
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
$plugin->version = 2018120300; // The current module version (Date: YYYYMMDDXX).
$plugin->requires = 2018120300; // Requires this Moodle version (3.6).
$plugin->component = 'customcertelement_grade';

View file

@ -0,0 +1,149 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the customcert element gradeitemname's core interaction API.
*
* @package customcertelement_gradeitemname
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customcertelement_gradeitemname;
defined('MOODLE_INTERNAL') || die();
/**
* The customcert element gradeitemname's core interaction API.
*
* @package customcertelement_gradeitemname
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class element extends \mod_customcert\element {
/**
* This function renders the form elements when adding a customcert element.
*
* @param \MoodleQuickForm $mform the edit_form instance
*/
public function render_form_elements($mform) {
global $COURSE;
$mform->addElement('select', 'gradeitem', get_string('gradeitem', 'customcertelement_gradeitemname'),
\mod_customcert\element_helper::get_grade_items($COURSE));
$mform->addHelpButton('gradeitem', 'gradeitem', 'customcertelement_gradeitemname');
parent::render_form_elements($mform);
}
/**
* This will handle how form data will be saved into the data column in the
* customcert_elements table.
*
* @param \stdClass $data the form data
* @return string the text
*/
public function save_unique_data($data) {
if (!empty($data->gradeitem)) {
return $data->gradeitem;
}
return '';
}
/**
* Handles rendering the element on the pdf.
*
* @param \pdf $pdf the pdf object
* @param bool $preview true if it is a preview, false otherwise
* @param \stdClass $user the user we are rendering this for
*/
public function render($pdf, $preview, $user) {
// Check that the grade item is not empty.
if (!empty($this->get_data())) {
\mod_customcert\element_helper::render_content($pdf, $this, $this->get_grade_item_name());
}
}
/**
* Render the element in html.
*
* This function is used to render the element when we are using the
* drag and drop interface to position it.
*
* @return string the html
*/
public function render_html() {
// Check that the grade item is not empty.
if (!empty($this->get_data())) {
return \mod_customcert\element_helper::render_html_content($this, $this->get_grade_item_name());
}
return '';
}
/**
* Sets the data on the form when editing an element.
*
* @param \MoodleQuickForm $mform the edit_form instance
*/
public function definition_after_data($mform) {
if (!empty($this->get_data())) {
$element = $mform->getElement('gradeitem');
$element->setValue($this->get_data());
}
parent::definition_after_data($mform);
}
/**
* Helper function that returns the grade item name.
*
* @return string
*/
protected function get_grade_item_name() : string {
global $DB;
$gradeitem = $this->get_data();
if (strpos($gradeitem, 'gradeitem:') === 0) {
$gradeitemid = substr($gradeitem, 10);
$gradeitem = \grade_item::fetch(['id' => $gradeitemid]);
return $gradeitem->get_name();
} else {
if (!$cm = $DB->get_record('course_modules', array('id' => $gradeitem))) {
return '';
}
if (!$module = $DB->get_record('modules', array('id' => $cm->module))) {
return '';
}
$params = [
'itemtype' => 'mod',
'itemmodule' => $module->name,
'iteminstance' => $cm->instance,
'courseid' => $cm->course,
'itemnumber' => 0
];
$gradeitem = \grade_item::fetch($params);
return $gradeitem->get_name();
}
}
}

View file

@ -0,0 +1,46 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Privacy Subsystem implementation for customcertelement_gradeitemname.
*
* @package customcertelement_gradeitemname
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customcertelement_gradeitemname\privacy;
defined('MOODLE_INTERNAL') || die();
/**
* Privacy Subsystem for customcertelement_gradeitemname implementing null_provider.
*
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements \core_privacy\local\metadata\null_provider {
/**
* Get the language string identifier with the component's language
* file to explain why this plugin stores no data.
*
* @return string
*/
public static function get_reason() : string {
return 'privacy:metadata';
}
}

View file

@ -0,0 +1,28 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'customcertelement_gradeitemname', language 'en'.
*
* @package customcertelement_gradeitemname
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['gradeitem'] = 'Grade item';
$string['gradeitem_help'] = 'The name of the selected item will be displayed on the PDF.';
$string['pluginname'] = 'Grade item name';
$string['privacy:metadata'] = 'The Grade item name plugin does not store any personal data.';

View file

@ -0,0 +1,29 @@
<?php
// This file is part of the customcert module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the version information for the gradeitemname plugin.
*
* @package customcertelement_gradeitemname
* @copyright 2013 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
$plugin->version = 2018120300; // The current module version (Date: YYYYMMDDXX).
$plugin->requires = 2018120300; // Requires this Moodle version (3.6).
$plugin->component = 'customcertelement_gradeitemname';

Some files were not shown because too many files have changed in this diff Show more