on-demand release 3.7dev+
[moodle.git] / lib / tests / behat / behat_data_generators.php
CommitLineData
f0200d14 1<?php
f0200d14
DM
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.
13//
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/>.
16
17/**
18 * Data generators for acceptance testing.
19 *
20 * @package core
21 * @category test
22 * @copyright 2012 David MonllaĆ³
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26// NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.
27
28require_once(__DIR__ . '/../../behat/behat_base.php');
f0200d14
DM
29
30use Behat\Gherkin\Node\TableNode as TableNode;
134494e0 31use Behat\Behat\Tester\Exception\PendingException as PendingException;
f0200d14
DM
32
33/**
34 * Class to set up quickly a Given environment.
35 *
36 * Acceptance tests are block-boxed, so this steps definitions should only
37 * be used to set up the test environment as we are not replicating user steps.
38 *
d2eca4cd 39 * All data generators should be in lib/testing/generator/*, shared between phpunit
f0200d14 40 * and behat and they should be called from here, if possible using the standard
d2eca4cd
DM
41 * 'create_$elementname($options)' and if it's not possible (data generators arguments will not be
42 * always the same) or the element is not suitable to be a data generator, create a
43 * 'process_$elementname($options)' method and use the data generator from there if possible.
f0200d14
DM
44 *
45 * @todo If the available elements list grows too much this class must be split into smaller pieces
46 * @package core
47 * @category test
48 * @copyright 2012 David MonllaĆ³
49 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
50 */
51class behat_data_generators extends behat_base {
52
46ac40cd
DM
53 /**
54 * @var testing_data_generator
55 */
f0200d14
DM
56 protected $datagenerator;
57
58 /**
59 * Each element specifies:
60 * - The data generator sufix used.
61 * - The required fields.
62 * - The mapping between other elements references and database field names.
63 * @var array
64 */
65 protected static $elements = array(
66 'users' => array(
67 'datagenerator' => 'user',
68 'required' => array('username')
69 ),
70 'categories' => array(
71 'datagenerator' => 'category',
72 'required' => array('idnumber'),
73 'switchids' => array('category' => 'parent')
74 ),
75 'courses' => array(
76 'datagenerator' => 'course',
77 'required' => array('shortname'),
78 'switchids' => array('category' => 'category')
79 ),
80 'groups' => array(
81 'datagenerator' => 'group',
82 'required' => array('idnumber', 'course'),
83 'switchids' => array('course' => 'courseid')
84 ),
85 'groupings' => array(
86 'datagenerator' => 'grouping',
87 'required' => array('idnumber', 'course'),
88 'switchids' => array('course' => 'courseid')
89 ),
90 'course enrolments' => array(
91 'datagenerator' => 'enrol_user',
92 'required' => array('user', 'course', 'role'),
93 'switchids' => array('user' => 'userid', 'course' => 'courseid', 'role' => 'roleid')
f0200d14 94 ),
01c10959
DNA
95 'custom field categories' => array(
96 'datagenerator' => 'custom_field_category',
97 'required' => array('name', 'component', 'area', 'itemid'),
98 'switchids' => array()
99 ),
100 'custom fields' => array(
101 'datagenerator' => 'custom_field',
102 'required' => array('name', 'category', 'type', 'shortname'),
103 'switchids' => array()
104 ),
81cd8572
DM
105 'permission overrides' => array(
106 'datagenerator' => 'permission_override',
107 'required' => array('capability', 'permission', 'role', 'contextlevel', 'reference'),
108 'switchids' => array('role' => 'roleid')
109 ),
d2eca4cd 110 'system role assigns' => array(
72ddc05f 111 'datagenerator' => 'system_role_assign',
d2eca4cd
DM
112 'required' => array('user', 'role'),
113 'switchids' => array('user' => 'userid', 'role' => 'roleid')
114 ),
72ddc05f
DM
115 'role assigns' => array(
116 'datagenerator' => 'role_assign',
117 'required' => array('user', 'role', 'contextlevel', 'reference'),
118 'switchids' => array('user' => 'userid', 'role' => 'roleid')
119 ),
a0902967
DM
120 'activities' => array(
121 'datagenerator' => 'activity',
122 'required' => array('activity', 'idnumber', 'course'),
15ace204 123 'switchids' => array('course' => 'course', 'gradecategory' => 'gradecat')
a0902967 124 ),
eb3884e4
TH
125 'blocks' => array(
126 'datagenerator' => 'block_instance',
127 'required' => array('blockname', 'contextlevel', 'reference'),
128 ),
f0200d14
DM
129 'group members' => array(
130 'datagenerator' => 'group_member',
131 'required' => array('user', 'group'),
132 'switchids' => array('user' => 'userid', 'group' => 'groupid')
133 ),
134 'grouping groups' => array(
135 'datagenerator' => 'grouping_group',
136 'required' => array('grouping', 'group'),
137 'switchids' => array('grouping' => 'groupingid', 'group' => 'groupid')
23349a73
DM
138 ),
139 'cohorts' => array(
140 'datagenerator' => 'cohort',
141 'required' => array('idnumber')
702851c0 142 ),
9cc66e86
MG
143 'cohort members' => array(
144 'datagenerator' => 'cohort_member',
145 'required' => array('user', 'cohort'),
146 'switchids' => array('user' => 'userid', 'cohort' => 'cohortid')
147 ),
702851c0
DM
148 'roles' => array(
149 'datagenerator' => 'role',
150 'required' => array('shortname')
15ace204
DW
151 ),
152 'grade categories' => array(
153 'datagenerator' => 'grade_category',
154 'required' => array('fullname', 'course'),
155 'switchids' => array('course' => 'courseid', 'gradecategory' => 'parent')
cfa91962
JO
156 ),
157 'grade items' => array(
158 'datagenerator' => 'grade_item',
159 'required' => array('course'),
160 'switchids' => array('scale' => 'scaleid', 'outcome' => 'outcomeid', 'course' => 'courseid',
161 'gradecategory' => 'categoryid')
162 ),
163 'grade outcomes' => array(
164 'datagenerator' => 'grade_outcome',
165 'required' => array('shortname', 'scale'),
166 'switchids' => array('course' => 'courseid', 'gradecategory' => 'categoryid', 'scale' => 'scaleid')
167 ),
168 'scales' => array(
169 'datagenerator' => 'scale',
170 'required' => array('name', 'scale'),
171 'switchids' => array('course' => 'courseid')
0db16e08
TH
172 ),
173 'question categories' => array(
174 'datagenerator' => 'question_category',
175 'required' => array('name', 'contextlevel', 'reference'),
834cc0ed 176 'switchids' => array('questioncategory' => 'parent')
0db16e08
TH
177 ),
178 'questions' => array(
179 'datagenerator' => 'question',
180 'required' => array('qtype', 'questioncategory', 'name'),
181 'switchids' => array('questioncategory' => 'category', 'user' => 'createdby')
182 ),
9a7e3986
MG
183 'tags' => array(
184 'datagenerator' => 'tag',
185 'required' => array('name')
186 ),
fb3c0fc3
AN
187 'events' => array(
188 'datagenerator' => 'event',
189 'required' => array('name', 'eventtype'),
190 'switchids' => array(
191 'user' => 'userid',
192 'course' => 'courseid',
193 'category' => 'categoryid',
194 )
195 ),
029a3e73 196 'message contacts' => array(
197 'datagenerator' => 'message_contacts',
198 'required' => array('user', 'contact'),
199 'switchids' => array('user' => 'userid', 'contact' => 'contactid')
200 ),
f0200d14
DM
201 );
202
203 /**
204 * Creates the specified element. More info about available elements in http://docs.moodle.org/dev/Acceptance_testing#Fixtures.
205 *
c51c3b55 206 * @Given /^the following "(?P<element_string>(?:[^"]|\\")*)" exist:$/
f0200d14
DM
207 *
208 * @throws Exception
209 * @throws PendingException
210 * @param string $elementname The name of the entity to add
211 * @param TableNode $data
212 */
c51c3b55 213 public function the_following_exist($elementname, TableNode $data) {
f0200d14 214
c29e3e24
DM
215 // Now that we need them require the data generators.
216 require_once(__DIR__ . '/../../testing/generator/lib.php');
217
f0200d14
DM
218 if (empty(self::$elements[$elementname])) {
219 throw new PendingException($elementname . ' data generator is not implemented');
220 }
221
222 $this->datagenerator = testing_util::get_data_generator();
223
224 $elementdatagenerator = self::$elements[$elementname]['datagenerator'];
225 $requiredfields = self::$elements[$elementname]['required'];
226 if (!empty(self::$elements[$elementname]['switchids'])) {
227 $switchids = self::$elements[$elementname]['switchids'];
228 }
229
230 foreach ($data->getHash() as $elementdata) {
231
232 // Check if all the required fields are there.
233 foreach ($requiredfields as $requiredfield) {
234 if (!isset($elementdata[$requiredfield])) {
235 throw new Exception($elementname . ' requires the field ' . $requiredfield . ' to be specified');
236 }
237 }
238
239 // Switch from human-friendly references to ids.
240 if (isset($switchids)) {
241 foreach ($switchids as $element => $field) {
242 $methodname = 'get_' . $element . '_id';
243
244 // Not all the switch fields are required, default vars will be assigned by data generators.
48a3a50a 245 if (isset($elementdata[$element])) {
f0200d14
DM
246 // Temp $id var to avoid problems when $element == $field.
247 $id = $this->{$methodname}($elementdata[$element]);
248 unset($elementdata[$element]);
249 $elementdata[$field] = $id;
250 }
251 }
252 }
253
254 // Preprocess the entities that requires a special treatment.
255 if (method_exists($this, 'preprocess_' . $elementdatagenerator)) {
256 $elementdata = $this->{'preprocess_' . $elementdatagenerator}($elementdata);
257 }
258
259 // Creates element.
260 $methodname = 'create_' . $elementdatagenerator;
261 if (method_exists($this->datagenerator, $methodname)) {
262 // Using data generators directly.
263 $this->datagenerator->{$methodname}($elementdata);
264
d2eca4cd
DM
265 } else if (method_exists($this, 'process_' . $elementdatagenerator)) {
266 // Using an alternative to the direct data generator call.
267 $this->{'process_' . $elementdatagenerator}($elementdata);
f0200d14
DM
268 } else {
269 throw new PendingException($elementname . ' data generator is not implemented');
270 }
271 }
272
273 }
274
275 /**
276 * If password is not set it uses the username.
277 * @param array $data
278 * @return array
279 */
280 protected function preprocess_user($data) {
281 if (!isset($data['password'])) {
282 $data['password'] = $data['username'];
283 }
284 return $data;
285 }
286
5f079af4
MG
287 /**
288 * If contextlevel and reference are specified for cohort, transform them to the contextid.
289 *
290 * @param array $data
291 * @return array
292 */
293 protected function preprocess_cohort($data) {
294 if (isset($data['contextlevel'])) {
295 if (!isset($data['reference'])) {
296 throw new Exception('If field contextlevel is specified, field reference must also be present');
297 }
298 $context = $this->get_context($data['contextlevel'], $data['reference']);
299 unset($data['contextlevel']);
300 unset($data['reference']);
301 $data['contextid'] = $context->id;
302 }
303 return $data;
304 }
305
cfa91962
JO
306 /**
307 * Preprocesses the creation of a grade item. Converts gradetype text to a number.
308 * @param array $data
309 * @return array
310 */
311 protected function preprocess_grade_item($data) {
312 global $CFG;
313 require_once("$CFG->libdir/grade/constants.php");
314
315 if (isset($data['gradetype'])) {
316 $data['gradetype'] = constant("GRADE_TYPE_" . strtoupper($data['gradetype']));
317 }
b13afc36
FM
318
319 if (!empty($data['category']) && !empty($data['courseid'])) {
320 $cat = grade_category::fetch(array('fullname' => $data['category'], 'courseid' => $data['courseid']));
321 if (!$cat) {
322 throw new Exception('Could not resolve category with name "' . $data['category'] . '"');
323 }
324 unset($data['category']);
325 $data['categoryid'] = $cat->id;
326 }
327
cfa91962
JO
328 return $data;
329 }
330
a0902967
DM
331 /**
332 * Adapter to modules generator
333 * @throws Exception Custom exception for test writers
334 * @param array $data
335 * @return void
336 */
337 protected function process_activity($data) {
cfa91962 338 global $DB, $CFG;
a0902967
DM
339
340 // The the_following_exists() method checks that the field exists.
341 $activityname = $data['activity'];
342 unset($data['activity']);
343
cfa91962
JO
344 // Convert scale name into scale id (negative number indicates using scale).
345 if (isset($data['grade']) && strlen($data['grade']) && !is_number($data['grade'])) {
346 $data['grade'] = - $this->get_scale_id($data['grade']);
347 require_once("$CFG->libdir/grade/constants.php");
348
349 if (!isset($data['gradetype'])) {
350 $data['gradetype'] = GRADE_TYPE_SCALE;
351 }
352 }
353
041cf62b
DM
354 // We split $data in the activity $record and the course module $options.
355 $cmoptions = array();
356 $cmcolumns = $DB->get_columns('course_modules');
357 foreach ($cmcolumns as $key => $value) {
358 if (isset($data[$key])) {
359 $cmoptions[$key] = $data[$key];
360 }
361 }
362
a0902967
DM
363 // Custom exception.
364 try {
041cf62b 365 $this->datagenerator->create_module($activityname, $data, $cmoptions);
a0902967
DM
366 } catch (coding_exception $e) {
367 throw new Exception('\'' . $activityname . '\' activity can not be added using this step,' .
368 ' use the step \'I add a "ACTIVITY_OR_RESOURCE_NAME_STRING" to section "SECTION_NUMBER"\' instead');
369 }
eb3884e4
TH
370 }
371
372 /**
373 * Add a block to a page.
374 *
375 * @param array $data should mostly match the fields of the block_instances table.
376 * The block type is specified by blockname.
377 * The parentcontextid is set from contextlevel and reference.
378 * Missing values are filled in by testing_block_generator::prepare_record.
379 * $data is passed to create_block as both $record and $options. Normally
380 * the keys are different, so this is a way to let people set values in either place.
381 */
382 protected function process_block_instance($data) {
383
384 if (empty($data['blockname'])) {
385 throw new Exception('\'blocks\' requires the field \'block\' type to be specified');
386 }
387
388 if (empty($data['contextlevel'])) {
389 throw new Exception('\'blocks\' requires the field \'contextlevel\' to be specified');
390 }
391
392 if (!isset($data['reference'])) {
393 throw new Exception('\'blocks\' requires the field \'reference\' to be specified');
394 }
395
396 $context = $this->get_context($data['contextlevel'], $data['reference']);
397 $data['parentcontextid'] = $context->id;
398
399 // Pass $data as both $record and $options. I think that is unlikely to
400 // cause problems since the relevant key names are different.
401 // $options is not used in most blocks I have seen, but where it is, it is necessary.
402 $this->datagenerator->create_block($data['blockname'], $data, $data);
a0902967 403 }
f0200d14
DM
404
405 /**
406 * Adapter to enrol_user() data generator.
407 * @throws Exception
d2eca4cd 408 * @param array $data
f0200d14
DM
409 * @return void
410 */
d2eca4cd 411 protected function process_enrol_user($data) {
a8a48495 412 global $SITE;
f0200d14
DM
413
414 if (empty($data['roleid'])) {
415 throw new Exception('\'course enrolments\' requires the field \'role\' to be specified');
416 }
417
418 if (!isset($data['userid'])) {
419 throw new Exception('\'course enrolments\' requires the field \'user\' to be specified');
420 }
421
422 if (!isset($data['courseid'])) {
423 throw new Exception('\'course enrolments\' requires the field \'course\' to be specified');
424 }
425
426 if (!isset($data['enrol'])) {
427 $data['enrol'] = 'manual';
428 }
429
2f29dd62
TB
430 if (!isset($data['timestart'])) {
431 $data['timestart'] = 0;
432 }
433
434 if (!isset($data['timeend'])) {
435 $data['timeend'] = 0;
436 }
437
438 if (!isset($data['status'])) {
439 $data['status'] = null;
440 }
441
a8a48495
DM
442 // If the provided course shortname is the site shortname we consider it a system role assign.
443 if ($data['courseid'] == $SITE->id) {
444 // Frontpage course assign.
445 $context = context_course::instance($data['courseid']);
446 role_assign($data['roleid'], $data['userid'], $context->id);
447
448 } else {
449 // Course assign.
2f29dd62
TB
450 $this->datagenerator->enrol_user($data['userid'], $data['courseid'], $data['roleid'], $data['enrol'],
451 $data['timestart'], $data['timeend'], $data['status']);
a8a48495
DM
452 }
453
f0200d14
DM
454 }
455
81cd8572
DM
456 /**
457 * Allows/denies a capability at the specified context
458 *
459 * @throws Exception
460 * @param array $data
461 * @return void
462 */
463 protected function process_permission_override($data) {
464
465 // Will throw an exception if it does not exist.
466 $context = $this->get_context($data['contextlevel'], $data['reference']);
467
468 switch ($data['permission']) {
a5254141 469 case get_string('allow', 'role'):
81cd8572
DM
470 $permission = CAP_ALLOW;
471 break;
a5254141 472 case get_string('prevent', 'role'):
81cd8572
DM
473 $permission = CAP_PREVENT;
474 break;
a5254141 475 case get_string('prohibit', 'role'):
81cd8572
DM
476 $permission = CAP_PROHIBIT;
477 break;
478 default:
479 throw new Exception('The \'' . $data['permission'] . '\' permission does not exist');
480 break;
481 }
482
483 if (is_null(get_capability_info($data['capability']))) {
484 throw new Exception('The \'' . $data['capability'] . '\' capability does not exist');
485 }
486
487 role_change_permission($data['roleid'], $context, $data['capability'], $permission);
488 }
489
d2eca4cd 490 /**
72ddc05f
DM
491 * Assigns a role to a user at system context
492 *
493 * Used by "system role assigns" can be deleted when
494 * system role assign will be deprecated in favour of
495 * "role assigns"
496 *
d2eca4cd
DM
497 * @throws Exception
498 * @param array $data
499 * @return void
500 */
72ddc05f 501 protected function process_system_role_assign($data) {
d2eca4cd
DM
502
503 if (empty($data['roleid'])) {
504 throw new Exception('\'system role assigns\' requires the field \'role\' to be specified');
505 }
506
507 if (!isset($data['userid'])) {
508 throw new Exception('\'system role assigns\' requires the field \'user\' to be specified');
509 }
510
511 $context = context_system::instance();
72ddc05f
DM
512
513 $this->datagenerator->role_assign($data['roleid'], $data['userid'], $context->id);
514 }
515
516 /**
517 * Assigns a role to a user at the specified context
518 *
519 * @throws Exception
520 * @param array $data
521 * @return void
522 */
523 protected function process_role_assign($data) {
524
525 if (empty($data['roleid'])) {
526 throw new Exception('\'role assigns\' requires the field \'role\' to be specified');
527 }
528
529 if (!isset($data['userid'])) {
530 throw new Exception('\'role assigns\' requires the field \'user\' to be specified');
531 }
532
533 if (empty($data['contextlevel'])) {
534 throw new Exception('\'role assigns\' requires the field \'contextlevel\' to be specified');
535 }
536
537 if (!isset($data['reference'])) {
538 throw new Exception('\'role assigns\' requires the field \'reference\' to be specified');
539 }
540
541 // Getting the context id.
542 $context = $this->get_context($data['contextlevel'], $data['reference']);
543
544 $this->datagenerator->role_assign($data['roleid'], $data['userid'], $context->id);
f0200d14
DM
545 }
546
702851c0
DM
547 /**
548 * Creates a role.
549 *
550 * @param array $data
551 * @return void
552 */
553 protected function process_role($data) {
554
555 // We require the user to fill the role shortname.
556 if (empty($data['shortname'])) {
557 throw new Exception('\'role\' requires the field \'shortname\' to be specified');
558 }
559
560 $this->datagenerator->create_role($data);
561 }
562
9cc66e86
MG
563 /**
564 * Adds members to cohorts
565 *
566 * @param array $data
567 * @return void
568 */
569 protected function process_cohort_member($data) {
570 cohort_add_member($data['cohortid'], $data['userid']);
571 }
572
0db16e08
TH
573 /**
574 * Create a question category.
575 *
576 * @param array $data the row of data from the behat script.
577 */
578 protected function process_question_category($data) {
579 $context = $this->get_context($data['contextlevel'], $data['reference']);
580 $data['contextid'] = $context->id;
581 $this->datagenerator->get_plugin_generator('core_question')->create_question_category($data);
582 }
583
584 /**
585 * Create a question.
586 *
587 * Creating questions relies on the question/type/.../tests/helper.php mechanism.
588 * We start with test_question_maker::get_question_form_data($data['qtype'], $data['template'])
589 * and then overlay the values from any other fields of $data that are set.
590 *
591 * @param array $data the row of data from the behat script.
592 */
593 protected function process_question($data) {
594 if (array_key_exists('questiontext', $data)) {
595 $data['questiontext'] = array(
596 'text' => $data['questiontext'],
597 'format' => FORMAT_HTML,
598 );
599 }
600
601 if (array_key_exists('generalfeedback', $data)) {
602 $data['generalfeedback'] = array(
603 'text' => $data['generalfeedback'],
604 'format' => FORMAT_HTML,
605 );
606 }
607
608 $which = null;
609 if (!empty($data['template'])) {
610 $which = $data['template'];
611 }
612
613 $this->datagenerator->get_plugin_generator('core_question')->create_question($data['qtype'], $which, $data);
614 }
615
15ace204
DW
616 /**
617 * Gets the grade category id from the grade category fullname
618 * @throws Exception
619 * @param string $username
620 * @return int
621 */
622 protected function get_gradecategory_id($fullname) {
623 global $DB;
624
625 if (!$id = $DB->get_field('grade_categories', 'id', array('fullname' => $fullname))) {
626 throw new Exception('The specified grade category with fullname "' . $fullname . '" does not exist');
627 }
628 return $id;
629 }
630
f0200d14
DM
631 /**
632 * Gets the user id from it's username.
633 * @throws Exception
46ac40cd 634 * @param string $username
f0200d14
DM
635 * @return int
636 */
637 protected function get_user_id($username) {
638 global $DB;
639
640 if (!$id = $DB->get_field('user', 'id', array('username' => $username))) {
1f9ffbdb 641 throw new Exception('The specified user with username "' . $username . '" does not exist');
f0200d14
DM
642 }
643 return $id;
644 }
645
646 /**
647 * Gets the role id from it's shortname.
648 * @throws Exception
46ac40cd 649 * @param string $roleshortname
f0200d14
DM
650 * @return int
651 */
652 protected function get_role_id($roleshortname) {
653 global $DB;
654
655 if (!$id = $DB->get_field('role', 'id', array('shortname' => $roleshortname))) {
702851c0 656 throw new Exception('The specified role with shortname "' . $roleshortname . '" does not exist');
f0200d14
DM
657 }
658
659 return $id;
660 }
661
662 /**
663 * Gets the category id from it's idnumber.
664 * @throws Exception
665 * @param string $idnumber
666 * @return int
667 */
668 protected function get_category_id($idnumber) {
669 global $DB;
670
671 // If no category was specified use the data generator one.
672 if ($idnumber == false) {
673 return null;
674 }
675
676 if (!$id = $DB->get_field('course_categories', 'id', array('idnumber' => $idnumber))) {
1f9ffbdb 677 throw new Exception('The specified category with idnumber "' . $idnumber . '" does not exist');
f0200d14
DM
678 }
679
680 return $id;
681 }
682
683 /**
684 * Gets the course id from it's shortname.
685 * @throws Exception
686 * @param string $shortname
687 * @return int
688 */
689 protected function get_course_id($shortname) {
690 global $DB;
691
692 if (!$id = $DB->get_field('course', 'id', array('shortname' => $shortname))) {
702851c0 693 throw new Exception('The specified course with shortname "' . $shortname . '" does not exist');
f0200d14
DM
694 }
695 return $id;
696 }
697
698 /**
699 * Gets the group id from it's idnumber.
700 * @throws Exception
701 * @param string $idnumber
702 * @return int
703 */
704 protected function get_group_id($idnumber) {
705 global $DB;
706
707 if (!$id = $DB->get_field('groups', 'id', array('idnumber' => $idnumber))) {
1f9ffbdb 708 throw new Exception('The specified group with idnumber "' . $idnumber . '" does not exist');
f0200d14
DM
709 }
710 return $id;
711 }
712
713 /**
714 * Gets the grouping id from it's idnumber.
715 * @throws Exception
716 * @param string $idnumber
717 * @return int
718 */
719 protected function get_grouping_id($idnumber) {
720 global $DB;
721
722 if (!$id = $DB->get_field('groupings', 'id', array('idnumber' => $idnumber))) {
1f9ffbdb 723 throw new Exception('The specified grouping with idnumber "' . $idnumber . '" does not exist');
f0200d14
DM
724 }
725 return $id;
726 }
72ddc05f 727
9cc66e86
MG
728 /**
729 * Gets the cohort id from it's idnumber.
730 * @throws Exception
731 * @param string $idnumber
732 * @return int
733 */
734 protected function get_cohort_id($idnumber) {
735 global $DB;
736
737 if (!$id = $DB->get_field('cohort', 'id', array('idnumber' => $idnumber))) {
738 throw new Exception('The specified cohort with idnumber "' . $idnumber . '" does not exist');
739 }
740 return $id;
741 }
742
cfa91962
JO
743 /**
744 * Gets the outcome item id from its shortname.
745 * @throws Exception
746 * @param string $shortname
747 * @return int
748 */
749 protected function get_outcome_id($shortname) {
750 global $DB;
751
752 if (!$id = $DB->get_field('grade_outcomes', 'id', array('shortname' => $shortname))) {
753 throw new Exception('The specified outcome with shortname "' . $shortname . '" does not exist');
754 }
755 return $id;
756 }
757
758 /**
0db16e08
TH
759 * Get the id of a named scale.
760 * @param string $name the name of the scale.
761 * @return int the scale id.
cfa91962
JO
762 */
763 protected function get_scale_id($name) {
764 global $DB;
765
766 if (!$id = $DB->get_field('scale', 'id', array('name' => $name))) {
767 throw new Exception('The specified scale with name "' . $name . '" does not exist');
768 }
769 return $id;
770 }
771
0db16e08
TH
772 /**
773 * Get the id of a named question category (must be globally unique).
774 * Note that 'Top' is a special value, used when setting the parent of another
775 * category, meaning top-level.
776 *
777 * @param string $name the question category name.
778 * @return int the question category id.
779 */
780 protected function get_questioncategory_id($name) {
781 global $DB;
782
783 if ($name == 'Top') {
784 return 0;
785 }
786
787 if (!$id = $DB->get_field('question_categories', 'id', array('name' => $name))) {
788 throw new Exception('The specified question category with name "' . $name . '" does not exist');
789 }
790 return $id;
791 }
792
72ddc05f
DM
793 /**
794 * Gets the internal context id from the context reference.
795 *
796 * The context reference changes depending on the context
797 * level, it can be the system, a user, a category, a course or
798 * a module.
799 *
800 * @throws Exception
801 * @param string $levelname The context level string introduced by the test writer
802 * @param string $contextref The context reference introduced by the test writer
803 * @return context
804 */
805 protected function get_context($levelname, $contextref) {
806 global $DB;
807
808 // Getting context levels and names (we will be using the English ones as it is the test site language).
809 $contextlevels = context_helper::get_all_levels();
810 $contextnames = array();
811 foreach ($contextlevels as $level => $classname) {
812 $contextnames[context_helper::get_level_name($level)] = $level;
813 }
814
815 if (empty($contextnames[$levelname])) {
816 throw new Exception('The specified "' . $levelname . '" context level does not exist');
817 }
818 $contextlevel = $contextnames[$levelname];
819
820 // Return it, we don't need to look for other internal ids.
821 if ($contextlevel == CONTEXT_SYSTEM) {
822 return context_system::instance();
823 }
824
825 switch ($contextlevel) {
826
827 case CONTEXT_USER:
828 $instanceid = $DB->get_field('user', 'id', array('username' => $contextref));
829 break;
830
831 case CONTEXT_COURSECAT:
832 $instanceid = $DB->get_field('course_categories', 'id', array('idnumber' => $contextref));
833 break;
834
835 case CONTEXT_COURSE:
836 $instanceid = $DB->get_field('course', 'id', array('shortname' => $contextref));
837 break;
838
839 case CONTEXT_MODULE:
840 $instanceid = $DB->get_field('course_modules', 'id', array('idnumber' => $contextref));
841 break;
842
843 default:
844 break;
845 }
846
847 $contextclass = $contextlevels[$contextlevel];
848 if (!$context = $contextclass::instance($instanceid, IGNORE_MISSING)) {
849 throw new Exception('The specified "' . $contextref . '" context reference does not exist');
850 }
851
852 return $context;
853 }
854
029a3e73 855 /**
856 * Adds user to contacts
857 *
858 * @param array $data
859 * @return void
860 */
861 protected function process_message_contacts($data) {
862 \core_message\api::add_contact($data['userid'], $data['contactid']);
863 }
864
865 /**
866 * Gets the contact id from it's username.
867 * @throws Exception
868 * @param string $username
869 * @return int
870 */
871 protected function get_contact_id($username) {
872 global $DB;
873
874 if (!$id = $DB->get_field('user', 'id', array('username' => $username))) {
875 throw new Exception('The specified user with username "' . $username . '" does not exist');
876 }
877 return $id;
878 }
f0200d14 879}