~ubuntu-branches/ubuntu/utopic/moodle/utopic

« back to all changes in this revision

Viewing changes to lib/tests/moodlelib_test.php

  • Committer: Package Import Robot
  • Author(s): Thijs Kinkhorst
  • Date: 2014-05-12 16:10:38 UTC
  • mfrom: (36.1.3 sid)
  • Revision ID: package-import@ubuntu.com-20140512161038-puyqf65k4e0s8ytz
Tags: 2.6.3-1
New upstream release.

Show diffs side-by-side

added added

removed removed

Lines of Context:
26
26
 
27
27
defined('MOODLE_INTERNAL') || die();
28
28
 
29
 
global $CFG;
30
 
require_once($CFG->libdir . '/moodlelib.php');
31
 
 
32
 
 
33
 
class moodlelib_testcase extends advanced_testcase {
 
29
class core_moodlelib_testcase extends advanced_testcase {
34
30
 
35
31
    public static $includecoverage = array('lib/moodlelib.php');
36
32
 
37
 
    var $user_agents = array(
38
 
        'MSIE' => array(
39
 
            '5.0' => array('Windows 98' => 'Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)'),
40
 
            '5.5' => array('Windows 2000' => 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)'),
41
 
            '6.0' => array('Windows XP SP2' => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)'),
42
 
            '7.0' => array('Windows XP SP2' => 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; YPC 3.0.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)'),
43
 
            '8.0' => array('Windows Vista' => 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648)'),
44
 
            '9.0' => array('Windows 7' => 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)'),
45
 
            '9.0i' => array('Windows 7' => 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)'),
46
 
            '10.0' => array('Windows 8' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0; Touch)'),
47
 
            '10.0i' => array('Windows 8' => 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.2; Trident/6.0; Touch; .NET4.0E; .NET4.0C; Tablet PC 2.0)'),
48
 
            '11.0' => array('Windows 8.1' => 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0)'),
49
 
        ),
50
 
        'Firefox' => array(
51
 
            '1.0.6'   => array('Windows XP' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6'),
52
 
            '1.5'     => array('Windows XP' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; nl; rv:1.8) Gecko/20051107 Firefox/1.5'),
53
 
            '1.5.0.1' => array('Windows XP' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.0.1) Gecko/20060111 Firefox/1.5.0.1'),
54
 
            '2.0'     => array('Windows XP' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1',
55
 
                               'Ubuntu Linux AMD64' => 'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.8.1) Gecko/20060601 Firefox/2.0 (Ubuntu-edgy)'),
56
 
            '3.0.6'   => array('SUSE' => 'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.6) Gecko/2009012700 SUSE/3.0.6-1.4 Firefox/3.0.6'),
57
 
            '3.6'     => array('Linux' => 'Mozilla/5.0 (X11; Linux i686; rv:2.0) Gecko/20100101 Firefox/3.6'),
58
 
            '11.0'    => array('Windows' => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko Firefox/11.0'),
59
 
            '15.0a2'  => array('Windows' => 'Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20120716 Firefox/15.0a2'),
60
 
            '18.0'    => array('Mac OS X' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:18.0) Gecko/18.0 Firefox/18.0'),
61
 
        ),
62
 
        'SeaMonkey' => array(
63
 
            '2.0' => array('Windows' => 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1b3pre) Gecko/20081208 SeaMonkey/2.0'),
64
 
            '2.1' => array('Linux' => 'Mozilla/5.0 (X11; Linux x86_64; rv:2.0.1) Gecko/20110609 Firefox/4.0.1 SeaMonkey/2.1'),
65
 
            '2.3' => array('FreeBSD' => 'Mozilla/5.0 (X11; FreeBSD amd64; rv:6.0) Gecko/20110818 Firefox/6.0 SeaMonkey/2.3'),
66
 
        ),
67
 
        'Safari' => array(
68
 
            '312' => array('Mac OS X' => 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/312.1 (KHTML, like Gecko) Safari/312'),
69
 
            '412' => array('Mac OS X' => 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/412 (KHTML, like Gecko) Safari/412')
70
 
        ),
71
 
        'Safari iOS' => array(
72
 
            '528' => array('iPhone' => 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_1_2 like Mac OS X; cs-cz) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7D11 Safari/528.16'),
73
 
            '533' => array('iPad' => 'Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5'),
74
 
        ),
75
 
        'WebKit Android' => array(
76
 
            '525' => array('G1 Phone' => 'Mozilla/5.0 (Linux; U; Android 1.1; en-gb; dream) AppleWebKit/525.10+ (KHTML, like Gecko) Version/3.0.4 Mobile Safari/523.12.2 – G1 Phone'),
77
 
            '530' => array('Nexus' => 'Mozilla/5.0 (Linux; U; Android 2.1; en-us; Nexus One Build/ERD62) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17 –Nexus'),
78
 
        ),
79
 
        'Chrome' => array(
80
 
            '8' => array('Mac OS X' => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.215 Safari/534.10'),
81
 
        ),
82
 
        'Opera' => array(
83
 
            '8.51' => array('Windows XP' => 'Opera/8.51 (Windows NT 5.1; U; en)'),
84
 
            '9.0'  => array('Windows XP' => 'Opera/9.0 (Windows NT 5.1; U; en)',
85
 
                'Debian Linux' => 'Opera/9.01 (X11; Linux i686; U; en)')
86
 
        )
87
 
    );
88
 
 
89
33
    /**
90
34
     * Define a local decimal separator.
91
35
     *
95
39
     * The example separator used here is 'X'; on PHP 5.3 and before this
96
40
     * must be a single byte character due to PHP bug/limitation in
97
41
     * number_format, so you can't use UTF-8 characters.
98
 
     *
99
 
     * @global type $SESSION
100
 
     * @global type $CFG
101
42
     */
102
43
    protected function define_local_decimal_separator() {
103
44
        global $SESSION, $CFG;
109
50
        file_put_contents($langfolder . '/langconfig.php', $langconfig);
110
51
    }
111
52
 
112
 
    function test_cleanremoteaddr() {
113
 
        //IPv4
114
 
        $this->assertEquals(cleanremoteaddr('1023.121.234.1'), null);
115
 
        $this->assertEquals(cleanremoteaddr('123.121.234.01 '), '123.121.234.1');
 
53
    public function test_cleanremoteaddr() {
 
54
        // IPv4.
 
55
        $this->assertNull(cleanremoteaddr('1023.121.234.1'));
 
56
        $this->assertSame('123.121.234.1', cleanremoteaddr('123.121.234.01 '));
116
57
 
117
 
        //IPv6
118
 
        $this->assertEquals(cleanremoteaddr('0:0:0:0:0:0:0:0:0'), null);
119
 
        $this->assertEquals(cleanremoteaddr('0:0:0:0:0:0:0:abh'), null);
120
 
        $this->assertEquals(cleanremoteaddr('0:0:0:::0:0:1'), null);
121
 
        $this->assertEquals(cleanremoteaddr('0:0:0:0:0:0:0:0', true), '::');
122
 
        $this->assertEquals(cleanremoteaddr('0:0:0:0:0:0:1:1', true), '::1:1');
123
 
        $this->assertEquals(cleanremoteaddr('abcd:00ef:0:0:0:0:0:0', true), 'abcd:ef::');
124
 
        $this->assertEquals(cleanremoteaddr('1:0:0:0:0:0:0:1', true), '1::1');
125
 
        $this->assertEquals(cleanremoteaddr('::10:1', false), '0:0:0:0:0:0:10:1');
126
 
        $this->assertEquals(cleanremoteaddr('01:1::', false), '1:1:0:0:0:0:0:0');
127
 
        $this->assertEquals(cleanremoteaddr('10::10', false), '10:0:0:0:0:0:0:10');
128
 
        $this->assertEquals(cleanremoteaddr('::ffff:192.168.1.1', true), '::ffff:c0a8:11');
 
58
        // IPv6.
 
59
        $this->assertNull(cleanremoteaddr('0:0:0:0:0:0:0:0:0'));
 
60
        $this->assertNull(cleanremoteaddr('0:0:0:0:0:0:0:abh'));
 
61
        $this->assertNull(cleanremoteaddr('0:0:0:::0:0:1'));
 
62
        $this->assertSame('::', cleanremoteaddr('0:0:0:0:0:0:0:0', true));
 
63
        $this->assertSame('::1:1', cleanremoteaddr('0:0:0:0:0:0:1:1', true));
 
64
        $this->assertSame('abcd:ef::', cleanremoteaddr('abcd:00ef:0:0:0:0:0:0', true));
 
65
        $this->assertSame('1::1', cleanremoteaddr('1:0:0:0:0:0:0:1', true));
 
66
        $this->assertSame('0:0:0:0:0:0:10:1', cleanremoteaddr('::10:1', false));
 
67
        $this->assertSame('1:1:0:0:0:0:0:0', cleanremoteaddr('01:1::', false));
 
68
        $this->assertSame('10:0:0:0:0:0:0:10', cleanremoteaddr('10::10', false));
 
69
        $this->assertSame('::ffff:c0a8:11', cleanremoteaddr('::ffff:192.168.1.1', true));
129
70
    }
130
71
 
131
 
    function test_address_in_subnet() {
132
 
        /// 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn          (number of bits in net mask)
 
72
    public function test_address_in_subnet() {
 
73
        // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask).
133
74
        $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.1/32'));
134
75
        $this->assertFalse(address_in_subnet('123.121.23.1', '123.121.23.0/32'));
135
76
        $this->assertTrue(address_in_subnet('10.10.10.100',  '123.121.23.45/0'));
147
88
        $this->assertFalse(address_in_subnet('baba::aba:00ba', 'baba::baba:0/112'));
148
89
        $this->assertFalse(address_in_subnet('aba::baba:0000', 'baba::baba:0/112'));
149
90
 
150
 
        // fixed input
 
91
        // Fixed input.
151
92
        $this->assertTrue(address_in_subnet('123.121.23.1   ', ' 123.121.23.0 / 24'));
152
93
        $this->assertTrue(address_in_subnet('::ffff:10.1.1.1', ' 0:0:0:000:0:ffff:a1:10 / 126'));
153
94
 
154
 
        // incorrect input
 
95
        // Incorrect input.
155
96
        $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/-2'));
156
97
        $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/64'));
157
98
        $this->assertFalse(address_in_subnet('123.121.234.x', '123.121.234.1/24'));
163
104
        $this->assertFalse(address_in_subnet('x:1', '::aa:0/130'));
164
105
        $this->assertFalse(address_in_subnet('::1', '::ax:0/130'));
165
106
 
166
 
 
167
 
        /// 2: xxx.xxx.xxx.xxx-yyy or  xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::xxxx-yyyy (a range of IP addresses in the last group)
 
107
        // 2: xxx.xxx.xxx.xxx-yyy or  xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::xxxx-yyyy (a range of IP addresses in the last group).
168
108
        $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12-14'));
169
109
        $this->assertTrue(address_in_subnet('123.121.234.13', '123.121.234.12-14'));
170
110
        $this->assertTrue(address_in_subnet('123.121.234.14', '123.121.234.12-14'));
180
120
        $this->assertFalse(address_in_subnet('bab:baba::bfbe', 'bab:baba::baba-babe'));
181
121
        $this->assertFalse(address_in_subnet('bfb:baba::babe', 'bab:baba::baba-babe'));
182
122
 
183
 
        // fixed input
 
123
        // Fixed input.
184
124
        $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12 - 14 '));
185
125
        $this->assertTrue(address_in_subnet('bab:baba::babe', 'bab:baba::baba - babe  '));
186
126
 
187
 
        // incorrect input
 
127
        // Incorrect input.
188
128
        $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12-234.14'));
189
129
        $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12-256'));
190
130
        $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12--256'));
191
131
 
192
 
 
193
 
        /// 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.                  (incomplete address, a bit non-technical ;-)
 
132
        // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-).
194
133
        $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12'));
195
134
        $this->assertFalse(address_in_subnet('123.121.23.12', '123.121.23.13'));
196
135
        $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.'));
205
144
        $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:'));
206
145
        $this->assertFalse(address_in_subnet('bab:baba::bab', 'baba:'));
207
146
 
208
 
 
209
 
        /// multiple subnets
 
147
        // Multiple subnets.
210
148
        $this->assertTrue(address_in_subnet('123.121.234.12', '::1/64, 124., 123.121.234.10-30'));
211
149
        $this->assertTrue(address_in_subnet('124.121.234.12', '::1/64, 124., 123.121.234.10-30'));
212
150
        $this->assertTrue(address_in_subnet('::2',            '::1/64, 124., 123.121.234.10-30'));
213
151
        $this->assertFalse(address_in_subnet('12.121.234.12', '::1/64, 124., 123.121.234.10-30'));
214
152
 
215
 
 
216
 
        /// other incorrect input
 
153
        // Other incorrect input.
217
154
        $this->assertFalse(address_in_subnet('123.123.123.123', ''));
218
155
    }
219
156
 
220
 
    /**
221
 
     * Modifies $_SERVER['HTTP_USER_AGENT'] manually to check if check_browser_version
222
 
     * works as expected.
223
 
     */
224
 
    function test_check_browser_version()
225
 
    {
226
 
        global $CFG;
227
 
 
228
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Safari']['412']['Mac OS X'];
229
 
        $this->assertTrue(check_browser_version('Safari'));
230
 
        $this->assertTrue(check_browser_version('WebKit'));
231
 
        $this->assertTrue(check_browser_version('Safari', '312'));
232
 
        $this->assertFalse(check_browser_version('Safari', '500'));
233
 
        $this->assertFalse(check_browser_version('Chrome'));
234
 
        $this->assertFalse(check_browser_version('Safari iOS'));
235
 
 
236
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Safari iOS']['528']['iPhone'];
237
 
        $this->assertTrue(check_browser_version('Safari iOS'));
238
 
        $this->assertTrue(check_browser_version('WebKit'));
239
 
        $this->assertTrue(check_browser_version('Safari iOS', '527'));
240
 
        $this->assertFalse(check_browser_version('Safari iOS', 590));
241
 
        $this->assertFalse(check_browser_version('Safari', '312'));
242
 
        $this->assertFalse(check_browser_version('Safari', '500'));
243
 
        $this->assertFalse(check_browser_version('Chrome'));
244
 
 
245
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['WebKit Android']['530']['Nexus'];
246
 
        $this->assertTrue(check_browser_version('WebKit'));
247
 
        $this->assertTrue(check_browser_version('WebKit Android', '527'));
248
 
        $this->assertFalse(check_browser_version('WebKit Android', 590));
249
 
        $this->assertFalse(check_browser_version('Safari'));
250
 
        $this->assertFalse(check_browser_version('Chrome'));
251
 
 
252
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Chrome']['8']['Mac OS X'];
253
 
        $this->assertTrue(check_browser_version('Chrome'));
254
 
        $this->assertTrue(check_browser_version('WebKit'));
255
 
        $this->assertTrue(check_browser_version('Chrome', 8));
256
 
        $this->assertFalse(check_browser_version('Chrome', 10));
257
 
        $this->assertFalse(check_browser_version('Safari', '1'));
258
 
 
259
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Opera']['9.0']['Windows XP'];
260
 
        $this->assertTrue(check_browser_version('Opera'));
261
 
        $this->assertTrue(check_browser_version('Opera', '8.0'));
262
 
        $this->assertFalse(check_browser_version('Opera', '10.0'));
263
 
 
264
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['6.0']['Windows XP SP2'];
265
 
        $this->assertTrue(check_browser_version('MSIE'));
266
 
        $this->assertTrue(check_browser_version('MSIE', '5.0'));
267
 
        $this->assertFalse(check_browser_version('MSIE', '7.0'));
268
 
 
269
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['5.0']['Windows 98'];
270
 
        $this->assertFalse(check_browser_version('MSIE'));
271
 
        $this->assertTrue(check_browser_version('MSIE', 0));
272
 
        $this->assertTrue(check_browser_version('MSIE', '5.0'));
273
 
        $this->assertFalse(check_browser_version('MSIE', '7.0'));
274
 
 
275
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['9.0']['Windows 7'];
276
 
        $this->assertTrue(check_browser_version('MSIE'));
277
 
        $this->assertTrue(check_browser_version('MSIE', 0));
278
 
        $this->assertTrue(check_browser_version('MSIE', '5.0'));
279
 
        $this->assertTrue(check_browser_version('MSIE', '9.0'));
280
 
        $this->assertFalse(check_browser_version('MSIE', '10'));
281
 
 
282
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['9.0i']['Windows 7'];
283
 
        $this->assertTrue(check_browser_version('MSIE'));
284
 
        $this->assertTrue(check_browser_version('MSIE', 0));
285
 
        $this->assertTrue(check_browser_version('MSIE', '5.0'));
286
 
        $this->assertTrue(check_browser_version('MSIE', '9.0'));
287
 
        $this->assertFalse(check_browser_version('MSIE', '10'));
288
 
 
289
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['10.0']['Windows 8'];
290
 
        $this->assertTrue(check_browser_version('MSIE'));
291
 
        $this->assertTrue(check_browser_version('MSIE', 0));
292
 
        $this->assertTrue(check_browser_version('MSIE', '5.0'));
293
 
        $this->assertTrue(check_browser_version('MSIE', '9.0'));
294
 
        $this->assertTrue(check_browser_version('MSIE', '10'));
295
 
        $this->assertFalse(check_browser_version('MSIE', '11'));
296
 
 
297
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['10.0i']['Windows 8'];
298
 
        $this->assertTrue(check_browser_version('MSIE'));
299
 
        $this->assertTrue(check_browser_version('MSIE', 0));
300
 
        $this->assertTrue(check_browser_version('MSIE', '5.0'));
301
 
        $this->assertTrue(check_browser_version('MSIE', '9.0'));
302
 
        $this->assertTrue(check_browser_version('MSIE', '10'));
303
 
        $this->assertFalse(check_browser_version('MSIE', '11'));
304
 
 
305
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['11.0']['Windows 8.1'];
306
 
        $this->assertTrue(check_browser_version('MSIE'));
307
 
        $this->assertTrue(check_browser_version('MSIE', 0));
308
 
        $this->assertTrue(check_browser_version('MSIE', '5.0'));
309
 
        $this->assertTrue(check_browser_version('MSIE', '9.0'));
310
 
        $this->assertTrue(check_browser_version('MSIE', '10'));
311
 
        $this->assertTrue(check_browser_version('MSIE', '11'));
312
 
        $this->assertFalse(check_browser_version('MSIE', '12'));
313
 
 
314
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['2.0']['Windows XP'];
315
 
        $this->assertTrue(check_browser_version('Firefox'));
316
 
        $this->assertTrue(check_browser_version('Firefox', '1.5'));
317
 
        $this->assertFalse(check_browser_version('Firefox', '3.0'));
318
 
        $this->assertTrue(check_browser_version('Gecko', '2'));
319
 
        $this->assertTrue(check_browser_version('Gecko', 20030516));
320
 
        $this->assertTrue(check_browser_version('Gecko', 20051106));
321
 
        $this->assertTrue(check_browser_version('Gecko', 2006010100));
322
 
 
323
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['1.0.6']['Windows XP'];
324
 
        $this->assertTrue(check_browser_version('Firefox'));
325
 
        $this->assertTrue(check_browser_version('Gecko', '1'));
326
 
        $this->assertFalse(check_browser_version('Gecko', 20030516));
327
 
        $this->assertFalse(check_browser_version('Gecko', 20051106));
328
 
        $this->assertFalse(check_browser_version('Gecko', 2006010100));
329
 
        $this->assertFalse(check_browser_version('Firefox', '1.5'));
330
 
        $this->assertFalse(check_browser_version('Firefox', '3.0'));
331
 
        $this->assertFalse(check_browser_version('Gecko', '2'));
332
 
 
333
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['2.0']['Windows XP'];
334
 
        $this->assertTrue(check_browser_version('Firefox'));
335
 
        $this->assertTrue(check_browser_version('Firefox', '1.5'));
336
 
        $this->assertTrue(check_browser_version('Gecko', '1'));
337
 
        $this->assertTrue(check_browser_version('Gecko', '2'));
338
 
        $this->assertTrue(check_browser_version('Gecko', 20030516));
339
 
        $this->assertTrue(check_browser_version('Gecko', 20051106));
340
 
        $this->assertTrue(check_browser_version('Gecko', 2006010100));
341
 
        $this->assertFalse(check_browser_version('Firefox', '3.0'));
342
 
 
343
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['3.6']['Linux'];
344
 
        $this->assertTrue(check_browser_version('Firefox'));
345
 
        $this->assertTrue(check_browser_version('Firefox', '1.5'));
346
 
        $this->assertTrue(check_browser_version('Firefox', '3.0'));
347
 
        $this->assertTrue(check_browser_version('Gecko', '2'));
348
 
        $this->assertTrue(check_browser_version('Gecko', '3.6'));
349
 
        $this->assertTrue(check_browser_version('Gecko', 20030516));
350
 
        $this->assertTrue(check_browser_version('Gecko', 20051106));
351
 
        $this->assertTrue(check_browser_version('Gecko', 2006010100));
352
 
        $this->assertFalse(check_browser_version('Firefox', '4'));
353
 
        $this->assertFalse(check_browser_version('Firefox', '10'));
354
 
 
355
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['3.6']['Linux'];
356
 
        $this->assertTrue(check_browser_version('Firefox'));
357
 
        $this->assertTrue(check_browser_version('Firefox', '1.5'));
358
 
        $this->assertTrue(check_browser_version('Firefox', '3.0'));
359
 
        $this->assertTrue(check_browser_version('Gecko', '2'));
360
 
        $this->assertTrue(check_browser_version('Gecko', '3.6'));
361
 
        $this->assertTrue(check_browser_version('Gecko', 20030516));
362
 
        $this->assertTrue(check_browser_version('Gecko', 20051106));
363
 
        $this->assertTrue(check_browser_version('Gecko', 2006010100));
364
 
        $this->assertFalse(check_browser_version('Firefox', '4'));
365
 
        $this->assertFalse(check_browser_version('Firefox', '10'));
366
 
        $this->assertFalse(check_browser_version('Firefox', '18'));
367
 
        $this->assertFalse(check_browser_version('Gecko', '4'));
368
 
 
369
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['15.0a2']['Windows'];
370
 
        $this->assertTrue(check_browser_version('Firefox'));
371
 
        $this->assertTrue(check_browser_version('Firefox', '1.5'));
372
 
        $this->assertTrue(check_browser_version('Firefox', '3.0'));
373
 
        $this->assertTrue(check_browser_version('Gecko', '2'));
374
 
        $this->assertTrue(check_browser_version('Gecko', '3.6'));
375
 
        $this->assertTrue(check_browser_version('Gecko', '15.0'));
376
 
        $this->assertTrue(check_browser_version('Gecko', 20030516));
377
 
        $this->assertTrue(check_browser_version('Gecko', 20051106));
378
 
        $this->assertTrue(check_browser_version('Gecko', 2006010100));
379
 
        $this->assertTrue(check_browser_version('Firefox', '4'));
380
 
        $this->assertTrue(check_browser_version('Firefox', '10'));
381
 
        $this->assertTrue(check_browser_version('Firefox', '15'));
382
 
        $this->assertFalse(check_browser_version('Firefox', '18'));
383
 
        $this->assertFalse(check_browser_version('Gecko', '18'));
384
 
 
385
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['18.0']['Mac OS X'];
386
 
        $this->assertTrue(check_browser_version('Firefox'));
387
 
        $this->assertTrue(check_browser_version('Firefox', '1.5'));
388
 
        $this->assertTrue(check_browser_version('Firefox', '3.0'));
389
 
        $this->assertTrue(check_browser_version('Gecko', '2'));
390
 
        $this->assertTrue(check_browser_version('Gecko', '3.6'));
391
 
        $this->assertTrue(check_browser_version('Gecko', '15.0'));
392
 
        $this->assertTrue(check_browser_version('Gecko', '18.0'));
393
 
        $this->assertTrue(check_browser_version('Gecko', 20030516));
394
 
        $this->assertTrue(check_browser_version('Gecko', 20051106));
395
 
        $this->assertTrue(check_browser_version('Gecko', 2006010100));
396
 
        $this->assertTrue(check_browser_version('Firefox', '4'));
397
 
        $this->assertTrue(check_browser_version('Firefox', '10'));
398
 
        $this->assertTrue(check_browser_version('Firefox', '15'));
399
 
        $this->assertTrue(check_browser_version('Firefox', '18'));
400
 
        $this->assertFalse(check_browser_version('Firefox', '19'));
401
 
        $this->assertFalse(check_browser_version('Gecko', '19'));
402
 
 
403
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['SeaMonkey']['2.0']['Windows'];
404
 
 
405
 
        $this->assertTrue(check_browser_version('Gecko', '2'));
406
 
        $this->assertTrue(check_browser_version('Gecko', 20030516));
407
 
        $this->assertTrue(check_browser_version('Gecko', 20051106));
408
 
        $this->assertTrue(check_browser_version('Gecko', 2006010100));
409
 
        $this->assertFalse(check_browser_version('Gecko', '3.6'));
410
 
        $this->assertFalse(check_browser_version('Gecko', '4.0'));
411
 
        $this->assertFalse(check_browser_version('Firefox'));
412
 
 
413
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['SeaMonkey']['2.1']['Linux'];
414
 
        $this->assertTrue(check_browser_version('Gecko', '2'));
415
 
        $this->assertTrue(check_browser_version('Gecko', '3.6'));
416
 
        $this->assertTrue(check_browser_version('Gecko', '4.0'));
417
 
        $this->assertTrue(check_browser_version('Gecko', 20030516));
418
 
        $this->assertTrue(check_browser_version('Gecko', 20051106));
419
 
        $this->assertTrue(check_browser_version('Gecko', 2006010100));
420
 
        $this->assertTrue(check_browser_version('Firefox'));
421
 
        $this->assertTrue(check_browser_version('Firefox', 4.0));
422
 
        $this->assertFalse(check_browser_version('Firefox', 5));
423
 
        $this->assertFalse(check_browser_version('Gecko', '18.0'));
424
 
 
425
 
    }
426
 
 
427
 
    function test_get_browser_version_classes() {
428
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Safari']['412']['Mac OS X'];
429
 
        $this->assertEquals(array('safari'), get_browser_version_classes());
430
 
 
431
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Chrome']['8']['Mac OS X'];
432
 
        $this->assertEquals(array('safari'), get_browser_version_classes());
433
 
 
434
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Safari iOS']['528']['iPhone'];
435
 
        $this->assertEquals(array('safari', 'ios'), get_browser_version_classes());
436
 
 
437
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['WebKit Android']['530']['Nexus'];
438
 
        $this->assertEquals(array('safari', 'android'), get_browser_version_classes());
439
 
 
440
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Chrome']['8']['Mac OS X'];
441
 
        $this->assertEquals(array('safari'), get_browser_version_classes());
442
 
 
443
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Opera']['9.0']['Windows XP'];
444
 
        $this->assertEquals(array('opera'), get_browser_version_classes());
445
 
 
446
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['6.0']['Windows XP SP2'];
447
 
        $this->assertEquals(array('ie', 'ie6'), get_browser_version_classes());
448
 
 
449
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['7.0']['Windows XP SP2'];
450
 
        $this->assertEquals(array('ie', 'ie7'), get_browser_version_classes());
451
 
 
452
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['8.0']['Windows Vista'];
453
 
        $this->assertEquals(array('ie', 'ie8'), get_browser_version_classes());
454
 
 
455
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['9.0']['Windows 7'];
456
 
        $this->assertEquals(array('ie', 'ie9'), get_browser_version_classes());
457
 
 
458
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['9.0i']['Windows 7'];
459
 
        $this->assertEquals(array('ie', 'ie9'), get_browser_version_classes());
460
 
 
461
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['10.0']['Windows 8'];
462
 
        $this->assertEquals(array('ie', 'ie10'), get_browser_version_classes());
463
 
 
464
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['10.0i']['Windows 8'];
465
 
        $this->assertEquals(array('ie', 'ie10'), get_browser_version_classes());
466
 
 
467
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['2.0']['Windows XP'];
468
 
        $this->assertEquals(array('gecko', 'gecko18'), get_browser_version_classes());
469
 
 
470
 
        $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['3.0.6']['SUSE'];
471
 
        $this->assertEquals(array('gecko', 'gecko19'), get_browser_version_classes());
472
 
    }
473
 
 
474
 
    function test_get_device_type() {
475
 
        // IE8 (common pattern ~1.5% of IE7/8 users have embedded IE6 agent))
476
 
        $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; BT Openworld BB; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; Hotbar 10.2.197.0; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727)';
477
 
        $this->assertEquals('default', get_device_type());
478
 
        // Genuine IE6
479
 
        $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/4.0 (compatible; MSIE 6.0; AOL 9.0; Windows NT 5.1; SV1; FunWebProducts; .NET CLR 1.0.3705; Media Center PC 2.8)';
480
 
        $this->assertEquals('legacy', get_device_type());
481
 
    }
482
 
 
483
 
    function test_fix_utf8() {
484
 
        // make sure valid data including other types is not changed
 
157
    public function test_fix_utf8() {
 
158
        // Make sure valid data including other types is not changed.
485
159
        $this->assertSame(null, fix_utf8(null));
486
160
        $this->assertSame(1, fix_utf8(1));
487
161
        $this->assertSame(1.1, fix_utf8(1.1));
498
172
        // valid utf8 string
499
173
        $this->assertSame("žlutý koníček přeskočil potůček \n\t\r", fix_utf8("žlutý koníček přeskočil potůček \n\t\r\0"));
500
174
 
501
 
        // invalid utf8 string
 
175
        // Invalid utf8 string.
502
176
        $this->assertSame('aš', fix_utf8('a'.chr(130).'š'), 'This fails with buggy iconv() when mbstring extenstion is not available as fallback.');
503
177
    }
504
178
 
505
 
    function test_optional_param() {
 
179
    public function test_optional_param() {
506
180
        global $CFG;
507
181
 
508
182
        $_POST['username'] = 'post_user';
509
183
        $_GET['username'] = 'get_user';
510
 
        $this->assertSame(optional_param('username', 'default_user', PARAM_RAW), $_POST['username']);
 
184
        $this->assertSame($_POST['username'], optional_param('username', 'default_user', PARAM_RAW));
511
185
 
512
186
        unset($_POST['username']);
513
 
        $this->assertSame(optional_param('username', 'default_user', PARAM_RAW), $_GET['username']);
 
187
        $this->assertSame($_GET['username'], optional_param('username', 'default_user', PARAM_RAW));
514
188
 
515
189
        unset($_GET['username']);
516
 
        $this->assertSame(optional_param('username', 'default_user', PARAM_RAW), 'default_user');
 
190
        $this->assertSame('default_user', optional_param('username', 'default_user', PARAM_RAW));
517
191
 
518
 
        // make sure exception is triggered when some params are missing, hide error notices here - new in 2.2
 
192
        // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
519
193
        $_POST['username'] = 'post_user';
520
194
        try {
521
195
            optional_param('username', 'default_user', null);
522
196
            $this->fail('coding_exception expected');
523
 
        } catch (coding_exception $ex) {
524
 
            $this->assertTrue(true);
 
197
        } catch (moodle_exception $ex) {
 
198
            $this->assertInstanceOf('coding_exception', $ex);
525
199
        }
526
200
        try {
527
201
            @optional_param('username', 'default_user');
528
202
            $this->fail('coding_exception expected');
529
 
        } catch (coding_exception $ex) {
530
 
            $this->assertTrue(true);
 
203
        } catch (moodle_exception $ex) {
 
204
            $this->assertInstanceOf('coding_exception', $ex);
531
205
        }
532
206
        try {
533
207
            @optional_param('username');
534
208
            $this->fail('coding_exception expected');
535
 
        } catch (coding_exception $ex) {
536
 
            $this->assertTrue(true);
 
209
        } catch (moodle_exception $ex) {
 
210
            $this->assertInstanceOf('coding_exception', $ex);
537
211
        }
538
212
        try {
539
213
            optional_param('', 'default_user', PARAM_RAW);
540
214
            $this->fail('coding_exception expected');
541
 
        } catch (coding_exception $ex) {
542
 
            $this->assertTrue(true);
 
215
        } catch (moodle_exception $ex) {
 
216
            $this->assertInstanceOf('coding_exception', $ex);
543
217
        }
544
218
 
545
 
        // make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3
 
219
        // Make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3.
546
220
        $_POST['username'] = array('a'=>'a');
547
 
        $this->assertSame(optional_param('username', 'default_user', PARAM_RAW), $_POST['username']);
 
221
        $this->assertSame($_POST['username'], optional_param('username', 'default_user', PARAM_RAW));
548
222
        $this->assertDebuggingCalled();
549
223
    }
550
224
 
551
 
    function test_optional_param_array() {
 
225
    public function test_optional_param_array() {
552
226
        global $CFG;
553
227
 
554
228
        $_POST['username'] = array('a'=>'post_user');
555
229
        $_GET['username'] = array('a'=>'get_user');
556
 
        $this->assertSame(optional_param_array('username', array('a'=>'default_user'), PARAM_RAW), $_POST['username']);
 
230
        $this->assertSame($_POST['username'], optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
557
231
 
558
232
        unset($_POST['username']);
559
 
        $this->assertSame(optional_param_array('username', array('a'=>'default_user'), PARAM_RAW), $_GET['username']);
 
233
        $this->assertSame($_GET['username'], optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
560
234
 
561
235
        unset($_GET['username']);
562
 
        $this->assertSame(optional_param_array('username', array('a'=>'default_user'), PARAM_RAW), array('a'=>'default_user'));
 
236
        $this->assertSame(array('a'=>'default_user'), optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
563
237
 
564
 
        // make sure exception is triggered when some params are missing, hide error notices here - new in 2.2
 
238
        // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
565
239
        $_POST['username'] = array('a'=>'post_user');
566
240
        try {
567
241
            optional_param_array('username', array('a'=>'default_user'), null);
568
242
            $this->fail('coding_exception expected');
569
 
        } catch (coding_exception $ex) {
570
 
            $this->assertTrue(true);
 
243
        } catch (moodle_exception $ex) {
 
244
            $this->assertInstanceOf('coding_exception', $ex);
571
245
        }
572
246
        try {
573
247
            @optional_param_array('username', array('a'=>'default_user'));
574
248
            $this->fail('coding_exception expected');
575
 
        } catch (coding_exception $ex) {
576
 
            $this->assertTrue(true);
 
249
        } catch (moodle_exception $ex) {
 
250
            $this->assertInstanceOf('coding_exception', $ex);
577
251
        }
578
252
        try {
579
253
            @optional_param_array('username');
580
254
            $this->fail('coding_exception expected');
581
 
        } catch (coding_exception $ex) {
582
 
            $this->assertTrue(true);
 
255
        } catch (moodle_exception $ex) {
 
256
            $this->assertInstanceOf('coding_exception', $ex);
583
257
        }
584
258
        try {
585
259
            optional_param_array('', array('a'=>'default_user'), PARAM_RAW);
586
260
            $this->fail('coding_exception expected');
587
 
        } catch (coding_exception $ex) {
588
 
            $this->assertTrue(true);
 
261
        } catch (moodle_exception $ex) {
 
262
            $this->assertInstanceOf('coding_exception', $ex);
589
263
        }
590
264
 
591
 
        // do not allow nested arrays
 
265
        // Do not allow nested arrays.
592
266
        try {
593
267
            $_POST['username'] = array('a'=>array('b'=>'post_user'));
594
268
            optional_param_array('username', array('a'=>'default_user'), PARAM_RAW);
597
271
            $this->assertTrue(true);
598
272
        }
599
273
 
600
 
        // do not allow non-arrays
 
274
        // Do not allow non-arrays.
601
275
        $_POST['username'] = 'post_user';
602
 
        $this->assertSame(optional_param_array('username', array('a'=>'default_user'), PARAM_RAW), array('a'=>'default_user'));
 
276
        $this->assertSame(array('a'=>'default_user'), optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
603
277
        $this->assertDebuggingCalled();
604
278
 
605
 
        // make sure array keys are sanitised
 
279
        // Make sure array keys are sanitised.
606
280
        $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
607
 
        $this->assertSame(optional_param_array('username', array(), PARAM_RAW), array('a1_-'=>'post_user'));
 
281
        $this->assertSame(array('a1_-'=>'post_user'), optional_param_array('username', array(), PARAM_RAW));
608
282
        $this->assertDebuggingCalled();
609
283
    }
610
284
 
611
 
    function test_required_param() {
612
 
        global $CFG;
613
 
 
 
285
    public function test_required_param() {
614
286
        $_POST['username'] = 'post_user';
615
287
        $_GET['username'] = 'get_user';
616
 
        $this->assertSame(required_param('username', PARAM_RAW), 'post_user');
 
288
        $this->assertSame('post_user', required_param('username', PARAM_RAW));
617
289
 
618
290
        unset($_POST['username']);
619
 
        $this->assertSame(required_param('username', PARAM_RAW), 'get_user');
 
291
        $this->assertSame('get_user', required_param('username', PARAM_RAW));
620
292
 
621
293
        unset($_GET['username']);
622
294
        try {
623
 
            $this->assertSame(required_param('username', PARAM_RAW), 'default_user');
 
295
            $this->assertSame('default_user', required_param('username', PARAM_RAW));
624
296
            $this->fail('moodle_exception expected');
625
297
        } catch (moodle_exception $ex) {
626
 
            $this->assertTrue(true);
 
298
            $this->assertInstanceOf('moodle_exception', $ex);
627
299
        }
628
300
 
629
 
        // make sure exception is triggered when some params are missing, hide error notices here - new in 2.2
 
301
        // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
630
302
        $_POST['username'] = 'post_user';
631
303
        try {
632
304
            @required_param('username');
633
305
            $this->fail('coding_exception expected');
634
 
        } catch (coding_exception $ex) {
635
 
            $this->assertTrue(true);
 
306
        } catch (moodle_exception $ex) {
 
307
            $this->assertInstanceOf('coding_exception', $ex);
636
308
        }
637
309
        try {
638
310
            required_param('username', '');
639
311
            $this->fail('coding_exception expected');
640
 
        } catch (coding_exception $ex) {
641
 
            $this->assertTrue(true);
 
312
        } catch (moodle_exception $ex) {
 
313
            $this->assertInstanceOf('coding_exception', $ex);
642
314
        }
643
315
        try {
644
316
            required_param('', PARAM_RAW);
645
317
            $this->fail('coding_exception expected');
646
 
        } catch (coding_exception $ex) {
647
 
            $this->assertTrue(true);
 
318
        } catch (moodle_exception $ex) {
 
319
            $this->assertInstanceOf('coding_exception', $ex);
648
320
        }
649
321
 
650
 
        // make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3
 
322
        // Make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3.
651
323
        $_POST['username'] = array('a'=>'a');
652
 
        $this->assertSame(required_param('username', PARAM_RAW), $_POST['username']);
 
324
        $this->assertSame($_POST['username'], required_param('username', PARAM_RAW));
653
325
        $this->assertDebuggingCalled();
654
326
    }
655
327
 
656
 
    function test_required_param_array() {
 
328
    public function test_required_param_array() {
657
329
        global $CFG;
658
330
 
659
331
        $_POST['username'] = array('a'=>'post_user');
660
332
        $_GET['username'] = array('a'=>'get_user');
661
 
        $this->assertSame(required_param_array('username', PARAM_RAW), $_POST['username']);
 
333
        $this->assertSame($_POST['username'], required_param_array('username', PARAM_RAW));
662
334
 
663
335
        unset($_POST['username']);
664
 
        $this->assertSame(required_param_array('username', PARAM_RAW), $_GET['username']);
 
336
        $this->assertSame($_GET['username'], required_param_array('username', PARAM_RAW));
665
337
 
666
 
        // make sure exception is triggered when some params are missing, hide error notices here - new in 2.2
 
338
        // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
667
339
        $_POST['username'] = array('a'=>'post_user');
668
340
        try {
669
341
            required_param_array('username', null);
670
342
            $this->fail('coding_exception expected');
671
 
        } catch (coding_exception $ex) {
672
 
            $this->assertTrue(true);
 
343
        } catch (moodle_exception $ex) {
 
344
            $this->assertInstanceOf('coding_exception', $ex);
673
345
        }
674
346
        try {
675
347
            @required_param_array('username');
676
348
            $this->fail('coding_exception expected');
677
 
        } catch (coding_exception $ex) {
678
 
            $this->assertTrue(true);
 
349
        } catch (moodle_exception $ex) {
 
350
            $this->assertInstanceOf('coding_exception', $ex);
679
351
        }
680
352
        try {
681
353
            required_param_array('', PARAM_RAW);
682
354
            $this->fail('coding_exception expected');
683
 
        } catch (coding_exception $ex) {
684
 
            $this->assertTrue(true);
 
355
        } catch (moodle_exception $ex) {
 
356
            $this->assertInstanceOf('coding_exception', $ex);
685
357
        }
686
358
 
687
 
        // do not allow nested arrays
 
359
        // Do not allow nested arrays.
688
360
        try {
689
361
            $_POST['username'] = array('a'=>array('b'=>'post_user'));
690
362
            required_param_array('username', PARAM_RAW);
691
363
            $this->fail('coding_exception expected');
692
 
        } catch (coding_exception $ex) {
693
 
            $this->assertTrue(true);
 
364
        } catch (moodle_exception $ex) {
 
365
            $this->assertInstanceOf('coding_exception', $ex);
694
366
        }
695
367
 
696
 
        // do not allow non-arrays
 
368
        // Do not allow non-arrays.
697
369
        try {
698
370
            $_POST['username'] = 'post_user';
699
371
            required_param_array('username', PARAM_RAW);
700
372
            $this->fail('moodle_exception expected');
701
373
        } catch (moodle_exception $ex) {
702
 
            $this->assertTrue(true);
 
374
            $this->assertInstanceOf('moodle_exception', $ex);
703
375
        }
704
376
 
705
 
        // make sure array keys are sanitised
 
377
        // Make sure array keys are sanitised.
706
378
        $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
707
 
        $this->assertSame(required_param_array('username', PARAM_RAW), array('a1_-'=>'post_user'));
 
379
        $this->assertSame(array('a1_-'=>'post_user'), required_param_array('username', PARAM_RAW));
708
380
        $this->assertDebuggingCalled();
709
381
    }
710
382
 
711
 
    function test_clean_param() {
712
 
        // forbid objects and arrays
 
383
    public function test_clean_param() {
 
384
        // Forbid objects and arrays.
713
385
        try {
714
386
            clean_param(array('x', 'y'), PARAM_RAW);
715
387
            $this->fail('coding_exception expected');
716
 
        } catch (coding_exception $ex) {
717
 
            $this->assertTrue(true);
 
388
        } catch (moodle_exception $ex) {
 
389
            $this->assertInstanceOf('coding_exception', $ex);
718
390
        }
719
391
        try {
720
392
            $param = new stdClass();
721
393
            $param->id = 1;
722
394
            clean_param($param, PARAM_RAW);
723
395
            $this->fail('coding_exception expected');
724
 
        } catch (coding_exception $ex) {
725
 
            $this->assertTrue(true);
 
396
        } catch (moodle_exception $ex) {
 
397
            $this->assertInstanceOf('coding_exception', $ex);
726
398
        }
727
399
 
728
 
        // require correct type
 
400
        // Require correct type.
729
401
        try {
730
402
            clean_param('x', 'xxxxxx');
731
403
            $this->fail('moodle_exception expected');
732
404
        } catch (moodle_exception $ex) {
733
 
            $this->assertTrue(true);
 
405
            $this->assertInstanceOf('moodle_exception', $ex);
734
406
        }
735
407
        try {
736
408
            @clean_param('x');
737
409
            $this->fail('moodle_exception expected');
738
410
        } catch (moodle_exception $ex) {
739
 
            $this->assertTrue(true);
 
411
            $this->assertInstanceOf('moodle_exception', $ex);
740
412
        }
741
 
 
742
413
    }
743
414
 
744
 
    function test_clean_param_array() {
745
 
        $this->assertSame(clean_param_array(null, PARAM_RAW), array());
746
 
        $this->assertSame(clean_param_array(array('a', 'b'), PARAM_RAW), array('a', 'b'));
747
 
        $this->assertSame(clean_param_array(array('a', array('b')), PARAM_RAW, true), array('a', array('b')));
 
415
    public function test_clean_param_array() {
 
416
        $this->assertSame(array(), clean_param_array(null, PARAM_RAW));
 
417
        $this->assertSame(array('a', 'b'), clean_param_array(array('a', 'b'), PARAM_RAW));
 
418
        $this->assertSame(array('a', array('b')), clean_param_array(array('a', array('b')), PARAM_RAW, true));
748
419
 
749
 
        // require correct type
 
420
        // Require correct type.
750
421
        try {
751
422
            clean_param_array(array('x'), 'xxxxxx');
752
423
            $this->fail('moodle_exception expected');
753
424
        } catch (moodle_exception $ex) {
754
 
            $this->assertTrue(true);
 
425
            $this->assertInstanceOf('moodle_exception', $ex);
755
426
        }
756
427
        try {
757
428
            @clean_param_array(array('x'));
758
429
            $this->fail('moodle_exception expected');
759
430
        } catch (moodle_exception $ex) {
760
 
            $this->assertTrue(true);
 
431
            $this->assertInstanceOf('moodle_exception', $ex);
761
432
        }
762
433
 
763
434
        try {
764
435
            clean_param_array(array('x', array('y')), PARAM_RAW);
765
436
            $this->fail('coding_exception expected');
766
 
        } catch (coding_exception $ex) {
767
 
            $this->assertTrue(true);
 
437
        } catch (moodle_exception $ex) {
 
438
            $this->assertInstanceOf('coding_exception', $ex);
768
439
        }
769
440
 
770
 
        // test recursive
771
 
    }
772
 
 
773
 
    function test_clean_param_raw() {
774
 
        $this->assertEquals(clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_RAW),
775
 
            '#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)');
776
 
    }
777
 
 
778
 
    function test_clean_param_trim() {
779
 
        $this->assertEquals(clean_param("   Frog toad   \r\n  ", PARAM_RAW_TRIMMED), 'Frog toad');
780
 
    }
781
 
 
782
 
    function test_clean_param_clean() {
783
 
        // PARAM_CLEAN is an ugly hack, do not use in new code (skodak)
784
 
        // instead use more specific type, or submit sothing that can be verified properly
785
 
        $this->assertEquals(clean_param('xx<script>', PARAM_CLEAN), 'xx');
786
 
    }
787
 
 
788
 
    function test_clean_param_alpha() {
789
 
        $this->assertEquals(clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHA),
790
 
            'DSFMOSDJ');
791
 
    }
792
 
 
793
 
    function test_clean_param_alphanum() {
794
 
        $this->assertEquals(clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHANUM),
795
 
            '978942897DSFMOSDJ');
796
 
    }
797
 
 
798
 
    function test_clean_param_alphaext() {
799
 
        $this->assertEquals(clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHAEXT),
800
 
            'DSFMOSDJ');
801
 
    }
802
 
 
803
 
    function test_clean_param_sequence() {
804
 
        $this->assertEquals(clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_SEQUENCE),
805
 
            ',9789,42897');
806
 
    }
807
 
 
808
 
    function test_clean_param_component() {
809
 
        // please note the cleaning of component names is very strict, no guessing here
810
 
        $this->assertSame(clean_param('mod_forum', PARAM_COMPONENT), 'mod_forum');
811
 
        $this->assertSame(clean_param('block_online_users', PARAM_COMPONENT), 'block_online_users');
812
 
        $this->assertSame(clean_param('block_blond_online_users', PARAM_COMPONENT), 'block_blond_online_users');
813
 
        $this->assertSame(clean_param('mod_something2', PARAM_COMPONENT), 'mod_something2');
814
 
        $this->assertSame(clean_param('forum', PARAM_COMPONENT), 'forum');
815
 
        $this->assertSame(clean_param('user', PARAM_COMPONENT), 'user');
816
 
        $this->assertSame(clean_param('rating', PARAM_COMPONENT), 'rating');
817
 
        $this->assertSame(clean_param('mod_2something', PARAM_COMPONENT), '');
818
 
        $this->assertSame(clean_param('2mod_something', PARAM_COMPONENT), '');
819
 
        $this->assertSame(clean_param('mod_something_xx', PARAM_COMPONENT), '');
820
 
        $this->assertSame(clean_param('auth_something__xx', PARAM_COMPONENT), '');
821
 
        $this->assertSame(clean_param('mod_Something', PARAM_COMPONENT), '');
822
 
        $this->assertSame(clean_param('mod_somethíng', PARAM_COMPONENT), '');
823
 
        $this->assertSame(clean_param('auth_xx-yy', PARAM_COMPONENT), '');
824
 
        $this->assertSame(clean_param('_auth_xx', PARAM_COMPONENT), '');
825
 
        $this->assertSame(clean_param('a2uth_xx', PARAM_COMPONENT), '');
826
 
        $this->assertSame(clean_param('auth_xx_', PARAM_COMPONENT), '');
827
 
        $this->assertSame(clean_param('auth_xx.old', PARAM_COMPONENT), '');
828
 
        $this->assertSame(clean_param('_user', PARAM_COMPONENT), '');
829
 
        $this->assertSame(clean_param('2rating', PARAM_COMPONENT), '');
830
 
        $this->assertSame(clean_param('user_', PARAM_COMPONENT), '');
831
 
    }
832
 
 
833
 
    function test_is_valid_plugin_name() {
 
441
        // Test recursive.
 
442
    }
 
443
 
 
444
    public function test_clean_param_raw() {
 
445
        $this->assertSame(
 
446
            '#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)',
 
447
            clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_RAW));
 
448
    }
 
449
 
 
450
    public function test_clean_param_trim() {
 
451
        $this->assertSame('Frog toad', clean_param("   Frog toad   \r\n  ", PARAM_RAW_TRIMMED));
 
452
    }
 
453
 
 
454
    public function test_clean_param_clean() {
 
455
        // PARAM_CLEAN is an ugly hack, do not use in new code (skodak),
 
456
        // instead use more specific type, or submit sothing that can be verified properly.
 
457
        $this->assertSame('xx', clean_param('xx<script>', PARAM_CLEAN));
 
458
    }
 
459
 
 
460
    public function test_clean_param_alpha() {
 
461
        $this->assertSame('DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHA));
 
462
    }
 
463
 
 
464
    public function test_clean_param_alphanum() {
 
465
        $this->assertSame('978942897DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHANUM));
 
466
    }
 
467
 
 
468
    public function test_clean_param_alphaext() {
 
469
        $this->assertSame('DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHAEXT));
 
470
    }
 
471
 
 
472
    public function test_clean_param_sequence() {
 
473
        $this->assertSame(',9789,42897', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_SEQUENCE));
 
474
    }
 
475
 
 
476
    public function test_clean_param_component() {
 
477
        // Please note the cleaning of component names is very strict, no guessing here.
 
478
        $this->assertSame('mod_forum', clean_param('mod_forum', PARAM_COMPONENT));
 
479
        $this->assertSame('block_online_users', clean_param('block_online_users', PARAM_COMPONENT));
 
480
        $this->assertSame('block_blond_online_users', clean_param('block_blond_online_users', PARAM_COMPONENT));
 
481
        $this->assertSame('mod_something2', clean_param('mod_something2', PARAM_COMPONENT));
 
482
        $this->assertSame('forum', clean_param('forum', PARAM_COMPONENT));
 
483
        $this->assertSame('user', clean_param('user', PARAM_COMPONENT));
 
484
        $this->assertSame('rating', clean_param('rating', PARAM_COMPONENT));
 
485
        $this->assertSame('feedback360', clean_param('feedback360', PARAM_COMPONENT));
 
486
        $this->assertSame('mod_feedback360', clean_param('mod_feedback360', PARAM_COMPONENT));
 
487
        $this->assertSame('', clean_param('mod_2something', PARAM_COMPONENT));
 
488
        $this->assertSame('', clean_param('2mod_something', PARAM_COMPONENT));
 
489
        $this->assertSame('', clean_param('mod_something_xx', PARAM_COMPONENT));
 
490
        $this->assertSame('', clean_param('auth_something__xx', PARAM_COMPONENT));
 
491
        $this->assertSame('', clean_param('mod_Something', PARAM_COMPONENT));
 
492
        $this->assertSame('', clean_param('mod_somethíng', PARAM_COMPONENT));
 
493
        $this->assertSame('', clean_param('mod__something', PARAM_COMPONENT));
 
494
        $this->assertSame('', clean_param('auth_xx-yy', PARAM_COMPONENT));
 
495
        $this->assertSame('', clean_param('_auth_xx', PARAM_COMPONENT));
 
496
        $this->assertSame('', clean_param('a2uth_xx', PARAM_COMPONENT));
 
497
        $this->assertSame('', clean_param('auth_xx_', PARAM_COMPONENT));
 
498
        $this->assertSame('', clean_param('auth_xx.old', PARAM_COMPONENT));
 
499
        $this->assertSame('', clean_param('_user', PARAM_COMPONENT));
 
500
        $this->assertSame('', clean_param('2rating', PARAM_COMPONENT));
 
501
        $this->assertSame('', clean_param('user_', PARAM_COMPONENT));
 
502
    }
 
503
 
 
504
    public function test_is_valid_plugin_name() {
834
505
        $this->assertTrue(is_valid_plugin_name('forum'));
835
506
        $this->assertTrue(is_valid_plugin_name('forum2'));
 
507
        $this->assertTrue(is_valid_plugin_name('feedback360'));
836
508
        $this->assertTrue(is_valid_plugin_name('online_users'));
837
509
        $this->assertTrue(is_valid_plugin_name('blond_online_users'));
838
510
        $this->assertFalse(is_valid_plugin_name('online__users'));
845
517
        $this->assertFalse(is_valid_plugin_name('xx_'));
846
518
    }
847
519
 
848
 
    function test_clean_param_plugin() {
849
 
        // please note the cleaning of plugin names is very strict, no guessing here
850
 
        $this->assertSame(clean_param('forum', PARAM_PLUGIN), 'forum');
851
 
        $this->assertSame(clean_param('forum2', PARAM_PLUGIN), 'forum2');
852
 
        $this->assertSame(clean_param('online_users', PARAM_PLUGIN), 'online_users');
853
 
        $this->assertSame(clean_param('blond_online_users', PARAM_PLUGIN), 'blond_online_users');
854
 
        $this->assertSame(clean_param('online__users', PARAM_PLUGIN), '');
855
 
        $this->assertSame(clean_param('forum ', PARAM_PLUGIN), '');
856
 
        $this->assertSame(clean_param('forum.old', PARAM_PLUGIN), '');
857
 
        $this->assertSame(clean_param('xx-yy', PARAM_PLUGIN), '');
858
 
        $this->assertSame(clean_param('2xx', PARAM_PLUGIN), '');
859
 
        $this->assertSame(clean_param('Xx', PARAM_PLUGIN), '');
860
 
        $this->assertSame(clean_param('_xx', PARAM_PLUGIN), '');
861
 
        $this->assertSame(clean_param('xx_', PARAM_PLUGIN), '');
862
 
    }
863
 
 
864
 
    function test_clean_param_area() {
865
 
        // please note the cleaning of area names is very strict, no guessing here
866
 
        $this->assertSame(clean_param('something', PARAM_AREA), 'something');
867
 
        $this->assertSame(clean_param('something2', PARAM_AREA), 'something2');
868
 
        $this->assertSame(clean_param('some_thing', PARAM_AREA), 'some_thing');
869
 
        $this->assertSame(clean_param('some_thing_xx', PARAM_AREA), 'some_thing_xx');
870
 
        $this->assertSame(clean_param('_something', PARAM_AREA), '');
871
 
        $this->assertSame(clean_param('something_', PARAM_AREA), '');
872
 
        $this->assertSame(clean_param('2something', PARAM_AREA), '');
873
 
        $this->assertSame(clean_param('Something', PARAM_AREA), '');
874
 
        $this->assertSame(clean_param('some-thing', PARAM_AREA), '');
875
 
        $this->assertSame(clean_param('somethííng', PARAM_AREA), '');
876
 
        $this->assertSame(clean_param('something.x', PARAM_AREA), '');
877
 
    }
878
 
 
879
 
    function test_clean_param_text() {
880
 
        $this->assertEquals(PARAM_TEXT, PARAM_MULTILANG);
881
 
        //standard
882
 
        $this->assertEquals(clean_param('xx<lang lang="en">aa</lang><lang lang="yy">pp</lang>', PARAM_TEXT), 'xx<lang lang="en">aa</lang><lang lang="yy">pp</lang>');
883
 
        $this->assertEquals(clean_param('<span lang="en" class="multilang">aa</span><span lang="xy" class="multilang">bb</span>', PARAM_TEXT), '<span lang="en" class="multilang">aa</span><span lang="xy" class="multilang">bb</span>');
884
 
        $this->assertEquals(clean_param('xx<lang lang="en">aa'."\n".'</lang><lang lang="yy">pp</lang>', PARAM_TEXT), 'xx<lang lang="en">aa'."\n".'</lang><lang lang="yy">pp</lang>');
885
 
        //malformed
886
 
        $this->assertEquals(clean_param('<span lang="en" class="multilang">aa</span>', PARAM_TEXT), '<span lang="en" class="multilang">aa</span>');
887
 
        $this->assertEquals(clean_param('<span lang="en" class="nothing" class="multilang">aa</span>', PARAM_TEXT), 'aa');
888
 
        $this->assertEquals(clean_param('<lang lang="en" class="multilang">aa</lang>', PARAM_TEXT), 'aa');
889
 
        $this->assertEquals(clean_param('<lang lang="en!!">aa</lang>', PARAM_TEXT), 'aa');
890
 
        $this->assertEquals(clean_param('<span lang="en==" class="multilang">aa</span>', PARAM_TEXT), 'aa');
891
 
        $this->assertEquals(clean_param('a<em>b</em>c', PARAM_TEXT), 'abc');
892
 
        $this->assertEquals(clean_param('a><xx >c>', PARAM_TEXT), 'a>c>'); // standard strip_tags() behaviour
893
 
        $this->assertEquals(clean_param('a<b', PARAM_TEXT), 'a');
894
 
        $this->assertEquals(clean_param('a>b', PARAM_TEXT), 'a>b');
895
 
        $this->assertEquals(clean_param('<lang lang="en">a>a</lang>', PARAM_TEXT), '<lang lang="en">a>a</lang>'); // standard strip_tags() behaviour
896
 
        $this->assertEquals(clean_param('<lang lang="en">a<a</lang>', PARAM_TEXT), 'a');
897
 
        $this->assertEquals(clean_param('<lang lang="en">a<br>a</lang>', PARAM_TEXT), '<lang lang="en">aa</lang>');
898
 
    }
899
 
 
900
 
    function test_clean_param_url() {
901
 
        // Test PARAM_URL and PARAM_LOCALURL a bit
902
 
        $this->assertEquals(clean_param('http://google.com/', PARAM_URL), 'http://google.com/');
903
 
        $this->assertEquals(clean_param('http://some.very.long.and.silly.domain/with/a/path/', PARAM_URL), 'http://some.very.long.and.silly.domain/with/a/path/');
904
 
        $this->assertEquals(clean_param('http://localhost/', PARAM_URL), 'http://localhost/');
905
 
        $this->assertEquals(clean_param('http://0.255.1.1/numericip.php', PARAM_URL), 'http://0.255.1.1/numericip.php');
906
 
        $this->assertEquals(clean_param('/just/a/path', PARAM_URL), '/just/a/path');
907
 
        $this->assertEquals(clean_param('funny:thing', PARAM_URL), '');
908
 
    }
909
 
 
910
 
    function test_clean_param_localurl() {
 
520
    public function test_clean_param_plugin() {
 
521
        // Please note the cleaning of plugin names is very strict, no guessing here.
 
522
        $this->assertSame('forum', clean_param('forum', PARAM_PLUGIN));
 
523
        $this->assertSame('forum2', clean_param('forum2', PARAM_PLUGIN));
 
524
        $this->assertSame('feedback360', clean_param('feedback360', PARAM_PLUGIN));
 
525
        $this->assertSame('online_users', clean_param('online_users', PARAM_PLUGIN));
 
526
        $this->assertSame('blond_online_users', clean_param('blond_online_users', PARAM_PLUGIN));
 
527
        $this->assertSame('', clean_param('online__users', PARAM_PLUGIN));
 
528
        $this->assertSame('', clean_param('forum ', PARAM_PLUGIN));
 
529
        $this->assertSame('', clean_param('forum.old', PARAM_PLUGIN));
 
530
        $this->assertSame('', clean_param('xx-yy', PARAM_PLUGIN));
 
531
        $this->assertSame('', clean_param('2xx', PARAM_PLUGIN));
 
532
        $this->assertSame('', clean_param('Xx', PARAM_PLUGIN));
 
533
        $this->assertSame('', clean_param('_xx', PARAM_PLUGIN));
 
534
        $this->assertSame('', clean_param('xx_', PARAM_PLUGIN));
 
535
    }
 
536
 
 
537
    public function test_clean_param_area() {
 
538
        // Please note the cleaning of area names is very strict, no guessing here.
 
539
        $this->assertSame('something', clean_param('something', PARAM_AREA));
 
540
        $this->assertSame('something2', clean_param('something2', PARAM_AREA));
 
541
        $this->assertSame('some_thing', clean_param('some_thing', PARAM_AREA));
 
542
        $this->assertSame('some_thing_xx', clean_param('some_thing_xx', PARAM_AREA));
 
543
        $this->assertSame('feedback360', clean_param('feedback360', PARAM_AREA));
 
544
        $this->assertSame('', clean_param('_something', PARAM_AREA));
 
545
        $this->assertSame('', clean_param('something_', PARAM_AREA));
 
546
        $this->assertSame('', clean_param('2something', PARAM_AREA));
 
547
        $this->assertSame('', clean_param('Something', PARAM_AREA));
 
548
        $this->assertSame('', clean_param('some-thing', PARAM_AREA));
 
549
        $this->assertSame('', clean_param('somethííng', PARAM_AREA));
 
550
        $this->assertSame('', clean_param('something.x', PARAM_AREA));
 
551
    }
 
552
 
 
553
    public function test_clean_param_text() {
 
554
        $this->assertSame(PARAM_TEXT, PARAM_MULTILANG);
 
555
        // Standard.
 
556
        $this->assertSame('xx<lang lang="en">aa</lang><lang lang="yy">pp</lang>', clean_param('xx<lang lang="en">aa</lang><lang lang="yy">pp</lang>', PARAM_TEXT));
 
557
        $this->assertSame('<span lang="en" class="multilang">aa</span><span lang="xy" class="multilang">bb</span>', clean_param('<span lang="en" class="multilang">aa</span><span lang="xy" class="multilang">bb</span>', PARAM_TEXT));
 
558
        $this->assertSame('xx<lang lang="en">aa'."\n".'</lang><lang lang="yy">pp</lang>', clean_param('xx<lang lang="en">aa'."\n".'</lang><lang lang="yy">pp</lang>', PARAM_TEXT));
 
559
        // Malformed.
 
560
        $this->assertSame('<span lang="en" class="multilang">aa</span>', clean_param('<span lang="en" class="multilang">aa</span>', PARAM_TEXT));
 
561
        $this->assertSame('aa', clean_param('<span lang="en" class="nothing" class="multilang">aa</span>', PARAM_TEXT));
 
562
        $this->assertSame('aa', clean_param('<lang lang="en" class="multilang">aa</lang>', PARAM_TEXT));
 
563
        $this->assertSame('aa', clean_param('<lang lang="en!!">aa</lang>', PARAM_TEXT));
 
564
        $this->assertSame('aa', clean_param('<span lang="en==" class="multilang">aa</span>', PARAM_TEXT));
 
565
        $this->assertSame('abc', clean_param('a<em>b</em>c', PARAM_TEXT));
 
566
        $this->assertSame('a>c>', clean_param('a><xx >c>', PARAM_TEXT)); // Standard strip_tags() behaviour.
 
567
        $this->assertSame('a', clean_param('a<b', PARAM_TEXT));
 
568
        $this->assertSame('a>b', clean_param('a>b', PARAM_TEXT));
 
569
        $this->assertSame('<lang lang="en">a>a</lang>', clean_param('<lang lang="en">a>a</lang>', PARAM_TEXT)); // Standard strip_tags() behaviour.
 
570
        $this->assertSame('a', clean_param('<lang lang="en">a<a</lang>', PARAM_TEXT));
 
571
        $this->assertSame('<lang lang="en">aa</lang>', clean_param('<lang lang="en">a<br>a</lang>', PARAM_TEXT));
 
572
    }
 
573
 
 
574
    public function test_clean_param_url() {
 
575
        // Test PARAM_URL and PARAM_LOCALURL a bit.
 
576
        $this->assertSame('http://google.com/', clean_param('http://google.com/', PARAM_URL));
 
577
        $this->assertSame('http://some.very.long.and.silly.domain/with/a/path/', clean_param('http://some.very.long.and.silly.domain/with/a/path/', PARAM_URL));
 
578
        $this->assertSame('http://localhost/', clean_param('http://localhost/', PARAM_URL));
 
579
        $this->assertSame('http://0.255.1.1/numericip.php', clean_param('http://0.255.1.1/numericip.php', PARAM_URL));
 
580
        $this->assertSame('/just/a/path', clean_param('/just/a/path', PARAM_URL));
 
581
        $this->assertSame('', clean_param('funny:thing', PARAM_URL));
 
582
    }
 
583
 
 
584
    public function test_clean_param_localurl() {
911
585
        global $CFG;
912
 
        $this->assertEquals(clean_param('http://google.com/', PARAM_LOCALURL), '');
913
 
        $this->assertEquals(clean_param('http://some.very.long.and.silly.domain/with/a/path/', PARAM_LOCALURL), '');
914
 
        $this->assertEquals(clean_param($CFG->wwwroot, PARAM_LOCALURL), $CFG->wwwroot);
915
 
        $this->assertEquals(clean_param('/just/a/path', PARAM_LOCALURL), '/just/a/path');
916
 
        $this->assertEquals(clean_param('funny:thing', PARAM_LOCALURL), '');
917
 
        $this->assertEquals(clean_param('course/view.php?id=3', PARAM_LOCALURL), 'course/view.php?id=3');
918
 
    }
919
 
 
920
 
    function test_clean_param_file() {
921
 
        $this->assertEquals(clean_param('correctfile.txt', PARAM_FILE), 'correctfile.txt');
922
 
        $this->assertEquals(clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_FILE), 'badfile.txt');
923
 
        $this->assertEquals(clean_param('../parentdirfile.txt', PARAM_FILE), '..parentdirfile.txt');
924
 
        $this->assertEquals(clean_param('../../grandparentdirfile.txt', PARAM_FILE), '....grandparentdirfile.txt');
925
 
        $this->assertEquals(clean_param('..\winparentdirfile.txt', PARAM_FILE), '..winparentdirfile.txt');
926
 
        $this->assertEquals(clean_param('..\..\wingrandparentdir.txt', PARAM_FILE), '....wingrandparentdir.txt');
927
 
        $this->assertEquals(clean_param('myfile.a.b.txt', PARAM_FILE), 'myfile.a.b.txt');
928
 
        $this->assertEquals(clean_param('myfile..a..b.txt', PARAM_FILE), 'myfile..a..b.txt');
929
 
        $this->assertEquals(clean_param('myfile.a..b...txt', PARAM_FILE), 'myfile.a..b...txt');
930
 
        $this->assertEquals(clean_param('myfile.a.txt', PARAM_FILE), 'myfile.a.txt');
931
 
        $this->assertEquals(clean_param('myfile...txt', PARAM_FILE), 'myfile...txt');
932
 
        $this->assertEquals(clean_param('...jpg', PARAM_FILE), '...jpg');
933
 
        $this->assertEquals(clean_param('.a.b.', PARAM_FILE), '.a.b.');
934
 
        $this->assertEquals(clean_param('.', PARAM_FILE), '');
935
 
        $this->assertEquals(clean_param('..', PARAM_FILE), '');
936
 
        $this->assertEquals(clean_param('...', PARAM_FILE), '...');
937
 
        $this->assertEquals(clean_param('. . . .', PARAM_FILE), '. . . .');
938
 
        $this->assertEquals(clean_param('dontrtrim.me. .. .. . ', PARAM_FILE), 'dontrtrim.me. .. .. . ');
939
 
        $this->assertEquals(clean_param(' . .dontltrim.me', PARAM_FILE), ' . .dontltrim.me');
940
 
        $this->assertEquals(clean_param("here is a tab\t.txt", PARAM_FILE), 'here is a tab.txt');
941
 
        $this->assertEquals(clean_param("here is a line\r\nbreak.txt", PARAM_FILE), 'here is a linebreak.txt');
942
 
 
943
 
        //The following behaviours have been maintained although they seem a little odd
944
 
        $this->assertEquals(clean_param('funny:thing', PARAM_FILE), 'funnything');
945
 
        $this->assertEquals(clean_param('./currentdirfile.txt', PARAM_FILE), '.currentdirfile.txt');
946
 
        $this->assertEquals(clean_param('c:\temp\windowsfile.txt', PARAM_FILE), 'ctempwindowsfile.txt');
947
 
        $this->assertEquals(clean_param('/home/user/linuxfile.txt', PARAM_FILE), 'homeuserlinuxfile.txt');
948
 
        $this->assertEquals(clean_param('~/myfile.txt', PARAM_FILE), '~myfile.txt');
949
 
    }
950
 
 
951
 
    function test_clean_param_path() {
952
 
        $this->assertEquals(clean_param('correctfile.txt', PARAM_PATH), 'correctfile.txt');
953
 
        $this->assertEquals(clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_PATH), 'bad/file.txt');
954
 
        $this->assertEquals(clean_param('../parentdirfile.txt', PARAM_PATH), '/parentdirfile.txt');
955
 
        $this->assertEquals(clean_param('../../grandparentdirfile.txt', PARAM_PATH), '/grandparentdirfile.txt');
956
 
        $this->assertEquals(clean_param('..\winparentdirfile.txt', PARAM_PATH), '/winparentdirfile.txt');
957
 
        $this->assertEquals(clean_param('..\..\wingrandparentdir.txt', PARAM_PATH), '/wingrandparentdir.txt');
958
 
        $this->assertEquals(clean_param('funny:thing', PARAM_PATH), 'funnything');
959
 
        $this->assertEquals(clean_param('./././here', PARAM_PATH), './here');
960
 
        $this->assertEquals(clean_param('./currentdirfile.txt', PARAM_PATH), './currentdirfile.txt');
961
 
        $this->assertEquals(clean_param('c:\temp\windowsfile.txt', PARAM_PATH), 'c/temp/windowsfile.txt');
962
 
        $this->assertEquals(clean_param('/home/user/linuxfile.txt', PARAM_PATH), '/home/user/linuxfile.txt');
963
 
        $this->assertEquals(clean_param('/home../user ./.linuxfile.txt', PARAM_PATH), '/home../user ./.linuxfile.txt');
964
 
        $this->assertEquals(clean_param('~/myfile.txt', PARAM_PATH), '~/myfile.txt');
965
 
        $this->assertEquals(clean_param('~/../myfile.txt', PARAM_PATH), '~/myfile.txt');
966
 
        $this->assertEquals(clean_param('/..b../.../myfile.txt', PARAM_PATH), '/..b../.../myfile.txt');
967
 
        $this->assertEquals(clean_param('..b../.../myfile.txt', PARAM_PATH), '..b../.../myfile.txt');
968
 
        $this->assertEquals(clean_param('/super//slashes///', PARAM_PATH), '/super/slashes/');
969
 
    }
970
 
 
971
 
    function test_clean_param_username() {
 
586
        $this->assertSame('', clean_param('http://google.com/', PARAM_LOCALURL));
 
587
        $this->assertSame('', clean_param('http://some.very.long.and.silly.domain/with/a/path/', PARAM_LOCALURL));
 
588
        $this->assertSame(clean_param($CFG->wwwroot, PARAM_LOCALURL), $CFG->wwwroot);
 
589
        $this->assertSame('/just/a/path', clean_param('/just/a/path', PARAM_LOCALURL));
 
590
        $this->assertSame('', clean_param('funny:thing', PARAM_LOCALURL));
 
591
        $this->assertSame('course/view.php?id=3', clean_param('course/view.php?id=3', PARAM_LOCALURL));
 
592
    }
 
593
 
 
594
    public function test_clean_param_file() {
 
595
        $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_FILE));
 
596
        $this->assertSame('badfile.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_FILE));
 
597
        $this->assertSame('..parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_FILE));
 
598
        $this->assertSame('....grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_FILE));
 
599
        $this->assertSame('..winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_FILE));
 
600
        $this->assertSame('....wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_FILE));
 
601
        $this->assertSame('myfile.a.b.txt', clean_param('myfile.a.b.txt', PARAM_FILE));
 
602
        $this->assertSame('myfile..a..b.txt', clean_param('myfile..a..b.txt', PARAM_FILE));
 
603
        $this->assertSame('myfile.a..b...txt', clean_param('myfile.a..b...txt', PARAM_FILE));
 
604
        $this->assertSame('myfile.a.txt', clean_param('myfile.a.txt', PARAM_FILE));
 
605
        $this->assertSame('myfile...txt', clean_param('myfile...txt', PARAM_FILE));
 
606
        $this->assertSame('...jpg', clean_param('...jpg', PARAM_FILE));
 
607
        $this->assertSame('.a.b.', clean_param('.a.b.', PARAM_FILE));
 
608
        $this->assertSame('', clean_param('.', PARAM_FILE));
 
609
        $this->assertSame('', clean_param('..', PARAM_FILE));
 
610
        $this->assertSame('...', clean_param('...', PARAM_FILE));
 
611
        $this->assertSame('. . . .', clean_param('. . . .', PARAM_FILE));
 
612
        $this->assertSame('dontrtrim.me. .. .. . ', clean_param('dontrtrim.me. .. .. . ', PARAM_FILE));
 
613
        $this->assertSame(' . .dontltrim.me', clean_param(' . .dontltrim.me', PARAM_FILE));
 
614
        $this->assertSame('here is a tab.txt', clean_param("here is a tab\t.txt", PARAM_FILE));
 
615
        $this->assertSame('here is a linebreak.txt', clean_param("here is a line\r\nbreak.txt", PARAM_FILE));
 
616
 
 
617
        // The following behaviours have been maintained although they seem a little odd.
 
618
        $this->assertSame('funnything', clean_param('funny:thing', PARAM_FILE));
 
619
        $this->assertSame('.currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_FILE));
 
620
        $this->assertSame('ctempwindowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_FILE));
 
621
        $this->assertSame('homeuserlinuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_FILE));
 
622
        $this->assertSame('~myfile.txt', clean_param('~/myfile.txt', PARAM_FILE));
 
623
    }
 
624
 
 
625
    public function test_clean_param_path() {
 
626
        $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_PATH));
 
627
        $this->assertSame('bad/file.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_PATH));
 
628
        $this->assertSame('/parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_PATH));
 
629
        $this->assertSame('/grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_PATH));
 
630
        $this->assertSame('/winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_PATH));
 
631
        $this->assertSame('/wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_PATH));
 
632
        $this->assertSame('funnything', clean_param('funny:thing', PARAM_PATH));
 
633
        $this->assertSame('./here', clean_param('./././here', PARAM_PATH));
 
634
        $this->assertSame('./currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_PATH));
 
635
        $this->assertSame('c/temp/windowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_PATH));
 
636
        $this->assertSame('/home/user/linuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_PATH));
 
637
        $this->assertSame('/home../user ./.linuxfile.txt', clean_param('/home../user ./.linuxfile.txt', PARAM_PATH));
 
638
        $this->assertSame('~/myfile.txt', clean_param('~/myfile.txt', PARAM_PATH));
 
639
        $this->assertSame('~/myfile.txt', clean_param('~/../myfile.txt', PARAM_PATH));
 
640
        $this->assertSame('/..b../.../myfile.txt', clean_param('/..b../.../myfile.txt', PARAM_PATH));
 
641
        $this->assertSame('..b../.../myfile.txt', clean_param('..b../.../myfile.txt', PARAM_PATH));
 
642
        $this->assertSame('/super/slashes/', clean_param('/super//slashes///', PARAM_PATH));
 
643
    }
 
644
 
 
645
    public function test_clean_param_username() {
972
646
        global $CFG;
973
647
        $currentstatus =  $CFG->extendedusernamechars;
974
648
 
975
 
        // Run tests with extended character == FALSE;
976
 
        $CFG->extendedusernamechars = FALSE;
977
 
        $this->assertEquals(clean_param('johndoe123', PARAM_USERNAME), 'johndoe123' );
978
 
        $this->assertEquals(clean_param('john.doe', PARAM_USERNAME), 'john.doe');
979
 
        $this->assertEquals(clean_param('john-doe', PARAM_USERNAME), 'john-doe');
980
 
        $this->assertEquals(clean_param('john- doe', PARAM_USERNAME), 'john-doe');
981
 
        $this->assertEquals(clean_param('john_doe', PARAM_USERNAME), 'john_doe');
982
 
        $this->assertEquals(clean_param('john@doe', PARAM_USERNAME), 'john@doe');
983
 
        $this->assertEquals(clean_param('john~doe', PARAM_USERNAME), 'johndoe');
984
 
        $this->assertEquals(clean_param('john´doe', PARAM_USERNAME), 'johndoe');
985
 
        $this->assertEquals(clean_param('john#$%&() ', PARAM_USERNAME), 'john');
986
 
        $this->assertEquals(clean_param('JOHNdóé ', PARAM_USERNAME), 'johnd');
987
 
        $this->assertEquals(clean_param('john.,:;-_/|\ñÑ[]A_X-,D {} ~!@#$%^&*()_+ ?><[] ščřžžý ?ýáž?žý??šdoe ', PARAM_USERNAME), 'john.-_a_x-d@_doe');
988
 
 
989
 
 
990
 
        // Test success condition, if extendedusernamechars == ENABLE;
991
 
        $CFG->extendedusernamechars = TRUE;
992
 
        $this->assertEquals(clean_param('john_doe', PARAM_USERNAME), 'john_doe');
993
 
        $this->assertEquals(clean_param('john@doe', PARAM_USERNAME), 'john@doe');
994
 
        $this->assertEquals(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john#$%&()+_^');
995
 
        $this->assertEquals(clean_param('john~doe', PARAM_USERNAME), 'john~doe');
996
 
        $this->assertEquals(clean_param('joHN´doe', PARAM_USERNAME), 'john´doe');
997
 
        $this->assertEquals(clean_param('johnDOE', PARAM_USERNAME), 'johndoe');
998
 
        $this->assertEquals(clean_param('johndóé ', PARAM_USERNAME), 'johndóé');
 
649
        // Run tests with extended character == false;.
 
650
        $CFG->extendedusernamechars = false;
 
651
        $this->assertSame('johndoe123', clean_param('johndoe123', PARAM_USERNAME) );
 
652
        $this->assertSame('john.doe', clean_param('john.doe', PARAM_USERNAME));
 
653
        $this->assertSame('john-doe', clean_param('john-doe', PARAM_USERNAME));
 
654
        $this->assertSame('john-doe', clean_param('john- doe', PARAM_USERNAME));
 
655
        $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
 
656
        $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
 
657
        $this->assertSame('johndoe', clean_param('john~doe', PARAM_USERNAME));
 
658
        $this->assertSame('johndoe', clean_param('john´doe', PARAM_USERNAME));
 
659
        $this->assertSame(clean_param('john#$%&() ', PARAM_USERNAME), 'john');
 
660
        $this->assertSame('johnd', clean_param('JOHNdóé ', PARAM_USERNAME));
 
661
        $this->assertSame(clean_param('john.,:;-_/|\ñÑ[]A_X-,D {} ~!@#$%^&*()_+ ?><[] ščřžžý ?ýáž?žý??šdoe ', PARAM_USERNAME), 'john.-_a_x-d@_doe');
 
662
 
 
663
        // Test success condition, if extendedusernamechars == ENABLE;.
 
664
        $CFG->extendedusernamechars = true;
 
665
        $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
 
666
        $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
 
667
        $this->assertSame(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john#$%&()+_^');
 
668
        $this->assertSame('john~doe', clean_param('john~doe', PARAM_USERNAME));
 
669
        $this->assertSame('john´doe', clean_param('joHN´doe', PARAM_USERNAME));
 
670
        $this->assertSame('johndoe', clean_param('johnDOE', PARAM_USERNAME));
 
671
        $this->assertSame('johndóé', clean_param('johndóé ', PARAM_USERNAME));
999
672
 
1000
673
        $CFG->extendedusernamechars = $currentstatus;
1001
674
    }
1002
675
 
1003
 
    function test_clean_param_stringid() {
1004
 
        // Test string identifiers validation
1005
 
        // valid strings:
1006
 
        $this->assertEquals(clean_param('validstring', PARAM_STRINGID), 'validstring');
1007
 
        $this->assertEquals(clean_param('mod/foobar:valid_capability', PARAM_STRINGID), 'mod/foobar:valid_capability');
1008
 
        $this->assertEquals(clean_param('CZ', PARAM_STRINGID), 'CZ');
1009
 
        $this->assertEquals(clean_param('application/vnd.ms-powerpoint', PARAM_STRINGID), 'application/vnd.ms-powerpoint');
1010
 
        $this->assertEquals(clean_param('grade2', PARAM_STRINGID), 'grade2');
1011
 
        // invalid strings:
1012
 
        $this->assertEquals(clean_param('trailing ', PARAM_STRINGID), '');
1013
 
        $this->assertEquals(clean_param('space bar', PARAM_STRINGID), '');
1014
 
        $this->assertEquals(clean_param('0numeric', PARAM_STRINGID), '');
1015
 
        $this->assertEquals(clean_param('*', PARAM_STRINGID), '');
1016
 
        $this->assertEquals(clean_param(' ', PARAM_STRINGID), '');
 
676
    public function test_clean_param_stringid() {
 
677
        // Test string identifiers validation.
 
678
        // Valid strings.
 
679
        $this->assertSame('validstring', clean_param('validstring', PARAM_STRINGID));
 
680
        $this->assertSame('mod/foobar:valid_capability', clean_param('mod/foobar:valid_capability', PARAM_STRINGID));
 
681
        $this->assertSame('CZ', clean_param('CZ', PARAM_STRINGID));
 
682
        $this->assertSame('application/vnd.ms-powerpoint', clean_param('application/vnd.ms-powerpoint', PARAM_STRINGID));
 
683
        $this->assertSame('grade2', clean_param('grade2', PARAM_STRINGID));
 
684
        // Invalid strings.
 
685
        $this->assertSame('', clean_param('trailing ', PARAM_STRINGID));
 
686
        $this->assertSame('', clean_param('space bar', PARAM_STRINGID));
 
687
        $this->assertSame('', clean_param('0numeric', PARAM_STRINGID));
 
688
        $this->assertSame('', clean_param('*', PARAM_STRINGID));
 
689
        $this->assertSame('', clean_param(' ', PARAM_STRINGID));
1017
690
    }
1018
691
 
1019
 
    function test_clean_param_timezone() {
1020
 
        // Test timezone validation
 
692
    public function test_clean_param_timezone() {
 
693
        // Test timezone validation.
1021
694
        $testvalues = array (
1022
695
            'America/Jamaica'                => 'America/Jamaica',
1023
696
            'America/Argentina/Cordoba'      => 'America/Argentina/Cordoba',
1052
725
 
1053
726
        foreach ($testvalues as $testvalue => $expectedvalue) {
1054
727
            $actualvalue = clean_param($testvalue, PARAM_TIMEZONE);
1055
 
            $this->assertEquals($actualvalue, $expectedvalue);
 
728
            $this->assertEquals($expectedvalue, $actualvalue);
1056
729
        }
1057
730
    }
1058
731
 
1059
 
    function test_validate_param() {
 
732
    public function test_validate_param() {
1060
733
        try {
1061
734
            $param = validate_param('11a', PARAM_INT);
1062
735
            $this->fail('invalid_parameter_exception expected');
1063
 
        } catch (invalid_parameter_exception $ex) {
1064
 
            $this->assertTrue(true);
1065
 
        }
1066
 
        try {
1067
 
            $param = validate_param('11', PARAM_INT);
1068
 
            $this->assertEquals($param, 11);
1069
 
        } catch (invalid_parameter_exception $ex) {
1070
 
            $this->fail('invalid_parameter_exception not expected');
1071
 
        }
 
736
        } catch (moodle_exception $ex) {
 
737
            $this->assertInstanceOf('invalid_parameter_exception', $ex);
 
738
        }
 
739
 
 
740
        $param = validate_param('11', PARAM_INT);
 
741
        $this->assertSame(11, $param);
 
742
 
1072
743
        try {
1073
744
            $param = validate_param(null, PARAM_INT, false);
1074
745
            $this->fail('invalid_parameter_exception expected');
1075
 
        } catch (invalid_parameter_exception $ex) {
1076
 
            $this->assertTrue(true);
1077
 
        }
1078
 
        try {
1079
 
            $param = validate_param(null, PARAM_INT, true);
1080
 
            $this->assertTrue($param===null);
1081
 
        } catch (invalid_parameter_exception $ex) {
1082
 
            $this->fail('invalid_parameter_exception expected');
1083
 
        }
 
746
        } catch (moodle_exception $ex) {
 
747
            $this->assertInstanceOf('invalid_parameter_exception', $ex);
 
748
        }
 
749
 
 
750
        $param = validate_param(null, PARAM_INT, true);
 
751
        $this->assertSame(null, $param);
 
752
 
1084
753
        try {
1085
754
            $param = validate_param(array(), PARAM_INT);
1086
755
            $this->fail('invalid_parameter_exception expected');
1087
 
        } catch (invalid_parameter_exception $ex) {
1088
 
            $this->assertTrue(true);
 
756
        } catch (moodle_exception $ex) {
 
757
            $this->assertInstanceOf('invalid_parameter_exception', $ex);
1089
758
        }
1090
759
        try {
1091
760
            $param = validate_param(new stdClass, PARAM_INT);
1092
761
            $this->fail('invalid_parameter_exception expected');
1093
 
        } catch (invalid_parameter_exception $ex) {
1094
 
            $this->assertTrue(true);
1095
 
        }
1096
 
        try {
1097
 
            $param = validate_param('1.0', PARAM_FLOAT);
1098
 
            $this->assertSame(1.0, $param);
1099
 
 
1100
 
            // Make sure valid floats do not cause exception.
1101
 
            validate_param(1.0, PARAM_FLOAT);
1102
 
            validate_param(10, PARAM_FLOAT);
1103
 
            validate_param('0', PARAM_FLOAT);
1104
 
            validate_param('119813454.545464564564546564545646556564465465456465465465645645465645645645', PARAM_FLOAT);
1105
 
            validate_param('011.1', PARAM_FLOAT);
1106
 
            validate_param('11', PARAM_FLOAT);
1107
 
            validate_param('+.1', PARAM_FLOAT);
1108
 
            validate_param('-.1', PARAM_FLOAT);
1109
 
            validate_param('1e10', PARAM_FLOAT);
1110
 
            validate_param('.1e+10', PARAM_FLOAT);
1111
 
            validate_param('1E-1', PARAM_FLOAT);
1112
 
            $this->assertTrue(true);
1113
 
        } catch (invalid_parameter_exception $ex) {
1114
 
            $this->fail('Valid float notation not accepted');
1115
 
        }
 
762
        } catch (moodle_exception $ex) {
 
763
            $this->assertInstanceOf('invalid_parameter_exception', $ex);
 
764
        }
 
765
 
 
766
        $param = validate_param('1.0', PARAM_FLOAT);
 
767
        $this->assertSame(1.0, $param);
 
768
 
 
769
        // Make sure valid floats do not cause exception.
 
770
        validate_param(1.0, PARAM_FLOAT);
 
771
        validate_param(10, PARAM_FLOAT);
 
772
        validate_param('0', PARAM_FLOAT);
 
773
        validate_param('119813454.545464564564546564545646556564465465456465465465645645465645645645', PARAM_FLOAT);
 
774
        validate_param('011.1', PARAM_FLOAT);
 
775
        validate_param('11', PARAM_FLOAT);
 
776
        validate_param('+.1', PARAM_FLOAT);
 
777
        validate_param('-.1', PARAM_FLOAT);
 
778
        validate_param('1e10', PARAM_FLOAT);
 
779
        validate_param('.1e+10', PARAM_FLOAT);
 
780
        validate_param('1E-1', PARAM_FLOAT);
 
781
 
1116
782
        try {
1117
783
            $param = validate_param('1,2', PARAM_FLOAT);
1118
784
            $this->fail('invalid_parameter_exception expected');
1119
 
        } catch (invalid_parameter_exception $ex) {
1120
 
            $this->assertTrue(true);
 
785
        } catch (moodle_exception $ex) {
 
786
            $this->assertInstanceOf('invalid_parameter_exception', $ex);
1121
787
        }
1122
788
        try {
1123
789
            $param = validate_param('', PARAM_FLOAT);
1124
790
            $this->fail('invalid_parameter_exception expected');
1125
 
        } catch (invalid_parameter_exception $ex) {
1126
 
            $this->assertTrue(true);
 
791
        } catch (moodle_exception $ex) {
 
792
            $this->assertInstanceOf('invalid_parameter_exception', $ex);
1127
793
        }
1128
794
        try {
1129
795
            $param = validate_param('.', PARAM_FLOAT);
1130
796
            $this->fail('invalid_parameter_exception expected');
1131
 
        } catch (invalid_parameter_exception $ex) {
1132
 
            $this->assertTrue(true);
 
797
        } catch (moodle_exception $ex) {
 
798
            $this->assertInstanceOf('invalid_parameter_exception', $ex);
1133
799
        }
1134
800
        try {
1135
801
            $param = validate_param('e10', PARAM_FLOAT);
1136
802
            $this->fail('invalid_parameter_exception expected');
1137
 
        } catch (invalid_parameter_exception $ex) {
1138
 
            $this->assertTrue(true);
 
803
        } catch (moodle_exception $ex) {
 
804
            $this->assertInstanceOf('invalid_parameter_exception', $ex);
1139
805
        }
1140
806
        try {
1141
807
            $param = validate_param('abc', PARAM_FLOAT);
1142
808
            $this->fail('invalid_parameter_exception expected');
1143
 
        } catch (invalid_parameter_exception $ex) {
1144
 
            $this->assertTrue(true);
 
809
        } catch (moodle_exception $ex) {
 
810
            $this->assertInstanceOf('invalid_parameter_exception', $ex);
1145
811
        }
1146
812
    }
1147
813
 
1148
 
    function test_shorten_text_no_tags_already_short_enough() {
 
814
    public function test_shorten_text_no_tags_already_short_enough() {
1149
815
        // ......12345678901234567890123456.
1150
816
        $text = "short text already no tags";
1151
 
        $this->assertEquals($text, shorten_text($text));
 
817
        $this->assertSame($text, shorten_text($text));
1152
818
    }
1153
819
 
1154
 
    function test_shorten_text_with_tags_already_short_enough() {
 
820
    public function test_shorten_text_with_tags_already_short_enough() {
1155
821
        // .........123456...7890....12345678.......901234567.
1156
822
        $text = "<p>short <b>text</b> already</p><p>with tags</p>";
1157
 
        $this->assertEquals($text, shorten_text($text));
 
823
        $this->assertSame($text, shorten_text($text));
1158
824
    }
1159
825
 
1160
 
    function test_shorten_text_no_tags_needs_shortening() {
 
826
    public function test_shorten_text_no_tags_needs_shortening() {
1161
827
        // Default truncation is after 30 chars, but allowing 3 for the final '...'.
1162
828
        // ......12345678901234567890123456789023456789012345678901234.
1163
829
        $text = "long text without any tags blah de blah blah blah what";
1164
 
        $this->assertEquals('long text without any tags ...', shorten_text($text));
 
830
        $this->assertSame('long text without any tags ...', shorten_text($text));
1165
831
    }
1166
832
 
1167
 
    function test_shorten_text_with_tags_needs_shortening() {
 
833
    public function test_shorten_text_with_tags_needs_shortening() {
1168
834
        // .......................................123456789012345678901234567890...
1169
835
        $text = "<div class='frog'><p><blockquote>Long text with tags that will ".
1170
836
            "be chopped off but <b>should be added back again</b></blockquote></p></div>";
1172
838
            "tags that ...</blockquote></p></div>", shorten_text($text));
1173
839
    }
1174
840
 
1175
 
    function test_shorten_text_with_entities() {
 
841
    public function test_shorten_text_with_entities() {
1176
842
        // Remember to allow 3 chars for the final '...'.
1177
843
        // ......123456789012345678901234567_____890...
1178
844
        $text = "some text which shouldn't &nbsp; break there";
1179
 
        $this->assertEquals("some text which shouldn't &nbsp; ...",
1180
 
            shorten_text($text, 31));
1181
 
        $this->assertEquals("some text which shouldn't &nbsp;...",
1182
 
            shorten_text($text, 30));
1183
 
        $this->assertEquals("some text which shouldn't ...",
1184
 
            shorten_text($text, 29));
 
845
        $this->assertSame("some text which shouldn't &nbsp; ...", shorten_text($text, 31));
 
846
        $this->assertSame("some text which shouldn't &nbsp;...", shorten_text($text, 30));
 
847
        $this->assertSame("some text which shouldn't ...", shorten_text($text, 29));
1185
848
    }
1186
849
 
1187
 
    function test_shorten_text_known_tricky_case() {
 
850
    public function test_shorten_text_known_tricky_case() {
1188
851
        // This case caused a bug up to 1.9.5
1189
852
        // ..........123456789012345678901234567890123456789.....0_____1___2___...
1190
853
        $text = "<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;&lt;&lt;There are several";
1191
 
        $this->assertEquals("<h3>standard 'break-out' sub groups in ...</h3>",
 
854
        $this->assertSame("<h3>standard 'break-out' sub groups in ...</h3>",
1192
855
            shorten_text($text, 41));
1193
 
        $this->assertEquals("<h3>standard 'break-out' sub groups in TGs?...</h3>",
 
856
        $this->assertSame("<h3>standard 'break-out' sub groups in TGs?...</h3>",
1194
857
            shorten_text($text, 42));
1195
 
        $this->assertEquals("<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;...",
 
858
        $this->assertSame("<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;...",
1196
859
            shorten_text($text, 43));
1197
860
    }
1198
861
 
1199
 
    function test_shorten_text_no_spaces() {
 
862
    public function test_shorten_text_no_spaces() {
1200
863
        // ..........123456789.
1201
864
        $text = "<h1>123456789</h1>"; // A string with no convenient breaks.
1202
 
        $this->assertEquals("<h1>12345...</h1>",
1203
 
            shorten_text($text, 8));
 
865
        $this->assertSame("<h1>12345...</h1>", shorten_text($text, 8));
1204
866
    }
1205
867
 
1206
 
    function test_shorten_text_utf8_european() {
 
868
    public function test_shorten_text_utf8_european() {
1207
869
        // Text without tags.
1208
870
        // ......123456789012345678901234567.
1209
871
        $text = "Žluťoučký koníček přeskočil";
1210
 
        $this->assertEquals($text, shorten_text($text)); // 30 chars by default.
1211
 
        $this->assertEquals("Žluťoučký koníče...", shorten_text($text, 19, true));
1212
 
        $this->assertEquals("Žluťoučký ...", shorten_text($text, 19, false));
 
872
        $this->assertSame($text, shorten_text($text)); // 30 chars by default.
 
873
        $this->assertSame("Žluťoučký koníče...", shorten_text($text, 19, true));
 
874
        $this->assertSame("Žluťoučký ...", shorten_text($text, 19, false));
1213
875
        // And try it with 2-less (that are, in bytes, the middle of a sequence).
1214
 
        $this->assertEquals("Žluťoučký koní...", shorten_text($text, 17, true));
1215
 
        $this->assertEquals("Žluťoučký ...", shorten_text($text, 17, false));
 
876
        $this->assertSame("Žluťoučký koní...", shorten_text($text, 17, true));
 
877
        $this->assertSame("Žluťoučký ...", shorten_text($text, 17, false));
1216
878
 
1217
879
        // .........123456789012345678...901234567....89012345.
1218
880
        $text = "<p>Žluťoučký koníček <b>přeskočil</b> potůček</p>";
1219
 
        $this->assertEquals($text, shorten_text($text, 60));
1220
 
        $this->assertEquals("<p>Žluťoučký koníček ...</p>", shorten_text($text, 21));
1221
 
        $this->assertEquals("<p>Žluťoučký koníče...</p>", shorten_text($text, 19, true));
1222
 
        $this->assertEquals("<p>Žluťoučký ...</p>", shorten_text($text, 19, false));
 
881
        $this->assertSame($text, shorten_text($text, 60));
 
882
        $this->assertSame("<p>Žluťoučký koníček ...</p>", shorten_text($text, 21));
 
883
        $this->assertSame("<p>Žluťoučký koníče...</p>", shorten_text($text, 19, true));
 
884
        $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 19, false));
1223
885
        // And try it with 2 fewer (that are, in bytes, the middle of a sequence).
1224
 
        $this->assertEquals("<p>Žluťoučký koní...</p>", shorten_text($text, 17, true));
1225
 
        $this->assertEquals("<p>Žluťoučký ...</p>", shorten_text($text, 17, false));
 
886
        $this->assertSame("<p>Žluťoučký koní...</p>", shorten_text($text, 17, true));
 
887
        $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 17, false));
1226
888
        // And try over one tag (start/end), it does proper text len.
1227
 
        $this->assertEquals("<p>Žluťoučký koníček <b>př...</b></p>", shorten_text($text, 23, true));
1228
 
        $this->assertEquals("<p>Žluťoučký koníček <b>přeskočil</b> pot...</p>", shorten_text($text, 34, true));
 
889
        $this->assertSame("<p>Žluťoučký koníček <b>př...</b></p>", shorten_text($text, 23, true));
 
890
        $this->assertSame("<p>Žluťoučký koníček <b>přeskočil</b> pot...</p>", shorten_text($text, 34, true));
1229
891
        // And in the middle of one tag.
1230
 
        $this->assertEquals("<p>Žluťoučký koníček <b>přeskočil...</b></p>", shorten_text($text, 30, true));
 
892
        $this->assertSame("<p>Žluťoučký koníček <b>přeskočil...</b></p>", shorten_text($text, 30, true));
1231
893
    }
1232
894
 
1233
 
    function test_shorten_text_utf8_oriental() {
 
895
    public function test_shorten_text_utf8_oriental() {
1234
896
        // Japanese
1235
897
        // text without tags
1236
898
        // ......123456789012345678901234.
1237
899
        $text = '言語設定言語設定abcdefghijkl';
1238
 
        $this->assertEquals($text, shorten_text($text)); // 30 chars by default
1239
 
        $this->assertEquals("言語設定言語...", shorten_text($text, 9, true));
1240
 
        $this->assertEquals("言語設定言語...", shorten_text($text, 9, false));
1241
 
        $this->assertEquals("言語設定言語設定ab...", shorten_text($text, 13, true));
1242
 
        $this->assertEquals("言語設定言語設定...", shorten_text($text, 13, false));
 
900
        $this->assertSame($text, shorten_text($text)); // 30 chars by default.
 
901
        $this->assertSame("言語設定言語...", shorten_text($text, 9, true));
 
902
        $this->assertSame("言語設定言語...", shorten_text($text, 9, false));
 
903
        $this->assertSame("言語設定言語設定ab...", shorten_text($text, 13, true));
 
904
        $this->assertSame("言語設定言語設定...", shorten_text($text, 13, false));
1243
905
 
1244
906
        // Chinese
1245
907
        // text without tags
1246
908
        // ......123456789012345678901234.
1247
909
        $text = '简体中文简体中文abcdefghijkl';
1248
 
        $this->assertEquals($text, shorten_text($text)); // 30 chars by default
1249
 
        $this->assertEquals("简体中文简体...", shorten_text($text, 9, true));
1250
 
        $this->assertEquals("简体中文简体...", shorten_text($text, 9, false));
1251
 
        $this->assertEquals("简体中文简体中文ab...", shorten_text($text, 13, true));
1252
 
        $this->assertEquals("简体中文简体中文...", shorten_text($text, 13, false));
 
910
        $this->assertSame($text, shorten_text($text)); // 30 chars by default.
 
911
        $this->assertSame("简体中文简体...", shorten_text($text, 9, true));
 
912
        $this->assertSame("简体中文简体...", shorten_text($text, 9, false));
 
913
        $this->assertSame("简体中文简体中文ab...", shorten_text($text, 13, true));
 
914
        $this->assertSame("简体中文简体中文...", shorten_text($text, 13, false));
1253
915
    }
1254
916
 
1255
 
    function test_shorten_text_multilang() {
 
917
    public function test_shorten_text_multilang() {
1256
918
        // This is not necessaryily specific to multilang. The issue is really
1257
919
        // tags with attributes, where before we were generating invalid HTML
1258
 
        // output like shorten_text('<span id="x" class="y">A</span> B', 1);
 
920
        // output like shorten_text('<span id="x" class="y">A</span> B', 1)
1259
921
        // returning '<span id="x" ...</span>'. It is just that multilang
1260
922
        // requires the sort of HTML that is quite likely to trigger this.
1261
923
        // ........................................1...
1262
924
        $text = '<span lang="en" class="multilang">A</span>' .
1263
925
                '<span lang="fr" class="multilang">B</span>';
1264
 
        $this->assertEquals('<span lang="en" class="multilang">...</span>',
 
926
        $this->assertSame('<span lang="en" class="multilang">...</span>',
1265
927
                shorten_text($text, 1));
1266
928
    }
1267
929
 
1268
 
    function test_usergetdate() {
 
930
    public function test_usergetdate() {
1269
931
        global $USER, $CFG, $DB;
 
932
        $this->resetAfterTest();
1270
933
 
1271
 
        //Check if forcetimezone is set then save it and set it to use user timezone
 
934
        // Check if forcetimezone is set then save it and set it to use user timezone.
1272
935
        $cfgforcetimezone = null;
1273
936
        if (isset($CFG->forcetimezone)) {
1274
937
            $cfgforcetimezone = $CFG->forcetimezone;
1275
 
            $CFG->forcetimezone = 99; //get user default timezone.
 
938
            $CFG->forcetimezone = 99; // Get user default timezone.
1276
939
        }
1277
940
 
1278
 
        $olduser = $USER;
1279
 
        $USER = $DB->get_record('user', array('id'=>2)); //admin
 
941
        $this->setAdminUser();
1280
942
 
1281
943
        $userstimezone = $USER->timezone;
1282
 
        $USER->timezone = 2;//set the timezone to a known state
 
944
        $USER->timezone = 2;// Set the timezone to a known state.
1283
945
 
1284
946
        // The string version of date comes from server locale setting and does
1285
947
        // not respect user language, so it is necessary to reset that.
1286
948
        $oldlocale = setlocale(LC_TIME, '0');
1287
949
        setlocale(LC_TIME, 'en_AU.UTF-8');
1288
950
 
1289
 
        $ts = 1261540267; //the time this function was created
1290
 
 
1291
 
        $arr = usergetdate($ts,1);//specify the timezone as an argument
1292
 
        $arr = array_values($arr);
1293
 
 
1294
 
        list($seconds,$minutes,$hours,$mday,$wday,$mon,$year,$yday,$weekday,$month) = $arr;
1295
 
        $this->assertSame($seconds, 7);
1296
 
        $this->assertSame($minutes, 51);
1297
 
        $this->assertSame($hours, 4);
1298
 
        $this->assertSame($mday, 23);
1299
 
        $this->assertSame($wday, 3);
1300
 
        $this->assertSame($mon, 12);
1301
 
        $this->assertSame($year, 2009);
1302
 
        $this->assertSame($yday, 356);
1303
 
        $this->assertSame($weekday, 'Wednesday');
1304
 
        $this->assertSame($month, 'December');
1305
 
        $arr = usergetdate($ts);//gets the timezone from the $USER object
1306
 
        $arr = array_values($arr);
1307
 
 
1308
 
        list($seconds,$minutes,$hours,$mday,$wday,$mon,$year,$yday,$weekday,$month) = $arr;
1309
 
        $this->assertSame($seconds, 7);
1310
 
        $this->assertSame($minutes, 51);
1311
 
        $this->assertSame($hours, 5);
1312
 
        $this->assertSame($mday, 23);
1313
 
        $this->assertSame($wday, 3);
1314
 
        $this->assertSame($mon, 12);
1315
 
        $this->assertSame($year, 2009);
1316
 
        $this->assertSame($yday, 356);
1317
 
        $this->assertSame($weekday, 'Wednesday');
1318
 
        $this->assertSame($month, 'December');
1319
 
        //set the timezone back to what it was
 
951
        $ts = 1261540267; // The time this function was created.
 
952
 
 
953
        $arr = usergetdate($ts, 1); // Specify the timezone as an argument.
 
954
        $arr = array_values($arr);
 
955
 
 
956
        list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
 
957
        $this->assertSame(7, $seconds);
 
958
        $this->assertSame(51, $minutes);
 
959
        $this->assertSame(4, $hours);
 
960
        $this->assertSame(23, $mday);
 
961
        $this->assertSame(3, $wday);
 
962
        $this->assertSame(12, $mon);
 
963
        $this->assertSame(2009, $year);
 
964
        $this->assertSame(356, $yday);
 
965
        $this->assertSame('Wednesday', $weekday);
 
966
        $this->assertSame('December', $month);
 
967
        $arr = usergetdate($ts); // Gets the timezone from the $USER object.
 
968
        $arr = array_values($arr);
 
969
 
 
970
        list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
 
971
        $this->assertSame(7, $seconds);
 
972
        $this->assertSame(51, $minutes);
 
973
        $this->assertSame(5, $hours);
 
974
        $this->assertSame(23, $mday);
 
975
        $this->assertSame(3, $wday);
 
976
        $this->assertSame(12, $mon);
 
977
        $this->assertSame(2009, $year);
 
978
        $this->assertSame(356, $yday);
 
979
        $this->assertSame('Wednesday', $weekday);
 
980
        $this->assertSame('December', $month);
 
981
        // Set the timezone back to what it was.
1320
982
        $USER->timezone = $userstimezone;
1321
983
 
1322
 
        //restore forcetimezone if changed.
 
984
        // Restore forcetimezone if changed.
1323
985
        if (!is_null($cfgforcetimezone)) {
1324
986
            $CFG->forcetimezone = $cfgforcetimezone;
1325
987
        }
1326
988
 
1327
989
        setlocale(LC_TIME, $oldlocale);
1328
 
 
1329
 
        $USER = $olduser;
1330
 
    }
1331
 
 
1332
 
    public function test_normalize_component() {
1333
 
 
1334
 
        // moodle core
1335
 
        $this->assertEquals(normalize_component('moodle'), array('core', null));
1336
 
        $this->assertEquals(normalize_component('core'), array('core', null));
1337
 
 
1338
 
        // moodle core subsystems
1339
 
        $this->assertEquals(normalize_component('admin'), array('core', 'admin'));
1340
 
        $this->assertEquals(normalize_component('core_admin'), array('core', 'admin'));
1341
 
 
1342
 
        // activity modules and their subplugins
1343
 
        $this->assertEquals(normalize_component('workshop'), array('mod', 'workshop'));
1344
 
        $this->assertEquals(normalize_component('mod_workshop'), array('mod', 'workshop'));
1345
 
        $this->assertEquals(normalize_component('workshopform_accumulative'), array('workshopform', 'accumulative'));
1346
 
        $this->assertEquals(normalize_component('quiz'), array('mod', 'quiz'));
1347
 
        $this->assertEquals(normalize_component('quiz_grading'), array('quiz', 'grading'));
1348
 
        $this->assertEquals(normalize_component('data'), array('mod', 'data'));
1349
 
        $this->assertEquals(normalize_component('datafield_checkbox'), array('datafield', 'checkbox'));
1350
 
 
1351
 
        // other plugin types
1352
 
        $this->assertEquals(normalize_component('auth_mnet'), array('auth', 'mnet'));
1353
 
        $this->assertEquals(normalize_component('enrol_self'), array('enrol', 'self'));
1354
 
        $this->assertEquals(normalize_component('block_html'), array('block', 'html'));
1355
 
        $this->assertEquals(normalize_component('block_mnet_hosts'), array('block', 'mnet_hosts'));
1356
 
        $this->assertEquals(normalize_component('local_amos'), array('local', 'amos'));
1357
 
 
1358
 
        // unknown components are supposed to be activity modules
1359
 
        $this->assertEquals(normalize_component('whothefuckwouldcomewithsuchastupidnameofcomponent'),
1360
 
            array('mod', 'whothefuckwouldcomewithsuchastupidnameofcomponent'));
1361
 
        $this->assertEquals(normalize_component('whothefuck_wouldcomewithsuchastupidnameofcomponent'),
1362
 
            array('mod', 'whothefuck_wouldcomewithsuchastupidnameofcomponent'));
1363
 
        $this->assertEquals(normalize_component('whothefuck_would_come_withsuchastupidnameofcomponent'),
1364
 
            array('mod', 'whothefuck_would_come_withsuchastupidnameofcomponent'));
1365
 
    }
1366
 
 
1367
 
    protected function get_fake_preference_test_userid() {
1368
 
        global $DB;
1369
 
 
1370
 
        // we need some nonexistent user id
1371
 
        $id = 2147483647 - 666;
1372
 
        if ($DB->get_records('user', array('id'=>$id))) {
1373
 
            //weird!
1374
 
            return false;
1375
 
        }
1376
 
        return $id;
1377
990
    }
1378
991
 
1379
992
    public function test_mark_user_preferences_changed() {
1380
 
        $this->resetAfterTest(true);
1381
 
        if (!$otheruserid = $this->get_fake_preference_test_userid()) {
1382
 
            $this->fail('Can not find unused user id for the preferences test');
1383
 
            return;
1384
 
        }
 
993
        $this->resetAfterTest();
 
994
        $otheruser = $this->getDataGenerator()->create_user();
 
995
        $otheruserid = $otheruser->id;
1385
996
 
1386
 
        set_cache_flag('userpreferenceschanged', $otheruserid, NULL);
 
997
        set_cache_flag('userpreferenceschanged', $otheruserid, null);
1387
998
        mark_user_preferences_changed($otheruserid);
1388
999
 
1389
1000
        $this->assertEquals(get_cache_flag('userpreferenceschanged', $otheruserid, time()-10), 1);
1390
 
        set_cache_flag('userpreferenceschanged', $otheruserid, NULL);
 
1001
        set_cache_flag('userpreferenceschanged', $otheruserid, null);
1391
1002
    }
1392
1003
 
1393
1004
    public function test_check_user_preferences_loaded() {
1394
1005
        global $DB;
1395
 
        $this->resetAfterTest(true);
 
1006
        $this->resetAfterTest();
1396
1007
 
1397
 
        if (!$otheruserid = $this->get_fake_preference_test_userid()) {
1398
 
            $this->fail('Can not find unused user id for the preferences test');
1399
 
            return;
1400
 
        }
 
1008
        $otheruser = $this->getDataGenerator()->create_user();
 
1009
        $otheruserid = $otheruser->id;
1401
1010
 
1402
1011
        $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1403
 
        set_cache_flag('userpreferenceschanged', $otheruserid, NULL);
 
1012
        set_cache_flag('userpreferenceschanged', $otheruserid, null);
1404
1013
 
1405
1014
        $user = new stdClass();
1406
1015
        $user->id = $otheruserid;
1407
1016
 
1408
 
        // load
 
1017
        // Load.
1409
1018
        check_user_preferences_loaded($user);
1410
1019
        $this->assertTrue(isset($user->preference));
1411
1020
        $this->assertTrue(is_array($user->preference));
1412
 
        $this->assertTrue(isset($user->preference['_lastloaded']));
1413
 
        $this->assertEquals(count($user->preference), 1);
 
1021
        $this->assertArrayHasKey('_lastloaded', $user->preference);
 
1022
        $this->assertCount(1, $user->preference);
1414
1023
 
1415
 
        // add preference via direct call
 
1024
        // Add preference via direct call.
1416
1025
        $DB->insert_record('user_preferences', array('name'=>'xxx', 'value'=>'yyy', 'userid'=>$user->id));
1417
1026
 
1418
 
        // no cache reload yet
 
1027
        // No cache reload yet.
1419
1028
        check_user_preferences_loaded($user);
1420
 
        $this->assertEquals(count($user->preference), 1);
 
1029
        $this->assertCount(1, $user->preference);
1421
1030
 
1422
 
        // forced reloading of cache
 
1031
        // Forced reloading of cache.
1423
1032
        unset($user->preference);
1424
1033
        check_user_preferences_loaded($user);
1425
 
        $this->assertEquals(count($user->preference), 2);
1426
 
        $this->assertEquals($user->preference['xxx'], 'yyy');
 
1034
        $this->assertCount(2, $user->preference);
 
1035
        $this->assertSame('yyy', $user->preference['xxx']);
1427
1036
 
1428
 
        // add preference via direct call
 
1037
        // Add preference via direct call.
1429
1038
        $DB->insert_record('user_preferences', array('name'=>'aaa', 'value'=>'bbb', 'userid'=>$user->id));
1430
1039
 
1431
 
        // test timeouts and modifications from different session
 
1040
        // Test timeouts and modifications from different session.
1432
1041
        set_cache_flag('userpreferenceschanged', $user->id, 1, time() + 1000);
1433
1042
        $user->preference['_lastloaded'] = $user->preference['_lastloaded'] - 20;
1434
1043
        check_user_preferences_loaded($user);
1435
 
        $this->assertEquals(count($user->preference), 2);
 
1044
        $this->assertCount(2, $user->preference);
1436
1045
        check_user_preferences_loaded($user, 10);
1437
 
        $this->assertEquals(count($user->preference), 3);
1438
 
        $this->assertEquals($user->preference['aaa'], 'bbb');
 
1046
        $this->assertCount(3, $user->preference);
 
1047
        $this->assertSame('bbb', $user->preference['aaa']);
1439
1048
        set_cache_flag('userpreferenceschanged', $user->id, null);
1440
1049
    }
1441
1050
 
1442
1051
    public function test_set_user_preference() {
1443
1052
        global $DB, $USER;
1444
 
        $this->resetAfterTest(true);
1445
 
 
1446
 
        $olduser = $USER;
1447
 
        $USER = $DB->get_record('user', array('id'=>2)); //admin
1448
 
 
1449
 
        if (!$otheruserid = $this->get_fake_preference_test_userid()) {
1450
 
            $this->fail('Can not find unused user id for the preferences test');
1451
 
            return;
1452
 
        }
 
1053
        $this->resetAfterTest();
 
1054
 
 
1055
        $this->setAdminUser();
 
1056
 
 
1057
        $otheruser = $this->getDataGenerator()->create_user();
 
1058
        $otheruserid = $otheruser->id;
1453
1059
 
1454
1060
        $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1455
1061
        set_cache_flag('userpreferenceschanged', $otheruserid, null);
1458
1064
        $user->id = $otheruserid;
1459
1065
 
1460
1066
        set_user_preference('aaa', 'bbb', $otheruserid);
1461
 
        $this->assertEquals('bbb', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'aaa')));
1462
 
        $this->assertEquals('bbb', get_user_preferences('aaa', null, $otheruserid));
 
1067
        $this->assertSame('bbb', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'aaa')));
 
1068
        $this->assertSame('bbb', get_user_preferences('aaa', null, $otheruserid));
1463
1069
 
1464
1070
        set_user_preference('xxx', 'yyy', $user);
1465
 
        $this->assertEquals('yyy', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1466
 
        $this->assertEquals('yyy', get_user_preferences('xxx', null, $otheruserid));
 
1071
        $this->assertSame('yyy', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
 
1072
        $this->assertSame('yyy', get_user_preferences('xxx', null, $otheruserid));
1467
1073
        $this->assertTrue(is_array($user->preference));
1468
 
        $this->assertEquals($user->preference['aaa'], 'bbb');
1469
 
        $this->assertEquals($user->preference['xxx'], 'yyy');
 
1074
        $this->assertSame('bbb', $user->preference['aaa']);
 
1075
        $this->assertSame('yyy', $user->preference['xxx']);
1470
1076
 
1471
 
        set_user_preference('xxx', NULL, $user);
1472
 
        $this->assertSame(false, $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1473
 
        $this->assertSame(null, get_user_preferences('xxx', null, $otheruserid));
 
1077
        set_user_preference('xxx', null, $user);
 
1078
        $this->assertFalse($DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
 
1079
        $this->assertNull(get_user_preferences('xxx', null, $otheruserid));
1474
1080
 
1475
1081
        set_user_preference('ooo', true, $user);
1476
1082
        $prefs = get_user_preferences(null, null, $otheruserid);
1477
 
        $this->assertSame($prefs['aaa'], $user->preference['aaa']);
1478
 
        $this->assertSame($prefs['ooo'], $user->preference['ooo']);
1479
 
        $this->assertSame($prefs['ooo'], '1');
 
1083
        $this->assertSame($user->preference['aaa'], $prefs['aaa']);
 
1084
        $this->assertSame($user->preference['ooo'], $prefs['ooo']);
 
1085
        $this->assertSame('1', $prefs['ooo']);
1480
1086
 
1481
1087
        set_user_preference('null', 0, $user);
1482
1088
        $this->assertSame('0', get_user_preferences('null', null, $otheruserid));
1486
1092
        $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1487
1093
        set_cache_flag('userpreferenceschanged', $otheruserid, null);
1488
1094
 
1489
 
        // test $USER default
 
1095
        // Test $USER default.
1490
1096
        set_user_preference('_test_user_preferences_pref', 'ok');
1491
1097
        $this->assertSame('ok', $USER->preference['_test_user_preferences_pref']);
1492
1098
        unset_user_preference('_test_user_preferences_pref');
1493
1099
        $this->assertTrue(!isset($USER->preference['_test_user_preferences_pref']));
1494
1100
 
1495
 
        // Test 1333 char values (no need for unicode, there are already tests for that in DB tests)
 
1101
        // Test 1333 char values (no need for unicode, there are already tests for that in DB tests).
1496
1102
        $longvalue = str_repeat('a', 1333);
1497
1103
        set_user_preference('_test_long_user_preference', $longvalue);
1498
1104
        $this->assertEquals($longvalue, get_user_preferences('_test_long_user_preference'));
1499
1105
        $this->assertEquals($longvalue,
1500
1106
            $DB->get_field('user_preferences', 'value', array('userid' => $USER->id, 'name' => '_test_long_user_preference')));
1501
1107
 
1502
 
        // Test > 1333 char values, coding_exception expected
 
1108
        // Test > 1333 char values, coding_exception expected.
1503
1109
        $longvalue = str_repeat('a', 1334);
1504
1110
        try {
1505
1111
            set_user_preference('_test_long_user_preference', $longvalue);
1506
1112
            $this->fail('Exception expected - longer than 1333 chars not allowed as preference value');
1507
 
        } catch (coding_exception $ex) {
1508
 
            $this->assertTrue(true);
 
1113
        } catch (moodle_exception $ex) {
 
1114
            $this->assertInstanceOf('coding_exception', $ex);
1509
1115
        }
1510
1116
 
1511
 
        //test invalid params
 
1117
        // Test invalid params.
1512
1118
        try {
1513
1119
            set_user_preference('_test_user_preferences_pref', array());
1514
1120
            $this->fail('Exception expected - array not valid preference value');
1515
 
        } catch (coding_exception $ex) {
1516
 
            $this->assertTrue(true);
 
1121
        } catch (moodle_exception $ex) {
 
1122
            $this->assertInstanceOf('coding_exception', $ex);
1517
1123
        }
1518
1124
        try {
1519
1125
            set_user_preference('_test_user_preferences_pref', new stdClass);
1520
1126
            $this->fail('Exception expected - class not valid preference value');
1521
 
        } catch (coding_exception $ex) {
1522
 
            $this->assertTrue(true);
 
1127
        } catch (moodle_exception $ex) {
 
1128
            $this->assertInstanceOf('coding_exception', $ex);
1523
1129
        }
1524
1130
        try {
1525
1131
            set_user_preference('_test_user_preferences_pref', 1, array('xx' => 1));
1526
1132
            $this->fail('Exception expected - user instance expected');
1527
 
        } catch (coding_exception $ex) {
1528
 
            $this->assertTrue(true);
 
1133
        } catch (moodle_exception $ex) {
 
1134
            $this->assertInstanceOf('coding_exception', $ex);
1529
1135
        }
1530
1136
        try {
1531
1137
            set_user_preference('_test_user_preferences_pref', 1, 'abc');
1532
1138
            $this->fail('Exception expected - user instance expected');
1533
 
        } catch (coding_exception $ex) {
1534
 
            $this->assertTrue(true);
 
1139
        } catch (moodle_exception $ex) {
 
1140
            $this->assertInstanceOf('coding_exception', $ex);
1535
1141
        }
1536
1142
        try {
1537
1143
            set_user_preference('', 1);
1538
1144
            $this->fail('Exception expected - invalid name accepted');
1539
 
        } catch (coding_exception $ex) {
1540
 
            $this->assertTrue(true);
 
1145
        } catch (moodle_exception $ex) {
 
1146
            $this->assertInstanceOf('coding_exception', $ex);
1541
1147
        }
1542
1148
        try {
1543
1149
            set_user_preference('1', 1);
1544
1150
            $this->fail('Exception expected - invalid name accepted');
1545
 
        } catch (coding_exception $ex) {
1546
 
            $this->assertTrue(true);
 
1151
        } catch (moodle_exception $ex) {
 
1152
            $this->assertInstanceOf('coding_exception', $ex);
1547
1153
        }
1548
 
 
1549
 
        $USER = $olduser;
1550
1154
    }
1551
1155
 
1552
1156
    public function test_get_extra_user_fields() {
1553
1157
        global $CFG, $USER, $DB;
1554
 
        $oldshowuseridentity = $CFG->showuseridentity;
 
1158
        $this->resetAfterTest();
1555
1159
 
1556
 
        $olduser = $USER;
1557
 
        $USER = $DB->get_record('user', array('id'=>2)); //admin
 
1160
        $this->setAdminUser();
1558
1161
 
1559
1162
        // It would be really nice if there were a way to 'mock' has_capability
1560
1163
        // checks (either to return true or false) but as there is not, this
1562
1165
        // unit tests will have the capability.
1563
1166
        $context = context_system::instance();
1564
1167
 
1565
 
        // No fields
 
1168
        // No fields.
1566
1169
        $CFG->showuseridentity = '';
1567
1170
        $this->assertEquals(array(), get_extra_user_fields($context));
1568
1171
 
1569
 
        // One field
 
1172
        // One field.
1570
1173
        $CFG->showuseridentity = 'frog';
1571
1174
        $this->assertEquals(array('frog'), get_extra_user_fields($context));
1572
1175
 
1573
 
        // Two fields
 
1176
        // Two fields.
1574
1177
        $CFG->showuseridentity = 'frog,zombie';
1575
1178
        $this->assertEquals(array('frog', 'zombie'), get_extra_user_fields($context));
1576
1179
 
1577
 
        // No fields, except
 
1180
        // No fields, except.
1578
1181
        $CFG->showuseridentity = '';
1579
1182
        $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1580
1183
 
1581
 
        // One field
 
1184
        // One field.
1582
1185
        $CFG->showuseridentity = 'frog';
1583
1186
        $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1584
1187
 
1585
 
        // Two fields
 
1188
        // Two fields.
1586
1189
        $CFG->showuseridentity = 'frog,zombie';
1587
1190
        $this->assertEquals(array('zombie'), get_extra_user_fields($context, array('frog')));
1588
 
 
1589
 
        // As long as this test passes, the value will be set back. This is only
1590
 
        // in-memory anyhow
1591
 
        $CFG->showuseridentity = $oldshowuseridentity;
1592
 
 
1593
 
        $USER = $olduser;
1594
1191
    }
1595
1192
 
1596
1193
    public function test_get_extra_user_fields_sql() {
1597
1194
        global $CFG, $USER, $DB;
1598
 
 
1599
 
        $olduser = $USER;
1600
 
        $USER = $DB->get_record('user', array('id'=>2)); //admin
1601
 
 
1602
 
        $oldshowuseridentity = $CFG->showuseridentity;
 
1195
        $this->resetAfterTest();
 
1196
 
 
1197
        $this->setAdminUser();
 
1198
 
1603
1199
        $context = context_system::instance();
1604
1200
 
1605
 
        // No fields
 
1201
        // No fields.
1606
1202
        $CFG->showuseridentity = '';
1607
 
        $this->assertEquals('', get_extra_user_fields_sql($context));
 
1203
        $this->assertSame('', get_extra_user_fields_sql($context));
1608
1204
 
1609
 
        // One field
 
1205
        // One field.
1610
1206
        $CFG->showuseridentity = 'frog';
1611
 
        $this->assertEquals(', frog', get_extra_user_fields_sql($context));
1612
 
 
1613
 
        // Two fields with table prefix
1614
 
        $CFG->showuseridentity = 'frog,zombie';
1615
 
        $this->assertEquals(', u1.frog, u1.zombie', get_extra_user_fields_sql($context, 'u1'));
1616
 
 
1617
 
        // Two fields with field prefix
1618
 
        $CFG->showuseridentity = 'frog,zombie';
1619
 
        $this->assertEquals(', frog AS u_frog, zombie AS u_zombie',
 
1207
        $this->assertSame(', frog', get_extra_user_fields_sql($context));
 
1208
 
 
1209
        // Two fields with table prefix.
 
1210
        $CFG->showuseridentity = 'frog,zombie';
 
1211
        $this->assertSame(', u1.frog, u1.zombie', get_extra_user_fields_sql($context, 'u1'));
 
1212
 
 
1213
        // Two fields with field prefix.
 
1214
        $CFG->showuseridentity = 'frog,zombie';
 
1215
        $this->assertSame(', frog AS u_frog, zombie AS u_zombie',
1620
1216
            get_extra_user_fields_sql($context, '', 'u_'));
1621
1217
 
1622
 
        // One field excluded
 
1218
        // One field excluded.
1623
1219
        $CFG->showuseridentity = 'frog';
1624
 
        $this->assertEquals('', get_extra_user_fields_sql($context, '', '', array('frog')));
 
1220
        $this->assertSame('', get_extra_user_fields_sql($context, '', '', array('frog')));
1625
1221
 
1626
 
        // Two fields, one excluded, table+field prefix
 
1222
        // Two fields, one excluded, table+field prefix.
1627
1223
        $CFG->showuseridentity = 'frog,zombie';
1628
1224
        $this->assertEquals(', u1.zombie AS u_zombie',
1629
1225
            get_extra_user_fields_sql($context, 'u1', 'u_', array('frog')));
1630
 
 
1631
 
        // As long as this test passes, the value will be set back. This is only
1632
 
        // in-memory anyhow
1633
 
        $CFG->showuseridentity = $oldshowuseridentity;
1634
 
        $USER = $olduser;
1635
1226
    }
1636
1227
 
1637
1228
    /**
1689
1280
 
1690
1281
    public function test_userdate() {
1691
1282
        global $USER, $CFG, $DB;
 
1283
        $this->resetAfterTest();
1692
1284
 
1693
 
        $olduser = $USER;
1694
 
        $USER = $DB->get_record('user', array('id'=>2)); //admin
 
1285
        $this->setAdminUser();
1695
1286
 
1696
1287
        $testvalues = array(
1697
1288
            array(
1698
1289
                'time' => '1309514400',
1699
1290
                'usertimezone' => 'America/Moncton',
1700
 
                'timezone' => '0.0', //no dst offset
 
1291
                'timezone' => '0.0', // No dst offset.
1701
1292
                'expectedoutput' => 'Friday, 1 July 2011, 10:00 AM'
1702
1293
            ),
1703
1294
            array(
1704
1295
                'time' => '1309514400',
1705
1296
                'usertimezone' => 'America/Moncton',
1706
 
                'timezone' => '99', //dst offset and timezone offset.
 
1297
                'timezone' => '99', // Dst offset and timezone offset.
1707
1298
                'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1708
1299
            ),
1709
1300
            array(
1710
1301
                'time' => '1309514400',
1711
1302
                'usertimezone' => 'America/Moncton',
1712
 
                'timezone' => 'America/Moncton', //dst offset and timezone offset.
 
1303
                'timezone' => 'America/Moncton', // Dst offset and timezone offset.
1713
1304
                'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1714
1305
            ),
1715
1306
            array(
1716
1307
                'time' => '1293876000 ',
1717
1308
                'usertimezone' => 'America/Moncton',
1718
 
                'timezone' => '0.0', //no dst offset
 
1309
                'timezone' => '0.0', // No dst offset.
1719
1310
                'expectedoutput' => 'Saturday, 1 January 2011, 10:00 AM'
1720
1311
            ),
1721
1312
            array(
1722
1313
                'time' => '1293876000 ',
1723
1314
                'usertimezone' => 'America/Moncton',
1724
 
                'timezone' => '99', //no dst offset in jan, so just timezone offset.
 
1315
                'timezone' => '99', // No dst offset in jan, so just timezone offset.
1725
1316
                'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1726
1317
            ),
1727
1318
            array(
1728
1319
                'time' => '1293876000 ',
1729
1320
                'usertimezone' => 'America/Moncton',
1730
 
                'timezone' => 'America/Moncton', //no dst offset in jan
 
1321
                'timezone' => 'America/Moncton', // No dst offset in jan.
1731
1322
                'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1732
1323
            ),
1733
1324
            array(
1734
1325
                'time' => '1293876000 ',
1735
1326
                'usertimezone' => '2',
1736
 
                'timezone' => '99', //take user timezone
 
1327
                'timezone' => '99', // Take user timezone.
1737
1328
                'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1738
1329
            ),
1739
1330
            array(
1740
1331
                'time' => '1293876000 ',
1741
1332
                'usertimezone' => '-2',
1742
 
                'timezone' => '99', //take user timezone
 
1333
                'timezone' => '99', // Take user timezone.
1743
1334
                'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1744
1335
            ),
1745
1336
            array(
1746
1337
                'time' => '1293876000 ',
1747
1338
                'usertimezone' => '-10',
1748
 
                'timezone' => '2', //take this timezone
 
1339
                'timezone' => '2', // Take this timezone.
1749
1340
                'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1750
1341
            ),
1751
1342
            array(
1752
1343
                'time' => '1293876000 ',
1753
1344
                'usertimezone' => '-10',
1754
 
                'timezone' => '-2', //take this timezone
 
1345
                'timezone' => '-2', // Take this timezone.
1755
1346
                'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1756
1347
            ),
1757
1348
            array(
1758
1349
                'time' => '1293876000 ',
1759
1350
                'usertimezone' => '-10',
1760
 
                'timezone' => 'random/time', //this should show server time
 
1351
                'timezone' => 'random/time', // This should show server time.
1761
1352
                'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1762
1353
            ),
1763
1354
            array(
1764
1355
                'time' => '1293876000 ',
1765
 
                'usertimezone' => '14', //server time zone
1766
 
                'timezone' => '99', //this should show user time
 
1356
                'usertimezone' => '14', // Server time zone.
 
1357
                'timezone' => '99',     // This should show user time.
1767
1358
                'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1768
1359
            ),
1769
1360
        );
1770
1361
 
1771
 
        //Check if forcetimezone is set then save it and set it to use user timezone
 
1362
        // Check if forcetimezone is set then save it and set it to use user timezone.
1772
1363
        $cfgforcetimezone = null;
1773
1364
        if (isset($CFG->forcetimezone)) {
1774
1365
            $cfgforcetimezone = $CFG->forcetimezone;
1775
 
            $CFG->forcetimezone = 99; //get user default timezone.
 
1366
            $CFG->forcetimezone = 99; // Get user default timezone.
1776
1367
        }
1777
 
        //store user default timezone to restore later
 
1368
        // Store user default timezone to restore later.
1778
1369
        $userstimezone = $USER->timezone;
1779
1370
 
1780
1371
        // The string version of date comes from server locale setting and does
1782
1373
        $oldlocale = setlocale(LC_TIME, '0');
1783
1374
        setlocale(LC_TIME, 'en_AU.UTF-8');
1784
1375
 
1785
 
        //set default timezone to Australia/Perth, else time calculated
1786
 
        //will not match expected values. Before that save system defaults.
 
1376
        // Set default timezone to Australia/Perth, else time calculated
 
1377
        // will not match expected values. Before that save system defaults.
1787
1378
        $systemdefaulttimezone = date_default_timezone_get();
1788
1379
        date_default_timezone_set('Australia/Perth');
1789
1380
 
1791
1382
            $USER->timezone = $vals['usertimezone'];
1792
1383
            $actualoutput = userdate($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
1793
1384
 
1794
 
            //On different systems case of AM PM changes so compare case insensitive
1795
 
            $vals['expectedoutput'] = textlib::strtolower($vals['expectedoutput']);
1796
 
            $actualoutput = textlib::strtolower($actualoutput);
 
1385
            // On different systems case of AM PM changes so compare case insensitive.
 
1386
            $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
 
1387
            $actualoutput = core_text::strtolower($actualoutput);
1797
1388
 
1798
 
            $this->assertEquals($vals['expectedoutput'], $actualoutput,
 
1389
            $this->assertSame($vals['expectedoutput'], $actualoutput,
1799
1390
                "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
1800
1391
                Please check if timezones are updated (Site adminstration -> location -> update timezone)");
1801
1392
        }
1802
1393
 
1803
 
        //restore user timezone back to what it was
 
1394
        // Restore user timezone back to what it was.
1804
1395
        $USER->timezone = $userstimezone;
1805
1396
 
1806
 
        //restore forcetimezone
 
1397
        // Restore forcetimezone.
1807
1398
        if (!is_null($cfgforcetimezone)) {
1808
1399
            $CFG->forcetimezone = $cfgforcetimezone;
1809
1400
        }
1810
1401
 
1811
 
        //restore system default values.
 
1402
        // Restore system default values.
1812
1403
        date_default_timezone_set($systemdefaulttimezone);
1813
1404
        setlocale(LC_TIME, $oldlocale);
1814
 
 
1815
 
        $USER = $olduser;
1816
1405
    }
1817
1406
 
1818
1407
    public function test_make_timestamp() {
1819
1408
        global $USER, $CFG, $DB;
 
1409
        $this->resetAfterTest();
1820
1410
 
1821
 
        $olduser = $USER;
1822
 
        $USER = $DB->get_record('user', array('id'=>2)); //admin
 
1411
        $this->setAdminUser();
1823
1412
 
1824
1413
        $testvalues = array(
1825
1414
            array(
1831
1420
                'minutes' => '00',
1832
1421
                'seconds' => '00',
1833
1422
                'timezone' => '0.0',
1834
 
                'applydst' => false, //no dst offset
1835
 
                'expectedoutput' => '1309514400' // 6pm at UTC+0
 
1423
                'applydst' => false, // No dst offset.
 
1424
                'expectedoutput' => '1309514400' // 6pm at UTC+0.
1836
1425
            ),
1837
1426
            array(
1838
1427
                'usertimezone' => 'America/Moncton',
1842
1431
                'hour' => '10',
1843
1432
                'minutes' => '00',
1844
1433
                'seconds' => '00',
1845
 
                'timezone' => '99', //user default timezone
1846
 
                'applydst' => false, //don't apply dst
 
1434
                'timezone' => '99',  // User default timezone.
 
1435
                'applydst' => false, // Don't apply dst.
1847
1436
                'expectedoutput' => '1309528800'
1848
1437
            ),
1849
1438
            array(
1854
1443
                'hour' => '10',
1855
1444
                'minutes' => '00',
1856
1445
                'seconds' => '00',
1857
 
                'timezone' => '99', //user default timezone
1858
 
                'applydst' => true, //apply dst
 
1446
                'timezone' => '99', // User default timezone.
 
1447
                'applydst' => true, // Apply dst.
1859
1448
                'expectedoutput' => '1309525200'
1860
1449
            ),
1861
1450
            array(
1866
1455
                'hour' => '10',
1867
1456
                'minutes' => '00',
1868
1457
                'seconds' => '00',
1869
 
                'timezone' => 'America/Moncton', //string timezone
1870
 
                'applydst' => true, //apply dst
 
1458
                'timezone' => 'America/Moncton', // String timezone.
 
1459
                'applydst' => true, // Apply dst.
1871
1460
                'expectedoutput' => '1309525200'
1872
1461
            ),
1873
1462
            array(
1874
 
                'usertimezone' => '2',//no dst applyed
1875
 
                'year' => '2011',
1876
 
                'month' => '7',
1877
 
                'day' => '1',
1878
 
                'hour' => '10',
1879
 
                'minutes' => '00',
1880
 
                'seconds' => '00',
1881
 
                'timezone' => '99', //take user timezone
1882
 
                'applydst' => true, //apply dst
1883
 
                'expectedoutput' => '1309507200'
1884
 
            ),
1885
 
            array(
1886
 
                'usertimezone' => '-2',//no dst applyed
1887
 
                'year' => '2011',
1888
 
                'month' => '7',
1889
 
                'day' => '1',
1890
 
                'hour' => '10',
1891
 
                'minutes' => '00',
1892
 
                'seconds' => '00',
1893
 
                'timezone' => '99', //take usertimezone
1894
 
                'applydst' => true, //apply dst
1895
 
                'expectedoutput' => '1309521600'
1896
 
            ),
1897
 
            array(
1898
 
                'usertimezone' => '-10',//no dst applyed
1899
 
                'year' => '2011',
1900
 
                'month' => '7',
1901
 
                'day' => '1',
1902
 
                'hour' => '10',
1903
 
                'minutes' => '00',
1904
 
                'seconds' => '00',
1905
 
                'timezone' => '2', //take this timezone
1906
 
                'applydst' => true, //apply dst
1907
 
                'expectedoutput' => '1309507200'
1908
 
            ),
1909
 
            array(
1910
 
                'usertimezone' => '-10',//no dst applyed
1911
 
                'year' => '2011',
1912
 
                'month' => '7',
1913
 
                'day' => '1',
1914
 
                'hour' => '10',
1915
 
                'minutes' => '00',
1916
 
                'seconds' => '00',
1917
 
                'timezone' => '-2', //take this timezone
1918
 
                'applydst' => true, //apply dst,
1919
 
                'expectedoutput' => '1309521600'
1920
 
            ),
1921
 
            array(
1922
 
                'usertimezone' => '-10',//no dst applyed
1923
 
                'year' => '2011',
1924
 
                'month' => '7',
1925
 
                'day' => '1',
1926
 
                'hour' => '10',
1927
 
                'minutes' => '00',
1928
 
                'seconds' => '00',
1929
 
                'timezone' => 'random/time', //This should show server time
1930
 
                'applydst' => true, //apply dst,
 
1463
                'usertimezone' => '2', // No dst applyed.
 
1464
                'year' => '2011',
 
1465
                'month' => '7',
 
1466
                'day' => '1',
 
1467
                'hour' => '10',
 
1468
                'minutes' => '00',
 
1469
                'seconds' => '00',
 
1470
                'timezone' => '99', // Take user timezone.
 
1471
                'applydst' => true, // Apply dst.
 
1472
                'expectedoutput' => '1309507200'
 
1473
            ),
 
1474
            array(
 
1475
                'usertimezone' => '-2', // No dst applyed.
 
1476
                'year' => '2011',
 
1477
                'month' => '7',
 
1478
                'day' => '1',
 
1479
                'hour' => '10',
 
1480
                'minutes' => '00',
 
1481
                'seconds' => '00',
 
1482
                'timezone' => '99', // Take usertimezone.
 
1483
                'applydst' => true, // Apply dst.
 
1484
                'expectedoutput' => '1309521600'
 
1485
            ),
 
1486
            array(
 
1487
                'usertimezone' => '-10', // No dst applyed.
 
1488
                'year' => '2011',
 
1489
                'month' => '7',
 
1490
                'day' => '1',
 
1491
                'hour' => '10',
 
1492
                'minutes' => '00',
 
1493
                'seconds' => '00',
 
1494
                'timezone' => '2',  // Take this timezone.
 
1495
                'applydst' => true, // Apply dst.
 
1496
                'expectedoutput' => '1309507200'
 
1497
            ),
 
1498
            array(
 
1499
                'usertimezone' => '-10', // No dst applyed.
 
1500
                'year' => '2011',
 
1501
                'month' => '7',
 
1502
                'day' => '1',
 
1503
                'hour' => '10',
 
1504
                'minutes' => '00',
 
1505
                'seconds' => '00',
 
1506
                'timezone' => '-2', // Take this timezone.
 
1507
                'applydst' => true, // Apply dst.
 
1508
                'expectedoutput' => '1309521600'
 
1509
            ),
 
1510
            array(
 
1511
                'usertimezone' => '-10', // No dst applyed.
 
1512
                'year' => '2011',
 
1513
                'month' => '7',
 
1514
                'day' => '1',
 
1515
                'hour' => '10',
 
1516
                'minutes' => '00',
 
1517
                'seconds' => '00',
 
1518
                'timezone' => 'random/time', // This should show server time.
 
1519
                'applydst' => true,          // Apply dst.
1931
1520
                'expectedoutput' => '1309485600'
1932
1521
            ),
1933
1522
            array(
1934
 
                'usertimezone' => '14',//server time
 
1523
                'usertimezone' => '14', // Server time.
1935
1524
                'year' => '2011',
1936
1525
                'month' => '7',
1937
1526
                'day' => '1',
1938
1527
                'hour' => '10',
1939
1528
                'minutes' => '00',
1940
1529
                'seconds' => '00',
1941
 
                'timezone' => '99', //get user time
1942
 
                'applydst' => true, //apply dst,
 
1530
                'timezone' => '99', // Get user time.
 
1531
                'applydst' => true, // Apply dst.
1943
1532
                'expectedoutput' => '1309485600'
1944
1533
            )
1945
1534
        );
1946
1535
 
1947
 
        //Check if forcetimezone is set then save it and set it to use user timezone
 
1536
        // Check if forcetimezone is set then save it and set it to use user timezone.
1948
1537
        $cfgforcetimezone = null;
1949
1538
        if (isset($CFG->forcetimezone)) {
1950
1539
            $cfgforcetimezone = $CFG->forcetimezone;
1951
 
            $CFG->forcetimezone = 99; //get user default timezone.
 
1540
            $CFG->forcetimezone = 99; // Get user default timezone.
1952
1541
        }
1953
1542
 
1954
 
        //store user default timezone to restore later
 
1543
        // Store user default timezone to restore later.
1955
1544
        $userstimezone = $USER->timezone;
1956
1545
 
1957
1546
        // The string version of date comes from server locale setting and does
1959
1548
        $oldlocale = setlocale(LC_TIME, '0');
1960
1549
        setlocale(LC_TIME, 'en_AU.UTF-8');
1961
1550
 
1962
 
        //set default timezone to Australia/Perth, else time calulated
1963
 
        //will not match expected values. Before that save system defaults.
 
1551
        // Set default timezone to Australia/Perth, else time calculated
 
1552
        // Will not match expected values. Before that save system defaults.
1964
1553
        $systemdefaulttimezone = date_default_timezone_get();
1965
1554
        date_default_timezone_set('Australia/Perth');
1966
1555
 
1967
 
        //Test make_timestamp with all testvals and assert if anything wrong.
 
1556
        // Test make_timestamp with all testvals and assert if anything wrong.
1968
1557
        foreach ($testvalues as $vals) {
1969
1558
            $USER->timezone = $vals['usertimezone'];
1970
1559
            $actualoutput = make_timestamp(
1978
1567
                $vals['applydst']
1979
1568
            );
1980
1569
 
1981
 
            //On different systems case of AM PM changes so compare case insenitive
1982
 
            $vals['expectedoutput'] = textlib::strtolower($vals['expectedoutput']);
1983
 
            $actualoutput = textlib::strtolower($actualoutput);
 
1570
            // On different systems case of AM PM changes so compare case insensitive.
 
1571
            $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
 
1572
            $actualoutput = core_text::strtolower($actualoutput);
1984
1573
 
1985
 
            $this->assertEquals($vals['expectedoutput'], $actualoutput,
 
1574
            $this->assertSame($vals['expectedoutput'], $actualoutput,
1986
1575
                "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
1987
1576
                Please check if timezones are updated (Site adminstration -> location -> update timezone)");
1988
1577
        }
1989
1578
 
1990
 
        //restore user timezone back to what it was
 
1579
        // Restore user timezone back to what it was.
1991
1580
        $USER->timezone = $userstimezone;
1992
1581
 
1993
 
        //restore forcetimezone
 
1582
        // Restore forcetimezone.
1994
1583
        if (!is_null($cfgforcetimezone)) {
1995
1584
            $CFG->forcetimezone = $cfgforcetimezone;
1996
1585
        }
1997
1586
 
1998
 
        //restore system default values.
 
1587
        // Restore system default values.
1999
1588
        date_default_timezone_set($systemdefaulttimezone);
2000
1589
        setlocale(LC_TIME, $oldlocale);
2001
 
 
2002
 
        $USER = $olduser;
2003
1590
    }
2004
1591
 
2005
1592
    /**
2009
1596
    public function test_get_string() {
2010
1597
        global $COURSE;
2011
1598
 
2012
 
        // Make sure we are using English
 
1599
        // Make sure we are using English.
2013
1600
        $originallang = $COURSE->lang;
2014
1601
        $COURSE->lang = 'en';
2015
1602
 
2016
1603
        $yes = get_string('yes');
2017
1604
        $yesexpected = 'Yes';
2018
 
        $this->assertEquals(getType($yes), 'string');
2019
 
        $this->assertEquals($yes, $yesexpected);
 
1605
        $this->assertInternalType('string', $yes);
 
1606
        $this->assertSame($yesexpected, $yes);
2020
1607
 
2021
1608
        $yes = get_string('yes', 'moodle');
2022
 
        $this->assertEquals(getType($yes), 'string');
2023
 
        $this->assertEquals($yes, $yesexpected);
 
1609
        $this->assertInternalType('string', $yes);
 
1610
        $this->assertSame($yesexpected, $yes);
2024
1611
 
2025
1612
        $yes = get_string('yes', 'core');
2026
 
        $this->assertEquals(getType($yes), 'string');
2027
 
        $this->assertEquals($yes, $yesexpected);
 
1613
        $this->assertInternalType('string', $yes);
 
1614
        $this->assertSame($yesexpected, $yes);
2028
1615
 
2029
1616
        $yes = get_string('yes', '');
2030
 
        $this->assertEquals(getType($yes), 'string');
2031
 
        $this->assertEquals($yes, $yesexpected);
 
1617
        $this->assertInternalType('string', $yes);
 
1618
        $this->assertSame($yesexpected, $yes);
2032
1619
 
2033
1620
        $yes = get_string('yes', null);
2034
 
        $this->assertEquals(getType($yes), 'string');
2035
 
        $this->assertEquals($yes, $yesexpected);
 
1621
        $this->assertInternalType('string', $yes);
 
1622
        $this->assertSame($yesexpected, $yes);
2036
1623
 
2037
1624
        $yes = get_string('yes', null, 1);
2038
 
        $this->assertEquals(getType($yes), 'string');
2039
 
        $this->assertEquals($yes, $yesexpected);
 
1625
        $this->assertInternalType('string', $yes);
 
1626
        $this->assertSame($yesexpected, $yes);
2040
1627
 
2041
1628
        $days = 1;
2042
1629
        $numdays = get_string('numdays', 'core', '1');
2043
1630
        $numdaysexpected = $days.' days';
2044
 
        $this->assertEquals(getType($numdays), 'string');
2045
 
        $this->assertEquals($numdays, $numdaysexpected);
 
1631
        $this->assertInternalType('string', $numdays);
 
1632
        $this->assertSame($numdaysexpected, $numdays);
2046
1633
 
2047
1634
        $yes = get_string('yes', null, null, true);
2048
 
        $this->assertEquals(get_class($yes), 'lang_string');
2049
 
        $this->assertEquals((string)$yes, $yesexpected);
 
1635
        $this->assertInstanceOf('lang_string', $yes);
 
1636
        $this->assertSame($yesexpected, (string)$yes);
2050
1637
 
2051
1638
        // Test using a lang_string object as the $a argument for a normal
2052
 
        // get_string call (returning string)
 
1639
        // get_string call (returning string).
2053
1640
        $test = new lang_string('yes', null, null, true);
2054
1641
        $testexpected = get_string('numdays', 'core', get_string('yes'));
2055
1642
        $testresult = get_string('numdays', null, $test);
2056
 
        $this->assertEquals(getType($testresult), 'string');
2057
 
        $this->assertEquals($testresult, $testexpected);
 
1643
        $this->assertInternalType('string', $testresult);
 
1644
        $this->assertSame($testexpected, $testresult);
2058
1645
 
2059
1646
        // Test using a lang_string object as the $a argument for an object
2060
 
        // get_string call (returning lang_string)
 
1647
        // get_string call (returning lang_string).
2061
1648
        $test = new lang_string('yes', null, null, true);
2062
1649
        $testexpected = get_string('numdays', 'core', get_string('yes'));
2063
1650
        $testresult = get_string('numdays', null, $test, true);
2064
 
        $this->assertEquals(get_class($testresult), 'lang_string');
2065
 
        $this->assertEquals("$testresult", $testexpected);
 
1651
        $this->assertInstanceOf('lang_string', $testresult);
 
1652
        $this->assertSame($testexpected, "$testresult");
2066
1653
 
2067
1654
        // Make sure that object properties that can't be converted don't cause
2068
 
        // errors
2069
 
        // Level one: This is as deep as current language processing goes
 
1655
        // errors.
 
1656
        // Level one: This is as deep as current language processing goes.
2070
1657
        $test = new stdClass;
2071
1658
        $test->one = 'here';
2072
1659
        $string = get_string('yes', null, $test, true);
2073
 
        $this->assertEquals($string, $yesexpected);
 
1660
        $this->assertEquals($yesexpected, $string);
2074
1661
 
2075
1662
        // Make sure that object properties that can't be converted don't cause
2076
1663
        // errors.
2080
1667
        $test->one = new stdClass;
2081
1668
        $test->one->two = 'here';
2082
1669
        $string = get_string('yes', null, $test, true);
2083
 
        $this->assertEquals($string, $yesexpected);
 
1670
        $this->assertEquals($yesexpected, $string);
2084
1671
 
2085
1672
        // Make sure that object properties that can't be converted don't cause
2086
1673
        // errors.
2091
1678
        $test->one->two = new stdClass;
2092
1679
        $test->one->two->three = 'here';
2093
1680
        $string = get_string('yes', null, $test, true);
2094
 
        $this->assertEquals($string, $yesexpected);
 
1681
        $this->assertEquals($yesexpected, $string);
2095
1682
 
2096
1683
        // Make sure that object properties that can't be converted don't cause
2097
1684
        // errors and check lang_string properties.
2098
 
        // Level one: This is as deep as current language processing goes
 
1685
        // Level one: This is as deep as current language processing goes.
2099
1686
        $test = new stdClass;
2100
1687
        $test->one = new lang_string('yes');
2101
1688
        $string = get_string('yes', null, $test, true);
2102
 
        $this->assertEquals($string, $yesexpected);
 
1689
        $this->assertEquals($yesexpected, $string);
2103
1690
 
2104
1691
        // Make sure that object properties that can't be converted don't cause
2105
1692
        // errors and check lang_string properties.
2109
1696
        $test->one = new stdClass;
2110
1697
        $test->one->two = new lang_string('yes');
2111
1698
        $string = get_string('yes', null, $test, true);
2112
 
        $this->assertEquals($string, $yesexpected);
 
1699
        $this->assertEquals($yesexpected, $string);
2113
1700
 
2114
1701
        // Make sure that object properties that can't be converted don't cause
2115
1702
        // errors and check lang_string properties.
2120
1707
        $test->one->two = new stdClass;
2121
1708
        $test->one->two->three = new lang_string('yes');
2122
1709
        $string = get_string('yes', null, $test, true);
2123
 
        $this->assertEquals($string, $yesexpected);
 
1710
        $this->assertEquals($yesexpected, $string);
2124
1711
 
2125
1712
        // Make sure that array properties that can't be converted don't cause
2126
 
        // errors
 
1713
        // errors.
2127
1714
        $test = array();
2128
1715
        $test['one'] = new stdClass;
2129
1716
        $test['one']->two = 'here';
2130
1717
        $string = get_string('yes', null, $test, true);
2131
 
        $this->assertEquals($string, $yesexpected);
 
1718
        $this->assertEquals($yesexpected, $string);
2132
1719
 
2133
 
        // Same thing but as above except using an object... this is allowed :P
 
1720
        // Same thing but as above except using an object... this is allowed :P.
2134
1721
        $string = get_string('yes', null, null, true);
2135
1722
        $object = new stdClass;
2136
1723
        $object->$string = 'Yes';
2137
 
        $this->assertEquals($string, $yesexpected);
2138
 
        $this->assertEquals($object->$string, $yesexpected);
 
1724
        $this->assertEquals($yesexpected, $string);
 
1725
        $this->assertEquals($yesexpected, $object->$string);
2139
1726
 
2140
 
        // Reset the language
 
1727
        // Reset the language.
2141
1728
        $COURSE->lang = $originallang;
2142
1729
    }
2143
1730
 
2144
1731
    /**
2145
1732
     * @expectedException PHPUnit_Framework_Error_Warning
2146
 
     * @return void
2147
1733
     */
2148
1734
    public function test_get_string_limitation() {
2149
1735
        // This is one of the limitations to the lang_string class. It can't be
2150
 
        // used as a key
 
1736
        // used as a key.
2151
1737
        $array = array(get_string('yes', null, null, true) => 'yes');
2152
1738
    }
2153
1739
 
2156
1742
     */
2157
1743
    public function test_format_float() {
2158
1744
 
2159
 
        // Special case for null
 
1745
        // Special case for null.
2160
1746
        $this->assertEquals('', format_float(null));
2161
1747
 
2162
 
        // Default 1 decimal place
 
1748
        // Default 1 decimal place.
2163
1749
        $this->assertEquals('5.4', format_float(5.43));
2164
1750
        $this->assertEquals('5.0', format_float(5.001));
2165
1751
 
2166
 
        // Custom number of decimal places
 
1752
        // Custom number of decimal places.
2167
1753
        $this->assertEquals('5.43000', format_float(5.43, 5));
2168
1754
 
2169
 
        // Option to strip ending zeros after rounding
 
1755
        // Option to strip ending zeros after rounding.
2170
1756
        $this->assertEquals('5.43', format_float(5.43, 5, true, true));
2171
1757
        $this->assertEquals('5', format_float(5.0001, 3, true, true));
2172
1758
 
2173
1759
        // Tests with a localised decimal separator.
2174
1760
        $this->define_local_decimal_separator();
2175
1761
 
2176
 
        // Localisation on (default)
 
1762
        // Localisation on (default).
2177
1763
        $this->assertEquals('5X43000', format_float(5.43, 5));
2178
1764
        $this->assertEquals('5X43', format_float(5.43, 5, true, true));
2179
1765
 
2180
 
        // Localisation off
 
1766
        // Localisation off.
2181
1767
        $this->assertEquals('5.43000', format_float(5.43, 5, false));
2182
1768
        $this->assertEquals('5.43', format_float(5.43, 5, false, true));
2183
1769
    }
2271
1857
        $user = $this->getDataGenerator()->create_user(array('idnumber'=>'abc'));
2272
1858
        $user2 = $this->getDataGenerator()->create_user(array('idnumber'=>'xyz'));
2273
1859
 
 
1860
        // Delete user and capture event.
 
1861
        $sink = $this->redirectEvents();
2274
1862
        $result = delete_user($user);
 
1863
        $events = $sink->get_events();
 
1864
        $sink->close();
 
1865
        $event = array_pop($events);
 
1866
 
 
1867
        // Test user is deleted in DB.
2275
1868
        $this->assertTrue($result);
2276
1869
        $deluser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
2277
1870
        $this->assertEquals(1, $deluser->deleted);
2282
1875
 
2283
1876
        $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1)));
2284
1877
 
 
1878
        // Test Event.
 
1879
        $this->assertInstanceOf('\core\event\user_deleted', $event);
 
1880
        $this->assertSame($user->id, $event->objectid);
 
1881
        $this->assertSame('user_deleted', $event->get_legacy_eventname());
 
1882
        $this->assertEventLegacyData($user, $event);
 
1883
        $expectedlogdata = array(SITEID, 'user', 'delete', "view.php?id=$user->id", $user->firstname.' '.$user->lastname);
 
1884
        $this->assertEventLegacyLogData($expectedlogdata, $event);
 
1885
        $eventdata = $event->get_data();
 
1886
        $this->assertSame($eventdata['other']['username'], $user->username);
 
1887
        $this->assertSame($eventdata['other']['email'], $user->email);
 
1888
        $this->assertSame($eventdata['other']['idnumber'], $user->idnumber);
 
1889
        $this->assertSame($eventdata['other']['picture'], $user->picture);
 
1890
        $this->assertSame($eventdata['other']['mnethostid'], $user->mnethostid);
 
1891
        $this->assertEquals($user, $event->get_record_snapshot('user', $event->objectid));
 
1892
 
2285
1893
        // Try invalid params.
2286
 
 
2287
1894
        $record = new stdClass();
2288
1895
        $record->grrr = 1;
2289
1896
        try {
2290
1897
            delete_user($record);
2291
1898
            $this->fail('Expecting exception for invalid delete_user() $user parameter');
2292
 
        } catch (coding_exception $e) {
2293
 
            $this->assertTrue(true);
 
1899
        } catch (moodle_exception $ex) {
 
1900
            $this->assertInstanceOf('coding_exception', $ex);
2294
1901
        }
2295
1902
        $record->id = 1;
2296
1903
        try {
2297
1904
            delete_user($record);
2298
1905
            $this->fail('Expecting exception for invalid delete_user() $user parameter');
2299
 
        } catch (coding_exception $e) {
2300
 
            $this->assertTrue(true);
 
1906
        } catch (moodle_exception $ex) {
 
1907
            $this->assertInstanceOf('coding_exception', $ex);
2301
1908
        }
2302
1909
 
2303
1910
        $record = new stdClass();
2320
1927
     * Test function convert_to_array()
2321
1928
     */
2322
1929
    public function test_convert_to_array() {
2323
 
        // check that normal classes are converted to arrays the same way as (array) would do
 
1930
        // Check that normal classes are converted to arrays the same way as (array) would do.
2324
1931
        $obj = new stdClass();
2325
1932
        $obj->prop1 = 'hello';
2326
1933
        $obj->prop2 = array('first', 'second', 13);
2327
1934
        $obj->prop3 = 15;
2328
1935
        $this->assertEquals(convert_to_array($obj), (array)$obj);
2329
1936
 
2330
 
        // check that context object (with iterator) is converted to array properly
2331
 
        $obj = get_system_context();
 
1937
        // Check that context object (with iterator) is converted to array properly.
 
1938
        $obj = context_system::instance();
2332
1939
        $ar = array(
2333
1940
            'id'           => $obj->id,
2334
1941
            'contextlevel' => $obj->contextlevel,
2342
1949
    /**
2343
1950
     * Test the function date_format_string().
2344
1951
     */
2345
 
    function test_date_format_string() {
 
1952
    public function test_date_format_string() {
2346
1953
        global $CFG;
2347
1954
 
2348
1955
        // Forcing locale and timezone.
2398
2005
        // On different systems case of AM PM changes so compare case insensitive.
2399
2006
        foreach ($tests as $test) {
2400
2007
            $str = date_format_string(1293876000, $test['str'], $test['tz']);
2401
 
            $this->assertEquals(textlib::strtolower($test['expected']), textlib::strtolower($str));
 
2008
            $this->assertSame(core_text::strtolower($test['expected']), core_text::strtolower($str));
2402
2009
        }
2403
2010
 
2404
2011
        // Restore system default values.
2429
2036
        $CFG->phpunit_test_get_config_5 = 'test 5';
2430
2037
 
2431
2038
        // Testing.
2432
 
        $this->assertEquals('test 1', get_config('core', 'phpunit_test_get_config_1'));
2433
 
        $this->assertEquals('test 2', get_config('mod_forum', 'phpunit_test_get_config_2'));
2434
 
        $this->assertEquals('test 3', get_config('core', 'phpunit_test_get_config_3'));
2435
 
        $this->assertEquals('test 4', get_config('mod_forum', 'phpunit_test_get_config_4'));
 
2039
        $this->assertSame('test 1', get_config('core', 'phpunit_test_get_config_1'));
 
2040
        $this->assertSame('test 2', get_config('mod_forum', 'phpunit_test_get_config_2'));
 
2041
        $this->assertSame('test 3', get_config('core', 'phpunit_test_get_config_3'));
 
2042
        $this->assertSame('test 4', get_config('mod_forum', 'phpunit_test_get_config_4'));
2436
2043
        $this->assertFalse(get_config('core', 'phpunit_test_get_config_5'));
2437
2044
        $this->assertFalse(get_config('core', 'phpunit_test_get_config_x'));
2438
2045
        $this->assertFalse(get_config('mod_forum', 'phpunit_test_get_config_x'));
2439
2046
 
2440
2047
        // Test config we know to exist.
2441
 
        $this->assertEquals($CFG->dataroot, get_config('core', 'dataroot'));
2442
 
        $this->assertEquals($CFG->phpunit_dataroot, get_config('core', 'phpunit_dataroot'));
2443
 
        $this->assertEquals($CFG->dataroot, get_config('core', 'phpunit_dataroot'));
2444
 
        $this->assertEquals(get_config('core', 'dataroot'), get_config('core', 'phpunit_dataroot'));
 
2048
        $this->assertSame($CFG->dataroot, get_config('core', 'dataroot'));
 
2049
        $this->assertSame($CFG->phpunit_dataroot, get_config('core', 'phpunit_dataroot'));
 
2050
        $this->assertSame($CFG->dataroot, get_config('core', 'phpunit_dataroot'));
 
2051
        $this->assertSame(get_config('core', 'dataroot'), get_config('core', 'phpunit_dataroot'));
2445
2052
 
2446
2053
        // Test setting a config var that already exists.
2447
2054
        set_config('phpunit_test_get_config_1', 'test a');
2448
 
        $this->assertEquals('test a', $CFG->phpunit_test_get_config_1);
2449
 
        $this->assertEquals('test a', get_config('core', 'phpunit_test_get_config_1'));
 
2055
        $this->assertSame('test a', $CFG->phpunit_test_get_config_1);
 
2056
        $this->assertSame('test a', get_config('core', 'phpunit_test_get_config_1'));
2450
2057
 
2451
2058
        // Test cache invalidation.
2452
2059
        $cache = cache::make('core', 'config');
2458
2065
        $this->assertFalse($cache->get('mod_forum'));
2459
2066
    }
2460
2067
 
2461
 
    function test_get_max_upload_sizes() {
 
2068
    public function test_get_max_upload_sizes() {
2462
2069
        // Test with very low limits so we are not affected by php upload limits.
2463
2070
        // Test activity limit smallest.
2464
2071
        $sitebytes = 102400;
2466
2073
        $modulebytes = 10240;
2467
2074
        $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2468
2075
 
2469
 
        $this->assertEquals('Activity upload limit (10KB)', $result['0']);
2470
 
        $this->assertEquals(2, count($result));
 
2076
        $this->assertSame('Activity upload limit (10KB)', $result['0']);
 
2077
        $this->assertCount(2, $result);
2471
2078
 
2472
2079
        // Test course limit smallest.
2473
2080
        $sitebytes = 102400;
2475
2082
        $modulebytes = 51200;
2476
2083
        $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2477
2084
 
2478
 
        $this->assertEquals('Course upload limit (10KB)', $result['0']);
2479
 
        $this->assertEquals(2, count($result));
 
2085
        $this->assertSame('Course upload limit (10KB)', $result['0']);
 
2086
        $this->assertCount(2, $result);
2480
2087
 
2481
2088
        // Test site limit smallest.
2482
2089
        $sitebytes = 10240;
2484
2091
        $modulebytes = 51200;
2485
2092
        $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2486
2093
 
2487
 
        $this->assertEquals('Site upload limit (10KB)', $result['0']);
2488
 
        $this->assertEquals(2, count($result));
 
2094
        $this->assertSame('Site upload limit (10KB)', $result['0']);
 
2095
        $this->assertCount(2, $result);
2489
2096
 
2490
2097
        // Test site limit not set.
2491
2098
        $sitebytes = 0;
2493
2100
        $modulebytes = 51200;
2494
2101
        $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2495
2102
 
2496
 
        $this->assertEquals('Activity upload limit (50KB)', $result['0']);
2497
 
        $this->assertEquals(3, count($result));
 
2103
        $this->assertSame('Activity upload limit (50KB)', $result['0']);
 
2104
        $this->assertCount(3, $result);
2498
2105
 
2499
2106
        $sitebytes = 0;
2500
2107
        $coursebytes = 51200;
2501
2108
        $modulebytes = 102400;
2502
2109
        $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2503
2110
 
2504
 
        $this->assertEquals('Course upload limit (50KB)', $result['0']);
2505
 
        $this->assertEquals(3, count($result));
 
2111
        $this->assertSame('Course upload limit (50KB)', $result['0']);
 
2112
        $this->assertCount(3, $result);
2506
2113
 
2507
2114
        // Test custom bytes in range.
2508
2115
        $sitebytes = 102400;
2511
2118
        $custombytes = 10240;
2512
2119
        $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2513
2120
 
2514
 
        $this->assertEquals(3, count($result));
 
2121
        $this->assertCount(3, $result);
2515
2122
 
2516
2123
        // Test custom bytes in range but non-standard.
2517
2124
        $sitebytes = 102400;
2520
2127
        $custombytes = 25600;
2521
2128
        $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2522
2129
 
2523
 
        $this->assertEquals(4, count($result));
 
2130
        $this->assertCount(4, $result);
2524
2131
 
2525
2132
        // Test custom bytes out of range.
2526
2133
        $sitebytes = 102400;
2529
2136
        $custombytes = 102400;
2530
2137
        $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2531
2138
 
2532
 
        $this->assertEquals(3, count($result));
 
2139
        $this->assertCount(3, $result);
2533
2140
 
2534
2141
        // Test custom bytes out of range and non-standard.
2535
2142
        $sitebytes = 102400;
2538
2145
        $custombytes = 256000;
2539
2146
        $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2540
2147
 
2541
 
        $this->assertEquals(3, count($result));
 
2148
        $this->assertCount(3, $result);
2542
2149
 
2543
2150
        // Test site limit only.
2544
2151
        $sitebytes = 51200;
2545
2152
        $result = get_max_upload_sizes($sitebytes);
2546
2153
 
2547
 
        $this->assertEquals('Site upload limit (50KB)', $result['0']);
2548
 
        $this->assertEquals('50KB', $result['51200']);
2549
 
        $this->assertEquals('10KB', $result['10240']);
 
2154
        $this->assertSame('Site upload limit (50KB)', $result['0']);
 
2155
        $this->assertSame('50KB', $result['51200']);
 
2156
        $this->assertSame('10KB', $result['10240']);
2550
2157
        $this->assertCount(3, $result);
2551
2158
 
2552
2159
        // Test no limit.
2648
2255
            $this->assertTrue(validate_internal_user_password($user, $password));
2649
2256
            // The database field for the user should also have been updated to the
2650
2257
            // same value.
2651
 
            $this->assertEquals($user->password, $DB->get_field('user', 'password', array('id' => $user->id)));
 
2258
            $this->assertSame($user->password, $DB->get_field('user', 'password', array('id' => $user->id)));
2652
2259
        }
2653
2260
 
2654
2261
        $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2661
2268
        if (password_compat_not_supported()) {
2662
2269
            // If bcrypt not properly supported the password should remain as an md5 hash.
2663
2270
            $expected_hash = hash_internal_user_password('password', true);
2664
 
            $this->assertEquals($user->password, $expected_hash);
 
2271
            $this->assertSame($user->password, $expected_hash);
2665
2272
            $this->assertTrue(password_is_legacy_hash($user->password));
2666
2273
        } else {
2667
2274
            // Otherwise password should have been updated to a bcrypt hash.
2669
2276
        }
2670
2277
    }
2671
2278
 
 
2279
    public function test_fullname() {
 
2280
        global $CFG;
 
2281
 
 
2282
        $this->resetAfterTest();
 
2283
 
 
2284
        // Create a user to test the name display on.
 
2285
        $record = array();
 
2286
        $record['firstname'] = 'Scott';
 
2287
        $record['lastname'] = 'Fletcher';
 
2288
        $record['firstnamephonetic'] = 'スコット';
 
2289
        $record['lastnamephonetic'] = 'フレチャー';
 
2290
        $record['alternatename'] = 'No friends';
 
2291
        $user = $this->getDataGenerator()->create_user($record);
 
2292
 
 
2293
        // Back up config settings for restore later.
 
2294
        $originalcfg = new stdClass();
 
2295
        $originalcfg->fullnamedisplay = $CFG->fullnamedisplay;
 
2296
 
 
2297
        // Testing existing fullnamedisplay settings.
 
2298
        $CFG->fullnamedisplay = 'firstname';
 
2299
        $testname = fullname($user);
 
2300
        $this->assertSame($user->firstname, $testname);
 
2301
 
 
2302
        $CFG->fullnamedisplay = 'firstname lastname';
 
2303
        $expectedname = "$user->firstname $user->lastname";
 
2304
        $testname = fullname($user);
 
2305
        $this->assertSame($expectedname, $testname);
 
2306
 
 
2307
        $CFG->fullnamedisplay = 'lastname firstname';
 
2308
        $expectedname = "$user->lastname $user->firstname";
 
2309
        $testname = fullname($user);
 
2310
        $this->assertSame($expectedname, $testname);
 
2311
 
 
2312
        $expectedname = get_string('fullnamedisplay', null, $user);
 
2313
        $CFG->fullnamedisplay = 'language';
 
2314
        $testname = fullname($user);
 
2315
        $this->assertSame($expectedname, $testname);
 
2316
 
 
2317
        // Test override parameter.
 
2318
        $CFG->fullnamedisplay = 'firstname';
 
2319
        $expectedname = "$user->firstname $user->lastname";
 
2320
        $testname = fullname($user, true);
 
2321
        $this->assertSame($expectedname, $testname);
 
2322
 
 
2323
        // Test additional name fields.
 
2324
        $CFG->fullnamedisplay = 'lastname lastnamephonetic firstname firstnamephonetic';
 
2325
        $expectedname = "$user->lastname $user->lastnamephonetic $user->firstname $user->firstnamephonetic";
 
2326
        $testname = fullname($user);
 
2327
        $this->assertSame($expectedname, $testname);
 
2328
 
 
2329
        // Test for handling missing data.
 
2330
        $user->middlename = null;
 
2331
        // Parenthesis with no data.
 
2332
        $CFG->fullnamedisplay = 'firstname (middlename) lastname';
 
2333
        $expectedname = "$user->firstname $user->lastname";
 
2334
        $testname = fullname($user);
 
2335
        $this->assertSame($expectedname, $testname);
 
2336
 
 
2337
        // Extra spaces due to no data.
 
2338
        $CFG->fullnamedisplay = 'firstname middlename lastname';
 
2339
        $expectedname = "$user->firstname $user->lastname";
 
2340
        $testname = fullname($user);
 
2341
        $this->assertSame($expectedname, $testname);
 
2342
 
 
2343
        // Regular expression testing.
 
2344
        // Remove some data from the user fields.
 
2345
        $user->firstnamephonetic = '';
 
2346
        $user->lastnamephonetic = '';
 
2347
 
 
2348
        // Removing empty brackets and excess whitespace.
 
2349
        // All of these configurations should resolve to just firstname lastname.
 
2350
        $configarray = array();
 
2351
        $configarray[] = 'firstname lastname [firstnamephonetic lastnamephonetic]';
 
2352
        $configarray[] = 'firstname lastname \'middlename\'';
 
2353
        $configarray[] = 'firstname "firstnamephonetic" lastname';
 
2354
        $configarray[] = 'firstname 「firstnamephonetic」 lastname 「lastnamephonetic」';
 
2355
 
 
2356
        foreach ($configarray as $config) {
 
2357
            $CFG->fullnamedisplay = $config;
 
2358
            $expectedname = "$user->firstname $user->lastname";
 
2359
            $testname = fullname($user);
 
2360
            $this->assertSame($expectedname, $testname);
 
2361
        }
 
2362
 
 
2363
        // Check to make sure that other characters are left in place.
 
2364
        $configarray = array();
 
2365
        $configarray['0'] = new stdClass();
 
2366
        $configarray['0']->config = 'lastname firstname, middlename';
 
2367
        $configarray['0']->expectedname = "$user->lastname $user->firstname,";
 
2368
        $configarray['1'] = new stdClass();
 
2369
        $configarray['1']->config = 'lastname firstname + alternatename';
 
2370
        $configarray['1']->expectedname = "$user->lastname $user->firstname + $user->alternatename";
 
2371
        $configarray['2'] = new stdClass();
 
2372
        $configarray['2']->config = 'firstname aka: alternatename';
 
2373
        $configarray['2']->expectedname = "$user->firstname aka: $user->alternatename";
 
2374
        $configarray['3'] = new stdClass();
 
2375
        $configarray['3']->config = 'firstname (alternatename)';
 
2376
        $configarray['3']->expectedname = "$user->firstname ($user->alternatename)";
 
2377
        $configarray['4'] = new stdClass();
 
2378
        $configarray['4']->config = 'firstname [alternatename]';
 
2379
        $configarray['4']->expectedname = "$user->firstname [$user->alternatename]";
 
2380
        $configarray['5'] = new stdClass();
 
2381
        $configarray['5']->config = 'firstname "lastname"';
 
2382
        $configarray['5']->expectedname = "$user->firstname \"$user->lastname\"";
 
2383
 
 
2384
        foreach ($configarray as $config) {
 
2385
            $CFG->fullnamedisplay = $config->config;
 
2386
            $expectedname = $config->expectedname;
 
2387
            $testname = fullname($user);
 
2388
            $this->assertSame($expectedname, $testname);
 
2389
        }
 
2390
 
 
2391
        // Test debugging message displays when
 
2392
        // fullnamedisplay setting is "normal".
 
2393
        $CFG->fullnamedisplay = 'firstname lastname';
 
2394
        unset($user);
 
2395
        $user = new stdClass();
 
2396
        $user->firstname = 'Stan';
 
2397
        $user->lastname = 'Lee';
 
2398
        $namedisplay = fullname($user);
 
2399
        $this->assertDebuggingCalled();
 
2400
 
 
2401
        // Tidy up after we finish testing.
 
2402
        $CFG->fullnamedisplay = $originalcfg->fullnamedisplay;
 
2403
    }
 
2404
 
 
2405
    public function test_get_all_user_name_fields() {
 
2406
        $this->resetAfterTest();
 
2407
 
 
2408
        // Additional names in an array.
 
2409
        $testarray = array('firstnamephonetic' => 'firstnamephonetic',
 
2410
                'lastnamephonetic' => 'lastnamephonetic',
 
2411
                'middlename' => 'middlename',
 
2412
                'alternatename' => 'alternatename',
 
2413
                'firstname' => 'firstname',
 
2414
                'lastname' => 'lastname');
 
2415
        $this->assertEquals($testarray, get_all_user_name_fields());
 
2416
 
 
2417
        // Additional names as a string.
 
2418
        $teststring = 'firstnamephonetic,lastnamephonetic,middlename,alternatename,firstname,lastname';
 
2419
        $this->assertEquals($teststring, get_all_user_name_fields(true));
 
2420
 
 
2421
        // Additional names as a string with an alias.
 
2422
        $teststring = 't.firstnamephonetic,t.lastnamephonetic,t.middlename,t.alternatename,t.firstname,t.lastname';
 
2423
        $this->assertEquals($teststring, get_all_user_name_fields(true, 't'));
 
2424
 
 
2425
        // Additional name fields with a prefix - object.
 
2426
        $testarray = array('firstnamephonetic' => 'authorfirstnamephonetic',
 
2427
                'lastnamephonetic' => 'authorlastnamephonetic',
 
2428
                'middlename' => 'authormiddlename',
 
2429
                'alternatename' => 'authoralternatename',
 
2430
                'firstname' => 'authorfirstname',
 
2431
                'lastname' => 'authorlastname');
 
2432
        $this->assertEquals($testarray, get_all_user_name_fields(false, null, 'author'));
 
2433
 
 
2434
        // Additional name fields with an alias and a title - string.
 
2435
        $teststring = 'u.firstnamephonetic AS authorfirstnamephonetic,u.lastnamephonetic AS authorlastnamephonetic,u.middlename AS authormiddlename,u.alternatename AS authoralternatename,u.firstname AS authorfirstname,u.lastname AS authorlastname';
 
2436
        $this->assertEquals($teststring, get_all_user_name_fields(true, 'u', null, 'author'));
 
2437
    }
 
2438
 
 
2439
    public function test_order_in_string() {
 
2440
        $this->resetAfterTest();
 
2441
 
 
2442
        // Return an array in an order as they are encountered in a string.
 
2443
        $valuearray = array('second', 'firsthalf', 'first');
 
2444
        $formatstring = 'first firsthalf some other text (second)';
 
2445
        $expectedarray = array('0' => 'first', '6' => 'firsthalf', '33' => 'second');
 
2446
        $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
 
2447
 
 
2448
        // Try again with a different order for the format.
 
2449
        $valuearray = array('second', 'firsthalf', 'first');
 
2450
        $formatstring = 'firsthalf first second';
 
2451
        $expectedarray = array('0' => 'firsthalf', '10' => 'first', '16' => 'second');
 
2452
        $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
 
2453
 
 
2454
        // Try again with yet another different order for the format.
 
2455
        $valuearray = array('second', 'firsthalf', 'first');
 
2456
        $formatstring = 'start seconds away second firstquater first firsthalf';
 
2457
        $expectedarray = array('19' => 'second', '38' => 'first', '44' => 'firsthalf');
 
2458
        $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
 
2459
    }
 
2460
 
 
2461
    public function test_complete_user_login() {
 
2462
        global $USER, $DB;
 
2463
 
 
2464
        $this->resetAfterTest();
 
2465
        $user = $this->getDataGenerator()->create_user();
 
2466
        $this->setUser(0);
 
2467
 
 
2468
        $sink = $this->redirectEvents();
 
2469
        $loginuser = clone($user);
 
2470
        $this->setCurrentTimeStart();
 
2471
        @complete_user_login($loginuser); // Hide session header errors.
 
2472
        $this->assertSame($loginuser, $USER);
 
2473
        $this->assertEquals($user->id, $USER->id);
 
2474
        $events = $sink->get_events();
 
2475
        $sink->close();
 
2476
 
 
2477
        $this->assertCount(1, $events);
 
2478
        $event = reset($events);
 
2479
        $this->assertInstanceOf('\core\event\user_loggedin', $event);
 
2480
        $this->assertEquals('user', $event->objecttable);
 
2481
        $this->assertEquals($user->id, $event->objectid);
 
2482
        $this->assertEquals(context_system::instance()->id, $event->contextid);
 
2483
 
 
2484
        $user = $DB->get_record('user', array('id'=>$user->id));
 
2485
 
 
2486
        $this->assertTimeCurrent($user->firstaccess);
 
2487
        $this->assertTimeCurrent($user->lastaccess);
 
2488
 
 
2489
        $this->assertTimeCurrent($USER->firstaccess);
 
2490
        $this->assertTimeCurrent($USER->lastaccess);
 
2491
        $this->assertTimeCurrent($USER->currentlogin);
 
2492
        $this->assertSame(sesskey(), $USER->sesskey);
 
2493
        $this->assertTimeCurrent($USER->preference['_lastloaded']);
 
2494
        $this->assertObjectNotHasAttribute('password', $USER);
 
2495
        $this->assertObjectNotHasAttribute('description', $USER);
 
2496
    }
 
2497
 
 
2498
    /**
 
2499
     * Test require_logout.
 
2500
     */
 
2501
    public function test_require_logout() {
 
2502
        $this->resetAfterTest();
 
2503
        $user = $this->getDataGenerator()->create_user();
 
2504
        $this->setUser($user);
 
2505
 
 
2506
        $this->assertTrue(isloggedin());
 
2507
 
 
2508
        // Logout user and capture event.
 
2509
        $sink = $this->redirectEvents();
 
2510
        require_logout();
 
2511
        $events = $sink->get_events();
 
2512
        $sink->close();
 
2513
        $event = array_pop($events);
 
2514
 
 
2515
        // Check if user is logged out.
 
2516
        $this->assertFalse(isloggedin());
 
2517
 
 
2518
        // Test Event.
 
2519
        $this->assertInstanceOf('\core\event\user_loggedout', $event);
 
2520
        $this->assertSame($user->id, $event->objectid);
 
2521
        $this->assertSame('user_logout', $event->get_legacy_eventname());
 
2522
        $this->assertEventLegacyData($user, $event);
 
2523
        $expectedlogdata = array(SITEID, 'user', 'logout', 'view.php?id='.$event->objectid.'&course='.SITEID, $event->objectid, 0,
 
2524
            $event->objectid);
 
2525
        $this->assertEventLegacyLogData($expectedlogdata, $event);
 
2526
    }
 
2527
 
2672
2528
    public function test_email_to_user() {
 
2529
        global $CFG;
 
2530
 
2673
2531
        $this->resetAfterTest();
2674
2532
 
2675
2533
        $user1 = $this->getDataGenerator()->create_user();
2680
2538
        $subject2 = 'subject 2';
2681
2539
        $messagetext2 = 'message text 2';
2682
2540
 
 
2541
        $this->assertNotEmpty($CFG->noemailever);
 
2542
        email_to_user($user1, $user2, $subject, $messagetext);
 
2543
        $this->assertDebuggingCalled('Not sending email due to $CFG->noemailever config setting');
 
2544
 
2683
2545
        unset_config('noemailever');
2684
2546
 
 
2547
        email_to_user($user1, $user2, $subject, $messagetext);
 
2548
        $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
 
2549
 
2685
2550
        $sink = $this->redirectEmails();
2686
2551
        email_to_user($user1, $user2, $subject, $messagetext);
2687
2552
        email_to_user($user2, $user1, $subject2, $messagetext2);
2699
2564
        $this->assertSame($messagetext2, trim($result[1]->body));
2700
2565
        $this->assertSame($user2->email, $result[1]->to);
2701
2566
        $this->assertSame($user1->email, $result[1]->from);
 
2567
 
 
2568
        email_to_user($user1, $user2, $subject, $messagetext);
 
2569
        $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
 
2570
    }
 
2571
 
 
2572
    /**
 
2573
     * Test user_updated event trigger by various apis.
 
2574
     */
 
2575
    public function test_user_updated_event() {
 
2576
        global $DB, $CFG;
 
2577
 
 
2578
        $this->resetAfterTest();
 
2579
 
 
2580
        $user = $this->getDataGenerator()->create_user();
 
2581
 
 
2582
        // Set config to allow email_to_user() to be called.
 
2583
        $CFG->noemailever = false;
 
2584
 
 
2585
        // Update user password.
 
2586
        $sink = $this->redirectEvents();
 
2587
        $sink2 = $this->redirectEmails(); // Make sure we are redirecting emails.
 
2588
        setnew_password_and_mail($user);
 
2589
        update_internal_user_password($user, 'randompass');
 
2590
        $events = $sink->get_events();
 
2591
        $sink->close();
 
2592
        $sink2->close();
 
2593
 
 
2594
        // Test updated value.
 
2595
        $dbuser = $DB->get_record('user', array('id' => $user->id));
 
2596
        $this->assertSame($user->firstname, $dbuser->firstname);
 
2597
        $this->assertNotSame('M00dLe@T', $dbuser->password);
 
2598
 
 
2599
        // Test event.
 
2600
        foreach ($events as $event) {
 
2601
            $this->assertInstanceOf('\core\event\user_updated', $event);
 
2602
            $this->assertSame($user->id, $event->objectid);
 
2603
            $this->assertSame('user_updated', $event->get_legacy_eventname());
 
2604
            $this->assertEventLegacyData($user, $event);
 
2605
            $this->assertEquals(context_user::instance($user->id), $event->get_context());
 
2606
            $expectedlogdata = array(SITEID, 'user', 'update', 'view.php?id='.$user->id, '');
 
2607
            $this->assertEventLegacyLogData($expectedlogdata, $event);
 
2608
        }
 
2609
    }
 
2610
 
 
2611
    /**
 
2612
     * Test remove_course_content deletes course contents
 
2613
     * TODO Add asserts to verify other data related to course is deleted as well.
 
2614
     */
 
2615
    public function test_remove_course_contents() {
 
2616
 
 
2617
        $this->resetAfterTest();
 
2618
 
 
2619
        $course = $this->getDataGenerator()->create_course();
 
2620
        $user = $this->getDataGenerator()->create_user();
 
2621
        $gen = $this->getDataGenerator()->get_plugin_generator('core_notes');
 
2622
        $note = $gen->create_instance(array('courseid' => $course->id, 'userid' => $user->id));
 
2623
 
 
2624
        $this->assertNotEquals(false, note_load($note->id));
 
2625
        remove_course_contents($course->id, false);
 
2626
        $this->assertFalse(note_load($note->id));
 
2627
    }
 
2628
 
 
2629
    /**
 
2630
     * Test function username_load_fields_from_object().
 
2631
     */
 
2632
    public function test_username_load_fields_from_object() {
 
2633
        $this->resetAfterTest();
 
2634
 
 
2635
        // This object represents the information returned from an sql query.
 
2636
        $userinfo = new stdClass();
 
2637
        $userinfo->userid = 1;
 
2638
        $userinfo->username = 'loosebruce';
 
2639
        $userinfo->firstname = 'Bruce';
 
2640
        $userinfo->lastname = 'Campbell';
 
2641
        $userinfo->firstnamephonetic = 'ブルース';
 
2642
        $userinfo->lastnamephonetic = 'カンベッル';
 
2643
        $userinfo->middlename = '';
 
2644
        $userinfo->alternatename = '';
 
2645
        $userinfo->email = '';
 
2646
        $userinfo->picture = 23;
 
2647
        $userinfo->imagealt = 'Michael Jordan draining another basket.';
 
2648
        $userinfo->idnumber = 3982;
 
2649
 
 
2650
        // Just user name fields.
 
2651
        $user = new stdClass();
 
2652
        $user = username_load_fields_from_object($user, $userinfo);
 
2653
        $expectedarray = new stdClass();
 
2654
        $expectedarray->firstname = 'Bruce';
 
2655
        $expectedarray->lastname = 'Campbell';
 
2656
        $expectedarray->firstnamephonetic = 'ブルース';
 
2657
        $expectedarray->lastnamephonetic = 'カンベッル';
 
2658
        $expectedarray->middlename = '';
 
2659
        $expectedarray->alternatename = '';
 
2660
        $this->assertEquals($user, $expectedarray);
 
2661
 
 
2662
        // User information for showing a picture.
 
2663
        $user = new stdClass();
 
2664
        $additionalfields = explode(',', user_picture::fields());
 
2665
        $user = username_load_fields_from_object($user, $userinfo, null, $additionalfields);
 
2666
        $user->id = $userinfo->userid;
 
2667
        $expectedarray = new stdClass();
 
2668
        $expectedarray->id = 1;
 
2669
        $expectedarray->firstname = 'Bruce';
 
2670
        $expectedarray->lastname = 'Campbell';
 
2671
        $expectedarray->firstnamephonetic = 'ブルース';
 
2672
        $expectedarray->lastnamephonetic = 'カンベッル';
 
2673
        $expectedarray->middlename = '';
 
2674
        $expectedarray->alternatename = '';
 
2675
        $expectedarray->email = '';
 
2676
        $expectedarray->picture = 23;
 
2677
        $expectedarray->imagealt = 'Michael Jordan draining another basket.';
 
2678
        $this->assertEquals($user, $expectedarray);
 
2679
 
 
2680
        // Alter the userinfo object to have a prefix.
 
2681
        $userinfo->authorfirstname = 'Bruce';
 
2682
        $userinfo->authorlastname = 'Campbell';
 
2683
        $userinfo->authorfirstnamephonetic = 'ブルース';
 
2684
        $userinfo->authorlastnamephonetic = 'カンベッル';
 
2685
        $userinfo->authormiddlename = '';
 
2686
        $userinfo->authorpicture = 23;
 
2687
        $userinfo->authorimagealt = 'Michael Jordan draining another basket.';
 
2688
        $userinfo->authoremail = 'test@testing.net';
 
2689
 
 
2690
 
 
2691
        // Return an object with user picture information.
 
2692
        $user = new stdClass();
 
2693
        $additionalfields = explode(',', user_picture::fields());
 
2694
        $user = username_load_fields_from_object($user, $userinfo, 'author', $additionalfields);
 
2695
        $user->id = $userinfo->userid;
 
2696
        $expectedarray = new stdClass();
 
2697
        $expectedarray->id = 1;
 
2698
        $expectedarray->firstname = 'Bruce';
 
2699
        $expectedarray->lastname = 'Campbell';
 
2700
        $expectedarray->firstnamephonetic = 'ブルース';
 
2701
        $expectedarray->lastnamephonetic = 'カンベッル';
 
2702
        $expectedarray->middlename = '';
 
2703
        $expectedarray->alternatename = '';
 
2704
        $expectedarray->email = 'test@testing.net';
 
2705
        $expectedarray->picture = 23;
 
2706
        $expectedarray->imagealt = 'Michael Jordan draining another basket.';
 
2707
        $this->assertEquals($user, $expectedarray);
2702
2708
    }
2703
2709
}