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;
     }
 }
Esempio n. 2
0
 static function getAssociatedDimensions($associated_dimension_id, $associated_object_type, $get_properties = true)
 {
     if ($get_properties) {
         $dim_field = 'associated_dimension_id';
         $ot_field = 'associated_object_type_id';
         $res_dim_field = 'dimension_id';
     } else {
         $dim_field = 'dimension_id';
         $ot_field = 'object_type_id';
         $res_dim_field = 'associated_dimension_id';
     }
     $search_condition = "`{$dim_field}` = {$associated_dimension_id} AND `{$ot_field}` = {$associated_object_type}";
     $associations = DimensionMemberAssociations::findAll(array('conditions' => $search_condition));
     // TODO: Hacerlo recursivo cuando get_properties = true
     $dimensions = array();
     foreach ($associations as $assoc) {
         $dimensions[] = Dimensions::getDimensionById($assoc->getColumnValue($res_dim_field));
     }
     return $dimensions;
 }
 function dimension_options_submit()
 {
     ajx_current("empty");
     if (!can_manage_dimensions(logged_user())) {
         flash_error(lang('no access permissions'));
         return;
     }
     $folder_ots = ObjectTypes::findAll(array('id' => true, 'conditions' => "name IN ('folder','project_folder','customer_folder')"));
     $data = array_var($_POST, 'enabled_dots');
     $names_data = array_var($_POST, 'custom_names');
     if (is_array($data) || is_array($names_data)) {
         try {
             DB::beginWork();
             // enabled dimension object types
             foreach ($data as $dim_id => $ots_info) {
                 foreach ($ots_info as $ot_id => $enabled) {
                     DB::execute("UPDATE " . TABLE_PREFIX . "dimension_object_types SET enabled=" . DB::escape($enabled) . " \r\n\t\t\t\t\t\t\tWHERE dimension_id=" . DB::escape($dim_id) . " AND object_type_id=" . DB::escape($ot_id));
                     // if object type is folder, set the same configuration to all folder types
                     if (in_array($ot_id, $folder_ots)) {
                         DB::execute("UPDATE " . TABLE_PREFIX . "dimension_object_types SET enabled=" . DB::escape($enabled) . "\r\n\t\t\t\t\t\t\t\tWHERE dimension_id=" . DB::escape($dim_id) . " AND object_type_id IN (" . implode(',', $folder_ots) . ")");
                     }
                 }
             }
             // custom dimension names
             foreach ($names_data as $dim_id => $custom_name) {
                 $cname = trim($custom_name);
                 $dimension = Dimensions::getDimensionById($dim_id);
                 if ($dimension instanceof Dimension) {
                     $dimension->setOptionValue('custom_dimension_name', $cname);
                 }
             }
             DB::commit();
             flash_success(lang("success edit dimension options"));
             evt_add('tabs changed');
             //ajx_current("back");
         } catch (Exception $e) {
             DB::rollback();
             flash_error($e->getMessage());
             ajx_current("empty");
         }
     }
 }
 private function getDimensionGroups($dim_id, $conditions, $show_more_conditions, $list_subtasks_cond)
 {
     $groupId = $show_more_conditions['groupId'];
     $start = $show_more_conditions['start'];
     $limit = $show_more_conditions['limit'];
     $join_params['join_type'] = "INNER ";
     $join_params['table'] = TABLE_PREFIX . "object_members";
     $join_params['jt_field'] = "object_id";
     $join_params['e_field'] = "object_id";
     //this condition is used when we want show more task for a member
     $member_more_cond = "";
     if (!is_null($groupId) && $groupId > 0) {
         $member_more_cond = " AND  `jt`.`member_id` = {$groupId}";
     }
     $join_params['on_extra'] = " INNER  JOIN `" . TABLE_PREFIX . "members` `jtm` ON `jt`.`member_id` = `jtm`.`id` AND `jtm`.`dimension_id` = {$dim_id} AND `jt`.`is_optimization` = 0 {$member_more_cond}";
     if (is_null($groupId) || $groupId > 0) {
         $groups = ProjectTasks::instance()->listing(array("select_columns" => array("`jtm`.`id` AS group_id ", "`jtm`.`name` AS group_name ", "`jtm`.`color` AS group_icon ", "SUM(time_estimate) AS group_time_estimate ", "COUNT(`e`.`object_id`) AS total"), "extra_conditions" => $conditions . $list_subtasks_cond, "group_by" => " `jtm`.`id`", "join_params" => $join_params, "count_results" => false, "raw_data" => true))->objects;
         foreach ($groups as $key => $group) {
             if (!is_null($groupId) && $group['group_id'] != $groupId) {
                 continue;
             }
             $group_conditions = " AND `jtm`.`id` = " . $group['group_id'];
             $tasks_in_group = $this->getTasksInGroup($conditions . $group_conditions . $list_subtasks_cond, $start, $limit, $join_params);
             $groups[$key]['root_total'] = $tasks_in_group['total_roots_tasks'];
             $groups[$key]['group_tasks'] = $tasks_in_group['tasks'];
             //group totals
             $group_time_estimate = ProjectTasks::instance()->listing(array("select_columns" => array("SUM(time_estimate) AS group_time_estimate "), "extra_conditions" => $conditions . $group_conditions, "join_params" => $join_params, "count_results" => false, "raw_data" => true))->objects;
             $group_time_estimate = $group_time_estimate[0]['group_time_estimate'];
             $join_on_extra = " INNER  JOIN `" . TABLE_PREFIX . "object_members` `jtom` ON `e`.`object_id` = `jtom`.`object_id` ";
             $join_on_extra .= " INNER  JOIN `" . TABLE_PREFIX . "members` `jtm` ON `jtom`.`member_id` = `jtm`.`id` AND `jtm`.`dimension_id` = {$dim_id} AND `jtom`.`is_optimization` = 0";
             $totals = $this->getGroupTotals($conditions . $group_conditions, $group_time_estimate, $join_on_extra);
             foreach ($totals as $total_key => $total) {
                 $groups[$key][$total_key] = $total;
             }
             $groups[$key]['group_icon'] = "ico-color" . $group['group_icon'];
         }
     }
     //START unknown group
     if (is_null($groupId) || $groupId == 0) {
         $unknown_group['group_id'] = 0;
         $dimension = Dimensions::getDimensionById($dim_id);
         $unknown_group['group_name'] = lang('without a member') . " " . lang($dimension->getCode());
         $join_params['join_type'] = "LEFT ";
         $join_params['on_extra'] = " LEFT  JOIN `" . TABLE_PREFIX . "members` `jtm` ON `jt`.`member_id` = `jtm`.`id` AND `jtm`.`dimension_id` = {$dim_id} AND `jt`.`is_optimization` = 0";
         $tasks_in_group = $this->getTasksInGroup($conditions . $list_subtasks_cond, $start, $limit, $join_params, " `e`.`object_id` HAVING SUM(`jtm`.`dimension_id`) is null");
         $unknown_group['root_total'] = $tasks_in_group['total_roots_tasks'];
         $unknown_group['group_tasks'] = $tasks_in_group['tasks'];
         $unknown_group_totals = ProjectTasks::instance()->listing(array("select_columns" => array("time_estimate"), "extra_conditions" => $conditions, "group_by" => " `e`.`object_id` HAVING SUM(`jtm`.`dimension_id`) is null", "join_params" => $join_params, "count_results" => false, "raw_data" => true, "query_wraper_start" => "SELECT count(*)  AS total  , SUM(time_estimate) AS group_time_estimate FROM (", "query_wraper_end" => " ) AS temporal "))->objects;
         $unknown_group['total'] = $unknown_group_totals[0]['total'];
         $unknown_group['group_time_estimate'] = $unknown_group_totals[0]['group_time_estimate'];
         $unknown_group['estimatedTime'] = str_replace(',', ',<br>', DateTimeValue::FormatTimeDiff(new DateTimeValue(0), new DateTimeValue($unknown_group['group_time_estimate'] * 60), 'hm', 60));
         if (count($unknown_group['tasks']) > 0) {
             $groups[] = $unknown_group;
         }
     }
     //END unknown group
     return $groups;
 }
	/** 
	 * Returns all the members to be displayed in the panel that corresponds to the dimension whose id is received by
	 * parameter. It is called when the application is first loaded. 
	*/
	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){
		$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().'();');
				}
			}
		}
		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)){
				$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;
	}
	function getMembersToDisplayPath($member_ids = null, $show_all_members = false) {
		$members_info = array();
		
		if (is_null($member_ids)) {
			$member_ids = ObjectMembers::getMemberIdsByObject($this->getId());
		}
		$members = $this->manager()->getCachedMembersInfo($member_ids);

		$dimension_options = array();
		$member_count = array();
		
		$active_context_ids = active_context_members(false);

		if(count($members) > 0){
			foreach ($members as $mem) {
				$options = Dimensions::getDimensionById($mem['dimension_id'])->getOptions(true);
				if (isset($options->showInPaths) && $options->showInPaths) {
					if (!isset($members_info[$mem['dimension_id']])) $members_info[$mem['dimension_id']] = array();
					
					if (!$show_all_members && count($members_info[$mem['dimension_id']]) < 2 && !in_array($mem['id'], $active_context_ids)) {
						$members_info[$mem['dimension_id']][$mem['id']] = array(
							'ot' => $mem['object_type_id'],
							'c' => Members::getMemberById($mem['id'])->getMemberColor(),
							'name' => $mem['name'],
						);
					}
					if (!isset($member_count[$mem['dimension_id']])) $member_count[$mem['dimension_id']] = 1;
					else $member_count[$mem['dimension_id']]++;
				}
			}
		}
		
		foreach ($member_count as $did => $cant) {
			$members_info[$did]['total'] = $cant;
		}
		
		return $members_info;
	}
 function get_dimensions_for_properties()
 {
     if (!can_manage_dimension_members(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $dim_id = get_id();
     $obj_type = get_id('otype');
     $parent_id = get_id('parent');
     if ($parent_id == 0) {
         $dim_obj_type = DimensionObjectTypes::findById(array('dimension_id' => $dim_id, 'object_type_id' => $obj_type));
         if (!$dim_obj_type->getIsRoot()) {
             flash_error(lang('parent member must be selected to set properties'));
             ajx_current("empty");
             return;
         }
     }
     $dimensions = array();
     $associations_info = array();
     $associations_info_tmp = array();
     $member_parents = array();
     $associations = DimensionMemberAssociations::getAssociatations($dim_id, $obj_type);
     foreach ($associations as $assoc) {
         $assoc_info = array('id' => $assoc->getId(), 'required' => $assoc->getIsRequired(), 'multi' => $assoc->getIsMultiple(), 'ot' => $assoc->getAssociatedObjectType());
         $assoc_info['members'] = Members::getByDimensionObjType($assoc->getAssociatedDimensionMemberAssociationId(), $assoc->getAssociatedObjectType());
         $ot = ObjectTypes::findById($assoc->getAssociatedObjectType());
         $assoc_info['ot_name'] = $ot->getName();
         if (!isset($associations_info_tmp[$assoc->getAssociatedDimensionMemberAssociationId()])) {
             $associations_info_tmp[$assoc->getAssociatedDimensionMemberAssociationId()] = array();
             $dimensions[] = Dimensions::getDimensionById($assoc->getAssociatedDimensionMemberAssociationId());
         }
         $associations_info_tmp[$assoc->getAssociatedDimensionMemberAssociationId()][] = $assoc_info;
     }
     // check for restrictions
     if ($parent_id > 0) {
         $parent = Members::findById($parent_id);
         $all_parents = $parent->getAllParentMembersInHierarchy();
         $all_parent_ids = array($parent_id);
         foreach ($all_parents as $p) {
             $all_parent_ids[] = $p->getId();
         }
     } else {
         $all_parent_ids = array(0);
     }
     $all_property_members = array();
     foreach ($associations_info_tmp as $assoc_dim => $ot_infos) {
         foreach ($ot_infos as $info) {
             $restriction_defs = DimensionMemberRestrictionDefinitions::findAll(array("conditions" => "`dimension_id` = {$dim_id} AND `restricted_dimension_id` = {$assoc_dim} \n\t\t\t\t\tAND `restricted_object_type_id` = " . $info['ot']));
             if (!is_array($restriction_defs) || count($restriction_defs) == 0) {
                 // no restriction definitions => include all members
                 $associations_info[$assoc_dim][] = $info;
                 $restricted_dimensions[$assoc_dim] = false;
             } else {
                 // restriction definition found => filter members
                 $restricted_dimensions[$assoc_dim] = true;
                 $restrictions = array();
                 $rest_members = array();
                 $conditions = "";
                 foreach ($restriction_defs as $rdef) {
                     $conditions = "`restricted_member_id` IN (SELECT `id` FROM " . Members::instance()->getTableName(true) . " WHERE \n\t\t\t\t\t\t\t`object_type_id` = " . $rdef->getRestrictedObjectTypeId() . " AND `dimension_id` = {$assoc_dim}) AND `member_id` IN (" . implode(",", $all_parent_ids) . ")";
                     $restrictions[] = MemberRestrictions::findAll(array("conditions" => $conditions));
                 }
                 $to_intersect = array();
                 foreach ($restrictions as $k => $rests) {
                     $to_intersect[$k] = array();
                     foreach ($rests as $rest) {
                         $to_intersect[$k][] = $rest->getRestrictedMemberId();
                     }
                     if (count($to_intersect[$k]) == 0) {
                         unset($to_intersect[$k]);
                     }
                 }
                 $apply_filter = true;
                 $intersection = array_var($to_intersect, 0, array());
                 if (count($to_intersect) > 1) {
                     $k = 1;
                     while ($k < count($to_intersect)) {
                         $intersection = array_intersect($intersection, $to_intersect[$k++]);
                     }
                 } else {
                     if (count($to_intersect) == 0) {
                         // no restrictions found for members
                         $apply_filter = false;
                     }
                 }
                 if ($apply_filter) {
                     $rest_members = Members::findAll(array("conditions" => "`id` IN (" . implode(",", $intersection) . ")"));
                 } else {
                     $rest_members = $info['members'];
                 }
                 $new_info = $info;
                 $new_info['members'] = $rest_members;
                 $associations_info[$assoc_dim][] = $new_info;
                 foreach ($rest_members as $member) {
                     if (!isset($member_parents[$assoc_dim])) {
                         $member_parents[$assoc_dim] = array();
                     }
                     if ($member->getParentMemberId() > 0) {
                         $member_parents[$assoc_dim][$member->getId()] = $member->getParentMemberId();
                     }
                 }
             }
         }
     }
     foreach ($associations_info as $assoc_dim => $ot_infos) {
         foreach ($ot_infos as $info) {
             foreach ($info['members'] as $mem) {
                 $all_property_members[] = $mem->getId();
             }
         }
     }
     // para cada $info['ot'] ver si en el resultado hay miembros que los restringen
     foreach ($associations_info as $assoc_dim => &$ot_infos) {
         foreach ($ot_infos as &$info) {
             $restriction_defs = DimensionMemberRestrictionDefinitions::findAll(array("conditions" => "`restricted_dimension_id` = {$assoc_dim} \n\t\t\t\t\tAND `restricted_object_type_id` = " . $info['ot']));
             $restrictions = array();
             foreach ($restriction_defs as $rdef) {
                 $restrictions_tmp = MemberRestrictions::findAll(array("conditions" => "`member_id` IN (\n\t\t\t\t\t\tSELECT `id` FROM " . Members::instance()->getTableName(true) . " WHERE `dimension_id` = " . $rdef->getDimensionId() . " AND `object_type_id` = " . $rdef->getObjectTypeId() . " AND `id` IN (" . implode(",", $all_property_members) . "))"));
                 $restrictions = array_merge($restrictions, $restrictions_tmp);
             }
             $restricted_ids = array();
             if (count($restrictions) == 0) {
                 continue;
             }
             foreach ($restrictions as $rest) {
                 $restricted_ids[] = $rest->getRestrictedMemberId();
             }
             $tmp = array();
             foreach ($info['members'] as $rmem) {
                 if (in_array($rmem->getId(), $restricted_ids)) {
                     $tmp[] = $rmem;
                 }
             }
             $info['members'] = $tmp;
         }
     }
     $req_dimensions = array();
     foreach ($associations_info as $assoc_dim => &$ot_infos) {
         $required_count = 0;
         foreach ($ot_infos as &$info) {
             if ($info['required']) {
                 $required_count++;
             }
         }
         $req_dimensions[$assoc_dim] = $required_count > 0;
     }
     $member_id = get_id('mem_id');
     $actual_associations_info = array();
     if ($member_id > 0) {
         // actual associations
         $actual_associations = MemberPropertyMembers::getAssociatedPropertiesForMember($member_id);
         foreach ($actual_associations as $actual_assoc) {
             $actual_associations_info[$actual_assoc->getPropertyMemberId()] = true;
         }
     }
     tpl_assign('genid', array_var($_GET, 'genid'));
     tpl_assign('dimensions', $dimensions);
     tpl_assign('associations', $associations_info);
     tpl_assign('actual_associations', $actual_associations_info);
     tpl_assign('req_dimensions', $req_dimensions);
     tpl_assign('restricted_dimensions', isset($restricted_dimensions) ? $restricted_dimensions : array());
     ajx_extra_data(array('parents' => $member_parents, 'genid' => array_var($_GET, 'genid')));
     $this->setTemplate('dim_properties');
 }
 /**
  * Execute a report and return results
  *
  * @param $id
  * @param $params
  *
  * @return array
  */
 static function executeReport($id, $params, $order_by_col = '', $order_by_asc = true, $offset = 0, $limit = 50, $to_print = false)
 {
     if (is_null(active_context())) {
         CompanyWebsite::instance()->setContext(build_context_array(array_var($_REQUEST, 'context')));
     }
     $results = array();
     $report = self::getReport($id);
     $show_archived = false;
     if ($report instanceof Report) {
         $conditionsFields = ReportConditions::getAllReportConditionsForFields($id);
         $conditionsCp = ReportConditions::getAllReportConditionsForCustomProperties($id);
         $ot = ObjectTypes::findById($report->getReportObjectTypeId());
         $table = $ot->getTableName();
         if ($ot->getType() == 'dimension_object' || $ot->getType() == 'dimension_group') {
             $hook_parameters = array('report' => $report, 'params' => $params, 'order_by_col' => $order_by_col, 'order_by_asc' => $order_by_asc, 'offset' => $offset, 'limit' => $limit, 'to_print' => $to_print);
             $report_result = null;
             Hook::fire('replace_execute_report_function', $hook_parameters, $report_result);
             if ($report_result) {
                 return $report_result;
             }
         }
         eval('$managerInstance = ' . $ot->getHandlerClass() . "::instance();");
         eval('$item_class = ' . $ot->getHandlerClass() . '::instance()->getItemClass(); $object = new $item_class();');
         $order_by = '';
         if (is_object($params)) {
             $params = get_object_vars($params);
         }
         $report_columns = ReportColumns::getAllReportColumns($id);
         $allConditions = "";
         $contact_extra_columns = self::get_extra_contact_columns();
         if (count($conditionsFields) > 0) {
             foreach ($conditionsFields as $condField) {
                 if ($condField->getFieldName() == "archived_on") {
                     $show_archived = true;
                 }
                 $skip_condition = false;
                 $model = $ot->getHandlerClass();
                 $model_instance = new $model();
                 $col_type = $model_instance->getColumnType($condField->getFieldName());
                 $allConditions .= ' AND ';
                 $dateFormat = 'm/d/Y';
                 if (isset($params[$condField->getId()])) {
                     $value = $params[$condField->getId()];
                     if ($col_type == DATA_TYPE_DATE || $col_type == DATA_TYPE_DATETIME) {
                         $dateFormat = user_config_option('date_format');
                     }
                 } else {
                     $value = $condField->getValue();
                 }
                 if ($ot->getHandlerClass() == 'Contacts' && in_array($condField->getFieldName(), $contact_extra_columns)) {
                     $allConditions .= self::get_extra_contact_column_condition($condField->getFieldName(), $condField->getCondition(), $value);
                 } else {
                     if ($value == '' && $condField->getIsParametrizable()) {
                         $skip_condition = true;
                     }
                     if (!$skip_condition) {
                         $field_name = $condField->getFieldName();
                         if (in_array($condField->getFieldName(), Objects::getColumns())) {
                             $field_name = 'o`.`' . $condField->getFieldName();
                         }
                         if ($condField->getCondition() == 'like' || $condField->getCondition() == 'not like') {
                             $value = '%' . $value . '%';
                         }
                         if ($col_type == DATA_TYPE_DATE || $col_type == DATA_TYPE_DATETIME) {
                             if ($value == date_format_tip($dateFormat)) {
                                 $value = EMPTY_DATE;
                             } else {
                                 $dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value);
                                 $value = $dtValue->format('Y-m-d');
                             }
                         }
                         if ($condField->getCondition() != '%') {
                             if ($col_type == DATA_TYPE_INTEGER || $col_type == DATA_TYPE_FLOAT) {
                                 $allConditions .= '`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value);
                             } else {
                                 if ($condField->getCondition() == '=' || $condField->getCondition() == '<=' || $condField->getCondition() == '>=') {
                                     if ($col_type == DATA_TYPE_DATETIME || $col_type == DATA_TYPE_DATE) {
                                         $equal = 'datediff(' . DB::escape($value) . ', `' . $field_name . '`)=0';
                                     } else {
                                         $equal = '`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value);
                                     }
                                     switch ($condField->getCondition()) {
                                         case '=':
                                             $allConditions .= $equal;
                                             break;
                                         case '<=':
                                         case '>=':
                                             $allConditions .= '(`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value) . ' OR ' . $equal . ') ';
                                             break;
                                     }
                                 } else {
                                     $allConditions .= '`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value);
                                 }
                             }
                         } else {
                             $allConditions .= '`' . $field_name . '` like ' . DB::escape("%{$value}");
                         }
                     } else {
                         $allConditions .= ' true';
                     }
                 }
             }
         }
         if (count($conditionsCp) > 0) {
             $dateFormat = user_config_option('date_format');
             $date_format_tip = date_format_tip($dateFormat);
             foreach ($conditionsCp as $condCp) {
                 $cp = CustomProperties::getCustomProperty($condCp->getCustomPropertyId());
                 $skip_condition = false;
                 if (isset($params[$condCp->getId() . "_" . $cp->getName()])) {
                     $value = $params[$condCp->getId() . "_" . $cp->getName()];
                 } else {
                     $value = $condCp->getValue();
                 }
                 if ($value == '' && $condCp->getIsParametrizable()) {
                     $skip_condition = true;
                 }
                 if (!$skip_condition) {
                     $current_condition = ' AND ';
                     $current_condition .= 'o.id IN ( SELECT object_id as id FROM ' . TABLE_PREFIX . 'custom_property_values cpv WHERE ';
                     $current_condition .= ' cpv.custom_property_id = ' . $condCp->getCustomPropertyId();
                     $fieldType = $object->getColumnType($condCp->getFieldName());
                     if ($condCp->getCondition() == 'like' || $condCp->getCondition() == 'not like') {
                         $value = '%' . $value . '%';
                     }
                     if ($cp->getType() == 'date') {
                         if ($value == $date_format_tip) {
                             continue;
                         }
                         $dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value);
                         $value = $dtValue->format('Y-m-d H:i:s');
                     }
                     if ($condCp->getCondition() != '%') {
                         if ($cp->getType() == 'numeric') {
                             $current_condition .= ' AND cpv.value ' . $condCp->getCondition() . ' ' . DB::escape($value);
                         } else {
                             if ($cp->getType() == 'boolean') {
                                 $current_condition .= ' AND cpv.value ' . $condCp->getCondition() . ' ' . ($value ? '1' : '0');
                                 if (!$value) {
                                     $current_condition .= ') OR o.id NOT IN (SELECT object_id as id FROM ' . TABLE_PREFIX . 'custom_property_values cpv2 WHERE cpv2.object_id=o.id AND cpv2.value=1 AND cpv2.custom_property_id = ' . $condCp->getCustomPropertyId();
                                 }
                             } else {
                                 $current_condition .= ' AND cpv.value ' . $condCp->getCondition() . ' ' . DB::escape($value);
                             }
                         }
                     } else {
                         $current_condition .= ' AND cpv.value like ' . DB::escape("%{$value}");
                     }
                     $current_condition .= ')';
                     $allConditions .= $current_condition;
                 }
             }
         }
         $select_columns = array('*');
         $join_params = null;
         if ($order_by_col == '') {
             $order_by_col = $report->getOrderBy();
         }
         if ($ot->getHandlerClass() == 'Contacts' && in_array($order_by_col, $contact_extra_columns)) {
             $join_params = self::get_extra_contact_column_order_by($order_by_col, $order_by_col, $select_columns);
         }
         $original_order_by_col = $order_by_col;
         if (in_array($order_by_col, self::$external_columns)) {
             $order_by_col = 'name_order';
             $join_params = array('table' => Objects::instance()->getTableName(), 'jt_field' => 'id', 'e_field' => $original_order_by_col, 'join_type' => 'left');
             $select_columns = array();
             $tmp_cols = $managerInstance->getColumns();
             foreach ($tmp_cols as $col) {
                 $select_columns[] = "e.{$col}";
             }
             $tmp_cols = Objects::instance()->getColumns();
             foreach ($tmp_cols as $col) {
                 $select_columns[] = "o.{$col}";
             }
             $select_columns[] = 'jt.name as name_order';
         }
         if ($order_by_asc == null) {
             $order_by_asc = $report->getIsOrderByAsc();
         }
         if ($ot->getName() == 'task' && !SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) {
             $allConditions .= " AND assigned_to_contact_id = " . logged_user()->getId();
         }
         if ($managerInstance) {
             if ($order_by_col == "order") {
                 $order_by_col = "`{$order_by_col}`";
             }
             $listing_parameters = array("select_columns" => $select_columns, "order" => "{$order_by_col}", "order_dir" => $order_by_asc ? "ASC" : "DESC", "extra_conditions" => $allConditions, "count_results" => true, "join_params" => $join_params);
             if ($limit > 0) {
                 $listing_parameters["start"] = $offset;
                 $listing_parameters["limit"] = $limit;
             }
             if ($show_archived) {
                 $listing_parameters["archived"] = true;
             }
             $result = $managerInstance->listing($listing_parameters);
         } else {
             // TODO Performance Killer
             $result = ContentDataObjects::getContentObjects(active_context(), $ot, $order_by_col, $order_by_asc ? "ASC" : "DESC", $allConditions);
         }
         $objects = $result->objects;
         $totalResults = $result->total;
         $results['pagination'] = Reports::getReportPagination($id, $params, $original_order_by_col, $order_by_asc, $offset, $limit, $totalResults);
         $dimensions_cache = array();
         foreach ($report_columns as $column) {
             if ($column->getCustomPropertyId() == 0) {
                 $field = $column->getFieldName();
                 if (str_starts_with($field, 'dim_')) {
                     $dim_id = str_replace("dim_", "", $field);
                     $dimension = Dimensions::getDimensionById($dim_id);
                     $dimensions_cache[$dim_id] = $dimension;
                     $column_name = $dimension->getName();
                     $results['columns'][$field] = $column_name;
                     $results['db_columns'][$column_name] = $field;
                 } else {
                     if ($managerInstance->columnExists($field) || Objects::instance()->columnExists($field)) {
                         $column_name = Localization::instance()->lang('field ' . $ot->getHandlerClass() . ' ' . $field);
                         if (is_null($column_name)) {
                             $column_name = lang('field Objects ' . $field);
                         }
                         $results['columns'][$field] = $column_name;
                         $results['db_columns'][$column_name] = $field;
                     } else {
                         if ($ot->getHandlerClass() == 'Contacts') {
                             if (in_array($field, $contact_extra_columns)) {
                                 $results['columns'][$field] = lang($field);
                                 $results['db_columns'][lang($field)] = $field;
                             }
                         } else {
                             if ($ot->getHandlerClass() == 'Timeslots') {
                                 if (in_array($field, array('time', 'billing'))) {
                                     $results['columns'][$field] = lang('field Objects ' . $field);
                                     $results['db_columns'][lang('field Objects ' . $field)] = $field;
                                 }
                             } else {
                                 if ($ot->getHandlerClass() == 'MailContents') {
                                     if (in_array($field, array('to', 'cc', 'bcc', 'body_plain', 'body_html'))) {
                                         $results['columns'][$field] = lang('field Objects ' . $field);
                                         $results['db_columns'][lang('field Objects ' . $field)] = $field;
                                     }
                                 }
                             }
                         }
                     }
                 }
             } else {
                 $results['columns'][$column->getCustomPropertyId()] = $column->getCustomPropertyId();
             }
         }
         $report_rows = array();
         foreach ($objects as &$object) {
             /* @var $object Object */
             $obj_name = $object->getObjectName();
             $icon_class = $object->getIconClass();
             $row_values = array('object_type_id' => $object->getObjectTypeId());
             if (!$to_print) {
                 $row_values['link'] = '<a class="link-ico ' . $icon_class . '" title="' . clean($obj_name) . '" target="new" href="' . $object->getViewUrl() . '">&nbsp;</a>';
             }
             foreach ($report_columns as $column) {
                 if ($column->getCustomPropertyId() == 0) {
                     $field = $column->getFieldName();
                     if (str_starts_with($field, 'dim_')) {
                         $dim_id = str_replace("dim_", "", $field);
                         if (!array_var($dimensions_cache, $dim_id) instanceof Dimension) {
                             $dimension = Dimensions::getDimensionById($dim_id);
                             $dimensions_cache[$dim_id] = $dimension;
                         } else {
                             $dimension = array_var($dimensions_cache, $dim_id);
                         }
                         $om_object_id = $object instanceof Timeslot ? $object->getRelObjectId() : $object->getId();
                         $members = ObjectMembers::getMembersByObjectAndDimension($om_object_id, $dim_id, " AND om.is_optimization=0");
                         $value = "";
                         foreach ($members as $member) {
                             /* @var $member Member */
                             $val = $member->getPath();
                             $val .= ($val == "" ? "" : "/") . $member->getName();
                             if ($value != "") {
                                 $val = " - {$val}";
                             }
                             $value .= $val;
                         }
                         $row_values[$field] = $value;
                     } else {
                         if ($object instanceof Timeslot) {
                             if ($field == 'id') {
                                 $value = $object->getObjectId();
                             } else {
                                 $value = $object->getColumnValue($field);
                                 // if it is a task column
                                 if (in_array($field, ProjectTasks::instance()->getColumns())) {
                                     $task = ProjectTasks::findById($object->getRelObjectId());
                                     // if task exists
                                     if ($task instanceof ProjectTask) {
                                         $value = $task->getColumnValue($field);
                                         // if it is an external task column
                                         if (in_array($field, ProjectTasks::instance()->getExternalColumns())) {
                                             $value = self::instance()->getExternalColumnValue($field, $value, ProjectTasks::instance());
                                         } else {
                                             // if is a date then use format
                                             if (ProjectTasks::instance()->getColumnType($field) == DATA_TYPE_DATETIME && $value instanceof DateTimeValue) {
                                                 $value = format_value_to_print($field, $value->toMySQL(), DATA_TYPE_DATETIME, $report->getReportObjectTypeId());
                                             }
                                         }
                                     }
                                     $results['columns'][$field] = lang('field ProjectTasks ' . $field);
                                     $results['db_columns'][lang('field ProjectTasks ' . $field)] = $field;
                                 }
                             }
                         } else {
                             $value = $object->getColumnValue($field);
                         }
                         if ($value instanceof DateTimeValue) {
                             $dateFormat = user_config_option('date_format');
                             Hook::fire("custom_property_date_format", null, $dateFormat);
                             $tz = logged_user()->getTimezone();
                             if ($object instanceof ProjectTask) {
                                 if ($field == 'due_date' && !$object->getUseDueTime() || $field == 'start_date' && !$object->getUseStartTime()) {
                                     $dateFormat = user_config_option('date_format');
                                     $tz = 0;
                                 }
                             }
                             $value = format_date($value, $dateFormat, $tz * 3600);
                         }
                         if (in_array($field, $managerInstance->getExternalColumns())) {
                             if ($object instanceof Timeslot && $field == 'time') {
                                 $lastStop = $object->getEndTime() != null ? $object->getEndTime() : ($object->isPaused() ? $object->getPausedOn() : DateTimeValueLib::now());
                                 $seconds = $lastStop->getTimestamp() - $object->getStartTime()->getTimestamp();
                                 $hours = number_format($seconds / 3600, 2, ',', '.');
                                 $value = $hours;
                                 //$value = DateTimeValue::FormatTimeDiff($object->getStartTime(), $lastStop, "hm", 60, $object->getSubtract());
                             } else {
                                 if ($object instanceof Timeslot && $field == 'billing') {
                                     $value = config_option('currency_code', '$') . ' ' . $object->getFixedBilling();
                                 } else {
                                     $value = self::instance()->getExternalColumnValue($field, $value, $managerInstance);
                                 }
                             }
                         } else {
                             if ($field != 'link') {
                                 //$value = html_to_text(html_entity_decode($value));
                                 if ($object->getColumnType($field) == DATA_TYPE_STRING) {
                                     // change html block end tags and brs to \n, then remove all other html tags, then replace \n with <br>, to remove all styles and keep the enters
                                     $value = str_replace(array("</div>", "</p>", "<br>", "<br />", "<br/>"), "\n", $value);
                                     $value = nl2br(strip_tags($value));
                                 }
                             }
                         }
                         if (self::isReportColumnEmail($value)) {
                             if (logged_user()->hasMailAccounts()) {
                                 $value = '<a class="internalLink" href="' . get_url('mail', 'add_mail', array('to' => clean($value))) . '">' . clean($value) . '</a></div>';
                             } else {
                                 $value = '<a class="internalLink" target="_self" href="mailto:' . clean($value) . '">' . clean($value) . '</a></div>';
                             }
                         }
                         $row_values[$field] = $value;
                         if ($ot->getHandlerClass() == 'Contacts') {
                             if ($managerInstance instanceof Contacts) {
                                 $contact = Contacts::findOne(array("conditions" => "object_id = " . $object->getId()));
                                 if ($field == "email_address") {
                                     $row_values[$field] = $contact->getEmailAddress();
                                 }
                                 if ($field == "is_user") {
                                     $row_values[$field] = $contact->getUserType() > 0 && !$contact->getIsCompany();
                                 }
                                 if ($field == "im_values") {
                                     $str = "";
                                     foreach ($contact->getAllImValues() as $type => $value) {
                                         $str .= ($str == "" ? "" : " | ") . "{$type}: {$value}";
                                     }
                                     $row_values[$field] = $str;
                                 }
                                 if (in_array($field, array("mobile_phone", "work_phone", "home_phone"))) {
                                     if ($field == "mobile_phone") {
                                         $row_values[$field] = $contact->getPhoneNumber('mobile', null, false);
                                     } else {
                                         if ($field == "work_phone") {
                                             $row_values[$field] = $contact->getPhoneNumber('work', null, false);
                                         } else {
                                             if ($field == "home_phone") {
                                                 $row_values[$field] = $contact->getPhoneNumber('home', null, false);
                                             }
                                         }
                                     }
                                 }
                                 if (in_array($field, array("personal_webpage", "work_webpage", "other_webpage"))) {
                                     if ($field == "personal_webpage") {
                                         $row_values[$field] = $contact->getWebpageUrl('personal');
                                     } else {
                                         if ($field == "work_webpage") {
                                             $row_values[$field] = $contact->getWebpageUrl('work');
                                         } else {
                                             if ($field == "other_webpage") {
                                                 $row_values[$field] = $contact->getWebpageUrl('other');
                                             }
                                         }
                                     }
                                 }
                                 if (in_array($field, array("home_address", "work_address", "other_address"))) {
                                     if ($field == "home_address") {
                                         $row_values[$field] = $contact->getStringAddress('home');
                                     } else {
                                         if ($field == "work_address") {
                                             $row_values[$field] = $contact->getStringAddress('work');
                                         } else {
                                             if ($field == "other_address") {
                                                 $row_values[$field] = $contact->getStringAddress('other');
                                             }
                                         }
                                     }
                                 }
                             }
                         } else {
                             if ($ot->getHandlerClass() == 'MailContents') {
                                 if (in_array($field, array('to', 'cc', 'bcc', 'body_plain', 'body_html'))) {
                                     $mail_data = MailDatas::findById($object->getId());
                                     $row_values[$field] = $mail_data->getColumnValue($field);
                                     if ($field == "body_html") {
                                         if (class_exists("DOMDocument")) {
                                             $d = new DOMDocument();
                                             $mock = new DOMDocument();
                                             $d->loadHTML(remove_css_and_scripts($row_values[$field]));
                                             $body = $d->getElementsByTagName('body')->item(0);
                                             foreach ($body->childNodes as $child) {
                                                 $mock->appendChild($mock->importNode($child, true));
                                             }
                                             // if css is inside an html comment => remove it
                                             $row_values[$field] = preg_replace('/<!--(.*)-->/Uis', '', remove_css($row_values[$field]));
                                         } else {
                                             $row_values[$field] = preg_replace('/<!--(.*)-->/Uis', '', remove_css_and_scripts($row_values[$field]));
                                         }
                                     }
                                 }
                             }
                         }
                         if (!$to_print && $field == "name") {
                             $row_values[$field] = '<a target="new-' . $object->getId() . '" href="' . $object->getViewUrl() . '">' . $value . '</a>';
                         }
                     }
                 } else {
                     $colCp = $column->getCustomPropertyId();
                     $cp = CustomProperties::getCustomProperty($colCp);
                     if ($cp instanceof CustomProperty) {
                         /* @var $cp CustomProperty */
                         $row_values[$cp->getName()] = get_custom_property_value_for_listing($cp, $object);
                         $results['columns'][$colCp] = $cp->getName();
                         $results['db_columns'][$cp->getName()] = $colCp;
                     }
                 }
             }
             Hook::fire("report_row", $object, $row_values);
             $report_rows[] = $row_values;
         }
         if (!$to_print) {
             if (is_array($results['columns'])) {
                 array_unshift($results['columns'], '');
             } else {
                 $results['columns'] = array('');
             }
             Hook::fire("report_header", $ot, $results['columns']);
         }
         $results['rows'] = $report_rows;
     }
     return $results;
 }
 function getMembersToDisplayPath()
 {
     $members_info = array();
     $member_ids = ObjectMembers::getMemberIdsByObject($this->getId());
     if (count($member_ids) == 0) {
         $member_ids[] = 0;
     }
     $db_res = DB::execute("SELECT id, name, dimension_id, object_type_id FROM " . TABLE_PREFIX . "members WHERE id IN (" . implode(",", $member_ids) . ")");
     $members = $db_res->fetchAll();
     $dimension_options = array();
     if (count($members) > 0) {
         foreach ($members as $mem) {
             $options = Dimensions::getDimensionById($mem['dimension_id'])->getOptions(true);
             if (isset($options->showInPaths) && $options->showInPaths) {
                 if (!isset($members_info[$mem['dimension_id']])) {
                     $members_info[$mem['dimension_id']] = array();
                 }
                 $members_info[$mem['dimension_id']][$mem['id']] = array('ot' => $mem['object_type_id'], 'c' => Members::findById($mem['id'])->getMemberColor(), 'name' => $mem['name']);
             }
         }
     }
     return $members_info;
 }
Esempio n. 10
0
/**
 * Returns the users with permissions for the object type $object_type for the context $context
 * 
 * @param $object_type_id Object Type
 * @param $context Context
 * @param $access_level (ACCESS_LEVEL_READ, ACCESS_LEVEL_WRITE, ACCESS_LEVEL_DELETE)
 * @param $extra_conditions Extra conditions to add to the users query
 * @param $to_assign true if this function is called to fill the "assigned to" combobox when editing a task
 */
function allowed_users_in_context($object_type_id, $context = null, $access_level = ACCESS_LEVEL_READ, $extra_conditions = "")
{
    $result = array();
    $members = array();
    if (isset($context) && is_array($context)) {
        foreach ($context as $selection) {
            if ($selection instanceof Member) {
                $members[] = $selection;
            }
        }
    }
    if (count($members) == 0) {
        $logged_user_pgs = logged_user()->getPermissionGroupIds();
        if (count($logged_user_pgs) > 0) {
            $dimensions = Dimensions::getAllowedDimensions($object_type_id);
            foreach ($dimensions as $d) {
                $dim = Dimensions::getDimensionById(array_var($d, 'dimension_id'));
                if ($dim instanceof Dimension && $dim->getDefinesPermissions() && $dim->getCode() != 'feng_persons' && $dim->getCode() != 'feng_users') {
                    if ($dim->hasAllowAllForContact(implode(",", $logged_user_pgs))) {
                        $permission_conditions = "";
                    } else {
                        $permission_conditions = " AND EXISTS (SELECT cmp.permission_group_id FROM " . TABLE_PREFIX . "contact_member_permissions cmp \n\t\t\t\t\t\t\t\tWHERE cmp.permission_group_id IN (" . implode(",", $logged_user_pgs) . ") AND cmp.member_id=" . TABLE_PREFIX . "members.id AND cmp.object_type_id={$object_type_id})";
                    }
                    $members = array_merge($members, $dim->getAllMembers(false, null, true, $permission_conditions));
                }
            }
        }
    }
    $all_permission_groups = array();
    $rows = DB::executeAll("SELECT DISTINCT permission_group_id FROM " . TABLE_PREFIX . "contact_permission_groups");
    foreach ($rows as $row) {
        $all_permission_groups[] = $row['permission_group_id'];
    }
    $allowed_permission_groups = can_access_pgids($all_permission_groups, $members, $object_type_id, $access_level);
    if (count($allowed_permission_groups) > 0) {
        $result = Contacts::instance()->findAll(array('conditions' => "id IN (SELECT DISTINCT contact_id FROM " . TABLE_PREFIX . "contact_permission_groups\n\t\t\t\t\t\t\t\tWHERE permission_group_id IN (" . implode(",", $allowed_permission_groups) . ") {$extra_conditions})", 'order' => 'name'));
    }
    return $result;
}
Esempio n. 11
0
 function workEstimate(ProjectTask $task)
 {
     tpl_assign('task_assigned', $task);
     if (!$task->getAssignedTo() instanceof Contact) {
         return true;
         // not assigned to user
     }
     if (!is_valid_email($task->getAssignedTo()->getEmailAddress())) {
         return true;
     }
     $locale = $task->getAssignedTo()->getLocale();
     Localization::instance()->loadSettings($locale, ROOT . '/language');
     tpl_assign('title', $task->getObjectName());
     tpl_assign('by', $task->getAssignedBy()->getObjectName());
     tpl_assign('asigned', $task->getAssignedTo()->getObjectName());
     $text = "";
     if (config_option("wysiwyg_tasks")) {
         $text = purify_html(nl2br($task->getDescription()));
     } else {
         $text = escape_html_whitespace($task->getDescription());
     }
     tpl_assign('description', $text);
     //descripction
     tpl_assign('description_title', lang("new task work estimate to you desc", $task->getObjectName(), $task->getCreatedBy()->getObjectName()));
     //description_title
     //priority
     if ($task->getPriority()) {
         if ($task->getPriority() >= ProjectTasks::PRIORITY_URGENT) {
             $priorityColor = "#FF0000";
             $priority = lang('urgent priority');
         } else {
             if ($task->getPriority() >= ProjectTasks::PRIORITY_HIGH) {
                 $priorityColor = "#FF9088";
                 $priority = lang('high priority');
             } else {
                 if ($task->getPriority() <= ProjectTasks::PRIORITY_LOW) {
                     $priorityColor = "white";
                     $priority = lang('low priority');
                 } else {
                     $priorityColor = "#DAE3F0";
                     $priority = lang('normal priority');
                 }
             }
         }
         tpl_assign('priority', array($priority, $priorityColor));
     }
     //context
     $contexts = array();
     if ($task->getMembersToDisplayPath()) {
         $members = $task->getMembersToDisplayPath();
         foreach ($members as $key => $member) {
             $dim = Dimensions::getDimensionById($key);
             if ($dim->getCode() == "customer_project") {
                 foreach ($members[$key] as $member) {
                     $obj_type = ObjectTypes::findById($member['ot']);
                     $contexts[$dim->getCode()][$obj_type->getName()][] = '<span style="' . get_workspace_css_properties($member['c']) . '">' . $member['name'] . '</span>';
                 }
             } else {
                 foreach ($members[$key] as $member) {
                     $contexts[$dim->getCode()][] = '<span style="' . get_workspace_css_properties($member['c']) . '">' . $member['name'] . '</span>';
                 }
             }
         }
     }
     tpl_assign('contexts', $contexts);
     //workspaces
     //start date, due date or start
     if ($task->getStartDate() instanceof DateTimeValue) {
         $date = Localization::instance()->formatDescriptiveDate($task->getStartDate(), $task->getAssignedTo()->getTimezone());
         $time = Localization::instance()->formatTime($task->getStartDate(), $task->getAssignedTo()->getTimezone());
         if ($time > 0) {
             $date .= " " . $time;
         }
         tpl_assign('start_date', $date);
         //start_date
     }
     if ($task->getDueDate() instanceof DateTimeValue) {
         $date = Localization::instance()->formatDescriptiveDate($task->getDueDate(), $task->getAssignedTo()->getTimezone());
         $time = Localization::instance()->formatTime($task->getDueDate(), $task->getAssignedTo()->getTimezone());
         if ($time > 0) {
             $date .= " " . $time;
         }
         tpl_assign('due_date', $date);
         //due_date
     }
     $attachments = array();
     try {
         $content = FileRepository::getBackend()->getFileContent(owner_company()->getPictureFile());
         $file_path = ROOT . "/upload/logo_empresa.png";
         $handle = fopen($file_path, 'wb');
         fwrite($handle, $content);
         fclose($handle);
         if ($content != "") {
             $attachments['logo'] = array('cid' => gen_id() . substr($task->getAssignedBy()->getEmailAddress(), strpos($task->getAssignedBy()->getEmailAddress(), '@')), 'path' => $file_path, 'type' => 'image/png', 'disposition' => 'inline', 'name' => 'logo_empresa.png');
             tpl_assign('attachments', $attachments);
             // attachments
         }
     } catch (FileNotInRepositoryError $e) {
         // If no logo is set, don't interrupt notifications.
     }
     tpl_assign('attachments', $attachments);
     // attachments
     self::queueEmail(array(self::prepareEmailAddress($task->getCreatedBy()->getEmailAddress(), $task->getCreatedBy()->getObjectName())), self::prepareEmailAddress($task->getUpdatedBy()->getEmailAddress(), $task->getUpdatedByDisplayName()), lang('work estimate title'), tpl_fetch(get_template_path('work_estimate', 'notifier')), 'text/html', '8bit', $attachments);
     // send
     $locale = logged_user() instanceof Contact ? logged_user()->getLocale() : DEFAULT_LOCALIZATION;
     Localization::instance()->loadSettings($locale, ROOT . '/language');
 }
Esempio n. 12
0
/**
 * Returns the users with permissions for the object type $object_type for the context $context
 * 
 * @param $object_type_id Object Type
 * @param $context Context
 * @param $access_level (ACCESS_LEVEL_READ, ACCESS_LEVEL_WRITE, ACCESS_LEVEL_DELETE)
 * @param $extra_conditions Extra conditions to add to the users query
 * @param $to_assign true if this function is called to fill the "assigned to" combobox when editing a task
 */
function allowed_users_in_context($object_type_id, $context = null, $access_level = ACCESS_LEVEL_READ, $extra_conditions = "", $for_tasks_filter = false)
{
    $result = array();
    $members = array();
    if (isset($context) && is_array($context)) {
        foreach ($context as $selection) {
            if ($selection instanceof Member && $selection->getDimension()->getDefinesPermissions() && $selection->getDimension()->getIsManageable()) {
                $members[] = $selection;
            }
        }
    }
    $zero_members = false;
    if (count($members) == 0) {
        $zero_members = true;
        $logged_user_pgs = logged_user()->getPermissionGroupIds();
        if (count($logged_user_pgs) > 0) {
            $dimensions = Dimensions::getAllowedDimensions($object_type_id);
            foreach ($dimensions as $d) {
                $dim = Dimensions::getDimensionById(array_var($d, 'dimension_id'));
                if ($dim instanceof Dimension && $dim->getDefinesPermissions() && $dim->getCode() != 'feng_persons' && $dim->getCode() != 'feng_users') {
                    if ($dim->hasAllowAllForContact(implode(",", $logged_user_pgs))) {
                        $permission_conditions = "";
                    } else {
                        $permission_conditions = " AND EXISTS (SELECT cmp.permission_group_id FROM " . TABLE_PREFIX . "contact_member_permissions cmp \r\n\t\t\t\t\t\t\t\tWHERE cmp.permission_group_id IN (" . implode(",", $logged_user_pgs) . ") AND cmp.member_id=" . TABLE_PREFIX . "members.id AND cmp.object_type_id={$object_type_id})";
                    }
                    $members = array_merge($members, $dim->getAllMembers(false, null, true, $permission_conditions));
                }
            }
        }
    }
    $all_permission_groups = array();
    $rows = DB::executeAll("SELECT DISTINCT permission_group_id FROM " . TABLE_PREFIX . "contact_permission_groups");
    foreach ($rows as $row) {
        $all_permission_groups[] = $row['permission_group_id'];
    }
    if ($zero_members && $for_tasks_filter) {
        $allowed_permission_groups = get_user_pgs_with_permissions_in_my_members($object_type_id);
    } else {
        if ($zero_members && config_option('let_users_create_objects_in_root') && (logged_user()->isAdminGroup() || logged_user()->isExecutive() || logged_user()->isManager())) {
            $allowed_permission_groups = array_flat(DB::executeAll("SELECT permission_group_id FROM " . TABLE_PREFIX . "contact_member_permissions WHERE member_id=0 AND object_type_id={$object_type_id}"));
        } else {
            $allowed_permission_groups = can_access_pgids($all_permission_groups, $members, $object_type_id, $access_level);
        }
    }
    foreach ($allowed_permission_groups as $k => &$apg) {
        if (trim($apg) == '') {
            unset($allowed_permission_groups[$k]);
        }
    }
    if (count($allowed_permission_groups) > 0) {
        $isSuperAdmin = " OR user_type IN (SELECT id FROM " . TABLE_PREFIX . "permission_groups WHERE type='roles' AND name = 'Super Administrator')";
        $result = Contacts::instance()->findAll(array('conditions' => "disabled=0 AND (\r\n\t\t\t\t\t\t\t\t\t\t\tid IN (SELECT DISTINCT contact_id FROM " . TABLE_PREFIX . "contact_permission_groups\r\n\t\t\t\t\t\t\t\t\t\t\tWHERE permission_group_id IN (" . implode(",", $allowed_permission_groups) . ") \r\n\t\t\t\t\t\t\t\t\t\t\t{$isSuperAdmin}\r\n\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t{$extra_conditions})", 'order' => 'name'));
    }
    return $result;
}
 /**
  * 
  * 
  */
 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;
     }
 }
 function getMembersToDisplayPath($member_ids = null, $show_all_members = false, $show_active_context_members = true)
 {
     $members_info = array();
     if (is_null($member_ids)) {
         $member_ids = ObjectMembers::getMemberIdsByObject($this->getId());
     }
     $members = $this->manager()->getCachedMembersInfo($member_ids);
     $dimension_options = array();
     $member_count = array();
     $active_context_ids = active_context_members(false);
     $to_display = user_config_option('breadcrumb_member_count');
     if (count($members) > 0) {
         foreach ($members as $mem) {
             $dimension = Dimensions::getDimensionById($mem['dimension_id']);
             if (intval($dimension->getOptionValue('showInPaths'))) {
                 if (!isset($members_info[$mem['dimension_id']])) {
                     $members_info[$mem['dimension_id']] = array();
                 }
                 $active_context_condition = true;
                 if (!$show_active_context_members) {
                     $active_context_condition = !in_array($mem['id'], $active_context_ids);
                 }
                 if (!$show_all_members && count($members_info[$mem['dimension_id']]) < $to_display && $active_context_condition) {
                     $members_info[$mem['dimension_id']][$mem['id']] = array('ot' => $mem['object_type_id'], 'c' => Members::getMemberById($mem['id'])->getMemberColor(), 'name' => $mem['name']);
                 }
                 if (!isset($member_count[$mem['dimension_id']])) {
                     $member_count[$mem['dimension_id']] = 1;
                 } else {
                     $member_count[$mem['dimension_id']]++;
                 }
             }
         }
     }
     foreach ($member_count as $did => $cant) {
         $members_info[$did]['total'] = $cant;
     }
     return $members_info;
 }
    /**
     * Used for Drag & Drop, adds objects to a member
     * @author alvaro
     */
    function add_objects_to_member()
    {
        $ids = json_decode(array_var($_POST, 'objects'));
        $mem_id = array_var($_POST, 'member');
        if (!is_array($ids) || count($ids) == 0) {
            ajx_current("empty");
            return;
        }
        try {
            DB::beginWork();
            if ($mem_id) {
                $user_ids = array();
                $member = Members::findById($mem_id);
                $objects = array();
                $from = array();
                foreach ($ids as $oid) {
                    /* @var $obj ContentDataObject */
                    $obj = Objects::findObject($oid);
                    if ($obj instanceof ContentDataObject && $obj->canAddToMember(logged_user(), $member, active_context())) {
                        $dim_obj_type_content = DimensionObjectTypeContents::findOne(array('conditions' => array('`dimension_id`=? AND `dimension_object_type_id`=? AND `content_object_type_id`=?', $member->getDimensionId(), $member->getObjectTypeId(), $obj->getObjectTypeId())));
                        if (!$dim_obj_type_content instanceof DimensionObjectTypeContent) {
                            continue;
                        }
                        if (!$dim_obj_type_content->getIsMultiple() || array_var($_POST, 'remove_prev')) {
                            $db_res = DB::execute("SELECT group_concat(om.member_id) as old_members FROM " . TABLE_PREFIX . "object_members om INNER JOIN " . TABLE_PREFIX . "members m ON om.member_id=m.id WHERE m.dimension_id=" . $member->getDimensionId() . " AND om.object_id=" . $obj->getId());
                            $row = $db_res->fetchRow();
                            if (array_var($row, 'old_members') != "") {
                                $from[$obj->getId()] = $row['old_members'];
                            }
                            // remove from previous members
                            ObjectMembers::delete('`object_id` = ' . $obj->getId() . ' AND `member_id` IN (SELECT `m`.`id` FROM `' . TABLE_PREFIX . 'members` `m` WHERE `m`.`dimension_id` = ' . $member->getDimensionId() . ')');
                        }
                        $obj->addToMembers(array($member));
                        $obj->addToSharingTable();
                        $objects[] = $obj;
                        if (Plugins::instance()->isActivePlugin('mail') && $obj instanceof MailContent) {
                            $conversation = MailContents::getMailsFromConversation($obj);
                            foreach ($conversation as $conv_email) {
                                if (array_var($_POST, 'attachment') && $conv_email->getHasAttachments()) {
                                    MailUtilities::parseMail($conv_email->getContent(), $decoded, $parsedEmail, $warnings);
                                    $classification_data = array();
                                    for ($j = 0; $j < count(array_var($parsedEmail, "Attachments", array())); $j++) {
                                        $classification_data["att_" . $j] = true;
                                    }
                                    MailController::classifyFile($classification_data, $conv_email, $parsedEmail, array($member), array_var($_POST, 'remove_prev'), false);
                                }
                            }
                        }
                        // if object is contact ask to add default permissions in member
                        if ($obj instanceof Contact && $obj->isUser() && can_manage_security(logged_user())) {
                            $user_ids[] = $obj->getId();
                        }
                    } else {
                        throw new Exception(lang('you dont have permissions to classify object in member', $obj->getName(), $member->getName()));
                    }
                }
                // if object is contact ask to add default permissions in member
                if (can_manage_security(logged_user()) && count($user_ids) > 0 && $member->getDimension()->getDefinesPermissions()) {
                    evt_add('ask to assign default permissions', array('user_ids' => $user_ids, 'member' => array('id' => $member->getId(), 'name' => clean($member->getName())), ''));
                }
                Hook::fire('after_dragdrop_classify', $objects, $member);
                $display_name = $member->getName();
                $lang_key = count($ids) > 1 ? 'objects moved to member success' : 'object moved to member success';
                $log_datas = array();
                $actions = array();
                // add to application logs
                foreach ($objects as $obj) {
                    $actions[$obj->getId()] = array_var($from, $obj->getId()) ? ApplicationLogs::ACTION_MOVE : ApplicationLogs::ACTION_COPY;
                    $log_datas[$obj->getId()] = (array_var($from, $obj->getId()) ? "from:" . array_var($from, $obj->getId()) . ";" : "") . "to:" . $member->getId();
                }
            } else {
                if ($dim_id = array_var($_POST, 'dimension')) {
                    $dimension = Dimensions::getDimensionById($dim_id);
                    $from = array();
                    foreach ($ids as $oid) {
                        /* @var $obj ContentDataObject */
                        $obj = Objects::findObject($oid);
                        if ($obj instanceof ContentDataObject) {
                            $db_res = DB::execute("SELECT group_concat(om.member_id) as old_members FROM " . TABLE_PREFIX . "object_members om INNER JOIN " . TABLE_PREFIX . "members m ON om.member_id=m.id WHERE m.dimension_id=" . $dim_id . " AND om.object_id=" . $obj->getId());
                            $row = $db_res->fetchRow();
                            if (array_var($row, 'old_members') != "") {
                                $from[$obj->getId()] = $row['old_members'];
                            }
                            // remove from previous members
                            ObjectMembers::delete('`object_id` = ' . $obj->getId() . ' AND `member_id` IN (
							SELECT `m`.`id` FROM `' . TABLE_PREFIX . 'members` `m` WHERE `m`.`dimension_id` = ' . $dim_id . ')');
                        }
                        $obj->addToMembers(array());
                        $obj->addToSharingTable();
                        $objects[] = $obj;
                    }
                    $display_name = $dimension->getName();
                    $lang_key = count($ids) > 1 ? 'objects removed from' : 'object removed from';
                    $log_datas = array();
                    $actions = array();
                    // add to application logs
                    foreach ($objects as $obj) {
                        $actions[$obj->getId()] = array_var($from, $obj->getId()) ? ApplicationLogs::ACTION_MOVE : ApplicationLogs::ACTION_COPY;
                        $log_datas[$obj->getId()] = array_var($from, $obj->getId()) ? "from:" . array_var($from, $obj->getId()) . ";" : "";
                    }
                }
            }
            DB::commit();
            foreach ($objects as $object) {
                ApplicationLogs::instance()->createLog($object, $actions[$object->getId()], false, true, true, $log_datas[$object->getId()]);
            }
            flash_success(lang($lang_key, $display_name));
            if (array_var($_POST, 'reload')) {
                ajx_current('reload');
            } else {
                ajx_current('empty');
            }
        } catch (Exception $e) {
            DB::rollback();
            ajx_current("empty");
            flash_error($e->getMessage());
        }
    }
Esempio n. 16
0
 /**
  * @return Dimension
  * Returns the dimension associated to this member
  */
 function getDimension()
 {
     return Dimensions::getDimensionById($this->getDimensionId());
 }
 function search_dimension_members_tree()
 {
     $dimension_id = array_var($_REQUEST, 'dimension_id');
     $dimension = Dimensions::getDimensionById($dimension_id);
     $name = trim(array_var($_REQUEST, 'query', ''));
     $random = trim(array_var($_REQUEST, 'random', 0));
     $start = array_var($_REQUEST, 'start', 0);
     $limit = array_var($_REQUEST, 'limit');
     $order = array_var($_REQUEST, 'order', 'id');
     $parents = array_var($_REQUEST, 'parents', true);
     $allowed_member_types_str = array_var($_REQUEST, 'allowed_member_types', '');
     if ($allowed_member_types_str != '') {
         $allowed_member_types = explode(',', $allowed_member_types_str);
     } else {
         $allowed_member_types = array();
     }
     if (strlen($name) > 0 || $random) {
         //get the member list
         //Super admins are not using the contact member cache
         if (logged_user()->isAdministrator() || !$dimension->getDefinesPermissions()) {
             $limit_t = '';
             if (isset($limit)) {
                 $limit_t = $limit + 1;
             }
             $search_name_cond = "";
             if (!$random) {
                 $name = mysql_real_escape_string($name);
                 $search_name_cond = " AND name LIKE '%" . $name . "%'";
             }
             $member_type_cond = "";
             if (count($allowed_member_types) > 0) {
                 $member_type_cond = " AND object_type_id IN (" . implode(',', $allowed_member_types) . ")";
             }
             $memberList = Members::findAll(array('conditions' => array("`dimension_id`=? AND archived_by_id=0 {$search_name_cond} {$member_type_cond}", $dimension_id), 'order' => '`' . $order . '` ASC', 'offset' => $start, 'limit' => $limit_t));
             // filter $childs by other dimension associations
             $context = active_context();
             $filter_by_members = array();
             foreach ($context as $selection) {
                 if ($selection instanceof Member) {
                     $filter_by_members[] = $selection;
                 }
             }
             $memberList = $this->apply_association_filters($dimension, $memberList, $filter_by_members);
             //include all parents
             //Check hierarchy
             if ($parents) {
                 $members_ids = array();
                 $parent_members = array();
                 foreach ($memberList as $mem) {
                     $members_ids[] = $mem->getId();
                 }
                 foreach ($memberList as $mem) {
                     $parents = $mem->getAllParentMembersInHierarchy(false);
                     foreach ($parents as $parent) {
                         if (!in_array($parent->getId(), $members_ids)) {
                             $members_ids[] = $parent->getId();
                             $parent_members[] = $parent;
                         }
                     }
                 }
                 $memberList = array_merge($memberList, $parent_members);
             }
         } else {
             //Use contact member cache
             $params = array();
             $params["dimension"] = $dimension;
             $params["contact_id"] = logged_user()->getId();
             $params["get_all_parent_in_hierarchy"] = $parents;
             $params["order"] = $order;
             if (!$random) {
                 $params["member_name"] = $name;
             }
             if (isset($limit)) {
                 $params["start"] = $start;
                 $params["limit"] = $limit + 1;
             }
             $params["extra_condition"] = " AND m.archived_by_id=0 ";
             if (count($allowed_member_types) > 0) {
                 $params["extra_condition"] .= " AND m.object_type_id IN (" . implode(',', $allowed_member_types) . ")";
             }
             $memberList = ContactMemberCaches::getAllMembersWithCachedParentId($params);
         }
         //show more
         $show_more = false;
         if (isset($limit) && count($memberList) > $limit) {
             array_pop($memberList);
             $show_more = true;
         }
         if (!empty($memberList)) {
             $allMemebers = $this->buildMemberList($memberList, $dimension, array(), array(), null, null);
             if (isset($limit)) {
                 ajx_extra_data(array('show_more' => $show_more));
             }
             $row = "search-result-row-medium";
             if (!$dimension->canHaveHierarchies()) {
                 $row = "search-result-row-small";
             }
             ajx_extra_data(array('row_class' => $row));
             ajx_extra_data(array('members' => $allMemebers));
         }
     }
     ajx_extra_data(array('dimension_id' => $dimension_id));
     ajx_current("empty");
 }
Esempio n. 18
0
function build_context_array($context_plain) {
	$context = null ;
	if (!empty($context_plain)) {
		$dimensions = json_decode($context_plain) ;
		if ($dimensions) {
			$context = array () ;
			foreach ($dimensions as $dimensionId => $members) {
				if (!$dimensionId || $dimensionId == 'undefined') continue;
				if ($members && is_array($members)) {
					//cambiar
					foreach ($members as $member) {
						if ($member && is_numeric($member)) { 
							$member = Members::findById($member) ;													
							if ($member instanceof Member ){
								$context[] = $member ;
							}
						}elseif($member === 0 && count($members)<=1){
							// IS root. Retrieve the dimension 
							$dimension = Dimensions::getDimensionById($dimensionId) ;								
							if ($dimension instanceof Dimension ){					
								$context[] = $dimension ;
							}
						}
					}
				}
			}
		}
	}
	return $context;
}
 static function prepareAssociationConditions($redefined_context, $dimensions, $properties, $object_type_id, $pg_ids, $selection_members)
 {
     $is_property = array();
     foreach ($properties as $p => $value) {
         //obtener miembros de la dimension asociada que tienen como propiedad los miembros seleccionados de esta dimension
         foreach ($value as $v) {
             $associations = DimensionMemberAssociations::getAllAssociations($v, $p);
             if (!is_null($associations)) {
                 foreach ($associations as $association) {
                     $is_property[$v] = true;
                     $v_ids_csv = is_array($dimensions[$v]['allowed_members']) && count($dimensions[$v]['allowed_members']) > 0 ? implode(",", $dimensions[$v]['allowed_members']) : '0';
                     $p_ids_csv = is_array($dimensions[$p]['allowed_members']) && count($dimensions[$p]['allowed_members']) > 0 ? implode(",", $dimensions[$p]['allowed_members']) : '0';
                     $prop_members = MemberPropertyMembers::getAssociatedMembers($association->getId(), $v_ids_csv, $p_ids_csv);
                     if (count($prop_members) > 0) {
                         $property_members[] = $prop_members;
                     }
                 }
             }
         }
     }
     // intersect the allowed members for each property
     $member_intersection = array_var($property_members, 0, array());
     if (count($property_members) > 1) {
         $k = 1;
         while ($k < count($property_members)) {
             $member_intersection = array_intersect($member_intersection, $property_members[$k++]);
         }
     }
     $association_conditions = "";
     foreach ($redefined_context as $key => $value) {
         $dimension = Dimensions::getDimensionById($value);
         if (!isset($is_property[$value])) {
             $member_ids = $dimensions[$value]['allowed_members'];
         } else {
             $member_ids = $member_intersection;
         }
         $association_conditions .= self::prepareQuery($association_conditions, $dimension, $member_ids, $object_type_id, $pg_ids, 'AND', $selection_members);
     }
     $dims = Dimensions::findAll();
     foreach ($dims as $dim) {
         if (!in_array($dim->getId(), $redefined_context) && !isset($properties[$dim->getId()]) && $dim->canContainObjects()) {
             $member_ids = array();
             $all_members = $dim->getAllMembers();
             foreach ($all_members as $member) {
                 $member_ids[] = $member->getId();
             }
             $association_conditions .= self::prepareQuery($association_conditions, $dim, $member_ids, $object_type_id, $pg_ids, 'OR', $selection_members, true);
         }
     }
     return $association_conditions;
 }
Esempio n. 20
0
	/**
	 * Execute a report and return results
	 *
	 * @param $id
	 * @param $params
	 *
	 * @return array
	 */
	static function executeReport($id, $params, $order_by_col = '', $order_by_asc = true, $offset=0, $limit=50, $to_print = false) {
		if (is_null(active_context())) {
			CompanyWebsite::instance()->setContext(build_context_array(array_var($_REQUEST, 'context')));
		}
		$results = array();
		$report = self::getReport($id);
		if($report instanceof Report){
			$conditionsFields = ReportConditions::getAllReportConditionsForFields($id);
			$conditionsCp = ReportConditions::getAllReportConditionsForCustomProperties($id);
			
			$ot = ObjectTypes::findById($report->getReportObjectTypeId());
			$table = $ot->getTableName();
			
			eval('$managerInstance = ' . $ot->getHandlerClass() . "::instance();");
			eval('$item_class = ' . $ot->getHandlerClass() . '::instance()->getItemClass(); $object = new $item_class();');
			
			$order_by = '';
			if (is_object($params)) {
				$params = get_object_vars($params);				
			}
			
			$report_columns = ReportColumns::getAllReportColumns($id);

			$allConditions = "";
			
			if(count($conditionsFields) > 0){
				foreach($conditionsFields as $condField){
					
					$skip_condition = false;
					$model = $ot->getHandlerClass();
					$model_instance = new $model();
					$col_type = $model_instance->getColumnType($condField->getFieldName());

					$allConditions .= ' AND ';
					$dateFormat = 'm/d/Y';
					if(isset($params[$condField->getId()])){
						$value = $params[$condField->getId()];
						if ($col_type == DATA_TYPE_DATE || $col_type == DATA_TYPE_DATETIME)
						$dateFormat = user_config_option('date_format');
					} else {
						$value = $condField->getValue();
					}
					if ($value == '' && $condField->getIsParametrizable()) $skip_condition = true;
					if (!$skip_condition) {
						if($condField->getCondition() == 'like' || $condField->getCondition() == 'not like'){
							$value = '%'.$value.'%';
						}
						if ($col_type == DATA_TYPE_DATE || $col_type == DATA_TYPE_DATETIME) {
							$dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value);
							$value = $dtValue->format('Y-m-d');
						}
						if($condField->getCondition() != '%'){
							if ($col_type == DATA_TYPE_INTEGER || $col_type == DATA_TYPE_FLOAT) {
								$allConditions .= '`'.$condField->getFieldName().'` '.$condField->getCondition().' '.DB::escape($value);
							} else {
								if ($condField->getCondition()=='=' || $condField->getCondition()=='<=' || $condField->getCondition()=='>='){
									if ($col_type == DATA_TYPE_DATETIME || $col_type == DATA_TYPE_DATE) {
										$equal = 'datediff('.DB::escape($value).', `'.$condField->getFieldName().'`)=0';
									} else {
										$equal = '`'.$condField->getFieldName().'` '.$condField->getCondition().' '.DB::escape($value);
									}
									switch($condField->getCondition()){
										case '=':
											$allConditions .= $equal;
											break;
										case '<=':
										case '>=':
											$allConditions .= '(`'.$condField->getFieldName().'` '.$condField->getCondition().' '.DB::escape($value).' OR '.$equal.') ';
											break;																
									}										
								} else {
									$allConditions .= '`'.$condField->getFieldName().'` '.$condField->getCondition().' '.DB::escape($value);
								}									
							}
						} else {
							$allConditions .= '`'.$condField->getFieldName().'` like '.DB::escape("%$value");
						}
					} else $allConditions .= ' true';
					
				}
			}
			if(count($conditionsCp) > 0){
				$dateFormat = user_config_option('date_format');
				$date_format_tip = date_format_tip($dateFormat);
				
				foreach($conditionsCp as $condCp){
					$cp = CustomProperties::getCustomProperty($condCp->getCustomPropertyId());

					$skip_condition = false;
					
					if(isset($params[$condCp->getId()."_".$cp->getName()])){
						$value = $params[$condCp->getId()."_".$cp->getName()];
					}else{
						$value = $condCp->getValue();
					}
					if ($value == '' && $condCp->getIsParametrizable()) $skip_condition = true;
					if (!$skip_condition) {
						$current_condition = ' AND ';
						$current_condition .= 'o.id IN ( SELECT object_id as id FROM '.TABLE_PREFIX.'custom_property_values cpv WHERE ';
						$current_condition .= ' cpv.custom_property_id = '.$condCp->getCustomPropertyId();
						$fieldType = $object->getColumnType($condCp->getFieldName());

						if($condCp->getCondition() == 'like' || $condCp->getCondition() == 'not like'){
							$value = '%'.$value.'%';
						}
						if ($cp->getType() == 'date') {
							if ($value == $date_format_tip) continue;
							$dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value);
							$value = $dtValue->format('Y-m-d H:i:s');
						}
						if($condCp->getCondition() != '%'){
							if ($cp->getType() == 'numeric') {
								$current_condition .= ' AND cpv.value '.$condCp->getCondition().' '.DB::escape($value);
							}else if ($cp->getType() == 'boolean') {
								$current_condition .= ' AND cpv.value '.$condCp->getCondition().' '.$value;
								if (!$value) {
									$current_condition .= ') OR o.id NOT IN (SELECT object_id as id FROM '.TABLE_PREFIX.'custom_property_values cpv2 WHERE cpv2.object_id=o.id AND cpv2.value=1 AND cpv2.custom_property_id = '.$condCp->getCustomPropertyId();
								}
							}else{
								$current_condition .= ' AND cpv.value '.$condCp->getCondition().' '.DB::escape($value);
							}
						}else{
							$current_condition .= ' AND cpv.value like '.DB::escape("%$value");
						}
						$current_condition .= ')';
						$allConditions .= $current_condition;
					}
				}
			}
			
			$select_columns = array('*');
			$join_params = null;
			if ($order_by_col == '') {
				$order_by_col = $report->getOrderBy();
			}
			if (in_array($order_by_col, self::$external_columns)) {
				$original_order_by_col = $order_by_col;
				$order_by_col = 'name_order';
				$join_params = array(
					'table' => Objects::instance()->getTableName(),
					'jt_field' => 'id',
					'e_field' => $original_order_by_col,
					'join_type' => 'left'
				);
				$select_columns = array();
				$tmp_cols = $managerInstance->getColumns();
				foreach ($tmp_cols as $col) $select_columns[] = "e.$col";
				$tmp_cols = Objects::instance()->getColumns();
				foreach ($tmp_cols as $col) $select_columns[] = "o.$col";
				$select_columns[] = 'jt.name as name_order';
			}
			if ($order_by_asc == null) $order_by_asc = $report->getIsOrderByAsc();

			if ($ot->getName() == 'task' && !SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) {
				$allConditions .= " AND assigned_to_contact_id = ".logged_user()->getId();
			}
			
			if ($managerInstance) {
				$result = $managerInstance->listing(array(
					"select_columns" => $select_columns,
					"order" => "$order_by_col",
					"order_dir" => ($order_by_asc ? "ASC" : "DESC"),
					"extra_conditions" => $allConditions,
					"join_params" => $join_params
				));
			}else{
				// TODO Performance Killer
				$result = ContentDataObjects::getContentObjects(active_context(), $ot, $order_by_col, ($order_by_asc ? "ASC" : "DESC"), $allConditions);
			}
			$objects = $result->objects;
			$totalResults = $result->total;

			$results['pagination'] = Reports::getReportPagination($id, $params, $order_by_col, $order_by_asc, $offset, $limit, $totalResults);
		
			$dimensions_cache = array();
			
			foreach($report_columns as $column){
				if ($column->getCustomPropertyId() == 0) {
					$field = $column->getFieldName();
					if (str_starts_with($field, 'dim_')) {
						$dim_id = str_replace("dim_", "", $field);
						$dimension = Dimensions::getDimensionById($dim_id);
						$dimensions_cache[$dim_id] = $dimension;
						$doptions = $dimension->getOptions(true);
						$column_name = $doptions && isset($doptions->useLangs) && $doptions->useLangs ? lang($dimension->getCode()) : $dimension->getName();
						
						$results['columns'][$field] = $column_name;
						$results['db_columns'][$column_name] = $field;
					} else {
						if ($managerInstance->columnExists($field) || Objects::instance()->columnExists($field)) {
							$column_name = Localization::instance()->lang('field '.$ot->getHandlerClass().' '.$field);
							if (is_null($column_name)) $column_name = lang('field Objects '.$field);
							$results['columns'][$field] = $column_name;
							$results['db_columns'][$column_name] = $field;
						}
					}
				} else {
					$results['columns'][$column->getCustomPropertyId()] = $column->getCustomPropertyId();
				}
			}
			
			$report_rows = array();
			foreach($objects as &$object){/* @var $object Object */
				$obj_name = $object->getObjectName();
				$icon_class = $object->getIconClass();
				
				$row_values = array('object_type_id' => $object->getObjectTypeId());
				
				if (!$to_print) {
					$row_values['link'] = '<a class="link-ico '.$icon_class.'" title="' . $obj_name . '" target="new" href="' . $object->getViewUrl() . '">&nbsp;</a>';
				}
				
				foreach($report_columns as $column){
					if ($column->getCustomPropertyId() == 0) {
						
						$field = $column->getFieldName();
						
						if (str_starts_with($field, 'dim_')) {
							$dim_id = str_replace("dim_", "", $field);
							if (!array_var($dimensions_cache, $dim_id) instanceof Dimension) {
								$dimension = Dimensions::getDimensionById($dim_id);
								$dimensions_cache[$dim_id] = $dimension;
							} else {
								$dimension = array_var($dimensions_cache, $dim_id);
							}
							$members = ObjectMembers::getMembersByObjectAndDimension($object->getId(), $dim_id, " AND om.is_optimization=0");
							
							$value = "";
							foreach ($members as $member) {/* @var $member Member */
								$val = $member->getPath();
								$val .= ($val == "" ? "" : "/") . $member->getName();
								
								if ($value != "") $val = " - $val";
								$value .= $val;
							}
							
							$row_values[$field] = $value;
						} else {
						
							$value = $object->getColumnValue($field);
								
							if ($value instanceof DateTimeValue) {
								$field_type = $managerInstance->columnExists($field) ? $managerInstance->getColumnType($field) : Objects::instance()->getColumnType($field);
								$value = format_value_to_print($field, $value->toMySQL(), $field_type, $report->getReportObjectTypeId());
							}
								
							if(in_array($field, $managerInstance->getExternalColumns())){
								$value = self::instance()->getExternalColumnValue($field, $value, $managerInstance);
							} else if ($field != 'link'){
								$value = html_to_text($value);
							}
							if(self::isReportColumnEmail($value)) {
								if(logged_user()->hasMailAccounts()){
									$value = '<a class="internalLink" href="'.get_url('mail', 'add_mail', array('to' => clean($value))).'">'.clean($value).'</a></div>';
								}else{
									$value = '<a class="internalLink" target="_self" href="mailto:'.clean($value).'">'.clean($value).'</a></div>';
								}
							}	
							$row_values[$field] = $value;
						}
					} else {
						
						$colCp = $column->getCustomPropertyId();
						$cp = CustomProperties::getCustomProperty($colCp);
						if ($cp instanceof CustomProperty) { /* @var $cp CustomProperty */
							
							$cp_val = CustomPropertyValues::getCustomPropertyValue($object->getId(), $colCp);
							$row_values[$cp->getName()] = $cp_val instanceof CustomPropertyValue ? $cp_val->getValue() : "";
							
							$results['columns'][$colCp] = $cp->getName();
							$results['db_columns'][$cp->getName()] = $colCp;
							
						}
					}
				}
				

				Hook::fire("report_row", $object, $row_values);
				$report_rows[] = $row_values;
			}
			
			if (!$to_print) {
				if (is_array($results['columns'])) {
					array_unshift($results['columns'], '');
				} else {
					$results['columns'] = array('');
				}
				Hook::fire("report_header", $ot, $results['columns']);
			}
			$results['rows'] = $report_rows;
		}

		return $results;
	} //  executeReport
Esempio n. 21
0
</th><th><?php 
echo lang('type');
?>
</th><th class="center"><?php 
echo lang('status');
?>
</th></tr>
				<?php 
$last_dim = 0;
$isAlt = true;
foreach ($dimension_ots as $dimension_ot) {
    $dim_changed = $last_dim != $dimension_ot->getDimensionId();
    if ($dim_changed) {
        $isAlt = !$isAlt;
    }
    $dimension = Dimensions::getDimensionById($dimension_ot->getDimensionId());
    if (!$dimension instanceof Dimension || !$dimension->getIsManageable()) {
        continue;
    }
    $dimension_name = $dimension->getName();
    $ot = ObjectTypes::findById($dimension_ot->getObjectTypeId());
    if (!$ot instanceof ObjectType || in_array($ot->getName(), array('customer_folder', 'project_folder'))) {
        continue;
    }
    $ot_name = lang($ot->getName());
    ?>
				<tr class="<?php 
    echo ($isAlt ? 'altRow ' : '') . ($dim_changed ? 'bordered-top' : '');
    ?>
">
				
Esempio n. 22
0
:</label>
<?php 
}
$container_width = 385;
if (array_var($options, 'width')) {
    $container_width = array_var($options, 'width');
    $opts['width'] = array_var($options, 'width');
}
?>
<div style="display: inline-block;float:right;width: <?php 
echo $container_width;
?>
px;">
<?php 
// tree with members where user has permissions
$dim = Dimensions::getDimensionById($dimension_id);
$opts = array('checkBoxes' => false, 'all_members' => false, 'use_ajax_member_tree' => true, 'search_placeholder' => $search_placeholder, 'select_function' => $select_function);
if (array_var($options, 'allowedMemberTypes', false)) {
    $opts["allowedMemberTypes"] = array_var($options, 'allowedMemberTypes');
}
$is_multiple = false;
if (array_var($options, 'is_multiple', true)) {
    $is_multiple = array_var($options, 'is_multiple', true);
}
$opts["is_multiple"] = $is_multiple;
if (trim(array_var($options, 'root_lang')) != "") {
    $opts["root_lang"] = array_var($options, 'root_lang');
}
?>
		
	<div id="<?php