From be5526be2a22a940f60644361d3a8376ca1f925f Mon Sep 17 00:00:00 2001 From: Kordan Date: Tue, 20 Feb 2024 21:18:23 +0100 Subject: [PATCH] Assigned a class to each landing page In the frame of this PR I also tried to provide a better name to managers. The rationale of this PR is to assign to each section of each area of surveypro a specific class. Once each section will use its specific class it will be simple to: - better debug the code; - make code improvements; - create unit tests. As far as I know, this PR along with #932 and #931, accomplishes this goal. What was in my mind (and I hope I reached this target) was to assign a specific class to each landing page of sPro. In other words... sPro is divided into 6 areas and each area is divided into sections. The structure of sPro, is: [Spro area] surveypro (managed in view.php) - [Area section] cover - [Area section] submissionslist - [Area section] submissionform - [Area section] searchsubmissions [Spro area] layout (managed in layout.php) - [Area section] itemslist - [Area section] itemsetup - [Area section] branchingvalidation - [Area section] preview [Spro area] reports (managed in reports.php) - [report] attachement overview - [report] frequency distribution - [report] late users - [report] responses per user - [report] users per count of responses [Spro area] tools (managed in tools.php) - [Area section] export - [Area section] import [Spro area] user templates (managed in utemplates.php) - [Area section] manage - [Area section] save - [Area section] import - [Area section] apply [Spro area] master templates (managed in mtemplates.php) - [Area section] save - [Area section] apply Well, if I am not wrong, now each section uses a specific class. (reports are an exception) Names of classes always start with the name of the area and ends with the name of the section. They are: [Spro area] surveypro (managed in view.php) - [Area section] cover -----------------------------------> view_cover - [Area section] submissionslist -------------------------> view_submissionlist - [Area section] submissionform --------------------------> view_submissionform - [Area section] searchsubmissions -----------------------> view_submissionsearch [Spro area] layout (managed in layout.php) - [Area section] itemslist -------------------------------> layout_itemlist - [Area section] itemsetup -------------------------------> layout_itemsetup - [Area section] branchingvalidation ---------------------> layout_branchingvalidation - [Area section] preview ---------------------------------> layout_preview [Spro area] reports (managed in reports.php) - [report] attachement overview --------------------------> report from its own specific plugin classes - [report] frequency distribution ------------------------> report from its own specific plugin classes - [report] late users ------------------------------------> report from its own specific plugin classes - [report] responses per user ----------------------------> report from its own specific plugin classes - [report] users per count of responses ------------------> report from its own specific plugin classes [Spro area] tools (managed in tools.php) - [Area section] export -----------------------------------> tools_export - [Area section] import -----------------------------------> tools_import [Spro area] user templates (managed in utemplates.php) - [Area section] manage -----------------------------------> utemplate_manage - [Area section] save -------------------------------------> utemplate_save - [Area section] import -----------------------------------> utemplate_import - [Area section] apply ------------------------------------> utemplate_apply [Spro area] master templates (managed in mtemplates.php) - [Area section] save -------------------------------------> mtemplate_save - [Area section] apply ------------------------------------> mtemplate_apply The corresponding manager (still, if I am not wrong) is named with the name of the section and finishes with 'man'. So, for instance: corverman, itemlistman, exportman, manageman and so forth. --- classes/itembase.php | 38 +- classes/layout_branchingvalidation.php | 271 ++ classes/layout_itemlist.php | 2324 +++++++++++++++++ classes/layout_itemsetup.php | 2073 +-------------- classes/layout_preview.php | 2 +- classes/local/form/mtemplate_applyform.php | 8 +- classes/local/form/utemplate_createform.php | 10 +- classes/local/form/utemplate_importform.php | 14 +- classes/mtemplate_apply.php | 293 +++ classes/mtemplate_base.php | 60 + ...{mastertemplate.php => mtemplate_save.php} | 419 +-- classes/tools_export.php | 2 +- classes/tools_import.php | 2 +- classes/usertemplate.php | 1199 --------- classes/utemplate_apply.php | 405 +++ classes/utemplate_base.php | 239 ++ classes/utemplate_import.php | 196 ++ classes/utemplate_manage.php | 390 +++ classes/utemplate_save.php | 230 ++ classes/utility_page.php | 2 +- classes/utility_submission.php | 2 +- classes/{cover.php => view_cover.php} | 4 +- ...sions_form.php => view_submissionform.php} | 4 +- ...sions_list.php => view_submissionlist.php} | 4 +- ...s_search.php => view_submissionsearch.php} | 4 +- layout.php | 171 +- mtemplates.php | 35 +- report/attachments/view.php | 2 +- tests/mastertemplate_test.php | 8 +- tools.php | 4 +- utemplates.php | 103 +- version.php | 2 +- view.php | 96 +- 33 files changed, 4749 insertions(+), 3867 deletions(-) create mode 100644 classes/layout_branchingvalidation.php create mode 100644 classes/layout_itemlist.php create mode 100644 classes/mtemplate_apply.php create mode 100644 classes/mtemplate_base.php rename classes/{mastertemplate.php => mtemplate_save.php} (64%) delete mode 100644 classes/usertemplate.php create mode 100644 classes/utemplate_apply.php create mode 100644 classes/utemplate_base.php create mode 100644 classes/utemplate_import.php create mode 100644 classes/utemplate_manage.php create mode 100644 classes/utemplate_save.php rename classes/{cover.php => view_cover.php} (99%) rename classes/{submissions_form.php => view_submissionform.php} (99%) rename classes/{submissions_list.php => view_submissionlist.php} (99%) rename classes/{submissions_search.php => view_submissionsearch.php} (98%) diff --git a/classes/itembase.php b/classes/itembase.php index c1559925ec1..62688ef56c7 100644 --- a/classes/itembase.php +++ b/classes/itembase.php @@ -619,22 +619,23 @@ private function item_manage_chains($itemid, $oldhidden, $newhidden, $oldreserve if ($oldhidden != $newhidden) { $action = ($oldhidden) ? SURVEYPRO_SHOWITEM : SURVEYPRO_HIDEITEM; - $layoutman = new layout_itemsetup($this->cm, $context, $this->surveypro); - $layoutman->set_type($this->type); - $layoutman->set_plugin($this->plugin); - $layoutman->set_itemid($itemid); - $layoutman->set_action($action); - $layoutman->set_view(SURVEYPRO_NOMODE); - $layoutman->set_confirm(SURVEYPRO_CONFIRMED_YES); + $itemsetupman = new layout_itemsetup($this->cm, $context, $this->surveypro); + $itemsetupman->setup(); + $itemsetupman->set_type($this->type); + $itemsetupman->set_plugin($this->plugin); + $itemsetupman->set_itemid($itemid); + $itemsetupman->set_action($action); + $itemsetupman->set_view(SURVEYPRO_NOMODE); + $itemsetupman->set_confirm(SURVEYPRO_CONFIRMED_YES); // Begin of: Hide/unhide part 2. if ( ($oldhidden == 1) && ($newhidden == 0) ) { - $layoutman->item_show_execute(); + $itemsetupman->item_show_execute(); // A chain of parent items was shown. $this->itemeditingfeedback += 4; // 1*2^2. } if ( ($oldhidden == 0) && ($newhidden == 1) ) { - $layoutman->item_hide_execute(); + $itemsetupman->item_hide_execute(); // Chain of children items was hided. $this->itemeditingfeedback += 8; // 1*2^3. } @@ -645,23 +646,24 @@ private function item_manage_chains($itemid, $oldhidden, $newhidden, $oldreserve if ($oldreserved != $newreserved) { $action = ($oldreserved) ? SURVEYPRO_MAKEAVAILABLE : SURVEYPRO_MAKERESERVED; - $layoutman = new layout_itemsetup($this->cm, $context, $this->surveypro); - $layoutman->set_type($this->type); - $layoutman->set_plugin($this->plugin); - $layoutman->set_itemid($itemid); - $layoutman->set_action($action); - $layoutman->set_view(SURVEYPRO_NOMODE); - $layoutman->set_confirm(SURVEYPRO_CONFIRMED_YES); + $itemsetupman = new layout_itemsetup($this->cm, $context, $this->surveypro); + $itemsetupman->setup(); + $itemsetupman->set_type($this->type); + $itemsetupman->set_plugin($this->plugin); + $itemsetupman->set_itemid($itemid); + $itemsetupman->set_action($action); + $itemsetupman->set_view(SURVEYPRO_NOMODE); + $itemsetupman->set_confirm(SURVEYPRO_CONFIRMED_YES); // Begin of: Make reserved/free part 2. if ( ($oldreserved == 1) && ($newreserved == 0) ) { - if ($layoutman->item_makeavailable_execute()) { + if ($itemsetupman->item_makeavailable_execute()) { // A chain of parents items inherited free access. $this->itemeditingfeedback += 16; // 1*2^4. } } if ( ($oldreserved == 0) && ($newreserved == 1) ) { - if ($layoutman->item_makereserved_execute()) { + if ($itemsetupman->item_makereserved_execute()) { // A chain of children items inherited reserved access. $this->itemeditingfeedback += 32; // 1*2^5. } diff --git a/classes/layout_branchingvalidation.php b/classes/layout_branchingvalidation.php new file mode 100644 index 00000000000..86268db63cc --- /dev/null +++ b/classes/layout_branchingvalidation.php @@ -0,0 +1,271 @@ +. + +/** + * Surveypro layout class. + * + * @package mod_surveypro + * @copyright 2013 onwards kordan + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_surveypro; + +/** + * The base class representing the list of elements of this surveypro + * + * @package mod_surveypro + * @copyright 2013 onwards kordan + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class layout_branchingvalidation { + + /** + * @var object Course module object + */ + protected $cm; + + /** + * @var object Context object + */ + protected $context; + + /** + * @var object Surveypro object + */ + protected $surveypro; + + /** + * Class constructor. + * + * @param object $cm + * @param object $context + * @param object $surveypro + */ + public function __construct($cm, $context, $surveypro) { + $this->cm = $cm; + $this->context = $context; + $this->surveypro = $surveypro; + } + + /** + * Display the "validate_relations" table. + * + * @return void + */ + public function display_relations_table() { + global $CFG, $DB, $OUTPUT; + + require_once($CFG->libdir.'/tablelib.php'); + + $statusstr = get_string('relation_status', 'mod_surveypro'); + $table = new \flexible_table('relations'); + + $paramurl = ['s' => $this->cm->instance, 'section' => 'branchingvalidation']; + $baseurl = new \moodle_url('/mod/surveypro/layout.php', $paramurl); + $table->define_baseurl($baseurl); + + $tablecolumns = []; + $tablecolumns[] = 'plugin'; + $tablecolumns[] = 'sortindex'; + $tablecolumns[] = 'parentitem'; + $tablecolumns[] = 'customnumber'; + $tablecolumns[] = 'content'; + $tablecolumns[] = 'parentconstraints'; + $tablecolumns[] = 'status'; + $tablecolumns[] = 'actions'; + $table->define_columns($tablecolumns); + + $tableheaders = []; + $tableheaders[] = get_string('typeplugin', 'mod_surveypro'); + $tableheaders[] = get_string('sortindex', 'mod_surveypro'); + $tableheaders[] = get_string('branching', 'mod_surveypro'); + $tableheaders[] = get_string('customnumber_header', 'mod_surveypro'); + $tableheaders[] = get_string('content', 'mod_surveypro'); + $tableheaders[] = get_string('parentconstraints', 'mod_surveypro'); + $tableheaders[] = $statusstr; + $tableheaders[] = get_string('actions'); + $table->define_headers($tableheaders); + + $table->column_class('plugin', 'plugin'); + $table->column_class('sortindex', 'sortindex'); + $table->column_class('parentitem', 'parentitem'); + $table->column_class('customnumber', 'customnumber'); + $table->column_class('content', 'content'); + $table->column_class('parentconstraints', 'parentconstraints'); + $table->column_class('status', 'status'); + $table->column_class('actions', 'actions'); + + // General properties for the whole table. + $table->set_attribute('id', 'validaterelations'); + $table->set_attribute('class', 'generaltable'); + $table->setup(); + + $okstr = get_string('ok'); + + $iconparams = []; + + $editstr = get_string('edit'); + $iconparams = ['title' => $editstr]; + $editicn = new \pix_icon('t/edit', $editstr, 'moodle', $iconparams); + + $parentelementstr = get_string('parentelement_title', 'mod_surveypro'); + $iconparams = ['title' => $parentelementstr]; + $branchicn = new \pix_icon('branch', $parentelementstr, 'surveypro', $iconparams); + + // Get parents id only. + $sql = 'SELECT DISTINCT id as paretid, 1 + FROM {surveypro_item} parent + WHERE EXISTS ( + SELECT \'x\' + FROM {surveypro_item} child + WHERE child.parentid = parent.id) + AND surveyproid = ?'; + $whereparams = [$this->surveypro->id]; + $isparent = $DB->get_records_sql_menu($sql, $whereparams); + + // Get itemseeds. + $sql = 'SELECT DISTINCT id as itemid, plugin, type, sortindex + FROM {surveypro_item} parent + WHERE EXISTS ( + SELECT \'x\' + FROM {surveypro_item} child + WHERE child.parentid = parent.id) + AND surveyproid = ? + + UNION + + SELECT DISTINCT id as itemid, plugin, type, sortindex + FROM {surveypro_item} + WHERE surveyproid = ? + AND parentid > 0 + + ORDER BY sortindex;'; + $whereparams = [$this->surveypro->id, $this->surveypro->id]; + $itemseeds = $DB->get_recordset_sql($sql, $whereparams); + + $message = get_string('welcome_relationvalidation', 'mod_surveypro', $statusstr); + echo $OUTPUT->notification($message, 'notifymessage'); + + foreach ($itemseeds as $itemseed) { + $item = surveypro_get_item($this->cm, $this->surveypro, $itemseed->itemid, $itemseed->type, $itemseed->plugin, true); + $itemishidden = $item->get_hidden(); + + if ($item->get_parentid()) { + // Here I do not know type and plugin. + $parentitem = surveypro_get_item($this->cm, $this->surveypro, $item->get_parentid()); + } + + $tablerow = []; + + // Plugin. + $component = 'surveypro'.$item->get_type().'_'.$item->get_plugin(); + $alt = get_string('pluginname', $component); + $iconparams = ['title' => $alt, 'class' => 'icon']; + $content = $OUTPUT->pix_icon('icon', $alt, $component, $iconparams); + $tablerow[] = $content; + + // Sortindex. + $tablerow[] = $item->get_sortindex(); + + // Parentid. + if ($item->get_parentid()) { + $content = $parentitem->get_sortindex(); + $content .= \html_writer::tag('span', $OUTPUT->render($branchicn), ['class' => 'branch']); + $content .= $item->get_parentcontent('; '); + } else { + $content = ''; + } + $tablerow[] = $content; + + // Customnumber. + if (($item->get_type() == SURVEYPRO_TYPEFIELD) || ($item->get_plugin() == 'label')) { + $tablerow[] = $item->get_customnumber(); + } else { + $tablerow[] = ''; + } + + // Content. + $tablerow[] = $item->get_content(); + + // Parentconstraints. + if (isset($isparent[$itemseed->itemid])) { + $tablerow[] = $item->item_list_constraints(); + } else { + $tablerow[] = '-'; + } + + // Status. + if ($item->get_parentid()) { + $status = $parentitem->parent_validate_child_constraints($item->get_parentvalue()); + if ($status == SURVEYPRO_CONDITIONOK) { + $tablerow[] = $okstr; + } else { + if ($status == SURVEYPRO_CONDITIONNEVERMATCH) { + if (empty($itemishidden)) { + $errormessage = \html_writer::start_tag('span', ['class' => 'errormessage']); + $errormessage .= get_string('wrongrelation', 'mod_surveypro', $item->get_parentcontent('; ')); + $errormessage .= \html_writer::end_tag('span'); + $tablerow[] = $errormessage; + } else { + $tablerow[] = get_string('wrongrelation', 'mod_surveypro', $item->get_parentcontent('; ')); + } + } + if ($status == SURVEYPRO_CONDITIONMALFORMED) { + if (empty($itemishidden)) { + $errormessage = \html_writer::start_tag('span', ['class' => 'errormessage']); + $errormessage .= get_string('badchildparentvalue', 'mod_surveypro', $item->get_parentcontent('; ')); + $errormessage .= \html_writer::end_tag('span'); + $tablerow[] = $errormessage; + } else { + $tablerow[] = get_string('badchildparentvalue', 'mod_surveypro', $item->get_parentcontent('; ')); + } + } + } + } else { + $tablerow[] = '-'; + } + + // Actions. + // Begin of: $paramurlbase definition. + $paramurlbase = []; + $paramurlbase['s'] = $this->cm->instance; + $paramurlbase['itemid'] = $item->get_itemid(); + $paramurlbase['type'] = $item->get_type(); + $paramurlbase['plugin'] = $item->get_plugin(); + $paramurlbase['section'] = 'itemsetup'; + // End of $paramurlbase definition. + + // SURVEYPRO_NEWITEM. + $paramurl = $paramurlbase; + $paramurl['mode'] = SURVEYPRO_NEWITEM; + + $link = new \moodle_url('/mod/surveypro/layout.php', $paramurl); + $paramlink = ['id' => 'edit_'.$item->get_itemid(), 'title' => $editstr]; + $icons = $OUTPUT->action_icon($link, $editicn, null, $paramlink); + + $tablerow[] = $icons; + + $rowclass = empty($itemishidden) ? '' : 'dimmed'; + $table->add_data($tablerow, $rowclass); + } + $itemseeds->close(); + + $table->set_attribute('align', 'center'); + $table->summary = get_string('itemlist', 'mod_surveypro'); + $table->print_html(); + } +} diff --git a/classes/layout_itemlist.php b/classes/layout_itemlist.php new file mode 100644 index 00000000000..9f75cb6b51b --- /dev/null +++ b/classes/layout_itemlist.php @@ -0,0 +1,2324 @@ +. + +/** + * Surveypro layout class. + * + * @package mod_surveypro + * @copyright 2013 onwards kordan + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_surveypro; + +use core_text; +use mod_surveypro\local\ipe\layout_customnumber; +use mod_surveypro\local\ipe\layout_insearchform; +use mod_surveypro\local\ipe\layout_required; +use mod_surveypro\local\ipe\layout_reserved; +use mod_surveypro\local\ipe\layout_variable; +use mod_surveypro\utility_layout; + +/** + * The base class representing the list of elements of this surveypro + * + * @package mod_surveypro + * @copyright 2013 onwards kordan + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class layout_itemlist { + + /** + * @var object Course module object + */ + protected $cm; + + /** + * @var object Context object + */ + protected $context; + + /** + * @var object Surveypro object + */ + protected $surveypro; + + /** + * @var string Type of the leading item + */ + protected $type; + + /** + * @var string Plugin of the leading item + */ + protected $plugin; + + /** + * @var int Id of the leading item + */ + protected $rootitemid; + + /** + * @var int Sortindex of the leading item + */ + protected $sortindex; + + /** + * @var int Required action + */ + protected $action; + + /** + * @var int Required mode + */ + protected $mode; + + /** + * @var int Id of the item to move + */ + protected $itemtomove; + + /** + * @var int Id of the last item before the moving one + */ + protected $lastitembefore; + + /** + * @var int User confirmation to actions + */ + protected $confirm; + + /** + * @var int New indent requested for $itemid + */ + protected $nextindent; + + /** + * @var int Id of the parent item of $itemid + */ + protected $parentid; + + /** + * @var bool True if this surveypro has submissions; false otherwise + */ + protected $hassubmissions; + + /** + * @var int Count of the items of this surveypro + */ + protected $itemcount; + + /** + * @var int Binary number providing a mask for the feedback of the item editing + */ + protected $itemeditingfeedback; + + /** + * @var StdClass object with the feedback for the user + */ + protected $actionfeedback; + + /** + * Class constructor. + * + * @param object $cm + * @param object $context + * @param object $surveypro + */ + public function __construct($cm, $context, $surveypro) { + $this->cm = $cm; + $this->context = $context; + $this->surveypro = $surveypro; + } + + /** + * Setup. + * + * @return void + */ + public function setup() { + $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); + $itemcount = $utilitylayoutman->has_items(0, null, true, true, true); + $this->set_itemcount($itemcount); + } + + /** + * Display all the items in a table. + * + * @return void + */ + public function display_items_table() { + global $CFG, $DB, $OUTPUT; + + require_once($CFG->libdir.'/tablelib.php'); + + $riskyediting = ($this->surveypro->riskyeditdeadline > time()); + + $table = new \flexible_table('itemslist'); + + $paramurl = ['s' => $this->cm->instance, 'section' => 'itemslist']; + $baseurl = new \moodle_url('/mod/surveypro/layout.php', $paramurl); + $table->define_baseurl($baseurl); + + $tablecolumns = []; + $tablecolumns[] = 'plugin'; + $tablecolumns[] = 'sortindex'; + $tablecolumns[] = 'parentid'; + $tablecolumns[] = 'customnumber'; + $tablecolumns[] = 'content'; + $tablecolumns[] = 'variable'; + $tablecolumns[] = 'formpage'; + $tablecolumns[] = 'availability'; + $tablecolumns[] = 'actions'; + $table->define_columns($tablecolumns); + + $tableheaders = []; + $tableheaders[] = get_string('typeplugin', 'mod_surveypro'); + $tableheaders[] = get_string('sortindex', 'mod_surveypro'); + $tableheaders[] = get_string('branching', 'mod_surveypro'); + $tableheaders[] = get_string('customnumber_header', 'mod_surveypro'); + $tableheaders[] = get_string('content', 'mod_surveypro'); + $tableheaders[] = get_string('variable', 'mod_surveypro'); + $tableheaders[] = get_string('page'); + $tableheaders[] = get_string('availability', 'mod_surveypro'); + $tableheaders[] = get_string('actions'); + $table->define_headers($tableheaders); + + $table->sortable(true, 'sortindex'); // Sorted by sortindex by default. + $table->no_sorting('customnumber'); + $table->no_sorting('content'); + $table->no_sorting('variable'); + $table->no_sorting('availability'); + $table->no_sorting('actions'); + + $table->column_class('plugin', 'plugin'); + $table->column_class('sortindex', 'sortindex'); + $table->column_class('parentid', 'parentitem'); + $table->column_class('customnumber', 'customnumber'); + $table->column_class('content', 'content'); + $table->column_class('variable', 'variable'); + $table->column_class('formpage', 'formpage'); + $table->column_class('availability', 'availability'); + $table->column_class('actions', 'actions'); + + // General properties for the whole table. + if ($this->mode == SURVEYPRO_CHANGEORDERASK) { + $table->set_attribute('id', 'sortitems'); + } else { + $table->set_attribute('id', 'manageitems'); + } + $table->set_attribute('class', 'generaltable'); + $table->setup(); + + // Strings. + $iconparams = []; + // Icons for further use. + $editstr = get_string('edit'); + $iconparams = ['title' => $editstr]; + $editicn = new \pix_icon('t/edit', $editstr, 'moodle', $iconparams); + + $parentelementstr = get_string('parentelement_title', 'mod_surveypro'); + $iconparams = ['title' => $parentelementstr]; + $branchicn = new \pix_icon('branch', $parentelementstr, 'surveypro', $iconparams); + + $reorderstr = get_string('changeorder_title', 'mod_surveypro'); + $iconparams = ['title' => $reorderstr]; + $moveicn = new \pix_icon('t/move', $editstr, 'moodle', $iconparams); + + $hidestr = get_string('hidefield_title', 'mod_surveypro'); + $iconparams = ['title' => $hidestr]; + $hideicn = new \pix_icon('i/hide', $hidestr, 'moodle', $iconparams); + + $showstr = get_string('showfield_title', 'mod_surveypro'); + $iconparams = ['title' => $showstr]; + $showicn = new \pix_icon('i/show', $showstr, 'moodle', $iconparams); + + $deletestr = get_string('delete'); + $iconparams = ['title' => $deletestr]; + $deleteicn = new \pix_icon('t/delete', $deletestr, 'moodle', $iconparams); + + $indentstr = get_string('indent', 'mod_surveypro'); + $iconparams = ['title' => $indentstr]; + $lefticn = new \pix_icon('t/left', $indentstr, 'moodle', $iconparams); + $righticn = new \pix_icon('t/right', $indentstr, 'moodle', $iconparams); + + $moveherestr = get_string('movehere'); + $movehereicn = new \pix_icon('movehere', $moveherestr, 'moodle', ['title' => $moveherestr, 'class' => 'placeholder']); + + $availablestr = get_string('available_title', 'mod_surveypro'); + $iconparams = ['title' => $availablestr]; + $freeicn = new \pix_icon('free', $availablestr, 'surveypro', $iconparams); + + $reservedstr = get_string('reserved_title', 'mod_surveypro'); + $iconparams = ['title' => $reservedstr]; + $reservedicn = new \pix_icon('reserved', $reservedstr, 'surveypro', $iconparams); + + $unreservablestr = get_string('unreservable_title', 'mod_surveypro'); + $iconparams = ['title' => $unreservablestr]; + $unreservableicn = new \pix_icon('unreservable', $unreservablestr, 'surveypro', $iconparams); + + $unsearchablestr = get_string('unsearchable_title', 'mod_surveypro'); + $iconparams = ['title' => $unsearchablestr]; + $unsearchableicn = new \pix_icon('unsearchable', $unsearchablestr, 'surveypro', $iconparams); + + $unavailablestr = get_string('unavailableelement_title', 'mod_surveypro'); + $iconparams = ['title' => $unavailablestr]; + $unavailableicn = new \pix_icon('unavailable', $unavailablestr, 'surveypro', $iconparams); + + $forcedoptionalitemstr = get_string('forcedoptionalitem_title', 'mod_surveypro'); + $iconparams = ['title' => $forcedoptionalitemstr]; + $lockedgreenicn = new \pix_icon('lockedgreen', $forcedoptionalitemstr, 'surveypro', $iconparams); + + // Begin of: $paramurlmove definition. + $paramurlmove = []; + $paramurlmove['s'] = $this->cm->instance; + $paramurlmove['act'] = SURVEYPRO_CHANGEORDER; + $paramurlmove['itm'] = $this->itemtomove; + // End of: $paramurlmove definition. + + [$where, $params] = surveypro_fetch_items_seeds($this->surveypro->id, false, true, null, null, null, true); + // If you are reordering, force ordering to... + $orderby = ($this->mode == SURVEYPRO_CHANGEORDERASK) ? 'sortindex ASC' : $table->get_sql_sort(); + $itemseeds = $DB->get_recordset_select('surveypro_item', $where, $params, $orderby, 'id as itemid, type, plugin'); + + // This is the very first position, so if the item has a parent, no "moveherebox" must appear. + if (($this->mode == SURVEYPRO_CHANGEORDERASK) && (!$this->parentid)) { + $drawmoveherebox = true; + $paramurl = $paramurlmove; + $paramurl['lib'] = 0; // Move just after this sortindex (lib == last item before). + $paramurl['section'] = 'itemslist'; + $paramurl['sesskey'] = sesskey(); + + $link = new \moodle_url('/mod/surveypro/layout.php', $paramurl); + $paramlink = ['id' => 'moveafter_0', 'title' => $moveherestr]; + $icons = $OUTPUT->action_icon($link, $movehereicn, null, $paramlink); + + $tablerow = []; + $tablerow[] = $icons; + $tablerow = array_pad($tablerow, count($table->columns), ''); + + $table->add_data($tablerow); + } else { + $drawmoveherebox = false; + } + + foreach ($itemseeds as $itemseed) { + $item = surveypro_get_item($this->cm, $this->surveypro, $itemseed->itemid, $itemseed->type, $itemseed->plugin, true); + $itemid = $itemseed->itemid; + $itemishidden = $item->get_hidden(); + $sortindex = $item->get_sortindex(); + + // Begin of: $paramurlbase definition. + $paramurlbase = []; + $paramurlbase['s'] = $this->cm->instance; + $paramurlbase['itemid'] = $item->get_itemid(); + $paramurlbase['type'] = $item->get_type(); + $paramurlbase['plugin'] = $item->get_plugin(); + // End of: $paramurlbase definition. + + $tablerow = []; + + if (($this->mode == SURVEYPRO_CHANGEORDERASK) && ($item->get_itemid() == $this->rootitemid)) { + // Do not draw the item you are going to move. + continue; + } + + // Plugin. + $component = 'surveypro'.$item->get_type().'_'.$item->get_plugin(); + $alt = get_string('userfriendlypluginname', $component); + $content = \html_writer::tag('a', '', ['name' => 'sortindex_'.$sortindex]); + $iconparams = ['title' => $alt]; + $icon = $OUTPUT->pix_icon('icon', $alt, $component, $iconparams); + $content .= \html_writer::tag('span', $icon, ['class' => 'pluginicon']); + + $tablerow[] = $content; + + // Sortindex. + $tablerow[] = $sortindex; + + // Parentid. + if ($item->get_parentid()) { + $parentsortindex = $DB->get_field('surveypro_item', 'sortindex', ['id' => $item->get_parentid()]); + $content = $parentsortindex; + $content .= \html_writer::tag('span', $OUTPUT->render($branchicn), ['class' => 'branch']); + $content .= $item->get_parentcontent('; '); + } else { + $content = ''; + } + $tablerow[] = $content; + + // Customnumber. + if (($item->get_type() == SURVEYPRO_TYPEFIELD) || ($item->get_plugin() == 'label')) { + $itemid = $item->get_itemid(); + $customnumber = $item->get_customnumber(); + $tmpl = new layout_customnumber($itemid, $customnumber); + + $tablerow[] = $OUTPUT->render_from_template('core/inplace_editable', $tmpl->export_for_template($OUTPUT)); + } else { + $tablerow[] = ''; + } + + // Content. + $tablerow[] = $item->get_content(); + + // Variable. + if ($item->get_type() == SURVEYPRO_TYPEFIELD) { + $itemid = $item->get_itemid(); + $variablename = $item->get_variable(); + $tmpl = new layout_variable($itemid, $variablename); + + $tablerow[] = $OUTPUT->render_from_template('core/inplace_editable', $tmpl->export_for_template($OUTPUT)); + } else { + $tablerow[] = ''; + } + + // Page. + if ($item->item_uses_form_page()) { + $content = $item->get_formpage(); + } else { + $content = ''; + } + $tablerow[] = $content; + + // Availability. + $icons = ''; + // First icon: reserved vs generally available. + if (!$itemishidden) { + if ($item->get_insetupform('reserved')) { + $reserved = $item->get_reserved(); + if ($item->item_has_children() || $item->item_is_child()) { + $paramurl = $paramurlbase; + if ($reserved) { + $paramurl['act'] = SURVEYPRO_MAKEAVAILABLE; + $paramurl['sortindex'] = $sortindex; + $paramurl['section'] = 'itemslist'; + $paramurl['sesskey'] = sesskey(); + + $link = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$sortindex, $paramurl); + $paramlink = ['id' => 'makeavailable_item_'.$sortindex, 'title' => $reservedstr]; + $actionicon = $OUTPUT->action_icon($link, $reservedicn, null, $paramlink); + $icons .= \html_writer::tag('span', $actionicon, ['class' => 'reserveitem']); + } else { + $paramurl['act'] = SURVEYPRO_MAKERESERVED; + $paramurl['sortindex'] = $sortindex; + $paramurl['section'] = 'itemslist'; + $paramurl['sesskey'] = sesskey(); + + $link = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$sortindex, $paramurl); + $paramlink = ['id' => 'makereserved_item_'.$sortindex, 'title' => $availablestr]; + $actionicon = $OUTPUT->action_icon($link, $freeicn, null, $paramlink); + $icons .= \html_writer::tag('span', $actionicon, ['class' => 'freeitem']); + } + } else { + $tmpl = new layout_reserved($itemid, $reserved, $sortindex); + $tmpl->set_type_toggle(); + $icons .= $OUTPUT->render_from_template('core/inplace_editable', $tmpl->export_for_template($OUTPUT)); + } + } else { + // Icon only, not a link! + $icons .= \html_writer::tag('span', $OUTPUT->render($unreservableicn), ['class' => 'noactionicon']); + } + } else { + // Icon only, not a link! + $icons .= \html_writer::tag('span', $OUTPUT->render($unavailableicn), ['class' => 'noactionicon']); + } + + // Second icon: insearchform vs notinsearchform. + if (!$itemishidden) { + if ($item->get_insetupform('insearchform')) { + // Second icon: insearchform vs not insearchform. + $insearchform = $item->get_insearchform(); + $tmpl = new layout_insearchform($itemid, $insearchform, $sortindex); + $tmpl->set_type_toggle(); + $icons .= $OUTPUT->render_from_template('core/inplace_editable', $tmpl->export_for_template($OUTPUT)); + } else { + // Icon only, not a link! + $icons .= \html_writer::tag('span', $OUTPUT->render($unsearchableicn), ['class' => 'noactionicon']); + } + } else { + // Icon only, not a link! + $icons .= \html_writer::tag('span', $OUTPUT->render($unavailableicn), ['class' => 'noactionicon']); + } + + // Third icon: hide vs show. + // Here I can not use the cool \core\output\inplace_editable because + // this action make changes not limited to the state of this icon. + if (!$this->hassubmissions || $riskyediting) { + $paramurl = $paramurlbase; + $paramurl['section'] = 'itemslist'; + $paramurl['sesskey'] = sesskey(); + if (empty($itemishidden)) { + $paramurl['act'] = SURVEYPRO_HIDEITEM; + $paramurl['sortindex'] = $sortindex; + $linkidprefix = 'hide_item_'; + } else { + $paramurl['act'] = SURVEYPRO_SHOWITEM; + $paramurl['sortindex'] = $sortindex; + $linkidprefix = 'show_item_'; + } + $link = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$sortindex, $paramurl); + $paramlink = ['id' => $linkidprefix.$sortindex, 'class' => 'icon']; + if (empty($itemishidden)) { + $paramlink['title'] = $hidestr; + $actionicon = $OUTPUT->action_icon($link, $hideicn, null, $paramlink); + $icons .= \html_writer::tag('span', $actionicon, ['class' => 'hideitem']); + } else { + $paramlink['title'] = $showstr; + $actionicon = $OUTPUT->action_icon($link, $showicn, null, $paramlink); + $icons .= \html_writer::tag('span', $actionicon, ['class' => 'showitem']); + } + } + $tablerow[] = $icons; + + // Action icons. + $icons = ''; + if ($this->mode != SURVEYPRO_CHANGEORDERASK) { + // SURVEYPRO_EDITITEM. + $paramurl = $paramurlbase; + $paramurl['mode'] = SURVEYPRO_EDITITEM; + $paramurl['section'] = 'itemsetup'; + + $link = new \moodle_url('/mod/surveypro/layout.php', $paramurl); + $paramlink = ['id' => 'edit_item_'.$sortindex, 'class' => 'icon', 'title' => $editstr]; + $actionicon = $OUTPUT->action_icon($link, $editicn, null, $paramlink); + $icons .= \html_writer::tag('span', $actionicon, ['class' => 'fatspan']); + + // SURVEYPRO_CHANGEORDERASK. + if ($this->itemcount > 1) { + $paramurl = $paramurlbase; + $paramurl['mode'] = SURVEYPRO_CHANGEORDERASK; + $paramurl['itm'] = $sortindex; + $paramurl['section'] = 'itemslist'; + + $currentparentid = $item->get_parentid(); + if (!empty($currentparentid)) { + $paramurl['pid'] = $currentparentid; + } + + $link = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.($sortindex - 1), $paramurl); + $paramlink = ['id' => 'move_item_'.$sortindex, 'class' => 'icon', 'title' => $reorderstr]; + $actionicon = $OUTPUT->action_icon($link, $moveicn, null, $paramlink); + $icons .= \html_writer::tag('span', $actionicon, ['class' => 'fatspan']); + } + + // SURVEYPRO_DELETEITEM. + if (!$this->hassubmissions || $riskyediting) { + $paramurl = $paramurlbase; + $paramurl['act'] = SURVEYPRO_DELETEITEM; + $paramurl['sortindex'] = $sortindex; + $paramurl['section'] = 'itemslist'; + $paramurl['sesskey'] = sesskey(); + + $link = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$sortindex, $paramurl); + $paramlink = ['id' => 'delete_item_'.$sortindex, 'class' => 'icon', 'title' => $deletestr]; + $actionicon = $OUTPUT->action_icon($link, $deleteicn, null, $paramlink); + $icons .= \html_writer::tag('span', $actionicon, ['class' => 'fatspan']); + } + + // SURVEYPRO_REQUIRED ON/OFF. + $currentrequired = $item->get_required(); + if ($currentrequired !== false) { // It may be "not set" as in page_break, autofill or some more. + $paramurl = $paramurlbase; + $paramurl['sesskey'] = sesskey(); + + if ($item->item_canbemandatory()) { + $required = $item->get_required(); + $tmpl = new layout_required($itemid, $required, $sortindex); + $tmpl->set_type_toggle(); + $icons .= $OUTPUT->render_from_template('core/inplace_editable', $tmpl->export_for_template($OUTPUT)); + } else { + $icons .= \html_writer::tag('span', $OUTPUT->render($lockedgreenicn), ['class' => 'noactionicon']); + } + } else { + // Icon only, not a link! + $icons .= \html_writer::tag('span', $OUTPUT->spacer(), ['class' => 'spacericon']); + } + + // SURVEYPRO_CHANGEINDENT. + if ($item->get_insetupform('indent')) { // It may not be set as in page_break, fieldset and some more. + $currentindent = $item->get_indent(); + if ($currentindent !== false) { // It may be false like for labels with fullwidth == 1. + $paramurl = $paramurlbase; + $paramurl['act'] = SURVEYPRO_CHANGEINDENT; + $paramurl['section'] = 'itemslist'; + $paramurl['sesskey'] = sesskey(); + + $actionicon = ''; + $paramlink = ['title' => $indentstr, 'class' => 'lastspan']; + if ($currentindent > 0) { + $indentvalue = $currentindent - 1; + $paramurl['ind'] = $indentvalue; + + $link = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$sortindex, $paramurl); + $paramlink += ['id' => 'reduceindent_item_'.$sortindex]; + $actionicon .= $OUTPUT->action_icon($link, $lefticn, null, $paramlink); + } else { + // Icon only, not a link! + $actionicon .= $OUTPUT->spacer(['class' => 'spacericon']); + } + $actionicon .= '['.$currentindent.']'; + if ($currentindent < 9) { + $indentvalue = $currentindent + 1; + $paramurl['ind'] = $indentvalue; + + $link = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$sortindex, $paramurl); + $paramlink += ['id' => 'increaseindent_item_'.$sortindex]; + $actionicon .= $OUTPUT->action_icon($link, $righticn, null, $paramlink); + } + $icons .= \html_writer::tag('span', $actionicon, ['class' => 'lastspan']); + } + } + } + $tablerow[] = $icons; + + $rowclass = empty($itemishidden) ? '' : 'dimmed'; + $table->add_data($tablerow, $rowclass); + + if ($this->mode == SURVEYPRO_CHANGEORDERASK) { + // It was asked to move the item with: $this->rootitemid and $this->parentid. + if ($this->parentid) { // This is the parentid of the item that I am going to move. + // If a parentid is foreseen then... + // Draw the moveherebox only if the current (already displayed) item has: $item->itemid == $this->parentid. + // Once you start to draw the moveherebox, you will never stop. + $drawmoveherebox = $drawmoveherebox || ($item->get_itemid() == $this->parentid); + + // If you just passed an item with $item->get_parentid == $itemid, stop forever. + if ($item->get_parentid() == $this->rootitemid) { + $drawmoveherebox = false; + } + } else { + $drawmoveherebox = $drawmoveherebox && ($item->get_parentid() != $this->rootitemid); + } + + if (!empty($drawmoveherebox)) { + $paramurl = $paramurlmove; + $paramurl['lib'] = $sortindex; + $paramurl['section'] = 'itemslist'; + $paramurl['sesskey'] = sesskey(); + + $link = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$sortindex, $paramurl); + $paramlink = ['id' => 'move_item_'.$sortindex, 'title' => $moveherestr]; + $icons = $OUTPUT->action_icon($link, $movehereicn, null, $paramlink); + + $tablerow = []; + $tablerow[] = $icons; + $tablerow = array_pad($tablerow, count($table->columns), ''); + + $table->add_data($tablerow); + } + } + } + + $table->set_attribute('align', 'center'); + $table->summary = get_string('itemlist', 'mod_surveypro'); + $table->print_html(); + } + + /** + * Display the "validate_relations" table. + * + * @return void + */ + public function display_relations_table() { + global $CFG, $DB, $OUTPUT; + + require_once($CFG->libdir.'/tablelib.php'); + + $statusstr = get_string('relation_status', 'mod_surveypro'); + $table = new \flexible_table('relations'); + + $paramurl = ['s' => $this->cm->instance, 'section' => 'branchingvalidation']; + $baseurl = new \moodle_url('/mod/surveypro/layout.php', $paramurl); + $table->define_baseurl($baseurl); + + $tablecolumns = []; + $tablecolumns[] = 'plugin'; + $tablecolumns[] = 'sortindex'; + $tablecolumns[] = 'parentitem'; + $tablecolumns[] = 'customnumber'; + $tablecolumns[] = 'content'; + $tablecolumns[] = 'parentconstraints'; + $tablecolumns[] = 'status'; + $tablecolumns[] = 'actions'; + $table->define_columns($tablecolumns); + + $tableheaders = []; + $tableheaders[] = get_string('typeplugin', 'mod_surveypro'); + $tableheaders[] = get_string('sortindex', 'mod_surveypro'); + $tableheaders[] = get_string('branching', 'mod_surveypro'); + $tableheaders[] = get_string('customnumber_header', 'mod_surveypro'); + $tableheaders[] = get_string('content', 'mod_surveypro'); + $tableheaders[] = get_string('parentconstraints', 'mod_surveypro'); + $tableheaders[] = $statusstr; + $tableheaders[] = get_string('actions'); + $table->define_headers($tableheaders); + + $table->column_class('plugin', 'plugin'); + $table->column_class('sortindex', 'sortindex'); + $table->column_class('parentitem', 'parentitem'); + $table->column_class('customnumber', 'customnumber'); + $table->column_class('content', 'content'); + $table->column_class('parentconstraints', 'parentconstraints'); + $table->column_class('status', 'status'); + $table->column_class('actions', 'actions'); + + // General properties for the whole table. + $table->set_attribute('id', 'validaterelations'); + $table->set_attribute('class', 'generaltable'); + $table->setup(); + + $okstr = get_string('ok'); + + $iconparams = []; + + $editstr = get_string('edit'); + $iconparams = ['title' => $editstr]; + $editicn = new \pix_icon('t/edit', $editstr, 'moodle', $iconparams); + + $parentelementstr = get_string('parentelement_title', 'mod_surveypro'); + $iconparams = ['title' => $parentelementstr]; + $branchicn = new \pix_icon('branch', $parentelementstr, 'surveypro', $iconparams); + + // Get parents id only. + $sql = 'SELECT DISTINCT id as paretid, 1 + FROM {surveypro_item} parent + WHERE EXISTS ( + SELECT \'x\' + FROM {surveypro_item} child + WHERE child.parentid = parent.id) + AND surveyproid = ?'; + $whereparams = [$this->surveypro->id]; + $isparent = $DB->get_records_sql_menu($sql, $whereparams); + + // Get itemseeds. + $sql = 'SELECT DISTINCT id as itemid, plugin, type, sortindex + FROM {surveypro_item} parent + WHERE EXISTS ( + SELECT \'x\' + FROM {surveypro_item} child + WHERE child.parentid = parent.id) + AND surveyproid = ? + + UNION + + SELECT DISTINCT id as itemid, plugin, type, sortindex + FROM {surveypro_item} + WHERE surveyproid = ? + AND parentid > 0 + + ORDER BY sortindex;'; + $whereparams = [$this->surveypro->id, $this->surveypro->id]; + $itemseeds = $DB->get_recordset_sql($sql, $whereparams); + + $message = get_string('welcome_relationvalidation', 'mod_surveypro', $statusstr); + echo $OUTPUT->notification($message, 'notifymessage'); + + foreach ($itemseeds as $itemseed) { + $item = surveypro_get_item($this->cm, $this->surveypro, $itemseed->itemid, $itemseed->type, $itemseed->plugin, true); + $itemishidden = $item->get_hidden(); + + if ($item->get_parentid()) { + // Here I do not know type and plugin. + $parentitem = surveypro_get_item($this->cm, $this->surveypro, $item->get_parentid()); + } + + $tablerow = []; + + // Plugin. + $component = 'surveypro'.$item->get_type().'_'.$item->get_plugin(); + $alt = get_string('pluginname', $component); + $iconparams = ['title' => $alt, 'class' => 'icon']; + $content = $OUTPUT->pix_icon('icon', $alt, $component, $iconparams); + $tablerow[] = $content; + + // Sortindex. + $tablerow[] = $item->get_sortindex(); + + // Parentid. + if ($item->get_parentid()) { + $content = $parentitem->get_sortindex(); + $content .= \html_writer::tag('span', $OUTPUT->render($branchicn), ['class' => 'branch']); + $content .= $item->get_parentcontent('; '); + } else { + $content = ''; + } + $tablerow[] = $content; + + // Customnumber. + if (($item->get_type() == SURVEYPRO_TYPEFIELD) || ($item->get_plugin() == 'label')) { + $tablerow[] = $item->get_customnumber(); + } else { + $tablerow[] = ''; + } + + // Content. + $tablerow[] = $item->get_content(); + + // Parentconstraints. + if (isset($isparent[$itemseed->itemid])) { + $tablerow[] = $item->item_list_constraints(); + } else { + $tablerow[] = '-'; + } + + // Status. + if ($item->get_parentid()) { + $status = $parentitem->parent_validate_child_constraints($item->get_parentvalue()); + if ($status == SURVEYPRO_CONDITIONOK) { + $tablerow[] = $okstr; + } else { + if ($status == SURVEYPRO_CONDITIONNEVERMATCH) { + if (empty($itemishidden)) { + $errormessage = \html_writer::start_tag('span', ['class' => 'errormessage']); + $errormessage .= get_string('wrongrelation', 'mod_surveypro', $item->get_parentcontent('; ')); + $errormessage .= \html_writer::end_tag('span'); + $tablerow[] = $errormessage; + } else { + $tablerow[] = get_string('wrongrelation', 'mod_surveypro', $item->get_parentcontent('; ')); + } + } + if ($status == SURVEYPRO_CONDITIONMALFORMED) { + if (empty($itemishidden)) { + $errormessage = \html_writer::start_tag('span', ['class' => 'errormessage']); + $errormessage .= get_string('badchildparentvalue', 'mod_surveypro', $item->get_parentcontent('; ')); + $errormessage .= \html_writer::end_tag('span'); + $tablerow[] = $errormessage; + } else { + $tablerow[] = get_string('badchildparentvalue', 'mod_surveypro', $item->get_parentcontent('; ')); + } + } + } + } else { + $tablerow[] = '-'; + } + + // Actions. + // Begin of: $paramurlbase definition. + $paramurlbase = []; + $paramurlbase['s'] = $this->cm->instance; + $paramurlbase['itemid'] = $item->get_itemid(); + $paramurlbase['type'] = $item->get_type(); + $paramurlbase['plugin'] = $item->get_plugin(); + $paramurlbase['section'] = 'itemsetup'; + // End of $paramurlbase definition. + + // SURVEYPRO_NEWITEM. + $paramurl = $paramurlbase; + $paramurl['mode'] = SURVEYPRO_NEWITEM; + + $link = new \moodle_url('/mod/surveypro/layout.php', $paramurl); + $paramlink = ['id' => 'edit_'.$item->get_itemid(), 'title' => $editstr]; + $icons = $OUTPUT->action_icon($link, $editicn, null, $paramlink); + + $tablerow[] = $icons; + + $rowclass = empty($itemishidden) ? '' : 'dimmed'; + $table->add_data($tablerow, $rowclass); + } + $itemseeds->close(); + + $table->set_attribute('align', 'center'); + $table->summary = get_string('itemlist', 'mod_surveypro'); + $table->print_html(); + } + + /** + * Adds elements to an array starting from initial conditions. + * + * Called by: + * item_show_execute() + * item_show_feedback() + * item_makereserved_execute() + * item_makereserved_feedback() + * item_makeavailable_execute() + * item_makeavailable_feedback() + * + * $additionalcondition is ['hidden' => 1] OR ['reserved' => 1] + * + * @param array $additionalcondition + * @return array $nodelist + */ + public function add_parent_node($additionalcondition) { + global $DB; + + if (!is_array($additionalcondition)) { + $a = 'add_parent_node'; + throw new \moodle_exception('arrayexpected', 'mod_surveypro', null, $a); + } + + $nodelist = [$this->sortindex => $this->rootitemid]; + + // Get the first parentid. + $parentitem = new \stdClass(); + $parentitem->parentid = $DB->get_field('surveypro_item', 'parentid', ['id' => $this->rootitemid]); + + $where = ['id' => $parentitem->parentid] + $additionalcondition; + + while ($parentitem = $DB->get_record('surveypro_item', $where, 'id, parentid, sortindex')) { + $nodelist[$parentitem->sortindex] = (int)$parentitem->id; + $where = ['id' => $parentitem->parentid] + $additionalcondition; + } + + return $nodelist; + } + + /** + * Get the recursive list of children of a specific item. + * This method counts children and children of children for as much generation as it founds. + * + * Called by: + * item_hide_execute() + * item_hide_feedback() + * item_makereserved_execute() + * item_makereserved_feedback() + * item_makeavailable_execute() + * item_makeavailable_feedback() + * item_delete_execute() + * item_delete_feedback() + * + * @param int $baseitemid the id of the root item for the tree of children to get + * @param array $where permanent condition needed to filter target items + * @return object $childrenitems + */ + public function get_children($baseitemid=null, $where=null) { + global $DB; + + if (empty($baseitemid)) { + $baseitemid = $this->rootitemid; + } + + if (empty($where)) { + $where = []; + } + + if (!is_array($where)) { + $a = 'get_children'; + throw new \moodle_exception('arrayexpected', 'mod_surveypro', null, $a); + } + + $idscontainer = [$baseitemid]; + + // Lets start populating the list of items to return. + $childrenitems = $DB->get_records('surveypro_item', ['id' => $baseitemid], 'sortindex', 'id, parentid, sortindex'); + + $childid = $baseitemid; + $i = 1; + do { + $where['parentid'] = $childid; + if ($morechildren = $DB->get_records('surveypro_item', $where, 'sortindex', 'id, parentid, sortindex')) { + foreach ($morechildren as $k => $unused) { + $idscontainer[] = $k; + } + $childrenitems += $morechildren; + } + $childid = next($idscontainer); + $i++; + } while ($i <= count($idscontainer)); + + return $childrenitems; + } + + // MARK item action execution. + + /** + * Ask for confirmation before a bulk action. + * + * Called by: + * show_all_feedback() + * + * @param string $message + * @param string $yeskey + * @return void + */ + public function bulk_action_ask($message, $yeskey=null) { + global $OUTPUT; + + $optionbase = ['s' => $this->cm->instance, 'act' => $this->action, 'section' => 'itemslist', 'sesskey' => sesskey()]; + + $optionsyes = $optionbase; + $optionsyes['cnf'] = SURVEYPRO_CONFIRMED_YES; + $urlyes = new \moodle_url('/mod/surveypro/layout.php', $optionsyes); + + $yeslabel = ($yeskey) ? get_string($yeskey, 'mod_surveypro') : get_string('continue'); + $buttonyes = new \single_button($urlyes, $yeslabel); + + $optionsno = $optionbase; + $optionsno['cnf'] = SURVEYPRO_CONFIRMED_NO; + $urlno = new \moodle_url('/mod/surveypro/layout.php', $optionsno); + $buttonno = new \single_button($urlno, get_string('no')); + + echo $OUTPUT->confirm($message, $buttonyes, $buttonno); + echo $OUTPUT->footer(); + die(); + } + + /** + * Perform the actions required through icon click into items table. + * + * Called by: + * layout.php + * + * @return void + */ + public function actions_execution() { + global $DB; + + switch ($this->action) { + case SURVEYPRO_NOACTION: + break; + case SURVEYPRO_HIDEITEM: + $this->item_hide_execute(); + break; + case SURVEYPRO_SHOWITEM: + $this->item_show_execute(); + break; + case SURVEYPRO_DELETEITEM: + $this->item_delete_execute(); + break; + case SURVEYPRO_DROPMULTILANG: + $this->drop_multilang_execute(); + break; + case SURVEYPRO_CHANGEORDER: + $this->reorder_items(); + // After item reorder, if you reload the page whithout cleaning the url, the reorder action is performed again. + $returnurl = new \moodle_url('/mod/surveypro/layout.php', ['s' => $this->cm->instance, 'section' => 'itemslist']); + redirect($returnurl); + break; + case SURVEYPRO_CHANGEINDENT: + $where = ['itemid' => $this->rootitemid]; + $DB->set_field('surveypro'.$this->type.'_'.$this->plugin, 'indent', $this->nextindent, $where); + break; + case SURVEYPRO_MAKERESERVED: + $this->item_makereserved_execute(); + break; + case SURVEYPRO_MAKEAVAILABLE: + $this->item_makeavailable_execute(); + break; + case SURVEYPRO_HIDEALLITEMS: + $this->hide_all_execute(); + break; + case SURVEYPRO_SHOWALLITEMS: + $this->show_all_execute(); + break; + case SURVEYPRO_DELETEALLITEMS: + $this->delete_all_execute(); + break; + case SURVEYPRO_DELETEVISIBLEITEMS: + $this->delete_visible_execute(); + break; + case SURVEYPRO_DELETEHIDDENITEMS: + $this->delete_hidden_execute(); + break; + default: + $message = 'Unexpected $this->action = '.$this->action; + debugging('Error at line '.__LINE__.' of '.__FILE__.'. '.$message , DEBUG_DEVELOPER); + } + } + + /** + * Provide a feedback for the actions performed in actions_execution. + * + * Called by: + * layout.php + * + * @return void + */ + public function actions_feedback() { + switch ($this->action) { + case SURVEYPRO_NOACTION: + if (!empty($this->surveypro->template)) { + $this->drop_multilang_feedback(); + } + break; + case SURVEYPRO_HIDEITEM: + $this->item_hide_feedback(); + break; + case SURVEYPRO_SHOWITEM: + $this->item_show_feedback(); + break; + case SURVEYPRO_DELETEITEM: + $this->item_delete_feedback(); + break; + case SURVEYPRO_MAKERESERVED: + $this->item_makereserved_feedback(); + break; + case SURVEYPRO_MAKEAVAILABLE: + $this->item_makeavailable_feedback(); + break; + case SURVEYPRO_HIDEALLITEMS: + $this->hide_all_feedback(); + break; + case SURVEYPRO_SHOWALLITEMS: + $this->show_all_feedback(); + break; + case SURVEYPRO_DELETEALLITEMS: + $this->delete_all_feedback(); + break; + case SURVEYPRO_DELETEVISIBLEITEMS: + $this->delete_visible_feedback(); + break; + case SURVEYPRO_DELETEHIDDENITEMS: + $this->delete_hidden_feedback(); + break; + default: + // Black hole for all the actions not needing feedback. + } + } + + /** + * Store to the database sortindex field, the relative position at the items according to last changes. + * + * Called by: + * actions_execution() + * + * @return void + */ + public function reorder_items() { + global $DB; + + // I start loading the id of the item I want to move starting from its known sortindex. + $where = ['surveyproid' => $this->surveypro->id, 'sortindex' => $this->itemtomove]; + $itemid = $DB->get_field('surveypro_item', 'id', $where); + + // Am I moving it backward or forward? + if ($this->itemtomove > $this->lastitembefore) { + // Moving the item backward. + $searchitem = $this->itemtomove - 1; + $replaceitem = $this->itemtomove; + + $where = ['surveyproid' => $this->surveypro->id]; + while ($searchitem > $this->lastitembefore) { + $where['sortindex'] = $searchitem; + $DB->set_field('surveypro_item', 'sortindex', $replaceitem, $where); + $replaceitem = $searchitem; + $searchitem--; + } + + $DB->set_field('surveypro_item', 'sortindex', $replaceitem, ['id' => $itemid]); + } else { + // Moving the item forward. + $searchitem = $this->itemtomove + 1; + $replaceitem = $this->itemtomove; + + $where = ['surveyproid' => $this->surveypro->id]; + while ($searchitem <= $this->lastitembefore) { + $where['sortindex'] = $searchitem; + $DB->set_field('surveypro_item', 'sortindex', $replaceitem, $where); + $replaceitem = $searchitem; + $searchitem++; + } + + $DB->set_field('surveypro_item', 'sortindex', $replaceitem, ['id' => $itemid]); + } + + // You changed item order. Don't forget to reset the page of each items. + $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); + $utilitylayoutman->reset_pages(); + } + + // MARK ITEM - hide. + + /** + * Hide an item and (maybe) all its descendants. + * + * Called by: + * actions_execution() + * + * @return void + */ + public function item_hide_execute() { + global $DB; + + // Build tohidelist. + // Here I must select the whole tree down. + $itemstohide = $this->get_children(null, ['hidden' => 0]); + + $itemstoprocess = count($itemstohide); + if ( ($this->confirm == SURVEYPRO_CONFIRMED_YES) || ($itemstoprocess == 1) ) { + // Hide items. + foreach ($itemstohide as $itemtohide) { + $DB->set_field('surveypro_item', 'hidden', 1, ['id' => $itemtohide->id]); + } + $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); + $utilitylayoutman->reset_pages(); + } + } + + /** + * Provide a feedback after item_hide_execute. + * + * @return void + */ + public function item_hide_feedback() { + global $OUTPUT; + + // Build tohidelist. + // Here I must select the whole tree down. + $itemstohide = $this->get_children(null, ['hidden' => 0]); + + $itemstoprocess = count($itemstohide); + if ($this->confirm == SURVEYPRO_UNCONFIRMED) { + if ($itemstoprocess > 1) { // Ask for confirmation. + $dependencies = []; + $item = surveypro_get_item($this->cm, $this->surveypro, $this->rootitemid, $this->type, $this->plugin); + + $a = new \stdClass(); + $a->itemcontent = $item->get_content(); + foreach ($itemstohide as $itemtohide) { + $dependencies[] = $itemtohide->sortindex; + } + // Drop the original item because it doesn't go in the message. + $key = array_search($this->sortindex, $dependencies); + if ($key !== false) { // Should always happen. + unset($dependencies[$key]); + } + $a->dependencies = implode(', ', $dependencies); + if (count($dependencies) == 1) { + $message = get_string('confirm_hide1item', 'mod_surveypro', $a); + } else { + $message = get_string('confirm_hidechainitems', 'mod_surveypro', $a); + } + + $optionbase = ['s' => $this->cm->instance]; + $optionbase['act'] = SURVEYPRO_HIDEITEM; + $optionbase['section'] = 'itemslist'; + $optionbase['sesskey'] = sesskey(); + + $optionsyes = $optionbase; + $optionsyes['cnf'] = SURVEYPRO_CONFIRMED_YES; + $optionsyes['itemid'] = $this->rootitemid; + $optionsyes['plugin'] = $this->plugin; + $optionsyes['type'] = $this->type; + $urlyes = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$this->sortindex, $optionsyes); + $buttonyes = new \single_button($urlyes, get_string('continue')); + + $optionsno = $optionbase; + $optionsno['cnf'] = SURVEYPRO_CONFIRMED_NO; + $urlno = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$this->sortindex, $optionsno); + $buttonno = new \single_button($urlno, get_string('no')); + + echo $OUTPUT->confirm($message, $buttonyes, $buttonno); + echo $OUTPUT->footer(); + die(); + } + } + + if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { + $message = get_string('usercanceled', 'mod_surveypro'); + echo $OUTPUT->notification($message, 'notifymessage'); + } + } + + // MARK ITEM - show. + + /** + * Show an item and (maybe) all its ascendants. + * + * Called by: + * actions_execution() + * + * @return void + */ + public function item_show_execute() { + global $DB; + + // Build toshowlist. + $toshowlist = $this->add_parent_node(['hidden' => 1]); + + $itemstoprocess = count($toshowlist); // This is the list of ancestors. + if ( ($this->confirm == SURVEYPRO_CONFIRMED_YES) || ($itemstoprocess == 1) ) { + // Show items. + foreach ($toshowlist as $toshowitemid) { + $DB->set_field('surveypro_item', 'hidden', 0, ['id' => $toshowitemid]); + } + $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); + $utilitylayoutman->reset_pages(); + } + } + + /** + * Provide a feedback after item_show_execute. + * + * @return void + */ + public function item_show_feedback() { + global $OUTPUT; + + // Build toshowlist. + $toshowlist = $this->add_parent_node(['hidden' => 1]); + + $itemstoprocess = count($toshowlist); // This is the list of ancestors. + if ($this->confirm == SURVEYPRO_UNCONFIRMED) { + if ($itemstoprocess > 1) { // Ask for confirmation. + $item = surveypro_get_item($this->cm, $this->surveypro, $this->rootitemid, $this->type, $this->plugin); + + $a = new \stdClass(); + $a->lastitem = $item->get_content(); + $ancestors = array_keys($toshowlist); + // Drop the original item because it doesn't go in the message. + $key = array_search($this->sortindex, $ancestors); + if ($key !== false) { // Should always happen. + unset($ancestors[$key]); + } + $a->ancestors = implode(', ', $ancestors); + if (count($ancestors) == 1) { + $message = get_string('confirm_show1item', 'mod_surveypro', $a); + } else { + $message = get_string('confirm_showchainitems', 'mod_surveypro', $a); + } + + $optionbase = []; + $optionbase['s'] = $this->cm->instance; + $optionbase['act'] = SURVEYPRO_SHOWITEM; + $optionbase['itemid'] = $this->rootitemid; + $optionbase['section'] = 'itemslist'; + $optionbase['sesskey'] = sesskey(); + + $optionsyes = $optionbase; + $optionsyes['cnf'] = SURVEYPRO_CONFIRMED_YES; + $optionsyes['itemid'] = $this->rootitemid; + $optionsyes['plugin'] = $this->plugin; + $optionsyes['type'] = $this->type; + $urlyes = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$this->sortindex, $optionsyes); + $buttonyes = new \single_button($urlyes, get_string('continue')); + + $optionsno = $optionbase; + $optionsno['cnf'] = SURVEYPRO_CONFIRMED_NO; + $urlno = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$this->sortindex, $optionsno); + $buttonno = new \single_button($urlno, get_string('no')); + + echo $OUTPUT->confirm($message, $buttonyes, $buttonno); + echo $OUTPUT->footer(); + die(); + } + } + + if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { + $message = get_string('usercanceled', 'mod_surveypro'); + echo $OUTPUT->notification($message, 'notifymessage'); + } + } + + // MARK ITEM - make reserved. + + /** + * Set the item as reserved. + * + * Called by: + * actions_execution() + * + * the idea is this: in a chain of parent-child items, + * -> reserved items can be parent of reserved items only + * -> reserved items can be child of reserved items only + * + * @return void + */ + public function item_makereserved_execute() { + global $DB; + + if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { + return; + } + + // Here I must select the whole tree down. + $itemstoreserve = $this->add_parent_node(['reserved' => 0]); + + // I am interested to oldest parent only. + $baseitemid = end($itemstoreserve); + + // Build itemstoreserve starting from the oldest parent. + $itemstoreserve = $this->get_children($baseitemid, ['reserved' => 0]); + + $itemstoprocess = count($itemstoreserve); + if ( ($this->confirm == SURVEYPRO_CONFIRMED_YES) || ($itemstoprocess == 1) ) { + // Make items reserved. + foreach ($itemstoreserve as $itemtoreserve) { + $DB->set_field('surveypro_item', 'reserved', 1, ['id' => $itemtoreserve->id]); + } + $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); + $utilitylayoutman->reset_pages(); + } + } + + /** + * Provide a feedback after item_makereserved_execute. + * + * Called by: + * actions_feedback() + * + * the idea is this: in a chain of parent-child items, + * -> reserved items can be parent of reserved items only + * -> reserved items can be child of reserved items only + * + * @return void + */ + public function item_makereserved_feedback() { + global $OUTPUT; + + if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { + $message = get_string('usercanceled', 'mod_surveypro'); + echo $OUTPUT->notification($message, 'notifymessage'); + return; + } + + if ($this->confirm == SURVEYPRO_UNCONFIRMED) { + // Here I must select the whole tree down. + $itemstoreserve = $this->add_parent_node(['reserved' => 0]); + + // I am interested to oldest parent only. + $baseitemid = end($itemstoreserve); + + // Build itemstoreserve starting from the oldest parent. + $itemstoreserve = $this->get_children($baseitemid, ['reserved' => 0]); + + $itemstoprocess = count($itemstoreserve); // This is the list of ancestors. + if ($itemstoprocess > 1) { // Ask for confirmation. + // If the clicked element has not parents. + $a = new \stdClass(); + $item = surveypro_get_item($this->cm, $this->surveypro, $this->rootitemid, $this->type, $this->plugin); + $a->itemcontent = $item->get_content(); + foreach ($itemstoreserve as $itemtoreserve) { + $dependencies[] = $itemtoreserve->sortindex; + } + // Drop the original item because it doesn't go in the message. + $key = array_search($this->sortindex, $dependencies); + if ($key !== false) { // Should always happen. + unset($dependencies[$key]); + } + $a->dependencies = implode(', ', $dependencies); + + if ($baseitemid != $this->rootitemid) { + $firstparentitem = reset($itemstoreserve); + $parentitem = surveypro_get_item($this->cm, $this->surveypro, $firstparentitem->id); + $a->parentcontent = $parentitem->get_content(); + $message = get_string('confirm_reservechainitems_newparent', 'mod_surveypro', $a); + } else { + if (count($dependencies) == 1) { + $message = get_string('confirm_reserve1item', 'mod_surveypro', $a); + } else { + $message = get_string('confirm_reservechainitems', 'mod_surveypro', $a); + } + } + + $optionbase = []; + $optionbase['s'] = $this->cm->instance; + $optionbase['act'] = SURVEYPRO_MAKERESERVED; + $optionbase['section'] = 'itemslist'; + $optionbase['sesskey'] = sesskey(); + + $optionsyes = $optionbase; + $optionsyes['cnf'] = SURVEYPRO_CONFIRMED_YES; + $optionsyes['itemid'] = $this->rootitemid; + $optionsyes['plugin'] = $this->plugin; + $optionsyes['type'] = $this->type; + $urlyes = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$this->sortindex, $optionsyes); + $buttonyes = new \single_button($urlyes, get_string('continue')); + + $optionsno = $optionbase; + $optionsno['cnf'] = SURVEYPRO_CONFIRMED_NO; + $urlno = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$this->sortindex, $optionsno); + $buttonno = new \single_button($urlno, get_string('no')); + + echo $OUTPUT->confirm($message, $buttonyes, $buttonno); + echo $OUTPUT->footer(); + die(); + } + } + } + + // MARK ITEM - make available. + + /** + * Set the item as standard (free). + * + * Called by: + * actions_execution() + * + * the idea is this: in a chain of parent-child items, + * -> available items (not reserved) can be parent of available items only + * -> available items (not reserved) can be child of available items only + * + * @return void + */ + public function item_makeavailable_execute() { + global $DB; + + if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { + return; + } + + // Build itemstoavailable. + $itemstoavailable = $this->add_parent_node(['reserved' => 1]); + + // I am interested to oldest parent only. + $baseitemid = end($itemstoavailable); + + // Build itemstoavailable starting from the oldest parent. + $itemstoavailable = $this->get_children($baseitemid, ['reserved' => 1]); + + $itemstoprocess = count($itemstoavailable); // This is the list of ancestors. + if ( ($this->confirm == SURVEYPRO_CONFIRMED_YES) || ($itemstoprocess == 1) ) { + // Make items available. + foreach ($itemstoavailable as $itemtoavailable) { + $DB->set_field('surveypro_item', 'reserved', 0, ['id' => $itemtoavailable->id]); + } + $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); + $utilitylayoutman->reset_pages(); + } + } + + /** + * Provide a feedback after item_makeavailable_execute. + * + * Called by: + * actions_feedback() + * + * the idea is this: in a chain of parent-child items, + * -> available items (not reserved) can be parent of available items only + * -> available items (not reserved) can be child of available items only + * + * @return void + */ + public function item_makeavailable_feedback() { + global $OUTPUT; + + if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { + $message = get_string('usercanceled', 'mod_surveypro'); + echo $OUTPUT->notification($message, 'notifymessage'); + return; + } + + if ($this->confirm == SURVEYPRO_UNCONFIRMED) { + // Build itemstoavailable. + $itemstoavailable = $this->add_parent_node(['reserved' => 1]); + + // I am interested to oldest parent only. + $baseitemid = end($itemstoavailable); + + // Build itemstoavailable starting from the oldest parent. + $itemstoavailable = $this->get_children($baseitemid, ['reserved' => 1]); + + $itemstoprocess = count($itemstoavailable); // This is the list of ancestors. + if ($itemstoprocess > 1) { // Ask for confirmation. + // If the clicked element has not parents. + $a = new \stdClass(); + $item = surveypro_get_item($this->cm, $this->surveypro, $this->rootitemid, $this->type, $this->plugin); + $a->itemcontent = $item->get_content(); + foreach ($itemstoavailable as $itemtoavailable) { + $dependencies[] = $itemtoavailable->sortindex; + } + // Drop the original item because it doesn't go in the message. + $key = array_search($this->sortindex, $dependencies); + if ($key !== false) { // Should always happen. + unset($dependencies[$key]); + } + $a->dependencies = implode(', ', $dependencies); + + if ($baseitemid != $this->rootitemid) { + $firstparentitem = reset($itemstoavailable); + $parentitem = surveypro_get_item($this->cm, $this->surveypro, $firstparentitem->id); + $a->parentcontent = $parentitem->get_content(); + $message = get_string('confirm_freechainitems_newparent', 'mod_surveypro', $a); + } else { + if (count($dependencies) == 1) { + $message = get_string('confirm_free1item', 'mod_surveypro', $a); + } else { + $message = get_string('confirm_freechainitems', 'mod_surveypro', $a); + } + } + + $optionbase = []; + $optionbase['s'] = $this->cm->instance; + $optionbase['act'] = SURVEYPRO_MAKEAVAILABLE; + $optionbase['itemid'] = $this->rootitemid; + $optionbase['section'] = 'itemslist'; + $optionbase['sesskey'] = sesskey(); + + $optionsyes = $optionbase; + $optionsyes['cnf'] = SURVEYPRO_CONFIRMED_YES; + $optionsyes['itemid'] = $this->rootitemid; + $optionsyes['plugin'] = $this->plugin; + $optionsyes['type'] = $this->type; + $urlyes = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$this->sortindex, $optionsyes); + $buttonyes = new \single_button($urlyes, get_string('continue')); + + $optionsno = $optionbase; + $optionsno['cnf'] = SURVEYPRO_CONFIRMED_NO; + $urlno = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$this->sortindex, $optionsno); + $buttonno = new \single_button($urlno, get_string('no')); + + echo $OUTPUT->confirm($message, $buttonyes, $buttonno); + echo $OUTPUT->footer(); + die(); + } + } + } + + // MARK ITEM - delete. + + /** + * Delete an item and (maybe) all its descendants. + * + * @return void + */ + public function item_delete_execute() { + global $DB; + + if ($this->confirm == SURVEYPRO_CONFIRMED_YES) { + // After the item deletion action, if the user reload the page, the deletion is performed again rising up an error. + // If the item to drop is not in the db, this means that the user already deleted it and is reloading the page. + // In this case, stop the deletion execution. + if (!$DB->record_exists('surveypro_item', ['id' => $this->rootitemid])) { + return; + } + + $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); + $utilitylayoutman->reset_pages(); + + $whereparams = ['surveyproid' => $this->surveypro->id]; + + $itemstodelete = $this->get_children(); + array_shift($itemstodelete); + if ($itemstodelete) { + foreach ($itemstodelete as $itemtodelete) { + $whereparams['id'] = $itemtodelete->id; + $utilitylayoutman->delete_items($whereparams); + } + } + + // Get the content of the item for the feedback message. + $item = surveypro_get_item($this->cm, $this->surveypro, $this->rootitemid, $this->type, $this->plugin); + + $killedsortindex = $item->get_sortindex(); + $whereparams = ['id' => $this->rootitemid]; + $utilitylayoutman->delete_items($whereparams); + + $utilitylayoutman->items_reindex($killedsortindex); + $this->confirm = SURVEYPRO_ACTION_EXECUTED; + + $itemcount = $utilitylayoutman->has_items(0, SURVEYPRO_TYPEFIELD, true, true, true); + $this->set_itemcount($itemcount); + + $this->actionfeedback = new \stdClass(); + $this->actionfeedback->chain = !empty($itemstodelete); + $this->actionfeedback->content = $item->get_content(); + $this->actionfeedback->pluginname = strtolower(get_string('pluginname', 'surveypro'.$this->type.'_'.$this->plugin)); + } + } + + /** + * Provide a feedback after item_delete_execute. + * + * @return void + */ + public function item_delete_feedback() { + global $DB, $OUTPUT; + + if ($this->confirm == SURVEYPRO_UNCONFIRMED) { + // Ask for confirmation. + // In the frame of the confirmation I need to declare whether some child will break the link. + $item = surveypro_get_item($this->cm, $this->surveypro, $this->rootitemid, $this->type, $this->plugin); + + $a = new \stdClass(); + $a->content = $item->get_content(); + $a->pluginname = strtolower(get_string('pluginname', 'surveypro'.$this->type.'_'.$this->plugin)); + $message = get_string('confirm_delete1item', 'mod_surveypro', $a); + + // Is there any child item chain to break? (Sortindex is supposed to be a valid key in the next query). + $itemstodelete = $this->get_children(); + array_shift($itemstodelete); + if ($itemstodelete) { + foreach ($itemstodelete as $itemtodelete) { + $childrenids[] = $itemtodelete->sortindex; + } + $nodes = implode(', ', $childrenids); + $message .= ' '.get_string('confirm_deletechainitems', 'mod_surveypro', $nodes); + $labelyes = get_string('continue'); + } else { + $labelyes = get_string('yes'); + } + + $optionbase['s'] = $this->cm->instance; + $optionbase['act'] = SURVEYPRO_DELETEITEM; + $optionbase['section'] = 'itemslist'; + $optionbase['sesskey'] = sesskey(); + + $optionsyes = $optionbase; + $optionsyes['cnf'] = SURVEYPRO_CONFIRMED_YES; + $optionsyes['itemid'] = $this->rootitemid; + $optionsyes['plugin'] = $this->plugin; + $optionsyes['type'] = $this->type; + + $urlyes = new \moodle_url('/mod/surveypro/layout.php', $optionsyes); + $buttonyes = new \single_button($urlyes, $labelyes); + + $optionsno = $optionbase; + $optionsno['cnf'] = SURVEYPRO_CONFIRMED_NO; + + $urlno = new \moodle_url('/mod/surveypro/layout.php', $optionsno); + $buttonno = new \single_button($urlno, get_string('no')); + + echo $OUTPUT->confirm($message, $buttonyes, $buttonno); + echo $OUTPUT->footer(); + die(); + } + + if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { + $message = get_string('usercanceled', 'mod_surveypro'); + echo $OUTPUT->notification($message, 'notifymessage'); + } + + if ($this->confirm == SURVEYPRO_ACTION_EXECUTED) { + $a = new \stdClass(); + $a->content = $this->actionfeedback->content; + $a->pluginname = $this->actionfeedback->pluginname; + if ($this->actionfeedback->chain) { + $message = get_string('feedback_deletechainitems', 'mod_surveypro', $a); + } else { + $message = get_string('feedback_delete1item', 'mod_surveypro', $a); + } + echo $OUTPUT->notification($message, 'notifysuccess'); + } + } + + // MARK BULK - all show. + + /** + * Show all items. + * + * Called by: + * actions_execution() + * + * @return void + */ + public function show_all_execute() { + if ($this->confirm == SURVEYPRO_CONFIRMED_YES) { + $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); + + $whereparams = ['surveyproid' => $this->surveypro->id]; + $utilitylayoutman->items_set_visibility($whereparams, 1); + + $utilitylayoutman->items_reindex(); + + $this->set_confirm(SURVEYPRO_ACTION_EXECUTED); + } + } + + /** + * Provide a feedback after show_all_execute. + * + * Called by: + * actions_feedback() + * + * @return void + */ + public function show_all_feedback() { + global $OUTPUT; + + if ($this->confirm == SURVEYPRO_UNCONFIRMED) { + $message = get_string('confirm_showallitems', 'mod_surveypro'); + $yeskey = 'yes_showallitems'; + $this->bulk_action_ask($message, $yeskey); + } + + if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { + $message = get_string('usercanceled', 'mod_surveypro'); + echo $OUTPUT->notification($message, 'notifymessage'); + } + + if ($this->confirm == SURVEYPRO_ACTION_EXECUTED) { + $message = get_string('feedback_showallitems', 'mod_surveypro'); + echo $OUTPUT->notification($message, 'notifysuccess'); + } + } + + // MARK BULK - all hide. + + /** + * Hide all items. + * + * Called by: + * actions_execution() + * + * @return void + */ + public function hide_all_execute() { + if ($this->confirm == SURVEYPRO_CONFIRMED_YES) { + $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); + $whereparams = ['surveyproid' => $this->surveypro->id]; + $utilitylayoutman->items_set_visibility($whereparams, 0); + + $utilitylayoutman->reset_pages(); + + $this->set_confirm(SURVEYPRO_ACTION_EXECUTED); + } + } + + /** + * Provide a feedback after hide_all_execute. + * + * Called by: + * actions_feedback() + * + * @return void + */ + public function hide_all_feedback() { + global $OUTPUT; + + if ($this->confirm == SURVEYPRO_UNCONFIRMED) { + $message = get_string('confirm_hideallitems', 'mod_surveypro'); + $yeskey = 'yes_hideallitems'; + $this->bulk_action_ask($message, $yeskey); + } + + if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { + $message = get_string('usercanceled', 'mod_surveypro'); + echo $OUTPUT->notification($message, 'notifymessage'); + } + + if ($this->confirm == SURVEYPRO_ACTION_EXECUTED) { + $message = get_string('feedback_hideallitems', 'mod_surveypro'); + echo $OUTPUT->notification($message, 'notifysuccess'); + } + } + + // MARK BULK - all delete. + + /** + * Delete all items. + * + * Called by: + * actions_execution() + * + * @return void + */ + public function delete_all_execute() { + if ($this->confirm == SURVEYPRO_CONFIRMED_YES) { + $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); + + $whereparams = ['surveyproid' => $this->surveypro->id]; + $utilitylayoutman->delete_items($whereparams); + + $paramurl = []; + $paramurl['s'] = $this->cm->instance; + $paramurl['section'] = 'itemslist'; + $returnurl = new \moodle_url('/mod/surveypro/layout.php', $paramurl); + redirect($returnurl); + } + } + + /** + * Provide a feedback after delete_all_execute. + * + * Called by: + * actions_feedback() + * + * @return void + */ + public function delete_all_feedback() { + global $OUTPUT; + + if ($this->confirm == SURVEYPRO_UNCONFIRMED) { + $message = get_string('confirm_deleteallitems', 'mod_surveypro'); + $yeskey = 'yes_deleteallitems'; + $this->bulk_action_ask($message, $yeskey); + } + + if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { + $message = get_string('usercanceled', 'mod_surveypro'); + echo $OUTPUT->notification($message, 'notifymessage'); + } + + if ($this->confirm == SURVEYPRO_ACTION_EXECUTED) { + $message = get_string('feedback_deleteallitems', 'mod_surveypro'); + echo $OUTPUT->notification($message, 'notifysuccess'); + } + } + + // MARK BULK - visible delete. + + /** + * Delete visible items. + * + * Called by: + * actions_execution() + * + * @return void + */ + public function delete_visible_execute() { + if ($this->confirm == SURVEYPRO_CONFIRMED_YES) { + $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); + + $whereparams = ['surveyproid' => $this->surveypro->id]; + $whereparams['hidden'] = 0; + $utilitylayoutman->delete_items($whereparams); + + $utilitylayoutman->items_reindex(); + + $paramurl = []; + $paramurl['s'] = $this->cm->instance; + $paramurl['act'] = SURVEYPRO_DELETEVISIBLEITEMS; + $paramurl['section'] = 'itemslist'; + $paramurl['sesskey'] = sesskey(); + $paramurl['cnf'] = SURVEYPRO_ACTION_EXECUTED; + $returnurl = new \moodle_url('/mod/surveypro/layout.php', $paramurl); + redirect($returnurl); + } + } + + /** + * Provide a feedback after delete_visible_execute. + * + * Called by: + * actions_feedback() + * + * @return void + */ + public function delete_visible_feedback() { + global $OUTPUT; + + if ($this->confirm == SURVEYPRO_UNCONFIRMED) { + $message = get_string('confirm_deletevisibleitems', 'mod_surveypro'); + $yeskey = 'yes_deletevisibleitems'; + $this->bulk_action_ask($message, $yeskey); + } + + if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { + $message = get_string('usercanceled', 'mod_surveypro'); + echo $OUTPUT->notification($message, 'notifymessage'); + } + + if ($this->confirm == SURVEYPRO_ACTION_EXECUTED) { + $message = get_string('feedback_deletevisibleitems', 'mod_surveypro'); + echo $OUTPUT->notification($message, 'notifysuccess'); + } + } + + // MARK BULK - hidden delete. + + /** + * Delete hidden items. + * + * Called by: + * actions_execution() + * + * @return void + */ + public function delete_hidden_execute() { + if ($this->confirm == SURVEYPRO_CONFIRMED_YES) { + $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); + + $whereparams = ['surveyproid' => $this->surveypro->id]; + $whereparams['hidden'] = 1; + $utilitylayoutman->delete_items($whereparams); + + $utilitylayoutman->items_reindex(); + + $paramurl = []; + $paramurl['s'] = $this->cm->instance; + $paramurl['act'] = SURVEYPRO_DELETEHIDDENITEMS; + $paramurl['section'] = 'itemslist'; + $paramurl['sesskey'] = sesskey(); + $paramurl['cnf'] = SURVEYPRO_ACTION_EXECUTED; + $returnurl = new \moodle_url('/mod/surveypro/layout.php', $paramurl); + redirect($returnurl); + } + } + + /** + * Provide a feedback after delete_hidden_feedback. + * + * Called by: + * actions_feedback + * + * @return void + */ + public function delete_hidden_feedback() { + global $OUTPUT; + + if ($this->confirm == SURVEYPRO_UNCONFIRMED) { + $message = get_string('confirm_deletehiddenitems', 'mod_surveypro'); + $yeskey = 'yes_deletehiddenitems'; + $this->bulk_action_ask($message, $yeskey); + } + + if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { + $message = get_string('usercanceled', 'mod_surveypro'); + echo $OUTPUT->notification($message, 'notifymessage'); + } + + if ($this->confirm == SURVEYPRO_ACTION_EXECUTED) { + $message = get_string('feedback_deletehiddenitems', 'mod_surveypro'); + echo $OUTPUT->notification($message, 'notifysuccess'); + } + } + + // MARK feedback section. + + /** + * Display a feedback for the editing teacher once an item is edited. + * + * Called by: + * layout.php + * + * @return void + */ + public function display_item_editing_feedback() { + global $OUTPUT; + + if ($this->itemeditingfeedback == SURVEYPRO_NOFEEDBACK) { + return; + } + + // Look at position 1. + $bit = $this->itemeditingfeedback & 2; // Bitwise logic. + if ($bit) { // Edit. + $bit = $this->itemeditingfeedback & 1; // Bitwise logic. + if ($bit) { + $message = get_string('feedback_itemediting_ok', 'mod_surveypro'); + $class = 'notifysuccess'; + } else { + $message = get_string('feedback_itemediting_ko', 'mod_surveypro'); + $class = 'notifyproblem'; + } + } else { // Add. + $bit = $this->itemeditingfeedback & 1; // Bitwise logic. + if ($bit) { + $message = get_string('feedback_itemadd_ok', 'mod_surveypro'); + $class = 'notifysuccess'; + } else { + $message = get_string('feedback_itemadd_ko', 'mod_surveypro'); + $class = 'notifyproblem'; + } + } + + for ($position = 2; $position <= 5; $position++) { + $bit = $this->itemeditingfeedback & pow(2, $position); // Bitwise logic. + switch ($position) { + case 2: // A chain of items is now shown. + if ($bit) { + $message .= '
'.get_string('feedback_itemediting_showchainitems', 'mod_surveypro'); + } + break; + case 3: // A chain of items is now hided because one item was hided. + if ($bit) { + $message .= '
'.get_string('feedback_itemediting_hidechainitems', 'mod_surveypro'); + } + break; + case 4: // A chain of items was moved in the user entry form. + if ($bit) { + $message .= '
'.get_string('feedback_itemediting_freechainitems', 'mod_surveypro'); + } + break; + case 5: // A chain of items was removed from the user entry form. + if ($bit) { + $message .= '
'.get_string('feedback_itemediting_reservechainitems', 'mod_surveypro'); + } + break; + } + } + echo $OUTPUT->notification($message, $class); + } + + // MARK drop multilang. + + /** + * Drop multilang from all the item. + * + * Called by: + * actions_execution() + * + * @return void + */ + public function drop_multilang_execute() { + global $DB; + + if ($this->confirm == SURVEYPRO_CONFIRMED_YES) { + $template = $this->surveypro->template; + $where = ['surveyproid' => $this->surveypro->id]; + $itemseeds = $DB->get_records('surveypro_item', $where, 'sortindex', 'id, type, plugin'); + foreach ($itemseeds as $itemseed) { + $id = $itemseed->id; + $type = $itemseed->type; + $plugin = $itemseed->plugin; + $item = surveypro_get_item($this->cm, $this->surveypro, $id, $type, $plugin); + $itemsmlfields = $item->get_multilang_fields(); // Pagebreak and fieldsetend have no multilang_fields. + if ($itemsmlfields[$plugin]) { + // Note: ml means multi language. + foreach ($itemsmlfields as $itemmlfield) { // Note: $itemmlfield is an array of fields. + $record = new \stdClass(); + $record->id = $item->get_pluginid(); + + $where = ['id' => $record->id]; + $fieldlist = implode(',', $itemmlfield); + // SELECT content,extranote,options,labelother,defaultvalue FROM {surveyprofield_radiobutton} WHERE id = 8. + $reference = $DB->get_record('surveypro'.$type.'_'.$plugin, $where, $fieldlist, MUST_EXIST); + foreach ($itemmlfield as $mlfieldname) { + $stringkey = $reference->{$mlfieldname}; + if (core_text::strlen($stringkey)) { + $record->{$mlfieldname} = get_string($stringkey, 'surveyprotemplate_'.$template); + } else { + $record->{$mlfieldname} = null; + } + } + $DB->update_record('surveypro'.$type.'_'.$plugin, $record); + } + } + } + $surveypro = new \stdClass(); + $surveypro->id = $this->surveypro->id; + $surveypro->template = null; + $DB->update_record('surveypro', $surveypro); + + $paramurl = []; + $paramurl['s'] = $this->cm->instance; + $paramurl['act'] = SURVEYPRO_DROPMULTILANG; + $paramurl['section'] = 'itemslist'; + $paramurl['sesskey'] = sesskey(); + $paramurl['cnf'] = SURVEYPRO_ACTION_EXECUTED; + $returnurl = new \moodle_url('/mod/surveypro/layout.php', $paramurl); + redirect($returnurl); + } + + if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { + $paramurl = ['s' => $this->cm->instance, 'section' => 'itemslist']; + $returnurl = new \moodle_url('/mod/surveypro/layout.php', $paramurl); + redirect($returnurl); + } + } + + /** + * Provide a feedback after drop_multilang_execute. + * + * Called by: + * actions_feedback() + * + * @return void + */ + public function drop_multilang_feedback() { + global $OUTPUT; + + if ($this->confirm == SURVEYPRO_UNCONFIRMED) { + // Ask for confirmation. + $message = get_string('confirm_dropmultilang', 'mod_surveypro'); + + $optionbase = ['s' => $this->cm->instance, 'act' => SURVEYPRO_DROPMULTILANG, 'section' => 'itemslist']; + + $optionsyes = $optionbase; + $optionsyes['cnf'] = SURVEYPRO_CONFIRMED_YES; + $urlyes = new \moodle_url('/mod/surveypro/layout.php', $optionsyes); + $buttonyes = new \single_button($urlyes, get_string('yes')); + + $optionsno = $optionbase; + $optionsno['cnf'] = SURVEYPRO_CONFIRMED_NO; + $urlno = new \moodle_url('/mod/surveypro/layout.php', $optionsno); + $buttonno = new \single_button($urlno, get_string('no')); + + echo $OUTPUT->confirm($message, $buttonyes, $buttonno); + echo $OUTPUT->footer(); + die(); + } + + if ($this->confirm == SURVEYPRO_ACTION_EXECUTED) { + $message = get_string('feedback_dropmultilang', 'mod_surveypro'); + echo $OUTPUT->notification($message, 'notifysuccess'); + } + } + + // MARK set. + + /** + * Set type. + * + * Called by: + * layout.php + * + * @param string $type + * @return void + */ + public function set_type($type) { + $this->type = $type; + } + + /** + * Set plugin. + * + * Called by: + * layout.php + * + * @param string $plugin + * @return void + */ + public function set_plugin($plugin) { + $this->plugin = $plugin; + } + + /** + * Set itemid. + * + * Called by: + * layout.php + * + * @param int $itemid + * @return void + */ + public function set_itemid($itemid) { + $this->rootitemid = $itemid; + } + + /** + * Set sortindex. + * + * Called by: + * layout.php + * + * @param int $sortindex + * @return void + */ + public function set_sortindex($sortindex) { + $this->sortindex = $sortindex; + } + + /** + * Set action. + * + * Called by: + * layout.php + * + * @param int $action + * @return void + */ + public function set_action($action) { + $this->action = $action; + } + + /** + * Set mode. + * + * Called by: + * layout.php + * + * @param int $mode + * @return void + */ + public function set_mode($mode) { + $this->mode = $mode; + } + + /** + * Set itemtomove. + * + * Called by: + * layout.php + * + * @param int $itemtomove + * @return void + */ + public function set_itemtomove($itemtomove) { + $this->itemtomove = $itemtomove; + } + + /** + * Set last item before. + * + * Called by: + * layout.php + * + * @param int $lastitembefore + * @return void + */ + public function set_lastitembefore($lastitembefore) { + $this->lastitembefore = $lastitembefore; + } + + /** + * Set nextindent. + * + * Called by: + * layout.php + * + * @param int $nextindent + * @return void + */ + public function set_nextindent($nextindent) { + $this->nextindent = $nextindent; + } + + /** + * Set parentid. + * + * Called by: + * layout.php + * + * @param int $parentid + * @return void + */ + public function set_parentid($parentid) { + $this->parentid = $parentid; + } + + /** + * Set confirm. + * + * Called by: + * layout.php + * + * @param int $confirm + * @return void + */ + public function set_confirm($confirm) { + $this->confirm = $confirm; + } + + /** + * Set item editing feedback. + * + * Called by: + * layout.php + * + * @param int $itemeditingfeedback + * @return void + */ + public function set_itemeditingfeedback($itemeditingfeedback) { + $this->itemeditingfeedback = $itemeditingfeedback; + } + + /** + * Set hassubmissions. + * + * Called by: + * layout.php + * + * @param int $hassubmissions + * @return void + */ + public function set_hassubmissions($hassubmissions) { + $this->hassubmissions = $hassubmissions; + } + + /** + * Set itemcount. + * + * Called by: + * setup() + * + * @param int $itemcount + * @return void + */ + public function set_itemcount($itemcount) { + $this->itemcount = $itemcount; + } +} diff --git a/classes/layout_itemsetup.php b/classes/layout_itemsetup.php index e62584749df..787a285ea1f 100644 --- a/classes/layout_itemsetup.php +++ b/classes/layout_itemsetup.php @@ -15,7 +15,7 @@ // along with Moodle. If not, see . /** - * Surveypro layout class. + * Surveypro layout_itemsetup class. * * @package mod_surveypro * @copyright 2013 onwards kordan @@ -154,1983 +154,16 @@ public function __construct($cm, $context, $surveypro) { } /** - * Display all the items in a table. + * Setup. * * @return void */ - public function display_items_table() { - global $CFG, $DB, $OUTPUT; - - require_once($CFG->libdir.'/tablelib.php'); - - $riskyediting = ($this->surveypro->riskyeditdeadline > time()); - - $table = new \flexible_table('itemslist'); - - $paramurl = ['s' => $this->cm->instance, 'section' => 'itemslist']; - $baseurl = new \moodle_url('/mod/surveypro/layout.php', $paramurl); - $table->define_baseurl($baseurl); - - $tablecolumns = []; - $tablecolumns[] = 'plugin'; - $tablecolumns[] = 'sortindex'; - $tablecolumns[] = 'parentid'; - $tablecolumns[] = 'customnumber'; - $tablecolumns[] = 'content'; - $tablecolumns[] = 'variable'; - $tablecolumns[] = 'formpage'; - $tablecolumns[] = 'availability'; - $tablecolumns[] = 'actions'; - $table->define_columns($tablecolumns); - - $tableheaders = []; - $tableheaders[] = get_string('typeplugin', 'mod_surveypro'); - $tableheaders[] = get_string('sortindex', 'mod_surveypro'); - $tableheaders[] = get_string('branching', 'mod_surveypro'); - $tableheaders[] = get_string('customnumber_header', 'mod_surveypro'); - $tableheaders[] = get_string('content', 'mod_surveypro'); - $tableheaders[] = get_string('variable', 'mod_surveypro'); - $tableheaders[] = get_string('page'); - $tableheaders[] = get_string('availability', 'mod_surveypro'); - $tableheaders[] = get_string('actions'); - $table->define_headers($tableheaders); - - $table->sortable(true, 'sortindex'); // Sorted by sortindex by default. - $table->no_sorting('customnumber'); - $table->no_sorting('content'); - $table->no_sorting('variable'); - $table->no_sorting('availability'); - $table->no_sorting('actions'); - - $table->column_class('plugin', 'plugin'); - $table->column_class('sortindex', 'sortindex'); - $table->column_class('parentid', 'parentitem'); - $table->column_class('customnumber', 'customnumber'); - $table->column_class('content', 'content'); - $table->column_class('variable', 'variable'); - $table->column_class('formpage', 'formpage'); - $table->column_class('availability', 'availability'); - $table->column_class('actions', 'actions'); - - // General properties for the whole table. - if ($this->mode == SURVEYPRO_CHANGEORDERASK) { - $table->set_attribute('id', 'sortitems'); - } else { - $table->set_attribute('id', 'manageitems'); - } - $table->set_attribute('class', 'generaltable'); - $table->setup(); - - // Strings. - $iconparams = []; - // Icons for further use. - $editstr = get_string('edit'); - $iconparams = ['title' => $editstr]; - $editicn = new \pix_icon('t/edit', $editstr, 'moodle', $iconparams); - - $parentelementstr = get_string('parentelement_title', 'mod_surveypro'); - $iconparams = ['title' => $parentelementstr]; - $branchicn = new \pix_icon('branch', $parentelementstr, 'surveypro', $iconparams); - - $reorderstr = get_string('changeorder_title', 'mod_surveypro'); - $iconparams = ['title' => $reorderstr]; - $moveicn = new \pix_icon('t/move', $editstr, 'moodle', $iconparams); - - $hidestr = get_string('hidefield_title', 'mod_surveypro'); - $iconparams = ['title' => $hidestr]; - $hideicn = new \pix_icon('i/hide', $hidestr, 'moodle', $iconparams); - - $showstr = get_string('showfield_title', 'mod_surveypro'); - $iconparams = ['title' => $showstr]; - $showicn = new \pix_icon('i/show', $showstr, 'moodle', $iconparams); - - $deletestr = get_string('delete'); - $iconparams = ['title' => $deletestr]; - $deleteicn = new \pix_icon('t/delete', $deletestr, 'moodle', $iconparams); - - $indentstr = get_string('indent', 'mod_surveypro'); - $iconparams = ['title' => $indentstr]; - $lefticn = new \pix_icon('t/left', $indentstr, 'moodle', $iconparams); - $righticn = new \pix_icon('t/right', $indentstr, 'moodle', $iconparams); - - $moveherestr = get_string('movehere'); - $movehereicn = new \pix_icon('movehere', $moveherestr, 'moodle', ['title' => $moveherestr, 'class' => 'placeholder']); - - $availablestr = get_string('available_title', 'mod_surveypro'); - $iconparams = ['title' => $availablestr]; - $freeicn = new \pix_icon('free', $availablestr, 'surveypro', $iconparams); - - $reservedstr = get_string('reserved_title', 'mod_surveypro'); - $iconparams = ['title' => $reservedstr]; - $reservedicn = new \pix_icon('reserved', $reservedstr, 'surveypro', $iconparams); - - $unreservablestr = get_string('unreservable_title', 'mod_surveypro'); - $iconparams = ['title' => $unreservablestr]; - $unreservableicn = new \pix_icon('unreservable', $unreservablestr, 'surveypro', $iconparams); - - $unsearchablestr = get_string('unsearchable_title', 'mod_surveypro'); - $iconparams = ['title' => $unsearchablestr]; - $unsearchableicn = new \pix_icon('unsearchable', $unsearchablestr, 'surveypro', $iconparams); - - $unavailablestr = get_string('unavailableelement_title', 'mod_surveypro'); - $iconparams = ['title' => $unavailablestr]; - $unavailableicn = new \pix_icon('unavailable', $unavailablestr, 'surveypro', $iconparams); - - $forcedoptionalitemstr = get_string('forcedoptionalitem_title', 'mod_surveypro'); - $iconparams = ['title' => $forcedoptionalitemstr]; - $lockedgreenicn = new \pix_icon('lockedgreen', $forcedoptionalitemstr, 'surveypro', $iconparams); - - // Begin of: $paramurlmove definition. - $paramurlmove = []; - $paramurlmove['s'] = $this->cm->instance; - $paramurlmove['act'] = SURVEYPRO_CHANGEORDER; - $paramurlmove['itm'] = $this->itemtomove; - // End of: $paramurlmove definition. - - [$where, $params] = surveypro_fetch_items_seeds($this->surveypro->id, false, true, null, null, null, true); - // If you are reordering, force ordering to... - $orderby = ($this->mode == SURVEYPRO_CHANGEORDERASK) ? 'sortindex ASC' : $table->get_sql_sort(); - $itemseeds = $DB->get_recordset_select('surveypro_item', $where, $params, $orderby, 'id as itemid, type, plugin'); - - // This is the very first position, so if the item has a parent, no "moveherebox" must appear. - if (($this->mode == SURVEYPRO_CHANGEORDERASK) && (!$this->parentid)) { - $drawmoveherebox = true; - $paramurl = $paramurlmove; - $paramurl['lib'] = 0; // Move just after this sortindex (lib == last item before). - $paramurl['section'] = 'itemslist'; - $paramurl['sesskey'] = sesskey(); - - $link = new \moodle_url('/mod/surveypro/layout.php', $paramurl); - $paramlink = ['id' => 'moveafter_0', 'title' => $moveherestr]; - $icons = $OUTPUT->action_icon($link, $movehereicn, null, $paramlink); - - $tablerow = []; - $tablerow[] = $icons; - $tablerow = array_pad($tablerow, count($table->columns), ''); - - $table->add_data($tablerow); - } else { - $drawmoveherebox = false; - } - - foreach ($itemseeds as $itemseed) { - $item = surveypro_get_item($this->cm, $this->surveypro, $itemseed->itemid, $itemseed->type, $itemseed->plugin, true); - $itemid = $itemseed->itemid; - $itemishidden = $item->get_hidden(); - $sortindex = $item->get_sortindex(); - - // Begin of: $paramurlbase definition. - $paramurlbase = []; - $paramurlbase['s'] = $this->cm->instance; - $paramurlbase['itemid'] = $item->get_itemid(); - $paramurlbase['type'] = $item->get_type(); - $paramurlbase['plugin'] = $item->get_plugin(); - // End of: $paramurlbase definition. - - $tablerow = []; - - if (($this->mode == SURVEYPRO_CHANGEORDERASK) && ($item->get_itemid() == $this->rootitemid)) { - // Do not draw the item you are going to move. - continue; - } - - // Plugin. - $component = 'surveypro'.$item->get_type().'_'.$item->get_plugin(); - $alt = get_string('userfriendlypluginname', $component); - $content = \html_writer::tag('a', '', ['name' => 'sortindex_'.$sortindex]); - $iconparams = ['title' => $alt]; - $icon = $OUTPUT->pix_icon('icon', $alt, $component, $iconparams); - $content .= \html_writer::tag('span', $icon, ['class' => 'pluginicon']); - - $tablerow[] = $content; - - // Sortindex. - $tablerow[] = $sortindex; - - // Parentid. - if ($item->get_parentid()) { - $parentsortindex = $DB->get_field('surveypro_item', 'sortindex', ['id' => $item->get_parentid()]); - $content = $parentsortindex; - $content .= \html_writer::tag('span', $OUTPUT->render($branchicn), ['class' => 'branch']); - $content .= $item->get_parentcontent('; '); - } else { - $content = ''; - } - $tablerow[] = $content; - - // Customnumber. - if (($item->get_type() == SURVEYPRO_TYPEFIELD) || ($item->get_plugin() == 'label')) { - $itemid = $item->get_itemid(); - $customnumber = $item->get_customnumber(); - $tmpl = new layout_customnumber($itemid, $customnumber); - - $tablerow[] = $OUTPUT->render_from_template('core/inplace_editable', $tmpl->export_for_template($OUTPUT)); - } else { - $tablerow[] = ''; - } - - // Content. - $tablerow[] = $item->get_content(); - - // Variable. - if ($item->get_type() == SURVEYPRO_TYPEFIELD) { - $itemid = $item->get_itemid(); - $variablename = $item->get_variable(); - $tmpl = new layout_variable($itemid, $variablename); - - $tablerow[] = $OUTPUT->render_from_template('core/inplace_editable', $tmpl->export_for_template($OUTPUT)); - } else { - $tablerow[] = ''; - } - - // Page. - if ($item->item_uses_form_page()) { - $content = $item->get_formpage(); - } else { - $content = ''; - } - $tablerow[] = $content; - - // Availability. - $icons = ''; - // First icon: reserved vs generally available. - if (!$itemishidden) { - if ($item->get_insetupform('reserved')) { - $reserved = $item->get_reserved(); - if ($item->item_has_children() || $item->item_is_child()) { - $paramurl = $paramurlbase; - if ($reserved) { - $paramurl['act'] = SURVEYPRO_MAKEAVAILABLE; - $paramurl['sortindex'] = $sortindex; - $paramurl['area'] = 'layout'; - $paramurl['section'] = 'itemslist'; - $paramurl['sesskey'] = sesskey(); - - $link = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$sortindex, $paramurl); - $paramlink = ['id' => 'makeavailable_item_'.$sortindex, 'title' => $reservedstr]; - $actionicon = $OUTPUT->action_icon($link, $reservedicn, null, $paramlink); - $icons .= \html_writer::tag('span', $actionicon, ['class' => 'reserveitem']); - } else { - $paramurl['act'] = SURVEYPRO_MAKERESERVED; - $paramurl['sortindex'] = $sortindex; - $paramurl['area'] = 'layout'; - $paramurl['section'] = 'itemslist'; - $paramurl['sesskey'] = sesskey(); - - $link = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$sortindex, $paramurl); - $paramlink = ['id' => 'makereserved_item_'.$sortindex, 'title' => $availablestr]; - $actionicon = $OUTPUT->action_icon($link, $freeicn, null, $paramlink); - $icons .= \html_writer::tag('span', $actionicon, ['class' => 'freeitem']); - } - } else { - $tmpl = new layout_reserved($itemid, $reserved, $sortindex); - $tmpl->set_type_toggle(); - $icons .= $OUTPUT->render_from_template('core/inplace_editable', $tmpl->export_for_template($OUTPUT)); - } - } else { - // Icon only, not a link! - $icons .= \html_writer::tag('span', $OUTPUT->render($unreservableicn), ['class' => 'noactionicon']); - } - } else { - // Icon only, not a link! - $icons .= \html_writer::tag('span', $OUTPUT->render($unavailableicn), ['class' => 'noactionicon']); - } - - // Second icon: insearchform vs notinsearchform. - if (!$itemishidden) { - if ($item->get_insetupform('insearchform')) { - // Second icon: insearchform vs not insearchform. - $insearchform = $item->get_insearchform(); - $tmpl = new layout_insearchform($itemid, $insearchform, $sortindex); - $tmpl->set_type_toggle(); - $icons .= $OUTPUT->render_from_template('core/inplace_editable', $tmpl->export_for_template($OUTPUT)); - } else { - // Icon only, not a link! - $icons .= \html_writer::tag('span', $OUTPUT->render($unsearchableicn), ['class' => 'noactionicon']); - } - } else { - // Icon only, not a link! - $icons .= \html_writer::tag('span', $OUTPUT->render($unavailableicn), ['class' => 'noactionicon']); - } - - // Third icon: hide vs show. - // Here I can not use the cool \core\output\inplace_editable because - // this action make changes not limited to the state of this icon. - if (!$this->hassubmissions || $riskyediting) { - $paramurl = $paramurlbase; - $paramurl['section'] = 'itemslist'; - $paramurl['sesskey'] = sesskey(); - if (empty($itemishidden)) { - $paramurl['act'] = SURVEYPRO_HIDEITEM; - $paramurl['sortindex'] = $sortindex; - $linkidprefix = 'hide_item_'; - } else { - $paramurl['act'] = SURVEYPRO_SHOWITEM; - $paramurl['sortindex'] = $sortindex; - $linkidprefix = 'show_item_'; - } - $link = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$sortindex, $paramurl); - $paramlink = ['id' => $linkidprefix.$sortindex, 'class' => 'icon']; - if (empty($itemishidden)) { - $paramlink['title'] = $hidestr; - $actionicon = $OUTPUT->action_icon($link, $hideicn, null, $paramlink); - $icons .= \html_writer::tag('span', $actionicon, ['class' => 'hideitem']); - } else { - $paramlink['title'] = $showstr; - $actionicon = $OUTPUT->action_icon($link, $showicn, null, $paramlink); - $icons .= \html_writer::tag('span', $actionicon, ['class' => 'showitem']); - } - } - $tablerow[] = $icons; - - // Action icons. - $icons = ''; - if ($this->mode != SURVEYPRO_CHANGEORDERASK) { - // SURVEYPRO_EDITITEM. - $paramurl = $paramurlbase; - $paramurl['mode'] = SURVEYPRO_EDITITEM; - $paramurl['area'] = 'layout'; - $paramurl['section'] = 'itemsetup'; - - $link = new \moodle_url('/mod/surveypro/layout.php', $paramurl); - $paramlink = ['id' => 'edit_item_'.$sortindex, 'class' => 'icon', 'title' => $editstr]; - $actionicon = $OUTPUT->action_icon($link, $editicn, null, $paramlink); - $icons .= \html_writer::tag('span', $actionicon, ['class' => 'fatspan']); - - // SURVEYPRO_CHANGEORDERASK. - if ($this->itemcount > 1) { - $paramurl = $paramurlbase; - $paramurl['mode'] = SURVEYPRO_CHANGEORDERASK; - $paramurl['itm'] = $sortindex; - $paramurl['section'] = 'itemslist'; - - $currentparentid = $item->get_parentid(); - if (!empty($currentparentid)) { - $paramurl['pid'] = $currentparentid; - } - - $link = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.($sortindex - 1), $paramurl); - $paramlink = ['id' => 'move_item_'.$sortindex, 'class' => 'icon', 'title' => $reorderstr]; - $actionicon = $OUTPUT->action_icon($link, $moveicn, null, $paramlink); - $icons .= \html_writer::tag('span', $actionicon, ['class' => 'fatspan']); - } - - // SURVEYPRO_DELETEITEM. - if (!$this->hassubmissions || $riskyediting) { - $paramurl = $paramurlbase; - $paramurl['act'] = SURVEYPRO_DELETEITEM; - $paramurl['sortindex'] = $sortindex; - $paramurl['area'] = 'layout'; - $paramurl['section'] = 'itemslist'; - $paramurl['sesskey'] = sesskey(); - - $link = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$sortindex, $paramurl); - $paramlink = ['id' => 'delete_item_'.$sortindex, 'class' => 'icon', 'title' => $deletestr]; - $actionicon = $OUTPUT->action_icon($link, $deleteicn, null, $paramlink); - $icons .= \html_writer::tag('span', $actionicon, ['class' => 'fatspan']); - } - - // SURVEYPRO_REQUIRED ON/OFF. - $currentrequired = $item->get_required(); - if ($currentrequired !== false) { // It may be "not set" as in page_break, autofill or some more. - $paramurl = $paramurlbase; - $paramurl['sesskey'] = sesskey(); - - if ($item->item_canbemandatory()) { - $required = $item->get_required(); - $tmpl = new layout_required($itemid, $required, $sortindex); - $tmpl->set_type_toggle(); - $icons .= $OUTPUT->render_from_template('core/inplace_editable', $tmpl->export_for_template($OUTPUT)); - } else { - $icons .= \html_writer::tag('span', $OUTPUT->render($lockedgreenicn), ['class' => 'noactionicon']); - } - } else { - // Icon only, not a link! - $icons .= \html_writer::tag('span', $OUTPUT->spacer(), ['class' => 'spacericon']); - } - - // SURVEYPRO_CHANGEINDENT. - if ($item->get_insetupform('indent')) { // It may not be set as in page_break, fieldset and some more. - $currentindent = $item->get_indent(); - if ($currentindent !== false) { // It may be false like for labels with fullwidth == 1. - $paramurl = $paramurlbase; - $paramurl['act'] = SURVEYPRO_CHANGEINDENT; - $paramurl['area'] = 'layout'; - $paramurl['section'] = 'itemslist'; - $paramurl['sesskey'] = sesskey(); - - $actionicon = ''; - $paramlink = ['title' => $indentstr, 'class' => 'lastspan']; - if ($currentindent > 0) { - $indentvalue = $currentindent - 1; - $paramurl['ind'] = $indentvalue; - - $link = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$sortindex, $paramurl); - $paramlink += ['id' => 'reduceindent_item_'.$sortindex]; - $actionicon .= $OUTPUT->action_icon($link, $lefticn, null, $paramlink); - } else { - // Icon only, not a link! - $actionicon .= $OUTPUT->spacer(['class' => 'spacericon']); - } - $actionicon .= '['.$currentindent.']'; - if ($currentindent < 9) { - $indentvalue = $currentindent + 1; - $paramurl['ind'] = $indentvalue; - - $link = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$sortindex, $paramurl); - $paramlink += ['id' => 'increaseindent_item_'.$sortindex]; - $actionicon .= $OUTPUT->action_icon($link, $righticn, null, $paramlink); - } - $icons .= \html_writer::tag('span', $actionicon, ['class' => 'lastspan']); - } - } - } - $tablerow[] = $icons; - - $rowclass = empty($itemishidden) ? '' : 'dimmed'; - $table->add_data($tablerow, $rowclass); - - if ($this->mode == SURVEYPRO_CHANGEORDERASK) { - // It was asked to move the item with: $this->rootitemid and $this->parentid. - if ($this->parentid) { // This is the parentid of the item that I am going to move. - // If a parentid is foreseen then... - // Draw the moveherebox only if the current (already displayed) item has: $item->itemid == $this->parentid. - // Once you start to draw the moveherebox, you will never stop. - $drawmoveherebox = $drawmoveherebox || ($item->get_itemid() == $this->parentid); - - // If you just passed an item with $item->get_parentid == $itemid, stop forever. - if ($item->get_parentid() == $this->rootitemid) { - $drawmoveherebox = false; - } - } else { - $drawmoveherebox = $drawmoveherebox && ($item->get_parentid() != $this->rootitemid); - } - - if (!empty($drawmoveherebox)) { - $paramurl = $paramurlmove; - $paramurl['lib'] = $sortindex; - $paramurl['area'] = 'layout'; - $paramurl['section'] = 'itemslist'; - $paramurl['sesskey'] = sesskey(); - - $link = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$sortindex, $paramurl); - $paramlink = ['id' => 'move_item_'.$sortindex, 'title' => $moveherestr]; - $icons = $OUTPUT->action_icon($link, $movehereicn, null, $paramlink); - - $tablerow = []; - $tablerow[] = $icons; - $tablerow = array_pad($tablerow, count($table->columns), ''); - - $table->add_data($tablerow); - } - } - } - - $table->set_attribute('align', 'center'); - $table->summary = get_string('itemlist', 'mod_surveypro'); - $table->print_html(); - } - - /** - * Display the "validate_relations" table. - * - * @return void - */ - public function display_relations_table() { - global $CFG, $DB, $OUTPUT; - - require_once($CFG->libdir.'/tablelib.php'); - - $statusstr = get_string('relation_status', 'mod_surveypro'); - $table = new \flexible_table('relations'); - - $paramurl = ['s' => $this->cm->instance, 'section' => 'branchingvalidation']; - $baseurl = new \moodle_url('/mod/surveypro/layout.php', $paramurl); - $table->define_baseurl($baseurl); - - $tablecolumns = []; - $tablecolumns[] = 'plugin'; - $tablecolumns[] = 'sortindex'; - $tablecolumns[] = 'parentitem'; - $tablecolumns[] = 'customnumber'; - $tablecolumns[] = 'content'; - $tablecolumns[] = 'parentconstraints'; - $tablecolumns[] = 'status'; - $tablecolumns[] = 'actions'; - $table->define_columns($tablecolumns); - - $tableheaders = []; - $tableheaders[] = get_string('typeplugin', 'mod_surveypro'); - $tableheaders[] = get_string('sortindex', 'mod_surveypro'); - $tableheaders[] = get_string('branching', 'mod_surveypro'); - $tableheaders[] = get_string('customnumber_header', 'mod_surveypro'); - $tableheaders[] = get_string('content', 'mod_surveypro'); - $tableheaders[] = get_string('parentconstraints', 'mod_surveypro'); - $tableheaders[] = $statusstr; - $tableheaders[] = get_string('actions'); - $table->define_headers($tableheaders); - - $table->column_class('plugin', 'plugin'); - $table->column_class('sortindex', 'sortindex'); - $table->column_class('parentitem', 'parentitem'); - $table->column_class('customnumber', 'customnumber'); - $table->column_class('content', 'content'); - $table->column_class('parentconstraints', 'parentconstraints'); - $table->column_class('status', 'status'); - $table->column_class('actions', 'actions'); - - // General properties for the whole table. - $table->set_attribute('id', 'validaterelations'); - $table->set_attribute('class', 'generaltable'); - $table->setup(); - - $okstr = get_string('ok'); - - $iconparams = []; - - $editstr = get_string('edit'); - $iconparams = ['title' => $editstr]; - $editicn = new \pix_icon('t/edit', $editstr, 'moodle', $iconparams); - - $parentelementstr = get_string('parentelement_title', 'mod_surveypro'); - $iconparams = ['title' => $parentelementstr]; - $branchicn = new \pix_icon('branch', $parentelementstr, 'surveypro', $iconparams); - - // Get parents id only. - $sql = 'SELECT DISTINCT id as paretid, 1 - FROM {surveypro_item} parent - WHERE EXISTS ( - SELECT \'x\' - FROM {surveypro_item} child - WHERE child.parentid = parent.id) - AND surveyproid = ?'; - $whereparams = [$this->surveypro->id]; - $isparent = $DB->get_records_sql_menu($sql, $whereparams); - - // Get itemseeds. - $sql = 'SELECT DISTINCT id as itemid, plugin, type, sortindex - FROM {surveypro_item} parent - WHERE EXISTS ( - SELECT \'x\' - FROM {surveypro_item} child - WHERE child.parentid = parent.id) - AND surveyproid = ? - - UNION - - SELECT DISTINCT id as itemid, plugin, type, sortindex - FROM {surveypro_item} - WHERE surveyproid = ? - AND parentid > 0 - - ORDER BY sortindex;'; - $whereparams = [$this->surveypro->id, $this->surveypro->id]; - $itemseeds = $DB->get_recordset_sql($sql, $whereparams); - - $message = get_string('welcome_relationvalidation', 'mod_surveypro', $statusstr); - echo $OUTPUT->notification($message, 'notifymessage'); - - foreach ($itemseeds as $itemseed) { - $item = surveypro_get_item($this->cm, $this->surveypro, $itemseed->itemid, $itemseed->type, $itemseed->plugin, true); - $itemishidden = $item->get_hidden(); - - if ($item->get_parentid()) { - // Here I do not know type and plugin. - $parentitem = surveypro_get_item($this->cm, $this->surveypro, $item->get_parentid()); - } - - $tablerow = []; - - // Plugin. - $component = 'surveypro'.$item->get_type().'_'.$item->get_plugin(); - $alt = get_string('pluginname', $component); - $iconparams = ['title' => $alt, 'class' => 'icon']; - $content = $OUTPUT->pix_icon('icon', $alt, $component, $iconparams); - $tablerow[] = $content; - - // Sortindex. - $tablerow[] = $item->get_sortindex(); - - // Parentid. - if ($item->get_parentid()) { - $content = $parentitem->get_sortindex(); - $content .= \html_writer::tag('span', $OUTPUT->render($branchicn), ['class' => 'branch']); - $content .= $item->get_parentcontent('; '); - } else { - $content = ''; - } - $tablerow[] = $content; - - // Customnumber. - if (($item->get_type() == SURVEYPRO_TYPEFIELD) || ($item->get_plugin() == 'label')) { - $tablerow[] = $item->get_customnumber(); - } else { - $tablerow[] = ''; - } - - // Content. - $tablerow[] = $item->get_content(); - - // Parentconstraints. - if (isset($isparent[$itemseed->itemid])) { - $tablerow[] = $item->item_list_constraints(); - } else { - $tablerow[] = '-'; - } - - // Status. - if ($item->get_parentid()) { - $status = $parentitem->parent_validate_child_constraints($item->get_parentvalue()); - if ($status == SURVEYPRO_CONDITIONOK) { - $tablerow[] = $okstr; - } else { - if ($status == SURVEYPRO_CONDITIONNEVERMATCH) { - if (empty($itemishidden)) { - $errormessage = \html_writer::start_tag('span', ['class' => 'errormessage']); - $errormessage .= get_string('wrongrelation', 'mod_surveypro', $item->get_parentcontent('; ')); - $errormessage .= \html_writer::end_tag('span'); - $tablerow[] = $errormessage; - } else { - $tablerow[] = get_string('wrongrelation', 'mod_surveypro', $item->get_parentcontent('; ')); - } - } - if ($status == SURVEYPRO_CONDITIONMALFORMED) { - if (empty($itemishidden)) { - $errormessage = \html_writer::start_tag('span', ['class' => 'errormessage']); - $errormessage .= get_string('badchildparentvalue', 'mod_surveypro', $item->get_parentcontent('; ')); - $errormessage .= \html_writer::end_tag('span'); - $tablerow[] = $errormessage; - } else { - $tablerow[] = get_string('badchildparentvalue', 'mod_surveypro', $item->get_parentcontent('; ')); - } - } - } - } else { - $tablerow[] = '-'; - } - - // Actions. - // Begin of: $paramurlbase definition. - $paramurlbase = []; - $paramurlbase['s'] = $this->cm->instance; - $paramurlbase['itemid'] = $item->get_itemid(); - $paramurlbase['type'] = $item->get_type(); - $paramurlbase['plugin'] = $item->get_plugin(); - $paramurlbase['section'] = 'itemsetup'; - // End of $paramurlbase definition. - - // SURVEYPRO_NEWITEM. - $paramurl = $paramurlbase; - $paramurl['mode'] = SURVEYPRO_NEWITEM; - - $link = new \moodle_url('/mod/surveypro/layout.php', $paramurl); - $paramlink = ['id' => 'edit_'.$item->get_itemid(), 'title' => $editstr]; - $icons = $OUTPUT->action_icon($link, $editicn, null, $paramlink); - - $tablerow[] = $icons; - - $rowclass = empty($itemishidden) ? '' : 'dimmed'; - $table->add_data($tablerow, $rowclass); - } - $itemseeds->close(); - - $table->set_attribute('align', 'center'); - $table->summary = get_string('itemlist', 'mod_surveypro'); - $table->print_html(); - } - - /** - * Get the recursive list of children of a specific item. - * This list counts children and children of children for as much generation as it is. - * - * @param int $baseitemid the id of the root item for the tree of children to get - * @param array $where permanent condition needed to filter target items - * @return object $childrenitems - */ - public function get_children($baseitemid=null, $where=null) { - global $DB; - - if (empty($baseitemid)) { - $baseitemid = $this->rootitemid; - } - - if (empty($where)) { - $where = []; - } - - if (!is_array($where)) { - $a = 'get_children'; - throw new \moodle_exception('arrayexpected', 'mod_surveypro', null, $a); - } - - $idscontainer = [$baseitemid]; - - // Lets start populating the list of items to return. - $childrenitems = $DB->get_records('surveypro_item', ['id' => $baseitemid], 'sortindex', 'id, parentid, sortindex'); - - $childid = $baseitemid; - $i = 1; - do { - $where['parentid'] = $childid; - if ($morechildren = $DB->get_records('surveypro_item', $where, 'sortindex', 'id, parentid, sortindex')) { - foreach ($morechildren as $k => $unused) { - $idscontainer[] = $k; - } - $childrenitems += $morechildren; - } - $childid = next($idscontainer); - $i++; - } while ($i <= count($idscontainer)); - - return $childrenitems; - } - - /** - * Adds elements to an array starting from initial conditions. - * - * $additionalcondition is ['hidden' => 1] OR ['reserved' => 1] - * - * @param array $additionalcondition - * @return array $nodelist - */ - public function add_parent_node($additionalcondition) { - global $DB; - - if (!is_array($additionalcondition)) { - $a = 'add_parent_node'; - throw new \moodle_exception('arrayexpected', 'mod_surveypro', null, $a); - } - - $nodelist = [$this->sortindex => $this->rootitemid]; - - // Get the first parentid. - $parentitem = new \stdClass(); - $parentitem->parentid = $DB->get_field('surveypro_item', 'parentid', ['id' => $this->rootitemid]); - - $where = ['id' => $parentitem->parentid] + $additionalcondition; - - while ($parentitem = $DB->get_record('surveypro_item', $where, 'id, parentid, sortindex')) { - $nodelist[$parentitem->sortindex] = (int)$parentitem->id; - $where = ['id' => $parentitem->parentid] + $additionalcondition; - } - - return $nodelist; - } - - /** - * Store to the database sortindex field, the relative position at the items according to last changes. - * - * @return void - */ - public function reorder_items() { - global $DB; - - // I start loading the id of the item I want to move starting from its known sortindex. - $where = ['surveyproid' => $this->surveypro->id, 'sortindex' => $this->itemtomove]; - $itemid = $DB->get_field('surveypro_item', 'id', $where); - - // Am I moving it backward or forward? - if ($this->itemtomove > $this->lastitembefore) { - // Moving the item backward. - $searchitem = $this->itemtomove - 1; - $replaceitem = $this->itemtomove; - - $where = ['surveyproid' => $this->surveypro->id]; - while ($searchitem > $this->lastitembefore) { - $where['sortindex'] = $searchitem; - $DB->set_field('surveypro_item', 'sortindex', $replaceitem, $where); - $replaceitem = $searchitem; - $searchitem--; - } - - $DB->set_field('surveypro_item', 'sortindex', $replaceitem, ['id' => $itemid]); - } else { - // Moving the item forward. - $searchitem = $this->itemtomove + 1; - $replaceitem = $this->itemtomove; - - $where = ['surveyproid' => $this->surveypro->id]; - while ($searchitem <= $this->lastitembefore) { - $where['sortindex'] = $searchitem; - $DB->set_field('surveypro_item', 'sortindex', $replaceitem, $where); - $replaceitem = $searchitem; - $searchitem++; - } - - $DB->set_field('surveypro_item', 'sortindex', $replaceitem, ['id' => $itemid]); - } - - // You changed item order. Don't forget to reset the page of each items. - $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); - $utilitylayoutman->reset_pages(); - } - - /** - * Display a feedback for the editing teacher once an item is edited. - * - * @return void - */ - public function display_item_editing_feedback() { - global $OUTPUT; - - if ($this->itemeditingfeedback == SURVEYPRO_NOFEEDBACK) { - return; - } - - // Look at position 1. - $bit = $this->itemeditingfeedback & 2; // Bitwise logic. - if ($bit) { // Edit. - $bit = $this->itemeditingfeedback & 1; // Bitwise logic. - if ($bit) { - $message = get_string('feedback_itemediting_ok', 'mod_surveypro'); - $class = 'notifysuccess'; - } else { - $message = get_string('feedback_itemediting_ko', 'mod_surveypro'); - $class = 'notifyproblem'; - } - } else { // Add. - $bit = $this->itemeditingfeedback & 1; // Bitwise logic. - if ($bit) { - $message = get_string('feedback_itemadd_ok', 'mod_surveypro'); - $class = 'notifysuccess'; - } else { - $message = get_string('feedback_itemadd_ko', 'mod_surveypro'); - $class = 'notifyproblem'; - } - } - - for ($position = 2; $position <= 5; $position++) { - $bit = $this->itemeditingfeedback & pow(2, $position); // Bitwise logic. - switch ($position) { - case 2: // A chain of items is now shown. - if ($bit) { - $message .= '
'.get_string('feedback_itemediting_showchainitems', 'mod_surveypro'); - } - break; - case 3: // A chain of items is now hided because one item was hided. - if ($bit) { - $message .= '
'.get_string('feedback_itemediting_hidechainitems', 'mod_surveypro'); - } - break; - case 4: // A chain of items was moved in the user entry form. - if ($bit) { - $message .= '
'.get_string('feedback_itemediting_freechainitems', 'mod_surveypro'); - } - break; - case 5: // A chain of items was removed from the user entry form. - if ($bit) { - $message .= '
'.get_string('feedback_itemediting_reservechainitems', 'mod_surveypro'); - } - break; - } - } - echo $OUTPUT->notification($message, $class); - } - - /** - * Display the identity card of the item going to be created/edited just before the beginning of the item form. - * - * @return void - */ - public function item_identitycard() { - global $OUTPUT; - - $labelsep = get_string('labelsep', 'langconfig'); // Separator usually is ': '.. - $friendlyname = get_string('userfriendlypluginname', 'surveypro'.$this->type.'_'.$this->plugin); - - $iconparams = ['title' => $friendlyname, 'class' => 'icon']; - $message = $OUTPUT->pix_icon('icon', $friendlyname, 'surveypro'.$this->type.'_'.$this->plugin, $iconparams); - $message .= get_string($this->type, 'mod_surveypro').$labelsep.$friendlyname; - - echo $OUTPUT->box($message); - } - - /** - * Prevent direct user input. - * - * @return void - */ - public function prevent_direct_user_input() { - if ($this->surveypro->template) { - throw new \moodle_exception('incorrectaccessdetected', 'mod_surveypro'); - } - } - - // MARK item action execution. - - /** - * Perform the actions required through icon click into items table. - * - * @return void - */ - public function actions_execution() { - global $DB; - - switch ($this->action) { - case SURVEYPRO_NOACTION: - break; - case SURVEYPRO_HIDEITEM: - $this->item_hide_execute(); - break; - case SURVEYPRO_SHOWITEM: - $this->item_show_execute(); - break; - case SURVEYPRO_DELETEITEM: - $this->item_delete_execute(); - break; - case SURVEYPRO_DROPMULTILANG: - $this->drop_multilang_execute(); - break; - case SURVEYPRO_CHANGEORDER: - $this->reorder_items(); - // After item reorder, if you reload the page whithout cleaning the url, the reorder action is performed again. - $returnurl = new \moodle_url('/mod/surveypro/layout.php', ['s' => $this->cm->instance, 'section' => 'itemslist']); - redirect($returnurl); - break; - case SURVEYPRO_CHANGEINDENT: - $where = ['itemid' => $this->rootitemid]; - $DB->set_field('surveypro'.$this->type.'_'.$this->plugin, 'indent', $this->nextindent, $where); - break; - case SURVEYPRO_MAKERESERVED: - $this->item_makereserved_execute(); - break; - case SURVEYPRO_MAKEAVAILABLE: - $this->item_makeavailable_execute(); - break; - case SURVEYPRO_HIDEALLITEMS: - $this->hide_all_execute(); - break; - case SURVEYPRO_SHOWALLITEMS: - $this->show_all_execute(); - break; - case SURVEYPRO_DELETEALLITEMS: - $this->delete_all_execute(); - break; - case SURVEYPRO_DELETEVISIBLEITEMS: - $this->delete_visible_execute(); - break; - case SURVEYPRO_DELETEHIDDENITEMS: - $this->delete_hidden_execute(); - break; - default: - $message = 'Unexpected $this->action = '.$this->action; - debugging('Error at line '.__LINE__.' of '.__FILE__.'. '.$message , DEBUG_DEVELOPER); - } - } - - /** - * Provide a feedback for the actions performed in actions_execution. - * - * @return void - */ - public function actions_feedback() { - switch ($this->action) { - case SURVEYPRO_NOACTION: - if (!empty($this->surveypro->template)) { - $this->drop_multilang_feedback(); - } - break; - case SURVEYPRO_HIDEITEM: - $this->item_hide_feedback(); - break; - case SURVEYPRO_SHOWITEM: - $this->item_show_feedback(); - break; - case SURVEYPRO_DELETEITEM: - $this->item_delete_feedback(); - break; - case SURVEYPRO_MAKERESERVED: - $this->item_makereserved_feedback(); - break; - case SURVEYPRO_MAKEAVAILABLE: - $this->item_makeavailable_feedback(); - break; - case SURVEYPRO_HIDEALLITEMS: - $this->hide_all_feedback(); - break; - case SURVEYPRO_SHOWALLITEMS: - $this->show_all_feedback(); - break; - case SURVEYPRO_DELETEALLITEMS: - $this->delete_all_feedback(); - break; - case SURVEYPRO_DELETEVISIBLEITEMS: - $this->delete_visible_feedback(); - break; - case SURVEYPRO_DELETEHIDDENITEMS: - $this->delete_hidden_feedback(); - break; - default: - // Black hole for all the actions not needing feedback. - } - } - - /** - * Ask for confirmation before a bulk action. - * - * @param string $message - * @param string $yeskey - * @return void - */ - public function bulk_action_ask($message, $yeskey=null) { - global $OUTPUT; - - $optionbase = ['s' => $this->cm->instance, 'act' => $this->action, 'section' => 'itemslist', 'sesskey' => sesskey()]; - - $optionsyes = $optionbase; - $optionsyes['cnf'] = SURVEYPRO_CONFIRMED_YES; - $urlyes = new \moodle_url('/mod/surveypro/layout.php', $optionsyes); - - $yeslabel = ($yeskey) ? get_string($yeskey, 'mod_surveypro') : get_string('continue'); - $buttonyes = new \single_button($urlyes, $yeslabel); - - $optionsno = $optionbase; - $optionsno['cnf'] = SURVEYPRO_CONFIRMED_NO; - $urlno = new \moodle_url('/mod/surveypro/layout.php', $optionsno); - $buttonno = new \single_button($urlno, get_string('no')); - - echo $OUTPUT->confirm($message, $buttonyes, $buttonno); - echo $OUTPUT->footer(); - die(); - } - - // MARK item hide. - - /** - * Hide an item and (maybe) all its descendants. - * - * @return void - */ - public function item_hide_execute() { - global $DB; - - // Build tohidelist. - // Here I must select the whole tree down. - $itemstohide = $this->get_children(null, ['hidden' => 0]); - - $itemstoprocess = count($itemstohide); - if ( ($this->confirm == SURVEYPRO_CONFIRMED_YES) || ($itemstoprocess == 1) ) { - // Hide items. - foreach ($itemstohide as $itemtohide) { - $DB->set_field('surveypro_item', 'hidden', 1, ['id' => $itemtohide->id]); - } - $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); - $utilitylayoutman->reset_pages(); - } - } - - /** - * Provide a feedback after item_hide_execute. - * - * @return void - */ - public function item_hide_feedback() { - global $OUTPUT; - - // Build tohidelist. - // Here I must select the whole tree down. - $itemstohide = $this->get_children(null, ['hidden' => 0]); - - $itemstoprocess = count($itemstohide); - if ($this->confirm == SURVEYPRO_UNCONFIRMED) { - if ($itemstoprocess > 1) { // Ask for confirmation. - $dependencies = []; - $item = surveypro_get_item($this->cm, $this->surveypro, $this->rootitemid, $this->type, $this->plugin); - - $a = new \stdClass(); - $a->itemcontent = $item->get_content(); - foreach ($itemstohide as $itemtohide) { - $dependencies[] = $itemtohide->sortindex; - } - // Drop the original item because it doesn't go in the message. - $key = array_search($this->sortindex, $dependencies); - if ($key !== false) { // Should always happen. - unset($dependencies[$key]); - } - $a->dependencies = implode(', ', $dependencies); - if (count($dependencies) == 1) { - $message = get_string('confirm_hide1item', 'mod_surveypro', $a); - } else { - $message = get_string('confirm_hidechainitems', 'mod_surveypro', $a); - } - - $optionbase = ['s' => $this->cm->instance]; - $optionbase['act'] = SURVEYPRO_HIDEITEM; - $optionbase['section'] = 'itemslist'; - $optionbase['sesskey'] = sesskey(); - - $optionsyes = $optionbase; - $optionsyes['cnf'] = SURVEYPRO_CONFIRMED_YES; - $optionsyes['itemid'] = $this->rootitemid; - $optionsyes['plugin'] = $this->plugin; - $optionsyes['type'] = $this->type; - $urlyes = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$this->sortindex, $optionsyes); - $buttonyes = new \single_button($urlyes, get_string('continue')); - - $optionsno = $optionbase; - $optionsno['cnf'] = SURVEYPRO_CONFIRMED_NO; - $urlno = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$this->sortindex, $optionsno); - $buttonno = new \single_button($urlno, get_string('no')); - - echo $OUTPUT->confirm($message, $buttonyes, $buttonno); - echo $OUTPUT->footer(); - die(); - } - } - - if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { - $message = get_string('usercanceled', 'mod_surveypro'); - echo $OUTPUT->notification($message, 'notifymessage'); - } - } - - // MARK item show. - - /** - * Show an item and (maybe) all its ascendants. - * - * @return void - */ - public function item_show_execute() { - global $DB; - - // Build toshowlist. - $toshowlist = $this->add_parent_node(['hidden' => 1]); - - $itemstoprocess = count($toshowlist); // This is the list of ancestors. - if ( ($this->confirm == SURVEYPRO_CONFIRMED_YES) || ($itemstoprocess == 1) ) { - // Show items. - foreach ($toshowlist as $toshowitemid) { - $DB->set_field('surveypro_item', 'hidden', 0, ['id' => $toshowitemid]); - } - $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); - $utilitylayoutman->reset_pages(); - } - } - - /** - * Provide a feedback after item_show_execute. - * - * @return void - */ - public function item_show_feedback() { - global $OUTPUT; - - // Build toshowlist. - $toshowlist = $this->add_parent_node(['hidden' => 1]); - - $itemstoprocess = count($toshowlist); // This is the list of ancestors. - if ($this->confirm == SURVEYPRO_UNCONFIRMED) { - if ($itemstoprocess > 1) { // Ask for confirmation. - $item = surveypro_get_item($this->cm, $this->surveypro, $this->rootitemid, $this->type, $this->plugin); - - $a = new \stdClass(); - $a->lastitem = $item->get_content(); - $ancestors = array_keys($toshowlist); - // Drop the original item because it doesn't go in the message. - $key = array_search($this->sortindex, $ancestors); - if ($key !== false) { // Should always happen. - unset($ancestors[$key]); - } - $a->ancestors = implode(', ', $ancestors); - if (count($ancestors) == 1) { - $message = get_string('confirm_show1item', 'mod_surveypro', $a); - } else { - $message = get_string('confirm_showchainitems', 'mod_surveypro', $a); - } - - $optionbase = []; - $optionbase['s'] = $this->cm->instance; - $optionbase['act'] = SURVEYPRO_SHOWITEM; - $optionbase['itemid'] = $this->rootitemid; - $optionbase['section'] = 'itemslist'; - $optionbase['sesskey'] = sesskey(); - - $optionsyes = $optionbase; - $optionsyes['cnf'] = SURVEYPRO_CONFIRMED_YES; - $optionsyes['itemid'] = $this->rootitemid; - $optionsyes['plugin'] = $this->plugin; - $optionsyes['type'] = $this->type; - $urlyes = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$this->sortindex, $optionsyes); - $buttonyes = new \single_button($urlyes, get_string('continue')); - - $optionsno = $optionbase; - $optionsno['cnf'] = SURVEYPRO_CONFIRMED_NO; - $urlno = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$this->sortindex, $optionsno); - $buttonno = new \single_button($urlno, get_string('no')); - - echo $OUTPUT->confirm($message, $buttonyes, $buttonno); - echo $OUTPUT->footer(); - die(); - } - } - - if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { - $message = get_string('usercanceled', 'mod_surveypro'); - echo $OUTPUT->notification($message, 'notifymessage'); - } - } - - // MARK item delete. - - /** - * Delete an item and (maybe) all its descendants. - * - * @return void - */ - public function item_delete_execute() { - global $DB; - - if ($this->confirm == SURVEYPRO_CONFIRMED_YES) { - // After the item deletion action, if the user reload the page, the deletion is performed again rising up an error. - // If the item to drop is not in the db, this means that the user already deleted it and is reloading the page. - // In this case, stop the deletion execution. - if (!$DB->record_exists('surveypro_item', ['id' => $this->rootitemid])) { - return; - } - - $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); - $utilitylayoutman->reset_pages(); - - $whereparams = ['surveyproid' => $this->surveypro->id]; - - $itemstodelete = $this->get_children(); - array_shift($itemstodelete); - if ($itemstodelete) { - foreach ($itemstodelete as $itemtodelete) { - $whereparams['id'] = $itemtodelete->id; - $utilitylayoutman->delete_items($whereparams); - } - } - - // Get the content of the item for the feedback message. - $item = surveypro_get_item($this->cm, $this->surveypro, $this->rootitemid, $this->type, $this->plugin); - - $killedsortindex = $item->get_sortindex(); - $whereparams = ['id' => $this->rootitemid]; - $utilitylayoutman->delete_items($whereparams); - - $utilitylayoutman->items_reindex($killedsortindex); - $this->confirm = SURVEYPRO_ACTION_EXECUTED; - - $itemcount = $utilitylayoutman->has_items(0, SURVEYPRO_TYPEFIELD, true, true, true); - $this->set_itemcount($itemcount); - - $this->actionfeedback = new \stdClass(); - $this->actionfeedback->chain = !empty($itemstodelete); - $this->actionfeedback->content = $item->get_content(); - $this->actionfeedback->pluginname = strtolower(get_string('pluginname', 'surveypro'.$this->type.'_'.$this->plugin)); - } - } - - /** - * Provide a feedback after item_delete_execute. - * - * @return void - */ - public function item_delete_feedback() { - global $DB, $OUTPUT; - - if ($this->confirm == SURVEYPRO_UNCONFIRMED) { - // Ask for confirmation. - // In the frame of the confirmation I need to declare whether some child will break the link. - $item = surveypro_get_item($this->cm, $this->surveypro, $this->rootitemid, $this->type, $this->plugin); - - $a = new \stdClass(); - $a->content = $item->get_content(); - $a->pluginname = strtolower(get_string('pluginname', 'surveypro'.$this->type.'_'.$this->plugin)); - $message = get_string('confirm_delete1item', 'mod_surveypro', $a); - - // Is there any child item chain to break? (Sortindex is supposed to be a valid key in the next query). - $itemstodelete = $this->get_children(); - array_shift($itemstodelete); - if ($itemstodelete) { - foreach ($itemstodelete as $itemtodelete) { - $childrenids[] = $itemtodelete->sortindex; - } - $nodes = implode(', ', $childrenids); - $message .= ' '.get_string('confirm_deletechainitems', 'mod_surveypro', $nodes); - $labelyes = get_string('continue'); - } else { - $labelyes = get_string('yes'); - } - - $optionbase['s'] = $this->cm->instance; - $optionbase['act'] = SURVEYPRO_DELETEITEM; - $optionbase['section'] = 'itemslist'; - $optionbase['sesskey'] = sesskey(); - - $optionsyes = $optionbase; - $optionsyes['cnf'] = SURVEYPRO_CONFIRMED_YES; - $optionsyes['itemid'] = $this->rootitemid; - $optionsyes['plugin'] = $this->plugin; - $optionsyes['type'] = $this->type; - - $urlyes = new \moodle_url('/mod/surveypro/layout.php', $optionsyes); - $buttonyes = new \single_button($urlyes, $labelyes); - - $optionsno = $optionbase; - $optionsno['cnf'] = SURVEYPRO_CONFIRMED_NO; - - $urlno = new \moodle_url('/mod/surveypro/layout.php', $optionsno); - $buttonno = new \single_button($urlno, get_string('no')); - - echo $OUTPUT->confirm($message, $buttonyes, $buttonno); - echo $OUTPUT->footer(); - die(); - } - - if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { - $message = get_string('usercanceled', 'mod_surveypro'); - echo $OUTPUT->notification($message, 'notifymessage'); - } - - if ($this->confirm == SURVEYPRO_ACTION_EXECUTED) { - $a = new \stdClass(); - $a->content = $this->actionfeedback->content; - $a->pluginname = $this->actionfeedback->pluginname; - if ($this->actionfeedback->chain) { - $message = get_string('feedback_deletechainitems', 'mod_surveypro', $a); - } else { - $message = get_string('feedback_delete1item', 'mod_surveypro', $a); - } - echo $OUTPUT->notification($message, 'notifysuccess'); - } - } - - // MARK drop multilang. - - /** - * Drop multilang from all the item. - * - * @return void - */ - public function drop_multilang_execute() { - global $DB; - - if ($this->confirm == SURVEYPRO_CONFIRMED_YES) { - $template = $this->surveypro->template; - $where = ['surveyproid' => $this->surveypro->id]; - $itemseeds = $DB->get_records('surveypro_item', $where, 'sortindex', 'id, type, plugin'); - foreach ($itemseeds as $itemseed) { - $id = $itemseed->id; - $type = $itemseed->type; - $plugin = $itemseed->plugin; - $item = surveypro_get_item($this->cm, $this->surveypro, $id, $type, $plugin); - $itemsmlfields = $item->get_multilang_fields(); // Pagebreak and fieldsetend have no multilang_fields. - if ($itemsmlfields[$plugin]) { - // Note: ml means multi language. - foreach ($itemsmlfields as $itemmlfield) { // Note: $itemmlfield is an array of fields. - $record = new \stdClass(); - $record->id = $item->get_pluginid(); - - $where = ['id' => $record->id]; - $fieldlist = implode(',', $itemmlfield); - // SELECT content,extranote,options,labelother,defaultvalue FROM {surveyprofield_radiobutton} WHERE id = 8. - $reference = $DB->get_record('surveypro'.$type.'_'.$plugin, $where, $fieldlist, MUST_EXIST); - foreach ($itemmlfield as $mlfieldname) { - $stringkey = $reference->{$mlfieldname}; - if (core_text::strlen($stringkey)) { - $record->{$mlfieldname} = get_string($stringkey, 'surveyprotemplate_'.$template); - } else { - $record->{$mlfieldname} = null; - } - } - $DB->update_record('surveypro'.$type.'_'.$plugin, $record); - } - } - } - $surveypro = new \stdClass(); - $surveypro->id = $this->surveypro->id; - $surveypro->template = null; - $DB->update_record('surveypro', $surveypro); - - $paramurl = []; - $paramurl['s'] = $this->cm->instance; - $paramurl['act'] = SURVEYPRO_DROPMULTILANG; - $paramurl['section'] = 'itemslist'; - $paramurl['sesskey'] = sesskey(); - $paramurl['cnf'] = SURVEYPRO_ACTION_EXECUTED; - $returnurl = new \moodle_url('/mod/surveypro/layout.php', $paramurl); - redirect($returnurl); - } - - if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { - $paramurl = ['s' => $this->cm->instance, 'section' => 'itemslist']; - $returnurl = new \moodle_url('/mod/surveypro/layout.php', $paramurl); - redirect($returnurl); - } - } - - /** - * Provide a feedback after drop_multilang_execute. - * - * @return void - */ - public function drop_multilang_feedback() { - global $OUTPUT; - - if ($this->confirm == SURVEYPRO_UNCONFIRMED) { - // Ask for confirmation. - $message = get_string('confirm_dropmultilang', 'mod_surveypro'); - - $optionbase = ['s' => $this->cm->instance, 'act' => SURVEYPRO_DROPMULTILANG, 'section' => 'itemslist']; - - $optionsyes = $optionbase; - $optionsyes['cnf'] = SURVEYPRO_CONFIRMED_YES; - $urlyes = new \moodle_url('/mod/surveypro/layout.php', $optionsyes); - $buttonyes = new \single_button($urlyes, get_string('yes')); - - $optionsno = $optionbase; - $optionsno['cnf'] = SURVEYPRO_CONFIRMED_NO; - $urlno = new \moodle_url('/mod/surveypro/layout.php', $optionsno); - $buttonno = new \single_button($urlno, get_string('no')); - - echo $OUTPUT->confirm($message, $buttonyes, $buttonno); - echo $OUTPUT->footer(); - die(); - } - - if ($this->confirm == SURVEYPRO_ACTION_EXECUTED) { - $message = get_string('feedback_dropmultilang', 'mod_surveypro'); - echo $OUTPUT->notification($message, 'notifysuccess'); - } - } - - // MARK item make reserved. - - /** - * Set the item as reserved. - * - * the idea is this: in a chain of parent-child items, - * -> reserved items can be parent of reserved items only - * -> reserved items can be child of reserved items only - * - * @return void - */ - public function item_makereserved_execute() { - global $DB; - - if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { - return; - } - - // Here I must select the whole tree down. - $itemstoreserve = $this->add_parent_node(['reserved' => 0]); - - // I am interested to oldest parent only. - $baseitemid = end($itemstoreserve); - - // Build itemstoreserve starting from the oldest parent. - $itemstoreserve = $this->get_children($baseitemid, ['reserved' => 0]); - - $itemstoprocess = count($itemstoreserve); - if ( ($this->confirm == SURVEYPRO_CONFIRMED_YES) || ($itemstoprocess == 1) ) { - // Make items reserved. - foreach ($itemstoreserve as $itemtoreserve) { - $DB->set_field('surveypro_item', 'reserved', 1, ['id' => $itemtoreserve->id]); - } - $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); - $utilitylayoutman->reset_pages(); - } - } - - /** - * Provide a feedback after item_makereserved_execute. - * - * the idea is this: in a chain of parent-child items, - * -> reserved items can be parent of reserved items only - * -> reserved items can be child of reserved items only - * - * @return void - */ - public function item_makereserved_feedback() { - global $OUTPUT; - - if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { - $message = get_string('usercanceled', 'mod_surveypro'); - echo $OUTPUT->notification($message, 'notifymessage'); - return; - } - - if ($this->confirm == SURVEYPRO_UNCONFIRMED) { - // Here I must select the whole tree down. - $itemstoreserve = $this->add_parent_node(['reserved' => 0]); - - // I am interested to oldest parent only. - $baseitemid = end($itemstoreserve); - - // Build itemstoreserve starting from the oldest parent. - $itemstoreserve = $this->get_children($baseitemid, ['reserved' => 0]); - - $itemstoprocess = count($itemstoreserve); // This is the list of ancestors. - if ($itemstoprocess > 1) { // Ask for confirmation. - // If the clicked element has not parents. - $a = new \stdClass(); - $item = surveypro_get_item($this->cm, $this->surveypro, $this->rootitemid, $this->type, $this->plugin); - $a->itemcontent = $item->get_content(); - foreach ($itemstoreserve as $itemtoreserve) { - $dependencies[] = $itemtoreserve->sortindex; - } - // Drop the original item because it doesn't go in the message. - $key = array_search($this->sortindex, $dependencies); - if ($key !== false) { // Should always happen. - unset($dependencies[$key]); - } - $a->dependencies = implode(', ', $dependencies); - - if ($baseitemid != $this->rootitemid) { - $firstparentitem = reset($itemstoreserve); - $parentitem = surveypro_get_item($this->cm, $this->surveypro, $firstparentitem->id); - $a->parentcontent = $parentitem->get_content(); - $message = get_string('confirm_reservechainitems_newparent', 'mod_surveypro', $a); - } else { - if (count($dependencies) == 1) { - $message = get_string('confirm_reserve1item', 'mod_surveypro', $a); - } else { - $message = get_string('confirm_reservechainitems', 'mod_surveypro', $a); - } - } - - $optionbase = []; - $optionbase['s'] = $this->cm->instance; - $optionbase['act'] = SURVEYPRO_MAKERESERVED; - $optionbase['section'] = 'itemslist'; - $optionbase['sesskey'] = sesskey(); - - $optionsyes = $optionbase; - $optionsyes['cnf'] = SURVEYPRO_CONFIRMED_YES; - $optionsyes['itemid'] = $this->rootitemid; - $optionsyes['plugin'] = $this->plugin; - $optionsyes['type'] = $this->type; - $urlyes = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$this->sortindex, $optionsyes); - $buttonyes = new \single_button($urlyes, get_string('continue')); - - $optionsno = $optionbase; - $optionsno['cnf'] = SURVEYPRO_CONFIRMED_NO; - $urlno = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$this->sortindex, $optionsno); - $buttonno = new \single_button($urlno, get_string('no')); - - echo $OUTPUT->confirm($message, $buttonyes, $buttonno); - echo $OUTPUT->footer(); - die(); - } - } - } - - // MARK item make free. - - /** - * Set the item as standard (free). - * - * the idea is this: in a chain of parent-child items, - * -> available items (not reserved) can be parent of available items only - * -> available items (not reserved) can be child of available items only - * - * @return void - */ - public function item_makeavailable_execute() { - global $DB; - - if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { - return; - } - - // Build itemstoavailable. - $itemstoavailable = $this->add_parent_node(['reserved' => 1]); - - // I am interested to oldest parent only. - $baseitemid = end($itemstoavailable); - - // Build itemstoavailable starting from the oldest parent. - $itemstoavailable = $this->get_children($baseitemid, ['reserved' => 1]); - - $itemstoprocess = count($itemstoavailable); // This is the list of ancestors. - if ( ($this->confirm == SURVEYPRO_CONFIRMED_YES) || ($itemstoprocess == 1) ) { - // Make items available. - foreach ($itemstoavailable as $itemtoavailable) { - $DB->set_field('surveypro_item', 'reserved', 0, ['id' => $itemtoavailable->id]); - } - $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); - $utilitylayoutman->reset_pages(); - } - } - - /** - * Provide a feedback after item_makeavailable_execute. - * - * the idea is this: in a chain of parent-child items, - * -> available items (not reserved) can be parent of available items only - * -> available items (not reserved) can be child of available items only - * - * @return void - */ - public function item_makeavailable_feedback() { - global $OUTPUT; - - if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { - $message = get_string('usercanceled', 'mod_surveypro'); - echo $OUTPUT->notification($message, 'notifymessage'); - return; - } - - if ($this->confirm == SURVEYPRO_UNCONFIRMED) { - // Build itemstoavailable. - $itemstoavailable = $this->add_parent_node(['reserved' => 1]); - - // I am interested to oldest parent only. - $baseitemid = end($itemstoavailable); - - // Build itemstoavailable starting from the oldest parent. - $itemstoavailable = $this->get_children($baseitemid, ['reserved' => 1]); - - $itemstoprocess = count($itemstoavailable); // This is the list of ancestors. - if ($itemstoprocess > 1) { // Ask for confirmation. - // If the clicked element has not parents. - $a = new \stdClass(); - $item = surveypro_get_item($this->cm, $this->surveypro, $this->rootitemid, $this->type, $this->plugin); - $a->itemcontent = $item->get_content(); - foreach ($itemstoavailable as $itemtoavailable) { - $dependencies[] = $itemtoavailable->sortindex; - } - // Drop the original item because it doesn't go in the message. - $key = array_search($this->sortindex, $dependencies); - if ($key !== false) { // Should always happen. - unset($dependencies[$key]); - } - $a->dependencies = implode(', ', $dependencies); - - if ($baseitemid != $this->rootitemid) { - $firstparentitem = reset($itemstoavailable); - $parentitem = surveypro_get_item($this->cm, $this->surveypro, $firstparentitem->id); - $a->parentcontent = $parentitem->get_content(); - $message = get_string('confirm_freechainitems_newparent', 'mod_surveypro', $a); - } else { - if (count($dependencies) == 1) { - $message = get_string('confirm_free1item', 'mod_surveypro', $a); - } else { - $message = get_string('confirm_freechainitems', 'mod_surveypro', $a); - } - } - - $optionbase = []; - $optionbase['s'] = $this->cm->instance; - $optionbase['act'] = SURVEYPRO_MAKEAVAILABLE; - $optionbase['itemid'] = $this->rootitemid; - $optionbase['section'] = 'itemslist'; - $optionbase['sesskey'] = sesskey(); - - $optionsyes = $optionbase; - $optionsyes['cnf'] = SURVEYPRO_CONFIRMED_YES; - $optionsyes['itemid'] = $this->rootitemid; - $optionsyes['plugin'] = $this->plugin; - $optionsyes['type'] = $this->type; - $urlyes = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$this->sortindex, $optionsyes); - $buttonyes = new \single_button($urlyes, get_string('continue')); - - $optionsno = $optionbase; - $optionsno['cnf'] = SURVEYPRO_CONFIRMED_NO; - $urlno = new \moodle_url('/mod/surveypro/layout.php#sortindex_'.$this->sortindex, $optionsno); - $buttonno = new \single_button($urlno, get_string('no')); - - echo $OUTPUT->confirm($message, $buttonyes, $buttonno); - echo $OUTPUT->footer(); - die(); - } - } - } - - // MARK all hide. - - /** - * Hide all items. - * - * @return void - */ - public function hide_all_execute() { - if ($this->confirm == SURVEYPRO_CONFIRMED_YES) { - $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); - $whereparams = ['surveyproid' => $this->surveypro->id]; - $utilitylayoutman->items_set_visibility($whereparams, 0); - - $utilitylayoutman->reset_pages(); - - $this->set_confirm(SURVEYPRO_ACTION_EXECUTED); - } - } - - /** - * Provide a feedback after hide_all_execute. - * - * @return void - */ - public function hide_all_feedback() { - global $OUTPUT; - - if ($this->confirm == SURVEYPRO_UNCONFIRMED) { - $message = get_string('confirm_hideallitems', 'mod_surveypro'); - $yeskey = 'yes_hideallitems'; - $this->bulk_action_ask($message, $yeskey); - } - - if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { - $message = get_string('usercanceled', 'mod_surveypro'); - echo $OUTPUT->notification($message, 'notifymessage'); - } - - if ($this->confirm == SURVEYPRO_ACTION_EXECUTED) { - $message = get_string('feedback_hideallitems', 'mod_surveypro'); - echo $OUTPUT->notification($message, 'notifysuccess'); - } - } - - // MARK all show. - - /** - * Show all items. - * - * @return void - */ - public function show_all_execute() { - if ($this->confirm == SURVEYPRO_CONFIRMED_YES) { - $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); - - $whereparams = ['surveyproid' => $this->surveypro->id]; - $utilitylayoutman->items_set_visibility($whereparams, 1); - - $utilitylayoutman->items_reindex(); - - $this->set_confirm(SURVEYPRO_ACTION_EXECUTED); - } - } - - /** - * Provide a feedback after show_all_execute. - * - * @return void - */ - public function show_all_feedback() { - global $OUTPUT; - - if ($this->confirm == SURVEYPRO_UNCONFIRMED) { - $message = get_string('confirm_showallitems', 'mod_surveypro'); - $yeskey = 'yes_showallitems'; - $this->bulk_action_ask($message, $yeskey); - } - - if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { - $message = get_string('usercanceled', 'mod_surveypro'); - echo $OUTPUT->notification($message, 'notifymessage'); - } - - if ($this->confirm == SURVEYPRO_ACTION_EXECUTED) { - $message = get_string('feedback_showallitems', 'mod_surveypro'); - echo $OUTPUT->notification($message, 'notifysuccess'); - } - } - - // MARK all delete. - - /** - * Delete all items. - * - * @return void - */ - public function delete_all_execute() { - if ($this->confirm == SURVEYPRO_CONFIRMED_YES) { - $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); - - $whereparams = ['surveyproid' => $this->surveypro->id]; - $utilitylayoutman->delete_items($whereparams); - - $paramurl = []; - $paramurl['s'] = $this->cm->instance; - $paramurl['section'] = 'itemslist'; - $returnurl = new \moodle_url('/mod/surveypro/layout.php', $paramurl); - redirect($returnurl); - } - } - - /** - * Provide a feedback after delete_all_execute. - * - * @return void - */ - public function delete_all_feedback() { - global $OUTPUT; - - if ($this->confirm == SURVEYPRO_UNCONFIRMED) { - $message = get_string('confirm_deleteallitems', 'mod_surveypro'); - $yeskey = 'yes_deleteallitems'; - $this->bulk_action_ask($message, $yeskey); - } - - if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { - $message = get_string('usercanceled', 'mod_surveypro'); - echo $OUTPUT->notification($message, 'notifymessage'); - } - - if ($this->confirm == SURVEYPRO_ACTION_EXECUTED) { - $message = get_string('feedback_deleteallitems', 'mod_surveypro'); - echo $OUTPUT->notification($message, 'notifysuccess'); - } - } - - // MARK visible delete. - - /** - * Delete visible items. - * - * @return void - */ - public function delete_visible_execute() { - if ($this->confirm == SURVEYPRO_CONFIRMED_YES) { - $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); - - $whereparams = ['surveyproid' => $this->surveypro->id]; - $whereparams['hidden'] = 0; - $utilitylayoutman->delete_items($whereparams); - - $utilitylayoutman->items_reindex(); - - $paramurl = []; - $paramurl['s'] = $this->cm->instance; - $paramurl['act'] = SURVEYPRO_DELETEVISIBLEITEMS; - $paramurl['section'] = 'itemslist'; - $paramurl['sesskey'] = sesskey(); - $paramurl['cnf'] = SURVEYPRO_ACTION_EXECUTED; - $returnurl = new \moodle_url('/mod/surveypro/layout.php', $paramurl); - redirect($returnurl); - } - } - - /** - * Provide a feedback after delete_visible_execute. - * - * @return void - */ - public function delete_visible_feedback() { - global $OUTPUT; - - if ($this->confirm == SURVEYPRO_UNCONFIRMED) { - $message = get_string('confirm_deletevisibleitems', 'mod_surveypro'); - $yeskey = 'yes_deletevisibleitems'; - $this->bulk_action_ask($message, $yeskey); - } - - if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { - $message = get_string('usercanceled', 'mod_surveypro'); - echo $OUTPUT->notification($message, 'notifymessage'); - } - - if ($this->confirm == SURVEYPRO_ACTION_EXECUTED) { - $message = get_string('feedback_deletevisibleitems', 'mod_surveypro'); - echo $OUTPUT->notification($message, 'notifysuccess'); - } - } - - // MARK hidden delete. - - /** - * Delete hidden items. - * - * @return void - */ - public function delete_hidden_execute() { - if ($this->confirm == SURVEYPRO_CONFIRMED_YES) { - $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); - - $whereparams = ['surveyproid' => $this->surveypro->id]; - $whereparams['hidden'] = 1; - $utilitylayoutman->delete_items($whereparams); - - $utilitylayoutman->items_reindex(); - - $paramurl = []; - $paramurl['s'] = $this->cm->instance; - $paramurl['act'] = SURVEYPRO_DELETEHIDDENITEMS; - $paramurl['section'] = 'itemslist'; - $paramurl['sesskey'] = sesskey(); - $paramurl['cnf'] = SURVEYPRO_ACTION_EXECUTED; - $returnurl = new \moodle_url('/mod/surveypro/layout.php', $paramurl); - redirect($returnurl); - } - } - - /** - * Provide a feedback after delete_hidden_feedback. - * - * @return void - */ - public function delete_hidden_feedback() { - global $OUTPUT; - - if ($this->confirm == SURVEYPRO_UNCONFIRMED) { - $message = get_string('confirm_deletehiddenitems', 'mod_surveypro'); - $yeskey = 'yes_deletehiddenitems'; - $this->bulk_action_ask($message, $yeskey); - } - - if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { - $message = get_string('usercanceled', 'mod_surveypro'); - echo $OUTPUT->notification($message, 'notifymessage'); - } - - if ($this->confirm == SURVEYPRO_ACTION_EXECUTED) { - $message = get_string('feedback_deletehiddenitems', 'mod_surveypro'); - echo $OUTPUT->notification($message, 'notifysuccess'); - } - } - - // MARK get. - - /** - * Get item id. - * - * @return void - */ - public function get_itemid() { - return $this->rootitemid; - } - - /** - * Get type. - * - * @return void - */ - public function get_type() { - return $this->type; - } - - /** - * Get plugin. - * - * @return void - */ - public function get_plugin() { - return $this->plugin; - } - - /** - * Get has submissions. - * - * @return void - */ - public function get_hassubmissions() { - return $this->hassubmissions; - } - - /** - * Get item count. - * - * @return void - */ - public function get_itemcount() { - return $this->itemcount; + public function setup() { + $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); + $itemcount = $utilitylayoutman->has_items(0, null, true, true, true); + $this->set_itemcount($itemcount); } - // MARK set. - /** * Set typeplugin. * @@ -2148,6 +181,8 @@ public function set_typeplugin($typeplugin) { } } + // MARK set. + /** * Set type. * @@ -2179,23 +214,23 @@ public function set_itemid($itemid) { } /** - * Set sortindex. + * Set action. * - * @param int $sortindex + * @param int $action * @return void */ - public function set_sortindex($sortindex) { - $this->sortindex = $sortindex; + public function set_action($action) { + $this->action = $action; } /** - * Set action. + * Set itemcount. * - * @param int $action + * @param int $itemcount * @return void */ - public function set_action($action) { - $this->action = $action; + public function set_itemcount($itemcount) { + $this->itemcount = $itemcount; } /** @@ -2209,82 +244,64 @@ public function set_mode($mode) { } /** - * Set last item before. + * Set hassubmissions. * - * @param int $lastitembefore + * @param int $hassubmissions * @return void */ - public function set_lastitembefore($lastitembefore) { - $this->lastitembefore = $lastitembefore; + public function set_hassubmissions($hassubmissions) { + $this->hassubmissions = $hassubmissions; } - /** - * Set confirm. - * - * @param int $confirm - * @return void - */ - public function set_confirm($confirm) { - $this->confirm = $confirm; - } + // MARK get. /** - * Set nextindent. + * Get type. * - * @param int $nextindent * @return void */ - public function set_nextindent($nextindent) { - $this->nextindent = $nextindent; + public function get_type() { + return $this->type; } /** - * Set parentid. + * Get plugin. * - * @param int $parentid * @return void */ - public function set_parentid($parentid) { - $this->parentid = $parentid; + public function get_plugin() { + return $this->plugin; } - /** - * Set item editing feedback. - * - * @param int $itemeditingfeedback - * @return void - */ - public function set_itemeditingfeedback($itemeditingfeedback) { - $this->itemeditingfeedback = $itemeditingfeedback; - } + // MARK other. /** - * Set itemtomove. + * Prevent direct user input. * - * @param int $itemtomove * @return void */ - public function set_itemtomove($itemtomove) { - $this->itemtomove = $itemtomove; + public function prevent_direct_user_input() { + if ($this->surveypro->template) { + throw new \moodle_exception('incorrectaccessdetected', 'mod_surveypro'); + } } /** - * Set hassubmissions. + * Display the identity card of the item going to be created/edited just before the beginning of the item form. * - * @param int $hassubmissions * @return void */ - public function set_hassubmissions($hassubmissions) { - $this->hassubmissions = $hassubmissions; - } + public function item_identitycard() { + global $OUTPUT; - /** - * Set itemcount. - * - * @param int $itemcount - * @return void - */ - public function set_itemcount($itemcount) { - $this->itemcount = $itemcount; + $labelsep = get_string('labelsep', 'langconfig'); // Separator usually is ': '.. + $friendlyname = get_string('userfriendlypluginname', 'surveypro'.$this->type.'_'.$this->plugin); + + $iconparams = ['title' => $friendlyname, 'class' => 'icon']; + $message = $OUTPUT->pix_icon('icon', $friendlyname, 'surveypro'.$this->type.'_'.$this->plugin, $iconparams); + $message .= get_string($this->type, 'mod_surveypro').$labelsep.$friendlyname; + + echo $OUTPUT->box($message); } + } diff --git a/classes/layout_preview.php b/classes/layout_preview.php index dc7f7ac732b..6ca69ed8316 100644 --- a/classes/layout_preview.php +++ b/classes/layout_preview.php @@ -15,7 +15,7 @@ // along with Moodle. If not, see . /** - * Surveypro formpreview class. + * Surveypro layout_preview class. * * @package mod_surveypro * @copyright 2013 onwards kordan diff --git a/classes/local/form/mtemplate_applyform.php b/classes/local/form/mtemplate_applyform.php index 1e000b1f346..dc96c33c6d6 100644 --- a/classes/local/form/mtemplate_applyform.php +++ b/classes/local/form/mtemplate_applyform.php @@ -49,10 +49,10 @@ public function definition() { $mform = $this->_form; // Get _customdata. - $mtemplateman = $this->_customdata->mtemplateman; + $applyman = $this->_customdata->applyman; $inlineform = $this->_customdata->inlineform; - $mtemplates = $mtemplateman->get_mtemplates(); + $mtemplates = $applyman->get_mtemplates(); // Applymtemplate: mastertemplate. if (count($mtemplates)) { $fieldname = 'mastertemplate'; @@ -90,7 +90,7 @@ public function validation($data, $files) { // Useless: $mform = $this->_form;. // Get _customdata. - $mtemplateman = $this->_customdata->mtemplateman; + $applyman = $this->_customdata->applyman; // Useless: $mtemplates = $this->_customdata->mtemplates;. // Useless: $inlineform = $this->_customdata->inlineform;. @@ -99,7 +99,7 @@ public function validation($data, $files) { $templatename = $data['mastertemplate']; $templatepath = $CFG->dirroot.'/mod/surveypro/template/'.$templatename.'/template.xml'; $xml = file_get_contents($templatepath); - $errormessage = $mtemplateman->validate_xml($xml); + $errormessage = $applyman->validate_xml($xml); if ($errormessage !== false) { $addendum = get_string('mastertemplateaddendum', 'mod_surveypro'); if (isset($errormessage->a)) { diff --git a/classes/local/form/utemplate_createform.php b/classes/local/form/utemplate_createform.php index 75fbb33b4ca..6fad930ad87 100644 --- a/classes/local/form/utemplate_createform.php +++ b/classes/local/form/utemplate_createform.php @@ -46,7 +46,7 @@ public function definition() { $mform = $this->_form; // Get _customdata. - $utemplateman = $this->_customdata->utemplateman; + $saveman = $this->_customdata->saveman; $defaultname = $this->_customdata->defaultname; // Utemplatecreate: surveyproid. @@ -74,10 +74,10 @@ public function definition() { // Utemplatecreate: sharinglevel. $fieldname = 'sharinglevel'; - $contexts = $utemplateman->get_sharingcontexts(); + $contexts = $saveman->get_sharingcontexts(); $options = []; foreach ($contexts as $context) { - $options[$context->id] = $utemplateman->contextlevel_to_scontextlabel($context->contextlevel); + $options[$context->id] = $saveman->get_label_forcontextid($context->contextlevel); } $mform->addElement('select', $fieldname, get_string($fieldname, 'mod_surveypro'), $options); $mform->addHelpButton($fieldname, $fieldname, 'surveypro'); @@ -118,7 +118,7 @@ public function validation($data, $files) { // Useless: $mform = $this->_form;. // Get _customdata. - $utemplateman = $this->_customdata->utemplateman; + $saveman = $this->_customdata->saveman; // Useless: $defaultname = $this->_customdata->defaultname;. $errors = parent::validation($data, $files); @@ -130,7 +130,7 @@ public function validation($data, $files) { } // Get all template files. - $xmlfiles = $utemplateman->get_xmlfiles_list($data['sharinglevel']); + $xmlfiles = $saveman->get_xmlfiles_list($data['sharinglevel']); foreach ($xmlfiles as $contextid => $xmlfile) { foreach ($xmlfiles[$contextid] as $xmlfile) { diff --git a/classes/local/form/utemplate_importform.php b/classes/local/form/utemplate_importform.php index e19c16db258..6fc4a83425d 100644 --- a/classes/local/form/utemplate_importform.php +++ b/classes/local/form/utemplate_importform.php @@ -46,7 +46,7 @@ public function definition() { $mform = $this->_form; // Get _customdata. - $utemplateman = $this->_customdata->utemplateman; + $importman = $this->_customdata->importman; $attributes = $this->_customdata->filemanageroptions; // Templateimport: importfile. @@ -62,10 +62,10 @@ public function definition() { // Templateimport: sharinglevel. $fieldname = 'sharinglevel'; - $contexts = $utemplateman->get_sharingcontexts(); + $contexts = $importman->get_sharingcontexts(); $options = []; foreach ($contexts as $k => $context) { - $options[$k] = $utemplateman->contextlevel_to_scontextlabel($context->contextlevel); + $options[$k] = $importman->get_label_forcontextid($context->contextlevel); } $mform->addElement('select', $fieldname, get_string($fieldname, 'mod_surveypro'), $options); $mform->addHelpButton($fieldname, $fieldname, 'surveypro'); @@ -87,7 +87,7 @@ public function validation($data, $files) { // Useless: $mform = $this->_form;. // Get _customdata. - $utemplateman = $this->_customdata->utemplateman; + $importman = $this->_customdata->importman; // Useless: $attributes = $this->_customdata->filemanager_options;. $errors = parent::validation($data, $files); @@ -108,8 +108,8 @@ public function validation($data, $files) { $importedfiles[] = $xmlfilename; $xmlfileid = $file->get_id(); - $xml = $utemplateman->get_utemplate_content($xmlfileid); - $errormessage = $utemplateman->validate_xml($xml); + $xml = $importman->get_utemplate_content($xmlfileid); + $errormessage = $importman->validate_xml($xml); if ($errormessage !== false) { if (isset($errormessage->a)) { $errors['importfile_filemanager'] = get_string($errormessage->key, 'mod_surveypro', $errormessage->a); @@ -128,7 +128,7 @@ public function validation($data, $files) { } // Get all template files in the specified context. - $contextfiles = $utemplateman->get_utemplates_per_contextlevel($data['sharinglevel']); + $contextfiles = $importman->get_utemplates_per_contextlevel($data['sharinglevel']); foreach ($contextfiles as $xmlfile) { $filename = $xmlfile->get_filename(); diff --git a/classes/mtemplate_apply.php b/classes/mtemplate_apply.php new file mode 100644 index 00000000000..1036174b0b6 --- /dev/null +++ b/classes/mtemplate_apply.php @@ -0,0 +1,293 @@ +. + +/** + * Surveypro mtemplate_apply class. + * + * @package mod_surveypro + * @copyright 2013 onwards kordan + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_surveypro; + +use core_text; +use mod_surveypro\utility_layout; + +/** + * The class representing a master template + * + * @package mod_surveypro + * @copyright 2013 onwards kordan + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class mtemplate_apply extends mtemplate_base { + + /** + * @var array + */ + protected $langtree = []; + + // MARK get. + + /** + * Count available user template. + * + * @return array + */ + public function get_mtemplates() { + $mtemplates = []; + if ($mtemplatepluginlist = \core_component::get_plugin_list('surveyprotemplate')) { + foreach ($mtemplatepluginlist as $mtemplatename => $mtemplatepath) { + if (!get_config('surveyprotemplate_'.$mtemplatename, 'disabled')) { + $mtemplates[$mtemplatename] = get_string('pluginname', 'surveyprotemplate_'.$mtemplatename); + } + } + asort($mtemplates); + } + + return $mtemplates; + } + + // MARK other. + + /** + * Actually add items coming from template to the db. + * + * @return void + */ + public function add_items_from_template() { + global $CFG, $DB; + + // Create the class to apply mastertemplate settings. + $classname = 'surveyprotemplate_'.$this->templatename.'\template'; + $mastertemplate = new $classname(); + + $fs = get_file_storage(); + + $templatepath = $CFG->dirroot.'/mod/surveypro/template/'.$this->templatename.'/template.xml'; + $templatecontent = file_get_contents($templatepath); + + $simplexml = new \SimpleXMLElement($templatecontent); + + if (!$sortindexoffset = $DB->get_field('surveypro_item', 'MAX(sortindex)', ['surveyproid' => $this->surveypro->id])) { + $sortindexoffset = 0; + } + + // Load it only once. You are going to use it later. + $config = get_config('surveyprotemplate_'.$this->templatename); + + $naturalsortindex = 0; + foreach ($simplexml->children() as $xmlitem) { + + // Read the attributes of the item node. + foreach ($xmlitem->attributes() as $attribute => $value) { + // The $xmlitem looks like: . + if ($attribute == 'type') { + $currenttype = (string)$value; + } + if ($attribute == 'plugin') { + $currentplugin = (string)$value; + } + } + + // Take care to details. + // Load the item class in order to call its methods to validate $record before saving it. + $item = surveypro_get_item($this->cm, $this->surveypro, 0, $currenttype, $currentplugin); + + foreach ($xmlitem->children() as $xmltable) { // Surveypro_item and surveypro_<>. + $tablename = $xmltable->getName(); + if ($tablename == 'surveypro_item') { + $currenttablestructure = $this->get_table_structure(); + } else { + $currenttablestructure = $this->get_table_structure($currenttype, $currentplugin); + } + + $record = new \stdClass(); + + // Add to $record mandatory fields that will be overwritten, hopefully, with the content of the usertemplate. + $record->surveyproid = (int)$this->surveypro->id; + $record->type = $currenttype; + $record->plugin = $currentplugin; + if ($tablename == 'surveypro_item') { + $item->item_add_mandatory_base_fields($record); + } else { + $item->item_add_mandatory_plugin_fields($record); + } + + foreach ($xmltable->children() as $xmlfield) { + $fieldname = $xmlfield->getName(); + + // Tag always belong to surveypro_item table. + if ($fieldname == 'parent') { + foreach ($xmlfield->children() as $xmlparentattribute) { + $fieldname = $xmlparentattribute->getName(); + $fieldexists = in_array($fieldname, $currenttablestructure); + if ($fieldexists) { + $record->{$fieldname} = (string)$xmlparentattribute; + } + } + continue; + } + + // Tag always belong to surveypro(field|format)_<> table. + // So: ($fieldname == 'embedded') only when surveypro_item has already been saved. + // So: $itemid is known. + if ($fieldname == 'embedded') { + // Debug: $label = 'Count of attributes of the field '.$fieldname; + // Debug: echo '
'.$label.': '.count($xmlfield->children()).'
';. + foreach ($xmlfield->children() as $xmlfileattribute) { + $fileattributename = $xmlfileattribute->getName(); + if ($fileattributename == 'filename') { + $filename = $xmlfileattribute; + } + if ($fileattributename == 'filecontent') { + $filecontent = base64_decode($xmlfileattribute); + } + } + + // Add the file described by $filename and $filecontent to filearea. + // Alias, add pictures found in the utemplate to filearea. + $filerecord = new \stdClass(); + $filerecord->contextid = $this->context->id; + $filerecord->component = 'mod_surveypro'; + $filerecord->filearea = SURVEYPRO_ITEMCONTENTFILEAREA; + $filerecord->itemid = $itemid; + $filerecord->filepath = '/'; + $filerecord->filename = $filename; + $fileinfo = $fs->create_file_from_string($filerecord, $filecontent); + continue; + } + + $fieldexists = in_array($fieldname, $currenttablestructure); + if ($fieldexists) { + $record->{$fieldname} = (string)$xmlfield; + } + } + + unset($record->id); + + // Apply master template settings. + [$tablename, $record] = $mastertemplate->apply_template_settings($tablename, $record, $config); + + if ($tablename == 'surveypro_item') { + $naturalsortindex++; + $record->sortindex = $naturalsortindex + $sortindexoffset; + if (!empty($record->parentid)) { + $whereparams = ['surveyproid' => $this->surveypro->id]; + $whereparams['sortindex'] = $record->parentid + $sortindexoffset; + $record->parentid = $DB->get_field('surveypro_item', 'id', $whereparams, MUST_EXIST); + } + + $itemid = $DB->insert_record($tablename, $record); + } else { + // Take care to details. + $item->item_force_coherence($record); + $item->item_validate_variablename($record, $itemid); + $record->itemid = $itemid; + + $DB->insert_record($tablename, $record, false); + } + } + } + } + + /** + * Apply template. + * + * @return void + */ + public function apply_template() { + global $DB, $CFG; + + // Begin of: delete all existing items. + $utilitylayoutman = new utility_layout($this->cm); + $whereparams = ['surveyproid' => $this->surveypro->id]; + $utilitylayoutman->delete_items($whereparams); + // End of: delete all existing items. + + $this->templatename = $this->formdata->mastertemplate; + $record = new \stdClass(); + + $record->id = $this->surveypro->id; + $record->template = $this->templatename; + $DB->update_record('surveypro', $record); + + $this->add_items_from_template(); + + $paramurl = ['s' => $this->surveypro->id, 'section' => 'preview']; + $redirecturl = new \moodle_url('/mod/surveypro/layout.php', $paramurl); + redirect($redirecturl); + } + + /** + * Display a friendly message to stop the page load under particular conditions. + * + * @return void + */ + public function friendly_stop() { + global $OUTPUT; + + $riskyediting = ($this->surveypro->riskyeditdeadline > time()); + $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); + $hassubmissions = $utilitylayoutman->has_submissions(); + + if ($hassubmissions && (!$riskyediting)) { + echo $OUTPUT->notification(get_string('applyusertemplatedenied01', 'mod_surveypro'), 'notifyproblem'); + $url = new \moodle_url('/mod/surveypro/view.php', ['s' => $this->surveypro->id, 'section' => 'submissionslist']); + echo $OUTPUT->continue_button($url); + echo $OUTPUT->footer(); + die(); + } + } + + /** + * Trigger the provided event. + * + * @param string $eventname Event to trigger + * @return void + */ + public function trigger_event($eventname) { + $eventdata = ['context' => $this->context, 'objectid' => $this->surveypro->id]; + $eventdata['other'] = ['templatename' => $this->formdata->mastertemplate]; + switch ($eventname) { + case 'mastertemplate_applied': + $event = \mod_surveypro\event\mastertemplate_applied::create($eventdata); + break; + case 'mastertemplate_saved': // Sometimes called 'downloaded' too. + $event = \mod_surveypro\event\mastertemplate_saved::create($eventdata); + break; + default: + $message = 'Unexpected $eventname = '.$eventname; + debugging('Error at line '.__LINE__.' of '.__FILE__.'. '.$message , DEBUG_DEVELOPER); + } + $event->trigger(); + } + + /** + * Display the welcome message of the apply page. + * + * @return void + */ + public function welcome_apply_message() { + global $OUTPUT; + + $message = get_string('welcome_mtemplateapply', 'mod_surveypro'); + echo $OUTPUT->notification($message, 'notifymessage'); + } + + +} diff --git a/classes/mtemplate_base.php b/classes/mtemplate_base.php new file mode 100644 index 00000000000..be0ec931b89 --- /dev/null +++ b/classes/mtemplate_base.php @@ -0,0 +1,60 @@ +. + +/** + * Surveypro utemplate_base class. + * + * @package mod_surveypro + * @copyright 2013 onwards kordan + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_surveypro; + +/** + * The base class for templates + * + * @package mod_surveypro + * @copyright 2013 onwards kordan + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class mtemplate_base extends templatebase { + + // MARK other. + + /** + * Trigger the provided event. + * + * @param string $eventname Event to trigger + * @return void + */ + public function trigger_event($eventname) { + $eventdata = ['context' => $this->context, 'objectid' => $this->surveypro->id]; + $eventdata['other'] = ['templatename' => $this->formdata->mastertemplate]; + switch ($eventname) { + case 'mastertemplate_applied': + $event = \mod_surveypro\event\mastertemplate_applied::create($eventdata); + break; + case 'mastertemplate_saved': // Sometimes called 'downloaded' too. + $event = \mod_surveypro\event\mastertemplate_saved::create($eventdata); + break; + default: + $message = 'Unexpected $eventname = '.$eventname; + debugging('Error at line '.__LINE__.' of '.__FILE__.'. '.$message , DEBUG_DEVELOPER); + } + $event->trigger(); + } +} diff --git a/classes/mastertemplate.php b/classes/mtemplate_save.php similarity index 64% rename from classes/mastertemplate.php rename to classes/mtemplate_save.php index 5856f9ff624..843e9db1913 100644 --- a/classes/mastertemplate.php +++ b/classes/mtemplate_save.php @@ -15,7 +15,7 @@ // along with Moodle. If not, see . /** - * Surveypro mastertemplate class. + * Surveypro mtemplate_save class. * * @package mod_surveypro * @copyright 2013 onwards kordan @@ -26,7 +26,6 @@ use core_text; use mod_surveypro\utility_layout; -use mod_surveypro\templatebase; /** * The class representing a master template @@ -35,42 +34,31 @@ * @copyright 2013 onwards kordan * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class mastertemplate extends templatebase { +class mtemplate_save extends mtemplate_base { /** * @var array */ protected $langtree = []; - /** - * Display the welcome message of the apply page. - * - * @return void - */ - public function welcome_apply_message() { - global $OUTPUT; - - $message = get_string('welcome_mtemplateapply', 'mod_surveypro'); - echo $OUTPUT->notification($message, 'notifymessage'); - } + // MARK get. /** - * Download master template. + * Generate the array of strings for the lang file of the mastertemplate plugin. * * @return void */ - public function download_mtemplate() { - $this->templatename = $this->generate_mtemplate(); - $exportfilename = basename($this->templatename); - header("Content-Type: application/download\n"); - header("Content-Disposition: attachment; filename=\"$exportfilename\""); - header('Expires: 0'); - header('Cache-Control: must-revalidate,post-check=0,pre-check=0'); - header('Pragma: public'); - $exportfilehandler = fopen($this->templatename, 'rb'); - print fread($exportfilehandler, filesize($this->templatename)); - fclose($exportfilehandler); - unlink($this->templatename); + public function get_lang_file_content() { + $stringsastext = []; + foreach ($this->langtree as $langbranch) { + foreach ($langbranch as $k => $stringcontent) { + // Do not use php addslashes() because it adds slashes to " too. + $stringcontent = str_replace("'", "\\'", $stringcontent); + $stringsastext[] = '$string[\''.$k.'\'] = \''.$stringcontent.'\';'; + } + } + + return "\n".implode("\n", $stringsastext); } /** @@ -109,37 +97,48 @@ public function get_plugin_name() { return $pluginname; } + // MARK other. + /** - * Count available user template. + * Append all the field that will have content derived from the lang files. * - * @return array + * @param array $multilangfields + * @param object $item + * @return void */ - public function get_mtemplates() { - $mtemplates = []; - if ($mtemplatepluginlist = \core_component::get_plugin_list('surveyprotemplate')) { - foreach ($mtemplatepluginlist as $mtemplatename => $mtemplatepath) { - if (!get_config('surveyprotemplate_'.$mtemplatename, 'disabled')) { - $mtemplates[$mtemplatename] = get_string('pluginname', 'surveyprotemplate_'.$mtemplatename); + public function build_langtree($multilangfields, $item) { + foreach ($multilangfields as $plugin => $fieldnames) { + foreach ($fieldnames as $fieldname) { + $component = $plugin.'_'.$fieldname; + if (isset($this->langtree[$component])) { + $index = count($this->langtree[$component]); + } else { + $index = 0; } + $stringindex = sprintf('%02d', 1 + $index); + $content = str_replace("\r", '', $item->get_generic_property($fieldname)); + $this->langtree[$component][$component.'_'.$stringindex] = $content; } - asort($mtemplates); } - - return $mtemplates; } /** - * Count available user template. + * Download master template. * - * @return array + * @return void */ - public function get_mtemplates_count() { - $mtemplatescount = 0; - if ($mtemplatepluginlist = \core_component::get_plugin_list('surveyprotemplate')) { - $mtemplatescount += count($mtemplatepluginlist); - } - - return $mtemplatescount; + public function download_mtemplate() { + $this->templatename = $this->generate_mtemplate(); + $exportfilename = basename($this->templatename); + header("Content-Type: application/download\n"); + header("Content-Disposition: attachment; filename=\"$exportfilename\""); + header('Expires: 0'); + header('Cache-Control: must-revalidate,post-check=0,pre-check=0'); + header('Pragma: public'); + $exportfilehandler = fopen($this->templatename, 'rb'); + print fread($exportfilehandler, filesize($this->templatename)); + fclose($exportfilehandler); + unlink($this->templatename); } /** @@ -350,6 +349,28 @@ public function generate_mtemplate() { return $exportfile; } + /** + * Replace package. + * + * // Replace 'package mod_surveypro' with 'package surveyprotemplate_'.$pluginname + * // Replace ' templatemaster' with $pluginname + * + * @param string $filecontent + * @param string $pluginname + * @return string $filecontent + */ + public function replace_package($filecontent, $pluginname) { + $oldstring = 'templatemaster'; + $newstring = $pluginname; + $filecontent = str_replace($oldstring, $newstring, $filecontent); + + $oldstring = ' * @package mod_surveypro'; + $newstring = ' * @package surveyprotemplate_'.$pluginname; + $filecontent = str_replace($oldstring, $newstring, $filecontent); + + return $filecontent; + } + /** * Write master template content. * @@ -508,308 +529,4 @@ public function xml_get_field_content($item, $plugin, $field, $multilangfields) return $val; } - - /** - * Replace package. - * - * // Replace 'package mod_surveypro' with 'package surveyprotemplate_'.$pluginname - * // Replace ' templatemaster' with $pluginname - * - * @param string $filecontent - * @param string $pluginname - * @return string $filecontent - */ - public function replace_package($filecontent, $pluginname) { - $oldstring = 'templatemaster'; - $newstring = $pluginname; - $filecontent = str_replace($oldstring, $newstring, $filecontent); - - $oldstring = ' * @package mod_surveypro'; - $newstring = ' * @package surveyprotemplate_'.$pluginname; - $filecontent = str_replace($oldstring, $newstring, $filecontent); - - return $filecontent; - } - - /** - * Apply template. - * - * @return void - */ - public function apply_template() { - global $DB, $CFG; - - $this->trigger_event('mastertemplate_applied'); - - // Begin of: delete all existing items. - $utilitylayoutman = new utility_layout($this->cm); - $whereparams = ['surveyproid' => $this->surveypro->id]; - $utilitylayoutman->delete_items($whereparams); - // End of: delete all existing items. - - $this->templatename = $this->formdata->mastertemplate; - $record = new \stdClass(); - - $record->id = $this->surveypro->id; - $record->template = $this->templatename; - $DB->update_record('surveypro', $record); - - $this->add_items_from_template(); - - $paramurl = ['s' => $this->surveypro->id, 'section' => 'preview']; - $redirecturl = new \moodle_url('/mod/surveypro/layout.php', $paramurl); - redirect($redirecturl); - } - - /** - * Display a friendly message to stop the page load under particular conditions. - * - * @return void - */ - public function friendly_stop() { - global $OUTPUT; - - $riskyediting = ($this->surveypro->riskyeditdeadline > time()); - $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); - $hassubmissions = $utilitylayoutman->has_submissions(); - - if ($hassubmissions && (!$riskyediting)) { - echo $OUTPUT->notification(get_string('applyusertemplatedenied01', 'mod_surveypro'), 'notifyproblem'); - $url = new \moodle_url('/mod/surveypro/view.php', ['s' => $this->surveypro->id, 'section' => 'submissionslist']); - echo $OUTPUT->continue_button($url); - echo $OUTPUT->footer(); - die(); - } - } - - /** - * Actually add items coming from template to the db. - * - * @return void - */ - public function add_items_from_template() { - global $CFG, $DB; - - // Create the class to apply mastertemplate settings. - $classname = 'surveyprotemplate_'.$this->templatename.'\template'; - $mastertemplate = new $classname(); - - $fs = get_file_storage(); - - $templatepath = $CFG->dirroot.'/mod/surveypro/template/'.$this->templatename.'/template.xml'; - $templatecontent = file_get_contents($templatepath); - - $simplexml = new \SimpleXMLElement($templatecontent); - - if (!$sortindexoffset = $DB->get_field('surveypro_item', 'MAX(sortindex)', ['surveyproid' => $this->surveypro->id])) { - $sortindexoffset = 0; - } - - // Load it only once. You are going to use it later. - $config = get_config('surveyprotemplate_'.$this->templatename); - - $naturalsortindex = 0; - foreach ($simplexml->children() as $xmlitem) { - - // Read the attributes of the item node. - foreach ($xmlitem->attributes() as $attribute => $value) { - // The $xmlitem looks like: . - if ($attribute == 'type') { - $currenttype = (string)$value; - } - if ($attribute == 'plugin') { - $currentplugin = (string)$value; - } - } - - // Take care to details. - // Load the item class in order to call its methods to validate $record before saving it. - $item = surveypro_get_item($this->cm, $this->surveypro, 0, $currenttype, $currentplugin); - - foreach ($xmlitem->children() as $xmltable) { // Surveypro_item and surveypro_<>. - $tablename = $xmltable->getName(); - if ($tablename == 'surveypro_item') { - $currenttablestructure = $this->get_table_structure(); - } else { - $currenttablestructure = $this->get_table_structure($currenttype, $currentplugin); - } - - $record = new \stdClass(); - - // Add to $record mandatory fields that will be overwritten, hopefully, with the content of the usertemplate. - $record->surveyproid = (int)$this->surveypro->id; - $record->type = $currenttype; - $record->plugin = $currentplugin; - if ($tablename == 'surveypro_item') { - $item->item_add_mandatory_base_fields($record); - } else { - $item->item_add_mandatory_plugin_fields($record); - } - - foreach ($xmltable->children() as $xmlfield) { - $fieldname = $xmlfield->getName(); - - // Tag always belong to surveypro_item table. - if ($fieldname == 'parent') { - foreach ($xmlfield->children() as $xmlparentattribute) { - $fieldname = $xmlparentattribute->getName(); - $fieldexists = in_array($fieldname, $currenttablestructure); - if ($fieldexists) { - $record->{$fieldname} = (string)$xmlparentattribute; - } - } - continue; - } - - // Tag always belong to surveypro(field|format)_<> table. - // So: ($fieldname == 'embedded') only when surveypro_item has already been saved. - // So: $itemid is known. - if ($fieldname == 'embedded') { - // Debug: $label = 'Count of attributes of the field '.$fieldname; - // Debug: echo '
'.$label.': '.count($xmlfield->children()).'
';. - foreach ($xmlfield->children() as $xmlfileattribute) { - $fileattributename = $xmlfileattribute->getName(); - if ($fileattributename == 'filename') { - $filename = $xmlfileattribute; - } - if ($fileattributename == 'filecontent') { - $filecontent = base64_decode($xmlfileattribute); - } - } - - // Add the file described by $filename and $filecontent to filearea. - // Alias, add pictures found in the utemplate to filearea. - $filerecord = new \stdClass(); - $filerecord->contextid = $this->context->id; - $filerecord->component = 'mod_surveypro'; - $filerecord->filearea = SURVEYPRO_ITEMCONTENTFILEAREA; - $filerecord->itemid = $itemid; - $filerecord->filepath = '/'; - $filerecord->filename = $filename; - $fileinfo = $fs->create_file_from_string($filerecord, $filecontent); - continue; - } - - $fieldexists = in_array($fieldname, $currenttablestructure); - if ($fieldexists) { - $record->{$fieldname} = (string)$xmlfield; - } - } - - unset($record->id); - - // Apply master template settings. - [$tablename, $record] = $mastertemplate->apply_template_settings($tablename, $record, $config); - - if ($tablename == 'surveypro_item') { - $naturalsortindex++; - $record->sortindex = $naturalsortindex + $sortindexoffset; - if (!empty($record->parentid)) { - $whereparams = ['surveyproid' => $this->surveypro->id]; - $whereparams['sortindex'] = $record->parentid + $sortindexoffset; - $record->parentid = $DB->get_field('surveypro_item', 'id', $whereparams, MUST_EXIST); - } - - $itemid = $DB->insert_record($tablename, $record); - } else { - // Take care to details. - $item->item_force_coherence($record); - $item->item_validate_variablename($record, $itemid); - $record->itemid = $itemid; - - $DB->insert_record($tablename, $record, false); - } - } - } - } - - /** - * Append all the field that will have content derived from the lang files. - * - * @param array $multilangfields - * @param object $item - * @return void - */ - public function build_langtree($multilangfields, $item) { - foreach ($multilangfields as $plugin => $fieldnames) { - foreach ($fieldnames as $fieldname) { - $component = $plugin.'_'.$fieldname; - if (isset($this->langtree[$component])) { - $index = count($this->langtree[$component]); - } else { - $index = 0; - } - $stringindex = sprintf('%02d', 1 + $index); - $content = str_replace("\r", '', $item->get_generic_property($fieldname)); - $this->langtree[$component][$component.'_'.$stringindex] = $content; - } - } - } - - /** - * Generate the array of strings for the lang file of the mastertemplate plugin. - * - * @return void - */ - public function get_lang_file_content() { - $stringsastext = []; - foreach ($this->langtree as $langbranch) { - foreach ($langbranch as $k => $stringcontent) { - // Do not use php addslashes() because it adds slashes to " too. - $stringcontent = str_replace("'", "\\'", $stringcontent); - $stringsastext[] = '$string[\''.$k.'\'] = \''.$stringcontent.'\';'; - } - } - - return "\n".implode("\n", $stringsastext); - } - - /** - * Trigger the provided event. - * - * @param string $eventname Event to trigger - * @return void - */ - public function trigger_event($eventname) { - $eventdata = ['context' => $this->context, 'objectid' => $this->surveypro->id]; - $eventdata['other'] = ['templatename' => $this->formdata->mastertemplate]; - switch ($eventname) { - case 'mastertemplate_applied': - $event = \mod_surveypro\event\mastertemplate_applied::create($eventdata); - break; - case 'mastertemplate_saved': // Sometimes called 'downloaded' too. - $event = \mod_surveypro\event\mastertemplate_saved::create($eventdata); - break; - default: - $message = 'Unexpected $eventname = '.$eventname; - debugging('Error at line '.__LINE__.' of '.__FILE__.'. '.$message , DEBUG_DEVELOPER); - } - $event->trigger(); - } - - // MARK get. - - /** - * Get translated strings. - * - * @param string $userlang - * @return void - */ - public function get_translated_strings($userlang) { - $stringsastext = []; - $a = new \stdClass(); - $a->userlang = $userlang; - foreach ($this->langtree as $langbranch) { - foreach ($langbranch as $k => $originalstring) { - if (empty($originalstring)) { - $stringsastext[] = '$string[\''.$k.'\'] = \'\';'; - } else { - $a->stringkey = $k; - $stringsastext[] = get_string('translatedstring', 'mod_surveypro', $a); - } - } - } - - return "\n".implode("\n", $stringsastext); - } } diff --git a/classes/tools_export.php b/classes/tools_export.php index 154e98e6617..461e7927f5a 100644 --- a/classes/tools_export.php +++ b/classes/tools_export.php @@ -15,7 +15,7 @@ // along with Moodle. If not, see . /** - * The exportmanager class + * The tools_export class * * @package mod_surveypro * @copyright 2013 onwards kordan diff --git a/classes/tools_import.php b/classes/tools_import.php index afe6243a046..fd36f9473ef 100644 --- a/classes/tools_import.php +++ b/classes/tools_import.php @@ -15,7 +15,7 @@ // along with Moodle. If not, see . /** - * The importmanager class + * The tools_import class * * @package mod_surveypro * @copyright 2013 onwards kordan diff --git a/classes/usertemplate.php b/classes/usertemplate.php deleted file mode 100644 index b0b2b3199ca..00000000000 --- a/classes/usertemplate.php +++ /dev/null @@ -1,1199 +0,0 @@ -. - -/** - * Surveypro usertemplate class. - * - * @package mod_surveypro - * @copyright 2013 onwards kordan - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -namespace mod_surveypro; - -use core_text; -use mod_surveypro\local\ipe\usertemplate_name; -use mod_surveypro\utility_layout; -use mod_surveypro\templatebase; - -/** - * The class representing a user template - * - * @package mod_surveypro - * @copyright 2013 onwards kordan - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class usertemplate extends templatebase { - - /** - * @var int ID of the current user template - */ - protected $utemplateid; - - /** - * @var int User confirmation to actions - */ - protected $confirm; - - /** - * Setup. - * - * @param int $utemplateid - * @param int $action - * @param int $confirm - * @return void - */ - public function setup($utemplateid, $action, $confirm) { - $this->set_utemplateid($utemplateid); - $this->set_action($action); - $this->set_confirm($confirm); - } - - // MARK set. - - /** - * Set utemplateid. - * - * @param int $utemplateid - * @return void - */ - private function set_utemplateid($utemplateid) { - $this->utemplateid = $utemplateid; - } - - /** - * Set action. - * - * @param int $action - * @return void - */ - private function set_action($action) { - $this->action = $action; - } - - /** - * Set confirm. - * - * @param int $confirm - * @return void - */ - private function set_confirm($confirm) { - $this->confirm = $confirm; - } - - // MARK get. - - /** - * Get filemanager options. - * - * @return $filemanageroptions - */ - public function get_filemanager_options() { - $templateoptions = ['accepted_types' => '.xml']; - $templateoptions['maxbytes'] = 0; - $templateoptions['maxfiles'] = -1; - $templateoptions['mainfile'] = true; - $templateoptions['subdirs'] = false; - - return $templateoptions; - } - - /** - * Get the list of each user template file. - * - * @param int $acontextid Context that we are looking for - * @return array - */ - public function get_xmlfiles_list($acontextid=null) { - $utemplates = []; - - $contexts = $this->get_sharingcontexts(); - // I am allowed to "see" usertemplates if they belong to one of my parent contextid - // or if their uid is $USER->id. - foreach ($contexts as $context) { - $contextid = $context->id; - if (is_null($acontextid) || ($contextid == $acontextid)) { - $xmlfiles = $this->get_utemplates_per_contextlevel($contextid); - if (count($xmlfiles)) { - foreach ($xmlfiles as $xmlfile) { - $utemplates[$context->contextlevel][] = $xmlfile; - } - } - } - } - asort($utemplates); - - return $utemplates; - } - - /** - * Get the list of ech user template. - * - * As far as I know this method is never called - * - * @param int $acontextid Context that we are looking for - * @return array - */ - public function get_utemplates_names($acontextid=null) { - $xmlfiles = $this->get_xmlfiles_list($acontextid); - $items = []; - foreach ($xmlfiles as $contextid => $xmlfile) { - foreach ($xmlfiles[$contextid] as $xmlfile) { - $items[] = $xmlfile->get_filename(); - } - } - asort($items); - - return $items; - } - - /** - * Get the content of the user template drop down menu. - * - * @return array - */ - public function get_utemplates_items() { - $xmlfiles = $this->get_xmlfiles_list(); - - $items = []; - foreach ($xmlfiles as $contextid => $unused) { - $contextlabel = $this->contextlevel_to_scontextlabel($contextid); - foreach ($xmlfiles[$contextid] as $xmlfile) { - $xmlid = $xmlfile->get_id(); - $filename = $xmlfile->get_filename(); - $items[$contextid.'_'.$xmlid] = '('.$contextlabel.') '.$filename; - } - } - asort($items); - - return $items; - } - - /** - * Get the content of the user template drop down menu. - * - * @return array - */ - public function get_utemplates_count() { - $xmlfiles = $this->get_xmlfiles_list(); - - $utemplatescount = 0; - foreach ($xmlfiles as $contextid => $unused) { - $utemplatescount += count($xmlfiles[$contextid]); - } - - return $utemplatescount; - } - - /** - * Get sharing level contexts. - * - * @return $options - */ - public function get_sharingcontexts() { - global $USER; - - $parentcontexts = $this->context->get_parent_contexts(); - - $usercontext = \context_module::instance($this->cm->id); - $usercontextid = $usercontext->id; - $parentcontexts[$usercontextid] = $usercontext; - - $usercontext = \context_user::instance($USER->id); - $usercontextid = $usercontext->id; - $parentcontexts[$usercontextid] = $usercontext; - - return $parentcontexts; - } - - /** - * Gets an array of all of the templates that users have saved to the site. - * - * Few explanation to better understand. - * Asking for sharingcontexts I get the list of parentcontexts AND the usercontext. - * Each single context has a "context level" (50 for courses, 40 for categories, 10 for system, 30 for user). - * There are A LOT of contexts having "context level" == 50. One context per each course. - * The context of the course where I am in has: - * contextlevel = 50 (of course) AND id = another number, for instance, 79. - * 79 is the ID of the context of the course I am in, but 79 is NOT the ID of the course I am in. - - * When I ask for usertemplates saved at course level, I want to get all the usertemplates of MY COURSE - * and not all the usetemplates of EACH COURSE in this instance of moodle. - * This is why I ask for $this->get_utemplates_per_contextlevel($context->id); - * and NOT for $this->get_utemplates_per_contextlevel($context->contextlevel). - - * @param int $contextid Context that we are looking for - * @return array $templates - */ - public function get_utemplates_per_contextlevel($contextid) { - global $USER; - - $fs = get_file_storage(); - $files = $fs->get_area_files($contextid, 'mod_surveypro', SURVEYPRO_TEMPLATEFILEAREA, 0, 'sortorder', false); - if (empty($files)) { - return []; - } - - $templates = []; - foreach ($files as $file) { - if ($file->get_component() == 'user') { - $fileallowed = has_capability('mod/surveypro:applyusertemplates', $this->context); - $fileallowed = $fileallowed || ($file->userid == $USER->id); - if ($fileallowed) { - break; - } - } else { - $fileallowed = true; - } - if ($fileallowed) { - $templates[] = $file; - } - } - - return $templates; - } - - /** - * Get user template content. - * - * @param int $utemplateid - * @return void - */ - public function get_utemplate_content($utemplateid=0) { - $fs = get_file_storage(); - if (empty($utemplateid)) { - $utemplateid = $this->utemplateid; - } - $xmlfile = $fs->get_file_by_id($utemplateid); - - return $xmlfile->get_content(); - } - - /** - * Get user template name. - * - * @return void - */ - public function get_utemplate_name() { - $fs = get_file_storage(); - $xmlfile = $fs->get_file_by_id($this->utemplateid); - - return $xmlfile->get_filename(); - } - - /** - * Create the tool to sort usertemplates in the table. - * - * @param array $templates - * @param string $usersort - * @return void - */ - private function get_virtual_table($templates, $usersort) { - // Original table per columns: originaltablepercols. - $templatenamecol = []; - $sharinglevelcol = []; - $creationdatecol = []; - $xmlfileidcol = []; - foreach ($templates as $template) { - $templatenamecol[] = $template->filename; - $sharinglevelcol[] = $template->sharingcontext; - $creationdatecol[] = $template->timecreated; - $xmlfileidcol[] = $template->fileid; - } - $originaltablepercols = [$templatenamecol, $sharinglevelcol, $creationdatecol, $xmlfileidcol]; - - // Original table per rows: originaltableperrows. - $originaltableperrows = []; - foreach ($templatenamecol as $k => $unused) { - $tablerow = []; - $tablerow['templatename'] = $templatenamecol[$k]; - $tablerow['sharinglevel'] = $sharinglevelcol[$k]; - $tablerow['creationdate'] = $creationdatecol[$k]; - $tablerow['xmlfileid'] = $xmlfileidcol[$k]; - - $originaltableperrows[] = $tablerow; - } - - // Add orderpart. - $orderparts = explode(', ', $usersort); - $orderparts = str_replace('templatename', '0', $orderparts); - $orderparts = str_replace('sharinglevel', '1', $orderparts); - $orderparts = str_replace('timecreated', '2', $orderparts); - - // Include $fieldindex and $sortflag. - $fieldindex = [0, 0, 0]; - $sortflag = [SORT_ASC, SORT_ASC, SORT_ASC]; - foreach ($orderparts as $k => $orderpart) { - $pair = explode(' ', $orderpart); - $fieldindex[$k] = (int)$pair[0]; - $sortflag[$k] = ($pair[1] == 'ASC') ? SORT_ASC : SORT_DESC; - } - - array_multisort($originaltablepercols[$fieldindex[0]], $sortflag[0], - $originaltablepercols[$fieldindex[1]], $sortflag[1], - $originaltablepercols[$fieldindex[2]], $sortflag[2], $originaltableperrows); - - return $originaltableperrows; - } - - // MARK other. - - /** - * Delete usertemplate. - * - * @return void - */ - public function delete_utemplate() { - global $OUTPUT; - - if ($this->action != SURVEYPRO_DELETEUTEMPLATE) { - return; - } - - if ($this->confirm == SURVEYPRO_UNCONFIRMED) { - // Ask for confirmation. - $a = $this->get_utemplate_name(); - $message = get_string('confirm_delete1utemplate', 'mod_surveypro', $a); - $optionsbase = ['s' => $this->surveypro->id, 'act' => SURVEYPRO_DELETEUTEMPLATE]; - - $optionsyes = $optionsbase; - $optionsyes['cnf'] = SURVEYPRO_CONFIRMED_YES; - $optionsyes['fid'] = $this->utemplateid; - $optionsyes['section'] = 'manage'; - $urlyes = new \moodle_url('/mod/surveypro/utemplates.php', $optionsyes); - $buttonyes = new \single_button($urlyes, get_string('yes')); - - $optionsno = $optionsbase; - $optionsno['cnf'] = SURVEYPRO_CONFIRMED_NO; - $optionsno['section'] = 'manage'; - $urlno = new \moodle_url('/mod/surveypro/utemplates.php', $optionsno); - $buttonno = new \single_button($urlno, get_string('no')); - - echo $OUTPUT->confirm($message, $buttonyes, $buttonno); - echo $OUTPUT->footer(); - die(); - } - - if ($this->confirm == SURVEYPRO_CONFIRMED_YES) { - // Put the name in the gobal vaiable, to remember it for the log. - $this->templatename = $this->get_utemplate_name(); - - $fs = get_file_storage(); - $xmlfile = $fs->get_file_by_id($this->utemplateid); - $a = $xmlfile->get_filename(); - $xmlfile->delete(); - - $this->trigger_event('usertemplate_deleted'); - - // Feedback. - $message = get_string('feedback_delete1utemplate', 'mod_surveypro', $a); - echo $OUTPUT->notification($message, 'notifymessage'); - } - - if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { - $message = get_string('usercanceled', 'mod_surveypro'); - echo $OUTPUT->notification($message, 'notifymessage'); - } - } - - /** - * Display the welcome message of the save page. - * - * @return void - */ - public function welcome_save_message() { - global $OUTPUT; - - $a = get_string('sharinglevel', 'mod_surveypro'); - $message = get_string('welcome_utemplatesave', 'mod_surveypro', $a); - echo $OUTPUT->notification($message, 'notifymessage'); - } - - /** - * Display the welcome message of the import page. - * - * @return void - */ - public function welcome_import_message() { - global $OUTPUT; - - $a = get_string('utemplate_save', 'mod_surveypro'); - $message = get_string('welcome_utemplateimport', 'mod_surveypro', $a); - echo $OUTPUT->notification($message, 'notifymessage'); - } - - /** - * Display the welcome message of the apply page. - * - * @return void - */ - public function welcome_apply_message() { - global $OUTPUT; - - $a = new \stdClass(); - $a->uploadpage = get_string('utemplate_import', 'mod_surveypro'); - $a->savepage = get_string('utemplate_save', 'mod_surveypro'); - $message = get_string('welcome_utemplateapply', 'mod_surveypro', $a); - echo $OUTPUT->notification($message, 'notifymessage'); - } - - /** - * Write template content. - * - * @param boolean $visiblesonly - * @return void - */ - public function write_template_content($visiblesonly=true) { - global $DB; - - $pluginversion = self::get_subplugin_versions(); - $where = ['surveyproid' => $this->surveypro->id]; - if ($visiblesonly) { - $where['hidden'] = '0'; - } - $itemseeds = $DB->get_records('surveypro_item', $where, 'sortindex', 'id, type, plugin'); - - $fs = get_file_storage(); - $context = \context_module::instance($this->cm->id); - - $xmltemplate = new \SimpleXMLElement(''); - foreach ($itemseeds as $itemseed) { - $item = surveypro_get_item($this->cm, $this->surveypro, $itemseed->id, $itemseed->type, $itemseed->plugin); - - $xmlitem = $xmltemplate->addChild('item'); - $xmlitem->addAttribute('type', $itemseed->type); - $xmlitem->addAttribute('plugin', $itemseed->plugin); - $index = $itemseed->type.'_'.$itemseed->plugin; - $xmlitem->addAttribute('version', $pluginversion[$index]); - - // Surveypro_item. - $xmltable = $xmlitem->addChild('surveypro_item'); - $structure = $this->get_table_structure(); - foreach ($structure as $field) { - if ($field == 'parentid') { - $parentid = $item->get_parentid(); - if ($parentid) { - // Store the sortindex of the parent instead of its id, because at restore time parentid will change. - $whereparams = ['id' => $parentid]; - $sortindex = $DB->get_field('surveypro_item', 'sortindex', $whereparams, MUST_EXIST); - $val = $item->get_parentvalue(); - - $xmlparent = $xmltable->addChild('parent'); - $xmlfield = $xmlparent->addChild('parentid', $sortindex); - $xmlfield = $xmlparent->addChild('parentvalue', $val); - } // Otherwise: It is empty, do not evaluate: jump. - continue; - } - if ($field == 'parentvalue') { - continue; - } - - $val = $item->get_generic_property($field); - if (core_text::strlen($val)) { - $xmlfield = $xmltable->addChild($field, $val); - } // Otherwise: It is empty, do not evaluate: jump. - } - - // Child table. - $structure = $this->get_table_structure($itemseed->type, $itemseed->plugin); - // Take care: some items plugin may be free of their own specific table. - if (!count($structure)) { - continue; - } - - $tablename = 'surveypro'.$itemseed->type.'_'.$itemseed->plugin; - $xmltable = $xmlitem->addChild($tablename); - foreach ($structure as $field) { - // If $field == 'content' I can not use the property of the object $item because - // in case of pictures, for instance, $item->content has to look like: - // 'MMM' - // and not like: - // 'img1get_generic_property($field); - } else { - $val = $DB->get_field($tablename, 'content', ['itemid' => $itemseed->id], MUST_EXIST); - } - - if (core_text::strlen($val)) { - $xmlfield = $xmltable->addChild($field, htmlspecialchars($val, ENT_QUOTES | ENT_SUBSTITUTE)); - } // Otherwise: It is empty, do not evaluate: jump. - - if ($field == 'content') { - $itemid = $item->get_itemid(); - if ($files = $fs->get_area_files($context->id, 'mod_surveypro', SURVEYPRO_ITEMCONTENTFILEAREA, $itemid)) { - foreach ($files as $file) { - $filename = $file->get_filename(); - if ($filename == '.') { - continue; - } - $xmlembedded = $xmltable->addChild('embedded'); - $xmlembedded->addChild('filename', $filename); - $xmlembedded->addChild('filecontent', base64_encode($file->get_content())); - } - } - } - } - } - - // In the coming code, "$option == false;" if 100% waste of time and should be changed to "$option == true;" - // BUT BUT BUT... - // the output in $dom->saveXML() is well written. - // I prefer a more readable xml file instead of few nanoseconds saved. - $option = false; - if ($option) { - return $xmltemplate->asXML(); - } else { - $dom = new \DOMDocument('1.0'); - $dom->preserveWhiteSpace = false; - $dom->formatOutput = true; - $dom->loadXML($xmltemplate->asXML()); - - return $dom->saveXML(); - } - } - - /** - * Apply template. - * - * @return void - */ - public function apply_template() { - $action = $this->formdata->action; - $parts = explode('_', $this->formdata->usertemplateinfo); - $this->utemplateid = $parts[1]; - - // Before continuing. - if ($action != SURVEYPRO_DELETEALLITEMS) { - // Dispose assignemnt of pages. - $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); - $utilitylayoutman->reset_pages(); - } - - $this->trigger_event('usertemplate_applied', $action); - - // Begin the process executing preliminary actions. - switch ($action) { - case SURVEYPRO_IGNOREITEMS: - break; - case SURVEYPRO_HIDEALLITEMS: - $whereparams = ['surveyproid' => $this->surveypro->id]; - $utilitylayoutman->items_set_visibility($whereparams, 0); - - $utilitylayoutman->reset_pages(); - - break; - case SURVEYPRO_DELETEALLITEMS: - $utilitylayoutman = new utility_layout($this->cm); - $whereparams = ['surveyproid' => $this->surveypro->id]; - $utilitylayoutman->delete_items($whereparams); - break; - case SURVEYPRO_DELETEVISIBLEITEMS: - $whereparams = ['surveyproid' => $this->surveypro->id]; - $whereparams['hidden'] = 0; - $utilitylayoutman->delete_items($whereparams); - - $utilitylayoutman->items_reindex(); - - break; - case SURVEYPRO_DELETEHIDDENITEMS: - $whereparams = ['surveyproid' => $this->surveypro->id]; - $whereparams['hidden'] = 1; - $utilitylayoutman->delete_items($whereparams); - - $utilitylayoutman->items_reindex(); - - break; - break; - default: - $message = 'Unexpected $action = '.$action; - debugging('Error at line '.__LINE__.' of '.__FILE__.'. '.$message , DEBUG_DEVELOPER); - } - - // Now actually add items from template. - $this->add_items_from_template(); - - $paramurl = ['s' => $this->surveypro->id, 'section' => 'itemslist']; - $redirecturl = new \moodle_url('/mod/surveypro/layout.php', $paramurl); - redirect($redirecturl); - } - - /** - * Display a friendly message to stop the page load under particular conditions. - * - * @return void - */ - public function friendly_stop() { - global $OUTPUT; - - $riskyediting = ($this->surveypro->riskyeditdeadline > time()); - $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); - $hassubmissions = $utilitylayoutman->has_submissions(); - - if ($hassubmissions && (!$riskyediting)) { - echo $OUTPUT->notification(get_string('applyusertemplatedenied01', 'mod_surveypro'), 'notifyproblem'); - $url = new \moodle_url('/mod/surveypro/view.php', ['s' => $this->surveypro->id, 'section' => 'submissionslist']); - echo $OUTPUT->continue_button($url); - echo $OUTPUT->footer(); - die(); - } - - if ($this->surveypro->template && (!$riskyediting)) { // This survey comes from a master template so it is multilang. - echo $OUTPUT->notification(get_string('applyusertemplatedenied02', 'mod_surveypro'), 'notifyproblem'); - $url = new \moodle_url('/mod/surveypro/view.php', ['s' => $this->surveypro->id, 'section' => 'submissionform']); - echo $OUTPUT->continue_button($url); - echo $OUTPUT->footer(); - die(); - } - } - - /** - * Actually add items from template. - * - * @return void - */ - public function add_items_from_template() { - global $CFG, $DB; - - $fs = get_file_storage(); - - $this->templatename = $this->get_utemplate_name(); - $templatecontent = $this->get_utemplate_content(); - - $simplexml = new \SimpleXMLElement($templatecontent); - // Debug: echo '

Items saved in the file ('.count($simplexml->item).')

';. - - if (!$sortindexoffset = $DB->get_field('surveypro_item', 'MAX(sortindex)', ['surveyproid' => $this->surveypro->id])) { - $sortindexoffset = 0; - } - - $naturalsortindex = 0; - foreach ($simplexml->children() as $xmlitem) { - - // Read the attributes of the item node: - // The xmlitem looks like: . - foreach ($xmlitem->attributes() as $attribute => $value) { - if ($attribute == 'type') { - $currenttype = (string)$value; - } - if ($attribute == 'plugin') { - $currentplugin = (string)$value; - } - } - - // Take care to details. - // Load the item class in order to call its methods to validate $record before saving it. - $item = surveypro_get_item($this->cm, $this->surveypro, 0, $currenttype, $currentplugin); - - foreach ($xmlitem->children() as $xmltable) { // Tables are: surveypro_item and surveypro(field|format)_<>. - $tablename = $xmltable->getName(); - if ($tablename == 'surveypro_item') { - $currenttablestructure = $this->get_table_structure(); - } else { - $currenttablestructure = $this->get_table_structure($currenttype, $currentplugin); - } - - $record = new \stdClass(); - - // Add to $record mandatory fields that will be overwritten, hopefully, with the content of the usertemplate. - $record->surveyproid = (int)$this->surveypro->id; - $record->type = $currenttype; - $record->plugin = $currentplugin; - if ($tablename == 'surveypro_item') { - $item->item_add_mandatory_base_fields($record); - } else { - $item->item_add_mandatory_plugin_fields($record); - } - - foreach ($xmltable->children() as $xmlfield) { - $fieldname = $xmlfield->getName(); - - // Tag always belong to surveypro_item table. - if ($fieldname == 'parent') { - // Debug: $label = 'Count of attributes of the field '.$fieldname;. - // Debug: echo '
'.$label.': '.count($xmlfield->children()).'
';. - foreach ($xmlfield->children() as $xmlparentattribute) { - $fieldname = $xmlparentattribute->getName(); - $fieldexists = in_array($fieldname, $currenttablestructure); - if ($fieldexists) { - $record->{$fieldname} = (string)$xmlparentattribute; - } - } - continue; - } - - // Tag always belong to surveypro(field|format)_<> table - // so: ($fieldname == 'embedded') only when surveypro_item has already been saved... - // so: $itemid is known. - if ($fieldname == 'embedded') { - // Debug: $label = 'Count of attributes of the field '.$fieldname;. - // Debug: echo '
'.$label.': '.count($xmlfield->children()).'
';. - foreach ($xmlfield->children() as $xmlfileattribute) { - $fileattributename = $xmlfileattribute->getName(); - if ($fileattributename == 'filename') { - $filename = $xmlfileattribute; - } - if ($fileattributename == 'filecontent') { - $filecontent = base64_decode($xmlfileattribute); - } - } - - // Debug: echo 'I need to add: "'.$filename.'" to the filearea
';. - - // Add the file described by $filename and $filecontent to filearea, - // alias, add pictures found in the utemplate to filearea. - $filerecord = new \stdClass(); - $filerecord->contextid = $this->context->id; - $filerecord->component = 'mod_surveypro'; - $filerecord->filearea = SURVEYPRO_ITEMCONTENTFILEAREA; - $filerecord->itemid = $itemid; - $filerecord->filepath = '/'; - $filerecord->filename = $filename; - $fileinfo = $fs->create_file_from_string($filerecord, $filecontent); - continue; - } - - // The method xml_validation checks only the formal schema validity. - // It does not know whether the xml is old and holds no longer needed fields - // or does not hold fields that are now mandatory. - // Because of this, I can not SIMPLY add $fieldname to $record but I need to make some more investigation. - // I neglect no longer used fields, here. - // I will add mandatory (but missing because the usertemplate may be old) fields, - // before saving in the frame of the $item->item_force_coherence. - $fieldexists = in_array($fieldname, $currenttablestructure); - if ($fieldexists) { - $record->{$fieldname} = (string)$xmlfield; - } - } - - unset($record->id); - - if ($tablename == 'surveypro_item') { - $naturalsortindex++; - $record->sortindex = $naturalsortindex + $sortindexoffset; - if (!empty($record->parentid)) { - $whereparams = ['surveyproid' => $this->surveypro->id]; - $whereparams['sortindex'] = $record->parentid + $sortindexoffset; - $record->parentid = $DB->get_field('surveypro_item', 'id', $whereparams, MUST_EXIST); - } - - $itemid = $DB->insert_record($tablename, $record); - } else { - // Take care to details. - $item->item_force_coherence($record); - $item->item_validate_variablename($record, $itemid); - $record->itemid = $itemid; - - $DB->insert_record($tablename, $record, false); - } - } - } - } - - /** - * Make the usertemplate available for the download. - * - * @return void - */ - public function export_utemplate() { - global $CFG; - - $fs = get_file_storage(); - $xmlfile = $fs->get_file_by_id($this->utemplateid); - $filename = $xmlfile->get_filename(); - $content = $xmlfile->get_content(); - - // Debug: echo '';. - - $templatename = clean_filename('temptemplate-' . gmdate("Ymd_Hi")); - $exportsubdir = "mod_surveypro/templateexport"; - make_temp_directory($exportsubdir); - $exportdir = "$CFG->tempdir/$exportsubdir"; - $exportfile = $exportdir.'/'.$templatename; - if (!preg_match('~\.xml$~', $exportfile)) { - $exportfile .= '.xml'; - } - $this->templatename = basename($exportfile); - - $this->trigger_event('usertemplate_exported'); - - header("Content-Type: application/download\n"); - header("Content-Disposition: attachment; filename=\"$filename\""); - header('Expires: 0'); - header('Cache-Control: must-revalidate,post-check=0,pre-check=0'); - header('Pragma: public'); - $xmlfile = fopen($exportdir.'/'.$this->templatename, 'w'); - print $content; - fclose($xmlfile); - unlink($exportdir.'/'.$this->templatename); - } - - /** - * Upload the usertemplate. - * - * @return void - */ - public function upload_utemplate() { - $templateoptions = $this->get_filemanager_options(); - $contextid = $this->formdata->sharinglevel; - $fs = get_file_storage(); - - // Look at what is already on board. - $oldfiles = []; - if ($files = $fs->get_area_files($contextid, 'mod_surveypro', SURVEYPRO_TEMPLATEFILEAREA, 0, 'sortorder', false)) { - foreach ($files as $file) { - $oldfiles[] = $file->get_filename(); - } - } - - // Add current files. - $fieldname = 'importfile'; - if ($draftitemid = $this->formdata->{$fieldname.'_filemanager'}) { - if (isset($templateoptions['return_types']) && !($templateoptions['return_types'] & FILE_REFERENCE)) { - // We assume that if $options['return_types'] is NOT specified, we DO allow references. - // This is not exactly right. BUT there are many places in code where filemanager options... - // ...are not passed to file_save_draft_area_files(). - $allowreferences = false; - } - - file_save_draft_area_files($draftitemid, $contextid, 'mod_surveypro', 'temporaryarea', 0, $templateoptions); - $files = $fs->get_area_files($contextid, 'mod_surveypro', 'temporaryarea'); - $filecount = 0; - foreach ($files as $file) { - if (in_array($file->get_filename(), $oldfiles)) { - continue; - } - - $filerecord = ['contextid' => $contextid]; - $filerecord['component'] = 'mod_surveypro'; - $filerecord['filearea'] = SURVEYPRO_TEMPLATEFILEAREA; - $filerecord['itemid'] = 0; - $filerecord['timemodified'] = time(); - if (!$templateoptions['subdirs']) { - if ($file->get_filepath() !== '/' || $file->is_directory()) { - continue; - } - } - if ($templateoptions['maxbytes'] && $templateoptions['maxbytes'] < $file->get_filesize()) { - // Oversized file - should not get here at all. - continue; - } - if ($templateoptions['maxfiles'] != -1 && $templateoptions['maxfiles'] <= $filecount) { - // More files - should not get here at all. - break; - } - if (!$file->is_directory()) { - $filecount++; - } - - if ($file->is_external_file()) { - if (!$allowreferences) { - continue; - } - $repoid = $file->get_repository_id(); - if (!empty($repoid)) { - $filerecord['repositoryid'] = $repoid; - $filerecord['reference'] = $file->get_reference(); - } - } - - $fs->create_file_from_storedfile($filerecord, $file); - } - } - - if ($files = $fs->get_area_files($contextid, 'mod_surveypro', SURVEYPRO_TEMPLATEFILEAREA, 0, 'sortorder', false)) { - if (count($files) == 1) { - // Only one file attached, set it as main file automatically. - $file = array_shift($files); - $filepath = $file->get_filepath(); - $filename = $file->get_filename(); - file_set_sortorder($contextid, 'mod_surveypro', SURVEYPRO_TEMPLATEFILEAREA, 0, $filepath, $filename, 1); - } - } - - $this->utemplateid = $file->get_id(); - } - - /** - * Generate the usertemplate. - * - * @return void - */ - public function generate_utemplate() { - global $USER; - - $this->templatename = $this->formdata->templatename; - $this->templatename = str_replace(' ', '_', $this->templatename); - if (!preg_match('~\.xml$~', $this->templatename)) { - $this->templatename .= '.xml'; - } - $xmlcontent = $this->write_template_content($this->formdata->visiblesonly); - // Debug: echo '';. - - $fs = get_file_storage(); - $filerecord = new \stdClass; - - $contextid = $this->formdata->sharinglevel; - $filerecord->contextid = $contextid; - - $filerecord->component = 'mod_surveypro'; - $filerecord->filearea = SURVEYPRO_TEMPLATEFILEAREA; - $filerecord->itemid = 0; - $filerecord->filepath = '/'; - $filerecord->userid = $USER->id; - - $filerecord->filename = str_replace(' ', '_', $this->templatename); - if (!preg_match('~\.xml$~', $filerecord->filename)) { - $filerecord->filename .= '.xml'; - } - $fs->create_file_from_string($filerecord, $xmlcontent); - - return true; - } - - /** - * Provide a label explaining the meaning of the contexid - * - * @param int $contextid The contextid I am interested in - * @return string - */ - public function contextlevel_to_scontextlabel($contextid) { - switch ($contextid) { - case CONTEXT_SYSTEM: - $sharinglabel = get_string('system', 'mod_surveypro'); - break; - case CONTEXT_COURSECAT: - $sharinglabel = get_string('currentcategory', 'mod_surveypro'); - break; - case CONTEXT_COURSE: - $sharinglabel = get_string('currentcourse', 'mod_surveypro'); - break; - case CONTEXT_MODULE: - $a = get_string('modulename', 'mod_surveypro'); - $sharinglabel = get_string('module', 'mod_surveypro', $a); - break; - case CONTEXT_USER: - $sharinglabel = get_string('user'); - break; - default: - $message = 'Unexpected $contextid = '.$contextid; - debugging('Error at line '.__LINE__.' of '.__FILE__.'. '.$message , DEBUG_DEVELOPER); - } - - return $sharinglabel; - } - - /** - * Display the usertemplates table. - * - * @return void - */ - public function display_usertemplates_table() { - global $CFG, $USER, $OUTPUT; - - require_once($CFG->libdir.'/tablelib.php'); - - $candownloadutemplates = has_capability('mod/surveypro:downloadusertemplates', $this->context); - $candeleteutemplates = has_capability('mod/surveypro:deleteusertemplates', $this->context); - - // Begin of: $paramurlbase definition. - $paramurlbase = ['s' => $this->cm->instance]; - // End of $paramurlbase definition. - - $deletetitle = get_string('delete'); - $iconparams = ['title' => $deletetitle]; - $deleteicn = new \pix_icon('t/delete', $deletetitle, 'moodle', $iconparams); - - $importtitle = get_string('exporttemplate', 'mod_surveypro'); - $iconparams = ['title' => $importtitle]; - $importicn = new \pix_icon('t/download', $importtitle, 'moodle', $iconparams); - - $table = new \flexible_table('templatelist'); - - $paramurl = ['s' => $this->cm->instance, 'section' => 'manage']; - $baseurl = new \moodle_url('/mod/surveypro/utemplates.php', $paramurl); - $table->define_baseurl($baseurl); - - $tablecolumns = []; - $tablecolumns[] = 'templatename'; - $tablecolumns[] = 'sharinglevel'; - $tablecolumns[] = 'timecreated'; - $tablecolumns[] = 'actions'; - $table->define_columns($tablecolumns); - - $tableheaders = []; - $tableheaders[] = get_string('templatename', 'mod_surveypro'); - $tableheaders[] = get_string('sharinglevel', 'mod_surveypro'); - $tableheaders[] = get_string('timecreated', 'mod_surveypro'); - $tableheaders[] = get_string('actions'); - $table->define_headers($tableheaders); - - $table->sortable(true, 'templatename'); // Sorted by templatename by default. - $table->no_sorting('actions'); - - $table->column_class('templatename', 'templatename'); - $table->column_class('sharinglevel', 'sharinglevel'); - $table->column_class('timecreated', 'timecreated'); - $table->column_class('actions', 'actions'); - - $table->set_attribute('id', 'managetemplates'); - $table->set_attribute('class', 'generaltable'); - $table->setup(); - - $utemplateman = new usertemplate($this->cm, $this->context, $this->surveypro); - $xmlfiles = $utemplateman->get_xmlfiles_list(); - - $utemplates = []; - foreach ($xmlfiles as $contextid => $xmlfile) { - foreach ($xmlfiles[$contextid] as $xmlfile) { - $utemplate = new \stdClass(); - $utemplate->filename = $xmlfile->get_filename(); - $utemplate->sharingcontext = $this->contextlevel_to_scontextlabel($contextid); - $utemplate->timecreated = $xmlfile->get_timecreated(); - $utemplate->fileid = $xmlfile->get_id(); - $utemplate->userid = $xmlfile->get_userid(); - $utemplates[] = $utemplate; - } - } - - $virtualtable = $this->get_virtual_table($utemplates, $table->get_sql_sort()); - - $row = 0; - foreach ($utemplates as $utemplate) { - - $xmlfileid = $virtualtable[$row]['xmlfileid']; - $templatename = $virtualtable[$row]['templatename']; - $tmpl = new usertemplate_name($xmlfileid, $templatename); - - $tablerow = []; - $tablerow[] = $OUTPUT->render_from_template('core/inplace_editable', $tmpl->export_for_template($OUTPUT)); - $tablerow[] = $virtualtable[$row]['sharinglevel']; - $tablerow[] = userdate($virtualtable[$row]['creationdate']); - - $paramurlbase['fid'] = $virtualtable[$row]['xmlfileid']; - $row++; - - $icons = ''; - // SURVEYPRO_DELETEUTEMPLATE. - if ($candeleteutemplates) { - if ($utemplate->userid == $USER->id) { // The user template can be deleted only by its owner. - $paramurl = $paramurlbase; - $paramurl['act'] = SURVEYPRO_DELETEUTEMPLATE; - $paramurl['section'] = 'manage'; - $paramurl['sesskey'] = sesskey(); - - $link = new \moodle_url('/mod/surveypro/utemplates.php', $paramurl); - $icons .= $OUTPUT->action_icon($link, $deleteicn, null, ['title' => $deletetitle]); - } - } - - // SURVEYPRO_EXPORTUTEMPLATE. - if ($candownloadutemplates) { - $paramurl = $paramurlbase; - $paramurl['act'] = SURVEYPRO_EXPORTUTEMPLATE; - $paramurl['section'] = 'manage'; - $paramurl['sesskey'] = sesskey(); - - $link = new \moodle_url('/mod/surveypro/utemplates.php', $paramurl); - $icons .= $OUTPUT->action_icon($link, $importicn, null, ['title' => $importtitle]); - } - - $tablerow[] = $icons; - - $table->add_data($tablerow); - } - $table->set_attribute('align', 'center'); - $table->summary = get_string('templatelist', 'mod_surveypro'); - $table->print_html(); - } - - /** - * Prevent direct user input. - * - * @return void - */ - public function prevent_direct_user_input() { - if ($this->action != SURVEYPRO_NOACTION) { - require_sesskey(); - } - if ($this->action == SURVEYPRO_DELETEUTEMPLATE) { - require_capability('mod/surveypro:deleteusertemplates', $this->context); - } - if ($this->action == SURVEYPRO_DELETEALLITEMS) { - require_capability('mod/surveypro:manageusertemplates', $this->context); - } - if ($this->action == SURVEYPRO_EXPORTUTEMPLATE) { - require_capability('mod/surveypro:downloadusertemplates', $this->context); - } - } - - /** - * Trigger the provided event. - * - * @param string $eventname Event to trigger - * @param int $action - * @return void - */ - public function trigger_event($eventname, $action=null) { - $eventdata = ['context' => $this->context, 'objectid' => $this->surveypro->id]; - switch ($eventname) { - case 'all_usertemplates_viewed': - $event = \mod_surveypro\event\all_usertemplates_viewed::create($eventdata); - break; - case 'usertemplate_applied': - if ($action == SURVEYPRO_IGNOREITEMS) { - $straction = get_string('ignoreitems', 'mod_surveypro'); - } - if ($action == SURVEYPRO_HIDEALLITEMS) { - $straction = get_string('hideitems', 'mod_surveypro'); - } - if ($action == SURVEYPRO_DELETEALLITEMS) { - $straction = get_string('deleteallitems', 'mod_surveypro'); - } - if ($action == SURVEYPRO_DELETEVISIBLEITEMS) { - $straction = get_string('deletevisibleitems', 'mod_surveypro'); - } - if ($action == SURVEYPRO_DELETEHIDDENITEMS) { - $straction = get_string('deletehiddenitems', 'mod_surveypro'); - } - $other = ['templatename' => $this->get_utemplate_name()]; - $other['action'] = $straction; - $eventdata['other'] = $other; - $event = \mod_surveypro\event\usertemplate_applied::create($eventdata); - break; - case 'usertemplate_exported': - $eventdata['other'] = ['templatename' => $this->get_utemplate_name()]; - $event = \mod_surveypro\event\usertemplate_exported::create($eventdata); - break; - case 'usertemplate_imported': - $eventdata['other'] = ['templatename' => $this->get_utemplate_name()]; - $event = \mod_surveypro\event\usertemplate_imported::create($eventdata); - break; - case 'usertemplate_saved': - $eventdata['other'] = ['templatename' => $this->templatename]; - $event = \mod_surveypro\event\usertemplate_saved::create($eventdata); - break; - case 'usertemplate_deleted': - $eventdata['other'] = ['templatename' => $this->templatename]; - $event = \mod_surveypro\event\usertemplate_deleted::create($eventdata); - break; - default: - $message = 'Unexpected $event = '.$eventname; - debugging('Error at line '.__LINE__.' of '.__FILE__.'. '.$message , DEBUG_DEVELOPER); - } - $event->trigger(); - } -} diff --git a/classes/utemplate_apply.php b/classes/utemplate_apply.php new file mode 100644 index 00000000000..7f4f186d819 --- /dev/null +++ b/classes/utemplate_apply.php @@ -0,0 +1,405 @@ +. + +/** + * Surveypro utemplate_apply class. + * + * @package mod_surveypro + * @copyright 2013 onwards kordan + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_surveypro; + +use core_text; +use mod_surveypro\utility_layout; + +use mod_surveypro\local\ipe\usertemplate_name; + +/** + * The class representing a user template + * + * @package mod_surveypro + * @copyright 2013 onwards kordan + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class utemplate_apply extends utemplate_base { + + /** + * @var int User confirmation to actions + */ + protected $confirm; + + /** + * Setup. + * + * @param int $utemplateid + * @param int $action + * @param int $confirm + * @return void + */ + public function setup($utemplateid, $action, $confirm) { + $this->set_utemplateid($utemplateid); + $this->set_action($action); + $this->set_confirm($confirm); + } + + // MARK set. + + /** + * Set utemplateid. + * + * @param int $utemplateid + * @return void + */ + private function set_utemplateid($utemplateid) { + $this->utemplateid = $utemplateid; + } + + /** + * Set action. + * + * @param int $action + * @return void + */ + private function set_action($action) { + $this->action = $action; + } + + /** + * Set confirm. + * + * @param int $confirm + * @return void + */ + private function set_confirm($confirm) { + $this->confirm = $confirm; + } + + // MARK get. + + /** + * Get user template content. + * + * @param int $utemplateid + * @return void + */ + public function get_utemplate_content($utemplateid=0) { + $fs = get_file_storage(); + if (empty($utemplateid)) { + $utemplateid = $this->utemplateid; + } + $xmlfile = $fs->get_file_by_id($utemplateid); + + return $xmlfile->get_content(); + } + + /** + * Get the content of the user template drop down menu. + * + * @return array + */ + public function get_utemplates_items() { + $xmlfiles = $this->get_xmlfiles_list(); + + $items = []; + foreach ($xmlfiles as $contextid => $unused) { + $contextlabel = $this->get_label_forcontextid($contextid); + foreach ($xmlfiles[$contextid] as $xmlfile) { + $xmlid = $xmlfile->get_id(); + $filename = $xmlfile->get_filename(); + $items[$contextid.'_'.$xmlid] = '('.$contextlabel.') '.$filename; + } + } + asort($items); + + return $items; + } + + // MARK other. + + /** + * Actually add items from template. + * + * @return void + */ + public function add_items_from_template() { + global $CFG, $DB; + + $fs = get_file_storage(); + + $this->templatename = $this->get_utemplate_name(); + $templatecontent = $this->get_utemplate_content(); + + $simplexml = new \SimpleXMLElement($templatecontent); + // Debug: echo '

Items saved in the file ('.count($simplexml->item).')

';. + + if (!$sortindexoffset = $DB->get_field('surveypro_item', 'MAX(sortindex)', ['surveyproid' => $this->surveypro->id])) { + $sortindexoffset = 0; + } + + $naturalsortindex = 0; + foreach ($simplexml->children() as $xmlitem) { + + // Read the attributes of the item node: + // The xmlitem looks like: . + foreach ($xmlitem->attributes() as $attribute => $value) { + if ($attribute == 'type') { + $currenttype = (string)$value; + } + if ($attribute == 'plugin') { + $currentplugin = (string)$value; + } + } + + // Take care to details. + // Load the item class in order to call its methods to validate $record before saving it. + $item = surveypro_get_item($this->cm, $this->surveypro, 0, $currenttype, $currentplugin); + + foreach ($xmlitem->children() as $xmltable) { // Tables are: surveypro_item and surveypro(field|format)_<>. + $tablename = $xmltable->getName(); + if ($tablename == 'surveypro_item') { + $currenttablestructure = $this->get_table_structure(); + } else { + $currenttablestructure = $this->get_table_structure($currenttype, $currentplugin); + } + + $record = new \stdClass(); + + // Add to $record mandatory fields that will be overwritten, hopefully, with the content of the usertemplate. + $record->surveyproid = (int)$this->surveypro->id; + $record->type = $currenttype; + $record->plugin = $currentplugin; + if ($tablename == 'surveypro_item') { + $item->item_add_mandatory_base_fields($record); + } else { + $item->item_add_mandatory_plugin_fields($record); + } + + foreach ($xmltable->children() as $xmlfield) { + $fieldname = $xmlfield->getName(); + + // Tag always belong to surveypro_item table. + if ($fieldname == 'parent') { + // Debug: $label = 'Count of attributes of the field '.$fieldname;. + // Debug: echo '
'.$label.': '.count($xmlfield->children()).'
';. + foreach ($xmlfield->children() as $xmlparentattribute) { + $fieldname = $xmlparentattribute->getName(); + $fieldexists = in_array($fieldname, $currenttablestructure); + if ($fieldexists) { + $record->{$fieldname} = (string)$xmlparentattribute; + } + } + continue; + } + + // Tag always belong to surveypro(field|format)_<> table + // so: ($fieldname == 'embedded') only when surveypro_item has already been saved... + // so: $itemid is known. + if ($fieldname == 'embedded') { + // Debug: $label = 'Count of attributes of the field '.$fieldname;. + // Debug: echo '
'.$label.': '.count($xmlfield->children()).'
';. + foreach ($xmlfield->children() as $xmlfileattribute) { + $fileattributename = $xmlfileattribute->getName(); + if ($fileattributename == 'filename') { + $filename = $xmlfileattribute; + } + if ($fileattributename == 'filecontent') { + $filecontent = base64_decode($xmlfileattribute); + } + } + + // Debug: echo 'I need to add: "'.$filename.'" to the filearea
';. + + // Add the file described by $filename and $filecontent to filearea, + // alias, add pictures found in the utemplate to filearea. + $filerecord = new \stdClass(); + $filerecord->contextid = $this->context->id; + $filerecord->component = 'mod_surveypro'; + $filerecord->filearea = SURVEYPRO_ITEMCONTENTFILEAREA; + $filerecord->itemid = $itemid; + $filerecord->filepath = '/'; + $filerecord->filename = $filename; + $fileinfo = $fs->create_file_from_string($filerecord, $filecontent); + continue; + } + + // The method xml_validation checks only the formal schema validity. + // It does not know whether the xml is old and holds no longer needed fields + // or does not hold fields that are now mandatory. + // Because of this, I can not SIMPLY add $fieldname to $record but I need to make some more investigation. + // I neglect no longer used fields, here. + // I will add mandatory (but missing because the usertemplate may be old) fields, + // before saving in the frame of the $item->item_force_coherence. + $fieldexists = in_array($fieldname, $currenttablestructure); + if ($fieldexists) { + $record->{$fieldname} = (string)$xmlfield; + } + } + + unset($record->id); + + if ($tablename == 'surveypro_item') { + $naturalsortindex++; + $record->sortindex = $naturalsortindex + $sortindexoffset; + if (!empty($record->parentid)) { + $whereparams = ['surveyproid' => $this->surveypro->id]; + $whereparams['sortindex'] = $record->parentid + $sortindexoffset; + $record->parentid = $DB->get_field('surveypro_item', 'id', $whereparams, MUST_EXIST); + } + + $itemid = $DB->insert_record($tablename, $record); + } else { + // Take care to details. + $item->item_force_coherence($record); + $item->item_validate_variablename($record, $itemid); + $record->itemid = $itemid; + + $DB->insert_record($tablename, $record, false); + } + } + } + } + + /** + * Apply template. + * + * @return void + */ + public function apply_template() { + $applyction = $this->formdata->action; + $parts = explode('_', $this->formdata->usertemplateinfo); + $this->utemplateid = $parts[1]; + + // Before continuing. + if ($applyction != SURVEYPRO_DELETEALLITEMS) { + // Dispose assignemnt of pages. + $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); + $utilitylayoutman->reset_pages(); + } + + $this->trigger_event('usertemplate_applied', $applyction); + + // Begin the process executing preliminary actions. + switch ($applyction) { + case SURVEYPRO_IGNOREITEMS: + break; + case SURVEYPRO_HIDEALLITEMS: + $whereparams = ['surveyproid' => $this->surveypro->id]; + $utilitylayoutman->items_set_visibility($whereparams, 0); + + $utilitylayoutman->reset_pages(); + + break; + case SURVEYPRO_DELETEALLITEMS: + $utilitylayoutman = new utility_layout($this->cm); + $whereparams = ['surveyproid' => $this->surveypro->id]; + $utilitylayoutman->delete_items($whereparams); + break; + case SURVEYPRO_DELETEVISIBLEITEMS: + $whereparams = ['surveyproid' => $this->surveypro->id]; + $whereparams['hidden'] = 0; + $utilitylayoutman->delete_items($whereparams); + + $utilitylayoutman->items_reindex(); + + break; + case SURVEYPRO_DELETEHIDDENITEMS: + $whereparams = ['surveyproid' => $this->surveypro->id]; + $whereparams['hidden'] = 1; + $utilitylayoutman->delete_items($whereparams); + + $utilitylayoutman->items_reindex(); + + break; + break; + default: + $message = 'Unexpected $applyction = '.$applyction; + debugging('Error at line '.__LINE__.' of '.__FILE__.'. '.$message , DEBUG_DEVELOPER); + } + + // Now actually add items from template. + $this->add_items_from_template(); + + $paramurl = ['s' => $this->surveypro->id, 'section' => 'itemslist']; + $redirecturl = new \moodle_url('/mod/surveypro/layout.php', $paramurl); + redirect($redirecturl); + } + + /** + * Display a friendly message to stop the page load under particular conditions. + * + * @return void + */ + public function friendly_stop() { + global $OUTPUT; + + $riskyediting = ($this->surveypro->riskyeditdeadline > time()); + $utilitylayoutman = new utility_layout($this->cm, $this->surveypro); + $hassubmissions = $utilitylayoutman->has_submissions(); + + if ($hassubmissions && (!$riskyediting)) { + echo $OUTPUT->notification(get_string('applyusertemplatedenied01', 'mod_surveypro'), 'notifyproblem'); + $url = new \moodle_url('/mod/surveypro/view.php', ['s' => $this->surveypro->id, 'section' => 'submissionslist']); + echo $OUTPUT->continue_button($url); + echo $OUTPUT->footer(); + die(); + } + + if ($this->surveypro->template && (!$riskyediting)) { // This survey comes from a master template so it is multilang. + echo $OUTPUT->notification(get_string('applyusertemplatedenied02', 'mod_surveypro'), 'notifyproblem'); + $url = new \moodle_url('/mod/surveypro/view.php', ['s' => $this->surveypro->id, 'section' => 'submissionform']); + echo $OUTPUT->continue_button($url); + echo $OUTPUT->footer(); + die(); + } + } + + /** + * Prevent direct user input. + * + * @return void + */ + public function prevent_direct_user_input() { + if ($this->action != SURVEYPRO_NOACTION) { + require_sesskey(); + } + if ($this->action == SURVEYPRO_DELETEUTEMPLATE) { + require_capability('mod/surveypro:deleteusertemplates', $this->context); + } + if ($this->action == SURVEYPRO_DELETEALLITEMS) { + require_capability('mod/surveypro:manageusertemplates', $this->context); + } + if ($this->action == SURVEYPRO_EXPORTUTEMPLATE) { + require_capability('mod/surveypro:downloadusertemplates', $this->context); + } + } + + /** + * Display the welcome message of the apply page. + * + * @return void + */ + public function welcome_apply_message() { + global $OUTPUT; + + $a = new \stdClass(); + $a->uploadpage = get_string('utemplate_import', 'mod_surveypro'); + $a->savepage = get_string('utemplate_save', 'mod_surveypro'); + $message = get_string('welcome_utemplateapply', 'mod_surveypro', $a); + echo $OUTPUT->notification($message, 'notifymessage'); + } +} diff --git a/classes/utemplate_base.php b/classes/utemplate_base.php new file mode 100644 index 00000000000..90644aef513 --- /dev/null +++ b/classes/utemplate_base.php @@ -0,0 +1,239 @@ +. + +/** + * Surveypro utemplate_base class. + * + * @package mod_surveypro + * @copyright 2013 onwards kordan + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_surveypro; + +/** + * The base class for templates + * + * @package mod_surveypro + * @copyright 2013 onwards kordan + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class utemplate_base extends templatebase { + + /** + * @var int ID of the current user template + */ + protected $utemplateid; + + // MARK get. + + /** + * Provide a label explaining the meaning of the contexid + * + * @param int $contextid The contextid I am interested in + * @return string + */ + public function get_label_forcontextid($contextid) { + switch ($contextid) { + case CONTEXT_SYSTEM: + $sharinglabel = get_string('system', 'mod_surveypro'); + break; + case CONTEXT_COURSECAT: + $sharinglabel = get_string('currentcategory', 'mod_surveypro'); + break; + case CONTEXT_COURSE: + $sharinglabel = get_string('currentcourse', 'mod_surveypro'); + break; + case CONTEXT_MODULE: + $a = get_string('modulename', 'mod_surveypro'); + $sharinglabel = get_string('module', 'mod_surveypro', $a); + break; + case CONTEXT_USER: + $sharinglabel = get_string('user'); + break; + default: + $message = 'Unexpected $contextid = '.$contextid; + debugging('Error at line '.__LINE__.' of '.__FILE__.'. '.$message , DEBUG_DEVELOPER); + } + + return $sharinglabel; + } + + /** + * Get sharing level contexts. + * + * @return $options + */ + public function get_sharingcontexts() { + global $USER; + + $parentcontexts = $this->context->get_parent_contexts(); + + $usercontext = \context_module::instance($this->cm->id); + $usercontextid = $usercontext->id; + $parentcontexts[$usercontextid] = $usercontext; + + $usercontext = \context_user::instance($USER->id); + $usercontextid = $usercontext->id; + $parentcontexts[$usercontextid] = $usercontext; + + return $parentcontexts; + } + + /** + * Get user template name. + * + * @return void + */ + public function get_utemplate_name() { + $fs = get_file_storage(); + $xmlfile = $fs->get_file_by_id($this->utemplateid); + + return $xmlfile->get_filename(); + } + + /** + * Gets an array of all of the templates that users have saved to the site. + * + * Few explanation to better understand. + * Asking for sharingcontexts I get the list of parentcontexts AND the usercontext. + * Each single context has a "context level" (50 for courses, 40 for categories, 10 for system, 30 for user). + * There are A LOT of contexts having "context level" == 50. One context per each course. + * The context of the course where I am in has: + * contextlevel = 50 (of course) AND id = another number, for instance, 79. + * 79 is the ID of the context of the course I am in, but 79 is NOT the ID of the course I am in. + + * When I ask for usertemplates saved at course level, I want to get all the usertemplates of MY COURSE + * and not all the usetemplates of EACH COURSE in this instance of moodle. + * This is why I ask for $this->get_utemplates_per_contextlevel($context->id); + * and NOT for $this->get_utemplates_per_contextlevel($context->contextlevel). + + * @param int $contextid Context that we are looking for + * @return array $templates + */ + public function get_utemplates_per_contextlevel($contextid) { + global $USER; + + $fs = get_file_storage(); + $files = $fs->get_area_files($contextid, 'mod_surveypro', SURVEYPRO_TEMPLATEFILEAREA, 0, 'sortorder', false); + if (empty($files)) { + return []; + } + + $templates = []; + foreach ($files as $file) { + if ($file->get_component() == 'user') { + $fileallowed = has_capability('mod/surveypro:applyusertemplates', $this->context); + $fileallowed = $fileallowed || ($file->userid == $USER->id); + if ($fileallowed) { + break; + } + } else { + $fileallowed = true; + } + if ($fileallowed) { + $templates[] = $file; + } + } + + return $templates; + } + + /** + * Get the list of each user template file. + * + * @param int $acontextid Context that we are looking for + * @return array + */ + public function get_xmlfiles_list($acontextid=null) { + $utemplates = []; + + $contexts = $this->get_sharingcontexts(); + // I am allowed to "see" usertemplates if they belong to one of my parent contextid + // or if their uid is $USER->id. + foreach ($contexts as $context) { + $contextid = $context->id; + if (is_null($acontextid) || ($contextid == $acontextid)) { + $xmlfiles = $this->get_utemplates_per_contextlevel($contextid); + if (count($xmlfiles)) { + foreach ($xmlfiles as $xmlfile) { + $utemplates[$context->contextlevel][] = $xmlfile; + } + } + } + } + asort($utemplates); + + return $utemplates; + } + + /** + * Trigger the provided event. + * + * @param string $eventname Event to trigger + * @param int $action + * @return void + */ + public function trigger_event($eventname, $action=null) { + $eventdata = ['context' => $this->context, 'objectid' => $this->surveypro->id]; + switch ($eventname) { + case 'all_usertemplates_viewed': + $event = \mod_surveypro\event\all_usertemplates_viewed::create($eventdata); + break; + case 'usertemplate_applied': + if ($action == SURVEYPRO_IGNOREITEMS) { + $straction = get_string('ignoreitems', 'mod_surveypro'); + } + if ($action == SURVEYPRO_HIDEALLITEMS) { + $straction = get_string('hideitems', 'mod_surveypro'); + } + if ($action == SURVEYPRO_DELETEALLITEMS) { + $straction = get_string('deleteallitems', 'mod_surveypro'); + } + if ($action == SURVEYPRO_DELETEVISIBLEITEMS) { + $straction = get_string('deletevisibleitems', 'mod_surveypro'); + } + if ($action == SURVEYPRO_DELETEHIDDENITEMS) { + $straction = get_string('deletehiddenitems', 'mod_surveypro'); + } + $other = ['templatename' => $this->get_utemplate_name()]; + $other['action'] = $straction; + $eventdata['other'] = $other; + $event = \mod_surveypro\event\usertemplate_applied::create($eventdata); + break; + case 'usertemplate_exported': + $eventdata['other'] = ['templatename' => $this->get_utemplate_name()]; + $event = \mod_surveypro\event\usertemplate_exported::create($eventdata); + break; + case 'usertemplate_imported': + $eventdata['other'] = ['templatename' => $this->get_utemplate_name()]; + $event = \mod_surveypro\event\usertemplate_imported::create($eventdata); + break; + case 'usertemplate_saved': + $eventdata['other'] = ['templatename' => $this->templatename]; + $event = \mod_surveypro\event\usertemplate_saved::create($eventdata); + break; + case 'usertemplate_deleted': + $eventdata['other'] = ['templatename' => $this->templatename]; + $event = \mod_surveypro\event\usertemplate_deleted::create($eventdata); + break; + default: + $message = 'Unexpected $event = '.$eventname; + debugging('Error at line '.__LINE__.' of '.__FILE__.'. '.$message , DEBUG_DEVELOPER); + } + $event->trigger(); + } +} diff --git a/classes/utemplate_import.php b/classes/utemplate_import.php new file mode 100644 index 00000000000..b1dbd2c0872 --- /dev/null +++ b/classes/utemplate_import.php @@ -0,0 +1,196 @@ +. + +/** + * Surveypro utemplate_import class. + * + * @package mod_surveypro + * @copyright 2013 onwards kordan + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_surveypro; + +use core_text; +use mod_surveypro\utility_layout; + +use mod_surveypro\local\ipe\usertemplate_name; + +/** + * The class representing a user template + * + * @package mod_surveypro + * @copyright 2013 onwards kordan + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class utemplate_import extends utemplate_base { + + /** + * Setup. + * + * @param int $utemplateid + * @return void + */ + public function setup($utemplateid) { + $this->set_utemplateid($utemplateid); + } + + // MARK set. + + /** + * Set utemplateid. + * + * @param int $utemplateid + * @return void + */ + private function set_utemplateid($utemplateid) { + $this->utemplateid = $utemplateid; + } + + // MARK get. + + /** + * Get filemanager options. + * + * @return $filemanageroptions + */ + public function get_filemanager_options() { + $templateoptions = ['accepted_types' => '.xml']; + $templateoptions['maxbytes'] = 0; + $templateoptions['maxfiles'] = -1; + $templateoptions['mainfile'] = true; + $templateoptions['subdirs'] = false; + + return $templateoptions; + } + + /** + * Get user template content. + * + * @param int $utemplateid + * @return void + */ + public function get_utemplate_content($utemplateid=0) { + $fs = get_file_storage(); + if (empty($utemplateid)) { + $utemplateid = $this->utemplateid; + } + $xmlfile = $fs->get_file_by_id($utemplateid); + + return $xmlfile->get_content(); + } + + // MARK other. + + /** + * Upload the usertemplate. + * + * @return void + */ + public function upload_utemplate() { + $templateoptions = $this->get_filemanager_options(); + $contextid = $this->formdata->sharinglevel; + $fs = get_file_storage(); + + // Look at what is already on board. + $oldfiles = []; + if ($files = $fs->get_area_files($contextid, 'mod_surveypro', SURVEYPRO_TEMPLATEFILEAREA, 0, 'sortorder', false)) { + foreach ($files as $file) { + $oldfiles[] = $file->get_filename(); + } + } + + // Add current files. + $fieldname = 'importfile'; + if ($draftitemid = $this->formdata->{$fieldname.'_filemanager'}) { + if (isset($templateoptions['return_types']) && !($templateoptions['return_types'] & FILE_REFERENCE)) { + // We assume that if $options['return_types'] is NOT specified, we DO allow references. + // This is not exactly right. BUT there are many places in code where filemanager options... + // ...are not passed to file_save_draft_area_files(). + $allowreferences = false; + } + + file_save_draft_area_files($draftitemid, $contextid, 'mod_surveypro', 'temporaryarea', 0, $templateoptions); + $files = $fs->get_area_files($contextid, 'mod_surveypro', 'temporaryarea'); + $filecount = 0; + foreach ($files as $file) { + if (in_array($file->get_filename(), $oldfiles)) { + continue; + } + + $filerecord = ['contextid' => $contextid]; + $filerecord['component'] = 'mod_surveypro'; + $filerecord['filearea'] = SURVEYPRO_TEMPLATEFILEAREA; + $filerecord['itemid'] = 0; + $filerecord['timemodified'] = time(); + if (!$templateoptions['subdirs']) { + if ($file->get_filepath() !== '/' || $file->is_directory()) { + continue; + } + } + if ($templateoptions['maxbytes'] && $templateoptions['maxbytes'] < $file->get_filesize()) { + // Oversized file - should not get here at all. + continue; + } + if ($templateoptions['maxfiles'] != -1 && $templateoptions['maxfiles'] <= $filecount) { + // More files - should not get here at all. + break; + } + if (!$file->is_directory()) { + $filecount++; + } + + if ($file->is_external_file()) { + if (!$allowreferences) { + continue; + } + $repoid = $file->get_repository_id(); + if (!empty($repoid)) { + $filerecord['repositoryid'] = $repoid; + $filerecord['reference'] = $file->get_reference(); + } + } + + $fs->create_file_from_storedfile($filerecord, $file); + } + } + + if ($files = $fs->get_area_files($contextid, 'mod_surveypro', SURVEYPRO_TEMPLATEFILEAREA, 0, 'sortorder', false)) { + if (count($files) == 1) { + // Only one file attached, set it as main file automatically. + $file = array_shift($files); + $filepath = $file->get_filepath(); + $filename = $file->get_filename(); + file_set_sortorder($contextid, 'mod_surveypro', SURVEYPRO_TEMPLATEFILEAREA, 0, $filepath, $filename, 1); + } + } + + $this->utemplateid = $file->get_id(); + } + + /** + * Display the welcome message of the import page. + * + * @return void + */ + public function welcome_import_message() { + global $OUTPUT; + + $a = get_string('utemplate_save', 'mod_surveypro'); + $message = get_string('welcome_utemplateimport', 'mod_surveypro', $a); + echo $OUTPUT->notification($message, 'notifymessage'); + } +} diff --git a/classes/utemplate_manage.php b/classes/utemplate_manage.php new file mode 100644 index 00000000000..15c03f86b05 --- /dev/null +++ b/classes/utemplate_manage.php @@ -0,0 +1,390 @@ +. + +/** + * Surveypro utemplate_manage class. + * + * @package mod_surveypro + * @copyright 2013 onwards kordan + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_surveypro; + +use core_text; +use mod_surveypro\utility_layout; + +use mod_surveypro\local\ipe\usertemplate_name; + +/** + * The class representing a user template + * + * @package mod_surveypro + * @copyright 2013 onwards kordan + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class utemplate_manage extends utemplate_base { + + /** + * @var int What the user is trying to do. + */ + protected $action; + + /** + * @var int User confirmation to actions. + */ + protected $confirm; + + /** + * Setup. + * + * @param int $utemplateid + * @param int $action + * @param int $confirm + * @return void + */ + public function setup($utemplateid, $action, $confirm) { + $this->set_utemplateid($utemplateid); + $this->set_action($action); + $this->set_confirm($confirm); + } + + // MARK set. + + /** + * Set utemplateid. + * + * @param int $utemplateid + * @return void + */ + private function set_utemplateid($utemplateid) { + $this->utemplateid = $utemplateid; + } + + /** + * Set action. + * + * @param int $action + * @return void + */ + private function set_action($action) { + $this->action = $action; + } + + /** + * Set confirm. + * + * @param int $confirm + * @return void + */ + private function set_confirm($confirm) { + $this->confirm = $confirm; + } + + // MARK get. + + /** + * Create the tool to sort usertemplates in the table. + * + * @param array $templates + * @param string $usersort + * @return void + */ + private function get_virtual_table($templates, $usersort) { + // Original table per columns: originaltablepercols. + $templatenamecol = []; + $sharinglevelcol = []; + $creationdatecol = []; + $xmlfileidcol = []; + foreach ($templates as $template) { + $templatenamecol[] = $template->filename; + $sharinglevelcol[] = $template->sharingcontext; + $creationdatecol[] = $template->timecreated; + $xmlfileidcol[] = $template->fileid; + } + $originaltablepercols = [$templatenamecol, $sharinglevelcol, $creationdatecol, $xmlfileidcol]; + + // Original table per rows: originaltableperrows. + $originaltableperrows = []; + foreach ($templatenamecol as $k => $unused) { + $tablerow = []; + $tablerow['templatename'] = $templatenamecol[$k]; + $tablerow['sharinglevel'] = $sharinglevelcol[$k]; + $tablerow['creationdate'] = $creationdatecol[$k]; + $tablerow['xmlfileid'] = $xmlfileidcol[$k]; + + $originaltableperrows[] = $tablerow; + } + + // Add orderpart. + $orderparts = explode(', ', $usersort); + $orderparts = str_replace('templatename', '0', $orderparts); + $orderparts = str_replace('sharinglevel', '1', $orderparts); + $orderparts = str_replace('timecreated', '2', $orderparts); + + // Include $fieldindex and $sortflag. + $fieldindex = [0, 0, 0]; + $sortflag = [SORT_ASC, SORT_ASC, SORT_ASC]; + foreach ($orderparts as $k => $orderpart) { + $pair = explode(' ', $orderpart); + $fieldindex[$k] = (int)$pair[0]; + $sortflag[$k] = ($pair[1] == 'ASC') ? SORT_ASC : SORT_DESC; + } + + array_multisort($originaltablepercols[$fieldindex[0]], $sortflag[0], + $originaltablepercols[$fieldindex[1]], $sortflag[1], + $originaltablepercols[$fieldindex[2]], $sortflag[2], $originaltableperrows); + + return $originaltableperrows; + } + + // MARK other. + + /** + * Delete usertemplate. + * + * @return void + */ + public function delete_utemplate() { + global $OUTPUT; + + if ($this->confirm == SURVEYPRO_UNCONFIRMED) { + // Ask for confirmation. + $a = $this->get_utemplate_name(); + $message = get_string('confirm_delete1utemplate', 'mod_surveypro', $a); + $optionsbase = ['s' => $this->surveypro->id, 'act' => SURVEYPRO_DELETEUTEMPLATE]; + + $optionsyes = $optionsbase; + $optionsyes['cnf'] = SURVEYPRO_CONFIRMED_YES; + $optionsyes['fid'] = $this->utemplateid; + $optionsyes['section'] = 'manage'; + $urlyes = new \moodle_url('/mod/surveypro/utemplates.php', $optionsyes); + $buttonyes = new \single_button($urlyes, get_string('yes')); + + $optionsno = $optionsbase; + $optionsno['cnf'] = SURVEYPRO_CONFIRMED_NO; + $optionsno['section'] = 'manage'; + $urlno = new \moodle_url('/mod/surveypro/utemplates.php', $optionsno); + $buttonno = new \single_button($urlno, get_string('no')); + + echo $OUTPUT->confirm($message, $buttonyes, $buttonno); + echo $OUTPUT->footer(); + die(); + } + + if ($this->confirm == SURVEYPRO_CONFIRMED_YES) { + // Put the name in the gobal vaiable, to remember it for the log. + $this->templatename = $this->get_utemplate_name(); + + $fs = get_file_storage(); + $xmlfile = $fs->get_file_by_id($this->utemplateid); + $a = $xmlfile->get_filename(); + $xmlfile->delete(); + + $this->trigger_event('usertemplate_deleted'); + + // Feedback. + $message = get_string('feedback_delete1utemplate', 'mod_surveypro', $a); + echo $OUTPUT->notification($message, 'notifymessage'); + } + + if ($this->confirm == SURVEYPRO_CONFIRMED_NO) { + $message = get_string('usercanceled', 'mod_surveypro'); + echo $OUTPUT->notification($message, 'notifymessage'); + } + } + + /** + * Display the usertemplates table. + * + * @return void + */ + public function display_usertemplates_table() { + global $CFG, $USER, $OUTPUT; + + require_once($CFG->libdir.'/tablelib.php'); + + $candownloadutemplates = has_capability('mod/surveypro:downloadusertemplates', $this->context); + $candeleteutemplates = has_capability('mod/surveypro:deleteusertemplates', $this->context); + + // Begin of: $paramurlbase definition. + $paramurlbase = ['s' => $this->cm->instance]; + // End of $paramurlbase definition. + + $deletetitle = get_string('delete'); + $iconparams = ['title' => $deletetitle]; + $deleteicn = new \pix_icon('t/delete', $deletetitle, 'moodle', $iconparams); + + $importtitle = get_string('exporttemplate', 'mod_surveypro'); + $iconparams = ['title' => $importtitle]; + $importicn = new \pix_icon('t/download', $importtitle, 'moodle', $iconparams); + + $table = new \flexible_table('templatelist'); + + $paramurl = ['s' => $this->cm->instance, 'section' => 'manage']; + $baseurl = new \moodle_url('/mod/surveypro/utemplates.php', $paramurl); + $table->define_baseurl($baseurl); + + $tablecolumns = []; + $tablecolumns[] = 'templatename'; + $tablecolumns[] = 'sharinglevel'; + $tablecolumns[] = 'timecreated'; + $tablecolumns[] = 'actions'; + $table->define_columns($tablecolumns); + + $tableheaders = []; + $tableheaders[] = get_string('templatename', 'mod_surveypro'); + $tableheaders[] = get_string('sharinglevel', 'mod_surveypro'); + $tableheaders[] = get_string('timecreated', 'mod_surveypro'); + $tableheaders[] = get_string('actions'); + $table->define_headers($tableheaders); + + $table->sortable(true, 'templatename'); // Sorted by templatename by default. + $table->no_sorting('actions'); + + $table->column_class('templatename', 'templatename'); + $table->column_class('sharinglevel', 'sharinglevel'); + $table->column_class('timecreated', 'timecreated'); + $table->column_class('actions', 'actions'); + + $table->set_attribute('id', 'managetemplates'); + $table->set_attribute('class', 'generaltable'); + $table->setup(); + + $xmlfiles = $this->get_xmlfiles_list(); + + $utemplates = []; + foreach ($xmlfiles as $contextid => $xmlfile) { + foreach ($xmlfiles[$contextid] as $xmlfile) { + $utemplate = new \stdClass(); + $utemplate->filename = $xmlfile->get_filename(); + $utemplate->sharingcontext = $this->get_label_forcontextid($contextid); + $utemplate->timecreated = $xmlfile->get_timecreated(); + $utemplate->fileid = $xmlfile->get_id(); + $utemplate->userid = $xmlfile->get_userid(); + $utemplates[] = $utemplate; + } + } + + $virtualtable = $this->get_virtual_table($utemplates, $table->get_sql_sort()); + + $row = 0; + foreach ($utemplates as $utemplate) { + + $xmlfileid = $virtualtable[$row]['xmlfileid']; + $templatename = $virtualtable[$row]['templatename']; + $tmpl = new usertemplate_name($xmlfileid, $templatename); + + $tablerow = []; + $tablerow[] = $OUTPUT->render_from_template('core/inplace_editable', $tmpl->export_for_template($OUTPUT)); + $tablerow[] = $virtualtable[$row]['sharinglevel']; + $tablerow[] = userdate($virtualtable[$row]['creationdate']); + + $paramurlbase['fid'] = $virtualtable[$row]['xmlfileid']; + $row++; + + $icons = ''; + // SURVEYPRO_DELETEUTEMPLATE. + if ($candeleteutemplates) { + if ($utemplate->userid == $USER->id) { // The user template can be deleted only by its owner. + $paramurl = $paramurlbase; + $paramurl['act'] = SURVEYPRO_DELETEUTEMPLATE; + $paramurl['section'] = 'manage'; + $paramurl['sesskey'] = sesskey(); + + $link = new \moodle_url('/mod/surveypro/utemplates.php', $paramurl); + $icons .= $OUTPUT->action_icon($link, $deleteicn, null, ['title' => $deletetitle]); + } + } + + // SURVEYPRO_EXPORTUTEMPLATE. + if ($candownloadutemplates) { + $paramurl = $paramurlbase; + $paramurl['act'] = SURVEYPRO_EXPORTUTEMPLATE; + $paramurl['section'] = 'manage'; + $paramurl['sesskey'] = sesskey(); + + $link = new \moodle_url('/mod/surveypro/utemplates.php', $paramurl); + $icons .= $OUTPUT->action_icon($link, $importicn, null, ['title' => $importtitle]); + } + + $tablerow[] = $icons; + + $table->add_data($tablerow); + } + $table->set_attribute('align', 'center'); + $table->summary = get_string('templatelist', 'mod_surveypro'); + $table->print_html(); + } + + /** + * Make the usertemplate available for the download. + * + * @return void + */ + public function export_utemplate() { + global $CFG; + + $fs = get_file_storage(); + $xmlfile = $fs->get_file_by_id($this->utemplateid); + $filename = $xmlfile->get_filename(); + $content = $xmlfile->get_content(); + + // Debug: echo '';. + + $templatename = clean_filename('temptemplate-' . gmdate("Ymd_Hi")); + $exportsubdir = "mod_surveypro/templateexport"; + make_temp_directory($exportsubdir); + $exportdir = "$CFG->tempdir/$exportsubdir"; + $exportfile = $exportdir.'/'.$templatename; + if (!preg_match('~\.xml$~', $exportfile)) { + $exportfile .= '.xml'; + } + $this->templatename = basename($exportfile); + + $this->trigger_event('usertemplate_exported'); + + header("Content-Type: application/download\n"); + header("Content-Disposition: attachment; filename=\"$filename\""); + header('Expires: 0'); + header('Cache-Control: must-revalidate,post-check=0,pre-check=0'); + header('Pragma: public'); + $xmlfile = fopen($exportdir.'/'.$this->templatename, 'w'); + print $content; + fclose($xmlfile); + unlink($exportdir.'/'.$this->templatename); + } + + /** + * Prevent direct user input. + * + * @return void + */ + public function prevent_direct_user_input() { + if ($this->action != SURVEYPRO_NOACTION) { + require_sesskey(); + } + if ($this->action == SURVEYPRO_DELETEUTEMPLATE) { + require_capability('mod/surveypro:deleteusertemplates', $this->context); + } + if ($this->action == SURVEYPRO_DELETEALLITEMS) { + require_capability('mod/surveypro:manageusertemplates', $this->context); + } + if ($this->action == SURVEYPRO_EXPORTUTEMPLATE) { + require_capability('mod/surveypro:downloadusertemplates', $this->context); + } + } +} diff --git a/classes/utemplate_save.php b/classes/utemplate_save.php new file mode 100644 index 00000000000..882812c7117 --- /dev/null +++ b/classes/utemplate_save.php @@ -0,0 +1,230 @@ +. + +/** + * Surveypro utemplate_save class. + * + * @package mod_surveypro + * @copyright 2013 onwards kordan + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_surveypro; + +use core_text; +use mod_surveypro\utility_layout; + +use mod_surveypro\local\ipe\usertemplate_name; + +/** + * The class representing a user template + * + * @package mod_surveypro + * @copyright 2013 onwards kordan + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class utemplate_save extends utemplate_base { + + /** + * Setup. + * + * @param int $utemplateid + * @return void + */ + public function setup($utemplateid) { + $this->set_utemplateid($utemplateid); + } + + // MARK set. + + /** + * Set utemplateid. + * + * @param int $utemplateid + * @return void + */ + private function set_utemplateid($utemplateid) { + $this->utemplateid = $utemplateid; + } + + // MARK other. + + /** + * Display the welcome message of the save page. + * + * @return void + */ + public function welcome_save_message() { + global $OUTPUT; + + $a = get_string('sharinglevel', 'mod_surveypro'); + $message = get_string('welcome_utemplatesave', 'mod_surveypro', $a); + echo $OUTPUT->notification($message, 'notifymessage'); + } + + /** + * Write template content. + * + * @param boolean $visiblesonly + * @return void + */ + public function write_template_content($visiblesonly=true) { + global $DB; + + $pluginversion = self::get_subplugin_versions(); + $where = ['surveyproid' => $this->surveypro->id]; + if ($visiblesonly) { + $where['hidden'] = '0'; + } + $itemseeds = $DB->get_records('surveypro_item', $where, 'sortindex', 'id, type, plugin'); + + $fs = get_file_storage(); + $context = \context_module::instance($this->cm->id); + + $xmltemplate = new \SimpleXMLElement(''); + foreach ($itemseeds as $itemseed) { + $item = surveypro_get_item($this->cm, $this->surveypro, $itemseed->id, $itemseed->type, $itemseed->plugin); + + $xmlitem = $xmltemplate->addChild('item'); + $xmlitem->addAttribute('type', $itemseed->type); + $xmlitem->addAttribute('plugin', $itemseed->plugin); + $index = $itemseed->type.'_'.$itemseed->plugin; + $xmlitem->addAttribute('version', $pluginversion[$index]); + + // Surveypro_item. + $xmltable = $xmlitem->addChild('surveypro_item'); + $structure = $this->get_table_structure(); + foreach ($structure as $field) { + if ($field == 'parentid') { + $parentid = $item->get_parentid(); + if ($parentid) { + // Store the sortindex of the parent instead of its id, because at restore time parentid will change. + $whereparams = ['id' => $parentid]; + $sortindex = $DB->get_field('surveypro_item', 'sortindex', $whereparams, MUST_EXIST); + $val = $item->get_parentvalue(); + + $xmlparent = $xmltable->addChild('parent'); + $xmlfield = $xmlparent->addChild('parentid', $sortindex); + $xmlfield = $xmlparent->addChild('parentvalue', $val); + } // Otherwise: It is empty, do not evaluate: jump. + continue; + } + if ($field == 'parentvalue') { + continue; + } + + $val = $item->get_generic_property($field); + if (core_text::strlen($val)) { + $xmlfield = $xmltable->addChild($field, $val); + } // Otherwise: It is empty, do not evaluate: jump. + } + + // Child table. + $structure = $this->get_table_structure($itemseed->type, $itemseed->plugin); + // Take care: some items plugin may be free of their own specific table. + if (!count($structure)) { + continue; + } + + $tablename = 'surveypro'.$itemseed->type.'_'.$itemseed->plugin; + $xmltable = $xmlitem->addChild($tablename); + foreach ($structure as $field) { + // If $field == 'content' I can not use the property of the object $item because + // in case of pictures, for instance, $item->content has to look like: + // 'MMM' + // and not like: + // 'img1get_generic_property($field); + } else { + $val = $DB->get_field($tablename, 'content', ['itemid' => $itemseed->id], MUST_EXIST); + } + + if (core_text::strlen($val)) { + $xmlfield = $xmltable->addChild($field, htmlspecialchars($val, ENT_QUOTES | ENT_SUBSTITUTE)); + } // Otherwise: It is empty, do not evaluate: jump. + + if ($field == 'content') { + $itemid = $item->get_itemid(); + if ($files = $fs->get_area_files($context->id, 'mod_surveypro', SURVEYPRO_ITEMCONTENTFILEAREA, $itemid)) { + foreach ($files as $file) { + $filename = $file->get_filename(); + if ($filename == '.') { + continue; + } + $xmlembedded = $xmltable->addChild('embedded'); + $xmlembedded->addChild('filename', $filename); + $xmlembedded->addChild('filecontent', base64_encode($file->get_content())); + } + } + } + } + } + + // In the coming code, "$option == false;" if 100% waste of time and should be changed to "$option == true;" + // BUT BUT BUT... + // the output in $dom->saveXML() is well written. + // I prefer a more readable xml file instead of few nanoseconds saved. + $option = false; + if ($option) { + return $xmltemplate->asXML(); + } else { + $dom = new \DOMDocument('1.0'); + $dom->preserveWhiteSpace = false; + $dom->formatOutput = true; + $dom->loadXML($xmltemplate->asXML()); + + return $dom->saveXML(); + } + } + + /** + * Generate the usertemplate. + * + * @return void + */ + public function generate_utemplate() { + global $USER; + + $this->templatename = $this->formdata->templatename; + $this->templatename = str_replace(' ', '_', $this->templatename); + if (!preg_match('~\.xml$~', $this->templatename)) { + $this->templatename .= '.xml'; + } + $xmlcontent = $this->write_template_content($this->formdata->visiblesonly); + // Debug: echo '';. + + $fs = get_file_storage(); + $filerecord = new \stdClass; + + $contextid = $this->formdata->sharinglevel; + $filerecord->contextid = $contextid; + + $filerecord->component = 'mod_surveypro'; + $filerecord->filearea = SURVEYPRO_TEMPLATEFILEAREA; + $filerecord->itemid = 0; + $filerecord->filepath = '/'; + $filerecord->userid = $USER->id; + + $filerecord->filename = str_replace(' ', '_', $this->templatename); + if (!preg_match('~\.xml$~', $filerecord->filename)) { + $filerecord->filename .= '.xml'; + } + $fs->create_file_from_string($filerecord, $xmlcontent); + + return true; + } +} diff --git a/classes/utility_page.php b/classes/utility_page.php index 4d52cc1b8ae..157c7853f90 100644 --- a/classes/utility_page.php +++ b/classes/utility_page.php @@ -15,7 +15,7 @@ // along with Moodle. If not, see . /** - * Surveypro utility class. + * Surveypro utility_page class. * * @package mod_surveypro * @copyright 2013 onwards kordan diff --git a/classes/utility_submission.php b/classes/utility_submission.php index 222aaa0cbf7..ea1464f7192 100644 --- a/classes/utility_submission.php +++ b/classes/utility_submission.php @@ -15,7 +15,7 @@ // along with Moodle. If not, see . /** - * Surveypro utility class. + * Surveypro utility_submission class. * * @package mod_surveypro * @copyright 2013 onwards kordan diff --git a/classes/cover.php b/classes/view_cover.php similarity index 99% rename from classes/cover.php rename to classes/view_cover.php index 0bf6693ffce..9b496f1eae5 100644 --- a/classes/cover.php +++ b/classes/view_cover.php @@ -15,7 +15,7 @@ // along with Moodle. If not, see . /** - * The covermanager class + * The view_cover class * * @package mod_surveypro * @copyright 2013 onwards kordan @@ -33,7 +33,7 @@ * @copyright 2013 onwards kordan * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class cover { +class view_cover { /** * @var object Course module object diff --git a/classes/submissions_form.php b/classes/view_submissionform.php similarity index 99% rename from classes/submissions_form.php rename to classes/view_submissionform.php index 8afd997f447..7f850a4e014 100644 --- a/classes/submissions_form.php +++ b/classes/view_submissionform.php @@ -15,7 +15,7 @@ // along with Moodle. If not, see . /** - * The userform class + * The view_submissionform class * * @package mod_surveypro * @copyright 2013 onwards kordan @@ -36,7 +36,7 @@ * @copyright 2013 onwards kordan * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class submissions_form extends formbase { +class view_submissionform extends formbase { /** * @var int $mode diff --git a/classes/submissions_list.php b/classes/view_submissionlist.php similarity index 99% rename from classes/submissions_list.php rename to classes/view_submissionlist.php index 0b050715732..9ae5dc6892e 100644 --- a/classes/submissions_list.php +++ b/classes/view_submissionlist.php @@ -15,7 +15,7 @@ // along with Moodle. If not, see . /** - * The submissionmanager class + * The view_submissionlist class * * @package mod_surveypro * @copyright 2013 onwards kordan @@ -35,7 +35,7 @@ * @copyright 2013 onwards kordan * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class submissions_list { +class view_submissionlist { /** * @var object Course module object diff --git a/classes/submissions_search.php b/classes/view_submissionsearch.php similarity index 98% rename from classes/submissions_search.php rename to classes/view_submissionsearch.php index b6c7541d107..9b10f780224 100644 --- a/classes/submissions_search.php +++ b/classes/view_submissionsearch.php @@ -15,7 +15,7 @@ // along with Moodle. If not, see . /** - * The searchmanager class + * The view_submissionsearch class * * @package mod_surveypro * @copyright 2013 onwards kordan @@ -33,7 +33,7 @@ * @copyright 2013 onwards kordan * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class submissions_search { +class view_submissionsearch { /** * @var object Course module object diff --git a/layout.php b/layout.php index b0202bf6d03..3d373c7066f 100644 --- a/layout.php +++ b/layout.php @@ -23,19 +23,23 @@ */ use mod_surveypro\utility_page; -use mod_surveypro\layout_itemsetup; use mod_surveypro\utility_layout; use mod_surveypro\utility_submission; -use mod_surveypro\usertemplate; +use mod_surveypro\utility_mform; + +use mod_surveypro\layout_itemsetup; +use mod_surveypro\layout_itemlist; +use mod_surveypro\layout_preview; + +use mod_surveypro\utemplate_apply; +use mod_surveypro\mtemplate_apply; + use mod_surveypro\mastertemplate; + use mod_surveypro\local\form\item_chooser; use mod_surveypro\local\form\utemplate_applyform; use mod_surveypro\local\form\mtemplate_applyform; use mod_surveypro\local\form\item_bulkactionform; - -// Needed only if $section == 'preview'. -use mod_surveypro\layout_preview; -use mod_surveypro\utility_mform; use mod_surveypro\local\form\userform; require_once(dirname(__FILE__).'/../../config.php'); @@ -72,7 +76,7 @@ $utilitypageman = new utility_page($cm, $surveypro); // MARK preview. -if ($section == 'preview') { // It was layout_validation.php +if ($section == 'preview') { // Get additional specific params. $submissionid = optional_param('submissionid', 0, PARAM_INT); $formpage = optional_param('formpage', 1, PARAM_INT); // Form page number. @@ -175,7 +179,7 @@ } // MARK itemslist. -if ($section == 'itemslist') { // It was layout_itemlist.php. +if ($section == 'itemslist') { // Get additional specific params. $type = optional_param('type', null, PARAM_TEXT); $plugin = optional_param('plugin', null, PARAM_TEXT); @@ -204,21 +208,22 @@ $hassubmissions = $utilitylayoutman->has_submissions(); // Define the manager. - $layoutman = new layout_itemsetup($cm, $context, $surveypro); - $layoutman->set_type($type); - $layoutman->set_plugin($plugin); - $layoutman->set_itemid($itemid); - $layoutman->set_sortindex($sortindex); - $layoutman->set_action($action); - $layoutman->set_mode($mode); - $layoutman->set_itemtomove($itemtomove); - $layoutman->set_lastitembefore($lastitembefore); - $layoutman->set_confirm($confirm); - $layoutman->set_nextindent($nextindent); - $layoutman->set_parentid($parentid); - $layoutman->set_itemeditingfeedback($itemeditingfeedback); - $layoutman->set_hassubmissions($hassubmissions); - $layoutman->actions_execution(); + $itemlistman = new layout_itemlist($cm, $context, $surveypro); + $itemlistman->setup(); + $itemlistman->set_type($type); + $itemlistman->set_plugin($plugin); + $itemlistman->set_itemid($itemid); + $itemlistman->set_sortindex($sortindex); + $itemlistman->set_action($action); + $itemlistman->set_mode($mode); + $itemlistman->set_itemtomove($itemtomove); + $itemlistman->set_lastitembefore($lastitembefore); + $itemlistman->set_confirm($confirm); + $itemlistman->set_nextindent($nextindent); + $itemlistman->set_parentid($parentid); + $itemlistman->set_itemeditingfeedback($itemeditingfeedback); + $itemlistman->set_hassubmissions($hassubmissions); + $itemlistman->actions_execution(); // You must count items AFTER actions_execution() otherwise the count may be wrong (when $action == SURVEYPRO_DELETEITEM). $itemcount = $utilitylayoutman->has_items(0, 'field', true, true, true); @@ -245,8 +250,8 @@ $templatecondition = $templatecondition && has_capability('mod/surveypro:manageitems', $context); if ($templatecondition) { // Begin of: User templates form. - $utemplateman = new usertemplate($cm, $context, $surveypro); - $utemplates = $utemplateman->get_utemplates_items(); + $applyman = new utemplate_apply($cm, $context, $surveypro); + $utemplates = $applyman->get_utemplates_items(); if (count($utemplates)) { $formurl = new \moodle_url('/mod/surveypro/utemplates.php', ['s' => $cm->instance, 'section' => 'apply']); @@ -258,13 +263,13 @@ // End of: User templates form. // Begin of: Master templates form. - $mtemplateman = new mastertemplate($cm, $context, $surveypro); - $mtemplates = $mtemplateman->get_mtemplates(); + $applyman = new mtemplate_apply($cm, $context, $surveypro); + $mtemplates = $applyman->get_mtemplates(); if (count($mtemplates)) { $formurl = new \moodle_url('/mod/surveypro/mtemplates.php', ['s' => $cm->instance, 'section' => 'apply']); $formparams = new \stdClass(); - $formparams->mtemplateman = $mtemplateman; + $formparams->applyman = $applyman; $formparams->inlineform = true; $mtemplateform = new mtemplate_applyform($formurl, $formparams); } @@ -284,7 +289,7 @@ // Manage bulkaction form. if ($formdata = $bulkactionform->get_data()) { - $layoutman->set_action($formdata->bulkaction); + $itemlistman->set_action($formdata->bulkaction); } } // End of: Bulk action form. @@ -319,8 +324,8 @@ echo $OUTPUT->notification($message, 'notifyproblem'); } - $layoutman->actions_feedback(); - $layoutman->display_item_editing_feedback(); + $itemlistman->actions_feedback(); + $itemlistman->display_item_editing_feedback(); // Display welcome message. if (!$itemcount) { @@ -349,11 +354,11 @@ $bulkactionform->display(); } - $layoutman->display_items_table(); + $itemlistman->display_items_table(); } // MARK itemsetup. -if ($section == 'itemsetup') { // It was layout_itemsetup.php +if ($section == 'itemsetup') { // Get additional specific params. $typeplugin = optional_param('typeplugin', null, PARAM_TEXT); $type = optional_param('type', null, PARAM_TEXT); @@ -373,48 +378,26 @@ $utilitylayoutman = new utility_layout($cm, $surveypro); $hassubmissions = $utilitylayoutman->has_submissions(); - $layoutman = new layout_itemsetup($cm, $context, $surveypro); + $itemsetupman = new layout_itemsetup($cm, $context, $surveypro); + $itemsetupman->setup(); if (!empty($typeplugin)) { - $layoutman->set_typeplugin($typeplugin); + $itemsetupman->set_typeplugin($typeplugin); } else { - $layoutman->set_type($type); - $layoutman->set_plugin($plugin); + $itemsetupman->set_type($type); + $itemsetupman->set_plugin($plugin); } - $layoutman->set_itemid($itemid); - $layoutman->set_action($action); - $layoutman->set_mode($mode); - $layoutman->set_hassubmissions($hassubmissions); - // Property itemtomove is useless (it is set to its default), do not set it. - // So, jump: $layoutman->set_itemtomove(0); - - // Property lastitembefore is useless (it is set to its default), do not set it. - // So, jump: $layoutman->set_lastitembefore(0); - - // Property confirm is useless (it is set to its default), do not set it. - // So, jump: $layoutman->set_confirm(SURVEYPRO_UNCONFIRMED); - - // Property nextindent is useless (it is set to its default), do not set it. - // So, jump: $layoutman->set_nextindent(0); - - // Property parentid is useless (it is set to its default), do not set it. - // So, jump: $layoutman->set_parentid(0); - - // Property itemeditingfeedback is useless (it is set to its default), do not set it. - // So, jump: $layoutman->set_itemeditingfeedback(SURVEYPRO_NOFEEDBACK); + $itemsetupman->set_itemid($itemid); + $itemsetupman->set_action($action); + $itemsetupman->set_mode($mode); + $itemsetupman->set_hassubmissions($hassubmissions); - // Property hassubmissions is useless (it is set to its default), do not set it. - // So, jump: $layoutman->set_hassubmissions($hassubmissions); + $itemsetupman->prevent_direct_user_input(); - // Property itemcount is useless (it is set to its default), do not set it. - // So, jump: $layoutman->set_itemcount($itemcount); - - $layoutman->prevent_direct_user_input(); - - require_once($CFG->dirroot.'/mod/surveypro/'.$layoutman->get_type().'/'.$layoutman->get_plugin().'/classes/itemsetupform.php'); + require_once($CFG->dirroot.'/mod/surveypro/'.$itemsetupman->get_type().'/'.$itemsetupman->get_plugin().'/classes/itemsetupform.php'); // Begin of: get item. - $itemtype = $layoutman->get_type(); - $itemplugin = $layoutman->get_plugin(); + $itemtype = $itemsetupman->get_type(); + $itemplugin = $itemsetupman->get_plugin(); $item = surveypro_get_item($cm, $surveypro, $itemid, $itemtype, $itemplugin, true); $item->set_editor(); // End of: get item. @@ -425,8 +408,8 @@ $paramurl['area'] = 'layout'; $paramurl['section'] = 'itemsetup'; $paramurl['itemid'] = $itemid; - $paramurl['type'] = $layoutman->get_type(); - $paramurl['plugin'] = $layoutman->get_plugin(); + $paramurl['type'] = $itemsetupman->get_type(); + $paramurl['plugin'] = $itemsetupman->get_plugin(); $paramurl['mode'] = $mode; $url = new \moodle_url('/mod/surveypro/layout.php', $paramurl); @@ -485,7 +468,7 @@ $message = $utilitysubmissionman->get_submissions_warning(); echo $OUTPUT->notification($message, 'notifyproblem'); } - $layoutman->item_identitycard(); + $itemsetupman->item_identitycard(); $data = $item->get_itemform_preset(); $itemform->set_data($data); @@ -494,53 +477,17 @@ } // MARK branchingvalidation. -if ($section == 'branchingvalidation') { // It was layout_validation.php +if ($section == 'branchingvalidation') { // Get additional specific params. // Required capability. require_capability('mod/surveypro:additems', $context); // Calculations. - $layoutman = new layout_itemsetup($cm, $context, $surveypro); - - // Property type is useless, do not set it. - // So, jump: $layoutman->set_type(''); - - // Property plugin is useless, do not set it - // So, jump: $layoutman->set_plugin(''); - - // Property itemid is useless (it is set to its default), do not set it - // So, jump: $layoutman->set_itemid(0); - - // Property action is useless (it is set to its default), do not set it - // So, jump: $layoutman->set_action(SURVEYPRO_NOACTION); - - // Property mode is useless (it is set to its default), do not set it - // So, jump: $layoutman->set_mode(SURVEYPRO_NEWRESPONSEMODE); - - // Property itemtomove is useless (it is set to its default), do not set it - // So, jump: $layoutman->set_itemtomove(0); + $branchingvalidationman = new layout_branchingvalidation($cm, $context, $surveypro); - // Property lastitembefore is useless (it is set to its default), do not set it - // So, jump: $layoutman->set_lastitembefore(0); - - // Property confirm is useless (it is set to its default), do not set it - // So, jump: $layoutman->set_confirm(SURVEYPRO_UNCONFIRMED); - - // Property nextindent is useless (it is set to its default), do not set it - // So, jump: $layoutman->set_nextindent(0); - - // Property parentid is useless (it is set to its default), do not set it - // So, jump: $layoutman->set_parentid(0); - - // Property itemeditingfeedback is useless (it is set to its default), do not set it - // So, jump: $layoutman->set_itemeditingfeedback(SURVEYPRO_NOFEEDBACK); - - // Property hassubmissions is useless (it is set to its default), do not set it. - // So, jump: $layoutman->set_hassubmissions($hassubmissions); - - // Property itemcount is useless (it is set to its default), do not set it. - // So, jump: $layoutman->set_itemcount($itemcount); + // Output starts here. + $url = new \moodle_url('/mod/surveypro/layout.php', ['s' => $surveypro->id, 'section' => 'branchingvalidation']); // Set $PAGE params. $paramurl = ['s' => $surveypro->id, 'area' => 'layout', 'section' => 'branchingvalidation']; @@ -560,7 +507,7 @@ $actionbar = new \mod_surveypro\output\action_bar($cm, $context, $surveypro); echo $actionbar->draw_layout_action_bar(); - $layoutman->display_relations_table(); + $branchingvalidationman->display_relations_table(); } // Finish the page. diff --git a/mtemplates.php b/mtemplates.php index 4d78143d65d..a2b5f68a4d5 100644 --- a/mtemplates.php +++ b/mtemplates.php @@ -23,13 +23,13 @@ */ use mod_surveypro\utility_page; - -use mod_surveypro\mastertemplate; -use mod_surveypro\local\form\mtemplate_createform; - -// Needed only if $section == 'apply'. use mod_surveypro\utility_layout; use mod_surveypro\utility_submission; + +use mod_surveypro\mtemplate_apply; +use mod_surveypro\mtemplate_save; + +use mod_surveypro\local\form\mtemplate_createform; use mod_surveypro\local\form\mtemplate_applyform; require_once(dirname(__FILE__).'/../../config.php'); @@ -66,14 +66,14 @@ $utilitypageman = new utility_page($cm, $surveypro); // MARK save. -if ($section == 'save') { // It was mtemplate_save.php +if ($section == 'save') { // Get additional specific params. // Required capability. require_capability('mod/surveypro:savemastertemplates', $context); // Calculations. - $mtemplateman = new mastertemplate($cm, $context, $surveypro); + $saveman = new mtemplate_save($cm, $context, $surveypro); // Start of: define $createmtemplate return url. $formurl = new \moodle_url('/mod/surveypro/mtemplates.php', ['s' => $cm->instance, 'section' => 'save']); @@ -81,9 +81,9 @@ // End of: define $createmtemplate return url. // Start of: manage form submission. - if ($mtemplateman->formdata = $createmtemplate->get_data()) { - $mtemplateman->download_mtemplate(); - $mtemplateman->trigger_event('mastertemplate_saved'); + if ($saveman->formdata = $createmtemplate->get_data()) { + $saveman->download_mtemplate(); + $saveman->trigger_event('mastertemplate_saved'); exit(0); } // End of: manage form submission. @@ -116,14 +116,14 @@ } // MARK apply. -if ($section == 'apply') { // It was mtemplate_apply.php +if ($section == 'apply') { // Get additional specific params. // Required capability. require_capability('mod/surveypro:applymastertemplates', $context); // Calculations. - $mtemplateman = new mastertemplate($cm, $context, $surveypro); + $applyman = new mtemplate_apply($cm, $context, $surveypro); // Begin of: define $applymtemplate return url. $formurl = new \moodle_url('/mod/surveypro/mtemplates.php', ['s' => $cm->instance, 'section' => 'apply']); @@ -133,14 +133,15 @@ $formparams = new \stdClass(); $formparams->cmid = $cm->id; $formparams->surveypro = $surveypro; - $formparams->mtemplateman = $mtemplateman; + $formparams->applyman = $applyman; $formparams->inlineform = false; $applymtemplate = new mtemplate_applyform($formurl, $formparams); // End of: prepare params for the form. // Begin of: manage form submission. - if ($mtemplateman->formdata = $applymtemplate->get_data()) { - $mtemplateman->apply_template(); + if ($applyman->formdata = $applymtemplate->get_data()) { + $applyman->apply_template(); + $applyman->trigger_event('mastertemplate_applied'); } // End of: manage form submission. @@ -162,7 +163,7 @@ $actionbar = new \mod_surveypro\output\action_bar($cm, $context, $surveypro); echo $actionbar->draw_mtemplates_action_bar(); - $mtemplateman->friendly_stop(); + $applyman->friendly_stop(); $riskyediting = ($surveypro->riskyeditdeadline > time()); $utilitylayoutman = new utility_layout($cm, $surveypro); @@ -172,7 +173,7 @@ echo $OUTPUT->notification($message, 'notifyproblem'); } - $mtemplateman->welcome_apply_message(); + $applyman->welcome_apply_message(); $applymtemplate->display(); } diff --git a/report/attachments/view.php b/report/attachments/view.php index ca87d668acb..ac63569891a 100644 --- a/report/attachments/view.php +++ b/report/attachments/view.php @@ -130,7 +130,7 @@ } // MARK details. -if ($section == 'details') { // It was report/attachments/uploads.php +if ($section == 'details') { $container = required_param('container', PARAM_ALPHANUMEXT); $itemid = optional_param('itemid', 0, PARAM_INT); // Item id. $changeuser = optional_param('changeuser', 0, PARAM_TEXT); diff --git a/tests/mastertemplate_test.php b/tests/mastertemplate_test.php index ee2acd2f416..3dbc2a1d643 100644 --- a/tests/mastertemplate_test.php +++ b/tests/mastertemplate_test.php @@ -61,10 +61,10 @@ public function test_surveyprotemplate_get_plugin_name($userinput, $expected) { $cm = get_coursemodule_from_instance('surveypro', $surveypro->id); $context = \context_module::instance($cm->id); - $mtemplateman = new mastertemplate($cm, $context, $surveypro); - $mtemplateman->formdata = (object)['mastertemplatename' => $userinput]; - // $mtemplateman->formdata->mastertemplatename = $userinput; - $returned = $mtemplateman->get_plugin_name(); + $saveman = new mtemplate_save($cm, $context, $surveypro); + $saveman->formdata = (object)['mastertemplatename' => $userinput]; + // $saveman->formdata->mastertemplatename = $userinput; + $returned = $saveman->get_plugin_name(); $this->assertEquals($expected, $returned); } } diff --git a/tools.php b/tools.php index 041238565b5..1f3ae31dd92 100644 --- a/tools.php +++ b/tools.php @@ -66,7 +66,7 @@ $utilitypageman = new utility_page($cm, $surveypro); // MARK export. -if ($section == 'export') { // It was tools_export.php +if ($section == 'export') { // Get additional specific params. // Required capability. @@ -138,7 +138,7 @@ } // MARK import. -if ($section == 'import') { // It was tools_import.php +if ($section == 'import') { // Get additional specific params. // Required capability. diff --git a/utemplates.php b/utemplates.php index adb2990b5a6..134e079e569 100644 --- a/utemplates.php +++ b/utemplates.php @@ -23,18 +23,17 @@ */ use mod_surveypro\utility_page; -use mod_surveypro\usertemplate; - -// Needed only if $section == 'save'. -use mod_surveypro\local\form\utemplate_createform; - -// Needed only if $section == 'import'. -use mod_surveypro\local\form\utemplate_importform; - -// Needed only if $section == 'apply'. use mod_surveypro\utility_layout; use mod_surveypro\utility_submission; + use mod_surveypro\templatebase; +use mod_surveypro\utemplate_manage; +use mod_surveypro\utemplate_save; +use mod_surveypro\utemplate_import; +use mod_surveypro\utemplate_apply; + +use mod_surveypro\local\form\utemplate_createform; +use mod_surveypro\local\form\utemplate_importform; use mod_surveypro\local\form\utemplate_applyform; require_once(dirname(__FILE__).'/../../config.php'); @@ -71,7 +70,7 @@ $utilitypageman = new utility_page($cm, $surveypro); // MARK manage. -if ($section == 'manage') { // It was utemplate_manage.php +if ($section == 'manage') { // Get additional specific params. $utemplateid = optional_param('fid', 0, PARAM_INT); $action = optional_param('act', SURVEYPRO_NOACTION, PARAM_INT); @@ -81,13 +80,14 @@ require_capability('mod/surveypro:manageusertemplates', $context); // Calculations. - $utemplateman = new usertemplate($cm, $context, $surveypro); - $utemplateman->setup($utemplateid, $action, $confirm); + $manageman = new utemplate_manage($cm, $context, $surveypro); + $manageman->setup($utemplateid, $action, $confirm); - $utemplateman->prevent_direct_user_input(); + $manageman->prevent_direct_user_input(); if ($action == SURVEYPRO_EXPORTUTEMPLATE) { - $utemplateman->export_utemplate(); + $manageman->trigger_event('usertemplate_exported'); + $manageman->export_utemplate(); die(); } @@ -109,29 +109,28 @@ $actionbar = new \mod_surveypro\output\action_bar($cm, $context, $surveypro); echo $actionbar->draw_utemplates_action_bar(); - $utemplateman->delete_utemplate(); + if ($action == SURVEYPRO_DELETEUTEMPLATE) { + $manageman->trigger_event('usertemplate_deleted'); + $manageman->delete_utemplate(); + } - $utemplateman->display_usertemplates_table(); - $utemplateman->trigger_event('all_usertemplates_viewed'); // Event: all_usertemplates_viewed. + $manageman->display_usertemplates_table(); + $manageman->trigger_event('all_usertemplates_viewed'); // Event: all_usertemplates_viewed. } // MARK save. -if ($section == 'save') { // It was utemplate_save.php +if ($section == 'save') { // Get additional specific params. $utemplateid = optional_param('fid', 0, PARAM_INT); // Required capability. require_capability('mod/surveypro:saveusertemplates', $context); - // Params never passed but needed by called class. - $action = SURVEYPRO_NOACTION; - $confirm = SURVEYPRO_UNCONFIRMED; - // Calculations. - $utemplateman = new usertemplate($cm, $context, $surveypro); - $utemplateman->setup($utemplateid, $action, $confirm); + $saveman = new utemplate_save($cm, $context, $surveypro); + $saveman->setup($utemplateid); - // $utemplateman->prevent_direct_user_input(); + // $saveman->prevent_direct_user_input(); // is not needed because the check has already been done here with: require_capability('mod/surveypro:saveusertemplates',... // Begin of: define $createutemplate return url. @@ -140,15 +139,15 @@ // Begin of: prepare params for the form. $formparams = new \stdClass(); - $formparams->utemplateman = $utemplateman; + $formparams->saveman = $saveman; $formparams->defaultname = $surveypro->name; $createutemplate = new utemplate_createform($formurl, $formparams); // End of: prepare params for the form. // Begin of: manage form submission. - if ($utemplateman->formdata = $createutemplate->get_data()) { - $utemplateman->generate_utemplate(); - $utemplateman->trigger_event('usertemplate_saved'); + if ($saveman->formdata = $createutemplate->get_data()) { + $saveman->generate_utemplate(); + $saveman->trigger_event('usertemplate_saved'); $redirecturl = new \moodle_url('/mod/surveypro/utemplates.php', ['s' => $surveypro->id, 'section' => 'manage']); redirect($redirecturl); @@ -173,7 +172,7 @@ $actionbar = new \mod_surveypro\output\action_bar($cm, $context, $surveypro); echo $actionbar->draw_utemplates_action_bar(); - $utemplateman->welcome_save_message(); + $saveman->welcome_save_message(); $record = new \stdClass(); $record->surveyproid = $surveypro->id; @@ -183,22 +182,18 @@ } // MARK import. -if ($section == 'import') { // It was utemplate_import.php +if ($section == 'import') { // Get additional specific params. $utemplateid = optional_param('fid', 0, PARAM_INT); // Required capability. require_capability('mod/surveypro:importusertemplates', $context); - // Params never passed but needed by called class. - $action = SURVEYPRO_NOACTION; - $confirm = SURVEYPRO_UNCONFIRMED; - // Calculations. - $utemplateman = new usertemplate($cm, $context, $surveypro); - $utemplateman->setup($utemplateid, $action, $confirm); + $importman = new utemplate_import($cm, $context, $surveypro); + $importman->setup($utemplateid); - // $utemplateman->prevent_direct_user_input(); + // $importman->prevent_direct_user_input(); // is not needed because the check has already been done here with: require_capability('mod/surveypro:importusertemplates', $context); // Begin of: define $importutemplate return url. @@ -207,15 +202,15 @@ // Begin of: prepare params for the form. $formparams = new \stdClass(); - $formparams->utemplateman = $utemplateman; - $formparams->filemanageroptions = $utemplateman->get_filemanager_options(); + $formparams->importman = $importman; + $formparams->filemanageroptions = $importman->get_filemanager_options(); $importutemplate = new utemplate_importform($formurl, $formparams); // End of: prepare params for the form. // Begin of: manage form submission. - if ($utemplateman->formdata = $importutemplate->get_data()) { - $utemplateman->upload_utemplate(); - $utemplateman->trigger_event('usertemplate_imported'); + if ($importman->formdata = $importutemplate->get_data()) { + $importman->upload_utemplate(); + $importman->trigger_event('usertemplate_imported'); $redirecturl = new \moodle_url('/mod/surveypro/utemplates.php', ['s' => $surveypro->id, 'section' => 'manage']); redirect($redirecturl); @@ -240,12 +235,12 @@ $actionbar = new \mod_surveypro\output\action_bar($cm, $context, $surveypro); echo $actionbar->draw_utemplates_action_bar(); - $utemplateman->welcome_import_message(); + $importman->welcome_import_message(); $importutemplate->display(); } // MARK apply. -if ($section == 'apply') { // It was utemplate_apply.php +if ($section == 'apply') { // Get additional specific params. $utemplateid = optional_param('fid', 0, PARAM_INT); $action = optional_param('act', SURVEYPRO_NOACTION, PARAM_INT); @@ -255,11 +250,11 @@ require_capability('mod/surveypro:applyusertemplates', $context); // Calculations. - $utemplateman = new usertemplate($cm, $context, $surveypro); - $utemplateman->setup($utemplateid, $action, $confirm); + $applyman = new utemplate_apply($cm, $context, $surveypro); + $applyman->setup($utemplateid, $action, $confirm); - $utemplateman->prevent_direct_user_input(); - $utemplates = $utemplateman->get_utemplates_items(); + $applyman->prevent_direct_user_input(); + $utemplates = $applyman->get_utemplates_items(); // Begin of: define $applyutemplate return url. $formurl = new \moodle_url('/mod/surveypro/utemplates.php', ['s' => $cm->instance, 'section' => 'apply']); @@ -273,11 +268,11 @@ // End of: prepare params for the form. // Begin of: manage form submission. - if ($utemplateman->formdata = $applyutemplate->get_data()) { + if ($applyman->formdata = $applyutemplate->get_data()) { // Here I don't need to execute validate_xml because xml was validated at upload time // Here I only need to verfy that plugin versions still match - // $utemplateman->check_items_versions(); - $utemplateman->apply_template(); + // $applyman->check_items_versions(); + $applyman->apply_template(); } // End of: manage form submission. @@ -299,7 +294,7 @@ $actionbar = new \mod_surveypro\output\action_bar($cm, $context, $surveypro); echo $actionbar->draw_utemplates_action_bar(); - $utemplateman->friendly_stop(); + $applyman->friendly_stop(); $riskyediting = ($surveypro->riskyeditdeadline > time()); $utilitylayoutman = new utility_layout($cm, $surveypro); @@ -309,7 +304,7 @@ echo $OUTPUT->notification($message, 'notifyproblem'); } - $utemplateman->welcome_apply_message(); + $applyman->welcome_apply_message(); $applyutemplate->display(); } diff --git a/version.php b/version.php index abefb9c951c..5e3d0b2e9be 100644 --- a/version.php +++ b/version.php @@ -26,6 +26,6 @@ $plugin->component = 'mod_surveypro'; $plugin->maturity = MATURITY_BETA; -$plugin->version = 2023120106; +$plugin->version = 2024022700; $plugin->release = '4.4dev'; $plugin->requires = 2023100900; diff --git a/view.php b/view.php index c3fe8d06b40..82f0db0ae74 100644 --- a/view.php +++ b/view.php @@ -24,20 +24,14 @@ use mod_surveypro\utility_layout; use mod_surveypro\utility_page; +use mod_surveypro\utility_mform; -// Needed only if $section == 'cover'. -use mod_surveypro\cover; - -// Needed only if $section == 'submissionslist'. -use mod_surveypro\submissions_list; +use mod_surveypro\view_cover; +use mod_surveypro\view_submissionlist; +use mod_surveypro\view_submissionform; +use mod_surveypro\view_submissionsearch; -// Needed only if $section == 'submissionform'. -use mod_surveypro\utility_mform; -use mod_surveypro\submissions_form; use mod_surveypro\local\form\userform; - -// Needed only if $section == 'searchsubmission'. -use mod_surveypro\submissions_search; use mod_surveypro\local\form\usersearch; require_once(dirname(__FILE__).'/../../config.php'); @@ -74,7 +68,7 @@ $utilitypageman = new utility_page($cm, $surveypro); // MARK cover. -if ($section == 'cover') { // It was view_cover.php +if ($section == 'cover') { // Get additional specific params. // Required capability. @@ -87,7 +81,7 @@ $utilitylayoutman->noitem_redirect(); $itemcount = $utilitylayoutman->has_items(0, SURVEYPRO_TYPEFIELD, $canmanageitems, $canaccessreserveditems, true); - $coverman = new cover($cm, $context, $surveypro); + $coverman = new view_cover($cm, $context, $surveypro); // Set $PAGE params. $paramurl = ['s' => $surveypro->id, 'area' => 'surveypro', 'section' => 'cover']; @@ -122,7 +116,7 @@ // - delete a submission; // - delete all gathered submissions; // - print to PDF a submission. -if ($section == 'submissionslist') { // It was view_submissions.php +if ($section == 'submissionslist') { // Get additional specific params. $tifirst = optional_param('tifirst', '', PARAM_ALPHA); // First letter of the name. $tilast = optional_param('tilast', '', PARAM_ALPHA); // First letter of the surname. @@ -144,7 +138,7 @@ } // Calculations. - $submissionlistman = new submissions_list($cm, $context, $surveypro); + $submissionlistman = new view_submissionlist($cm, $context, $surveypro); $submissionlistman->setup($submissionid, $action, $mode, $confirm, $searchquery); if ($action == SURVEYPRO_RESPONSETOPDF) { @@ -190,7 +184,7 @@ // - edit existing submissions [$mode = SURVEYPRO_EDITMODE]; // - view in readonly mode [$mode = SURVEYPRO_READONLYMODE]; // - preview submission form [$mode = SURVEYPRO_PREVIEWMODE]; -if ($section == 'submissionform') { // It was view_form.php +if ($section == 'submissionform') { // Get additional specific params. $submissionid = optional_param('submissionid', 0, PARAM_INT); $formpage = optional_param('formpage', 1, PARAM_INT); // Form page number. @@ -201,8 +195,8 @@ // Calculations. mod_surveypro\utility_mform::register_form_elements(); - $userformman = new submissions_form($cm, $context, $surveypro); - $userformman->setup($submissionid, $formpage, $mode); + $submissionformman = new view_submissionform($cm, $context, $surveypro); + $submissionformman->setup($submissionid, $formpage, $mode); $utilitylayoutman = new utility_layout($cm, $surveypro); $utilitylayoutman->add_custom_css(); @@ -218,19 +212,19 @@ $formparams->surveypro = $surveypro; $formparams->submissionid = $submissionid; $formparams->mode = $mode; - $formparams->userformpagecount = $userformman->get_userformpagecount(); + $formparams->userformpagecount = $submissionformman->get_userformpagecount(); $formparams->canaccessreserveditems = has_capability('mod/surveypro:accessreserveditems', $context); - $formparams->userfirstpage = $userformman->get_userfirstpage(); // The user first page - $formparams->userlastpage = $userformman->get_userlastpage(); // The user last page + $formparams->userfirstpage = $submissionformman->get_userfirstpage(); // The user first page + $formparams->userlastpage = $submissionformman->get_userlastpage(); // The user last page $formparams->overflowpage = $overflowpage; // Went the user to a overflow page? // End of: prepare params for the form. if ($begin == 1) { - $userformman->next_not_empty_page(true, 0); // True means direction = right. - $nextpage = $userformman->get_nextpage(); // The page of the form to select subset of fields - $userformman->set_formpage($nextpage); + $submissionformman->next_not_empty_page(true, 0); // True means direction = right. + $nextpage = $submissionformman->get_nextpage(); // The page of the form to select subset of fields + $submissionformman->set_formpage($nextpage); } - $formparams->formpage = $userformman->get_formpage(); // The page of the form to select subset of fields + $formparams->formpage = $submissionformman->get_formpage(); // The page of the form to select subset of fields // End of: prepare params for the form. $editable = ($mode == SURVEYPRO_READONLYMODE) ? false : true; @@ -243,42 +237,42 @@ redirect($redirecturl, get_string('usercanceled', 'mod_surveypro')); } - if ($userformman->formdata = $userform->get_data()) { - $userformman->save_user_data(); // SAVE SAVE SAVE SAVE. + if ($submissionformman->formdata = $userform->get_data()) { + $submissionformman->save_user_data(); // SAVE SAVE SAVE SAVE. // If "pause" button has been pressed, redirect. - $pausebutton = isset($userformman->formdata->pausebutton); + $pausebutton = isset($submissionformman->formdata->pausebutton); if ($pausebutton) { $localparamurl = ['s' => $cm->instance, 'mode' => $mode, 'section' => 'submissionslist']; $redirecturl = new \moodle_url('/mod/surveypro/view.php', $localparamurl); redirect($redirecturl); // Go somewhere. } - $paramurl['submissionid'] = $userformman->get_submissionid(); + $paramurl['submissionid'] = $submissionformman->get_submissionid(); $paramurl['section'] = 'submissionform'; // If "previous" button has been pressed, redirect. - $prevbutton = isset($userformman->formdata->prevbutton); + $prevbutton = isset($submissionformman->formdata->prevbutton); if ($prevbutton) { - $userformman->next_not_empty_page(false); - $paramurl['formpage'] = $userformman->get_nextpage(); - $paramurl['overflowpage'] = $userformman->get_overflowpage(); + $submissionformman->next_not_empty_page(false); + $paramurl['formpage'] = $submissionformman->get_nextpage(); + $paramurl['overflowpage'] = $submissionformman->get_overflowpage(); $redirecturl = new \moodle_url('/mod/surveypro/view.php', $paramurl); redirect($redirecturl); // Redirect to the first non empty page. } // If "next" button has been pressed, redirect. - $nextbutton = isset($userformman->formdata->nextbutton); + $nextbutton = isset($submissionformman->formdata->nextbutton); if ($nextbutton) { - $userformman->next_not_empty_page(true); - $paramurl['formpage'] = $userformman->get_nextpage(); - $paramurl['overflowpage'] = $userformman->get_overflowpage(); + $submissionformman->next_not_empty_page(true); + $paramurl['formpage'] = $submissionformman->get_nextpage(); + $paramurl['overflowpage'] = $submissionformman->get_overflowpage(); $redirecturl = new \moodle_url('/mod/surveypro/view.php', $paramurl); redirect($redirecturl); // Redirect to the first non empty page. } // Surveypro has been submitted. Notify people. - $userformman->notifypeople(); + $submissionformman->notifypeople(); // If none redirected you, reload THE RIGHT page WITHOUT $paramurl['mode']. // This is necessary otherwise if the user switches language using the corresponding menu @@ -289,9 +283,9 @@ // instead of remaining in the view submissions page. $paramurl = []; $paramurl['s'] = $surveypro->id; - // $paramurl['responsestatus'] = $userformman->get_responsestatus(); - $paramurl['justsubmitted'] = 1 + $userformman->get_userdeservesthanks(); - $paramurl['formview'] = $userformman->get_mode(); // In which way am I using this form? + // $paramurl['responsestatus'] = $submissionformman->get_responsestatus(); + $paramurl['justsubmitted'] = 1 + $submissionformman->get_userdeservesthanks(); + $paramurl['formview'] = $submissionformman->get_mode(); // In which way am I using this form? $paramurl['section'] = 'submissionslist'; $redirecturl = new \moodle_url('/mod/surveypro/view.php', $paramurl); redirect($redirecturl); @@ -344,28 +338,28 @@ $actionbar = new \mod_surveypro\output\action_bar($cm, $context, $surveypro); echo $actionbar->draw_view_action_bar(); - $userformman->noitem_stopexecution(); - $userformman->nomoresubmissions_stopexecution(); - $userformman->warning_submission_copy(); - $userformman->display_page_x_of_y(); + $submissionformman->noitem_stopexecution(); + $submissionformman->nomoresubmissions_stopexecution(); + $submissionformman->warning_submission_copy(); + $submissionformman->display_page_x_of_y(); // Begin of: calculate prefill for fields and prepare standard editors and filemanager. // If sumission already exists. - $prefill = $userformman->get_prefill_data(); - $prefill['formpage'] = $userformman->get_formpage(); + $prefill = $submissionformman->get_prefill_data(); + $prefill['formpage'] = $submissionformman->get_formpage(); // End of: calculate prefill for fields and prepare standard editors and filemanager. $userform->set_data($prefill); $userform->display(); - // If surveypro is multipage and $userformman->tabpage == SURVEYPRO_READONLYMODE. + // If surveypro is multipage and $submissionformman->tabpage == SURVEYPRO_READONLYMODE. // I need to add navigation buttons manually // Because the surveypro is not displayed as a form but as a simple list of graphic user items. - $userformman->add_readonly_browsing_buttons(); + $submissionformman->add_readonly_browsing_buttons(); } // MARK searchsubmissions. -if ($section == 'searchsubmissions') { // It was view_search.php +if ($section == 'searchsubmissions') { // Get additional specific params. $formpage = optional_param('formpage', 1, PARAM_INT); // Form page number. @@ -375,7 +369,7 @@ // Calculations. mod_surveypro\utility_mform::register_form_elements(); - $submissionsearchman = new submissions_search($cm, $context, $surveypro); + $submissionsearchman = new view_submissionsearch($cm, $context, $surveypro); // Begin of: define $searchform return url. $paramurl = ['s' => $cm->instance, 'section' => 'searchsubmissions'];