Merge branch 'wip-MDL-62796-master' of git://github.com/marinaglancy/moodle
[moodle.git] / user / profile / definelib.php
blobdabf9a9b617f41fdc6200343035bcf15a6d323ca
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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/>.
17 /**
18 * This file contains the profile_define_base class.
20 * @package core_user
21 * @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 /**
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 {
33 /**
34 * Prints out the form snippet for creating or editing a profile field
35 * @param moodleform $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);
45 /**
46 * Prints out the form snippet for the part of creating or editing a profile field common to all data types.
48 * @param moodleform $form instance of the moodleform class
50 public function define_form_common(&$form) {
52 $strrequired = get_string('required');
54 $form->addElement('text', 'shortname', get_string('profileshortname', 'admin'), 'maxlength="100" size="25"');
55 $form->addRule('shortname', $strrequired, 'required', null, 'client');
56 $form->setType('shortname', PARAM_ALPHANUM);
58 $form->addElement('text', 'name', get_string('profilename', 'admin'), 'size="50"');
59 $form->addRule('name', $strrequired, 'required', null, 'client');
60 $form->setType('name', PARAM_TEXT);
62 $form->addElement('editor', 'description', get_string('profiledescription', 'admin'), null, null);
64 $form->addElement('selectyesno', 'required', get_string('profilerequired', 'admin'));
66 $form->addElement('selectyesno', 'locked', get_string('profilelocked', 'admin'));
68 $form->addElement('selectyesno', 'forceunique', get_string('profileforceunique', 'admin'));
70 $form->addElement('selectyesno', 'signup', get_string('profilesignup', 'admin'));
72 $choices = array();
73 $choices[PROFILE_VISIBLE_NONE] = get_string('profilevisiblenone', 'admin');
74 $choices[PROFILE_VISIBLE_PRIVATE] = get_string('profilevisibleprivate', 'admin');
75 $choices[PROFILE_VISIBLE_ALL] = get_string('profilevisibleall', 'admin');
76 $form->addElement('select', 'visible', get_string('profilevisible', 'admin'), $choices);
77 $form->addHelpButton('visible', 'profilevisible', 'admin');
78 $form->setDefault('visible', PROFILE_VISIBLE_ALL);
80 $choices = profile_list_categories();
81 $form->addElement('select', 'categoryid', get_string('profilecategory', 'admin'), $choices);
84 /**
85 * Prints out the form snippet for the part of creating or editing a profile field specific to the current data type.
86 * @param moodleform $form instance of the moodleform class
88 public function define_form_specific($form) {
89 // Do nothing - overwrite if necessary.
92 /**
93 * Validate the data from the add/edit profile field form.
95 * Generally this method should not be overwritten by child classes.
97 * @param stdClass|array $data from the add/edit profile field form
98 * @param array $files
99 * @return array associative array of error messages
101 public function define_validate($data, $files) {
103 $data = (object)$data;
104 $err = array();
106 $err += $this->define_validate_common($data, $files);
107 $err += $this->define_validate_specific($data, $files);
109 return $err;
113 * Validate the data from the add/edit profile field form that is common to all data types.
115 * Generally this method should not be overwritten by child classes.
117 * @param stdClass|array $data from the add/edit profile field form
118 * @param array $files
119 * @return array associative array of error messages
121 public function define_validate_common($data, $files) {
122 global $DB;
124 $err = array();
126 // Check the shortname was not truncated by cleaning.
127 if (empty($data->shortname)) {
128 $err['shortname'] = get_string('required');
130 } else {
131 // Fetch field-record from DB.
132 $field = $DB->get_record('user_info_field', array('shortname' => $data->shortname));
133 // Check the shortname is unique.
134 if ($field and $field->id <> $data->id) {
135 $err['shortname'] = get_string('profileshortnamenotunique', 'admin');
137 // NOTE: since 2.0 the shortname may collide with existing fields in $USER because we load these fields into
138 // $USER->profile array instead.
141 // No further checks necessary as the form class will take care of it.
142 return $err;
146 * Validate the data from the add/edit profile field form
147 * that is specific to the current data type
148 * @param array $data
149 * @param array $files
150 * @return array associative array of error messages
152 public function define_validate_specific($data, $files) {
153 // Do nothing - overwrite if necessary.
154 return array();
158 * Alter form based on submitted or existing data
159 * @param moodleform $mform
161 public function define_after_data(&$mform) {
162 // Do nothing - overwrite if necessary.
166 * Add a new profile field or save changes to current field
167 * @param array|stdClass $data from the add/edit profile field form
169 public function define_save($data) {
170 global $DB;
172 $data = $this->define_save_preprocess($data); // Hook for child classes.
174 $old = false;
175 if (!empty($data->id)) {
176 $old = $DB->get_record('user_info_field', array('id' => (int)$data->id));
179 // Check to see if the category has changed.
180 if (!$old or $old->categoryid != $data->categoryid) {
181 $data->sortorder = $DB->count_records('user_info_field', array('categoryid' => $data->categoryid)) + 1;
184 if (empty($data->id)) {
185 unset($data->id);
186 $data->id = $DB->insert_record('user_info_field', $data);
187 } else {
188 $DB->update_record('user_info_field', $data);
191 $field = $DB->get_record('user_info_field', array('id' => $data->id));
192 if ($old) {
193 \core\event\user_info_field_updated::create_from_field($field)->trigger();
194 } else {
195 \core\event\user_info_field_created::create_from_field($field)->trigger();
200 * Preprocess data from the add/edit profile field form before it is saved.
202 * This method is a hook for the child classes to overwrite.
204 * @param array|stdClass $data from the add/edit profile field form
205 * @return array|stdClass processed data object
207 public function define_save_preprocess($data) {
208 // Do nothing - overwrite if necessary.
209 return $data;
213 * Provides a method by which we can allow the default data in profile_define_* to use an editor
215 * This should return an array of editor names (which will need to be formatted/cleaned)
217 * @return array
219 public function define_editors() {
220 return array();
227 * Reorder the profile fields within a given category starting at the field at the given startorder.
229 function profile_reorder_fields() {
230 global $DB;
232 if ($categories = $DB->get_records('user_info_category')) {
233 foreach ($categories as $category) {
234 $i = 1;
235 if ($fields = $DB->get_records('user_info_field', array('categoryid' => $category->id), 'sortorder ASC')) {
236 foreach ($fields as $field) {
237 $f = new stdClass();
238 $f->id = $field->id;
239 $f->sortorder = $i++;
240 $DB->update_record('user_info_field', $f);
248 * Reorder the profile categoriess starting at the category at the given startorder.
250 function profile_reorder_categories() {
251 global $DB;
253 $i = 1;
254 if ($categories = $DB->get_records('user_info_category', null, 'sortorder ASC')) {
255 foreach ($categories as $cat) {
256 $c = new stdClass();
257 $c->id = $cat->id;
258 $c->sortorder = $i++;
259 $DB->update_record('user_info_category', $c);
265 * Delete a profile category
266 * @param int $id of the category to be deleted
267 * @return bool success of operation
269 function profile_delete_category($id) {
270 global $DB;
272 // Retrieve the category.
273 if (!$category = $DB->get_record('user_info_category', array('id' => $id))) {
274 print_error('invalidcategoryid');
277 if (!$categories = $DB->get_records('user_info_category', null, 'sortorder ASC')) {
278 print_error('nocate', 'debug');
281 unset($categories[$category->id]);
283 if (!count($categories)) {
284 return false; // We can not delete the last category.
287 // Does the category contain any fields.
288 if ($DB->count_records('user_info_field', array('categoryid' => $category->id))) {
289 if (array_key_exists($category->sortorder - 1, $categories)) {
290 $newcategory = $categories[$category->sortorder - 1];
291 } else if (array_key_exists($category->sortorder + 1, $categories)) {
292 $newcategory = $categories[$category->sortorder + 1];
293 } else {
294 $newcategory = reset($categories); // Get first category if sortorder broken.
297 $sortorder = $DB->count_records('user_info_field', array('categoryid' => $newcategory->id)) + 1;
299 if ($fields = $DB->get_records('user_info_field', array('categoryid' => $category->id), 'sortorder ASC')) {
300 foreach ($fields as $field) {
301 $f = new stdClass();
302 $f->id = $field->id;
303 $f->sortorder = $sortorder++;
304 $f->categoryid = $newcategory->id;
305 if ($DB->update_record('user_info_field', $f)) {
306 $field->sortorder = $f->sortorder;
307 $field->categoryid = $f->categoryid;
308 \core\event\user_info_field_updated::create_from_field($field)->trigger();
314 // Finally we get to delete the category.
315 $DB->delete_records('user_info_category', array('id' => $category->id));
316 profile_reorder_categories();
318 \core\event\user_info_category_deleted::create_from_category($category)->trigger();
320 return true;
324 * Deletes a profile field.
325 * @param int $id
327 function profile_delete_field($id) {
328 global $DB;
330 // Remove any user data associated with this field.
331 if (!$DB->delete_records('user_info_data', array('fieldid' => $id))) {
332 print_error('cannotdeletecustomfield');
335 // Note: Any availability conditions that depend on this field will remain,
336 // but show the field as missing until manually corrected to something else.
338 // Need to rebuild course cache to update the info.
339 rebuild_course_cache(0, true);
341 // Prior to the delete, pull the record for the event.
342 $field = $DB->get_record('user_info_field', array('id' => $id));
344 // Try to remove the record from the database.
345 $DB->delete_records('user_info_field', array('id' => $id));
347 \core\event\user_info_field_deleted::create_from_field($field)->trigger();
349 // Reorder the remaining fields in the same category.
350 profile_reorder_fields();
354 * Change the sort order of a field
356 * @param int $id of the field
357 * @param string $move direction of move
358 * @return bool success of operation
360 function profile_move_field($id, $move) {
361 global $DB;
363 // Get the field object.
364 if (!$field = $DB->get_record('user_info_field', array('id' => $id))) {
365 return false;
367 // Count the number of fields in this category.
368 $fieldcount = $DB->count_records('user_info_field', array('categoryid' => $field->categoryid));
370 // Calculate the new sortorder.
371 if ( ($move == 'up') and ($field->sortorder > 1)) {
372 $neworder = $field->sortorder - 1;
373 } else if (($move == 'down') and ($field->sortorder < $fieldcount)) {
374 $neworder = $field->sortorder + 1;
375 } else {
376 return false;
379 // Retrieve the field object that is currently residing in the new position.
380 $params = array('categoryid' => $field->categoryid, 'sortorder' => $neworder);
381 if ($swapfield = $DB->get_record('user_info_field', $params)) {
383 // Swap the sortorders.
384 $swapfield->sortorder = $field->sortorder;
385 $field->sortorder = $neworder;
387 // Update the field records.
388 $DB->update_record('user_info_field', $field);
389 $DB->update_record('user_info_field', $swapfield);
391 \core\event\user_info_field_updated::create_from_field($field)->trigger();
392 \core\event\user_info_field_updated::create_from_field($swapfield)->trigger();
395 profile_reorder_fields();
396 return true;
400 * Change the sort order of a category.
402 * @param int $id of the category
403 * @param string $move direction of move
404 * @return bool success of operation
406 function profile_move_category($id, $move) {
407 global $DB;
408 // Get the category object.
409 if (!($category = $DB->get_record('user_info_category', array('id' => $id)))) {
410 return false;
413 // Count the number of categories.
414 $categorycount = $DB->count_records('user_info_category');
416 // Calculate the new sortorder.
417 if (($move == 'up') and ($category->sortorder > 1)) {
418 $neworder = $category->sortorder - 1;
419 } else if (($move == 'down') and ($category->sortorder < $categorycount)) {
420 $neworder = $category->sortorder + 1;
421 } else {
422 return false;
425 // Retrieve the category object that is currently residing in the new position.
426 if ($swapcategory = $DB->get_record('user_info_category', array('sortorder' => $neworder))) {
428 // Swap the sortorders.
429 $swapcategory->sortorder = $category->sortorder;
430 $category->sortorder = $neworder;
432 // Update the category records.
433 $DB->update_record('user_info_category', $category);
434 $DB->update_record('user_info_category', $swapcategory);
436 \core\event\user_info_category_updated::create_from_category($category)->trigger();
437 \core\event\user_info_category_updated::create_from_category($swapcategory)->trigger();
439 return true;
442 return false;
446 * Retrieve a list of all the available data types
447 * @return array a list of the datatypes suitable to use in a select statement
449 function profile_list_datatypes() {
450 $datatypes = array();
452 $plugins = core_component::get_plugin_list('profilefield');
453 foreach ($plugins as $type => $unused) {
454 $datatypes[$type] = get_string('pluginname', 'profilefield_'.$type);
456 asort($datatypes);
458 return $datatypes;
462 * Retrieve a list of categories and ids suitable for use in a form
463 * @return array
465 function profile_list_categories() {
466 global $DB;
467 $categories = $DB->get_records_menu('user_info_category', null, 'sortorder ASC', 'id, name');
468 return array_map('format_string', $categories);
473 * Edit a category
475 * @param int $id
476 * @param string $redirect
478 function profile_edit_category($id, $redirect) {
479 global $DB, $OUTPUT, $CFG;
481 require_once($CFG->dirroot.'/user/profile/index_category_form.php');
482 $categoryform = new category_form();
484 if ($category = $DB->get_record('user_info_category', array('id' => $id))) {
485 $categoryform->set_data($category);
488 if ($categoryform->is_cancelled()) {
489 redirect($redirect);
490 } else {
491 if ($data = $categoryform->get_data()) {
492 if (empty($data->id)) {
493 unset($data->id);
494 $data->sortorder = $DB->count_records('user_info_category') + 1;
495 $data->id = $DB->insert_record('user_info_category', $data, true);
497 $createdcategory = $DB->get_record('user_info_category', array('id' => $data->id));
498 \core\event\user_info_category_created::create_from_category($createdcategory)->trigger();
499 } else {
500 $DB->update_record('user_info_category', $data);
502 $updatedcateogry = $DB->get_record('user_info_category', array('id' => $data->id));
503 \core\event\user_info_category_updated::create_from_category($updatedcateogry)->trigger();
505 profile_reorder_categories();
506 redirect($redirect);
510 if (empty($id)) {
511 $strheading = get_string('profilecreatenewcategory', 'admin');
512 } else {
513 $strheading = get_string('profileeditcategory', 'admin', format_string($category->name));
516 // Print the page.
517 echo $OUTPUT->header();
518 echo $OUTPUT->heading($strheading);
519 $categoryform->display();
520 echo $OUTPUT->footer();
521 die;
527 * Edit a profile field.
529 * @param int $id
530 * @param string $datatype
531 * @param string $redirect
533 function profile_edit_field($id, $datatype, $redirect) {
534 global $CFG, $DB, $OUTPUT, $PAGE;
536 if (!$field = $DB->get_record('user_info_field', array('id' => $id))) {
537 $field = new stdClass();
538 $field->datatype = $datatype;
539 $field->description = '';
540 $field->descriptionformat = FORMAT_HTML;
541 $field->defaultdata = '';
542 $field->defaultdataformat = FORMAT_HTML;
545 // Clean and prepare description for the editor.
546 $field->description = clean_text($field->description, $field->descriptionformat);
547 $field->description = array('text' => $field->description, 'format' => $field->descriptionformat, 'itemid' => 0);
549 require_once($CFG->dirroot.'/user/profile/index_field_form.php');
550 $fieldform = new field_form(null, $field->datatype);
552 // Convert the data format for.
553 if (is_array($fieldform->editors())) {
554 foreach ($fieldform->editors() as $editor) {
555 if (isset($field->$editor)) {
556 $field->$editor = clean_text($field->$editor, $field->{$editor.'format'});
557 $field->$editor = array('text' => $field->$editor, 'format' => $field->{$editor.'format'}, 'itemid' => 0);
562 $fieldform->set_data($field);
564 if ($fieldform->is_cancelled()) {
565 redirect($redirect);
567 } else {
568 if ($data = $fieldform->get_data()) {
569 require_once($CFG->dirroot.'/user/profile/field/'.$datatype.'/define.class.php');
570 $newfield = 'profile_define_'.$datatype;
571 $formfield = new $newfield();
573 // Collect the description and format back into the proper data structure from the editor.
574 // Note: This field will ALWAYS be an editor.
575 $data->descriptionformat = $data->description['format'];
576 $data->description = $data->description['text'];
578 // Check whether the default data is an editor, this is (currently) only the textarea field type.
579 if (is_array($data->defaultdata) && array_key_exists('text', $data->defaultdata)) {
580 // Collect the default data and format back into the proper data structure from the editor.
581 $data->defaultdataformat = $data->defaultdata['format'];
582 $data->defaultdata = $data->defaultdata['text'];
585 // Convert the data format for.
586 if (is_array($fieldform->editors())) {
587 foreach ($fieldform->editors() as $editor) {
588 if (isset($field->$editor)) {
589 $field->{$editor.'format'} = $field->{$editor}['format'];
590 $field->$editor = $field->{$editor}['text'];
595 $formfield->define_save($data);
596 profile_reorder_fields();
597 profile_reorder_categories();
598 redirect($redirect);
601 $datatypes = profile_list_datatypes();
603 if (empty($id)) {
604 $strheading = get_string('profilecreatenewfield', 'admin', $datatypes[$datatype]);
605 } else {
606 $strheading = get_string('profileeditfield', 'admin', format_string($field->name));
609 // Print the page.
610 $PAGE->navbar->add($strheading);
611 echo $OUTPUT->header();
612 echo $OUTPUT->heading($strheading);
613 $fieldform->display();
614 echo $OUTPUT->footer();
615 die;