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