Completed
Push — member-groupset-delete ( a90a9a )
by Loz
11:22
created

Member_GroupSet::removeAll()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 30
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

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

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

Consider the following code:

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

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

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

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

Loading history...
1818
		$subSelect = $selectQuery->sql($parameters);
1819
		$delete->addWhere(array(
1820
			"\"{$this->joinTable}\".\"{$this->localKey}\" IN ($subSelect)" => $parameters
1821
		));
1822
		$delete->execute();
1823
	}
1824
1825
	/**
1826
	 * Determine if the following groups IDs can be added
1827
	 *
1828
	 * @param array $itemIDs
1829
	 * @return boolean
1830
	 */
1831
	protected function canAddGroups($itemIDs) {
1832
		if(empty($itemIDs)) {
1833
			return true;
1834
		}
1835
		$member = $this->getMember();
1836
		return empty($member) || $member->onChangeGroups($itemIDs);
1837
	}
1838
1839
	/**
1840
	 * Get foreign member record for this relation
1841
	 *
1842
	 * @return Member
1843
	 */
1844
	protected function getMember() {
1845
		$id = $this->getForeignID();
1846
		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...
1847
			return DataObject::get_by_id('Member', $id);
1848
		}
1849
	}
1850
}
1851
1852
/**
1853
 * Class used as template to send an email saying that the password has been
1854
 * changed.
1855
 *
1856
 * @package framework
1857
 * @subpackage security
1858
 */
1859
class Member_ChangePasswordEmail extends Email {
1860
1861
	protected $from = '';   // setting a blank from address uses the site's default administrator email
1862
	protected $subject = '';
1863
	protected $ss_template = 'ChangePasswordEmail';
1864
1865
	public function __construct() {
1866
		parent::__construct();
1867
1868
		$this->subject = _t('Member.SUBJECTPASSWORDCHANGED', "Your password has been changed", 'Email subject');
1869
	}
1870
}
1871
1872
1873
1874
/**
1875
 * Class used as template to send the forgot password email
1876
 *
1877
 * @package framework
1878
 * @subpackage security
1879
 */
1880
class Member_ForgotPasswordEmail extends Email {
1881
	protected $from = '';  // setting a blank from address uses the site's default administrator email
1882
	protected $subject = '';
1883
	protected $ss_template = 'ForgotPasswordEmail';
1884
1885
	public function __construct() {
1886
		parent::__construct();
1887
1888
		$this->subject = _t('Member.SUBJECTPASSWORDRESET', "Your password reset link", 'Email subject');
1889
	}
1890
}
1891
1892
/**
1893
 * Member Validator
1894
 *
1895
 * Custom validation for the Member object can be achieved either through an
1896
 * {@link DataExtension} on the Member_Validator object or, by specifying a subclass of
1897
 * {@link Member_Validator} through the {@link Injector} API.
1898
 * The Validator can also be modified by adding an Extension to Member and implement the
1899
 * <code>updateValidator</code> hook.
1900
 * {@see Member::getValidator()}
1901
 *
1902
 * Additional required fields can also be set via config API, eg.
1903
 * <code>
1904
 * Member_Validator:
1905
 *   customRequired:
1906
 *     - Surname
1907
 * </code>
1908
 *
1909
 * @package framework
1910
 * @subpackage security
1911
 */
1912
class Member_Validator extends RequiredFields
1913
{
1914
	/**
1915
	 * Fields that are required by this validator
1916
	 * @config
1917
	 * @var array
1918
	 */
1919
	protected $customRequired = array(
1920
		'FirstName',
1921
		'Email'
1922
	);
1923
1924
	/**
1925
	 * Determine what member this validator is meant for
1926
	 * @var Member
1927
	 */
1928
	protected $forMember = null;
1929
1930
	/**
1931
	 * Constructor
1932
	 */
1933
	public function __construct() {
1934
		$required = func_get_args();
1935
1936
		if(isset($required[0]) && is_array($required[0])) {
1937
			$required = $required[0];
1938
		}
1939
1940
		$required = array_merge($required, $this->customRequired);
1941
1942
		// check for config API values and merge them in
1943
		$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...
1944
		if(is_array($config)){
1945
			$required = array_merge($required, $config);
1946
		}
1947
1948
		parent::__construct(array_unique($required));
1949
	}
1950
1951
	/**
1952
	 * Get the member this validator applies to.
1953
	 * @return Member
1954
	 */
1955
	public function getForMember()
1956
	{
1957
		return $this->forMember;
1958
	}
1959
1960
	/**
1961
	 * Set the Member this validator applies to.
1962
	 * @param Member $value
1963
	 * @return $this
1964
	 */
1965
	public function setForMember(Member $value)
1966
	{
1967
		$this->forMember = $value;
1968
		return $this;
1969
	}
1970
1971
	/**
1972
	 * Check if the submitted member data is valid (server-side)
1973
	 *
1974
	 * Check if a member with that email doesn't already exist, or if it does
1975
	 * that it is this member.
1976
	 *
1977
	 * @param array $data Submitted data
1978
	 * @return bool Returns TRUE if the submitted data is valid, otherwise
1979
	 *              FALSE.
1980
	 */
1981
	public function php($data)
1982
	{
1983
		$valid = parent::php($data);
1984
1985
		$identifierField = (string)Member::config()->unique_identifier_field;
1986
1987
		// Only validate identifier field if it's actually set. This could be the case if
1988
		// somebody removes `Email` from the list of required fields.
1989
		if(isset($data[$identifierField])){
1990
			$id = isset($data['ID']) ? (int)$data['ID'] : 0;
1991
			if(!$id && ($ctrl = $this->form->getController())){
1992
				// get the record when within GridField (Member editing page in CMS)
1993
				if($ctrl instanceof GridFieldDetailForm_ItemRequest && $record = $ctrl->getRecord()){
1994
					$id = $record->ID;
1995
				}
1996
			}
1997
1998
			// If there's no ID passed via controller or form-data, use the assigned member (if available)
1999
			if(!$id && ($member = $this->getForMember())){
2000
				$id = $member->exists() ? $member->ID : 0;
2001
			}
2002
2003
			// set the found ID to the data array, so that extensions can also use it
2004
			$data['ID'] = $id;
2005
2006
			$members = Member::get()->filter($identifierField, $data[$identifierField]);
2007
			if($id) {
2008
				$members = $members->exclude('ID', $id);
2009
			}
2010
2011
			if($members->count() > 0) {
2012
				$this->validationError(
2013
					$identifierField,
2014
					_t(
2015
						'Member.VALIDATIONMEMBEREXISTS',
2016
						'A member already exists with the same {identifier}',
2017
						array('identifier' => Member::singleton()->fieldLabel($identifierField))
2018
					),
2019
					'required'
2020
				);
2021
				$valid = false;
2022
			}
2023
		}
2024
2025
2026
		// Execute the validators on the extensions
2027
		$results = $this->extend('updatePHP', $data, $this->form);
2028
		$results[] = $valid;
2029
		return min($results);
2030
	}
2031
}
2032