Completed
Push — 2.3 ( 07b9ab...95473c )
by Jeroen
24:31 queued 11:55
created
install/cli/travis_installer.php 1 patch
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
 	exit(2);
18 18
 }
19 19
 
20
-require_once __DIR__ . "/../../autoloader.php";
20
+require_once __DIR__."/../../autoloader.php";
21 21
 
22 22
 $installer = new ElggInstaller();
23 23
 
@@ -36,7 +36,7 @@  discard block
 block discarded – undo
36 36
 	'sitename' => 'Elgg Travis Site',
37 37
 	'siteemail' => '[email protected]',
38 38
 	'wwwroot' => 'http://localhost:8888/',
39
-	'dataroot' => getenv('HOME') . '/elgg_data/',
39
+	'dataroot' => getenv('HOME').'/elgg_data/',
40 40
 
41 41
 	// admin account
42 42
 	'displayname' => 'Administrator',
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
 $version = elgg_get_version(true);
57 57
 
58 58
 // at this point installation has completed (otherwise an exception halted execution).
59
-echo "Elgg $version install successful" . PHP_EOL;
60
-echo "wwwroot: " . elgg_get_config('wwwroot') . PHP_EOL;
59
+echo "Elgg $version install successful".PHP_EOL;
60
+echo "wwwroot: ".elgg_get_config('wwwroot').PHP_EOL;
61 61
 
62 62
 
Please login to merge, or discard this patch.
engine/classes/Elgg/Database/Seeds/Seed.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -263,7 +263,7 @@  discard block
 block discarded – undo
263 263
 
264 264
 	/**
265 265
 	 * Create a new faker object
266
-	 * @return ElggObject|false
266
+	 * @return string|null
267 267
 	 */
268 268
 	public function createObject(array $attributes = [], array $metadata = []) {
269 269
 
@@ -368,7 +368,7 @@  discard block
 block discarded – undo
368 368
 	 *
369 369
 	 * @param int[] $exclude GUIDs to exclude
370 370
 	 *
371
-	 * @return ElggUser|false
371
+	 * @return integer
372 372
 	 */
373 373
 	public function getRandomUser(array $exclude = []) {
374 374
 
Please login to merge, or discard this patch.
Indentation   +662 added lines, -662 removed lines patch added patch discarded remove patch
@@ -17,687 +17,687 @@
 block discarded – undo
17 17
  */
18 18
 abstract class Seed {
19 19
 
20
-	/**
21
-	 * @var int Max number of items to be created by the seed
22
-	 */
23
-	protected $limit = 20;
24
-
25
-	/**
26
-	 * @var \Faker\Generator
27
-	 */
28
-	protected $faker;
29
-
30
-	/**
31
-	 * Seed constructor.
32
-	 *
33
-	 * @param string $locale Locale
34
-	 */
35
-	public function __construct($locale = 'en_US') {
36
-		$this->faker = Factory::create($locale);
37
-	}
38
-
39
-	/**
40
-	 * Populate database
41
-	 * @return mixed
42
-	 */
43
-	abstract function seed();
44
-
45
-	/**
46
-	 * Removed seeded rows from database
47
-	 * @return mixed
48
-	 */
49
-	abstract function unseed();
50
-
51
-	/**
52
-	 * Get site domain
53
-	 * @return string
54
-	 */
55
-	public function getDomain() {
56
-		return elgg_get_site_entity()->getDomain();
57
-	}
58
-
59
-	/**
60
-	 * Create a new faker user
61
-	 * @return ElggUser|false
62
-	 */
63
-	public function createUser(array $attributes = [], array $metadata = []) {
64
-
65
-		$metadata['__faker'] = true;
66
-
67
-		if (empty($attributes['password'])) {
68
-			$attributes['password'] = generate_random_cleartext_password();
69
-		}
70
-
71
-		if (empty($attributes['username'])) {
72
-			$attributes['name'] = $this->faker->name;
73
-		}
74
-
75
-		if (empty($attributes['username'])) {
76
-			$attributes['username'] = $this->getRandomUsername($attributes['name']);
77
-		}
78
-
79
-		if (empty($attributes['email'])) {
80
-			$attributes['email'] = "{$attributes['username']}@{$this->getDomain()}";
81
-			if (!filter_var($attributes['email'], FILTER_VALIDATE_EMAIL)) {
82
-				// Travis tests use localhost as the domain name, which generates invalid email addresses
83
-				$attributes['email'] = "{$attributes['username']}@localhost.com";
84
-			}
85
-		}
86
-
87
-		$user = false;
88
-
89
-		try {
90
-			$guid = register_user($attributes['username'], $attributes['password'], $attributes['name'], $attributes['email']);
91
-			$user = get_entity($guid);
92
-			/* @var $user ElggUser */
93
-
94
-			elgg_set_user_validation_status($guid, $this->faker->boolean(), 'seeder');
95
-
96
-			$user->setNotificationSetting('email', false);
97
-			$user->setNotificationSetting('site', true);
98
-
99
-			$profile_fields = elgg_get_config('profile_fields');
100
-
101
-			$user = $this->populateMetadata($user, $profile_fields, $metadata);
102
-
103
-			$user->save();
104
-
105
-			$this->createIcon($user);
106
-			$this->createComments($user);
107
-			$this->createLikes($user);
108
-
109
-			$this->log("Created new user $user->name [guid: $user->guid]");
20
+    /**
21
+     * @var int Max number of items to be created by the seed
22
+     */
23
+    protected $limit = 20;
24
+
25
+    /**
26
+     * @var \Faker\Generator
27
+     */
28
+    protected $faker;
29
+
30
+    /**
31
+     * Seed constructor.
32
+     *
33
+     * @param string $locale Locale
34
+     */
35
+    public function __construct($locale = 'en_US') {
36
+        $this->faker = Factory::create($locale);
37
+    }
38
+
39
+    /**
40
+     * Populate database
41
+     * @return mixed
42
+     */
43
+    abstract function seed();
44
+
45
+    /**
46
+     * Removed seeded rows from database
47
+     * @return mixed
48
+     */
49
+    abstract function unseed();
50
+
51
+    /**
52
+     * Get site domain
53
+     * @return string
54
+     */
55
+    public function getDomain() {
56
+        return elgg_get_site_entity()->getDomain();
57
+    }
58
+
59
+    /**
60
+     * Create a new faker user
61
+     * @return ElggUser|false
62
+     */
63
+    public function createUser(array $attributes = [], array $metadata = []) {
64
+
65
+        $metadata['__faker'] = true;
66
+
67
+        if (empty($attributes['password'])) {
68
+            $attributes['password'] = generate_random_cleartext_password();
69
+        }
70
+
71
+        if (empty($attributes['username'])) {
72
+            $attributes['name'] = $this->faker->name;
73
+        }
74
+
75
+        if (empty($attributes['username'])) {
76
+            $attributes['username'] = $this->getRandomUsername($attributes['name']);
77
+        }
78
+
79
+        if (empty($attributes['email'])) {
80
+            $attributes['email'] = "{$attributes['username']}@{$this->getDomain()}";
81
+            if (!filter_var($attributes['email'], FILTER_VALIDATE_EMAIL)) {
82
+                // Travis tests use localhost as the domain name, which generates invalid email addresses
83
+                $attributes['email'] = "{$attributes['username']}@localhost.com";
84
+            }
85
+        }
86
+
87
+        $user = false;
88
+
89
+        try {
90
+            $guid = register_user($attributes['username'], $attributes['password'], $attributes['name'], $attributes['email']);
91
+            $user = get_entity($guid);
92
+            /* @var $user ElggUser */
93
+
94
+            elgg_set_user_validation_status($guid, $this->faker->boolean(), 'seeder');
95
+
96
+            $user->setNotificationSetting('email', false);
97
+            $user->setNotificationSetting('site', true);
98
+
99
+            $profile_fields = elgg_get_config('profile_fields');
100
+
101
+            $user = $this->populateMetadata($user, $profile_fields, $metadata);
102
+
103
+            $user->save();
104
+
105
+            $this->createIcon($user);
106
+            $this->createComments($user);
107
+            $this->createLikes($user);
108
+
109
+            $this->log("Created new user $user->name [guid: $user->guid]");
110 110
 
111
-			return $user;
112
-		} catch (Exception $e) {
113
-			if ($user && $user->guid) {
114
-				$user->delete();
115
-			}
116
-
117
-			$this->log($e->getMessage());
118
-
119
-			return false;
120
-		}
121
-
122
-	}
111
+            return $user;
112
+        } catch (Exception $e) {
113
+            if ($user && $user->guid) {
114
+                $user->delete();
115
+            }
116
+
117
+            $this->log($e->getMessage());
118
+
119
+            return false;
120
+        }
121
+
122
+    }
123 123
 
124
-	/**
125
-	 * Create a new faker group
126
-	 * @return ElggGroup|false
127
-	 */
128
-	public function createGroup(array $attributes = [], array $metadata = []) {
124
+    /**
125
+     * Create a new faker group
126
+     * @return ElggGroup|false
127
+     */
128
+    public function createGroup(array $attributes = [], array $metadata = []) {
129 129
 
130
-		$metadata['__faker'] = true;
130
+        $metadata['__faker'] = true;
131 131
 
132
-		if (empty($attributes['access_id'])) {
133
-			$attributes['access_id'] = ACCESS_PUBLIC;
134
-		}
132
+        if (empty($attributes['access_id'])) {
133
+            $attributes['access_id'] = ACCESS_PUBLIC;
134
+        }
135 135
 
136
-		if (empty($metadata['content_access_mode'])) {
137
-			$metadata['content_access_mode'] = ElggGroup::CONTENT_ACCESS_MODE_UNRESTRICTED;
138
-		}
136
+        if (empty($metadata['content_access_mode'])) {
137
+            $metadata['content_access_mode'] = ElggGroup::CONTENT_ACCESS_MODE_UNRESTRICTED;
138
+        }
139 139
 
140
-		if (empty($metadata['membership'])) {
141
-			$metadata['membership'] = ACCESS_PUBLIC;
142
-		}
140
+        if (empty($metadata['membership'])) {
141
+            $metadata['membership'] = ACCESS_PUBLIC;
142
+        }
143 143
 
144
-		if (empty($attributes['name'])) {
145
-			$attributes['name'] = $this->faker->sentence();
146
-		}
144
+        if (empty($attributes['name'])) {
145
+            $attributes['name'] = $this->faker->sentence();
146
+        }
147 147
 
148
-		if (empty($attributes['description'])) {
149
-			$attributes['description'] = $this->faker->text($this->faker->numberBetween(500, 1000));
150
-		}
148
+        if (empty($attributes['description'])) {
149
+            $attributes['description'] = $this->faker->text($this->faker->numberBetween(500, 1000));
150
+        }
151 151
 
152
-		if (empty($attributes['owner_guid'])) {
153
-			$user = $this->getRandomUser();
154
-			if (!$user) {
155
-				$user = $this->createUser();
156
-			}
152
+        if (empty($attributes['owner_guid'])) {
153
+            $user = $this->getRandomUser();
154
+            if (!$user) {
155
+                $user = $this->createUser();
156
+            }
157 157
 
158
-			$attributes['owner_guid'] = $user->guid;
159
-		}
158
+            $attributes['owner_guid'] = $user->guid;
159
+        }
160 160
 
161
-		if (empty($attributes['container_guid'])) {
162
-			$attributes['container_guid'] = $attributes['owner_guid'];
163
-		}
161
+        if (empty($attributes['container_guid'])) {
162
+            $attributes['container_guid'] = $attributes['owner_guid'];
163
+        }
164 164
 
165
-		$owner = get_entity($attributes['owner_guid']);
166
-		if (!$owner) {
167
-			return false;
168
-		}
165
+        $owner = get_entity($attributes['owner_guid']);
166
+        if (!$owner) {
167
+            return false;
168
+        }
169 169
 
170
-		$container = get_entity($attributes['container_guid']);
171
-		if (!$container) {
172
-			return false;
173
-		}
170
+        $container = get_entity($attributes['container_guid']);
171
+        if (!$container) {
172
+            return false;
173
+        }
174 174
 
175
-		$tool_options = elgg_get_config('group_tool_options');
176
-		if ($tool_options) {
177
-			foreach ($tool_options as $group_option) {
178
-				$option_toggle_name = $group_option->name . "_enable";
179
-				$option_default = $group_option->default_on ? 'yes' : 'no';
180
-				$metadata[$option_toggle_name] = $option_default;
181
-			}
182
-		}
175
+        $tool_options = elgg_get_config('group_tool_options');
176
+        if ($tool_options) {
177
+            foreach ($tool_options as $group_option) {
178
+                $option_toggle_name = $group_option->name . "_enable";
179
+                $option_default = $group_option->default_on ? 'yes' : 'no';
180
+                $metadata[$option_toggle_name] = $option_default;
181
+            }
182
+        }
183 183
 
184
-		if ($this->faker->boolean(20)) {
185
-			$metadata['featured_group'] = 'yes';
186
-		}
184
+        if ($this->faker->boolean(20)) {
185
+            $metadata['featured_group'] = 'yes';
186
+        }
187 187
 
188
-		$group = false;
188
+        $group = false;
189 189
 
190
-		try {
190
+        try {
191 191
 
192
-			$group = new ElggGroup();
193
-			foreach ($attributes as $name => $value) {
194
-				$group->$name = $value;
195
-			}
192
+            $group = new ElggGroup();
193
+            foreach ($attributes as $name => $value) {
194
+                $group->$name = $value;
195
+            }
196 196
 
197
-			$group = $this->populateMetadata($group, elgg_get_config('group'), $metadata);
197
+            $group = $this->populateMetadata($group, elgg_get_config('group'), $metadata);
198 198
 
199
-			$group->save();
199
+            $group->save();
200 200
 
201
-			if ($group->access_id == ACCESS_PRIVATE) {
202
-				$group->access_id = $group->group_acl;
203
-				$group->save();
204
-			}
205
-
206
-			$group->join(get_entity($attributes['owner_guid']));
207
-
208
-			$this->createIcon($group);
209
-
210
-			$this->createComments($group);
211
-			$this->createLikes($group);
212
-
213
-			elgg_create_river_item([
214
-				'view' => 'river/group/create',
215
-				'action_type' => 'create',
216
-				'subject_guid' => $owner->guid,
217
-				'object_guid' => $group->guid,
218
-				'target_guid' => $container->guid,
219
-			]);
220
-
221
-			$this->log("Created new group $group->name [guid: $group->guid]");
222
-
223
-			return $group;
224
-		} catch (Exception $e) {
225
-			if ($group && $group->guid) {
226
-				$group->delete();
227
-			}
228
-
229
-			$this->log($e->getMessage());
230
-
231
-			return false;
232
-		}
233
-
234
-	}
235
-
236
-	/**
237
-	 * Create a new faker object
238
-	 * @return ElggObject|false
239
-	 */
240
-	public function createObject(array $attributes = [], array $metadata = []) {
241
-
242
-		$metadata['__faker'] = true;
243
-
244
-		if (empty($attributes['title'])) {
245
-			$attributes['title'] = $this->faker->sentence();
246
-		}
247
-
248
-		if (empty($attributes['description'])) {
249
-			$attributes['description'] = $this->faker->text($this->faker->numberBetween(500, 1000));
250
-		}
251
-
252
-		if (empty($attributes['container_guid'])) {
253
-			if ($this->faker->boolean()) {
254
-				$container = $this->getRandomGroup();
255
-			} else {
256
-				$container = $this->getRandomUser();
257
-			}
258
-
259
-			$attributes['container_guid'] = $container->guid;
260
-		}
261
-
262
-		if (empty($attributes['subtype'])) {
263
-			$attributes['subtype'] = strtolower($this->faker->word);
264
-		}
265
-
266
-		if (empty($metadata['tags'])) {
267
-			$metadata['tags'] = $this->faker->words(10);
268
-		}
269
-
270
-		if (empty($attributes['owner_guid'])) {
271
-			if ($container instanceof ElggGroup) {
272
-				$members = elgg_get_entities_from_relationship([
273
-					'types' => 'user',
274
-					'relationship' => 'member',
275
-					'relationship_guid' => $container->guid,
276
-					'inverse_relationship' => true,
277
-					'limit' => 0,
278
-					'metadata_names' => '__faker',
279
-					'order_by' => 'RAND()',
280
-				]);
281
-				$owner = array_shift($members);
282
-			} else {
283
-				$owner = $container;
284
-			}
285
-
286
-			$attributes['owner_guid'] = $owner->guid;
287
-		}
288
-
289
-		$owner = get_entity($attributes['owner_guid']);
290
-		if (!$owner) {
291
-			return false;
292
-		}
293
-
294
-		$container = get_entity($attributes['container_guid']);
295
-		if (!$container) {
296
-			return false;
297
-		}
298
-
299
-		if (empty($attributes['access_id'])) {
300
-			$attributes['access_id'] = $this->getRandomAccessId($owner, $container);
301
-		}
302
-
303
-		$object = false;
304
-
305
-		try {
306
-			$class = get_subtype_class('object', $attributes['subtype']);
307
-			if ($class && class_exists($class)) {
308
-				$object = new $class();
309
-			} else {
310
-				$object = new ElggObject();
311
-			}
312
-			foreach ($attributes as $name => $value) {
313
-				$object->$name = $value;
314
-			}
315
-
316
-			$object = $this->populateMetadata($object, [], $metadata);
317
-
318
-			$object->save();
319
-
320
-			$this->createComments($object);
321
-			$this->createLikes($object);
322
-
323
-			$type_str = elgg_echo("item:object:{$object->getSubtype()}");
324
-
325
-			$this->log("Created new item in $type_str $object->title [guid: $object->guid]");
326
-
327
-			return $object;
328
-		} catch (Exception $e) {
329
-			if ($object && $object->guid) {
330
-				$object->delete();
331
-			}
332
-
333
-			$this->log($e->getMessage());
334
-
335
-			return false;
336
-		}
337
-
338
-	}
339
-
340
-	/**
341
-	 * Returns random fake user
342
-	 *
343
-	 * @param int[] $exclude GUIDs to exclude
344
-	 *
345
-	 * @return ElggUser|false
346
-	 */
347
-	public function getRandomUser(array $exclude = []) {
348
-
349
-		$exclude[] = 0;
350
-		$exclude_in = implode(',', array_map(function ($e) {
351
-			return (int) $e;
352
-		}, $exclude));
353
-
354
-		$users = elgg_get_entities_from_metadata([
355
-			'types' => 'user',
356
-			'metadata_names' => ['__faker'],
357
-			'limit' => 1,
358
-			'wheres' => [
359
-				"e.guid NOT IN ($exclude_in)",
360
-			],
361
-			'order_by' => 'RAND()',
362
-		]);
363
-
364
-		return $users ? $users[0] : false;
365
-	}
366
-
367
-	/**
368
-	 * Returns random fake group
369
-	 *
370
-	 * @param int[] $exclude GUIDs to exclude
371
-	 *
372
-	 * @return ElggGroup|false
373
-	 */
374
-	public function getRandomGroup(array $exclude = []) {
375
-
376
-		$exclude[] = 0;
377
-		$exclude_in = implode(',', array_map(function ($e) {
378
-			return (int) $e;
379
-		}, $exclude));
380
-
381
-		$groups = elgg_get_entities_from_metadata([
382
-			'types' => 'group',
383
-			'metadata_names' => ['__faker'],
384
-			'limit' => 1,
385
-			'wheres' => [
386
-				"e.guid NOT IN ($exclude_in)",
387
-			],
388
-			'order_by' => 'RAND()',
389
-		]);
390
-
391
-		return $groups ? $groups[0] : false;
392
-	}
393
-
394
-	/**
395
-	 * Get random access id
396
-	 *
397
-	 * @param ElggUser   $user      User
398
-	 * @param ElggEntity $container Container
399
-	 *
400
-	 * @return int
401
-	 */
402
-	public function getRandomAccessId(\ElggUser $user = null, ElggEntity $container = null) {
403
-
404
-		$params = [
405
-			'container_guid' => $container->guid,
406
-		];
407
-
408
-		$access_array = get_write_access_array($user->guid, null, null, $params);
409
-
410
-		$access_key = array_rand($access_array, 1);
411
-
412
-		return $access_array[$access_key];
413
-	}
414
-
415
-	/**
416
-	 * Generates a unique available and valid username
417
-	 *
418
-	 * @param string $base_name Display name, email or other prefix to use as basis
419
-	 *
420
-	 * @return string
421
-	 */
422
-	public function getRandomUsername($base_name = 'user') {
423
-
424
-		$available = false;
425
-
426
-		$base_name = iconv('UTF-8', 'ASCII//TRANSLIT', $base_name);
427
-		$blacklist = '/[\x{0080}-\x{009f}\x{00a0}\x{2000}-\x{200f}\x{2028}-\x{202f}\x{3000}\x{e000}-\x{f8ff}]/u';
428
-		$blacklist2 = [
429
-			' ',
430
-			'\'',
431
-			'/',
432
-			'\\',
433
-			'"',
434
-			'*',
435
-			'&',
436
-			'?',
437
-			'#',
438
-			'%',
439
-			'^',
440
-			'(',
441
-			')',
442
-			'{',
443
-			'}',
444
-			'[',
445
-			']',
446
-			'~',
447
-			'?',
448
-			'<',
449
-			'>',
450
-			';',
451
-			'|',
452
-			'¬',
453
-			'`',
454
-			'@',
455
-			'-',
456
-			'+',
457
-			'='
458
-		];
459
-
460
-		$base_name = preg_replace($blacklist, '', $base_name);
461
-		$base_name = str_replace($blacklist2, '.', $base_name);
462
-
463
-		$ia = elgg_set_ignore_access(true);
464
-
465
-		$ha = access_get_show_hidden_status();
466
-		access_show_hidden_entities(true);
467
-
468
-		$minlength = elgg_get_config('minusername') ? : 4;
469
-		if ($base_name) {
470
-			$fill = $minlength - strlen($base_name);
471
-		} else {
472
-			$fill = 8;
473
-		}
474
-
475
-		$separator = '.';
476
-
477
-		if ($fill > 0) {
478
-			$suffix = (new ElggCrypto())->getRandomString($fill);
479
-			$base_name = "$base_name$separator$suffix";
480
-		}
481
-
482
-		$iterator = 0;
483
-		while (!$available) {
484
-			if ($iterator > 0) {
485
-				$base_name = "$base_name$separator$iterator";
486
-			}
487
-			$user = get_user_by_username($base_name);
488
-			$available = !$user;
489
-			try {
490
-				if ($available) {
491
-					validate_username($base_name);
492
-				}
493
-			} catch (\Exception $e) {
494
-				if ($iterator >= 10) {
495
-					// too many failed attempts
496
-					$base_name = (new ElggCrypto())->getRandomString(8);
497
-				}
498
-			}
499
-
500
-			$iterator++;
501
-		}
502
-
503
-		access_show_hidden_entities($ha);
504
-		elgg_set_ignore_access($ia);
505
-
506
-		return strtolower($base_name);
507
-	}
508
-
509
-	/**
510
-	 * Set random metadata
511
-	 *
512
-	 * @param ElggEntity $entity   Entity
513
-	 * @param array      $fields   An array of profile fields in $name => $input_type format
514
-	 * @param array      $metadata Other metadata $name => $value pairs to set
515
-	 *
516
-	 * @return ElggEntity
517
-	 */
518
-	public function populateMetadata(ElggEntity $entity, array $fields = [], array $metadata = []) {
519
-
520
-		foreach ($fields as $name => $type) {
521
-			if (isset($metadata[$name])) {
522
-				continue;
523
-			}
524
-
525
-			switch ($name) {
526
-				case 'phone' :
527
-				case 'mobile' :
528
-					$metadata[$name] = $this->faker->phoneNumber;
529
-					break;
530
-
531
-				default :
532
-					switch ($type) {
533
-						case 'plaintext' :
534
-						case 'longtext' :
535
-							$metadata[$name] = $this->faker->text($this->faker->numberBetween(500, 1000));
536
-							break;
537
-
538
-						case 'text' :
539
-							$metadata[$name] = $this->faker->sentence;
540
-							break;
541
-
542
-						case 'tags' :
543
-							$metadata[$name] = $this->faker->words(10);
544
-							break;
545
-
546
-						case 'url' :
547
-							$metadata[$name] = $this->faker->url;
548
-
549
-						case 'email' :
550
-							$metadata[$name] = $this->faker->email;
551
-							break;
552
-
553
-						case 'number' :
554
-							$metadata[$name] = $this->faker->randomNumber();
555
-							break;
556
-
557
-						case 'date' :
558
-							$metadata[$name] = $this->faker->unixTime;
559
-							break;
560
-
561
-						case 'password' :
562
-							$metadata[$name] = generate_random_cleartext_password();
563
-							break;
564
-
565
-						case 'location' :
566
-							$metadata[$name] = $this->faker->address;
567
-							$metadata['geo:lat'] = $this->faker->latitude;
568
-							$metadata['geo:long'] = $this->faker->longitude;
569
-							break;
570
-
571
-						case 'email' :
572
-							$metadata[$name] = $this->faker->address;
573
-							$metadata['geo:lat'] = $this->faker->latitude;
574
-							$metadata['geo:long'] = $this->faker->longitude;
575
-							break;
576
-
577
-						default :
578
-							$metadata[$name] = '';
579
-							break;
580
-					}
581
-
582
-					break;
583
-			}
584
-		}
585
-
586
-		foreach ($metadata as $key => $value) {
587
-			$entity->$key = $value;
588
-		}
589
-
590
-		return $entity;
591
-	}
592
-
593
-	/**
594
-	 * Create an icon for an entity
595
-	 *
596
-	 * @param ElggEntity $entity Entity
597
-	 *
598
-	 * @return bool
599
-	 */
600
-	public function createIcon(ElggEntity $entity) {
601
-
602
-		$icon_url = $this->faker->imageURL();
603
-
604
-		$file_contents = file_get_contents($icon_url);
605
-
606
-		$tmp = new \ElggFile();
607
-		$tmp->owner_guid = $entity->guid;
608
-		$tmp->setFilename("tmp/icon_src.jpg");
609
-		$tmp->open('write');
610
-		$tmp->write($file_contents);
611
-		$tmp->close();
612
-
613
-		$result = $entity->saveIconFromElggFile($tmp);
614
-
615
-		$tmp->delete();
616
-
617
-		if ($result && $entity instanceof ElggUser) {
618
-			elgg_create_river_item([
619
-				'view' => 'river/user/default/profileiconupdate',
620
-				'action_type' => 'update',
621
-				'subject_guid' => $entity->guid,
622
-				'object_guid' => $entity->guid,
623
-			]);
624
-		}
625
-
626
-		return $result;
627
-	}
628
-
629
-	/**
630
-	 * Create comments/replies
631
-	 *
632
-	 * @param ElggEntity $entity Entity to comment on
633
-	 * @param int        $limit  Number of comments to create
634
-	 *
635
-	 * @return int Number of generated comments
636
-	 */
637
-	public function createComments(ElggEntity $entity, $limit = null) {
638
-
639
-		$success = 0;
640
-
641
-		if (!$limit) {
642
-			$limit = $this->faker->numberBetween(1, 20);
643
-		}
644
-
645
-		while ($success < $limit) {
646
-
647
-			$comment = new ElggObject();
648
-			$comment->subtype = $entity->getSubtype() == 'discussion' ? 'discussion_reply' : 'comment';
649
-			$comment->owner_guid = $this->getRandomUser()->guid ? : $entity->owner_guid;
650
-			$comment->container_guid = $entity->guid;
651
-			$comment->description = $this->faker->paragraph;
652
-
653
-			if ($comment->save()) {
654
-				$success++;
655
-			}
656
-		}
657
-
658
-		return $success;
659
-
660
-	}
661
-
662
-	/**
663
-	 * Create likes
664
-	 *
665
-	 * @param ElggEntity $entity Entity to like
666
-	 * @param int        $limit  Number of likes to create
667
-	 *
668
-	 * @return int
669
-	 */
670
-	public function createLikes(ElggEntity $entity, $limit = null) {
671
-
672
-		$success = 0;
673
-
674
-		if (!$limit) {
675
-			$limit = $this->faker->numberBetween(1, 20);
676
-		}
677
-
678
-		while ($success < $limit) {
679
-			if ($entity->annotate('likes', true, $entity->access_id, $this->getRandomUser()->guid)) {
680
-				$success++;
681
-			}
682
-		}
683
-
684
-		return $success;
685
-	}
686
-
687
-	/**
688
-	 * Log a message
689
-	 *
690
-	 * @param string $msg Message to log
691
-	 *
692
-	 * @return void
693
-	 */
694
-	public function log($msg, $level = 'NOTICE') {
695
-
696
-		if (php_sapi_name() === 'cli') {
697
-			$handle = $level === 'ERROR' ? STDERR : STDOUT;
698
-			fwrite($handle, $msg . PHP_EOL);
699
-		} else {
700
-			elgg_log($msg, $level);
701
-		}
702
-	}
201
+            if ($group->access_id == ACCESS_PRIVATE) {
202
+                $group->access_id = $group->group_acl;
203
+                $group->save();
204
+            }
205
+
206
+            $group->join(get_entity($attributes['owner_guid']));
207
+
208
+            $this->createIcon($group);
209
+
210
+            $this->createComments($group);
211
+            $this->createLikes($group);
212
+
213
+            elgg_create_river_item([
214
+                'view' => 'river/group/create',
215
+                'action_type' => 'create',
216
+                'subject_guid' => $owner->guid,
217
+                'object_guid' => $group->guid,
218
+                'target_guid' => $container->guid,
219
+            ]);
220
+
221
+            $this->log("Created new group $group->name [guid: $group->guid]");
222
+
223
+            return $group;
224
+        } catch (Exception $e) {
225
+            if ($group && $group->guid) {
226
+                $group->delete();
227
+            }
228
+
229
+            $this->log($e->getMessage());
230
+
231
+            return false;
232
+        }
233
+
234
+    }
235
+
236
+    /**
237
+     * Create a new faker object
238
+     * @return ElggObject|false
239
+     */
240
+    public function createObject(array $attributes = [], array $metadata = []) {
241
+
242
+        $metadata['__faker'] = true;
243
+
244
+        if (empty($attributes['title'])) {
245
+            $attributes['title'] = $this->faker->sentence();
246
+        }
247
+
248
+        if (empty($attributes['description'])) {
249
+            $attributes['description'] = $this->faker->text($this->faker->numberBetween(500, 1000));
250
+        }
251
+
252
+        if (empty($attributes['container_guid'])) {
253
+            if ($this->faker->boolean()) {
254
+                $container = $this->getRandomGroup();
255
+            } else {
256
+                $container = $this->getRandomUser();
257
+            }
258
+
259
+            $attributes['container_guid'] = $container->guid;
260
+        }
261
+
262
+        if (empty($attributes['subtype'])) {
263
+            $attributes['subtype'] = strtolower($this->faker->word);
264
+        }
265
+
266
+        if (empty($metadata['tags'])) {
267
+            $metadata['tags'] = $this->faker->words(10);
268
+        }
269
+
270
+        if (empty($attributes['owner_guid'])) {
271
+            if ($container instanceof ElggGroup) {
272
+                $members = elgg_get_entities_from_relationship([
273
+                    'types' => 'user',
274
+                    'relationship' => 'member',
275
+                    'relationship_guid' => $container->guid,
276
+                    'inverse_relationship' => true,
277
+                    'limit' => 0,
278
+                    'metadata_names' => '__faker',
279
+                    'order_by' => 'RAND()',
280
+                ]);
281
+                $owner = array_shift($members);
282
+            } else {
283
+                $owner = $container;
284
+            }
285
+
286
+            $attributes['owner_guid'] = $owner->guid;
287
+        }
288
+
289
+        $owner = get_entity($attributes['owner_guid']);
290
+        if (!$owner) {
291
+            return false;
292
+        }
293
+
294
+        $container = get_entity($attributes['container_guid']);
295
+        if (!$container) {
296
+            return false;
297
+        }
298
+
299
+        if (empty($attributes['access_id'])) {
300
+            $attributes['access_id'] = $this->getRandomAccessId($owner, $container);
301
+        }
302
+
303
+        $object = false;
304
+
305
+        try {
306
+            $class = get_subtype_class('object', $attributes['subtype']);
307
+            if ($class && class_exists($class)) {
308
+                $object = new $class();
309
+            } else {
310
+                $object = new ElggObject();
311
+            }
312
+            foreach ($attributes as $name => $value) {
313
+                $object->$name = $value;
314
+            }
315
+
316
+            $object = $this->populateMetadata($object, [], $metadata);
317
+
318
+            $object->save();
319
+
320
+            $this->createComments($object);
321
+            $this->createLikes($object);
322
+
323
+            $type_str = elgg_echo("item:object:{$object->getSubtype()}");
324
+
325
+            $this->log("Created new item in $type_str $object->title [guid: $object->guid]");
326
+
327
+            return $object;
328
+        } catch (Exception $e) {
329
+            if ($object && $object->guid) {
330
+                $object->delete();
331
+            }
332
+
333
+            $this->log($e->getMessage());
334
+
335
+            return false;
336
+        }
337
+
338
+    }
339
+
340
+    /**
341
+     * Returns random fake user
342
+     *
343
+     * @param int[] $exclude GUIDs to exclude
344
+     *
345
+     * @return ElggUser|false
346
+     */
347
+    public function getRandomUser(array $exclude = []) {
348
+
349
+        $exclude[] = 0;
350
+        $exclude_in = implode(',', array_map(function ($e) {
351
+            return (int) $e;
352
+        }, $exclude));
353
+
354
+        $users = elgg_get_entities_from_metadata([
355
+            'types' => 'user',
356
+            'metadata_names' => ['__faker'],
357
+            'limit' => 1,
358
+            'wheres' => [
359
+                "e.guid NOT IN ($exclude_in)",
360
+            ],
361
+            'order_by' => 'RAND()',
362
+        ]);
363
+
364
+        return $users ? $users[0] : false;
365
+    }
366
+
367
+    /**
368
+     * Returns random fake group
369
+     *
370
+     * @param int[] $exclude GUIDs to exclude
371
+     *
372
+     * @return ElggGroup|false
373
+     */
374
+    public function getRandomGroup(array $exclude = []) {
375
+
376
+        $exclude[] = 0;
377
+        $exclude_in = implode(',', array_map(function ($e) {
378
+            return (int) $e;
379
+        }, $exclude));
380
+
381
+        $groups = elgg_get_entities_from_metadata([
382
+            'types' => 'group',
383
+            'metadata_names' => ['__faker'],
384
+            'limit' => 1,
385
+            'wheres' => [
386
+                "e.guid NOT IN ($exclude_in)",
387
+            ],
388
+            'order_by' => 'RAND()',
389
+        ]);
390
+
391
+        return $groups ? $groups[0] : false;
392
+    }
393
+
394
+    /**
395
+     * Get random access id
396
+     *
397
+     * @param ElggUser   $user      User
398
+     * @param ElggEntity $container Container
399
+     *
400
+     * @return int
401
+     */
402
+    public function getRandomAccessId(\ElggUser $user = null, ElggEntity $container = null) {
403
+
404
+        $params = [
405
+            'container_guid' => $container->guid,
406
+        ];
407
+
408
+        $access_array = get_write_access_array($user->guid, null, null, $params);
409
+
410
+        $access_key = array_rand($access_array, 1);
411
+
412
+        return $access_array[$access_key];
413
+    }
414
+
415
+    /**
416
+     * Generates a unique available and valid username
417
+     *
418
+     * @param string $base_name Display name, email or other prefix to use as basis
419
+     *
420
+     * @return string
421
+     */
422
+    public function getRandomUsername($base_name = 'user') {
423
+
424
+        $available = false;
425
+
426
+        $base_name = iconv('UTF-8', 'ASCII//TRANSLIT', $base_name);
427
+        $blacklist = '/[\x{0080}-\x{009f}\x{00a0}\x{2000}-\x{200f}\x{2028}-\x{202f}\x{3000}\x{e000}-\x{f8ff}]/u';
428
+        $blacklist2 = [
429
+            ' ',
430
+            '\'',
431
+            '/',
432
+            '\\',
433
+            '"',
434
+            '*',
435
+            '&',
436
+            '?',
437
+            '#',
438
+            '%',
439
+            '^',
440
+            '(',
441
+            ')',
442
+            '{',
443
+            '}',
444
+            '[',
445
+            ']',
446
+            '~',
447
+            '?',
448
+            '<',
449
+            '>',
450
+            ';',
451
+            '|',
452
+            '¬',
453
+            '`',
454
+            '@',
455
+            '-',
456
+            '+',
457
+            '='
458
+        ];
459
+
460
+        $base_name = preg_replace($blacklist, '', $base_name);
461
+        $base_name = str_replace($blacklist2, '.', $base_name);
462
+
463
+        $ia = elgg_set_ignore_access(true);
464
+
465
+        $ha = access_get_show_hidden_status();
466
+        access_show_hidden_entities(true);
467
+
468
+        $minlength = elgg_get_config('minusername') ? : 4;
469
+        if ($base_name) {
470
+            $fill = $minlength - strlen($base_name);
471
+        } else {
472
+            $fill = 8;
473
+        }
474
+
475
+        $separator = '.';
476
+
477
+        if ($fill > 0) {
478
+            $suffix = (new ElggCrypto())->getRandomString($fill);
479
+            $base_name = "$base_name$separator$suffix";
480
+        }
481
+
482
+        $iterator = 0;
483
+        while (!$available) {
484
+            if ($iterator > 0) {
485
+                $base_name = "$base_name$separator$iterator";
486
+            }
487
+            $user = get_user_by_username($base_name);
488
+            $available = !$user;
489
+            try {
490
+                if ($available) {
491
+                    validate_username($base_name);
492
+                }
493
+            } catch (\Exception $e) {
494
+                if ($iterator >= 10) {
495
+                    // too many failed attempts
496
+                    $base_name = (new ElggCrypto())->getRandomString(8);
497
+                }
498
+            }
499
+
500
+            $iterator++;
501
+        }
502
+
503
+        access_show_hidden_entities($ha);
504
+        elgg_set_ignore_access($ia);
505
+
506
+        return strtolower($base_name);
507
+    }
508
+
509
+    /**
510
+     * Set random metadata
511
+     *
512
+     * @param ElggEntity $entity   Entity
513
+     * @param array      $fields   An array of profile fields in $name => $input_type format
514
+     * @param array      $metadata Other metadata $name => $value pairs to set
515
+     *
516
+     * @return ElggEntity
517
+     */
518
+    public function populateMetadata(ElggEntity $entity, array $fields = [], array $metadata = []) {
519
+
520
+        foreach ($fields as $name => $type) {
521
+            if (isset($metadata[$name])) {
522
+                continue;
523
+            }
524
+
525
+            switch ($name) {
526
+                case 'phone' :
527
+                case 'mobile' :
528
+                    $metadata[$name] = $this->faker->phoneNumber;
529
+                    break;
530
+
531
+                default :
532
+                    switch ($type) {
533
+                        case 'plaintext' :
534
+                        case 'longtext' :
535
+                            $metadata[$name] = $this->faker->text($this->faker->numberBetween(500, 1000));
536
+                            break;
537
+
538
+                        case 'text' :
539
+                            $metadata[$name] = $this->faker->sentence;
540
+                            break;
541
+
542
+                        case 'tags' :
543
+                            $metadata[$name] = $this->faker->words(10);
544
+                            break;
545
+
546
+                        case 'url' :
547
+                            $metadata[$name] = $this->faker->url;
548
+
549
+                        case 'email' :
550
+                            $metadata[$name] = $this->faker->email;
551
+                            break;
552
+
553
+                        case 'number' :
554
+                            $metadata[$name] = $this->faker->randomNumber();
555
+                            break;
556
+
557
+                        case 'date' :
558
+                            $metadata[$name] = $this->faker->unixTime;
559
+                            break;
560
+
561
+                        case 'password' :
562
+                            $metadata[$name] = generate_random_cleartext_password();
563
+                            break;
564
+
565
+                        case 'location' :
566
+                            $metadata[$name] = $this->faker->address;
567
+                            $metadata['geo:lat'] = $this->faker->latitude;
568
+                            $metadata['geo:long'] = $this->faker->longitude;
569
+                            break;
570
+
571
+                        case 'email' :
572
+                            $metadata[$name] = $this->faker->address;
573
+                            $metadata['geo:lat'] = $this->faker->latitude;
574
+                            $metadata['geo:long'] = $this->faker->longitude;
575
+                            break;
576
+
577
+                        default :
578
+                            $metadata[$name] = '';
579
+                            break;
580
+                    }
581
+
582
+                    break;
583
+            }
584
+        }
585
+
586
+        foreach ($metadata as $key => $value) {
587
+            $entity->$key = $value;
588
+        }
589
+
590
+        return $entity;
591
+    }
592
+
593
+    /**
594
+     * Create an icon for an entity
595
+     *
596
+     * @param ElggEntity $entity Entity
597
+     *
598
+     * @return bool
599
+     */
600
+    public function createIcon(ElggEntity $entity) {
601
+
602
+        $icon_url = $this->faker->imageURL();
603
+
604
+        $file_contents = file_get_contents($icon_url);
605
+
606
+        $tmp = new \ElggFile();
607
+        $tmp->owner_guid = $entity->guid;
608
+        $tmp->setFilename("tmp/icon_src.jpg");
609
+        $tmp->open('write');
610
+        $tmp->write($file_contents);
611
+        $tmp->close();
612
+
613
+        $result = $entity->saveIconFromElggFile($tmp);
614
+
615
+        $tmp->delete();
616
+
617
+        if ($result && $entity instanceof ElggUser) {
618
+            elgg_create_river_item([
619
+                'view' => 'river/user/default/profileiconupdate',
620
+                'action_type' => 'update',
621
+                'subject_guid' => $entity->guid,
622
+                'object_guid' => $entity->guid,
623
+            ]);
624
+        }
625
+
626
+        return $result;
627
+    }
628
+
629
+    /**
630
+     * Create comments/replies
631
+     *
632
+     * @param ElggEntity $entity Entity to comment on
633
+     * @param int        $limit  Number of comments to create
634
+     *
635
+     * @return int Number of generated comments
636
+     */
637
+    public function createComments(ElggEntity $entity, $limit = null) {
638
+
639
+        $success = 0;
640
+
641
+        if (!$limit) {
642
+            $limit = $this->faker->numberBetween(1, 20);
643
+        }
644
+
645
+        while ($success < $limit) {
646
+
647
+            $comment = new ElggObject();
648
+            $comment->subtype = $entity->getSubtype() == 'discussion' ? 'discussion_reply' : 'comment';
649
+            $comment->owner_guid = $this->getRandomUser()->guid ? : $entity->owner_guid;
650
+            $comment->container_guid = $entity->guid;
651
+            $comment->description = $this->faker->paragraph;
652
+
653
+            if ($comment->save()) {
654
+                $success++;
655
+            }
656
+        }
657
+
658
+        return $success;
659
+
660
+    }
661
+
662
+    /**
663
+     * Create likes
664
+     *
665
+     * @param ElggEntity $entity Entity to like
666
+     * @param int        $limit  Number of likes to create
667
+     *
668
+     * @return int
669
+     */
670
+    public function createLikes(ElggEntity $entity, $limit = null) {
671
+
672
+        $success = 0;
673
+
674
+        if (!$limit) {
675
+            $limit = $this->faker->numberBetween(1, 20);
676
+        }
677
+
678
+        while ($success < $limit) {
679
+            if ($entity->annotate('likes', true, $entity->access_id, $this->getRandomUser()->guid)) {
680
+                $success++;
681
+            }
682
+        }
683
+
684
+        return $success;
685
+    }
686
+
687
+    /**
688
+     * Log a message
689
+     *
690
+     * @param string $msg Message to log
691
+     *
692
+     * @return void
693
+     */
694
+    public function log($msg, $level = 'NOTICE') {
695
+
696
+        if (php_sapi_name() === 'cli') {
697
+            $handle = $level === 'ERROR' ? STDERR : STDOUT;
698
+            fwrite($handle, $msg . PHP_EOL);
699
+        } else {
700
+            elgg_log($msg, $level);
701
+        }
702
+    }
703 703
 }
704 704
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
 		$tool_options = elgg_get_config('group_tool_options');
176 176
 		if ($tool_options) {
177 177
 			foreach ($tool_options as $group_option) {
178
-				$option_toggle_name = $group_option->name . "_enable";
178
+				$option_toggle_name = $group_option->name."_enable";
179 179
 				$option_default = $group_option->default_on ? 'yes' : 'no';
180 180
 				$metadata[$option_toggle_name] = $option_default;
181 181
 			}
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
 	public function getRandomUser(array $exclude = []) {
348 348
 
349 349
 		$exclude[] = 0;
350
-		$exclude_in = implode(',', array_map(function ($e) {
350
+		$exclude_in = implode(',', array_map(function($e) {
351 351
 			return (int) $e;
352 352
 		}, $exclude));
353 353
 
@@ -374,7 +374,7 @@  discard block
 block discarded – undo
374 374
 	public function getRandomGroup(array $exclude = []) {
375 375
 
376 376
 		$exclude[] = 0;
377
-		$exclude_in = implode(',', array_map(function ($e) {
377
+		$exclude_in = implode(',', array_map(function($e) {
378 378
 			return (int) $e;
379 379
 		}, $exclude));
380 380
 
@@ -465,7 +465,7 @@  discard block
 block discarded – undo
465 465
 		$ha = access_get_show_hidden_status();
466 466
 		access_show_hidden_entities(true);
467 467
 
468
-		$minlength = elgg_get_config('minusername') ? : 4;
468
+		$minlength = elgg_get_config('minusername') ?: 4;
469 469
 		if ($base_name) {
470 470
 			$fill = $minlength - strlen($base_name);
471 471
 		} else {
@@ -646,7 +646,7 @@  discard block
 block discarded – undo
646 646
 
647 647
 			$comment = new ElggObject();
648 648
 			$comment->subtype = $entity->getSubtype() == 'discussion' ? 'discussion_reply' : 'comment';
649
-			$comment->owner_guid = $this->getRandomUser()->guid ? : $entity->owner_guid;
649
+			$comment->owner_guid = $this->getRandomUser()->guid ?: $entity->owner_guid;
650 650
 			$comment->container_guid = $entity->guid;
651 651
 			$comment->description = $this->faker->paragraph;
652 652
 
@@ -695,7 +695,7 @@  discard block
 block discarded – undo
695 695
 
696 696
 		if (php_sapi_name() === 'cli') {
697 697
 			$handle = $level === 'ERROR' ? STDERR : STDOUT;
698
-			fwrite($handle, $msg . PHP_EOL);
698
+			fwrite($handle, $msg.PHP_EOL);
699 699
 		} else {
700 700
 			elgg_log($msg, $level);
701 701
 		}
Please login to merge, or discard this patch.
engine/lib/notification.php 2 patches
Indentation   +336 added lines, -336 removed lines patch added patch discarded remove patch
@@ -63,7 +63,7 @@  discard block
 block discarded – undo
63 63
  * @since 1.9
64 64
  */
65 65
 function elgg_register_notification_event($object_type, $object_subtype, array $actions = array()) {
66
-	_elgg_services()->notifications->registerEvent($object_type, $object_subtype, $actions);
66
+    _elgg_services()->notifications->registerEvent($object_type, $object_subtype, $actions);
67 67
 }
68 68
 
69 69
 /**
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
  * @since 1.9
76 76
  */
77 77
 function elgg_unregister_notification_event($object_type, $object_subtype) {
78
-	return _elgg_services()->notifications->unregisterEvent($object_type, $object_subtype);
78
+    return _elgg_services()->notifications->unregisterEvent($object_type, $object_subtype);
79 79
 }
80 80
 
81 81
 /**
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
  * @since 1.9
92 92
  */
93 93
 function elgg_register_notification_method($name) {
94
-	_elgg_services()->notifications->registerMethod($name);
94
+    _elgg_services()->notifications->registerMethod($name);
95 95
 }
96 96
 
97 97
 /**
@@ -107,7 +107,7 @@  discard block
 block discarded – undo
107 107
  * @since 2.3
108 108
  */
109 109
 function elgg_get_notification_methods() {
110
-	return _elgg_services()->notifications->getMethods();
110
+    return _elgg_services()->notifications->getMethods();
111 111
 }
112 112
 
113 113
 /**
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
  * @since 1.9
120 120
  */
121 121
 function elgg_unregister_notification_method($name) {
122
-	return _elgg_services()->notifications->unregisterMethod($name);
122
+    return _elgg_services()->notifications->unregisterMethod($name);
123 123
 }
124 124
 
125 125
 /**
@@ -132,10 +132,10 @@  discard block
 block discarded – undo
132 132
  * @since 1.9
133 133
  */
134 134
 function elgg_add_subscription($user_guid, $method, $target_guid) {
135
-	$methods = _elgg_services()->notifications->getMethods();
136
-	$db = _elgg_services()->db;
137
-	$subs = new \Elgg\Notifications\SubscriptionsService($db, $methods);
138
-	return $subs->addSubscription($user_guid, $method, $target_guid);
135
+    $methods = _elgg_services()->notifications->getMethods();
136
+    $db = _elgg_services()->db;
137
+    $subs = new \Elgg\Notifications\SubscriptionsService($db, $methods);
138
+    return $subs->addSubscription($user_guid, $method, $target_guid);
139 139
 }
140 140
 
141 141
 /**
@@ -148,10 +148,10 @@  discard block
 block discarded – undo
148 148
  * @since 1.9
149 149
  */
150 150
 function elgg_remove_subscription($user_guid, $method, $target_guid) {
151
-	$methods = _elgg_services()->notifications->getMethods();
152
-	$db = _elgg_services()->db;
153
-	$subs = new \Elgg\Notifications\SubscriptionsService($db, $methods);
154
-	return $subs->removeSubscription($user_guid, $method, $target_guid);
151
+    $methods = _elgg_services()->notifications->getMethods();
152
+    $db = _elgg_services()->db;
153
+    $subs = new \Elgg\Notifications\SubscriptionsService($db, $methods);
154
+    return $subs->removeSubscription($user_guid, $method, $target_guid);
155 155
 }
156 156
 
157 157
 /**
@@ -169,10 +169,10 @@  discard block
 block discarded – undo
169 169
  * @todo deprecate once new subscriptions system has been added
170 170
  */
171 171
 function elgg_get_subscriptions_for_container($container_guid) {
172
-	$methods = _elgg_services()->notifications->getMethods();
173
-	$db = _elgg_services()->db;
174
-	$subs = new \Elgg\Notifications\SubscriptionsService($db, $methods);
175
-	return $subs->getSubscriptionsForContainer($container_guid);
172
+    $methods = _elgg_services()->notifications->getMethods();
173
+    $db = _elgg_services()->db;
174
+    $subs = new \Elgg\Notifications\SubscriptionsService($db, $methods);
175
+    return $subs->getSubscriptionsForContainer($container_guid);
176 176
 }
177 177
 
178 178
 /**
@@ -191,17 +191,17 @@  discard block
 block discarded – undo
191 191
  * @since 1.9
192 192
  */
193 193
 function _elgg_enqueue_notification_event($action, $type, $object) {
194
-	_elgg_services()->notifications->enqueueEvent($action, $type, $object);
194
+    _elgg_services()->notifications->enqueueEvent($action, $type, $object);
195 195
 }
196 196
 
197 197
 /**
198 198
  * @access private
199 199
  */
200 200
 function _elgg_notifications_cron() {
201
-	// calculate when we should stop
202
-	// @todo make configurable?
203
-	$stop_time = time() + 45;
204
-	_elgg_services()->notifications->processQueue($stop_time);
201
+    // calculate when we should stop
202
+    // @todo make configurable?
203
+    $stop_time = time() + 45;
204
+    _elgg_services()->notifications->processQueue($stop_time);
205 205
 }
206 206
 
207 207
 /**
@@ -216,39 +216,39 @@  discard block
 block discarded – undo
216 216
  */
217 217
 function _elgg_send_email_notification($hook, $type, $result, $params) {
218 218
 	
219
-	if ($result === true) {
220
-		// assume someone else already sent the message
221
-		return;
222
-	}
219
+    if ($result === true) {
220
+        // assume someone else already sent the message
221
+        return;
222
+    }
223 223
 	
224
-	/* @var \Elgg\Notifications\Notification $message */
225
-	$message = $params['notification'];
226
-
227
-	$sender = $message->getSender();
228
-	$recipient = $message->getRecipient();
229
-
230
-	if (!$sender) {
231
-		return false;
232
-	}
233
-
234
-	if (!$recipient || !$recipient->email) {
235
-		return false;
236
-	}
237
-
238
-	$to = $recipient->email;
239
-
240
-	$site = elgg_get_site_entity();
241
-	// If there's an email address, use it - but only if it's not from a user.
242
-	if (!($sender instanceof \ElggUser) && $sender->email) {
243
-		$from = $sender->email;
244
-	} else if ($site->email) {
245
-		$from = $site->email;
246
-	} else {
247
-		// If all else fails, use the domain of the site.
248
-		$from = 'noreply@' . $site->getDomain();
249
-	}
250
-
251
-	return elgg_send_email($from, $to, $message->subject, $message->body, $params);
224
+    /* @var \Elgg\Notifications\Notification $message */
225
+    $message = $params['notification'];
226
+
227
+    $sender = $message->getSender();
228
+    $recipient = $message->getRecipient();
229
+
230
+    if (!$sender) {
231
+        return false;
232
+    }
233
+
234
+    if (!$recipient || !$recipient->email) {
235
+        return false;
236
+    }
237
+
238
+    $to = $recipient->email;
239
+
240
+    $site = elgg_get_site_entity();
241
+    // If there's an email address, use it - but only if it's not from a user.
242
+    if (!($sender instanceof \ElggUser) && $sender->email) {
243
+        $from = $sender->email;
244
+    } else if ($site->email) {
245
+        $from = $site->email;
246
+    } else {
247
+        // If all else fails, use the domain of the site.
248
+        $from = 'noreply@' . $site->getDomain();
249
+    }
250
+
251
+    return elgg_send_email($from, $to, $message->subject, $message->body, $params);
252 252
 }
253 253
 
254 254
 /**
@@ -267,19 +267,19 @@  discard block
 block discarded – undo
267 267
  */
268 268
 function _elgg_notifications_smtp_default_message_id_header($hook, $type, $returnvalue, $params) {
269 269
 	
270
-	if (!is_array($returnvalue) || !is_array($returnvalue['params'])) {
271
-		// another hook handler returned a non-array, let's not override it
272
-		return;
273
-	}
270
+    if (!is_array($returnvalue) || !is_array($returnvalue['params'])) {
271
+        // another hook handler returned a non-array, let's not override it
272
+        return;
273
+    }
274 274
 	
275
-	$hostname = parse_url(elgg_get_site_url(), PHP_URL_HOST);
276
-	$url_path = parse_url(elgg_get_site_url(), PHP_URL_PATH);
275
+    $hostname = parse_url(elgg_get_site_url(), PHP_URL_HOST);
276
+    $url_path = parse_url(elgg_get_site_url(), PHP_URL_PATH);
277 277
 	
278
-	$mt = microtime(true);
278
+    $mt = microtime(true);
279 279
 	
280
-	$returnvalue['headers']['Message-ID'] = "{$url_path}.default.{$mt}@{$hostname}";
280
+    $returnvalue['headers']['Message-ID'] = "{$url_path}.default.{$mt}@{$hostname}";
281 281
 	
282
-	return $returnvalue;
282
+    return $returnvalue;
283 283
 }
284 284
 /**
285 285
  * Adds default thread SMTP headers to group messages correctly.
@@ -294,66 +294,66 @@  discard block
 block discarded – undo
294 294
  */
295 295
 function _elgg_notifications_smtp_thread_headers($hook, $type, $returnvalue, $params) {
296 296
 
297
-	if (!is_array($returnvalue) || !is_array($returnvalue['params'])) {
298
-		// another hook handler returned a non-array, let's not override it
299
-		return;
300
-	}
301
-
302
-	$notificationParams = elgg_extract('params', $returnvalue, array());
303
-	/** @var \Elgg\Notifications\Notification */
304
-	$notification = elgg_extract('notification', $notificationParams);
305
-
306
-	if (!($notification instanceof \Elgg\Notifications\Notification)) {
307
-		return $returnvalue;
308
-	}
309
-
310
-	$hostname = parse_url(elgg_get_site_url(), PHP_URL_HOST);
311
-	$urlPath = parse_url(elgg_get_site_url(), PHP_URL_PATH);
312
-
313
-	$object = elgg_extract('object', $notification->params);
314
-	/** @var \Elgg\Notifications\Event $event */
315
-	$event = elgg_extract('event', $notification->params);
316
-
317
-	if (($object instanceof \ElggEntity) && ($event instanceof \Elgg\Notifications\NotificationEvent)) {
318
-		if ($event->getAction() === 'create') {
319
-			// create event happens once per entity and we need to guarantee message id uniqueness
320
-			// and at the same time have thread message id that we don't need to store
321
-			$messageId = "{$urlPath}.entity.{$object->guid}@{$hostname}";
322
-		} else {
323
-			$mt = microtime(true);
324
-			$messageId = "{$urlPath}.entity.{$object->guid}.$mt@{$hostname}";
325
-		}
326
-		$returnvalue['headers']["Message-ID"] = $messageId;
327
-		$container = $object->getContainerEntity();
328
-
329
-		// let's just thread comments by default
330
-		if (($container instanceof \ElggEntity) && ($object instanceof \ElggComment)) {
331
-
332
-			$threadMessageId = "<{$urlPath}.entity.{$container->guid}@{$hostname}>";
333
-			$returnvalue['headers']['In-Reply-To'] = $threadMessageId;
334
-			$returnvalue['headers']['References'] = $threadMessageId;
335
-		}
336
-	}
337
-
338
-	return $returnvalue;
297
+    if (!is_array($returnvalue) || !is_array($returnvalue['params'])) {
298
+        // another hook handler returned a non-array, let's not override it
299
+        return;
300
+    }
301
+
302
+    $notificationParams = elgg_extract('params', $returnvalue, array());
303
+    /** @var \Elgg\Notifications\Notification */
304
+    $notification = elgg_extract('notification', $notificationParams);
305
+
306
+    if (!($notification instanceof \Elgg\Notifications\Notification)) {
307
+        return $returnvalue;
308
+    }
309
+
310
+    $hostname = parse_url(elgg_get_site_url(), PHP_URL_HOST);
311
+    $urlPath = parse_url(elgg_get_site_url(), PHP_URL_PATH);
312
+
313
+    $object = elgg_extract('object', $notification->params);
314
+    /** @var \Elgg\Notifications\Event $event */
315
+    $event = elgg_extract('event', $notification->params);
316
+
317
+    if (($object instanceof \ElggEntity) && ($event instanceof \Elgg\Notifications\NotificationEvent)) {
318
+        if ($event->getAction() === 'create') {
319
+            // create event happens once per entity and we need to guarantee message id uniqueness
320
+            // and at the same time have thread message id that we don't need to store
321
+            $messageId = "{$urlPath}.entity.{$object->guid}@{$hostname}";
322
+        } else {
323
+            $mt = microtime(true);
324
+            $messageId = "{$urlPath}.entity.{$object->guid}.$mt@{$hostname}";
325
+        }
326
+        $returnvalue['headers']["Message-ID"] = $messageId;
327
+        $container = $object->getContainerEntity();
328
+
329
+        // let's just thread comments by default
330
+        if (($container instanceof \ElggEntity) && ($object instanceof \ElggComment)) {
331
+
332
+            $threadMessageId = "<{$urlPath}.entity.{$container->guid}@{$hostname}>";
333
+            $returnvalue['headers']['In-Reply-To'] = $threadMessageId;
334
+            $returnvalue['headers']['References'] = $threadMessageId;
335
+        }
336
+    }
337
+
338
+    return $returnvalue;
339 339
 }
340 340
 
341 341
 /**
342 342
  * @access private
343 343
  */
344 344
 function _elgg_notifications_init() {
345
-	elgg_register_plugin_hook_handler('cron', 'minute', '_elgg_notifications_cron', 100);
346
-	elgg_register_event_handler('all', 'all', '_elgg_enqueue_notification_event', 700);
347
-
348
-	// add email notifications
349
-	elgg_register_notification_method('email');
350
-	elgg_register_plugin_hook_handler('send', 'notification:email', '_elgg_send_email_notification');
351
-	elgg_register_plugin_hook_handler('email', 'system', '_elgg_notifications_smtp_default_message_id_header', 1);
352
-	elgg_register_plugin_hook_handler('email', 'system', '_elgg_notifications_smtp_thread_headers');
353
-
354
-	// add ability to set personal notification method
355
-	elgg_extend_view('forms/account/settings', 'core/settings/account/notifications');
356
-	elgg_register_plugin_hook_handler('usersettings:save', 'user', '_elgg_save_notification_user_settings');
345
+    elgg_register_plugin_hook_handler('cron', 'minute', '_elgg_notifications_cron', 100);
346
+    elgg_register_event_handler('all', 'all', '_elgg_enqueue_notification_event', 700);
347
+
348
+    // add email notifications
349
+    elgg_register_notification_method('email');
350
+    elgg_register_plugin_hook_handler('send', 'notification:email', '_elgg_send_email_notification');
351
+    elgg_register_plugin_hook_handler('email', 'system', '_elgg_notifications_smtp_default_message_id_header', 1);
352
+    elgg_register_plugin_hook_handler('email', 'system', '_elgg_notifications_smtp_thread_headers');
353
+
354
+    // add ability to set personal notification method
355
+    elgg_extend_view('forms/account/settings', 'core/settings/account/notifications');
356
+    elgg_register_plugin_hook_handler('usersettings:save', 'user', '_elgg_save_notification_user_settings');
357 357
 }
358 358
 
359 359
 /**
@@ -373,74 +373,74 @@  discard block
 block discarded – undo
373 373
  */
374 374
 function _elgg_notify_user($to, $from, $subject, $message, array $params = null, $methods_override = "") {
375 375
 
376
-	$notify_service = _elgg_services()->notifications;
377
-
378
-	// Sanitise
379
-	if (!is_array($to)) {
380
-		$to = array((int) $to);
381
-	}
382
-	$from = (int) $from;
383
-	//$subject = sanitise_string($subject);
384
-	// Get notification methods
385
-	if (($methods_override) && (!is_array($methods_override))) {
386
-		$methods_override = array($methods_override);
387
-	}
388
-
389
-	$result = array();
390
-
391
-	foreach ($to as $guid) {
392
-		// Results for a user are...
393
-		$result[$guid] = array();
394
-
395
-		if ($guid) { // Is the guid > 0?
396
-			// Are we overriding delivery?
397
-			$methods = $methods_override;
398
-			if (!$methods) {
399
-				$tmp = get_user_notification_settings($guid);
400
-				$methods = array();
401
-				// $tmp may be false. don't cast
402
-				if (is_object($tmp)) {
403
-					foreach ($tmp as $k => $v) {
404
-						// Add method if method is turned on for user!
405
-						if ($v) {
406
-							$methods[] = $k;
407
-						}
408
-					}
409
-				}
410
-			}
411
-
412
-			if ($methods) {
413
-				// Deliver
414
-				foreach ($methods as $method) {
415
-
416
-					$handler = $notify_service->getDeprecatedHandler($method);
417
-					/* @var callable $handler */
418
-					if (!$handler || !is_callable($handler)) {
419
-						elgg_log("No handler registered for the method $method", 'WARNING');
420
-						continue;
421
-					}
422
-
423
-					elgg_log("Sending message to $guid using $method");
424
-
425
-					// Trigger handler and retrieve result.
426
-					try {
427
-						$result[$guid][$method] = call_user_func(
428
-							$handler,
429
-							$from ? get_entity($from) : null,
430
-							get_entity($guid),
431
-							$subject,
432
-							$message,
433
-							$params
434
-						);
435
-					} catch (Exception $e) {
436
-						error_log($e->getMessage());
437
-					}
438
-				}
439
-			}
440
-		}
441
-	}
442
-
443
-	return $result;
376
+    $notify_service = _elgg_services()->notifications;
377
+
378
+    // Sanitise
379
+    if (!is_array($to)) {
380
+        $to = array((int) $to);
381
+    }
382
+    $from = (int) $from;
383
+    //$subject = sanitise_string($subject);
384
+    // Get notification methods
385
+    if (($methods_override) && (!is_array($methods_override))) {
386
+        $methods_override = array($methods_override);
387
+    }
388
+
389
+    $result = array();
390
+
391
+    foreach ($to as $guid) {
392
+        // Results for a user are...
393
+        $result[$guid] = array();
394
+
395
+        if ($guid) { // Is the guid > 0?
396
+            // Are we overriding delivery?
397
+            $methods = $methods_override;
398
+            if (!$methods) {
399
+                $tmp = get_user_notification_settings($guid);
400
+                $methods = array();
401
+                // $tmp may be false. don't cast
402
+                if (is_object($tmp)) {
403
+                    foreach ($tmp as $k => $v) {
404
+                        // Add method if method is turned on for user!
405
+                        if ($v) {
406
+                            $methods[] = $k;
407
+                        }
408
+                    }
409
+                }
410
+            }
411
+
412
+            if ($methods) {
413
+                // Deliver
414
+                foreach ($methods as $method) {
415
+
416
+                    $handler = $notify_service->getDeprecatedHandler($method);
417
+                    /* @var callable $handler */
418
+                    if (!$handler || !is_callable($handler)) {
419
+                        elgg_log("No handler registered for the method $method", 'WARNING');
420
+                        continue;
421
+                    }
422
+
423
+                    elgg_log("Sending message to $guid using $method");
424
+
425
+                    // Trigger handler and retrieve result.
426
+                    try {
427
+                        $result[$guid][$method] = call_user_func(
428
+                            $handler,
429
+                            $from ? get_entity($from) : null,
430
+                            get_entity($guid),
431
+                            $subject,
432
+                            $message,
433
+                            $params
434
+                        );
435
+                    } catch (Exception $e) {
436
+                        error_log($e->getMessage());
437
+                    }
438
+                }
439
+            }
440
+        }
441
+    }
442
+
443
+    return $result;
444 444
 }
445 445
 
446 446
 /**
@@ -493,30 +493,30 @@  discard block
 block discarded – undo
493 493
  */
494 494
 function notify_user($to, $from = 0, $subject = '', $message = '', array $params = array(), $methods_override = null) {
495 495
 
496
-	$params['subject'] = $subject;
497
-	$params['body'] = $message;
498
-	$params['methods_override'] = $methods_override;
499
-
500
-	if ($from) {
501
-		$sender = get_entity($from);
502
-	} else {
503
-		$sender = elgg_get_site_entity();
504
-	}
505
-	if (!$sender) {
506
-		return [];
507
-	}
508
-
509
-	$recipients = [];
510
-	$to = (array) $to;
511
-	foreach ($to as $guid) {
512
-		$recipient = get_entity($guid);
513
-		if (!$recipient) {
514
-			continue;
515
-		}
516
-		$recipients[] = $recipient;
517
-	}
518
-
519
-	return _elgg_services()->notifications->sendInstantNotifications($sender, $recipients, $params);
496
+    $params['subject'] = $subject;
497
+    $params['body'] = $message;
498
+    $params['methods_override'] = $methods_override;
499
+
500
+    if ($from) {
501
+        $sender = get_entity($from);
502
+    } else {
503
+        $sender = elgg_get_site_entity();
504
+    }
505
+    if (!$sender) {
506
+        return [];
507
+    }
508
+
509
+    $recipients = [];
510
+    $to = (array) $to;
511
+    foreach ($to as $guid) {
512
+        $recipient = get_entity($guid);
513
+        if (!$recipient) {
514
+            continue;
515
+        }
516
+        $recipients[] = $recipient;
517
+    }
518
+
519
+    return _elgg_services()->notifications->sendInstantNotifications($sender, $recipients, $params);
520 520
 }
521 521
 
522 522
 /**
@@ -529,18 +529,18 @@  discard block
 block discarded – undo
529 529
  */
530 530
 function get_user_notification_settings($user_guid = 0) {
531 531
 
532
-	elgg_deprecated_notice(__FUNCTION__ . ' has been deprecated by ElggUser::getNotificationSettings()', '2.3');
532
+    elgg_deprecated_notice(__FUNCTION__ . ' has been deprecated by ElggUser::getNotificationSettings()', '2.3');
533 533
 
534
-	if ((int) $user_guid == 0) {
535
-		$user_guid = elgg_get_logged_in_user_guid();
536
-	}
534
+    if ((int) $user_guid == 0) {
535
+        $user_guid = elgg_get_logged_in_user_guid();
536
+    }
537 537
 
538
-	$user = get_entity($user_guid);
539
-	if (!$user instanceof \ElggUser) {
540
-		return false;
541
-	}
538
+    $user = get_entity($user_guid);
539
+    if (!$user instanceof \ElggUser) {
540
+        return false;
541
+    }
542 542
 
543
-	return (object) $user->getNotificationSettings();
543
+    return (object) $user->getNotificationSettings();
544 544
 }
545 545
 
546 546
 /**
@@ -554,26 +554,26 @@  discard block
 block discarded – undo
554 554
  * @deprecated 2.3
555 555
  */
556 556
 function set_user_notification_setting($user_guid, $method, $value) {
557
-	elgg_deprecated_notice(__FUNCTION__ . ' has been deprecated by ElggUser::setNotificationSetting()', '2.3');
558
-
559
-	if (!$user_guid) {
560
-		$user_guid = elgg_get_logged_in_user_guid();
561
-	}
562
-	$user = get_entity($user_guid);
563
-	if (!$user instanceof \ElggUser) {
564
-		return false;
565
-	}
566
-
567
-	if (is_string($value)) {
568
-		$value = strtolower($value);
569
-	}
570
-	if ($value == 'yes' || $value == 'on' || $value == 'enabled') {
571
-		$value = true;
572
-	} else if ($value == 'no' || $value == 'off' || $value == 'disabled') {
573
-		$value = false;
574
-	}
575
-
576
-	return $user->setNotificationSetting($method, (bool) $value);
557
+    elgg_deprecated_notice(__FUNCTION__ . ' has been deprecated by ElggUser::setNotificationSetting()', '2.3');
558
+
559
+    if (!$user_guid) {
560
+        $user_guid = elgg_get_logged_in_user_guid();
561
+    }
562
+    $user = get_entity($user_guid);
563
+    if (!$user instanceof \ElggUser) {
564
+        return false;
565
+    }
566
+
567
+    if (is_string($value)) {
568
+        $value = strtolower($value);
569
+    }
570
+    if ($value == 'yes' || $value == 'on' || $value == 'enabled') {
571
+        $value = true;
572
+    } else if ($value == 'no' || $value == 'off' || $value == 'disabled') {
573
+        $value = false;
574
+    }
575
+
576
+    return $user->setNotificationSetting($method, (bool) $value);
577 577
 }
578 578
 
579 579
 /**
@@ -590,79 +590,79 @@  discard block
 block discarded – undo
590 590
  * @since 1.7.2
591 591
  */
592 592
 function elgg_send_email($from, $to, $subject, $body, array $params = null) {
593
-	if (!$from) {
594
-		$msg = "Missing a required parameter, '" . 'from' . "'";
595
-		throw new \NotificationException($msg);
596
-	}
597
-
598
-	if (!$to) {
599
-		$msg = "Missing a required parameter, '" . 'to' . "'";
600
-		throw new \NotificationException($msg);
601
-	}
602
-
603
-	$headers = array(
604
-		"Content-Type" => "text/plain; charset=UTF-8; format=flowed",
605
-		"MIME-Version" => "1.0",
606
-		"Content-Transfer-Encoding" => "8bit",
607
-	);
608
-
609
-	// return true/false to stop elgg_send_email() from sending
610
-	$mail_params = array(
611
-		'to' => $to,
612
-		'from' => $from,
613
-		'subject' => $subject,
614
-		'body' => $body,
615
-		'headers' => $headers,
616
-		'params' => $params,
617
-	);
618
-
619
-	// $mail_params is passed as both params and return value. The former is for backwards
620
-	// compatibility. The latter is so handlers can now alter the contents/headers of
621
-	// the email by returning the array
622
-	$result = _elgg_services()->hooks->trigger('email', 'system', $mail_params, $mail_params);
623
-	if (!is_array($result)) {
624
-		// don't need null check: Handlers can't set a hook value to null!
625
-		return (bool) $result;
626
-	}
627
-
628
-	// strip name from to and from
629
-
630
-	$to_address = Address::fromString($result['to']);
631
-	$from_address = Address::fromString($result['from']);
632
-
633
-
634
-	$subject = elgg_strip_tags($result['subject']);
635
-	$subject = html_entity_decode($subject, ENT_QUOTES, 'UTF-8');
636
-	// Sanitise subject by stripping line endings
637
-	$subject = preg_replace("/(\r\n|\r|\n)/", " ", $subject);
638
-	$subject = trim($subject);
639
-
640
-	$body = elgg_strip_tags($result['body']);
641
-	$body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
642
-	$body = wordwrap($body);
643
-
644
-	$message = new Message();
645
-	$message->setEncoding('UTF-8');
646
-	$message->addFrom($from_address);
647
-	$message->addTo($to_address);
648
-	$message->setSubject($subject);
649
-	$message->setBody($body);
650
-
651
-	foreach ($result['headers'] as $headerName => $headerValue) {
652
-		// Create a headerline in the format 'name: value'
653
-		// This is done to force correct class detection for each header type
654
-		// which influences the output of the header in the message
655
-		$message->getHeaders()->addHeaderLine("{$headerName}: {$headerValue}");
656
-	}
657
-
658
-	try {
659
-		_elgg_services()->mailer->send($message);
660
-	} catch (\Zend\Mail\Exception\RuntimeException $e) {
661
-		_elgg_services()->logger->error($e->getMessage());
662
-		return false;
663
-	}
664
-
665
-	return true;
593
+    if (!$from) {
594
+        $msg = "Missing a required parameter, '" . 'from' . "'";
595
+        throw new \NotificationException($msg);
596
+    }
597
+
598
+    if (!$to) {
599
+        $msg = "Missing a required parameter, '" . 'to' . "'";
600
+        throw new \NotificationException($msg);
601
+    }
602
+
603
+    $headers = array(
604
+        "Content-Type" => "text/plain; charset=UTF-8; format=flowed",
605
+        "MIME-Version" => "1.0",
606
+        "Content-Transfer-Encoding" => "8bit",
607
+    );
608
+
609
+    // return true/false to stop elgg_send_email() from sending
610
+    $mail_params = array(
611
+        'to' => $to,
612
+        'from' => $from,
613
+        'subject' => $subject,
614
+        'body' => $body,
615
+        'headers' => $headers,
616
+        'params' => $params,
617
+    );
618
+
619
+    // $mail_params is passed as both params and return value. The former is for backwards
620
+    // compatibility. The latter is so handlers can now alter the contents/headers of
621
+    // the email by returning the array
622
+    $result = _elgg_services()->hooks->trigger('email', 'system', $mail_params, $mail_params);
623
+    if (!is_array($result)) {
624
+        // don't need null check: Handlers can't set a hook value to null!
625
+        return (bool) $result;
626
+    }
627
+
628
+    // strip name from to and from
629
+
630
+    $to_address = Address::fromString($result['to']);
631
+    $from_address = Address::fromString($result['from']);
632
+
633
+
634
+    $subject = elgg_strip_tags($result['subject']);
635
+    $subject = html_entity_decode($subject, ENT_QUOTES, 'UTF-8');
636
+    // Sanitise subject by stripping line endings
637
+    $subject = preg_replace("/(\r\n|\r|\n)/", " ", $subject);
638
+    $subject = trim($subject);
639
+
640
+    $body = elgg_strip_tags($result['body']);
641
+    $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
642
+    $body = wordwrap($body);
643
+
644
+    $message = new Message();
645
+    $message->setEncoding('UTF-8');
646
+    $message->addFrom($from_address);
647
+    $message->addTo($to_address);
648
+    $message->setSubject($subject);
649
+    $message->setBody($body);
650
+
651
+    foreach ($result['headers'] as $headerName => $headerValue) {
652
+        // Create a headerline in the format 'name: value'
653
+        // This is done to force correct class detection for each header type
654
+        // which influences the output of the header in the message
655
+        $message->getHeaders()->addHeaderLine("{$headerName}: {$headerValue}");
656
+    }
657
+
658
+    try {
659
+        _elgg_services()->mailer->send($message);
660
+    } catch (\Zend\Mail\Exception\RuntimeException $e) {
661
+        _elgg_services()->logger->error($e->getMessage());
662
+        return false;
663
+    }
664
+
665
+    return true;
666 666
 }
667 667
 
668 668
 /**
@@ -673,44 +673,44 @@  discard block
 block discarded – undo
673 673
  */
674 674
 function _elgg_save_notification_user_settings() {
675 675
 
676
-	$user = elgg_get_logged_in_user_entity();
677
-	if (!$user) {
678
-		return;
679
-	}
676
+    $user = elgg_get_logged_in_user_entity();
677
+    if (!$user) {
678
+        return;
679
+    }
680 680
 
681
-	$method = get_input('method');
681
+    $method = get_input('method');
682 682
 
683
-	$current_settings = $user->getNotificationSettings();
683
+    $current_settings = $user->getNotificationSettings();
684 684
 
685
-	$result = false;
686
-	foreach ($method as $k => $v) {
687
-		// check if setting has changed and skip if not
688
-		if ($current_settings[$k] == ($v == 'yes')) {
689
-			continue;
690
-		}
685
+    $result = false;
686
+    foreach ($method as $k => $v) {
687
+        // check if setting has changed and skip if not
688
+        if ($current_settings[$k] == ($v == 'yes')) {
689
+            continue;
690
+        }
691 691
 
692
-		$result = $user->setNotificationSetting($k, ($v == 'yes'));
693
-		if (!$result) {
694
-			register_error(elgg_echo('notifications:usersettings:save:fail'));
695
-		}
696
-	}
692
+        $result = $user->setNotificationSetting($k, ($v == 'yes'));
693
+        if (!$result) {
694
+            register_error(elgg_echo('notifications:usersettings:save:fail'));
695
+        }
696
+    }
697 697
 
698
-	if ($result) {
699
-		system_message(elgg_echo('notifications:usersettings:save:ok'));
700
-	}
698
+    if ($result) {
699
+        system_message(elgg_echo('notifications:usersettings:save:ok'));
700
+    }
701 701
 }
702 702
 
703 703
 /**
704 704
  * @access private
705 705
  */
706 706
 function _elgg_notifications_test($hook, $type, $tests) {
707
-	global $CONFIG;
708
-	$tests[] = "{$CONFIG->path}engine/tests/ElggCoreDatabaseQueueTest.php";
709
-	return $tests;
707
+    global $CONFIG;
708
+    $tests[] = "{$CONFIG->path}engine/tests/ElggCoreDatabaseQueueTest.php";
709
+    return $tests;
710 710
 }
711 711
 
712 712
 return function(\Elgg\EventsService $events, \Elgg\HooksRegistrationService $hooks) {
713
-	$events->registerHandler('init', 'system', '_elgg_notifications_init');
713
+    $events->registerHandler('init', 'system', '_elgg_notifications_init');
714 714
 
715
-	$hooks->registerHandler('unit_test', 'system', '_elgg_notifications_test');
715
+    $hooks->registerHandler('unit_test', 'system', '_elgg_notifications_test');
716 716
 };
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -245,7 +245,7 @@  discard block
 block discarded – undo
245 245
 		$from = $site->email;
246 246
 	} else {
247 247
 		// If all else fails, use the domain of the site.
248
-		$from = 'noreply@' . $site->getDomain();
248
+		$from = 'noreply@'.$site->getDomain();
249 249
 	}
250 250
 
251 251
 	return elgg_send_email($from, $to, $message->subject, $message->body, $params);
@@ -529,7 +529,7 @@  discard block
 block discarded – undo
529 529
  */
530 530
 function get_user_notification_settings($user_guid = 0) {
531 531
 
532
-	elgg_deprecated_notice(__FUNCTION__ . ' has been deprecated by ElggUser::getNotificationSettings()', '2.3');
532
+	elgg_deprecated_notice(__FUNCTION__.' has been deprecated by ElggUser::getNotificationSettings()', '2.3');
533 533
 
534 534
 	if ((int) $user_guid == 0) {
535 535
 		$user_guid = elgg_get_logged_in_user_guid();
@@ -554,7 +554,7 @@  discard block
 block discarded – undo
554 554
  * @deprecated 2.3
555 555
  */
556 556
 function set_user_notification_setting($user_guid, $method, $value) {
557
-	elgg_deprecated_notice(__FUNCTION__ . ' has been deprecated by ElggUser::setNotificationSetting()', '2.3');
557
+	elgg_deprecated_notice(__FUNCTION__.' has been deprecated by ElggUser::setNotificationSetting()', '2.3');
558 558
 
559 559
 	if (!$user_guid) {
560 560
 		$user_guid = elgg_get_logged_in_user_guid();
@@ -591,12 +591,12 @@  discard block
 block discarded – undo
591 591
  */
592 592
 function elgg_send_email($from, $to, $subject, $body, array $params = null) {
593 593
 	if (!$from) {
594
-		$msg = "Missing a required parameter, '" . 'from' . "'";
594
+		$msg = "Missing a required parameter, '".'from'."'";
595 595
 		throw new \NotificationException($msg);
596 596
 	}
597 597
 
598 598
 	if (!$to) {
599
-		$msg = "Missing a required parameter, '" . 'to' . "'";
599
+		$msg = "Missing a required parameter, '".'to'."'";
600 600
 		throw new \NotificationException($msg);
601 601
 	}
602 602
 
Please login to merge, or discard this patch.
engine/classes/Elgg/Di/ServiceProvider.php 1 patch
Indentation   +398 added lines, -398 removed lines patch added patch discarded remove patch
@@ -89,402 +89,402 @@
 block discarded – undo
89 89
  */
90 90
 class ServiceProvider extends \Elgg\Di\DiContainer {
91 91
 
92
-	/**
93
-	 * Constructor
94
-	 *
95
-	 * @param \Elgg\Config $config Elgg Config service
96
-	 */
97
-	public function __construct(\Elgg\Config $config) {
98
-
99
-		$this->setFactory('classLoader', function(ServiceProvider $c) {
100
-			$loader = new \Elgg\ClassLoader(new \Elgg\ClassMap());
101
-			$loader->register();
102
-			return $loader;
103
-		});
104
-
105
-		$this->setFactory('autoloadManager', function(ServiceProvider $c) {
106
-			$manager = new \Elgg\AutoloadManager($c->classLoader);
107
-			if (!$c->config->get('AutoloaderManager_skip_storage')) {
108
-				$manager->setStorage($c->fileCache);
109
-				$manager->loadCache();
110
-			}
111
-			return $manager;
112
-		});
113
-
114
-		$this->setFactory('accessCache', function(ServiceProvider $c) {
115
-			return new \ElggStaticVariableCache('access');
116
-		});
117
-
118
-		$this->setFactory('accessCollections', function(ServiceProvider $c) {
119
-			return new \Elgg\Database\AccessCollections(
120
-					$c->config, $c->db, $c->entityTable, $c->accessCache, $c->hooks, $c->session, $c->translator);
121
-		});
122
-
123
-		$this->setFactory('actions', function(ServiceProvider $c) {
124
-			return new \Elgg\ActionsService($c->config, $c->session, $c->crypto);
125
-		});
126
-
127
-		$this->setClassName('adminNotices', \Elgg\Database\AdminNotices::class);
128
-
129
-		$this->setFactory('ajax', function(ServiceProvider $c) {
130
-			return new \Elgg\Ajax\Service($c->hooks, $c->systemMessages, $c->input, $c->amdConfig);
131
-		});
132
-
133
-		$this->setFactory('amdConfig', function(ServiceProvider $c) {
134
-			$obj = new \Elgg\Amd\Config($c->hooks);
135
-			$obj->setBaseUrl($c->simpleCache->getRoot());
136
-			return $obj;
137
-		});
138
-
139
-		$this->setFactory('annotations', function(ServiceProvider $c) {
140
-			return new \Elgg\Database\Annotations($c->db, $c->session, $c->events);
141
-		});
142
-
143
-		$this->setClassName('autoP', \ElggAutoP::class);
144
-
145
-		$this->setFactory('boot', function(ServiceProvider $c) {
146
-			$boot = new \Elgg\BootService();
147
-			if ($c->config->getVolatile('enable_profiling')) {
148
-				$boot->setTimer($c->timer);
149
-			}
150
-			return $boot;
151
-		});
152
-
153
-		$this->setValue('config', $config);
154
-
155
-		$this->setClassName('configTable', \Elgg\Database\ConfigTable::class);
156
-
157
-		$this->setClassName('context', \Elgg\Context::class);
158
-
159
-		$this->setFactory('crypto', function(ServiceProvider $c) {
160
-			return new \ElggCrypto($c->siteSecret);
161
-		});
162
-
163
-		$this->setFactory('datalist', function(ServiceProvider $c) {
164
-			// TODO(ewinslow): Add back memcached support
165
-			$db = $c->db;
166
-			$dbprefix = $db->prefix;
167
-			$pool = new Pool\InMemory();
168
-			return new \Elgg\Database\Datalist($pool, $db, $c->logger, "{$dbprefix}datalists");
169
-		});
170
-
171
-		$this->setFactory('db', function(ServiceProvider $c) {
172
-			// gonna need dbprefix from settings
173
-			$c->config->loadSettingsFile();
174
-			$db_config = new \Elgg\Database\Config($c->config->getStorageObject());
175
-
176
-			// we inject the logger in _elgg_engine_boot()
177
-			$db = new \Elgg\Database($db_config);
178
-
179
-			if ($c->config->getVolatile('profiling_sql')) {
180
-				$db->setTimer($c->timer);
181
-			}
182
-
183
-			return $db;
184
-		});
185
-
186
-		$this->setFactory('deprecation', function(ServiceProvider $c) {
187
-			return new \Elgg\DeprecationService($c->logger);
188
-		});
189
-
190
-		$this->setFactory('entityCache', function(ServiceProvider $c) {
191
-			return new \Elgg\Cache\EntityCache($c->session, $c->metadataCache);
192
-		});
193
-
194
-		$this->setFactory('entityPreloader', function(ServiceProvider $c) {
195
-			return new \Elgg\EntityPreloader($c->entityCache, $c->entityTable);
196
-		});
197
-
198
-		$this->setFactory('entityTable', function(ServiceProvider $c) {
199
-			return new \Elgg\Database\EntityTable(
200
-				$c->config,
201
-				$c->db,
202
-				$c->entityCache,
203
-				$c->metadataCache,
204
-				$c->subtypeTable,
205
-				$c->events,
206
-				$c->session,
207
-				$c->translator,
208
-				$c->logger
209
-			);
210
-		});
211
-
212
-		$this->setFactory('events', function(ServiceProvider $c) {
213
-			return $this->resolveLoggerDependencies('events');
214
-		});
215
-
216
-		$this->setFactory('externalFiles', function(ServiceProvider $c) {
217
-			return new \Elgg\Assets\ExternalFiles($c->config->getStorageObject());
218
-		});
219
-
220
-		$this->setFactory('fileCache', function(ServiceProvider $c) {
221
-			return new \ElggFileCache($c->config->getCachePath() . 'system_cache/');
222
-		});
223
-
224
-		$this->setFactory('forms', function(ServiceProvider $c) {
225
-			return new \Elgg\FormsService($c->views, $c->logger);
226
-		});
227
-
228
-		$this->setFactory('hooks', function(ServiceProvider $c) {
229
-			return $this->resolveLoggerDependencies('hooks');
230
-		});
231
-
232
-		$this->setFactory('iconService', function(ServiceProvider $c) {
233
-			return new \Elgg\EntityIconService($c->config, $c->hooks, $c->request, $c->logger, $c->entityTable);
234
-		});
235
-
236
-		$this->setClassName('input', \Elgg\Http\Input::class);
237
-
238
-		$this->setFactory('imageService', function(ServiceProvider $c) {
239
-			$imagine = new \Imagine\Gd\Imagine();
240
-			return new \Elgg\ImageService($imagine, $c->config);
241
-		});
242
-
243
-		$this->setFactory('logger', function(ServiceProvider $c) {
244
-			return $this->resolveLoggerDependencies('logger');
245
-		});
246
-
247
-		// TODO(evan): Support configurable transports...
248
-		$this->setClassName('mailer', 'Zend\Mail\Transport\Sendmail');
249
-
250
-		$this->setFactory('menus', function(ServiceProvider $c) {
251
-			return new \Elgg\Menu\Service($c->hooks, $c->config);
252
-		});
253
-
254
-		$this->setFactory('metadataCache', function (ServiceProvider $c) {
255
-			return new \Elgg\Cache\MetadataCache($c->session);
256
-		});
257
-
258
-		$this->setFactory('memcacheStashPool', function(ServiceProvider $c) {
259
-			if (!$c->config->getVolatile('memcache')) {
260
-				return null;
261
-			}
262
-
263
-			$servers = $c->config->getVolatile('memcache_servers');
264
-			if (!$servers) {
265
-				return null;
266
-			}
267
-			$driver = new \Stash\Driver\Memcache([
268
-				'servers' => $servers,
269
-			]);
270
-			return new \Stash\Pool($driver);
271
-		});
272
-
273
-		$this->setFactory('metadataTable', function(ServiceProvider $c) {
274
-			// TODO(ewinslow): Use Pool instead of MetadataCache for caching
275
-			return new \Elgg\Database\MetadataTable(
276
-				$c->metadataCache, $c->db, $c->entityTable, $c->events, $c->metastringsTable, $c->session);
277
-		});
278
-
279
-		$this->setFactory('metastringsTable', function(ServiceProvider $c) {
280
-			// TODO(ewinslow): Use memcache-based Pool if available...
281
-			$pool = new Pool\InMemory();
282
-			return new \Elgg\Database\MetastringsTable($pool, $c->db);
283
-		});
284
-
285
-		$this->setFactory('mutex', function(ServiceProvider $c) {
286
-			return new \Elgg\Database\Mutex(
287
-				$c->db,
288
-				$c->logger
289
-			);
290
-		});
291
-
292
-		$this->setFactory('notifications', function(ServiceProvider $c) {
293
-			// @todo move queue in service provider
294
-			$queue_name = \Elgg\Notifications\NotificationsService::QUEUE_NAME;
295
-			$queue = new \Elgg\Queue\DatabaseQueue($queue_name, $c->db);
296
-			$sub = new \Elgg\Notifications\SubscriptionsService($c->db);
297
-			return new \Elgg\Notifications\NotificationsService($sub, $queue, $c->hooks, $c->session, $c->translator, $c->entityTable, $c->logger);
298
-		});
299
-
300
-		$this->setClassName('nullCache', \Elgg\Cache\NullCache::class);
301
-
302
-		$this->setFactory('persistentLogin', function(ServiceProvider $c) {
303
-			$global_cookies_config = $c->config->getCookieConfig();
304
-			$cookie_config = $global_cookies_config['remember_me'];
305
-			$cookie_name = $cookie_config['name'];
306
-			$cookie_token = $c->request->cookies->get($cookie_name, '');
307
-			return new \Elgg\PersistentLoginService(
308
-				$c->db, $c->session, $c->crypto, $cookie_config, $cookie_token);
309
-		});
310
-
311
-		$this->setClassName('passwords', \Elgg\PasswordService::class);
312
-
313
-		$this->setFactory('plugins', function(ServiceProvider $c) {
314
-			$pool = new Pool\InMemory();
315
-			$plugins = new \Elgg\Database\Plugins($pool, $c->pluginSettingsCache);
316
-			if ($c->config->getVolatile('enable_profiling')) {
317
-				$plugins->setTimer($c->timer);
318
-			}
319
-			return $plugins;
320
-		});
321
-
322
-		$this->setClassName('pluginSettingsCache', \Elgg\Cache\PluginSettingsCache::class);
323
-
324
-		$this->setFactory('privateSettings', function(ServiceProvider $c) {
325
-			return new \Elgg\Database\PrivateSettingsTable($c->db, $c->entityTable, $c->pluginSettingsCache);
326
-		});
327
-
328
-		$this->setFactory('publicDb', function(ServiceProvider $c) {
329
-			return new \Elgg\Application\Database($c->db);
330
-		});
331
-
332
-		$this->setFactory('queryCounter', function(ServiceProvider $c) {
333
-			return new \Elgg\Database\QueryCounter($c->db);
334
-		}, false);
335
-
336
-		$this->setFactory('redirects', function(ServiceProvider $c) {
337
-			$url = current_page_url();
338
-			$is_xhr = $c->request->isXmlHttpRequest();
339
-			return new \Elgg\RedirectService($c->session, $is_xhr, $c->config->getSiteUrl(), $url);
340
-		});
341
-
342
-		$this->setFactory('relationshipsTable', function(ServiceProvider $c) {
343
-			return new \Elgg\Database\RelationshipsTable($c->db, $c->entityTable, $c->metadataTable, $c->events);
344
-		});
345
-
346
-		$this->setFactory('request', [\Elgg\Http\Request::class, 'createFromGlobals']);
347
-
348
-		$this->setFactory('responseFactory', function(ServiceProvider $c) {
349
-			if (PHP_SAPI === 'cli') {
350
-				$transport = new \Elgg\Http\OutputBufferTransport();
351
-			} else {
352
-				$transport = new \Elgg\Http\HttpProtocolTransport();
353
-			}
354
-			return new \Elgg\Http\ResponseFactory($c->request, $c->hooks, $c->ajax, $transport);
355
-		});
356
-
357
-		$this->setFactory('router', function(ServiceProvider $c) {
358
-			// TODO(evan): Init routes from plugins or cache
359
-			$router = new \Elgg\Router($c->hooks);
360
-			if ($c->config->getVolatile('enable_profiling')) {
361
-				$router->setTimer($c->timer);
362
-			}
363
-			return $router;
364
-		});
365
-
366
-		$this->setFactory('seeder', function(ServiceProvider $c) {
367
-			return new \Elgg\Database\Seeder($c->hooks);
368
-		});
369
-
370
-		$this->setFactory('serveFileHandler', function(ServiceProvider $c) {
371
-			return new \Elgg\Application\ServeFileHandler($c->crypto, $c->config);
372
-		});
373
-
374
-		$this->setFactory('session', function(ServiceProvider $c) {
375
-			$params = $c->config->getCookieConfig()['session'];
376
-			$options = [
377
-				// session.cache_limiter is unfortunately set to "" by the NativeSessionStorage
378
-				// constructor, so we must capture and inject it directly.
379
-				'cache_limiter' => session_cache_limiter(),
380
-
381
-				'name' => $params['name'],
382
-				'cookie_path' => $params['path'],
383
-				'cookie_domain' => $params['domain'],
384
-				'cookie_secure' => $params['secure'],
385
-				'cookie_httponly' => $params['httponly'],
386
-				'cookie_lifetime' => $params['lifetime'],
387
-			];
388
-
389
-			$handler = new \Elgg\Http\DatabaseSessionHandler($c->db);
390
-			$storage = new NativeSessionStorage($options, $handler);
391
-			$session = new SymfonySession($storage);
392
-			return new \ElggSession($session);
393
-		});
394
-
395
-		$this->setClassName('urlSigner', \Elgg\Security\UrlSigner::class);
396
-
397
-		$this->setFactory('simpleCache', function(ServiceProvider $c) {
398
-			return new \Elgg\Cache\SimpleCache($c->config, $c->datalist, $c->views);
399
-		});
400
-
401
-		$this->setFactory('siteSecret', function(ServiceProvider $c) {
402
-			return new \Elgg\Database\SiteSecret($c->datalist);
403
-		});
404
-
405
-		$this->setClassName('stickyForms', \Elgg\Forms\StickyForms::class);
406
-
407
-		$this->setFactory('subtypeTable', function(ServiceProvider $c) {
408
-			return new \Elgg\Database\SubtypeTable($c->db);
409
-		});
410
-
411
-		$this->setFactory('systemCache', function (ServiceProvider $c) {
412
-			$cache = new \Elgg\Cache\SystemCache($c->fileCache, $c->config, $c->datalist);
413
-			if ($c->config->getVolatile('enable_profiling')) {
414
-				$cache->setTimer($c->timer);
415
-			}
416
-			return $cache;
417
-		});
418
-
419
-		$this->setFactory('systemMessages', function(ServiceProvider $c) {
420
-			return new \Elgg\SystemMessagesService($c->session);
421
-		});
422
-
423
-		$this->setClassName('table_columns', \Elgg\Views\TableColumn\ColumnFactory::class);
424
-
425
-		$this->setClassName('timer', \Elgg\Timer::class);
426
-
427
-		$this->setClassName('translator', \Elgg\I18n\Translator::class);
428
-
429
-		$this->setFactory('uploads', function(ServiceProvider $c) {
430
-			return new \Elgg\UploadService($c->request);
431
-		});
432
-
433
-		$this->setFactory('upgrades', function(ServiceProvider $c) {
434
-			return new \Elgg\UpgradeService(
435
-				$c->translator,
436
-				$c->events,
437
-				$c->hooks,
438
-				$c->datalist,
439
-				$c->logger,
440
-				$c->mutex
441
-			);
442
-		});
443
-
444
-		$this->setFactory('userCapabilities', function(ServiceProvider $c) {
445
-			return new \Elgg\UserCapabilities($c->hooks, $c->entityTable, $c->session);
446
-		});
447
-
448
-		$this->setFactory('usersTable', function(ServiceProvider $c) {
449
-			return new \Elgg\Database\UsersTable(
450
-				$c->config,
451
-				$c->db,
452
-				$c->entityTable,
453
-				$c->entityCache,
454
-				$c->events
455
-			);
456
-		});
457
-
458
-		$this->setFactory('views', function(ServiceProvider $c) {
459
-			return new \Elgg\ViewsService($c->hooks, $c->logger);
460
-		});
461
-
462
-		$this->setClassName('widgets', \Elgg\WidgetsService::class);
463
-
464
-	}
465
-
466
-	/**
467
-	 * Returns the first requested service of the logger, events, and hooks. It sets the
468
-	 * hooks and events up in the right order to prevent circular dependency.
469
-	 *
470
-	 * @param string $service_needed The service requested first
471
-	 * @return mixed
472
-	 */
473
-	protected function resolveLoggerDependencies($service_needed) {
474
-		$svcs['hooks'] = new \Elgg\PluginHooksService();
475
-
476
-		$svcs['logger'] = new \Elgg\Logger($svcs['hooks'], $this->config, $this->context);
477
-		$svcs['hooks']->setLogger($svcs['logger']);
478
-
479
-		$svcs['events'] = new \Elgg\EventsService();
480
-		$svcs['events']->setLogger($svcs['logger']);
481
-		if ($this->config->getVolatile('enable_profiling')) {
482
-			$svcs['events']->setTimer($this->timer);
483
-		}
484
-
485
-		foreach ($svcs as $key => $service) {
486
-			$this->setValue($key, $service);
487
-		}
488
-		return $svcs[$service_needed];
489
-	}
92
+    /**
93
+     * Constructor
94
+     *
95
+     * @param \Elgg\Config $config Elgg Config service
96
+     */
97
+    public function __construct(\Elgg\Config $config) {
98
+
99
+        $this->setFactory('classLoader', function(ServiceProvider $c) {
100
+            $loader = new \Elgg\ClassLoader(new \Elgg\ClassMap());
101
+            $loader->register();
102
+            return $loader;
103
+        });
104
+
105
+        $this->setFactory('autoloadManager', function(ServiceProvider $c) {
106
+            $manager = new \Elgg\AutoloadManager($c->classLoader);
107
+            if (!$c->config->get('AutoloaderManager_skip_storage')) {
108
+                $manager->setStorage($c->fileCache);
109
+                $manager->loadCache();
110
+            }
111
+            return $manager;
112
+        });
113
+
114
+        $this->setFactory('accessCache', function(ServiceProvider $c) {
115
+            return new \ElggStaticVariableCache('access');
116
+        });
117
+
118
+        $this->setFactory('accessCollections', function(ServiceProvider $c) {
119
+            return new \Elgg\Database\AccessCollections(
120
+                    $c->config, $c->db, $c->entityTable, $c->accessCache, $c->hooks, $c->session, $c->translator);
121
+        });
122
+
123
+        $this->setFactory('actions', function(ServiceProvider $c) {
124
+            return new \Elgg\ActionsService($c->config, $c->session, $c->crypto);
125
+        });
126
+
127
+        $this->setClassName('adminNotices', \Elgg\Database\AdminNotices::class);
128
+
129
+        $this->setFactory('ajax', function(ServiceProvider $c) {
130
+            return new \Elgg\Ajax\Service($c->hooks, $c->systemMessages, $c->input, $c->amdConfig);
131
+        });
132
+
133
+        $this->setFactory('amdConfig', function(ServiceProvider $c) {
134
+            $obj = new \Elgg\Amd\Config($c->hooks);
135
+            $obj->setBaseUrl($c->simpleCache->getRoot());
136
+            return $obj;
137
+        });
138
+
139
+        $this->setFactory('annotations', function(ServiceProvider $c) {
140
+            return new \Elgg\Database\Annotations($c->db, $c->session, $c->events);
141
+        });
142
+
143
+        $this->setClassName('autoP', \ElggAutoP::class);
144
+
145
+        $this->setFactory('boot', function(ServiceProvider $c) {
146
+            $boot = new \Elgg\BootService();
147
+            if ($c->config->getVolatile('enable_profiling')) {
148
+                $boot->setTimer($c->timer);
149
+            }
150
+            return $boot;
151
+        });
152
+
153
+        $this->setValue('config', $config);
154
+
155
+        $this->setClassName('configTable', \Elgg\Database\ConfigTable::class);
156
+
157
+        $this->setClassName('context', \Elgg\Context::class);
158
+
159
+        $this->setFactory('crypto', function(ServiceProvider $c) {
160
+            return new \ElggCrypto($c->siteSecret);
161
+        });
162
+
163
+        $this->setFactory('datalist', function(ServiceProvider $c) {
164
+            // TODO(ewinslow): Add back memcached support
165
+            $db = $c->db;
166
+            $dbprefix = $db->prefix;
167
+            $pool = new Pool\InMemory();
168
+            return new \Elgg\Database\Datalist($pool, $db, $c->logger, "{$dbprefix}datalists");
169
+        });
170
+
171
+        $this->setFactory('db', function(ServiceProvider $c) {
172
+            // gonna need dbprefix from settings
173
+            $c->config->loadSettingsFile();
174
+            $db_config = new \Elgg\Database\Config($c->config->getStorageObject());
175
+
176
+            // we inject the logger in _elgg_engine_boot()
177
+            $db = new \Elgg\Database($db_config);
178
+
179
+            if ($c->config->getVolatile('profiling_sql')) {
180
+                $db->setTimer($c->timer);
181
+            }
182
+
183
+            return $db;
184
+        });
185
+
186
+        $this->setFactory('deprecation', function(ServiceProvider $c) {
187
+            return new \Elgg\DeprecationService($c->logger);
188
+        });
189
+
190
+        $this->setFactory('entityCache', function(ServiceProvider $c) {
191
+            return new \Elgg\Cache\EntityCache($c->session, $c->metadataCache);
192
+        });
193
+
194
+        $this->setFactory('entityPreloader', function(ServiceProvider $c) {
195
+            return new \Elgg\EntityPreloader($c->entityCache, $c->entityTable);
196
+        });
197
+
198
+        $this->setFactory('entityTable', function(ServiceProvider $c) {
199
+            return new \Elgg\Database\EntityTable(
200
+                $c->config,
201
+                $c->db,
202
+                $c->entityCache,
203
+                $c->metadataCache,
204
+                $c->subtypeTable,
205
+                $c->events,
206
+                $c->session,
207
+                $c->translator,
208
+                $c->logger
209
+            );
210
+        });
211
+
212
+        $this->setFactory('events', function(ServiceProvider $c) {
213
+            return $this->resolveLoggerDependencies('events');
214
+        });
215
+
216
+        $this->setFactory('externalFiles', function(ServiceProvider $c) {
217
+            return new \Elgg\Assets\ExternalFiles($c->config->getStorageObject());
218
+        });
219
+
220
+        $this->setFactory('fileCache', function(ServiceProvider $c) {
221
+            return new \ElggFileCache($c->config->getCachePath() . 'system_cache/');
222
+        });
223
+
224
+        $this->setFactory('forms', function(ServiceProvider $c) {
225
+            return new \Elgg\FormsService($c->views, $c->logger);
226
+        });
227
+
228
+        $this->setFactory('hooks', function(ServiceProvider $c) {
229
+            return $this->resolveLoggerDependencies('hooks');
230
+        });
231
+
232
+        $this->setFactory('iconService', function(ServiceProvider $c) {
233
+            return new \Elgg\EntityIconService($c->config, $c->hooks, $c->request, $c->logger, $c->entityTable);
234
+        });
235
+
236
+        $this->setClassName('input', \Elgg\Http\Input::class);
237
+
238
+        $this->setFactory('imageService', function(ServiceProvider $c) {
239
+            $imagine = new \Imagine\Gd\Imagine();
240
+            return new \Elgg\ImageService($imagine, $c->config);
241
+        });
242
+
243
+        $this->setFactory('logger', function(ServiceProvider $c) {
244
+            return $this->resolveLoggerDependencies('logger');
245
+        });
246
+
247
+        // TODO(evan): Support configurable transports...
248
+        $this->setClassName('mailer', 'Zend\Mail\Transport\Sendmail');
249
+
250
+        $this->setFactory('menus', function(ServiceProvider $c) {
251
+            return new \Elgg\Menu\Service($c->hooks, $c->config);
252
+        });
253
+
254
+        $this->setFactory('metadataCache', function (ServiceProvider $c) {
255
+            return new \Elgg\Cache\MetadataCache($c->session);
256
+        });
257
+
258
+        $this->setFactory('memcacheStashPool', function(ServiceProvider $c) {
259
+            if (!$c->config->getVolatile('memcache')) {
260
+                return null;
261
+            }
262
+
263
+            $servers = $c->config->getVolatile('memcache_servers');
264
+            if (!$servers) {
265
+                return null;
266
+            }
267
+            $driver = new \Stash\Driver\Memcache([
268
+                'servers' => $servers,
269
+            ]);
270
+            return new \Stash\Pool($driver);
271
+        });
272
+
273
+        $this->setFactory('metadataTable', function(ServiceProvider $c) {
274
+            // TODO(ewinslow): Use Pool instead of MetadataCache for caching
275
+            return new \Elgg\Database\MetadataTable(
276
+                $c->metadataCache, $c->db, $c->entityTable, $c->events, $c->metastringsTable, $c->session);
277
+        });
278
+
279
+        $this->setFactory('metastringsTable', function(ServiceProvider $c) {
280
+            // TODO(ewinslow): Use memcache-based Pool if available...
281
+            $pool = new Pool\InMemory();
282
+            return new \Elgg\Database\MetastringsTable($pool, $c->db);
283
+        });
284
+
285
+        $this->setFactory('mutex', function(ServiceProvider $c) {
286
+            return new \Elgg\Database\Mutex(
287
+                $c->db,
288
+                $c->logger
289
+            );
290
+        });
291
+
292
+        $this->setFactory('notifications', function(ServiceProvider $c) {
293
+            // @todo move queue in service provider
294
+            $queue_name = \Elgg\Notifications\NotificationsService::QUEUE_NAME;
295
+            $queue = new \Elgg\Queue\DatabaseQueue($queue_name, $c->db);
296
+            $sub = new \Elgg\Notifications\SubscriptionsService($c->db);
297
+            return new \Elgg\Notifications\NotificationsService($sub, $queue, $c->hooks, $c->session, $c->translator, $c->entityTable, $c->logger);
298
+        });
299
+
300
+        $this->setClassName('nullCache', \Elgg\Cache\NullCache::class);
301
+
302
+        $this->setFactory('persistentLogin', function(ServiceProvider $c) {
303
+            $global_cookies_config = $c->config->getCookieConfig();
304
+            $cookie_config = $global_cookies_config['remember_me'];
305
+            $cookie_name = $cookie_config['name'];
306
+            $cookie_token = $c->request->cookies->get($cookie_name, '');
307
+            return new \Elgg\PersistentLoginService(
308
+                $c->db, $c->session, $c->crypto, $cookie_config, $cookie_token);
309
+        });
310
+
311
+        $this->setClassName('passwords', \Elgg\PasswordService::class);
312
+
313
+        $this->setFactory('plugins', function(ServiceProvider $c) {
314
+            $pool = new Pool\InMemory();
315
+            $plugins = new \Elgg\Database\Plugins($pool, $c->pluginSettingsCache);
316
+            if ($c->config->getVolatile('enable_profiling')) {
317
+                $plugins->setTimer($c->timer);
318
+            }
319
+            return $plugins;
320
+        });
321
+
322
+        $this->setClassName('pluginSettingsCache', \Elgg\Cache\PluginSettingsCache::class);
323
+
324
+        $this->setFactory('privateSettings', function(ServiceProvider $c) {
325
+            return new \Elgg\Database\PrivateSettingsTable($c->db, $c->entityTable, $c->pluginSettingsCache);
326
+        });
327
+
328
+        $this->setFactory('publicDb', function(ServiceProvider $c) {
329
+            return new \Elgg\Application\Database($c->db);
330
+        });
331
+
332
+        $this->setFactory('queryCounter', function(ServiceProvider $c) {
333
+            return new \Elgg\Database\QueryCounter($c->db);
334
+        }, false);
335
+
336
+        $this->setFactory('redirects', function(ServiceProvider $c) {
337
+            $url = current_page_url();
338
+            $is_xhr = $c->request->isXmlHttpRequest();
339
+            return new \Elgg\RedirectService($c->session, $is_xhr, $c->config->getSiteUrl(), $url);
340
+        });
341
+
342
+        $this->setFactory('relationshipsTable', function(ServiceProvider $c) {
343
+            return new \Elgg\Database\RelationshipsTable($c->db, $c->entityTable, $c->metadataTable, $c->events);
344
+        });
345
+
346
+        $this->setFactory('request', [\Elgg\Http\Request::class, 'createFromGlobals']);
347
+
348
+        $this->setFactory('responseFactory', function(ServiceProvider $c) {
349
+            if (PHP_SAPI === 'cli') {
350
+                $transport = new \Elgg\Http\OutputBufferTransport();
351
+            } else {
352
+                $transport = new \Elgg\Http\HttpProtocolTransport();
353
+            }
354
+            return new \Elgg\Http\ResponseFactory($c->request, $c->hooks, $c->ajax, $transport);
355
+        });
356
+
357
+        $this->setFactory('router', function(ServiceProvider $c) {
358
+            // TODO(evan): Init routes from plugins or cache
359
+            $router = new \Elgg\Router($c->hooks);
360
+            if ($c->config->getVolatile('enable_profiling')) {
361
+                $router->setTimer($c->timer);
362
+            }
363
+            return $router;
364
+        });
365
+
366
+        $this->setFactory('seeder', function(ServiceProvider $c) {
367
+            return new \Elgg\Database\Seeder($c->hooks);
368
+        });
369
+
370
+        $this->setFactory('serveFileHandler', function(ServiceProvider $c) {
371
+            return new \Elgg\Application\ServeFileHandler($c->crypto, $c->config);
372
+        });
373
+
374
+        $this->setFactory('session', function(ServiceProvider $c) {
375
+            $params = $c->config->getCookieConfig()['session'];
376
+            $options = [
377
+                // session.cache_limiter is unfortunately set to "" by the NativeSessionStorage
378
+                // constructor, so we must capture and inject it directly.
379
+                'cache_limiter' => session_cache_limiter(),
380
+
381
+                'name' => $params['name'],
382
+                'cookie_path' => $params['path'],
383
+                'cookie_domain' => $params['domain'],
384
+                'cookie_secure' => $params['secure'],
385
+                'cookie_httponly' => $params['httponly'],
386
+                'cookie_lifetime' => $params['lifetime'],
387
+            ];
388
+
389
+            $handler = new \Elgg\Http\DatabaseSessionHandler($c->db);
390
+            $storage = new NativeSessionStorage($options, $handler);
391
+            $session = new SymfonySession($storage);
392
+            return new \ElggSession($session);
393
+        });
394
+
395
+        $this->setClassName('urlSigner', \Elgg\Security\UrlSigner::class);
396
+
397
+        $this->setFactory('simpleCache', function(ServiceProvider $c) {
398
+            return new \Elgg\Cache\SimpleCache($c->config, $c->datalist, $c->views);
399
+        });
400
+
401
+        $this->setFactory('siteSecret', function(ServiceProvider $c) {
402
+            return new \Elgg\Database\SiteSecret($c->datalist);
403
+        });
404
+
405
+        $this->setClassName('stickyForms', \Elgg\Forms\StickyForms::class);
406
+
407
+        $this->setFactory('subtypeTable', function(ServiceProvider $c) {
408
+            return new \Elgg\Database\SubtypeTable($c->db);
409
+        });
410
+
411
+        $this->setFactory('systemCache', function (ServiceProvider $c) {
412
+            $cache = new \Elgg\Cache\SystemCache($c->fileCache, $c->config, $c->datalist);
413
+            if ($c->config->getVolatile('enable_profiling')) {
414
+                $cache->setTimer($c->timer);
415
+            }
416
+            return $cache;
417
+        });
418
+
419
+        $this->setFactory('systemMessages', function(ServiceProvider $c) {
420
+            return new \Elgg\SystemMessagesService($c->session);
421
+        });
422
+
423
+        $this->setClassName('table_columns', \Elgg\Views\TableColumn\ColumnFactory::class);
424
+
425
+        $this->setClassName('timer', \Elgg\Timer::class);
426
+
427
+        $this->setClassName('translator', \Elgg\I18n\Translator::class);
428
+
429
+        $this->setFactory('uploads', function(ServiceProvider $c) {
430
+            return new \Elgg\UploadService($c->request);
431
+        });
432
+
433
+        $this->setFactory('upgrades', function(ServiceProvider $c) {
434
+            return new \Elgg\UpgradeService(
435
+                $c->translator,
436
+                $c->events,
437
+                $c->hooks,
438
+                $c->datalist,
439
+                $c->logger,
440
+                $c->mutex
441
+            );
442
+        });
443
+
444
+        $this->setFactory('userCapabilities', function(ServiceProvider $c) {
445
+            return new \Elgg\UserCapabilities($c->hooks, $c->entityTable, $c->session);
446
+        });
447
+
448
+        $this->setFactory('usersTable', function(ServiceProvider $c) {
449
+            return new \Elgg\Database\UsersTable(
450
+                $c->config,
451
+                $c->db,
452
+                $c->entityTable,
453
+                $c->entityCache,
454
+                $c->events
455
+            );
456
+        });
457
+
458
+        $this->setFactory('views', function(ServiceProvider $c) {
459
+            return new \Elgg\ViewsService($c->hooks, $c->logger);
460
+        });
461
+
462
+        $this->setClassName('widgets', \Elgg\WidgetsService::class);
463
+
464
+    }
465
+
466
+    /**
467
+     * Returns the first requested service of the logger, events, and hooks. It sets the
468
+     * hooks and events up in the right order to prevent circular dependency.
469
+     *
470
+     * @param string $service_needed The service requested first
471
+     * @return mixed
472
+     */
473
+    protected function resolveLoggerDependencies($service_needed) {
474
+        $svcs['hooks'] = new \Elgg\PluginHooksService();
475
+
476
+        $svcs['logger'] = new \Elgg\Logger($svcs['hooks'], $this->config, $this->context);
477
+        $svcs['hooks']->setLogger($svcs['logger']);
478
+
479
+        $svcs['events'] = new \Elgg\EventsService();
480
+        $svcs['events']->setLogger($svcs['logger']);
481
+        if ($this->config->getVolatile('enable_profiling')) {
482
+            $svcs['events']->setTimer($this->timer);
483
+        }
484
+
485
+        foreach ($svcs as $key => $service) {
486
+            $this->setValue($key, $service);
487
+        }
488
+        return $svcs[$service_needed];
489
+    }
490 490
 }
Please login to merge, or discard this patch.
engine/classes/Elgg/Database/Seeds/Users.php 2 patches
Indentation   +100 added lines, -100 removed lines patch added patch discarded remove patch
@@ -9,105 +9,105 @@
 block discarded – undo
9 9
  */
10 10
 class Users extends Seed {
11 11
 
12
-	/**
13
-	 * {@inheritdoc}
14
-	 */
15
-	public function seed() {
16
-
17
-		$count_users = function () {
18
-			return elgg_get_entities_from_metadata([
19
-				'types' => 'user',
20
-				'metadata_names' => '__faker',
21
-				'count' => true,
22
-			]);
23
-		};
24
-
25
-		$count_friends = function ($user) {
26
-			return elgg_get_entities_from_relationship([
27
-				'types' => 'user',
28
-				'relationship' => 'friend',
29
-				'relationship_guid' => $user->guid,
30
-				'inverse_relationship' => false,
31
-				'metadata_names' => '__faker',
32
-				'count' => true,
33
-			]);
34
-		};
35
-
36
-		$exclude = [];
37
-
38
-		while ($count_users() < $this->limit) {
39
-			$user = $this->getRandomUser($exclude);
40
-			if (!$user) {
41
-				$user = $this->createUser();
42
-				if (!$user) {
43
-					continue;
44
-				}
45
-			}
46
-
47
-			$exclude[] = $user->guid;
48
-
49
-			// Friend the user other members
50
-			// Create a friend access collection and add some random friends to it
51
-
52
-			if ($count_friends($user)) {
53
-				continue;
54
-			}
55
-
56
-			$collection_id = create_access_collection('Best Fake Friends Collection', $user->guid);
57
-			if ($collection_id) {
58
-				$this->log("Created new friend collection for user $user->name [collection_id: $collection_id]");
59
-			}
60
-
61
-			$friends_limit = $this->faker->numberBetween(5, 10);
62
-
63
-			$friends_exclude = [$user->guid];
64
-			while ($count_friends($user) < $friends_limit) {
65
-
66
-				$friend = $this->getRandomUser($friends_exclude);
67
-				if (!$friend) {
68
-					$this->createUser();
69
-					if (!$friend) {
70
-						continue;
71
-					}
72
-				}
73
-
74
-				$friends_exclude[] = $friend->guid;
75
-
76
-				if ($user->addFriend($friend->guid, true)) {
77
-					$this->log("User $user->name [guid: $user->guid] friended user $friend->name [guid: $friend->guid]");
78
-					if ($this->faker->boolean() && $collection_id) {
79
-						add_user_to_access_collection($friend->guid, $collection_id);
80
-					}
81
-				}
82
-			}
83
-
84
-		}
85
-
86
-	}
87
-
88
-	/**
89
-	 * {@inheritdoc}
90
-	 */
91
-	public function unseed() {
92
-
93
-		$users = elgg_get_entities_from_metadata([
94
-			'types' => 'user',
95
-			'metadata_names' => '__faker',
96
-			'limit' => 0,
97
-			'batch' => true,
98
-		]);
99
-
100
-		/* @var $users \ElggBatch */
101
-
102
-		$users->setIncrementOffset(false);
103
-
104
-		foreach ($users as $user) {
105
-			if ($user->delete()) {
106
-				$this->log("Deleted user $user->guid");
107
-			} else {
108
-				$this->log("Failed to delete user $user->guid");
109
-			}
110
-		}
111
-	}
12
+    /**
13
+     * {@inheritdoc}
14
+     */
15
+    public function seed() {
16
+
17
+        $count_users = function () {
18
+            return elgg_get_entities_from_metadata([
19
+                'types' => 'user',
20
+                'metadata_names' => '__faker',
21
+                'count' => true,
22
+            ]);
23
+        };
24
+
25
+        $count_friends = function ($user) {
26
+            return elgg_get_entities_from_relationship([
27
+                'types' => 'user',
28
+                'relationship' => 'friend',
29
+                'relationship_guid' => $user->guid,
30
+                'inverse_relationship' => false,
31
+                'metadata_names' => '__faker',
32
+                'count' => true,
33
+            ]);
34
+        };
35
+
36
+        $exclude = [];
37
+
38
+        while ($count_users() < $this->limit) {
39
+            $user = $this->getRandomUser($exclude);
40
+            if (!$user) {
41
+                $user = $this->createUser();
42
+                if (!$user) {
43
+                    continue;
44
+                }
45
+            }
46
+
47
+            $exclude[] = $user->guid;
48
+
49
+            // Friend the user other members
50
+            // Create a friend access collection and add some random friends to it
51
+
52
+            if ($count_friends($user)) {
53
+                continue;
54
+            }
55
+
56
+            $collection_id = create_access_collection('Best Fake Friends Collection', $user->guid);
57
+            if ($collection_id) {
58
+                $this->log("Created new friend collection for user $user->name [collection_id: $collection_id]");
59
+            }
60
+
61
+            $friends_limit = $this->faker->numberBetween(5, 10);
62
+
63
+            $friends_exclude = [$user->guid];
64
+            while ($count_friends($user) < $friends_limit) {
65
+
66
+                $friend = $this->getRandomUser($friends_exclude);
67
+                if (!$friend) {
68
+                    $this->createUser();
69
+                    if (!$friend) {
70
+                        continue;
71
+                    }
72
+                }
73
+
74
+                $friends_exclude[] = $friend->guid;
75
+
76
+                if ($user->addFriend($friend->guid, true)) {
77
+                    $this->log("User $user->name [guid: $user->guid] friended user $friend->name [guid: $friend->guid]");
78
+                    if ($this->faker->boolean() && $collection_id) {
79
+                        add_user_to_access_collection($friend->guid, $collection_id);
80
+                    }
81
+                }
82
+            }
83
+
84
+        }
85
+
86
+    }
87
+
88
+    /**
89
+     * {@inheritdoc}
90
+     */
91
+    public function unseed() {
92
+
93
+        $users = elgg_get_entities_from_metadata([
94
+            'types' => 'user',
95
+            'metadata_names' => '__faker',
96
+            'limit' => 0,
97
+            'batch' => true,
98
+        ]);
99
+
100
+        /* @var $users \ElggBatch */
101
+
102
+        $users->setIncrementOffset(false);
103
+
104
+        foreach ($users as $user) {
105
+            if ($user->delete()) {
106
+                $this->log("Deleted user $user->guid");
107
+            } else {
108
+                $this->log("Failed to delete user $user->guid");
109
+            }
110
+        }
111
+    }
112 112
 
113 113
 }
114 114
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -14,7 +14,7 @@  discard block
 block discarded – undo
14 14
 	 */
15 15
 	public function seed() {
16 16
 
17
-		$count_users = function () {
17
+		$count_users = function() {
18 18
 			return elgg_get_entities_from_metadata([
19 19
 				'types' => 'user',
20 20
 				'metadata_names' => '__faker',
@@ -22,7 +22,7 @@  discard block
 block discarded – undo
22 22
 			]);
23 23
 		};
24 24
 
25
-		$count_friends = function ($user) {
25
+		$count_friends = function($user) {
26 26
 			return elgg_get_entities_from_relationship([
27 27
 				'types' => 'user',
28 28
 				'relationship' => 'friend',
Please login to merge, or discard this patch.
engine/classes/Elgg/Database/Seeds/Groups.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
 	 */
36 36
 	public function seed() {
37 37
 
38
-		$count_groups = function () {
38
+		$count_groups = function() {
39 39
 			return elgg_get_entities_from_metadata([
40 40
 				'types' => 'group',
41 41
 				'metadata_names' => '__faker',
@@ -43,7 +43,7 @@  discard block
 block discarded – undo
43 43
 			]);
44 44
 		};
45 45
 
46
-		$count_members = function ($group) {
46
+		$count_members = function($group) {
47 47
 			return elgg_get_entities_from_relationship([
48 48
 				'types' => 'user',
49 49
 				'relationship' => 'member',
Please login to merge, or discard this patch.
Indentation   +169 added lines, -169 removed lines patch added patch discarded remove patch
@@ -9,173 +9,173 @@
 block discarded – undo
9 9
  */
10 10
 class Groups extends Seed {
11 11
 
12
-	/**
13
-	 * @var \ElggUser[]
14
-	 */
15
-	private $users;
16
-
17
-	private $visibility = [
18
-		ACCESS_PUBLIC,
19
-		ACCESS_LOGGED_IN,
20
-		ACCESS_PRIVATE,
21
-	];
22
-
23
-	private $content_access_modes = [
24
-		\ElggGroup::CONTENT_ACCESS_MODE_MEMBERS_ONLY,
25
-		\ElggGroup::CONTENT_ACCESS_MODE_UNRESTRICTED,
26
-	];
27
-
28
-	private $membership = [
29
-		ACCESS_PUBLIC,
30
-		ACCESS_PRIVATE,
31
-	];
32
-
33
-	/**
34
-	 * {@inheritdoc}
35
-	 */
36
-	public function seed() {
37
-
38
-		$count_groups = function () {
39
-			return elgg_get_entities_from_metadata([
40
-				'types' => 'group',
41
-				'metadata_names' => '__faker',
42
-				'count' => true,
43
-			]);
44
-		};
45
-
46
-		$count_members = function ($group) {
47
-			return elgg_get_entities_from_relationship([
48
-				'types' => 'user',
49
-				'relationship' => 'member',
50
-				'relationship_guid' => $group->getGUID(),
51
-				'inverse_relationship' => true,
52
-				'metadata_names' => '__faker',
53
-				'count' => true,
54
-			]);
55
-		};
56
-
57
-		$exclude = [];
58
-
59
-		while ($count_groups() < $this->limit) {
60
-			$group = $this->getRandomGroup($exclude);
61
-			if (!$group) {
62
-				$group = $this->createGroup([
63
-					'access_id' => $this->getRandomVisibility(),
64
-				], [
65
-					'content_access_mode' => $this->getRandomContentAccessMode(),
66
-					'membership' => $this->getRandomMembership(),
67
-				]);
68
-				if (!$group) {
69
-					continue;
70
-				}
71
-			}
72
-
73
-			$exclude[] = $group->guid;
74
-
75
-			if ($count_members($group) > 1) {
76
-				// exclude owner from count
77
-				continue;
78
-			}
79
-
80
-			$members_limit = $this->faker->numberBetween(5, 10);
81
-
82
-			$members_exclude = [];
83
-
84
-			while ($count_members($group) - 1 < $members_limit) {
85
-
86
-				$member = $this->getRandomUser($members_exclude);
87
-				if (!$member) {
88
-					$member = $this->createUser();
89
-					if (!$member) {
90
-						continue;
91
-					}
92
-				}
93
-
94
-				$members_exclude[] = $member->guid;
95
-
96
-				if ($group->join($member)) {
97
-					$this->log("User $member->name [guid: $member->guid] joined group $group->name [guid: $group->guid]");
98
-				}
99
-
100
-				if (!$group->isPublicMembership()) {
101
-					$invitee = $this->getRandomUser($members_exclude);
102
-					if ($invitee) {
103
-						$members_exclude[] = $invitee->guid;
104
-						if (!check_entity_relationship($invitee->guid, 'member', $group->guid)) {
105
-							add_entity_relationship($group->guid, 'invited', $invitee->guid);
106
-							$this->log("User $invitee->name [guid: $invitee->guid] was invited to $group->name [guid: $group->guid]");
107
-						}
108
-					}
109
-
110
-					$requestor = $this->getRandomUser($members_exclude);
111
-					if ($requestor) {
112
-						$members_exclude[] = $requestor->guid;
113
-						if (!check_entity_relationship($group->guid, 'invited', $requestor->guid)
114
-							&& !check_entity_relationship($requestor->guid, 'member', $group->guid)
115
-						) {
116
-							add_entity_relationship($requestor->guid, 'membership_request', $group->guid);
117
-							$this->log("User $invitee->name [guid: $invitee->guid] requested to join $group->name [guid: $group->guid]");
118
-						}
119
-					}
120
-				}
121
-			}
122
-
123
-		}
124
-
125
-	}
126
-
127
-	/**
128
-	 * {@inheritdoc}
129
-	 */
130
-	public function unseed() {
131
-
132
-		$groups = elgg_get_entities_from_metadata([
133
-			'types' => 'group',
134
-			'metadata_names' => '__faker',
135
-			'limit' => 0,
136
-			'batch' => true,
137
-		]);
138
-
139
-		/* @var $groups \ElggBatch */
140
-
141
-		$groups->setIncrementOffset(false);
142
-
143
-		foreach ($groups as $group) {
144
-			if ($group->delete()) {
145
-				$this->log("Deleted group $group->guid");
146
-			} else {
147
-				$this->log("Failed to delete group $group->guid");
148
-			}
149
-		}
150
-	}
151
-
152
-	/**
153
-	 * Returns random visibility value
154
-	 * @return int
155
-	 */
156
-	public function getRandomVisibility() {
157
-		$key = array_rand($this->visibility, 1);
158
-
159
-		return $this->visibility[$key];
160
-	}
161
-
162
-	/**
163
-	 * Returns random content access mode value
164
-	 * @return string
165
-	 */
166
-	public function getRandomContentAccessMode() {
167
-		$key = array_rand($this->content_access_modes, 1);
168
-
169
-		return $this->content_access_modes[$key];
170
-	}
171
-
172
-	/**
173
-	 * Returns random membership mode
174
-	 * @return mixed
175
-	 */
176
-	public function getRandomMembership() {
177
-		$key = array_rand($this->membership, 1);
178
-
179
-		return $this->membership[$key];
180
-	}
12
+    /**
13
+     * @var \ElggUser[]
14
+     */
15
+    private $users;
16
+
17
+    private $visibility = [
18
+        ACCESS_PUBLIC,
19
+        ACCESS_LOGGED_IN,
20
+        ACCESS_PRIVATE,
21
+    ];
22
+
23
+    private $content_access_modes = [
24
+        \ElggGroup::CONTENT_ACCESS_MODE_MEMBERS_ONLY,
25
+        \ElggGroup::CONTENT_ACCESS_MODE_UNRESTRICTED,
26
+    ];
27
+
28
+    private $membership = [
29
+        ACCESS_PUBLIC,
30
+        ACCESS_PRIVATE,
31
+    ];
32
+
33
+    /**
34
+     * {@inheritdoc}
35
+     */
36
+    public function seed() {
37
+
38
+        $count_groups = function () {
39
+            return elgg_get_entities_from_metadata([
40
+                'types' => 'group',
41
+                'metadata_names' => '__faker',
42
+                'count' => true,
43
+            ]);
44
+        };
45
+
46
+        $count_members = function ($group) {
47
+            return elgg_get_entities_from_relationship([
48
+                'types' => 'user',
49
+                'relationship' => 'member',
50
+                'relationship_guid' => $group->getGUID(),
51
+                'inverse_relationship' => true,
52
+                'metadata_names' => '__faker',
53
+                'count' => true,
54
+            ]);
55
+        };
56
+
57
+        $exclude = [];
58
+
59
+        while ($count_groups() < $this->limit) {
60
+            $group = $this->getRandomGroup($exclude);
61
+            if (!$group) {
62
+                $group = $this->createGroup([
63
+                    'access_id' => $this->getRandomVisibility(),
64
+                ], [
65
+                    'content_access_mode' => $this->getRandomContentAccessMode(),
66
+                    'membership' => $this->getRandomMembership(),
67
+                ]);
68
+                if (!$group) {
69
+                    continue;
70
+                }
71
+            }
72
+
73
+            $exclude[] = $group->guid;
74
+
75
+            if ($count_members($group) > 1) {
76
+                // exclude owner from count
77
+                continue;
78
+            }
79
+
80
+            $members_limit = $this->faker->numberBetween(5, 10);
81
+
82
+            $members_exclude = [];
83
+
84
+            while ($count_members($group) - 1 < $members_limit) {
85
+
86
+                $member = $this->getRandomUser($members_exclude);
87
+                if (!$member) {
88
+                    $member = $this->createUser();
89
+                    if (!$member) {
90
+                        continue;
91
+                    }
92
+                }
93
+
94
+                $members_exclude[] = $member->guid;
95
+
96
+                if ($group->join($member)) {
97
+                    $this->log("User $member->name [guid: $member->guid] joined group $group->name [guid: $group->guid]");
98
+                }
99
+
100
+                if (!$group->isPublicMembership()) {
101
+                    $invitee = $this->getRandomUser($members_exclude);
102
+                    if ($invitee) {
103
+                        $members_exclude[] = $invitee->guid;
104
+                        if (!check_entity_relationship($invitee->guid, 'member', $group->guid)) {
105
+                            add_entity_relationship($group->guid, 'invited', $invitee->guid);
106
+                            $this->log("User $invitee->name [guid: $invitee->guid] was invited to $group->name [guid: $group->guid]");
107
+                        }
108
+                    }
109
+
110
+                    $requestor = $this->getRandomUser($members_exclude);
111
+                    if ($requestor) {
112
+                        $members_exclude[] = $requestor->guid;
113
+                        if (!check_entity_relationship($group->guid, 'invited', $requestor->guid)
114
+                            && !check_entity_relationship($requestor->guid, 'member', $group->guid)
115
+                        ) {
116
+                            add_entity_relationship($requestor->guid, 'membership_request', $group->guid);
117
+                            $this->log("User $invitee->name [guid: $invitee->guid] requested to join $group->name [guid: $group->guid]");
118
+                        }
119
+                    }
120
+                }
121
+            }
122
+
123
+        }
124
+
125
+    }
126
+
127
+    /**
128
+     * {@inheritdoc}
129
+     */
130
+    public function unseed() {
131
+
132
+        $groups = elgg_get_entities_from_metadata([
133
+            'types' => 'group',
134
+            'metadata_names' => '__faker',
135
+            'limit' => 0,
136
+            'batch' => true,
137
+        ]);
138
+
139
+        /* @var $groups \ElggBatch */
140
+
141
+        $groups->setIncrementOffset(false);
142
+
143
+        foreach ($groups as $group) {
144
+            if ($group->delete()) {
145
+                $this->log("Deleted group $group->guid");
146
+            } else {
147
+                $this->log("Failed to delete group $group->guid");
148
+            }
149
+        }
150
+    }
151
+
152
+    /**
153
+     * Returns random visibility value
154
+     * @return int
155
+     */
156
+    public function getRandomVisibility() {
157
+        $key = array_rand($this->visibility, 1);
158
+
159
+        return $this->visibility[$key];
160
+    }
161
+
162
+    /**
163
+     * Returns random content access mode value
164
+     * @return string
165
+     */
166
+    public function getRandomContentAccessMode() {
167
+        $key = array_rand($this->content_access_modes, 1);
168
+
169
+        return $this->content_access_modes[$key];
170
+    }
171
+
172
+    /**
173
+     * Returns random membership mode
174
+     * @return mixed
175
+     */
176
+    public function getRandomMembership() {
177
+        $key = array_rand($this->membership, 1);
178
+
179
+        return $this->membership[$key];
180
+    }
181 181
 }
182 182
\ No newline at end of file
Please login to merge, or discard this patch.
engine/classes/ElggPlugin.php 1 patch
Indentation   +1140 added lines, -1140 removed lines patch added patch discarded remove patch
@@ -12,1182 +12,1182 @@
 block discarded – undo
12 12
  * @subpackage Plugins.Settings
13 13
  */
14 14
 class ElggPlugin extends \ElggObject {
15
-	private $package;
16
-	private $manifest;
17
-
18
-	/**
19
-	 * Data from static config file. null if not yet read.
20
-	 *
21
-	 * @var array|null
22
-	 */
23
-	private $static_config;
24
-
25
-	private $path;
26
-	private $errorMsg = '';
27
-
28
-	/**
29
-	 * Set subtype to 'plugin'
30
-	 *
31
-	 * @return void
32
-	 */
33
-	protected function initializeAttributes() {
34
-		parent::initializeAttributes();
35
-
36
-		$this->attributes['subtype'] = "plugin";
37
-
38
-		// plugins must be public.
39
-		$this->access_id = ACCESS_PUBLIC;
40
-	}
41
-
42
-	/**
43
-	 * Creates a new plugin from path
44
-	 *
45
-	 * @note Internal: also supports database objects
46
-	 *
47
-	 * @warning Unlike other \ElggEntity objects, you cannot null instantiate
48
-	 *          \ElggPlugin. You must provide the path to the plugin directory.
49
-	 *
50
-	 * @param string $path The absolute path of the plugin
51
-	 *
52
-	 * @throws PluginException
53
-	 */
54
-	public function __construct($path) {
55
-		if (!$path) {
56
-			throw new \PluginException("ElggPlugin cannot be null instantiated. You must pass a full path.");
57
-		}
58
-
59
-		if (is_object($path)) {
60
-			// database object
61
-			parent::__construct($path);
62
-			$this->path = _elgg_services()->config->getPluginsPath() . $this->getID();
63
-		} else if (is_numeric($path)) {
64
-			// guid
65
-			// @todo plugins with directory names of '12345'
66
-			elgg_deprecated_notice("Use elgg_get_plugin_from_id() to load a plugin.", 1.9);
67
-			parent::__construct($path);
68
-			$this->path = _elgg_services()->config->getPluginsPath() . $this->getID();
69
-		} else {
70
-			$this->initializeAttributes();
15
+    private $package;
16
+    private $manifest;
17
+
18
+    /**
19
+     * Data from static config file. null if not yet read.
20
+     *
21
+     * @var array|null
22
+     */
23
+    private $static_config;
24
+
25
+    private $path;
26
+    private $errorMsg = '';
27
+
28
+    /**
29
+     * Set subtype to 'plugin'
30
+     *
31
+     * @return void
32
+     */
33
+    protected function initializeAttributes() {
34
+        parent::initializeAttributes();
35
+
36
+        $this->attributes['subtype'] = "plugin";
37
+
38
+        // plugins must be public.
39
+        $this->access_id = ACCESS_PUBLIC;
40
+    }
41
+
42
+    /**
43
+     * Creates a new plugin from path
44
+     *
45
+     * @note Internal: also supports database objects
46
+     *
47
+     * @warning Unlike other \ElggEntity objects, you cannot null instantiate
48
+     *          \ElggPlugin. You must provide the path to the plugin directory.
49
+     *
50
+     * @param string $path The absolute path of the plugin
51
+     *
52
+     * @throws PluginException
53
+     */
54
+    public function __construct($path) {
55
+        if (!$path) {
56
+            throw new \PluginException("ElggPlugin cannot be null instantiated. You must pass a full path.");
57
+        }
58
+
59
+        if (is_object($path)) {
60
+            // database object
61
+            parent::__construct($path);
62
+            $this->path = _elgg_services()->config->getPluginsPath() . $this->getID();
63
+        } else if (is_numeric($path)) {
64
+            // guid
65
+            // @todo plugins with directory names of '12345'
66
+            elgg_deprecated_notice("Use elgg_get_plugin_from_id() to load a plugin.", 1.9);
67
+            parent::__construct($path);
68
+            $this->path = _elgg_services()->config->getPluginsPath() . $this->getID();
69
+        } else {
70
+            $this->initializeAttributes();
71 71
 			
72
-			$mod_dir = _elgg_services()->config->getPluginsPath();
73
-
74
-			// not a full path, so assume a directory name and use the default path
75
-			if (strpos($path, $mod_dir) !== 0) {
76
-				elgg_deprecated_notice("You should pass a full path to ElggPlugin.", 1.9);
77
-				$path = $mod_dir . $path;
78
-			}
79
-
80
-			// path checking is done in the package
81
-			$path = sanitise_filepath($path);
82
-			$this->path = $path;
83
-			$path_parts = explode('/', rtrim($path, '/'));
84
-			$plugin_id = array_pop($path_parts);
85
-			$this->title = $plugin_id;
86
-
87
-			// check if we're loading an existing plugin
88
-			$existing_plugin = elgg_get_plugin_from_id($plugin_id);
72
+            $mod_dir = _elgg_services()->config->getPluginsPath();
73
+
74
+            // not a full path, so assume a directory name and use the default path
75
+            if (strpos($path, $mod_dir) !== 0) {
76
+                elgg_deprecated_notice("You should pass a full path to ElggPlugin.", 1.9);
77
+                $path = $mod_dir . $path;
78
+            }
79
+
80
+            // path checking is done in the package
81
+            $path = sanitise_filepath($path);
82
+            $this->path = $path;
83
+            $path_parts = explode('/', rtrim($path, '/'));
84
+            $plugin_id = array_pop($path_parts);
85
+            $this->title = $plugin_id;
86
+
87
+            // check if we're loading an existing plugin
88
+            $existing_plugin = elgg_get_plugin_from_id($plugin_id);
89 89
 			
90
-			if ($existing_plugin) {
91
-				$this->load($existing_plugin->guid);
92
-			}
93
-		}
94
-
95
-		_elgg_cache_plugin_by_id($this);
96
-	}
97
-
98
-	/**
99
-	 * Save the plugin object.  Make sure required values exist.
100
-	 *
101
-	 * @see \ElggObject::save()
102
-	 * @return bool
103
-	 */
104
-	public function save() {
105
-		// own by the current site so users can be deleted without affecting plugins
106
-		$site = _elgg_services()->configTable->get('site');
107
-		$this->attributes['site_guid'] = $site->guid;
108
-		$this->attributes['owner_guid'] = $site->guid;
109
-		$this->attributes['container_guid'] = $site->guid;
90
+            if ($existing_plugin) {
91
+                $this->load($existing_plugin->guid);
92
+            }
93
+        }
94
+
95
+        _elgg_cache_plugin_by_id($this);
96
+    }
97
+
98
+    /**
99
+     * Save the plugin object.  Make sure required values exist.
100
+     *
101
+     * @see \ElggObject::save()
102
+     * @return bool
103
+     */
104
+    public function save() {
105
+        // own by the current site so users can be deleted without affecting plugins
106
+        $site = _elgg_services()->configTable->get('site');
107
+        $this->attributes['site_guid'] = $site->guid;
108
+        $this->attributes['owner_guid'] = $site->guid;
109
+        $this->attributes['container_guid'] = $site->guid;
110 110
 		
111
-		if (parent::save()) {
112
-			// make sure we have a priority
113
-			$priority = $this->getPriority();
114
-			if ($priority === false || $priority === null) {
115
-				return $this->setPriority('last');
116
-			}
117
-		} else {
118
-			return false;
119
-		}
120
-	}
121
-
122
-
123
-	// Plugin ID and path
124
-
125
-	/**
126
-	 * Returns the ID (dir name) of this plugin
127
-	 *
128
-	 * @return string
129
-	 */
130
-	public function getID() {
131
-		return $this->title;
132
-	}
133
-
134
-	/**
135
-	 * Returns the manifest's name if available, otherwise the ID.
136
-	 *
137
-	 * @return string
138
-	 * @since 1.8.1
139
-	 */
140
-	public function getFriendlyName() {
141
-		$manifest = $this->getManifest();
142
-		if ($manifest) {
143
-			return $manifest->getName();
144
-		}
145
-
146
-		return $this->getID();
147
-	}
148
-
149
-	/**
150
-	 * Returns the plugin's full path with trailing slash.
151
-	 *
152
-	 * @return string
153
-	 */
154
-	public function getPath() {
155
-		return sanitise_filepath($this->path);
156
-	}
157
-
158
-	/**
159
-	 * Get a value from the plugins's static config file.
160
-	 *
161
-	 * @note If the system cache is on, Elgg APIs should not call this on every request.
162
-	 *
163
-	 * @param string $key     Config key
164
-	 * @param mixed  $default Value returned if missing
165
-	 *
166
-	 * @return mixed
167
-	 * @throws PluginException
168
-	 * @access private
169
-	 * @internal For Elgg internal use only
170
-	 */
171
-	public function getStaticConfig($key, $default = null) {
172
-		if ($this->static_config === null) {
173
-			$this->static_config = [];
174
-
175
-			if ($this->canReadFile(ElggPluginPackage::STATIC_CONFIG_FILENAME)) {
176
-				$this->static_config = $this->includeFile(ElggPluginPackage::STATIC_CONFIG_FILENAME);
177
-			}
178
-		}
179
-
180
-		if (array_key_exists($key, $this->static_config)) {
181
-			return $this->static_config[$key];
182
-		} else {
183
-			return $default;
184
-		}
185
-	}
186
-
187
-	/**
188
-	 * Sets the location of this plugin.
189
-	 *
190
-	 * @param string $id The path to the plugin's dir.
191
-	 * @return bool
192
-	 */
193
-	public function setID($id) {
194
-		return $this->attributes['title'] = $id;
195
-	}
196
-
197
-	/**
198
-	 * Returns an array of available markdown files for this plugin
199
-	 *
200
-	 * @return array
201
-	 */
202
-	public function getAvailableTextFiles() {
203
-		$filenames = $this->getPackage()->getTextFilenames();
204
-
205
-		$files = array();
206
-		foreach ($filenames as $filename) {
207
-			if ($this->canReadFile($filename)) {
208
-				$files[$filename] = "$this->path/$filename";
209
-			}
210
-		}
211
-
212
-		return $files;
213
-	}
214
-
215
-	// Load Priority
216
-
217
-	/**
218
-	 * Gets the plugin's load priority.
219
-	 *
220
-	 * @return int
221
-	 */
222
-	public function getPriority() {
223
-		$name = _elgg_namespace_plugin_private_setting('internal', 'priority');
224
-		return $this->$name;
225
-	}
226
-
227
-	/**
228
-	 * Sets the priority of the plugin
229
-	 *
230
-	 * @param mixed $priority  The priority to set. One of +1, -1, first, last, or a number.
231
-	 *                         If given a number, this will displace all plugins at that number
232
-	 *                         and set their priorities +1
233
-	 * @param mixed $site_guid Optional site GUID.
234
-	 * @return bool
235
-	 */
236
-	public function setPriority($priority, $site_guid = null) {
237
-		if (!$this->guid) {
238
-			return false;
239
-		}
240
-
241
-		$db_prefix = _elgg_services()->configTable->get('dbprefix');
242
-		$name = _elgg_namespace_plugin_private_setting('internal', 'priority');
243
-		// if no priority assume a priority of 1
244
-		$old_priority = (int) $this->getPriority();
245
-		$old_priority = (!$old_priority) ? 1 : $old_priority;
246
-		$max_priority = _elgg_get_max_plugin_priority();
247
-
248
-		// can't use switch here because it's not strict and
249
-		// php evaluates +1 == 1
250
-		if ($priority === '+1') {
251
-			$priority = $old_priority + 1;
252
-		} elseif ($priority === '-1') {
253
-			$priority = $old_priority - 1;
254
-		} elseif ($priority === 'first') {
255
-			$priority = 1;
256
-		} elseif ($priority === 'last') {
257
-			$priority = $max_priority;
258
-		}
259
-
260
-		// should be a number by now
261
-		if ($priority > 0) {
262
-			if (!is_numeric($priority)) {
263
-				return false;
264
-			}
265
-
266
-			// there's nothing above the max.
267
-			if ($priority > $max_priority) {
268
-				$priority = $max_priority;
269
-			}
270
-
271
-			// there's nothing below 1.
272
-			if ($priority < 1) {
273
-				$priority = 1;
274
-			}
275
-
276
-			if ($priority > $old_priority) {
277
-				$op = '-';
278
-				$where = "CAST(value as unsigned) BETWEEN $old_priority AND $priority";
279
-			} else {
280
-				$op = '+';
281
-				$where = "CAST(value as unsigned) BETWEEN $priority AND $old_priority";
282
-			}
283
-
284
-			// displace the ones affected by this change
285
-			$q = "UPDATE {$db_prefix}private_settings
111
+        if (parent::save()) {
112
+            // make sure we have a priority
113
+            $priority = $this->getPriority();
114
+            if ($priority === false || $priority === null) {
115
+                return $this->setPriority('last');
116
+            }
117
+        } else {
118
+            return false;
119
+        }
120
+    }
121
+
122
+
123
+    // Plugin ID and path
124
+
125
+    /**
126
+     * Returns the ID (dir name) of this plugin
127
+     *
128
+     * @return string
129
+     */
130
+    public function getID() {
131
+        return $this->title;
132
+    }
133
+
134
+    /**
135
+     * Returns the manifest's name if available, otherwise the ID.
136
+     *
137
+     * @return string
138
+     * @since 1.8.1
139
+     */
140
+    public function getFriendlyName() {
141
+        $manifest = $this->getManifest();
142
+        if ($manifest) {
143
+            return $manifest->getName();
144
+        }
145
+
146
+        return $this->getID();
147
+    }
148
+
149
+    /**
150
+     * Returns the plugin's full path with trailing slash.
151
+     *
152
+     * @return string
153
+     */
154
+    public function getPath() {
155
+        return sanitise_filepath($this->path);
156
+    }
157
+
158
+    /**
159
+     * Get a value from the plugins's static config file.
160
+     *
161
+     * @note If the system cache is on, Elgg APIs should not call this on every request.
162
+     *
163
+     * @param string $key     Config key
164
+     * @param mixed  $default Value returned if missing
165
+     *
166
+     * @return mixed
167
+     * @throws PluginException
168
+     * @access private
169
+     * @internal For Elgg internal use only
170
+     */
171
+    public function getStaticConfig($key, $default = null) {
172
+        if ($this->static_config === null) {
173
+            $this->static_config = [];
174
+
175
+            if ($this->canReadFile(ElggPluginPackage::STATIC_CONFIG_FILENAME)) {
176
+                $this->static_config = $this->includeFile(ElggPluginPackage::STATIC_CONFIG_FILENAME);
177
+            }
178
+        }
179
+
180
+        if (array_key_exists($key, $this->static_config)) {
181
+            return $this->static_config[$key];
182
+        } else {
183
+            return $default;
184
+        }
185
+    }
186
+
187
+    /**
188
+     * Sets the location of this plugin.
189
+     *
190
+     * @param string $id The path to the plugin's dir.
191
+     * @return bool
192
+     */
193
+    public function setID($id) {
194
+        return $this->attributes['title'] = $id;
195
+    }
196
+
197
+    /**
198
+     * Returns an array of available markdown files for this plugin
199
+     *
200
+     * @return array
201
+     */
202
+    public function getAvailableTextFiles() {
203
+        $filenames = $this->getPackage()->getTextFilenames();
204
+
205
+        $files = array();
206
+        foreach ($filenames as $filename) {
207
+            if ($this->canReadFile($filename)) {
208
+                $files[$filename] = "$this->path/$filename";
209
+            }
210
+        }
211
+
212
+        return $files;
213
+    }
214
+
215
+    // Load Priority
216
+
217
+    /**
218
+     * Gets the plugin's load priority.
219
+     *
220
+     * @return int
221
+     */
222
+    public function getPriority() {
223
+        $name = _elgg_namespace_plugin_private_setting('internal', 'priority');
224
+        return $this->$name;
225
+    }
226
+
227
+    /**
228
+     * Sets the priority of the plugin
229
+     *
230
+     * @param mixed $priority  The priority to set. One of +1, -1, first, last, or a number.
231
+     *                         If given a number, this will displace all plugins at that number
232
+     *                         and set their priorities +1
233
+     * @param mixed $site_guid Optional site GUID.
234
+     * @return bool
235
+     */
236
+    public function setPriority($priority, $site_guid = null) {
237
+        if (!$this->guid) {
238
+            return false;
239
+        }
240
+
241
+        $db_prefix = _elgg_services()->configTable->get('dbprefix');
242
+        $name = _elgg_namespace_plugin_private_setting('internal', 'priority');
243
+        // if no priority assume a priority of 1
244
+        $old_priority = (int) $this->getPriority();
245
+        $old_priority = (!$old_priority) ? 1 : $old_priority;
246
+        $max_priority = _elgg_get_max_plugin_priority();
247
+
248
+        // can't use switch here because it's not strict and
249
+        // php evaluates +1 == 1
250
+        if ($priority === '+1') {
251
+            $priority = $old_priority + 1;
252
+        } elseif ($priority === '-1') {
253
+            $priority = $old_priority - 1;
254
+        } elseif ($priority === 'first') {
255
+            $priority = 1;
256
+        } elseif ($priority === 'last') {
257
+            $priority = $max_priority;
258
+        }
259
+
260
+        // should be a number by now
261
+        if ($priority > 0) {
262
+            if (!is_numeric($priority)) {
263
+                return false;
264
+            }
265
+
266
+            // there's nothing above the max.
267
+            if ($priority > $max_priority) {
268
+                $priority = $max_priority;
269
+            }
270
+
271
+            // there's nothing below 1.
272
+            if ($priority < 1) {
273
+                $priority = 1;
274
+            }
275
+
276
+            if ($priority > $old_priority) {
277
+                $op = '-';
278
+                $where = "CAST(value as unsigned) BETWEEN $old_priority AND $priority";
279
+            } else {
280
+                $op = '+';
281
+                $where = "CAST(value as unsigned) BETWEEN $priority AND $old_priority";
282
+            }
283
+
284
+            // displace the ones affected by this change
285
+            $q = "UPDATE {$db_prefix}private_settings
286 286
 				SET value = CAST(value as unsigned) $op 1
287 287
 				WHERE entity_guid != $this->guid
288 288
 				AND name = '$name'
289 289
 				AND $where";
290 290
 
291
-			if (!$this->getDatabase()->updateData($q)) {
292
-				return false;
293
-			}
294
-
295
-			// set this priority
296
-			if ($this->setPrivateSetting($name, $priority)) {
297
-				return true;
298
-			} else {
299
-				return false;
300
-			}
301
-		}
302
-
303
-		return false;
304
-	}
305
-
306
-
307
-	// Plugin settings
308
-
309
-	/**
310
-	 * Returns a plugin setting
311
-	 *
312
-	 * @param string $name    The setting name
313
-	 * @param mixed  $default The default value to return if none is set
314
-	 * @return mixed
315
-	 */
316
-	public function getSetting($name, $default = null) {
317
-		$values = _elgg_services()->pluginSettingsCache->getAll($this->guid);
318
-
319
-		if ($values !== null) {
320
-			return isset($values[$name]) ? $values[$name] : $default;
321
-		}
322
-
323
-		$val = $this->$name;
324
-		return $val !== null ? $val : $default;
325
-	}
326
-
327
-	/**
328
-	 * Returns an array of all settings saved for this plugin.
329
-	 *
330
-	 * @note Unlike user settings, plugin settings are not namespaced.
331
-	 *
332
-	 * @return array An array of key/value pairs.
333
-	 */
334
-	public function getAllSettings() {
335
-		$values = _elgg_services()->pluginSettingsCache->getAll($this->guid);
336
-		if ($values !== null) {
337
-			return $values;
338
-		}
339
-
340
-		if (!$this->guid) {
341
-			return false;
342
-		}
343
-
344
-		$db_prefix = _elgg_services()->config->get('dbprefix');
345
-		// need to remove all namespaced private settings.
346
-		$us_prefix = _elgg_namespace_plugin_private_setting('user_setting', '', $this->getID());
347
-		$is_prefix = _elgg_namespace_plugin_private_setting('internal', '', $this->getID());
348
-
349
-		// Get private settings for user
350
-		$q = "SELECT * FROM {$db_prefix}private_settings
291
+            if (!$this->getDatabase()->updateData($q)) {
292
+                return false;
293
+            }
294
+
295
+            // set this priority
296
+            if ($this->setPrivateSetting($name, $priority)) {
297
+                return true;
298
+            } else {
299
+                return false;
300
+            }
301
+        }
302
+
303
+        return false;
304
+    }
305
+
306
+
307
+    // Plugin settings
308
+
309
+    /**
310
+     * Returns a plugin setting
311
+     *
312
+     * @param string $name    The setting name
313
+     * @param mixed  $default The default value to return if none is set
314
+     * @return mixed
315
+     */
316
+    public function getSetting($name, $default = null) {
317
+        $values = _elgg_services()->pluginSettingsCache->getAll($this->guid);
318
+
319
+        if ($values !== null) {
320
+            return isset($values[$name]) ? $values[$name] : $default;
321
+        }
322
+
323
+        $val = $this->$name;
324
+        return $val !== null ? $val : $default;
325
+    }
326
+
327
+    /**
328
+     * Returns an array of all settings saved for this plugin.
329
+     *
330
+     * @note Unlike user settings, plugin settings are not namespaced.
331
+     *
332
+     * @return array An array of key/value pairs.
333
+     */
334
+    public function getAllSettings() {
335
+        $values = _elgg_services()->pluginSettingsCache->getAll($this->guid);
336
+        if ($values !== null) {
337
+            return $values;
338
+        }
339
+
340
+        if (!$this->guid) {
341
+            return false;
342
+        }
343
+
344
+        $db_prefix = _elgg_services()->config->get('dbprefix');
345
+        // need to remove all namespaced private settings.
346
+        $us_prefix = _elgg_namespace_plugin_private_setting('user_setting', '', $this->getID());
347
+        $is_prefix = _elgg_namespace_plugin_private_setting('internal', '', $this->getID());
348
+
349
+        // Get private settings for user
350
+        $q = "SELECT * FROM {$db_prefix}private_settings
351 351
 			WHERE entity_guid = $this->guid
352 352
 			AND name NOT LIKE '$us_prefix%'
353 353
 			AND name NOT LIKE '$is_prefix%'";
354 354
 
355
-		$private_settings = $this->getDatabase()->getData($q);
356
-
357
-		$return = array();
358
-
359
-		if ($private_settings) {
360
-			foreach ($private_settings as $setting) {
361
-				$return[$setting->name] = $setting->value;
362
-			}
363
-		}
364
-
365
-		return $return;
366
-	}
367
-
368
-	/**
369
-	 * Set a plugin setting for the plugin
370
-	 *
371
-	 * @todo This will only work once the plugin has a GUID.
372
-	 *
373
-	 * @param string $name  The name to set
374
-	 * @param string $value The value to set
375
-	 *
376
-	 * @return bool
377
-	 */
378
-	public function setSetting($name, $value) {
379
-		if (!$this->guid) {
380
-			return false;
381
-		}
355
+        $private_settings = $this->getDatabase()->getData($q);
356
+
357
+        $return = array();
358
+
359
+        if ($private_settings) {
360
+            foreach ($private_settings as $setting) {
361
+                $return[$setting->name] = $setting->value;
362
+            }
363
+        }
364
+
365
+        return $return;
366
+    }
367
+
368
+    /**
369
+     * Set a plugin setting for the plugin
370
+     *
371
+     * @todo This will only work once the plugin has a GUID.
372
+     *
373
+     * @param string $name  The name to set
374
+     * @param string $value The value to set
375
+     *
376
+     * @return bool
377
+     */
378
+    public function setSetting($name, $value) {
379
+        if (!$this->guid) {
380
+            return false;
381
+        }
382 382
 		
383
-		// Hook to validate setting
384
-		$value = elgg_trigger_plugin_hook('setting', 'plugin', array(
385
-			'plugin_id' => $this->getID(),
386
-			'plugin' => $this,
387
-			'name' => $name,
388
-			'value' => $value,
389
-		), $value);
383
+        // Hook to validate setting
384
+        $value = elgg_trigger_plugin_hook('setting', 'plugin', array(
385
+            'plugin_id' => $this->getID(),
386
+            'plugin' => $this,
387
+            'name' => $name,
388
+            'value' => $value,
389
+        ), $value);
390 390
 		
391
-		if (is_array($value)) {
392
-			elgg_log('Plugin settings cannot store arrays.', 'ERROR');
393
-			return false;
394
-		}
391
+        if (is_array($value)) {
392
+            elgg_log('Plugin settings cannot store arrays.', 'ERROR');
393
+            return false;
394
+        }
395 395
 		
396
-		return $this->setPrivateSetting($name, $value);
397
-	}
398
-
399
-	/**
400
-	 * Removes a plugin setting name and value.
401
-	 *
402
-	 * @param string $name The setting name to remove
403
-	 *
404
-	 * @return bool
405
-	 */
406
-	public function unsetSetting($name) {
407
-		return remove_private_setting($this->guid, $name);
408
-	}
409
-
410
-	/**
411
-	 * Removes all settings for this plugin.
412
-	 *
413
-	 * @todo Should be a better way to do this without dropping to raw SQL.
414
-	 * @todo If we could namespace the plugin settings this would be cleaner.
415
-	 * @todo this shouldn't work because ps_prefix will be empty string
416
-	 * @return bool
417
-	 */
418
-	public function unsetAllSettings() {
419
-		_elgg_services()->pluginSettingsCache->clear($this->guid);
420
-		_elgg_services()->boot->invalidateCache();
421
-
422
-		$db_prefix = _elgg_services()->configTable->get('dbprefix');
423
-		$us_prefix = _elgg_namespace_plugin_private_setting('user_setting', '', $this->getID());
424
-		$is_prefix = _elgg_namespace_plugin_private_setting('internal', '', $this->getID());
425
-
426
-		$q = "DELETE FROM {$db_prefix}private_settings
396
+        return $this->setPrivateSetting($name, $value);
397
+    }
398
+
399
+    /**
400
+     * Removes a plugin setting name and value.
401
+     *
402
+     * @param string $name The setting name to remove
403
+     *
404
+     * @return bool
405
+     */
406
+    public function unsetSetting($name) {
407
+        return remove_private_setting($this->guid, $name);
408
+    }
409
+
410
+    /**
411
+     * Removes all settings for this plugin.
412
+     *
413
+     * @todo Should be a better way to do this without dropping to raw SQL.
414
+     * @todo If we could namespace the plugin settings this would be cleaner.
415
+     * @todo this shouldn't work because ps_prefix will be empty string
416
+     * @return bool
417
+     */
418
+    public function unsetAllSettings() {
419
+        _elgg_services()->pluginSettingsCache->clear($this->guid);
420
+        _elgg_services()->boot->invalidateCache();
421
+
422
+        $db_prefix = _elgg_services()->configTable->get('dbprefix');
423
+        $us_prefix = _elgg_namespace_plugin_private_setting('user_setting', '', $this->getID());
424
+        $is_prefix = _elgg_namespace_plugin_private_setting('internal', '', $this->getID());
425
+
426
+        $q = "DELETE FROM {$db_prefix}private_settings
427 427
 			WHERE entity_guid = $this->guid
428 428
 			AND name NOT LIKE '$us_prefix%'
429 429
 			AND name NOT LIKE '$is_prefix%'";
430 430
 
431
-		return $this->getDatabase()->deleteData($q);
432
-	}
431
+        return $this->getDatabase()->deleteData($q);
432
+    }
433 433
 
434 434
 
435
-	// User settings
435
+    // User settings
436 436
 
437
-	/**
438
-	 * Returns a user's setting for this plugin
439
-	 *
440
-	 * @param string $name      The setting name
441
-	 * @param int    $user_guid The user GUID
442
-	 * @param mixed  $default   The default value to return if none is set
443
-	 *
444
-	 * @return mixed The setting string value, the default value or false if there is no user
445
-	 */
446
-	public function getUserSetting($name, $user_guid = 0, $default = null) {
447
-		$user_guid = (int)$user_guid;
437
+    /**
438
+     * Returns a user's setting for this plugin
439
+     *
440
+     * @param string $name      The setting name
441
+     * @param int    $user_guid The user GUID
442
+     * @param mixed  $default   The default value to return if none is set
443
+     *
444
+     * @return mixed The setting string value, the default value or false if there is no user
445
+     */
446
+    public function getUserSetting($name, $user_guid = 0, $default = null) {
447
+        $user_guid = (int)$user_guid;
448 448
 
449
-		if ($user_guid) {
450
-			$user = get_entity($user_guid);
451
-		} else {
452
-			$user = _elgg_services()->session->getLoggedInUser();
453
-		}
449
+        if ($user_guid) {
450
+            $user = get_entity($user_guid);
451
+        } else {
452
+            $user = _elgg_services()->session->getLoggedInUser();
453
+        }
454 454
 
455
-		if (!($user instanceof \ElggUser)) {
456
-			return false;
457
-		}
455
+        if (!($user instanceof \ElggUser)) {
456
+            return false;
457
+        }
458 458
 
459
-		$name = _elgg_namespace_plugin_private_setting('user_setting', $name, $this->getID());
459
+        $name = _elgg_namespace_plugin_private_setting('user_setting', $name, $this->getID());
460 460
 		
461
-		$val = get_private_setting($user->guid, $name);
462
-		return $val !== null ? $val : $default;
463
-	}
464
-
465
-	/**
466
-	 * Returns an array of all user settings saved for this plugin for the user.
467
-	 *
468
-	 * @note Plugin settings are saved with a prefix. This removes that prefix.
469
-	 *
470
-	 * @param int $user_guid The user GUID. Defaults to logged in.
471
-	 * @return array An array of key/value pairs.
472
-	 */
473
-	public function getAllUserSettings($user_guid = 0) {
474
-		$user_guid = (int)$user_guid;
475
-
476
-		if ($user_guid) {
477
-			$user = get_entity($user_guid);
478
-		} else {
479
-			$user = _elgg_services()->session->getLoggedInUser();
480
-		}
481
-
482
-		if (!($user instanceof \ElggUser)) {
483
-			return false;
484
-		}
485
-
486
-		$db_prefix = _elgg_services()->config->get('dbprefix');
487
-		// send an empty name so we just get the first part of the namespace
488
-		$ps_prefix = _elgg_namespace_plugin_private_setting('user_setting', '', $this->getID());
489
-		$ps_prefix_len = strlen($ps_prefix);
490
-
491
-		// Get private settings for user
492
-		$q = "SELECT * FROM {$db_prefix}private_settings
461
+        $val = get_private_setting($user->guid, $name);
462
+        return $val !== null ? $val : $default;
463
+    }
464
+
465
+    /**
466
+     * Returns an array of all user settings saved for this plugin for the user.
467
+     *
468
+     * @note Plugin settings are saved with a prefix. This removes that prefix.
469
+     *
470
+     * @param int $user_guid The user GUID. Defaults to logged in.
471
+     * @return array An array of key/value pairs.
472
+     */
473
+    public function getAllUserSettings($user_guid = 0) {
474
+        $user_guid = (int)$user_guid;
475
+
476
+        if ($user_guid) {
477
+            $user = get_entity($user_guid);
478
+        } else {
479
+            $user = _elgg_services()->session->getLoggedInUser();
480
+        }
481
+
482
+        if (!($user instanceof \ElggUser)) {
483
+            return false;
484
+        }
485
+
486
+        $db_prefix = _elgg_services()->config->get('dbprefix');
487
+        // send an empty name so we just get the first part of the namespace
488
+        $ps_prefix = _elgg_namespace_plugin_private_setting('user_setting', '', $this->getID());
489
+        $ps_prefix_len = strlen($ps_prefix);
490
+
491
+        // Get private settings for user
492
+        $q = "SELECT * FROM {$db_prefix}private_settings
493 493
 			WHERE entity_guid = {$user->guid}
494 494
 			AND name LIKE '$ps_prefix%'";
495 495
 
496
-		$private_settings = $this->getDatabase()->getData($q);
497
-
498
-		$return = array();
499
-
500
-		if ($private_settings) {
501
-			foreach ($private_settings as $setting) {
502
-				$name = substr($setting->name, $ps_prefix_len);
503
-				$value = $setting->value;
504
-
505
-				$return[$name] = $value;
506
-			}
507
-		}
508
-
509
-		return $return;
510
-	}
511
-
512
-	/**
513
-	 * Sets a user setting for a plugin
514
-	 *
515
-	 * @param string $name      The setting name
516
-	 * @param string $value     The setting value
517
-	 * @param int    $user_guid The user GUID
518
-	 *
519
-	 * @return mixed The new setting ID or false
520
-	 */
521
-	public function setUserSetting($name, $value, $user_guid = 0) {
522
-		$user_guid = (int)$user_guid;
523
-
524
-		if ($user_guid) {
525
-			$user = get_entity($user_guid);
526
-		} else {
527
-			$user = _elgg_services()->session->getLoggedInUser();
528
-		}
529
-
530
-		if (!($user instanceof \ElggUser)) {
531
-			return false;
532
-		}
533
-
534
-		// Hook to validate setting
535
-		// note: this doesn't pass the namespaced name
536
-		$value = _elgg_services()->hooks->trigger('usersetting', 'plugin', array(
537
-			'user' => $user,
538
-			'plugin' => $this,
539
-			'plugin_id' => $this->getID(),
540
-			'name' => $name,
541
-			'value' => $value
542
-		), $value);
496
+        $private_settings = $this->getDatabase()->getData($q);
497
+
498
+        $return = array();
499
+
500
+        if ($private_settings) {
501
+            foreach ($private_settings as $setting) {
502
+                $name = substr($setting->name, $ps_prefix_len);
503
+                $value = $setting->value;
504
+
505
+                $return[$name] = $value;
506
+            }
507
+        }
508
+
509
+        return $return;
510
+    }
511
+
512
+    /**
513
+     * Sets a user setting for a plugin
514
+     *
515
+     * @param string $name      The setting name
516
+     * @param string $value     The setting value
517
+     * @param int    $user_guid The user GUID
518
+     *
519
+     * @return mixed The new setting ID or false
520
+     */
521
+    public function setUserSetting($name, $value, $user_guid = 0) {
522
+        $user_guid = (int)$user_guid;
523
+
524
+        if ($user_guid) {
525
+            $user = get_entity($user_guid);
526
+        } else {
527
+            $user = _elgg_services()->session->getLoggedInUser();
528
+        }
529
+
530
+        if (!($user instanceof \ElggUser)) {
531
+            return false;
532
+        }
533
+
534
+        // Hook to validate setting
535
+        // note: this doesn't pass the namespaced name
536
+        $value = _elgg_services()->hooks->trigger('usersetting', 'plugin', array(
537
+            'user' => $user,
538
+            'plugin' => $this,
539
+            'plugin_id' => $this->getID(),
540
+            'name' => $name,
541
+            'value' => $value
542
+        ), $value);
543 543
 		
544
-		if (is_array($value)) {
545
-			elgg_log('Plugin user settings cannot store arrays.', 'ERROR');
546
-			return false;
547
-		}
544
+        if (is_array($value)) {
545
+            elgg_log('Plugin user settings cannot store arrays.', 'ERROR');
546
+            return false;
547
+        }
548 548
 		
549
-		// set the namespaced name.
550
-		$name = _elgg_namespace_plugin_private_setting('user_setting', $name, $this->getID());
551
-
552
-		return set_private_setting($user->guid, $name, $value);
553
-	}
554
-
555
-	/**
556
-	 * Removes a user setting name and value.
557
-	 *
558
-	 * @param string $name      The user setting name
559
-	 * @param int    $user_guid The user GUID
560
-	 * @return bool
561
-	 */
562
-	public function unsetUserSetting($name, $user_guid = 0) {
563
-		$user_guid = (int)$user_guid;
564
-
565
-		if ($user_guid) {
566
-			$user = get_entity($user_guid);
567
-		} else {
568
-			$user = _elgg_services()->session->getLoggedInUser();
569
-		}
570
-
571
-		if (!($user instanceof \ElggUser)) {
572
-			return false;
573
-		}
574
-
575
-		// set the namespaced name.
576
-		$name = _elgg_namespace_plugin_private_setting('user_setting', $name, $this->getID());
577
-
578
-		return remove_private_setting($user->guid, $name);
579
-	}
580
-
581
-	/**
582
-	 * Removes all User Settings for this plugin for a particular user
583
-	 *
584
-	 * Use {@link removeAllUsersSettings()} to remove all user
585
-	 * settings for all users.  (Note the plural 'Users'.)
586
-	 *
587
-	 * @warning 0 does not equal logged in user for this method!
588
-	 * @todo fix that
589
-	 *
590
-	 * @param int $user_guid The user GUID to remove user settings.
591
-	 * @return bool
592
-	 */
593
-	public function unsetAllUserSettings($user_guid) {
594
-		$db_prefix = _elgg_services()->configTable->get('dbprefix');
595
-		$ps_prefix = _elgg_namespace_plugin_private_setting('user_setting', '', $this->getID());
596
-
597
-		$q = "DELETE FROM {$db_prefix}private_settings
549
+        // set the namespaced name.
550
+        $name = _elgg_namespace_plugin_private_setting('user_setting', $name, $this->getID());
551
+
552
+        return set_private_setting($user->guid, $name, $value);
553
+    }
554
+
555
+    /**
556
+     * Removes a user setting name and value.
557
+     *
558
+     * @param string $name      The user setting name
559
+     * @param int    $user_guid The user GUID
560
+     * @return bool
561
+     */
562
+    public function unsetUserSetting($name, $user_guid = 0) {
563
+        $user_guid = (int)$user_guid;
564
+
565
+        if ($user_guid) {
566
+            $user = get_entity($user_guid);
567
+        } else {
568
+            $user = _elgg_services()->session->getLoggedInUser();
569
+        }
570
+
571
+        if (!($user instanceof \ElggUser)) {
572
+            return false;
573
+        }
574
+
575
+        // set the namespaced name.
576
+        $name = _elgg_namespace_plugin_private_setting('user_setting', $name, $this->getID());
577
+
578
+        return remove_private_setting($user->guid, $name);
579
+    }
580
+
581
+    /**
582
+     * Removes all User Settings for this plugin for a particular user
583
+     *
584
+     * Use {@link removeAllUsersSettings()} to remove all user
585
+     * settings for all users.  (Note the plural 'Users'.)
586
+     *
587
+     * @warning 0 does not equal logged in user for this method!
588
+     * @todo fix that
589
+     *
590
+     * @param int $user_guid The user GUID to remove user settings.
591
+     * @return bool
592
+     */
593
+    public function unsetAllUserSettings($user_guid) {
594
+        $db_prefix = _elgg_services()->configTable->get('dbprefix');
595
+        $ps_prefix = _elgg_namespace_plugin_private_setting('user_setting', '', $this->getID());
596
+
597
+        $q = "DELETE FROM {$db_prefix}private_settings
598 598
 			WHERE entity_guid = $user_guid
599 599
 			AND name LIKE '$ps_prefix%'";
600 600
 
601
-		return $this->getDatabase()->deleteData($q);
602
-	}
603
-
604
-	/**
605
-	 * Removes this plugin's user settings for all users.
606
-	 *
607
-	 * Use {@link removeAllUserSettings()} if you just want to remove
608
-	 * settings for a single user.
609
-	 *
610
-	 * @return bool
611
-	 */
612
-	public function unsetAllUsersSettings() {
613
-		$db_prefix = _elgg_services()->configTable->get('dbprefix');
614
-		$ps_prefix = _elgg_namespace_plugin_private_setting('user_setting', '', $this->getID());
615
-
616
-		$q = "DELETE FROM {$db_prefix}private_settings
601
+        return $this->getDatabase()->deleteData($q);
602
+    }
603
+
604
+    /**
605
+     * Removes this plugin's user settings for all users.
606
+     *
607
+     * Use {@link removeAllUserSettings()} if you just want to remove
608
+     * settings for a single user.
609
+     *
610
+     * @return bool
611
+     */
612
+    public function unsetAllUsersSettings() {
613
+        $db_prefix = _elgg_services()->configTable->get('dbprefix');
614
+        $ps_prefix = _elgg_namespace_plugin_private_setting('user_setting', '', $this->getID());
615
+
616
+        $q = "DELETE FROM {$db_prefix}private_settings
617 617
 			WHERE name LIKE '$ps_prefix%'";
618 618
 
619
-		return $this->getDatabase()->deleteData($q);
620
-	}
621
-
622
-
623
-	// validation
624
-
625
-	/**
626
-	 * Returns if the plugin is complete, meaning has all required files
627
-	 * and Elgg can read them and they make sense.
628
-	 *
629
-	 * @todo bad name? This could be confused with isValid() from \ElggPluginPackage.
630
-	 *
631
-	 * @return bool
632
-	 */
633
-	public function isValid() {
634
-		if (!$this->getID()) {
635
-			$this->errorMsg = _elgg_services()->translator->translate('ElggPlugin:MissingID', array($this->guid));
636
-			return false;
637
-		}
638
-
639
-		if (!$this->getPackage() instanceof \ElggPluginPackage) {
640
-			$this->errorMsg = _elgg_services()->translator->translate('ElggPlugin:NoPluginPackagePackage', array($this->getID(), $this->guid));
641
-			return false;
642
-		}
643
-
644
-		if (!$this->getPackage()->isValid()) {
645
-			$this->errorMsg = $this->getPackage()->getError();
646
-			return false;
647
-		}
648
-
649
-		return true;
650
-	}
651
-
652
-	/**
653
-	 * Is this plugin active?
654
-	 *
655
-	 * @param int $site_guid Optional site guid.
656
-	 * @return bool
657
-	 */
658
-	public function isActive($site_guid = null) {
659
-		if (!$this->guid) {
660
-			return false;
661
-		}
662
-
663
-		if ($site_guid) {
664
-			$site = get_entity($site_guid);
665
-		} else {
666
-			$site = _elgg_services()->configTable->get('site');
667
-		}
668
-
669
-		if (!($site instanceof \ElggSite)) {
670
-			return false;
671
-		}
672
-
673
-		return check_entity_relationship($this->guid, 'active_plugin', $site->guid);
674
-	}
675
-
676
-	/**
677
-	 * Checks if this plugin can be activated on the current
678
-	 * Elgg installation.
679
-	 *
680
-	 * @todo remove $site_guid param or implement it
681
-	 *
682
-	 * @param mixed $site_guid Optional site guid
683
-	 * @return bool
684
-	 */
685
-	public function canActivate($site_guid = null) {
686
-		if ($this->isActive($site_guid)) {
687
-			return false;
688
-		}
689
-
690
-		if ($this->getPackage()) {
691
-			$result = $this->getPackage()->isValid() && $this->getPackage()->checkDependencies();
692
-			if (!$result) {
693
-				$this->errorMsg = $this->getPackage()->getError();
694
-			}
695
-
696
-			return $result;
697
-		}
698
-
699
-		return false;
700
-	}
701
-
702
-
703
-	// activating and deactivating
704
-
705
-	/**
706
-	 * Actives the plugin for the current site.
707
-	 *
708
-	 * @param mixed $site_guid Optional site GUID.
709
-	 * @return bool
710
-	 */
711
-	public function activate($site_guid = null) {
712
-		if ($this->isActive($site_guid)) {
713
-			return false;
714
-		}
715
-
716
-		if (!$this->canActivate()) {
717
-			return false;
718
-		}
719
-
720
-		// Check this before setting status because the file could potentially throw
721
-		if (!$this->isStaticConfigValid()) {
722
-			return false;
723
-		}
724
-
725
-		if (!$this->setStatus(true, $site_guid)) {
726
-			return false;
727
-		}
728
-
729
-		// perform tasks and emit events
730
-		// emit an event. returning false will make this not be activated.
731
-		// we need to do this after it's been fully activated
732
-		// or the deactivate will be confused.
733
-		$params = array(
734
-			'plugin_id' => $this->getID(),
735
-			'plugin_entity' => $this,
736
-		);
737
-
738
-		$return = _elgg_services()->events->trigger('activate', 'plugin', $params);
739
-
740
-		// if there are any on_enable functions, start the plugin now and run them
741
-		// Note: this will not run re-run the init hooks!
742
-		if ($return) {
743
-			if ($this->canReadFile('activate.php')) {
744
-				$flags = ELGG_PLUGIN_INCLUDE_START | ELGG_PLUGIN_REGISTER_CLASSES |
745
-						ELGG_PLUGIN_REGISTER_LANGUAGES | ELGG_PLUGIN_REGISTER_VIEWS;
746
-
747
-				$this->start($flags);
748
-
749
-				$return = $this->includeFile('activate.php');
750
-			}
751
-		}
752
-
753
-		if ($return === false) {
754
-			$this->deactivate($site_guid);
755
-		}
756
-
757
-		return $return;
758
-	}
759
-
760
-	/**
761
-	 * Checks if this plugin can be deactivated on the current
762
-	 * Elgg installation. Validates that this plugin has no
763
-	 * active dependants.
764
-	 *
765
-	 * @param mixed $site_guid Optional site guid
766
-	 * @return bool
767
-	 */
768
-	public function canDeactivate($site_guid = null) {
769
-		if (!$this->isActive($site_guid)) {
770
-			return false;
771
-		}
772
-
773
-		$dependents = [];
774
-
775
-		$active_plugins = elgg_get_plugins();
776
-
777
-		foreach ($active_plugins as $plugin) {
778
-			$manifest = $plugin->getManifest();
779
-			if (!$manifest) {
780
-				return true;
781
-			}
782
-			$requires = $manifest->getRequires();
783
-
784
-			foreach ($requires as $required) {
785
-				if ($required['type'] == 'plugin' && $required['name'] == $this->getID()) {
786
-					// there are active dependents
787
-					$dependents[$manifest->getPluginID()] = $plugin;
788
-				}
789
-			}
790
-		}
791
-
792
-		if (!empty($dependents)) {
793
-			$list = array_map(function(\ElggPlugin $plugin) {
794
-				$css_id = preg_replace('/[^a-z0-9-]/i', '-', $plugin->getManifest()->getID());
795
-				return elgg_view('output/url', [
796
-					'text' => $plugin->getManifest()->getName(),
797
-					'href' => "#$css_id",
798
-				]);
799
-			}, $dependents);
800
-			$name = $this->getManifest()->getName();
801
-			$list = implode(', ', $list);
802
-			$this->errorMsg = elgg_echo('ElggPlugin:Dependencies:ActiveDependent', [$name, $list]);
803
-			return false;
804
-		}
805
-
806
-		return true;
807
-	}
808
-
809
-	/**
810
-	 * Deactivates the plugin.
811
-	 *
812
-	 * @param mixed $site_guid Optional site GUID.
813
-	 * @return bool
814
-	 */
815
-	public function deactivate($site_guid = null) {
816
-		if (!$this->isActive($site_guid)) {
817
-			return false;
818
-		}
819
-
820
-		if (!$this->canDeactivate($site_guid)) {
821
-			return false;
822
-		}
619
+        return $this->getDatabase()->deleteData($q);
620
+    }
621
+
622
+
623
+    // validation
624
+
625
+    /**
626
+     * Returns if the plugin is complete, meaning has all required files
627
+     * and Elgg can read them and they make sense.
628
+     *
629
+     * @todo bad name? This could be confused with isValid() from \ElggPluginPackage.
630
+     *
631
+     * @return bool
632
+     */
633
+    public function isValid() {
634
+        if (!$this->getID()) {
635
+            $this->errorMsg = _elgg_services()->translator->translate('ElggPlugin:MissingID', array($this->guid));
636
+            return false;
637
+        }
638
+
639
+        if (!$this->getPackage() instanceof \ElggPluginPackage) {
640
+            $this->errorMsg = _elgg_services()->translator->translate('ElggPlugin:NoPluginPackagePackage', array($this->getID(), $this->guid));
641
+            return false;
642
+        }
643
+
644
+        if (!$this->getPackage()->isValid()) {
645
+            $this->errorMsg = $this->getPackage()->getError();
646
+            return false;
647
+        }
648
+
649
+        return true;
650
+    }
651
+
652
+    /**
653
+     * Is this plugin active?
654
+     *
655
+     * @param int $site_guid Optional site guid.
656
+     * @return bool
657
+     */
658
+    public function isActive($site_guid = null) {
659
+        if (!$this->guid) {
660
+            return false;
661
+        }
662
+
663
+        if ($site_guid) {
664
+            $site = get_entity($site_guid);
665
+        } else {
666
+            $site = _elgg_services()->configTable->get('site');
667
+        }
668
+
669
+        if (!($site instanceof \ElggSite)) {
670
+            return false;
671
+        }
672
+
673
+        return check_entity_relationship($this->guid, 'active_plugin', $site->guid);
674
+    }
675
+
676
+    /**
677
+     * Checks if this plugin can be activated on the current
678
+     * Elgg installation.
679
+     *
680
+     * @todo remove $site_guid param or implement it
681
+     *
682
+     * @param mixed $site_guid Optional site guid
683
+     * @return bool
684
+     */
685
+    public function canActivate($site_guid = null) {
686
+        if ($this->isActive($site_guid)) {
687
+            return false;
688
+        }
689
+
690
+        if ($this->getPackage()) {
691
+            $result = $this->getPackage()->isValid() && $this->getPackage()->checkDependencies();
692
+            if (!$result) {
693
+                $this->errorMsg = $this->getPackage()->getError();
694
+            }
695
+
696
+            return $result;
697
+        }
698
+
699
+        return false;
700
+    }
701
+
702
+
703
+    // activating and deactivating
704
+
705
+    /**
706
+     * Actives the plugin for the current site.
707
+     *
708
+     * @param mixed $site_guid Optional site GUID.
709
+     * @return bool
710
+     */
711
+    public function activate($site_guid = null) {
712
+        if ($this->isActive($site_guid)) {
713
+            return false;
714
+        }
715
+
716
+        if (!$this->canActivate()) {
717
+            return false;
718
+        }
719
+
720
+        // Check this before setting status because the file could potentially throw
721
+        if (!$this->isStaticConfigValid()) {
722
+            return false;
723
+        }
724
+
725
+        if (!$this->setStatus(true, $site_guid)) {
726
+            return false;
727
+        }
728
+
729
+        // perform tasks and emit events
730
+        // emit an event. returning false will make this not be activated.
731
+        // we need to do this after it's been fully activated
732
+        // or the deactivate will be confused.
733
+        $params = array(
734
+            'plugin_id' => $this->getID(),
735
+            'plugin_entity' => $this,
736
+        );
737
+
738
+        $return = _elgg_services()->events->trigger('activate', 'plugin', $params);
739
+
740
+        // if there are any on_enable functions, start the plugin now and run them
741
+        // Note: this will not run re-run the init hooks!
742
+        if ($return) {
743
+            if ($this->canReadFile('activate.php')) {
744
+                $flags = ELGG_PLUGIN_INCLUDE_START | ELGG_PLUGIN_REGISTER_CLASSES |
745
+                        ELGG_PLUGIN_REGISTER_LANGUAGES | ELGG_PLUGIN_REGISTER_VIEWS;
746
+
747
+                $this->start($flags);
748
+
749
+                $return = $this->includeFile('activate.php');
750
+            }
751
+        }
752
+
753
+        if ($return === false) {
754
+            $this->deactivate($site_guid);
755
+        }
756
+
757
+        return $return;
758
+    }
759
+
760
+    /**
761
+     * Checks if this plugin can be deactivated on the current
762
+     * Elgg installation. Validates that this plugin has no
763
+     * active dependants.
764
+     *
765
+     * @param mixed $site_guid Optional site guid
766
+     * @return bool
767
+     */
768
+    public function canDeactivate($site_guid = null) {
769
+        if (!$this->isActive($site_guid)) {
770
+            return false;
771
+        }
772
+
773
+        $dependents = [];
774
+
775
+        $active_plugins = elgg_get_plugins();
776
+
777
+        foreach ($active_plugins as $plugin) {
778
+            $manifest = $plugin->getManifest();
779
+            if (!$manifest) {
780
+                return true;
781
+            }
782
+            $requires = $manifest->getRequires();
783
+
784
+            foreach ($requires as $required) {
785
+                if ($required['type'] == 'plugin' && $required['name'] == $this->getID()) {
786
+                    // there are active dependents
787
+                    $dependents[$manifest->getPluginID()] = $plugin;
788
+                }
789
+            }
790
+        }
791
+
792
+        if (!empty($dependents)) {
793
+            $list = array_map(function(\ElggPlugin $plugin) {
794
+                $css_id = preg_replace('/[^a-z0-9-]/i', '-', $plugin->getManifest()->getID());
795
+                return elgg_view('output/url', [
796
+                    'text' => $plugin->getManifest()->getName(),
797
+                    'href' => "#$css_id",
798
+                ]);
799
+            }, $dependents);
800
+            $name = $this->getManifest()->getName();
801
+            $list = implode(', ', $list);
802
+            $this->errorMsg = elgg_echo('ElggPlugin:Dependencies:ActiveDependent', [$name, $list]);
803
+            return false;
804
+        }
805
+
806
+        return true;
807
+    }
808
+
809
+    /**
810
+     * Deactivates the plugin.
811
+     *
812
+     * @param mixed $site_guid Optional site GUID.
813
+     * @return bool
814
+     */
815
+    public function deactivate($site_guid = null) {
816
+        if (!$this->isActive($site_guid)) {
817
+            return false;
818
+        }
819
+
820
+        if (!$this->canDeactivate($site_guid)) {
821
+            return false;
822
+        }
823 823
 		
824
-		// emit an event. returning false will cause this to not be deactivated.
825
-		$params = array(
826
-			'plugin_id' => $this->getID(),
827
-			'plugin_entity' => $this,
828
-		);
829
-
830
-		$return = _elgg_services()->events->trigger('deactivate', 'plugin', $params);
831
-
832
-		// run any deactivate code
833
-		if ($return) {
834
-			if ($this->canReadFile('deactivate.php')) {
835
-				$return = $this->includeFile('deactivate.php');
836
-			}
837
-		}
838
-
839
-		if ($return === false) {
840
-			return false;
841
-		} else {
842
-			return $this->setStatus(false, $site_guid);
843
-		}
844
-	}
845
-
846
-	/**
847
-	 * Start the plugin.
848
-	 *
849
-	 * @param int $flags Start flags for the plugin. See the constants in lib/plugins.php for details.
850
-	 * @return true
851
-	 * @throws PluginException
852
-	 */
853
-	public function start($flags) {
854
-		//if (!$this->canActivate()) {
855
-		//	return false;
856
-		//}
857
-
858
-		// include classes
859
-		if ($flags & ELGG_PLUGIN_REGISTER_CLASSES) {
860
-			$this->registerClasses();
861
-		}
824
+        // emit an event. returning false will cause this to not be deactivated.
825
+        $params = array(
826
+            'plugin_id' => $this->getID(),
827
+            'plugin_entity' => $this,
828
+        );
829
+
830
+        $return = _elgg_services()->events->trigger('deactivate', 'plugin', $params);
831
+
832
+        // run any deactivate code
833
+        if ($return) {
834
+            if ($this->canReadFile('deactivate.php')) {
835
+                $return = $this->includeFile('deactivate.php');
836
+            }
837
+        }
838
+
839
+        if ($return === false) {
840
+            return false;
841
+        } else {
842
+            return $this->setStatus(false, $site_guid);
843
+        }
844
+    }
845
+
846
+    /**
847
+     * Start the plugin.
848
+     *
849
+     * @param int $flags Start flags for the plugin. See the constants in lib/plugins.php for details.
850
+     * @return true
851
+     * @throws PluginException
852
+     */
853
+    public function start($flags) {
854
+        //if (!$this->canActivate()) {
855
+        //	return false;
856
+        //}
857
+
858
+        // include classes
859
+        if ($flags & ELGG_PLUGIN_REGISTER_CLASSES) {
860
+            $this->registerClasses();
861
+        }
862 862
 		
863
-		// include start file
864
-		if ($flags & ELGG_PLUGIN_INCLUDE_START) {
865
-			$this->includeFile('start.php');
866
-		}
867
-
868
-		// include views
869
-		if ($flags & ELGG_PLUGIN_REGISTER_VIEWS) {
870
-			$this->registerViews();
871
-		}
872
-
873
-		// include languages
874
-		if ($flags & ELGG_PLUGIN_REGISTER_LANGUAGES) {
875
-			$this->registerLanguages();
876
-		}
877
-
878
-		return true;
879
-	}
880
-
881
-
882
-	// start helpers
883
-
884
-	/**
885
-	 * Get the config object in a deprecation wrapper
886
-	 *
887
-	 * @return \Elgg\DeprecationWrapper
888
-	 */
889
-	protected static function getConfigWrapper() {
890
-		static $wrapper;
891
-		if (null === $wrapper) {
892
-			global $CONFIG;
893
-			$warning = 'Do not rely on local $CONFIG being available in start.php';
894
-			$wrapper = new \Elgg\DeprecationWrapper($CONFIG, $warning, "1.10");
895
-		}
896
-		return $wrapper;
897
-	}
898
-
899
-	/**
900
-	 * Includes one of the plugins files
901
-	 *
902
-	 * @param string $filename The name of the file
903
-	 *
904
-	 * @throws PluginException
905
-	 * @return mixed The return value of the included file (or 1 if there is none)
906
-	 */
907
-	protected function includeFile($filename) {
908
-		// This needs to be here to be backwards compatible for 1.0-1.7.
909
-		// They expect the global config object to be available in start.php.
910
-		if ($filename == 'start.php') {
911
-			$CONFIG = self::getConfigWrapper();
912
-		}
913
-
914
-		$filepath = "$this->path/$filename";
915
-
916
-		if (!$this->canReadFile($filename)) {
917
-			$msg = _elgg_services()->translator->translate('ElggPlugin:Exception:CannotIncludeFile',
918
-							array($filename, $this->getID(), $this->guid, $this->path));
919
-			throw new \PluginException($msg);
920
-		}
921
-
922
-		try {
923
-			$ret = require_once $filepath;
924
-		} catch (Exception $e) {
925
-			$msg = _elgg_services()->translator->translate('ElggPlugin:Exception:IncludeFileThrew',
926
-				array($filename, $this->getID(), $this->guid, $this->path));
927
-			throw new \PluginException($msg, 0, $e);
928
-		}
929
-
930
-		return $ret;
931
-	}
932
-
933
-	/**
934
-	 * Checks whether a plugin file with the given name exists
935
-	 *
936
-	 * @param string $filename The name of the file
937
-	 * @return bool
938
-	 */
939
-	protected function canReadFile($filename) {
940
-		$path = "{$this->path}/$filename";
941
-		return is_file($path) && is_readable($path);
942
-	}
943
-
944
-	/**
945
-	 * If a static config file is present, is it a serializable array?
946
-	 *
947
-	 * @return bool
948
-	 * @throws PluginException
949
-	 */
950
-	private function isStaticConfigValid() {
951
-		if (!$this->canReadFile(ElggPluginPackage::STATIC_CONFIG_FILENAME)) {
952
-			return true;
953
-		}
954
-
955
-		ob_start();
956
-		$value = $this->includeFile(ElggPluginPackage::STATIC_CONFIG_FILENAME);
957
-		if (ob_get_clean() !== '') {
958
-			$this->errorMsg = _elgg_services()->translator->translate('ElggPlugin:activate:ConfigSentOutput');
959
-			return false;
960
-		}
961
-
962
-		// make sure can serialize
963
-		$value = @unserialize(serialize($value));
964
-		if (!is_array($value)) {
965
-			$this->errorMsg = _elgg_services()->translator->translate('ElggPlugin:activate:BadConfigFormat');
966
-			return false;
967
-		}
968
-
969
-		return true;
970
-	}
971
-
972
-	/**
973
-	 * Registers the plugin's views
974
-	 *
975
-	 * @throws PluginException
976
-	 * @return void
977
-	 */
978
-	protected function registerViews() {
979
-		$views = _elgg_services()->views;
980
-
981
-		// Declared views first
982
-		$file = "{$this->path}/views.php";
983
-		if (is_file($file)) {
984
-			$spec = Includer::includeFile($file);
985
-			if (is_array($spec)) {
986
-				$views->mergeViewsSpec($spec);
987
-			}
988
-		}
989
-
990
-		$spec = $this->getStaticConfig('views');
991
-		if ($spec) {
992
-			$views->mergeViewsSpec($spec);
993
-		}
994
-
995
-		// Allow /views directory files to override
996
-		if (!$views->registerPluginViews($this->path, $failed_dir)) {
997
-			$key = 'ElggPlugin:Exception:CannotRegisterViews';
998
-			$args = [$this->getID(), $this->guid, $failed_dir];
999
-			$msg = _elgg_services()->translator->translate($key, $args);
1000
-			throw new \PluginException($msg);
1001
-		}
1002
-	}
1003
-
1004
-	/**
1005
-	 * Registers the plugin's languages
1006
-	 *
1007
-	 * @throws PluginException
1008
-	 * @return true
1009
-	 */
1010
-	protected function registerLanguages() {
1011
-		return _elgg_services()->translator->registerPluginTranslations($this->path);
1012
-	}
1013
-
1014
-	/**
1015
-	 * Registers the plugin's classes
1016
-	 *
1017
-	 * @throws PluginException
1018
-	 * @return true
1019
-	 */
1020
-	protected function registerClasses() {
1021
-		$classes_path = "$this->path/classes";
1022
-
1023
-		if (is_dir($classes_path)) {
1024
-			_elgg_services()->autoloadManager->addClasses($classes_path);
1025
-		}
1026
-
1027
-		return true;
1028
-	}
1029
-
1030
-	/**
1031
-	 * Get an attribute or private setting value
1032
-	 *
1033
-	 * @param string $name Name of the attribute or private setting
1034
-	 * @return mixed
1035
-	 */
1036
-	public function __get($name) {
1037
-		// See if its in our base attribute
1038
-		if (array_key_exists($name, $this->attributes)) {
1039
-			return $this->attributes[$name];
1040
-		}
1041
-
1042
-		// @todo clean below - getPrivateSetting() should return null now
1043
-		// No, so see if its in the private data store.
1044
-		// get_private_setting() returns false if it doesn't exist
1045
-		$meta = $this->getPrivateSetting($name);
1046
-
1047
-		if ($meta === false) {
1048
-			// Can't find it, so return null
1049
-			return null;
1050
-		}
1051
-
1052
-		return $meta;
1053
-	}
1054
-
1055
-	/**
1056
-	 * Get a value from private settings.
1057
-	 *
1058
-	 * @param string $name Name
1059
-	 * @return mixed
1060
-	 * @deprecated 1.9
1061
-	 */
1062
-	public function get($name) {
1063
-		elgg_deprecated_notice("Use -> instead of get()", 1.9);
1064
-		return $this->__get($name);
1065
-	}
1066
-
1067
-	/**
1068
-	 * Set a value as private setting or attribute.
1069
-	 *
1070
-	 * Attributes include title and description.
1071
-	 *
1072
-	 * @param string $name  Name of the attribute or private_setting
1073
-	 * @param mixed  $value Value to be set
1074
-	 * @return void
1075
-	 */
1076
-	public function __set($name, $value) {
1077
-		if (array_key_exists($name, $this->attributes)) {
1078
-			// Check that we're not trying to change the guid!
1079
-			if ((array_key_exists('guid', $this->attributes)) && ($name == 'guid')) {
1080
-				return;
1081
-			}
1082
-
1083
-			$this->attributes[$name] = $value;
1084
-		} else {
1085
-			// to make sure we trigger the correct hooks
1086
-			$this->setSetting($name, $value);
1087
-		}
1088
-	}
1089
-
1090
-	/**
1091
-	 * Save a value as private setting or attribute.
1092
-	 *
1093
-	 * Attributes include title and description.
1094
-	 *
1095
-	 * @param string $name  Name
1096
-	 * @param mixed  $value Value
1097
-	 * @return bool
1098
-	 */
1099
-	public function set($name, $value) {
1100
-		elgg_deprecated_notice("Use -> instead of set()", 1.9);
1101
-		$this->__set($name, $value);
1102
-
1103
-		return true;
1104
-	}
1105
-
1106
-	/**
1107
-	 * Sets the plugin to active or inactive for $site_guid.
1108
-	 *
1109
-	 * @param bool  $active    Set to active or inactive
1110
-	 * @param mixed $site_guid Int for specific site, null for current site.
1111
-	 *
1112
-	 * @return bool
1113
-	 */
1114
-	private function setStatus($active, $site_guid = null) {
1115
-		if (!$this->guid) {
1116
-			return false;
1117
-		}
1118
-
1119
-		if ($site_guid) {
1120
-			$site = get_entity($site_guid);
1121
-
1122
-			if (!($site instanceof \ElggSite)) {
1123
-				return false;
1124
-			}
1125
-		} else {
1126
-			$site = _elgg_services()->configTable->get('site');
1127
-		}
1128
-
1129
-		if ($active) {
1130
-			$result = add_entity_relationship($this->guid, 'active_plugin', $site->guid);
1131
-		} else {
1132
-			$result = remove_entity_relationship($this->guid, 'active_plugin', $site->guid);
1133
-		}
1134
-
1135
-		_elgg_invalidate_plugins_provides_cache();
1136
-		_elgg_services()->boot->invalidateCache();
1137
-
1138
-		return $result;
1139
-	}
1140
-
1141
-	/**
1142
-	 * Returns the last error message registered.
1143
-	 *
1144
-	 * @return string|null
1145
-	 */
1146
-	public function getError() {
1147
-		return $this->errorMsg;
1148
-	}
1149
-
1150
-	/**
1151
-	 * Returns this plugin's \ElggPluginManifest object
1152
-	 *
1153
-	 * @return \ElggPluginManifest|null
1154
-	 */
1155
-	public function getManifest() {
1156
-		if ($this->manifest instanceof \ElggPluginManifest) {
1157
-			return $this->manifest;
1158
-		}
1159
-
1160
-		try {
1161
-			$package = $this->getPackage();
1162
-			if (!$package) {
1163
-				throw new \Exception('Package cannot be loaded');
1164
-			}
1165
-			$this->manifest = $package->getManifest();
1166
-		} catch (Exception $e) {
1167
-			_elgg_services()->logger->warn("Failed to load manifest for plugin $this->guid. " . $e->getMessage());
1168
-			$this->errorMsg = $e->getmessage();
1169
-		}
1170
-
1171
-		return $this->manifest;
1172
-	}
1173
-
1174
-	/**
1175
-	 * Returns this plugin's \ElggPluginPackage object
1176
-	 *
1177
-	 * @return \ElggPluginPackage|null
1178
-	 */
1179
-	public function getPackage() {
1180
-		if ($this->package instanceof \ElggPluginPackage) {
1181
-			return $this->package;
1182
-		}
1183
-
1184
-		try {
1185
-			$this->package = new \ElggPluginPackage($this->path, false);
1186
-		} catch (Exception $e) {
1187
-			_elgg_services()->logger->warn("Failed to load package for $this->guid. " . $e->getMessage());
1188
-			$this->errorMsg = $e->getmessage();
1189
-		}
1190
-
1191
-		return $this->package;
1192
-	}
863
+        // include start file
864
+        if ($flags & ELGG_PLUGIN_INCLUDE_START) {
865
+            $this->includeFile('start.php');
866
+        }
867
+
868
+        // include views
869
+        if ($flags & ELGG_PLUGIN_REGISTER_VIEWS) {
870
+            $this->registerViews();
871
+        }
872
+
873
+        // include languages
874
+        if ($flags & ELGG_PLUGIN_REGISTER_LANGUAGES) {
875
+            $this->registerLanguages();
876
+        }
877
+
878
+        return true;
879
+    }
880
+
881
+
882
+    // start helpers
883
+
884
+    /**
885
+     * Get the config object in a deprecation wrapper
886
+     *
887
+     * @return \Elgg\DeprecationWrapper
888
+     */
889
+    protected static function getConfigWrapper() {
890
+        static $wrapper;
891
+        if (null === $wrapper) {
892
+            global $CONFIG;
893
+            $warning = 'Do not rely on local $CONFIG being available in start.php';
894
+            $wrapper = new \Elgg\DeprecationWrapper($CONFIG, $warning, "1.10");
895
+        }
896
+        return $wrapper;
897
+    }
898
+
899
+    /**
900
+     * Includes one of the plugins files
901
+     *
902
+     * @param string $filename The name of the file
903
+     *
904
+     * @throws PluginException
905
+     * @return mixed The return value of the included file (or 1 if there is none)
906
+     */
907
+    protected function includeFile($filename) {
908
+        // This needs to be here to be backwards compatible for 1.0-1.7.
909
+        // They expect the global config object to be available in start.php.
910
+        if ($filename == 'start.php') {
911
+            $CONFIG = self::getConfigWrapper();
912
+        }
913
+
914
+        $filepath = "$this->path/$filename";
915
+
916
+        if (!$this->canReadFile($filename)) {
917
+            $msg = _elgg_services()->translator->translate('ElggPlugin:Exception:CannotIncludeFile',
918
+                            array($filename, $this->getID(), $this->guid, $this->path));
919
+            throw new \PluginException($msg);
920
+        }
921
+
922
+        try {
923
+            $ret = require_once $filepath;
924
+        } catch (Exception $e) {
925
+            $msg = _elgg_services()->translator->translate('ElggPlugin:Exception:IncludeFileThrew',
926
+                array($filename, $this->getID(), $this->guid, $this->path));
927
+            throw new \PluginException($msg, 0, $e);
928
+        }
929
+
930
+        return $ret;
931
+    }
932
+
933
+    /**
934
+     * Checks whether a plugin file with the given name exists
935
+     *
936
+     * @param string $filename The name of the file
937
+     * @return bool
938
+     */
939
+    protected function canReadFile($filename) {
940
+        $path = "{$this->path}/$filename";
941
+        return is_file($path) && is_readable($path);
942
+    }
943
+
944
+    /**
945
+     * If a static config file is present, is it a serializable array?
946
+     *
947
+     * @return bool
948
+     * @throws PluginException
949
+     */
950
+    private function isStaticConfigValid() {
951
+        if (!$this->canReadFile(ElggPluginPackage::STATIC_CONFIG_FILENAME)) {
952
+            return true;
953
+        }
954
+
955
+        ob_start();
956
+        $value = $this->includeFile(ElggPluginPackage::STATIC_CONFIG_FILENAME);
957
+        if (ob_get_clean() !== '') {
958
+            $this->errorMsg = _elgg_services()->translator->translate('ElggPlugin:activate:ConfigSentOutput');
959
+            return false;
960
+        }
961
+
962
+        // make sure can serialize
963
+        $value = @unserialize(serialize($value));
964
+        if (!is_array($value)) {
965
+            $this->errorMsg = _elgg_services()->translator->translate('ElggPlugin:activate:BadConfigFormat');
966
+            return false;
967
+        }
968
+
969
+        return true;
970
+    }
971
+
972
+    /**
973
+     * Registers the plugin's views
974
+     *
975
+     * @throws PluginException
976
+     * @return void
977
+     */
978
+    protected function registerViews() {
979
+        $views = _elgg_services()->views;
980
+
981
+        // Declared views first
982
+        $file = "{$this->path}/views.php";
983
+        if (is_file($file)) {
984
+            $spec = Includer::includeFile($file);
985
+            if (is_array($spec)) {
986
+                $views->mergeViewsSpec($spec);
987
+            }
988
+        }
989
+
990
+        $spec = $this->getStaticConfig('views');
991
+        if ($spec) {
992
+            $views->mergeViewsSpec($spec);
993
+        }
994
+
995
+        // Allow /views directory files to override
996
+        if (!$views->registerPluginViews($this->path, $failed_dir)) {
997
+            $key = 'ElggPlugin:Exception:CannotRegisterViews';
998
+            $args = [$this->getID(), $this->guid, $failed_dir];
999
+            $msg = _elgg_services()->translator->translate($key, $args);
1000
+            throw new \PluginException($msg);
1001
+        }
1002
+    }
1003
+
1004
+    /**
1005
+     * Registers the plugin's languages
1006
+     *
1007
+     * @throws PluginException
1008
+     * @return true
1009
+     */
1010
+    protected function registerLanguages() {
1011
+        return _elgg_services()->translator->registerPluginTranslations($this->path);
1012
+    }
1013
+
1014
+    /**
1015
+     * Registers the plugin's classes
1016
+     *
1017
+     * @throws PluginException
1018
+     * @return true
1019
+     */
1020
+    protected function registerClasses() {
1021
+        $classes_path = "$this->path/classes";
1022
+
1023
+        if (is_dir($classes_path)) {
1024
+            _elgg_services()->autoloadManager->addClasses($classes_path);
1025
+        }
1026
+
1027
+        return true;
1028
+    }
1029
+
1030
+    /**
1031
+     * Get an attribute or private setting value
1032
+     *
1033
+     * @param string $name Name of the attribute or private setting
1034
+     * @return mixed
1035
+     */
1036
+    public function __get($name) {
1037
+        // See if its in our base attribute
1038
+        if (array_key_exists($name, $this->attributes)) {
1039
+            return $this->attributes[$name];
1040
+        }
1041
+
1042
+        // @todo clean below - getPrivateSetting() should return null now
1043
+        // No, so see if its in the private data store.
1044
+        // get_private_setting() returns false if it doesn't exist
1045
+        $meta = $this->getPrivateSetting($name);
1046
+
1047
+        if ($meta === false) {
1048
+            // Can't find it, so return null
1049
+            return null;
1050
+        }
1051
+
1052
+        return $meta;
1053
+    }
1054
+
1055
+    /**
1056
+     * Get a value from private settings.
1057
+     *
1058
+     * @param string $name Name
1059
+     * @return mixed
1060
+     * @deprecated 1.9
1061
+     */
1062
+    public function get($name) {
1063
+        elgg_deprecated_notice("Use -> instead of get()", 1.9);
1064
+        return $this->__get($name);
1065
+    }
1066
+
1067
+    /**
1068
+     * Set a value as private setting or attribute.
1069
+     *
1070
+     * Attributes include title and description.
1071
+     *
1072
+     * @param string $name  Name of the attribute or private_setting
1073
+     * @param mixed  $value Value to be set
1074
+     * @return void
1075
+     */
1076
+    public function __set($name, $value) {
1077
+        if (array_key_exists($name, $this->attributes)) {
1078
+            // Check that we're not trying to change the guid!
1079
+            if ((array_key_exists('guid', $this->attributes)) && ($name == 'guid')) {
1080
+                return;
1081
+            }
1082
+
1083
+            $this->attributes[$name] = $value;
1084
+        } else {
1085
+            // to make sure we trigger the correct hooks
1086
+            $this->setSetting($name, $value);
1087
+        }
1088
+    }
1089
+
1090
+    /**
1091
+     * Save a value as private setting or attribute.
1092
+     *
1093
+     * Attributes include title and description.
1094
+     *
1095
+     * @param string $name  Name
1096
+     * @param mixed  $value Value
1097
+     * @return bool
1098
+     */
1099
+    public function set($name, $value) {
1100
+        elgg_deprecated_notice("Use -> instead of set()", 1.9);
1101
+        $this->__set($name, $value);
1102
+
1103
+        return true;
1104
+    }
1105
+
1106
+    /**
1107
+     * Sets the plugin to active or inactive for $site_guid.
1108
+     *
1109
+     * @param bool  $active    Set to active or inactive
1110
+     * @param mixed $site_guid Int for specific site, null for current site.
1111
+     *
1112
+     * @return bool
1113
+     */
1114
+    private function setStatus($active, $site_guid = null) {
1115
+        if (!$this->guid) {
1116
+            return false;
1117
+        }
1118
+
1119
+        if ($site_guid) {
1120
+            $site = get_entity($site_guid);
1121
+
1122
+            if (!($site instanceof \ElggSite)) {
1123
+                return false;
1124
+            }
1125
+        } else {
1126
+            $site = _elgg_services()->configTable->get('site');
1127
+        }
1128
+
1129
+        if ($active) {
1130
+            $result = add_entity_relationship($this->guid, 'active_plugin', $site->guid);
1131
+        } else {
1132
+            $result = remove_entity_relationship($this->guid, 'active_plugin', $site->guid);
1133
+        }
1134
+
1135
+        _elgg_invalidate_plugins_provides_cache();
1136
+        _elgg_services()->boot->invalidateCache();
1137
+
1138
+        return $result;
1139
+    }
1140
+
1141
+    /**
1142
+     * Returns the last error message registered.
1143
+     *
1144
+     * @return string|null
1145
+     */
1146
+    public function getError() {
1147
+        return $this->errorMsg;
1148
+    }
1149
+
1150
+    /**
1151
+     * Returns this plugin's \ElggPluginManifest object
1152
+     *
1153
+     * @return \ElggPluginManifest|null
1154
+     */
1155
+    public function getManifest() {
1156
+        if ($this->manifest instanceof \ElggPluginManifest) {
1157
+            return $this->manifest;
1158
+        }
1159
+
1160
+        try {
1161
+            $package = $this->getPackage();
1162
+            if (!$package) {
1163
+                throw new \Exception('Package cannot be loaded');
1164
+            }
1165
+            $this->manifest = $package->getManifest();
1166
+        } catch (Exception $e) {
1167
+            _elgg_services()->logger->warn("Failed to load manifest for plugin $this->guid. " . $e->getMessage());
1168
+            $this->errorMsg = $e->getmessage();
1169
+        }
1170
+
1171
+        return $this->manifest;
1172
+    }
1173
+
1174
+    /**
1175
+     * Returns this plugin's \ElggPluginPackage object
1176
+     *
1177
+     * @return \ElggPluginPackage|null
1178
+     */
1179
+    public function getPackage() {
1180
+        if ($this->package instanceof \ElggPluginPackage) {
1181
+            return $this->package;
1182
+        }
1183
+
1184
+        try {
1185
+            $this->package = new \ElggPluginPackage($this->path, false);
1186
+        } catch (Exception $e) {
1187
+            _elgg_services()->logger->warn("Failed to load package for $this->guid. " . $e->getMessage());
1188
+            $this->errorMsg = $e->getmessage();
1189
+        }
1190
+
1191
+        return $this->package;
1192
+    }
1193 1193
 }
Please login to merge, or discard this patch.
mod/web_services/start.php 1 patch
Indentation   +186 added lines, -186 removed lines patch added patch discarded remove patch
@@ -6,42 +6,42 @@  discard block
 block discarded – undo
6 6
 elgg_register_event_handler('init', 'system', 'ws_init');
7 7
 
8 8
 function ws_init() {
9
-	$lib_dir = __DIR__ . "/lib";
10
-	elgg_register_library('elgg:ws', "$lib_dir/web_services.php");
11
-	elgg_register_library('elgg:ws:api_user', "$lib_dir/api_user.php");
12
-	elgg_register_library('elgg:ws:client', "$lib_dir/client.php");
13
-	elgg_register_library('elgg:ws:tokens', "$lib_dir/tokens.php");
14
-
15
-	elgg_load_library('elgg:ws:api_user');
16
-	elgg_load_library('elgg:ws:tokens');
17
-
18
-	elgg_register_page_handler('services', 'ws_page_handler');
19
-
20
-	// Register a service handler for the default web services
21
-	// The name rest is a misnomer as they are not RESTful
22
-	elgg_ws_register_service_handler('rest', 'ws_rest_handler');
23
-
24
-	// expose the list of api methods
25
-	elgg_ws_expose_function("system.api.list", "list_all_apis", null,
26
-		elgg_echo("system.api.list"), "GET", false, false);
27
-
28
-	// The authentication token api
29
-	elgg_ws_expose_function(
30
-		"auth.gettoken",
31
-		"auth_gettoken",
32
-		array(
33
-			'username' => array ('type' => 'string'),
34
-			'password' => array ('type' => 'string'),
35
-		),
36
-		elgg_echo('auth.gettoken'),
37
-		'POST',
38
-		false,
39
-		false
40
-	);
41
-
42
-	elgg_register_plugin_hook_handler('unit_test', 'system', 'ws_unit_test');
43
-
44
-	elgg_register_plugin_hook_handler('rest:output', 'system.api.list', 'ws_system_api_list_hook');
9
+    $lib_dir = __DIR__ . "/lib";
10
+    elgg_register_library('elgg:ws', "$lib_dir/web_services.php");
11
+    elgg_register_library('elgg:ws:api_user', "$lib_dir/api_user.php");
12
+    elgg_register_library('elgg:ws:client', "$lib_dir/client.php");
13
+    elgg_register_library('elgg:ws:tokens', "$lib_dir/tokens.php");
14
+
15
+    elgg_load_library('elgg:ws:api_user');
16
+    elgg_load_library('elgg:ws:tokens');
17
+
18
+    elgg_register_page_handler('services', 'ws_page_handler');
19
+
20
+    // Register a service handler for the default web services
21
+    // The name rest is a misnomer as they are not RESTful
22
+    elgg_ws_register_service_handler('rest', 'ws_rest_handler');
23
+
24
+    // expose the list of api methods
25
+    elgg_ws_expose_function("system.api.list", "list_all_apis", null,
26
+        elgg_echo("system.api.list"), "GET", false, false);
27
+
28
+    // The authentication token api
29
+    elgg_ws_expose_function(
30
+        "auth.gettoken",
31
+        "auth_gettoken",
32
+        array(
33
+            'username' => array ('type' => 'string'),
34
+            'password' => array ('type' => 'string'),
35
+        ),
36
+        elgg_echo('auth.gettoken'),
37
+        'POST',
38
+        false,
39
+        false
40
+    );
41
+
42
+    elgg_register_plugin_hook_handler('unit_test', 'system', 'ws_unit_test');
43
+
44
+    elgg_register_plugin_hook_handler('rest:output', 'system.api.list', 'ws_system_api_list_hook');
45 45
 }
46 46
 
47 47
 /**
@@ -62,19 +62,19 @@  discard block
 block discarded – undo
62 62
  * @return bool
63 63
  */
64 64
 function ws_page_handler($segments) {
65
-	elgg_load_library('elgg:ws');
65
+    elgg_load_library('elgg:ws');
66 66
 
67
-	if (!isset($segments[0]) || $segments[0] != 'api') {
68
-		return false;
69
-	}
70
-	array_shift($segments);
67
+    if (!isset($segments[0]) || $segments[0] != 'api') {
68
+        return false;
69
+    }
70
+    array_shift($segments);
71 71
 
72
-	$handler = array_shift($segments);
73
-	$request = implode('/', $segments);
72
+    $handler = array_shift($segments);
73
+    $request = implode('/', $segments);
74 74
 
75
-	service_handler($handler, $request);
75
+    service_handler($handler, $request);
76 76
 
77
-	return true;
77
+    return true;
78 78
 }
79 79
 
80 80
 /**
@@ -140,79 +140,79 @@  discard block
 block discarded – undo
140 140
  * @throws InvalidParameterException
141 141
  */
142 142
 function elgg_ws_expose_function(
143
-	$method,
144
-	$function,
145
-	array $parameters = null,
146
-	$description = "",
147
-	$call_method = "GET",
148
-	$require_api_auth = false,
149
-	$require_user_auth = false,
150
-	$assoc = false
143
+    $method,
144
+    $function,
145
+    array $parameters = null,
146
+    $description = "",
147
+    $call_method = "GET",
148
+    $require_api_auth = false,
149
+    $require_user_auth = false,
150
+    $assoc = false
151 151
 ) {
152 152
 
153
-	global $API_METHODS;
154
-
155
-	if (empty($method) || empty($function)) {
156
-		$msg = elgg_echo('InvalidParameterException:APIMethodOrFunctionNotSet');
157
-		throw new InvalidParameterException($msg);
158
-	}
159
-
160
-	// does not check whether this method has already been exposed - good idea?
161
-	$API_METHODS[$method] = array();
162
-
163
-	$API_METHODS[$method]["description"] = $description;
164
-
165
-	// does not check whether callable - done in execute_method()
166
-	$API_METHODS[$method]["function"] = $function;
167
-
168
-	if ($parameters != NULL) {
169
-		if (!is_array($parameters)) {
170
-			$msg = elgg_echo('InvalidParameterException:APIParametersArrayStructure', array($method));
171
-			throw new InvalidParameterException($msg);
172
-		}
173
-
174
-		// catch common mistake of not setting up param array correctly
175
-		$first = current($parameters);
176
-		if (!is_array($first)) {
177
-			$msg = elgg_echo('InvalidParameterException:APIParametersArrayStructure', array($method));
178
-			throw new InvalidParameterException($msg);
179
-		}
180
-	}
181
-
182
-	if ($parameters != NULL) {
183
-		// ensure the required flag is set correctly in default case for each parameter
184
-		foreach ($parameters as $key => $value) {
185
-			// check if 'required' was specified - if not, make it true
186
-			if (!array_key_exists('required', $value)) {
187
-				$parameters[$key]['required'] = true;
188
-			}
189
-		}
190
-
191
-		$API_METHODS[$method]["parameters"] = $parameters;
192
-	}
193
-
194
-	$call_method = strtoupper($call_method);
195
-	switch ($call_method) {
196
-		case 'POST' :
197
-			$API_METHODS[$method]["call_method"] = 'POST';
198
-			break;
199
-		case 'GET' :
200
-			$API_METHODS[$method]["call_method"] = 'GET';
201
-			break;
202
-		default :
203
-			$msg = elgg_echo('InvalidParameterException:UnrecognisedHttpMethod',
204
-			array($call_method, $method));
205
-
206
-			throw new InvalidParameterException($msg);
207
-	}
208
-
209
-	$API_METHODS[$method]["require_api_auth"] = $require_api_auth;
210
-
211
-	$API_METHODS[$method]["require_user_auth"] = $require_user_auth;
212
-
213
-	$API_METHODS[$method]["assoc"] = (bool)$assoc;
214
-
215
-	return true;
153
+    global $API_METHODS;
154
+
155
+    if (empty($method) || empty($function)) {
156
+        $msg = elgg_echo('InvalidParameterException:APIMethodOrFunctionNotSet');
157
+        throw new InvalidParameterException($msg);
158
+    }
159
+
160
+    // does not check whether this method has already been exposed - good idea?
161
+    $API_METHODS[$method] = array();
162
+
163
+    $API_METHODS[$method]["description"] = $description;
164
+
165
+    // does not check whether callable - done in execute_method()
166
+    $API_METHODS[$method]["function"] = $function;
167
+
168
+    if ($parameters != NULL) {
169
+        if (!is_array($parameters)) {
170
+            $msg = elgg_echo('InvalidParameterException:APIParametersArrayStructure', array($method));
171
+            throw new InvalidParameterException($msg);
172
+        }
173
+
174
+        // catch common mistake of not setting up param array correctly
175
+        $first = current($parameters);
176
+        if (!is_array($first)) {
177
+            $msg = elgg_echo('InvalidParameterException:APIParametersArrayStructure', array($method));
178
+            throw new InvalidParameterException($msg);
179
+        }
180
+    }
181
+
182
+    if ($parameters != NULL) {
183
+        // ensure the required flag is set correctly in default case for each parameter
184
+        foreach ($parameters as $key => $value) {
185
+            // check if 'required' was specified - if not, make it true
186
+            if (!array_key_exists('required', $value)) {
187
+                $parameters[$key]['required'] = true;
188
+            }
189
+        }
190
+
191
+        $API_METHODS[$method]["parameters"] = $parameters;
192
+    }
193
+
194
+    $call_method = strtoupper($call_method);
195
+    switch ($call_method) {
196
+        case 'POST' :
197
+            $API_METHODS[$method]["call_method"] = 'POST';
198
+            break;
199
+        case 'GET' :
200
+            $API_METHODS[$method]["call_method"] = 'GET';
201
+            break;
202
+        default :
203
+            $msg = elgg_echo('InvalidParameterException:UnrecognisedHttpMethod',
204
+            array($call_method, $method));
205
+
206
+            throw new InvalidParameterException($msg);
207
+    }
208
+
209
+    $API_METHODS[$method]["require_api_auth"] = $require_api_auth;
210
+
211
+    $API_METHODS[$method]["require_user_auth"] = $require_user_auth;
212
+
213
+    $API_METHODS[$method]["assoc"] = (bool)$assoc;
214
+
215
+    return true;
216 216
 }
217 217
 
218 218
 /**
@@ -222,11 +222,11 @@  discard block
 block discarded – undo
222 222
  * @return void
223 223
  */
224 224
 function elgg_ws_unexpose_function($method) {
225
-	global $API_METHODS;
225
+    global $API_METHODS;
226 226
 
227
-	if (isset($API_METHODS[$method])) {
228
-		unset($API_METHODS[$method]);
229
-	}
227
+    if (isset($API_METHODS[$method])) {
228
+        unset($API_METHODS[$method]);
229
+    }
230 230
 }
231 231
 
232 232
 /**
@@ -236,12 +236,12 @@  discard block
 block discarded – undo
236 236
  * @access private
237 237
  */
238 238
 function list_all_apis() {
239
-	global $API_METHODS;
239
+    global $API_METHODS;
240 240
 
241
-	// sort first
242
-	ksort($API_METHODS);
241
+    // sort first
242
+    ksort($API_METHODS);
243 243
 
244
-	return $API_METHODS;
244
+    return $API_METHODS;
245 245
 }
246 246
 
247 247
 /**
@@ -253,17 +253,17 @@  discard block
 block discarded – undo
253 253
  * @return bool Depending on success
254 254
  */
255 255
 function elgg_ws_register_service_handler($handler, $function) {
256
-	global $CONFIG;
256
+    global $CONFIG;
257 257
 
258
-	if (!isset($CONFIG->servicehandler)) {
259
-		$CONFIG->servicehandler = array();
260
-	}
261
-	if (is_callable($function, true)) {
262
-		$CONFIG->servicehandler[$handler] = $function;
263
-		return true;
264
-	}
258
+    if (!isset($CONFIG->servicehandler)) {
259
+        $CONFIG->servicehandler = array();
260
+    }
261
+    if (is_callable($function, true)) {
262
+        $CONFIG->servicehandler[$handler] = $function;
263
+        return true;
264
+    }
265 265
 
266
-	return false;
266
+    return false;
267 267
 }
268 268
 
269 269
 /**
@@ -275,11 +275,11 @@  discard block
 block discarded – undo
275 275
  * @return void
276 276
  */
277 277
 function elgg_ws_unregister_service_handler($handler) {
278
-	global $CONFIG;
278
+    global $CONFIG;
279 279
 
280
-	if (isset($CONFIG->servicehandler, $CONFIG->servicehandler[$handler])) {
281
-		unset($CONFIG->servicehandler[$handler]);
282
-	}
280
+    if (isset($CONFIG->servicehandler, $CONFIG->servicehandler[$handler])) {
281
+        unset($CONFIG->servicehandler[$handler]);
282
+    }
283 283
 }
284 284
 
285 285
 /**
@@ -292,58 +292,58 @@  discard block
 block discarded – undo
292 292
  */
293 293
 function ws_rest_handler() {
294 294
 
295
-	$viewtype = elgg_get_viewtype();
295
+    $viewtype = elgg_get_viewtype();
296 296
 
297
-	if (!elgg_view_exists('api/output', $viewtype)) {
298
-		header("HTTP/1.0 400 Bad Request");
299
-		header("Content-type: text/plain");
300
-		echo "Missing view 'api/output' in viewtype '$viewtype'.";
301
-		if (in_array($viewtype, ['xml', 'php'])) {
302
-			echo "\nEnable the 'data_views' plugin to add this view.";
303
-		}
304
-		exit;
305
-	}
297
+    if (!elgg_view_exists('api/output', $viewtype)) {
298
+        header("HTTP/1.0 400 Bad Request");
299
+        header("Content-type: text/plain");
300
+        echo "Missing view 'api/output' in viewtype '$viewtype'.";
301
+        if (in_array($viewtype, ['xml', 'php'])) {
302
+            echo "\nEnable the 'data_views' plugin to add this view.";
303
+        }
304
+        exit;
305
+    }
306 306
 
307
-	elgg_load_library('elgg:ws');
307
+    elgg_load_library('elgg:ws');
308 308
 
309
-	// Register the error handler
310
-	error_reporting(E_ALL);
311
-	set_error_handler('_php_api_error_handler');
309
+    // Register the error handler
310
+    error_reporting(E_ALL);
311
+    set_error_handler('_php_api_error_handler');
312 312
 
313
-	// Register a default exception handler
314
-	set_exception_handler('_php_api_exception_handler');
313
+    // Register a default exception handler
314
+    set_exception_handler('_php_api_exception_handler');
315 315
 
316
-	// plugins should return true to control what API and user authentication handlers are registered
317
-	if (elgg_trigger_plugin_hook('rest', 'init', null, false) == false) {
318
-		// for testing from a web browser, you can use the session PAM
319
-		// do not use for production sites!!
320
-		//register_pam_handler('pam_auth_session');
316
+    // plugins should return true to control what API and user authentication handlers are registered
317
+    if (elgg_trigger_plugin_hook('rest', 'init', null, false) == false) {
318
+        // for testing from a web browser, you can use the session PAM
319
+        // do not use for production sites!!
320
+        //register_pam_handler('pam_auth_session');
321 321
 
322
-		// user token can also be used for user authentication
323
-		register_pam_handler('pam_auth_usertoken');
322
+        // user token can also be used for user authentication
323
+        register_pam_handler('pam_auth_usertoken');
324 324
 
325
-		// simple API key check
326
-		register_pam_handler('api_auth_key', "sufficient", "api");
327
-		// hmac
328
-		register_pam_handler('api_auth_hmac', "sufficient", "api");
329
-	}
325
+        // simple API key check
326
+        register_pam_handler('api_auth_key', "sufficient", "api");
327
+        // hmac
328
+        register_pam_handler('api_auth_hmac', "sufficient", "api");
329
+    }
330 330
 
331
-	// Get parameter variables
332
-	$method = get_input('method');
333
-	$result = null;
331
+    // Get parameter variables
332
+    $method = get_input('method');
333
+    $result = null;
334 334
 
335
-	// this will throw an exception if authentication fails
336
-	authenticate_method($method);
335
+    // this will throw an exception if authentication fails
336
+    authenticate_method($method);
337 337
 
338
-	$result = execute_method($method);
338
+    $result = execute_method($method);
339 339
 
340 340
 
341
-	if (!($result instanceof GenericResult)) {
342
-		throw new APIException(elgg_echo('APIException:ApiResultUnknown'));
343
-	}
341
+    if (!($result instanceof GenericResult)) {
342
+        throw new APIException(elgg_echo('APIException:ApiResultUnknown'));
343
+    }
344 344
 
345
-	// Output the result
346
-	echo elgg_view_page($method, elgg_view("api/output", array("result" => $result)));
345
+    // Output the result
346
+    echo elgg_view_page($method, elgg_view("api/output", array("result" => $result)));
347 347
 }
348 348
 
349 349
 /**
@@ -358,10 +358,10 @@  discard block
 block discarded – undo
358 358
  * @access private
359 359
  */
360 360
 function ws_unit_test($hook, $type, $value, $params) {
361
-	elgg_load_library('elgg:ws');
362
-	elgg_load_library('elgg:ws:client');
363
-	$value[] = dirname(__FILE__) . '/tests/ElggCoreWebServicesApiTest.php';
364
-	return $value;
361
+    elgg_load_library('elgg:ws');
362
+    elgg_load_library('elgg:ws:client');
363
+    $value[] = dirname(__FILE__) . '/tests/ElggCoreWebServicesApiTest.php';
364
+    return $value;
365 365
 }
366 366
 
367 367
 /**
@@ -375,11 +375,11 @@  discard block
 block discarded – undo
375 375
  */
376 376
 function ws_system_api_list_hook($hook, $type, $return, $params) {
377 377
 
378
-	if (!empty($return) && is_array($return)) {
379
-		foreach($return as $method => $settings) {
380
-			unset($return[$method]['function']);
381
-		}
382
-	}
378
+    if (!empty($return) && is_array($return)) {
379
+        foreach($return as $method => $settings) {
380
+            unset($return[$method]['function']);
381
+        }
382
+    }
383 383
 
384
-	return $return;
384
+    return $return;
385 385
 }
Please login to merge, or discard this patch.
engine/classes/Elgg/Database/Seeder.php 1 patch
Indentation   +74 added lines, -74 removed lines patch added patch discarded remove patch
@@ -17,79 +17,79 @@
 block discarded – undo
17 17
  */
18 18
 class Seeder {
19 19
 
20
-	private $seeds = [
21
-		Users::class,
22
-		Groups::class,
23
-		Objects::class,
24
-	];
25
-
26
-	/**
27
-	 * @var PluginHooksService
28
-	 */
29
-	protected $hooks;
30
-
31
-	/**
32
-	 * Seeder constructor.
33
-	 *
34
-	 * @param PluginHooksService $hooks Hooks registration service
35
-	 */
36
-	public function __construct(PluginHooksService $hooks) {
37
-		$this->hooks = $hooks;
38
-	}
39
-
40
-	/**
41
-	 * Load seed scripts
42
-	 *
43
-	 * @return void
44
-	 */
45
-	public function seed() {
46
-		$ia = elgg_set_ignore_access(true);
47
-
48
-		$ha = access_get_show_hidden_status();
49
-		access_show_hidden_entities(true);
20
+    private $seeds = [
21
+        Users::class,
22
+        Groups::class,
23
+        Objects::class,
24
+    ];
25
+
26
+    /**
27
+     * @var PluginHooksService
28
+     */
29
+    protected $hooks;
30
+
31
+    /**
32
+     * Seeder constructor.
33
+     *
34
+     * @param PluginHooksService $hooks Hooks registration service
35
+     */
36
+    public function __construct(PluginHooksService $hooks) {
37
+        $this->hooks = $hooks;
38
+    }
39
+
40
+    /**
41
+     * Load seed scripts
42
+     *
43
+     * @return void
44
+     */
45
+    public function seed() {
46
+        $ia = elgg_set_ignore_access(true);
47
+
48
+        $ha = access_get_show_hidden_status();
49
+        access_show_hidden_entities(true);
50 50
 		
51
-		foreach ($this->seeds as $seed) {
52
-			if (!class_exists($seed)) {
53
-				continue;
54
-			}
55
-			$seed = new $seed();
56
-			if (!is_subclass_of($seed, Seed::class)) {
57
-				continue;
58
-			}
59
-
60
-			$seed->seed();
61
-		}
62
-
63
-		access_show_hidden_entities($ha);
64
-
65
-		elgg_set_ignore_access($ia);
66
-	}
67
-
68
-	/**
69
-	 * Remove all seeded entities
70
-	 * @return void
71
-	 */
72
-	public function unseed() {
73
-
74
-		$ia = elgg_set_ignore_access(true);
75
-
76
-		$ha = access_get_show_hidden_status();
77
-		access_show_hidden_entities(true);
78
-
79
-		foreach ($this->seeds as $seed) {
80
-			if (!class_exists($seed)) {
81
-				continue;
82
-			}
83
-			$seed = new $seed();
84
-			if (!is_subclass_of($seed, Seed::class)) {
85
-				continue;
86
-			}
87
-
88
-			$seed->unseed();
89
-		}
90
-
91
-		access_show_hidden_entities($ha);
92
-
93
-		elgg_set_ignore_access($ia);
94
-	}
51
+        foreach ($this->seeds as $seed) {
52
+            if (!class_exists($seed)) {
53
+                continue;
54
+            }
55
+            $seed = new $seed();
56
+            if (!is_subclass_of($seed, Seed::class)) {
57
+                continue;
58
+            }
59
+
60
+            $seed->seed();
61
+        }
62
+
63
+        access_show_hidden_entities($ha);
64
+
65
+        elgg_set_ignore_access($ia);
66
+    }
67
+
68
+    /**
69
+     * Remove all seeded entities
70
+     * @return void
71
+     */
72
+    public function unseed() {
73
+
74
+        $ia = elgg_set_ignore_access(true);
75
+
76
+        $ha = access_get_show_hidden_status();
77
+        access_show_hidden_entities(true);
78
+
79
+        foreach ($this->seeds as $seed) {
80
+            if (!class_exists($seed)) {
81
+                continue;
82
+            }
83
+            $seed = new $seed();
84
+            if (!is_subclass_of($seed, Seed::class)) {
85
+                continue;
86
+            }
87
+
88
+            $seed->unseed();
89
+        }
90
+
91
+        access_show_hidden_entities($ha);
92
+
93
+        elgg_set_ignore_access($ia);
94
+    }
95 95
 }
96 96
\ No newline at end of file
Please login to merge, or discard this patch.