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