Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
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 |
||
58 | class Member extends DataObject |
||
59 | { |
||
60 | |||
61 | private static $db = array( |
||
|
|||
62 | 'FirstName' => 'Varchar', |
||
63 | 'Surname' => 'Varchar', |
||
64 | 'Email' => 'Varchar(254)', // See RFC 5321, Section 4.5.3.1.3. (256 minus the < and > character) |
||
65 | 'TempIDHash' => 'Varchar(160)', // Temporary id used for cms re-authentication |
||
66 | 'TempIDExpired' => 'Datetime', // Expiry of temp login |
||
67 | 'Password' => 'Varchar(160)', |
||
68 | 'AutoLoginHash' => 'Varchar(160)', // Used to auto-login the user on password reset |
||
69 | 'AutoLoginExpired' => 'Datetime', |
||
70 | // This is an arbitrary code pointing to a PasswordEncryptor instance, |
||
71 | // not an actual encryption algorithm. |
||
72 | // Warning: Never change this field after its the first password hashing without |
||
73 | // providing a new cleartext password as well. |
||
74 | 'PasswordEncryption' => "Varchar(50)", |
||
75 | 'Salt' => 'Varchar(50)', |
||
76 | 'PasswordExpiry' => 'Date', |
||
77 | 'LockedOutUntil' => 'Datetime', |
||
78 | 'Locale' => 'Varchar(6)', |
||
79 | // handled in registerFailedLogin(), only used if $lock_out_after_incorrect_logins is set |
||
80 | 'FailedLoginCount' => 'Int', |
||
81 | ); |
||
82 | |||
83 | private static $belongs_many_many = array( |
||
84 | 'Groups' => Group::class, |
||
85 | ); |
||
86 | |||
87 | private static $has_many = array( |
||
88 | 'LoggedPasswords' => MemberPassword::class, |
||
89 | 'RememberLoginHashes' => RememberLoginHash::class, |
||
90 | ); |
||
91 | |||
92 | private static $table_name = "Member"; |
||
93 | |||
94 | private static $default_sort = '"Surname", "FirstName"'; |
||
95 | |||
96 | private static $indexes = array( |
||
97 | 'Email' => true, |
||
98 | //Removed due to duplicate null values causing MSSQL problems |
||
99 | //'AutoLoginHash' => Array('type'=>'unique', 'value'=>'AutoLoginHash', 'ignoreNulls'=>true) |
||
100 | ); |
||
101 | |||
102 | /** |
||
103 | * @config |
||
104 | * @var boolean |
||
105 | */ |
||
106 | private static $notify_password_change = false; |
||
107 | |||
108 | /** |
||
109 | * All searchable database columns |
||
110 | * in this object, currently queried |
||
111 | * with a "column LIKE '%keywords%' |
||
112 | * statement. |
||
113 | * |
||
114 | * @var array |
||
115 | * @todo Generic implementation of $searchable_fields on DataObject, |
||
116 | * with definition for different searching algorithms |
||
117 | * (LIKE, FULLTEXT) and default FormFields to construct a searchform. |
||
118 | */ |
||
119 | private static $searchable_fields = array( |
||
120 | 'FirstName', |
||
121 | 'Surname', |
||
122 | 'Email', |
||
123 | ); |
||
124 | |||
125 | /** |
||
126 | * @config |
||
127 | * @var array |
||
128 | */ |
||
129 | private static $summary_fields = array( |
||
130 | 'FirstName', |
||
131 | 'Surname', |
||
132 | 'Email', |
||
133 | ); |
||
134 | |||
135 | /** |
||
136 | * @config |
||
137 | * @var array |
||
138 | */ |
||
139 | private static $casting = array( |
||
140 | 'Name' => 'Varchar', |
||
141 | ); |
||
142 | |||
143 | /** |
||
144 | * Internal-use only fields |
||
145 | * |
||
146 | * @config |
||
147 | * @var array |
||
148 | */ |
||
149 | private static $hidden_fields = array( |
||
150 | 'AutoLoginHash', |
||
151 | 'AutoLoginExpired', |
||
152 | 'PasswordEncryption', |
||
153 | 'PasswordExpiry', |
||
154 | 'LockedOutUntil', |
||
155 | 'TempIDHash', |
||
156 | 'TempIDExpired', |
||
157 | 'Salt', |
||
158 | ); |
||
159 | |||
160 | /** |
||
161 | * @config |
||
162 | * @var array See {@link set_title_columns()} |
||
163 | */ |
||
164 | private static $title_format = null; |
||
165 | |||
166 | /** |
||
167 | * The unique field used to identify this member. |
||
168 | * By default, it's "Email", but another common |
||
169 | * field could be Username. |
||
170 | * |
||
171 | * @config |
||
172 | * @var string |
||
173 | * @skipUpgrade |
||
174 | */ |
||
175 | private static $unique_identifier_field = 'Email'; |
||
176 | |||
177 | /** |
||
178 | * Object for validating user's password |
||
179 | * |
||
180 | * @config |
||
181 | * @var PasswordValidator |
||
182 | */ |
||
183 | private static $password_validator = null; |
||
184 | |||
185 | /** |
||
186 | * @config |
||
187 | * The number of days that a password should be valid for. |
||
188 | * By default, this is null, which means that passwords never expire |
||
189 | */ |
||
190 | private static $password_expiry_days = null; |
||
191 | |||
192 | /** |
||
193 | * @config |
||
194 | * @var bool enable or disable logging of previously used passwords. See {@link onAfterWrite} |
||
195 | */ |
||
196 | private static $password_logging_enabled = true; |
||
197 | |||
198 | /** |
||
199 | * @config |
||
200 | * @var Int Number of incorrect logins after which |
||
201 | * the user is blocked from further attempts for the timespan |
||
202 | * defined in {@link $lock_out_delay_mins}. |
||
203 | */ |
||
204 | private static $lock_out_after_incorrect_logins = 10; |
||
205 | |||
206 | /** |
||
207 | * @config |
||
208 | * @var integer Minutes of enforced lockout after incorrect password attempts. |
||
209 | * Only applies if {@link $lock_out_after_incorrect_logins} greater than 0. |
||
210 | */ |
||
211 | private static $lock_out_delay_mins = 15; |
||
212 | |||
213 | /** |
||
214 | * @config |
||
215 | * @var String If this is set, then a session cookie with the given name will be set on log-in, |
||
216 | * and cleared on logout. |
||
217 | */ |
||
218 | private static $login_marker_cookie = null; |
||
219 | |||
220 | /** |
||
221 | * Indicates that when a {@link Member} logs in, Member:session_regenerate_id() |
||
222 | * should be called as a security precaution. |
||
223 | * |
||
224 | * This doesn't always work, especially if you're trying to set session cookies |
||
225 | * across an entire site using the domain parameter to session_set_cookie_params() |
||
226 | * |
||
227 | * @config |
||
228 | * @var boolean |
||
229 | */ |
||
230 | private static $session_regenerate_id = true; |
||
231 | |||
232 | |||
233 | /** |
||
234 | * Default lifetime of temporary ids. |
||
235 | * |
||
236 | * This is the period within which a user can be re-authenticated within the CMS by entering only their password |
||
237 | * and without losing their workspace. |
||
238 | * |
||
239 | * Any session expiration outside of this time will require them to login from the frontend using their full |
||
240 | * username and password. |
||
241 | * |
||
242 | * Defaults to 72 hours. Set to zero to disable expiration. |
||
243 | * |
||
244 | * @config |
||
245 | * @var int Lifetime in seconds |
||
246 | */ |
||
247 | private static $temp_id_lifetime = 259200; |
||
248 | |||
249 | /** |
||
250 | * Ensure the locale is set to something sensible by default. |
||
251 | */ |
||
252 | public function populateDefaults() |
||
257 | |||
258 | public function requireDefaultRecords() |
||
264 | |||
265 | /** |
||
266 | * Get the default admin record if it exists, or creates it otherwise if enabled |
||
267 | * |
||
268 | * @return Member |
||
269 | */ |
||
270 | public static function default_admin() |
||
307 | |||
308 | /** |
||
309 | * Check if the passed password matches the stored one (if the member is not locked out). |
||
310 | * |
||
311 | * @param string $password |
||
312 | * @return ValidationResult |
||
313 | */ |
||
314 | public function checkPassword($password) |
||
345 | |||
346 | /** |
||
347 | * Check if this user is the currently configured default admin |
||
348 | * |
||
349 | * @return bool |
||
350 | */ |
||
351 | public function isDefaultAdmin() |
||
356 | |||
357 | /** |
||
358 | * Returns a valid {@link ValidationResult} if this member can currently log in, or an invalid |
||
359 | * one with error messages to display if the member is locked out. |
||
360 | * |
||
361 | * You can hook into this with a "canLogIn" method on an attached extension. |
||
362 | * |
||
363 | * @return ValidationResult |
||
364 | */ |
||
365 | public function canLogIn() |
||
385 | |||
386 | /** |
||
387 | * Returns true if this user is locked out |
||
388 | * |
||
389 | * @return bool |
||
390 | */ |
||
391 | public function isLockedOut() |
||
399 | |||
400 | /** |
||
401 | * Set a {@link PasswordValidator} object to use to validate member's passwords. |
||
402 | * |
||
403 | * @param PasswordValidator $pv |
||
404 | */ |
||
405 | public static function set_password_validator($pv) |
||
409 | |||
410 | /** |
||
411 | * Returns the current {@link PasswordValidator} |
||
412 | * |
||
413 | * @return PasswordValidator |
||
414 | */ |
||
415 | public static function password_validator() |
||
419 | |||
420 | |||
421 | public function isPasswordExpired() |
||
429 | |||
430 | /** |
||
431 | * @deprecated 5.0.0 Use Security::setCurrentUser() or IdentityStore::logIn() |
||
432 | * |
||
433 | */ |
||
434 | public function logIn() |
||
442 | |||
443 | /** |
||
444 | * Called before a member is logged in via session/cookie/etc |
||
445 | */ |
||
446 | public function beforeMemberLoggedIn() |
||
451 | |||
452 | /** |
||
453 | * Called after a member is logged in via session/cookie/etc |
||
454 | */ |
||
455 | public function afterMemberLoggedIn() |
||
469 | |||
470 | /** |
||
471 | * Trigger regeneration of TempID. |
||
472 | * |
||
473 | * This should be performed any time the user presents their normal identification (normally Email) |
||
474 | * and is successfully authenticated. |
||
475 | */ |
||
476 | public function regenerateTempID() |
||
477 | { |
||
478 | $generator = new RandomGenerator(); |
||
479 | $lifetime = self::config()->get('temp_id_lifetime'); |
||
480 | $this->TempIDHash = $generator->randomToken('sha1'); |
||
481 | $this->TempIDExpired = $lifetime |
||
482 | ? date('Y-m-d H:i:s', strtotime(DBDatetime::now()->getValue()) + $lifetime) |
||
483 | : null; |
||
484 | $this->write(); |
||
485 | } |
||
486 | |||
487 | /** |
||
488 | * Check if the member ID logged in session actually |
||
489 | * has a database record of the same ID. If there is |
||
490 | * no logged in user, FALSE is returned anyway. |
||
491 | * |
||
492 | * @deprecated Not needed anymore, as it returns Security::getCurrentUser(); |
||
493 | * |
||
494 | * @return boolean TRUE record found FALSE no record found |
||
495 | */ |
||
496 | public static function logged_in_session_exists() |
||
497 | { |
||
498 | Deprecation::notice( |
||
499 | '5.0.0', |
||
500 | 'This method is deprecated and now does not add value. Please use Security::getCurrentUser()' |
||
501 | ); |
||
502 | |||
503 | if ($member = Security::getCurrentUser()) { |
||
504 | if ($member && $member->exists()) { |
||
505 | return true; |
||
506 | } |
||
507 | } |
||
508 | |||
509 | return false; |
||
510 | } |
||
511 | |||
512 | /** |
||
513 | * @deprecated Use Security::setCurrentUser(null) or an IdentityStore |
||
514 | * Logs this member out. |
||
515 | */ |
||
516 | public function logOut() |
||
517 | { |
||
518 | Deprecation::notice( |
||
519 | '5.0.0', |
||
520 | 'This method is deprecated and now does not persist. Please use Security::setCurrentUser(null) or an IdenityStore' |
||
521 | ); |
||
522 | |||
523 | $this->extend('beforeMemberLoggedOut'); |
||
524 | |||
525 | Injector::inst()->get(IdentityStore::class)->logOut(Controller::curr()->getRequest()); |
||
526 | // Audit logging hook |
||
527 | $this->extend('afterMemberLoggedOut'); |
||
528 | } |
||
529 | |||
530 | /** |
||
531 | * Utility for generating secure password hashes for this member. |
||
532 | * |
||
533 | * @param string $string |
||
534 | * @return string |
||
535 | * @throws PasswordEncryptor_NotFoundException |
||
536 | */ |
||
537 | public function encryptWithUserSettings($string) |
||
538 | { |
||
539 | if (!$string) { |
||
540 | return null; |
||
541 | } |
||
542 | |||
543 | // If the algorithm or salt is not available, it means we are operating |
||
544 | // on legacy account with unhashed password. Do not hash the string. |
||
545 | if (!$this->PasswordEncryption) { |
||
546 | return $string; |
||
547 | } |
||
548 | |||
549 | // We assume we have PasswordEncryption and Salt available here. |
||
550 | $e = PasswordEncryptor::create_for_algorithm($this->PasswordEncryption); |
||
551 | |||
552 | return $e->encrypt($string, $this->Salt); |
||
553 | } |
||
554 | |||
555 | /** |
||
556 | * Generate an auto login token which can be used to reset the password, |
||
557 | * at the same time hashing it and storing in the database. |
||
558 | * |
||
559 | * @param int $lifetime The lifetime of the auto login hash in days (by default 2 days) |
||
560 | * |
||
561 | * @returns string Token that should be passed to the client (but NOT persisted). |
||
562 | * |
||
563 | * @todo Make it possible to handle database errors such as a "duplicate key" error |
||
564 | */ |
||
565 | public function generateAutologinTokenAndStoreHash($lifetime = 2) |
||
566 | { |
||
567 | do { |
||
568 | $generator = new RandomGenerator(); |
||
569 | $token = $generator->randomToken(); |
||
570 | $hash = $this->encryptWithUserSettings($token); |
||
571 | } while (DataObject::get_one(Member::class, array( |
||
572 | '"Member"."AutoLoginHash"' => $hash |
||
573 | ))); |
||
574 | |||
575 | $this->AutoLoginHash = $hash; |
||
576 | $this->AutoLoginExpired = date('Y-m-d H:i:s', time() + (86400 * $lifetime)); |
||
577 | |||
578 | $this->write(); |
||
579 | |||
580 | return $token; |
||
581 | } |
||
582 | |||
583 | /** |
||
584 | * Check the token against the member. |
||
585 | * |
||
586 | * @param string $autologinToken |
||
587 | * |
||
588 | * @returns bool Is token valid? |
||
589 | */ |
||
590 | public function validateAutoLoginToken($autologinToken) |
||
591 | { |
||
592 | $hash = $this->encryptWithUserSettings($autologinToken); |
||
593 | $member = self::member_from_autologinhash($hash, false); |
||
594 | |||
595 | return (bool)$member; |
||
596 | } |
||
597 | |||
598 | /** |
||
599 | * Return the member for the auto login hash |
||
600 | * |
||
601 | * @param string $hash The hash key |
||
602 | * @param bool $login Should the member be logged in? |
||
603 | * |
||
604 | * @return Member the matching member, if valid |
||
605 | * @return Member |
||
606 | */ |
||
607 | public static function member_from_autologinhash($hash, $login = false) |
||
608 | { |
||
609 | /** @var Member $member */ |
||
610 | $member = static::get()->filter([ |
||
611 | 'AutoLoginHash' => $hash, |
||
612 | 'AutoLoginExpired:GreaterThan' => DBDatetime::now()->getValue(), |
||
613 | ])->first(); |
||
614 | |||
615 | if ($login && $member) { |
||
616 | Injector::inst()->get(IdentityStore::class)->logIn($member); |
||
617 | } |
||
618 | |||
619 | return $member; |
||
620 | } |
||
621 | |||
622 | /** |
||
623 | * Find a member record with the given TempIDHash value |
||
624 | * |
||
625 | * @param string $tempid |
||
626 | * @return Member |
||
627 | */ |
||
628 | public static function member_from_tempid($tempid) |
||
629 | { |
||
630 | $members = static::get() |
||
631 | ->filter('TempIDHash', $tempid); |
||
632 | |||
633 | // Exclude expired |
||
634 | if (static::config()->get('temp_id_lifetime')) { |
||
635 | /** @var DataList|Member[] $members */ |
||
636 | $members = $members->filter('TempIDExpired:GreaterThan', DBDatetime::now()->getValue()); |
||
637 | } |
||
638 | |||
639 | return $members->first(); |
||
640 | } |
||
641 | |||
642 | /** |
||
643 | * Returns the fields for the member form - used in the registration/profile module. |
||
644 | * It should return fields that are editable by the admin and the logged-in user. |
||
645 | * |
||
646 | * @todo possibly move this to an extension |
||
647 | * |
||
648 | * @return FieldList Returns a {@link FieldList} containing the fields for |
||
649 | * the member form. |
||
650 | */ |
||
651 | public function getMemberFormFields() |
||
652 | { |
||
653 | $fields = parent::getFrontEndFields(); |
||
654 | |||
655 | $fields->replaceField('Password', $this->getMemberPasswordField()); |
||
656 | |||
657 | $fields->replaceField('Locale', new DropdownField( |
||
658 | 'Locale', |
||
659 | $this->fieldLabel('Locale'), |
||
660 | i18n::getSources()->getKnownLocales() |
||
661 | )); |
||
662 | |||
663 | $fields->removeByName(static::config()->get('hidden_fields')); |
||
664 | $fields->removeByName('FailedLoginCount'); |
||
665 | |||
666 | |||
667 | $this->extend('updateMemberFormFields', $fields); |
||
668 | |||
669 | return $fields; |
||
670 | } |
||
671 | |||
672 | /** |
||
673 | * Builds "Change / Create Password" field for this member |
||
674 | * |
||
675 | * @return ConfirmedPasswordField |
||
676 | */ |
||
677 | public function getMemberPasswordField() |
||
678 | { |
||
679 | $editingPassword = $this->isInDB(); |
||
680 | $label = $editingPassword |
||
681 | ? _t(__CLASS__ . '.EDIT_PASSWORD', 'New Password') |
||
682 | : $this->fieldLabel('Password'); |
||
683 | /** @var ConfirmedPasswordField $password */ |
||
684 | $password = ConfirmedPasswordField::create( |
||
685 | 'Password', |
||
686 | $label, |
||
687 | null, |
||
688 | null, |
||
689 | $editingPassword |
||
690 | ); |
||
691 | |||
692 | // If editing own password, require confirmation of existing |
||
693 | if ($editingPassword && $this->ID == Security::getCurrentUser()->ID) { |
||
694 | $password->setRequireExistingPassword(true); |
||
695 | } |
||
696 | |||
697 | $password->setCanBeEmpty(true); |
||
698 | $this->extend('updateMemberPasswordField', $password); |
||
699 | |||
700 | return $password; |
||
701 | } |
||
702 | |||
703 | |||
704 | /** |
||
705 | * Returns the {@link RequiredFields} instance for the Member object. This |
||
706 | * Validator is used when saving a {@link CMSProfileController} or added to |
||
707 | * any form responsible for saving a users data. |
||
708 | * |
||
709 | * To customize the required fields, add a {@link DataExtension} to member |
||
710 | * calling the `updateValidator()` method. |
||
711 | * |
||
712 | * @return Member_Validator |
||
713 | */ |
||
714 | public function getValidator() |
||
715 | { |
||
716 | $validator = Member_Validator::create(); |
||
717 | $validator->setForMember($this); |
||
718 | $this->extend('updateValidator', $validator); |
||
719 | |||
720 | return $validator; |
||
721 | } |
||
722 | |||
723 | |||
724 | /** |
||
725 | * Returns the current logged in user |
||
726 | * |
||
727 | * @deprecated 5.0.0 use Security::getCurrentUser() |
||
728 | * |
||
729 | * @return Member |
||
730 | */ |
||
731 | public static function currentUser() |
||
732 | { |
||
733 | Deprecation::notice( |
||
734 | '5.0.0', |
||
735 | 'This method is deprecated. Please use Security::getCurrentUser() or an IdentityStore' |
||
736 | ); |
||
737 | |||
738 | return Security::getCurrentUser(); |
||
739 | } |
||
740 | |||
741 | /** |
||
742 | * Temporarily act as the specified user, limited to a $callback, but |
||
743 | * without logging in as that user. |
||
744 | * |
||
745 | * E.g. |
||
746 | * <code> |
||
747 | * Member::logInAs(Security::findAnAdministrator(), function() { |
||
748 | * $record->write(); |
||
749 | * }); |
||
750 | * </code> |
||
751 | * |
||
752 | * @param Member|null|int $member Member or member ID to log in as. |
||
753 | * Set to null or 0 to act as a logged out user. |
||
754 | * @param callable $callback |
||
755 | */ |
||
756 | public static function actAs($member, $callback) |
||
757 | { |
||
758 | $previousUser = Security::getCurrentUser(); |
||
759 | |||
760 | // Transform ID to member |
||
761 | if (is_numeric($member)) { |
||
762 | $member = DataObject::get_by_id(Member::class, $member); |
||
763 | } |
||
764 | Security::setCurrentUser($member); |
||
765 | |||
766 | try { |
||
767 | return $callback(); |
||
768 | } finally { |
||
769 | Security::setCurrentUser($previousUser); |
||
770 | } |
||
771 | } |
||
772 | |||
773 | /** |
||
774 | * Get the ID of the current logged in user |
||
775 | * |
||
776 | * @deprecated 5.0.0 use Security::getCurrentUser() |
||
777 | * |
||
778 | * @return int Returns the ID of the current logged in user or 0. |
||
779 | */ |
||
780 | public static function currentUserID() |
||
781 | { |
||
782 | Deprecation::notice( |
||
783 | '5.0.0', |
||
784 | 'This method is deprecated. Please use Security::getCurrentUser() or an IdentityStore' |
||
785 | ); |
||
786 | |||
787 | if ($member = Security::getCurrentUser()) { |
||
788 | return $member->ID; |
||
789 | } else { |
||
790 | return 0; |
||
791 | } |
||
792 | } |
||
793 | |||
794 | /** |
||
795 | * Generate a random password, with randomiser to kick in if there's no words file on the |
||
796 | * filesystem. |
||
797 | * |
||
798 | * @return string Returns a random password. |
||
799 | */ |
||
800 | public static function create_new_password() |
||
801 | { |
||
802 | $words = Security::config()->uninherited('word_list'); |
||
803 | |||
804 | if ($words && file_exists($words)) { |
||
805 | $words = file($words); |
||
806 | |||
807 | list($usec, $sec) = explode(' ', microtime()); |
||
808 | mt_srand($sec + ((float)$usec * 100000)); |
||
809 | |||
810 | $word = trim($words[random_int(0, count($words) - 1)]); |
||
811 | $number = random_int(10, 999); |
||
812 | |||
813 | return $word . $number; |
||
814 | } else { |
||
815 | $random = mt_rand(); |
||
816 | $string = md5($random); |
||
817 | $output = substr($string, 0, 8); |
||
818 | |||
819 | return $output; |
||
820 | } |
||
821 | } |
||
822 | |||
823 | /** |
||
824 | * Event handler called before writing to the database. |
||
825 | */ |
||
826 | public function onBeforeWrite() |
||
827 | { |
||
828 | if ($this->SetPassword) { |
||
829 | $this->Password = $this->SetPassword; |
||
830 | } |
||
831 | |||
832 | // If a member with the same "unique identifier" already exists with a different ID, don't allow merging. |
||
833 | // Note: This does not a full replacement for safeguards in the controller layer (e.g. in a registration form), |
||
834 | // but rather a last line of defense against data inconsistencies. |
||
835 | $identifierField = Member::config()->get('unique_identifier_field'); |
||
836 | if ($this->$identifierField) { |
||
837 | // Note: Same logic as Member_Validator class |
||
838 | $filter = [ |
||
839 | "\"Member\".\"$identifierField\"" => $this->$identifierField |
||
840 | ]; |
||
841 | if ($this->ID) { |
||
842 | $filter[] = array('"Member"."ID" <> ?' => $this->ID); |
||
843 | } |
||
844 | $existingRecord = DataObject::get_one(Member::class, $filter); |
||
845 | |||
846 | if ($existingRecord) { |
||
847 | throw new ValidationException(_t( |
||
848 | __CLASS__ . '.ValidationIdentifierFailed', |
||
849 | 'Can\'t overwrite existing member #{id} with identical identifier ({name} = {value}))', |
||
850 | 'Values in brackets show "fieldname = value", usually denoting an existing email address', |
||
851 | array( |
||
852 | 'id' => $existingRecord->ID, |
||
853 | 'name' => $identifierField, |
||
854 | 'value' => $this->$identifierField |
||
855 | ) |
||
856 | )); |
||
857 | } |
||
858 | } |
||
859 | |||
860 | // We don't send emails out on dev/tests sites to prevent accidentally spamming users. |
||
861 | // However, if TestMailer is in use this isn't a risk. |
||
862 | // @todo some developers use external tools, so emailing might be a good idea anyway |
||
863 | if ((Director::isLive() || Injector::inst()->get(Mailer::class) instanceof TestMailer) |
||
864 | && $this->isChanged('Password') |
||
865 | && $this->record['Password'] |
||
866 | && static::config()->get('notify_password_change') |
||
867 | ) { |
||
868 | Email::create() |
||
869 | ->setHTMLTemplate('SilverStripe\\Control\\Email\\ChangePasswordEmail') |
||
870 | ->setData($this) |
||
871 | ->setTo($this->Email) |
||
872 | ->setSubject(_t(__CLASS__ . '.SUBJECTPASSWORDCHANGED', "Your password has been changed", 'Email subject')) |
||
873 | ->send(); |
||
874 | } |
||
875 | |||
876 | // The test on $this->ID is used for when records are initially created. |
||
877 | // Note that this only works with cleartext passwords, as we can't rehash |
||
878 | // existing passwords. |
||
879 | if ((!$this->ID && $this->Password) || $this->isChanged('Password')) { |
||
880 | //reset salt so that it gets regenerated - this will invalidate any persistent login cookies |
||
881 | // or other information encrypted with this Member's settings (see self::encryptWithUserSettings) |
||
882 | $this->Salt = ''; |
||
883 | // Password was changed: encrypt the password according the settings |
||
884 | $encryption_details = Security::encrypt_password( |
||
885 | $this->Password, // this is assumed to be cleartext |
||
886 | $this->Salt, |
||
887 | ($this->PasswordEncryption) ? |
||
888 | $this->PasswordEncryption : Security::config()->get('password_encryption_algorithm'), |
||
889 | $this |
||
890 | ); |
||
891 | |||
892 | // Overwrite the Password property with the hashed value |
||
893 | $this->Password = $encryption_details['password']; |
||
894 | $this->Salt = $encryption_details['salt']; |
||
895 | $this->PasswordEncryption = $encryption_details['algorithm']; |
||
896 | |||
897 | // If we haven't manually set a password expiry |
||
898 | if (!$this->isChanged('PasswordExpiry')) { |
||
899 | // then set it for us |
||
900 | if (static::config()->get('password_expiry_days')) { |
||
901 | $this->PasswordExpiry = date('Y-m-d', time() + 86400 * static::config()->get('password_expiry_days')); |
||
902 | } else { |
||
903 | $this->PasswordExpiry = null; |
||
904 | } |
||
905 | } |
||
906 | } |
||
907 | |||
908 | // save locale |
||
909 | if (!$this->Locale) { |
||
910 | $this->Locale = i18n::get_locale(); |
||
911 | } |
||
912 | |||
913 | parent::onBeforeWrite(); |
||
914 | } |
||
915 | |||
916 | public function onAfterWrite() |
||
917 | { |
||
918 | parent::onAfterWrite(); |
||
919 | |||
920 | Permission::reset(); |
||
921 | |||
922 | if ($this->isChanged('Password') && static::config()->get('password_logging_enabled')) { |
||
923 | MemberPassword::log($this); |
||
924 | } |
||
925 | } |
||
926 | |||
927 | public function onAfterDelete() |
||
928 | { |
||
929 | parent::onAfterDelete(); |
||
930 | |||
931 | //prevent orphaned records remaining in the DB |
||
932 | $this->deletePasswordLogs(); |
||
933 | } |
||
934 | |||
935 | /** |
||
936 | * Delete the MemberPassword objects that are associated to this user |
||
937 | * |
||
938 | * @return $this |
||
939 | */ |
||
940 | protected function deletePasswordLogs() |
||
941 | { |
||
942 | foreach ($this->LoggedPasswords() as $password) { |
||
943 | $password->delete(); |
||
944 | $password->destroy(); |
||
945 | } |
||
946 | |||
947 | return $this; |
||
948 | } |
||
949 | |||
950 | /** |
||
951 | * Filter out admin groups to avoid privilege escalation, |
||
952 | * If any admin groups are requested, deny the whole save operation. |
||
953 | * |
||
954 | * @param array $ids Database IDs of Group records |
||
955 | * @return bool True if the change can be accepted |
||
956 | */ |
||
957 | public function onChangeGroups($ids) |
||
958 | { |
||
959 | // unless the current user is an admin already OR the logged in user is an admin |
||
960 | if (Permission::check('ADMIN') || Permission::checkMember($this, 'ADMIN')) { |
||
961 | return true; |
||
962 | } |
||
963 | |||
964 | // If there are no admin groups in this set then it's ok |
||
965 | $adminGroups = Permission::get_groups_by_permission('ADMIN'); |
||
966 | $adminGroupIDs = ($adminGroups) ? $adminGroups->column('ID') : array(); |
||
967 | |||
968 | return count(array_intersect($ids, $adminGroupIDs)) == 0; |
||
969 | } |
||
970 | |||
971 | |||
972 | /** |
||
973 | * Check if the member is in one of the given groups. |
||
974 | * |
||
975 | * @param array|SS_List $groups Collection of {@link Group} DataObjects to check |
||
976 | * @param boolean $strict Only determine direct group membership if set to true (Default: false) |
||
977 | * @return bool Returns TRUE if the member is in one of the given groups, otherwise FALSE. |
||
978 | */ |
||
979 | public function inGroups($groups, $strict = false) |
||
980 | { |
||
981 | if ($groups) { |
||
982 | foreach ($groups as $group) { |
||
983 | if ($this->inGroup($group, $strict)) { |
||
984 | return true; |
||
985 | } |
||
986 | } |
||
987 | } |
||
988 | |||
989 | return false; |
||
990 | } |
||
991 | |||
992 | |||
993 | /** |
||
994 | * Check if the member is in the given group or any parent groups. |
||
995 | * |
||
996 | * @param int|Group|string $group Group instance, Group Code or ID |
||
997 | * @param boolean $strict Only determine direct group membership if set to TRUE (Default: FALSE) |
||
998 | * @return bool Returns TRUE if the member is in the given group, otherwise FALSE. |
||
999 | */ |
||
1000 | public function inGroup($group, $strict = false) |
||
1001 | { |
||
1002 | if (is_numeric($group)) { |
||
1003 | $groupCheckObj = DataObject::get_by_id(Group::class, $group); |
||
1004 | } elseif (is_string($group)) { |
||
1005 | $groupCheckObj = DataObject::get_one(Group::class, array( |
||
1006 | '"Group"."Code"' => $group |
||
1007 | )); |
||
1008 | } elseif ($group instanceof Group) { |
||
1009 | $groupCheckObj = $group; |
||
1010 | } else { |
||
1011 | throw new InvalidArgumentException('Member::inGroup(): Wrong format for $group parameter'); |
||
1012 | } |
||
1013 | |||
1014 | if (!$groupCheckObj) { |
||
1015 | return false; |
||
1016 | } |
||
1017 | |||
1018 | $groupCandidateObjs = ($strict) ? $this->getManyManyComponents("Groups") : $this->Groups(); |
||
1019 | if ($groupCandidateObjs) { |
||
1020 | foreach ($groupCandidateObjs as $groupCandidateObj) { |
||
1021 | if ($groupCandidateObj->ID == $groupCheckObj->ID) { |
||
1022 | return true; |
||
1023 | } |
||
1024 | } |
||
1025 | } |
||
1026 | |||
1027 | return false; |
||
1028 | } |
||
1029 | |||
1030 | /** |
||
1031 | * Adds the member to a group. This will create the group if the given |
||
1032 | * group code does not return a valid group object. |
||
1033 | * |
||
1034 | * @param string $groupcode |
||
1035 | * @param string $title Title of the group |
||
1036 | */ |
||
1037 | public function addToGroupByCode($groupcode, $title = "") |
||
1038 | { |
||
1039 | $group = DataObject::get_one(Group::class, array( |
||
1040 | '"Group"."Code"' => $groupcode |
||
1041 | )); |
||
1042 | |||
1043 | if ($group) { |
||
1044 | $this->Groups()->add($group); |
||
1045 | } else { |
||
1046 | if (!$title) { |
||
1047 | $title = $groupcode; |
||
1048 | } |
||
1049 | |||
1050 | $group = new Group(); |
||
1051 | $group->Code = $groupcode; |
||
1052 | $group->Title = $title; |
||
1053 | $group->write(); |
||
1054 | |||
1055 | $this->Groups()->add($group); |
||
1056 | } |
||
1057 | } |
||
1058 | |||
1059 | /** |
||
1060 | * Removes a member from a group. |
||
1061 | * |
||
1062 | * @param string $groupcode |
||
1063 | */ |
||
1064 | public function removeFromGroupByCode($groupcode) |
||
1065 | { |
||
1066 | $group = Group::get()->filter(array('Code' => $groupcode))->first(); |
||
1067 | |||
1068 | if ($group) { |
||
1069 | $this->Groups()->remove($group); |
||
1070 | } |
||
1071 | } |
||
1072 | |||
1073 | /** |
||
1074 | * @param array $columns Column names on the Member record to show in {@link getTitle()}. |
||
1075 | * @param String $sep Separator |
||
1076 | */ |
||
1077 | public static function set_title_columns($columns, $sep = ' ') |
||
1078 | { |
||
1079 | Deprecation::notice('5.0', 'Use Member.title_format config instead'); |
||
1080 | if (!is_array($columns)) { |
||
1081 | $columns = array($columns); |
||
1082 | } |
||
1083 | self::config()->set( |
||
1084 | 'title_format', |
||
1085 | [ |
||
1086 | 'columns' => $columns, |
||
1087 | 'sep' => $sep |
||
1088 | ] |
||
1089 | ); |
||
1090 | } |
||
1091 | |||
1092 | //------------------- HELPER METHODS -----------------------------------// |
||
1093 | |||
1094 | /** |
||
1095 | * Get the complete name of the member, by default in the format "<Surname>, <FirstName>". |
||
1096 | * Falls back to showing either field on its own. |
||
1097 | * |
||
1098 | * You can overload this getter with {@link set_title_format()} |
||
1099 | * and {@link set_title_sql()}. |
||
1100 | * |
||
1101 | * @return string Returns the first- and surname of the member. If the ID |
||
1102 | * of the member is equal 0, only the surname is returned. |
||
1103 | */ |
||
1104 | public function getTitle() |
||
1105 | { |
||
1106 | $format = static::config()->get('title_format'); |
||
1107 | if ($format) { |
||
1108 | $values = array(); |
||
1109 | foreach ($format['columns'] as $col) { |
||
1110 | $values[] = $this->getField($col); |
||
1111 | } |
||
1112 | |||
1113 | return implode($format['sep'], $values); |
||
1114 | } |
||
1115 | if ($this->getField('ID') === 0) { |
||
1116 | return $this->getField('Surname'); |
||
1117 | } else { |
||
1118 | if ($this->getField('Surname') && $this->getField('FirstName')) { |
||
1119 | return $this->getField('Surname') . ', ' . $this->getField('FirstName'); |
||
1120 | } elseif ($this->getField('Surname')) { |
||
1121 | return $this->getField('Surname'); |
||
1122 | } elseif ($this->getField('FirstName')) { |
||
1123 | return $this->getField('FirstName'); |
||
1124 | } else { |
||
1125 | return null; |
||
1126 | } |
||
1127 | } |
||
1128 | } |
||
1129 | |||
1130 | /** |
||
1131 | * Return a SQL CONCAT() fragment suitable for a SELECT statement. |
||
1132 | * Useful for custom queries which assume a certain member title format. |
||
1133 | * |
||
1134 | * @return String SQL |
||
1135 | */ |
||
1136 | public static function get_title_sql() |
||
1137 | { |
||
1138 | |||
1139 | // Get title_format with fallback to default |
||
1140 | $format = static::config()->get('title_format'); |
||
1141 | if (!$format) { |
||
1142 | $format = [ |
||
1143 | 'columns' => ['Surname', 'FirstName'], |
||
1144 | 'sep' => ' ', |
||
1145 | ]; |
||
1146 | } |
||
1147 | |||
1148 | $columnsWithTablename = array(); |
||
1149 | foreach ($format['columns'] as $column) { |
||
1150 | $columnsWithTablename[] = static::getSchema()->sqlColumnForField(__CLASS__, $column); |
||
1151 | } |
||
1152 | |||
1153 | $sepSQL = Convert::raw2sql($format['sep'], true); |
||
1154 | $op = DB::get_conn()->concatOperator(); |
||
1155 | return "(" . join(" $op $sepSQL $op ", $columnsWithTablename) . ")"; |
||
1156 | } |
||
1157 | |||
1158 | |||
1159 | /** |
||
1160 | * Get the complete name of the member |
||
1161 | * |
||
1162 | * @return string Returns the first- and surname of the member. |
||
1163 | */ |
||
1164 | public function getName() |
||
1168 | |||
1169 | |||
1170 | /** |
||
1171 | * Set first- and surname |
||
1172 | * |
||
1173 | * This method assumes that the last part of the name is the surname, e.g. |
||
1174 | * <i>A B C</i> will result in firstname <i>A B</i> and surname <i>C</i> |
||
1175 | * |
||
1176 | * @param string $name The name |
||
1177 | */ |
||
1178 | public function setName($name) |
||
1184 | |||
1185 | |||
1186 | /** |
||
1187 | * Alias for {@link setName} |
||
1188 | * |
||
1189 | * @param string $name The name |
||
1190 | * @see setName() |
||
1191 | */ |
||
1192 | public function splitName($name) |
||
1196 | |||
1197 | /** |
||
1198 | * Return the date format based on the user's chosen locale, |
||
1199 | * falling back to the default format defined by the {@link i18n.get_locale()} setting. |
||
1200 | * |
||
1201 | * @return string ISO date format |
||
1202 | */ |
||
1203 | View Code Duplication | public function getDateFormat() |
|
1216 | |||
1217 | /** |
||
1218 | * Get user locale |
||
1219 | */ |
||
1220 | public function getLocale() |
||
1229 | |||
1230 | /** |
||
1231 | * Return the time format based on the user's chosen locale, |
||
1232 | * falling back to the default format defined by the {@link i18n.get_locale()} setting. |
||
1233 | * |
||
1234 | * @return string ISO date format |
||
1235 | */ |
||
1236 | View Code Duplication | public function getTimeFormat() |
|
1249 | |||
1250 | //---------------------------------------------------------------------// |
||
1251 | |||
1252 | |||
1253 | /** |
||
1254 | * Get a "many-to-many" map that holds for all members their group memberships, |
||
1255 | * including any parent groups where membership is implied. |
||
1256 | * Use {@link DirectGroups()} to only retrieve the group relations without inheritance. |
||
1257 | * |
||
1258 | * @todo Push all this logic into Member_GroupSet's getIterator()? |
||
1259 | * @return Member_Groupset |
||
1260 | */ |
||
1261 | public function Groups() |
||
1270 | |||
1271 | /** |
||
1272 | * @return ManyManyList |
||
1273 | */ |
||
1274 | public function DirectGroups() |
||
1278 | |||
1279 | /** |
||
1280 | * Get a member SQLMap of members in specific groups |
||
1281 | * |
||
1282 | * If no $groups is passed, all members will be returned |
||
1283 | * |
||
1284 | * @param mixed $groups - takes a SS_List, an array or a single Group.ID |
||
1285 | * @return Map Returns an Map that returns all Member data. |
||
1286 | */ |
||
1287 | public static function map_in_groups($groups = null) |
||
1288 | { |
||
1289 | $groupIDList = array(); |
||
1290 | |||
1291 | if ($groups instanceof SS_List) { |
||
1292 | foreach ($groups as $group) { |
||
1293 | $groupIDList[] = $group->ID; |
||
1294 | } |
||
1295 | } elseif (is_array($groups)) { |
||
1296 | $groupIDList = $groups; |
||
1297 | } elseif ($groups) { |
||
1298 | $groupIDList[] = $groups; |
||
1299 | } |
||
1300 | |||
1301 | // No groups, return all Members |
||
1302 | if (!$groupIDList) { |
||
1303 | return static::get()->sort(array('Surname' => 'ASC', 'FirstName' => 'ASC'))->map(); |
||
1304 | } |
||
1305 | |||
1317 | |||
1318 | |||
1319 | /** |
||
1320 | * Get a map of all members in the groups given that have CMS permissions |
||
1321 | * |
||
1322 | * If no groups are passed, all groups with CMS permissions will be used. |
||
1323 | * |
||
1324 | * @param array $groups Groups to consider or NULL to use all groups with |
||
1325 | * CMS permissions. |
||
1326 | * @return Map Returns a map of all members in the groups given that |
||
1327 | * have CMS permissions. |
||
1328 | */ |
||
1329 | public static function mapInCMSGroups($groups = null) |
||
1381 | |||
1382 | |||
1383 | /** |
||
1384 | * Get the groups in which the member is NOT in |
||
1385 | * |
||
1386 | * When passed an array of groups, and a component set of groups, this |
||
1387 | * function will return the array of groups the member is NOT in. |
||
1388 | * |
||
1389 | * @param array $groupList An array of group code names. |
||
1390 | * @param array $memberGroups A component set of groups (if set to NULL, |
||
1391 | * $this->groups() will be used) |
||
1392 | * @return array Groups in which the member is NOT in. |
||
1393 | */ |
||
1394 | public function memberNotInGroups($groupList, $memberGroups = null) |
||
1409 | |||
1410 | |||
1411 | /** |
||
1412 | * Return a {@link FieldList} of fields that would appropriate for editing |
||
1413 | * this member. |
||
1414 | * |
||
1415 | * @return FieldList Return a FieldList of fields that would appropriate for |
||
1416 | * editing this member. |
||
1417 | */ |
||
1418 | public function getCMSFields() |
||
1490 | |||
1491 | /** |
||
1492 | * @param bool $includerelations Indicate if the labels returned include relation fields |
||
1493 | * @return array |
||
1494 | */ |
||
1495 | public function fieldLabels($includerelations = true) |
||
1517 | |||
1518 | /** |
||
1519 | * Users can view their own record. |
||
1520 | * Otherwise they'll need ADMIN or CMS_ACCESS_SecurityAdmin permissions. |
||
1521 | * This is likely to be customized for social sites etc. with a looser permission model. |
||
1522 | * |
||
1523 | * @param Member $member |
||
1524 | * @return bool |
||
1525 | */ |
||
1526 | public function canView($member = null) |
||
1550 | |||
1551 | /** |
||
1552 | * Users can edit their own record. |
||
1553 | * Otherwise they'll need ADMIN or CMS_ACCESS_SecurityAdmin permissions |
||
1554 | * |
||
1555 | * @param Member $member |
||
1556 | * @return bool |
||
1557 | */ |
||
1558 | View Code Duplication | public function canEdit($member = null) |
|
1587 | |||
1588 | /** |
||
1589 | * Users can edit their own record. |
||
1590 | * Otherwise they'll need ADMIN or CMS_ACCESS_SecurityAdmin permissions |
||
1591 | * |
||
1592 | * @param Member $member |
||
1593 | * @return bool |
||
1594 | */ |
||
1595 | View Code Duplication | public function canDelete($member = null) |
|
1628 | |||
1629 | /** |
||
1630 | * Validate this member object. |
||
1631 | */ |
||
1632 | public function validate() |
||
1650 | |||
1651 | /** |
||
1652 | * Change password. This will cause rehashing according to |
||
1653 | * the `PasswordEncryption` property. |
||
1654 | * |
||
1655 | * @param string $password Cleartext password |
||
1656 | * @return ValidationResult |
||
1657 | */ |
||
1658 | public function changePassword($password) |
||
1670 | |||
1671 | /** |
||
1672 | * Tell this member that someone made a failed attempt at logging in as them. |
||
1673 | * This can be used to lock the user out temporarily if too many failed attempts are made. |
||
1674 | */ |
||
1675 | public function registerFailedLogin() |
||
1691 | |||
1692 | /** |
||
1693 | * Tell this member that a successful login has been made |
||
1694 | */ |
||
1695 | public function registerSuccessfulLogin() |
||
1703 | |||
1704 | /** |
||
1705 | * Get the HtmlEditorConfig for this user to be used in the CMS. |
||
1706 | * This is set by the group. If multiple configurations are set, |
||
1707 | * the one with the highest priority wins. |
||
1708 | * |
||
1709 | * @return string |
||
1710 | */ |
||
1711 | public function getHtmlEditorConfigForCMS() |
||
1730 | } |
||
1731 |