MDL-64666 core_message: Favourite private conversations data generator
[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 ),
7042ecf7
AA
201 'private messages' => array(
202 'datagenerator' => 'private_messages',
203 'required' => array('user', 'contact', 'message'),
204 'switchids' => array('user' => 'userid', 'contact' => 'contactid')
205 ),
206 'favourite conversations' => array(
207 'datagenerator' => 'favourite_conversations',
208 'required' => array('user', 'contact'),
209 'switchids' => array('user' => 'userid', 'contact' => 'contactid')
210 ),
f0200d14
DM
211 );
212
213 /**
214 * Creates the specified element. More info about available elements in http://docs.moodle.org/dev/Acceptance_testing#Fixtures.
215 *
c51c3b55 216 * @Given /^the following "(?P<element_string>(?:[^"]|\\")*)" exist:$/
f0200d14
DM
217 *
218 * @throws Exception
219 * @throws PendingException
220 * @param string $elementname The name of the entity to add
221 * @param TableNode $data
222 */
c51c3b55 223 public function the_following_exist($elementname, TableNode $data) {
f0200d14 224
c29e3e24
DM
225 // Now that we need them require the data generators.
226 require_once(__DIR__ . '/../../testing/generator/lib.php');
227
f0200d14
DM
228 if (empty(self::$elements[$elementname])) {
229 throw new PendingException($elementname . ' data generator is not implemented');
230 }
231
232 $this->datagenerator = testing_util::get_data_generator();
233
234 $elementdatagenerator = self::$elements[$elementname]['datagenerator'];
235 $requiredfields = self::$elements[$elementname]['required'];
236 if (!empty(self::$elements[$elementname]['switchids'])) {
237 $switchids = self::$elements[$elementname]['switchids'];
238 }
239
240 foreach ($data->getHash() as $elementdata) {
241
242 // Check if all the required fields are there.
243 foreach ($requiredfields as $requiredfield) {
244 if (!isset($elementdata[$requiredfield])) {
245 throw new Exception($elementname . ' requires the field ' . $requiredfield . ' to be specified');
246 }
247 }
248
249 // Switch from human-friendly references to ids.
250 if (isset($switchids)) {
251 foreach ($switchids as $element => $field) {
252 $methodname = 'get_' . $element . '_id';
253
254 // Not all the switch fields are required, default vars will be assigned by data generators.
48a3a50a 255 if (isset($elementdata[$element])) {
f0200d14
DM
256 // Temp $id var to avoid problems when $element == $field.
257 $id = $this->{$methodname}($elementdata[$element]);
258 unset($elementdata[$element]);
259 $elementdata[$field] = $id;
260 }
261 }
262 }
263
264 // Preprocess the entities that requires a special treatment.
265 if (method_exists($this, 'preprocess_' . $elementdatagenerator)) {
266 $elementdata = $this->{'preprocess_' . $elementdatagenerator}($elementdata);
267 }
268
269 // Creates element.
270 $methodname = 'create_' . $elementdatagenerator;
271 if (method_exists($this->datagenerator, $methodname)) {
272 // Using data generators directly.
273 $this->datagenerator->{$methodname}($elementdata);
274
d2eca4cd
DM
275 } else if (method_exists($this, 'process_' . $elementdatagenerator)) {
276 // Using an alternative to the direct data generator call.
277 $this->{'process_' . $elementdatagenerator}($elementdata);
f0200d14
DM
278 } else {
279 throw new PendingException($elementname . ' data generator is not implemented');
280 }
281 }
282
283 }
284
285 /**
286 * If password is not set it uses the username.
287 * @param array $data
288 * @return array
289 */
290 protected function preprocess_user($data) {
291 if (!isset($data['password'])) {
292 $data['password'] = $data['username'];
293 }
294 return $data;
295 }
296
5f079af4
MG
297 /**
298 * If contextlevel and reference are specified for cohort, transform them to the contextid.
299 *
300 * @param array $data
301 * @return array
302 */
303 protected function preprocess_cohort($data) {
304 if (isset($data['contextlevel'])) {
305 if (!isset($data['reference'])) {
306 throw new Exception('If field contextlevel is specified, field reference must also be present');
307 }
308 $context = $this->get_context($data['contextlevel'], $data['reference']);
309 unset($data['contextlevel']);
310 unset($data['reference']);
311 $data['contextid'] = $context->id;
312 }
313 return $data;
314 }
315
cfa91962
JO
316 /**
317 * Preprocesses the creation of a grade item. Converts gradetype text to a number.
318 * @param array $data
319 * @return array
320 */
321 protected function preprocess_grade_item($data) {
322 global $CFG;
323 require_once("$CFG->libdir/grade/constants.php");
324
325 if (isset($data['gradetype'])) {
326 $data['gradetype'] = constant("GRADE_TYPE_" . strtoupper($data['gradetype']));
327 }
b13afc36
FM
328
329 if (!empty($data['category']) && !empty($data['courseid'])) {
330 $cat = grade_category::fetch(array('fullname' => $data['category'], 'courseid' => $data['courseid']));
331 if (!$cat) {
332 throw new Exception('Could not resolve category with name "' . $data['category'] . '"');
333 }
334 unset($data['category']);
335 $data['categoryid'] = $cat->id;
336 }
337
cfa91962
JO
338 return $data;
339 }
340
a0902967
DM
341 /**
342 * Adapter to modules generator
343 * @throws Exception Custom exception for test writers
344 * @param array $data
345 * @return void
346 */
347 protected function process_activity($data) {
cfa91962 348 global $DB, $CFG;
a0902967
DM
349
350 // The the_following_exists() method checks that the field exists.
351 $activityname = $data['activity'];
352 unset($data['activity']);
353
cfa91962
JO
354 // Convert scale name into scale id (negative number indicates using scale).
355 if (isset($data['grade']) && strlen($data['grade']) && !is_number($data['grade'])) {
356 $data['grade'] = - $this->get_scale_id($data['grade']);
357 require_once("$CFG->libdir/grade/constants.php");
358
359 if (!isset($data['gradetype'])) {
360 $data['gradetype'] = GRADE_TYPE_SCALE;
361 }
362 }
363
041cf62b
DM
364 // We split $data in the activity $record and the course module $options.
365 $cmoptions = array();
366 $cmcolumns = $DB->get_columns('course_modules');
367 foreach ($cmcolumns as $key => $value) {
368 if (isset($data[$key])) {
369 $cmoptions[$key] = $data[$key];
370 }
371 }
372
a0902967
DM
373 // Custom exception.
374 try {
041cf62b 375 $this->datagenerator->create_module($activityname, $data, $cmoptions);
a0902967
DM
376 } catch (coding_exception $e) {
377 throw new Exception('\'' . $activityname . '\' activity can not be added using this step,' .
378 ' use the step \'I add a "ACTIVITY_OR_RESOURCE_NAME_STRING" to section "SECTION_NUMBER"\' instead');
379 }
eb3884e4
TH
380 }
381
382 /**
383 * Add a block to a page.
384 *
385 * @param array $data should mostly match the fields of the block_instances table.
386 * The block type is specified by blockname.
387 * The parentcontextid is set from contextlevel and reference.
388 * Missing values are filled in by testing_block_generator::prepare_record.
389 * $data is passed to create_block as both $record and $options. Normally
390 * the keys are different, so this is a way to let people set values in either place.
391 */
392 protected function process_block_instance($data) {
393
394 if (empty($data['blockname'])) {
395 throw new Exception('\'blocks\' requires the field \'block\' type to be specified');
396 }
397
398 if (empty($data['contextlevel'])) {
399 throw new Exception('\'blocks\' requires the field \'contextlevel\' to be specified');
400 }
401
402 if (!isset($data['reference'])) {
403 throw new Exception('\'blocks\' requires the field \'reference\' to be specified');
404 }
405
406 $context = $this->get_context($data['contextlevel'], $data['reference']);
407 $data['parentcontextid'] = $context->id;
408
409 // Pass $data as both $record and $options. I think that is unlikely to
410 // cause problems since the relevant key names are different.
411 // $options is not used in most blocks I have seen, but where it is, it is necessary.
412 $this->datagenerator->create_block($data['blockname'], $data, $data);
a0902967 413 }
f0200d14
DM
414
415 /**
416 * Adapter to enrol_user() data generator.
417 * @throws Exception
d2eca4cd 418 * @param array $data
f0200d14
DM
419 * @return void
420 */
d2eca4cd 421 protected function process_enrol_user($data) {
a8a48495 422 global $SITE;
f0200d14
DM
423
424 if (empty($data['roleid'])) {
425 throw new Exception('\'course enrolments\' requires the field \'role\' to be specified');
426 }
427
428 if (!isset($data['userid'])) {
429 throw new Exception('\'course enrolments\' requires the field \'user\' to be specified');
430 }
431
432 if (!isset($data['courseid'])) {
433 throw new Exception('\'course enrolments\' requires the field \'course\' to be specified');
434 }
435
436 if (!isset($data['enrol'])) {
437 $data['enrol'] = 'manual';
438 }
439
2f29dd62
TB
440 if (!isset($data['timestart'])) {
441 $data['timestart'] = 0;
442 }
443
444 if (!isset($data['timeend'])) {
445 $data['timeend'] = 0;
446 }
447
448 if (!isset($data['status'])) {
449 $data['status'] = null;
450 }
451
a8a48495
DM
452 // If the provided course shortname is the site shortname we consider it a system role assign.
453 if ($data['courseid'] == $SITE->id) {
454 // Frontpage course assign.
455 $context = context_course::instance($data['courseid']);
456 role_assign($data['roleid'], $data['userid'], $context->id);
457
458 } else {
459 // Course assign.
2f29dd62
TB
460 $this->datagenerator->enrol_user($data['userid'], $data['courseid'], $data['roleid'], $data['enrol'],
461 $data['timestart'], $data['timeend'], $data['status']);
a8a48495
DM
462 }
463
f0200d14
DM
464 }
465
81cd8572
DM
466 /**
467 * Allows/denies a capability at the specified context
468 *
469 * @throws Exception
470 * @param array $data
471 * @return void
472 */
473 protected function process_permission_override($data) {
474
475 // Will throw an exception if it does not exist.
476 $context = $this->get_context($data['contextlevel'], $data['reference']);
477
478 switch ($data['permission']) {
a5254141 479 case get_string('allow', 'role'):
81cd8572
DM
480 $permission = CAP_ALLOW;
481 break;
a5254141 482 case get_string('prevent', 'role'):
81cd8572
DM
483 $permission = CAP_PREVENT;
484 break;
a5254141 485 case get_string('prohibit', 'role'):
81cd8572
DM
486 $permission = CAP_PROHIBIT;
487 break;
488 default:
489 throw new Exception('The \'' . $data['permission'] . '\' permission does not exist');
490 break;
491 }
492
493 if (is_null(get_capability_info($data['capability']))) {
494 throw new Exception('The \'' . $data['capability'] . '\' capability does not exist');
495 }
496
497 role_change_permission($data['roleid'], $context, $data['capability'], $permission);
498 }
499
d2eca4cd 500 /**
72ddc05f
DM
501 * Assigns a role to a user at system context
502 *
503 * Used by "system role assigns" can be deleted when
504 * system role assign will be deprecated in favour of
505 * "role assigns"
506 *
d2eca4cd
DM
507 * @throws Exception
508 * @param array $data
509 * @return void
510 */
72ddc05f 511 protected function process_system_role_assign($data) {
d2eca4cd
DM
512
513 if (empty($data['roleid'])) {
514 throw new Exception('\'system role assigns\' requires the field \'role\' to be specified');
515 }
516
517 if (!isset($data['userid'])) {
518 throw new Exception('\'system role assigns\' requires the field \'user\' to be specified');
519 }
520
521 $context = context_system::instance();
72ddc05f
DM
522
523 $this->datagenerator->role_assign($data['roleid'], $data['userid'], $context->id);
524 }
525
526 /**
527 * Assigns a role to a user at the specified context
528 *
529 * @throws Exception
530 * @param array $data
531 * @return void
532 */
533 protected function process_role_assign($data) {
534
535 if (empty($data['roleid'])) {
536 throw new Exception('\'role assigns\' requires the field \'role\' to be specified');
537 }
538
539 if (!isset($data['userid'])) {
540 throw new Exception('\'role assigns\' requires the field \'user\' to be specified');
541 }
542
543 if (empty($data['contextlevel'])) {
544 throw new Exception('\'role assigns\' requires the field \'contextlevel\' to be specified');
545 }
546
547 if (!isset($data['reference'])) {
548 throw new Exception('\'role assigns\' requires the field \'reference\' to be specified');
549 }
550
551 // Getting the context id.
552 $context = $this->get_context($data['contextlevel'], $data['reference']);
553
554 $this->datagenerator->role_assign($data['roleid'], $data['userid'], $context->id);
f0200d14
DM
555 }
556
702851c0
DM
557 /**
558 * Creates a role.
559 *
560 * @param array $data
561 * @return void
562 */
563 protected function process_role($data) {
564
565 // We require the user to fill the role shortname.
566 if (empty($data['shortname'])) {
567 throw new Exception('\'role\' requires the field \'shortname\' to be specified');
568 }
569
570 $this->datagenerator->create_role($data);
571 }
572
9cc66e86
MG
573 /**
574 * Adds members to cohorts
575 *
576 * @param array $data
577 * @return void
578 */
579 protected function process_cohort_member($data) {
580 cohort_add_member($data['cohortid'], $data['userid']);
581 }
582
0db16e08
TH
583 /**
584 * Create a question category.
585 *
586 * @param array $data the row of data from the behat script.
587 */
588 protected function process_question_category($data) {
589 $context = $this->get_context($data['contextlevel'], $data['reference']);
590 $data['contextid'] = $context->id;
591 $this->datagenerator->get_plugin_generator('core_question')->create_question_category($data);
592 }
593
594 /**
595 * Create a question.
596 *
597 * Creating questions relies on the question/type/.../tests/helper.php mechanism.
598 * We start with test_question_maker::get_question_form_data($data['qtype'], $data['template'])
599 * and then overlay the values from any other fields of $data that are set.
600 *
601 * @param array $data the row of data from the behat script.
602 */
603 protected function process_question($data) {
604 if (array_key_exists('questiontext', $data)) {
605 $data['questiontext'] = array(
606 'text' => $data['questiontext'],
607 'format' => FORMAT_HTML,
608 );
609 }
610
611 if (array_key_exists('generalfeedback', $data)) {
612 $data['generalfeedback'] = array(
613 'text' => $data['generalfeedback'],
614 'format' => FORMAT_HTML,
615 );
616 }
617
618 $which = null;
619 if (!empty($data['template'])) {
620 $which = $data['template'];
621 }
622
623 $this->datagenerator->get_plugin_generator('core_question')->create_question($data['qtype'], $which, $data);
624 }
625
15ace204
DW
626 /**
627 * Gets the grade category id from the grade category fullname
628 * @throws Exception
629 * @param string $username
630 * @return int
631 */
632 protected function get_gradecategory_id($fullname) {
633 global $DB;
634
635 if (!$id = $DB->get_field('grade_categories', 'id', array('fullname' => $fullname))) {
636 throw new Exception('The specified grade category with fullname "' . $fullname . '" does not exist');
637 }
638 return $id;
639 }
640
f0200d14
DM
641 /**
642 * Gets the user id from it's username.
643 * @throws Exception
46ac40cd 644 * @param string $username
f0200d14
DM
645 * @return int
646 */
647 protected function get_user_id($username) {
648 global $DB;
649
650 if (!$id = $DB->get_field('user', 'id', array('username' => $username))) {
1f9ffbdb 651 throw new Exception('The specified user with username "' . $username . '" does not exist');
f0200d14
DM
652 }
653 return $id;
654 }
655
656 /**
657 * Gets the role id from it's shortname.
658 * @throws Exception
46ac40cd 659 * @param string $roleshortname
f0200d14
DM
660 * @return int
661 */
662 protected function get_role_id($roleshortname) {
663 global $DB;
664
665 if (!$id = $DB->get_field('role', 'id', array('shortname' => $roleshortname))) {
702851c0 666 throw new Exception('The specified role with shortname "' . $roleshortname . '" does not exist');
f0200d14
DM
667 }
668
669 return $id;
670 }
671
672 /**
673 * Gets the category id from it's idnumber.
674 * @throws Exception
675 * @param string $idnumber
676 * @return int
677 */
678 protected function get_category_id($idnumber) {
679 global $DB;
680
681 // If no category was specified use the data generator one.
682 if ($idnumber == false) {
683 return null;
684 }
685
686 if (!$id = $DB->get_field('course_categories', 'id', array('idnumber' => $idnumber))) {
1f9ffbdb 687 throw new Exception('The specified category with idnumber "' . $idnumber . '" does not exist');
f0200d14
DM
688 }
689
690 return $id;
691 }
692
693 /**
694 * Gets the course id from it's shortname.
695 * @throws Exception
696 * @param string $shortname
697 * @return int
698 */
699 protected function get_course_id($shortname) {
700 global $DB;
701
702 if (!$id = $DB->get_field('course', 'id', array('shortname' => $shortname))) {
702851c0 703 throw new Exception('The specified course with shortname "' . $shortname . '" does not exist');
f0200d14
DM
704 }
705 return $id;
706 }
707
708 /**
709 * Gets the group id from it's idnumber.
710 * @throws Exception
711 * @param string $idnumber
712 * @return int
713 */
714 protected function get_group_id($idnumber) {
715 global $DB;
716
717 if (!$id = $DB->get_field('groups', 'id', array('idnumber' => $idnumber))) {
1f9ffbdb 718 throw new Exception('The specified group with idnumber "' . $idnumber . '" does not exist');
f0200d14
DM
719 }
720 return $id;
721 }
722
723 /**
724 * Gets the grouping id from it's idnumber.
725 * @throws Exception
726 * @param string $idnumber
727 * @return int
728 */
729 protected function get_grouping_id($idnumber) {
730 global $DB;
731
732 if (!$id = $DB->get_field('groupings', 'id', array('idnumber' => $idnumber))) {
1f9ffbdb 733 throw new Exception('The specified grouping with idnumber "' . $idnumber . '" does not exist');
f0200d14
DM
734 }
735 return $id;
736 }
72ddc05f 737
9cc66e86
MG
738 /**
739 * Gets the cohort id from it's idnumber.
740 * @throws Exception
741 * @param string $idnumber
742 * @return int
743 */
744 protected function get_cohort_id($idnumber) {
745 global $DB;
746
747 if (!$id = $DB->get_field('cohort', 'id', array('idnumber' => $idnumber))) {
748 throw new Exception('The specified cohort with idnumber "' . $idnumber . '" does not exist');
749 }
750 return $id;
751 }
752
cfa91962
JO
753 /**
754 * Gets the outcome item id from its shortname.
755 * @throws Exception
756 * @param string $shortname
757 * @return int
758 */
759 protected function get_outcome_id($shortname) {
760 global $DB;
761
762 if (!$id = $DB->get_field('grade_outcomes', 'id', array('shortname' => $shortname))) {
763 throw new Exception('The specified outcome with shortname "' . $shortname . '" does not exist');
764 }
765 return $id;
766 }
767
768 /**
0db16e08
TH
769 * Get the id of a named scale.
770 * @param string $name the name of the scale.
771 * @return int the scale id.
cfa91962
JO
772 */
773 protected function get_scale_id($name) {
774 global $DB;
775
776 if (!$id = $DB->get_field('scale', 'id', array('name' => $name))) {
777 throw new Exception('The specified scale with name "' . $name . '" does not exist');
778 }
779 return $id;
780 }
781
0db16e08
TH
782 /**
783 * Get the id of a named question category (must be globally unique).
784 * Note that 'Top' is a special value, used when setting the parent of another
785 * category, meaning top-level.
786 *
787 * @param string $name the question category name.
788 * @return int the question category id.
789 */
790 protected function get_questioncategory_id($name) {
791 global $DB;
792
793 if ($name == 'Top') {
794 return 0;
795 }
796
797 if (!$id = $DB->get_field('question_categories', 'id', array('name' => $name))) {
798 throw new Exception('The specified question category with name "' . $name . '" does not exist');
799 }
800 return $id;
801 }
802
72ddc05f
DM
803 /**
804 * Gets the internal context id from the context reference.
805 *
806 * The context reference changes depending on the context
807 * level, it can be the system, a user, a category, a course or
808 * a module.
809 *
810 * @throws Exception
811 * @param string $levelname The context level string introduced by the test writer
812 * @param string $contextref The context reference introduced by the test writer
813 * @return context
814 */
815 protected function get_context($levelname, $contextref) {
816 global $DB;
817
818 // Getting context levels and names (we will be using the English ones as it is the test site language).
819 $contextlevels = context_helper::get_all_levels();
820 $contextnames = array();
821 foreach ($contextlevels as $level => $classname) {
822 $contextnames[context_helper::get_level_name($level)] = $level;
823 }
824
825 if (empty($contextnames[$levelname])) {
826 throw new Exception('The specified "' . $levelname . '" context level does not exist');
827 }
828 $contextlevel = $contextnames[$levelname];
829
830 // Return it, we don't need to look for other internal ids.
831 if ($contextlevel == CONTEXT_SYSTEM) {
832 return context_system::instance();
833 }
834
835 switch ($contextlevel) {
836
837 case CONTEXT_USER:
838 $instanceid = $DB->get_field('user', 'id', array('username' => $contextref));
839 break;
840
841 case CONTEXT_COURSECAT:
842 $instanceid = $DB->get_field('course_categories', 'id', array('idnumber' => $contextref));
843 break;
844
845 case CONTEXT_COURSE:
846 $instanceid = $DB->get_field('course', 'id', array('shortname' => $contextref));
847 break;
848
849 case CONTEXT_MODULE:
850 $instanceid = $DB->get_field('course_modules', 'id', array('idnumber' => $contextref));
851 break;
852
853 default:
854 break;
855 }
856
857 $contextclass = $contextlevels[$contextlevel];
858 if (!$context = $contextclass::instance($instanceid, IGNORE_MISSING)) {
859 throw new Exception('The specified "' . $contextref . '" context reference does not exist');
860 }
861
862 return $context;
863 }
864
029a3e73 865 /**
866 * Adds user to contacts
867 *
868 * @param array $data
869 * @return void
870 */
871 protected function process_message_contacts($data) {
872 \core_message\api::add_contact($data['userid'], $data['contactid']);
873 }
874
875 /**
876 * Gets the contact id from it's username.
877 * @throws Exception
878 * @param string $username
879 * @return int
880 */
881 protected function get_contact_id($username) {
882 global $DB;
883
884 if (!$id = $DB->get_field('user', 'id', array('username' => $username))) {
885 throw new Exception('The specified user with username "' . $username . '" does not exist');
886 }
887 return $id;
888 }
7042ecf7
AA
889
890 /**
891 * Send a new message from user to contact in a private conversation
892 *
893 * @param array $data
894 * @return void
895 */
896 protected function process_private_messages(array $data) {
897 if (!$conversationid = \core_message\api::get_conversation_between_users([$data['userid'], $data['contactid']])) {
898 $conversation = \core_message\api::create_conversation(
899 \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
900 [$data['userid'], $data['contactid']]
901 );
902 $conversationid = $conversation->id;
903 }
904 \core_message\api::send_message_to_conversation($data['userid'], $conversationid, $data['message'], FORMAT_PLAIN);
905 }
906
907 /**
908 * Mark a private conversation as favourite for user
909 *
910 * @param array $data
911 * @return void
912 */
913 protected function process_favourite_conversations(array $data) {
914 if (!$conversationid = \core_message\api::get_conversation_between_users([$data['userid'], $data['contactid']])) {
915 $conversation = \core_message\api::create_conversation(
916 \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
917 [$data['userid'], $data['contactid']]
918 );
919 $conversationid = $conversation->id;
920 }
921 \core_message\api::set_favourite_conversation($conversationid, $data['userid']);
922 }
f0200d14 923}