TestingDataGenerator.php 81.7 KB
Newer Older
1
<?php
Son Nguyen's avatar
Son Nguyen committed
2
3
4
5
6
7
8
9
10
11
/**
 * @package    mahara
 * @subpackage test/generator
 * @author     Son Nguyen, Catalyst IT Ltd
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
 * @copyright  portions from Moodle 2012, Petr Skoda {@link http://skodak.org}
 *
 */

Son Nguyen's avatar
Son Nguyen committed
12
13
14
15
require_once(get_config('libroot') . 'institution.php');
require_once(get_config('libroot') . 'group.php');
require_once(get_config('libroot') . 'view.php');

Son Nguyen's avatar
Son Nguyen committed
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
 * Data generator class for unit tests and other tools like behat that need to create fake test sites.
 *
 */
use Behat\Behat\Exception\UndefinedException as UndefinedException;

class TestingDataGenerator {

    protected $usercounter = 0;
    protected $groupcount = 0;
    protected $institutioncount = 0;
    protected $tagcount = 0;

29
    /** @var array list to track location to know where to create block on each view */
Doris Tam's avatar
Doris Tam committed
30
    public static $viewcolcounts = array();
31

Son Nguyen's avatar
Son Nguyen committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
    /** @var array list of plugin generators */
    protected $generators = array();

    /** @var array lis of common last names */
    public $lastnames = array(
            'Smith', 'Johnson', 'Williams', 'Brown', 'Jones', 'Miller', 'Davis', 'García', 'Rodríguez', 'Wilson',
            'Müller', 'Schmidt', 'Schneider', 'Fischer', 'Meyer', 'Weber', 'Schulz', 'Wagner', 'Becker', 'Hoffmann',
            'Novák', 'Svoboda', 'Novotný', 'Dvořák', 'Černý', 'Procházková', 'Kučerová', 'Veselá', 'Horáková', 'Němcová',
            'Смирнов', 'Иванов', 'Кузнецов', 'Соколов', 'Попов', 'Лебедева', 'Козлова', 'Новикова', 'Морозова', 'Петрова',
            '王', '李', '张', '刘', '陈', '楊', '黃', '趙', '吳', '周',
            '佐藤', '鈴木', '高橋', '田中', '渡辺', '伊藤', '山本', '中村', '小林', '斎藤',
    );

    /** @var array lis of common first names */
    public $firstnames = array(
            'Jacob', 'Ethan', 'Michael', 'Jayden', 'William', 'Isabella', 'Sophia', 'Emma', 'Olivia', 'Ava',
            'Lukas', 'Leon', 'Luca', 'Timm', 'Paul', 'Leonie', 'Leah', 'Lena', 'Hanna', 'Laura',
            'Jakub', 'Jan', 'Tomáš', 'Lukáš', 'Matěj', 'Tereza', 'Eliška', 'Anna', 'Adéla', 'Karolína',
            'Даниил', 'Максим', 'Артем', 'Иван', 'Александр', 'София', 'Анастасия', 'Дарья', 'Мария', 'Полина',
            '伟', '伟', '芳', '伟', '秀英', '秀英', '娜', '秀英', '伟', '敏',
            '翔', '大翔', '拓海', '翔太', '颯太', '陽菜', 'さくら', '美咲', '葵', '美羽',
    );

    public $loremipsum = <<<EOD
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla non arcu lacinia neque faucibus fringilla. Vivamus porttitor turpis ac leo. Integer in sapien. Nullam eget nisl. Aliquam erat volutpat. Cras elementum. Mauris suscipit, ligula sit amet pharetra semper, nibh ante cursus purus, vel sagittis velit mauris vel metus. Integer malesuada. Nullam lectus justo, vulputate eget mollis sed, tempor sed magna. Mauris elementum mauris vitae tortor. Aliquam erat volutpat.
Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Pellentesque ipsum. Cras pede libero, dapibus nec, pretium sit amet, tempor quis. Aliquam ante. Proin in tellus sit amet nibh dignissim sagittis. Vivamus porttitor turpis ac leo. Duis bibendum, lectus ut viverra rhoncus, dolor nunc faucibus libero, eget facilisis enim ipsum id lacus. In sem justo, commodo ut, suscipit at, pharetra vitae, orci. Aliquam erat volutpat. Nulla est.
Vivamus luctus egestas leo. Aenean fermentum risus id tortor. Mauris dictum facilisis augue. Aliquam erat volutpat. Aliquam ornare wisi eu metus. Aliquam id dolor. Duis condimentum augue id magna semper rutrum. Donec iaculis gravida nulla. Pellentesque ipsum. Etiam dictum tincidunt diam. Quisque tincidunt scelerisque libero. Etiam egestas wisi a erat.
Integer lacinia. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris tincidunt sem sed arcu. Nullam feugiat, turpis at pulvinar vulputate, erat libero tristique tellus, nec bibendum odio risus sit amet ante. Aliquam id dolor. Maecenas sollicitudin. Et harum quidem rerum facilis est et expedita distinctio. Mauris suscipit, ligula sit amet pharetra semper, nibh ante cursus purus, vel sagittis velit mauris vel metus. Nullam dapibus fermentum ipsum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Pellentesque sapien. Duis risus. Mauris elementum mauris vitae tortor. Suspendisse nisl. Integer rutrum, orci vestibulum ullamcorper ultricies, lacus quam ultricies odio, vitae placerat pede sem sit amet enim.
In laoreet, magna id viverra tincidunt, sem odio bibendum justo, vel imperdiet sapien wisi sed libero. Proin pede metus, vulputate nec, fermentum fringilla, vehicula vitae, justo. Nullam justo enim, consectetuer nec, ullamcorper ac, vestibulum in, elit. Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? Maecenas lorem. Etiam posuere lacus quis dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Curabitur ligula sapien, pulvinar a vestibulum quis, facilisis vel sapien. Nam sed tellus id magna elementum tincidunt. Suspendisse nisl. Vivamus luctus egestas leo. Nulla non arcu lacinia neque faucibus fringilla. Etiam dui sem, fermentum vitae, sagittis id, malesuada in, quam. Etiam dictum tincidunt diam. Etiam commodo dui eget wisi. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Proin pede metus, vulputate nec, fermentum fringilla, vehicula vitae, justo. Duis ante orci, molestie vitae vehicula venenatis, tincidunt ac pede. Pellentesque sapien.
EOD;

    /**
     * To be called from data reset code only,
    * do not use in tests.
    * @return void
    */
    public function reset() {
        $this->usercounter = 0;
        $this->$groupcount = 0;
        $this->$institutioncount = 0;
Doris Tam's avatar
Doris Tam committed
72
        self::$viewcolcounts = array();
Son Nguyen's avatar
Son Nguyen committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103

        foreach ($this->generators as $generator) {
            $generator->reset();
        }
    }

    /**
     * Return generator for given plugin.
     * @param string $plugintype the plugin type, e.g. 'artefact' or 'blocktype'.
     * @param string $pluginname the plugin name, e.g. 'blog' or 'file'.
     * @return an instance of a plugin generator extending from CoreGenerator.
     */
    public function get_plugin_generator($plugintype, $pluginname) {
        $pluginfullname = "{$plugintype}.{$pluginname}";
        if (isset($this->generators[$pluginfullname])) {
            return $this->generators[$pluginfullname];
        }
        safe_require($plugintype, $pluginname, 'tests/generator/lib.php');

        $classname =  generate_generator_class_name($plugintype, $pluginname);

        if (!class_exists($classname)) {
            throw new UndefinedException("The plugin $pluginfullname does not support " .
                            "data generators yet. Class {$classname} not found.");
        }

        $this->generators[$pluginfullname] = new $classname($this);
        return $this->generators[$pluginfullname];

    }

104
105
106
107
    /**
     * Gets the user id from it's username.
     * @param string $username
     * @return int the user id
108
     *     = false if not exists
109
110
111
112
113
114
115
116
117
118
119
120
121
     */
    protected function get_user_id($username) {
        if (($res = get_records_sql_array('SELECT id FROM {usr} WHERE LOWER(TRIM(username)) = ?', array(strtolower(trim($username)))))
            && count($res) === 1) {
            return $res[0]->id;
        }
        return false;
    }

    /**
     * Gets the group id from it's name.
     * @param string $groupname
     * @return int the group id
122
     *     = false if not exists
123
124
125
126
127
128
129
130
131
132
133
134
135
     */
    protected function get_group_id($groupname) {
        if (($res = get_records_sql_array('SELECT id FROM {group} WHERE LOWER(TRIM(name)) = ?', array(strtolower(trim($groupname)))))
            && count($res) === 1) {
            return $res[0]->id;
        }
        return false;
    }

    /**
     * Gets the institution id from it's name.
     * @param string $instname
     * @return int the institution id
136
     *     = false if not exists
137
138
139
140
141
142
143
144
145
     */
    protected function get_institution_id($instname) {
        if (($res = get_records_sql_array('SELECT id FROM {institution} WHERE name = ?', array($instname)))
            && count($res) === 1) {
            return $res[0]->id;
        }
        return false;
    }

146
147
148
149
150
151
152
153
154
155
156
157
158
    /**
     * Gets the view id from it's title.
     * @param string $viewtitle
     * @return int the view id
     *     = false if not exists
     */
    protected function get_view_id($viewtitle) {
        if ($res = get_record('view', 'title', $viewtitle)) {
            return $res->id;
        }
        return false;
    }

159
160
161
    /**
     * Gets the id of one site administrator.
     * @return int the admin id
162
     *     = false if not exists
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
     */
    protected function get_first_site_admin_id() {
        if ($admins = get_records_sql_array('
            SELECT u.id
            FROM {usr} u
            WHERE u.admin = 1 AND u.active = 1', array())) {
            return $admins[0]->id;
        }
        return false;
    }

    /**
     * Gets the id of one administrator of the institution given by name.
     * @param string $instname
     * @return int the admin id
178
     *     = false if not exists
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
     */
    protected function get_first_institution_admin_id($instname) {
        if ($admins = get_records_sql_array('
            SELECT u.id
            FROM {usr} u
                INNER JOIN {usr_institution} ui ON ui.usr = u.id
            WHERE ui.institution = ?
                AND ui.admin = 1
                AND u.active = 1', array($instname))) {
            return $admins[0]->id;
        }
        return false;
    }

    /**
     * Gets the id of one administrator of the group given by ID.
     * @param int $groupid
     * @return int the group admin id
197
     *     = false if not exists
198
199
200
201
202
203
204
205
206
207
208
209
210
211
     */
    protected function get_first_group_admin_id($groupid) {
        if ($admins = get_records_sql_array('
            SELECT u.id
            FROM {usr} u
                INNER JOIN {group_member} gm ON gm.member = u.id
            WHERE  gm.group = ?
                AND gm.role = ?
                AND u.active = 1', array($groupid, 'admin'))) {
            return $admins[0]->id;
        }
        return false;
    }

Son Nguyen's avatar
Son Nguyen committed
212
213
214
215
216
217
218
219
220
221
222
223
224
    /**
     * Create a test user
     * @param array $record
     * @throws SystemException if creating failed
     * @return int new user id
     */
    public function create_user($record) {
        // Data validation
        // Set default auth method for a new user is 'internal' for 'No institution' if not set
        if (empty($record['institution']) || empty($record['authname'])) {
            $record['institution'] = 'mahara';
            $record['authname'] = 'internal';
        }
225
        if (!$auth = get_record('auth_instance', 'institution', $record['institution'], 'authname', $record['authname'], 'active', 1)) {
226
            throw new SystemException("The authentication method authname " . $record['authname'] . " for institution '" . $record['institution'] . "' does not exist.");
Son Nguyen's avatar
Son Nguyen committed
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
        }
        $record['authinstance'] = $auth->id;
        // Don't exceed max user accounts for the institution
        $institution = new Institution($record['institution']);
        if ($institution->isFull()) {
            throw new SystemException("Can not add new users to the institution '" . $record['institution'] . "' as it is full.");
        }

        $record['firstname'] = sanitize_firstname($record['firstname']);
        $record['lastname']  = sanitize_lastname($record['lastname']);
        $record['email']     = sanitize_email($record['email']);

        $authobj = AuthFactory::create($auth->id);
        if (method_exists($authobj, 'is_username_valid_admin') && !$authobj->is_username_valid_admin($record['username'])) {
            throw new SystemException("New username'" . $record['username'] . "' is not valid.");
        }
        if (method_exists($authobj, 'is_username_valid') && !$authobj->is_username_valid($record['username'])) {
            throw new SystemException("New username'" . $record['username'] . "' is not valid.");
        }
246
        if (record_exists_select('usr', 'LOWER(username) = ?', array(strtolower($record['username'])))) {
Son Nguyen's avatar
Son Nguyen committed
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
            throw new ErrorException("The username'" . $record['username'] . "' has been taken.");
        }
        if (method_exists($authobj, 'is_password_valid') && !$authobj->is_password_valid($record['password'])) {
            throw new ErrorException("The password'" . $record['password'] . "' is not valid.");
        }
        if (record_exists('usr', 'email', $record['email'])
                        || record_exists('artefact_internal_profile_email', 'email', $record['email'])) {
            throw new ErrorException("The email'" . $record['email'] . "' has been taken.");
        }

        // Create new user
        db_begin();
        raise_time_limit(180);

        $user = (object)array(
                'authinstance'   => $record['authinstance'],
                'username'       => $record['username'],
                'firstname'      => $record['firstname'],
                'lastname'       => $record['lastname'],
                'email'          => $record['email'],
                'password'       => $record['password'],
                'passwordchange' => 0,
        );
        if ($record['institution'] == 'mahara') {
            if ($record['role'] == 'admin') {
                $user->admin = 1;
            }
            else if ($record['role'] == 'staff') {
                $user->staff = 1;
            }
        }

        $remoteauth = $record['authname'] != 'internal';
        if (!isset($record['remoteusername'])) {
            $record['remoteusername'] = null;
        }

284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
        $valid_profile_fields = array('studentid', 'preferredname', 'town', 'country', 'occupation');
        $profiles = array();
        foreach ($valid_profile_fields as $field) {
            if (isset($record[$field]) && !empty($record[$field])) {
                if ($field == 'country') {
                    $countries = getoptions_country();
                    $validcountry = false;
                    if (array_key_exists($record[$field], $countries)) {
                        $validcountry = $record[$field];
                    }
                    else if ($key = array_search($record[$field], $countries)) {
                        $validcountry = $key;
                    }
                    else {
                        throw new SystemException("Invalid profile country name '" . $record['country'] . "'");
                    }
                    $record[$field] = $validcountry;
                }
                $profiles[$field] = $record[$field];
            }
        }
        $user->id = create_user($user, $profiles, $record['institution'], $remoteauth, $record['remoteusername'], $record);
Son Nguyen's avatar
Son Nguyen committed
306
307
308
309
310

        if (isset($user->admin) && $user->admin) {
            require_once('activity.php');
            activity_add_admin_defaults(array($user->id));
        }
311
312
313
314
315
316
317
318
        // Use the institution's privacy option if exists
        $instprivacy = get_field('site_content_version', 'id', 'type', 'privacy', 'institution', $record['institution']);
        $siteprivacy = get_field('site_content_version', 'id', 'type', 'privacy', 'institution', 'mahara');

        // Accept the user privacy agreement
        $sitecontentid = $instprivacy ? $instprivacy : $siteprivacy;
        $agreed = !empty($record['agreement']) ? (bool)$record['agreement'] : 1; // accept by default
        save_user_reply_to_agreement($user->id, $sitecontentid, $agreed);
Son Nguyen's avatar
Son Nguyen committed
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362

        if ($record['institution'] != 'mahara') {
            if ($record['role'] == 'admin') {
                set_field('usr_institution', 'admin', 1, 'usr', $user->id, 'institution', $record['institution']);
            }
            else if ($record['role'] == 'staff') {
                set_field('usr_institution', 'staff', 1, 'usr', $user->id, 'institution', $record['institution']);
            }
        }

        db_commit();
        $this->usercounter++;
        return $user->id;
    }

    /**
     * Create a test group
     * @param array $record
     * @throws ErrorException if creating failed
     * @return int new group id
     */
    public function create_group($record) {
        // Data validation
        $record['name'] = trim($record['name']);
        if ($ids = get_records_sql_array('SELECT id FROM {group} WHERE LOWER(TRIM(name)) = ?', array(strtolower($record['name'])))) {
            if (count($ids) > 1 || $ids[0]->id != $group_data->id) {
                throw new SystemException("Invalid group name '" . $record['name'] . "'. " . get_string('groupalreadyexists', 'group'));
            }
        }
        $record['owner'] = trim($record['owner']);
        $ids = get_records_sql_array('SELECT id FROM {usr} WHERE LOWER(TRIM(username)) = ?', array(strtolower($record['owner'])));
        if (!$ids || count($ids) > 1) {
            throw new SystemException("Invalid group owner '" . $record['owner'] . "'. The username does not exist or duplicated");
        }
        $members = array($ids[0]->id => 'admin');
        if (!empty($record['members'])) {
            foreach (explode(',', $record['members']) as $membername) {
                $ids = get_records_sql_array('SELECT id FROM {usr} WHERE LOWER(TRIM(username)) = ?', array(strtolower(trim($membername))));
                if (!$ids || count($ids) > 1) {
                    throw new SystemException("Invalid group member '" . $membername . "'. The username does not exist or duplicated");
                }
                $members[$ids[0]->id] = 'member';
            }
        }
363
        if (!empty($record['staff']) && !empty($record['grouptype'])) {
Son Nguyen's avatar
Son Nguyen committed
364
365
366
367
368
            foreach (explode(',', $record['staff']) as $membername) {
                $ids = get_records_sql_array('SELECT id FROM {usr} WHERE LOWER(TRIM(username)) = ?', array(strtolower(trim($membername))));
                if (!$ids || count($ids) > 1) {
                    throw new SystemException("Invalid group staff '" . $membername . "'. The username does not exist or duplicated");
                }
369
370
371
372
373
374
                if ($record['grouptype'] == 'course') {
                    $members[$ids[0]->id] = 'tutor';
                }
                else {
                    $members[$ids[0]->id] = 'admin';
                }
Son Nguyen's avatar
Son Nguyen committed
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
            }
        }
        if (!empty($record['admins'])) {
            foreach (explode(',', $record['admins']) as $membername) {
                $ids = get_records_sql_array('SELECT id FROM {usr} WHERE LOWER(TRIM(username)) = ?', array(strtolower(trim($membername))));
                if (!$ids || count($ids) > 1) {
                    throw new SystemException("Invalid group admin '" . $membername . "'. The username does not exist or duplicated");
                }
                $members[$ids[0]->id] = 'admin';
            }
        }
        $availablegrouptypes = group_get_grouptypes();
        if (!in_array($record['grouptype'], $availablegrouptypes)) {
            throw new SystemException("Invalid grouptype '" . $record['grouptype'] . "'. This grouptype does not exist.\n"
                            . "The available grouptypes are " . join(', ', $availablegrouptypes));
        }
        $availablegroupeditroles = array_keys(group_get_editroles_options());
        if (!in_array($record['editroles'], $availablegroupeditroles)) {
            throw new SystemException("Invalid group editroles '" . $record['editroles'] . "'. This edit role does not exist.\n"
                            . "The available group editroles are " . join(', ', $availablegroupeditroles));
        }
        if (!empty($record['open'])) {
            if (!empty($record['controlled'])) {
                throw new SystemException('Invalid group membership setting. ' . get_string('membershipopencontrolled', 'group'));
            }
            if (!empty($record['request'])) {
                throw new SystemException('Invalid group membership setting. ' . get_string('membershipopenrequest', 'group'));
            }
        }
        if (!empty($record['invitefriends']) && !empty($record['suggestfriends'])) {
            throw new SystemException('Invalid friend invitation setting. ' . get_string('suggestinvitefriends', 'group'));
        }
        if (!empty($record['suggestfriends']) && empty($record['open']) && empty($record['request'])) {
            throw new SystemException('Invalid friend invitation setting. ' . get_string('suggestfriendsrequesterror', 'group'));
        }
        if (!empty($record['editwindowstart']) && !empty($record['editwindowend']) && ($record['editwindowstart'] >= $record['editwindowend'])) {
            throw new SystemException('Invalid group editability setting. ' . get_string('editwindowendbeforestart', 'group'));
        }
413
414
415
416
417
        if (!empty($record['institution'])) {
            if (!get_field('institution', 'id', 'name', $record['institution'])) {
                throw new SystemException('Invalid institution for group - Institution with short name "' . $record['institution'] . '" does not exist');
            }
        }
Son Nguyen's avatar
Son Nguyen committed
418
419
420
421
422
423
424
425
426
427
428
        $group_data = array(
                'id'             => null,
                'name'           => $record['name'],
                'description'    => isset($record['description']) ? $record['description'] : null,
                'grouptype'      => $record['grouptype'],
                'open'           => isset($record['open']) ? $record['open'] : 1,
                'controlled'     => isset($record['controlled']) ? $record['controlled'] : 0,
                'request'        => isset($record['request']) ? $record['request'] : 0,
                'invitefriends'  => isset($record['invitefriends']) ? $record['invitefriends'] : 0,
                'suggestfriends' => isset($record['suggestfriends']) ? $record['suggestfriends'] : 0,
                'category'       => null,
429
                'public'         => isset($record['public']) ? $record['public'] : 0,
Son Nguyen's avatar
Son Nguyen committed
430
431
432
                'usersautoadded' => 0,
                'viewnotify'     => GROUP_ROLES_ALL,
                'submittableto'  => isset($record['submittableto']) ? $record['submittableto'] : 0,
433
                'allowarchives'  => isset($record['allowarchives']) ? $record['allowarchives'] : 0,
Son Nguyen's avatar
Son Nguyen committed
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
                'editroles'      => isset($record['editroles']) ? $record['editroles'] : 'all',
                'hidden'         => 0,
                'hidemembers'    => 0,
                'hidemembersfrommembers' => 0,
                'groupparticipationreports' => 0,
                'urlid'          => null,
                'editwindowstart' => isset($record['editwindowstart']) ? $record['editwindowstart'] : null,
                'editwindowend'  => isset($record['editwindowend']) ? $record['editwindowend'] : null,
                'sendnow'        => 0,
                'feedbacknotify' => GROUP_ROLES_ALL,
                'members'        => $members,
        );

        // Create a new group
        db_begin();
        $group_data['id'] = group_create($group_data);
450
451
452
453
454
        // Because group_create expects user to be logged in to check if they can create a group for a particular institution
        // we will make it for 'mahara' institution and then adjust it here
        if (!empty($record['institution'])) {
            set_field('group', 'institution', $record['institution'], 'id', $group_data['id']);
        }
Son Nguyen's avatar
Son Nguyen committed
455
456
457
458
459
460
461
462
463
464
465
466
467
468
        db_commit();

        $this->groupcount++;
        return $group_data['id'];
    }

    /**
     * Create a test institution
     * @param array $record
     * @throws ErrorException if creating failed
     * @return int new institution id
     */
    public function create_institution($record) {
        // Data validation
469
470
471
472
        if (empty($record['name']) || !preg_match('/^[a-zA-Z]{1,255}$/', $record['name'])) {
            throw new SystemException("Invalid institution name '" . $record['name'] .
                         "'. The institution name is entered for system database identification only and must be a single text word without numbers or symbols.");
        }
Son Nguyen's avatar
Son Nguyen committed
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
        if (!empty($record['name']) && record_exists('institution', 'name', $record['name'])) {
            throw new SystemException("Invalid institution name '" . $record['name'] . "'. " . get_string('institutionnamealreadytaken', 'admin'));
        }

        if (get_config('licensemetadata') && !empty($record['licensemandatory']) &&
                        (isset($record['licensedefault']) && $record['licensedefault'] == '')) {
            throw new SystemException("Invalid institution license setting. " . get_string('licensedefaultmandatory', 'admin'));
        }

        if (!empty($record['lang']) && $record['lang'] != 'sitedefault' && !array_key_exists($record['lang'], get_languages())) {
            throw new SystemException("Invalid institution language setting: '" . $record['lang'] . "'. This language is not installed for the site.");
        }
        // Create a new institution
        db_begin();
        // Update the basic institution record...
        $newinstitution = new Institution();
        $newinstitution->initialise($record['name'], $record['displayname']);
        $institution = $newinstitution->name;

        $newinstitution->showonlineusers = !isset($record['showonlineusers']) ? 2 : $record['showonlineusers'];
        if (get_config('usersuniquebyusername')) {
            // Registering absolutely not allowed when this setting is on, it's a
            // security risk. See the documentation for the usersuniquebyusername
            // setting for more information
            $newinstitution->registerallowed = 0;
        }
        else {
            $newinstitution->registerallowed = !empty($record['registerallowed']) ? 1 : 0;
            $newinstitution->registerconfirm  = !empty($record['registerconfirm']) ? 1 : 0;
        }

        if (!empty($record['lang'])) {
            if ($record['lang'] == 'sitedefault') {
                $newinstitution->lang = null;
            }
            else {
                $newinstitution->lang = $record['lang'];
            }
        }

        $newinstitution->theme = (empty($record['theme']) || $record['theme'] == 'sitedefault') ? null : $record['theme'];
        $newinstitution->dropdownmenu = (!empty($record['dropdownmenu'])) ? 1 : 0;
        $newinstitution->skins = (!empty($record['skins'])) ? 1 : 0;
516
        $newinstitution->tags = (!empty($record['tags'])) ? 1 : 0;
Son Nguyen's avatar
Son Nguyen committed
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
        $newinstitution->style = null;

        if (get_config('licensemetadata')) {
            $newinstitution->licensemandatory = (!empty($record['licensemandatory'])) ? 1 : 0;
            $newinstitution->licensedefault = (isset($record['licensedefault'])) ? $record['licensedefault'] : '';
        }

        $newinstitution->defaultquota = empty($record['defaultquota']) ? get_config_plugin('artefact', 'file', 'defaultquota') : $record['defaultquota'];

        $newinstitution->defaultmembershipperiod  = !empty($record['defaultmembershipperiod']) ? intval($record['defaultmembershipperiod']) : null;
        $newinstitution->maxuseraccounts = !empty($record['maxuseraccounts']) ? intval($record['maxuseraccounts']) : null;
        $newinstitution->expiry = !empty($record['expiry']) ? db_format_timestamp($record['expiry']) : null;

        $newinstitution->allowinstitutionpublicviews  = (isset($record['allowinstitutionpublicviews']) && $record['allowinstitutionpublicviews']) ? 1 : 0;

        // Save the changes to the DB
        $newinstitution->commit();

        // Automatically create an internal authentication authinstance
        $authinstance = (object)array(
                'instancename' => 'internal',
                'priority'     => 0,
539
                'active'       => 1,
Son Nguyen's avatar
Son Nguyen committed
540
541
542
543
                'institution'  => $newinstitution->name,
                'authname'     => 'internal',
        );
        insert_record('auth_instance', $authinstance);
544
545
546
547
548
549
550
551
552
553
        if (!empty($record['authname'])) {
            $authinstance = (object)array(
                'instancename' => $record['authname'],
                'priority'     => 1,
                'active'       => 1,
                'institution'  => $newinstitution->name,
                'authname'     => $record['authname'],
            );
            insert_record('auth_instance', $authinstance);
        }
Son Nguyen's avatar
Son Nguyen committed
554
555
556
557
558
559
560
561
562
563
        // We need to add the default lines to the site_content table for this institution
        // We also need to set the institution to be using default static pages to begin with
        // so that using custom institution pages is an opt-in situation
        $pages = site_content_pages();
        $now = db_format_timestamp(time());
        foreach ($pages as $name) {
            $page = new stdClass();
            $page->name = $name;
            $page->ctime = $now;
            $page->mtime = $now;
564
            $page->mauthor = 0;
565
            $page->content = get_string($page->name . 'defaultcontent', 'install', get_string('staticpageconfiginstitutions', 'install', get_config('wwwroot') . 'admin/users/institutionpages.php'));
Son Nguyen's avatar
Son Nguyen committed
566
567
568
569
570
571
572
573
574
575
            $page->institution = $newinstitution->name;
            insert_record('site_content', $page);

            $institutionconfig = new stdClass();
            $institutionconfig->institution = $newinstitution->name;
            $institutionconfig->field = 'sitepages_' . $name;
            $institutionconfig->value = 'mahara';
            insert_record('institution_config', $institutionconfig);
        }

Aaron Wells's avatar
Aaron Wells committed
576
577
578
579
        if (isset($record['commentthreaded'])) {
            set_config_institution($newinstitution->name, 'commentthreaded', (bool) $record['commentthreaded']);
        }

Son Nguyen's avatar
Son Nguyen committed
580
581
        db_commit();
    }
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634

    /**
     * Create an empty view
     * @param array $record
     * @throws SystemException if creating failed
     * @return int new view id
     */
    public function create_view($record) {
        switch ($record['ownertype']) {
            case 'institution':
                if (empty($record['ownername'])) {
                    $record['institution'] = 'mahara';
                    break;
                }
                if ($institutionid = $this->get_institution_id($record['ownername'])) {
                    $record['institution'] = $record['ownername'];
                    // Find one of the institution admins
                    if (!$userid = $this->get_first_institution_admin_id($record['ownername'])) {
                        // Find one of site admins
                        $userid = $this->get_first_site_admin_id();
                    }
                }
                else {
                    throw new SystemException("The institution '" . $record['ownername'] . "' does not exist.");
                }
                break;
            case 'group':
                if ($groupid = $this->get_group_id($record['ownername'])) {
                    $record['group'] = $groupid;
                    // Find one of the group admins
                    if (!$userid = $this->get_first_group_admin_id($groupid)) {
                        throw new SystemException("The group '" . $record['ownername'] . "' must have at least one administrator.");
                    }
                }
                else {
                    throw new SystemException("The group '" . $record['ownername'] . "' does not exist.");
                }
                break;
            case 'user':
            default:
                if ($ownerid = get_field('usr', 'id', 'username', $record['ownername'])) {
                    $record['owner'] = $ownerid;
                    // Find one of the site admins
                    $userid = $this->get_first_site_admin_id();
                }
                else {
                    throw new SystemException("The user '" . $record['ownername'] . "' does not exist.");
                }
                break;
        }
        if (empty($userid)) {
            $userid = $this->get_first_site_admin_id();
        }
635
636
637
638
        if (!empty($record['tags'])) {
            $record['tags'] = array_map('trim', explode(',', $record['tags']));
        }

639
        require_once('view.php');
640
641
642
        $view = View::create($record, $userid);
    }

643
644
    /**
     * Create block content for existing view
645
     * @param array $record data for each blocktype in each row of the testing table
646
647
648
649
650
651
652
     * @throws SystemException if creating failed
     * @return int new block id
     */
    public function create_block($record) {
        global $USER;
        $sql = "SELECT id FROM {view} WHERE LOWER(TRIM(title)) = ?";
        $page = strtolower(trim($record['page']));
653

Doris Tam's avatar
Doris Tam committed
654
655
656
657
658
        $view = trim($record['page']);
        $viewid = $this->get_view_id($view);

        if (!isset(self::$viewcolcounts[$viewid])) {
          self::$viewcolcounts[$viewid] = 1;
659
660
        }

661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
        $ids = get_records_sql_array($sql, array($page));
        if (!$ids || count($ids) > 1) {
            throw new SystemException("Invalid page name '" . $record['page'] . "'. The page title does not exist, or is duplicated.");
        }
        else {
            require_once('view.php');
            $view = new View($ids[0]->id);
            if (!empty($view->get('institution'))) {
                $ownertype = 'institution';
                $ownerid = $view->get('institution');
            }
            else if (!empty($view->get('group'))) {
                $ownertype = 'group';
                $ownerid = $view->get('group');
            }
            else {
                $ownertype = 'owner';
                $ownerid = $view->get('owner');
            }
        }
681
682
683

        $maxcols = 3;

684
685
686
687
688
689
690
691
692
        // We have a valid page so lets see if we can add a block to it
        $blocktype = strtolower(trim($record['type']));
        // Check that the blocktype exists and is active
        if (!get_record('blocktype_installed', 'active', 1, 'name', $blocktype)) {
            throw new SystemException("Invalid block type '" . $record['type'] . "'. The block type is either not installed or not active.");
        }
        $title = strtolower(trim($record['title']));

        // build configdata
693
        $configdata = $this->setup_retractable($record['retractable']);
694
        $data = trim($record['data']);
695
696
        $functionname = 'generate_configdata_'.$record['type'];
        $classname = 'TestingDataGenerator';
697

698
        if (is_callable($classname . '::'.$functionname)) {
Doris Tam's avatar
Doris Tam committed
699
            $result = call_static_method($classname, $functionname, $data, $ownertype, $ownerid, $title, $view);
700
            $configdata = array_merge($configdata, $result);
701
        }
702
703
704
705
        else {
            throw new SystemException("The blocktype {$record['type']} is not supported yet.");
        }

706
        // make new block
Doris Tam's avatar
Doris Tam committed
707
708
        self::create_new_block_instance($blocktype, $view, $viewid, $title, self::$viewcolcounts, $configdata, $maxcols);
    }
709

Doris Tam's avatar
Doris Tam committed
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
    public static function create_new_block_instance($blocktype, $view, $viewid, $title, $viewcolcounts, $configdata, $maxcols, $otherview = null) {
      safe_require('blocktype', $blocktype);
      $bi = new BlockInstance(0,
          array(
              'blocktype'  => $blocktype,
              'title'      => $title,
              'view'       => $viewid,
              'row'        => 1,
          )
      );
      if (!isset(self::$viewcolcounts[$viewid])) self::$viewcolcounts[$viewid] = 0;
      $bi->set('order', $view->get_current_max_order(1, self::$viewcolcounts[$viewid]) + 1);
      $bi->set('configdata', $configdata);
      $bi->set('column', self::$viewcolcounts[$viewid]);
      self::$viewcolcounts[$viewid] = ((self::$viewcolcounts[$viewid]+1) % $maxcols) ? (self::$viewcolcounts[$viewid]+1) % $maxcols : $maxcols;

      //in cases such as navigation where we want to add a block to a different view than the current.
      if ($otherview) {
        $otherview->addblockinstance($bi);
      }
      else {
        $bi->commit();
      }
733
734
    }

735
736
737
738
739
740
741
742
743
744
745
    /**
     * generate configdata for blocktype: blog aka journal
     * displaying the blogs that were created using the function create_blog
     * given a matching blog title
     *
     * @param string $data inside data column in behat test
     * @return array $configdata of key and values for db table
     */
    public static function generate_configdata_blog($data) {
      if (!$data) return;
      $configdata = array();
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766

        $fields = explode(';',$data);
        foreach($fields as $field) {
            list($key, $value) = explode('=', $field);
            $key=trim($key);
            $value=trim($value);

            if ($key == 'journaltitle') {
                $blogid = get_field('artefact', 'id', 'title', $value, 'artefacttype', 'blog');
                $configdata['artefactid'] = $blogid;
            }
            if ($key == 'copytype') {
                $configdata[$key]=$value;
            }
            if ($key == 'count') {
                $configdata[$key]=$value;
            }
        }
        return $configdata;
    }

767
768
769
770
771
772
773
774
    /**
     * generate configdata for blocktype: blogpost aka journalentry
     * displaying the blogposts that were created using the function create_blogpost
     * matching a given blog and entry title
     *
     * @param string $data inside data column in behat test
     * @return array $configdata of key and values for db table
     */
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
    public static function generate_configdata_blogpost($data) {
        if (!$data) return;
        $configdata = array();

        $blogpostid;
        $blogid;

        $fields = explode(';',$data);
        foreach($fields as $field) {
            list($key, $value) = explode('=', $field);
            $key = trim($key);
            $value = trim($value);

            if ($key == 'journaltitle') {
                $blogid = get_field('artefact', 'id', 'title', $value, 'artefacttype','blog');
            }
            if ($key == 'entrytitle') {
                $blogpostid = get_field('artefact','id','title',$value, 'parent',$blogid, 'artefacttype','blogpost');
                $configdata['artefactid'] = $blogpostid;
            }
            if ($key == 'copytype') {
                $configdata[$key]=$value;
            }
        }
        return $configdata;
    }

802
    /**
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
     * generate a comment blocktype.
     * @param string data inside the columm for data in behat table
     * @return array with redundant information as there is no specific artefact connected to it.
     * as it part of a view rather than a block instance, there is not configdata for the block
     * itself, but an empty array cannot be returned :(
     */
    public static function generate_configdata_comment($data) {
        if (!$data) return;
        $configdata = array();
        $configdata[] = $data;
        //cannot return an empty array even though the comment blocktype that refers to a view
        //does not require any configdata
        return $configdata;
    }

818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
    /**
     * generate configdata and instance for blocktype: creativecommons
     * @param string data inside the columm for data in behat table
     * @return array $configdata of key and values for db table
     */
    public static function generate_configdata_creativecommons($data) {
      $configdata = array();

      // there is no compulsory filled field in this blocktype but there cannot
      // be an empty array returned
      if (!$data)  $configdata[] = ' ';

      $fields = explode(';', $data);

      foreach( $fields as $field) {
        list($key, $value) = explode('=', $field);
        $value = trim(strtolower($value));

        switch ($key) {
          case 'commercialuse':
            //yes=0, no=1
            $configdata['noncommercial'] = $value == 'yes' ? 0:1;
            break;
          case 'license':
            //must be 3.0 or 2.0
            if ($value == 3.0 || $value == 2.0) {
              $configdata['version'] = (string)($value*10);
            }
            else $configdata['version'] = '30';
            break;
          case 'allowmods':
            //yes=0, yes(with mutual sharing)=1, no=2
            if ($value == 'yes') $configdata['noderivatives'] = '0';
            if ($value == 'yeswithsharing') $configdata['noderivatives'] = '1';
            if ($value == 'no') $configdata['noderivatives'] = '2';
            break;
          default:
            break;
        }
      }
      $configdata = PluginBlocktypeCreativecommons::instance_config_save($configdata);
      return $configdata;
    }

862
863
864
865
866
    /**
     * generate configdata for the blocktype: rss feeds/external feeds
     * @param string $data inside data column in behat test
     * @return array $configdata of key and values for db table
    */
Doris Tam's avatar
Doris Tam committed
867
    public static function generate_configdata_externalfeed($data) {
868
869
        if (!$data) return;

Doris Tam's avatar
Doris Tam committed
870
        list($key, $value) = explode('=', $data);
871

872
        if ($key == 'source') {
Doris Tam's avatar
Doris Tam committed
873
874
875
876
877
878
879
880
            $wheredata = array('url' => $value);
            $feeddata = PluginBlocktypeExternalfeed::parse_feed($value);
            $feeddata->content  = serialize($feeddata->content);
            $feeddata->image    = serialize($feeddata->image);
            $value = ensure_record_exists('blocktype_externalfeed_data', $wheredata, $feeddata, 'id', true);
        }
        return $configdata = array('feedid' => $value);
    }
881

Doris Tam's avatar
Doris Tam committed
882
    /**
883
884
885
886
     * generate configdata for the blocktype: external video
     * @param string $data inside data column in behat test
     * @return array $configdata of key and values for db table
     */
Doris Tam's avatar
Doris Tam committed
887
888
889
890
    public static function generate_configdata_externalvideo($data) {
        if (!$data) return;

        list($key, $value) = explode('=', $data);
891
        if ($key == 'source') {
Doris Tam's avatar
Doris Tam committed
892
893
            $sourceinfo = PluginBlocktypeExternalvideo::process_url($value);
            return $sourceinfo;
894
895
896
897
        }
    }

    /**
898
899
900
901
902
903
     * generate configdata for the blocktype: filedownload
     * @param string $data inside data column in behat test
     * @param string $ownertype of user
     * @param string $ownerid of the user
     * @return array $configdata of key and values for db table
     */
Doris Tam's avatar
Doris Tam committed
904
    public static function generate_configdata_filedownload($data, $ownertype, $ownerid) {
905
        if (!$data) return;
906

907
908
        $fields = explode(';', $data);
        $configdata = array();
909

910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
        foreach ($fields as $field) {
            list($key, $value) = explode('=', $field);
            $key=trim($key);
            $value=trim($value);

            if ($key == 'attachments') {
                $attachments = explode(',',$value);
                foreach ($attachments as $attachment) {
                    $path = get_mahararoot_dir() . '/test/behat/upload_files/' . $attachment;
                    $mimetype = mime_content_type($path);
                    list($media, $ext) = explode('/', $mimetype);
                    $mediatype = $media == 'application' ? 'attachment' : $media;

                    // we need to find the id of the item we are trying to attach and save it as artefactid
                    if (!$artefactid = get_field('artefact', 'id', 'title', $attachment, $ownertype, $ownerid)) {
925
                        $artefactid = TestingDataGenerator::create_artefact($file=$attachment, $ownertype, $ownerid, $mediatype);
926
927
928
929
                        TestingDataGenerator::file_creation($artefactid, $attachment, $ownertype, $ownerid);
                    }
                    $configdata['artefactids'][] = $artefactid;
                }
930
931
            }
        }
932
        return $configdata;
933
934
    }
    /**
935
936
937
938
939
940
941
     * generate configdata for the blocktype folder, which dealts with creating a folder artefact_type
     * as well as file artefacts and connecting them parent ids.
     * @param $data holds the config information from data column
     * @param $ownertype of user
     * @param $owenerid of the user
     * @return array $configdata of key and values for db table
     */
Doris Tam's avatar
Doris Tam committed
942
    public static function generate_configdata_folder($data, $ownertype, $ownerid) {
943
        if (!$data) return;
944

945
946
947
        $fields = explode(';', $data);
        $configdata = array();
        $foldername;
948

949
950
        foreach ($fields as $field) {
            list($key, $value) = explode('=', $field);
951

952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
            if ($key == 'dirname') {
                $foldername = $value;
                $folderartefactid = ArtefactTypeFolder::get_folder_id($foldername, $foldername, null, true, $ownerid);
                $configdata['artefactid'] = $folderartefactid;
            }
            if ($key == 'attachments') {
                $files = explode(',', $value);
                // upload each image and put into a folder
                foreach($files as $file) {
                    $path = get_mahararoot_dir() . '/test/behat/upload_files/' . $file;
                    $mimetype = mime_content_type($path);
                    list($media, $ext) = explode('/', $mimetype);
                    $mediatype = $media == 'application' ? 'attachment' : $media;

                    // we need to find the id of the item we are trying to attach and save it as artefactid
                    if (!$artefactid = get_field('artefact', 'id', 'title', $file, 'parent', $folderartefactid)) {
968
                        $artefactid = TestingDataGenerator::create_artefact($file, $ownertype, $ownerid, $mediatype, $folderartefactid);
969
970
971
                        TestingDataGenerator::file_creation($artefactid, $file, $ownertype, $ownerid);
                    }
                }
972
973
            }
        }
974
        return $configdata;
975
976
977
    }

    /**
978
979
980
981
982
983
     * generate configdata for blocktype: gallery
     * @param string $data inside data column in behat test
     * @param string $ownertype of user
     * @param string $ownerid of the user
     * @return array $configdata of key and values for db table
     */
Doris Tam's avatar
Doris Tam committed
984
    public static function generate_configdata_gallery($data, $ownertype, $ownerid) {
985
        if (!$data) return;
Doris Tam's avatar
Doris Tam committed
986

987
        $configdata = array();
Doris Tam's avatar
Doris Tam committed
988

989
990
991
        //separate gallery_images, select, width, style etc.
        $fields = explode(';', $data);
        foreach ($fields as $field) {
Doris Tam's avatar
Doris Tam committed
992

993
            list($key, $value) = explode('=', $field);
994
995
            $key = trim($key);
            $value = trim($value);
Doris Tam's avatar
Doris Tam committed
996

997
998
999
            if ($key == 'attachments') {
                $galleryimages = explode(',', $value);
                $value = array();
Doris Tam's avatar
Doris Tam committed
1000

1001
1002
                foreach ($galleryimages as $image) {
                    if (!$artefactid = get_field('artefact','id', 'title', $image)) {
1003
                        $artefactid = TestingDataGenerator::create_artefact($image, $ownertype, $ownerid, 'image');
1004
1005
1006
                        TestingDataGenerator::file_creation($artefactid, $image, $ownertype, $ownerid);
                    }
                    $configdata['artefactids'][] = $artefactid;
Doris Tam's avatar
Doris Tam committed
1007
                }
1008
            }
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
            if ($key == 'imagesel' || $key == 'width' || $key == 'showdesc' || $key == 'imagestyle' || 'photoframe' ) {

                //imageselection options are 0,1,2 in the table, changed for tester -_-
                if ($key == 'imagesel') {
                    $value -= 1;
                    $configdata['select'] = $value;
                }
                else if ($key == 'showdesc') {
                    $value = strtolower($value) == 'yes' ? 1:0;
                    $configdata['showdescription'] = $value;
                }
                else if ($key == 'imagestyle') {
                    $value -= 1;
                    $configdata['style'] = $value;
                }
                else {
                    $configdata[$key] = $value;
                }
1027
1028
1029
            }
        }
        return $configdata;
Doris Tam's avatar
Doris Tam committed
1030
1031
    }

1032
1033
1034
1035
1036
1037
1038
    /**
     * generate configdata for blocktype: html
     * @param string $data inside data column in blocktype tables
     * @param string $ownertype of user
     * @param string $ownerid of the user
     * @return array $configdata of key and values for db table
     */
Doris Tam's avatar
Doris Tam committed
1039
    public static function generate_configdata_html($data, $ownertype, $ownerid) {
1040
1041
        if (!$data) return;

Doris Tam's avatar
Doris Tam committed
1042
        $fields = explode(';', $data);
Doris Tam's avatar
Doris Tam committed
1043
1044
1045
1046
        $configdata = array();

        foreach ($fields as $field) {
            list($key, $value) = explode('=', $field);
Doris Tam's avatar
Doris Tam committed
1047
1048
            $key = trim($key);
            $value = trim($value);
1049
            if ($key == 'attachment') {
Doris Tam's avatar
Doris Tam committed
1050
1051
1052
                //retrieve/create and retrieve artefactid of artefact we are attaching to the block
                if (!$artefactid = get_field('artefact', 'id', 'title', $value)) {
                    //we must create the file artefact as it doesn't exist in the table
1053
                    $artefactid = TestingDataGenerator::create_artefact($file=$value, $ownertype, $ownerid, 'attachment');
Doris Tam's avatar
Doris Tam committed
1054
                    TestingDataGenerator::file_creation($artefactid, $file, $ownertype, $ownerid);
Doris Tam's avatar
Doris Tam committed
1055
                }
Doris Tam's avatar
Doris Tam committed
1056
                $configdata['artefactid'] = $artefactid;
Doris Tam's avatar
Doris Tam committed
1057
            }
1058
        }
Doris Tam's avatar
Doris Tam committed
1059
        return $configdata;
1060
1061
1062
    }

    /**
1063
1064
1065
1066
1067
1068
     * generate configdata for the blocktype: image
     * @param string $data inside data column in blocktype tables
     * @param string $ownertype of user
     * @param string $ownerid of the user
     * @return array $configdata of key and values for db table
     */
Doris Tam's avatar
Doris Tam committed
1069
    public static function generate_configdata_image($data, $ownertype, $ownerid) {
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
        if (!$data) return;

        $fields = explode(';', $data);
        $configdata = array();

        foreach ($fields as $field) {
            list($key, $value) = explode('=', $field);
            if ($key == 'attachment') {

                // we need to find the id of the item we are trying to attach and save it as artefactid
                if (!$artefactimageid = get_field('artefact', 'id', 'title', $value, $ownertype, $ownerid)) {
                    $artefactimageid = TestingDataGenerator::create_artefact($file=$value, $ownertype, $ownerid, 'image');
                    self::file_creation($artefactimageid, $value, $ownertype, $ownerid);
                }
                $configdata = array('artefactid' => $artefactimageid);
            }
            if ($key == 'width' || $key == 'showdescription' || $key == 'style' ) {
                $configdata[$key] = $value;
            }
        }
        return $configdata;
    }

    /**
1094
1095
1096
1097
1098
1099
     * generate configdata for the blocktype: internalmedia aka 'embeddedmedia
     * @param string $data inside data column in blocktype tables
     * @param string $ownertype of user
     * @param string $ownerid of the user
     * @return array $configdata of key and values of db table
     */
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
    public static function generate_configdata_internalmedia($data, $ownertype, $ownerid) {
        if (!$data) return;
        $mediatype;
        $configdata = array();

        $fields = explode(';', $data);
        foreach ($fields as $field) {

            list($key,$value) = explode('=', $field);
            $key=trim($key);
            $value=trim($value);

            if ($key == 'attachment') {
                $filenameparts = explode('.', $value);
                $ext = end($filenameparts);

                // we need to find the id of the item we are trying to attach and save it as artefactid
                if (!$artefactid = get_field('artefact', 'id', 'title', $value)) {

                    if ($ext == 'wmv' || $ext == 'webm' || $ext == 'mov'|| $ext == 'ogv' || $ext == 'mpeg' || $ext == 'mp4' || $ext == 'flv' || $ext == 'avi' || $ext == '3gp') {
                        $artefactid = TestingDataGenerator::create_artefact($file=$value, $ownertype, $ownerid, 'video');
                        TestingDataGenerator::file_creation($artefactid, $value, $ownertype, $ownerid);
                    }
                    if ($ext == 'mp3' || $ext == 'oga' || $ext == 'ogg') {
                        $artefactid = TestingDataGenerator::create_artefact($file=$value, $ownertype, $ownerid, 'audio');
                        TestingDataGenerator::file_creation($artefactid, $file=$value, $ownertype, $ownerid);
                    }
                }
                $value = $artefactid;
                $configdata['artefactid'] = $value;
            }
        }
        return $configdata;
1133
    }
Doris Tam's avatar
Doris Tam committed
1134

Doris Tam's avatar
Doris Tam committed
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
    /**
     * generate configdata for the blocktype: navigation and create navblocks*
     * **when copytoall is true**
     * @param string $data inside data column in blocktype tables
     * @param string $ownertype of user
     * @param string $ownerid of the user
     * @param string $title of block to be created* (when copytoall is true)
     * @param object the current view to create block on
     * @return array $configdata of key and values of db table
     */
    public static function generate_configdata_navigation($data, $ownertype, $ownerid, $title, $view) {
      if (!$data) return;

      $configdata = array();
      $copytoall = true;
      $collectionid;

      $fields = explode(';', $data);
      foreach($fields as $field) {
        $field = trim(strtolower($field));
        list($key, $value) = explode('=', $field);
        if ($key == 'collection') {
          $configdata[$key] = $collectionid =  get_field('collection', 'id', 'name', $value);
        }
        if ($key == 'copytoall') {
           $copytoall = $value == 'yes'? true : false;
        }
        $collectionobj = new Collection($collectionid);
        // CASE 2: the navigation block being created IS one of the view in the collection
        if ($collectionobj) {
           if ($copytoall) {
             foreach ($viewids = $collectionobj->get_viewids() as $viewid) {
               //if vid is not the exactly the same as the og nav block for this collection
               if ($viewid !== (int)$view->get('id')) {
                 $needsblock = true;

                 //if there exists nav blocks on this view/page
                 if ($navblocks = get_records_sql_array("SELECT id FROM {block_instance} WHERE blocktype = ? AND view = ?", array('navigation', $viewid))) {
                    foreach ($navblocks as $navblock) {
                       $bi = new BlockInstance($navblock->id);
                       $navblockconfigdata = $bi->get('configdata');
                       //if there exists is a nav block on this view that already links to the intended collection
                       if (!empty($navblockconfigdata['collection']) && $navblockconfigdata['collection'] == $configdata['collection']) {
                         $needsblock = false;
                       }
                    }
                 }
                 if ($needsblock) {
                    //need to add new navigation block
                    $otherview = new View($viewid);
                    // make new block
                    self::create_new_block_instance('navigation', $view, $viewid, $title, self::$viewcolcounts, $configdata, $maxcols = 3, $otherview);
                 }
               }
             }
           }
        }
      }
      return $configdata;
    }

Doris Tam's avatar
Doris Tam committed
1196
    /**
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
     * generate configdata for the bloctype: peerassessment
     * @param string $data inside data column in blocktype tables
     * @return array $configdata of key and values of db table
     */
    public static function generate_configdata_peerassessment($data) {
        if (!$data) return;
        $configdata = array();
        $configdata[] = $data;
        return $configdata;
    }

    /**
     * generate configdata for the blocktype: pdf
     * @param string $data inside data column in blocktype tables
     * @param string $ownertype of user
     * @param string $ownerid of the user
     * @return array $configdata of key and values of db table
     */
Doris Tam's avatar
Doris Tam committed
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
    public static function generate_configdata_pdf($data, $ownertype, $ownerid) {
        if (!$data) return;

        list($key, $value) = explode('=', $data);
        $key=trim($key);
        $value=trim($value);

        if ($key == 'attachment') {
            $key = 'artefactid';

            // we need to find the id of the item we are trying to attach and save it as artefactid
            if (!$artefactid = get_field('artefact', 'id', 'title', $value, $ownertype, $ownerid)) {
                $artefactid = TestingDataGenerator::create_artefact($file=$value, $ownertype, $ownerid, 'attachment');
                TestingDataGenerator::file_creation($artefactid, $value, $ownertype, $ownerid);
            }

            $value = $artefactid;
            $configdata = array();
            $configdata[$key] = $value;
        }
        return $configdata;
    }

1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
    public static function generate_configdata_plans($data) {
        if (!$data) return;
        $configdata = array();

        $fields = explode(';', $data);
        foreach($fields as $field) {
            $field = trim($field);
            list($key,$value) = explode('=', $field);
            $key = trim($key);
            $value = trim($value);

            if ($key == 'plans') {
                $key = 'artefactids';

                $plans = explode(',',$value);
                foreach ($plans as $plan) {
                    $planid;

                    if ($plan) {
                        if (!$planid = get_field('artefact', 'id', 'title', $plan, 'artefacttype', 'plan')) {
                            throw new SystemException("Invalid Plan '" . $plan . "'");
                        }
                    }
                    else {
                        //pick any plan artefact owned by the given user
                        $planid = get_field_sql("SELECT id FROM {artefact} WHERE artefacttype = ? AND " . $ownertype . " = ? ORDER BY id LIMIT 1", array('plan', $owner));
                        if (!$planid) {
                            throw new SystemException("The " . $record['ownertype'] . " " . $record['owner'] . " does not have a plan to add task to. Please create plan first");
                        }
                    }

                    if ($key == 'artefactids') {
                        $values[] = $planid;
                        $newvalue = $values;
                    }
                }
                $value = $newvalue;
                $configdata[$key] = $value;

            }
            if ($key == 'tasksdisplaycount') {
                $configdata['count'] = $value;
            }
        }
        return $configdata;
    }

1285
    /**
1286
1287
1288
1289
1290
1291
     * generate configdata for the blocktype: social profile
     * @param string $data inside data column in behat test
     * @param string $ownertype of user
     * @param string $ownerid of the user
     * @return array $configdata of key and values for db table
     */
1292
1293
1294
1295
    public static function generate_configdata_socialprofile($data, $ownertype, $ownerid) {
        if (!$data) return;

        list($key, $value) = explode('=', $data);
1296
1297
1298
        $key = trim($key);
        $value = trim($value);

1299
        if ($key == 'sns') {
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
            //split the values for multiple social profile creation
            $medialist = explode(',', $value);
            $value = array();
            foreach($medialist as $media) {
                $newprofile = new ArtefactTypeSocialprofile();
                $newprofile->set('owner', $ownerid);
                $newprofile->set('author',$ownerid);
                $newprofile->set('title', $media);
                $newprofile->set('description', $media);
                $newprofile->set('note', $media);
                $id = $newprofile->commit(); //update the contents of the artefact table only
                $artefactid[] = $newprofile->get('id');
            }
            return $configdata = array('artefactids' => $artefactid);
        }
    }

    /**
1318
1319
1320
1321
     * generate configdata for the blocktype: text
     * @param string inside data column in behat test
     * @return array $configdata of key and values for db table
     */
Doris Tam's avatar
Doris Tam committed
1322
    public static function generate_configdata_text($data) {
1323
        if (!$data) return;
1324
        return $configdata = array('text' => $data);
Doris Tam's avatar
Doris Tam committed
1325
    }
1326

Doris Tam's avatar
Doris Tam committed
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
    /**
    * Copies file from /test/behat/upload_files folder and places it in the dataroot folder of the site.
    * Then write contents into it given the artefact id
    * @param int $artefactid of the file artefact created in the upload_file function
    * @param string $file attachment for uploading images, pdf, etc.
    * @param int $ownertype of the user
    * @param int $ownerid of the user
    **/
    public static function file_creation($artefactid, $file, $ownertype, $ownerid, $foldername='upload_files') {
        // get the path of the file artefact from given artefactid
        $filedir = get_config('dataroot') . ArtefactTypeFile::get_file_directory($artefactid);

        if (!check_dir_exists($filedir, true, true)) {
            throw new SystemException("Unable to create folder $filedir");
        }
        else {
            // Write contents to a file...
            $filepath = $filedir . '/' . $artefactid;
            $path = get_mahararoot_dir() . '/test/behat/upload_files/' . $file;
            copy($path, $filepath);
            chmod($filepath, get_config('filepermissions'));
        }
        if (!$artefactid) {
            throw new SystemException("Invalid attachment '" . $file . "'. No attachment by that name owned by " . $ownertype . " with id " . $ownerid);
        }
1352
    }
Doris Tam's avatar
Doris Tam committed
1353

1354
1355
    /**
     * set up configdata for retractable and retractable on load
1356
1357
     * @param string $setting: auto, yes, no
     * @return array $configdata of key and values for db table
1358
1359
     */
    public function setup_retractable($setting) {
1360
1361
1362
        $configdata = array();
        $configdata['retractable'] = strtolower($setting) =='no' ? 0:1;;
        $configdata['retractedonload'] = strtolower($setting) =='auto'? 1:0;
1363
1364
1365
1366
1367

        return $configdata;
    }

    /**
1368
    * Create artefacts
Doris Tam's avatar
Doris Tam committed
1369
1370
1371
    * @param string $file name
    * @param string $ownertype i.e. institution, group, onwer
    * @param int $ownerid
1372
    * @param string $filetype of the upload file
Doris Tam's avatar
Doris Tam committed
1373
1374
1375
    * @param string $foldername to upload the file into
    * @return int artefactid
    **/
1376
    public static function create_artefact($file, $ownertype, $ownerid, $filetype, $parentfolderid=null) {
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
        $ext = explode('.', $file);
        $now = date("Y-m-d H:i:s");
        $artefact = new stdClass();
        $artefact->title = $file;
        $artefact->oldextension = end($ext);
        $artefact->$ownertype = $ownerid;
        $artefact->author = $ownerid;
        $artefact->atime = $now;
        $artefact->ctime = $now;
        $artefact->mtime = $now;
Doris Tam's avatar
Doris Tam committed
1387
1388
1389
1390
1391
        if ($parentfolderid) {
            $artefact->parent = $parentfolderid;
        }

        $artefactid;
1392
        $path = get_mahararoot_dir() . '/test/behat/upload_files/' . $file;
1393
1394

        if ($filetype == 'image') {
Doris Tam's avatar
Doris Tam committed
1395

1396
1397
1398
1399
1400
1401
            $imageinfo      = getimagesize($path);
            $artefact->width    = $imageinfo[0];
            $artefact->height   = $imageinfo[1];

            $artimg = new ArtefactTypeImage(0, $artefact);
            $artimg->commit();
Doris Tam's avatar
Doris Tam committed
1402
            $artefactid = $artimg->get('id');
1403
        }
Doris Tam's avatar
Doris Tam committed
1404

1405
        if ($filetype == 'attachment') {
1406
1407
            $artobj = new ArtefactTypeFile(0, $artefact);
            $artobj->commit();
Doris Tam's avatar
Doris Tam committed
1408
            $artefactid = $artobj->get('id');
1409
        }
Doris Tam's avatar
Doris Tam committed
1410

1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
        if ($filetype == 'audio') {
            $artefact->filetype = 'audio';
            $artobj = ArtefactTypeFile::new_file($path, $artefact);
            $artobj->commit();
            $artefactid = $artobj->get('id');
        }

        if ($filetype == 'video') {
            //this function from artefact/file/lib.php creates the specific ArtefactType[]
            $artobj = ArtefactTypeFile::new_file($path, $artefact);
            $artobj->commit();
            $artefactid = $artobj->get('id');
        }
Doris Tam's avatar
Doris Tam committed
1424
        return $artefactid;
1425
1426
    }

1427
    /**
1428
1429
1430
1431
     * A fixture to set up collections of pages in bulk.
     * Currently it only supports adding title / description,
     * | title          | ownertype | ownername | description | pages             |
     * | collection one | user      | UserA     | desc of col |Page One,Page Two  |
1432
1433
1434
1435
1436
1437
     * @param array $record
     * @throws SystemException if creating failed
     * @return int new collection id
     */
    public function create_collection($record) {
        // Validation
1438
        $sqljoin = $sqlwhere = null;
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
        switch ($record['ownertype']) {
            case 'institution':
                if (empty($record['ownername'])) {
                    $record['institution'] = 'mahara';
                    break;
                }
                if ($institutionid = $this->get_institution_id($record['ownername'])) {
                    $record['institution'] = $record['ownername'];
                }
                else {
                    throw new SystemException("The institution '" . $record['ownername'] . "' does not exist.");
                }
1451
1452
                $sqljoin = 'INNER JOIN {institution} i ON i.name = v.institution';
                $sqlwhere = 'AND i.displayname = ?';
1453
1454
1455
1456
1457
1458
1459
1460
                break;
            case 'group':
                if ($groupid = $this->get_group_id($record['ownername'])) {
                    $record['group'] = $groupid;
                }
                else {
                    throw new SystemException("The group '" . $record['ownername'] . "' does not exist.");
                }
1461
1462
                $sqljoin = 'INNER JOIN {group} g ON g.id = v.group';
                $sqlwhere = 'AND g.name = ?';
1463
1464
1465
1466
1467
1468
1469
1470
1471
                break;
            case 'user':
            default:
                if ($ownerid = get_field('usr', 'id', 'username', $record['ownername'])) {
                    $record['owner'] = $ownerid;
                }
                else {
                    throw new SystemException("The user '" . $record['ownername'] . "' does not exist.");
                }
1472
1473
                $sqljoin = 'INNER JOIN {usr} u ON u.id = v.owner';
                $sqlwhere = 'AND u.username = ?';
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
                break;
        }
        // Check if the given pages exist and belong to the collection's owner
        $addviews = array();
        if (!empty($record['pages'])) {
            $record['pages'] = trim($record['pages']);
            $viewtitles = !empty($record['pages']) ?
                                  explode(',', $record['pages'])
                                : false;
            if (!empty($viewtitles)) {
                foreach ($viewtitles as $viewtitle) {
                    if (!empty($viewtitle) &&
1486
                        ! $view = get_record_sql('SELECT v.id FROM {view} v ' . $sqljoin . ' WHERE v.title = ? ' . $sqlwhere
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
                            , array(trim($viewtitle), $record['ownername']))
                        ) {
                        throw new SystemException("The page '" . $viewtitle
                            . "' does not exist or not belong to the user '" . $record['ownername'] . "'.");
                    }
                    $addviews['view_' . $view->id] = true;
                }
            }
        }

        // Create a new collection
        require_once('collection.php');
1499
        $data = new stdClass();
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
        $data->name = $record['title'];
        $data->description = $record['description'];
        if (!empty($record['group'])) {
            $data->group = $record['group'];
        }
        else if (!empty($record['institution'])) {
            $data->institution = $record['institution'];
        }
        else if (!empty($record['owner'])) {
            $data->owner = $record['owner'];
        }
1511
1512
        $data->navigation = 1;
        $data->submittedstatus = 0;
1513
1514
1515
1516
1517
1518
1519
1520
        $collection = new Collection(0, $data);
        $collection->commit();
        // Add views to the collection
        if (!empty($addviews)) {
            $collection->add_views($addviews);
        }
    }

1521
1522
1523
1524
1525
1526
1527

    /**
     * A fixture to set up journals in bulk.
     * Currently it only supports adding title / description / tags for a blog
     *
     * Example:
     * Given the following "journals" exist:
1528
1529
1530
     * | owner   | ownertype | title      | description           | tags      |
     * | userA   | user      | Blog One   | This is my new blog   | cats,dogs |
     * | Group B | group     | Group Blog | This is my group blog |           |
1531
1532
1533
     * @param unknown $record
     * @throws SystemException
     */
1534
    public function create_blog($record) {
1535
1536
        $owner = null;
        $ownertype = null;
1537
1538
        $this->set_owner($record, $owner, $ownertype);

1539
1540
1541
        $record['title'] = trim($record['title']);
        if (!empty($record['title'])) {
            // Check the blog does not already exist with that name
1542
            $blogid = get_field('artefact', 'id', 'artefacttype', 'blog', 'title', $record['title']);
1543
1544
1545
1546
1547
1548
1549
1550
            if ($blogid) {
                throw new SystemException("Invalid journal with '" . $record['title'] . "'. The blog already exists for this " . $record['owner'] . " " . $record['ownertype']);
            }
        }
        else {
            throw new systemException("The " . $record['title'] . " cannot be empty");
        }
        safe_require('artefact', 'blog');
1551
1552
1553
        if (!empty($record['tags'])) {
            $tags = array_map('trim', explode(',', $record['tags']));
        }
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
        $blogobj = new ArtefactTypeBlog(null, (object) array(
            'title' => trim($record['title']),
            'description' => trim($record['description']),
            'tags' => (!empty($tags) ? $tags : null),
            $ownertype => $owner,
        ));
        $blogobj->commit();
    }

    /**
     * A fixture to set up journal entries in bulk.
     * Currently it only supports adding title / description / tags for a blog entry
     *
     * Example: