Total Complexity | 200 |
Total Lines | 1779 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
Complex classes like Member often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Member, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
62 | class Member extends DataObject |
||
63 | { |
||
64 | private static $db = array( |
||
65 | 'FirstName' => 'Varchar', |
||
66 | 'Surname' => 'Varchar', |
||
67 | 'Email' => 'Varchar(254)', // See RFC 5321, Section 4.5.3.1.3. (256 minus the < and > character) |
||
68 | 'TempIDHash' => 'Varchar(160)', // Temporary id used for cms re-authentication |
||
69 | 'TempIDExpired' => 'Datetime', // Expiry of temp login |
||
70 | 'Password' => 'Varchar(160)', |
||
71 | 'AutoLoginHash' => 'Varchar(160)', // Used to auto-login the user on password reset |
||
72 | 'AutoLoginExpired' => 'Datetime', |
||
73 | // This is an arbitrary code pointing to a PasswordEncryptor instance, |
||
74 | // not an actual encryption algorithm. |
||
75 | // Warning: Never change this field after its the first password hashing without |
||
76 | // providing a new cleartext password as well. |
||
77 | 'PasswordEncryption' => "Varchar(50)", |
||
78 | 'Salt' => 'Varchar(50)', |
||
79 | 'PasswordExpiry' => 'Date', |
||
80 | 'LockedOutUntil' => 'Datetime', |
||
81 | 'Locale' => 'Varchar(6)', |
||
82 | // handled in registerFailedLogin(), only used if $lock_out_after_incorrect_logins is set |
||
83 | 'FailedLoginCount' => 'Int', |
||
84 | ); |
||
85 | |||
86 | private static $belongs_many_many = array( |
||
87 | 'Groups' => Group::class, |
||
88 | ); |
||
89 | |||
90 | private static $has_many = array( |
||
91 | 'LoggedPasswords' => MemberPassword::class, |
||
92 | 'RememberLoginHashes' => RememberLoginHash::class, |
||
93 | ); |
||
94 | |||
95 | private static $table_name = "Member"; |
||
96 | |||
97 | private static $default_sort = '"Surname", "FirstName"'; |
||
98 | |||
99 | private static $indexes = array( |
||
100 | 'Email' => true, |
||
101 | //Removed due to duplicate null values causing MSSQL problems |
||
102 | //'AutoLoginHash' => Array('type'=>'unique', 'value'=>'AutoLoginHash', 'ignoreNulls'=>true) |
||
103 | ); |
||
104 | |||
105 | /** |
||
106 | * @config |
||
107 | * @var boolean |
||
108 | */ |
||
109 | private static $notify_password_change = false; |
||
110 | |||
111 | /** |
||
112 | * All searchable database columns |
||
113 | * in this object, currently queried |
||
114 | * with a "column LIKE '%keywords%' |
||
115 | * statement. |
||
116 | * |
||
117 | * @var array |
||
118 | * @todo Generic implementation of $searchable_fields on DataObject, |
||
119 | * with definition for different searching algorithms |
||
120 | * (LIKE, FULLTEXT) and default FormFields to construct a searchform. |
||
121 | */ |
||
122 | private static $searchable_fields = array( |
||
123 | 'FirstName', |
||
124 | 'Surname', |
||
125 | 'Email', |
||
126 | ); |
||
127 | |||
128 | /** |
||
129 | * @config |
||
130 | * @var array |
||
131 | */ |
||
132 | private static $summary_fields = array( |
||
133 | 'FirstName', |
||
134 | 'Surname', |
||
135 | 'Email', |
||
136 | ); |
||
137 | |||
138 | /** |
||
139 | * @config |
||
140 | * @var array |
||
141 | */ |
||
142 | private static $casting = array( |
||
143 | 'Name' => 'Varchar', |
||
144 | ); |
||
145 | |||
146 | /** |
||
147 | * Internal-use only fields |
||
148 | * |
||
149 | * @config |
||
150 | * @var array |
||
151 | */ |
||
152 | private static $hidden_fields = array( |
||
153 | 'AutoLoginHash', |
||
154 | 'AutoLoginExpired', |
||
155 | 'PasswordEncryption', |
||
156 | 'PasswordExpiry', |
||
157 | 'LockedOutUntil', |
||
158 | 'TempIDHash', |
||
159 | 'TempIDExpired', |
||
160 | 'Salt', |
||
161 | ); |
||
162 | |||
163 | /** |
||
164 | * @config |
||
165 | * @var array See {@link set_title_columns()} |
||
166 | */ |
||
167 | private static $title_format = null; |
||
168 | |||
169 | /** |
||
170 | * The unique field used to identify this member. |
||
171 | * By default, it's "Email", but another common |
||
172 | * field could be Username. |
||
173 | * |
||
174 | * @config |
||
175 | * @var string |
||
176 | * @skipUpgrade |
||
177 | */ |
||
178 | private static $unique_identifier_field = 'Email'; |
||
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 bool enable or disable logging of previously used passwords. See {@link onAfterWrite} |
||
190 | */ |
||
191 | private static $password_logging_enabled = true; |
||
192 | |||
193 | /** |
||
194 | * @config |
||
195 | * @var Int Number of incorrect logins after which |
||
196 | * the user is blocked from further attempts for the timespan |
||
197 | * defined in {@link $lock_out_delay_mins}. |
||
198 | */ |
||
199 | private static $lock_out_after_incorrect_logins = 10; |
||
200 | |||
201 | /** |
||
202 | * @config |
||
203 | * @var integer Minutes of enforced lockout after incorrect password attempts. |
||
204 | * Only applies if {@link $lock_out_after_incorrect_logins} greater than 0. |
||
205 | */ |
||
206 | private static $lock_out_delay_mins = 15; |
||
207 | |||
208 | /** |
||
209 | * @config |
||
210 | * @var String If this is set, then a session cookie with the given name will be set on log-in, |
||
211 | * and cleared on logout. |
||
212 | */ |
||
213 | private static $login_marker_cookie = null; |
||
214 | |||
215 | /** |
||
216 | * Indicates that when a {@link Member} logs in, Member:session_regenerate_id() |
||
217 | * should be called as a security precaution. |
||
218 | * |
||
219 | * This doesn't always work, especially if you're trying to set session cookies |
||
220 | * across an entire site using the domain parameter to session_set_cookie_params() |
||
221 | * |
||
222 | * @config |
||
223 | * @var boolean |
||
224 | */ |
||
225 | private static $session_regenerate_id = true; |
||
226 | |||
227 | |||
228 | /** |
||
229 | * Default lifetime of temporary ids. |
||
230 | * |
||
231 | * This is the period within which a user can be re-authenticated within the CMS by entering only their password |
||
232 | * and without losing their workspace. |
||
233 | * |
||
234 | * Any session expiration outside of this time will require them to login from the frontend using their full |
||
235 | * username and password. |
||
236 | * |
||
237 | * Defaults to 72 hours. Set to zero to disable expiration. |
||
238 | * |
||
239 | * @config |
||
240 | * @var int Lifetime in seconds |
||
241 | */ |
||
242 | private static $temp_id_lifetime = 259200; |
||
243 | |||
244 | /** |
||
245 | * Default lifetime of auto login token. |
||
246 | * |
||
247 | * This is the maximum allowed period between a user requesting a password reset link and using it to reset |
||
248 | * their password. |
||
249 | * |
||
250 | * Defaults to 2 days. |
||
251 | * |
||
252 | * @config |
||
253 | * @var int Lifetime in seconds |
||
254 | */ |
||
255 | private static $auto_login_token_lifetime = 172800; |
||
256 | |||
257 | /** |
||
258 | * Used to track whether {@link Member::changePassword} has made changed that need to be written. Used to prevent |
||
259 | * the write from calling changePassword again. |
||
260 | * |
||
261 | * @var bool |
||
262 | */ |
||
263 | protected $passwordChangesToWrite = false; |
||
264 | |||
265 | /** |
||
266 | * Ensure the locale is set to something sensible by default. |
||
267 | */ |
||
268 | public function populateDefaults() |
||
272 | } |
||
273 | |||
274 | public function requireDefaultRecords() |
||
275 | { |
||
276 | parent::requireDefaultRecords(); |
||
277 | // Default groups should've been built by Group->requireDefaultRecords() already |
||
278 | $service = DefaultAdminService::singleton(); |
||
279 | $service->findOrCreateDefaultAdmin(); |
||
280 | } |
||
281 | |||
282 | /** |
||
283 | * Get the default admin record if it exists, or creates it otherwise if enabled |
||
284 | * |
||
285 | * @deprecated 4.0.0:5.0.0 Use DefaultAdminService::findOrCreateDefaultAdmin() instead |
||
286 | * @return Member |
||
287 | */ |
||
288 | public static function default_admin() |
||
289 | { |
||
290 | Deprecation::notice('5.0', 'Use DefaultAdminService::findOrCreateDefaultAdmin() instead'); |
||
291 | return DefaultAdminService::singleton()->findOrCreateDefaultAdmin(); |
||
292 | } |
||
293 | |||
294 | /** |
||
295 | * Check if the passed password matches the stored one (if the member is not locked out). |
||
296 | * |
||
297 | * @deprecated 4.0.0:5.0.0 Use Authenticator::checkPassword() instead |
||
298 | * |
||
299 | * @param string $password |
||
300 | * @return ValidationResult |
||
301 | */ |
||
302 | public function checkPassword($password) |
||
303 | { |
||
304 | Deprecation::notice('5.0', 'Use Authenticator::checkPassword() instead'); |
||
305 | |||
306 | // With a valid user and password, check the password is correct |
||
307 | $result = ValidationResult::create(); |
||
308 | $authenticators = Security::singleton()->getApplicableAuthenticators(Authenticator::CHECK_PASSWORD); |
||
309 | foreach ($authenticators as $authenticator) { |
||
310 | $authenticator->checkPassword($this, $password, $result); |
||
311 | if (!$result->isValid()) { |
||
312 | break; |
||
313 | } |
||
314 | } |
||
315 | return $result; |
||
316 | } |
||
317 | |||
318 | /** |
||
319 | * Check if this user is the currently configured default admin |
||
320 | * |
||
321 | * @return bool |
||
322 | */ |
||
323 | public function isDefaultAdmin() |
||
324 | { |
||
325 | return DefaultAdminService::isDefaultAdmin($this->Email); |
||
326 | } |
||
327 | |||
328 | /** |
||
329 | * Check if this user can login |
||
330 | * |
||
331 | * @return bool |
||
332 | */ |
||
333 | public function canLogin() |
||
336 | } |
||
337 | |||
338 | /** |
||
339 | * Returns a valid {@link ValidationResult} if this member can currently log in, or an invalid |
||
340 | * one with error messages to display if the member is locked out. |
||
341 | * |
||
342 | * You can hook into this with a "canLogIn" method on an attached extension. |
||
343 | * |
||
344 | * @param ValidationResult $result Optional result to add errors to |
||
345 | * @return ValidationResult |
||
346 | */ |
||
347 | public function validateCanLogin(ValidationResult &$result = null) |
||
348 | { |
||
349 | $result = $result ?: ValidationResult::create(); |
||
350 | if ($this->isLockedOut()) { |
||
351 | $result->addError( |
||
352 | _t( |
||
353 | __CLASS__ . '.ERRORLOCKEDOUT2', |
||
354 | 'Your account has been temporarily disabled because of too many failed attempts at ' . 'logging in. Please try again in {count} minutes.', |
||
355 | null, |
||
356 | array('count' => static::config()->get('lock_out_delay_mins')) |
||
357 | ) |
||
358 | ); |
||
359 | } |
||
360 | |||
361 | $this->extend('canLogIn', $result); |
||
362 | |||
363 | return $result; |
||
364 | } |
||
365 | |||
366 | /** |
||
367 | * Returns true if this user is locked out |
||
368 | * |
||
369 | * @skipUpgrade |
||
370 | * @return bool |
||
371 | */ |
||
372 | public function isLockedOut() |
||
373 | { |
||
374 | /** @var DBDatetime $lockedOutUntilObj */ |
||
375 | $lockedOutUntilObj = $this->dbObject('LockedOutUntil'); |
||
376 | if ($lockedOutUntilObj->InFuture()) { |
||
377 | return true; |
||
378 | } |
||
379 | |||
380 | $maxAttempts = $this->config()->get('lock_out_after_incorrect_logins'); |
||
381 | if ($maxAttempts <= 0) { |
||
382 | return false; |
||
383 | } |
||
384 | |||
385 | $idField = static::config()->get('unique_identifier_field'); |
||
386 | $attempts = LoginAttempt::getByEmail($this->{$idField}) |
||
387 | ->sort('Created', 'DESC') |
||
388 | ->limit($maxAttempts); |
||
389 | |||
390 | if ($attempts->count() < $maxAttempts) { |
||
391 | return false; |
||
392 | } |
||
393 | |||
394 | foreach ($attempts as $attempt) { |
||
395 | if ($attempt->Status === 'Success') { |
||
396 | return false; |
||
397 | } |
||
398 | } |
||
399 | |||
400 | // Calculate effective LockedOutUntil |
||
401 | /** @var DBDatetime $firstFailureDate */ |
||
402 | $firstFailureDate = $attempts->first()->dbObject('Created'); |
||
403 | $maxAgeSeconds = $this->config()->get('lock_out_delay_mins') * 60; |
||
404 | $lockedOutUntil = $firstFailureDate->getTimestamp() + $maxAgeSeconds; |
||
405 | $now = DBDatetime::now()->getTimestamp(); |
||
406 | if ($now < $lockedOutUntil) { |
||
407 | return true; |
||
408 | } |
||
409 | |||
410 | return false; |
||
411 | } |
||
412 | |||
413 | /** |
||
414 | * Set a {@link PasswordValidator} object to use to validate member's passwords. |
||
415 | * |
||
416 | * @param PasswordValidator $validator |
||
417 | */ |
||
418 | public static function set_password_validator(PasswordValidator $validator = null) |
||
419 | { |
||
420 | // Override existing config |
||
421 | Config::modify()->remove(Injector::class, PasswordValidator::class); |
||
422 | if ($validator) { |
||
423 | Injector::inst()->registerService($validator, PasswordValidator::class); |
||
424 | } else { |
||
425 | Injector::inst()->unregisterNamedObject(PasswordValidator::class); |
||
426 | } |
||
427 | } |
||
428 | |||
429 | /** |
||
430 | * Returns the default {@link PasswordValidator} |
||
431 | * |
||
432 | * @return PasswordValidator |
||
433 | */ |
||
434 | public static function password_validator() |
||
435 | { |
||
436 | if (Injector::inst()->has(PasswordValidator::class)) { |
||
437 | return Injector::inst()->get(PasswordValidator::class); |
||
438 | } |
||
439 | return null; |
||
440 | } |
||
441 | |||
442 | public function isPasswordExpired() |
||
443 | { |
||
444 | if (!$this->PasswordExpiry) { |
||
445 | return false; |
||
446 | } |
||
447 | |||
448 | return strtotime(date('Y-m-d')) >= strtotime($this->PasswordExpiry); |
||
449 | } |
||
450 | |||
451 | /** |
||
452 | * @deprecated 5.0.0 Use Security::setCurrentUser() or IdentityStore::logIn() |
||
453 | * |
||
454 | */ |
||
455 | public function logIn() |
||
456 | { |
||
457 | Deprecation::notice( |
||
458 | '5.0.0', |
||
459 | 'This method is deprecated and only logs in for the current request. Please use Security::setCurrentUser($user) or an IdentityStore' |
||
460 | ); |
||
461 | Security::setCurrentUser($this); |
||
462 | } |
||
463 | |||
464 | /** |
||
465 | * Called before a member is logged in via session/cookie/etc |
||
466 | */ |
||
467 | public function beforeMemberLoggedIn() |
||
471 | } |
||
472 | |||
473 | /** |
||
474 | * Called after a member is logged in via session/cookie/etc |
||
475 | */ |
||
476 | public function afterMemberLoggedIn() |
||
477 | { |
||
478 | // Clear the incorrect log-in count |
||
479 | $this->registerSuccessfulLogin(); |
||
480 | |||
481 | $this->LockedOutUntil = null; |
||
482 | |||
483 | $this->regenerateTempID(); |
||
484 | |||
485 | $this->write(); |
||
486 | |||
487 | // Audit logging hook |
||
488 | $this->extend('afterMemberLoggedIn'); |
||
489 | } |
||
490 | |||
491 | /** |
||
492 | * Trigger regeneration of TempID. |
||
493 | * |
||
494 | * This should be performed any time the user presents their normal identification (normally Email) |
||
495 | * and is successfully authenticated. |
||
496 | */ |
||
497 | public function regenerateTempID() |
||
498 | { |
||
499 | $generator = new RandomGenerator(); |
||
500 | $lifetime = self::config()->get('temp_id_lifetime'); |
||
501 | $this->TempIDHash = $generator->randomToken('sha1'); |
||
502 | $this->TempIDExpired = $lifetime |
||
503 | ? date('Y-m-d H:i:s', strtotime(DBDatetime::now()->getValue()) + $lifetime) |
||
504 | : null; |
||
505 | $this->write(); |
||
506 | } |
||
507 | |||
508 | /** |
||
509 | * Check if the member ID logged in session actually |
||
510 | * has a database record of the same ID. If there is |
||
511 | * no logged in user, FALSE is returned anyway. |
||
512 | * |
||
513 | * @deprecated Not needed anymore, as it returns Security::getCurrentUser(); |
||
514 | * |
||
515 | * @return boolean TRUE record found FALSE no record found |
||
516 | */ |
||
517 | public static function logged_in_session_exists() |
||
518 | { |
||
519 | Deprecation::notice( |
||
520 | '5.0.0', |
||
521 | 'This method is deprecated and now does not add value. Please use Security::getCurrentUser()' |
||
522 | ); |
||
523 | |||
524 | $member = Security::getCurrentUser(); |
||
525 | if ($member && $member->exists()) { |
||
526 | return true; |
||
527 | } |
||
528 | |||
529 | return false; |
||
530 | } |
||
531 | |||
532 | /** |
||
533 | * @deprecated Use Security::setCurrentUser(null) or an IdentityStore |
||
534 | * Logs this member out. |
||
535 | */ |
||
536 | public function logOut() |
||
537 | { |
||
538 | Deprecation::notice( |
||
539 | '5.0.0', |
||
540 | 'This method is deprecated and now does not persist. Please use Security::setCurrentUser(null) or an IdentityStore' |
||
541 | ); |
||
542 | |||
543 | Injector::inst()->get(IdentityStore::class)->logOut(Controller::curr()->getRequest()); |
||
544 | } |
||
545 | |||
546 | /** |
||
547 | * Audit logging hook, called before a member is logged out |
||
548 | * |
||
549 | * @param HTTPRequest|null $request |
||
550 | */ |
||
551 | public function beforeMemberLoggedOut(HTTPRequest $request = null) |
||
554 | } |
||
555 | |||
556 | /** |
||
557 | * Audit logging hook, called after a member is logged out |
||
558 | * |
||
559 | * @param HTTPRequest|null $request |
||
560 | */ |
||
561 | public function afterMemberLoggedOut(HTTPRequest $request = null) |
||
564 | } |
||
565 | |||
566 | /** |
||
567 | * Utility for generating secure password hashes for this member. |
||
568 | * |
||
569 | * @param string $string |
||
570 | * @return string |
||
571 | * @throws PasswordEncryptor_NotFoundException |
||
572 | */ |
||
573 | public function encryptWithUserSettings($string) |
||
574 | { |
||
575 | if (!$string) { |
||
576 | return null; |
||
577 | } |
||
578 | |||
579 | // If the algorithm or salt is not available, it means we are operating |
||
580 | // on legacy account with unhashed password. Do not hash the string. |
||
581 | if (!$this->PasswordEncryption) { |
||
582 | return $string; |
||
583 | } |
||
584 | |||
585 | // We assume we have PasswordEncryption and Salt available here. |
||
586 | $e = PasswordEncryptor::create_for_algorithm($this->PasswordEncryption); |
||
587 | |||
588 | return $e->encrypt($string, $this->Salt); |
||
589 | } |
||
590 | |||
591 | /** |
||
592 | * Generate an auto login token which can be used to reset the password, |
||
593 | * at the same time hashing it and storing in the database. |
||
594 | * |
||
595 | * @param int|null $lifetime DEPRECATED: The lifetime of the auto login hash in days. Overrides |
||
596 | * the Member.auto_login_token_lifetime config value |
||
597 | * @return string Token that should be passed to the client (but NOT persisted). |
||
598 | */ |
||
599 | public function generateAutologinTokenAndStoreHash($lifetime = null) |
||
600 | { |
||
601 | if ($lifetime !== null) { |
||
602 | Deprecation::notice( |
||
603 | '5.0', |
||
604 | 'Passing a $lifetime to Member::generateAutologinTokenAndStoreHash() is deprecated, |
||
605 | use the Member.auto_login_token_lifetime config setting instead', |
||
606 | Deprecation::SCOPE_GLOBAL |
||
607 | ); |
||
608 | $lifetime = (86400 * $lifetime); // Method argument is days, convert to seconds |
||
609 | } else { |
||
610 | $lifetime = $this->config()->auto_login_token_lifetime; |
||
611 | } |
||
612 | |||
613 | do { |
||
614 | $generator = new RandomGenerator(); |
||
615 | $token = $generator->randomToken(); |
||
616 | $hash = $this->encryptWithUserSettings($token); |
||
617 | } while (DataObject::get_one(Member::class, array( |
||
618 | '"Member"."AutoLoginHash"' => $hash |
||
619 | ))); |
||
620 | |||
621 | $this->AutoLoginHash = $hash; |
||
622 | $this->AutoLoginExpired = date('Y-m-d H:i:s', time() + $lifetime); |
||
623 | |||
624 | $this->write(); |
||
625 | |||
626 | return $token; |
||
627 | } |
||
628 | |||
629 | /** |
||
630 | * Check the token against the member. |
||
631 | * |
||
632 | * @param string $autologinToken |
||
633 | * |
||
634 | * @returns bool Is token valid? |
||
635 | */ |
||
636 | public function validateAutoLoginToken($autologinToken) |
||
637 | { |
||
638 | $hash = $this->encryptWithUserSettings($autologinToken); |
||
639 | $member = self::member_from_autologinhash($hash, false); |
||
640 | |||
641 | return (bool)$member; |
||
642 | } |
||
643 | |||
644 | /** |
||
645 | * Return the member for the auto login hash |
||
646 | * |
||
647 | * @param string $hash The hash key |
||
648 | * @param bool $login Should the member be logged in? |
||
649 | * |
||
650 | * @return Member the matching member, if valid |
||
651 | * @return Member |
||
652 | */ |
||
653 | public static function member_from_autologinhash($hash, $login = false) |
||
654 | { |
||
655 | /** @var Member $member */ |
||
656 | $member = static::get()->filter([ |
||
657 | 'AutoLoginHash' => $hash, |
||
658 | 'AutoLoginExpired:GreaterThan' => DBDatetime::now()->getValue(), |
||
659 | ])->first(); |
||
660 | |||
661 | if ($login && $member) { |
||
662 | Injector::inst()->get(IdentityStore::class)->logIn($member); |
||
663 | } |
||
664 | |||
665 | return $member; |
||
666 | } |
||
667 | |||
668 | /** |
||
669 | * Find a member record with the given TempIDHash value |
||
670 | * |
||
671 | * @param string $tempid |
||
672 | * @return Member |
||
673 | */ |
||
674 | public static function member_from_tempid($tempid) |
||
675 | { |
||
676 | $members = static::get() |
||
677 | ->filter('TempIDHash', $tempid); |
||
678 | |||
679 | // Exclude expired |
||
680 | if (static::config()->get('temp_id_lifetime')) { |
||
681 | /** @var DataList|Member[] $members */ |
||
682 | $members = $members->filter('TempIDExpired:GreaterThan', DBDatetime::now()->getValue()); |
||
683 | } |
||
684 | |||
685 | return $members->first(); |
||
686 | } |
||
687 | |||
688 | /** |
||
689 | * Returns the fields for the member form - used in the registration/profile module. |
||
690 | * It should return fields that are editable by the admin and the logged-in user. |
||
691 | * |
||
692 | * @todo possibly move this to an extension |
||
693 | * |
||
694 | * @return FieldList Returns a {@link FieldList} containing the fields for |
||
695 | * the member form. |
||
696 | */ |
||
697 | public function getMemberFormFields() |
||
698 | { |
||
699 | $fields = parent::getFrontEndFields(); |
||
700 | |||
701 | $fields->replaceField('Password', $this->getMemberPasswordField()); |
||
702 | |||
703 | $fields->replaceField('Locale', new DropdownField( |
||
704 | 'Locale', |
||
705 | $this->fieldLabel('Locale'), |
||
706 | i18n::getSources()->getKnownLocales() |
||
707 | )); |
||
708 | |||
709 | $fields->removeByName(static::config()->get('hidden_fields')); |
||
710 | $fields->removeByName('FailedLoginCount'); |
||
711 | |||
712 | |||
713 | $this->extend('updateMemberFormFields', $fields); |
||
714 | |||
715 | return $fields; |
||
716 | } |
||
717 | |||
718 | /** |
||
719 | * Builds "Change / Create Password" field for this member |
||
720 | * |
||
721 | * @return ConfirmedPasswordField |
||
722 | */ |
||
723 | public function getMemberPasswordField() |
||
747 | } |
||
748 | |||
749 | |||
750 | /** |
||
751 | * Returns the {@link RequiredFields} instance for the Member object. This |
||
752 | * Validator is used when saving a {@link CMSProfileController} or added to |
||
753 | * any form responsible for saving a users data. |
||
754 | * |
||
755 | * To customize the required fields, add a {@link DataExtension} to member |
||
756 | * calling the `updateValidator()` method. |
||
757 | * |
||
758 | * @return Member_Validator |
||
759 | */ |
||
760 | public function getValidator() |
||
761 | { |
||
762 | $validator = Member_Validator::create(); |
||
763 | $validator->setForMember($this); |
||
764 | $this->extend('updateValidator', $validator); |
||
765 | |||
766 | return $validator; |
||
767 | } |
||
768 | |||
769 | |||
770 | /** |
||
771 | * Returns the current logged in user |
||
772 | * |
||
773 | * @deprecated 5.0.0 use Security::getCurrentUser() |
||
774 | * |
||
775 | * @return Member |
||
776 | */ |
||
777 | public static function currentUser() |
||
778 | { |
||
779 | Deprecation::notice( |
||
780 | '5.0.0', |
||
781 | 'This method is deprecated. Please use Security::getCurrentUser() or an IdentityStore' |
||
782 | ); |
||
783 | |||
784 | return Security::getCurrentUser(); |
||
785 | } |
||
786 | |||
787 | /** |
||
788 | * Temporarily act as the specified user, limited to a $callback, but |
||
789 | * without logging in as that user. |
||
790 | * |
||
791 | * E.g. |
||
792 | * <code> |
||
793 | * Member::logInAs(Security::findAnAdministrator(), function() { |
||
794 | * $record->write(); |
||
795 | * }); |
||
796 | * </code> |
||
797 | * |
||
798 | * @param Member|null|int $member Member or member ID to log in as. |
||
799 | * Set to null or 0 to act as a logged out user. |
||
800 | * @param callable $callback |
||
801 | * @return mixed Result of $callback |
||
802 | */ |
||
803 | public static function actAs($member, $callback) |
||
804 | { |
||
805 | $previousUser = Security::getCurrentUser(); |
||
806 | |||
807 | // Transform ID to member |
||
808 | if (is_numeric($member)) { |
||
809 | $member = DataObject::get_by_id(Member::class, $member); |
||
810 | } |
||
811 | Security::setCurrentUser($member); |
||
812 | |||
813 | try { |
||
814 | return $callback(); |
||
815 | } finally { |
||
816 | Security::setCurrentUser($previousUser); |
||
817 | } |
||
818 | } |
||
819 | |||
820 | /** |
||
821 | * Get the ID of the current logged in user |
||
822 | * |
||
823 | * @deprecated 5.0.0 use Security::getCurrentUser() |
||
824 | * |
||
825 | * @return int Returns the ID of the current logged in user or 0. |
||
826 | */ |
||
827 | public static function currentUserID() |
||
828 | { |
||
829 | Deprecation::notice( |
||
830 | '5.0.0', |
||
831 | 'This method is deprecated. Please use Security::getCurrentUser() or an IdentityStore' |
||
832 | ); |
||
833 | |||
834 | $member = Security::getCurrentUser(); |
||
835 | if ($member) { |
||
836 | return $member->ID; |
||
837 | } |
||
838 | return 0; |
||
839 | } |
||
840 | |||
841 | /** |
||
842 | * Generate a random password, with randomiser to kick in if there's no words file on the |
||
843 | * filesystem. |
||
844 | * |
||
845 | * @return string Returns a random password. |
||
846 | */ |
||
847 | public static function create_new_password() |
||
848 | { |
||
849 | $words = Security::config()->uninherited('word_list'); |
||
850 | |||
851 | if ($words && file_exists($words)) { |
||
852 | $words = file($words); |
||
853 | |||
854 | list($usec, $sec) = explode(' ', microtime()); |
||
855 | mt_srand($sec + ((float)$usec * 100000)); |
||
856 | |||
857 | $word = trim($words[random_int(0, count($words) - 1)]); |
||
858 | $number = random_int(10, 999); |
||
859 | |||
860 | return $word . $number; |
||
861 | } else { |
||
862 | $random = mt_rand(); |
||
863 | $string = md5($random); |
||
864 | $output = substr($string, 0, 8); |
||
865 | |||
866 | return $output; |
||
867 | } |
||
868 | } |
||
869 | |||
870 | /** |
||
871 | * Event handler called before writing to the database. |
||
872 | */ |
||
873 | public function onBeforeWrite() |
||
874 | { |
||
875 | // If a member with the same "unique identifier" already exists with a different ID, don't allow merging. |
||
876 | // Note: This does not a full replacement for safeguards in the controller layer (e.g. in a registration form), |
||
877 | // but rather a last line of defense against data inconsistencies. |
||
878 | $identifierField = Member::config()->get('unique_identifier_field'); |
||
879 | if ($this->$identifierField) { |
||
880 | // Note: Same logic as Member_Validator class |
||
881 | $filter = [ |
||
882 | "\"Member\".\"$identifierField\"" => $this->$identifierField |
||
883 | ]; |
||
884 | if ($this->ID) { |
||
885 | $filter[] = array('"Member"."ID" <> ?' => $this->ID); |
||
886 | } |
||
887 | $existingRecord = DataObject::get_one(Member::class, $filter); |
||
888 | |||
889 | if ($existingRecord) { |
||
890 | throw new ValidationException(_t( |
||
891 | __CLASS__ . '.ValidationIdentifierFailed', |
||
892 | 'Can\'t overwrite existing member #{id} with identical identifier ({name} = {value}))', |
||
893 | 'Values in brackets show "fieldname = value", usually denoting an existing email address', |
||
894 | array( |
||
895 | 'id' => $existingRecord->ID, |
||
896 | 'name' => $identifierField, |
||
897 | 'value' => $this->$identifierField |
||
898 | ) |
||
899 | )); |
||
900 | } |
||
901 | } |
||
902 | |||
903 | // We don't send emails out on dev/tests sites to prevent accidentally spamming users. |
||
904 | // However, if TestMailer is in use this isn't a risk. |
||
905 | // @todo some developers use external tools, so emailing might be a good idea anyway |
||
906 | if ((Director::isLive() || Injector::inst()->get(Mailer::class) instanceof TestMailer) |
||
907 | && $this->isChanged('Password') |
||
908 | && $this->record['Password'] |
||
909 | && static::config()->get('notify_password_change') |
||
910 | && $this->isInDB() |
||
911 | ) { |
||
912 | Email::create() |
||
913 | ->setHTMLTemplate('SilverStripe\\Control\\Email\\ChangePasswordEmail') |
||
914 | ->setData($this) |
||
915 | ->setTo($this->Email) |
||
916 | ->setSubject(_t( |
||
917 | __CLASS__ . '.SUBJECTPASSWORDCHANGED', |
||
918 | "Your password has been changed", |
||
919 | 'Email subject' |
||
920 | )) |
||
921 | ->send(); |
||
922 | } |
||
923 | |||
924 | // The test on $this->ID is used for when records are initially created. Note that this only works with |
||
925 | // cleartext passwords, as we can't rehash existing passwords. |
||
926 | if (!$this->ID || $this->isChanged('Password')) { |
||
927 | $this->encryptPassword(); |
||
928 | } |
||
929 | |||
930 | // save locale |
||
931 | if (!$this->Locale) { |
||
932 | $this->Locale = i18n::config()->get('default_locale'); |
||
933 | } |
||
934 | |||
935 | parent::onBeforeWrite(); |
||
936 | } |
||
937 | |||
938 | public function onAfterWrite() |
||
939 | { |
||
940 | parent::onAfterWrite(); |
||
941 | |||
942 | Permission::reset(); |
||
943 | |||
944 | if ($this->isChanged('Password') && static::config()->get('password_logging_enabled')) { |
||
945 | MemberPassword::log($this); |
||
946 | } |
||
947 | } |
||
948 | |||
949 | public function onAfterDelete() |
||
950 | { |
||
951 | parent::onAfterDelete(); |
||
952 | |||
953 | // prevent orphaned records remaining in the DB |
||
954 | $this->deletePasswordLogs(); |
||
955 | $this->Groups()->removeAll(); |
||
956 | } |
||
957 | |||
958 | /** |
||
959 | * Delete the MemberPassword objects that are associated to this user |
||
960 | * |
||
961 | * @return $this |
||
962 | */ |
||
963 | protected function deletePasswordLogs() |
||
964 | { |
||
965 | foreach ($this->LoggedPasswords() as $password) { |
||
966 | $password->delete(); |
||
967 | $password->destroy(); |
||
968 | } |
||
969 | |||
970 | return $this; |
||
971 | } |
||
972 | |||
973 | /** |
||
974 | * Filter out admin groups to avoid privilege escalation, |
||
975 | * If any admin groups are requested, deny the whole save operation. |
||
976 | * |
||
977 | * @param array $ids Database IDs of Group records |
||
978 | * @return bool True if the change can be accepted |
||
979 | */ |
||
980 | public function onChangeGroups($ids) |
||
981 | { |
||
982 | // Ensure none of these match disallowed list |
||
983 | $disallowedGroupIDs = $this->disallowedGroups(); |
||
984 | return count(array_intersect($ids, $disallowedGroupIDs)) == 0; |
||
985 | } |
||
986 | |||
987 | /** |
||
988 | * List of group IDs this user is disallowed from |
||
989 | * |
||
990 | * @return int[] List of group IDs |
||
991 | */ |
||
992 | protected function disallowedGroups() |
||
993 | { |
||
994 | // unless the current user is an admin already OR the logged in user is an admin |
||
995 | if (Permission::check('ADMIN') || Permission::checkMember($this, 'ADMIN')) { |
||
996 | return []; |
||
997 | } |
||
998 | |||
999 | // Non-admins may not belong to admin groups |
||
1000 | return Permission::get_groups_by_permission('ADMIN')->column('ID'); |
||
1001 | } |
||
1002 | |||
1003 | |||
1004 | /** |
||
1005 | * Check if the member is in one of the given groups. |
||
1006 | * |
||
1007 | * @param array|SS_List $groups Collection of {@link Group} DataObjects to check |
||
1008 | * @param boolean $strict Only determine direct group membership if set to true (Default: false) |
||
1009 | * @return bool Returns TRUE if the member is in one of the given groups, otherwise FALSE. |
||
1010 | */ |
||
1011 | public function inGroups($groups, $strict = false) |
||
1012 | { |
||
1013 | if ($groups) { |
||
1014 | foreach ($groups as $group) { |
||
1015 | if ($this->inGroup($group, $strict)) { |
||
1016 | return true; |
||
1017 | } |
||
1018 | } |
||
1019 | } |
||
1020 | |||
1021 | return false; |
||
1022 | } |
||
1023 | |||
1024 | |||
1025 | /** |
||
1026 | * Check if the member is in the given group or any parent groups. |
||
1027 | * |
||
1028 | * @param int|Group|string $group Group instance, Group Code or ID |
||
1029 | * @param boolean $strict Only determine direct group membership if set to TRUE (Default: FALSE) |
||
1030 | * @return bool Returns TRUE if the member is in the given group, otherwise FALSE. |
||
1031 | */ |
||
1032 | public function inGroup($group, $strict = false) |
||
1033 | { |
||
1034 | if (is_numeric($group)) { |
||
1035 | $groupCheckObj = DataObject::get_by_id(Group::class, $group); |
||
1036 | } elseif (is_string($group)) { |
||
1037 | $groupCheckObj = DataObject::get_one(Group::class, array( |
||
1038 | '"Group"."Code"' => $group |
||
1039 | )); |
||
1040 | } elseif ($group instanceof Group) { |
||
1041 | $groupCheckObj = $group; |
||
1042 | } else { |
||
1043 | throw new InvalidArgumentException('Member::inGroup(): Wrong format for $group parameter'); |
||
1044 | } |
||
1045 | |||
1046 | if (!$groupCheckObj) { |
||
1047 | return false; |
||
1048 | } |
||
1049 | |||
1050 | $groupCandidateObjs = ($strict) ? $this->getManyManyComponents("Groups") : $this->Groups(); |
||
1051 | if ($groupCandidateObjs) { |
||
1052 | foreach ($groupCandidateObjs as $groupCandidateObj) { |
||
1053 | if ($groupCandidateObj->ID == $groupCheckObj->ID) { |
||
1054 | return true; |
||
1055 | } |
||
1056 | } |
||
1057 | } |
||
1058 | |||
1059 | return false; |
||
1060 | } |
||
1061 | |||
1062 | /** |
||
1063 | * Adds the member to a group. This will create the group if the given |
||
1064 | * group code does not return a valid group object. |
||
1065 | * |
||
1066 | * @param string $groupcode |
||
1067 | * @param string $title Title of the group |
||
1068 | */ |
||
1069 | public function addToGroupByCode($groupcode, $title = "") |
||
1070 | { |
||
1071 | $group = DataObject::get_one(Group::class, array( |
||
1072 | '"Group"."Code"' => $groupcode |
||
1073 | )); |
||
1074 | |||
1075 | if ($group) { |
||
1076 | $this->Groups()->add($group); |
||
1077 | } else { |
||
1078 | if (!$title) { |
||
1079 | $title = $groupcode; |
||
1080 | } |
||
1081 | |||
1082 | $group = new Group(); |
||
1083 | $group->Code = $groupcode; |
||
1084 | $group->Title = $title; |
||
1085 | $group->write(); |
||
1086 | |||
1087 | $this->Groups()->add($group); |
||
1088 | } |
||
1089 | } |
||
1090 | |||
1091 | /** |
||
1092 | * Removes a member from a group. |
||
1093 | * |
||
1094 | * @param string $groupcode |
||
1095 | */ |
||
1096 | public function removeFromGroupByCode($groupcode) |
||
1102 | } |
||
1103 | } |
||
1104 | |||
1105 | /** |
||
1106 | * @param array $columns Column names on the Member record to show in {@link getTitle()}. |
||
1107 | * @param String $sep Separator |
||
1108 | */ |
||
1109 | public static function set_title_columns($columns, $sep = ' ') |
||
1110 | { |
||
1111 | Deprecation::notice('5.0', 'Use Member.title_format config instead'); |
||
1112 | if (!is_array($columns)) { |
||
1113 | $columns = array($columns); |
||
1114 | } |
||
1115 | self::config()->set( |
||
1116 | 'title_format', |
||
1117 | [ |
||
1118 | 'columns' => $columns, |
||
1119 | 'sep' => $sep |
||
1120 | ] |
||
1121 | ); |
||
1122 | } |
||
1123 | |||
1124 | //------------------- HELPER METHODS -----------------------------------// |
||
1125 | |||
1126 | /** |
||
1127 | * Simple proxy method to get the Surname property of the member |
||
1128 | * |
||
1129 | * @return string |
||
1130 | */ |
||
1131 | public function getLastName() |
||
1132 | { |
||
1133 | return $this->owner->Surname; |
||
1134 | } |
||
1135 | |||
1136 | /** |
||
1137 | * Get the complete name of the member, by default in the format "<Surname>, <FirstName>". |
||
1138 | * Falls back to showing either field on its own. |
||
1139 | * |
||
1140 | * You can overload this getter with {@link set_title_format()} |
||
1141 | * and {@link set_title_sql()}. |
||
1142 | * |
||
1143 | * @return string Returns the first- and surname of the member. If the ID |
||
1144 | * of the member is equal 0, only the surname is returned. |
||
1145 | */ |
||
1146 | public function getTitle() |
||
1147 | { |
||
1148 | $format = static::config()->get('title_format'); |
||
1149 | if ($format) { |
||
1150 | $values = array(); |
||
1151 | foreach ($format['columns'] as $col) { |
||
1152 | $values[] = $this->getField($col); |
||
1153 | } |
||
1154 | |||
1155 | return implode($format['sep'], $values); |
||
1156 | } |
||
1157 | if ($this->getField('ID') === 0) { |
||
1158 | return $this->getField('Surname'); |
||
1159 | } else { |
||
1160 | if ($this->getField('Surname') && $this->getField('FirstName')) { |
||
1161 | return $this->getField('Surname') . ', ' . $this->getField('FirstName'); |
||
1162 | } elseif ($this->getField('Surname')) { |
||
1163 | return $this->getField('Surname'); |
||
1164 | } elseif ($this->getField('FirstName')) { |
||
1165 | return $this->getField('FirstName'); |
||
1166 | } else { |
||
1167 | return null; |
||
1168 | } |
||
1169 | } |
||
1170 | } |
||
1171 | |||
1172 | /** |
||
1173 | * Return a SQL CONCAT() fragment suitable for a SELECT statement. |
||
1174 | * Useful for custom queries which assume a certain member title format. |
||
1175 | * |
||
1176 | * @return String SQL |
||
1177 | */ |
||
1178 | public static function get_title_sql() |
||
1179 | { |
||
1180 | |||
1181 | // Get title_format with fallback to default |
||
1182 | $format = static::config()->get('title_format'); |
||
1183 | if (!$format) { |
||
1184 | $format = [ |
||
1185 | 'columns' => ['Surname', 'FirstName'], |
||
1186 | 'sep' => ' ', |
||
1187 | ]; |
||
1188 | } |
||
1189 | |||
1190 | $columnsWithTablename = array(); |
||
1191 | foreach ($format['columns'] as $column) { |
||
1192 | $columnsWithTablename[] = static::getSchema()->sqlColumnForField(__CLASS__, $column); |
||
1193 | } |
||
1194 | |||
1195 | $sepSQL = Convert::raw2sql($format['sep'], true); |
||
1196 | $op = DB::get_conn()->concatOperator(); |
||
1197 | return "(" . join(" $op $sepSQL $op ", $columnsWithTablename) . ")"; |
||
1198 | } |
||
1199 | |||
1200 | |||
1201 | /** |
||
1202 | * Get the complete name of the member |
||
1203 | * |
||
1204 | * @return string Returns the first- and surname of the member. |
||
1205 | */ |
||
1206 | public function getName() |
||
1207 | { |
||
1208 | return ($this->Surname) ? trim($this->FirstName . ' ' . $this->Surname) : $this->FirstName; |
||
1209 | } |
||
1210 | |||
1211 | |||
1212 | /** |
||
1213 | * Set first- and surname |
||
1214 | * |
||
1215 | * This method assumes that the last part of the name is the surname, e.g. |
||
1216 | * <i>A B C</i> will result in firstname <i>A B</i> and surname <i>C</i> |
||
1217 | * |
||
1218 | * @param string $name The name |
||
1219 | */ |
||
1220 | public function setName($name) |
||
1221 | { |
||
1222 | $nameParts = explode(' ', $name); |
||
1223 | $this->Surname = array_pop($nameParts); |
||
1224 | $this->FirstName = join(' ', $nameParts); |
||
1225 | } |
||
1226 | |||
1227 | |||
1228 | /** |
||
1229 | * Alias for {@link setName} |
||
1230 | * |
||
1231 | * @param string $name The name |
||
1232 | * @see setName() |
||
1233 | */ |
||
1234 | public function splitName($name) |
||
1235 | { |
||
1236 | return $this->setName($name); |
||
1237 | } |
||
1238 | |||
1239 | /** |
||
1240 | * Return the date format based on the user's chosen locale, |
||
1241 | * falling back to the default format defined by the i18n::config()->get('default_locale') config setting. |
||
1242 | * |
||
1243 | * @return string ISO date format |
||
1244 | */ |
||
1245 | public function getDateFormat() |
||
1246 | { |
||
1247 | $formatter = new IntlDateFormatter( |
||
1248 | $this->getLocale(), |
||
1249 | IntlDateFormatter::MEDIUM, |
||
1250 | IntlDateFormatter::NONE |
||
1251 | ); |
||
1252 | $format = $formatter->getPattern(); |
||
1253 | |||
1254 | $this->extend('updateDateFormat', $format); |
||
1255 | |||
1256 | return $format; |
||
1257 | } |
||
1258 | |||
1259 | /** |
||
1260 | * Get user locale, falling back to the configured default locale |
||
1261 | */ |
||
1262 | public function getLocale() |
||
1263 | { |
||
1264 | $locale = $this->getField('Locale'); |
||
1265 | if ($locale) { |
||
1266 | return $locale; |
||
1267 | } |
||
1268 | |||
1269 | return i18n::config()->get('default_locale'); |
||
1270 | } |
||
1271 | |||
1272 | /** |
||
1273 | * Return the time format based on the user's chosen locale, |
||
1274 | * falling back to the default format defined by the i18n::config()->get('default_locale') config setting. |
||
1275 | * |
||
1276 | * @return string ISO date format |
||
1277 | */ |
||
1278 | public function getTimeFormat() |
||
1279 | { |
||
1280 | $formatter = new IntlDateFormatter( |
||
1281 | $this->getLocale(), |
||
1282 | IntlDateFormatter::NONE, |
||
1283 | IntlDateFormatter::MEDIUM |
||
1284 | ); |
||
1285 | $format = $formatter->getPattern(); |
||
1286 | |||
1287 | $this->extend('updateTimeFormat', $format); |
||
1288 | |||
1289 | return $format; |
||
1290 | } |
||
1291 | |||
1292 | //---------------------------------------------------------------------// |
||
1293 | |||
1294 | |||
1295 | /** |
||
1296 | * Get a "many-to-many" map that holds for all members their group memberships, |
||
1297 | * including any parent groups where membership is implied. |
||
1298 | * Use {@link DirectGroups()} to only retrieve the group relations without inheritance. |
||
1299 | * |
||
1300 | * @todo Push all this logic into Member_GroupSet's getIterator()? |
||
1301 | * @return Member_Groupset |
||
1302 | */ |
||
1303 | public function Groups() |
||
1304 | { |
||
1305 | $groups = Member_GroupSet::create(Group::class, 'Group_Members', 'GroupID', 'MemberID'); |
||
1306 | $groups = $groups->forForeignID($this->ID); |
||
1307 | |||
1308 | $this->extend('updateGroups', $groups); |
||
1309 | |||
1310 | return $groups; |
||
1311 | } |
||
1312 | |||
1313 | /** |
||
1314 | * @return ManyManyList|UnsavedRelationList |
||
1315 | */ |
||
1316 | public function DirectGroups() |
||
1317 | { |
||
1318 | return $this->getManyManyComponents('Groups'); |
||
1319 | } |
||
1320 | |||
1321 | /** |
||
1322 | * Get a member SQLMap of members in specific groups |
||
1323 | * |
||
1324 | * If no $groups is passed, all members will be returned |
||
1325 | * |
||
1326 | * @param mixed $groups - takes a SS_List, an array or a single Group.ID |
||
1327 | * @return Map Returns an Map that returns all Member data. |
||
1328 | */ |
||
1329 | public static function map_in_groups($groups = null) |
||
1330 | { |
||
1331 | $groupIDList = array(); |
||
1332 | |||
1333 | if ($groups instanceof SS_List) { |
||
1334 | foreach ($groups as $group) { |
||
1335 | $groupIDList[] = $group->ID; |
||
1336 | } |
||
1337 | } elseif (is_array($groups)) { |
||
1338 | $groupIDList = $groups; |
||
1339 | } elseif ($groups) { |
||
1340 | $groupIDList[] = $groups; |
||
1341 | } |
||
1342 | |||
1343 | // No groups, return all Members |
||
1344 | if (!$groupIDList) { |
||
1345 | return static::get()->sort(array('Surname' => 'ASC', 'FirstName' => 'ASC'))->map(); |
||
1346 | } |
||
1347 | |||
1348 | $membersList = new ArrayList(); |
||
1349 | // This is a bit ineffective, but follow the ORM style |
||
1350 | /** @var Group $group */ |
||
1351 | foreach (Group::get()->byIDs($groupIDList) as $group) { |
||
1352 | $membersList->merge($group->Members()); |
||
1353 | } |
||
1354 | |||
1355 | $membersList->removeDuplicates('ID'); |
||
1356 | |||
1357 | return $membersList->map(); |
||
1358 | } |
||
1359 | |||
1360 | |||
1361 | /** |
||
1362 | * Get a map of all members in the groups given that have CMS permissions |
||
1363 | * |
||
1364 | * If no groups are passed, all groups with CMS permissions will be used. |
||
1365 | * |
||
1366 | * @param array $groups Groups to consider or NULL to use all groups with |
||
1367 | * CMS permissions. |
||
1368 | * @return Map Returns a map of all members in the groups given that |
||
1369 | * have CMS permissions. |
||
1370 | */ |
||
1371 | public static function mapInCMSGroups($groups = null) |
||
1372 | { |
||
1373 | // non-countable $groups will issue a warning when using count() in PHP 7.2+ |
||
1374 | if (!$groups) { |
||
1375 | $groups = []; |
||
1376 | } |
||
1377 | |||
1378 | // Check CMS module exists |
||
1379 | if (!class_exists(LeftAndMain::class)) { |
||
1380 | return ArrayList::create()->map(); |
||
1381 | } |
||
1382 | |||
1383 | if (count($groups) == 0) { |
||
1384 | $perms = array('ADMIN', 'CMS_ACCESS_AssetAdmin'); |
||
1385 | |||
1386 | if (class_exists(CMSMain::class)) { |
||
1387 | $cmsPerms = CMSMain::singleton()->providePermissions(); |
||
1388 | } else { |
||
1389 | $cmsPerms = LeftAndMain::singleton()->providePermissions(); |
||
1390 | } |
||
1391 | |||
1392 | if (!empty($cmsPerms)) { |
||
1393 | $perms = array_unique(array_merge($perms, array_keys($cmsPerms))); |
||
1394 | } |
||
1395 | |||
1396 | $permsClause = DB::placeholders($perms); |
||
1397 | /** @skipUpgrade */ |
||
1398 | $groups = Group::get() |
||
1399 | ->innerJoin("Permission", '"Permission"."GroupID" = "Group"."ID"') |
||
1400 | ->where(array( |
||
1401 | "\"Permission\".\"Code\" IN ($permsClause)" => $perms |
||
1402 | )); |
||
1403 | } |
||
1404 | |||
1405 | $groupIDList = array(); |
||
1406 | |||
1407 | if ($groups instanceof SS_List) { |
||
1408 | foreach ($groups as $group) { |
||
1409 | $groupIDList[] = $group->ID; |
||
1410 | } |
||
1411 | } elseif (is_array($groups)) { |
||
1412 | $groupIDList = $groups; |
||
1413 | } |
||
1414 | |||
1415 | /** @skipUpgrade */ |
||
1416 | $members = static::get() |
||
1417 | ->innerJoin("Group_Members", '"Group_Members"."MemberID" = "Member"."ID"') |
||
1418 | ->innerJoin("Group", '"Group"."ID" = "Group_Members"."GroupID"'); |
||
1419 | if ($groupIDList) { |
||
1420 | $groupClause = DB::placeholders($groupIDList); |
||
1421 | $members = $members->where(array( |
||
1422 | "\"Group\".\"ID\" IN ($groupClause)" => $groupIDList |
||
1423 | )); |
||
1424 | } |
||
1425 | |||
1426 | return $members->sort('"Member"."Surname", "Member"."FirstName"')->map(); |
||
1427 | } |
||
1428 | |||
1429 | |||
1430 | /** |
||
1431 | * Get the groups in which the member is NOT in |
||
1432 | * |
||
1433 | * When passed an array of groups, and a component set of groups, this |
||
1434 | * function will return the array of groups the member is NOT in. |
||
1435 | * |
||
1436 | * @param array $groupList An array of group code names. |
||
1437 | * @param array $memberGroups A component set of groups (if set to NULL, |
||
1438 | * $this->groups() will be used) |
||
1439 | * @return array Groups in which the member is NOT in. |
||
1440 | */ |
||
1441 | public function memberNotInGroups($groupList, $memberGroups = null) |
||
1442 | { |
||
1443 | if (!$memberGroups) { |
||
1444 | $memberGroups = $this->Groups(); |
||
1445 | } |
||
1446 | |||
1447 | foreach ($memberGroups as $group) { |
||
1448 | if (in_array($group->Code, $groupList)) { |
||
1449 | $index = array_search($group->Code, $groupList); |
||
1450 | unset($groupList[$index]); |
||
1451 | } |
||
1452 | } |
||
1453 | |||
1454 | return $groupList; |
||
1455 | } |
||
1456 | |||
1457 | |||
1458 | /** |
||
1459 | * Return a {@link FieldList} of fields that would appropriate for editing |
||
1460 | * this member. |
||
1461 | * |
||
1462 | * @skipUpgrade |
||
1463 | * @return FieldList Return a FieldList of fields that would appropriate for |
||
1464 | * editing this member. |
||
1465 | */ |
||
1466 | public function getCMSFields() |
||
1467 | { |
||
1468 | $this->beforeUpdateCMSFields(function (FieldList $fields) { |
||
1469 | /** @var TabSet $rootTabSet */ |
||
1470 | $rootTabSet = $fields->fieldByName("Root"); |
||
1471 | /** @var Tab $mainTab */ |
||
1472 | $mainTab = $rootTabSet->fieldByName("Main"); |
||
1473 | /** @var FieldList $mainFields */ |
||
1474 | $mainFields = $mainTab->getChildren(); |
||
1475 | |||
1476 | // Build change password field |
||
1477 | $mainFields->replaceField('Password', $this->getMemberPasswordField()); |
||
1478 | |||
1479 | $mainFields->replaceField('Locale', new DropdownField( |
||
1480 | "Locale", |
||
1481 | _t(__CLASS__ . '.INTERFACELANG', "Interface Language", 'Language of the CMS'), |
||
1482 | i18n::getSources()->getKnownLocales() |
||
1483 | )); |
||
1484 | $mainFields->removeByName(static::config()->get('hidden_fields')); |
||
1485 | |||
1486 | if (!static::config()->get('lock_out_after_incorrect_logins')) { |
||
1487 | $mainFields->removeByName('FailedLoginCount'); |
||
1488 | } |
||
1489 | |||
1490 | // Groups relation will get us into logical conflicts because |
||
1491 | // Members are displayed within group edit form in SecurityAdmin |
||
1492 | $fields->removeByName('Groups'); |
||
1493 | |||
1494 | // Members shouldn't be able to directly view/edit logged passwords |
||
1495 | $fields->removeByName('LoggedPasswords'); |
||
1496 | |||
1497 | $fields->removeByName('RememberLoginHashes'); |
||
1498 | |||
1499 | if (Permission::check('EDIT_PERMISSIONS')) { |
||
1500 | // Filter allowed groups |
||
1501 | $groups = Group::get(); |
||
1502 | $disallowedGroupIDs = $this->disallowedGroups(); |
||
1503 | if ($disallowedGroupIDs) { |
||
1504 | $groups = $groups->exclude('ID', $disallowedGroupIDs); |
||
1505 | } |
||
1506 | $groupsMap = array(); |
||
1507 | foreach ($groups as $group) { |
||
1508 | // Listboxfield values are escaped, use ASCII char instead of » |
||
1509 | $groupsMap[$group->ID] = $group->getBreadcrumbs(' > '); |
||
1510 | } |
||
1511 | asort($groupsMap); |
||
1512 | $fields->addFieldToTab( |
||
1513 | 'Root.Main', |
||
1514 | ListboxField::create('DirectGroups', Group::singleton()->i18n_plural_name()) |
||
1515 | ->setSource($groupsMap) |
||
1516 | ->setAttribute( |
||
1517 | 'data-placeholder', |
||
1518 | _t(__CLASS__ . '.ADDGROUP', 'Add group', 'Placeholder text for a dropdown') |
||
1519 | ) |
||
1520 | ); |
||
1521 | |||
1522 | |||
1523 | // Add permission field (readonly to avoid complicated group assignment logic). |
||
1524 | // This should only be available for existing records, as new records start |
||
1525 | // with no permissions until they have a group assignment anyway. |
||
1526 | if ($this->ID) { |
||
1527 | $permissionsField = new PermissionCheckboxSetField_Readonly( |
||
1528 | 'Permissions', |
||
1529 | false, |
||
1530 | Permission::class, |
||
1531 | 'GroupID', |
||
1532 | // we don't want parent relationships, they're automatically resolved in the field |
||
1533 | $this->getManyManyComponents('Groups') |
||
1534 | ); |
||
1535 | $fields->findOrMakeTab('Root.Permissions', Permission::singleton()->i18n_plural_name()); |
||
1536 | $fields->addFieldToTab('Root.Permissions', $permissionsField); |
||
1537 | } |
||
1538 | } |
||
1539 | |||
1540 | $permissionsTab = $rootTabSet->fieldByName('Permissions'); |
||
1541 | if ($permissionsTab) { |
||
1542 | $permissionsTab->addExtraClass('readonly'); |
||
1543 | } |
||
1544 | }); |
||
1545 | |||
1546 | return parent::getCMSFields(); |
||
1547 | } |
||
1548 | |||
1549 | /** |
||
1550 | * @param bool $includerelations Indicate if the labels returned include relation fields |
||
1551 | * @return array |
||
1552 | */ |
||
1553 | public function fieldLabels($includerelations = true) |
||
1554 | { |
||
1555 | $labels = parent::fieldLabels($includerelations); |
||
1556 | |||
1557 | $labels['FirstName'] = _t(__CLASS__ . '.FIRSTNAME', 'First Name'); |
||
1558 | $labels['Surname'] = _t(__CLASS__ . '.SURNAME', 'Surname'); |
||
1559 | /** @skipUpgrade */ |
||
1560 | $labels['Email'] = _t(__CLASS__ . '.EMAIL', 'Email'); |
||
1561 | $labels['Password'] = _t(__CLASS__ . '.db_Password', 'Password'); |
||
1562 | $labels['PasswordExpiry'] = _t( |
||
1563 | __CLASS__ . '.db_PasswordExpiry', |
||
1564 | 'Password Expiry Date', |
||
1565 | 'Password expiry date' |
||
1566 | ); |
||
1567 | $labels['LockedOutUntil'] = _t(__CLASS__ . '.db_LockedOutUntil', 'Locked out until', 'Security related date'); |
||
1568 | $labels['Locale'] = _t(__CLASS__ . '.db_Locale', 'Interface Locale'); |
||
1569 | if ($includerelations) { |
||
1570 | $labels['Groups'] = _t( |
||
1571 | __CLASS__ . '.belongs_many_many_Groups', |
||
1572 | 'Groups', |
||
1573 | 'Security Groups this member belongs to' |
||
1574 | ); |
||
1575 | } |
||
1576 | |||
1577 | return $labels; |
||
1578 | } |
||
1579 | |||
1580 | /** |
||
1581 | * Users can view their own record. |
||
1582 | * Otherwise they'll need ADMIN or CMS_ACCESS_SecurityAdmin permissions. |
||
1583 | * This is likely to be customized for social sites etc. with a looser permission model. |
||
1584 | * |
||
1585 | * @param Member $member |
||
1586 | * @return bool |
||
1587 | */ |
||
1588 | public function canView($member = null) |
||
1589 | { |
||
1590 | //get member |
||
1591 | if (!$member) { |
||
1592 | $member = Security::getCurrentUser(); |
||
1593 | } |
||
1594 | //check for extensions, we do this first as they can overrule everything |
||
1595 | $extended = $this->extendedCan(__FUNCTION__, $member); |
||
1596 | if ($extended !== null) { |
||
1597 | return $extended; |
||
1598 | } |
||
1599 | |||
1600 | //need to be logged in and/or most checks below rely on $member being a Member |
||
1601 | if (!$member) { |
||
1602 | return false; |
||
1603 | } |
||
1604 | // members can usually view their own record |
||
1605 | if ($this->ID == $member->ID) { |
||
1606 | return true; |
||
1607 | } |
||
1608 | |||
1609 | //standard check |
||
1610 | return Permission::checkMember($member, 'CMS_ACCESS_SecurityAdmin'); |
||
1611 | } |
||
1612 | |||
1613 | /** |
||
1614 | * Users can edit their own record. |
||
1615 | * Otherwise they'll need ADMIN or CMS_ACCESS_SecurityAdmin permissions |
||
1616 | * |
||
1617 | * @param Member $member |
||
1618 | * @return bool |
||
1619 | */ |
||
1620 | public function canEdit($member = null) |
||
1621 | { |
||
1622 | //get member |
||
1623 | if (!$member) { |
||
1624 | $member = Security::getCurrentUser(); |
||
1625 | } |
||
1626 | //check for extensions, we do this first as they can overrule everything |
||
1627 | $extended = $this->extendedCan(__FUNCTION__, $member); |
||
1628 | if ($extended !== null) { |
||
1629 | return $extended; |
||
1630 | } |
||
1631 | |||
1632 | //need to be logged in and/or most checks below rely on $member being a Member |
||
1633 | if (!$member) { |
||
1634 | return false; |
||
1635 | } |
||
1636 | |||
1637 | // HACK: we should not allow for an non-Admin to edit an Admin |
||
1638 | if (!Permission::checkMember($member, 'ADMIN') && Permission::checkMember($this, 'ADMIN')) { |
||
1639 | return false; |
||
1640 | } |
||
1641 | // members can usually edit their own record |
||
1642 | if ($this->ID == $member->ID) { |
||
1643 | return true; |
||
1644 | } |
||
1645 | |||
1646 | //standard check |
||
1647 | return Permission::checkMember($member, 'CMS_ACCESS_SecurityAdmin'); |
||
1648 | } |
||
1649 | |||
1650 | /** |
||
1651 | * Users can edit their own record. |
||
1652 | * Otherwise they'll need ADMIN or CMS_ACCESS_SecurityAdmin permissions |
||
1653 | * |
||
1654 | * @param Member $member |
||
1655 | * @return bool |
||
1656 | */ |
||
1657 | public function canDelete($member = null) |
||
1658 | { |
||
1659 | if (!$member) { |
||
1660 | $member = Security::getCurrentUser(); |
||
1661 | } |
||
1662 | //check for extensions, we do this first as they can overrule everything |
||
1663 | $extended = $this->extendedCan(__FUNCTION__, $member); |
||
1664 | if ($extended !== null) { |
||
1665 | return $extended; |
||
1666 | } |
||
1667 | |||
1668 | //need to be logged in and/or most checks below rely on $member being a Member |
||
1669 | if (!$member) { |
||
1670 | return false; |
||
1671 | } |
||
1672 | // Members are not allowed to remove themselves, |
||
1673 | // since it would create inconsistencies in the admin UIs. |
||
1674 | if ($this->ID && $member->ID == $this->ID) { |
||
1675 | return false; |
||
1676 | } |
||
1677 | |||
1678 | // HACK: if you want to delete a member, you have to be a member yourself. |
||
1679 | // this is a hack because what this should do is to stop a user |
||
1680 | // deleting a member who has more privileges (e.g. a non-Admin deleting an Admin) |
||
1681 | if (Permission::checkMember($this, 'ADMIN')) { |
||
1682 | if (!Permission::checkMember($member, 'ADMIN')) { |
||
1683 | return false; |
||
1684 | } |
||
1685 | } |
||
1686 | |||
1687 | //standard check |
||
1688 | return Permission::checkMember($member, 'CMS_ACCESS_SecurityAdmin'); |
||
1689 | } |
||
1690 | |||
1691 | /** |
||
1692 | * Validate this member object. |
||
1693 | */ |
||
1694 | public function validate() |
||
1695 | { |
||
1696 | // If validation is disabled, skip this step |
||
1697 | if (!DataObject::config()->uninherited('validation_enabled')) { |
||
1698 | return ValidationResult::create(); |
||
1699 | } |
||
1700 | |||
1701 | $valid = parent::validate(); |
||
1702 | $validator = static::password_validator(); |
||
1703 | |||
1704 | if (!$this->ID || $this->isChanged('Password')) { |
||
1705 | if ($this->Password && $validator) { |
||
1706 | $userValid = $validator->validate($this->Password, $this); |
||
1707 | $valid->combineAnd($userValid); |
||
1708 | } |
||
1709 | } |
||
1710 | |||
1711 | return $valid; |
||
1712 | } |
||
1713 | |||
1714 | /** |
||
1715 | * Change password. This will cause rehashing according to the `PasswordEncryption` property via the |
||
1716 | * `onBeforeWrite()` method. This method will allow extensions to perform actions and augment the validation |
||
1717 | * result if required before the password is written and can check it after the write also. |
||
1718 | * |
||
1719 | * `onBeforeWrite()` will encrypt the password prior to writing. |
||
1720 | * |
||
1721 | * @param string $password Cleartext password |
||
1722 | * @param bool $write Whether to write the member afterwards |
||
1723 | * @return ValidationResult |
||
1724 | */ |
||
1725 | public function changePassword($password, $write = true) |
||
1726 | { |
||
1727 | $this->Password = $password; |
||
1728 | $result = $this->validate(); |
||
1729 | |||
1730 | $this->extend('onBeforeChangePassword', $password, $result); |
||
1731 | |||
1732 | if ($result->isValid()) { |
||
1733 | $this->AutoLoginHash = null; |
||
1734 | |||
1735 | if ($write) { |
||
1736 | $this->write(); |
||
1737 | } |
||
1738 | } |
||
1739 | |||
1740 | $this->extend('onAfterChangePassword', $password, $result); |
||
1741 | |||
1742 | return $result; |
||
1743 | } |
||
1744 | |||
1745 | /** |
||
1746 | * Takes a plaintext password (on the Member object) and encrypts it |
||
1747 | * |
||
1748 | * @return $this |
||
1749 | */ |
||
1750 | protected function encryptPassword() |
||
1751 | { |
||
1752 | // reset salt so that it gets regenerated - this will invalidate any persistent login cookies |
||
1753 | // or other information encrypted with this Member's settings (see self::encryptWithUserSettings) |
||
1754 | $this->Salt = ''; |
||
1755 | |||
1756 | // Password was changed: encrypt the password according the settings |
||
1757 | $encryption_details = Security::encrypt_password( |
||
1758 | $this->Password, |
||
1759 | $this->Salt, |
||
1760 | $this->isChanged('PasswordEncryption') ? $this->PasswordEncryption : null, |
||
1761 | $this |
||
1762 | ); |
||
1763 | |||
1764 | // Overwrite the Password property with the hashed value |
||
1765 | $this->Password = $encryption_details['password']; |
||
1766 | $this->Salt = $encryption_details['salt']; |
||
1767 | $this->PasswordEncryption = $encryption_details['algorithm']; |
||
1768 | |||
1769 | // If we haven't manually set a password expiry |
||
1770 | if (!$this->isChanged('PasswordExpiry')) { |
||
1771 | // then set it for us |
||
1772 | if (static::config()->get('password_expiry_days')) { |
||
1773 | $this->PasswordExpiry = date('Y-m-d', time() + 86400 * static::config()->get('password_expiry_days')); |
||
1774 | } else { |
||
1775 | $this->PasswordExpiry = null; |
||
1776 | } |
||
1777 | } |
||
1778 | |||
1779 | return $this; |
||
1780 | } |
||
1781 | |||
1782 | /** |
||
1783 | * Tell this member that someone made a failed attempt at logging in as them. |
||
1784 | * This can be used to lock the user out temporarily if too many failed attempts are made. |
||
1785 | */ |
||
1786 | public function registerFailedLogin() |
||
1787 | { |
||
1788 | $lockOutAfterCount = self::config()->get('lock_out_after_incorrect_logins'); |
||
1789 | if ($lockOutAfterCount) { |
||
1790 | // Keep a tally of the number of failed log-ins so that we can lock people out |
||
1791 | ++$this->FailedLoginCount; |
||
1792 | |||
1793 | if ($this->FailedLoginCount >= $lockOutAfterCount) { |
||
1794 | $lockoutMins = self::config()->get('lock_out_delay_mins'); |
||
1795 | $this->LockedOutUntil = date('Y-m-d H:i:s', DBDatetime::now()->getTimestamp() + $lockoutMins * 60); |
||
1796 | $this->FailedLoginCount = 0; |
||
1797 | } |
||
1798 | } |
||
1799 | $this->extend('registerFailedLogin'); |
||
1800 | $this->write(); |
||
1801 | } |
||
1802 | |||
1803 | /** |
||
1804 | * Tell this member that a successful login has been made |
||
1805 | */ |
||
1806 | public function registerSuccessfulLogin() |
||
1807 | { |
||
1808 | if (self::config()->get('lock_out_after_incorrect_logins')) { |
||
1809 | // Forgive all past login failures |
||
1810 | $this->FailedLoginCount = 0; |
||
1811 | $this->LockedOutUntil = null; |
||
1812 | $this->write(); |
||
1813 | } |
||
1814 | } |
||
1815 | |||
1816 | /** |
||
1817 | * Get the HtmlEditorConfig for this user to be used in the CMS. |
||
1818 | * This is set by the group. If multiple configurations are set, |
||
1819 | * the one with the highest priority wins. |
||
1820 | * |
||
1821 | * @return string |
||
1822 | */ |
||
1823 | public function getHtmlEditorConfigForCMS() |
||
1841 | } |
||
1842 | } |
||
1843 |
The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g.
excluded_paths: ["lib/*"]
, you can move it to the dependency path list as follows:For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths