Completed
Push — 3.4 ( 9c2b9d...cf8f78 )
by Daniel
13:20
created

Member::isLockedOut()   C

Complexity

Conditions 8
Paths 8

Size

Total Lines 31
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 18
nc 8
nop 0
dl 0
loc 31
rs 5.3846
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
		global $debug;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
402
		if ($this->LockedOutUntil && $this->dbObject('LockedOutUntil')->InFuture()) {
403
			return true;
404
		}
405
406
		if ($this->config()->lock_out_after_incorrect_logins <= 0) {
407
			return false;
408
		}
409
410
		$attempts = LoginAttempt::get()->filter($filter = array(
411
				'Email' => $this->{static::config()->unique_identifier_field},
412
		))->sort('Created', 'DESC')->limit($this->config()->lock_out_after_incorrect_logins);
413
414
		if ($attempts->count() < $this->config()->lock_out_after_incorrect_logins) {
415
			return false;
416
		}
417
418
		foreach ($attempts as $attempt) {
419
			if ($attempt->Status === 'Success') {
420
				return false;
421
			}
422
		}
423
424
		$lockedOutUntil = $attempts->first()->dbObject('Created')->Format('U') + ($this->config()->lock_out_delay_mins * 60);
425
		if (SS_Datetime::now()->Format('U') < $lockedOutUntil) {
426
			return true;
427
		}
428
429
		return false;
430
	}
431
432
	/**
433
	 * Regenerate the session_id.
434
	 * This wrapper is here to make it easier to disable calls to session_regenerate_id(), should you need to.
435
	 * They have caused problems in certain
436
	 * quirky problems (such as using the Windmill 0.3.6 proxy).
437
	 */
438
	public static function session_regenerate_id() {
439
		if(!self::config()->session_regenerate_id) return;
440
441
		// This can be called via CLI during testing.
442
		if(Director::is_cli()) return;
443
444
		$file = '';
445
		$line = '';
446
447
		// @ is to supress win32 warnings/notices when session wasn't cleaned up properly
448
		// There's nothing we can do about this, because it's an operating system function!
449
		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...
450
	}
451
452
	/**
453
	 * Get the field used for uniquely identifying a member
454
	 * in the database. {@see Member::$unique_identifier_field}
455
	 *
456
	 * @deprecated 4.0 Use the "Member.unique_identifier_field" config setting instead
457
	 * @return string
458
	 */
459
	public static function get_unique_identifier_field() {
460
		Deprecation::notice('4.0', 'Use the "Member.unique_identifier_field" config setting instead');
461
		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...
462
	}
463
464
	/**
465
	 * Set the field used for uniquely identifying a member
466
	 * in the database. {@see Member::$unique_identifier_field}
467
	 *
468
	 * @deprecated 4.0 Use the "Member.unique_identifier_field" config setting instead
469
	 * @param $field The field name to set as the unique field
470
	 */
471
	public static function set_unique_identifier_field($field) {
472
		Deprecation::notice('4.0', 'Use the "Member.unique_identifier_field" config setting instead');
473
		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...
474
	}
475
476
	/**
477
	 * Set a {@link PasswordValidator} object to use to validate member's passwords.
478
	 */
479
	public static function set_password_validator($pv) {
480
		self::$password_validator = $pv;
481
	}
482
483
	/**
484
	 * Returns the current {@link PasswordValidator}
485
	 */
486
	public static function password_validator() {
487
		return self::$password_validator;
488
	}
489
490
	/**
491
	 * Set the number of days that a password should be valid for.
492
	 * Set to null (the default) to have passwords never expire.
493
	 *
494
	 * @deprecated 4.0 Use the "Member.password_expiry_days" config setting instead
495
	 */
496
	public static function set_password_expiry($days) {
497
		Deprecation::notice('4.0', 'Use the "Member.password_expiry_days" config setting instead');
498
		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...
499
	}
500
501
	/**
502
	 * Configure the security system to lock users out after this many incorrect logins
503
	 *
504
	 * @deprecated 4.0 Use the "Member.lock_out_after_incorrect_logins" config setting instead
505
	 */
506
	public static function lock_out_after_incorrect_logins($numLogins) {
507
		Deprecation::notice('4.0', 'Use the "Member.lock_out_after_incorrect_logins" config setting instead');
508
		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...
509
	}
510
511
512
	public function isPasswordExpired() {
513
		if(!$this->PasswordExpiry) return false;
514
		return strtotime(date('Y-m-d')) >= strtotime($this->PasswordExpiry);
515
	}
516
517
	/**
518
	 * Logs this member in
519
	 *
520
	 * @param bool $remember If set to TRUE, the member will be logged in automatically the next time.
521
	 */
522
	public function logIn($remember = false) {
523
		$this->extend('beforeMemberLoggedIn');
524
525
		self::session_regenerate_id();
526
527
		Session::set("loggedInAs", $this->ID);
528
		// This lets apache rules detect whether the user has logged in
529
		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...
530
531
		$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...
532
533
		// Only set the cookie if autologin is enabled
534
		if($remember && Security::config()->autologin_enabled) {
535
			// Store the hash and give the client the cookie with the token.
536
			$generator = new RandomGenerator();
537
			$token = $generator->randomToken('sha1');
538
			$hash = $this->encryptWithUserSettings($token);
539
			$this->RememberLoginToken = $hash;
540
			Cookie::set('alc_enc', $this->ID . ':' . $token, 90, null, null, null, true);
541
		} else {
542
			$this->RememberLoginToken = null;
543
			Cookie::force_expiry('alc_enc');
544
		}
545
546
		// Clear the incorrect log-in count
547
		$this->registerSuccessfulLogin();
548
549
		// Don't set column if its not built yet (the login might be precursor to a /dev/build...)
550
		if(array_key_exists('LockedOutUntil', DB::field_list('Member'))) {
551
			$this->LockedOutUntil = null;
552
		}
553
554
		$this->regenerateTempID();
555
556
		$this->write();
557
558
		// Audit logging hook
559
		$this->extend('memberLoggedIn');
560
	}
561
562
	/**
563
	 * @deprecated 4.0
564
	 */
565
	public function addVisit() {
566
		if($this->config()->log_num_visits) {
567
			Deprecation::notice(
568
				'4.0',
569
				'Member::$NumVisit is deprecated. From 4.0 onwards you should implement this as a custom extension'
570
			);
571
			$this->NumVisit++;
572
		}
573
	}
574
575
	/**
576
	 * Trigger regeneration of TempID.
577
	 *
578
	 * This should be performed any time the user presents their normal identification (normally Email)
579
	 * and is successfully authenticated.
580
	 */
581
	public function regenerateTempID() {
582
		$generator = new RandomGenerator();
583
		$this->TempIDHash = $generator->randomToken('sha1');
584
		$this->TempIDExpired = self::config()->temp_id_lifetime
585
			? date('Y-m-d H:i:s', strtotime(SS_Datetime::now()->getValue()) + self::config()->temp_id_lifetime)
586
			: null;
587
		$this->write();
588
	}
589
590
	/**
591
	 * Check if the member ID logged in session actually
592
	 * has a database record of the same ID. If there is
593
	 * no logged in user, FALSE is returned anyway.
594
	 *
595
	 * @return boolean TRUE record found FALSE no record found
596
	 */
597
	public static function logged_in_session_exists() {
598
		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...
599
			if($member = DataObject::get_by_id('Member', $id)) {
600
				if($member->exists()) return true;
601
			}
602
		}
603
604
		return false;
605
	}
606
607
	/**
608
	 * Log the user in if the "remember login" cookie is set
609
	 *
610
	 * The <i>remember login token</i> will be changed on every successful
611
	 * auto-login.
612
	 */
613
	public static function autoLogin() {
614
		// Don't bother trying this multiple times
615
		self::$_already_tried_to_auto_log_in = true;
616
617
		if(!Security::config()->autologin_enabled
618
			|| strpos(Cookie::get('alc_enc'), ':') === false
619
			|| Session::get("loggedInAs")
620
			|| !Security::database_is_ready()
621
		) {
622
			return;
623
		}
624
625
		list($uid, $token) = explode(':', Cookie::get('alc_enc'), 2);
626
627
		$member = DataObject::get_by_id("Member", $uid);
628
629
		// check if autologin token matches
630
		if($member) {
631
			$hash = $member->encryptWithUserSettings($token);
632
			if(!$member->RememberLoginToken || $member->RememberLoginToken !== $hash) {
633
				$member = null;
634
			}
635
		}
636
637
		if($member) {
638
			self::session_regenerate_id();
639
			Session::set("loggedInAs", $member->ID);
640
			// This lets apache rules detect whether the user has logged in
641
			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...
642
				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...
643
			}
644
645
			$generator = new RandomGenerator();
646
			$token = $generator->randomToken('sha1');
647
			$hash = $member->encryptWithUserSettings($token);
648
			$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...
649
			Cookie::set('alc_enc', $member->ID . ':' . $token, 90, null, null, false, true);
650
651
			$member->addVisit();
652
			$member->write();
653
654
			// Audit logging hook
655
			$member->extend('memberAutoLoggedIn');
656
		}
657
	}
658
659
	/**
660
	 * Logs this member out.
661
	 */
662
	public function logOut() {
663
		$this->extend('beforeMemberLoggedOut');
664
665
		Session::clear("loggedInAs");
666
		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...
667
668
		Session::destroy();
669
670
		$this->extend('memberLoggedOut');
671
672
		$this->RememberLoginToken = null;
673
		Cookie::force_expiry('alc_enc');
674
675
		// Switch back to live in order to avoid infinite loops when
676
		// redirecting to the login screen (if this login screen is versioned)
677
		Session::clear('readingMode');
678
679
		$this->write();
680
681
		// Audit logging hook
682
		$this->extend('memberLoggedOut');
683
	}
684
685
	/**
686
	 * Utility for generating secure password hashes for this member.
687
	 */
688
	public function encryptWithUserSettings($string) {
689
		if (!$string) return null;
690
691
		// If the algorithm or salt is not available, it means we are operating
692
		// on legacy account with unhashed password. Do not hash the string.
693
		if (!$this->PasswordEncryption) {
694
			return $string;
695
		}
696
697
		// We assume we have PasswordEncryption and Salt available here.
698
		$e = PasswordEncryptor::create_for_algorithm($this->PasswordEncryption);
699
		return $e->encrypt($string, $this->Salt);
700
701
	}
702
703
	/**
704
	 * Generate an auto login token which can be used to reset the password,
705
	 * at the same time hashing it and storing in the database.
706
	 *
707
	 * @param int $lifetime The lifetime of the auto login hash in days (by default 2 days)
708
	 *
709
	 * @returns string Token that should be passed to the client (but NOT persisted).
710
	 *
711
	 * @todo Make it possible to handle database errors such as a "duplicate key" error
712
	 */
713
	public function generateAutologinTokenAndStoreHash($lifetime = 2) {
714
		do {
715
			$generator = new RandomGenerator();
716
			$token = $generator->randomToken();
717
			$hash = $this->encryptWithUserSettings($token);
718
		} while(DataObject::get_one('Member', array(
719
			'"Member"."AutoLoginHash"' => $hash
720
		)));
721
722
		$this->AutoLoginHash = $hash;
723
		$this->AutoLoginExpired = date('Y-m-d H:i:s', time() + (86400 * $lifetime));
724
725
		$this->write();
726
727
		return $token;
728
	}
729
730
	/**
731
	 * Check the token against the member.
732
	 *
733
	 * @param string $autologinToken
734
	 *
735
	 * @returns bool Is token valid?
736
	 */
737
	public function validateAutoLoginToken($autologinToken) {
738
		$hash = $this->encryptWithUserSettings($autologinToken);
739
		$member = self::member_from_autologinhash($hash, false);
740
		return (bool)$member;
741
	}
742
743
	/**
744
	 * Return the member for the auto login hash
745
	 *
746
	 * @param string $hash The hash key
747
	 * @param bool $login Should the member be logged in?
748
	 *
749
	 * @return Member the matching member, if valid
750
	 * @return Member
751
	 */
752
	public static function member_from_autologinhash($hash, $login = false) {
753
754
		$nowExpression = DB::get_conn()->now();
755
		$member = DataObject::get_one('Member', array(
756
			"\"Member\".\"AutoLoginHash\"" => $hash,
757
			"\"Member\".\"AutoLoginExpired\" > $nowExpression" // NOW() can't be parameterised
758
		));
759
760
		if($login && $member) $member->logIn();
761
762
		return $member;
763
	}
764
765
	/**
766
	 * Find a member record with the given TempIDHash value
767
	 *
768
	 * @param string $tempid
769
	 * @return Member
770
	 */
771
	public static function member_from_tempid($tempid) {
772
		$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...
773
			->filter('TempIDHash', $tempid);
774
775
		// Exclude expired
776
		if(static::config()->temp_id_lifetime) {
777
			$members = $members->filter('TempIDExpired:GreaterThan', SS_Datetime::now()->getValue());
778
		}
779
780
		return $members->first();
781
	}
782
783
	/**
784
	 * Returns the fields for the member form - used in the registration/profile module.
785
	 * It should return fields that are editable by the admin and the logged-in user.
786
	 *
787
	 * @return FieldList Returns a {@link FieldList} containing the fields for
788
	 *                   the member form.
789
	 */
790
	public function getMemberFormFields() {
791
		$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...
792
793
		$fields->replaceField('Password', $this->getMemberPasswordField());
794
795
		$fields->replaceField('Locale', new DropdownField (
796
			'Locale',
797
			$this->fieldLabel('Locale'),
798
			i18n::get_existing_translations()
799
		));
800
801
		$fields->removeByName(static::config()->hidden_fields);
802
		$fields->removeByName('LastVisited');
803
		$fields->removeByName('FailedLoginCount');
804
805
806
		$this->extend('updateMemberFormFields', $fields);
807
		return $fields;
808
	}
809
810
	/**
811
	 * Builds "Change / Create Password" field for this member
812
	 *
813
	 * @return ConfirmedPasswordField
814
	 */
815
	public function getMemberPasswordField() {
816
		$editingPassword = $this->isInDB();
817
		$label = $editingPassword
818
			? _t('Member.EDIT_PASSWORD', 'New Password')
819
			: $this->fieldLabel('Password');
820
		/** @var ConfirmedPasswordField $password */
821
		$password = ConfirmedPasswordField::create(
822
			'Password',
823
			$label,
824
			null,
825
			null,
826
			$editingPassword
827
		);
828
829
		// If editing own password, require confirmation of existing
830
		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...
831
			$password->setRequireExistingPassword(true);
832
		}
833
834
		$password->setCanBeEmpty(true);
835
		$this->extend('updateMemberPasswordField', $password);
836
		return $password;
837
	}
838
839
840
	/**
841
	 * Returns the {@link RequiredFields} instance for the Member object. This
842
	 * Validator is used when saving a {@link CMSProfileController} or added to
843
	 * any form responsible for saving a users data.
844
	 *
845
	 * To customize the required fields, add a {@link DataExtension} to member
846
	 * calling the `updateValidator()` method.
847
	 *
848
	 * @return Member_Validator
849
	 */
850
	public function getValidator() {
851
		$validator = Injector::inst()->create('Member_Validator');
852
		$validator->setForMember($this);
853
		$this->extend('updateValidator', $validator);
854
855
		return $validator;
856
	}
857
858
859
	/**
860
	 * Returns the current logged in user
861
	 *
862
	 * @return Member|null
863
	 */
864
	public static function currentUser() {
865
		$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...
866
867
		if($id) {
868
			return DataObject::get_by_id('Member', $id) ?: null;
869
		}
870
	}
871
872
	/**
873
	 * Get the ID of the current logged in user
874
	 *
875
	 * @return int Returns the ID of the current logged in user or 0.
876
	 */
877
	public static function currentUserID() {
878
		$id = Session::get("loggedInAs");
879
		if(!$id && !self::$_already_tried_to_auto_log_in) {
880
			self::autoLogin();
881
			$id = Session::get("loggedInAs");
882
		}
883
884
		return is_numeric($id) ? $id : 0;
885
	}
886
	private static $_already_tried_to_auto_log_in = false;
887
888
889
	/*
890
	 * Generate a random password, with randomiser to kick in if there's no words file on the
891
	 * filesystem.
892
	 *
893
	 * @return string Returns a random password.
894
	 */
895
	public static function create_new_password() {
896
		$words = Config::inst()->get('Security', 'word_list');
897
898
		if($words && file_exists($words)) {
899
			$words = file($words);
900
901
			list($usec, $sec) = explode(' ', microtime());
902
			srand($sec + ((float) $usec * 100000));
903
904
			$word = trim($words[rand(0,sizeof($words)-1)]);
905
			$number = rand(10,999);
906
907
			return $word . $number;
908
		} else {
909
			$random = rand();
910
			$string = md5($random);
911
			$output = substr($string, 0, 8);
912
			return $output;
913
		}
914
	}
915
916
	/**
917
	 * Event handler called before writing to the database.
918
	 */
919
	public function onBeforeWrite() {
920
		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...
921
922
		// If a member with the same "unique identifier" already exists with a different ID, don't allow merging.
923
		// Note: This does not a full replacement for safeguards in the controller layer (e.g. in a registration form),
924
		// but rather a last line of defense against data inconsistencies.
925
		$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...
926
		if($this->$identifierField) {
927
928
			// Note: Same logic as Member_Validator class
929
			$filter = array("\"$identifierField\"" => $this->$identifierField);
930
			if($this->ID) {
931
				$filter[] = array('"Member"."ID" <> ?' => $this->ID);
932
			}
933
			$existingRecord = DataObject::get_one('Member', $filter);
934
935
			if($existingRecord) {
936
				throw new ValidationException(ValidationResult::create(false, _t(
937
					'Member.ValidationIdentifierFailed',
938
					'Can\'t overwrite existing member #{id} with identical identifier ({name} = {value}))',
939
					'Values in brackets show "fieldname = value", usually denoting an existing email address',
940
					array(
941
						'id' => $existingRecord->ID,
942
						'name' => $identifierField,
943
						'value' => $this->$identifierField
944
					)
945
				)));
946
			}
947
		}
948
949
		// We don't send emails out on dev/tests sites to prevent accidentally spamming users.
950
		// However, if TestMailer is in use this isn't a risk.
951
		if(
952
			(Director::isLive() || Email::mailer() instanceof TestMailer)
953
			&& $this->isChanged('Password')
954
			&& $this->record['Password']
955
			&& $this->config()->notify_password_change
956
		) {
957
			$e = Member_ChangePasswordEmail::create();
958
			$e->populateTemplate($this);
959
			$e->setTo($this->Email);
960
			$e->send();
961
		}
962
963
		// The test on $this->ID is used for when records are initially created.
964
		// Note that this only works with cleartext passwords, as we can't rehash
965
		// existing passwords.
966
		if((!$this->ID && $this->Password) || $this->isChanged('Password')) {
967
			//reset salt so that it gets regenerated - this will invalidate any persistant login cookies
968
			// or other information encrypted with this Member's settings (see self::encryptWithUserSettings)
969
			$this->Salt = '';
970
			// Password was changed: encrypt the password according the settings
971
			$encryption_details = Security::encrypt_password(
972
				$this->Password, // this is assumed to be cleartext
973
				$this->Salt,
974
				($this->PasswordEncryption) ?
975
					$this->PasswordEncryption : Security::config()->password_encryption_algorithm,
976
				$this
977
			);
978
979
			// Overwrite the Password property with the hashed value
980
			$this->Password = $encryption_details['password'];
981
			$this->Salt = $encryption_details['salt'];
982
			$this->PasswordEncryption = $encryption_details['algorithm'];
983
984
			// If we haven't manually set a password expiry
985
			if(!$this->isChanged('PasswordExpiry')) {
986
				// then set it for us
987
				if(self::config()->password_expiry_days) {
988
					$this->PasswordExpiry = date('Y-m-d', time() + 86400 * self::config()->password_expiry_days);
989
				} else {
990
					$this->PasswordExpiry = null;
991
				}
992
			}
993
		}
994
995
		// save locale
996
		if(!$this->Locale) {
997
			$this->Locale = i18n::get_locale();
998
		}
999
1000
		parent::onBeforeWrite();
1001
	}
1002
1003
	public function onAfterWrite() {
1004
		parent::onAfterWrite();
1005
1006
		Permission::flush_permission_cache();
1007
1008
		if($this->isChanged('Password')) {
1009
			MemberPassword::log($this);
1010
		}
1011
	}
1012
1013
	public function onAfterDelete() {
1014
		parent::onAfterDelete();
1015
1016
		//prevent orphaned records remaining in the DB
1017
		$this->deletePasswordLogs();
1018
	}
1019
1020
	/**
1021
	 * Delete the MemberPassword objects that are associated to this user
1022
	 *
1023
	 * @return self
1024
	 */
1025
	protected function deletePasswordLogs() {
1026
		foreach ($this->LoggedPasswords() as $password) {
1027
			$password->delete();
1028
			$password->destroy();
1029
		}
1030
		return $this;
1031
	}
1032
1033
	/**
1034
	 * Filter out admin groups to avoid privilege escalation,
1035
	 * If any admin groups are requested, deny the whole save operation.
1036
	 *
1037
	 * @param Array $ids Database IDs of Group records
1038
	 * @return boolean True if the change can be accepted
1039
	 */
1040
	public function onChangeGroups($ids) {
1041
		// unless the current user is an admin already OR the logged in user is an admin
1042
		if(Permission::check('ADMIN') || Permission::checkMember($this, 'ADMIN')) {
1043
			return true;
1044
		}
1045
1046
		// If there are no admin groups in this set then it's ok
1047
		$adminGroups = Permission::get_groups_by_permission('ADMIN');
1048
		$adminGroupIDs = ($adminGroups) ? $adminGroups->column('ID') : array();
1049
		return count(array_intersect($ids, $adminGroupIDs)) == 0;
1050
	}
1051
1052
1053
	/**
1054
	 * Check if the member is in one of the given groups.
1055
	 *
1056
	 * @param array|SS_List $groups Collection of {@link Group} DataObjects to check
1057
	 * @param boolean $strict Only determine direct group membership if set to true (Default: false)
1058
	 * @return bool Returns TRUE if the member is in one of the given groups, otherwise FALSE.
1059
	 */
1060
	public function inGroups($groups, $strict = false) {
1061
		if($groups) foreach($groups as $group) {
1062
			if($this->inGroup($group, $strict)) return true;
1063
		}
1064
1065
		return false;
1066
	}
1067
1068
1069
	/**
1070
	 * Check if the member is in the given group or any parent groups.
1071
	 *
1072
	 * @param int|Group|string $group Group instance, Group Code or ID
1073
	 * @param boolean $strict Only determine direct group membership if set to TRUE (Default: FALSE)
1074
	 * @return bool Returns TRUE if the member is in the given group, otherwise FALSE.
1075
	 */
1076
	public function inGroup($group, $strict = false) {
1077
		if(is_numeric($group)) {
1078
			$groupCheckObj = DataObject::get_by_id('Group', $group);
1079
		} elseif(is_string($group)) {
1080
			$groupCheckObj = DataObject::get_one('Group', array(
1081
				'"Group"."Code"' => $group
1082
			));
1083
		} elseif($group instanceof Group) {
1084
			$groupCheckObj = $group;
1085
		} else {
1086
			user_error('Member::inGroup(): Wrong format for $group parameter', E_USER_ERROR);
1087
		}
1088
1089
		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...
1090
1091
		$groupCandidateObjs = ($strict) ? $this->getManyManyComponents("Groups") : $this->Groups();
1092
		if($groupCandidateObjs) foreach($groupCandidateObjs as $groupCandidateObj) {
1093
			if($groupCandidateObj->ID == $groupCheckObj->ID) return true;
1094
		}
1095
1096
		return false;
1097
	}
1098
1099
	/**
1100
	 * Adds the member to a group. This will create the group if the given
1101
	 * group code does not return a valid group object.
1102
	 *
1103
	 * @param string $groupcode
1104
	 * @param string Title of the group
1105
	 */
1106
	public function addToGroupByCode($groupcode, $title = "") {
1107
		$group = DataObject::get_one('Group', array(
1108
			'"Group"."Code"' => $groupcode
1109
		));
1110
1111
		if($group) {
1112
			$this->Groups()->add($group);
1113
		} else {
1114
			if(!$title) $title = $groupcode;
1115
1116
			$group = new Group();
1117
			$group->Code = $groupcode;
1118
			$group->Title = $title;
1119
			$group->write();
1120
1121
			$this->Groups()->add($group);
1122
		}
1123
	}
1124
1125
	/**
1126
	 * Removes a member from a group.
1127
	 *
1128
	 * @param string $groupcode
1129
	 */
1130
	public function removeFromGroupByCode($groupcode) {
1131
		$group = Group::get()->filter(array('Code' => $groupcode))->first();
1132
1133
		if($group) {
1134
			$this->Groups()->remove($group);
1135
		}
1136
	}
1137
1138
	/**
1139
	 * @param Array $columns Column names on the Member record to show in {@link getTitle()}.
1140
	 * @param String $sep Separator
1141
	 */
1142
	public static function set_title_columns($columns, $sep = ' ') {
1143
		if (!is_array($columns)) $columns = array($columns);
1144
		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...
1145
	}
1146
1147
	//------------------- HELPER METHODS -----------------------------------//
1148
1149
	/**
1150
	 * Get the complete name of the member, by default in the format "<Surname>, <FirstName>".
1151
	 * Falls back to showing either field on its own.
1152
	 *
1153
	 * You can overload this getter with {@link set_title_format()}
1154
	 * and {@link set_title_sql()}.
1155
	 *
1156
	 * @return string Returns the first- and surname of the member. If the ID
1157
	 *  of the member is equal 0, only the surname is returned.
1158
	 */
1159
	public function getTitle() {
1160
		$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...
1161
		if ($format) {
1162
			$values = array();
1163
			foreach($format['columns'] as $col) {
1164
				$values[] = $this->getField($col);
1165
			}
1166
			return join($format['sep'], $values);
1167
		}
1168
		if($this->getField('ID') === 0)
1169
			return $this->getField('Surname');
1170
		else{
1171
			if($this->getField('Surname') && $this->getField('FirstName')){
1172
				return $this->getField('Surname') . ', ' . $this->getField('FirstName');
1173
			}elseif($this->getField('Surname')){
1174
				return $this->getField('Surname');
1175
			}elseif($this->getField('FirstName')){
1176
				return $this->getField('FirstName');
1177
			}else{
1178
				return null;
1179
			}
1180
		}
1181
	}
1182
1183
	/**
1184
	 * Return a SQL CONCAT() fragment suitable for a SELECT statement.
1185
	 * Useful for custom queries which assume a certain member title format.
1186
	 *
1187
	 * @param String $tableName
1188
	 * @return String SQL
1189
	 */
1190
	public static function get_title_sql($tableName = 'Member') {
1191
		// This should be abstracted to SSDatabase concatOperator or similar.
1192
		$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...
1193
1194
		$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...
1195
		if ($format) {
1196
			$columnsWithTablename = array();
1197
			foreach($format['columns'] as $column) {
1198
				$columnsWithTablename[] = "\"$tableName\".\"$column\"";
1199
			}
1200
1201
			return "(".join(" $op '".$format['sep']."' $op ", $columnsWithTablename).")";
1202
		} else {
1203
			return "(\"$tableName\".\"Surname\" $op ' ' $op \"$tableName\".\"FirstName\")";
1204
		}
1205
	}
1206
1207
1208
	/**
1209
	 * Get the complete name of the member
1210
	 *
1211
	 * @return string Returns the first- and surname of the member.
1212
	 */
1213
	public function getName() {
1214
		return ($this->Surname) ? trim($this->FirstName . ' ' . $this->Surname) : $this->FirstName;
1215
	}
1216
1217
1218
	/**
1219
	 * Set first- and surname
1220
	 *
1221
	 * This method assumes that the last part of the name is the surname, e.g.
1222
	 * <i>A B C</i> will result in firstname <i>A B</i> and surname <i>C</i>
1223
	 *
1224
	 * @param string $name The name
1225
	 */
1226
	public function setName($name) {
1227
		$nameParts = explode(' ', $name);
1228
		$this->Surname = array_pop($nameParts);
1229
		$this->FirstName = join(' ', $nameParts);
1230
	}
1231
1232
1233
	/**
1234
	 * Alias for {@link setName}
1235
	 *
1236
	 * @param string $name The name
1237
	 * @see setName()
1238
	 */
1239
	public function splitName($name) {
1240
		return $this->setName($name);
1241
	}
1242
1243
	/**
1244
	 * Override the default getter for DateFormat so the
1245
	 * default format for the user's locale is used
1246
	 * if the user has not defined their own.
1247
	 *
1248
	 * @return string ISO date format
1249
	 */
1250
	public function getDateFormat() {
1251
		if($this->getField('DateFormat')) {
1252
			return $this->getField('DateFormat');
1253
		} else {
1254
			return Config::inst()->get('i18n', 'date_format');
1255
		}
1256
	}
1257
1258
	/**
1259
	 * Override the default getter for TimeFormat so the
1260
	 * default format for the user's locale is used
1261
	 * if the user has not defined their own.
1262
	 *
1263
	 * @return string ISO date format
1264
	 */
1265
	public function getTimeFormat() {
1266
		if($this->getField('TimeFormat')) {
1267
			return $this->getField('TimeFormat');
1268
		} else {
1269
			return Config::inst()->get('i18n', 'time_format');
1270
		}
1271
	}
1272
1273
	//---------------------------------------------------------------------//
1274
1275
1276
	/**
1277
	 * Get a "many-to-many" map that holds for all members their group memberships,
1278
	 * including any parent groups where membership is implied.
1279
	 * Use {@link DirectGroups()} to only retrieve the group relations without inheritance.
1280
	 *
1281
	 * @todo Push all this logic into Member_GroupSet's getIterator()?
1282
	 * @return Member_Groupset
1283
	 */
1284
	public function Groups() {
1285
		$groups = Member_GroupSet::create('Group', 'Group_Members', 'GroupID', 'MemberID');
1286
		$groups = $groups->forForeignID($this->ID);
1287
1288
		$this->extend('updateGroups', $groups);
1289
1290
		return $groups;
1291
	}
1292
1293
	/**
1294
	 * @return ManyManyList
1295
	 */
1296
	public function DirectGroups() {
1297
		return $this->getManyManyComponents('Groups');
1298
	}
1299
1300
	/**
1301
	 * Get a member SQLMap of members in specific groups
1302
	 *
1303
	 * If no $groups is passed, all members will be returned
1304
	 *
1305
	 * @param mixed $groups - takes a SS_List, an array or a single Group.ID
1306
	 * @return SQLMap Returns an SQLMap that returns all Member data.
1307
	 * @see map()
1308
	 */
1309
	public static function map_in_groups($groups = null) {
1310
		$groupIDList = array();
1311
1312
		if($groups instanceof SS_List) {
1313
			foreach( $groups as $group ) {
1314
				$groupIDList[] = $group->ID;
1315
			}
1316
		} elseif(is_array($groups)) {
1317
			$groupIDList = $groups;
1318
		} elseif($groups) {
1319
			$groupIDList[] = $groups;
1320
		}
1321
1322
		// No groups, return all Members
1323
		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...
1324
			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...
1325
		}
1326
1327
		$membersList = new ArrayList();
1328
		// This is a bit ineffective, but follow the ORM style
1329
		foreach(Group::get()->byIDs($groupIDList) as $group) {
1330
			$membersList->merge($group->Members());
1331
		}
1332
1333
		$membersList->removeDuplicates('ID');
1334
		return $membersList->map();
1335
	}
1336
1337
1338
	/**
1339
	 * Get a map of all members in the groups given that have CMS permissions
1340
	 *
1341
	 * If no groups are passed, all groups with CMS permissions will be used.
1342
	 *
1343
	 * @param array $groups Groups to consider or NULL to use all groups with
1344
	 *                      CMS permissions.
1345
	 * @return SS_Map Returns a map of all members in the groups given that
1346
	 *                have CMS permissions.
1347
	 */
1348
	public static function mapInCMSGroups($groups = null) {
1349
		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...
1350
			$perms = array('ADMIN', 'CMS_ACCESS_AssetAdmin');
1351
1352
			if(class_exists('CMSMain')) {
1353
				$cmsPerms = singleton('CMSMain')->providePermissions();
1354
			} else {
1355
				$cmsPerms = singleton('LeftAndMain')->providePermissions();
1356
			}
1357
1358
			if(!empty($cmsPerms)) {
1359
				$perms = array_unique(array_merge($perms, array_keys($cmsPerms)));
1360
			}
1361
1362
			$permsClause = DB::placeholders($perms);
1363
			$groups = DataObject::get('Group')
1364
				->innerJoin("Permission", '"Permission"."GroupID" = "Group"."ID"')
1365
				->where(array(
1366
					"\"Permission\".\"Code\" IN ($permsClause)" => $perms
1367
				));
1368
		}
1369
1370
		$groupIDList = array();
1371
1372
		if(is_a($groups, 'SS_List')) {
1373
			foreach($groups as $group) {
1374
				$groupIDList[] = $group->ID;
1375
			}
1376
		} elseif(is_array($groups)) {
1377
			$groupIDList = $groups;
1378
		}
1379
1380
		$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...
1381
			->innerJoin("Group_Members", '"Group_Members"."MemberID" = "Member"."ID"')
1382
			->innerJoin("Group", '"Group"."ID" = "Group_Members"."GroupID"');
1383
		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...
1384
			$groupClause = DB::placeholders($groupIDList);
1385
			$members = $members->where(array(
1386
				"\"Group\".\"ID\" IN ($groupClause)" => $groupIDList
1387
			));
1388
		}
1389
1390
		return $members->sort('"Member"."Surname", "Member"."FirstName"')->map();
1391
	}
1392
1393
1394
	/**
1395
	 * Get the groups in which the member is NOT in
1396
	 *
1397
	 * When passed an array of groups, and a component set of groups, this
1398
	 * function will return the array of groups the member is NOT in.
1399
	 *
1400
	 * @param array $groupList An array of group code names.
1401
	 * @param array $memberGroups A component set of groups (if set to NULL,
1402
	 *                            $this->groups() will be used)
1403
	 * @return array Groups in which the member is NOT in.
1404
	 */
1405
	public function memberNotInGroups($groupList, $memberGroups = null){
1406
		if(!$memberGroups) $memberGroups = $this->Groups();
1407
1408
		foreach($memberGroups as $group) {
1409
			if(in_array($group->Code, $groupList)) {
1410
				$index = array_search($group->Code, $groupList);
1411
				unset($groupList[$index]);
1412
			}
1413
		}
1414
1415
		return $groupList;
1416
	}
1417
1418
1419
	/**
1420
	 * Return a {@link FieldList} of fields that would appropriate for editing
1421
	 * this member.
1422
	 *
1423
	 * @return FieldList Return a FieldList of fields that would appropriate for
1424
	 *                   editing this member.
1425
	 */
1426
	public function getCMSFields() {
1427
		require_once 'Zend/Date.php';
1428
1429
		$self = $this;
1430
		$this->beforeUpdateCMSFields(function(FieldList $fields) use ($self) {
1431
			/** @var FieldList $mainFields */
1432
			$mainFields = $fields->fieldByName("Root")->fieldByName("Main")->getChildren();
1433
1434
			// Build change password field
1435
			$mainFields->replaceField('Password', $self->getMemberPasswordField());
1436
1437
			$mainFields->replaceField('Locale', new DropdownField(
1438
				"Locale",
1439
				_t('Member.INTERFACELANG', "Interface Language", 'Language of the CMS'),
1440
				i18n::get_existing_translations()
1441
			));
1442
1443
			$mainFields->removeByName($self->config()->hidden_fields);
1444
1445
			// make sure that the "LastVisited" field exists
1446
			// it may have been removed using $self->config()->hidden_fields
1447
			if($mainFields->fieldByName("LastVisited")){
1448
			$mainFields->makeFieldReadonly('LastVisited');
1449
			}
1450
1451
			if( ! $self->config()->lock_out_after_incorrect_logins) {
1452
				$mainFields->removeByName('FailedLoginCount');
1453
			}
1454
1455
1456
			// Groups relation will get us into logical conflicts because
1457
			// Members are displayed within  group edit form in SecurityAdmin
1458
			$fields->removeByName('Groups');
1459
1460
			// Members shouldn't be able to directly view/edit logged passwords
1461
			$fields->removeByName('LoggedPasswords');
1462
1463
			if(Permission::check('EDIT_PERMISSIONS')) {
1464
				$groupsMap = array();
1465
				foreach(Group::get() as $group) {
1466
					// Listboxfield values are escaped, use ASCII char instead of &raquo;
1467
					$groupsMap[$group->ID] = $group->getBreadcrumbs(' > ');
1468
				}
1469
				asort($groupsMap);
1470
				$fields->addFieldToTab('Root.Main',
1471
					ListboxField::create('DirectGroups', singleton('Group')->i18n_plural_name())
1472
						->setMultiple(true)
1473
						->setSource($groupsMap)
1474
						->setAttribute(
1475
							'data-placeholder',
1476
							_t('Member.ADDGROUP', 'Add group', 'Placeholder text for a dropdown')
1477
						)
1478
				);
1479
1480
1481
				// Add permission field (readonly to avoid complicated group assignment logic).
1482
				// This should only be available for existing records, as new records start
1483
				// with no permissions until they have a group assignment anyway.
1484
				if($self->ID) {
1485
					$permissionsField = new PermissionCheckboxSetField_Readonly(
1486
						'Permissions',
1487
						false,
1488
						'Permission',
1489
						'GroupID',
1490
						// we don't want parent relationships, they're automatically resolved in the field
1491
						$self->getManyManyComponents('Groups')
1492
					);
1493
					$fields->findOrMakeTab('Root.Permissions', singleton('Permission')->i18n_plural_name());
1494
					$fields->addFieldToTab('Root.Permissions', $permissionsField);
1495
				}
1496
			}
1497
1498
			$permissionsTab = $fields->fieldByName("Root")->fieldByName('Permissions');
1499
			if($permissionsTab) $permissionsTab->addExtraClass('readonly');
1500
1501
			$defaultDateFormat = Zend_Locale_Format::getDateFormat(new Zend_Locale($self->Locale));
1502
			$dateFormatMap = array(
1503
				'MMM d, yyyy' => Zend_Date::now()->toString('MMM d, yyyy'),
1504
				'yyyy/MM/dd' => Zend_Date::now()->toString('yyyy/MM/dd'),
1505
				'MM/dd/yyyy' => Zend_Date::now()->toString('MM/dd/yyyy'),
1506
				'dd/MM/yyyy' => Zend_Date::now()->toString('dd/MM/yyyy'),
1507
			);
1508
			$dateFormatMap[$defaultDateFormat] = Zend_Date::now()->toString($defaultDateFormat)
1509
				. sprintf(' (%s)', _t('Member.DefaultDateTime', 'default'));
1510
			$mainFields->push(
1511
				$dateFormatField = new MemberDatetimeOptionsetField(
1512
					'DateFormat',
1513
					$self->fieldLabel('DateFormat'),
1514
					$dateFormatMap
1515
				)
1516
			);
1517
			$dateFormatField->setValue($self->DateFormat);
1518
1519
			$defaultTimeFormat = Zend_Locale_Format::getTimeFormat(new Zend_Locale($self->Locale));
1520
			$timeFormatMap = array(
1521
				'h:mm a' => Zend_Date::now()->toString('h:mm a'),
1522
				'H:mm' => Zend_Date::now()->toString('H:mm'),
1523
			);
1524
			$timeFormatMap[$defaultTimeFormat] = Zend_Date::now()->toString($defaultTimeFormat)
1525
				. sprintf(' (%s)', _t('Member.DefaultDateTime', 'default'));
1526
			$mainFields->push(
1527
				$timeFormatField = new MemberDatetimeOptionsetField(
1528
					'TimeFormat',
1529
					$self->fieldLabel('TimeFormat'),
1530
					$timeFormatMap
1531
				)
1532
			);
1533
			$timeFormatField->setValue($self->TimeFormat);
1534
		});
1535
1536
		return parent::getCMSFields();
1537
	}
1538
1539
	/**
1540
	 *
1541
	 * @param boolean $includerelations a boolean value to indicate if the labels returned include relation fields
1542
	 *
1543
	 */
1544
	public function fieldLabels($includerelations = true) {
1545
		$labels = parent::fieldLabels($includerelations);
1546
1547
		$labels['FirstName'] = _t('Member.FIRSTNAME', 'First Name');
1548
		$labels['Surname'] = _t('Member.SURNAME', 'Surname');
1549
		$labels['Email'] = _t('Member.EMAIL', 'Email');
1550
		$labels['Password'] = _t('Member.db_Password', 'Password');
1551
		$labels['NumVisit'] = _t('Member.db_NumVisit', 'Number of Visits');
1552
		$labels['LastVisited'] = _t('Member.db_LastVisited', 'Last Visited Date');
1553
		$labels['PasswordExpiry'] = _t('Member.db_PasswordExpiry', 'Password Expiry Date', 'Password expiry date');
1554
		$labels['LockedOutUntil'] = _t('Member.db_LockedOutUntil', 'Locked out until', 'Security related date');
1555
		$labels['Locale'] = _t('Member.db_Locale', 'Interface Locale');
1556
		$labels['DateFormat'] = _t('Member.DATEFORMAT', 'Date format');
1557
		$labels['TimeFormat'] = _t('Member.TIMEFORMAT', 'Time format');
1558
		if($includerelations){
1559
			$labels['Groups'] = _t('Member.belongs_many_many_Groups', 'Groups',
1560
				'Security Groups this member belongs to');
1561
		}
1562
		return $labels;
1563
	}
1564
1565
	/**
1566
	 * Users can view their own record.
1567
	 * Otherwise they'll need ADMIN or CMS_ACCESS_SecurityAdmin permissions.
1568
	 * This is likely to be customized for social sites etc. with a looser permission model.
1569
	 */
1570
	public function canView($member = null) {
1571
		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...
1572
1573
		// extended access checks
1574
		$results = $this->extend('canView', $member);
1575
		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...
1576
			if(!min($results)) return false;
1577
			else return true;
1578
		}
1579
1580
		// members can usually edit their own record
1581
		if($member && $this->ID == $member->ID) return true;
1582
1583
		if(
1584
			Permission::checkMember($member, 'ADMIN')
1585
			|| Permission::checkMember($member, 'CMS_ACCESS_SecurityAdmin')
1586
		) {
1587
			return true;
1588
		}
1589
1590
		return false;
1591
	}
1592
1593
	/**
1594
	 * Users can edit their own record.
1595
	 * Otherwise they'll need ADMIN or CMS_ACCESS_SecurityAdmin permissions
1596
	 */
1597
	public function canEdit($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('canEdit', $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
		// No member found
1608
		if(!($member && $member->exists())) return false;
1609
1610
		// If the requesting member is not an admin, but has access to manage members,
1611
		// they still can't edit other members with ADMIN permission.
1612
		// This is a bit weak, strictly speaking they shouldn't be allowed to
1613
		// perform any action that could change the password on a member
1614
		// with "higher" permissions than himself, but thats hard to determine.
1615
		if(!Permission::checkMember($member, 'ADMIN') && Permission::checkMember($this, 'ADMIN')) return false;
1616
1617
		return $this->canView($member);
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 canDelete($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('canDelete', $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
		// Members are not allowed to remove themselves,
1638
		// since it would create inconsistencies in the admin UIs.
1639
		if($this->ID && $member->ID == $this->ID) return false;
1640
1641
		return $this->canEdit($member);
1642
	}
1643
1644
1645
	/**
1646
	 * Validate this member object.
1647
	 */
1648
	public function validate() {
1649
		$valid = parent::validate();
1650
1651
		if(!$this->ID || $this->isChanged('Password')) {
1652
			if($this->Password && self::$password_validator) {
1653
				$valid->combineAnd(self::$password_validator->validate($this->Password, $this));
1654
			}
1655
		}
1656
1657
		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...
1658
			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...
1659
				$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...
1660
			}
1661
		}
1662
1663
		return $valid;
1664
	}
1665
1666
	/**
1667
	 * Change password. This will cause rehashing according to
1668
	 * the `PasswordEncryption` property.
1669
	 *
1670
	 * @param String $password Cleartext password
1671
	 */
1672
	public function changePassword($password) {
1673
		$this->Password = $password;
1674
		$valid = $this->validate();
1675
1676
		if($valid->valid()) {
1677
			$this->AutoLoginHash = null;
1678
			$this->write();
1679
		}
1680
1681
		return $valid;
1682
	}
1683
1684
	/**
1685
	 * Tell this member that someone made a failed attempt at logging in as them.
1686
	 * This can be used to lock the user out temporarily if too many failed attempts are made.
1687
	 */
1688
	public function registerFailedLogin() {
1689
		if(self::config()->lock_out_after_incorrect_logins) {
1690
			// Keep a tally of the number of failed log-ins so that we can lock people out
1691
			++$this->FailedLoginCount;
1692
1693
			if($this->FailedLoginCount >= self::config()->lock_out_after_incorrect_logins) {
1694
				$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...
1695
				$this->LockedOutUntil = date('Y-m-d H:i:s', SS_Datetime::now()->Format('U') + $lockoutMins*60);
1696
				$this->FailedLoginCount = 0;
1697
			}
1698
		}
1699
		$this->extend('registerFailedLogin');
1700
		$this->write();
1701
	}
1702
1703
	/**
1704
	 * Tell this member that a successful login has been made
1705
	 */
1706
	public function registerSuccessfulLogin() {
1707
		if(self::config()->lock_out_after_incorrect_logins) {
1708
			// Forgive all past login failures
1709
			$this->FailedLoginCount = 0;
1710
			$this->LockedOutUntil = null;
1711
			$this->write();
1712
		}
1713
	}
1714
	/**
1715
	 * Get the HtmlEditorConfig for this user to be used in the CMS.
1716
	 * This is set by the group. If multiple configurations are set,
1717
	 * the one with the highest priority wins.
1718
	 *
1719
	 * @return string
1720
	 */
1721
	public function getHtmlEditorConfigForCMS() {
1722
		$currentName = '';
1723
		$currentPriority = 0;
1724
1725
		foreach($this->Groups() as $group) {
1726
			$configName = $group->HtmlEditorConfig;
1727
			if($configName) {
1728
				$config = HtmlEditorConfig::get($group->HtmlEditorConfig);
1729
				if($config && $config->getOption('priority') > $currentPriority) {
1730
					$currentName = $configName;
1731
					$currentPriority = $config->getOption('priority');
1732
				}
1733
			}
1734
		}
1735
1736
		// If can't find a suitable editor, just default to cms
1737
		return $currentName ? $currentName : 'cms';
1738
	}
1739
1740
	public static function get_template_global_variables() {
1741
		return array(
1742
			'CurrentMember' => 'currentUser',
1743
			'currentUser',
1744
		);
1745
	}
1746
}
1747
1748
/**
1749
 * Represents a set of Groups attached to a member.
1750
 * Handles the hierarchy logic.
1751
 * @package framework
1752
 * @subpackage security
1753
 */
1754
class Member_GroupSet extends ManyManyList {
1755
1756
	protected function linkJoinTable() {
1757
		// Do not join the table directly
1758
		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...
1759
			user_error('Member_GroupSet does not support many_many_extraFields', E_USER_ERROR);
1760
		}
1761
	}
1762
1763
	/**
1764
	 * Link this group set to a specific member.
1765
	 *
1766
	 * Recursively selects all groups applied to this member, as well as any
1767
	 * parent groups of any applied groups
1768
	 *
1769
	 * @param array|integer $id (optional) An ID or an array of IDs - if not provided, will use the current
1770
	 * ids as per getForeignID
1771
	 * @return array Condition In array(SQL => parameters format)
1772
	 */
1773
	public function foreignIDFilter($id = null) {
1774
		if ($id === null) $id = $this->getForeignID();
1775
1776
		// Find directly applied groups
1777
		$manyManyFilter = parent::foreignIDFilter($id);
1778
		$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 1777 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...
1779
		$groupIDs = $query->execute()->column();
1780
1781
		// Get all ancestors, iteratively merging these into the master set
1782
		$allGroupIDs = array();
1783
		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...
1784
			$allGroupIDs = array_merge($allGroupIDs, $groupIDs);
1785
			$groupIDs = DataObject::get("Group")->byIDs($groupIDs)->column("ParentID");
1786
			$groupIDs = array_filter($groupIDs);
1787
		}
1788
1789
		// Add a filter to this DataList
1790
		if(!empty($allGroupIDs)) {
1791
			$allGroupIDsPlaceholders = DB::placeholders($allGroupIDs);
1792
			return array("\"Group\".\"ID\" IN ($allGroupIDsPlaceholders)" => $allGroupIDs);
1793
		} else {
1794
			return array('"Group"."ID"' => 0);
1795
		}
1796
	}
1797
1798
	public function foreignIDWriteFilter($id = null) {
1799
		// Use the ManyManyList::foreignIDFilter rather than the one
1800
		// in this class, otherwise we end up selecting all inherited groups
1801
		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...
1802
	}
1803
1804
	public function add($item, $extraFields = null) {
1805
		// Get Group.ID
1806
		$itemID = null;
1807
		if(is_numeric($item)) {
1808
			$itemID = $item;
1809
		} else if($item instanceof Group) {
1810
			$itemID = $item->ID;
1811
		}
1812
1813
		// Check if this group is allowed to be added
1814
		if($this->canAddGroups(array($itemID))) {
1815
			parent::add($item, $extraFields);
1816
		}
1817
	}
1818
1819
	/**
1820
	 * Determine if the following groups IDs can be added
1821
	 *
1822
	 * @param array $itemIDs
1823
	 * @return boolean
1824
	 */
1825
	protected function canAddGroups($itemIDs) {
1826
		if(empty($itemIDs)) {
1827
			return true;
1828
		}
1829
		$member = $this->getMember();
1830
		return empty($member) || $member->onChangeGroups($itemIDs);
1831
	}
1832
1833
	/**
1834
	 * Get foreign member record for this relation
1835
	 *
1836
	 * @return Member
1837
	 */
1838
	protected function getMember() {
1839
		$id = $this->getForeignID();
1840
		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...
1841
			return DataObject::get_by_id('Member', $id);
1842
		}
1843
	}
1844
}
1845
1846
/**
1847
 * Class used as template to send an email saying that the password has been
1848
 * changed.
1849
 *
1850
 * @package framework
1851
 * @subpackage security
1852
 */
1853
class Member_ChangePasswordEmail extends Email {
1854
1855
	protected $from = '';   // setting a blank from address uses the site's default administrator email
1856
	protected $subject = '';
1857
	protected $ss_template = 'ChangePasswordEmail';
1858
1859
	public function __construct() {
1860
		parent::__construct();
1861
1862
		$this->subject = _t('Member.SUBJECTPASSWORDCHANGED', "Your password has been changed", 'Email subject');
1863
	}
1864
}
1865
1866
1867
1868
/**
1869
 * Class used as template to send the forgot password email
1870
 *
1871
 * @package framework
1872
 * @subpackage security
1873
 */
1874
class Member_ForgotPasswordEmail extends Email {
1875
	protected $from = '';  // setting a blank from address uses the site's default administrator email
1876
	protected $subject = '';
1877
	protected $ss_template = 'ForgotPasswordEmail';
1878
1879
	public function __construct() {
1880
		parent::__construct();
1881
1882
		$this->subject = _t('Member.SUBJECTPASSWORDRESET', "Your password reset link", 'Email subject');
1883
	}
1884
}
1885
1886
/**
1887
 * Member Validator
1888
 *
1889
 * Custom validation for the Member object can be achieved either through an
1890
 * {@link DataExtension} on the Member_Validator object or, by specifying a subclass of
1891
 * {@link Member_Validator} through the {@link Injector} API.
1892
 * The Validator can also be modified by adding an Extension to Member and implement the
1893
 * <code>updateValidator</code> hook.
1894
 * {@see Member::getValidator()}
1895
 *
1896
 * Additional required fields can also be set via config API, eg.
1897
 * <code>
1898
 * Member_Validator:
1899
 *   customRequired:
1900
 *     - Surname
1901
 * </code>
1902
 *
1903
 * @package framework
1904
 * @subpackage security
1905
 */
1906
class Member_Validator extends RequiredFields
1907
{
1908
	/**
1909
	 * Fields that are required by this validator
1910
	 * @config
1911
	 * @var array
1912
	 */
1913
	protected $customRequired = array(
1914
		'FirstName',
1915
		'Email'
1916
	);
1917
1918
	/**
1919
	 * Determine what member this validator is meant for
1920
	 * @var Member
1921
	 */
1922
	protected $forMember = null;
1923
1924
	/**
1925
	 * Constructor
1926
	 */
1927
	public function __construct() {
1928
		$required = func_get_args();
1929
1930
		if(isset($required[0]) && is_array($required[0])) {
1931
			$required = $required[0];
1932
		}
1933
1934
		$required = array_merge($required, $this->customRequired);
1935
1936
		// check for config API values and merge them in
1937
		$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...
1938
		if(is_array($config)){
1939
			$required = array_merge($required, $config);
1940
		}
1941
1942
		parent::__construct(array_unique($required));
1943
	}
1944
1945
	/**
1946
	 * Get the member this validator applies to.
1947
	 * @return Member
1948
	 */
1949
	public function getForMember()
1950
	{
1951
		return $this->forMember;
1952
	}
1953
1954
	/**
1955
	 * Set the Member this validator applies to.
1956
	 * @param Member $value
1957
	 * @return $this
1958
	 */
1959
	public function setForMember(Member $value)
1960
	{
1961
		$this->forMember = $value;
1962
		return $this;
1963
	}
1964
1965
	/**
1966
	 * Check if the submitted member data is valid (server-side)
1967
	 *
1968
	 * Check if a member with that email doesn't already exist, or if it does
1969
	 * that it is this member.
1970
	 *
1971
	 * @param array $data Submitted data
1972
	 * @return bool Returns TRUE if the submitted data is valid, otherwise
1973
	 *              FALSE.
1974
	 */
1975
	public function php($data)
1976
	{
1977
		$valid = parent::php($data);
1978
1979
		$identifierField = (string)Member::config()->unique_identifier_field;
1980
1981
		// Only validate identifier field if it's actually set. This could be the case if
1982
		// somebody removes `Email` from the list of required fields.
1983
		if(isset($data[$identifierField])){
1984
			$id = isset($data['ID']) ? (int)$data['ID'] : 0;
1985
			if(!$id && ($ctrl = $this->form->getController())){
1986
				// get the record when within GridField (Member editing page in CMS)
1987
				if($ctrl instanceof GridFieldDetailForm_ItemRequest && $record = $ctrl->getRecord()){
1988
					$id = $record->ID;
1989
				}
1990
			}
1991
1992
			// If there's no ID passed via controller or form-data, use the assigned member (if available)
1993
			if(!$id && ($member = $this->getForMember())){
1994
				$id = $member->exists() ? $member->ID : 0;
1995
			}
1996
1997
			// set the found ID to the data array, so that extensions can also use it
1998
			$data['ID'] = $id;
1999
2000
			$members = Member::get()->filter($identifierField, $data[$identifierField]);
2001
			if($id) {
2002
				$members = $members->exclude('ID', $id);
2003
			}
2004
2005
			if($members->count() > 0) {
2006
				$this->validationError(
2007
					$identifierField,
2008
					_t(
2009
						'Member.VALIDATIONMEMBEREXISTS',
2010
						'A member already exists with the same {identifier}',
2011
						array('identifier' => Member::singleton()->fieldLabel($identifierField))
2012
					),
2013
					'required'
2014
				);
2015
				$valid = false;
2016
			}
2017
		}
2018
2019
2020
		// Execute the validators on the extensions
2021
		$results = $this->extend('updatePHP', $data, $this->form);
2022
		$results[] = $valid;
2023
		return min($results);
2024
	}
2025
}
2026