2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * This file contains the profile_define_base class.
21 * @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 * Class profile_define_base
28 * @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
29 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 class profile_define_base
{
34 * Prints out the form snippet for creating or editing a profile field
35 * @param MoodleQuickForm $form instance of the moodleform class
37 public function define_form(&$form) {
38 $form->addElement('header', '_commonsettings', get_string('profilecommonsettings', 'admin'));
39 $this->define_form_common($form);
41 $form->addElement('header', '_specificsettings', get_string('profilespecificsettings', 'admin'));
42 $this->define_form_specific($form);
46 * Prints out the form snippet for the part of creating or editing a profile field common to all data types.
48 * @param MoodleQuickForm $form instance of the moodleform class
50 public function define_form_common(&$form) {
52 $strrequired = get_string('required');
54 // Accepted values for 'shortname' would follow [a-zA-Z0-9_] pattern,
55 // but we are accepting any PARAM_TEXT value here,
56 // and checking [a-zA-Z0-9_] pattern in define_validate_common() function to throw an error when needed.
57 $form->addElement('text', 'shortname', get_string('profileshortname', 'admin'), 'maxlength="100" size="25"');
58 $form->addRule('shortname', $strrequired, 'required', null, 'client');
59 $form->setType('shortname', PARAM_TEXT
);
61 $form->addElement('text', 'name', get_string('profilename', 'admin'), 'size="50"');
62 $form->addRule('name', $strrequired, 'required', null, 'client');
63 $form->setType('name', PARAM_TEXT
);
65 $form->addElement('editor', 'description', get_string('profiledescription', 'admin'), null, null);
67 $form->addElement('selectyesno', 'required', get_string('profilerequired', 'admin'));
69 $form->addElement('selectyesno', 'locked', get_string('profilelocked', 'admin'));
71 $form->addElement('selectyesno', 'forceunique', get_string('profileforceunique', 'admin'));
73 $form->addElement('selectyesno', 'signup', get_string('profilesignup', 'admin'));
76 $choices[PROFILE_VISIBLE_NONE
] = get_string('profilevisiblenone', 'admin');
77 $choices[PROFILE_VISIBLE_PRIVATE
] = get_string('profilevisibleprivate', 'admin');
78 $choices[PROFILE_VISIBLE_TEACHERS
] = get_string('profilevisibleteachers', 'admin');
79 $choices[PROFILE_VISIBLE_ALL
] = get_string('profilevisibleall', 'admin');
81 $form->addElement('select', 'visible', get_string('profilevisible', 'admin'), $choices);
82 $form->addHelpButton('visible', 'profilevisible', 'admin');
83 $form->setDefault('visible', PROFILE_VISIBLE_ALL
);
85 $choices = profile_list_categories();
86 $form->addElement('select', 'categoryid', get_string('profilecategory', 'admin'), $choices);
90 * Prints out the form snippet for the part of creating or editing a profile field specific to the current data type.
91 * @param MoodleQuickForm $form instance of the moodleform class
93 public function define_form_specific($form) {
94 // Do nothing - overwrite if necessary.
98 * Validate the data from the add/edit profile field form.
100 * Generally this method should not be overwritten by child classes.
102 * @param stdClass|array $data from the add/edit profile field form
103 * @param array $files
104 * @return array associative array of error messages
106 public function define_validate($data, $files) {
108 $data = (object)$data;
111 $err +
= $this->define_validate_common($data, $files);
112 $err +
= $this->define_validate_specific($data, $files);
118 * Validate the data from the add/edit profile field form that is common to all data types.
120 * Generally this method should not be overwritten by child classes.
122 * @param stdClass|array $data from the add/edit profile field form
123 * @param array $files
124 * @return array associative array of error messages
126 public function define_validate_common($data, $files) {
131 // Check the shortname was not truncated by cleaning.
132 if (empty($data->shortname
)) {
133 $err['shortname'] = get_string('required');
136 // Check allowed pattern (numbers, letters and underscore).
137 if (!preg_match('/^[a-zA-Z0-9_]+$/', $data->shortname
)) {
138 $err['shortname'] = get_string('profileshortnameinvalid', 'admin');
140 // Fetch field-record from DB.
141 $field = profile_get_custom_field_data_by_shortname($data->shortname
);
142 // Check the shortname is unique.
143 if ($field and $field->id
<> $data->id
) {
144 $err['shortname'] = get_string('profileshortnamenotunique', 'admin');
146 // NOTE: since 2.0 the shortname may collide with existing fields in $USER because we load these fields into
147 // $USER->profile array instead.
151 // No further checks necessary as the form class will take care of it.
156 * Validate the data from the add/edit profile field form
157 * that is specific to the current data type
159 * @param array $files
160 * @return array associative array of error messages
162 public function define_validate_specific($data, $files) {
163 // Do nothing - overwrite if necessary.
168 * Alter form based on submitted or existing data
169 * @param MoodleQuickForm $mform
171 public function define_after_data(&$mform) {
172 // Do nothing - overwrite if necessary.
176 * Add a new profile field or save changes to current field
177 * @param array|stdClass $data from the add/edit profile field form
179 public function define_save($data) {
182 $data = $this->define_save_preprocess($data); // Hook for child classes.
185 if (!empty($data->id
)) {
186 $old = $DB->get_record('user_info_field', array('id' => (int)$data->id
));
189 // Check to see if the category has changed.
190 if (!$old or $old->categoryid
!= $data->categoryid
) {
191 $data->sortorder
= $DB->count_records('user_info_field', array('categoryid' => $data->categoryid
)) +
1;
194 if (empty($data->id
)) {
196 $data->id
= $DB->insert_record('user_info_field', $data);
198 $DB->update_record('user_info_field', $data);
201 $field = $DB->get_record('user_info_field', array('id' => $data->id
));
203 \core\event\user_info_field_updated
::create_from_field($field)->trigger();
205 \core\event\user_info_field_created
::create_from_field($field)->trigger();
207 profile_purge_user_fields_cache();
211 * Preprocess data from the add/edit profile field form before it is saved.
213 * This method is a hook for the child classes to overwrite.
215 * @param array|stdClass $data from the add/edit profile field form
216 * @return array|stdClass processed data object
218 public function define_save_preprocess($data) {
219 // Do nothing - overwrite if necessary.
224 * Provides a method by which we can allow the default data in profile_define_* to use an editor
226 * This should return an array of editor names (which will need to be formatted/cleaned)
230 public function define_editors() {
238 * Reorder the profile fields within a given category starting at the field at the given startorder.
240 function profile_reorder_fields() {
243 if ($categories = $DB->get_records('user_info_category')) {
244 foreach ($categories as $category) {
246 if ($fields = $DB->get_records('user_info_field', array('categoryid' => $category->id
), 'sortorder ASC')) {
247 foreach ($fields as $field) {
250 $f->sortorder
= $i++
;
251 $DB->update_record('user_info_field', $f);
255 profile_purge_user_fields_cache();
260 * Reorder the profile categoriess starting at the category at the given startorder.
262 function profile_reorder_categories() {
266 if ($categories = $DB->get_records('user_info_category', null, 'sortorder ASC')) {
267 foreach ($categories as $cat) {
270 $c->sortorder
= $i++
;
271 $DB->update_record('user_info_category', $c);
273 profile_purge_user_fields_cache();
278 * Delete a profile category
279 * @param int $id of the category to be deleted
280 * @return bool success of operation
282 function profile_delete_category($id) {
285 // Retrieve the category.
286 if (!$category = $DB->get_record('user_info_category', array('id' => $id))) {
287 print_error('invalidcategoryid');
290 if (!$categories = $DB->get_records('user_info_category', null, 'sortorder ASC')) {
291 print_error('nocate', 'debug');
294 unset($categories[$category->id
]);
296 if (!count($categories)) {
297 return false; // We can not delete the last category.
300 // Does the category contain any fields.
301 if ($DB->count_records('user_info_field', array('categoryid' => $category->id
))) {
302 if (array_key_exists($category->sortorder
- 1, $categories)) {
303 $newcategory = $categories[$category->sortorder
- 1];
304 } else if (array_key_exists($category->sortorder +
1, $categories)) {
305 $newcategory = $categories[$category->sortorder +
1];
307 $newcategory = reset($categories); // Get first category if sortorder broken.
310 $sortorder = $DB->count_records('user_info_field', array('categoryid' => $newcategory->id
)) +
1;
312 if ($fields = $DB->get_records('user_info_field', array('categoryid' => $category->id
), 'sortorder ASC')) {
313 foreach ($fields as $field) {
316 $f->sortorder
= $sortorder++
;
317 $f->categoryid
= $newcategory->id
;
318 if ($DB->update_record('user_info_field', $f)) {
319 $field->sortorder
= $f->sortorder
;
320 $field->categoryid
= $f->categoryid
;
321 \core\event\user_info_field_updated
::create_from_field($field)->trigger();
327 // Finally we get to delete the category.
328 $DB->delete_records('user_info_category', array('id' => $category->id
));
329 profile_reorder_categories();
331 \core\event\user_info_category_deleted
::create_from_category($category)->trigger();
332 profile_purge_user_fields_cache();
338 * Deletes a profile field.
341 function profile_delete_field($id) {
344 // Remove any user data associated with this field.
345 if (!$DB->delete_records('user_info_data', array('fieldid' => $id))) {
346 print_error('cannotdeletecustomfield');
349 // Note: Any availability conditions that depend on this field will remain,
350 // but show the field as missing until manually corrected to something else.
352 // Need to rebuild course cache to update the info.
353 rebuild_course_cache(0, true);
355 // Prior to the delete, pull the record for the event.
356 $field = $DB->get_record('user_info_field', array('id' => $id));
358 // Try to remove the record from the database.
359 $DB->delete_records('user_info_field', array('id' => $id));
361 \core\event\user_info_field_deleted
::create_from_field($field)->trigger();
362 profile_purge_user_fields_cache();
364 // Reorder the remaining fields in the same category.
365 profile_reorder_fields();
369 * Change the sort order of a field
371 * @param int $id of the field
372 * @param string $move direction of move
373 * @return bool success of operation
375 function profile_move_field($id, $move) {
378 // Get the field object.
379 if (!$field = $DB->get_record('user_info_field', array('id' => $id))) {
382 // Count the number of fields in this category.
383 $fieldcount = $DB->count_records('user_info_field', array('categoryid' => $field->categoryid
));
385 // Calculate the new sortorder.
386 if ( ($move == 'up') and ($field->sortorder
> 1)) {
387 $neworder = $field->sortorder
- 1;
388 } else if (($move == 'down') and ($field->sortorder
< $fieldcount)) {
389 $neworder = $field->sortorder +
1;
394 // Retrieve the field object that is currently residing in the new position.
395 $params = array('categoryid' => $field->categoryid
, 'sortorder' => $neworder);
396 if ($swapfield = $DB->get_record('user_info_field', $params)) {
398 // Swap the sortorders.
399 $swapfield->sortorder
= $field->sortorder
;
400 $field->sortorder
= $neworder;
402 // Update the field records.
403 $DB->update_record('user_info_field', $field);
404 $DB->update_record('user_info_field', $swapfield);
406 \core\event\user_info_field_updated
::create_from_field($field)->trigger();
407 \core\event\user_info_field_updated
::create_from_field($swapfield)->trigger();
410 profile_reorder_fields();
415 * Change the sort order of a category.
417 * @param int $id of the category
418 * @param string $move direction of move
419 * @return bool success of operation
421 function profile_move_category($id, $move) {
423 // Get the category object.
424 if (!($category = $DB->get_record('user_info_category', array('id' => $id)))) {
428 // Count the number of categories.
429 $categorycount = $DB->count_records('user_info_category');
431 // Calculate the new sortorder.
432 if (($move == 'up') and ($category->sortorder
> 1)) {
433 $neworder = $category->sortorder
- 1;
434 } else if (($move == 'down') and ($category->sortorder
< $categorycount)) {
435 $neworder = $category->sortorder +
1;
440 // Retrieve the category object that is currently residing in the new position.
441 if ($swapcategory = $DB->get_record('user_info_category', array('sortorder' => $neworder))) {
443 // Swap the sortorders.
444 $swapcategory->sortorder
= $category->sortorder
;
445 $category->sortorder
= $neworder;
447 // Update the category records.
448 $DB->update_record('user_info_category', $category);
449 $DB->update_record('user_info_category', $swapcategory);
451 \core\event\user_info_category_updated
::create_from_category($category)->trigger();
452 \core\event\user_info_category_updated
::create_from_category($swapcategory)->trigger();
453 profile_purge_user_fields_cache();
462 * Retrieve a list of all the available data types
463 * @return array a list of the datatypes suitable to use in a select statement
465 function profile_list_datatypes() {
466 $datatypes = array();
468 $plugins = core_component
::get_plugin_list('profilefield');
469 foreach ($plugins as $type => $unused) {
470 $datatypes[$type] = get_string('pluginname', 'profilefield_'.$type);
478 * Retrieve a list of categories and ids suitable for use in a form
481 function profile_list_categories() {
483 $categories = $DB->get_records_menu('user_info_category', null, 'sortorder ASC', 'id, name');
484 return array_map('format_string', $categories);
492 * @param string $redirect
494 function profile_edit_category($id, $redirect) {
495 global $DB, $OUTPUT, $CFG;
497 require_once($CFG->dirroot
.'/user/profile/index_category_form.php');
498 $categoryform = new category_form();
500 if ($category = $DB->get_record('user_info_category', array('id' => $id))) {
501 $categoryform->set_data($category);
504 if ($categoryform->is_cancelled()) {
507 if ($data = $categoryform->get_data()) {
508 if (empty($data->id
)) {
510 $data->sortorder
= $DB->count_records('user_info_category') +
1;
511 $data->id
= $DB->insert_record('user_info_category', $data, true);
513 $createdcategory = $DB->get_record('user_info_category', array('id' => $data->id
));
514 \core\event\user_info_category_created
::create_from_category($createdcategory)->trigger();
516 $DB->update_record('user_info_category', $data);
518 $updatedcateogry = $DB->get_record('user_info_category', array('id' => $data->id
));
519 \core\event\user_info_category_updated
::create_from_category($updatedcateogry)->trigger();
521 profile_reorder_categories();
522 profile_purge_user_fields_cache();
528 $strheading = get_string('profilecreatenewcategory', 'admin');
530 $strheading = get_string('profileeditcategory', 'admin', format_string($category->name
));
534 echo $OUTPUT->header();
535 echo $OUTPUT->heading($strheading);
536 $categoryform->display();
537 echo $OUTPUT->footer();
544 * Edit a profile field.
547 * @param string $datatype
548 * @param string $redirect
550 function profile_edit_field($id, $datatype, $redirect) {
551 global $CFG, $DB, $OUTPUT, $PAGE;
553 if (!$field = $DB->get_record('user_info_field', array('id' => $id))) {
554 $field = new stdClass();
555 $field->datatype
= $datatype;
556 $field->description
= '';
557 $field->descriptionformat
= FORMAT_HTML
;
558 $field->defaultdata
= '';
559 $field->defaultdataformat
= FORMAT_HTML
;
562 // Clean and prepare description for the editor.
563 $field->description
= clean_text($field->description
, $field->descriptionformat
);
564 $field->description
= array('text' => $field->description
, 'format' => $field->descriptionformat
, 'itemid' => 0);
566 require_once($CFG->dirroot
.'/user/profile/index_field_form.php');
567 $fieldform = new field_form(null, $field->datatype
);
569 // Convert the data format for.
570 if (is_array($fieldform->editors())) {
571 foreach ($fieldform->editors() as $editor) {
572 if (isset($field->$editor)) {
573 $field->$editor = clean_text($field->$editor, $field->{$editor.'format'});
574 $field->$editor = array('text' => $field->$editor, 'format' => $field->{$editor.'format'}, 'itemid' => 0);
579 $fieldform->set_data($field);
581 if ($fieldform->is_cancelled()) {
585 if ($data = $fieldform->get_data()) {
586 require_once($CFG->dirroot
.'/user/profile/field/'.$datatype.'/define.class.php');
587 $newfield = 'profile_define_'.$datatype;
588 /** @var profile_define_base $formfield */
589 $formfield = new $newfield();
591 // Collect the description and format back into the proper data structure from the editor.
592 // Note: This field will ALWAYS be an editor.
593 $data->descriptionformat
= $data->description
['format'];
594 $data->description
= $data->description
['text'];
596 // Check whether the default data is an editor, this is (currently) only the textarea field type.
597 if (is_array($data->defaultdata
) && array_key_exists('text', $data->defaultdata
)) {
598 // Collect the default data and format back into the proper data structure from the editor.
599 $data->defaultdataformat
= $data->defaultdata
['format'];
600 $data->defaultdata
= $data->defaultdata
['text'];
603 // Convert the data format for.
604 if (is_array($fieldform->editors())) {
605 foreach ($fieldform->editors() as $editor) {
606 if (isset($field->$editor)) {
607 $field->{$editor.'format'} = $field->{$editor}['format'];
608 $field->$editor = $field->{$editor}['text'];
613 $formfield->define_save($data);
614 profile_reorder_fields();
615 profile_reorder_categories();
619 $datatypes = profile_list_datatypes();
622 $strheading = get_string('profilecreatenewfield', 'admin', $datatypes[$datatype]);
624 $strheading = get_string('profileeditfield', 'admin', format_string($field->name
));
628 $PAGE->navbar
->add($strheading);
629 echo $OUTPUT->header();
630 echo $OUTPUT->heading($strheading);
631 $fieldform->display();
632 echo $OUTPUT->footer();
638 * Purge the cache for the user profile fields
640 function profile_purge_user_fields_cache() {
641 $cache = \cache
::make_from_params(cache_store
::MODE_REQUEST
, 'core_profile', 'customfields',
642 [], ['simplekeys' => true, 'simpledata' => true]);