diff --git a/backup/moodle2/restore_customcert_activity_task.class.php b/backup/moodle2/restore_customcert_activity_task.class.php index 10ed121..c883290 100644 --- a/backup/moodle2/restore_customcert_activity_task.class.php +++ b/backup/moodle2/restore_customcert_activity_task.class.php @@ -111,7 +111,7 @@ class restore_customcert_activity_task extends restore_activity_task { // Go through the elements for the certificate. foreach ($elements as $e) { // Get an instance of the element class. - if ($e = customcert_get_element_instance($e)) { + if ($e = \mod_customcert\element::instance($e)) { $e->after_restore($this); } } diff --git a/adminsetting.class.php b/classes/admin_setting_link.php similarity index 68% rename from adminsetting.class.php rename to classes/admin_setting_link.php index a5eb0cc..e12563f 100644 --- a/adminsetting.class.php +++ b/classes/admin_setting_link.php @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace mod_customcert; + /** * Creates an upload form on the settings page. * @@ -22,12 +24,28 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ require_once($CFG->libdir.'/adminlib.php'); -require_once($CFG->dirroot.'/mod/customcert/upload_image_form.php'); /** * Class extends admin setting class to allow/process an uploaded file */ -class mod_customcert_admin_setting_upload extends admin_setting_configtext { +class admin_setting_link extends \admin_setting_configtext { + + /** + * @var string the link. + */ + protected $link; + + /** + * @var string the link name. + */ + protected $linkname; + + public function __construct($name, $visiblename, $description, $linkname, $link, $defaultsetting, + $paramtype = PARAM_RAW, $size=null) { + $this->link = $link; + $this->linkname = $linkname; + parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size); + } /** * Output the link to the upload image page. @@ -41,7 +59,6 @@ class mod_customcert_admin_setting_upload extends admin_setting_configtext { $this->config_write($this->name, ''); return format_admin_setting($this, $this->visiblename, - html_writer::link(new moodle_url('/mod/customcert/upload_image.php'), get_string('upload')), - $this->description, true, '', null, $query); + \html_writer::link($this->link, $this->linkname), $this->description, true, '', null, $query); } -} +} \ No newline at end of file diff --git a/classes/certificate.php b/classes/certificate.php new file mode 100644 index 0000000..38b8dd7 --- /dev/null +++ b/classes/certificate.php @@ -0,0 +1,440 @@ +. + +/** + * Provides functionality needed by certificates. + * + * @package mod_customcert + * @copyright 2016 Mark Nelson + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_customcert; + +defined('MOODLE_INTERNAL') || die(); + +/** + * Class element + * + * All customercert element plugins are based on this class. + */ +class certificate { + + /** + * @var string the print protection variable + */ + const PROTECTION_PRINT = 'print'; + + /** + * @var string the modify protection variable + */ + const PROTECTION_MODIFY = 'modify'; + + /** + * @var string the copy protection variable + */ + const PROTECTION_COPY = 'copy'; + + /** + * @var int the number of issues that will be displayed on each page in the report + * If you want to display all customcerts on a page set this to 0. + */ + const CUSTOMCERT_PER_PAGE = '20'; + + /** + * @var int the max number of issues to display + */ + const CUSTOMCERT_MAX_PER_PAGE = '300'; + + /** + * Handles setting the protection field for the customcert + * + * @param \stdClass $data + * @return string the value to insert into the protection field + */ + public static function set_protection($data) { + $protection = array(); + + if (!empty($data->protection_print)) { + $protection[] = self::PROTECTION_PRINT; + } + if (!empty($data->protection_modify)) { + $protection[] = self::PROTECTION_MODIFY; + } + if (!empty($data->protection_copy)) { + $protection[] = self::PROTECTION_COPY; + } + + // Return the protection string. + return implode(', ', $protection); + } + + /** + * 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 + */ + public static function upload_imagefiles($draftitemid, $contextid) { + // Save the file if it exists that is currently in the draft area. + file_save_draft_area_files($draftitemid, $contextid, 'mod_customcert', 'image', 0); + } + + /** + * Return the list of possible fonts to use. + */ + public static function get_fonts() { + global $CFG; + + // Array to store the available fonts. + $options = array(); + + // Location of fonts in Moodle. + $fontdir = "$CFG->dirroot/lib/tcpdf/fonts"; + // Check that the directory exists. + if (file_exists($fontdir)) { + // Get directory contents. + $fonts = new \DirectoryIterator($fontdir); + // Loop through the font folder. + foreach ($fonts as $font) { + // If it is not a file, or either '.' or '..', or + // the extension is not php, or we can not open file, + // skip it. + if (!$font->isFile() || $font->isDot() || ($font->getExtension() != 'php')) { + continue; + } + // 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("$fontdir/$font"); + // If no $name variable in file, skip it. + if (is_null($name)) { + continue; + } + // Remove the extension of the ".php" file that contains the font information. + $filename = basename($font, ".php"); + // 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); + } + $options[$filename] = $displayname; + } + ksort($options); + } + + return $options; + } + + /** + * 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 <= 60; $i++) { + $sizes[$i] = $i; + } + + return $sizes; + } + + /** + * Get the time the user has spent in the course. + * + * @param int $courseid + * @return int the total time spent in seconds + */ + public static function get_course_time($courseid) { + global $CFG, $DB, $USER; + + $logmanager = get_log_manager(); + $readers = $logmanager->get_readers(); + $enabledreaders = get_config('tool_log', 'enabled_stores'); + $enabledreaders = explode(',', $enabledreaders); + + // Go through all the readers until we find one that we can use. + foreach ($enabledreaders as $enabledreader) { + $reader = $readers[$enabledreader]; + if ($reader instanceof \logstore_legacy\log\store) { + $logtable = 'log'; + $coursefield = 'course'; + $timefield = 'time'; + break; + } else if ($reader instanceof \core\log\sql_internal_reader) { + $logtable = $reader->get_internal_log_table_name(); + $coursefield = 'courseid'; + $timefield = 'timecreated'; + break; + } + } + + // If we didn't find a reader then return 0. + if (!isset($logtable)) { + return 0; + } + + $sql = "SELECT id, $timefield + FROM {{$logtable}} + WHERE userid = :userid + AND $coursefield = :courseid + ORDER BY $timefield ASC"; + $params = array('userid' => $USER->id, 'courseid' => $courseid); + $totaltime = 0; + if ($logs = $DB->get_recordset_sql($sql, $params)) { + foreach ($logs as $log) { + if (!isset($login)) { + // For the first time $login is not set so the first log is also the first login + $login = $log->$timefield; + $lasthit = $log->$timefield; + $totaltime = 0; + } + $delay = $log->$timefield - $lasthit; + 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; + } else { + $totaltime += $delay; + } + // Now the actual log became the previous log for the next cycle + $lasthit = $log->$timefield; + } + + return $totaltime; + } + + return 0; + } + + /** + * Returns a list of issued customcerts. + * + * @param int $customcertid + * @param bool $groupmode are we in group mode + * @param \stdClass $cm the course module + * @param int $page offset + * @param int $perpage total per page + * @return \stdClass the users + */ + public static function get_issues($customcertid, $groupmode, $cm, $page, $perpage) { + global $DB; + + // Get the conditional SQL. + list($conditionssql, $conditionsparams) = self::get_conditional_issues_sql($cm, $groupmode); + + // If it is empty then return an empty array. + if (empty($conditionsparams)) { + return array(); + } + + // Add the conditional SQL and the customcertid to form all used parameters. + $allparams = $conditionsparams + array('customcertid' => $customcertid); + + // Return the issues. + $sql = "SELECT u.*, ci.code, ci.timecreated + FROM {user} u + INNER JOIN {customcert_issues} ci + ON u.id = ci.userid + WHERE u.deleted = 0 + AND ci.customcertid = :customcertid + $conditionssql + ORDER BY " . $DB->sql_fullname(); + return $DB->get_records_sql($sql, $allparams, $page * $perpage, $perpage); + } + + /** + * Returns the total number of issues for a given customcert. + * + * @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($customcertid, $cm, $groupmode) { + global $DB; + + // Get the conditional SQL. + list($conditionssql, $conditionsparams) = self::get_conditional_issues_sql($cm, $groupmode); + + // If it is empty then return 0. + if (empty($conditionsparams)) { + return 0; + } + + // 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 {customcert_issues} ci + ON u.id = ci.userid + WHERE u.deleted = 0 + AND ci.customcertid = :customcertid + $conditionssql"; + return $DB->count_records_sql($sql, $allparams); + } + + /** + * Returns an array of the conditional variables to use in the get_issues SQL query. + * + * @param \stdClass $cm the course module + * @param bool $groupmode are we in group mode ? + * @return array the conditional variables + */ + public static function get_conditional_issues_sql($cm, $groupmode) { + global $DB, $USER; + + // 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/certificate: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"; + $conditionsparams += $params; + + if ($groupmode) { + $canaccessallgroups = has_capability('moodle/site:accessallgroups', $context); + $currentgroup = groups_get_activity_group($cm); + + // If we are viewing all participants and the user does not have access to all groups then return nothing. + if (!$currentgroup && !$canaccessallgroups) { + return array('', array()); + } + + if ($currentgroup) { + if (!$canaccessallgroups) { + // Guest users do not belong to any groups. + if (isguestuser()) { + return array('', array()); + } + + // Check that the user belongs to the group we are viewing. + $usersgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid); + if ($usersgroups) { + if (!isset($usersgroups[$currentgroup])) { + return array('', array()); + } + } else { // They belong to no group, so return an empty array. + return array('', array()); + } + } + + $groupusers = array_keys(groups_get_members($currentgroup, 'u.*')); + if (empty($groupusers)) { + return array('', array()); + } + + list($sql, $params) = $DB->get_in_or_equal($groupusers, SQL_PARAMS_NAMED, 'grp'); + $conditionssql .= "AND u.id $sql "; + $conditionsparams += $params; + } + } + + return array($conditionssql, $conditionsparams); + } + + /** + * Generates a 10-digit code of random letters and numbers. + * + * @return string + */ + public static function generate_code() { + global $DB; + + $uniquecodefound = false; + $code = random_string(10); + while (!$uniquecodefound) { + if (!$DB->record_exists('customcert_issues', array('code' => $code))) { + $uniquecodefound = true; + } else { + $code = random_string(10); + } + } + + return $code; + } + + /** + * Generate the report. + * + * @param \stdClass $customcert + * @param \stdClass $users the list of users who have had a customcert issued + * @param string $type + */ + public static function generate_report_file($customcert, $users, $type) { + global $CFG, $COURSE; + + if ($type == 'ods') { + require_once($CFG->libdir . '/odslib.class.php'); + $workbook = new \MoodleODSWorkbook('-'); + } else if ($type == 'xls') { + require_once($CFG->libdir . '/excellib.class.php'); + $workbook = new \MoodleExcelWorkbook('-'); + } + + $filename = clean_filename($COURSE->shortname . ' ' . rtrim($customcert->name, '.') . '.' . $type); + + // Send HTTP headers. + $workbook->send($filename); + + // Creating the first worksheet. + $myxls = $workbook->add_worksheet(get_string('report', 'customcert')); + + // Print names of all the fields. + $myxls->write_string(0, 0, get_string('lastname')); + $myxls->write_string(0, 1, get_string('firstname')); + $myxls->write_string(0, 2, get_string('idnumber')); + $myxls->write_string(0, 3, get_string('group')); + $myxls->write_string(0, 4, get_string('receiveddate', 'customcert')); + $myxls->write_string(0, 5, get_string('code', 'customcert')); + + // Generate the data for the body of the spreadsheet. + $row = 1; + if ($users) { + foreach ($users as $user) { + $myxls->write_string($row, 0, $user->lastname); + $myxls->write_string($row, 1, $user->firstname); + $studentid = (!empty($user->idnumber)) ? $user->idnumber : ' '; + $myxls->write_string($row, 2, $studentid); + $ug2 = ''; + if ($usergrps = groups_get_all_groups($COURSE->id, $user->id)) { + foreach ($usergrps as $ug) { + $ug2 = $ug2 . $ug->name; + } + } + $myxls->write_string($row, 3, $ug2); + $myxls->write_string($row, 4, userdate($user->timecreated)); + $myxls->write_string($row, 5, $user->code); + $row++; + } + } + // Close the workbook. + $workbook->close(); + } +} diff --git a/edit_element_form.php b/classes/edit_element_form.php similarity index 89% rename from edit_element_form.php rename to classes/edit_element_form.php index aa49626..a2df501 100644 --- a/edit_element_form.php +++ b/classes/edit_element_form.php @@ -14,13 +14,14 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +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/locallib.php'); require_once($CFG->dirroot . '/mod/customcert/includes/colourpicker.php'); -MoodleQuickForm::registerElementType('customcert_colourpicker', +\MoodleQuickForm::registerElementType('customcert_colourpicker', $CFG->dirroot . '/mod/customcert/includes/colourpicker.php', 'MoodleQuickForm_customcert_colourpicker'); /** @@ -30,12 +31,12 @@ MoodleQuickForm::registerElementType('customcert_colourpicker', * @copyright 2013 Mark Nelson * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class mod_customcert_edit_element_form extends moodleform { +class edit_element_form extends \moodleform { /** - * The element object. + * @var \mod_customcert\element The element object. */ - private $element; + protected $element; /** * Form definition. @@ -52,7 +53,7 @@ class mod_customcert_edit_element_form extends moodleform { $mform->addRule('name', get_string('required'), 'required', null, 'client'); $mform->addHelpButton('name', 'elementname', 'customcert'); - $this->element = customcert_get_element_instance($element); + $this->element = \mod_customcert\element::instance($element); $this->element->render_form_elements($mform); $this->add_action_buttons(true); diff --git a/edit_form.php b/classes/edit_form.php similarity index 69% rename from edit_form.php rename to classes/edit_form.php index 92b9aaa..4cdb961 100644 --- a/edit_form.php +++ b/classes/edit_form.php @@ -14,12 +14,14 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +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', +\MoodleQuickForm::registerElementType('customcert_colourpicker', $CFG->dirroot . '/mod/customcert/includes/colourpicker.php', 'MoodleQuickForm_customcert_colourpicker'); /** @@ -29,17 +31,17 @@ MoodleQuickForm::registerElementType('customcert_colourpicker', * @copyright 2013 Mark Nelson * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class mod_customcert_edit_form extends moodleform { +class edit_form extends \moodleform { /** - * The instance id. + * The id of the template being used. */ - private $id = null; + protected $tid = null; /** * The total number of pages for this cert. */ - private $numpages = 1; + protected $numpages = 1; /** * Form definition. @@ -47,16 +49,27 @@ class mod_customcert_edit_form extends moodleform { public function definition() { global $DB; - $this->id = $this->_customdata['customcertid']; - $mform =& $this->_form; + $mform->addElement('text', 'name', get_string('name', 'customcert')); + $mform->setType('name', PARAM_TEXT); + $mform->addRule('name', null, 'required'); + // Get the number of pages for this module. - if ($pages = $DB->get_records('customcert_pages', array('customcertid' => $this->id), 'pagenumber')) { - $this->numpages = count($pages); - foreach ($pages as $p) { - $this->add_customcert_page_elements($p); + if (isset($this->_customdata['tid'])) { + $this->tid = $this->_customdata['tid']; + if ($pages = $DB->get_records('customcert_pages', array('templateid' => $this->tid), 'pagenumber')) { + $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 = 1; + $page->pagenumber = 1; + $this->add_customcert_page_elements($page); } $mform->closeHeaderBefore('addcertpage'); @@ -71,12 +84,9 @@ class mod_customcert_edit_form extends moodleform { $group[] = $mform->createElement('submit', 'previewbtn', get_string('savechangespreview', 'customcert')); $mform->addElement('group', 'submitbtngroup', '', $group, '', false); - $mform->addElement('hidden', 'id'); - $mform->setType('id', PARAM_INT); - $mform->setDefault('id', $this->id); - $mform->addElement('hidden', 'cmid'); - $mform->setType('cmid', PARAM_INT); - $mform->setDefault('cmid', $this->_customdata['cmid']); + $mform->addElement('hidden', 'tid'); + $mform->setType('tid', PARAM_INT); + $mform->setDefault('tid', $this->tid); } /** @@ -88,9 +98,9 @@ class mod_customcert_edit_form extends moodleform { $mform = $this->_form; // Check that we are updating a current customcert. - if ($this->id) { + if ($this->tid) { // Get the pages for this customcert. - if ($pages = $DB->get_records('customcert_pages', array('customcertid' => $this->id))) { + if ($pages = $DB->get_records('customcert_pages', array('templateid' => $this->tid))) { // Loop through the pages. foreach ($pages as $p) { // Set the width. @@ -118,8 +128,17 @@ class mod_customcert_edit_form extends moodleform { * @return array the errors that were found */ public function validation($data, $files) { + global $DB; + $errors = parent::validation($data, $files); + // Check that the template name does not already exist for another template. + if ($template = $DB->get_record('customcert_templates', array('name' => $data['name']))) { + if (empty($data['tid']) || $template->id != $data['tid']) { + $errors['name'] = get_string('customcertnameexists', 'customcert'); + } + } + // Go through the data and check any width, height or margin values. foreach ($data as $key => $value) { if (strpos($key, 'pagewidth_') !== false) { @@ -158,26 +177,33 @@ class mod_customcert_edit_form extends moodleform { /** * Adds the page elements to the form. * - * @param stdClass $page the customcert page + * @param \stdClass $page the customcert page */ - private function add_customcert_page_elements($page) { + protected function add_customcert_page_elements($page) { global $DB, $OUTPUT; // Create the form object. $mform =& $this->_form; - $mform->addElement('header', 'page_' . $page->id, get_string('page', 'customcert', $page->pagenumber)); + if ($this->numpages > 1) { + $mform->addElement('header', 'page_' . $page->id, get_string('page', 'customcert', $page->pagenumber)); + } + + $editlink = '/mod/customcert/edit.php'; + $editlinkparams = array('tid' => $this->tid); + $editelementlink = '/mod/customcert/edit_element.php'; + $editelementlinkparams = array('tid' => $this->tid); // Place the ordering arrows. // Only display the move up arrow if it is not the first. if ($page->pagenumber > 1) { - $url = new moodle_url('/mod/customcert/edit.php', array('cmid' => $this->_customdata['cmid'], 'moveup' => $page->id)); - $mform->addElement('html', $OUTPUT->action_icon($url, new pix_icon('t/up', get_string('moveup')))); + $url = new \moodle_url($editlink, $editlinkparams + array('moveup' => $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->pagenumber < $this->numpages) { - $url = new moodle_url('/mod/customcert/edit.php', array('cmid' => $this->_customdata['cmid'], 'movedown' => $page->id)); - $mform->addElement('html', $OUTPUT->action_icon($url, new pix_icon('t/down', get_string('movedown')))); + $url = new \moodle_url($editlink, $editlinkparams + array('movedown' => $page->id)); + $mform->addElement('html', $OUTPUT->action_icon($url, new \pix_icon('t/down', get_string('movedown')))); } $mform->addElement('text', 'pagewidth_' . $page->id, get_string('width', 'customcert')); @@ -194,14 +220,16 @@ class mod_customcert_edit_form extends moodleform { $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'); $group = array(); - $group[] = $mform->createElement('select', 'element_' . $page->id, '', customcert_get_elements()); + $group[] = $mform->createElement('select', 'element_' . $page->id, '', element::get_available_types()); $group[] = $mform->createElement('submit', 'addelement_' . $page->id, get_string('addelement', 'customcert')); $mform->addElement('group', 'elementgroup', '', $group, '', false); @@ -210,7 +238,7 @@ class mod_customcert_edit_form extends moodleform { // Get the total number of elements. $numelements = count($elements); // Create a table to display these elements. - $table = new html_table(); + $table = new \html_table(); $table->head = array(get_string('name', 'customcert'), get_string('type', 'customcert'), ''); $table->align = array('left', 'left', 'center'); // If we have more than one element then we can change the order, so add extra column for the up and down arrow. @@ -220,29 +248,29 @@ class mod_customcert_edit_form extends moodleform { } // Loop through and add the elements to the table. foreach ($elements as $element) { - $row = new html_table_row(); + $row = new \html_table_row(); $row->cells[] = $element->name; $row->cells[] = $element->element; // Link to edit this element. - $editlink = new moodle_url('/mod/customcert/edit_element.php', array('id' => $element->id, - 'cmid' => $this->_customdata['cmid'], + $link = new \moodle_url($editelementlink, $editelementlinkparams + array('id' => $element->id, 'action' => 'edit')); - $icons = $OUTPUT->action_icon($editlink, new pix_icon('t/edit', get_string('edit'))); + $icons = $OUTPUT->action_icon($link, new \pix_icon('t/edit', get_string('edit'))); // Link to delete the element. - $deletelink = new moodle_url('/mod/customcert/edit.php', array('cmid' => $this->_customdata['cmid'], 'deleteelement' => $element->id)); - $icons .= $OUTPUT->action_icon($deletelink, new pix_icon('t/delete', get_string('delete', 'customcert'))); + $link = new \moodle_url($editlink, $editlinkparams + array('id' => $element->id, + 'deleteelement' => $element->id)); + $icons .= $OUTPUT->action_icon($link, new \pix_icon('t/delete', get_string('delete'))); // 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('/mod/customcert/edit.php', array('cmid' => $this->_customdata['cmid'], 'emoveup' => $element->id)); - $moveicons .= $OUTPUT->action_icon($url, new pix_icon('t/up', get_string('moveup'))); + $url = new \moodle_url($editlink, $editlinkparams + array('emoveup' => $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('/mod/customcert/edit.php', array('cmid' => $this->_customdata['cmid'], 'emovedown' => $element->id)); - $moveicons .= $OUTPUT->action_icon($url, new pix_icon('t/down', get_string('movedown'))); + $url = new \moodle_url($editlink, $editlinkparams + array('emovedown' => $element->id)); + $moveicons .= $OUTPUT->action_icon($url, new \pix_icon('t/down', get_string('movedown'))); } $icons .= $moveicons; } @@ -250,20 +278,20 @@ class mod_customcert_edit_form extends moodleform { $table->data[] = $row; } // Create link to order the elements. - $link = html_writer::link(new moodle_url('/mod/customcert/rearrange.php', array('id' => $page->id)), - get_string('rearrangeelements', 'customcert')); + $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, array('style' => 'text-align:right'))); + $mform->addElement('static', 'elements_' . $page->id, get_string('elements', 'customcert'), \html_writer::table($table) + . \html_writer::tag( 'div', $link, array('style' => 'text-align:right'))); $mform->addHelpButton('elements_' . $page->id, 'elements', 'customcert'); } // Add option to delete this page if there is more than one page. if ($this->numpages > 1) { // Link to delete the element. - $deletelink = new moodle_url('/mod/customcert/edit.php', array('cmid' => $this->_customdata['cmid'], 'deletepage' => $page->id)); - $deletelink = html_writer::tag('a', get_string('deletecertpage', 'customcert'), array('href' => $deletelink->out(false), 'class' => 'deletebutton')); - $mform->addElement('html', html_writer::tag('div', $deletelink, array('class' => 'deletebutton'))); + $deletelink = new \moodle_url($editlink, $editlinkparams + array('deletepage' => $page->id)); + $deletelink = \html_writer::tag('a', get_string('deletecertpage', 'customcert'), array('href' => $deletelink->out(false), 'class' => 'deletebutton')); + $mform->addElement('html', \html_writer::tag('div', $deletelink, array('class' => 'deletebutton'))); } } } diff --git a/classes/element.php b/classes/element.php index afb1750..f309d67 100644 --- a/classes/element.php +++ b/classes/element.php @@ -34,7 +34,7 @@ defined('MOODLE_INTERNAL') || die(); abstract class element { /** - * The data for the element we are adding. + * @var \stdClass $element The data for the element we are adding. */ public $element; @@ -51,20 +51,20 @@ abstract class element { * This function renders the form elements when adding a customcert element. * Can be overridden if more functionality is needed. * - * @param \mod_customcert_edit_element_form $mform the edit_form instance. + * @param edit_element_form $mform the edit_form instance. */ public function render_form_elements($mform) { // Render the common elements. - $this->render_form_element_font($mform); - $this->render_form_element_colour($mform); - $this->render_form_element_position($mform); + element_helper::render_form_element_font($mform); + element_helper::render_form_element_colour($mform); + element_helper::render_form_element_position($mform); } /** * Sets the data on the form when editing an element. * Can be overridden if more functionality is needed. * - * @param \mod_customcert_edit_element_form $mform the edit_form instance + * @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 @@ -90,8 +90,8 @@ abstract class element { $errors = array(); // Common validation methods. - $errors += $this->validate_form_element_colour($data); - $errors += $this->validate_form_element_position($data); + $errors += element_helper::validate_form_element_colour($data); + $errors += element_helper::validate_form_element_position($data); return $errors; } @@ -125,7 +125,7 @@ abstract class element { } else { // Must be adding a new one. $element->element = $data->element; $element->pageid = $data->pageid; - $element->sequence = $this->get_element_sequence($element->pageid); + $element->sequence = \mod_customcert\element_helper::get_element_sequence($element->pageid); $element->timecreated = time(); $DB->insert_record('customcert_elements', $element); } @@ -133,7 +133,7 @@ abstract class element { /** * This will handle how form data will be saved into the data column in the - * customcert column. + * customcert_elements table. * Can be overridden if more functionality is needed. * * @param \stdClass $data the form data @@ -144,31 +144,19 @@ abstract class element { } /** - * This will handle how individual elements save their data - * to a template to be loaded later. + * 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 saved to the template, false otherwise + * @return bool returns true if the data was copied successfully, false otherwise */ - public function save_data_to_template($data) { - return true; - } - - /** - * This will handle how individual elements load their data - * from a template to an existing customcert. - * Can be overridden if more functionality is needed. - * - * @param \stdClass $data the form data - * @return bool returns true if the data was loaded from the template, false otherwise - */ - public function load_data_from_template($data) { + public function copy_element($data) { return true; } /** * Handles rendering the element on the pdf. + * * Must be overridden. * * @param \pdf $pdf the pdf object @@ -176,56 +164,6 @@ abstract class element { */ public abstract function render($pdf, $preview); - /** - * Common behaviour for rendering specified content on the pdf. - * - * @param \pdf $pdf the pdf object - * @param string $content the content to render - */ - public function render_content($pdf, $content) { - list($font, $attr) = $this->get_font(); - $pdf->setFont($font, $attr, $this->element->size); - $fontcolour = \TCPDF_COLORS::convertHTMLColorToDec($this->element->colour, $fontcolour); - $pdf->SetTextColor($fontcolour['R'], $fontcolour['G'], $fontcolour['B']); - - $x = $this->element->posx; - $y = $this->element->posy; - $w = $this->element->width; - $refpoint = $this->element->refpoint; - $actualwidth = $pdf->GetStringWidth($content); - - if ($w and $w < $actualwidth) { - $actualwidth = $w; - } - - switch ($refpoint) { - case CUSTOMCERT_REF_POINT_TOPRIGHT: - $x = $this->element->posx - $actualwidth; - if ($x < 0) { - $x = 0; - $w = $this->element->posx; - } else { - $w = $actualwidth; - } - break; - case CUSTOMCERT_REF_POINT_TOPCENTER: - $x = $this->element->posx - $actualwidth / 2; - if ($x < 0) { - $x = 0; - $w = $this->element->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); - } - /** * Render the element in html. * @@ -233,27 +171,11 @@ abstract class element { * * 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(); - /** - * Common behaviour for rendering specified content on the drag and drop page. - * - * @param string $content the content to render - * @return string the html - */ - public function render_html_content($content) { - list($font, $attr) = $this->get_font(); - $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: ' . $this->element->colour . '; font-size: ' . $this->element->size . 'pt'; - return \html_writer::tag('span', $content, array('style' => $style)); - } /** * Handles deleting any data this element may have introduced. @@ -261,174 +183,12 @@ abstract class element { * * @return bool success return true if deletion success, false otherwise */ - public function delete_element() { + public function delete() { global $DB; return $DB->delete_records('customcert_elements', array('id' => $this->element->id)); } - /** - * 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 to render the font elements. - * - * @param \mod_customcert_edit_element_form $mform the edit_form instance. - */ - public function render_form_element_font($mform) { - $mform->addElement('select', 'font', get_string('font', 'customcert'), customcert_get_fonts()); - $mform->setType('font', PARAM_TEXT); - $mform->setDefault('font', 'times'); - $mform->addHelpButton('font', 'font', 'customcert'); - - $mform->addElement('select', 'size', get_string('fontsize', 'customcert'), customcert_get_font_sizes()); - $mform->setType('size', PARAM_INT); - $mform->setDefault('size', 12); - $mform->addHelpButton('size', 'fontsize', 'customcert'); - } - - /** - * Helper function to render the colour elements. - * - * @param \mod_customcert_edit_element_form $mform the edit_form instance. - */ - public 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 \mod_customcert_edit_element_form $mform the edit_form instance. - */ - public 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'); - - $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'); - - $refpointoptions = array(); - $refpointoptions[CUSTOMCERT_REF_POINT_TOPLEFT] = get_string('topleft', 'customcert'); - $refpointoptions[CUSTOMCERT_REF_POINT_TOPCENTER] = get_string('topcenter', 'customcert'); - $refpointoptions[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', 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 function validate_form_element_colour($data) { - $errors = array(); - - // Validate the colour. - if (!$this->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 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'); - } - - // 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. - * - * @return array the font and font attributes - */ - public function get_font() { - // Variable for the font. - $font = $this->element->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); - } - /** * This function is responsible for handling the restoration process of the element. * @@ -438,58 +198,74 @@ abstract class element { * * @param \restore_customcert_activity_task $restore */ - public function after_restore($restore) { + public function after_restore($restore) { } + /** + * Magic getter for read only access. + * + * @param string $name + */ + public function __get($name) { + if (property_exists($this->element, $name)) { + return $this->element->$name; + } } /** - * Validates the colour selected. + * Returns an instance of the element class. * - * @param string $colour - * @return bool returns true if the colour is valid, false otherwise + * @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. */ - protected 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' - ); + public static function instance($element) { + // Get the class name. + $classname = '\\customcertelement_' . $element->element . '\\element'; - if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $colour)) { - return true; - } else if (in_array(strtolower($colour), $colournames)) { - return true; + // Ensure the necessary class exists. + if (class_exists($classname)) { + return new $classname($element); } return false; } + + /** + * Return the list of possible elements to add. + * + * @return array the list of element types that can be used. + */ + public static function get_available_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)) { + $component = "customcertelement_{$foldername}"; + $options[$foldername] = get_string('pluginname', $component); + } + } + } + + \core_collator::asort($options); + return $options; + } } diff --git a/classes/element_helper.php b/classes/element_helper.php new file mode 100644 index 0000000..71a00ef --- /dev/null +++ b/classes/element_helper.php @@ -0,0 +1,325 @@ +. + +/** +* Provides useful functions related to elements. +* +* @package mod_customcert +* @copyright 2016 Mark Nelson +* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later +*/ + +namespace mod_customcert; + +defined('MOODLE_INTERNAL') || die(); + +/** + * Class helper. + * + * Provides useful functions related to elements. + */ +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) = \mod_customcert\element_helper::get_font($element); + $pdf->setFont($font, $attr, $element->size); + $fontcolour = \TCPDF_COLORS::convertHTMLColorToDec($element->colour, $fontcolour); + $pdf->SetTextColor($fontcolour['R'], $fontcolour['G'], $fontcolour['B']); + + $x = $element->posx; + $y = $element->posy; + $w = $element->width; + $refpoint = $element->refpoint; + $actualwidth = $pdf->GetStringWidth($content); + + if ($w and $w < $actualwidth) { + $actualwidth = $w; + } + + switch ($refpoint) { + case self::CUSTOMCERT_REF_POINT_TOPRIGHT: + $x = $element->posx - $actualwidth; + if ($x < 0) { + $x = 0; + $w = $element->posx; + } else { + $w = $actualwidth; + } + break; + case self::CUSTOMCERT_REF_POINT_TOPCENTER: + $x = $element->posx - $actualwidth / 2; + if ($x < 0) { + $x = 0; + $w = $element->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) = \mod_customcert\element_helper::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->colour . '; font-size: ' . $element->size . 'pt'; + return \html_writer::tag('span', $content, array('style' => $style)); + } + + /** + * Helper function to render the font elements. + * + * @param \mod_customcert\edit_element_form $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', 'size', get_string('fontsize', 'customcert'), \mod_customcert\certificate::get_font_sizes()); + $mform->setType('size', PARAM_INT); + $mform->setDefault('size', 12); + $mform->addHelpButton('size', 'fontsize', 'customcert'); + } + + /** + * Helper function to render the colour elements. + * + * @param \mod_customcert\edit_element_form $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 \mod_customcert\edit_element_form $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'); + $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'); + $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 (!\mod_customcert\element_helper::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'); + } + // 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->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; + } +} diff --git a/load_template_form.php b/classes/load_template_form.php similarity index 79% rename from load_template_form.php rename to classes/load_template_form.php index bb109fc..961cc0d 100644 --- a/load_template_form.php +++ b/classes/load_template_form.php @@ -14,10 +14,13 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace mod_customcert; + defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.'); require_once($CFG->libdir . '/formslib.php'); + /** * The form for loading customcert templates. * @@ -25,27 +28,25 @@ require_once($CFG->libdir . '/formslib.php'); * @copyright 2013 Mark Nelson * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class mod_customcert_load_template_form extends moodleform { +class load_template_form extends \moodleform { /** * Form definition. */ public function definition() { + global $DB; + $mform =& $this->_form; $mform->addElement('header', 'loadtemplateheader', get_string('loadtemplate', 'customcert')); + $templates = $DB->get_records_menu('customcert_templates', + array('contextid' => \CONTEXT_SYSTEM::instance()->id), 'name ASC', 'id, name'); + $group = array(); - $group[] = $mform->createElement('select', 'template', '', $this->_customdata['templates']); + $group[] = $mform->createElement('select', 'ltid', '', $templates); $group[] = $mform->createElement('submit', 'loadtemplatesubmit', get_string('load', 'customcert')); - $mform->addElement('group', 'loadtemplategroup', '', $group, '', false); - - // Set the type. - $mform->setType('template', PARAM_INT); - - $mform->addElement('hidden', 'cmid'); - $mform->setType('cmid', PARAM_INT); - $mform->setDefault('cmid', $this->_customdata['cmid']); + $mform->setType('ltid', PARAM_INT); } } diff --git a/classes/page_helper.php b/classes/page_helper.php new file mode 100644 index 0000000..4490194 --- /dev/null +++ b/classes/page_helper.php @@ -0,0 +1,61 @@ +. + +/** + * Provides useful functions related to setting up the page. + * + * @package mod_customcert + * @copyright 2016 Mark Nelson + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_customcert; + +defined('MOODLE_INTERNAL') || die(); + +/** + * Class helper. + * + * Provides useful functions. + */ +class page_helper { + + /** + * Sets up the page variables. + * + * @param \moodle_url $pageurl + * @param \context $context + * @param string $title the page title + */ + public static function page_setup($pageurl, $context, $title) { + global $COURSE, $PAGE, $SITE; + + $PAGE->set_url($pageurl); + $PAGE->set_context($context); + $PAGE->set_title(format_string($title)); + + // If we are in the system context then we are managing templates, and we want to show that in the navigation. + if ($context->contextlevel == CONTEXT_SYSTEM) { + $PAGE->set_pagelayout('admin'); + $PAGE->set_heading($SITE->fullname); + + $urloverride = new \moodle_url('/admin/settings.php?section=modsettingcustomcert'); + \navigation_node::override_active_url($urloverride); + } else { + $PAGE->set_heading(format_string($COURSE->fullname)); + } + } +} diff --git a/classes/template.php b/classes/template.php new file mode 100644 index 0000000..8081bb5 --- /dev/null +++ b/classes/template.php @@ -0,0 +1,455 @@ +. + +/** + * Class represents a customcert template. + * + * @copyright 2015 Mark Nelson + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_customcert; + +defined('MOODLE_INTERNAL') || die(); + +/** + * Class represents a customcert template. + * + * @copyright 2016 Mark Nelson + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class template { + + /** + * @var int $id The id of the template. + */ + protected $id; + + /** + * @var string $name The name of this template + */ + protected $name; + + /** + * @var int $contextid The context id of this template + */ + protected $contextid; + + /** + * The constructor. + * + * @param \stdClass $template + */ + public function __construct($template) { + $this->id = $template->id; + $this->name = $template->name; + $this->contextid = $template->contextid; + } + + /** + * Handles saving data. + * + * @param \stdClass $data the template data + */ + public function save($data) { + global $DB; + + $savedata = new \stdClass(); + $savedata->id = $this->id; + $savedata->name = $data->name; + $savedata->timemodified= time(); + + $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. + $pagenumber = 1; + // Get the max page number. + $sql = "SELECT MAX(pagenumber) as maxpage + FROM {customcert_pages} cp + WHERE cp.templateid = :templateid"; + if ($maxpage = $DB->get_record_sql($sql, array('templateid' => $this->id))) { + $pagenumber = $maxpage->maxpage + 1; + } + + // New page creation. + $page = new \stdClass(); + $page->templateid = $this->id; + $page->width = '210'; + $page->height = '297'; + $page->pagenumber = $pagenumber; + $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); + } + } + } + + /** + * Handles deleting the template. + * + * @return bool return true if the deletion was successful, false otherwise + */ + public function delete() { + global $CFG, $DB; + + // 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::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::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 pagenumber = pagenumber - 1 + WHERE templateid = :templateid + AND pagenumber > :pagenumber"; + $DB->execute($sql, array('templateid' => $this->id, 'pagenumber' => $page->pagenumber)); + } + + /** + * 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::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. + * + * @param bool $preview true if it is a preview, false otherwise + */ + public function generate_pdf($preview = false) { + global $CFG, $DB; + + require_once($CFG->libdir . '/pdflib.php'); + + // 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), 'pagenumber ASC')) { + // Create the pdf object. + $pdf = new \pdf(); + + // 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); + } + } + + $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, '.'); + $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::instance($element)) { + $e->render($pdf, $preview); + } + } + } + } + $pdf->Output($filename, 'D'); + } + } + + /** + * Handles moving the certificate page up. + * + * @param int $pageid + */ + public function move_page_up($pageid) { + global $DB; + + if ($movecertpage = $DB->get_record('customcert_pages', array('id' => $pageid))) { + $swapcertpage = $DB->get_record('customcert_pages', array('pagenumber' => $movecertpage->pagenumber - 1)); + } + + // Check that there is a page to move, and a page to swap it with. + if (isset($swapcertpage) && $movecertpage) { + $DB->set_field('customcert_pages', 'pagenumber', $swapcertpage->pagenumber, array('id' => $movecertpage->id)); + $DB->set_field('customcert_pages', 'pagenumber', $movecertpage->pagenumber, array('id' => $swapcertpage->id)); + } + } + + /** + * Handles moving the certificate page down. + * + * @param int $pageid + */ + public function move_page_down($pageid) { + global $DB; + + if ($movecertpage = $DB->get_record('customcert_pages', array('id' => $pageid))) { + $swapcertpage = $DB->get_record('customcert_pages', array('pagenumber' => $movecertpage->pagenumber + 1)); + } + + // Check that there is a page to move, and a page to swap it with. + if (isset($swapcertpage) && $movecertpage) { + $DB->set_field('customcert_pages', 'pagenumber', $swapcertpage->pagenumber, array('id' => $movecertpage->id)); + $DB->set_field('customcert_pages', 'pagenumber', $movecertpage->pagenumber, array('id' => $swapcertpage->id)); + } + } + + /** + * Handles moving the certificate element up. + * + * @param int $elementid + */ + public function move_element_up($elementid) { + global $DB; + + if ($movecertelement = $DB->get_record('customcert_elements', array('id' => $elementid))) { + $swapcertelement = $DB->get_record('customcert_elements', array('sequence' => $movecertelement->sequence - 1)); + } + + // Check that there is an element to move, and an element to swap it with. + if (isset($swapcertelement) && $movecertelement) { + $DB->set_field('customcert_elements', 'sequence', $swapcertelement->sequence, array('id' => $movecertelement->id)); + $DB->set_field('customcert_elements', 'sequence', $movecertelement->sequence, array('id' => $swapcertelement->id)); + } + } + + /** + * Handles moving the certificate element down. + * + * @param int $elementid + */ + public function move_element_down($elementid) { + global $DB; + + if ($movecertelement = $DB->get_record('customcert_elements', array('id' => $elementid))) { + $swapcertelement = $DB->get_record('customcert_elements', array('sequence' => $movecertelement->sequence + 1)); + } + + // Check that there is an element to move, and an element to swap it with. + if (isset($swapcertelement) && $movecertelement) { + $DB->set_field('customcert_elements', 'sequence', $swapcertelement->sequence, array('id' => $movecertelement->id)); + $DB->set_field('customcert_elements', 'sequence', $movecertelement->sequence, array('id' => $swapcertelement->id)); + } + } + + /** + * Returns the id of the template. + * + * @return int the id of the template + */ + public function get_id() { + return $this->id; + } + + /** + * Returns the name of the template. + * + * @return string the name of the template + */ + public function get_name() { + return $this->name; + } + + /** + * Returns the context id. + * + * @return int the context id + */ + public function get_contextid() { + return $this->contextid; + } + + /** + * Returns the context id. + * + * @return \context the context + */ + public function get_context() { + return \context::instance_by_id($this->contextid); + } + + /** + * Returns the context id. + * + * @return \context_module|null the context module, null if there is none + */ + public function get_cm() { + $context = $this->get_context(); + if ($context->contextlevel === CONTEXT_MODULE) { + return get_coursemodule_from_id('customcert', $context->instanceid, 0, false, MUST_EXIST); + } + + return null; + } + + /** + * Ensures the user has the proper capabilities to manage this template. + * + * @throws \required_capability_exception if the user does not have the necessary capabilities (ie. Fred) + */ + public function require_manage() { + require_capability('mod/customcert:manage', $this->get_context()); + } + + /** + * Creates a template. + * + * @param string $templatename the name of the template + * @param int $contextid the context id + * @return \mod_customcert\template the template object + */ + public static function create($templatename, $contextid) { + global $DB; + + $template = new \stdClass(); + $template->name = $templatename; + $template->contextid = $contextid; + $template->timecreated = time(); + $template->timemodified = $template->timecreated; + $template->id = $DB->insert_record('customcert_templates', $template); + + return new \mod_customcert\template($template); + } +} diff --git a/upload_image_form.php b/classes/upload_image_form.php similarity index 88% rename from upload_image_form.php rename to classes/upload_image_form.php index 75afa77..7caee4e 100644 --- a/upload_image_form.php +++ b/classes/upload_image_form.php @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace mod_customcert; + defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.'); require_once($CFG->libdir.'/formslib.php'); @@ -25,10 +27,10 @@ require_once($CFG->libdir.'/formslib.php'); * @copyright 2013 Mark Nelson * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class mod_customcert_upload_image_form extends moodleform { +class upload_image_form extends \moodleform { /** @var array the filemanager options */ - private $filemanageroptions = array(); + protected $filemanageroptions = array(); /** * Form definition. @@ -54,7 +56,7 @@ class mod_customcert_upload_image_form extends moodleform { // Editing existing instance - copy existing files into draft area. $draftitemid = file_get_submitted_draft_itemid('customcertimage'); - file_prepare_draft_area($draftitemid, context_system::instance()->id, 'mod_customcert', 'image', 0, $this->filemanageroptions); + file_prepare_draft_area($draftitemid, \context_system::instance()->id, 'mod_customcert', 'image', 0, $this->filemanageroptions); $element = $mform->getElement('customcertimage'); $element->setValue($draftitemid); } diff --git a/db/access.php b/db/access.php index fb6e789..407e96b 100644 --- a/db/access.php +++ b/db/access.php @@ -52,7 +52,7 @@ $capabilities = array( 'mod/customcert:manage' => array( 'captype' => 'write', - 'contextlevel' => CONTEXT_MODULE, + 'contextlevel' => CONTEXT_COURSE, CONTEXT_SYSTEM, 'archetypes' => array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, diff --git a/db/install.xml b/db/install.xml index 913765a..f252c25 100644 --- a/db/install.xml +++ b/db/install.xml @@ -8,6 +8,7 @@ + @@ -18,6 +19,20 @@ + + + + + + + + + + + + + +
@@ -36,7 +51,7 @@
- + @@ -47,7 +62,7 @@ - +
@@ -73,56 +88,5 @@
- - - - - - - - - - -
- - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - -
diff --git a/db/upgrade.php b/db/upgrade.php deleted file mode 100644 index 033528f..0000000 --- a/db/upgrade.php +++ /dev/null @@ -1,133 +0,0 @@ -. - -/** - * This file keeps track of upgrades to the customcert module - * - * @package mod_customcert - * @copyright 2015 Shamim Rezaie - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -function xmldb_customcert_upgrade($oldversion=0) { - - global $CFG, $DB; - $dbman = $DB->get_manager(); - - if ($oldversion < 2015073000) { - // Add the margin fields to customcert_pages table - $table = new xmldb_table('customcert_pages'); - $field = new xmldb_field('margin', XMLDB_TYPE_INTEGER, 10, null, null, null, 0, 'height'); - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // Add the margin fields to customcert_template_pages table - $table = new xmldb_table('customcert_template_pages'); - $field = new xmldb_field('margin', XMLDB_TYPE_INTEGER, 10, null, null, null, 0, 'height'); - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // Retrieve the customcert_elements table to add some elements to it - $table = new xmldb_table('customcert_elements'); - // Add the width fields to customcert_elements table - $field = new xmldb_field('width', XMLDB_TYPE_INTEGER, 10, null, null, null, 0, 'posy'); - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - // Add the refpoint fields to customcert_elements table. - $field = new xmldb_field('refpoint', XMLDB_TYPE_INTEGER, 4, null, null, null, 0, 'width'); - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - // Add the align fields to customcert_elements table. - $field = new xmldb_field('align', XMLDB_TYPE_CHAR, 1, null, null, null, 0, 'refpoint'); - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // Retrieve the customcert_template_elements table to add some elements to it - $table = new xmldb_table('customcert_template_elements'); - // Add the width fields to customcert_template_elements table - $field = new xmldb_field('width', XMLDB_TYPE_INTEGER, 10, null, null, null, 0, 'posy'); - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - // Add the refpoint fields to customcert_template_elements table. - $field = new xmldb_field('refpoint', XMLDB_TYPE_INTEGER, 4, null, null, null, 0, 'width'); - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - // Add the align fields to customcert_template_elements table. - $field = new xmldb_field('align', XMLDB_TYPE_CHAR, 1, null, null, null, 0, 'refpoint'); - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // Customcert savepoint reached. - upgrade_mod_savepoint(true, 2015073000, 'customcert'); - } - - if ($oldversion < 2015120800) { - // Remove the align column from both the 'customcert_elements' and 'customcert_template_elements' table. - $table = new xmldb_table('customcert_elements'); - $field = new xmldb_field('align'); - if ($dbman->field_exists($table, $field)) { - $dbman->drop_field($table, $field); - } - - $table = new xmldb_table('customcert_template_elements'); - if ($dbman->field_exists($table, $field)) { - $dbman->drop_field($table, $field); - } - - // Customcert savepoint reached. - upgrade_mod_savepoint(true, 2015120800, 'customcert'); - } - - if ($oldversion < 2015120801) { - // Rename the 'margin' field to 'rightmargin' in the 'customcert_pages' and 'customcert_template_pages' tables. - $table = new xmldb_table('customcert_pages'); - $field = new xmldb_field('margin', XMLDB_TYPE_INTEGER, 10, null, null, null, 0, 'height'); - if ($dbman->field_exists($table, $field)) { - $dbman->rename_field($table, $field, 'rightmargin'); - } - - $table = new xmldb_table('customcert_template_pages'); - if ($dbman->field_exists($table, $field)) { - $dbman->rename_field($table, $field, 'rightmargin'); - } - - // Add 'leftmargin' fields to the 'customcert_pages' and 'customcert_template_pages' tables. - $table = new xmldb_table('customcert_pages'); - $field = new xmldb_field('leftmargin', XMLDB_TYPE_INTEGER, 10, null, null, null, 0, 'height'); - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - $table = new xmldb_table('customcert_template_pages'); - if (!$dbman->field_exists($table, $field)) { - $dbman->add_field($table, $field); - } - - // Customcert savepoint reached. - upgrade_mod_savepoint(true, 2015120801, 'customcert'); - } - - return true; -} diff --git a/edit.php b/edit.php index a794a51..0284f47 100644 --- a/edit.php +++ b/edit.php @@ -23,12 +23,8 @@ */ require_once('../../config.php'); -require_once($CFG->dirroot . '/mod/customcert/locallib.php'); -require_once($CFG->dirroot . '/mod/customcert/edit_form.php'); -require_once($CFG->dirroot . '/mod/customcert/load_template_form.php'); -require_once($CFG->dirroot . '/mod/customcert/save_template_form.php'); -$cmid = required_param('cmid', PARAM_INT); +$tid = optional_param('tid', 0, PARAM_INT); $moveup = optional_param('moveup', 0, PARAM_INT); $movedown = optional_param('movedown', 0, PARAM_INT); $emoveup = optional_param('emoveup', 0, PARAM_INT); @@ -37,99 +33,97 @@ $deleteelement = optional_param('deleteelement', 0, PARAM_INT); $deletepage = optional_param('deletepage', 0, PARAM_INT); $confirm = optional_param('confirm', 0, PARAM_INT); -$cm = get_coursemodule_from_id('customcert', $cmid, 0, false, MUST_EXIST); -$course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST); -$customcert = $DB->get_record('customcert', array('id' => $cm->instance), '*', MUST_EXIST); -$context = context_module::instance($cm->id); - -require_login($course, false, $cm); - -require_capability('mod/customcert:manage', $context); - -// The form for loading a customcert templates. -$templates = customcert_get_templates(); -$loadtemplateform = new mod_customcert_load_template_form('', array('cmid' => $cm->id, 'templates' => $templates)); -// The form for saving the current information as a template. -$savetemplateform = new mod_customcert_save_template_form('', array('cmid' => $cm->id)); - -// Check if they chose to load a customcert template and redirect. -if ($data = $loadtemplateform->get_data()) { - $url = new moodle_url('/mod/customcert/load_template.php', array('cmid' => $cmid, 'tid' => $data->template)); - redirect($url); +// Edit an existing template. +if ($tid) { + // Create the template object. + $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/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/customcert/edit.php', array('contextid' => $contextid)); } -// Check if they chose to save the current information and redirect. -if ($data = $savetemplateform->get_data()) { - $url = new moodle_url('/mod/customcert/save_template.php', array('cmid' => $cmid, 'name' => $data->name)); - redirect($url); +$context = context::instance_by_id($contextid); +if ($context->contextlevel == CONTEXT_MODULE) { + $cm = get_coursemodule_from_id('customcert', $context->instanceid, 0, false, MUST_EXIST); + require_login($cm->course, false, $cm); +} else { + require_login(); +} +require_capability('mod/customcert:manage', $context); + +// Set up the page. +\mod_customcert\page_helper::page_setup($pageurl, $context, get_string('editcustomcert', 'customcert')); + +if ($context->contextlevel == CONTEXT_SYSTEM) { + // We are managing a template - add some navigation. + $PAGE->navbar->add(get_string('managetemplates', 'customcert'), + new moodle_url('/mod/customcert/manage_templates.php')); + $PAGE->navbar->add(get_string('editcustomcert', 'customcert')); +} + +// The form for loading a customcert templates. +if ($tid && $DB->count_records('customcert_templates', array('contextid' => CONTEXT_SYSTEM::instance()->id)) > 0) { + $loadtemplateurl = new moodle_url('/mod/customcert/load_template.php', array('tid' => $tid)); + $loadtemplateform = new \mod_customcert\load_template_form($loadtemplateurl); } // Flag to determine if we are deleting anything. $deleting = false; -// Check if they are moving a custom certificate page. -if ((!empty($moveup)) || (!empty($movedown))) { - // Check if we are moving a page up. - if (!empty($moveup)) { - if ($movecertpage = $DB->get_record('customcert_pages', array('id' => $moveup))) { - $swapcertpage = $DB->get_record('customcert_pages', array('pagenumber' => $movecertpage->pagenumber - 1)); +if ($tid) { + // Check if they are moving a custom certificate page. + if ((!empty($moveup)) || (!empty($movedown))) { + // Check if we are moving a page up. + if (!empty($moveup)) { + $template->move_page_up($moveup); + } else { // Must be moving a page down. + $template->move_page_down($movedown); } - } else { // Must be moving a page down. - if ($movecertpage = $DB->get_record('customcert_pages', array('id' => $movedown))) { - $swapcertpage = $DB->get_record('customcert_pages', array('pagenumber' => $movecertpage->pagenumber + 1)); + } else if ((!empty($emoveup)) || (!empty($emovedown))) { // Check if we are moving a custom certificate element. + // Check if we are moving an element up. + if (!empty($emoveup)) { + $template->move_element_up($emoveup); + } else { // Must be moving a element down. + $template->move_element_down($emovedown); } - } - // Check that there is a page to move, and a page to swap it with. - if ($swapcertpage && $movecertpage) { - $DB->set_field('customcert_pages', 'pagenumber', $swapcertpage->pagenumber, array('id' => $movecertpage->id)); - $DB->set_field('customcert_pages', 'pagenumber', $movecertpage->pagenumber, array('id' => $swapcertpage->id)); - } -} else if ((!empty($emoveup)) || (!empty($emovedown))) { // Check if we are moving a custom certificate element. - // Check if we are moving an element up. - if (!empty($emoveup)) { - if ($movecertelement = $DB->get_record('customcert_elements', array('id' => $emoveup))) { - $swapcertelement = $DB->get_record('customcert_elements', array('sequence' => $movecertelement->sequence - 1)); + } else if (!empty($deletepage)) { // Check if we are deleting a page. + if (!empty($confirm)) { // Check they have confirmed the deletion. + $template->delete_page($deletepage); + } 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, + 'deletepage' => $deletepage, + 'confirm' => 1, + 'sesskey' => sesskey())); } - } else { // Must be moving a element down. - if ($movecertelement = $DB->get_record('customcert_elements', array('id' => $emovedown))) { - $swapcertelement = $DB->get_record('customcert_elements', array('sequence' => $movecertelement->sequence + 1)); + } else if (!empty($deleteelement)) { // Check if we are deleting an element. + if (!empty($confirm)) { // Check they have confirmed the deletion. + $template->delete_element($deleteelement); + } 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, + 'deleteelement' => $deleteelement, + 'confirm' => 1, + 'sesskey' => sesskey())); } } - // Check that there is an element to move, and an element to swap it with. - if ($swapcertelement && $movecertelement) { - $DB->set_field('customcert_elements', 'sequence', $swapcertelement->sequence, array('id' => $movecertelement->id)); - $DB->set_field('customcert_elements', 'sequence', $movecertelement->sequence, array('id' => $swapcertelement->id)); - } -} else if (!empty($deletepage)) { // Check if we are deleting a page. - if (!empty($confirm)) { // Check they have confirmed the deletion. - customcert_delete_page($deletepage); - } 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('cmid' => $cm->id)); - $yesurl = new moodle_url('/mod/customcert/edit.php', array('cmid' => $cm->id, - 'deletepage' => $deletepage, - 'confirm' => 1, - 'sesskey' => sesskey())); - } -} else if (!empty($deleteelement)) { // Check if we are deleting an element. - if (!empty($confirm)) { // Check they have confirmed the deletion. - customcert_delete_element($deleteelement); - } 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('cmid' => $cm->id)); - $yesurl = new moodle_url('/mod/customcert/edit.php', array('cmid' => $cm->id, - 'deleteelement' => $deleteelement, - 'confirm' => 1, - 'sesskey' => sesskey())); - } } // Check if we are deleting either a page or an element. @@ -138,8 +132,6 @@ if ($deleting) { $strheading = get_string('deleteconfirm', 'customcert'); $PAGE->navbar->add($strheading); $PAGE->set_title($strheading); - $PAGE->set_heading($course->fullname); - $PAGE->set_url('/mod/customcert/edit.php', array('cmid' => $cmid)); echo $OUTPUT->header(); echo $OUTPUT->heading($strheading); echo $OUTPUT->confirm($message, $yesurl, $nourl); @@ -147,17 +139,57 @@ if ($deleting) { exit(); } -$mform = new mod_customcert_edit_form('', array('customcertid' => $customcert->id, - 'cmid' => $cm->id, - 'course' => $course)); +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())); +} else { + $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_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; + + // We may also have clicked to add an element, so these need changing as well. + if (isset($data->element_1) && isset($data->addelement_1)) { + $element = 'element_' . $pageid; + $addelement = 'addelement_' . $pageid; + $data->$element = $data->element_1; + $data->$addelement = $data->addelement_1; + + // 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_1); + unset($data->addelement_1); + } + + $data->$width = $data->pagewidth_1; + $data->$height = $data->pageheight_1; + $data->$leftmargin = $data->pageleftmargin_1; + $data->$rightmargin = $data->pagerightmargin_1; + } + + // Save any data for the template. + $template->save($data); + // Save any page data. - customcert_save_page_data($data); + $template->save_page($data); // Check if we are adding a page. if (!empty($data->addcertpage)) { - customcert_add_page($data); + $template->add_page(); } // Loop through the data. @@ -171,7 +203,7 @@ if ($data = $mform->get_data()) { $element = $data->$element; // Create the URL to redirect to to add this element. $params = array(); - $params['cmid'] = $cmid; + $params['tid'] = $template->get_id(); $params['action'] = 'add'; $params['element'] = $element; $params['pageid'] = $pageid; @@ -182,23 +214,18 @@ if ($data = $mform->get_data()) { // Check if we want to preview this custom certificate. if (!empty($data->previewbtn)) { - customcert_generate_pdf($customcert, true); + $template->generate_pdf(true); } // Redirect to the editing page to show form with recent updates. - $url = new moodle_url('/mod/customcert/edit.php', array('cmid' => $cmid)); + $url = new moodle_url('/mod/customcert/edit.php', array('tid' => $template->get_id())); redirect($url); } -$PAGE->set_title(get_string('editcustomcert', 'customcert', format_string($customcert->name))); -$PAGE->set_heading($course->fullname); -$PAGE->set_url('/mod/customcert/edit.php', array('cmid' => $cmid)); - echo $OUTPUT->header(); echo $OUTPUT->heading(get_string('editcustomcert', 'customcert')); $mform->display(); -if (!empty($templates)) { +if (isset($loadtemplateform)) { $loadtemplateform->display(); } -$savetemplateform->display(); echo $OUTPUT->footer(); diff --git a/edit_element.php b/edit_element.php index ac25515..eac6125 100644 --- a/edit_element.php +++ b/edit_element.php @@ -23,50 +23,56 @@ */ require_once('../../config.php'); -require_once($CFG->dirroot . '/mod/customcert/edit_element_form.php'); -$cmid = required_param('cmid', PARAM_INT); +$tid = required_param('tid', PARAM_INT); $action = required_param('action', PARAM_ALPHA); -$cm = get_coursemodule_from_id('customcert', $cmid, 0, false, MUST_EXIST); -$course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST); -$customcert = $DB->get_record('customcert', array('id' => $cm->instance), '*', MUST_EXIST); -$context = context_module::instance($cm->id); +$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 ($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, 'cmid' => $cmid, 'action' => $action)); + $pageurl = new moodle_url('/mod/customcert/edit_element.php', array('id' => $id, 'tid' => $tid, 'action' => $action)); } else { // Must be adding an element. - // Page id must be supplied in order to add an element. + // We need to supply what element we want added to what page. $pageid = required_param('pageid', PARAM_INT); - // Create the new element object, will have no data. $element = new stdClass(); $element->element = required_param('element', PARAM_ALPHA); - // Set the page url. - $params = array(); - $params['cmid'] = $cmid; - $params['action'] = 'add'; - $params['element'] = $element->element; - $params['pageid'] = $pageid; - $pageurl = new moodle_url('/mod/customcert/edit_element.php', $params); + $pageurl = new moodle_url('/mod/customcert/edit_element.php', array('tid' => $tid, 'element' => $element->element, + 'pageid' => $pageid, 'action' => $action)); } -require_login($course, false, $cm); +// Set up the page. +$title = get_string('editelement', 'customcert'); +\mod_customcert\page_helper::page_setup($pageurl, $template->get_context(), $title); -require_capability('mod/customcert:manage', $context); +// 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($title); -$PAGE->set_heading($course->fullname); -$PAGE->set_title(get_string('editcustomcert', 'customcert', format_string($customcert->name))); -$PAGE->set_url($pageurl); - -$mform = new mod_customcert_edit_element_form($pageurl, array('element' => $element, 'course' => $course, - 'cmid' => $cmid, 'action' => $action)); +$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('cmid' => $cmid)); + $url = new moodle_url('/mod/customcert/edit.php', array('tid' => $tid)); redirect($url); } @@ -80,15 +86,15 @@ if ($data = $mform->get_data()) { // Set the element variable. $data->element = $element->element; // Get an instance of the element class. - if ($e = customcert_get_element_instance($data)) { + if ($e = \mod_customcert\element::instance($data)) { $e->save_form_elements($data); } - $url = new moodle_url('/mod/customcert/edit.php', array('cmid' => $cmid)); + $url = new moodle_url('/mod/customcert/edit.php', array('tid' => $tid)); redirect($url); } echo $OUTPUT->header(); -echo $OUTPUT->heading(get_string('editcustomcert', 'customcert')); +echo $OUTPUT->heading(get_string('editelement', 'customcert')); $mform->display(); echo $OUTPUT->footer(); diff --git a/element/border/classes/element.php b/element/border/classes/element.php index a61eece..a27d48d 100644 --- a/element/border/classes/element.php +++ b/element/border/classes/element.php @@ -30,7 +30,7 @@ class element extends \mod_customcert\element { /** * This function renders the form elements when adding a customcert element. * - * @param \mod_customcert_edit_element_form $mform the edit_form instance + * @param \mod_customcert\edit_element_form $mform the edit_form instance */ public function render_form_elements($mform) { // We want to define the width of the border. @@ -39,7 +39,7 @@ class element extends \mod_customcert\element { $mform->addHelpButton('width', 'width', 'customcertelement_border'); // The only other thing to define is the colour we want the border to be. - parent::render_form_element_colour($mform); + \mod_customcert\element_helper::render_form_element_colour($mform); } /** @@ -62,6 +62,8 @@ class element extends \mod_customcert\element { * * 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 ''; @@ -84,7 +86,7 @@ class element extends \mod_customcert\element { } // Validate the colour. - $errors += $this->validate_form_element_colour($data); + $errors += \mod_customcert\element_helper::validate_form_element_colour($data); return $errors; } @@ -92,7 +94,7 @@ class element extends \mod_customcert\element { /** * Sets the data on the form when editing an element. * - * @param \mod_customcert_edit_element_form $mform the edit_form instance + * @param \mod_customcert\edit_element_form $mform the edit_form instance */ public function definition_after_data($mform) { if (!empty($this->element->data)) { diff --git a/element/border/version.php b/element/border/version.php index 2a91bfb..f5ca1d2 100644 --- a/element/border/version.php +++ b/element/border/version.php @@ -24,6 +24,6 @@ defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.'); -$plugin->version = 2015121400; // The current module version (Date: YYYYMMDDXX). +$plugin->version = 2016021900; // The current module version (Date: YYYYMMDDXX). $plugin->requires = 2015051100; // Requires this Moodle version (2.9). $plugin->component = 'customcertelement_border'; diff --git a/element/categoryname/classes/element.php b/element/categoryname/classes/element.php index 15b35d0..c9d9dd4 100644 --- a/element/categoryname/classes/element.php +++ b/element/categoryname/classes/element.php @@ -38,7 +38,7 @@ class element extends \mod_customcert\element { $categoryname = $DB->get_field('course_categories', 'name', array('id' => $COURSE->category), MUST_EXIST); - parent::render_content($pdf, $categoryname); + \mod_customcert\element_helper::render_content($pdf, $this, $categoryname); } /** @@ -46,12 +46,14 @@ class element extends \mod_customcert\element { * * 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, $COURSE; $categoryname = $DB->get_field('course_categories', 'name', array('id' => $COURSE->category), MUST_EXIST); - return parent::render_html_content($categoryname); + return \mod_customcert\element_helper::render_html_content($this, $categoryname); } } diff --git a/element/categoryname/version.php b/element/categoryname/version.php index 2cd59f9..2491451 100644 --- a/element/categoryname/version.php +++ b/element/categoryname/version.php @@ -24,6 +24,6 @@ defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.'); -$plugin->version = 2015121400; // The current module version (Date: YYYYMMDDXX). +$plugin->version = 2016021900; // The current module version (Date: YYYYMMDDXX). $plugin->requires = 2015051100; // Requires this Moodle version (2.9). $plugin->component = 'customcertelement_categoryname'; diff --git a/element/code/classes/element.php b/element/code/classes/element.php index 7849dda..b58cdf3 100644 --- a/element/code/classes/element.php +++ b/element/code/classes/element.php @@ -37,7 +37,7 @@ class element extends \mod_customcert\element { global $DB, $USER; if ($preview) { - $code = customcert_generate_code(); + $code = \mod_customcert\certificate::generate_code(); } else { // Get the page. $page = $DB->get_record('customcert_pages', array('id' => $this->element->pageid), '*', MUST_EXIST); @@ -46,7 +46,7 @@ class element extends \mod_customcert\element { $code = $issue->code; } - parent::render_content($pdf, $code); + \mod_customcert\element_helper::render_content($pdf, $this, $code); } /** @@ -54,10 +54,12 @@ class element extends \mod_customcert\element { * * 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 = customcert_generate_code(); + $code = \mod_customcert\certificate::generate_code(); - return parent::render_html_content($code); + return \mod_customcert\element_helper::render_html_content($this, $code); } } diff --git a/element/code/version.php b/element/code/version.php index f6dd75f..89e0428 100644 --- a/element/code/version.php +++ b/element/code/version.php @@ -24,6 +24,6 @@ defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.'); -$plugin->version = 2015121400; // The current module version (Date: YYYYMMDDXX). +$plugin->version = 2016021900; // The current module version (Date: YYYYMMDDXX). $plugin->requires = 2015051100; // Requires this Moodle version (2.9). $plugin->component = 'customcertelement_code'; diff --git a/element/coursename/classes/element.php b/element/coursename/classes/element.php index 8910b49..a00ca08 100644 --- a/element/coursename/classes/element.php +++ b/element/coursename/classes/element.php @@ -36,7 +36,7 @@ class element extends \mod_customcert\element { public function render($pdf, $preview) { global $COURSE; - parent::render_content($pdf, $COURSE->fullname); + \mod_customcert\element_helper::render_content($pdf, $this, $COURSE->fullname); } /** @@ -44,10 +44,12 @@ class element extends \mod_customcert\element { * * 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; - return parent::render_html_content($COURSE->fullname); + return \mod_customcert\element_helper::render_html_content($this, $COURSE->fullname); } } diff --git a/element/coursename/version.php b/element/coursename/version.php index c921803..dc13337 100644 --- a/element/coursename/version.php +++ b/element/coursename/version.php @@ -24,6 +24,6 @@ defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.'); -$plugin->version = 2015121400; // The current module version (Date: YYYYMMDDXX). +$plugin->version = 2016021900; // The current module version (Date: YYYYMMDDXX). $plugin->requires = 2015051100; // Requires this Moodle version (2.9). $plugin->component = 'customcertelement_coursename'; diff --git a/element/date/classes/element.php b/element/date/classes/element.php index 48633db..4b8a566 100644 --- a/element/date/classes/element.php +++ b/element/date/classes/element.php @@ -40,7 +40,7 @@ class element extends \mod_customcert\element { /** * This function renders the form elements when adding a customcert element. * - * @param \mod_customcert_edit_element_form $mform the edit_form instance + * @param \mod_customcert\edit_element_form $mform the edit_form instance */ public function render_form_elements($mform) { // Get the possible date options. @@ -129,7 +129,7 @@ class element extends \mod_customcert\element { // Ensure that a date has been set. if (!empty($date)) { - parent::render_content($pdf, $this->get_date_format_string($date, $dateformat)); + \mod_customcert\element_helper::render_content($pdf, $this, $this->get_date_format_string($date, $dateformat)); } } @@ -138,6 +138,8 @@ class element extends \mod_customcert\element { * * 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. @@ -149,13 +151,13 @@ class element extends \mod_customcert\element { $dateinfo = json_decode($this->element->data); $dateformat = $dateinfo->dateformat; - return parent::render_html_content($this->get_date_format_string(time(), $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 \mod_customcert_edit_element_form $mform the edit_form instance + * @param \mod_customcert\edit_element_form $mform the edit_form instance */ public function definition_after_data($mform) { // Set the item and format for this element. @@ -209,7 +211,7 @@ class element extends \mod_customcert\element { * @param string $dateformat * @return string */ - private function get_date_format_string($date, $dateformat) { + protected function get_date_format_string($date, $dateformat) { switch ($dateformat) { case 1: $certificatedate = userdate($date, '%B %d, %Y'); @@ -238,7 +240,7 @@ class element extends \mod_customcert\element { * @param int $day the day of the month * @return string the suffix. */ - private function get_ordinal_number_suffix($day) { + protected function get_ordinal_number_suffix($day) { if (!in_array(($day % 100), array(11, 12, 13))) { switch ($day % 10) { // Handle 1st, 2nd, 3rd. diff --git a/element/date/version.php b/element/date/version.php index 989fce5..4a68e10 100644 --- a/element/date/version.php +++ b/element/date/version.php @@ -24,6 +24,6 @@ defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.'); -$plugin->version = 2015121400; // The current module version (Date: YYYYMMDDXX). +$plugin->version = 2016021900; // The current module version (Date: YYYYMMDDXX). $plugin->requires = 2015051100; // Requires this Moodle version (2.9). $plugin->component = 'customcertelement_date'; diff --git a/element/grade/classes/element.php b/element/grade/classes/element.php index d3a93c9..7217fb0 100644 --- a/element/grade/classes/element.php +++ b/element/grade/classes/element.php @@ -39,7 +39,7 @@ class element extends \mod_customcert\element { /** * This function renders the form elements when adding a customcert element. * - * @param \mod_customcert_edit_element_form $mform the edit_form instance + * @param \mod_customcert\edit_element_form $mform the edit_form instance */ public function render_form_elements($mform) { // Get the grade items we can display. @@ -104,7 +104,7 @@ class element extends \mod_customcert\element { $grade = self::get_grade($gradeinfo, $USER->id); } - parent::render_content($pdf, $grade); + \mod_customcert\element_helper::render_content($pdf, $this, $grade); } /** @@ -112,6 +112,8 @@ class element extends \mod_customcert\element { * * 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; @@ -132,13 +134,13 @@ class element extends \mod_customcert\element { } $grade = grade_format_gradevalue('100', $courseitem, true, $gradeinfo->gradeformat, $decimals); - return parent::render_html_content($grade); + return \mod_customcert\element_helper::render_html_content($this, $grade); } /** * Sets the data on the form when editing an element. * - * @param \mod_customcert_edit_element_form $mform the edit_form instance + * @param \mod_customcert\edit_element_form $mform the edit_form instance */ public function definition_after_data($mform) { // Set the item and format for this element. diff --git a/element/grade/version.php b/element/grade/version.php index 3bd4ff2..1428b8d 100644 --- a/element/grade/version.php +++ b/element/grade/version.php @@ -24,6 +24,6 @@ defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.'); -$plugin->version = 2015121400; // The current module version (Date: YYYYMMDDXX). +$plugin->version = 2016021900; // The current module version (Date: YYYYMMDDXX). $plugin->requires = 2015051100; // Requires this Moodle version (2.9). $plugin->component = 'customcertelement_grade'; diff --git a/element/gradeitemname/classes/element.php b/element/gradeitemname/classes/element.php index 68e8958..d677f90 100644 --- a/element/gradeitemname/classes/element.php +++ b/element/gradeitemname/classes/element.php @@ -30,7 +30,7 @@ class element extends \mod_customcert\element { /** * This function renders the form elements when adding a customcert element. * - * @param \mod_customcert_edit_element_form $mform the edit_form instance + * @param \mod_customcert\edit_element_form $mform the edit_form instance */ public function render_form_elements($mform) { $mform->addElement('select', 'gradeitem', get_string('gradeitem', 'customcertelement_gradeitemname'), @@ -73,7 +73,7 @@ class element extends \mod_customcert\element { // Get the name of the item. $itemname = $DB->get_field($module->name, 'name', array('id' => $cm->instance), MUST_EXIST); - parent::render_content($pdf, $itemname); + \mod_customcert\element_helper::render_content($pdf, $this, $itemname); } } @@ -82,6 +82,8 @@ class element extends \mod_customcert\element { * * 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; @@ -95,14 +97,16 @@ class element extends \mod_customcert\element { // Get the name of the item. $itemname = $DB->get_field($module->name, 'name', array('id' => $cm->instance), MUST_EXIST); - return parent::render_html_content($itemname); + return \mod_customcert\element_helper::render_html_content($this, $itemname); } + + return ''; } /** * Sets the data on the form when editing an element. * - * @param \mod_customcert_edit_element_form $mform the edit_form instance + * @param \mod_customcert\edit_element_form $mform the edit_form instance */ public function definition_after_data($mform) { if (!empty($this->element->data)) { diff --git a/element/gradeitemname/version.php b/element/gradeitemname/version.php index fa61ac6..4b713bc 100644 --- a/element/gradeitemname/version.php +++ b/element/gradeitemname/version.php @@ -24,6 +24,6 @@ defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.'); -$plugin->version = 2015121400; // The current module version (Date: YYYYMMDDXX). +$plugin->version = 2016021900; // The current module version (Date: YYYYMMDDXX). $plugin->requires = 2015051100; // Requires this Moodle version (2.9). $plugin->component = 'customcertelement_gradeitemname'; diff --git a/element/image/classes/element.php b/element/image/classes/element.php index a9cacfc..43c6cfd 100644 --- a/element/image/classes/element.php +++ b/element/image/classes/element.php @@ -27,7 +27,7 @@ defined('MOODLE_INTERNAL') || die(); */ class element extends \mod_customcert\element { - private $filemanageroptions = array(); + protected $filemanageroptions = array(); /** * Constructor. @@ -49,7 +49,7 @@ class element extends \mod_customcert\element { /** * This function renders the form elements when adding a customcert element. * - * @param \mod_customcert_edit_element_form $mform the edit_form instance + * @param \mod_customcert\edit_element_form $mform the edit_form instance */ public function render_form_elements($mform) { $mform->addElement('select', 'image', get_string('image', 'customcertelement_image'), self::get_images()); @@ -99,7 +99,7 @@ class element extends \mod_customcert\element { } // Validate the position. - $errors += $this->validate_form_element_position($data); + $errors += \mod_customcert\element_helper::validate_form_element_position($data); return $errors; } @@ -114,7 +114,7 @@ class element extends \mod_customcert\element { global $COURSE; // Handle file uploads. - customcert_upload_imagefiles($data->customcertimage, \context_course::instance($COURSE->id)->id); + \mod_customcert\certificate::upload_imagefiles($data->customcertimage, \context_course::instance($COURSE->id)->id); parent::save_form_elements($data); } @@ -169,11 +169,13 @@ class element extends \mod_customcert\element { * * 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->element->data)) { - return; + return ''; } $imageinfo = json_decode($this->element->data); @@ -210,7 +212,7 @@ class element extends \mod_customcert\element { /** * Sets the data on the form when editing an element. * - * @param \mod_customcert_edit_element_form $mform the edit_form instance + * @param \mod_customcert\edit_element_form $mform the edit_form instance */ public function definition_after_data($mform) { global $COURSE; diff --git a/element/image/version.php b/element/image/version.php index f4c1b7c..8d5f090 100644 --- a/element/image/version.php +++ b/element/image/version.php @@ -24,6 +24,6 @@ defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.'); -$plugin->version = 2015121400; // The current module version (Date: YYYYMMDDXX). +$plugin->version = 2016021900; // The current module version (Date: YYYYMMDDXX). $plugin->requires = 2015051100; // Requires this Moodle version (2.9). $plugin->component = 'customcertelement_image'; diff --git a/element/studentname/classes/element.php b/element/studentname/classes/element.php index 0995021..1f870e4 100644 --- a/element/studentname/classes/element.php +++ b/element/studentname/classes/element.php @@ -36,7 +36,7 @@ class element extends \mod_customcert\element { public function render($pdf, $preview) { global $USER; - parent::render_content($pdf, fullname($USER)); + \mod_customcert\element_helper::render_content($pdf, $this, fullname($USER)); } /** @@ -44,10 +44,12 @@ class element extends \mod_customcert\element { * * 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 $USER; - return parent::render_html_content(fullname($USER)); + return \mod_customcert\element_helper::render_html_content($this, fullname($USER)); } } diff --git a/element/studentname/version.php b/element/studentname/version.php index b3551c0..466c77a 100644 --- a/element/studentname/version.php +++ b/element/studentname/version.php @@ -24,6 +24,6 @@ defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.'); -$plugin->version = 2015121400; // The current module version (Date: YYYYMMDDXX). +$plugin->version = 2016021900; // The current module version (Date: YYYYMMDDXX). $plugin->requires = 2015051100; // Requires this Moodle version (2.9). $plugin->component = 'customcertelement_studentname'; diff --git a/element/teachername/classes/element.php b/element/teachername/classes/element.php index 3dcffd6..286881c 100644 --- a/element/teachername/classes/element.php +++ b/element/teachername/classes/element.php @@ -30,7 +30,7 @@ class element extends \mod_customcert\element { /** * This function renders the form elements when adding a customcert element. * - * @param \mod_customcert_edit_element_form $mform the edit_form instance + * @param \mod_customcert\edit_element_form $mform the edit_form instance */ public function render_form_elements($mform) { $mform->addElement('select', 'teacher', get_string('teacher', 'customcertelement_teachername'), @@ -65,7 +65,7 @@ class element extends \mod_customcert\element { $teacher = $DB->get_record('user', array('id' => $this->element->data)); $teachername = fullname($teacher); - parent::render_content($pdf, $teachername); + \mod_customcert\element_helper::render_content($pdf, $this, $teachername); } /** @@ -73,6 +73,8 @@ class element extends \mod_customcert\element { * * 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; @@ -80,7 +82,7 @@ class element extends \mod_customcert\element { $teacher = $DB->get_record('user', array('id' => $this->element->data)); $teachername = fullname($teacher); - return parent::render_html_content($teachername); + return \mod_customcert\element_helper::render_html_content($this, $teachername); } /** @@ -88,15 +90,14 @@ class element extends \mod_customcert\element { * * @return array the list of teachers */ - private function get_list_of_teachers() { - // When editing this element the cmid will be present in the URL. - $cmid = required_param('cmid', PARAM_INT); + protected function get_list_of_teachers() { + global $PAGE; // The list of teachers to return. $teachers = array(); // Now return all users who can manage the customcert in this context. - if ($users = get_users_by_capability(\context_module::instance($cmid), 'mod/customcert:manage')) { + if ($users = get_users_by_capability($PAGE->context, 'mod/customcert:manage')) { foreach ($users as $user) { $teachers[$user->id] = fullname($user); } @@ -108,7 +109,7 @@ class element extends \mod_customcert\element { /** * Sets the data on the form when editing an element. * - * @param \mod_customcert_edit_element_form $mform the edit_form instance + * @param \mod_customcert\edit_element_form $mform the edit_form instance */ public function definition_after_data($mform) { if (!empty($this->element->data)) { diff --git a/element/teachername/version.php b/element/teachername/version.php index 8461365..4374044 100644 --- a/element/teachername/version.php +++ b/element/teachername/version.php @@ -24,6 +24,6 @@ defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.'); -$plugin->version = 2015121400; // The current module version (Date: YYYYMMDDXX). +$plugin->version = 2016021900; // The current module version (Date: YYYYMMDDXX). $plugin->requires = 2015051100; // Requires this Moodle version (2.9). $plugin->component = 'customcertelement_teachername'; diff --git a/element/text/classes/element.php b/element/text/classes/element.php index 98bc942..c025b05 100644 --- a/element/text/classes/element.php +++ b/element/text/classes/element.php @@ -30,7 +30,7 @@ class element extends \mod_customcert\element { /** * This function renders the form elements when adding a customcert element. * - * @param \mod_customcert_edit_element_form $mform the edit_form instance + * @param \mod_customcert\edit_element_form $mform the edit_form instance */ public function render_form_elements($mform) { $mform->addElement('textarea', 'text', get_string('text', 'customcertelement_text')); @@ -58,7 +58,7 @@ class element extends \mod_customcert\element { * @param bool $preview true if it is a preview, false otherwise */ public function render($pdf, $preview) { - parent::render_content($pdf, $this->element->data); + \mod_customcert\element_helper::render_content($pdf, $this, $this->element->data); } /** @@ -66,15 +66,17 @@ class element extends \mod_customcert\element { * * 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 parent::render_html_content($this->element->data); + return \mod_customcert\element_helper::render_html_content($this, $this->element->data); } /** * Sets the data on the form when editing an element. * - * @param \mod_customcert_edit_element_form $mform the edit_form instance + * @param \mod_customcert\edit_element_form $mform the edit_form instance */ public function definition_after_data($mform) { if (!empty($this->element->data)) { diff --git a/element/text/version.php b/element/text/version.php index a52ac27..e5d3335 100644 --- a/element/text/version.php +++ b/element/text/version.php @@ -24,6 +24,6 @@ defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.'); -$plugin->version = 2015121400; // The current module version (Date: YYYYMMDDXX). +$plugin->version = 2016021900; // The current module version (Date: YYYYMMDDXX). $plugin->requires = 2015051100; // Requires this Moodle version (2.9). $plugin->component = 'customcertelement_text'; diff --git a/element/userfield/classes/element.php b/element/userfield/classes/element.php index 4abeee0..5aa9d1c 100644 --- a/element/userfield/classes/element.php +++ b/element/userfield/classes/element.php @@ -30,7 +30,7 @@ class element extends \mod_customcert\element { /** * This function renders the form elements when adding a customcert element. * - * @param \mod_customcert_edit_element_form $mform the edit_form instance + * @param \mod_customcert\edit_element_form $mform the edit_form instance */ public function render_form_elements($mform) { // Get the user profile fields. @@ -103,7 +103,7 @@ class element extends \mod_customcert\element { $value = $USER->$field; } - parent::render_content($pdf, $value); + \mod_customcert\element_helper::render_content($pdf, $this, $value); } /** @@ -127,13 +127,13 @@ class element extends \mod_customcert\element { $value = $USER->$field; } - return parent::render_html_content($value); + return \mod_customcert\element_helper::render_html_content($this, $value); } /** * Sets the data on the form when editing an element. * - * @param \mod_customcert_edit_element_form $mform the edit_form instance + * @param \mod_customcert\edit_element_form $mform the edit_form instance */ public function definition_after_data($mform) { if (!empty($this->element->data)) { diff --git a/element/userfield/version.php b/element/userfield/version.php index e339838..47166cd 100644 --- a/element/userfield/version.php +++ b/element/userfield/version.php @@ -24,6 +24,6 @@ defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.'); -$plugin->version = 2015121400; // The current module version (Date: YYYYMMDDXX). +$plugin->version = 2016021900; // The current module version (Date: YYYYMMDDXX). $plugin->requires = 2015051100; // Requires this Moodle version (2.9). $plugin->component = 'customcertelement_userfield'; diff --git a/index.php b/index.php index 4b5d4dc..ac28912 100644 --- a/index.php +++ b/index.php @@ -23,7 +23,6 @@ */ require_once('../../config.php'); -require_once($CFG->dirroot . '/mod/customcert/locallib.php'); $id = required_param('id', PARAM_INT); // Course ID. @@ -33,11 +32,13 @@ $course = $DB->get_record('course', array('id' => $id), '*', MUST_EXIST); require_login($course); // Set up the page variables. +$pageurl = new moodle_url('/mod/customcert/index.php', array('id' => $course->id)); +\mod_customcert\page_helper::page_setup($pageurl, CONTEXT_COURSE::instance($id), + get_string('modulenameplural', 'customcert')); + +// Additional page setup needed. $PAGE->set_pagelayout('incourse'); -$PAGE->set_url('/mod/customcert/index.php', array('id' => $course->id)); $PAGE->navbar->add(get_string('modulenameplural', 'customcert')); -$PAGE->set_title(get_string('modulenameplural', 'customcert')); -$PAGE->set_heading($course->fullname); // Get the customcerts, if there are none display a notice. if (!$customcerts = get_all_instances_in_course('customcert', $course)) { diff --git a/lang/en/customcert.php b/lang/en/customcert.php index ed75cc1..a672d8d 100644 --- a/lang/en/customcert.php +++ b/lang/en/customcert.php @@ -30,17 +30,22 @@ $string['copy'] = 'Copy'; $string['coursetimereq'] = 'Required minutes in course'; $string['coursetimereq_help'] = 'Enter here the minimum amount of time, in minutes, that a student must be logged into the course before they will be able to receive the certificate.'; +$string['createtemplate'] = 'Create template'; +$string['customcertnameexists'] = 'A certificate already exists with this name'; +$string['customcertreport'] = 'Custom certificate report'; $string['customcert:addinstance'] = 'Add a new custom certificate instance'; $string['customcert:manage'] = 'Manage a custom certificate'; $string['customcert:view'] = 'View a custom certificate'; -$string['delete'] = 'Delete'; $string['deletecertpage'] = 'Delete certificate page'; $string['deleteconfirm'] = 'Delete confirmation'; $string['deleteelement'] = 'Delete element'; $string['deleteelementconfirm'] = 'Are you sure you want to delete this element?'; $string['deletepageconfirm'] = 'Are you sure you want to delete this certificate page?'; +$string['deletetemplateconfirm'] = 'Are you sure you want to delete this certificate template?'; $string['description'] = 'Description'; $string['editcustomcert'] = 'Edit custom certificate'; +$string['editelement'] = 'Edit element'; +$string['edittemplate'] = 'Edit template'; $string['elementname'] = 'Element name'; $string['elementname_help'] = 'This will be the name used to identify this element when editing a custom certificate. For example, you may have multiple images on a page and will want to distinguish between them quickly when editing the certificate. Note: this will not displayed on the PDF.'; @@ -48,8 +53,7 @@ $string['elements'] = 'Elements'; $string['elements_help'] = 'These are the list of elements that will be displayed on this PDF page.'; $string['elementwidth'] = 'Width'; $string['elementwidth_help'] = 'Specify the width of the element - \'0\' means that there is no width constraint.'; -$string['errorloadingelement'] = 'Error loading the element "{$a}"'; -$string['errorsavingelement'] = 'Error saving the element "{$a}"'; + $string['font'] = 'Font'; $string['font_help'] = 'The font used when generating this element.'; $string['fontcolour'] = 'Colour'; @@ -57,7 +61,6 @@ $string['fontcolour_help'] = 'The colour of the font.'; $string['fontsize'] = 'Size'; $string['fontsize_help'] = 'The size of the font in points.'; $string['getcustomcert'] = 'Get your custom certificate'; -$string['gridpdfname'] = 'grid_for_page_{$a}'; $string['height'] = 'Height'; $string['height_help'] = 'This is the height of the certificate PDF in mm. For reference an A4 piece of paper is 297mm high and a letter is 279mm high.'; $string['invalidcolour'] = 'Invalid colour chosen, please enter a valid HTML colour name, or a six-digit, or three-digit hexadecimal colour.'; @@ -73,17 +76,20 @@ $string['leftmargin_help'] = 'This is the left margin of the certificate PDF in $string['load'] = 'Load'; $string['loadtemplate'] = 'Load template'; $string['loadtemplatemsg'] = 'Are you sure you wish to load this template? This will remove any existing pages and elements for this certificate.'; +$string['managetemplates'] = 'Manage templates'; +$string['managetemplatesdesc'] = 'This link will take you to a new screen where you will be able to manage templates used by customcert activities in courses.'; $string['modify'] = 'Modify'; -$string['modulename'] = 'Custom Certificate'; -$string['modulenameplural'] = 'Custom Certificates'; +$string['modulename'] = 'Custom certificate'; +$string['modulenameplural'] = 'Custom certificates'; $string['name'] = 'Name'; $string['nocustomcerts'] = 'There are no custom certificates for this course'; $string['noimage'] = 'No image'; +$string['notemplates'] = 'No templates'; $string['notissued'] = 'Not issued'; $string['options'] = 'Options'; $string['page'] = 'Page {$a}'; -$string['pluginadministration'] = 'Custom Certificate administration'; -$string['pluginname'] = 'Custom Certificate'; +$string['pluginadministration'] = 'Custom certificate administration'; +$string['pluginname'] = 'Custom certificate'; $string['print'] = 'Print'; $string['portrait'] = 'Portrait'; $string['posx'] = 'Position X'; @@ -96,7 +102,6 @@ $string['receiveddate'] = 'Received date'; $string['refpoint'] = 'Reference point location'; $string['refpoint_help'] = 'This specifies which location of the element to be located at position X and position Y.'; $string['replacetemplate'] = 'Replace'; -$string['report'] = 'Report'; $string['rightmargin'] = 'Right margin'; $string['rightmargin_help'] = 'This is the right margin of the certificate PDF in mm.'; $string['save'] = 'Save'; diff --git a/lib.php b/lib.php index 6bf75fb..5c633f7 100644 --- a/lib.php +++ b/lib.php @@ -34,13 +34,19 @@ defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.'); function customcert_add_instance($data, $mform) { global $DB; - $data->protection = customcert_set_protection($data); + // Create a template for this customcert to use. + $context = context_module::instance($data->coursemodule); + $template = \mod_customcert\template::create($data->name, $context->id); + + // Add the data to the DB. + $data->templateid = $template->get_id(); + $data->protection = \mod_customcert\certificate::set_protection($data); $data->timecreated = time(); $data->timemodified = $data->timecreated; $data->id = $DB->insert_record('customcert', $data); // Add a page to this customcert. - customcert_add_page($data); + $template->add_page(); return $data->id; } @@ -55,7 +61,7 @@ function customcert_add_instance($data, $mform) { function customcert_update_instance($data, $mform) { global $DB; - $data->protection = customcert_set_protection($data); + $data->protection = \mod_customcert\certificate::set_protection($data); $data->timemodified = time(); $data->id = $data->instance; @@ -74,7 +80,7 @@ function customcert_delete_instance($id) { global $CFG, $DB; // Ensure the customcert exists. - if (!$DB->get_record('customcert', array('id' => $id))) { + if (!$customcert = $DB->get_record('customcert', array('id' => $id))) { return false; } @@ -88,28 +94,10 @@ function customcert_delete_instance($id) { return false; } - // Delete the elements. - $sql = "SELECT e.* - FROM {customcert_elements} e - INNER JOIN {customcert_pages} p - ON e.pageid = p.id - WHERE p.customcertid = :customcertid"; - if ($elements = $DB->get_records_sql($sql, array('customcertid' => $id))) { - require_once($CFG->dirroot . '/mod/customcert/locallib.php'); - foreach ($elements as $element) { - // Get an instance of the element class. - if ($e = customcert_get_element_instance($element)) { - $e->delete_element(); - } 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('customcertid' => $id))) { - return false; + // Now, delete the template associated with this certificate. + if ($template = $DB->get_record('customcert_templates', array('id' => $customcert->templateid))) { + $template = new \mod_customcert\template($template); + $template->delete(); } // Delete the customcert issues. @@ -130,7 +118,7 @@ function customcert_delete_instance($id) { * This function will remove all posts from the specified customcert * and clean up any related data. * - * @param $data the data submitted from the reset course. + * @param stdClass $data the data submitted from the reset course. * @return array status array */ function customcert_reset_userdata($data) { @@ -235,7 +223,7 @@ function customcert_user_complete($course, $user, $mod, $customcert) { * @param string $filearea * @param array $args * @param bool $forcedownload - * @return bool|nothing false if file not found, does not return anything if found - just send the file + * @return bool|null false if file not found, does not return anything if found - just send the file */ function customcert_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) { global $CFG; @@ -279,8 +267,6 @@ function customcert_supports($feature) { return true; case FEATURE_GROUPINGS: return true; - case FEATURE_GROUPMEMBERSONLY: - return true; case FEATURE_MOD_INTRO: return true; case FEATURE_COMPLETION_TRACKS_VIEWS: @@ -327,7 +313,7 @@ function customcert_cron() { * @param navigation_node $customcertnode */ function customcert_extend_settings_navigation(settings_navigation $settings, navigation_node $customcertnode) { - global $PAGE; + global $DB, $PAGE; $keys = $customcertnode->get_children_key_list(); $beforekey = null; @@ -339,8 +325,10 @@ function customcert_extend_settings_navigation(settings_navigation $settings, na } if (has_capability('mod/customcert:manage', $PAGE->cm->context)) { + // Get the template id. + $templateid = $DB->get_field('customcert', 'templateid', array('id' => $PAGE->cm->instance)); $node = navigation_node::create(get_string('editcustomcert', 'customcert'), - new moodle_url('/mod/customcert/edit.php', array('cmid' => $PAGE->cm->id)), + new moodle_url('/mod/customcert/edit.php', array('tid' => $templateid)), navigation_node::TYPE_SETTING, null, 'mod_customcert_edit', new pix_icon('t/edit', '')); $customcertnode->add_node($node, $beforekey); diff --git a/load_template.php b/load_template.php index 076339f..4f3181a 100644 --- a/load_template.php +++ b/load_template.php @@ -23,22 +23,23 @@ */ require_once('../../config.php'); -require_once($CFG->dirroot . '/mod/customcert/locallib.php'); -require_once($CFG->dirroot . '/mod/customcert/save_template_form.php'); -$cmid = required_param('cmid', PARAM_INT); $tid = required_param('tid', PARAM_INT); +$ltid = required_param('ltid', PARAM_INT); // The template to load. $confirm = optional_param('confirm', 0, PARAM_INT); -$cm = get_coursemodule_from_id('customcert', $cmid, 0, false, MUST_EXIST); -$course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST); -$customcert = $DB->get_record('customcert', array('id' => $cm->instance), '*', MUST_EXIST); -$template = $DB->get_record('customcert_template', array('id' => $tid), '*', MUST_EXIST); -$context = context_module::instance($cm->id); +$template = $DB->get_record('customcert_templates', array('id' => $tid), '*', MUST_EXIST); +$template = new \mod_customcert\template($template); -require_login($course, false, $cm); +$loadtemplate = $DB->get_record('customcert_templates', array('id' => $ltid), '*', MUST_EXIST); +$loadtemplate = new \mod_customcert\template($loadtemplate); -require_capability('mod/customcert:manage', $context); +if ($cm = $template->get_cm()) { + require_login($cm->course, false, $cm); +} else { + require_login(); +} +$template->require_manage(); // Check that they have confirmed they wish to load the template. if ($confirm) { @@ -47,36 +48,34 @@ if ($confirm) { FROM {customcert_elements} e INNER JOIN {customcert_pages} p ON e.pageid = p.id - WHERE p.customcertid = :customcertid"; - if ($elements = $DB->get_records_sql($sql, array('customcertid' => $customcert->id))) { + WHERE p.templateid = :templateid"; + if ($elements = $DB->get_records_sql($sql, array('templateid' => $template->get_id()))) { foreach ($elements as $element) { // Get an instance of the element class. - if ($e = customcert_get_element_instance($element)) { - $e->delete_element(); + if ($e = \mod_customcert\element::instance($element)) { + $e->delete(); } } } // Delete the pages. - $DB->delete_records('customcert_pages', array('customcertid' => $customcert->id)); + $DB->delete_records('customcert_pages', array('templateid' => $template->get_id())); // Store the current time in a variable. $time = time(); - // Now, get the template data. - if ($templatepages = $DB->get_records('customcert_template_pages', array('templateid' => $tid))) { - // Create an array to store any errors loading an element to a template. - $errors = array(); + // Now, get the template data we want to load. + if ($templatepages = $DB->get_records('customcert_pages', array('templateid' => $ltid))) { // Loop through the pages. foreach ($templatepages as $templatepage) { $page = clone($templatepage); - $page->customcertid = $customcert->id; + $page->templateid = $tid; $page->timecreated = $time; $page->timemodified = $time; // Insert into the database. $page->id = $DB->insert_record('customcert_pages', $page); - // Now go through the elements. - if ($templateelements = $DB->get_records('customcert_template_elements', array('templatepageid' => $templatepage->id))) { + // 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; @@ -85,12 +84,10 @@ if ($confirm) { // 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 = customcert_get_element_instance($element)) { - if (!$e->load_data_from_template($element)) { - // Remove from the customcert_elements table. - $DB->delete_records('customcert_elements', array('id' => $element->id)); - // Add the error message to the array to display later. - $errors[] = get_string('errorloadingelement', 'customcert', $element->element); + if ($e = \mod_customcert\element::instance($element)) { + if (!$e->copy_element($templateelement)) { + // Failed to copy - delete the element. + $e->delete(); } } } @@ -98,32 +95,21 @@ if ($confirm) { } } - // Get any errors caused by the loading of an element and put into a message. - $message = ''; - if (!empty($errors)) { - foreach ($errors as $e) { - $message .= $OUTPUT->notification($e) . '
'; - } - } - // Redirect. - $url = new moodle_url('/mod/customcert/edit.php', array('cmid' => $cmid)); - redirect($url, $message); + $url = new moodle_url('/mod/customcert/edit.php', array('tid' => $tid)); + redirect($url); } - // Create the link options. -$nourl = new moodle_url('/mod/customcert/edit.php', array('cmid' => $cmid)); -$yesurl = new moodle_url('/mod/customcert/load_template.php', array('cmid' => $cmid, - 'tid' => $tid, +$nourl = new moodle_url('/mod/customcert/edit.php', array('tid' => $tid)); +$yesurl = new moodle_url('/mod/customcert/load_template.php', array('tid' => $tid, + 'ltid' => $ltid, 'confirm' => 1)); + +$pageurl = new moodle_url('/mod/customcert/load_template.php', array('tid' => $tid, 'ltid' => $ltid)); +\mod_customcert\page_helper::page_setup($pageurl, $template->get_context(), get_string('loadtemplate', 'customcert')); + // Show a confirmation page. -$strheading = get_string('loadtemplate', 'customcert'); -$PAGE->navbar->add($strheading); -$PAGE->set_title($strheading); -$PAGE->set_heading($COURSE->fullname); -$PAGE->set_url('/mod/customcert/load_template.php', array('cmid' => $cmid, 'tid' => $tid)); echo $OUTPUT->header(); -echo $OUTPUT->heading($strheading); echo $OUTPUT->confirm(get_string('loadtemplatemsg', 'customcert'), $yesurl, $nourl); echo $OUTPUT->footer(); \ No newline at end of file diff --git a/locallib.php b/locallib.php deleted file mode 100644 index 6693b16..0000000 --- a/locallib.php +++ /dev/null @@ -1,697 +0,0 @@ -. - -/** - * Customcert module internal API. - * - * @package mod_customcert - * @copyright 2013 Mark Nelson - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -defined('MOODLE_INTERNAL') || die(); - -/** - * @var string the print protection variable - */ -define('PROTECTION_PRINT', 'print'); - -/** - * @var string the modify protection variable - */ -define('PROTECTION_MODIFY', 'modify'); - -/** - * @var string the copy protection variable - */ -define('PROTECTION_COPY', 'copy'); - -/** - * @var int the number of issues that will be displayed on each page in the report - * If you want to display all customcerts on a page set this to 0. - */ -define('CUSTOMCERT_PER_PAGE', 20); - -/** - * @var int the max number of issues to display - */ -define('CUSTOMCERT_MAX_PER_PAGE', 300); - -/** - * @var int the top-left of element - */ -define('CUSTOMCERT_REF_POINT_TOPLEFT', 0); - -/** - * @var int the top-center of element - */ -define('CUSTOMCERT_REF_POINT_TOPCENTER', 1); - -/** - * @var int the top-left of element - */ -define('CUSTOMCERT_REF_POINT_TOPRIGHT', 2); - -/** - * Handles setting the protection field for the customcert - * - * @param stdClass $data - * @return string the value to insert into the protection field - */ -function customcert_set_protection($data) { - $protection = array(); - - if (!empty($data->protection_print)) { - $protection[] = PROTECTION_PRINT; - } - if (!empty($data->protection_modify)) { - $protection[] = PROTECTION_MODIFY; - } - if (!empty($data->protection_copy)) { - $protection[] = PROTECTION_COPY; - } - - // Return the protection string. - return implode(', ', $protection); -} - -/** - * 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 - */ -function customcert_upload_imagefiles($draftitemid, $contextid) { - // Save the file if it exists that is currently in the draft area. - file_save_draft_area_files($draftitemid, $contextid, 'mod_customcert', 'image', 0); -} - -/** - * Return the list of possible elements to add. - * - * @return array the list of images that can be used. - */ -function customcert_get_elements() { - 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)) { - $component = "customcertelement_{$foldername}"; - $options[$foldername] = get_string('pluginname', $component); - } - } - } - - core_collator::asort($options); - return $options; -} - -/** - * Return the list of possible fonts to use. - */ -function customcert_get_fonts() { - global $CFG; - - // Array to store the available fonts. - $options = array(); - - // Location of fonts in Moodle. - $fontdir = "$CFG->dirroot/lib/tcpdf/fonts"; - // Check that the directory exists. - if (file_exists($fontdir)) { - // Get directory contents. - $fonts = new DirectoryIterator($fontdir); - // Loop through the font folder. - foreach ($fonts as $font) { - // If it is not a file, or either '.' or '..', or - // the extension is not php, or we can not open file, - // skip it. - if (!$font->isFile() || $font->isDot() || ($font->getExtension() != 'php')) { - continue; - } - // 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("$fontdir/$font"); - // If no $name variable in file, skip it. - if (is_null($name)) { - continue; - } - // Remove the extension of the ".php" file that contains the font information. - $filename = basename($font, ".php"); - // 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); - } - $options[$filename] = $displayname; - } - ksort($options); - } - - return $options; -} - -/** - * Return the list of possible font sizes to use. - */ -function customcert_get_font_sizes() { - // Array to store the sizes. - $sizes = array(); - - for ($i = 1; $i <= 60; $i++) { - $sizes[$i] = $i; - } - - return $sizes; -} - -/** - * Handles saving page data. - * - * @param stdClass $data the customcert data - */ -function customcert_save_page_data($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('customcertid' => $data->id))) { - // 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); - } - } -} - -/** - * Returns an instance of the element class. - * - * @param stdClass $element the element - * @return stdClass|bool returns the instance of the element class, or false if element - * class does not exists. - */ -function customcert_get_element_instance($element) { - // Get the class name. - $classname = '\\customcertelement_' . $element->element . '\\element'; - - // Ensure the necessary class exists. - if (class_exists($classname)) { - return new $classname($element); - } - - return false; -} - -/** - * Handles adding another page to the customcert. - * - * @param stdClass $data the form data - */ -function customcert_add_page($data) { - global $DB; - - // Set the page number to 1 to begin with. - $pagenumber = 1; - // Get the max page number. - $sql = "SELECT MAX(pagenumber) as maxpage - FROM {customcert_pages} cp - WHERE cp.customcertid = :customcertid"; - if ($maxpage = $DB->get_record_sql($sql, array('customcertid' => $data->id))) { - $pagenumber = $maxpage->maxpage + 1; - } - - // Store time in a variable. - $time = time(); - - // New page creation. - $page = new stdClass(); - $page->customcertid = $data->id; - $page->width = '210'; - $page->height = '297'; - $page->pagenumber = $pagenumber; - $page->timecreated = $time; - $page->timemodified = $time; - - // Insert the page. - $DB->insert_record('customcert_pages', $page); -} - -/** - * Handles deleting an element from the customcert. - * - * @param int $elementid the customcert page - */ -function customcert_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 = customcert_get_element_instance($element)) { - $e->delete_element(); - } 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)); -} - -/** - * Handles deleting a page from the customcert. - * - * @param int $pageid the customcert page - */ -function customcert_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 = customcert_get_element_instance($element)) { - $e->delete_element(); - } 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 pagenumber = pagenumber - 1 - WHERE customcertid = :customcertid - AND pagenumber > :pagenumber"; - $DB->execute($sql, array('customcertid' => $page->customcertid, 'pagenumber' => $page->pagenumber)); -} - -/** - * Returns a list of all the templates. - * - * @return bool returns true if success, false otherwise - */ -function customcert_get_templates() { - global $DB; - - return $DB->get_records_menu('customcert_template', array(), 'name ASC', 'id, name'); -} - -/** - * Get the time the user has spent in the course. - * - * @param int $courseid - * @return int the total time spent in seconds - */ -function customcert_get_course_time($courseid) { - global $CFG, $DB, $USER; - - $logmanager = get_log_manager(); - $readers = $logmanager->get_readers(); - $enabledreaders = get_config('tool_log', 'enabled_stores'); - $enabledreaders = explode(',', $enabledreaders); - - // Go through all the readers until we find one that we can use. - foreach ($enabledreaders as $enabledreader) { - $reader = $readers[$enabledreader]; - if ($reader instanceof \logstore_legacy\log\store) { - $logtable = 'log'; - $coursefield = 'course'; - $timefield = 'time'; - break; - } else if ($reader instanceof \core\log\sql_internal_reader) { - $logtable = $reader->get_internal_log_table_name(); - $coursefield = 'courseid'; - $timefield = 'timecreated'; - break; - } - } - - // If we didn't find a reader then return 0. - if (!isset($logtable)) { - return 0; - } - - $sql = "SELECT id, $timefield - FROM {{$logtable}} - WHERE userid = :userid - AND $coursefield = :courseid - ORDER BY $timefield ASC"; - $params = array('userid' => $USER->id, 'courseid' => $courseid); - $totaltime = 0; - if ($logs = $DB->get_recordset_sql($sql, $params)) { - foreach ($logs as $log) { - if (!isset($login)) { - // For the first time $login is not set so the first log is also the first login - $login = $log->$timefield; - $lasthit = $log->$timefield; - $totaltime = 0; - } - $delay = $log->$timefield - $lasthit; - 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; - } else { - $totaltime += $delay; - } - // Now the actual log became the previous log for the next cycle - $lasthit = $log->$timefield; - } - - return $totaltime; - } - - return 0; -} - -/** - * Returns a list of issued customcerts. - * - * @param int $customcertid - * @param bool $groupmode are we in group mode - * @param stdClass $cm the course module - * @param int $page offset - * @param int $perpage total per page - * @return stdClass the users - */ -function customcert_get_issues($customcertid, $groupmode, $cm, $page, $perpage) { - global $DB; - - // Get the conditional SQL. - list($conditionssql, $conditionsparams) = customcert_get_conditional_issues_sql($cm, $groupmode); - - // If it is empty then return an empty array. - if (empty($conditionsparams)) { - return array(); - } - - // Add the conditional SQL and the customcertid to form all used parameters. - $allparams = $conditionsparams + array('customcertid' => $customcertid); - - // Return the issues. - $sql = "SELECT u.*, ci.code, ci.timecreated - FROM {user} u - INNER JOIN {customcert_issues} ci - ON u.id = ci.userid - WHERE u.deleted = 0 - AND ci.customcertid = :customcertid - $conditionssql - ORDER BY " . $DB->sql_fullname(); - return $DB->get_records_sql($sql, $allparams, $page * $perpage, $perpage); -} - -/** - * Returns the total number of issues for a given customcert. - * - * @param int $customcertid - * @param stdClass $cm the course module - * @param bool $groupmode the group mode - * @return int the number of issues - */ -function customcert_get_number_of_issues($customcertid, $cm, $groupmode) { - global $DB; - - // Get the conditional SQL. - list($conditionssql, $conditionsparams) = customcert_get_conditional_issues_sql($cm, $groupmode); - - // If it is empty then return 0. - if (empty($conditionsparams)) { - return 0; - } - - // 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 {customcert_issues} ci - ON u.id = ci.userid - WHERE u.deleted = 0 - AND ci.customcertid = :customcertid - $conditionssql"; - return $DB->count_records_sql($sql, $allparams); -} - -/** - * Returns an array of the conditional variables to use in the get_issues SQL query. - * - * @param stdClass $cm the course module - * @param bool $groupmode are we in group mode ? - * @return array the conditional variables - */ -function customcert_get_conditional_issues_sql($cm, $groupmode) { - global $DB, $USER; - - // 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/certificate: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"; - $conditionsparams += $params; - - if ($groupmode) { - $canaccessallgroups = has_capability('moodle/site:accessallgroups', $context); - $currentgroup = groups_get_activity_group($cm); - - // If we are viewing all participants and the user does not have access to all groups then return nothing. - if (!$currentgroup && !$canaccessallgroups) { - return array('', array()); - } - - if ($currentgroup) { - if (!$canaccessallgroups) { - // Guest users do not belong to any groups. - if (isguestuser()) { - return array('', array()); - } - - // Check that the user belongs to the group we are viewing. - $usersgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid); - if ($usersgroups) { - if (!isset($usersgroups[$currentgroup])) { - return array('', array()); - } - } else { // They belong to no group, so return an empty array. - return array('', array()); - } - } - - $groupusers = array_keys(groups_get_members($currentgroup, 'u.*')); - if (empty($groupusers)) { - return array('', array()); - } - - list($sql, $params) = $DB->get_in_or_equal($groupusers, SQL_PARAMS_NAMED, 'grp'); - $conditionssql .= "AND u.id $sql "; - $conditionsparams += $params; - } - } - - return array($conditionssql, $conditionsparams); -} - -/** - * Generates a 10-digit code of random letters and numbers. - * - * @return string - */ -function customcert_generate_code() { - global $DB; - - $uniquecodefound = false; - $code = random_string(10); - while (!$uniquecodefound) { - if (!$DB->record_exists('customcert_issues', array('code' => $code))) { - $uniquecodefound = true; - } else { - $code = random_string(10); - } - } - - return $code; -} - -/** - * Generate the PDF for the specified customcert and user. - * - * @param stdClass $customcert - * @param bool $preview true if it is a preview, false otherwise - */ -function customcert_generate_pdf($customcert, $preview = false) { - global $CFG, $DB; - - require_once($CFG->libdir . '/pdflib.php'); - - // Get the pages for the customcert, there should always be at least one page for each customcert. - if ($pages = $DB->get_records('customcert_pages', array('customcertid' => $customcert->id), 'pagenumber ASC')) { - // Create the pdf object. - $pdf = new pdf(); - if (!empty($customcert->protection)) { - $protection = explode(', ', $customcert->protection); - $pdf->SetProtection($protection); - } - $pdf->setPrintHeader(false); - $pdf->setPrintFooter(false); - $pdf->SetTitle($customcert->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($customcert->name, '.'); - $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 = customcert_get_element_instance($element)) { - $e->render($pdf, $preview); - } - } - } - } - $pdf->Output($filename, 'D'); - } -} - -/** - * Generate the report. - * - * @param stdClass $customcert - * @param stdClass $users the list of users who have had a customcert issued - * @param string $type - */ -function customcert_generate_report_file($customcert, $users, $type) { - global $CFG, $COURSE; - - if ($type == 'ods') { - require_once($CFG->libdir . '/odslib.class.php'); - $workbook = new MoodleODSWorkbook('-'); - } else if ($type == 'xls') { - require_once($CFG->libdir . '/excellib.class.php'); - $workbook = new MoodleExcelWorkbook('-'); - } - - $filename = clean_filename($COURSE->shortname . ' ' . rtrim($customcert->name, '.') . '.' . $type); - - // Send HTTP headers. - $workbook->send($filename); - - // Creating the first worksheet. - $myxls = $workbook->add_worksheet(get_string('report', 'customcert')); - - // Print names of all the fields. - $myxls->write_string(0, 0, get_string('lastname')); - $myxls->write_string(0, 1, get_string('firstname')); - $myxls->write_string(0, 2, get_string('idnumber')); - $myxls->write_string(0, 3, get_string('group')); - $myxls->write_string(0, 4, get_string('receiveddate', 'customcert')); - $myxls->write_string(0, 5, get_string('code', 'customcert')); - - // Generate the data for the body of the spreadsheet. - $row = 1; - if ($users) { - foreach ($users as $user) { - $myxls->write_string($row, 0, $user->lastname); - $myxls->write_string($row, 1, $user->firstname); - $studentid = (!empty($user->idnumber)) ? $user->idnumber : ' '; - $myxls->write_string($row, 2, $studentid); - $ug2 = ''; - if ($usergrps = groups_get_all_groups($COURSE->id, $user->id)) { - foreach ($usergrps as $ug) { - $ug2 = $ug2 . $ug->name; - } - } - $myxls->write_string($row, 3, $ug2); - $myxls->write_string($row, 4, userdate($user->timecreated)); - $myxls->write_string($row, 5, $user->code); - $row++; - } - } - // Close the workbook. - $workbook->close(); -} diff --git a/manage_templates.php b/manage_templates.php new file mode 100644 index 0000000..67d7b51 --- /dev/null +++ b/manage_templates.php @@ -0,0 +1,115 @@ +. + +/** + * Manage customcert templates. + * + * @package mod_customcert + * @copyright 2016 Mark Nelson + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +require_once('../../config.php'); + +$contextid = optional_param('contextid', CONTEXT_SYSTEM::instance()->id, PARAM_INT); +$action = optional_param('action', '', PARAM_ALPHA); +$confirm = optional_param('confirm', 0, PARAM_INT); + +if ($action) { + $tid = required_param('tid', PARAM_INT); +} else { + $tid = optional_param('tid', 0, PARAM_INT); +} + +if ($tid) { + $template = $DB->get_record('customcert_templates', array('id' => $tid), '*', MUST_EXIST); + $template = new \mod_customcert\template($template); +} + +$context = context::instance_by_id($contextid); + +require_login(); +require_capability('mod/customcert:manage', $context); + +// Set up the page. +$pageurl = new moodle_url('/mod/customcert/manage_templates.php'); +\mod_customcert\page_helper::page_setup($pageurl, $context, get_string('managetemplates', 'customcert')); + +// Additional page setup. +$PAGE->navbar->add(get_string('managetemplates', 'customcert')); + +// Check if we are deleting a template. +if ($tid) { + if ($action == 'delete') { + if (!$confirm) { + $nourl = new moodle_url('/mod/customcert/manage_templates.php'); + $yesurl = new moodle_url('/mod/customcert/manage_templates.php', array('tid' => $tid, + 'action' => 'delete', + 'confirm' => 1, + 'sesskey' => sesskey())); + + // Show a confirmation page. + $strheading = get_string('deleteconfirm', 'customcert'); + $PAGE->navbar->add($strheading); + $PAGE->set_title($strheading); + $message = get_string('deletetemplateconfirm', 'customcert'); + echo $OUTPUT->header(); + echo $OUTPUT->heading($strheading); + echo $OUTPUT->confirm($message, $yesurl, $nourl); + echo $OUTPUT->footer(); + exit(); + } + + // Delete the template. + $template->delete(); + + // Redirect back to the manage templates page. + redirect(new moodle_url('/mod/customcert/manage_templates.php')); + } +} +// Get all the templates that are available. +if ($templates = $DB->get_records('customcert_templates', array('contextid' => $contextid), 'timecreated DESC')) { + // Create a table to display these elements. + $table = new html_table(); + $table->head = array(get_string('name', 'customcert'), ''); + $table->align = array('left', 'center'); + + foreach ($templates as $template) { + // Link to edit the element. + $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 delete the element. + $deletelink = new \moodle_url('/mod/customcert/manage_templates.php', array('tid' => $template->id, + 'action' => 'delete')); + $deleteicon = $OUTPUT->action_icon($deletelink, new \pix_icon('t/delete', get_string('delete'))); + + $row = new html_table_row(); + $row->cells[] = $template->name; + $row->cells[] = $editicon . $deleteicon; + $table->data[] = $row; + } +} + +echo $OUTPUT->header(); +if (isset($table)) { + echo html_writer::table($table); +} else { + echo html_writer::tag('div', get_string('notemplates', 'customcert'), array('class' => 'alert')); +} +$url = new moodle_url('/mod/customcert/edit.php?action=add&contextid=' . $contextid); +echo $OUTPUT->single_button($url, get_string('createtemplate', 'customcert'), 'get'); +echo $OUTPUT->footer(); diff --git a/mod_form.php b/mod_form.php index fbff402..9297d7c 100644 --- a/mod_form.php +++ b/mod_form.php @@ -17,7 +17,6 @@ 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/locallib.php'); /** * Instance add/edit form. diff --git a/pix/dash.gif b/pix/dash.gif deleted file mode 100644 index c535af8..0000000 Binary files a/pix/dash.gif and /dev/null differ diff --git a/rearrange.php b/rearrange.php index 8ab5640..dda8781 100644 --- a/rearrange.php +++ b/rearrange.php @@ -23,26 +23,28 @@ */ require_once('../../config.php'); -require_once($CFG->dirroot . '/mod/customcert/locallib.php'); // The page of the customcert we are editing. -$pid = required_param('id', PARAM_INT); +$pid = required_param('pid', PARAM_INT); $page = $DB->get_record('customcert_pages', array('id' => $pid), '*', MUST_EXIST); +$template = $DB->get_record('customcert_templates', array('id' => $page->templateid), '*', MUST_EXIST); $elements = $DB->get_records('customcert_elements', array('pageid' => $pid), 'sequence'); -$cm = get_coursemodule_from_instance('customcert', $page->customcertid, 0, false, MUST_EXIST); -$course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST); -$context = context_module::instance($cm->id); -require_login($course, false, $cm); - -require_capability('mod/customcert:manage', $context); +// Set the template. +$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(); // Set the $PAGE settings. -$PAGE->set_url(new moodle_url('/mod/customcert/rearrange.php', array('id' => $pid))); -$PAGE->set_pagetype('mod-customcert-position'); -$PAGE->set_title(get_string('rearrangeelements', 'customcert')); -$PAGE->set_heading($course->fullname); +$pageurl = new moodle_url('/mod/customcert/rearrange.php', array('pid' => $pid)); +\mod_customcert\page_helper::page_setup($pageurl, $template->get_context(), get_string('rearrangeelements', 'customcert')); // Include the JS we need. $module = array( @@ -50,15 +52,15 @@ $module = array( 'fullpath' => '/mod/customcert/yui/src/rearrange.js', 'requires' => array('dd-delegate', 'dd-drag') ); -$PAGE->requires->js_init_call('M.mod_customcert.rearrange.init', array($cm->id, $page, $elements), false, $module); +$PAGE->requires->js_init_call('M.mod_customcert.rearrange.init', array($template->get_id(), $page, $elements), false, $module); // Create the buttons to save the position of the elements. $html = html_writer::start_tag('div', array('class' => 'buttons')); -$html .= $OUTPUT->single_button(new moodle_url('/mod/customcert/edit.php', array('cmid' => $cm->id)), +$html .= $OUTPUT->single_button(new moodle_url('/mod/customcert/edit.php', array('tid' => $template->get_id())), get_string('saveandclose', 'customcert'), 'get', array('class' => 'savepositionsbtn')); -$html .= $OUTPUT->single_button(new moodle_url('/mod/customcert/rearrange.php', array('id' => $pid)), +$html .= $OUTPUT->single_button(new moodle_url('/mod/customcert/rearrange.php', array('pid' => $pid)), get_string('saveandcontinue', 'customcert'), 'get', array('class' => 'applypositionsbtn')); -$html .= $OUTPUT->single_button(new moodle_url('/mod/customcert/edit.php', array('cmid' => $cm->id)), +$html .= $OUTPUT->single_button(new moodle_url('/mod/customcert/edit.php', array('tid' => $template->get_id())), get_string('cancel'), 'get', array('class' => 'cancelbtn')); $html .= html_writer::end_tag('div'); @@ -73,15 +75,15 @@ if ($page->leftmargin) { if ($elements) { foreach ($elements as $element) { // Get an instance of the element class. - if ($e = customcert_get_element_instance($element)) { + if ($e = \mod_customcert\element::instance($element)) { switch ($element->refpoint) { - case CUSTOMCERT_REF_POINT_TOPRIGHT: + case \mod_customcert\element_helper::CUSTOMCERT_REF_POINT_TOPRIGHT: $class = 'element refpoint-right'; break; - case CUSTOMCERT_REF_POINT_TOPCENTER: + case \mod_customcert\element_helper::CUSTOMCERT_REF_POINT_TOPCENTER: $class = 'element refpoint-center'; break; - case CUSTOMCERT_REF_POINT_TOPLEFT: + case \mod_customcert\element_helper::CUSTOMCERT_REF_POINT_TOPLEFT: default: $class = 'element refpoint-left'; } @@ -96,7 +98,6 @@ if ($page->rightmargin) { $html .= html_writer::end_tag('div'); echo $OUTPUT->header(); -echo $OUTPUT->heading(get_string('editcustomcert', 'customcert')); echo $OUTPUT->heading(get_string('rearrangeelementsheading', 'customcert'), 4); echo $html; echo $OUTPUT->footer(); \ No newline at end of file diff --git a/report.php b/report.php index 84cf2f0..8997e44 100644 --- a/report.php +++ b/report.php @@ -23,20 +23,19 @@ */ require_once('../../config.php'); -require_once($CFG->dirroot . '/mod/customcert/locallib.php'); $id = required_param('id', PARAM_INT); $download = optional_param('download', '', PARAM_ALPHA); $page = optional_param('page', 0, PARAM_INT); -$perpage = optional_param('perpage', CUSTOMCERT_PER_PAGE, PARAM_INT); +$perpage = optional_param('perpage', \mod_customcert\certificate::CUSTOMCERT_PER_PAGE, PARAM_INT); $pageurl = $url = new moodle_url('/mod/customcert/report.php', array('id' => $id, 'page' => $page, 'perpage' => $perpage)); // Ensure the perpage variable does not exceed the max allowed if // the user has not specified they wish to view all customcerts. -if (CUSTOMCERT_PER_PAGE !== 0) { - if (($perpage > CUSTOMCERT_MAX_PER_PAGE) || ($perpage === 0)) { - $perpage = CUSTOMCERT_PER_PAGE; +if (\mod_customcert\certificate::CUSTOMCERT_PER_PAGE !== 0) { + if (($perpage > \mod_customcert\certificate::CUSTOMCERT_MAX_PER_PAGE) || ($perpage === 0)) { + $perpage = \mod_customcert\certificate::CUSTOMCERT_PER_PAGE; } } @@ -55,10 +54,10 @@ require_capability('mod/customcert:manage', $context); if ($groupmode = groups_get_activity_groupmode($cm)) { groups_get_activity_group($cm, true); } -$users = customcert_get_issues($customcert->id, $groupmode, $cm, $page, $perpage); +$users = \mod_customcert\certificate::get_issues($customcert->id, $groupmode, $cm, $page, $perpage); if ($download) { - customcert_generate_report_file($customcert, $users, $download); + \mod_customcert\certificate::generate_report_file($customcert, $users, $download); exit; } @@ -82,10 +81,11 @@ $btndownloadods = $OUTPUT->single_button(new moodle_url('report.php', array('id' $btndownloadxls = $OUTPUT->single_button(new moodle_url('report.php', array('id' => $cm->id, 'download' => 'xls')), get_string("downloadexcel")); $tablebutton->data[] = array($btndownloadods, $btndownloadxls); -$PAGE->set_url($pageurl); -$PAGE->navbar->add(get_string('report', 'customcert')); -$PAGE->set_title(format_string($customcert->name) . ": " . get_string('report', 'customcert')); -$PAGE->set_heading($course->fullname); +// Set up the page. +\mod_customcert\page_helper::page_setup($pageurl, $context, get_string('customcertreport', 'customcert')); + +// Additional page setup. +$PAGE->navbar->add(get_string('customcertreport', 'customcert')); echo $OUTPUT->header(); echo $OUTPUT->heading(get_string('modulenameplural', 'customcert')); diff --git a/rest.php b/rest.php index fa522ff..9c9e620 100644 --- a/rest.php +++ b/rest.php @@ -28,20 +28,24 @@ if (!defined('AJAX_SCRIPT')) { require_once(__DIR__ . '/../../config.php'); -$cmid = required_param('cmid', PARAM_INT); +$tid = required_param('tid', PARAM_INT); $values = required_param('values', PARAM_RAW); $values = json_decode($values); -$cm = get_coursemodule_from_id('customcert', $cmid, 0, false, MUST_EXIST); -$course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST); -$context = context_module::instance($cm->id); -$elements = $DB->get_records_sql('SELECT * FROM {customcert_elements} e - JOIN {customcert_pages} p ON e.pageid = p.id - WHERE p.customcertid = ?', array($cm->instance)); +// Make sure the template exists. +$template = $DB->get_record('customcert_templates', array('id' => $tid), '*', MUST_EXIST); -// Check that the user is able to perform the change. -require_login($course, false, $cm); -require_capability('mod/customcert:manage', $context); +// 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) { diff --git a/save_template.php b/save_template.php deleted file mode 100644 index d61dc36..0000000 --- a/save_template.php +++ /dev/null @@ -1,108 +0,0 @@ -. - -/** - * Handles saving customcert templates. - * - * @package mod_customcert - * @copyright 2013 Mark Nelson - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -require_once('../../config.php'); -require_once($CFG->dirroot . '/mod/customcert/locallib.php'); -require_once($CFG->dirroot . '/mod/customcert/save_template_form.php'); - -$cmid = required_param('cmid', PARAM_INT); -$name = required_param('name', PARAM_TEXT); - -$cm = get_coursemodule_from_id('customcert', $cmid, 0, false, MUST_EXIST); -$course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST); -$customcert = $DB->get_record('customcert', array('id' => $cm->instance), '*', MUST_EXIST); -$context = context_module::instance($cm->id); - -require_login($course, false, $cm); - -require_capability('mod/customcert:manage', $context); - -// Store the current time in a variable. -$time = time(); - -if (!$template = $DB->get_record('customcert_template', array('name' => $name))) { - // Create the template. - $template = new stdClass(); - $template->name = $name; - $template->timecreated = $time; -} - -$template->timemodified = $time; - -if (empty($template->id)) { - $template->id = $DB->insert_record('customcert_template', $template); -} else { - $DB->update_record('customcert_template', $template); - $templatepages = $DB->get_records_menu('customcert_template_pages', array('templateid' => $template->id)); - $DB->delete_records_list('customcert_template_elements', 'templatepageid', array_keys($templatepages)); - $DB->delete_records('customcert_template_pages', array('templateid' => $template->id)); -} - -// Get the pages of the customcert we are copying. -if ($pages = $DB->get_records('customcert_pages', array('customcertid' => $customcert->id))) { - // Create an array to store any errors saving an element to a template. - $errors = array(); - // Loop through and copy the data. - foreach ($pages as $page) { - // Insert into the template page table. - $templatepage = clone($page); - $templatepage->templateid = $template->id; - $templatepage->timecreated = $time; - $templatepage->timemodified = $time; - $templatepage->id = $DB->insert_record('customcert_template_pages', $templatepage); - // Get the elements. - if ($elements = $DB->get_records('customcert_elements', array('pageid' => $page->id))) { - // Loop through the elements. - foreach ($elements as $element) { - // Insert into the template element table. - $templateelement = clone($element); - $templateelement->templatepageid = $templatepage->id; - $templateelement->timecreated = $time; - $templateelement->timemodified = $time; - $templateelement->id = $DB->insert_record('customcert_template_elements', $templateelement); - // Save any other information the element may need to for the template. - if ($e = customcert_get_element_instance($element)) { - if (!$e->save_data_to_template($element)) { - // Remove from the customcert_template_elements table. - $DB->delete_records('customcert_template_elements', array('id' => $templateelement->id)); - // Add the error message to the array to display later. - $errors[] = get_string('errorsavingelement', 'customcert', $element->element); - } - } - } - } - } -} - -// Get any errors caused by the loading of an element and put into a message. -$message = ''; -if (!empty($errors)) { - foreach ($errors as $e) { - $message .= $OUTPUT->notification($e) . '
'; - } -} - -// Redirect. -$url = new moodle_url('/mod/customcert/edit.php', array('cmid' => $cmid)); -redirect($url, $message); \ No newline at end of file diff --git a/save_template_form.php b/save_template_form.php deleted file mode 100644 index 2127e20..0000000 --- a/save_template_form.php +++ /dev/null @@ -1,79 +0,0 @@ -. - -defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.'); - -require_once($CFG->libdir . '/formslib.php'); - -/** - * The form for handling saving customcert templates. - * - * @package mod_customcert - * @copyright 2013 Mark Nelson - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class mod_customcert_save_template_form extends moodleform { - - /** - * Form definition. - */ - public function definition() { - $mform =& $this->_form; - - $mform->addElement('header', 'savetemplateheader', get_string('savetemplate', 'customcert')); - - $group = array(); - $group[] = $mform->createElement('text', 'name'); - $group[] = $mform->createElement('submit', 'savetemplatesubmit', get_string('save', 'customcert')); - $group[] = $mform->createElement('checkbox', 'replace', null, get_string('replacetemplate', 'customcert')); - - $mform->addElement('group', 'savetemplategroup', get_string('templatename', 'customcert'), $group, '', false); - - // Set the template name to required and set the type. - $mform->addGroupRule('savetemplategroup', array( - 'name' => array( - array(null, 'required', null, 'client') - ) - )); - $mform->setType('name', PARAM_NOTAGS); - - $mform->addElement('hidden', 'cmid'); - $mform->setType('cmid', PARAM_INT); - $mform->setDefault('cmid', $this->_customdata['cmid']); - } - - /** - * Some basic validation. - * - * @param array $data - * @param array $files - * @return array the errors that were found - */ - public function validation($data, $files) { - global $DB; - - $errors = parent::validation($data, $files); - - if (empty($data['replace'])) { - // Ensure the name does not already exist. - if ($DB->record_exists('customcert_template', array('name' => $data['name']))) { - $errors['savetemplategroup'] = get_string('templatenameexists', 'customcert'); - } - } - - return $errors; - } -} diff --git a/settings.php b/settings.php index 6e35a3a..7c36d87 100644 --- a/settings.php +++ b/settings.php @@ -24,7 +24,10 @@ defined('MOODLE_INTERNAL') || die; -require_once($CFG->dirroot.'/mod/customcert/adminsetting.class.php'); +$settings->add(new \mod_customcert\admin_setting_link('customcert/managetemplates', + get_string('managetemplates', 'customcert'), get_string('managetemplatesdesc', 'customcert'), + get_string('managetemplates', 'customcert'), new moodle_url('/mod/customcert/manage_templates.php'), '')); -$settings->add(new mod_customcert_admin_setting_upload('customcert/uploadimage', - get_string('uploadimage', 'customcert'), get_string('uploadimagedesc', 'customcert'), '')); +$settings->add(new \mod_customcert\admin_setting_link('customcert/uploadimage', + get_string('uploadimage', 'customcert'), get_string('uploadimagedesc', 'customcert'), + get_string('uploadimage', 'customcert'), new moodle_url('/mod/customcert/upload_image.php'), '')); diff --git a/styles.css b/styles.css index a893056..d313631 100644 --- a/styles.css +++ b/styles.css @@ -11,19 +11,19 @@ margin-right: auto; } -#page-mod-customcert-position .savepositionsbtn, -#page-mod-customcert-position .applypositionsbtn, -#page-mod-customcert-position .cancelbtn { +#page-mod-customcert-rearrange .savepositionsbtn, +#page-mod-customcert-rearrange .applypositionsbtn, +#page-mod-customcert-rearrange .cancelbtn { float:left } -#page-mod-customcert-position .element { +#page-mod-customcert-rearrange .element { display:inline-block; position: absolute; word-wrap: break-word; } -#page-mod-customcert-position .element:before { +#page-mod-customcert-rearrange .element:before { content: ""; display: block; background-image: url([[pix:mod_customcert|target]]); @@ -33,35 +33,35 @@ float: left; } -#page-mod-customcert-position .element:hover { +#page-mod-customcert-rearrange .element:hover { cursor:move; } -#page-mod-customcert-position .element.refpoint-left:before { - background-position: left top; +#page-mod-customcert-rearrange .element.refpoint-left:before { + background-rearrange: left top; margin: -4px -5px -5px -4px; } -#page-mod-customcert-position .element.refpoint-center:before { - background-position: center top; +#page-mod-customcert-rearrange .element.refpoint-center:before { + background-rearrange: center top; margin: -4px 0 -5px 0; } -#page-mod-customcert-position .element.refpoint-right:before { - background-position: right top; +#page-mod-customcert-rearrange .element.refpoint-right:before { + background-rearrange: right top; margin: -4px -5px -5px 4px; } -#page-mod-customcert-position #pdf { +#page-mod-customcert-rearrange #pdf { clear:both; border-style:solid; border-width:1px; } -#page-mod-customcert-position div#leftmargin { +#page-mod-customcert-rearrange div#leftmargin { border-left: 1px dotted black; } -#page-mod-customcert-position div#rightmargin { +#page-mod-customcert-rearrange div#rightmargin { border-right: 1px dotted black; } diff --git a/upload_image.php b/upload_image.php index dc9a41b..93f359a 100644 --- a/upload_image.php +++ b/upload_image.php @@ -23,8 +23,6 @@ */ require('../../config.php'); -require_once($CFG->dirroot.'/mod/customcert/locallib.php'); -require_once($CFG->dirroot.'/mod/customcert/upload_image_form.php'); require_login(); @@ -33,21 +31,20 @@ require_capability('moodle/site:config', $context); $struploadimage = get_string('uploadimage', 'customcert'); -$PAGE->set_url('/admin/settings.php', array('section' => 'modsettingcustomcert')); -$PAGE->set_pagetype('admin-setting-modsettingcustomcert'); -$PAGE->set_pagelayout('admin'); -$PAGE->set_context($context); -$PAGE->set_title($struploadimage); -$PAGE->set_heading($SITE->fullname); +// Set the page variables. +$pageurl = new moodle_url('/mod/customcert/upload_image.php'); +\mod_customcert\page_helper::page_setup($pageurl, $context, $struploadimage, $SITE->fullname); + +// Additional page setup. $PAGE->navbar->add($struploadimage); -$uploadform = new mod_customcert_upload_image_form(); +$uploadform = new \mod_customcert\upload_image_form(); if ($uploadform->is_cancelled()) { redirect(new moodle_url('/admin/settings.php?section=modsettingcustomcert')); } else if ($data = $uploadform->get_data()) { // Handle file uploads. - customcert_upload_imagefiles($data->customcertimage, $context->id); + \mod_customcert\certificate::upload_imagefiles($data->customcertimage, $context->id); redirect(new moodle_url('/mod/customcert/upload_image.php'), get_string('changessaved')); } diff --git a/version.php b/version.php index 492c888..68b3280 100644 --- a/version.php +++ b/version.php @@ -24,10 +24,10 @@ defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.'); -$plugin->version = 2015121400; // The current module version (Date: YYYYMMDDXX). +$plugin->version = 2016021900; // The current module version (Date: YYYYMMDDXX). $plugin->requires = 2015051100; // Requires this Moodle version (2.9). $plugin->cron = 0; // Period for cron to check this module (secs). $plugin->component = 'mod_customcert'; $plugin->maturity = MATURITY_BETA; -$plugin->release = "Beta release"; // User-friendly version number. +$plugin->release = "Beta release (Build: 2016021900)"; // User-friendly version number. diff --git a/view.php b/view.php index 08fb585..93923df 100644 --- a/view.php +++ b/view.php @@ -23,7 +23,6 @@ */ require_once('../../config.php'); -require_once($CFG->dirroot . '/mod/customcert/locallib.php'); $id = required_param('id', PARAM_INT); $action = optional_param('action', '', PARAM_ALPHA); @@ -31,6 +30,7 @@ $action = optional_param('action', '', PARAM_ALPHA); $cm = get_coursemodule_from_id('customcert', $id, 0, false, MUST_EXIST); $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST); $customcert = $DB->get_record('customcert', array('id' => $cm->instance), '*', MUST_EXIST); +$template = $DB->get_record('customcert_templates', array('id' => $customcert->templateid), '*', MUST_EXIST); // Ensure the user is allowed to view this page. require_login($course, false, $cm); @@ -39,15 +39,11 @@ require_capability('mod/customcert:view', $context); // Initialise $PAGE. $pageurl = new moodle_url('/mod/customcert/view.php', array('id' => $cm->id)); -$PAGE->set_url($pageurl); -$PAGE->set_context($context); -$PAGE->set_cm($cm); -$PAGE->set_title(format_string($customcert->name)); -$PAGE->set_heading(format_string($course->fullname)); +\mod_customcert\page_helper::page_setup($pageurl, $context, format_string($customcert->name)); // Check if the user can view the certificate based on time spent in course. if ($customcert->requiredtime && !has_capability('mod/certificate:manage', $context)) { - if (customcert_get_course_time($course->id) < ($customcert->requiredtime * 60)) { + if (\mod_customcert\certificate::get_course_time($course->id) < ($customcert->requiredtime * 60)) { $a = new stdClass; $a->requiredtime = $customcert->requiredtime; notice(get_string('requiredtimenotmet', 'certificate', $a), "$CFG->wwwroot/course/view.php?id=$course->id"); @@ -66,7 +62,7 @@ if (empty($action)) { $reportlink = ''; if (has_capability('mod/customcert:manage', $context)) { // Get the total number of issues. - $numissues = customcert_get_number_of_issues($customcert->id, $cm, $groupmode); + $numissues = \mod_customcert\certificate::get_number_of_issues($customcert->id, $cm, $groupmode); $href = new moodle_urL('/mod/customcert/report.php', array('id' => $cm->id)); $url = html_writer::tag('a', get_string('viewcustomcertissues', 'customcert', $numissues), array('href' => $href->out())); @@ -121,11 +117,12 @@ if (empty($action)) { $customcertissue = new stdClass(); $customcertissue->customcertid = $customcert->id; $customcertissue->userid = $USER->id; - $customcertissue->code = customcert_generate_code(); + $customcertissue->code = \mod_customcert\certificate::generate_code(); $customcertissue->timecreated = time(); // Insert the record into the database. $DB->insert_record('customcert_issues', $customcertissue); } // Now we want to generate the PDF. - customcert_generate_pdf($customcert); + $template = new \mod_customcert\template($template); + $template->generate_pdf(); } diff --git a/yui/src/rearrange.js b/yui/src/rearrange.js index 07454dd..11dd0de 100644 --- a/yui/src/rearrange.js +++ b/yui/src/rearrange.js @@ -6,7 +6,7 @@ M.mod_customcert.rearrange = { /** * The course module id. */ - cmid : 0, + templateid : 0, /** * The customcert page we are displaying. @@ -63,13 +63,13 @@ M.mod_customcert.rearrange = { * Initialise. * * @param Y - * @param cmid + * @param templateid * @param page * @param elements */ - init : function(Y, cmid, page, elements) { + init : function(Y, templateid, page, elements) { // Set the course module id. - this.cmid = cmid; + this.templateid = templateid; // Set the page. this.page = page; // Set the elements. @@ -224,7 +224,7 @@ M.mod_customcert.rearrange = { save_positions : function(e) { // The parameters to send the AJAX call. var params = { - cmid: this.cmid, + tid: this.templateid, values: [] }; @@ -268,7 +268,15 @@ M.mod_customcert.rearrange = { }, success: function() { var formNode = e.currentTarget.ancestor('form', true); - window.location = formNode.getAttribute('action') + '?' + Y.QueryString.stringify({cmid:formNode.one('[name=cmid]').get('value')}); + var baseUrl = formNode.getAttribute('action'); + var pageinput = formNode.one('[name=pid]'); + if (pageinput) { + var pageid = pageinput.get('value'); + window.location = baseUrl + '?pid=' + pageid; + } else { + var templateid = formNode.one('[name=tid]').get('value'); + window.location = baseUrl + '?tid=' + templateid; + } } }, context: this