예제 #1
0
 /**
  * Edit logged user password
  *
  * @access public
  * @param void
  * @return null
  */
 function edit_password()
 {
     $user = Contacts::findById(get_id());
     if (!($user instanceof Contact && $user->isUser()) || $user->getDisabled()) {
         flash_error(lang('user dnx'));
         ajx_current("empty");
         return;
     }
     // if
     if (!$user->canUpdateProfile(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     // if
     $redirect_to = array_var($_GET, 'redirect_to');
     if (trim($redirect_to) == '' || !is_valid_url($redirect_to)) {
         $redirect_to = $user->getCardUserUrl();
     }
     // if
     tpl_assign('redirect_to', null);
     $password_data = array_var($_POST, 'password');
     tpl_assign('user', $user);
     if (is_array($password_data)) {
         $old_password = array_var($password_data, 'old_password');
         $new_password = array_var($password_data, 'new_password');
         $new_password_again = array_var($password_data, 'new_password_again');
         try {
             if (!logged_user()->isAdminGroup()) {
                 if (trim($old_password) == '') {
                     throw new Error(lang('old password required'));
                 }
                 // if
                 if (!$user->isValidPassword($old_password)) {
                     throw new Error(lang('invalid old password'));
                 }
                 // if
             }
             // if
             if (trim($new_password) == '') {
                 throw new Error(lang('password value required'));
             }
             // if
             if ($new_password != $new_password_again) {
                 throw new Error(lang('passwords dont match'));
             }
             // if
             $user_password = new ContactPassword();
             $user_password->setContactId(get_id());
             $user_password->password_temp = $new_password;
             $user_password->setPasswordDate(DateTimeValueLib::now());
             $user_password->setPassword(cp_encrypt($new_password, $user_password->getPasswordDate()->getTimestamp()));
             $user_password->save();
             $user->setPassword($new_password);
             $user->setUpdatedOn(DateTimeValueLib::now());
             $user->save();
             if ($user->getId() == logged_user()->getId()) {
                 CompanyWebsite::instance()->logUserIn($user, Cookie::getValue("remember", 0));
             }
             ApplicationLogs::createLog($user, ApplicationLogs::ACTION_EDIT);
             flash_success(lang('success edit user', $user->getUsername()));
             ajx_current("back");
         } catch (Exception $e) {
             DB::rollback();
             ajx_current("empty");
             flash_error($e->getMessage());
         }
         // try
     }
     // if
 }
 function reset_password()
 {
     $tok = array_var($_GET, 't');
     $uid = array_var($_GET, 'uid');
     $type_notifier = array_var($_GET, 'type_notifier');
     if (!$tok || !$uid) {
         flash_error(lang('invalid parameters'));
         $this->redirectTo('access', 'login');
     }
     $user = Contacts::findById($uid);
     if (!($user instanceof Contact && $user->isUser()) || $user->getDisabled()) {
         flash_error(lang('user dnx'));
         $this->redirectTo('access', 'login');
     }
     $stok = user_config_option('reset_password', null, $user->getId());
     if (!$stok) {
         flash_error(lang('reset password expired', lang('forgot password')));
         $this->redirectTo('access', 'login');
     }
     $split = explode(";", $stok);
     if (count($split) < 2) {
         flash_error(lang('reset password expired', lang('forgot password')));
         $this->redirectTo('access', 'login');
     }
     $token = $split[0];
     $timestamp = $split[1];
     if ($timestamp < time()) {
         set_user_config_option('reset_password', '', $user->getId());
         flash_error(lang('reset password expired', lang('forgot password')));
         $this->redirectTo('access', 'login');
     }
     if ($token != $tok) {
         flash_error(lang('reset password expired', lang('forgot password')));
         $this->redirectTo('access', 'login');
     }
     tpl_assign('token', $token);
     tpl_assign('user', $user);
     tpl_assign('type_notifier', $type_notifier);
     $new_password = array_var($_POST, 'new_password');
     if ($new_password) {
         $repeat_password = array_var($_POST, 'repeat_password');
         if ($new_password != $repeat_password) {
             flash_error(lang('passwords dont match'));
             return;
         }
         try {
             $user_password = new ContactPassword();
             $user_password->setContactId($user->getId());
             $user_password->password_temp = $new_password;
             $user_password->setPasswordDate(DateTimeValueLib::now());
             $user_password->setPassword(cp_encrypt($new_password, $user_password->getPasswordDate()->getTimestamp()));
             $user_password->save();
             $user->setPassword($new_password);
             $user->setUpdatedOn(DateTimeValueLib::now());
             $user->save();
             set_user_config_option('reset_password', '', $user->getId());
             flash_success(lang('success reset password'));
             CompanyWebsite::instance()->logUserOut();
             $this->redirectTo('access', 'login');
         } catch (Exception $e) {
             flash_error($e->getMessage());
         }
     }
 }
예제 #3
0
function create_user($user_data, $permissionsString) {
    
	// try to find contact by some properties 
	$contact_id = array_var($user_data, "contact_id") ;
	$contact =  Contacts::instance()->findById($contact_id) ; 
	
	if (!is_valid_email(array_var($user_data, 'email'))) {
		throw new Exception(lang("email value is required"));
	}

	if (!$contact instanceof Contact) {
		// Create a new user
		$contact = new Contact();
		$contact->setUsername(array_var($user_data, 'username'));
		$contact->setDisplayName(array_var($user_data, 'display_name'));
		$contact->setCompanyId(array_var($user_data, 'company_id'));
		$contact->setUserType(array_var($user_data, 'type'));
		$contact->setTimezone(array_var($user_data, 'timezone'));
		$contact->setFirstname($contact->getObjectName() != "" ? $contact->getObjectName() : $contact->getUsername());
		$contact->setObjectName();
	} else {
		// Create user from contact
		$contact->setUserType(array_var($user_data, 'type'));
		if (array_var($user_data, 'company_id')) {
			$contact->setCompanyId(array_var($user_data, 'company_id'));
		}	
		$contact->setUsername(array_var($user_data, 'username'));
		$contact->setTimezone(array_var($user_data, 'timezone'));
	}
	$contact->save();
	if (is_valid_email(array_var($user_data, 'email'))) {
		$contact->addEmail(array_var($user_data, 'email'), 'personal', true);
	}
	
	
	//permissions
	$permission_group = new PermissionGroup();
	$permission_group->setName('User '.$contact->getId().' Personal');
	$permission_group->setContactId($contact->getId());
	$permission_group->setIsContext(false);
	$permission_group->setType("permission_groups");
	$permission_group->save();
	$contact->setPermissionGroupId($permission_group->getId());
	
	$contact_pg = new ContactPermissionGroup();
	$contact_pg->setContactId($contact->getId());
	$contact_pg->setPermissionGroupId($permission_group->getId());
	$contact_pg->save();

	if ( can_manage_security(logged_user()) ) {
		
		$sp = new SystemPermission();
		$rol_permissions=SystemPermissions::getRolePermissions(array_var($user_data, 'type'));
		foreach($rol_permissions as $pr){
			$sp->setPermission($pr);
		}
		$sp->setPermissionGroupId($permission_group->getId());

		$sp->setCanManageSecurity(array_var($user_data, 'can_manage_security'));
		$sp->setCanManageConfiguration(array_var($user_data, 'can_manage_configuration'));
		$sp->setCanManageTemplates(array_var($user_data, 'can_manage_templates'));
		$sp->setCanManageTime(array_var($user_data, 'can_manage_time'));
		$sp->setCanAddMailAccounts(array_var($user_data, 'can_add_mail_accounts'));
		$sp->setCanManageDimensions(array_var($user_data, 'can_manage_dimensions'));
		$sp->setCanManageDimensionMembers(array_var($user_data, 'can_manage_dimension_members'));
		$sp->setCanManageTasks(array_var($user_data, 'can_manage_tasks'));
		$sp->setCanTasksAssignee(array_var($user_data, 'can_task_assignee'));
		$sp->setCanManageBilling(array_var($user_data, 'can_manage_billing'));
		$sp->setCanViewBilling(array_var($user_data, 'can_view_billing'));
		
		Hook::fire('add_user_permissions', $sp, $other_permissions);
		if (!is_null($other_permissions) && is_array($other_permissions)) {
			foreach ($other_permissions as $k => $v) {
				$sp->setColumnValue($k, array_var($user_data, $k));
			}
		}
		$sp->save();
		
		if ($contact->isAdminGroup()) {
			// allow all un all dimensions if new user is admin
			$dimensions = Dimensions::findAll();
			$permissions = array();
			foreach ($dimensions as $dimension) {
				if ($dimension->getDefinesPermissions()) {
					$cdp = ContactDimensionPermissions::findOne(array("conditions" => "`permission_group_id` = ".$contact->getPermissionGroupId()." AND `dimension_id` = ".$dimension->getId()));
					if (!$cdp instanceof ContactDimensionPermission) {
						$cdp = new ContactDimensionPermission();
						$cdp->setPermissionGroupId($contact->getPermissionGroupId());
						$cdp->setContactDimensionId($dimension->getId());
					}
					$cdp->setPermissionType('allow all');
					$cdp->save();
					
					// contact member permisssion entries
					$members = $dimension->getAllMembers();
					foreach ($members as $member) {
						
						$ots = DimensionObjectTypeContents::getContentObjectTypeIds($dimension->getId(), $member->getObjectTypeId());
						$ots[]=$member->getObjectId();
						foreach ($ots as $ot) {
							$cmp = ContactMemberPermissions::findOne(array("conditions" => "`permission_group_id` = ".$contact->getPermissionGroupId()." AND `member_id` = ".$member->getId()." AND `object_type_id` = $ot"));
							if (!$cmp instanceof ContactMemberPermission) {
								$cmp = new ContactMemberPermission();
								$cmp->setPermissionGroupId($contact->getPermissionGroupId());
								$cmp->setMemberId($member->getId());
								$cmp->setObjectTypeId($ot);
							}
							$cmp->setCanWrite(1);
							$cmp->setCanDelete(1);
							$cmp->save();
							
							// Add persmissions to sharing table
							$perm = new stdClass();
							$perm->m = $member->getId();
							$perm->r= 1;
							$perm->w= 1;
							$perm->d= 1;
							$perm->o= $ot;
							$permissions[] = $perm ;
						}
					}
				}
			}
			
			if(count($permissions)){
				$sharingTableController = new SharingTableController();
				$sharingTableController->afterPermissionChanged($contact->getPermissionGroupId(), $permissions);
			}
			
		}
		
	}
	if(!isset($_POST['sys_perm'])){
		$rol_permissions=SystemPermissions::getRolePermissions(array_var($user_data, 'type'));
		$_POST['sys_perm']=array();
		foreach($rol_permissions as $pr){
			$_POST['sys_perm'][$pr]=1;
		}
		
	}
	if(!isset($_POST['mod_perm'])){
		$tabs_permissions=TabPanelPermissions::getRoleModules(array_var($user_data, 'type'));
		$_POST['mod_perm']=array();
		foreach($tabs_permissions as $pr){
			$_POST['mod_perm'][$pr]=1;
		}
	}
        
    $password = '';
	if (array_var($user_data, 'password_generator') == 'specify') {
		$perform_password_validation = true;
		// Validate input
		$password = array_var($user_data, 'password');
		if (trim($password) == '') {
			throw new Error(lang('password value required'));
		} // if
		if ($password <> array_var($user_data, 'password_a')) {
			throw new Error(lang('passwords dont match'));
		} // if
	} else {
		$user_data['password_generator'] = 'link';
		$perform_password_validation = false;
	}

	$contact->setPassword($password);   
	$contact->save();

	$user_password = new ContactPassword();
	$user_password->setContactId($contact->getId());
	$user_password->setPasswordDate(DateTimeValueLib::now());
	$user_password->setPassword(cp_encrypt($password, $user_password->getPasswordDate()->getTimestamp()));
	$user_password->password_temp = $password;
	$user_password->perform_validation = $perform_password_validation;
	$user_password->save();
        
	if (array_var($user_data, 'autodetect_time_zone', 1) == 1) {
		set_user_config_option('autodetect_time_zone', 1, $contact->getId());
	}
	
	/* create contact for this user*/

	ApplicationLogs::createLog($contact, ApplicationLogs::ACTION_ADD);

	// Set role permissions for active members
	$active_context = active_context();
	$sel_members = array();
	foreach ($active_context as $selection) {
		if ($selection instanceof Member) {
			$sel_members[] = $selection;
			$has_project_permissions = ContactMemberPermissions::instance()->count("permission_group_id = '".$contact->getPermissionGroupId()."' AND member_id = ".$selection->getId()) > 0;
			if (!$has_project_permissions) {
				RoleObjectTypePermissions::createDefaultUserPermissions($contact, $selection);
			}
		}
	}
	save_permissions($contact->getPermissionGroupId(), $contact->isGuest());
	
	Hook::fire('after_user_add', $contact, $null);
	
	// add user content object to associated members
	if (count($sel_members) > 0) {
		ObjectMembers::addObjectToMembers($contact->getId(), $sel_members);
		$contact->addToSharingTable();
	}
	
	// Send notification
	try {
		if (array_var($user_data, 'send_email_notification') && $contact->getEmailAddress()) {
                    
			if (array_var($user_data, 'password_generator', 'link') == 'link') {
				// Generate link password
				$user = Contacts::getByEmail(array_var($user_data, 'email'));
				$token = sha1(gen_id() . (defined('SEED') ? SEED : ''));
				$timestamp = time() + 60*60*24;
				set_user_config_option('reset_password', $token . ";" . $timestamp, $user->getId());
				Notifier::newUserAccountLinkPassword($contact, $password, $token);

			} else {
				Notifier::newUserAccount($contact, $password);
			}
			
		}
	} catch(Exception $e) {
		Logger::log($e->getTraceAsString());
	} // try
	return $contact;
}
예제 #4
0
function create_user($user_data, $permissionsString)
{
    $user = new User();
    $user->setUsername(array_var($user_data, 'username'));
    $user->setDisplayName(array_var($user_data, 'display_name'));
    $user->setEmail(array_var($user_data, 'email'));
    $user->setCompanyId(array_var($user_data, 'company_id'));
    $user->setType(array_var($user_data, 'type'));
    $user->setTimezone(array_var($user_data, 'timezone'));
    if (!logged_user() instanceof User || can_manage_security(logged_user())) {
        $user->setCanEditCompanyData(array_var($user_data, 'can_edit_company_data'));
        $user->setCanManageSecurity(array_var($user_data, 'can_manage_security'));
        $user->setCanManageWorkspaces(array_var($user_data, 'can_manage_workspaces'));
        $user->setCanManageConfiguration(array_var($user_data, 'can_manage_configuration'));
        $user->setCanManageContacts(array_var($user_data, 'can_manage_contacts'));
        $user->setCanManageTemplates(array_var($user_data, 'can_manage_templates'));
        $user->setCanManageReports(array_var($user_data, 'can_manage_reports'));
        $user->setCanManageTime(array_var($user_data, 'can_manage_time'));
        $user->setCanAddMailAccounts(array_var($user_data, 'can_add_mail_accounts'));
        $other_permissions = array();
        Hook::fire('add_user_permissions', $user, $other_permissions);
        foreach ($other_permissions as $k => $v) {
            $user->setColumnValue($k, array_var($user_data, $k));
        }
    }
    if (array_var($user_data, 'password_generator', 'random') == 'random') {
        // Generate random password
        $password = UserPasswords::generateRandomPassword();
    } else {
        // Validate input
        $password = array_var($user_data, 'password');
        if (trim($password) == '') {
            throw new Error(lang('password value required'));
        }
        // if
        if ($password != array_var($user_data, 'password_a')) {
            throw new Error(lang('passwords dont match'));
        }
        // if
    }
    // if
    $user->setPassword($password);
    $user->save();
    $user_password = new UserPassword();
    $user_password->setUserId($user->getId());
    $user_password->setPasswordDate(DateTimeValueLib::now());
    $user_password->setPassword(cp_encrypt($password, $user_password->getPasswordDate()->getTimestamp()));
    $user_password->password_temp = $password;
    $user_password->save();
    if (array_var($user_data, 'autodetect_time_zone', 1) == 1) {
        set_user_config_option('autodetect_time_zone', 1, $user->getId());
    }
    if ($user->getType() == 'admin') {
        if ($user->getCompanyId() != owner_company()->getId() || logged_user() instanceof User && !can_manage_security(logged_user())) {
            // external users can't be admins or logged user has no rights to create admins => set as Normal
            $user->setType('normal');
        } else {
            $user->setAsAdministrator(true);
        }
    }
    /* create contact for this user*/
    if (array_var($user_data, 'create_contact', 1)) {
        // if contact with same email exists take it, else create new
        $contact = Contacts::getByEmail($user->getEmail(), true);
        if (!$contact instanceof Contact) {
            $contact = new Contact();
            $contact->setEmail($user->getEmail());
        } else {
            if ($contact->isTrashed()) {
                $contact->untrash();
            }
        }
        $contact->setFirstname($user->getDisplayName());
        $contact->setUserId($user->getId());
        $contact->setTimezone($user->getTimezone());
        $contact->setCompanyId($user->getCompanyId());
        $contact->save();
    } else {
        $contact_id = array_var($user_data, 'contact_id');
        $contact = Contacts::findById($contact_id);
        if ($contact instanceof Contact) {
            // user created from a contact
            $contact->setUserId($user->getId());
            $contact->save();
        } else {
            // if contact with same email exists use it as user's contact, without changing it
            $contact = Contacts::getByEmail($user->getEmail(), true);
            if ($contact instanceof Contact) {
                $contact->setUserId($user->getId());
                if ($contact->isTrashed()) {
                    $contact->untrash();
                }
                $contact->save();
            }
        }
    }
    $contact = $user->getContact();
    if ($contact instanceof Contact) {
        // update contact data with data entered for this user
        $contact->setCompanyId($user->getCompanyId());
        if ($contact->getEmail() != $user->getEmail()) {
            // make user's email the contact's main email address
            if ($contact->getEmail2() == $user->getEmail()) {
                $contact->setEmail2($contact->getEmail());
            } else {
                if ($contact->getEmail3() == $user->getEmail()) {
                    $contact->setEmail3($contact->getEmail());
                } else {
                    if ($contact->getEmail2() == "") {
                        $contact->setEmail2($contact->getEmail());
                    } else {
                        $contact->setEmail3($contact->getEmail());
                    }
                }
            }
        }
        $contact->setEmail($user->getEmail());
        $contact->save();
    }
    if (!$user->isGuest()) {
        /* create personal project or assing the selected*/
        //if recived a personal project assing this
        //project as personal project for this user
        $new_project = null;
        $personalProjectId = array_var($user_data, 'personal_project', 0);
        $project = Projects::findById($personalProjectId);
        if (!$project instanceof Project) {
            $project = new Project();
            $wname = new_personal_project_name($user->getUsername());
            $project->setName($wname);
            $wdesc = Localization::instance()->lang(lang('personal workspace description'));
            if (!is_null($wdesc)) {
                $project->setDescription($wdesc);
            }
            $project->setCreatedById($user->getId());
            $project->save();
            //Save to set an ID number
            $project->setP1($project->getId());
            //Set ID number to the first project
            $project->save();
            $new_project = $project;
        }
        $user->setPersonalProjectId($project->getId());
        $project_user = new ProjectUser();
        $project_user->setProjectId($project->getId());
        $project_user->setUserId($user->getId());
        $project_user->setCreatedById($user->getId());
        $project_user->setAllPermissions(true);
        $project_user->save();
        /* end personal project */
    }
    $user->save();
    ApplicationLogs::createLog($user, null, ApplicationLogs::ACTION_ADD);
    //TODO - Make batch update of these permissions
    if ($permissionsString && $permissionsString != '') {
        $permissions = json_decode($permissionsString);
    } else {
        $permissions = null;
    }
    if (is_array($permissions) && (!logged_user() instanceof User || can_manage_security(logged_user()))) {
        foreach ($permissions as $perm) {
            if (ProjectUser::hasAnyPermissions($perm->pr, $perm->pc)) {
                if (!$personalProjectId || $personalProjectId != $perm->wsid) {
                    $relation = new ProjectUser();
                    $relation->setProjectId($perm->wsid);
                    $relation->setUserId($user->getId());
                    $relation->setCheckboxPermissions($perm->pc, $user->isGuest() ? false : true);
                    $relation->setRadioPermissions($perm->pr, $user->isGuest() ? false : true);
                    $relation->save();
                }
            }
        }
    }
    // if
    if ($new_project instanceof Project && logged_user() instanceof User && logged_user()->isProjectUser($new_project)) {
        evt_add("workspace added", array("id" => $new_project->getId(), "name" => $new_project->getName(), "color" => $new_project->getColor()));
    }
    // Send notification...
    try {
        if (array_var($user_data, 'send_email_notification')) {
            Notifier::newUserAccount($user, $password);
        }
        // if
    } catch (Exception $e) {
    }
    // try
    return $user;
}
예제 #5
0
function create_user($user_data, $permissionsString, $rp_permissions_data = array(), $save_permissions = true)
{
    // try to find contact by some properties
    $contact_id = array_var($user_data, "contact_id");
    $contact = Contacts::instance()->findById($contact_id);
    if (!is_valid_email(array_var($user_data, 'email'))) {
        throw new Exception(lang("email value is required"));
    }
    if (!$contact instanceof Contact) {
        // Create a new user
        $contact = new Contact();
        $contact->setUsername(array_var($user_data, 'username'));
        $contact->setDisplayName(array_var($user_data, 'display_name'));
        $contact->setCompanyId(array_var($user_data, 'company_id'));
        $contact->setUserType(array_var($user_data, 'type'));
        $contact->setTimezone(array_var($user_data, 'timezone'));
        $contact->setFirstname($contact->getObjectName() != "" ? $contact->getObjectName() : $contact->getUsername());
        $contact->setObjectName();
        $user_from_contact = false;
    } else {
        // Create user from contact
        $contact->setUserType(array_var($user_data, 'type'));
        if (array_var($user_data, 'company_id')) {
            $contact->setCompanyId(array_var($user_data, 'company_id'));
        }
        $contact->setUsername(array_var($user_data, 'username'));
        $contact->setTimezone(array_var($user_data, 'timezone'));
        $user_from_contact = true;
    }
    $contact->save();
    if (is_valid_email(array_var($user_data, 'email'))) {
        $user = Contacts::getByEmail(array_var($user_data, 'email'));
        if (!$user) {
            $contact->addEmail(array_var($user_data, 'email'), 'personal', true);
        }
    }
    //permissions
    $additional_name = "";
    $tmp_pg = PermissionGroups::findOne(array('conditions' => "`name`='User " . $contact->getId() . " Personal'"));
    if ($tmp_pg instanceof PermissionGroup) {
        $additional_name = "_" . gen_id();
    }
    $permission_group = new PermissionGroup();
    $permission_group->setName('User ' . $contact->getId() . $additional_name . ' Personal');
    $permission_group->setContactId($contact->getId());
    $permission_group->setIsContext(false);
    $permission_group->setType("permission_groups");
    $permission_group->save();
    $contact->setPermissionGroupId($permission_group->getId());
    $null = null;
    Hook::fire('on_create_user_perm_group', $permission_group, $null);
    $contact_pg = new ContactPermissionGroup();
    $contact_pg->setContactId($contact->getId());
    $contact_pg->setPermissionGroupId($permission_group->getId());
    $contact_pg->save();
    if (can_manage_security(logged_user())) {
        $sp = new SystemPermission();
        if (!$user_from_contact) {
            $rol_permissions = SystemPermissions::getRolePermissions(array_var($user_data, 'type'));
            if (is_array($rol_permissions)) {
                foreach ($rol_permissions as $pr) {
                    $sp->setPermission($pr);
                }
            }
        }
        $sp->setPermissionGroupId($permission_group->getId());
        if (isset($user_data['can_manage_security'])) {
            $sp->setCanManageSecurity(array_var($user_data, 'can_manage_security'));
        }
        if (isset($user_data['can_manage_configuration'])) {
            $sp->setCanManageConfiguration(array_var($user_data, 'can_manage_configuration'));
        }
        if (isset($user_data['can_manage_templates'])) {
            $sp->setCanManageTemplates(array_var($user_data, 'can_manage_templates'));
        }
        if (isset($user_data['can_manage_time'])) {
            $sp->setCanManageTime(array_var($user_data, 'can_manage_time'));
        }
        if (isset($user_data['can_add_mail_accounts'])) {
            $sp->setCanAddMailAccounts(array_var($user_data, 'can_add_mail_accounts'));
        }
        if (isset($user_data['can_manage_dimensions'])) {
            $sp->setCanManageDimensions(array_var($user_data, 'can_manage_dimensions'));
        }
        if (isset($user_data['can_manage_dimension_members'])) {
            $sp->setCanManageDimensionMembers(array_var($user_data, 'can_manage_dimension_members'));
        }
        if (isset($user_data['can_manage_tasks'])) {
            $sp->setCanManageTasks(array_var($user_data, 'can_manage_tasks'));
        }
        if (isset($user_data['can_task_assignee'])) {
            $sp->setCanTasksAssignee(array_var($user_data, 'can_task_assignee'));
        }
        if (isset($user_data['can_manage_billing'])) {
            $sp->setCanManageBilling(array_var($user_data, 'can_manage_billing'));
        }
        if (isset($user_data['can_view_billing'])) {
            $sp->setCanViewBilling(array_var($user_data, 'can_view_billing'));
        }
        if (isset($user_data['can_see_assigned_to_other_tasks'])) {
            $sp->setColumnValue('can_see_assigned_to_other_tasks', array_var($user_data, 'can_see_assigned_to_other_tasks'));
        }
        Hook::fire('add_user_permissions', $sp, $other_permissions);
        if (!is_null($other_permissions) && is_array($other_permissions)) {
            foreach ($other_permissions as $k => $v) {
                $sp->setColumnValue($k, array_var($user_data, $k));
            }
        }
        $sp->save();
        $permissions_sent = array_var($_POST, 'manual_permissions_setted') == 1;
        // give permissions for user if user type defined in "give_member_permissions_to_new_users" config option
        $allowed_user_type_ids = config_option('give_member_permissions_to_new_users');
        if ($contact->isAdministrator() || !$permissions_sent && in_array($contact->getUserType(), $allowed_user_type_ids)) {
            ini_set('memory_limit', '512M');
            $permissions = array();
            $default_permissions = RoleObjectTypePermissions::instance()->findAll(array('conditions' => 'role_id = ' . $contact->getUserType()));
            $dimensions = Dimensions::findAll();
            foreach ($dimensions as $dimension) {
                if ($dimension->getDefinesPermissions()) {
                    $cdp = ContactDimensionPermissions::findOne(array("conditions" => "`permission_group_id` = " . $contact->getPermissionGroupId() . " AND `dimension_id` = " . $dimension->getId()));
                    if (!$cdp instanceof ContactDimensionPermission) {
                        $cdp = new ContactDimensionPermission();
                        $cdp->setPermissionGroupId($contact->getPermissionGroupId());
                        $cdp->setContactDimensionId($dimension->getId());
                    }
                    $cdp->setPermissionType('check');
                    $cdp->save();
                    // contact member permisssion entries
                    $members = DB::executeAll('SELECT * FROM ' . TABLE_PREFIX . 'members WHERE dimension_id=' . $dimension->getId());
                    foreach ($members as $member) {
                        foreach ($default_permissions as $p) {
                            // Add persmissions to sharing table
                            $perm = new stdClass();
                            $perm->m = $member['id'];
                            $perm->r = 1;
                            $perm->w = $p->getCanWrite();
                            $perm->d = $p->getCanDelete();
                            $perm->o = $p->getObjectTypeId();
                            $permissions[] = $perm;
                        }
                    }
                }
            }
            $_POST['permissions'] = json_encode($permissions);
        } else {
            if ($permissions_sent) {
                $_POST['permissions'] = $permissionsString;
            } else {
                $_POST['permissions'] = "";
            }
        }
        if (config_option('let_users_create_objects_in_root') && ($contact->isAdminGroup() || $contact->isExecutive() || $contact->isManager())) {
            if ($permissions_sent) {
                foreach ($rp_permissions_data as $name => $value) {
                    $ot_id = substr($name, strrpos($name, '_') + 1);
                    $cmp = new ContactMemberPermission();
                    $cmp->setPermissionGroupId($permission_group->getId());
                    $cmp->setMemberId(0);
                    $cmp->setObjectTypeId($ot_id);
                    $cmp->setCanDelete($value >= 3);
                    $cmp->setCanWrite($value >= 2);
                    $cmp->save();
                }
            } else {
                $default_permissions = RoleObjectTypePermissions::instance()->findAll(array('conditions' => 'role_id = ' . $contact->getUserType()));
                foreach ($default_permissions as $p) {
                    $cmp = new ContactMemberPermission();
                    $cmp->setPermissionGroupId($permission_group->getId());
                    $cmp->setMemberId(0);
                    $cmp->setObjectTypeId($p->getObjectTypeId());
                    $cmp->setCanDelete($p->getCanDelete());
                    $cmp->setCanWrite($p->getCanWrite());
                    $cmp->save();
                }
            }
        }
    }
    if (!isset($_POST['sys_perm']) && !$user_from_contact) {
        $rol_permissions = SystemPermissions::getRolePermissions(array_var($user_data, 'type'));
        $_POST['sys_perm'] = array();
        if (is_array($rol_permissions)) {
            foreach ($rol_permissions as $pr) {
                $_POST['sys_perm'][$pr] = 1;
            }
        }
    }
    if (!isset($_POST['mod_perm']) && !$user_from_contact) {
        $tabs_permissions = TabPanelPermissions::getRoleModules(array_var($user_data, 'type'));
        $_POST['mod_perm'] = array();
        foreach ($tabs_permissions as $pr) {
            $_POST['mod_perm'][$pr] = 1;
        }
    }
    $password = '';
    if (array_var($user_data, 'password_generator') == 'specify') {
        $perform_password_validation = true;
        // Validate input
        $password = array_var($user_data, 'password');
        if (trim($password) == '') {
            throw new Error(lang('password value required'));
        }
        // if
        if ($password != array_var($user_data, 'password_a')) {
            throw new Error(lang('passwords dont match'));
        }
        // if
    } else {
        $user_data['password_generator'] = 'link';
        $perform_password_validation = false;
    }
    $contact->setPassword($password);
    $contact->save();
    $user_password = new ContactPassword();
    $user_password->setContactId($contact->getId());
    $user_password->setPasswordDate(DateTimeValueLib::now());
    $user_password->setPassword(cp_encrypt($password, $user_password->getPasswordDate()->getTimestamp()));
    $user_password->password_temp = $password;
    $user_password->perform_validation = $perform_password_validation;
    $user_password->save();
    if (array_var($user_data, 'autodetect_time_zone', 1) == 1) {
        set_user_config_option('autodetect_time_zone', 1, $contact->getId());
    }
    /* create contact for this user*/
    ApplicationLogs::createLog($contact, ApplicationLogs::ACTION_ADD);
    // Set role permissions for active members
    $active_context = active_context();
    $sel_members = array();
    if (is_array($active_context) && !$permissions_sent) {
        $tmp_perms = array();
        if ($_POST['permissions'] != "") {
            $tmp_perms = json_decode($_POST['permissions']);
        }
        foreach ($active_context as $selection) {
            if ($selection instanceof Member) {
                $sel_members[] = $selection;
                $has_project_permissions = ContactMemberPermissions::instance()->count("permission_group_id = '" . $contact->getPermissionGroupId() . "' AND member_id = " . $selection->getId()) > 0;
                if (!$has_project_permissions) {
                    $new_cmps = RoleObjectTypePermissions::createDefaultUserPermissions($contact, $selection);
                    foreach ($new_cmps as $new_cmp) {
                        $perm = new stdClass();
                        $perm->m = $new_cmp->getMemberId();
                        $perm->r = 1;
                        $perm->w = $new_cmp->getCanWrite();
                        $perm->d = $new_cmp->getCanDelete();
                        $perm->o = $new_cmp->getObjectTypeId();
                        $tmp_perms[] = $perm;
                    }
                }
            }
        }
        if (count($tmp_perms) > 0) {
            $_POST['permissions'] = json_encode($tmp_perms);
        }
    }
    if ($save_permissions) {
        //save_permissions($contact->getPermissionGroupId(), $contact->isGuest());
        save_user_permissions_background(logged_user(), $contact->getPermissionGroupId(), $contact->isGuest());
    }
    Hook::fire('after_user_add', $contact, $null);
    // add user content object to associated members
    if (count($sel_members) > 0) {
        ObjectMembers::addObjectToMembers($contact->getId(), $sel_members);
        $contact->addToSharingTable();
    }
    return $contact;
}
 function reset_password()
 {
     $tok = array_var($_GET, 't');
     $uid = array_var($_GET, 'uid');
     if (!$tok || !$uid) {
         flash_error(lang('invalid parameters'));
         $this->redirectTo('access', 'login');
     }
     $user = Users::findById($uid);
     if (!$user instanceof User) {
         flash_error(lang('user dnx'));
         $this->redirectTo('access', 'login');
     }
     $stok = user_config_option('reset_password', null, $user->getId());
     if (!$stok) {
         flash_error(lang('reset password expired', lang('forgot password')));
         $this->redirectTo('access', 'login');
     }
     $split = explode(";", $stok);
     if (count($split) < 2) {
         flash_error(lang('reset password expired', lang('forgot password')));
         $this->redirectTo('access', 'login');
     }
     $token = $split[0];
     $timestamp = $split[1];
     if ($timestamp < time()) {
         set_user_config_option('reset_password', '', $user->getId());
         flash_error(lang('reset password expired', lang('forgot password')));
         $this->redirectTo('access', 'login');
     }
     if ($token != $tok) {
         flash_error(lang('reset password expired', lang('forgot password')));
         $this->redirectTo('access', 'login');
     }
     tpl_assign('token', $token);
     tpl_assign('user', $user);
     $new_password = array_var($_POST, 'new_password');
     if ($new_password) {
         $repeat_password = array_var($_POST, 'repeat_password');
         if ($new_password != $repeat_password) {
             flash_error(lang('passwords dont match'));
             return;
         }
         $user_password = new UserPassword();
         $user_password->setUserId($user->getId());
         $user_password->password_temp = $new_password;
         $user_password->setPasswordDate(DateTimeValueLib::now());
         $user_password->setPassword(cp_encrypt($new_password, $user_password->getPasswordDate()->getTimestamp()));
         $user_password->save();
         $user->setPassword($new_password);
         $user->setUpdatedOn(DateTimeValueLib::now());
         $user->save();
         set_user_config_option('reset_password', '', $user->getId());
         flash_success(lang('success reset password'));
         $this->redirectTo('access', 'login');
     }
 }