/**
  * 
  * @param Contact $user
  * @param array $permissions
  * @param ContactPermissionGroup $group
  */
 function afterUserPermissionChanged($user, $permissions, $group = null)
 {
     //get members ids
     $membersIds = array();
     if (is_null($group)) {
         //get all members affected from $permission
         foreach ($permissions as $permission) {
             $memberId = $permission->m;
             if (!in_array($memberId, $membersIds)) {
                 $membersIds[] = $memberId;
             }
         }
     } else {
         // dimension
         $dimensions = Dimensions::findAll();
         $contact_pg_ids = $group->getId();
         //get all allowed members for the group
         $allowed_members = array();
         foreach ($dimensions as $dimension) {
             $member_list = array();
             if ($dimension->getDefinesPermissions()) {
                 $member_list = DB::executeAll("SELECT * FROM " . TABLE_PREFIX . "members WHERE dimension_id = " . $dimension->getId() . " ORDER BY id");
             }
             foreach ($member_list as $dim_member) {
                 if (ContactMemberPermissions::instance()->contactCanAccessMemberAll($contact_pg_ids, $dim_member['id'], $user, ACCESS_LEVEL_READ, false)) {
                     $allowed_members[] = $dim_member['id'];
                 }
             }
         }
         $membersIds = $allowed_members;
     }
     foreach ($membersIds as $member_id) {
         ContactMemberCaches::updateContactMemberCache($user, $member_id);
     }
 }
예제 #2
0
 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");
     }
 }
 /**
  * Returns all the members to be displayed in the panel that corresponds to the dimension for which the id is received by
  * parameter.
  * It is called when the application is first loaded.
  * @todo: return only the members that are going to be retrieved
  * @todo: add a function to retrieve the rest of the members - dimension_members - and make it more efficient
  * @todo: add a funciton to retrieve a specific set of members
  * @todo: check where this function is called
  * @todo: check (and fix) that the system doesn't use the left-panel navigation tree to get member's data
  *
  */
 function initial_list_dimension_members($dimension_id, $object_type_id, $allowed_member_type_ids = null, $return_all_members = false, $extra_conditions = "", $limit = null, $return_member_objects = false, $order = null, $return_only_members_name = false, $filter_by_members = array(), $access_level = ACCESS_LEVEL_READ, $use_member_cache = false)
 {
     $allowed_member_types = array();
     $item_object = null;
     if (logged_user()->isAdministrator()) {
         $return_all_members = true;
     }
     $contact_pg_ids = ContactPermissionGroups::getPermissionGroupIdsByContactCSV(logged_user()->getId(), false);
     $dimension = Dimensions::getDimensionById($dimension_id);
     if ($object_type_id != null) {
         $dimension_object_type_contents = $dimension->getObjectTypeContent($object_type_id);
         foreach ($dimension_object_type_contents as $dotc) {
             $dot_id = $dotc->getDimensionObjectTypeId();
             if (is_null($allowed_member_type_ids) || in_array($dot_id, $allowed_member_type_ids)) {
                 $allowed_member_types[] = $dot_id;
             }
         }
         $object_type = ObjectTypes::findById($object_type_id);
         if ($object_type instanceof ObjectType && $object_type->getType() == 'dimension_object') {
             eval('$ot_manager = ' . $object_type->getHandlerClass() . '::instance();');
             if (isset($ot_manager)) {
                 eval('$item_object = new ' . $ot_manager->getItemClass() . '();');
             }
         }
     }
     $extra_conditions .= " AND archived_by_id=0";
     if ($dimension instanceof Dimension) {
         if (count($allowed_member_types) > 0) {
             $extra_conditions = " AND object_type_id IN (" . implode(",", $allowed_member_types) . ")" . $extra_conditions;
         }
         $parent = 0;
         if (is_null($order)) {
             $order = "parent_member_id, name";
         }
         if (!$dimension->getDefinesPermissions() || $dimension->hasAllowAllForContact($contact_pg_ids) || $return_all_members) {
             $all_members = $dimension->getAllMembers(false, $order, true, $extra_conditions, $limit);
         } else {
             if ($dimension->hasCheckForContact($contact_pg_ids)) {
                 if ($use_member_cache) {
                     //use the contact member cache
                     $params = array("dimension" => $dimension, "contact_id" => logged_user()->getId(), "parent_member_id" => 0, "start" => $limit['offset'], "limit" => $limit['limit'], "extra_condition" => $extra_conditions, "order" => '`name`', "order_dir" => 'ASC');
                     $all_members = ContactMemberCaches::getAllMembersWithCachedParentId($params);
                 } else {
                     $member_list = $dimension->getAllMembers(false, $order, true, $extra_conditions, $limit);
                     $allowed_members = array();
                     foreach ($member_list as $dim_member) {
                         if (ContactMemberPermissions::instance()->contactCanAccessMemberAll($contact_pg_ids, $dim_member->getId(), logged_user(), $access_level)) {
                             $allowed_members[] = $dim_member;
                         }
                     }
                     $all_members = $allowed_members;
                 }
             }
         }
         if (!isset($all_members)) {
             $all_members = array();
         }
         $tmp_array = array();
         foreach ($filter_by_members as $filter_id) {
             if ($filter_id) {
                 $tmp_array[] = $filter_id;
             }
         }
         $filter_by_members = $tmp_array;
         $all_members = $this->apply_association_filters($dimension, $all_members, $filter_by_members);
         if ($return_member_objects) {
             return $all_members;
         } else {
             return $this->buildMemberList($all_members, $dimension, $allowed_member_type_ids, $allowed_member_types, $item_object, $object_type_id, $return_only_members_name);
         }
     }
     return null;
 }
예제 #4
0
 function do_delete()
 {
     $id = $this->getId();
     ContactAddresses::instance()->delete("`contact_id` = {$id}");
     ContactImValues::instance()->delete("`contact_id` = {$id}");
     ContactEmails::instance()->delete("`contact_id` = {$id}");
     ContactTelephones::instance()->delete("`contact_id` = {$id}");
     ContactWebpages::instance()->delete("`contact_id` = {$id}");
     ContactConfigOptionValues::instance()->delete("`contact_id` = {$id}");
     ContactPasswords::instance()->delete("`contact_id` = {$id}");
     ObjectSubscriptions::instance()->delete("`contact_id` = {$id}");
     ObjectReminders::instance()->delete("`contact_id` = {$id}");
     ContactPermissionGroups::instance()->delete("`contact_id` = {$id}");
     ContactMemberPermissions::instance()->delete("`permission_group_id` = " . $this->getPermissionGroupId());
     ContactDimensionPermissions::instance()->delete("`permission_group_id` = " . $this->getPermissionGroupId());
     SystemPermissions::instance()->delete("`permission_group_id` = " . $this->getPermissionGroupId());
     TabPanelPermissions::instance()->delete("`permission_group_id` = " . $this->getPermissionGroupId());
     $this->delete();
     $ret = null;
     Hook::fire("after_user_deleted", $this, $ret);
 }
예제 #5
0
function core_dimensions_after_save_member_permissions($member, &$ignored) {
	if (!$member instanceof Member || !($member->getId()>0)) return;
	$permission_group_ids = array();
	
	$cmp_rows = DB::executeAll("SELECT DISTINCT permission_group_id FROM ".TABLE_PREFIX."contact_member_permissions WHERE member_id = '".$member->getId()."' AND permission_group_id IN (SELECT id FROM ".TABLE_PREFIX."permission_groups WHERE type IN ('permission_groups','user_groups'))");
	foreach ($cmp_rows as $row) {
		$permission_group_ids[$row['permission_group_id']] = $row['permission_group_id'];
	}
	
	$contacts = array();
	// users
	if (count($permission_group_ids) > 0) {
		$contacts = Contacts::findAll(array('conditions' => 'user_type > 0 && permission_group_id IN ('.implode(',', $permission_group_ids).')'));
	}
	// contacts
	$contact_rows = DB::executeAll("SELECT DISTINCT om.object_id FROM ".TABLE_PREFIX."object_members om INNER JOIN ".TABLE_PREFIX."contacts c ON c.object_id=om.object_id 
		WHERE om.member_id='".$member->getId()."' AND c.user_type=0");
	$no_user_ids = array();
	if (is_array($contact_rows)) {
		foreach ($contact_rows as $row) {
			$no_user_ids[] = $row['object_id'];
		}
	}
	$more_contacts = Contacts::findAll(array('conditions' => 'object_id IN ('.implode(',', $no_user_ids).')'));
	
	$contacts = array_merge($contacts, $more_contacts);
	$contact_ids = array(0);
	
	$persons_dim = Dimensions::findByCode("feng_persons");

	core_dim_remove_contacts_member_associations($member);
	
	foreach ($contacts as $contact) {
		$contact_id = $contact->getId();
		$contact_member = Members::findOneByObjectId($contact_id, $persons_dim->getId());
		if ($contact_member instanceof Member) {
			core_dim_add_contact_member_associations($contact_member, $member);
			
			if ($contact instanceof Contact && $contact->isUser()) {
				$has_project_permissions = ContactMemberPermissions::instance()->count("permission_group_id = '".$contact->getPermissionGroupId()."' AND member_id = ".$member->getId()) > 0;
				if (!$has_project_permissions) {
					RoleObjectTypePermissions::createDefaultUserPermissions($contact, $member);
				}
			}
		}
		// add user content object to customer member
		ObjectMembers::addObjectToMembers($contact_id, array($member));
		$contact->addToSharingTable();
		$contact_ids[] = $contact_id;
	}
	
	// remove contacts whose members are no longer associated to the customer member
	$previous_users_in_member = Contacts::instance()->listing(array(
		'member_ids' => array($member->getId()),
		'ignore_context' => true,
		'extra_conditions' => ' AND e.user_type > 0 AND e.object_id NOT IN ('.implode(',', $contact_ids).')',
	))->objects;
	foreach ($previous_users_in_member as $prev_u) {
		ObjectMembers::removeObjectFromMembers($prev_u, logged_user(), array($member), array($member->getId()));
	}
	
	// refresh dimensions
	evt_add("reload dimension tree", array('dim_id' => $persons_dim->getId(), 'node' => null));
}
 /**
  * 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);
         }
     }
 }
예제 #7
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;
}
예제 #8
0
 /**
  * Lists all contacts and clients
  *
  */
 function list_all()
 {
     ajx_current("empty");
     // Get all variables from request
     $start = array_var($_GET, 'start', 0);
     $limit = array_var($_GET, 'limit', config_option('files_per_page'));
     $page = 1;
     if ($start > 0) {
         $page = $start / $limit + 1;
     }
     $order = array_var($_GET, 'sort');
     $order_dir = array_var($_GET, 'dir');
     $action = array_var($_GET, 'action');
     $attributes = array("ids" => explode(',', array_var($_GET, 'ids')), "types" => explode(',', array_var($_GET, 'types')), "accountId" => array_var($_GET, 'account_id'), "viewType" => array_var($_GET, 'view_type'));
     //Resolve actions to perform
     $actionMessage = array();
     if (isset($action)) {
         $actionMessage = $this->resolveAction($action, $attributes);
         if ($actionMessage["errorCode"] == 0) {
             flash_success($actionMessage["errorMessage"]);
         } else {
             flash_error($actionMessage["errorMessage"]);
         }
     }
     $extra_conditions = "";
     if ($attributes['viewType'] == 'contacts') {
         $extra_conditions = 'AND `is_company` = 0';
     } else {
         if ($attributes['viewType'] == 'companies') {
             $extra_conditions = 'AND `is_company` = 1';
         }
     }
     $extra_conditions .= " AND disabled = 0 ";
     switch ($order) {
         case 'updatedOn':
             $order = '`updated_on`';
             break;
         case 'createdOn':
             $order = '`created_on`';
             break;
         case 'name':
             $order = ' concat(surname, first_name) ';
             break;
         default:
             $order = '`name`';
             break;
     }
     if (!$order_dir) {
         switch ($order) {
             case 'name':
                 $order_dir = 'ASC';
                 break;
             default:
                 $order_dir = 'DESC';
         }
     }
     $context = active_context();
     if (context_type() == 'mixed') {
         // There are members selected
         //$content_objects = Contacts::getContentObjects($context, ObjectTypes::findById(Contacts::instance()->getObjectTypeId()), $order, $order_dir, $extra_conditions, null, false,false, $start, $limit);
         $content_objects = Contacts::instance()->listing(array("order" => $order, "order_dir" => $order_dir, "extra_conditions" => $extra_conditions, "start" => $start, "limit" => $limit));
     } else {
         // Estoy parado en 'All'. Filtro solo por permisos TODO: Fix this !
         $conditions = "archived_on = '0000-00-00 00:00:00' AND trashed_on = '0000-00-00 00:00:00' {$extra_conditions}";
         $content_objects = new stdClass();
         $content_objects->objects = Contacts::instance()->findAll(array("conditions" => $conditions, "order" => "{$order} {$order_dir}", "offset" => $start, "limit" => $limit));
         $content_objects->total = Contacts::instance()->count(array("conditions" => $conditions));
         foreach ($content_objects->objects as $k => $contact) {
             /* @var $contact Contact */
             if (Plugins::instance()->isActivePlugin("core_dimensions")) {
                 $m = array_var(Members::instance()->findByObjectId($contact->getId(), Dimensions::findByCode("feng_persons")->getId()), 0);
                 if ($m instanceof Member) {
                     $mid = $m->getId();
                     if (!ContactMemberPermissions::instance()->contactCanReadMember(logged_user()->getPermissionGroupId(), $mid, logged_user())) {
                         unset($content_objects->objects[$k]);
                         $content_objects->total--;
                     }
                 }
             }
         }
         $content_objects->objects = array_values($content_objects->objects);
     }
     // Prepare response object
     $object = $this->newPrepareObject($content_objects->objects, $content_objects->total, $start, $attributes);
     ajx_extra_data($object);
     tpl_assign("listing", $object);
 }
 /**
 * This function will return paginated result. Result is an array where first element is 
 * array of returned object and second populated pagination object that can be used for 
 * obtaining and rendering pagination data using various helpers.
 * 
 * Items and pagination array vars are indexed with 0 for items and 1 for pagination
 * because you can't use associative indexing with list() construct
 *
 * @access public
 * @param array $arguments Query argumens (@see find()) Limit and offset are ignored!
 * @param integer $items_per_page Number of items per page
 * @param integer $current_page Current page number
 * @return array
 */
 function paginate($arguments = null, $items_per_page = 10, $current_page = 1) {
   if(isset($this) && instance_of($this, 'ContactMemberPermissions')) {
     return parent::paginate($arguments, $items_per_page, $current_page);
   } else {
     return ContactMemberPermissions::instance()->paginate($arguments, $items_per_page, $current_page);
   } // if
 } // paginate
예제 #10
0
function save_permissions($pg_id, $is_guest = false)
{
    $sys_permissions_data = array_var($_POST, 'sys_perm');
    $changed_members = array();
    //module permissions
    $mod_permissions_data = array_var($_POST, 'mod_perm');
    TabPanelPermissions::clearByPermissionGroup($pg_id);
    if (!is_null($mod_permissions_data) && is_array($mod_permissions_data)) {
        foreach ($mod_permissions_data as $tab_id => $val) {
            $tpp = new TabPanelPermission();
            $tpp->setPermissionGroupId($pg_id);
            $tpp->setTabPanelId($tab_id);
            $tpp->save();
        }
    }
    //system permissions
    $system_permissions = SystemPermissions::findById($pg_id);
    if (!$system_permissions instanceof SystemPermission) {
        $system_permissions = new SystemPermission();
        $system_permissions->setPermissionGroupId($pg_id);
    }
    $system_permissions->setAllPermissions(false);
    $other_permissions = array();
    Hook::fire('add_user_permissions', $pg_id, $other_permissions);
    foreach ($other_permissions as $k => $v) {
        $system_permissions->setColumnValue($k, false);
    }
    $sys_permissions_data['can_task_assignee'] = !$is_guest;
    $system_permissions->setFromAttributes($sys_permissions_data);
    $system_permissions->save();
    //member permissions
    $permissionsString = array_var($_POST, 'permissions');
    if ($permissionsString && $permissionsString != '') {
        $permissions = json_decode($permissionsString);
    }
    if (isset($permissions) && !is_null($permissions) && is_array($permissions)) {
        $allowed_members_ids = array();
        foreach ($permissions as $perm) {
            if (!isset($all_perm_deleted[$perm->m])) {
                $all_perm_deleted[$perm->m] = true;
            }
            $allowed_members_ids[$perm->m] = array();
            $allowed_members_ids[$perm->m]['pg'] = $pg_id;
            $cmp = ContactMemberPermissions::findById(array('permission_group_id' => $pg_id, 'member_id' => $perm->m, 'object_type_id' => $perm->o));
            if (!$cmp instanceof ContactMemberPermission) {
                $cmp = new ContactMemberPermission();
                $cmp->setPermissionGroupId($pg_id);
                $cmp->setMemberId($perm->m);
                $cmp->setObjectTypeId($perm->o);
            }
            $cmp->setCanWrite($is_guest ? false : $perm->w);
            $cmp->setCanDelete($is_guest ? false : $perm->d);
            if ($perm->r) {
                if (isset($allowed_members_ids[$perm->m]['w'])) {
                    if ($allowed_members_ids[$perm->m]['w'] != 1) {
                        $allowed_members_ids[$perm->m]['w'] = $is_guest ? false : $perm->w;
                    }
                } else {
                    $allowed_members_ids[$perm->m]['w'] = $is_guest ? false : $perm->w;
                }
                if (isset($allowed_members_ids[$perm->m]['d'])) {
                    if ($allowed_members_ids[$perm->m]['d'] != 1) {
                        $allowed_members_ids[$perm->m]['d'] = $is_guest ? false : $perm->d;
                    }
                } else {
                    $allowed_members_ids[$perm->m]['d'] = $is_guest ? false : $perm->d;
                }
                $cmp->save();
                $all_perm_deleted[$perm->m] = false;
            } else {
                $cmp->delete();
            }
            $changed_members[] = $perm->m;
        }
        $sharingTablecontroller = new SharingTableController();
        $sharingTablecontroller->afterPermissionChanged($pg_id, $permissions);
        foreach ($allowed_members_ids as $key => $mids) {
            $mbm = Members::findById($key);
            $root_cmp = ContactMemberPermissions::findById(array('permission_group_id' => $mids['pg'], 'member_id' => $key, 'object_type_id' => $mbm->getObjectTypeId()));
            if (!$root_cmp instanceof ContactMemberPermission) {
                $root_cmp = new ContactMemberPermission();
                $root_cmp->setPermissionGroupId($mids['pg']);
                $root_cmp->setMemberId($key);
                $root_cmp->setObjectTypeId($mbm->getObjectTypeId());
            }
            $root_cmp->setCanWrite($mids['w']);
            $root_cmp->setCanDelete($mids['d']);
            $root_cmp->save();
        }
        foreach ($all_perm_deleted as $mid => $pd) {
            if ($pd) {
                ContactMemberPermissions::instance()->delete("`permission_group_id` = {$pg_id} AND `member_id` = {$mid}");
            }
        }
    }
    // set all permissiions to read_only
    if ($is_guest) {
        $all_saved_permissions = ContactMemberPermissions::findAll(array("conditions" => "`permission_group_id` = {$pg_id}"));
        foreach ($all_saved_permissions as $sp) {
            /* @var $sp ContactMemberPermission */
            if ($sp->getCanDelete() || $sp->getCanWrite()) {
                $sp->setCanDelete(false);
                $sp->setCanWrite(false);
                $sp->save();
            }
        }
        $cdps = ContactDimensionPermissions::findAll(array("conditions" => "`permission_type` = 'allow all'"));
        foreach ($cdps as $cdp) {
            $cdp->setPermissionType('check');
            $cdp->save();
        }
    }
    // check the status of the changed dimensions to set 'allow_all', 'deny_all' or 'check'
    $dimensions = Dimensions::findAll(array("conditions" => array("`id` IN (SELECT DISTINCT `dimension_id` FROM " . Members::instance()->getTableName(true) . " WHERE `id` IN (?))", $changed_members)));
    foreach ($dimensions as $dimension) {
        $mem_ids = $dimension->getAllMembers(true);
        if (count($mem_ids) == 0) {
            $mem_ids[] = 0;
        }
        $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');
                }
            }
        }
    }
}
 /**
  * Return manager instance
  *
  * @access protected
  * @param void
  * @return ContactMemberPermissions 
  */
 function manager()
 {
     if (!$this->manager instanceof ContactMemberPermissions) {
         $this->manager = ContactMemberPermissions::instance();
     }
     return $this->manager;
 }
 /**
 * Return manager instance
 *
 * @access protected
 * @param void
 * @return ContactMemberPermissions 
 */
 function manager() {
   if(!($this->manager instanceof ContactMemberPermissions)) $this->manager = ContactMemberPermissions::instance();
   return $this->manager;
 } // manager
예제 #13
0
/**
 * Return true is $user can access an $object. False otherwise.
 *
 * @param Contact $user
 * @param array $members
 * @param $object_type_id
 * @return boolean
 */
function can_access_pgids($permission_group_ids, $members, $object_type_id, $access_level)
{
    $write = $access_level == ACCESS_LEVEL_WRITE;
    $delete = $access_level == ACCESS_LEVEL_DELETE;
    $tmp_contact = null;
    $max_role_ot_perm = null;
    if (count($permission_group_ids) > 0) {
        $permission_groups = PermissionGroups::findAll(array('conditions' => "id IN (" . implode(',', $permission_group_ids) . ")"));
        foreach ($permission_groups as $pgroup) {
            if ($pgroup->getType() == 'permission_groups' && $pgroup->getContactId() > 0) {
                $tmp_contact = Contacts::findById($pgroup->getContactId());
                $max_role_ot_perm = MaxRoleObjectTypePermissions::instance()->findOne(array('conditions' => "object_type_id='{$object_type_id}' AND role_id = '" . $tmp_contact->getUserType() . "'"));
                break;
            }
        }
    }
    try {
        $dimension_query_methods = array();
        $dimension_permissions = array();
        $enabled_dimensions = config_option('enabled_dimensions');
        $dimension_info = array();
        foreach ($members as $k => $m) {
            if (!$m instanceof Member || !in_array($m->getDimensionId(), $enabled_dimensions)) {
                unset($members[$k]);
                continue;
            }
            if (!isset($dimension_info[$m->getDimensionId()])) {
                $dimension_info[$m->getDimensionId()] = array('dim' => $m->getDimension(), 'members' => array($m->getId() => $m));
            } else {
                $dimension_info[$m->getDimensionId()]['members'][$m->getId()] = $m;
            }
        }
        foreach ($dimension_info as $did => $info) {
            $dimension = $info['dim'];
            if (!$dimension->getDefinesPermissions()) {
                continue;
            }
            if ($max_role_ot_perm && ($access_level == ACCESS_LEVEL_DELETE && $max_role_ot_perm->getCanDelete() || $access_level == ACCESS_LEVEL_WRITE && $max_role_ot_perm->getCanWrite() || $access_level == ACCESS_LEVEL_READ)) {
                if (!isset($dimension_query_methods[$dimension->getId()])) {
                    $dimension_query_methods[$dimension->getId()] = $dimension->getPermissionQueryMethod();
                }
                $dimension_id = $dimension->getId();
                $dimension_permissions[$dimension_id] = array();
                //dimension defines permissions and user has maximum level of permissions
                $dimension_permissions[$dimension_id] = array_merge($dimension_permissions[$dimension_id], $dimension->getPermissionGroupsAllowAll($permission_group_ids));
                //check
                $dimension_permissions[$dimension_id] = array_merge($dimension_permissions[$dimension_id], ContactMemberPermissions::instance()->canAccessObjectTypeinMembersPermissionGroups($permission_group_ids, array_keys($info['members']), $object_type_id, $write, $delete));
            }
        }
        $mandatory_dimension_ids = array();
        foreach ($dimension_query_methods as $dim_id => $qmethod) {
            if (!in_array($dim_id, $enabled_dimensions)) {
                continue;
            }
            if ($qmethod == DIMENSION_PERMISSION_QUERY_METHOD_MANDATORY) {
                $mandatory_dimension_ids[] = $dim_id;
            }
        }
        // if there are mandatory dimensions involved then intersect the allowed permission groups of each dimension
        if (count($mandatory_dimension_ids) > 0) {
            $first_mdid = array_pop($mandatory_dimension_ids);
            $pgs_accomplishing_mandatory = $dimension_permissions[$first_mdid];
            foreach ($mandatory_dimension_ids as $mdid) {
                $pgs_accomplishing_mandatory = array_intersect($pgs_accomplishing_mandatory, $dimension_permissions[$mdid]);
            }
            $all_permission_groups = array_unique($pgs_accomplishing_mandatory);
        } else {
            // No mandatory dimensions involved => return all allowed permission groups
            $other_pgs = array();
            foreach ($dimension_query_methods as $dim_id => $qmethod) {
                if (!in_array($dim_id, $enabled_dimensions)) {
                    continue;
                }
                if ($qmethod == DIMENSION_PERMISSION_QUERY_METHOD_NOT_MANDATORY) {
                    $other_pgs = array_merge($other_pgs, $dimension_permissions[$dim_id]);
                }
            }
            $all_permission_groups = array_unique($other_pgs);
        }
        return $all_permission_groups;
    } catch (Exception $e) {
        tpl_assign('error', $e);
        return array();
    }
    return array();
}
 /**
  * 
  * 
  */
 function list_dimension_members($member_id, $context_dimension_id, $object_type_id, $allowed_member_type_ids)
 {
     if ($member_id != 0) {
         $contact_pg_ids = ContactPermissionGroups::getPermissionGroupIdsByContactCSV(logged_user()->getId(), false);
         $member = members::findById($member_id);
         $dimension = Dimensions::getDimensionById($context_dimension_id);
         if ($object_type_id != null) {
             $dimension_object_type_contents = $dimension->getObjectTypeContent($object_type_id);
             foreach ($dimension_object_type_contents as $dotc) {
                 $dot_id = $dotc->getDimensionObjectTypeId();
                 if (is_null($allowed_member_type_ids) || in_array($dot_id, $allowed_member_type_ids)) {
                     $allowed_object_type_ids[] = $dot_id;
                 }
             }
         }
         if ($dimension instanceof Dimension && $member instanceof Member) {
             if (!$dimension->getDefinesPermissions() || $dimension->hasAllowAllForContact($contact_pg_ids)) {
                 $dimension_members = $dimension->getAllMembers(false, "parent_member_id, name", true);
             } else {
                 if ($dimension->hasCheckForContact($contact_pg_ids)) {
                     $member_list = $dimension->getAllMembers(false, "parent_member_id, name", true);
                     $allowed_members = array();
                     foreach ($member_list as $dim_member) {
                         if (ContactMemberPermissions::instance()->contactCanReadMemberAll($contact_pg_ids, $dim_member->getId(), logged_user())) {
                             $allowed_members[] = $dim_member;
                         }
                     }
                     $dimension_members = $allowed_members;
                 }
             }
             $members_to_retrieve = array();
             $association_ids = DimensionMemberAssociations::getAllAssociationIds($member->getDimensionId(), $context_dimension_id);
             if (count($association_ids) > 0) {
                 $associated_members_ids_csv = '';
                 foreach ($association_ids as $id) {
                     $association = DimensionMemberAssociations::findById($id);
                     $children = $member->getAllChildrenInHierarchy();
                     if ($association->getDimensionId() == $context_dimension_id) {
                         $new_csv = MemberPropertyMembers::getAllMemberIds($id, $member_id);
                         $associated_members_ids_csv .= $new_csv != '' ? $new_csv . "," : '';
                         foreach ($children as $child) {
                             $new_csv = MemberPropertyMembers::getAllMemberIds($id, $child->getId());
                             $associated_members_ids_csv .= $new_csv != '' ? $new_csv . "," : '';
                         }
                     } else {
                         $new_csv = MemberPropertyMembers::getAllPropertyMemberIds($id, $member_id) . ",";
                         $associated_members_ids_csv .= $new_csv != '' ? $new_csv . "," : '';
                         foreach ($children as $child) {
                             $new_csv = MemberPropertyMembers::getAllPropertyMemberIds($id, $child->getId());
                             $associated_members_ids_csv .= $new_csv != '' ? $new_csv . "," : '';
                         }
                     }
                 }
                 $associated_members_ids = explode(',', $associated_members_ids_csv);
                 $associated_members_ids = array_unique($associated_members_ids);
             }
             if (isset($associated_members_ids) && count($associated_members_ids) > 0) {
                 foreach ($associated_members_ids as $id) {
                     $associated_member = Members::findById($id);
                     if (in_array($associated_member, $dimension_members)) {
                         $context_hierarchy_members = $associated_member->getAllParentMembersInHierarchy(true);
                         foreach ($context_hierarchy_members as $context_member) {
                             if (!in_array($context_member, $members_to_retrieve) && in_array($context_member, $dimension_members)) {
                                 $members_to_retrieve[$context_member->getName()] = $context_member;
                             }
                         }
                     }
                 }
                 // alphabetical order
                 $members_to_retrieve = array_ksort($members_to_retrieve);
             } else {
                 $members_to_retrieve[] = $dimension_members;
             }
             $membersset = array();
             foreach ($members_to_retrieve as $m) {
                 $membersset[$m->getId()] = true;
             }
             $members = array();
             // Todo adapt this code to call "buildMemberList" - (performance and code improvement)
             foreach ($members_to_retrieve as $m) {
                 if ($m->getArchivedById() > 0) {
                     continue;
                 }
                 if ($object_type_id != null) {
                     $selectable = in_array($m->getObjectTypeId(), $allowed_object_type_ids) ? true : false;
                 }
                 $tempParent = $m->getParentMemberId();
                 $x = $m;
                 while ($x instanceof Member && !isset($membersset[$tempParent])) {
                     $tempParent = $x->getParentMemberId();
                     $x = $x->getParentMember();
                 }
                 if (!$x instanceof Member) {
                     $tempParent = 0;
                 }
                 if ($dot = DimensionObjectTypes::instance()->findOne(array("conditions" => "\n\t\t\t\t\t\tdimension_id = " . $dimension->getId() . " AND\n\t\t\t\t\t\tobject_type_id = " . $m->getObjectTypeId()))) {
                     $memberOptions = $dot->getOptions(true);
                 } else {
                     $memberOptions = '';
                 }
                 /* @var $m Member */
                 $member = array("id" => $m->getId(), "name" => clean($m->getName()), "parent" => $tempParent, "realParent" => $m->getParentMemberId(), "object_id" => $m->getObjectId(), "options" => $memberOptions, "depth" => $m->getDepth(), "iconCls" => $m->getIconClass(), "selectable" => isset($selectable) ? $selectable : false, "dimension_id" => $m->getDimensionId(), "object_type_id" => $m->getObjectTypeId(), "allow_childs" => $m->allowChilds());
                 if ($oid = $m->getObjectId()) {
                     if ($obj = Objects::instance()->findObject($m->getObjectId())) {
                         $editUrl = $obj->getEditUrl();
                     }
                 }
                 // Member Actions
                 if (can_manage_dimension_members(logged_user())) {
                     if ($oid = $m->getObjectId()) {
                         if ($obj = Objects::instance()->findObject($m->getObjectId())) {
                             $editUrl = $obj->getEditUrl();
                         }
                     } else {
                         $editUrl = get_url('member', 'edit', array('id' => $m->getId()));
                     }
                     $member['actions'] = array(array('url' => $editUrl, 'text' => '', 'iconCls' => 'ico-edit'));
                 }
                 $members[] = $member;
             }
             return $members;
         }
         return null;
     } else {
         $members = $this->initial_list_dimension_members($context_dimension_id, $object_type_id, $allowed_member_type_ids);
         return $members;
     }
 }
예제 #15
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;
}