Completed
Push — 3.6.6 ( 91327a )
by Robbie
10:10
created

Member::disallowedGroups()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 2
nop 0
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
1
<?php
2
/**
3
 * The member class which represents the users of the system
4
 *
5
 * @package framework
6
 * @subpackage security
7
 *
8
 * @property string $FirstName
9
 * @property string $Surname
10
 * @property string $Email
11
 * @property string $Password
12
 * @property string $RememberLoginToken
13
 * @property string $TempIDHash
14
 * @property string $TempIDExpired
15
 * @property int $NumVisit @deprecated 4.0
16
 * @property string $LastVisited @deprecated 4.0
17
 * @property string $AutoLoginHash
18
 * @property string $AutoLoginExpired
19
 * @property string $PasswordEncryption
20
 * @property string $Salt
21
 * @property string $PasswordExpiry
22
 * @property string $LockedOutUntil
23
 * @property string $Locale
24
 * @property int $FailedLoginCount
25
 * @property string $DateFormat
26
 * @property string $TimeFormat
27
 */
28
class Member extends DataObject implements TemplateGlobalProvider {
29
30
	private static $db = array(
31
		'FirstName' => 'Varchar',
32
		'Surname' => 'Varchar',
33
		'Email' => 'Varchar(254)', // See RFC 5321, Section 4.5.3.1.3. (256 minus the < and > character)
34
		'TempIDHash' => 'Varchar(160)', // Temporary id used for cms re-authentication
35
		'TempIDExpired' => 'SS_Datetime', // Expiry of temp login
36
		'Password' => 'Varchar(160)',
37
		'RememberLoginToken' => 'Varchar(160)', // Note: this currently holds a hash, not a token.
38
		'NumVisit' => 'Int', // @deprecated 4.0
39
		'LastVisited' => 'SS_Datetime', // @deprecated 4.0
40
		'AutoLoginHash' => 'Varchar(160)', // Used to auto-login the user on password reset
41
		'AutoLoginExpired' => 'SS_Datetime',
42
		// This is an arbitrary code pointing to a PasswordEncryptor instance,
43
		// not an actual encryption algorithm.
44
		// Warning: Never change this field after its the first password hashing without
45
		// providing a new cleartext password as well.
46
		'PasswordEncryption' => "Varchar(50)",
47
		'Salt' => 'Varchar(50)',
48
		'PasswordExpiry' => 'Date',
49
		'LockedOutUntil' => 'SS_Datetime',
50
		'Locale' => 'Varchar(6)',
51
		// handled in registerFailedLogin(), only used if $lock_out_after_incorrect_logins is set
52
		'FailedLoginCount' => 'Int',
53
		// In ISO format
54
		'DateFormat' => 'Varchar(30)',
55
		'TimeFormat' => 'Varchar(30)',
56
	);
57
58
	private static $belongs_many_many = array(
59
		'Groups' => 'Group',
60
	);
61
62
	private static $has_one = array();
63
64
	private static $has_many = array(
65
		'LoggedPasswords' => 'MemberPassword',
66
	);
67
68
	private static $many_many = array();
69
70
	private static $many_many_extraFields = array();
71
72
	private static $default_sort = '"Surname", "FirstName"';
73
74
	private static $indexes = array(
75
		'Email' => true,
76
		//Removed due to duplicate null values causing MSSQL problems
77
		//'AutoLoginHash' => Array('type'=>'unique', 'value'=>'AutoLoginHash', 'ignoreNulls'=>true)
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
78
	);
79
80
	/**
81
	 * @config
82
	 * @var boolean
83
	 */
84
	private static $notify_password_change = false;
85
86
	/**
87
	 * Flag whether or not member visits should be logged (count only)
88
	 *
89
	 * @deprecated 4.0
90
	 * @var bool
91
	 * @config
92
	 */
93
	private static $log_last_visited = true;
94
95
	/**
96
	 * Flag whether we should count number of visits
97
	 *
98
	 * @deprecated 4.0
99
	 * @var bool
100
	 * @config
101
	 */
102
	private static $log_num_visits = true;
103
104
	/**
105
	 * All searchable database columns
106
	 * in this object, currently queried
107
	 * with a "column LIKE '%keywords%'
108
	 * statement.
109
	 *
110
	 * @var array
111
	 * @todo Generic implementation of $searchable_fields on DataObject,
112
	 * with definition for different searching algorithms
113
	 * (LIKE, FULLTEXT) and default FormFields to construct a searchform.
114
	 */
115
	private static $searchable_fields = array(
116
		'FirstName',
117
		'Surname',
118
		'Email',
119
	);
120
121
	/**
122
	 * @config
123
	 * @var array
124
	 */
125
	private static $summary_fields = array(
126
		'FirstName',
127
		'Surname',
128
		'Email',
129
	);
130
131
	/**
132
	 * @config
133
	 * @var array
134
	 */
135
	private static $casting = array(
136
		'Name' => 'Varchar',
137
	);
138
139
	/**
140
	 * Internal-use only fields
141
	 *
142
	 * @config
143
	 * @var array
144
	 */
145
	private static $hidden_fields = array(
146
		'RememberLoginToken',
147
		'AutoLoginHash',
148
		'AutoLoginExpired',
149
		'PasswordEncryption',
150
		'PasswordExpiry',
151
		'LockedOutUntil',
152
		'TempIDHash',
153
		'TempIDExpired',
154
		'Salt',
155
		'NumVisit', // @deprecated 4.0
156
	);
157
158
	/**
159
	 * @config
160
	 * @var Array See {@link set_title_columns()}
161
	 */
162
	private static $title_format = null;
163
164
	/**
165
	 * The unique field used to identify this member.
166
	 * By default, it's "Email", but another common
167
	 * field could be Username.
168
	 *
169
	 * @config
170
	 * @var string
171
	 */
172
	private static $unique_identifier_field = 'Email';
173
174
	/**
175
	 * @config
176
	 * {@link PasswordValidator} object for validating user's password
177
	 */
178
	private static $password_validator = null;
179
180
	/**
181
	 * @config
182
	 * The number of days that a password should be valid for.
183
	 * By default, this is null, which means that passwords never expire
184
	 */
185
	private static $password_expiry_days = null;
186
187
	/**
188
	 * @config
189
	 * @var Int Number of incorrect logins after which
190
	 * the user is blocked from further attempts for the timespan
191
	 * defined in {@link $lock_out_delay_mins}.
192
	 */
193
	private static $lock_out_after_incorrect_logins = 10;
194
195
	/**
196
	 * @config
197
	 * @var integer Minutes of enforced lockout after incorrect password attempts.
198
	 * Only applies if {@link $lock_out_after_incorrect_logins} greater than 0.
199
	 */
200
	private static $lock_out_delay_mins = 15;
201
202
	/**
203
	 * @config
204
	 * @var String If this is set, then a session cookie with the given name will be set on log-in,
205
	 * and cleared on logout.
206
	 */
207
	private static $login_marker_cookie = null;
208
209
	/**
210
	 * Indicates that when a {@link Member} logs in, Member:session_regenerate_id()
211
	 * should be called as a security precaution.
212
	 *
213
	 * This doesn't always work, especially if you're trying to set session cookies
214
	 * across an entire site using the domain parameter to session_set_cookie_params()
215
	 *
216
	 * @config
217
	 * @var boolean
218
	 */
219
	private static $session_regenerate_id = true;
220
221
222
	/**
223
	 * Default lifetime of temporary ids.
224
	 *
225
	 * This is the period within which a user can be re-authenticated within the CMS by entering only their password
226
	 * and without losing their workspace.
227
	 *
228
	 * Any session expiration outside of this time will require them to login from the frontend using their full
229
	 * username and password.
230
	 *
231
	 * Defaults to 72 hours. Set to zero to disable expiration.
232
	 *
233
	 * @config
234
	 * @var int Lifetime in seconds
235
	 */
236
	private static $temp_id_lifetime = 259200;
237
238
	/**
239
	 * @deprecated 4.0 Use the "Member.session_regenerate_id" config setting instead
240
	 */
241
	public static function set_session_regenerate_id($bool) {
242
		Deprecation::notice('4.0', 'Use the "Member.session_regenerate_id" config setting instead');
243
		self::config()->session_regenerate_id = $bool;
0 ignored issues
show
Documentation introduced by
The property session_regenerate_id does not exist on object<Config_ForClass>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
244
	}
245
246
	/**
247
	 * Ensure the locale is set to something sensible by default.
248
	 */
249
	public function populateDefaults() {
250
		parent::populateDefaults();
251
		$this->Locale = i18n::get_closest_translation(i18n::get_locale());
252
	}
253
254
	public function requireDefaultRecords() {
255
		parent::requireDefaultRecords();
256
		// Default groups should've been built by Group->requireDefaultRecords() already
257
		static::default_admin();
258
	}
259
260
	/**
261
	 * Get the default admin record if it exists, or creates it otherwise if enabled
262
	 *
263
	 * @return Member
264
	 */
265
	public static function default_admin() {
266
		// Check if set
267
		if(!Security::has_default_admin()) return null;
268
269
		// Find or create ADMIN group
270
		singleton('Group')->requireDefaultRecords();
271
		$adminGroup = Permission::get_groups_by_permission('ADMIN')->First();
272
273
		// Find member
274
		$admin = Member::get()
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
275
			->filter('Email', Security::default_admin_username())
276
			->first();
277
		if(!$admin) {
278
			// 'Password' is not set to avoid creating
279
			// persistent logins in the database. See Security::setDefaultAdmin().
280
			// Set 'Email' to identify this as the default admin
281
			$admin = Member::create();
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
282
			$admin->FirstName = _t('Member.DefaultAdminFirstname', 'Default Admin');
283
			$admin->Email = Security::default_admin_username();
284
			$admin->write();
285
		}
286
287
		// Ensure this user is in the admin group
288
		if(!$admin->inGroup($adminGroup)) {
289
			// Add member to group instead of adding group to member
290
			// This bypasses the privilege escallation code in Member_GroupSet
291
			$adminGroup
292
				->DirectMembers()
293
				->add($admin);
294
		}
295
296
		return $admin;
297
	}
298
299
	/**
300
	 * If this is called, then a session cookie will be set to "1" whenever a user
301
	 * logs in.  This lets 3rd party tools, such as apache's mod_rewrite, detect
302
	 * whether a user is logged in or not and alter behaviour accordingly.
303
	 *
304
	 * One known use of this is to bypass static caching for logged in users.  This is
305
	 * done by putting this into _config.php
306
	 * <pre>
307
	 * Member::set_login_marker_cookie("SS_LOGGED_IN");
308
	 * </pre>
309
	 *
310
	 * And then adding this condition to each of the rewrite rules that make use of
311
	 * the static cache.
312
	 * <pre>
313
	 * RewriteCond %{HTTP_COOKIE} !SS_LOGGED_IN=1
314
	 * </pre>
315
	 *
316
	 * @deprecated 4.0 Use the "Member.login_marker_cookie" config setting instead
317
	 * @param $cookieName string The name of the cookie to set.
318
	 */
319
	public static function set_login_marker_cookie($cookieName) {
320
		Deprecation::notice('4.0', 'Use the "Member.login_marker_cookie" config setting instead');
321
		self::config()->login_marker_cookie = $cookieName;
0 ignored issues
show
Documentation introduced by
The property login_marker_cookie does not exist on object<Config_ForClass>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
322
	}
323
324
	/**
325
	 * Check if the passed password matches the stored one (if the member is not locked out).
326
	 *
327
	 * @param string $password
328
	 * @return ValidationResult
329
	 */
330
	public function checkPassword($password) {
331
		$result = $this->canLogIn();
332
333
		// Short-circuit the result upon failure, no further checks needed.
334
		if (!$result->valid()) {
335
			return $result;
336
		}
337
338
		// Allow default admin to login as self
339
		if($this->isDefaultAdmin() && Security::check_default_admin($this->Email, $password)) {
340
			return $result;
341
		}
342
343
		// Check a password is set on this member
344
		if(empty($this->Password) && $this->exists()) {
345
			$result->error(_t('Member.NoPassword','There is no password on this member.'));
346
			return $result;
347
		}
348
349
		$e = PasswordEncryptor::create_for_algorithm($this->PasswordEncryption);
350
		if(!$e->check($this->Password, $password, $this->Salt, $this)) {
351
			$result->error(_t (
352
				'Member.ERRORWRONGCRED',
353
				'The provided details don\'t seem to be correct. Please try again.'
354
			));
355
		}
356
357
		return $result;
358
	}
359
360
	/**
361
	 * Check if this user is the currently configured default admin
362
	 *
363
	 * @return bool
364
	 */
365
	public function isDefaultAdmin() {
366
		return Security::has_default_admin()
367
			&& $this->Email === Security::default_admin_username();
368
	}
369
370
	/**
371
	 * Returns a valid {@link ValidationResult} if this member can currently log in, or an invalid
372
	 * one with error messages to display if the member is locked out.
373
	 *
374
	 * You can hook into this with a "canLogIn" method on an attached extension.
375
	 *
376
	 * @return ValidationResult
377
	 */
378
	public function canLogIn() {
379
		$result = ValidationResult::create();
380
381
		if($this->isLockedOut()) {
382
			$result->error(
383
				_t(
384
					'Member.ERRORLOCKEDOUT2',
385
					'Your account has been temporarily disabled because of too many failed attempts at ' .
386
					'logging in. Please try again in {count} minutes.',
387
					null,
388
					array('count' => $this->config()->lock_out_delay_mins)
389
				)
390
			);
391
		}
392
393
		$this->extend('canLogIn', $result);
394
		return $result;
395
	}
396
397
	/**
398
	 * Returns true if this user is locked out
399
	 */
400
	public function isLockedOut() {
401
		$state = true;
402
		if ($this->LockedOutUntil && $this->dbObject('LockedOutUntil')->InFuture()) {
403
			$state = true;
404
		} elseif ($this->config()->lock_out_after_incorrect_logins <= 0) {
405
			$state = false;
406
		} else {
407
			$email = $this->{static::config()->unique_identifier_field};
408
			$attempts = LoginAttempt::getByEmail($email)
409
				->sort('Created', 'DESC')
410
				->limit($this->config()->lock_out_after_incorrect_logins);
411
412
			if ($attempts->count() < $this->config()->lock_out_after_incorrect_logins) {
413
				$state = false;
414
			} else {
415
416
				$success = false;
417
				foreach ($attempts as $attempt) {
418
					if ($attempt->Status === 'Success') {
419
						$success = true;
420
						$state = false;
421
						break;
422
					}
423
				}
424
425
				if (!$success) {
426
					$lockedOutUntil = $attempts->first()->dbObject('Created')->Format('U')
427
					                  + ($this->config()->lock_out_delay_mins * 60);
428
					if (SS_Datetime::now()->Format('U') < $lockedOutUntil) {
429
						$state = true;
430
					} else {
431
						$state = false;
432
					}
433
				}
434
			}
435
		}
436
437
		$this->extend('updateIsLockedOut', $state);
438
		return $state;
439
	}
440
441
	/**
442
	 * Regenerate the session_id.
443
	 * This wrapper is here to make it easier to disable calls to session_regenerate_id(), should you need to.
444
	 * They have caused problems in certain
445
	 * quirky problems (such as using the Windmill 0.3.6 proxy).
446
	 */
447
	public static function session_regenerate_id() {
448
		if(!self::config()->session_regenerate_id) return;
449
450
		// This can be called via CLI during testing.
451
		if(Director::is_cli()) return;
452
453
		$file = '';
454
		$line = '';
455
456
		// @ is to supress win32 warnings/notices when session wasn't cleaned up properly
457
		// There's nothing we can do about this, because it's an operating system function!
458
		if(!headers_sent($file, $line)) @session_regenerate_id(true);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
459
	}
460
461
	/**
462
	 * Get the field used for uniquely identifying a member
463
	 * in the database. {@see Member::$unique_identifier_field}
464
	 *
465
	 * @deprecated 4.0 Use the "Member.unique_identifier_field" config setting instead
466
	 * @return string
467
	 */
468
	public static function get_unique_identifier_field() {
469
		Deprecation::notice('4.0', 'Use the "Member.unique_identifier_field" config setting instead');
470
		return Member::config()->unique_identifier_field;
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
471
	}
472
473
	/**
474
	 * Set the field used for uniquely identifying a member
475
	 * in the database. {@see Member::$unique_identifier_field}
476
	 *
477
	 * @deprecated 4.0 Use the "Member.unique_identifier_field" config setting instead
478
	 * @param $field The field name to set as the unique field
479
	 */
480
	public static function set_unique_identifier_field($field) {
481
		Deprecation::notice('4.0', 'Use the "Member.unique_identifier_field" config setting instead');
482
		Member::config()->unique_identifier_field = $field;
0 ignored issues
show
Documentation introduced by
The property unique_identifier_field does not exist on object<Config_ForClass>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
483
	}
484
485
	/**
486
	 * Set a {@link PasswordValidator} object to use to validate member's passwords.
487
	 */
488
	public static function set_password_validator($pv) {
489
		self::$password_validator = $pv;
490
	}
491
492
	/**
493
	 * Returns the current {@link PasswordValidator}
494
	 */
495
	public static function password_validator() {
496
		return self::$password_validator;
497
	}
498
499
	/**
500
	 * Set the number of days that a password should be valid for.
501
	 * Set to null (the default) to have passwords never expire.
502
	 *
503
	 * @deprecated 4.0 Use the "Member.password_expiry_days" config setting instead
504
	 */
505
	public static function set_password_expiry($days) {
506
		Deprecation::notice('4.0', 'Use the "Member.password_expiry_days" config setting instead');
507
		self::config()->password_expiry_days = $days;
0 ignored issues
show
Documentation introduced by
The property password_expiry_days does not exist on object<Config_ForClass>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
508
	}
509
510
	/**
511
	 * Configure the security system to lock users out after this many incorrect logins
512
	 *
513
	 * @deprecated 4.0 Use the "Member.lock_out_after_incorrect_logins" config setting instead
514
	 */
515
	public static function lock_out_after_incorrect_logins($numLogins) {
516
		Deprecation::notice('4.0', 'Use the "Member.lock_out_after_incorrect_logins" config setting instead');
517
		self::config()->lock_out_after_incorrect_logins = $numLogins;
0 ignored issues
show
Documentation introduced by
The property lock_out_after_incorrect_logins does not exist on object<Config_ForClass>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
518
	}
519
520
521
	public function isPasswordExpired() {
522
		if(!$this->PasswordExpiry) return false;
523
		return strtotime(date('Y-m-d')) >= strtotime($this->PasswordExpiry);
524
	}
525
526
	/**
527
	 * Logs this member in
528
	 *
529
	 * @param bool $remember If set to TRUE, the member will be logged in automatically the next time.
530
	 */
531
	public function logIn($remember = false) {
532
		$this->extend('beforeMemberLoggedIn');
533
534
		self::session_regenerate_id();
535
536
		Session::set("loggedInAs", $this->ID);
537
		// This lets apache rules detect whether the user has logged in
538
		if(Member::config()->login_marker_cookie) Cookie::set(Member::config()->login_marker_cookie, 1, 0);
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
539
540
		$this->addVisit();
0 ignored issues
show
Deprecated Code introduced by
The method Member::addVisit() has been deprecated with message: 4.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
541
542
		// Only set the cookie if autologin is enabled
543
		if($remember && Security::config()->autologin_enabled) {
544
			// Store the hash and give the client the cookie with the token.
545
			$generator = new RandomGenerator();
546
			$token = $generator->randomToken('sha1');
547
			$hash = $this->encryptWithUserSettings($token);
548
			$this->RememberLoginToken = $hash;
549
			Cookie::set('alc_enc', $this->ID . ':' . $token, 90, null, null, null, true);
550
		} else {
551
			$this->RememberLoginToken = null;
552
			Cookie::force_expiry('alc_enc');
553
		}
554
555
		// Clear the incorrect log-in count
556
		$this->registerSuccessfulLogin();
557
558
		// Don't set column if its not built yet (the login might be precursor to a /dev/build...)
559
		if(array_key_exists('LockedOutUntil', DB::field_list('Member'))) {
560
			$this->LockedOutUntil = null;
561
		}
562
563
		$this->regenerateTempID();
564
565
		$this->write();
566
567
		// Audit logging hook
568
		$this->extend('memberLoggedIn');
569
	}
570
571
	/**
572
	 * @deprecated 4.0
573
	 */
574
	public function addVisit() {
575
		if($this->config()->log_num_visits) {
576
			Deprecation::notice(
577
				'4.0',
578
				'Member::$NumVisit is deprecated. From 4.0 onwards you should implement this as a custom extension'
579
			);
580
			$this->NumVisit++;
581
		}
582
	}
583
584
	/**
585
	 * Trigger regeneration of TempID.
586
	 *
587
	 * This should be performed any time the user presents their normal identification (normally Email)
588
	 * and is successfully authenticated.
589
	 */
590
	public function regenerateTempID() {
591
		$generator = new RandomGenerator();
592
		$this->TempIDHash = $generator->randomToken('sha1');
593
		$this->TempIDExpired = self::config()->temp_id_lifetime
594
			? date('Y-m-d H:i:s', strtotime(SS_Datetime::now()->getValue()) + self::config()->temp_id_lifetime)
595
			: null;
596
		$this->write();
597
	}
598
599
	/**
600
	 * Check if the member ID logged in session actually
601
	 * has a database record of the same ID. If there is
602
	 * no logged in user, FALSE is returned anyway.
603
	 *
604
	 * @return boolean TRUE record found FALSE no record found
605
	 */
606
	public static function logged_in_session_exists() {
607
		if($id = Member::currentUserID()) {
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
608
			if($member = DataObject::get_by_id('Member', $id)) {
609
				if($member->exists()) return true;
610
			}
611
		}
612
613
		return false;
614
	}
615
616
	/**
617
	 * Log the user in if the "remember login" cookie is set
618
	 *
619
	 * The <i>remember login token</i> will be changed on every successful
620
	 * auto-login.
621
	 */
622
	public static function autoLogin() {
623
		// Don't bother trying this multiple times
624
		self::$_already_tried_to_auto_log_in = true;
625
626
		if(!Security::config()->autologin_enabled
627
			|| strpos(Cookie::get('alc_enc'), ':') === false
628
			|| Session::get("loggedInAs")
629
			|| !Security::database_is_ready()
630
		) {
631
			return;
632
		}
633
634
		list($uid, $token) = explode(':', Cookie::get('alc_enc'), 2);
635
636
		if (!$uid || !$token) {
637
			return;
638
		}
639
640
		$member = DataObject::get_by_id("Member", $uid);
641
642
		// check if autologin token matches
643
		if($member) {
644
			$hash = $member->encryptWithUserSettings($token);
645
			if(!$member->RememberLoginToken || $member->RememberLoginToken !== $hash) {
646
				$member = null;
647
			}
648
		}
649
650
		if($member) {
651
			self::session_regenerate_id();
652
			Session::set("loggedInAs", $member->ID);
653
			// This lets apache rules detect whether the user has logged in
654
			if(Member::config()->login_marker_cookie) {
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
655
				Cookie::set(Member::config()->login_marker_cookie, 1, 0, null, null, false, true);
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
656
			}
657
658
			$generator = new RandomGenerator();
659
			$token = $generator->randomToken('sha1');
660
			$hash = $member->encryptWithUserSettings($token);
661
			$member->RememberLoginToken = $hash;
0 ignored issues
show
Documentation introduced by
The property RememberLoginToken does not exist on object<DataObject>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
662
			Cookie::set('alc_enc', $member->ID . ':' . $token, 90, null, null, false, true);
663
664
			$member->addVisit();
665
			$member->write();
666
667
			// Audit logging hook
668
			$member->extend('memberAutoLoggedIn');
669
		}
670
	}
671
672
	/**
673
	 * Logs this member out.
674
	 */
675
	public function logOut() {
676
		$this->extend('beforeMemberLoggedOut');
677
678
		Session::clear("loggedInAs");
679
		if(Member::config()->login_marker_cookie) Cookie::set(Member::config()->login_marker_cookie, null, 0);
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
680
681
		Session::destroy();
682
683
		$this->extend('memberLoggedOut');
684
685
		$this->RememberLoginToken = null;
686
		Cookie::force_expiry('alc_enc');
687
688
		// Switch back to live in order to avoid infinite loops when
689
		// redirecting to the login screen (if this login screen is versioned)
690
		Session::clear('readingMode');
691
692
		$this->write();
693
694
		// Audit logging hook
695
		$this->extend('memberLoggedOut');
696
	}
697
698
	/**
699
	 * Utility for generating secure password hashes for this member.
700
	 */
701
	public function encryptWithUserSettings($string) {
702
		if (!$string) return null;
703
704
		// If the algorithm or salt is not available, it means we are operating
705
		// on legacy account with unhashed password. Do not hash the string.
706
		if (!$this->PasswordEncryption) {
707
			return $string;
708
		}
709
710
		// We assume we have PasswordEncryption and Salt available here.
711
		$e = PasswordEncryptor::create_for_algorithm($this->PasswordEncryption);
712
		return $e->encrypt($string, $this->Salt);
713
714
	}
715
716
	/**
717
	 * Generate an auto login token which can be used to reset the password,
718
	 * at the same time hashing it and storing in the database.
719
	 *
720
	 * @param int $lifetime The lifetime of the auto login hash in days (by default 2 days)
721
	 *
722
	 * @returns string Token that should be passed to the client (but NOT persisted).
723
	 *
724
	 * @todo Make it possible to handle database errors such as a "duplicate key" error
725
	 */
726
	public function generateAutologinTokenAndStoreHash($lifetime = 2) {
727
		do {
728
			$generator = new RandomGenerator();
729
			$token = $generator->randomToken();
730
			$hash = $this->encryptWithUserSettings($token);
731
		} while(DataObject::get_one('Member', array(
732
			'"Member"."AutoLoginHash"' => $hash
733
		)));
734
735
		$this->AutoLoginHash = $hash;
736
		$this->AutoLoginExpired = date('Y-m-d H:i:s', time() + (86400 * $lifetime));
737
738
		$this->write();
739
740
		return $token;
741
	}
742
743
	/**
744
	 * Check the token against the member.
745
	 *
746
	 * @param string $autologinToken
747
	 *
748
	 * @returns bool Is token valid?
749
	 */
750
	public function validateAutoLoginToken($autologinToken) {
751
		$hash = $this->encryptWithUserSettings($autologinToken);
752
		$member = self::member_from_autologinhash($hash, false);
753
		return (bool)$member;
754
	}
755
756
	/**
757
	 * Return the member for the auto login hash
758
	 *
759
	 * @param string $hash The hash key
760
	 * @param bool $login Should the member be logged in?
761
	 *
762
	 * @return Member the matching member, if valid
763
	 * @return Member
764
	 */
765
	public static function member_from_autologinhash($hash, $login = false) {
766
767
		$nowExpression = DB::get_conn()->now();
768
		$member = DataObject::get_one('Member', array(
769
			"\"Member\".\"AutoLoginHash\"" => $hash,
770
			"\"Member\".\"AutoLoginExpired\" > $nowExpression" // NOW() can't be parameterised
771
		));
772
773
		if($login && $member) $member->logIn();
774
775
		return $member;
776
	}
777
778
	/**
779
	 * Find a member record with the given TempIDHash value
780
	 *
781
	 * @param string $tempid
782
	 * @return Member
783
	 */
784
	public static function member_from_tempid($tempid) {
785
		$members = Member::get()
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
786
			->filter('TempIDHash', $tempid);
787
788
		// Exclude expired
789
		if(static::config()->temp_id_lifetime) {
790
			$members = $members->filter('TempIDExpired:GreaterThan', SS_Datetime::now()->getValue());
791
		}
792
793
		return $members->first();
794
	}
795
796
	/**
797
	 * Returns the fields for the member form - used in the registration/profile module.
798
	 * It should return fields that are editable by the admin and the logged-in user.
799
	 *
800
	 * @return FieldList Returns a {@link FieldList} containing the fields for
801
	 *                   the member form.
802
	 */
803
	public function getMemberFormFields() {
804
		$fields = parent::getFrontendFields();
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (getFrontendFields() instead of getMemberFormFields()). Are you sure this is correct? If so, you might want to change this to $this->getFrontendFields().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
805
806
		$fields->replaceField('Password', $this->getMemberPasswordField());
807
808
		$fields->replaceField('Locale', new DropdownField (
809
			'Locale',
810
			$this->fieldLabel('Locale'),
811
			i18n::get_existing_translations()
812
		));
813
814
		$fields->removeByName(static::config()->hidden_fields);
815
		$fields->removeByName('LastVisited');
816
		$fields->removeByName('FailedLoginCount');
817
818
819
		$this->extend('updateMemberFormFields', $fields);
820
		return $fields;
821
	}
822
823
	/**
824
	 * Builds "Change / Create Password" field for this member
825
	 *
826
	 * @return ConfirmedPasswordField
827
	 */
828
	public function getMemberPasswordField() {
829
		$editingPassword = $this->isInDB();
830
		$label = $editingPassword
831
			? _t('Member.EDIT_PASSWORD', 'New Password')
832
			: $this->fieldLabel('Password');
833
		/** @var ConfirmedPasswordField $password */
834
		$password = ConfirmedPasswordField::create(
835
			'Password',
836
			$label,
837
			null,
838
			null,
839
			$editingPassword
840
		);
841
842
		// If editing own password, require confirmation of existing
843
		if($editingPassword && $this->ID == Member::currentUserID()) {
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
844
			$password->setRequireExistingPassword(true);
845
		}
846
847
		$password->setCanBeEmpty(true);
848
		$this->extend('updateMemberPasswordField', $password);
849
		return $password;
850
	}
851
852
853
	/**
854
	 * Returns the {@link RequiredFields} instance for the Member object. This
855
	 * Validator is used when saving a {@link CMSProfileController} or added to
856
	 * any form responsible for saving a users data.
857
	 *
858
	 * To customize the required fields, add a {@link DataExtension} to member
859
	 * calling the `updateValidator()` method.
860
	 *
861
	 * @return Member_Validator
862
	 */
863
	public function getValidator() {
864
		$validator = Injector::inst()->create('Member_Validator');
865
		$validator->setForMember($this);
866
		$this->extend('updateValidator', $validator);
867
868
		return $validator;
869
	}
870
871
872
	/**
873
	 * Returns the current logged in user
874
	 *
875
	 * @return Member|null
876
	 */
877
	public static function currentUser() {
878
		$id = Member::currentUserID();
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
879
880
		if($id) {
881
			return DataObject::get_by_id('Member', $id) ?: null;
882
		}
883
	}
884
885
	/**
886
	 * Get the ID of the current logged in user
887
	 *
888
	 * @return int Returns the ID of the current logged in user or 0.
889
	 */
890
	public static function currentUserID() {
891
		$id = Session::get("loggedInAs");
892
		if(!$id && !self::$_already_tried_to_auto_log_in) {
893
			self::autoLogin();
894
			$id = Session::get("loggedInAs");
895
		}
896
897
		return is_numeric($id) ? (int) $id : 0;
898
	}
899
	private static $_already_tried_to_auto_log_in = false;
900
901
902
	/*
903
	 * Generate a random password, with randomiser to kick in if there's no words file on the
904
	 * filesystem.
905
	 *
906
	 * @return string Returns a random password.
907
	 */
908
	public static function create_new_password() {
909
		$words = Config::inst()->get('Security', 'word_list');
910
911
		if($words && file_exists($words)) {
912
			$words = file($words);
913
914
			list($usec, $sec) = explode(' ', microtime());
915
			srand($sec + ((float) $usec * 100000));
916
917
			$word = trim($words[rand(0,sizeof($words)-1)]);
918
			$number = rand(10,999);
919
920
			return $word . $number;
921
		} else {
922
			$random = rand();
923
			$string = md5($random);
924
			$output = substr($string, 0, 8);
925
			return $output;
926
		}
927
	}
928
929
	/**
930
	 * Event handler called before writing to the database.
931
	 */
932
	public function onBeforeWrite() {
933
		if($this->SetPassword) $this->Password = $this->SetPassword;
0 ignored issues
show
Bug introduced by
The property SetPassword does not seem to exist. Did you mean Password?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
934
935
		// If a member with the same "unique identifier" already exists with a different ID, don't allow merging.
936
		// Note: This does not a full replacement for safeguards in the controller layer (e.g. in a registration form),
937
		// but rather a last line of defense against data inconsistencies.
938
		$identifierField = Member::config()->unique_identifier_field;
0 ignored issues
show
Documentation introduced by
The property unique_identifier_field does not exist on object<Config_ForClass>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
939
		if($this->$identifierField) {
940
941
			// Note: Same logic as Member_Validator class
942
			$filter = array("\"$identifierField\"" => $this->$identifierField);
943
			if($this->ID) {
944
				$filter[] = array('"Member"."ID" <> ?' => $this->ID);
945
			}
946
			$existingRecord = DataObject::get_one('Member', $filter);
947
948
			if($existingRecord) {
949
				throw new ValidationException(ValidationResult::create(false, _t(
950
					'Member.ValidationIdentifierFailed',
951
					'Can\'t overwrite existing member #{id} with identical identifier ({name} = {value}))',
952
					'Values in brackets show "fieldname = value", usually denoting an existing email address',
953
					array(
954
						'id' => $existingRecord->ID,
955
						'name' => $identifierField,
956
						'value' => $this->$identifierField
957
					)
958
				)));
959
			}
960
		}
961
962
		// We don't send emails out on dev/tests sites to prevent accidentally spamming users.
963
		// However, if TestMailer is in use this isn't a risk.
964
		if(
965
			(Director::isLive() || Email::mailer() instanceof TestMailer)
966
			&& $this->isChanged('Password')
967
			&& $this->record['Password']
968
			&& $this->config()->notify_password_change
969
		) {
970
			$e = Member_ChangePasswordEmail::create();
971
			$e->populateTemplate($this);
972
			$e->setTo($this->Email);
973
			$e->send();
974
		}
975
976
		// The test on $this->ID is used for when records are initially created.
977
		// Note that this only works with cleartext passwords, as we can't rehash
978
		// existing passwords.
979
		if((!$this->ID && $this->Password) || $this->isChanged('Password')) {
980
			//reset salt so that it gets regenerated - this will invalidate any persistant login cookies
981
			// or other information encrypted with this Member's settings (see self::encryptWithUserSettings)
982
			$this->Salt = '';
983
			// Password was changed: encrypt the password according the settings
984
			$encryption_details = Security::encrypt_password(
985
				$this->Password, // this is assumed to be cleartext
986
				$this->Salt,
987
				$this->isChanged('PasswordEncryption') ? $this->PasswordEncryption : null,
988
				$this
989
			);
990
991
			// Overwrite the Password property with the hashed value
992
			$this->Password = $encryption_details['password'];
993
			$this->Salt = $encryption_details['salt'];
994
			$this->PasswordEncryption = $encryption_details['algorithm'];
995
996
			// If we haven't manually set a password expiry
997
			if(!$this->isChanged('PasswordExpiry')) {
998
				// then set it for us
999
				if(self::config()->password_expiry_days) {
1000
					$this->PasswordExpiry = date('Y-m-d', time() + 86400 * self::config()->password_expiry_days);
1001
				} else {
1002
					$this->PasswordExpiry = null;
1003
				}
1004
			}
1005
		}
1006
1007
		// save locale
1008
		if(!$this->Locale) {
1009
			$this->Locale = i18n::get_locale();
1010
		}
1011
1012
		parent::onBeforeWrite();
1013
	}
1014
1015
	public function onAfterWrite() {
1016
		parent::onAfterWrite();
1017
1018
		Permission::flush_permission_cache();
1019
1020
		if($this->isChanged('Password')) {
1021
			MemberPassword::log($this);
1022
		}
1023
	}
1024
1025
	public function onAfterDelete() {
1026
		parent::onAfterDelete();
1027
1028
		//prevent orphaned records remaining in the DB
1029
		$this->deletePasswordLogs();
1030
	}
1031
1032
	/**
1033
	 * Delete the MemberPassword objects that are associated to this user
1034
	 *
1035
	 * @return self
1036
	 */
1037
	protected function deletePasswordLogs() {
1038
		foreach ($this->LoggedPasswords() as $password) {
1039
			$password->delete();
1040
			$password->destroy();
1041
		}
1042
		return $this;
1043
	}
1044
1045
	/**
1046
	 * Filter out admin groups to avoid privilege escalation,
1047
	 * If any admin groups are requested, deny the whole save operation.
1048
	 *
1049
	 * @param Array $ids Database IDs of Group records
1050
	 * @return boolean True if the change can be accepted
1051
	 */
1052
	public function onChangeGroups($ids) {
1053
		// Ensure none of these match disallowed list
1054
		$disallowedGroupIDs = $this->disallowedGroups();
1055
		return count(array_intersect($ids, $disallowedGroupIDs)) == 0;
1056
	}
1057
1058
	/**
1059
	 * List of group IDs this user is disallowed from
1060
	 *
1061
	 * @return int[] List of group IDs
1062
	 */
1063
	protected function disallowedGroups() {
1064
		// unless the current user is an admin already OR the logged in user is an admin
1065
		if (Permission::check('ADMIN') || Permission::checkMember($this, 'ADMIN')) {
1066
			return array();
1067
		}
1068
1069
		// Non-admins may not belong to admin groups
1070
		return Permission::get_groups_by_permission('ADMIN')->column('ID');
1071
	}
1072
1073
1074
	/**
1075
	 * Check if the member is in one of the given groups.
1076
	 *
1077
	 * @param array|SS_List $groups Collection of {@link Group} DataObjects to check
1078
	 * @param boolean $strict Only determine direct group membership if set to true (Default: false)
1079
	 * @return bool Returns TRUE if the member is in one of the given groups, otherwise FALSE.
1080
	 */
1081
	public function inGroups($groups, $strict = false) {
1082
		if($groups) foreach($groups as $group) {
1083
			if($this->inGroup($group, $strict)) return true;
1084
		}
1085
1086
		return false;
1087
	}
1088
1089
1090
	/**
1091
	 * Check if the member is in the given group or any parent groups.
1092
	 *
1093
	 * @param int|Group|string $group Group instance, Group Code or ID
1094
	 * @param boolean $strict Only determine direct group membership if set to TRUE (Default: FALSE)
1095
	 * @return bool Returns TRUE if the member is in the given group, otherwise FALSE.
1096
	 */
1097
	public function inGroup($group, $strict = false) {
1098
		if(is_numeric($group)) {
1099
			$groupCheckObj = DataObject::get_by_id('Group', $group);
1100
		} elseif(is_string($group)) {
1101
			$groupCheckObj = DataObject::get_one('Group', array(
1102
				'"Group"."Code"' => $group
1103
			));
1104
		} elseif($group instanceof Group) {
1105
			$groupCheckObj = $group;
1106
		} else {
1107
			user_error('Member::inGroup(): Wrong format for $group parameter', E_USER_ERROR);
1108
		}
1109
1110
		if(!$groupCheckObj) return false;
0 ignored issues
show
Bug introduced by
The variable $groupCheckObj does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1111
1112
		$groupCandidateObjs = ($strict) ? $this->getManyManyComponents("Groups") : $this->Groups();
1113
		if($groupCandidateObjs) foreach($groupCandidateObjs as $groupCandidateObj) {
1114
			if($groupCandidateObj->ID == $groupCheckObj->ID) return true;
1115
		}
1116
1117
		return false;
1118
	}
1119
1120
	/**
1121
	 * Adds the member to a group. This will create the group if the given
1122
	 * group code does not return a valid group object.
1123
	 *
1124
	 * @param string $groupcode
1125
	 * @param string Title of the group
1126
	 */
1127
	public function addToGroupByCode($groupcode, $title = "") {
1128
		$group = DataObject::get_one('Group', array(
1129
			'"Group"."Code"' => $groupcode
1130
		));
1131
1132
		if($group) {
1133
			$this->Groups()->add($group);
1134
		} else {
1135
			if(!$title) $title = $groupcode;
1136
1137
			$group = new Group();
1138
			$group->Code = $groupcode;
1139
			$group->Title = $title;
1140
			$group->write();
1141
1142
			$this->Groups()->add($group);
1143
		}
1144
	}
1145
1146
	/**
1147
	 * Removes a member from a group.
1148
	 *
1149
	 * @param string $groupcode
1150
	 */
1151
	public function removeFromGroupByCode($groupcode) {
1152
		$group = Group::get()->filter(array('Code' => $groupcode))->first();
1153
1154
		if($group) {
1155
			$this->Groups()->remove($group);
1156
		}
1157
	}
1158
1159
	/**
1160
	 * @param Array $columns Column names on the Member record to show in {@link getTitle()}.
1161
	 * @param String $sep Separator
1162
	 */
1163
	public static function set_title_columns($columns, $sep = ' ') {
1164
		if (!is_array($columns)) $columns = array($columns);
1165
		self::config()->title_format = array('columns' => $columns, 'sep' => $sep);
0 ignored issues
show
Documentation introduced by
The property title_format does not exist on object<Config_ForClass>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1166
	}
1167
1168
	//------------------- HELPER METHODS -----------------------------------//
1169
1170
	/**
1171
	 * Get the complete name of the member, by default in the format "<Surname>, <FirstName>".
1172
	 * Falls back to showing either field on its own.
1173
	 *
1174
	 * You can overload this getter with {@link set_title_format()}
1175
	 * and {@link set_title_sql()}.
1176
	 *
1177
	 * @return string Returns the first- and surname of the member. If the ID
1178
	 *  of the member is equal 0, only the surname is returned.
1179
	 */
1180
	public function getTitle() {
1181
		$format = $this->config()->title_format;
0 ignored issues
show
Documentation introduced by
The property title_format does not exist on object<Config_ForClass>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1182
		if ($format) {
1183
			$values = array();
1184
			foreach($format['columns'] as $col) {
1185
				$values[] = $this->getField($col);
1186
			}
1187
			return join($format['sep'], $values);
1188
		}
1189
		if($this->getField('ID') === 0)
1190
			return $this->getField('Surname');
1191
		else{
1192
			if($this->getField('Surname') && $this->getField('FirstName')){
1193
				return $this->getField('Surname') . ', ' . $this->getField('FirstName');
1194
			}elseif($this->getField('Surname')){
1195
				return $this->getField('Surname');
1196
			}elseif($this->getField('FirstName')){
1197
				return $this->getField('FirstName');
1198
			}else{
1199
				return null;
1200
			}
1201
		}
1202
	}
1203
1204
	/**
1205
	 * Return a SQL CONCAT() fragment suitable for a SELECT statement.
1206
	 * Useful for custom queries which assume a certain member title format.
1207
	 *
1208
	 * @param String $tableName
1209
	 * @return String SQL
1210
	 */
1211
	public static function get_title_sql($tableName = 'Member') {
1212
		// This should be abstracted to SSDatabase concatOperator or similar.
1213
		$op = (DB::get_conn() instanceof MSSQLDatabase) ? " + " : " || ";
0 ignored issues
show
Bug introduced by
The class MSSQLDatabase does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
1214
1215
		$format = self::config()->title_format;
0 ignored issues
show
Documentation introduced by
The property title_format does not exist on object<Config_ForClass>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1216
		if ($format) {
1217
			$columnsWithTablename = array();
1218
			foreach($format['columns'] as $column) {
1219
				$columnsWithTablename[] = "\"$tableName\".\"$column\"";
1220
			}
1221
1222
			return "(".join(" $op '".$format['sep']."' $op ", $columnsWithTablename).")";
1223
		} else {
1224
			return "(\"$tableName\".\"Surname\" $op ' ' $op \"$tableName\".\"FirstName\")";
1225
		}
1226
	}
1227
1228
1229
	/**
1230
	 * Get the complete name of the member
1231
	 *
1232
	 * @return string Returns the first- and surname of the member.
1233
	 */
1234
	public function getName() {
1235
		return ($this->Surname) ? trim($this->FirstName . ' ' . $this->Surname) : $this->FirstName;
1236
	}
1237
1238
1239
	/**
1240
	 * Set first- and surname
1241
	 *
1242
	 * This method assumes that the last part of the name is the surname, e.g.
1243
	 * <i>A B C</i> will result in firstname <i>A B</i> and surname <i>C</i>
1244
	 *
1245
	 * @param string $name The name
1246
	 */
1247
	public function setName($name) {
1248
		$nameParts = explode(' ', $name);
1249
		$this->Surname = array_pop($nameParts);
1250
		$this->FirstName = join(' ', $nameParts);
1251
	}
1252
1253
1254
	/**
1255
	 * Alias for {@link setName}
1256
	 *
1257
	 * @param string $name The name
1258
	 * @see setName()
1259
	 */
1260
	public function splitName($name) {
1261
		return $this->setName($name);
1262
	}
1263
1264
	/**
1265
	 * Override the default getter for DateFormat so the
1266
	 * default format for the user's locale is used
1267
	 * if the user has not defined their own.
1268
	 *
1269
	 * @return string ISO date format
1270
	 */
1271
	public function getDateFormat() {
1272
		if($this->getField('DateFormat')) {
1273
			return $this->getField('DateFormat');
1274
		} else {
1275
			return Config::inst()->get('i18n', 'date_format');
1276
		}
1277
	}
1278
1279
	/**
1280
	 * Override the default getter for TimeFormat so the
1281
	 * default format for the user's locale is used
1282
	 * if the user has not defined their own.
1283
	 *
1284
	 * @return string ISO date format
1285
	 */
1286
	public function getTimeFormat() {
1287
		if($this->getField('TimeFormat')) {
1288
			return $this->getField('TimeFormat');
1289
		} else {
1290
			return Config::inst()->get('i18n', 'time_format');
1291
		}
1292
	}
1293
1294
	//---------------------------------------------------------------------//
1295
1296
1297
	/**
1298
	 * Get a "many-to-many" map that holds for all members their group memberships,
1299
	 * including any parent groups where membership is implied.
1300
	 * Use {@link DirectGroups()} to only retrieve the group relations without inheritance.
1301
	 *
1302
	 * @todo Push all this logic into Member_GroupSet's getIterator()?
1303
	 * @return Member_Groupset
1304
	 */
1305
	public function Groups() {
1306
		$groups = Member_GroupSet::create('Group', 'Group_Members', 'GroupID', 'MemberID');
1307
		$groups = $groups->forForeignID($this->ID);
1308
1309
		$this->extend('updateGroups', $groups);
1310
1311
		return $groups;
1312
	}
1313
1314
	/**
1315
	 * @return ManyManyList
1316
	 */
1317
	public function DirectGroups() {
1318
		return $this->getManyManyComponents('Groups');
1319
	}
1320
1321
	/**
1322
	 * Get a member SQLMap of members in specific groups
1323
	 *
1324
	 * If no $groups is passed, all members will be returned
1325
	 *
1326
	 * @param mixed $groups - takes a SS_List, an array or a single Group.ID
1327
	 * @return SQLMap Returns an SQLMap that returns all Member data.
1328
	 * @see map()
1329
	 */
1330
	public static function map_in_groups($groups = null) {
1331
		$groupIDList = array();
1332
1333
		if($groups instanceof SS_List) {
1334
			foreach( $groups as $group ) {
1335
				$groupIDList[] = $group->ID;
1336
			}
1337
		} elseif(is_array($groups)) {
1338
			$groupIDList = $groups;
1339
		} elseif($groups) {
1340
			$groupIDList[] = $groups;
1341
		}
1342
1343
		// No groups, return all Members
1344
		if(!$groupIDList) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $groupIDList of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1345
			return Member::get()->sort(array('Surname'=>'ASC', 'FirstName'=>'ASC'))->map();
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
1346
		}
1347
1348
		$membersList = new ArrayList();
1349
		// This is a bit ineffective, but follow the ORM style
1350
		foreach(Group::get()->byIDs($groupIDList) as $group) {
1351
			$membersList->merge($group->Members());
1352
		}
1353
1354
		$membersList->removeDuplicates('ID');
1355
		return $membersList->map();
1356
	}
1357
1358
1359
	/**
1360
	 * Get a map of all members in the groups given that have CMS permissions
1361
	 *
1362
	 * If no groups are passed, all groups with CMS permissions will be used.
1363
	 *
1364
	 * @param array $groups Groups to consider or NULL to use all groups with
1365
	 *                      CMS permissions.
1366
	 * @return SS_Map Returns a map of all members in the groups given that
1367
	 *                have CMS permissions.
1368
	 */
1369
	public static function mapInCMSGroups($groups = null) {
1370
		if(!$groups || $groups->Count() == 0) {
0 ignored issues
show
Bug introduced by
The method Count cannot be called on $groups (of type array).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1371
			$perms = array('ADMIN', 'CMS_ACCESS_AssetAdmin');
1372
1373
			if(class_exists('CMSMain')) {
1374
				$cmsPerms = singleton('CMSMain')->providePermissions();
1375
			} else {
1376
				$cmsPerms = singleton('LeftAndMain')->providePermissions();
1377
			}
1378
1379
			if(!empty($cmsPerms)) {
1380
				$perms = array_unique(array_merge($perms, array_keys($cmsPerms)));
1381
			}
1382
1383
			$permsClause = DB::placeholders($perms);
1384
			$groups = DataObject::get('Group')
1385
				->innerJoin("Permission", '"Permission"."GroupID" = "Group"."ID"')
1386
				->where(array(
1387
					"\"Permission\".\"Code\" IN ($permsClause)" => $perms
1388
				));
1389
		}
1390
1391
		$groupIDList = array();
1392
1393
		if(is_a($groups, 'SS_List')) {
1394
			foreach($groups as $group) {
1395
				$groupIDList[] = $group->ID;
1396
			}
1397
		} elseif(is_array($groups)) {
1398
			$groupIDList = $groups;
1399
		}
1400
1401
		$members = Member::get()
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
1402
			->innerJoin("Group_Members", '"Group_Members"."MemberID" = "Member"."ID"')
1403
			->innerJoin("Group", '"Group"."ID" = "Group_Members"."GroupID"');
1404
		if($groupIDList) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $groupIDList of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1405
			$groupClause = DB::placeholders($groupIDList);
1406
			$members = $members->where(array(
1407
				"\"Group\".\"ID\" IN ($groupClause)" => $groupIDList
1408
			));
1409
		}
1410
1411
		return $members->sort('"Member"."Surname", "Member"."FirstName"')->map();
1412
	}
1413
1414
1415
	/**
1416
	 * Get the groups in which the member is NOT in
1417
	 *
1418
	 * When passed an array of groups, and a component set of groups, this
1419
	 * function will return the array of groups the member is NOT in.
1420
	 *
1421
	 * @param array $groupList An array of group code names.
1422
	 * @param array $memberGroups A component set of groups (if set to NULL,
1423
	 *                            $this->groups() will be used)
1424
	 * @return array Groups in which the member is NOT in.
1425
	 */
1426
	public function memberNotInGroups($groupList, $memberGroups = null){
1427
		if(!$memberGroups) $memberGroups = $this->Groups();
1428
1429
		foreach($memberGroups as $group) {
1430
			if(in_array($group->Code, $groupList)) {
1431
				$index = array_search($group->Code, $groupList);
1432
				unset($groupList[$index]);
1433
			}
1434
		}
1435
1436
		return $groupList;
1437
	}
1438
1439
1440
	/**
1441
	 * Return a {@link FieldList} of fields that would appropriate for editing
1442
	 * this member.
1443
	 *
1444
	 * @return FieldList Return a FieldList of fields that would appropriate for
1445
	 *                   editing this member.
1446
	 */
1447
	public function getCMSFields() {
1448
		require_once 'Zend/Date.php';
1449
1450
		$self = $this;
1451
		$this->beforeUpdateCMSFields(function(FieldList $fields) use ($self) {
1452
			/** @var FieldList $mainFields */
1453
			$mainFields = $fields->fieldByName("Root")->fieldByName("Main")->getChildren();
1454
1455
			// Build change password field
1456
			$mainFields->replaceField('Password', $self->getMemberPasswordField());
1457
1458
			$mainFields->replaceField('Locale', new DropdownField(
1459
				"Locale",
1460
				_t('Member.INTERFACELANG', "Interface Language", 'Language of the CMS'),
1461
				i18n::get_existing_translations()
1462
			));
1463
1464
			$mainFields->removeByName($self->config()->hidden_fields);
1465
1466
			// make sure that the "LastVisited" field exists
1467
			// it may have been removed using $self->config()->hidden_fields
1468
			if($mainFields->fieldByName("LastVisited")){
1469
			$mainFields->makeFieldReadonly('LastVisited');
1470
			}
1471
1472
			if( ! $self->config()->lock_out_after_incorrect_logins) {
1473
				$mainFields->removeByName('FailedLoginCount');
1474
			}
1475
1476
1477
			// Groups relation will get us into logical conflicts because
1478
			// Members are displayed within  group edit form in SecurityAdmin
1479
			$fields->removeByName('Groups');
1480
1481
			// Members shouldn't be able to directly view/edit logged passwords
1482
			$fields->removeByName('LoggedPasswords');
1483
1484
			if(Permission::check('EDIT_PERMISSIONS')) {
1485
                // Filter allowed groups
1486
                $groups = Group::get();
1487
                $disallowedGroupIDs = $this->disallowedGroups();
1488
                if ($disallowedGroupIDs) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $disallowedGroupIDs of type integer[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1489
                    $groups = $groups->exclude('ID', $disallowedGroupIDs);
1490
                }
1491
                $groupsMap = array();
1492
                foreach ($groups as $group) {
1493
                    // Listboxfield values are escaped, use ASCII char instead of &raquo;
1494
                    $groupsMap[$group->ID] = $group->getBreadcrumbs(' > ');
1495
                }
1496
                asort($groupsMap);
1497
				$fields->addFieldToTab('Root.Main',
1498
					ListboxField::create('DirectGroups', singleton('Group')->i18n_plural_name())
1499
						->setMultiple(true)
1500
						->setSource($groupsMap)
1501
						->setAttribute(
1502
							'data-placeholder',
1503
							_t('Member.ADDGROUP', 'Add group', 'Placeholder text for a dropdown')
1504
						)
1505
				);
1506
1507
1508
				// Add permission field (readonly to avoid complicated group assignment logic).
1509
				// This should only be available for existing records, as new records start
1510
				// with no permissions until they have a group assignment anyway.
1511
				if($self->ID) {
1512
					$permissionsField = new PermissionCheckboxSetField_Readonly(
1513
						'Permissions',
1514
						false,
1515
						'Permission',
1516
						'GroupID',
1517
						// we don't want parent relationships, they're automatically resolved in the field
1518
						$self->getManyManyComponents('Groups')
1519
					);
1520
					$fields->findOrMakeTab('Root.Permissions', singleton('Permission')->i18n_plural_name());
1521
					$fields->addFieldToTab('Root.Permissions', $permissionsField);
1522
				}
1523
			}
1524
1525
			$permissionsTab = $fields->fieldByName("Root")->fieldByName('Permissions');
1526
			if($permissionsTab) $permissionsTab->addExtraClass('readonly');
1527
1528
			$defaultDateFormat = Zend_Locale_Format::getDateFormat(new Zend_Locale($self->Locale));
1529
			$dateFormatMap = array(
1530
				'MMM d, yyyy' => Zend_Date::now()->toString('MMM d, yyyy'),
1531
				'yyyy/MM/dd' => Zend_Date::now()->toString('yyyy/MM/dd'),
1532
				'MM/dd/yyyy' => Zend_Date::now()->toString('MM/dd/yyyy'),
1533
				'dd/MM/yyyy' => Zend_Date::now()->toString('dd/MM/yyyy'),
1534
			);
1535
			$dateFormatMap[$defaultDateFormat] = Zend_Date::now()->toString($defaultDateFormat)
1536
				. sprintf(' (%s)', _t('Member.DefaultDateTime', 'default'));
1537
			$mainFields->push(
1538
				$dateFormatField = new MemberDatetimeOptionsetField(
1539
					'DateFormat',
1540
					$self->fieldLabel('DateFormat'),
1541
					$dateFormatMap
1542
				)
1543
			);
1544
			$dateFormatField->setValue($self->DateFormat);
1545
1546
			$defaultTimeFormat = Zend_Locale_Format::getTimeFormat(new Zend_Locale($self->Locale));
1547
			$timeFormatMap = array(
1548
				'h:mm a' => Zend_Date::now()->toString('h:mm a'),
1549
				'H:mm' => Zend_Date::now()->toString('H:mm'),
1550
			);
1551
			$timeFormatMap[$defaultTimeFormat] = Zend_Date::now()->toString($defaultTimeFormat)
1552
				. sprintf(' (%s)', _t('Member.DefaultDateTime', 'default'));
1553
			$mainFields->push(
1554
				$timeFormatField = new MemberDatetimeOptionsetField(
1555
					'TimeFormat',
1556
					$self->fieldLabel('TimeFormat'),
1557
					$timeFormatMap
1558
				)
1559
			);
1560
			$timeFormatField->setValue($self->TimeFormat);
1561
		});
1562
1563
		return parent::getCMSFields();
1564
	}
1565
1566
	/**
1567
	 *
1568
	 * @param boolean $includerelations a boolean value to indicate if the labels returned include relation fields
1569
	 *
1570
	 */
1571
	public function fieldLabels($includerelations = true) {
1572
		$labels = parent::fieldLabels($includerelations);
1573
1574
		$labels['FirstName'] = _t('Member.FIRSTNAME', 'First Name');
1575
		$labels['Surname'] = _t('Member.SURNAME', 'Surname');
1576
		$labels['Email'] = _t('Member.EMAIL', 'Email');
1577
		$labels['Password'] = _t('Member.db_Password', 'Password');
1578
		$labels['NumVisit'] = _t('Member.db_NumVisit', 'Number of Visits');
1579
		$labels['LastVisited'] = _t('Member.db_LastVisited', 'Last Visited Date');
1580
		$labels['PasswordExpiry'] = _t('Member.db_PasswordExpiry', 'Password Expiry Date', 'Password expiry date');
1581
		$labels['LockedOutUntil'] = _t('Member.db_LockedOutUntil', 'Locked out until', 'Security related date');
1582
		$labels['Locale'] = _t('Member.db_Locale', 'Interface Locale');
1583
		$labels['DateFormat'] = _t('Member.DATEFORMAT', 'Date format');
1584
		$labels['TimeFormat'] = _t('Member.TIMEFORMAT', 'Time format');
1585
		if($includerelations){
1586
			$labels['Groups'] = _t('Member.belongs_many_many_Groups', 'Groups',
1587
				'Security Groups this member belongs to');
1588
		}
1589
		return $labels;
1590
	}
1591
1592
	/**
1593
	 * Users can view their own record.
1594
	 * Otherwise they'll need ADMIN or CMS_ACCESS_SecurityAdmin permissions.
1595
	 * This is likely to be customized for social sites etc. with a looser permission model.
1596
	 */
1597
	public function canView($member = null) {
1598
		if(!$member || !(is_a($member, 'Member')) || is_numeric($member)) $member = Member::currentUser();
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
1599
1600
		// extended access checks
1601
		$results = $this->extend('canView', $member);
1602
		if($results && is_array($results)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $results of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1603
			if(!min($results)) return false;
1604
			else return true;
1605
		}
1606
1607
		// members can usually edit their own record
1608
		if($member && $this->ID == $member->ID) return true;
1609
1610
		if(
1611
			Permission::checkMember($member, 'ADMIN')
1612
			|| Permission::checkMember($member, 'CMS_ACCESS_SecurityAdmin')
1613
		) {
1614
			return true;
1615
		}
1616
1617
		return false;
1618
	}
1619
1620
	/**
1621
	 * Users can edit their own record.
1622
	 * Otherwise they'll need ADMIN or CMS_ACCESS_SecurityAdmin permissions
1623
	 */
1624
	public function canEdit($member = null) {
1625
		if(!$member || !(is_a($member, 'Member')) || is_numeric($member)) $member = Member::currentUser();
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
1626
1627
		// extended access checks
1628
		$results = $this->extend('canEdit', $member);
1629
		if($results && is_array($results)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $results of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1630
			if(!min($results)) return false;
1631
			else return true;
1632
		}
1633
1634
		// No member found
1635
		if(!($member && $member->exists())) return false;
1636
1637
		// If the requesting member is not an admin, but has access to manage members,
1638
		// they still can't edit other members with ADMIN permission.
1639
		// This is a bit weak, strictly speaking they shouldn't be allowed to
1640
		// perform any action that could change the password on a member
1641
		// with "higher" permissions than himself, but thats hard to determine.
1642
		if(!Permission::checkMember($member, 'ADMIN') && Permission::checkMember($this, 'ADMIN')) return false;
1643
1644
		return $this->canView($member);
1645
	}
1646
1647
	/**
1648
	 * Users can edit their own record.
1649
	 * Otherwise they'll need ADMIN or CMS_ACCESS_SecurityAdmin permissions
1650
	 */
1651
	public function canDelete($member = null) {
1652
		if(!$member || !(is_a($member, 'Member')) || is_numeric($member)) $member = Member::currentUser();
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
1653
1654
		// extended access checks
1655
		$results = $this->extend('canDelete', $member);
1656
		if($results && is_array($results)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $results of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1657
			if(!min($results)) return false;
1658
			else return true;
1659
		}
1660
1661
		// No member found
1662
		if(!($member && $member->exists())) return false;
1663
1664
		// Members are not allowed to remove themselves,
1665
		// since it would create inconsistencies in the admin UIs.
1666
		if($this->ID && $member->ID == $this->ID) return false;
1667
1668
		return $this->canEdit($member);
1669
	}
1670
1671
1672
	/**
1673
	 * Validate this member object.
1674
	 */
1675
	public function validate() {
1676
		$valid = parent::validate();
1677
1678
		if(!$this->ID || $this->isChanged('Password')) {
1679
			if($this->Password && self::$password_validator) {
1680
				$valid->combineAnd(self::$password_validator->validate($this->Password, $this));
1681
			}
1682
		}
1683
1684
		if((!$this->ID && $this->SetPassword) || $this->isChanged('SetPassword')) {
0 ignored issues
show
Bug introduced by
The property SetPassword does not seem to exist. Did you mean Password?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1685
			if($this->SetPassword && self::$password_validator) {
0 ignored issues
show
Bug introduced by
The property SetPassword does not seem to exist. Did you mean Password?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1686
				$valid->combineAnd(self::$password_validator->validate($this->SetPassword, $this));
0 ignored issues
show
Bug introduced by
The property SetPassword does not seem to exist. Did you mean Password?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1687
			}
1688
		}
1689
1690
		return $valid;
1691
	}
1692
1693
	/**
1694
	 * Change password. This will cause rehashing according to
1695
	 * the `PasswordEncryption` property.
1696
	 *
1697
	 * @param String $password Cleartext password
1698
	 */
1699
	public function changePassword($password) {
1700
		$this->Password = $password;
1701
		$valid = $this->validate();
1702
1703
		if($valid->valid()) {
1704
			$this->AutoLoginHash = null;
1705
			$this->write();
1706
		}
1707
1708
		return $valid;
1709
	}
1710
1711
	/**
1712
	 * Tell this member that someone made a failed attempt at logging in as them.
1713
	 * This can be used to lock the user out temporarily if too many failed attempts are made.
1714
	 */
1715
	public function registerFailedLogin() {
1716
		if(self::config()->lock_out_after_incorrect_logins) {
1717
			// Keep a tally of the number of failed log-ins so that we can lock people out
1718
			++$this->FailedLoginCount;
1719
1720
			if($this->FailedLoginCount >= self::config()->lock_out_after_incorrect_logins) {
1721
				$lockoutMins = self::config()->lock_out_delay_mins;
0 ignored issues
show
Documentation introduced by
The property lock_out_delay_mins does not exist on object<Config_ForClass>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1722
				$this->LockedOutUntil = date('Y-m-d H:i:s', SS_Datetime::now()->Format('U') + $lockoutMins*60);
1723
				$this->FailedLoginCount = 0;
1724
			}
1725
		}
1726
		$this->extend('registerFailedLogin');
1727
		$this->write();
1728
	}
1729
1730
	/**
1731
	 * Tell this member that a successful login has been made
1732
	 */
1733
	public function registerSuccessfulLogin() {
1734
		if(self::config()->lock_out_after_incorrect_logins) {
1735
			// Forgive all past login failures
1736
			$this->FailedLoginCount = 0;
1737
			$this->LockedOutUntil = null;
1738
			$this->write();
1739
		}
1740
        $this->extend('onAfterRegisterSuccessfulLogin');
1741
	}
1742
	/**
1743
	 * Get the HtmlEditorConfig for this user to be used in the CMS.
1744
	 * This is set by the group. If multiple configurations are set,
1745
	 * the one with the highest priority wins.
1746
	 *
1747
	 * @return string
1748
	 */
1749
	public function getHtmlEditorConfigForCMS() {
1750
		$currentName = '';
1751
		$currentPriority = 0;
1752
1753
		foreach($this->Groups() as $group) {
1754
			$configName = $group->HtmlEditorConfig;
1755
			if($configName) {
1756
				$config = HtmlEditorConfig::get($group->HtmlEditorConfig);
1757
				if($config && $config->getOption('priority') > $currentPriority) {
1758
					$currentName = $configName;
1759
					$currentPriority = $config->getOption('priority');
1760
				}
1761
			}
1762
		}
1763
1764
		// If can't find a suitable editor, just default to cms
1765
		return $currentName ? $currentName : 'cms';
1766
	}
1767
1768
	public static function get_template_global_variables() {
1769
		return array(
1770
			'CurrentMember' => 'currentUser',
1771
			'currentUser',
1772
		);
1773
	}
1774
}
1775
1776
/**
1777
 * Represents a set of Groups attached to a member.
1778
 * Handles the hierarchy logic.
1779
 * @package framework
1780
 * @subpackage security
1781
 */
1782
class Member_GroupSet extends ManyManyList {
1783
1784
	protected function linkJoinTable() {
1785
		// Do not join the table directly
1786
		if($this->extraFields) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->extraFields of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1787
			user_error('Member_GroupSet does not support many_many_extraFields', E_USER_ERROR);
1788
		}
1789
	}
1790
1791
	/**
1792
	 * Link this group set to a specific member.
1793
	 *
1794
	 * Recursively selects all groups applied to this member, as well as any
1795
	 * parent groups of any applied groups
1796
	 *
1797
	 * @param array|integer $id (optional) An ID or an array of IDs - if not provided, will use the current
1798
	 * ids as per getForeignID
1799
	 * @return array Condition In array(SQL => parameters format)
1800
	 */
1801
	public function foreignIDFilter($id = null) {
1802
		if ($id === null) $id = $this->getForeignID();
1803
1804
		// Find directly applied groups
1805
		$manyManyFilter = parent::foreignIDFilter($id);
1806
		$query = new SQLQuery('"Group_Members"."GroupID"', '"Group_Members"', $manyManyFilter);
0 ignored issues
show
Bug introduced by
It seems like $manyManyFilter defined by parent::foreignIDFilter($id) on line 1805 can also be of type null; however, SQLQuery::__construct() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
Deprecated Code introduced by
The class SQLQuery has been deprecated with message: since version 4.0

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
1807
		$groupIDs = $query->execute()->column();
1808
1809
		// Get all ancestors, iteratively merging these into the master set
1810
		$allGroupIDs = array();
1811
		while($groupIDs) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $groupIDs of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1812
			$allGroupIDs = array_merge($allGroupIDs, $groupIDs);
1813
			$groupIDs = DataObject::get("Group")->byIDs($groupIDs)->column("ParentID");
1814
			$groupIDs = array_filter($groupIDs);
1815
		}
1816
1817
		// Add a filter to this DataList
1818
		if(!empty($allGroupIDs)) {
1819
			$allGroupIDsPlaceholders = DB::placeholders($allGroupIDs);
1820
			return array("\"Group\".\"ID\" IN ($allGroupIDsPlaceholders)" => $allGroupIDs);
1821
		} else {
1822
			return array('"Group"."ID"' => 0);
1823
		}
1824
	}
1825
1826
	public function foreignIDWriteFilter($id = null) {
1827
		// Use the ManyManyList::foreignIDFilter rather than the one
1828
		// in this class, otherwise we end up selecting all inherited groups
1829
		return parent::foreignIDFilter($id);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (foreignIDFilter() instead of foreignIDWriteFilter()). Are you sure this is correct? If so, you might want to change this to $this->foreignIDFilter().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
1830
	}
1831
1832
	public function add($item, $extraFields = null) {
1833
		// Get Group.ID
1834
		$itemID = null;
1835
		if(is_numeric($item)) {
1836
			$itemID = $item;
1837
		} else if($item instanceof Group) {
1838
			$itemID = $item->ID;
1839
		}
1840
1841
		// Check if this group is allowed to be added
1842
		if($this->canAddGroups(array($itemID))) {
1843
			parent::add($item, $extraFields);
1844
		}
1845
	}
1846
1847
	public function removeAll() {
1848
		$base = ClassInfo::baseDataClass($this->dataClass());
1849
1850
		// Remove the join to the join table to avoid MySQL row locking issues.
1851
		$query = $this->dataQuery();
1852
		$foreignFilter = $query->getQueryParam('Foreign.Filter');
1853
		$query->removeFilterOn($foreignFilter);
1854
1855
		$selectQuery = $query->query();
1856
		$selectQuery->setSelect("\"{$base}\".\"ID\"");
1857
1858
		$from = $selectQuery->getFrom();
1859
		unset($from[$this->joinTable]);
1860
		$selectQuery->setFrom($from);
1861
		$selectQuery->setOrderBy(); // ORDER BY in subselects breaks MS SQL Server and is not necessary here
1862
		$selectQuery->setDistinct(false);
1863
1864
		// Use a sub-query as SQLite does not support setting delete targets in
1865
		// joined queries.
1866
		$delete = new SQLDelete();
1867
		$delete->setFrom("\"{$this->joinTable}\"");
1868
		// Use ManyManyList::foreignIDFilter() rather than the one in this class
1869
		// otherwise we end up selecting the wrong columns
1870
		$delete->addWhere(parent::foreignIDFilter());
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (foreignIDFilter() instead of removeAll()). Are you sure this is correct? If so, you might want to change this to $this->foreignIDFilter().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
1871
		$subSelect = $selectQuery->sql($parameters);
1872
		$delete->addWhere(array(
1873
			"\"{$this->joinTable}\".\"{$this->localKey}\" IN ($subSelect)" => $parameters
1874
		));
1875
		$delete->execute();
1876
	}
1877
1878
	/**
1879
	 * Determine if the following groups IDs can be added
1880
	 *
1881
	 * @param array $itemIDs
1882
	 * @return boolean
1883
	 */
1884
	protected function canAddGroups($itemIDs) {
1885
		if(empty($itemIDs)) {
1886
			return true;
1887
		}
1888
		$member = $this->getMember();
1889
		return empty($member) || $member->onChangeGroups($itemIDs);
1890
	}
1891
1892
	/**
1893
	 * Get foreign member record for this relation
1894
	 *
1895
	 * @return Member
1896
	 */
1897
	protected function getMember() {
1898
		$id = $this->getForeignID();
1899
		if($id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $id of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1900
			return DataObject::get_by_id('Member', $id);
1901
		}
1902
	}
1903
}
1904
1905
/**
1906
 * Class used as template to send an email saying that the password has been
1907
 * changed.
1908
 *
1909
 * @package framework
1910
 * @subpackage security
1911
 */
1912
class Member_ChangePasswordEmail extends Email {
1913
1914
	protected $from = '';   // setting a blank from address uses the site's default administrator email
1915
	protected $subject = '';
1916
	protected $ss_template = 'ChangePasswordEmail';
1917
1918
	public function __construct() {
1919
		parent::__construct();
1920
1921
		$this->subject = _t('Member.SUBJECTPASSWORDCHANGED', "Your password has been changed", 'Email subject');
1922
	}
1923
}
1924
1925
1926
1927
/**
1928
 * Class used as template to send the forgot password email
1929
 *
1930
 * @package framework
1931
 * @subpackage security
1932
 */
1933
class Member_ForgotPasswordEmail extends Email {
1934
	protected $from = '';  // setting a blank from address uses the site's default administrator email
1935
	protected $subject = '';
1936
	protected $ss_template = 'ForgotPasswordEmail';
1937
1938
	public function __construct() {
1939
		parent::__construct();
1940
1941
		$this->subject = _t('Member.SUBJECTPASSWORDRESET', "Your password reset link", 'Email subject');
1942
	}
1943
}
1944
1945
/**
1946
 * Member Validator
1947
 *
1948
 * Custom validation for the Member object can be achieved either through an
1949
 * {@link DataExtension} on the Member_Validator object or, by specifying a subclass of
1950
 * {@link Member_Validator} through the {@link Injector} API.
1951
 * The Validator can also be modified by adding an Extension to Member and implement the
1952
 * <code>updateValidator</code> hook.
1953
 * {@see Member::getValidator()}
1954
 *
1955
 * Additional required fields can also be set via config API, eg.
1956
 * <code>
1957
 * Member_Validator:
1958
 *   customRequired:
1959
 *     - Surname
1960
 * </code>
1961
 *
1962
 * @package framework
1963
 * @subpackage security
1964
 */
1965
class Member_Validator extends RequiredFields
1966
{
1967
	/**
1968
	 * Fields that are required by this validator
1969
	 * @config
1970
	 * @var array
1971
	 */
1972
	protected $customRequired = array(
1973
		'FirstName',
1974
		'Email'
1975
	);
1976
1977
	/**
1978
	 * Determine what member this validator is meant for
1979
	 * @var Member
1980
	 */
1981
	protected $forMember = null;
1982
1983
	/**
1984
	 * Constructor
1985
	 */
1986
	public function __construct() {
1987
		$required = func_get_args();
1988
1989
		if(isset($required[0]) && is_array($required[0])) {
1990
			$required = $required[0];
1991
		}
1992
1993
		$required = array_merge($required, $this->customRequired);
1994
1995
		// check for config API values and merge them in
1996
		$config = $this->config()->customRequired;
0 ignored issues
show
Documentation introduced by
The property customRequired does not exist on object<Config_ForClass>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1997
		if(is_array($config)){
1998
			$required = array_merge($required, $config);
1999
		}
2000
2001
		parent::__construct(array_unique($required));
2002
	}
2003
2004
	/**
2005
	 * Get the member this validator applies to.
2006
	 * @return Member
2007
	 */
2008
	public function getForMember()
2009
	{
2010
		return $this->forMember;
2011
	}
2012
2013
	/**
2014
	 * Set the Member this validator applies to.
2015
	 * @param Member $value
2016
	 * @return $this
2017
	 */
2018
	public function setForMember(Member $value)
2019
	{
2020
		$this->forMember = $value;
2021
		return $this;
2022
	}
2023
2024
	/**
2025
	 * Check if the submitted member data is valid (server-side)
2026
	 *
2027
	 * Check if a member with that email doesn't already exist, or if it does
2028
	 * that it is this member.
2029
	 *
2030
	 * @param array $data Submitted data
2031
	 * @return bool Returns TRUE if the submitted data is valid, otherwise
2032
	 *              FALSE.
2033
	 */
2034
	public function php($data)
2035
	{
2036
		$valid = parent::php($data);
2037
2038
		$identifierField = (string)Member::config()->unique_identifier_field;
2039
2040
		// Only validate identifier field if it's actually set. This could be the case if
2041
		// somebody removes `Email` from the list of required fields.
2042
		if(isset($data[$identifierField])){
2043
			$id = isset($data['ID']) ? (int)$data['ID'] : 0;
2044
			if(!$id && ($ctrl = $this->form->getController())){
2045
				// get the record when within GridField (Member editing page in CMS)
2046
				if($ctrl instanceof GridFieldDetailForm_ItemRequest && $record = $ctrl->getRecord()){
2047
					$id = $record->ID;
2048
				}
2049
			}
2050
2051
			// If there's no ID passed via controller or form-data, use the assigned member (if available)
2052
			if(!$id && ($member = $this->getForMember())){
2053
				$id = $member->exists() ? $member->ID : 0;
2054
			}
2055
2056
			// set the found ID to the data array, so that extensions can also use it
2057
			$data['ID'] = $id;
2058
2059
			$members = Member::get()->filter($identifierField, $data[$identifierField]);
2060
			if($id) {
2061
				$members = $members->exclude('ID', $id);
2062
			}
2063
2064
			if($members->count() > 0) {
2065
				$this->validationError(
2066
					$identifierField,
2067
					_t(
2068
						'Member.VALIDATIONMEMBEREXISTS',
2069
						'A member already exists with the same {identifier}',
2070
						array('identifier' => Member::singleton()->fieldLabel($identifierField))
2071
					),
2072
					'required'
2073
				);
2074
				$valid = false;
2075
			}
2076
		}
2077
2078
2079
		// Execute the validators on the extensions
2080
		$results = $this->extend('updatePHP', $data, $this->form);
2081
		$results[] = $valid;
2082
		return min($results);
2083
	}
2084
}
2085