Advertisement
Guest User

Untitled

a guest
Oct 8th, 2016
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 27.42 KB | None | 0 0
  1. <?php
  2. /*
  3.  * Copyright Intermesh
  4.  *
  5.  * This file is part of Group-Office. You should have received a copy of the
  6.  * Group-Office license along with Group-Office. See the file /LICENSE.TXT
  7.  *
  8.  * If you have questions write an e-mail to info@intermesh.nl
  9.  *
  10.  
  11.  */
  12.  
  13.  
  14.  
  15.  
  16. namespace GO\Base\Model;
  17.  
  18. use GO;
  19. use GO\Base\Mail\Message;
  20. use GO\Base\Mail\Mailer;
  21.  
  22. /**
  23.  * The User model
  24.  *
  25.  * @version $Id: Group.php 7607 2011-08-04 13:41:42Z mschering $
  26.  * @copyright Copyright Intermesh
  27.  * @author Merijn Schering <mschering@intermesh.nl>
  28.  * @package GO.base.model
  29.  *
  30.  * @property int $id
  31.  * @property String $username
  32.  * @property String $password
  33.  * @property String $password_type
  34.  * @property Boolean $enabled
  35.  * @property String $first_name
  36.  * @property String $middle_name
  37.  * @property String $last_name
  38.  * @property int $acl_id
  39.  * @property String $time_format
  40.  * @property String $thousands_separator
  41.  * @property String $decimal_separator
  42.  * @property String $currency
  43.  * @property int $logins
  44.  * @property int $lastlogin
  45.  * @property int $ctime
  46.  * @property int $max_rows_list
  47.  * @property String $timezone
  48.  * @property String $start_module
  49.  * @property String $language
  50.  * @property String $theme
  51.  * @property int $first_weekday
  52.  * @property String $sort_name
  53.  * @property String $bank
  54.  * @property String $bank_no
  55.  * @property int $mtime
  56.  * @property int $muser_id
  57.  * @property Boolean $mute_sound
  58.  * @property Boolean $mute_reminder_sound
  59.  * @property Boolean $mute_new_mail_sound
  60.  * @property Boolean $show_smilies
  61.  * @property Boolean $auto_punctuation
  62.  * @property String $list_separator
  63.  * @property String $text_separator
  64.  * @property int $files_folder_id
  65.  * @property int $disk_quota The amount of diskspace the user may use in MB
  66.  * @property int $disk_usage The diskspace used in Bytes (cache column with sum fs_files.size owned by this user)
  67.  * @property int $mail_reminders
  68.  * @property int $popup_reminders
  69.  * @property int $popup_emails
  70.  * @property int $contact_id
  71.  * @property String $holidayset
  72.  * @property boolean $no_reminders
  73.  *
  74.  * @property string $completeDateFormat
  75.  * @property string $date_separator
  76.  * @property string $date_format
  77.  * @property string $email
  78.  * @property \GO\Addressbook\Model\Contact $contact
  79.  * @property string $diges
  80.  *
  81.  * @method User findByPk();
  82.  *
  83.  * @property Boolean $sort_email_addresses_by_time
  84.  */
  85. class User extends \GO\Base\Db\ActiveRecord {
  86.    
  87.     /*
  88.      * Don't return the password hash by default, use getAttribute('password') instead
  89.      */
  90.     public function getPassword(){
  91.         return null;
  92.     }
  93.     /*
  94.      * Don't return the digest by default, use getAttribute('digest') instead
  95.      */
  96.     public function getDigest(){
  97.         return null;
  98.     }
  99.  
  100.     /**
  101.      * Run code as administrator
  102.      *
  103.      * Can be useful when you need to do stuff that the current user isn't
  104.      * allowed to. For example when you create a contact you don't have the
  105.      * permissions to do that while adding it.
  106.      *
  107.      * @param callable $callback Code in this function will run as administrator
  108.      */
  109.     public static function sudo($callback) {
  110.        
  111. //      $usr = \GO::user();
  112. //      $currentUserId = !empty($usr) ? $usr->id : false; // when not logged in
  113.    
  114.         $oldIgnore = GO::setIgnoreAclPermissions();
  115.        
  116.         try {
  117.             $ret = call_user_func($callback);
  118.            
  119.             GO::setIgnoreAclPermissions($oldIgnore);
  120.            
  121.             return $ret;
  122.         } catch (\Exception $ex) {         
  123.             GO::setIgnoreAclPermissions($oldIgnore);
  124.             throw $ex;
  125.         }
  126.     }
  127.    
  128.  
  129.     public $generatedRandomPassword = false;
  130.     public $passwordConfirm;
  131.    
  132.    
  133.     public $skip_contact_update=false;
  134.    
  135.     /**
  136.      * This variable will be set when the password is modified.
  137.      *
  138.      * @var string
  139.      */
  140.     private $_unencryptedPassword;
  141.     /**
  142.      * If this is set on a new user then it will be connected to this contact.
  143.      *
  144.      * @var int
  145.      */
  146.     public $contact_id;
  147.    
  148.     /**
  149.      * Returns a static model of itself
  150.      *
  151.      * @param String $className
  152.      * @return GO\Base\Model\User
  153.      */
  154.     public static function model($className=__CLASS__)
  155.     {  
  156.         return parent::model($className);
  157.     }
  158.    
  159.     protected function _trimSpacesFromAttributes() {
  160.         if(!static::$trimOnSave)
  161.             return;
  162.         foreach($this->columns as $field=>$col){
  163.            
  164.             // For passwords it is allowed to apply spaces at the begin or end.
  165.             if($field == 'password'){
  166.                 return;
  167.             }
  168.            
  169.             if(isset($this->_attributes[$field]) && $col['type'] == \PDO::PARAM_STR){
  170.                 $this->_attributes[$field] = trim($this->_attributes[$field]);
  171.             }
  172.         }
  173.     }
  174.    
  175.    
  176.     /**
  177.      * Create a new user
  178.      *
  179.      * When creating a user we also need to create a lot of default models and
  180.      * set permissions for this user. This function creates the user with permissions
  181.      * and the right models in one go.
  182.      *
  183.      * @param array $attributes
  184.      * @param array $groups array of group names array('Internal','Some group');
  185.      * @param array $modulePermissionLevels array('calendar'=>1,'projects'=>4)
  186.      * @return User
  187.      */
  188.     public static function newInstance($attributes, $groups=array(), $modulePermissionLevels=array()){
  189.         $user = new User();
  190.         $user->setAttributes($attributes);
  191.         $user->save();
  192.  
  193.         $user->addToGroups($groups);   
  194.        
  195.         foreach($modulePermissionLevels as $module=>$permissionLevel){
  196.             GO::modules()->$module->acl->addUser($user->id, $permissionLevel);
  197.         }
  198.        
  199.         $user->checkDefaultModels();
  200.        
  201.         return $user;
  202.     }
  203.  
  204.     public function aclField() {
  205.         return 'acl_id';
  206.     }
  207.  
  208.     public function tableName() {
  209.         return 'go_users';
  210.     }
  211.  
  212.     public function relations() {
  213.         return array(
  214.             'contact' => array('type' => self::HAS_ONE, 'model' => 'GO\Addressbook\Model\Contact', 'field' => 'go_user_id'),
  215.             'reminders' => array('type'=>self::MANY_MANY, 'model'=>'GO\Base\Model\Reminder', 'field'=>'user_id', 'linkModel' => 'GO\Base\Model\ReminderUser'),
  216.             'groups' => array('type'=>self::MANY_MANY, 'model'=>'GO\Base\Model\Group', 'field'=>'user_id', 'linkModel' => 'GO\Base\Model\UserGroup'),
  217.             '_workingWeek' => array('type' => self::HAS_ONE, 'model' => 'GO\Base\Model\WorkingWeek', 'field' => 'user_id')
  218.         );
  219.     }
  220.    
  221.     public function getWorkingWeek(){
  222.         $ww = $this->_workingWeek;
  223.         if(!$ww){
  224.             $ww = new WorkingWeek();
  225.             $ww->user_id=$this->id;
  226.             $ww->save();
  227.         }
  228.         return $ww;
  229.     }
  230.    
  231.     protected function getLocalizedName() {
  232.         return GO::t('strUser');
  233.     }
  234.  
  235.     public function customfieldsModel() {
  236.         return 'GO\Users\Customfields\Model\User';
  237.     }
  238.    
  239.     public function hasFiles(){
  240.         return false;
  241.     }
  242.    
  243.     public function hasLinks() {
  244.         return true;
  245.     }
  246.    
  247.     public function getAttributes($outputType = 'formatted') {
  248.        
  249.         $attr = parent::getAttributes($outputType);
  250.         $attr['name']=$this->getName();
  251.  
  252.         // Unset these 2 fields so they are not returned by default
  253.         $attr['password'] = null;
  254.         $attr['digest'] = null;
  255.  
  256.         return $attr;
  257.     }
  258.    
  259.     public function attributeLabels() {
  260.         $labels = parent::attributeLabels();
  261.         $labels['passwordConfirm']=GO::t("passwordConfirm");
  262.         return $labels;
  263.     }
  264.    
  265.     /**
  266.      * Getter function for the ACL function
  267.      * @return int
  268.      */
  269.     protected function getUser_id(){
  270.         return $this->id;
  271.     }
  272.  
  273.     public function init() {
  274.         $this->columns['email']['regex'] = \GO\Base\Util\StringHelper::get_email_validation_regex();
  275.         $this->columns['email']['required'] = true;
  276.         $this->columns['email2']['regex'] = \GO\Base\Util\StringHelper::get_email_validation_regex();
  277.  
  278.         $this->columns['password']['required'] = true;
  279.         $this->columns['username']['required'] = true;
  280.         $this->columns['username']['regex'] = '/^[A-Za-z0-9_\-\.\@]*$/';
  281.        
  282.         $this->columns['first_name']['required'] = true;
  283.  
  284.         $this->columns['last_name']['required'] = true;
  285.         $this->columns['timezone']['required']=true;
  286.        
  287.         $this->columns['lastlogin']['gotype']='unixtimestamp';
  288.         $this->columns['disk_quota']['gotype']='number';
  289.         $this->columns['disk_quota']['decimals']=0;
  290.         return parent::init();
  291.     }
  292.    
  293.     public function getFindSearchQueryParamFields($prefixTable = 't', $withCustomFields = true) {
  294.         $fields=array(
  295.                 "CONCAT(t.first_name,' ',t.middle_name,' ',t.last_name)",
  296.                 $prefixTable.".email",
  297.                 $prefixTable.".username"
  298.                 );
  299.        
  300.         if($withCustomFields && $this->customfieldsRecord)
  301.         {
  302.             $fields = array_merge($fields, $this->customfieldsRecord->getFindSearchQueryParamFields('cf'));
  303.         }
  304.        
  305.         return $fields;
  306.     }
  307.  
  308.     private function _maxUsersReached() {
  309.         return GO::config()->max_users > 0 && $this->count() >= GO::config()->max_users;
  310.     }
  311.  
  312.         /**
  313.      * This method will (re)calculate the used diskspace for this user
  314.      * @param integer $bytes The amount of bytes to add to the users used diskspace (negative for substraction)
  315.      * @return User itself for chaining eg. $user->calculatedDiskUsage()->save()
  316.      */
  317.     public function calculatedDiskUsage($bytes = false) {
  318.         if (GO::modules()->isInstalled('files')) {
  319.             if (!$bytes) { //recalculated
  320.                 $fp = \GO\Base\Db\FindParams::newInstance()->select('SUM(size) as total_size')
  321.                     ->joinModel(array(
  322.                         'model'=>'GO\Files\Model\Folder',  
  323.                         'localTableAlias'=>'t',
  324.                         'localField'=>'folder_id',
  325.                         'tableAlias'=>'d'
  326.                     ))
  327.                     ->criteria(\GO\Base\Db\FindCriteria::newInstance()->addCondition('quota_user_id', $this->id, '=', 'd'));
  328.                 $sumFilesize = \GO\Files\Model\File::model()->findSingle($fp);
  329.                 $fpVer = \GO\Base\Db\FindParams::newInstance()->select('SUM(size_bytes) as total_size')
  330.                     ->joinModel(array(
  331.                         'model'=>'GO\Files\Model\File',  
  332.                         'localTableAlias'=>'t',
  333.                         'localField'=>'file_id',
  334.                         'tableAlias'=>'f'
  335.                     ))->joinModel(array(
  336.                         'model'=>'GO\Files\Model\Folder',  
  337.                         'localTableAlias'=>'f',
  338.                         'localField'=>'folder_id',
  339.                         'tableAlias'=>'d'
  340.                     ))
  341.                     ->criteria(\GO\Base\Db\FindCriteria::newInstance()->addCondition('quota_user_id', $this->id, '=', 'd'));
  342.                 $sumVersionsize = \GO\Files\Model\Version::model()->findSingle($fpVer);
  343.                 //GO::debug($sumFilesize->total_size);
  344.                 if ($sumFilesize)
  345.                     $this->disk_usage = ($sumFilesize->total_size + $sumVersionsize->total_size);
  346.             } else {
  347.                 $this->disk_usage+=$bytes;
  348.             }
  349.         } else
  350.             throw new \Exceptions('Can not calculated diskusage without the files module');
  351.         return $this;
  352.     }
  353.    
  354.     /**
  355.      * Get the user disk quota in bytes
  356.      * @return int amount of bytes the user may use
  357.      */
  358.     public function getDiskQuota(){
  359.         return $this->disk_quota*1024*1024;
  360.     }
  361.  
  362.     public function validate() {
  363.        
  364.         if($this->max_rows_list > 250)
  365.                 $this->setValidationError('max_rows_list', GO::t('maxRowslistTooHigh'));
  366.        
  367.         if($this->isModified('password') && isset($this->passwordConfirm) && $this->passwordConfirm!=$this->getAttribute('password')){
  368.             $this->setValidationError('passwordConfirm', GO::t('passwordMatchError'));
  369.         }
  370.        
  371.         if($this->isModified('disk_quota') && !GO::$ignoreAclPermissions && GO::user()->getModulePermissionLevel('users') < Acl::MANAGE_PERMISSION)
  372.             $this->setValidationError('disk_quota', 'Only managers of the "users"  module may modify disk quota');
  373.        
  374.         if(GO::config()->password_validate && $this->isModified('password')){
  375.             if(!\GO\Base\Util\Validate::strongPassword($this->getAttribute('password'))){
  376.                 $this->setValidationError('password', \GO\Base\Util\Validate::getPasswordErrorString($this->getAttribute('password')));
  377.             }
  378.         }
  379.  
  380.         if ($this->isNew && $this->_maxUsersReached())             
  381.             $this->setValidationError('form', GO::t('max_users_reached', 'users'));
  382.            
  383.         if (!GO::config()->allow_duplicate_email) {
  384.            
  385.             $findParams = \GO\Base\Db\FindParams::newInstance();
  386.             $findCriteria = \GO\Base\Db\FindCriteria::newInstance()
  387.                         ->addCondition('email', $this->email, '=','t', false)
  388.                         ->addCondition('email2', $this->email, '=','t', false);
  389.        
  390.             $findParams->criteria($findCriteria);
  391.             $existing = \GO\Base\Model\User::model()->findSingle($findParams);
  392.            
  393.             if (($this->isNew && $existing) || $existing && $existing->id != $this->id )
  394.                 $this->setValidationError('email', GO::t('error_email_exists', 'users'));
  395.         }
  396.  
  397.         $existing = $this->findSingleByAttribute('username', $this->username);
  398.         if (($this->isNew && $existing) || $existing && $existing->id != $this->id )
  399.             $this->setValidationError('username', GO::t('error_username_exists', 'users'));
  400.  
  401.         $pwd = $this->getAttribute('password');
  402.         if(empty($pwd) && $this->isNew) {
  403.             $this->password = \GO\Base\Util\StringHelper::randomPassword();
  404.             $this->generatedRandomPassword = true;
  405.         }
  406.  
  407.         return parent::validate();
  408.     }
  409.    
  410.     public function buildFilesPath() {
  411.         return 'users/'.$this->username;
  412.     }
  413.    
  414.     protected function beforeSave(){
  415.        
  416.         if($this->isNew){
  417.             $holiday = Holiday::localeFromCountry($this->language);
  418.            
  419.         if($holiday !== false)
  420.             $this->holidayset = $holiday;
  421.         }
  422.        
  423.         if(!$this->isNew && empty($this->holidayset) && ($contact = $this->createContact())){
  424.             $holiday = Holiday::localeFromCountry($contact->country);
  425.  
  426.             if($holiday !== false)
  427.                 $this->holidayset = $holiday;
  428.         }
  429.        
  430.         $pwd = $this->getAttribute('password');
  431.         if($this->isModified('password') && !empty($pwd)){
  432.             $this->_unencryptedPassword=$this->getAttribute('password');
  433.            
  434.                
  435.             $this->password=$this->_encryptPassword($this->getAttribute('password'));
  436.             $this->password_type='crypt';
  437.            
  438.             $this->digest = md5($this->username.":".GO::config()->product_name.":".$this->_unencryptedPassword);
  439.         }
  440.        
  441.         return parent::beforeSave();
  442.     }  
  443.    
  444.    
  445.     private function _encryptPassword($password) {
  446.         if(function_exists('password_hash')) {
  447.             return password_hash($password,PASSWORD_DEFAULT);
  448.         }else
  449.         {
  450.             $salt = uniqid();
  451.             if(function_exists("mcrypt_create_iv")) {
  452.                 $salt = base64_encode(mcrypt_create_iv(24, MCRYPT_DEV_URANDOM));
  453.             }
  454.            
  455.             if (CRYPT_SHA256 == 1) {
  456.                     $salt = '$5$'.$salt;
  457.             }
  458.            
  459.             return crypt($password, $salt);
  460.         }
  461.     }
  462.        
  463.     /**
  464.      * When the password was just modified. You can call this function to get the
  465.      * plain text password.
  466.      *
  467.      * @return string
  468.      */
  469.     public function getUnencryptedPassword(){
  470.         return isset($this->_unencryptedPassword) ? $this->_unencryptedPassword : false;
  471.     }
  472.    
  473.  
  474.     protected function afterSave($wasNew) {
  475.  
  476.         if($wasNew){
  477.             $everyoneGroup = Group::model()->findByPk(GO::config()->group_everyone);       
  478.             $everyoneGroup->addUser($this->id);        
  479.            
  480.             $this->acl->user_id=$this->id;
  481.             $this->acl->save();
  482.            
  483.             if(!empty(GO::config()->register_user_groups)){
  484.                 $groups = explode(',',GO::config()->register_user_groups);
  485.                 foreach($groups as $groupName){
  486.  
  487.                     $group = Group::model()->findByName($groupName);
  488.  
  489.                     if($group)
  490.                         $group->addUser($this->id);
  491.                 }
  492.             }
  493.            
  494.             $this->_setVisibility();
  495.         }      
  496.        
  497.         if(!$this->skip_contact_update && ($this->isNew || $this->isModified(array('first_name','middle_name','last_name','email'))))
  498.             $this->createContact();
  499.        
  500.         return parent::afterSave($wasNew);
  501.     }
  502.    
  503.     private function _setVisibility(){
  504.         if(!empty(GO::config()->register_visible_user_groups)){
  505.             $groups = explode(',',GO::config()->register_visible_user_groups);
  506.             foreach($groups as $groupName){
  507.  
  508.                 $group = Group::model()->findByName(trim($groupName));
  509.                
  510.                 if($group)
  511.                     $this->acl->addGroup($group->id, Acl::MANAGE_PERMISSION);
  512.             }
  513.         }
  514.     }
  515.    
  516.     /**
  517.      * Makes shure that this model's user has all the default models it should have.
  518.      */
  519.     public function checkDefaultModels(){
  520.         $oldIgnore = GO::setIgnoreAclPermissions(true);
  521.       $defaultModels = AbstractUserDefaultModel::getAllUserDefaultModels($this->id);   
  522.         foreach($defaultModels as $model){
  523.             $model->getDefault($this);
  524.         }      
  525.         GO::setIgnoreAclPermissions($oldIgnore);
  526.     }
  527.    
  528.     protected function beforeDelete() {
  529.         if($this->id==1){
  530.             throw new \Exception(GO::t('deletePrimaryAdmin','users'));
  531.         }elseif($this->id==GO::user()->id){
  532.             throw new \Exception(GO::t('deleteYourself','users'));         
  533.         }else
  534.         {
  535.             return parent::beforeDelete();
  536.         }
  537.     }
  538.    
  539.     protected function afterDelete() {
  540.        
  541.        
  542.         //delete all acl records
  543.         $stmt = AclUsersGroups::model()->find(array(
  544.                 "by"=>array(array('user_id',$this->id))
  545.         ));
  546.        
  547.         while($r = $stmt->fetch())
  548.             $r->delete();
  549.        
  550.         $defaultModels = AbstractUserDefaultModel::getAllUserDefaultModels();
  551.    
  552.         foreach($defaultModels as $model){
  553.             $model->deleteByAttribute('user_id',$this->id);
  554.         }
  555. //      deprecated. It's inefficient and can be done with listeners
  556. //      GO::modules()->callModuleMethod('deleteUser', array(&$this));
  557.  
  558.         return parent::afterDelete();
  559.     }
  560.        
  561.    
  562.  
  563.     /**
  564.      *
  565.      * @return String Full formatted name of the user
  566.      */
  567.     public function getName($sort=false) {
  568.        
  569.         if(!$sort){
  570.             if(GO::user()){
  571.                 $sort = GO::user()->sort_name;
  572.             }else
  573.             {
  574.                 $sort = 'first_name';
  575.             }
  576.         }
  577.        
  578.         return \GO\Base\Util\StringHelper::format_name($this->last_name, $this->first_name, $this->middle_name,$sort);
  579.     }
  580.    
  581.     /**
  582.      *
  583.      * @return String Short name of the user
  584.      * Example: Foo Bar will output FB
  585.      */
  586.     public function getShortName() {
  587.        
  588.         if(!empty($this->first_name))
  589.             $short = \GO\Base\Util\StringHelper::substr($this->first_name,0,1);  
  590.        
  591.         if(!empty($this->last_name))
  592.             $short .= \GO\Base\Util\StringHelper::substr($this->last_name,0,1);  
  593.        
  594.         return strtoupper($short);
  595.     }
  596.  
  597.     /**
  598.      * Returns an array of user group id's
  599.      *
  600.      * @return Array
  601.      */
  602.     public static function getGroupIds($userId) {
  603.         $user = GO::user();
  604.         if ($user && $userId == $user->id) {
  605.             if (!isset(GO::session()->values['user_groups'])) {
  606.                 GO::session()->values['user_groups'] = array();
  607.  
  608.                 $stmt= UserGroup::model()->find(
  609.                                 \GO\Base\Db\FindParams::newInstance()
  610.                                 ->select('t.group_id')
  611.                                 ->criteria(\GO\Base\Db\FindCriteria::newInstance()
  612.                                                 ->addCondition("user_id", $userId))
  613.                                 );
  614.                 while ($r = $stmt->fetch()) {
  615.                     GO::session()->values['user_groups'][] = $r->group_id;
  616.                 }
  617.             }
  618.        
  619.             return GO::session()->values['user_groups'];
  620.         } else {
  621.             $ids = array();
  622.             $stmt= UserGroup::model()->find(
  623.                                 \GO\Base\Db\FindParams::newInstance()
  624.                                 ->select('t.group_id')
  625.                                 ->debugSql()
  626.                                 ->criteria(\GO\Base\Db\FindCriteria::newInstance()
  627.                                                 ->addCondition("user_id", $userId))
  628.                                 );
  629.            
  630.             while ($r = $stmt->fetch()) {
  631.                 $ids[] = $r->group_id;
  632.             }
  633.             return $ids;
  634.         }
  635.     }
  636.    
  637.     /**
  638.      * Get the default group ID's for a new user.
  639.      *
  640.      * @return array
  641.      */
  642.     public static function getDefaultGroupIds(){
  643.         $groupIds=array();
  644.         if(!empty(GO::config()->register_user_groups)){
  645.             $groups = explode(',',GO::config()->register_user_groups);
  646.             foreach($groups as $groupName){
  647.                 $group = GO\Base\Model\Group::model()->findByName(trim($groupName));
  648.                 if($group){
  649.                     $groupIds[]=$group->id;
  650.                 }
  651.             }
  652.         }
  653.  
  654.         if(!in_array(GO::config()->group_everyone, $groupIds))
  655.         {
  656.             $groupIds[]=GO::config()->group_everyone;
  657.         }
  658.        
  659.         return $groupIds;
  660.     }
  661.    
  662.    
  663.     /**
  664.      * Get the default group ID's for a new user.
  665.      *
  666.      * @return array
  667.      */
  668.     public static function getDefaultVisibleGroupIds(){
  669.         $groupIds=array();
  670.         if(!empty(GO::config()->register_visible_user_groups)){
  671.             $groups = explode(',',GO::config()->register_visible_user_groups);
  672.             foreach($groups as $groupName){
  673.                 $group = GO\Base\Model\Group::model()->findByName(trim($groupName));
  674.                 if($group){
  675.                     $groupIds[]=$group->id;
  676.                 }
  677.             }
  678.         }
  679.        
  680.         return $groupIds;
  681.     }
  682.    
  683.    
  684.    
  685.    
  686.     /**
  687.      * Check if the user is member of the admin group
  688.      *
  689.      * @return boolean
  690.      */
  691.     public function isAdmin() {
  692.         return in_array(GO::config()->group_root, User::getGroupIds($this->id));
  693.     }
  694.  
  695.    
  696.     /**
  697.      * Get the user's permission level for a given module.
  698.      *
  699.      * @param string $moduleId
  700.      * @return int
  701.      */
  702.     public function getModulePermissionLevel($moduleId) {
  703.         if (GO::modules()->$moduleId)
  704.             return GO::modules()->$moduleId->permissionLevel;
  705.         else
  706.             return false;
  707.     }
  708.    
  709.     private $_completeDateFormat;
  710.    
  711.     protected function getCompleteDateFormat(){
  712.         if(!isset($this->_completeDateFormat))
  713.             $this->_completeDateFormat=$this->date_format[0].$this->date_separator.$this->date_format[1].$this->date_separator.$this->date_format[2];
  714.         return $this->_completeDateFormat;
  715.     }
  716.    
  717.    
  718.     /**
  719.      * Check if the password is correct for this user.
  720.      *
  721.      * @param string $password
  722.      * @return boolean
  723.      */
  724.     public function checkPassword($password){
  725.        
  726. //      throw new \Exception($password);
  727.        
  728.         if(!\GO\Base\Util\Crypt::checkPassword($password, $this->getAttribute('password'), $this->password_type)){
  729.             return false;
  730.         } elseif($this->password_type != 'crypt' && md5($password) == $this->getAttribute('password')) {
  731.             $this->password=$password;
  732.             $oldIgnore=GO::setIgnoreAclPermissions(true);
  733.             $this->save();             
  734.             GO::setIgnoreAclPermissions($oldIgnore);
  735.         }
  736.        
  737.         $digest = md5($this->username.":".GO::config()->product_name.":".$password);
  738.         if($digest != $this->getAttribute('digest'))
  739.         {
  740.             $this->digest=$digest;
  741.             $this->save(true);
  742.         }
  743.        
  744.         return true;
  745.     }  
  746.    
  747.     public function defaultAttributes() {
  748.         $attr = parent::defaultAttributes();
  749.        
  750.         $attr['language']=GO::config()->language;
  751.         $attr['date_format']=GO::config()->default_date_format;
  752.         $attr['date_separator']=GO::config()->default_date_separator;
  753.         $attr['theme']=GO::config()->theme;
  754.         $attr['timezone']=GO::config()->default_timezone;
  755.         $attr['first_weekday']=GO::config()->default_first_weekday;
  756.         $attr['currency']=GO::config()->default_currency;
  757.         $attr['decimal_separator']=GO::config()->default_decimal_separator;
  758.         $attr['thousands_separator']=GO::config()->default_thousands_separator;
  759.         $attr['time_format']=GO::config()->default_time_format;
  760.         $attr['sort_name']=GO::config()->default_sort_name;
  761.         $attr['max_rows_list']=GO::config()->default_max_rows_list;
  762.         $attr['disk_quota']=GO::config()->default_diskquota;
  763.        
  764.        
  765.         return $attr;
  766.     }
  767.    
  768.     /**
  769.      * Get the contact model of this user. All the user profiles are stored in the
  770.      * addressbook.
  771.      *
  772.      * @return \GO\Addressbook\Model\Contact
  773.      */
  774.     public function createContact(){
  775.         if (GO::modules()->isInstalled("addressbook")) {
  776.            
  777.             if(!empty($this->contact_id)){
  778.                 //this is for old databases
  779.                 $contact = \GO\Addressbook\Model\Contact::model()->findByPk($this->contact_id);
  780.                 if($contact){
  781.                     $contact->go_user_id=$this->id;
  782.                     $contact->first_name = $this->first_name;
  783.                     $contact->middle_name = $this->middle_name;
  784.                     $contact->last_name = $this->last_name;
  785.                     $contact->email = $this->email;
  786.                    
  787.                     if($contact->isModified())
  788.                         $contact->save(true);
  789.                    
  790.                     return $contact;
  791.                 }
  792.             }
  793.            
  794.             $contact = $this->contact();
  795.             if (!$contact) {
  796.                 $contact = new \GO\Addressbook\Model\Contact();
  797.                 $addressbook = \GO\Addressbook\Model\Addressbook::model()->getUsersAddressbook();
  798.                 $contact->go_user_id = $this->id;
  799.                 $contact->addressbook_id = $addressbook->id;               
  800.             }          
  801.            
  802.             $contact->first_name = $this->first_name;
  803.             $contact->middle_name = $this->middle_name;
  804.             $contact->last_name = $this->last_name;
  805.             $contact->email = $this->email;
  806.  
  807.             if($contact->isNew || $contact->isModified()){
  808.                 $contact->skip_user_update=true;
  809.                 $contact->save(true);
  810.             }
  811.            
  812.             return $contact;
  813.         }else
  814.         {
  815.             return false;
  816.         }
  817.     }
  818.  
  819.     protected function remoteComboFields() {
  820.         return array(
  821.                 'user_id' => '$model->name'
  822.         );
  823.     }
  824.    
  825.     /**
  826.      * Add the user to user groups.
  827.      *
  828.      * @param string[] $groupNames
  829.      * @param boolean $autoCreate
  830.      */
  831.     public function addToGroups(array $groupNames, $autoCreate=false){     
  832.         foreach($groupNames as $groupName){
  833.             $group = Group::model()->findByName($groupName);
  834.            
  835.             if(!$group && $autoCreate){
  836.                 $group = new Group();
  837.                 $group->name = $groupName;
  838.                 $group->save();
  839.             }
  840.            
  841.             if($group)
  842.                 $group->addUser($this->id);
  843.         }
  844.     }
  845.    
  846.     /**
  847.      *
  848.      * @param boolean $internal Use go to reset the password(internal) or use a website/webpage to reset the password
  849.      */
  850.     public function sendResetPasswordMail($siteTitle=false,$url=false,$fromName=false,$fromEmail=false){
  851.         $message = \GO\Base\Mail\Message::newInstance();
  852.         $message->setSubject(GO::t('lost_password_subject','base','lostpassword'));
  853.        
  854.         if(!$siteTitle)
  855.             $siteTitle=GO::config()->title;
  856.        
  857.         if(!$url){
  858.             $url=GO::url("auth/resetPassword", array("email"=>$this->email, "usertoken"=>$this->getSecurityToken()),false);
  859. //          $url = GO::config()->full_url."index.php".$url;    
  860.         }else{
  861.             $url=\GO\Base\Util\Http::addParamsToUrl($url, array("email"=>$this->email, "usertoken"=>$this->getSecurityToken()),false);
  862.         }
  863.         //$url="<a href='".$url."'>".$url."</a>";
  864.        
  865.         if(!$fromName)
  866.             $fromName = GO::config()->title;
  867.        
  868.         if(!$fromEmail){
  869.             $fromEmail = GO::config()->webmaster_email;
  870.         }
  871.  
  872.         $emailBody = GO::t('lost_password_body','base','lostpassword');
  873.         $emailBody = sprintf($emailBody,$this->contact->salutation, $siteTitle, $this->username, $url);
  874.        
  875.         $message->setBody($emailBody);
  876.         $message->addFrom($fromEmail,$fromName);
  877.         $message->addTo($this->email,$this->getName());
  878.  
  879.         \GO\Base\Mail\Mailer::newGoInstance()->send($message);
  880.     }
  881.    
  882.     /**
  883.      * Send an email to the newly registrated user when he just created an account.
  884.      * The mail should contain a welcome message and a username and password
  885.      * @param string $view path to a template for the email. If the view is not set or
  886.      * not found the default email body will be loaded from groupoffice
  887.      * @param string $title title of email
  888.      * @param array $_data this array will be explode to the view. if the view template
  889.      * is not found it will be ignored
  890.      * @return boolean true when email was send
  891.      */
  892.     public function sendRegistrationMail($view=null, $title=null, $_data=array(),$message=false) {
  893.        
  894.         $this->password=$this->_unencryptedPassword; //to non-crypted email password
  895.        
  896.         if(!empty($view) && is_readable($view.'.php')) {
  897.             $model = $this;
  898.             if(!empty($_data))
  899.                 extract($_data, EXTR_PREFIX_SAME, 'data');
  900.             ob_start();
  901.             ob_implicit_flush(false);
  902.  
  903.             require($view.'.php');
  904.  
  905.             $emailBody = ob_get_clean();
  906.             $type= 'text/html';
  907.         } else { //fallback to register_email_body when no view
  908.             $emailBody = GO::config()->get_setting('register_email_body') ?: GO::t('register_email_body', 'users');
  909.            
  910.             // Fixed problem with selecting the password.
  911.             $pwd = $this->getAttribute('password');
  912.             $emailBody = str_replace('{password}', $pwd, $emailBody);
  913.            
  914.             foreach ($this->getAttributes() as $key => $value) {
  915.                 if(is_string($value))
  916.                     $emailBody = str_replace('{' . $key . '}', $value, $emailBody);
  917.             }
  918.             $emailBody = str_replace('{url}', GO::config()->full_url, $emailBody);
  919.             $emailBody = str_replace('{title}', GO::config()->title, $emailBody);
  920.             $type= null;
  921.         }
  922.         if(!$title)
  923.             $title=GO::config()->get_setting('register_email_subject') ?: GO::t('register_email_subject', 'users');
  924.  
  925.         if(empty($title) || empty($emailBody))
  926.             return false;
  927.         if(!$message) {
  928.             $message = new Message();
  929.             $message->addFrom(GO::config()->webmaster_email,GO::config()->title);
  930.         }
  931.         $message->setSubject($title)
  932.             ->setBody($emailBody, $type)
  933.             ->addTo($this->email,$this->getName());
  934.  
  935.         return Mailer::newGoInstance()->send($message);
  936.     }
  937.    
  938.     /**
  939.      * Get a security hash that can be used for verification. For example with
  940.      * reset password function. The token will change when the user's password or
  941.      * email address changes and when the user logs in.
  942.      *
  943.      * @return string
  944.      */
  945.     public function getSecurityToken(){
  946.         return md5($this->getAttribute('password').$this->email.$this->ctime.$this->lastlogin);
  947.     }
  948.    
  949.    
  950.     protected function getCacheAttributes() {
  951.         return array(
  952.                 'name' => $this->name
  953.         );
  954.     }
  955. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement