static function createDefaultUserPermissionsAllDimension(Contact $user, $dimension_id, $remove_previous = true)
 {
     $role_id = $user->getUserType();
     $permission_group_id = $user->getPermissionGroupId();
     $dimension = Dimensions::getDimensionById($dimension_id);
     if (!$dimension instanceof Dimension || !$dimension->getDefinesPermissions()) {
         return;
     }
     try {
         DB::beginWork();
         $shtab_permissions = array();
         $new_permissions = array();
         $role_permissions = self::findAll(array('conditions' => 'role_id = ' . $role_id));
         $members = Members::findAll(array('conditions' => 'dimension_id = ' . $dimension_id));
         foreach ($members as $member) {
             $member_id = $member->getId();
             if ($remove_previous) {
                 ContactMemberPermissions::delete("permission_group_id = {$permission_group_id} AND member_id = {$member_id}");
             }
             foreach ($role_permissions as $role_perm) {
                 if ($member->canContainObject($role_perm->getObjectTypeId())) {
                     $cmp = new ContactMemberPermission();
                     $cmp->setPermissionGroupId($permission_group_id);
                     $cmp->setMemberId($member_id);
                     $cmp->setObjectTypeId($role_perm->getObjectTypeId());
                     $cmp->setCanDelete($role_perm->getCanDelete());
                     $cmp->setCanWrite($role_perm->getCanWrite());
                     $cmp->save();
                     $new_permissions[] = $cmp;
                     $perm = new stdClass();
                     $perm->m = $member_id;
                     $perm->r = 1;
                     $perm->w = $role_perm->getCanWrite();
                     $perm->d = $role_perm->getCanDelete();
                     $perm->o = $role_perm->getObjectTypeId();
                     $shtab_permissions[] = $perm;
                 }
             }
         }
         if (count($shtab_permissions)) {
             $stCtrl = new SharingTableController();
             $stCtrl->afterPermissionChanged($permission_group_id, $shtab_permissions);
         }
         DB::commit();
         return $new_permissions;
     } catch (Exception $e) {
         DB::rollback();
         throw $e;
     }
 }
 function saveMember($member_data, Member $member, $is_new = true)
 {
     try {
         DB::beginWork();
         if (!$is_new) {
             $old_parent = $member->getParentMemberId();
         }
         $member->setFromAttributes($member_data);
         /* @var $member Member */
         $object_type = ObjectTypes::findById($member->getObjectTypeId());
         if (!$object_type instanceof ObjectType) {
             throw new Exception(lang("you must select a valid object type"));
         }
         if ($member->getParentMemberId() == 0) {
             $dot = DimensionObjectTypes::findById(array('dimension_id' => $member->getDimensionId(), 'object_type_id' => $member->getObjectTypeId()));
             if (!$dot->getIsRoot()) {
                 throw new Exception(lang("member cannot be root", lang($object_type->getName())));
             }
             $member->setDepth(1);
         } else {
             $allowedParents = $this->getAssignableParents($member->getDimensionId(), $member->getObjectTypeId());
             if (!$is_new) {
                 $childrenIds = $member->getAllChildrenIds(true);
             }
             $hasValidParent = false;
             if ($member->getId() == $member->getParentMemberId() || !$is_new && in_array($member->getParentMemberId(), $childrenIds)) {
                 throw new Exception(lang("invalid parent member"));
             }
             foreach ($allowedParents as $parent) {
                 if ($parent['id'] == $member->getParentMemberId()) {
                     $hasValidParent = true;
                     break;
                 }
             }
             if (!$hasValidParent) {
                 throw new Exception(lang("invalid parent member"));
             }
             $parent = Members::findById($member->getParentMemberId());
             if ($parent instanceof Member) {
                 $member->setDepth($parent->getDepth() + 1);
             } else {
                 $member->setDepth(1);
             }
         }
         if ($object_type->getType() == 'dimension_object') {
             $handler_class = $object_type->getHandlerClass();
             if ($is_new || $member->getObjectId() == 0) {
                 eval('$dimension_object = ' . $handler_class . '::instance()->newDimensionObject();');
             } else {
                 $dimension_object = Objects::findObject($member->getObjectId());
             }
             if ($dimension_object) {
                 $dimension_object->modifyMemberValidations($member);
                 $dimension_obj_data = array_var($_POST, 'dim_obj');
                 if (!array_var($dimension_obj_data, 'name')) {
                     $dimension_obj_data['name'] = $member->getName();
                 }
                 eval('$fields = ' . $handler_class . '::getPublicColumns();');
                 foreach ($fields as $field) {
                     if (array_var($field, 'type') == DATA_TYPE_DATETIME) {
                         $dimension_obj_data[$field['col']] = getDateValue($dimension_obj_data[$field['col']]);
                     }
                 }
                 $member->save();
                 $dimension_object->setFromAttributes($dimension_obj_data, $member);
                 $dimension_object->save();
                 $member->setObjectId($dimension_object->getId());
                 $member->save();
                 Hook::fire("after_add_dimension_object_member", $member, $null);
             }
         } else {
             $member->save();
         }
         // Other dimensions member restrictions
         $restricted_members = array_var($_POST, 'restricted_members');
         if (is_array($restricted_members)) {
             MemberRestrictions::clearRestrictions($member->getId());
             foreach ($restricted_members as $dim_id => $dim_members) {
                 foreach ($dim_members as $mem_id => $member_restrictions) {
                     $restricted = isset($member_restrictions['restricted']);
                     if ($restricted) {
                         $order_num = array_var($member_restrictions, 'order_num', 0);
                         $member_restriction = new MemberRestriction();
                         $member_restriction->setMemberId($member->getId());
                         $member_restriction->setRestrictedMemberId($mem_id);
                         $member_restriction->setOrder($order_num);
                         $member_restriction->save();
                     }
                 }
             }
         }
         // Save member property members (also check for required associations)
         if (array_var($_POST, 'save_properties')) {
             $required_association_ids = DimensionMemberAssociations::getRequiredAssociatations($member->getDimensionId(), $member->getObjectTypeId(), true);
             $missing_req_association_ids = array_fill_keys($required_association_ids, true);
             // if keeps record change is_active, if not delete record
             $old_properties = MemberPropertyMembers::getAssociatedPropertiesForMember($member->getId());
             foreach ($old_properties as $property) {
                 $association = DimensionMemberAssociations::findById($property->getAssociationId());
                 if (!$association->getKeepsRecord()) {
                     $property->delete();
                 }
             }
             $new_properties = array();
             $associated_members = array_var($_POST, 'associated_members', array());
             foreach ($associated_members as $prop_member_id => $assoc_id) {
                 $active_association = null;
                 if (isset($missing_req_association_ids[$assoc_id])) {
                     $missing_req_association_ids[$assoc_id] = false;
                 }
                 $conditions = "`association_id` = {$assoc_id} AND `member_id` = " . $member->getId() . " AND `is_active` = 1";
                 $active_associations = MemberPropertyMembers::find(array('conditions' => $conditions));
                 if (count($active_associations) > 0) {
                     $active_association = $active_associations[0];
                 }
                 $association = DimensionMemberAssociations::findById($assoc_id);
                 if ($active_association instanceof MemberPropertyMember) {
                     if ($active_association->getPropertyMemberId() != $prop_member_id) {
                         if ($association->getKeepsRecord()) {
                             $active_association->setIsActive(false);
                             $active_association->save();
                         }
                         // save current association
                         $mpm = new MemberPropertyMember();
                         $mpm->setAssociationId($assoc_id);
                         $mpm->setMemberId($member->getId());
                         $mpm->setPropertyMemberId($prop_member_id);
                         $mpm->setIsActive(true);
                         $mpm->save();
                         $new_properties[] = $mpm;
                     }
                 } else {
                     // save current association
                     $mpm = new MemberPropertyMember();
                     $mpm->setAssociationId($assoc_id);
                     $mpm->setMemberId($member->getId());
                     $mpm->setPropertyMemberId($prop_member_id);
                     $mpm->setIsActive(true);
                     $mpm->save();
                     $new_properties[] = $mpm;
                 }
             }
             $missing_names = array();
             $missing_count = 0;
             foreach ($missing_req_association_ids as $assoc => $missing) {
                 $assoc_instance = DimensionMemberAssociations::findById($assoc);
                 if ($assoc_instance instanceof DimensionMemberAssociation) {
                     $assoc_dim = Dimensions::getDimensionById($assoc_instance->getAssociatedDimensionMemberAssociationId());
                     if ($assoc_dim instanceof Dimension) {
                         if (!in_array($assoc_dim->getName(), $missing_names)) {
                             $missing_names[] = $assoc_dim->getName();
                         }
                     }
                 }
                 if ($missing) {
                     $missing_count++;
                 }
             }
             if ($missing_count > 0) {
                 throw new Exception(lang("missing required associations", implode(", ", $missing_names)));
             }
             $args = array($member, $old_properties, $new_properties);
             Hook::fire('edit_member_properties', $args, $ret);
         }
         if ($is_new) {
             // set all permissions for the creator
             $dimension = $member->getDimension();
             $allowed_object_types = array();
             $dim_obj_types = $dimension->getAllowedObjectTypeContents();
             foreach ($dim_obj_types as $dim_obj_type) {
                 // To draw a row for each object type of the dimension
                 if (!in_array($dim_obj_type->getContentObjectTypeId(), $allowed_object_types) && $dim_obj_type->getDimensionObjectTypeId() == $member->getObjectTypeId()) {
                     $allowed_object_types[] = $dim_obj_type->getContentObjectTypeId();
                 }
             }
             $allowed_object_types[] = $object_type->getId();
             foreach ($allowed_object_types as $ot) {
                 $cmp = ContactMemberPermissions::findOne(array('conditions' => 'permission_group_id = ' . logged_user()->getPermissionGroupId() . ' AND member_id = ' . $member->getId() . ' AND object_type_id = ' . $ot));
                 if (!$cmp instanceof ContactMemberPermission) {
                     $cmp = new ContactMemberPermission();
                     $cmp->setPermissionGroupId(logged_user()->getPermissionGroupId());
                     $cmp->setMemberId($member->getId());
                     $cmp->setObjectTypeId($ot);
                 }
                 $cmp->setCanWrite(1);
                 $cmp->setCanDelete(1);
                 $cmp->save();
             }
             // set all permissions for permission groups that has allow all in the dimension
             $permission_groups = ContactDimensionPermissions::findAll(array("conditions" => array("`dimension_id` = ? AND `permission_type` = 'allow all'", $dimension->getId())));
             if (is_array($permission_groups)) {
                 foreach ($permission_groups as $pg) {
                     foreach ($allowed_object_types as $ot) {
                         $cmp = ContactMemberPermissions::findById(array('permission_group_id' => $pg->getPermissionGroupId(), 'member_id' => $member->getId(), 'object_type_id' => $ot));
                         if (!$cmp instanceof ContactMemberPermission) {
                             $cmp = new ContactMemberPermission();
                             $cmp->setPermissionGroupId($pg->getPermissionGroupId());
                             $cmp->setMemberId($member->getId());
                             $cmp->setObjectTypeId($ot);
                         }
                         $cmp->setCanWrite(1);
                         $cmp->setCanDelete(1);
                         $cmp->save();
                     }
                 }
             }
             // Inherit permissions from parent node, if they are not already set
             if ($member->getDepth() && $member->getParentMember()) {
                 $parentNodeId = $member->getParentMember()->getId();
                 $condition = "member_id = {$parentNodeId}";
                 foreach (ContactMemberPermissions::instance()->findAll(array("conditions" => $condition)) as $parentPermission) {
                     /* @var $parentPermission ContactMemberPermission */
                     $g = $parentPermission->getPermissionGroupId();
                     $t = $parentPermission->getObjectTypeId();
                     $w = $parentPermission->getCanWrite();
                     $d = $parentPermission->getCanDelete();
                     $existsCondition = "member_id = " . $member->getId() . " AND permission_group_id= {$g} AND object_type_id = {$t}";
                     if (!ContactMemberPermissions::instance()->count(array("conditions" => $existsCondition))) {
                         $newPermission = new ContactMemberPermission();
                         $newPermission->setPermissionGroupId($g);
                         $newPermission->setObjectTypeId($t);
                         $newPermission->setCanWrite($w);
                         $newPermission->setCanDelete($d);
                         $newPermission->setMemberId($member->getId());
                         $newPermission->save();
                     }
                 }
             }
             // Fill sharing table if is a dimension object (after permission creation);
             if (isset($dimension_object) && $dimension_object instanceof ContentDataObject) {
                 $dimension_object->addToSharingTable();
             }
         } else {
             // if parent changed rebuild object_members for every object in this member
             if ($old_parent != $member->getParentMemberId()) {
                 $sql = "SELECT om.object_id FROM " . TABLE_PREFIX . "object_members om WHERE om.member_id=" . $member->getId();
                 $object_ids = DB::executeAll($sql);
                 if (!is_array($object_ids)) {
                     $object_ids = array();
                 }
                 foreach ($object_ids as $row) {
                     $content_object = Objects::findObject($row['object_id']);
                     if (!$content_object instanceof ContentDataObject) {
                         continue;
                     }
                     $parent_ids = array();
                     if ($old_parent > 0) {
                         $all_parents = Members::findById($old_parent)->getAllParentMembersInHierarchy(true);
                         foreach ($all_parents as $p) {
                             $parent_ids[] = $p->getId();
                         }
                         if (count($parent_ids) > 0) {
                             DB::execute("DELETE FROM " . TABLE_PREFIX . "object_members WHERE object_id=" . $content_object->getId() . " AND member_id IN (" . implode(",", $parent_ids) . ")");
                         }
                     }
                     $content_object->addToMembers(array($member));
                     $content_object->addToSharingTable();
                 }
             }
         }
         DB::commit();
         flash_success(lang('success save member', lang(ObjectTypes::findById($member->getObjectTypeId())->getName()), $member->getName()));
         ajx_current("back");
         // Add od to array on new members
         if ($is_new) {
             $member_data['member_id'] = $member->getId();
         }
         evt_add("after member save", $member_data);
         return $member;
     } catch (Exception $e) {
         DB::rollback();
         flash_error($e->getMessage());
         ajx_current("empty");
     }
 }
 /**
  * Finish the installation - create owner company and administrator
  *
  * @param void
  * @return null
  */
 function complete_installation()
 {
     if (Contacts::getOwnerCompany() instanceof Contact) {
         die('Owner company already exists');
         // Somebody is trying to access this method even if the user already exists
     }
     // if
     $form_data = array_var($_POST, 'form');
     tpl_assign('form_data', $form_data);
     if (array_var($form_data, 'submited') == 'submited') {
         try {
             $admin_password = trim(array_var($form_data, 'admin_password'));
             $admin_password_a = trim(array_var($form_data, 'admin_password_a'));
             if (trim($admin_password) == '') {
                 throw new Error(lang('password value required'));
             }
             // if
             if ($admin_password != $admin_password_a) {
                 throw new Error(lang('passwords dont match'));
             }
             // if
             DB::beginWork();
             Contacts::delete();
             // clear users table
             // Create a company
             $company = new Contact();
             $company->setFirstName(array_var($form_data, 'company_name'));
             $company->setObjectName();
             $company->setIsCompany(true);
             $company->save();
             // Init default colors
             set_config_option('brand_colors_head_back', "424242");
             set_config_option('brand_colors_tabs_back', "e7e7e7");
             set_config_option('brand_colors_head_font', "FFFFFF");
             set_config_option('brand_colors_tabs_font', "333333");
             // Create the administrator user
             $administrator = new Contact();
             $pergroup = PermissionGroups::findOne(array('conditions' => "`name`='Super Administrator'"));
             $administrator->setUserType($pergroup->getId());
             $administrator->setCompanyId($company->getId());
             $administrator->setUsername(array_var($form_data, 'admin_username'));
             $administrator->setPassword($admin_password);
             $administrator->setFirstname(array_var($form_data, 'admin_username'));
             $administrator->setObjectName();
             $administrator->save();
             $user_password = new ContactPassword();
             $user_password->setContactId($administrator->getId());
             $user_password->password_temp = $admin_password;
             $user_password->setPasswordDate(DateTimeValueLib::now());
             $user_password->setPassword(cp_encrypt($admin_password, $user_password->getPasswordDate()->getTimestamp()));
             $user_password->save();
             //Add email after save because is needed.
             $administrator->addEmail(array_var($form_data, 'admin_email'), 'personal', true);
             //permissions
             $permission_group = new PermissionGroup();
             $permission_group->setName('Account Owner');
             $permission_group->setContactId($administrator->getId());
             $permission_group->setIsContext(false);
             $permission_group->setType("permission_groups");
             $permission_group->save();
             $administrator->setPermissionGroupId($permission_group->getId());
             $administrator->save();
             $company->setCreatedById($administrator->getId());
             $company->setUpdatedById($administrator->getId());
             $company->save();
             $contact_pg = new ContactPermissionGroup();
             $contact_pg->setContactId($administrator->getId());
             $contact_pg->setPermissionGroupId($permission_group->getId());
             $contact_pg->save();
             // tab panel permissions
             $panels = TabPanels::getEnabled();
             foreach ($panels as $panel) {
                 $tpp = new TabPanelPermission();
                 $tpp->setPermissionGroupId($administrator->getPermissionGroupId());
                 $tpp->setTabPanelId($panel->getId());
                 $tpp->save();
             }
             // dimension permissions
             $dimensions = Dimensions::findAll();
             foreach ($dimensions as $dimension) {
                 if ($dimension->getDefinesPermissions()) {
                     $cdp = ContactDimensionPermissions::findOne(array("conditions" => "`permission_group_id` = " . $administrator->getPermissionGroupId() . " AND `dimension_id` = " . $dimension->getId()));
                     if (!$cdp instanceof ContactDimensionPermission) {
                         $cdp = new ContactDimensionPermission();
                         $cdp->setPermissionGroupId($administrator->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();
                             if (!$cmp instanceof ContactMemberPermission) {
                                 $cmp = new ContactMemberPermission(array("conditions" => "`permission_group_id` = " . $administrator->getPermissionGroupId() . " AND `member_id` = " . $member->getId() . " AND `object_type_id` = {$ot}"));
                                 $cmp->setPermissionGroupId($administrator->getPermissionGroupId());
                                 $cmp->setMemberId($member->getId());
                                 $cmp->setObjectTypeId($ot);
                             }
                             $cmp->setCanWrite(1);
                             $cmp->setCanDelete(1);
                             $cmp->save();
                         }
                     }
                 }
             }
             // system permissions
             $sp = new SystemPermission();
             $sp->setPermissionGroupId($administrator->getPermissionGroupId());
             $sp->setAllPermissions(true);
             $sp->save();
             // root permissions
             DB::executeAll("\r\n\t\t\t\tINSERT INTO " . TABLE_PREFIX . "contact_member_permissions (permission_group_id, member_id, object_type_id, can_delete, can_write)\r\n\t\t\t\t  SELECT " . $administrator->getPermissionGroupId() . ", 0, rtp.object_type_id, rtp.can_delete, rtp.can_write FROM " . TABLE_PREFIX . "role_object_type_permissions rtp \r\n\t\t\t\t  WHERE rtp.object_type_id NOT IN (SELECT id FROM " . TABLE_PREFIX . "object_types WHERE name IN ('mail','template','file_revision')) AND rtp.role_id in (\r\n\t\t\t\t    SELECT pg.id FROM " . TABLE_PREFIX . "permission_groups pg WHERE pg.type='roles' AND pg.name IN ('Super Administrator','Administrator','Manager','Executive')\r\n\t\t\t\t  )\r\n\t\t\t\tON DUPLICATE KEY UPDATE member_id=0;");
             Hook::fire('after_user_add', $administrator, $null);
             DB::commit();
             $this->redirectTo('access', 'login');
         } catch (Exception $e) {
             tpl_assign('error', $e);
             DB::rollback();
         }
         // try
     }
     // if
 }
 /**
  * Enter description here ...
  * @param Contact $contact
  * @param array of ObjectType $types
  * @param array of int  $members
  */
 function grantAllPermissions(Contact $contact, $members)
 {
     if ($contact->getUserType() > 0 && count($members)) {
         $userType = $contact->getUserTypeName();
         $permissions = array();
         // TO fill sharing table
         $gid = $contact->getPermissionGroupId();
         foreach ($members as $member_id) {
             //new
             $member = Members::findById($member_id);
             $dimension = $member->getDimension();
             $types = array();
             $member_types = DimensionObjectTypeContents::getContentObjectTypeIds($dimension->getId(), $member->getObjectTypeId());
             if (count($member_types)) {
                 switch ($userType) {
                     case 'Super Administrator':
                     case 'Administrator':
                     case 'Manager':
                     case 'Executive':
                         $types = $member_types;
                         break;
                     case 'Collaborator Customer':
                     case 'Non-Exec Director':
                         foreach (ObjectTypes::findAll(array("conditions" => " name NOT IN ('mail') ")) as $type) {
                             //TODO This sucks
                             $types[] = $type->getId();
                         }
                         break;
                     case 'Internal Collaborator':
                     case 'External Collaborator':
                         foreach (ObjectTypes::findAll(array("conditions" => " name NOT IN ('mail','contact', 'report') ")) as $type) {
                             //TODO This sucks
                             $types[] = $type->getId();
                         }
                         break;
                     case 'Guest Customer':
                         foreach (ObjectTypes::findAll(array("conditions" => " name IN ('message', 'weblink', 'event', 'file') ")) as $type) {
                             //TODO This sucks
                             $types[] = $type->getId();
                         }
                         break;
                     case 'Guest':
                         foreach (ObjectTypes::findAll(array("conditions" => " name IN ('message', 'weblink', 'event') ")) as $type) {
                             //TODO This sucks
                             $types[] = $type->getId();
                         }
                         break;
                 }
             }
             foreach ($types as $type_id) {
                 if (!ContactMemberPermissions::instance()->findOne(array("conditions" => "permission_group_id = {$gid}\tAND \n\t\t\t\t\t\t\tmember_id = {$member_id} AND \n\t\t\t\t\t\t\tobject_type_id = {$type_id}"))) {
                     $cmp = new ContactMemberPermission();
                     $cmp->setPermissionGroupId($gid);
                     $cmp->setMemberId($member_id);
                     $cmp->setObjectTypeId($type_id);
                     if ($userType != "Guest" && $userType != "Guest Customer") {
                         $cmp->setCanWrite(1);
                         $cmp->setCanDelete(1);
                     } else {
                         $cmp->setCanWrite(0);
                         $cmp->setCanDelete(0);
                     }
                     $cmp->save();
                     $perm = new stdClass();
                     $perm->m = $member_id;
                     $perm->r = 1;
                     $perm->w = 1;
                     $perm->d = 1;
                     $perm->o = $type_id;
                     $permissions[] = $perm;
                 }
             }
         }
         if (count($permissions)) {
             $stCtrl = new SharingTableController();
             $stCtrl->afterPermissionChanged($contact->getPermissionGroupId(), $permissions);
         }
     }
 }
Example #5
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;
}
	/**
	 * Finish the installation - create owner company and administrator
	 *
	 * @param void
	 * @return null
	 */
	function complete_installation() {
		
		if(Contacts::getOwnerCompany() instanceof Contact) {
			die('Owner company already exists'); // Somebody is trying to access this method even if the user already exists
		} // if

		$form_data = array_var($_POST, 'form');
		tpl_assign('form_data', $form_data);

		if(array_var($form_data, 'submited') == 'submited') {
			try {
				$admin_password = trim(array_var($form_data, 'admin_password'));
				$admin_password_a = trim(array_var($form_data, 'admin_password_a'));

				if(trim($admin_password) == '') {
					throw new Error(lang('password value required'));
				} // if

				if($admin_password <> $admin_password_a) {
					throw new Error(lang('passwords dont match'));
				} // if

				DB::beginWork();

				Contacts::delete(); // clear users table

				// Create a company
				$company = new Contact();
				$company->setFirstName(array_var($form_data, 'company_name'));
				$company->setObjectName();
				$company->setIsCompany(true);
				$company->save();
				
				// Init default colors
				set_config_option('brand_colors_head_back', "000000");
				set_config_option('brand_colors_tabs_back', "14780e");
				set_config_option('brand_colors_head_font', "ffffff");
				set_config_option('brand_colors_tabs_font', "ffffff");

				// Create the administrator user
				$administrator = new Contact();
				$pergroup = PermissionGroups::findOne(array('conditions'=>"`name`='Super Administrator'"));
				$administrator->setUserType($pergroup->getId());
				$administrator->setCompanyId($company->getId());
				$administrator->setUsername(array_var($form_data, 'admin_username'));
				
				
				$administrator->setPassword($admin_password);
				$administrator->setFirstname(array_var($form_data, 'admin_username'));
				$administrator->setObjectName();
				$administrator->save();
				
				$user_password = new ContactPassword();
				$user_password->setContactId($administrator->getId());
				$user_password->password_temp = $admin_password;
				$user_password->setPasswordDate(DateTimeValueLib::now());
				$user_password->setPassword(cp_encrypt($admin_password, $user_password->getPasswordDate()->getTimestamp()));
				$user_password->save();
				
				//Add email after save because is needed. 
				$administrator->addEmail(array_var($form_data, 'admin_email'), 'personal', true);
				
				//permissions
				$permission_group = new PermissionGroup();
				$permission_group->setName('Account Owner');
				$permission_group->setContactId($administrator->getId());
				$permission_group->setIsContext(false);
				$permission_group->setType("permission_groups");
				$permission_group->save();
				
				$administrator->setPermissionGroupId($permission_group->getId());
				$administrator->save();
				
				$company->setCreatedById($administrator->getId());
				$company->setUpdatedById($administrator->getId());
				$company->save();
				
				$contact_pg = new ContactPermissionGroup();
				$contact_pg->setContactId($administrator->getId());
				$contact_pg->setPermissionGroupId($permission_group->getId());
				$contact_pg->save();
				
				// tab panel permissions
				$panels = TabPanels::getEnabled();
				foreach ($panels as $panel) {
					$tpp = new TabPanelPermission();
					$tpp->setPermissionGroupId($administrator->getPermissionGroupId());
					$tpp->setTabPanelId($panel->getId());
					$tpp->save();
				}
				
				// dimension permissions
				$dimensions = Dimensions::findAll();
				foreach ($dimensions as $dimension) {
					if ($dimension->getDefinesPermissions()) {
						$cdp = ContactDimensionPermissions::findOne(array("conditions" => "`permission_group_id` = ".$administrator->getPermissionGroupId()." AND `dimension_id` = ".$dimension->getId()));
						if (!$cdp instanceof ContactDimensionPermission) {
							$cdp = new ContactDimensionPermission();
							$cdp->setPermissionGroupId($administrator->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();
								if (!$cmp instanceof ContactMemberPermission) {
									$cmp = new ContactMemberPermission(array("conditions" => "`permission_group_id` = ".$administrator->getPermissionGroupId()." AND `member_id` = ".$member->getId()." AND `object_type_id` = $ot"));
									$cmp->setPermissionGroupId($administrator->getPermissionGroupId());
									$cmp->setMemberId($member->getId());
									$cmp->setObjectTypeId($ot);
								}
								$cmp->setCanWrite(1);
								$cmp->setCanDelete(1);
								$cmp->save();
							}
						}
					}
				}
				
				// system permissions
				$sp = new SystemPermission();
				$sp->setPermissionGroupId($administrator->getPermissionGroupId());
				$sp->setAllPermissions(true);
				$sp->save();
				
				Hook::fire('after_user_add', $administrator, $null);
				
				DB::commit();

				$this->redirectTo('access', 'login');
			} catch(Exception $e) {
				tpl_assign('error', $e);
				DB::rollback();
			} // try
		} // if
	} // complete_installation
Example #7
0
function save_member_permissions($member)
{
    $permissionsString = array_var($_POST, 'permissions');
    if ($permissionsString && $permissionsString != '') {
        $permissions = json_decode($permissionsString);
    }
    $sharingTablecontroller = new SharingTableController();
    $changed_pgs = array();
    if (isset($permissions) && is_array($permissions)) {
        $allowed_pg_ids = array();
        foreach ($permissions as &$perm) {
            $cmp = ContactMemberPermissions::findById(array('permission_group_id' => $perm->pg, 'member_id' => $member->getId(), 'object_type_id' => $perm->o));
            if (!$cmp instanceof ContactMemberPermission) {
                $cmp = new ContactMemberPermission();
                $cmp->setPermissionGroupId($perm->pg);
                $cmp->setMemberId($member->getId());
                $cmp->setObjectTypeId($perm->o);
            }
            $cmp->setCanWrite($perm->w);
            $cmp->setCanDelete($perm->d);
            if ($perm->r) {
                $allowed_pg_ids[$perm->pg] = array();
                if (isset($allowed_pg_ids[$perm->pg]['w'])) {
                    if (!$allowed_pg_ids[$perm->pg]['w']) {
                        $allowed_pg_ids[$perm->pg]['w'] = $perm->w;
                    }
                } else {
                    $allowed_pg_ids[$perm->pg]['w'] = $perm->w;
                }
                if (isset($allowed_pg_ids[$perm->pg]['d'])) {
                    if (!$allowed_pg_ids[$perm->pg]['d']) {
                        $allowed_pg_ids[$perm->pg]['d'] = $perm->d;
                    }
                } else {
                    $allowed_pg_ids[$perm->pg]['d'] = $perm->d;
                }
                $cmp->save();
            } else {
                $cmp->delete();
            }
            $perm->m = $member->getId();
            $changed_pgs[] = $perm->pg;
        }
        foreach ($changed_pgs as $pg_id) {
            $sharingTablecontroller->afterPermissionChanged($pg_id, $permissions);
        }
        foreach ($allowed_pg_ids as $key => $mids) {
            $root_cmp = ContactMemberPermissions::findById(array('permission_group_id' => $key, 'member_id' => $member->getId(), 'object_type_id' => $member->getObjectTypeId()));
            if (!$root_cmp instanceof ContactMemberPermission) {
                $root_cmp = new ContactMemberPermission();
                $root_cmp->setPermissionGroupId($key);
                $root_cmp->setMemberId($member->getId());
                $root_cmp->setObjectTypeId($member->getObjectTypeId());
            }
            $root_cmp->setCanWrite($mids['w'] == true ? 1 : 0);
            $root_cmp->setCanDelete($mids['d'] == true ? 1 : 0);
            $root_cmp->save();
        }
    }
    // check the status of the dimension to set 'allow_all', 'deny_all' or 'check'
    $dimension = $member->getDimension();
    $mem_ids = $dimension->getAllMembers(true);
    if (count($mem_ids) == 0) {
        $mem_ids[] = 0;
    }
    foreach ($changed_pgs as $pg_id) {
        $count = ContactMemberPermissions::count(array('conditions' => "`permission_group_id`={$pg_id} AND `member_id` IN (" . implode(",", $mem_ids) . ") AND `can_delete` = 0"));
        if ($count > 0) {
            $dimension->setContactDimensionPermission($pg_id, 'check');
        } else {
            $count = ContactMemberPermissions::count(array('conditions' => "`permission_group_id`={$pg_id} AND `member_id` IN (" . implode(",", $mem_ids) . ")"));
            if ($count == 0) {
                $dimension->setContactDimensionPermission($pg_id, 'deny all');
            } else {
                $allow_all = true;
                $dim_obj_types = $dimension->getAllowedObjectTypeContents();
                $members = Members::findAll("`id` IN (" . implode(",", $mem_ids) . ")");
                foreach ($dim_obj_types as $dim_obj_type) {
                    $mem_ids_for_ot = array();
                    foreach ($members as $member) {
                        if ($dim_obj_type->getDimensionObjectTypeId() == $member->getObjectTypeId()) {
                            $mem_ids_for_ot[] = $member->getId();
                        }
                    }
                    if (count($mem_ids_for_ot) == 0) {
                        $mem_ids_for_ot[] = 0;
                    }
                    $count = ContactMemberPermissions::count(array('conditions' => "`permission_group_id`={$pg_id} AND \n\t\t\t\t\t\t`object_type_id` = " . $dim_obj_type->getContentObjectTypeId() . " AND `can_delete` = 1 AND `member_id` IN (" . implode(",", $mem_ids_for_ot) . ")"));
                    if ($count != count($mem_ids_for_ot)) {
                        $allow_all = false;
                        break;
                    }
                }
                if ($allow_all) {
                    $dimension->setContactDimensionPermission($pg_id, 'allow all');
                } else {
                    $dimension->setContactDimensionPermission($pg_id, 'check');
                }
            }
        }
    }
}
	static function createDefaultUserPermissionsAllDimension(Contact $user, $dimension_id, $remove_previous = true) {
		$role_id = $user->getUserType();
		$permission_group_id = $user->getPermissionGroupId();
		
		$dimension = Dimensions::getDimensionById($dimension_id);
		if (!$dimension instanceof Dimension || !$dimension->getDefinesPermissions()) return;
		
		try {
			
			$shtab_permissions = array();
			$new_permissions = array();
			$role_permissions = self::findAll(array('conditions' => 'role_id = '.$role_id));
			$members = Members::findAll(array('conditions' => 'dimension_id = '.$dimension_id));
			
			foreach ($members as $member) {
				$member_id = $member->getId();
				if ($remove_previous) {
					ContactMemberPermissions::delete("permission_group_id = $permission_group_id AND member_id = $member_id");
				}
				
				foreach ($role_permissions as $role_perm) {
					if ($member->canContainObject($role_perm->getObjectTypeId())) {
						$cmp = new ContactMemberPermission();
						$cmp->setPermissionGroupId($permission_group_id);
						$cmp->setMemberId($member_id);
						$cmp->setObjectTypeId($role_perm->getObjectTypeId());
						$cmp->setCanDelete($role_perm->getCanDelete());
						$cmp->setCanWrite($role_perm->getCanWrite());
						$cmp->save();
						$new_permissions[] = $cmp;
						
						$perm = new stdClass();
						$perm->m = $member_id;
						$perm->r = 1;
						$perm->w = $role_perm->getCanWrite();
						$perm->d = $role_perm->getCanDelete();
						$perm->o = $role_perm->getObjectTypeId();
						$shtab_permissions[] = $perm;
					}
				}
			}
			
			if (count($shtab_permissions)) {
				$cdp = ContactDimensionPermissions::instance()->findOne(array('conditions' => "permission_group_id = '$permission_group_id' AND dimension_id = $dimension_id"));
				if (!$cdp instanceof ContactDimensionPermission) {
					$cdp = new ContactDimensionPermission();
					$cdp->setPermissionGroupId($permission_group_id);
					$cdp->setContactDimensionId($dimension_id);
					$cdp->setPermissionType('check');
					$cdp->save();
				} else {
					if ($cdp->getPermissionType() == 'deny all') {
						$cdp->setPermissionType('check');
						$cdp->save();
					}
				}
				$stCtrl = new SharingTableController();
				$stCtrl->afterPermissionChanged($permission_group_id, $shtab_permissions);
			}
			
			return $new_permissions;
			
		} catch (Exception $e) {
			throw $e;
		}
	}
Example #9
0
function save_member_permissions($member, $permissionsString = null, $save_cmps = true, $update_sharing_table = true, $fire_hook = true, $update_contact_member_cache = true)
{
    @set_time_limit(0);
    ini_set('memory_limit', '1024M');
    if (!$member instanceof Member) {
        return;
    }
    if (is_null($permissionsString)) {
        $permissionsString = array_var($_POST, 'permissions');
    }
    if ($permissionsString && $permissionsString != '') {
        $permissions = json_decode($permissionsString);
    }
    $sharingTablecontroller = new SharingTableController();
    $contactMemberCacheController = new ContactMemberCacheController();
    $changed_pgs = array();
    $sql_insert_values = "";
    if (isset($permissions) && is_array($permissions)) {
        $allowed_pg_ids = array();
        foreach ($permissions as $k => &$perm) {
            if ($perm->r) {
                $allowed_pg_ids[$perm->pg] = array();
                if (isset($allowed_pg_ids[$perm->pg]['w'])) {
                    if (!$allowed_pg_ids[$perm->pg]['w']) {
                        $allowed_pg_ids[$perm->pg]['w'] = $perm->w;
                    }
                } else {
                    $allowed_pg_ids[$perm->pg]['w'] = $perm->w;
                }
                if (isset($allowed_pg_ids[$perm->pg]['d'])) {
                    if (!$allowed_pg_ids[$perm->pg]['d']) {
                        $allowed_pg_ids[$perm->pg]['d'] = $perm->d;
                    }
                } else {
                    $allowed_pg_ids[$perm->pg]['d'] = $perm->d;
                }
                // check max permissions for user type
                $tmp_contact = Contacts::findOne(array('conditions' => 'permission_group_id = ' . $perm->pg));
                if ($tmp_contact instanceof Contact) {
                    $max_role_ot_perms = MaxRoleObjectTypePermissions::instance()->findAll(array('conditions' => "role_id = '" . $tmp_contact->getUserType() . "'"));
                    $max_perm = null;
                    foreach ($max_role_ot_perms as $max_role_ot_perm) {
                        if ($max_role_ot_perm->getObjectTypeId() == $perm->o) {
                            $max_perm = $max_role_ot_perm;
                        }
                    }
                    $perm->m = $member->getId();
                    if ($max_perm) {
                        if (!$max_perm->getCanDelete()) {
                            $perm->d = 0;
                        }
                        if (!$max_perm->getCanWrite()) {
                            $perm->w = 0;
                        }
                    } else {
                        $perm->d = 0;
                        $perm->w = 0;
                        $perm->r = 0;
                        unset($permissions[$k]);
                        continue;
                    }
                }
                if ($save_cmps) {
                    $sql_insert_values .= ($sql_insert_values == "" ? "" : ",") . "('" . $perm->pg . "','" . $member->getId() . "','" . $perm->o . "','" . $perm->d . "','" . $perm->w . "')";
                }
            }
            $perm->m = $member->getId();
            $changed_pgs[$perm->pg] = $perm->pg;
        }
        if ($save_cmps) {
            if (count($changed_pgs) > 0) {
                DB::execute("DELETE FROM " . TABLE_PREFIX . "contact_member_permissions WHERE permission_group_id IN (" . implode(',', $changed_pgs) . ") AND member_id=" . $member->getId());
            }
            if ($sql_insert_values != "") {
                DB::execute("INSERT INTO " . TABLE_PREFIX . "contact_member_permissions (permission_group_id, member_id, object_type_id, can_delete, can_write) VALUES {$sql_insert_values} ON DUPLICATE KEY UPDATE member_id=member_id");
            }
        }
        foreach ($permissions as $p) {
            if (!$p->m) {
                $p->m = $member->getId();
            }
        }
        if ($update_sharing_table) {
            foreach ($changed_pgs as $pg_id) {
                $sharingTablecontroller->afterPermissionChanged($pg_id, $permissions);
            }
        }
        if ($update_contact_member_cache) {
            $contactMemberCacheController->afterMemberPermissionChanged(array('changed_pgs' => $changed_pgs, 'member' => $member));
        }
        foreach ($allowed_pg_ids as $key => $mids) {
            $root_cmp = ContactMemberPermissions::findById(array('permission_group_id' => $key, 'member_id' => $member->getId(), 'object_type_id' => $member->getObjectTypeId()));
            if (!$root_cmp instanceof ContactMemberPermission) {
                $root_cmp = new ContactMemberPermission();
                $root_cmp->setPermissionGroupId($key);
                $root_cmp->setMemberId($member->getId());
                $root_cmp->setObjectTypeId($member->getObjectTypeId());
            }
            $root_cmp->setCanWrite($mids['w'] == true ? 1 : 0);
            $root_cmp->setCanDelete($mids['d'] == true ? 1 : 0);
            $root_cmp->save();
        }
    }
    // check the status of the dimension to set 'allow_all', 'deny_all' or 'check'
    $dimension = $member->getDimension();
    foreach ($changed_pgs as $pg_id) {
        $dimension->setContactDimensionPermission($pg_id, 'check');
    }
    if ($fire_hook) {
        Hook::fire('after_save_member_permissions', array('member' => $member, 'user_id' => logged_user()->getId()), $member);
    }
    return array('changed_pgs' => $changed_pgs, 'member' => $member);
}
Example #10
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;
}