/** * @return Dimension */ static function findByCode($code) { if (count(self::$dimensions_by_code) == 0) { $dims = Dimensions::findAll(); foreach ($dims as $dim) self::$dimensions_by_code[$dim->getCode()] = $dim; } return array_var(self::$dimensions_by_code, $code); }
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; } }
/** * Render form control * * @param string $control_name * @return string */ function render($control_name) { $value = $this->getValue(); $dimensions = Dimensions::instance()->findAll(); $permission_group_ids = ContactPermissionGroups::getPermissionGroupIdsByContactCSV(logged_user()->getId(), false); $out = ''; foreach ($dimensions as $dim) { /* @var $dim Dimension */ if ($dim->getOptions(1) && isset($dim->getOptions(1)->hidden) && $dim->getOptions(1)->hidden) { continue; } if (!$dim->getDefinesPermissions() || !$dim->deniesAllForContact($permission_group_ids)) { if (array_search($dim->getId(), $value) !== false) { $checked = 1; } else { $checked = 0; } $out .= '<div class="dimension" >'; $out .= label_tag($dim->getName(), null, false, array('style' => 'display:inline;margin:10px;vertical-align:super;')); $out .= checkbox_field($control_name . '[' . $dim->getId() . ']', $checked); $out .= '</div >'; } } $out .= '<input type="hidden" name="' . $control_name . '[0]" value=" ">'; return $out; }
/** * * @param Contact $user * @param array $permissions * @param ContactPermissionGroup $group */ function afterUserPermissionChanged($user, $permissions, $group = null) { //get members ids $membersIds = array(); if (is_null($group)) { //get all members affected from $permission foreach ($permissions as $permission) { $memberId = $permission->m; if (!in_array($memberId, $membersIds)) { $membersIds[] = $memberId; } } } else { // dimension $dimensions = Dimensions::findAll(); $contact_pg_ids = $group->getId(); //get all allowed members for the group $allowed_members = array(); foreach ($dimensions as $dimension) { $member_list = array(); if ($dimension->getDefinesPermissions()) { $member_list = DB::executeAll("SELECT * FROM " . TABLE_PREFIX . "members WHERE dimension_id = " . $dimension->getId() . " ORDER BY id"); } foreach ($member_list as $dim_member) { if (ContactMemberPermissions::instance()->contactCanAccessMemberAll($contact_pg_ids, $dim_member['id'], $user, ACCESS_LEVEL_READ, false)) { $allowed_members[] = $dim_member['id']; } } } $membersIds = $allowed_members; } foreach ($membersIds as $member_id) { ContactMemberCaches::updateContactMemberCache($user, $member_id); } }
static function getWorkspaces($limit = 10) { $ws_dim = Dimensions::findByCode('workspaces'); $ws_object_type = self::instance()->getObjectTypeId(); $sql = "dimension_id = " . $ws_dim->getId() . " AND object_type_id = {$ws_object_type}"; $allowed_members = array(); $add_ctx_members = true; $context = active_context(); foreach ($context as $selection) { if ($selection instanceof Dimension && $selection->getCode() == 'workspaces') { $add_ctx_members = false; } else { if ($selection instanceof Member && $selection->getObjectTypeId() == $ws_object_type) { $allowed_members[] = $selection->getId(); } } } if ($add_ctx_members && count($allowed_members) > 0) { $sql .= " AND parent_member_id IN (" . implode(",", $allowed_members) . ")"; } else { $sql .= " AND parent_member_id = 0"; } $members = Members::findAll(array('conditions' => $sql, 'order' => 'name')); $res = array(); foreach ($members as $mem) { // controlar permissos para cada f*****g miembro } return $members; }
/** * Returns true if the object blongs to the texmplate context ($memberIds) * @author Ignacio Vazquez - elpepe.uy@gmail.com * @param ContentDataObject $object * @param array $memberIds */ static function validateObjectContext($object, $memberIds) { $valid = true; // Dimensiones requeridas para el tipo de objecto $dimensions = Dimensions::getAllowedDimensions(self::instance()->getObjectTypeId()); $requiredDimensions = array(); foreach ($dimensions as $dim) { if ($dim['is_required']) { $requiredDimensions[$dim['dimension_id']] = $dim; // Performance, dim id in the array key ! ! ! } } // Miembros del Objeto $objMembers = $object->getMemberIds(); // P/cada miembro foreach ($objMembers as $mid) { $member = Members::instance()->findById($mid); if ($member instanceof Member) { /* @var $member Member */ $did = $member->getDimensionId(); // Si la dimension del miembro esta en la requeridas if ($requiredDimensions[$did]) { if (!in_array($mid, $memberIds)) { $valid = false; } } } } if (!$valid) { throw new DAOValidationError($this, array(lang("template members do not match object members"))); } }
function workspaces_update_5_6() { // create associations DB::execute("\n\t\t\tINSERT INTO `" . TABLE_PREFIX . "dimension_member_associations` (`dimension_id`,`object_type_id`,`associated_dimension_id`, `associated_object_type_id`, `is_required`,`is_multiple`, `keeps_record`) VALUES\n\t\t\t((SELECT id from " . TABLE_PREFIX . "dimensions WHERE code = 'workspaces'),(SELECT id FROM " . TABLE_PREFIX . "object_types WHERE name = 'workspace'),(SELECT id from " . TABLE_PREFIX . "dimensions WHERE code = 'feng_persons'),(SELECT id FROM " . TABLE_PREFIX . "object_types WHERE name = 'person' LIMIT 1),0,1,0),\n\t\t\t((SELECT id from " . TABLE_PREFIX . "dimensions WHERE code = 'workspaces'),(SELECT id FROM " . TABLE_PREFIX . "object_types WHERE name = 'workspace'),(SELECT id from " . TABLE_PREFIX . "dimensions WHERE code = 'feng_persons'),(SELECT id FROM " . TABLE_PREFIX . "object_types WHERE name = 'company' LIMIT 1),0,1,0);\n\t\t"); // instantiate actual associations $ws_dim = Dimensions::findByCode('workspaces'); $ws_ot = ObjectTypes::findByName('workspace'); $ws_members = Members::findAll(array('conditions' => 'dimension_id = ' . $ws_dim->getId() . ' AND object_type_id = ' . $ws_ot->getId())); foreach ($ws_members as $ws_mem) { // after saving permissions the associations are instantiated by 'core_dimensions' plugin save_member_permissions($ws_mem); } }
function workspaces_custom_reports_additional_columns($args, &$ret) { $dimensions = Dimensions::findAll(array("conditions" => "code IN ('workspaces','tags')")); foreach ($dimensions as $dimension) { $doptions = $dimension->getOptions(true); if ($doptions && isset($doptions->useLangs) && $doptions->useLangs) { $name = lang($dimension->getCode()); } else { $name = $dimension->getName(); } $ret[] = array('id' => 'dim_' . $dimension->getId(), 'name' => $name, 'type' => DATA_TYPE_STRING); } }
/** * Render form control * * @param string $control_name * @return string */ function render($control_name) { $dimensions = Dimensions::instance()->findAll(array('conditions' => '`is_manageable` = 1')); $options = array(); $option_attributes = $this->getValue() == 0 ? array('selected' => 'selected') : null; $options[] = option_tag(lang('none'), 0, $option_attributes); foreach ($dimensions as $dim) { /* @var $dim Dimension */ if (in_array($dim->getId(), config_option('enabled_dimensions'))) { $dim_name = $dim->getName(); $option_attributes = $this->getValue() == $dim->getId() ? array('selected' => 'selected') : null; $options[] = option_tag($dim_name, $dim->getId(), $option_attributes); } } return select_box($control_name, $options); }
function mail_allowed_subscribers($object, &$contacts) { if ($object instanceof MailContent) { $person_dim = Dimensions::findByCode('feng_persons'); $person_dim_id = $person_dim instanceof Dimension ? $person_dim->getId() : "0"; $sql = "SELECT member_id FROM ".TABLE_PREFIX."object_members om INNER JOIN ".TABLE_PREFIX."members m ON m.id=om.member_id WHERE om.object_id = ".$object->getId()." AND om.is_optimization=0 AND m.dimension_id NOT IN (".$person_dim_id.")"; $member_ids_res = DB::executeAll($sql); $member_ids = array(); foreach ($member_ids_res as $row) { if (trim($row['member_id']) != "") $member_ids[] = $row['member_id']; } if (!$member_ids || count($member_ids) == 0) { $contacts = array(logged_user()); } } }
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; }
/** * Render form control * * @param string $control_name * @return string */ function render($control_name) { $value = $this->getValue(); $dimensions = Dimensions::instance()->findAll(); $permission_group_ids = ContactPermissionGroups::getPermissionGroupIdsByContactCSV(logged_user()->getId(),false); $out = '' ; foreach ($dimensions as $dim) { /* @var $dim Dimension */ if ( $dim->getOptions(1) && isset($dim->getOptions(1)->hidden) && $dim->getOptions(1)->hidden ) { continue ; } if (!$dim->getDefinesPermissions() || !$dim->deniesAllForContact($permission_group_ids)) { if (array_search($dim->getId(), $value) !== false ){ $checked = 1 ; }else{ $checked = 0 ; } $out.='<div class="dimension" >'; $out.=label_tag($dim->getName()); $out.=checkbox_field($control_name.'['.$dim->getId().']',$checked ); $out.='</div >'; } } return $out ; }
function workspaces_quickadd_extra_fields($parameters) { if (array_var($parameters, 'dimension_id') == Dimensions::findByCode("workspaces")->getId()) { $parent_member = Members::findById(array_var($parameters, 'parent_id')); if ($parent_member instanceof Member && $parent_member->getObjectId() > 0) { $dimension_object = Objects::findObject($parent_member->getObjectId()); $fields = $dimension_object->manager()->getPublicColumns(); $color_columns = array(); foreach ($fields as $f) { if ($f['type'] == DATA_TYPE_WSCOLOR) { $color_columns[] = $f['col']; } } foreach ($color_columns as $col) { foreach ($fields as &$f) { if ($f['col'] == $col && $dimension_object->columnExists($col)) { $color_code = $dimension_object->getColumnValue($col); echo '<input type="hidden" name="dim_obj['.$col.']" value="'.$color_code.'" />'; } } } } } }
function quick_add_form() { $this->setLayout('empty'); if ($dimension_id = array_var($_GET, 'dimension_id')) { $dimension = Dimensions::instance()->findById($dimension_id); $dimensionOptions = $dimension->getOptions(true); $object_Types = array(); $parent_member_id = array_var($_GET, 'parent_member_id'); if ($parent_member_id) { $parent_member = Members::instance()->findById($parent_member_id); $object_types = DimensionObjectTypes::getChildObjectTypes($parent_member_id); } else { $object_types = DimensionObjectTypes::instance()->findAll(array("conditions" => "dimension_id = {$dimension_id} AND is_root = 1 ")); } if (count($object_types)) { if (count($object_types) == 1) { // Input Hidden tpl_assign('object_type', $object_types[0]); tpl_assign('object_type_name', ObjectTypes::instance()->findById($object_types[0]->getObjectTypeId())->getName()); } else { // Input combo tpl_assign('object_types', $object_types); } } else { tpl_assign("error_msg", $parent_member->getName() . " does not accept child nodes "); } $editUrls = array(); foreach ($object_types as $object_type) { /* @var $object_type DimensionObjectType */ if (ObjectTypes::instance()->findById($object_type->getObjectTypeId())->getType() != 'dimension_object') { continue; } $options = $object_type->getOptions(1); if (isset($options->defaultAjax) && $options->defaultAjax->controller != "dashboard") { $editUrls[$object_type->getObjectTypeId()] = get_url($options->defaultAjax->controller, 'add'); } else { $t = ObjectTypes::instance()->findById($object_type->getObjectTypeId()); /* @var $t ObjectType */ $class_name = ucfirst($t->getName()) . "Controller"; if ($t && controller_exists($t->getName(), $t->getPluginId())) { $editUrls[$object_type->getObjectTypeId()] = get_url($t->getName(), 'add'); } else { $editUrls[$object_type->getObjectTypeId()] = get_url('member', 'add', array("dim_id" => $dimension_id)); } } } tpl_assign('editUrls', $editUrls); tpl_assign('parent_member_id', $parent_member_id); tpl_assign('dimension_id', $dimension_id); if (is_object($dimensionOptions) && is_object($dimensionOptions->quickAdd) && $dimensionOptions->quickAdd->formAction) { tpl_assign('form_action', ROOT_URL . "/" . $dimensionOptions->quickAdd->formAction); } else { tpl_assign('form_action', get_url('member', 'add', array('quick' => '1'))); } } else { die("SORRY. Invalid dimension"); } }
</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' : ''); ?> ">
static function addObjToSharingTable($oid, $tid, $obj_mem_ids) { $gids = array(); $table_prefix = defined('FORCED_TABLE_PREFIX') && FORCED_TABLE_PREFIX ? FORCED_TABLE_PREFIX : TABLE_PREFIX; //1. clear sharing table for this object SharingTables::delete("object_id={$oid}"); //2. get dimensions of this object's members that defines permissions $res = DB::execute("SELECT d.id as did FROM " . $table_prefix . "dimensions d INNER JOIN " . $table_prefix . "members m on m.dimension_id=d.id\r\n\t\t\t\tWHERE m.id IN ( SELECT member_id FROM " . $table_prefix . "object_members WHERE object_id = {$oid} AND is_optimization = 0 ) AND d.defines_permissions = 1"); $dids_tmp = array(); while ($row = $res->fetchRow()) { $dids_tmp[$row['did']] = $row['did']; } $res->free(); $dids = array_values($dids_tmp); $dids_tmp = null; $sql_from = "" . $table_prefix . "contact_member_permissions cmp\r\n\t\tLEFT JOIN " . $table_prefix . "members m ON m.id = cmp.member_id\r\n\t\tLEFT JOIN " . $table_prefix . "dimensions d ON d.id = m.dimension_id"; $member_where_conditions = ""; $dim_where_conditions = ""; // if users can add objects without classifying then check for permissions with member_id=0 if (config_option('let_users_create_objects_in_root')) { $member_where_conditions = "member_id=0 OR "; $dim_where_conditions = " OR d.id IS NULL"; } $sql_where = "({$member_where_conditions} member_id IN ( SELECT member_id FROM " . $table_prefix . "object_members WHERE object_id = {$oid} AND is_optimization = 0)) AND cmp.object_type_id = {$tid}"; //3. If there are dimensions that defines permissions containing any of the object members if (count($dids)) { // 3.1 get permission groups with permissions over the object. $sql_fields = "permission_group_id AS group_id"; $sql = "\r\n\t\t\t\tSELECT\r\n\t\t\t\t{$sql_fields}\r\n\t\t\t\tFROM\r\n\t\t\t\t{$sql_from}\r\n\t\t\t\tWHERE\r\n\t\t\t\t{$sql_where} AND (d.id IN (" . implode(',', $dids) . ") {$dim_where_conditions})\r\n\t\t\t"; $res = DB::execute($sql); $gids_tmp = array(); while ($row = $res->fetchRow()) { $gids_tmp[$row['group_id']] = $row['group_id']; } $res->free(); // allow all permission groups $allow_all_rows = DB::executeAll("SELECT DISTINCT permission_group_id FROM " . $table_prefix . "contact_dimension_permissions cdp\r\n\t\t\t\t\tINNER JOIN " . $table_prefix . "members m on m.dimension_id=cdp.dimension_id\r\n\t\t\t\t\tWHERE cdp.permission_type='allow all' AND cdp.dimension_id IN (" . implode(',', $dids) . ");"); if (is_array($allow_all_rows)) { foreach ($allow_all_rows as $row) { $gids_tmp[$row['permission_group_id']] = $row['permission_group_id']; } } $gids = array_values($gids_tmp); $gids_tmp = null; // check for mandatory dimensions $enabled_dimensions_sql = ""; $enabled_dimensions_ids = implode(',', config_option('enabled_dimensions')); if ($enabled_dimensions_ids != "") { $enabled_dimensions_sql = "AND id IN ({$enabled_dimensions_ids})"; } $mandatory_dim_ids = Dimensions::findAll(array('id' => true, 'conditions' => "`defines_permissions`=1 {$enabled_dimensions_sql} AND `permission_query_method`='" . DIMENSION_PERMISSION_QUERY_METHOD_MANDATORY . "'")); if (count($gids) > 0 && count($mandatory_dim_ids) > 0) { $sql = "SELECT om.member_id, m.dimension_id FROM " . $table_prefix . "object_members om\r\n\t\t\t\t\tINNER JOIN " . $table_prefix . "members m ON m.id=om.member_id INNER JOIN " . $table_prefix . "dimensions d ON d.id=m.dimension_id\r\n\t\t\t\t\tWHERE om.object_id = {$oid} AND om.is_optimization = 0 AND d.id IN (" . implode(",", $mandatory_dim_ids) . ")"; // Object members in mandatory dimensions $object_member_ids_res = DB::executeAll($sql); $mandatory_dim_members = array(); if (!is_null($object_member_ids_res)) { foreach ($object_member_ids_res as $row) { if (!isset($mandatory_dim_members[$row['dimension_id']])) { $mandatory_dim_members[$row['dimension_id']] = array(); } $mandatory_dim_members[$row['dimension_id']][] = $row['member_id']; } $mandatory_dim_allowed_pgs = array(); // Check foreach group that it has permissions over at least one member of each mandatory dimension foreach ($mandatory_dim_members as $mdim_id => $mmember_ids) { $sql = "SELECT pg.id FROM " . $table_prefix . "permission_groups pg\r\n\t\t\t\t\t\t\tINNER JOIN " . $table_prefix . "contact_dimension_permissions cdp ON cdp.permission_group_id=pg.id\r\n\t\t\t\t\t\t\tINNER JOIN " . $table_prefix . "contact_member_permissions cmp ON cmp.permission_group_id=pg.id\r\n\t\t\t\t\t\t\tWHERE cdp.dimension_id = '{$mdim_id}' AND (\r\n\t\t\t\t\t\t\tcdp.permission_type='allow all' OR cdp.permission_type='check' AND cmp.permission_group_id IN (" . implode(',', $gids) . ")\r\n\t\t\t\t\t\t\tAND cmp.member_id IN (" . implode(',', $mmember_ids) . ")\r\n\t\t\t\t\t\t)"; $permission_groups_res = DB::executeAll($sql); $mandatory_dim_allowed_pgs[$mdim_id] = array(); if (!is_null($permission_groups_res)) { foreach ($permission_groups_res as $row) { if (!in_array($row['id'], $mandatory_dim_allowed_pgs[$mdim_id])) { $mandatory_dim_allowed_pgs[$mdim_id][] = $row['id']; } } } } if (isset($mandatory_dim_allowed_pgs) && count($mandatory_dim_allowed_pgs) > 0) { $original_mandatory_dim_allowed_pgs = $mandatory_dim_allowed_pgs; $allowed_gids = array_pop($mandatory_dim_allowed_pgs); foreach ($mandatory_dim_allowed_pgs as $pg_array) { $allowed_gids = array_intersect($allowed_gids, $pg_array); } // If an user has permissions in one dim using a group and in other dim using his personal permissions then add to sharing table its personal permission group $pg_ids = array_unique(array_flat($original_mandatory_dim_allowed_pgs)); if (count($pg_ids) == 0) { $pg_ids[0] = 0; } $contact_pgs = array(); $contact_pg_rows = DB::executeAll("SELECT * FROM " . TABLE_PREFIX . "contact_permission_groups WHERE permission_group_id IN (" . implode(',', $pg_ids) . ") ORDER BY permission_group_id"); if (is_array($contact_pg_rows)) { foreach ($contact_pg_rows as $cpgr) { if (!isset($contact_pgs[$cpgr['contact_id']])) { $contact_pgs[$cpgr['contact_id']] = array(); } $contact_pgs[$cpgr['contact_id']][] = $cpgr['permission_group_id']; } } // each user must have at least one pg for every dimension foreach ($contact_pgs as $contact_id => $permission_groups) { $has_one = array_flip(array_keys($original_mandatory_dim_allowed_pgs)); foreach ($has_one as $k => &$v) { $v = false; } foreach ($permission_groups as $pg_id) { foreach ($original_mandatory_dim_allowed_pgs as $dim_id => $allowedpgs) { if (in_array($pg_id, $allowedpgs)) { $has_one[$dim_id] = true; break; } } } // all dims must be true in this array to allow permissions $has_permission = !in_array(false, $has_one); if ($has_permission) { $contact_row = DB::executeOne("SELECT permission_group_id FROM " . TABLE_PREFIX . "contacts where object_id = {$contact_id}"); if (is_array($contact_row) && $contact_row['permission_group_id'] > 0) { $allowed_gids[] = $contact_row['permission_group_id']; } } } $gids = array_unique($allowed_gids, SORT_NUMERIC); } else { $gids = array(); } } } } else { if ($obj_mem_ids) { // 3.2 No memeber dimensions defines permissions. // No esta en ninguna dimension que defina permisos, El objecto esta en algun lado // => En todas las dimensiones en la que está no definen permisos => Busco todos los grupos $gids = PermissionGroups::instance()->findAll(array('id' => true, 'conditions' => "type != 'roles'")); } else { // if this object is an email and it is unclassified => add to sharing table the permission groups of the users that have permissions in the email's account if (Plugins::instance()->isActivePlugin('mail')) { $mail_ot = ObjectTypes::instance()->findByName('mail'); if ($mail_ot instanceof ObjectType && $tid == $mail_ot->getId()) { $gids = array_flat(DB::executeAll("\r\n\t\t\t\t\t\t\tSELECT cpg.permission_group_id\r\n\t\t\t\t\t\t\tFROM " . TABLE_PREFIX . "contact_permission_groups cpg\r\n\t\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "contacts c ON c.permission_group_id=cpg.permission_group_id\r\n\t\t\t\t\t\t\tWHERE cpg.contact_id IN (\r\n\t\t\t\t\t\t\t SELECT mac.contact_id FROM " . TABLE_PREFIX . "mail_account_contacts mac WHERE mac.account_id = (SELECT mc.account_id FROM " . TABLE_PREFIX . "mail_contents mc WHERE mc.object_id={$oid})\r\n\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t")); } } } } if (count($gids)) { $stManager = SharingTables::instance(); $stManager->populateGroups($gids, $oid); $gids = null; } }
<?php $dimensions_info = array(); $dimensions = Dimensions::findAll(); foreach ($dimensions as $dimension) { if (in_array($dimension->getCode(), array('feng_users', 'feng_persons'))) { continue; } if (!isset($dimensions_info[$dimension->getName()])) { $dimensions_info[$dimension->getName()] = array('id' => $dimension->getId(), 'members' => array()); } } $members = $object->getMembers(); foreach ($members as $member) { /* @var $member Member */ $dimension = $member->getDimension(); if (in_array($dimension->getCode(), array('feng_users', 'feng_persons'))) { continue; } if (!can_read(logged_user(), array($member), $object->getObjectTypeId())) { continue; } if (!isset($dimensions_info[$dimension->getName()])) { $dimensions_info[$dimension->getName()] = array('members' => array(), 'icon' => $member->getIconClass()); } if (!isset($dimensions_info[$dimension->getName()]['icon'])) { $dimensions_info[$dimension->getName()]['icon'] = $member->getIconClass(); } $parents = array_reverse($member->getAllParentMembersInHierarchy(true)); foreach ($parents as $p) { $dimensions_info[$dimension->getName()]['members'][$p->getId()] = array('p' => $p->getParentMemberId(), 'name' => $p->getName(), 'ot' => $p->getObjectTypeId(), 'color' => $p->getMemberColor());
function list_members() { if (!logged_user()->isAdminGroup()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } ajx_set_no_toolbar(); $dim_id = array_var($_REQUEST, 'dim', 0); $dimension = Dimensions::findById($dim_id); if (!$dimension instanceof Dimension) { flash_error(lang('dimension snx')); ajx_current("empty"); return; } if (isset($_REQUEST['page'])) { ajx_replace(true); } // parameters $page = array_var($_REQUEST, 'page'); $order_by = array_var($_REQUEST, 'order'); $order_by_dir = array_var($_REQUEST, 'order_dir'); // pagination params $items_x_page = array_var($_REQUEST, 'items_x_page', 20); if (!$page) { $page = 1; } $offset = $items_x_page * ($page - 1); // order defaults if (!$order_by) { $order_by = 'name'; } if (!in_array($order_by_dir, array('ASC', 'DESC'))) { $order_by_dir = 'ASC'; } // this function already checks dimension options $dim_name = $dimension->getName(); // permissions sql $perm_sql = ""; if ($dimension->getDefinesPermissions() && !logged_user()->isAdministrator()) { $pg_ids = logged_user()->getPermissionGroupIds(); $perm_sql = " AND EXISTS (SELECT cmp.member_id FROM " . TABLE_PREFIX . "contact_member_permissions cmp WHERE cmp.member_id=m.id AND cmp.permission_group_id IN (" . implode(',', $pg_ids) . "))"; } $main_sql = "SELECT m.id, l.created_on, l.created_by_id, l.member_id FROM " . TABLE_PREFIX . "members m LEFT JOIN " . TABLE_PREFIX . "application_logs l ON l.member_id=m.id AND l.action='add' WHERE m.dimension_id='{$dim_id}' {$perm_sql}"; $sql = "{$main_sql}\r\n\t\t\t\tORDER BY {$order_by} {$order_by_dir} \r\n\t\t\t\tLIMIT {$offset}, {$items_x_page}"; $rows = DB::executeAll($sql); $count_sql = str_replace("SELECT m.id, l.created_on, l.created_by_id, l.member_id FROM", "SELECT count(*) as total FROM", $main_sql); $count_row = DB::executeAll($count_sql); $members = array(); $ids = array(); $log_data = array(); foreach ($rows as $row) { $members[] = Members::findById($row['id']); $log_data[$row['id']] = array('created_on' => $row['created_on'], 'created_by_id' => $row['created_by_id']); } $member_type_ids = array_flat(DB::executeAll("SELECT object_type_id FROM " . TABLE_PREFIX . "dimension_object_types WHERE dimension_id={$dim_id} AND is_root=1")); $member_types = ObjectTypes::findAll(array('conditions' => 'id IN (' . implode(',', $member_type_ids) . ')')); tpl_assign('members', $members); tpl_assign('log_data', $log_data); tpl_assign('dimension', $dimension); tpl_assign('dimension_name', $dim_name); tpl_assign('member_types', $member_types); tpl_assign('page', $page); tpl_assign('total_items', $count_row[0]['total']); tpl_assign('items_x_page', $items_x_page); tpl_assign('order_by', $order_by); tpl_assign('order_by_dir', $order_by_dir); }
/** * 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() . '"> </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 quick_add_task() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $notAllowedMember = ''; if (!ProjectTask::canAdd(logged_user(), active_context(), $notAllowedMember)) { if (str_starts_with($notAllowedMember, '-- req dim --')) { flash_error(lang('must choose at least one member of', str_replace_first('-- req dim --', '', $notAllowedMember, $in))); } else { flash_error(lang('no context permissions to add', lang("tasks"), $notAllowedMember)); } ajx_current("empty"); return; } ajx_current("empty"); $task = new ProjectTask(); $task_data = array_var($_POST, 'task'); $parent_id = array_var($task_data, 'parent_id', 0); $parent = ProjectTasks::findById($parent_id); if (is_array($task_data)) { $task_data['due_date'] = getDateValue(array_var($task_data, 'task_due_date')); $task_data['start_date'] = getDateValue(array_var($task_data, 'task_start_date')); if ($task_data['due_date'] instanceof DateTimeValue) { $duetime = getTimeValue(array_var($task_data, 'task_due_time')); if (is_array($duetime)) { $task_data['due_date']->setHour(array_var($duetime, 'hours')); $task_data['due_date']->setMinute(array_var($duetime, 'mins')); } $task_data['due_date']->advance(logged_user()->getTimezone() * -3600); $task_data['use_due_time'] = is_array($duetime); } if ($task_data['start_date'] instanceof DateTimeValue) { $starttime = getTimeValue(array_var($task_data, 'task_start_time')); if (is_array($starttime)) { $task_data['start_date']->setHour(array_var($starttime, 'hours')); $task_data['start_date']->setMinute(array_var($starttime, 'mins')); } $task_data['start_date']->advance(logged_user()->getTimezone() * -3600); $task_data['use_start_time'] = is_array($starttime); } if (config_option("wysiwyg_tasks")) { $task_data['type_content'] = "html"; $task_data['text'] = preg_replace("/[\n|\r|\n\r]/", '', array_var($task_data, 'text')); } else { $task_data['type_content'] = "text"; } $task_data['object_type_id'] = $task->getObjectTypeId(); $task->setFromAttributes($task_data); if (array_var($task_data, 'is_completed', false) == 'true') { $task->setCompletedOn(DateTimeValueLib::now()); $task->setCompletedById(logged_user()->getId()); } try { DB::beginWork(); $task->save(); $totalMinutes = array_var($task_data, 'hours') * 60 + array_var($task_data, 'minutes'); $task->setTimeEstimate($totalMinutes); $task->save(); $gb_member_id = array_var($task_data, 'member_id'); $member_ids = array(); $persons_dim = Dimensions::findByCode('feng_persons'); $persons_dim_id = $persons_dim instanceof Dimension ? $persons_dim->getId() : 0; if ($parent) { if (count($parent->getMembers()) > 0) { foreach ($parent->getMembers() as $member) { if ($member->getDimensionId() != $persons_dim_id) { $member_ids[] = $member->getId(); } } } $task->setMilestoneId($parent->getMilestoneId()); $task->save(); } if (count($member_ids) == 0) { $member_ids = active_context_members(false); } if ($gb_member_id && is_numeric($gb_member_id)) { $member_ids[] = $gb_member_id; } $object_controller = new ObjectController(); $object_controller->add_to_members($task, $member_ids); //Add new work timeslot for this task // if (array_var($task_data,'hours') != '' && array_var($task_data,'hours') > 0){ // $hours = array_var($task_data, 'hours'); // $hours = - $hours; // // $timeslot = new Timeslot(); // $dt = DateTimeValueLib::now(); // $dt2 = DateTimeValueLib::now(); // $timeslot->setEndTime($dt); // $dt2 = $dt2->add('h', $hours); // $timeslot->setStartTime($dt2); // $timeslot->setContactId(logged_user()->getId()); // $timeslot->setObjectId($task->getId()); // $timeslot->save(); // } ApplicationLogs::createLog($task, ApplicationLogs::ACTION_ADD); $assignee = $task->getAssignedToContact(); if ($assignee instanceof Contact) { $task->subscribeUser($assignee); } // create default reminder $reminder = new ObjectReminder(); $reminder->setMinutesBefore(1440); $reminder->setType("reminder_email"); $reminder->setContext("due_date"); $reminder->setObject($task); $reminder->setUserId(0); $date = $task->getDueDate(); if (!isset($minutes)) { $minutes = 0; } if ($date instanceof DateTimeValue) { $rdate = new DateTimeValue($date->getTimestamp() - $minutes * 60); $reminder->setDate($rdate); } $reminder->save(); $subs = array(); if (config_option('multi_assignment') && Plugins::instance()->isActivePlugin('crpm')) { $json_subtasks = json_decode(array_var($_POST, 'multi_assignment')); $line = 0; foreach ($json_subtasks as $json_subtask) { $subtasks[$line]['assigned_to_contact_id'] = $json_subtask->assigned_to_contact_id; $subtasks[$line]['name'] = $json_subtask->name; $subtasks[$line]['time_estimate_hours'] = $json_subtask->time_estimate_hours; $subtasks[$line]['time_estimate_minutes'] = $json_subtask->time_estimate_minutes; $line++; } Hook::fire('save_subtasks', $task, $subtasks); $subtasks = ProjectTasks::findAll(array('conditions' => '`parent_id` = ' . DB::escape($task->getId()))); // findAll foreach ($subtasks as $sub) { $subs[] = $sub->getArrayInfo(); } } // subscribe $task->subscribeUser(logged_user()); DB::commit(); // notify asignee if (array_var($task_data, 'notify') == 'true') { try { Notifier::taskAssigned($task); } catch (Exception $e) { } // try } ajx_extra_data(array("task" => $task->getArrayInfo(), 'subtasks' => $subs)); flash_success(lang('success add task', $task->getObjectName())); } catch (Exception $e) { DB::rollback(); flash_error($e->getMessage()); } // try } // if }
function core_dimensions_update_11_12() { // normaize dimension options $dimensions = Dimensions::findAll(); foreach ($dimensions as $dimension) { /* @var $dimension Dimension */ $options_json = $dimension->getOptions(); $options = json_decode($options_json, true); foreach ($options as $key => $value) { if (in_array($key, array('defaultAjax', 'quickAdd'))) { // skip defaultAjax and quickAdd continue; } $sql = "INSERT INTO " . TABLE_PREFIX . "dimension_options (`dimension_id`, `name`, `value`) \r\n\t\t\t\t\tVALUES (" . $dimension->getId() . ",'{$key}','{$value}') \r\n\t\t\t\t\tON DUPLICATE KEY UPDATE `value`='{$value}'"; DB::execute($sql); } } }
/** * Add/edit Dimension Members * * @access public * @param void * @return null */ function edit_members() { if (!can_manage_dimension_members(logged_user())) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } // if $dimensions = Dimensions::findAll(array('conditions' => '`is_manageable` = 1')); $members = array(); foreach ($dimensions as $dim) { $dimensions = Dimensions::findAll(array('conditions' => '`is_manageable` = 1')); $members = array(); foreach ($dimensions as $dim) { $root_members = Members::findAll(array('conditions' => array('`dimension_id`=? AND `parent_member_id`=0', $dim->getId()), 'order' => '`name` ASC')); foreach ($root_members as $mem) { $members[$dim->getId()][] = $mem; $members[$dim->getId()] = array_merge($members[$dim->getId()], $mem->getAllChildrenSorted()); } } } tpl_assign('members', $members); tpl_assign('dimensions', $dimensions); }
function modifyMemberValidations($member) { if ($member instanceof Member) { $member->add_skip_validation('uniqueness of parent - name'); } else { if ($this->getId() > 0 && Plugins::instance()->isActivePlugin('core_dimensions')) { $dim = Dimensions::findByCode('feng_persons'); if ($dim instanceof Dimension) { $m = Members::findByObjectId($this->getId(), $dim->getId()); if ($m instanceof Member) { $m->add_skip_validation('uniqueness of parent - name'); } } } } }
/** * Returns a list of emails according to the requested parameters * * @param string $tag * @param array $attributes * @param Project $project * @return array */ function getEmails($account_id = null, $state = null, $read_filter = "", $classif_filter = "", $context = null, $start = null, $limit = null, $order_by = 'received_date', $dir = 'ASC', $join_params = null, $archived = false, $conversation_list = null, $only_count_result = false) { $mailTablePrefix = "e"; if (!$limit) { $limit = user_config_option('mails_per_page') ? user_config_option('mails_per_page') : config_option('files_per_page'); } $accountConditions = ""; // Check for accounts $accountConditions = ''; if (isset($account_id) && $account_id > 0) { //Single account $accountConditions = " AND {$mailTablePrefix}.account_id = " . DB::escape($account_id); } else { // show mails for all visible accounts and classified mails where logged_user has permissions so we don't filter by account_id /*// show emails from other accounts $macs = MailAccountContacts::instance()->getByContact(logged_user()); $acc_ids = array(0); foreach ($macs as $mac) $acc_ids[] = $mac->getAccountId(); // permission conditions $pgs = ContactPermissionGroups::getPermissionGroupIdsByContactCSV(logged_user()->getId()); if (trim($pgs == '')) $pgs = '0'; $perm_sql = "(SELECT count(*) FROM ".TABLE_PREFIX."sharing_table st WHERE st.object_id = $mailTablePrefix.object_id AND st.group_id IN ($pgs)) > 0"; // show mails for all visible accounts and classified mails where logged_user has permissions $accountConditions = " AND ($mailTablePrefix.account_id IN (" . implode(",", $acc_ids) . ") OR $perm_sql)";*/ } // Check for unclassified emails $classified = ''; if ($classif_filter != '' && $classif_filter != 'all') { $persons_dim = Dimensions::findByCode('feng_persons'); $persons_dim_id = $persons_dim instanceof Dimension ? $persons_dim->getId() : "0"; $classified = "AND " . ($classif_filter == 'unclassified' ? "NOT " : ""); $classified .= "o.id IN (SELECT om.object_id FROM " . TABLE_PREFIX . "object_members om INNER JOIN " . TABLE_PREFIX . "members m ON m.id=om.member_id WHERE m.dimension_id<>{$persons_dim_id})"; } // if not filtering by account or classification then check that emails are classified or from one of my accounts if ($classified == '' && $accountConditions == '') { $macs = MailAccountContacts::instance()->getByContact(logged_user()); $acc_ids = array(0); foreach ($macs as $mac) { $acc_ids[] = $mac->getAccountId(); } $accountConditions = " AND ({$mailTablePrefix}.account_id IN (" . implode(',', $acc_ids) . ") OR EXISTS (\r\n\t\t\t\t\tSELECT om1.object_id FROM " . TABLE_PREFIX . "object_members om1 \r\n\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "members m1 ON m1.id=om1.member_id \r\n\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "dimensions d1 ON d1.id=m1.dimension_id \r\n\t\t\t\t\tWHERE om1.object_id={$mailTablePrefix}.object_id AND d1.is_manageable=1) ) "; } // Check for draft, junk, etc. emails if ($state == "draft") { $stateConditions = " {$mailTablePrefix}.state = '2'"; } else { if ($state == "sent") { $stateConditions = " {$mailTablePrefix}.state IN ('1','3','5')"; } else { if ($state == "received") { $stateConditions = " {$mailTablePrefix}.state IN ('0','5')"; } else { if ($state == "junk") { $stateConditions = " {$mailTablePrefix}.state = '4'"; } else { if ($state == "outbox") { $stateConditions = " {$mailTablePrefix}.state >= 200"; } else { $stateConditions = ""; } } } } } // Check read emails if ($read_filter != "" && $read_filter != "all") { if ($read_filter == "unread") { $read = "AND NOT "; $subread = "AND NOT mc."; } else { $read = "AND "; $subread = "AND mc."; } $read2 = "id IN (SELECT rel_object_id FROM " . TABLE_PREFIX . "read_objects t WHERE contact_id = " . logged_user()->getId() . " AND id = t.rel_object_id AND t.is_read = '1')"; $read .= $read2; $subread .= $read2; } else { $read = ""; $subread = ""; } $conversation_cond = ""; $box_cond = "AND {$stateConditions}"; if (isset($conversation_list) && $conversation_list > 0) { $conversation_cond = "AND e.conversation_last = 1"; } $extra_conditions = "{$accountConditions} {$classified} {$read} {$conversation_cond} {$box_cond}"; Hook::fire("listing_extra_conditions", null, $extra_conditions); return self::instance()->listing(array('limit' => $limit, 'start' => $start, 'order' => $order_by, 'order_dir' => $dir, 'extra_conditions' => $extra_conditions, 'count_results' => false, 'only_count_results' => $only_count_result, 'join_params' => $join_params)); }
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"); } } }
static function reloadPersonsDimension() { if (Plugins::instance()->isActivePlugin('core_dimensions')) { $person_dim = Dimensions::findByCode('feng_persons'); if ($person_dim instanceof Dimension) { evt_add('reload dimension tree', $person_dim->getId()); } } }
<?php $limit = 5; $genid = gen_id(); $ws_dimension = Dimensions::findByCode('workspaces'); $dim_controller = new DimensionController(); $selected_ws = '0'; $allowed_members = array(); $add_ctx_members = true; $show_widget = true; $context = active_context(); if (isset($context)) { foreach ($context as $selection) { if ($selection instanceof Dimension && $selection->getCode() == 'workspaces') { $add_ctx_members = false; } else { if ($selection instanceof Member) { if ($selection->getObjectTypeId() == Workspaces::instance()->getObjectTypeId()) { $allowed_members[] = $selection->getId(); $selected_ws = $selection->getId(); } else { $show_widget = false; } } } } } if ($show_widget) { $extra_conditions = " AND parent_member_id " . ($add_ctx_members && count($allowed_members) > 0 ? "IN (" . implode(",", $allowed_members) . ")" : "=0"); $parent = null; $context = active_context();
/** * 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()); } }
function getIconClass() { $d = Dimensions::findByCode('workspaces'); $m = Members::findOneByObjectId($this->getId(), $d->getId()); return "ico-color" . ($m instanceof Member ? $m->getColor() : '0'); }
function core_dimensions_quickadd_extra_fields($dimId) { if ($dimId == Dimensions::findByCode("feng_persons")->getId()) { tpl_display(PLUGIN_PATH . "/core_dimensions/templates/quickadd_extra_fields.php"); } }