function array_flat($a, $s = array(), $l = 0)
 {
     # check if this is an array
     if (!is_array($a)) {
         return $s;
     }
     # go through the array values
     foreach ($a as $k => $v) {
         # check if the contained values are arrays
         if (!is_array($v)) {
             # store the value
             $s[] = $v;
             # move to the next node
             continue;
         }
         # increment depth level
         $l++;
         # replace the content of stored values
         $s = array_flat($v, $s, $l);
         # decrement depth level
         $l--;
     }
     # get only unique values
     if ($l == 0) {
         $s = array_values(array_unique($s));
     }
     # return stored values
     return $s;
 }
Esempio n. 2
0
 /**
  * Takes a multidimensional array and flattens it
  * @param array $array
  * @return array
  */
 public function flatten(array $array)
 {
     $tmp = array();
     foreach ($array as $a) {
         if (is_array($a)) {
             $tmp = array_merge($tmp, array_flat($a));
         } else {
             $tmp[] = $a;
         }
     }
     return $tmp;
 }
Esempio n. 3
0
 function array_flat($array)
 {
     $output = array();
     if (is_array($array)) {
         foreach ($array as $element) {
             $output = array_merge($output, array_flat($element));
         }
     } else {
         $output[] = $array;
     }
     return $output;
 }
Esempio n. 4
0
/**
 * Contact member cache
 *
 */
function core_dimensions_update_7_8()
{
    //UPDATE depth for all members
    //update root members
    DB::execute("UPDATE " . TABLE_PREFIX . "members SET depth = 1  WHERE parent_member_id = 0;");
    //clean root members
    DB::execute("UPDATE " . TABLE_PREFIX . "members SET depth = 2  WHERE parent_member_id != 0 AND depth = 1;");
    $members_depth = DB::executeAll("SELECT id FROM " . TABLE_PREFIX . "members WHERE parent_member_id =0 ORDER BY id");
    $members_depth = array_flat($members_depth);
    $members_depth = implode(",", $members_depth);
    $depth = 2;
    $max_depth = DB::executeOne("SELECT  MAX(depth) AS depth FROM `" . TABLE_PREFIX . "members`");
    //update all depths
    for ($i = $depth; $i <= $max_depth['depth']; $i++) {
        //update members depth
        DB::execute("UPDATE " . TABLE_PREFIX . "members SET depth = " . $depth . " WHERE parent_member_id  IN (" . $members_depth . ");");
        //Get member from next depth
        $members_depth = DB::executeAll("SELECT id FROM " . TABLE_PREFIX . "members WHERE depth= " . $depth . " ORDER BY id");
        $members_depth = array_flat($members_depth);
        $members_depth = implode(",", $members_depth);
        $depth++;
    }
    //END UPDATE depth for all members
    //Load the contact member cache
    set_time_limit(0);
    ini_set('memory_limit', '512M');
    $users = Contacts::getAllUsers();
    $dimensions = Dimensions::findAll();
    $dimensions_ids = array();
    foreach ($dimensions as $dimension) {
        if ($dimension->getDefinesPermissions()) {
            $dimensions_ids[] = $dimension->getId();
        }
    }
    $dimensions_ids = implode(",", $dimensions_ids);
    $root_members = DB::executeAll("SELECT * FROM " . TABLE_PREFIX . "members WHERE dimension_id IN (" . $dimensions_ids . ") AND parent_member_id=0 ORDER BY id");
    foreach ($users as $user) {
        try {
            DB::beginWork();
            foreach ($root_members as $member) {
                ContactMemberCaches::updateContactMemberCache($user, $member['id'], $member['parent_member_id']);
            }
            DB::commit();
        } catch (Exception $e) {
            DB::rollback();
            throw $e;
        }
    }
    //END Load the contact member cache
}
 /**
  * 
  * Checks if user can access the member for a specified access level
  * @param $permission_group_ids - string array: User permission group ids
  * @param $member_id - integer: Member Id
  * @param $user - Contact
  * @param $access_level - enum: ACCESS_LEVEL_READ, ACCESS_LEVEL_WRITE, ACCESS_LEVEL_DELETE
  * @param $check_administrator bool - if user is super administrator do not check permission
  */
 function contactCanAccessMemberAll($permission_group_ids, $member_id, $user, $access_level, $check_administrator = true)
 {
     if ($user instanceof Contact && $user->isAdministrator() && $check_administrator) {
         return true;
     }
     $member = Members::findById($member_id);
     if ($member instanceof Member && !$member->getDimension()->getDefinesPermissions()) {
         return true;
     }
     $disabled_ots = array();
     $disableds = DB::executeAll("SELECT object_type_id FROM " . TABLE_PREFIX . "tab_panels WHERE object_type_id>0 AND enabled=0");
     if (is_array($disableds)) {
         $disabled_ots = array_flat($disableds);
     }
     $ws_ot = ObjectTypes::findByName('workspace')->getId();
     $comment_ot = ObjectTypes::findByName('comment')->getId();
     $disabled_ots[] = $ws_ot;
     $disabled_ots[] = $comment_ot;
     $disabled_ot_cond = "";
     if (count($disabled_ots) > 0) {
         $disabled_ot_cond = "AND object_type_id NOT IN (" . implode(",", $disabled_ots) . ")";
     }
     if ($access_level == ACCESS_LEVEL_READ) {
         if (!isset(self::$readable_members["{$permission_group_ids}"])) {
             $res = DB::execute("SELECT DISTINCT member_id FROM " . TABLE_PREFIX . "contact_member_permissions WHERE permission_group_id IN (" . $permission_group_ids . ") {$disabled_ot_cond}");
             $rows = $res->fetchAll();
             if (is_array($rows)) {
                 self::$readable_members["{$permission_group_ids}"] = array();
                 foreach ($rows as $row) {
                     self::$readable_members["{$permission_group_ids}"][] = $row['member_id'];
                 }
             }
         }
         return in_array($member_id, self::$readable_members["{$permission_group_ids}"]);
     } else {
         if (!isset(self::$writable_members["{$permission_group_ids}"])) {
             $res = DB::execute("SELECT DISTINCT member_id FROM " . TABLE_PREFIX . "contact_member_permissions WHERE can_write=1 AND permission_group_id IN (" . $permission_group_ids . ") {$disabled_ot_cond}");
             $rows = $res->fetchAll();
             if (is_array($rows)) {
                 self::$writable_members["{$permission_group_ids}"] = array();
                 foreach ($rows as $row) {
                     self::$writable_members["{$permission_group_ids}"][] = $row['member_id'];
                 }
             }
         }
         return in_array($member_id, self::$writable_members["{$permission_group_ids}"]);
     }
 }
 /**
  * Removes the object from those members where the user can see the object(and its corresponding parents)
  * 
  */
 static function removeObjectFromMembers(ContentDataObject $object, Contact $contact, $context_members, $members_to_remove = null, $check_permissions = true)
 {
     if (is_null($members_to_remove)) {
         $member_ids = array_flat(DB::executeAll("SELECT om.member_id FROM " . TABLE_PREFIX . "object_members om\r\n  \t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "members m ON m.id=om.member_id\r\n  \t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "dimensions d On d.id=m.dimension_id \r\n  \t\t\t\t\t\tWHERE d.is_manageable=1 AND om.object_id = " . $object->getId()));
     } else {
         $member_ids = $members_to_remove;
     }
     $memebers_deleted_ids = array();
     foreach ($member_ids as $id) {
         $member = Members::findById($id);
         if (!$member instanceof Member) {
             continue;
         }
         if ($check_permissions) {
             //can write this object type in the member
             $can_write = $object->canAddToMember($contact, $member, $context_members);
         } else {
             $can_write = true;
         }
         if ($can_write) {
             $om = self::findById(array('object_id' => $object->getId(), 'member_id' => $id));
             if ($om instanceof ObjectMember) {
                 $om->delete();
                 $memebers_deleted_ids[] = $id;
             }
             $stop = false;
             while ($member->getParentMember() != null && !$stop) {
                 $member = $member->getParentMember();
                 $obj_member = ObjectMembers::findOne(array("conditions" => array("`object_id` = ? AND `member_id` = ? AND \r\n\t\t\t\t\t\t\t\t\t`is_optimization` = 1", $object->getId(), $member->getId())));
                 if (!is_null($obj_member)) {
                     $obj_member->delete();
                 } else {
                     $stop = true;
                 }
             }
         }
     }
     return $memebers_deleted_ids;
 }
Esempio n. 7
0
		/**
		 * Removes the object from those members where the user can see the object(and its corresponding parents)
		 * 
		 */
  		static function removeObjectFromMembers(ContentDataObject $object, Contact $contact, $context_members, $members_to_remove = null){
  			
  			if (is_null($members_to_remove)) {
  				$member_ids = array_flat(DB::executeAll("SELECT member_id FROM ".TABLE_PREFIX."object_members WHERE object_id = " . $object->getId()));
  			} else {
  				$member_ids = $members_to_remove;
  			}
  			
  			foreach($member_ids as $id){
				
				$member = Members::findById($id);
				if (!$member instanceof Member) continue;
				
				//can write this object type in the member
				$can_write = $object->canAddToMember($contact, $member, $context_members);
				
				
				if ($can_write){
					$om = self::findById(array('object_id' => $object->getId(), 'member_id' => $id));
					if ($om instanceof ObjectMember) {
						$om->delete();
					}
					
					$stop = false;
					while ($member->getParentMember() != null && !$stop){
						$member = $member->getParentMember();
						$obj_member = ObjectMembers::findOne(array("conditions" => array("`object_id` = ? AND `member_id` = ? AND 
									`is_optimization` = 1", $object->getId(),$member->getId())));
						if (!is_null($obj_member)) {
							$obj_member->delete();
						}
						else $stop = true;
					}
				}
			}
  		}
Esempio n. 8
0
            $read_events[$rr['rel_object_id']] = 1;
        }
    }
}
// generate repetitive event instances
$repeated_instances = array();
foreach ($all_events as $k => $aev) {
    if ($aev->isRepetitive()) {
        $rep = $aev->getRepetitiveInstances($date_start, $date_end);
        if (count($rep) > 0) {
            $repeated_instances[] = $rep;
            unset($all_events[$k]);
        }
    }
}
$all_events = array_merge($all_events, array_flat($repeated_instances));
$can_add_events = ProjectEvent::canAdd(logged_user(), active_context());
// Loop to render the calendar
for ($week_index = 0;; $week_index++) {
    $month_aux = $month;
    $year_aux = $year;
    $day_of_month = $week_index * 7 + 2 - $firstday;
    $weeknumber = date("W", mktime(0, 0, 0, $month, $day_of_month, $year));
    ?>
						<tr>
						<?php 
    if (user_config_option("show_week_numbers")) {
        ?>
							<td style="width:20px" class="weeknumber" valign="top"><?php 
        echo $weeknumber;
        ?>
Esempio n. 9
0
 function array_flat($array)
 {
     foreach ($array as $a) {
         if (is_array($a)) {
             $tmp = array_merge($tmp, array_flat($a));
         } else {
             $tmp[] = $a;
         }
     }
     return $tmp;
 }
 /**
  * Set object tags. This function accepts tags as params
  *
  * @access public
  * @param void
  * @return boolean
  */
 function setTags()
 {
     if (!plugin_active('tags')) {
         return null;
     }
     if (!$this->isTaggable()) {
         throw new Error('Object not taggable');
     }
     $args = array_flat(func_get_args());
     return Tags::setObjectTags($args, $this, get_class($this->manager()), $this->getProject());
 }
Esempio n. 11
0
 static function select_values()
 {
     $results = call_user_func_array('DB::select', func_get_args());
     return array_flat($results);
 }
Esempio n. 12
0
 /**
  * Execute query and return all rows
  *
  * @access public
  * @param string $sql
  * @return array
  * @throws DBQueryError
  */
 static function executeAll($sql)
 {
     $arguments = func_get_args();
     array_shift($arguments);
     $arguments = count($arguments) ? array_flat($arguments) : null;
     return self::connection()->executeAll($sql, $arguments);
 }
Esempio n. 13
0
 function array_flat($arr)
 {
     $result = array();
     foreach ($arr as $value) {
         if (!is_array($value)) {
             $result[] = $value;
         } else {
             array_splice($result, count($result), 0, array_flat($value));
         }
     }
     return $result;
 }
 static function getLastActivities()
 {
     $members = active_context_members(false);
     // Context Members Ids
     $options = explode(",", user_config_option("filters_dashboard", null, null, true));
     $extra_conditions = "action <> 'login' AND action <> 'logout' AND action <> 'subscribe' AND created_by_id > '0'";
     if ($options[1] == 0) {
         //do not show timeslots
         $extra_conditions .= "AND action <> 'open' AND action <> 'close' AND ((action <> 'add' OR action <> 'edit' OR action <> 'delete') AND object_name NOT LIKE 'Time%')";
     }
     // task assignment conditions
     if (!SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) {
         $extra_conditions .= " AND IF((SELECT o.object_type_id FROM " . TABLE_PREFIX . "objects o WHERE o.id=rel_object_id)=(SELECT ot.id FROM " . TABLE_PREFIX . "object_types ot WHERE ot.name='task'),\r\n\t\t\t\t(SELECT t.assigned_to_contact_id FROM " . TABLE_PREFIX . "project_tasks t WHERE t.object_id=rel_object_id) = " . logged_user()->getId() . ",\r\n\t\t\t\ttrue)";
     }
     //do not display template tasks logs
     $extra_conditions .= " AND IF((SELECT o.object_type_id FROM " . TABLE_PREFIX . "objects o WHERE o.id=rel_object_id)=(SELECT ot.id FROM " . TABLE_PREFIX . "object_types ot WHERE ot.name='template_task'), false, true)";
     // if logged user is guest dont show other users logs
     if (logged_user()->isGuest()) {
         $extra_conditions .= " AND `created_by_id`=" . logged_user()->getId();
     }
     $members_sql = "";
     $is_member_child = "";
     if (count($members) > 0) {
         $members_sql = "(EXISTS(\r\n\t\t\t\tSELECT om.object_id FROM  " . TABLE_PREFIX . "object_members om\r\n\t\t\t\tWHERE om.member_id IN (" . implode(',', $members) . ") AND rel_object_id = om.object_id\r\n\t\t\t\tGROUP BY object_id\r\n\t\t\t\tHAVING count(member_id) = " . count($members) . "\r\n\t\t\t))";
         $is_member_child = "AND mem.parent_member_id IN (" . implode(',', $members) . ")";
     }
     //permissions
     $logged_user_pgs = implode(',', logged_user()->getPermissionGroupIds());
     $permissions_condition = "al.rel_object_id IN (\r\n\t\tSELECT sh.object_id FROM " . TABLE_PREFIX . "sharing_table sh\r\n\t\tWHERE al.rel_object_id = sh.object_id AND sh.object_id > 0\r\n\t\tAND sh.group_id  IN ({$logged_user_pgs})\r\n\t\t)";
     $sql = "SELECT al.id FROM " . TABLE_PREFIX . "application_logs al \r\n\t\t\t\tWHERE {$permissions_condition} AND {$extra_conditions}";
     if ($members_sql != "") {
         $sql .= " AND {$members_sql}";
         //do not display users logs
         $sql .= " AND NOT EXISTS(SELECT con.object_id FROM " . TABLE_PREFIX . "contacts con WHERE con.object_id=rel_object_id AND user_type > 0)";
     }
     $sql .= " ORDER BY created_on DESC LIMIT 100";
     $id_rows = array_flat(DB::executeAll($sql));
     // if logged user is guest dont show other users logs
     $user_condition = "";
     if (logged_user()->isGuest()) {
         $user_condition .= " AND `created_by_id`=" . logged_user()->getId();
     }
     $member_logs_sql = "SELECT al.id FROM " . TABLE_PREFIX . "application_logs al\r\n\t\t\t\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "members mem ON mem.id=al.member_id \r\n\t\t\t\t\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "contact_member_cache cmcache ON cmcache.member_id=mem.id AND cmcache.contact_id = " . logged_user()->getId() . "\r\n\t\t\t\t\t\t\t\t\t\t\tWHERE al.member_id>0\r\n\t\t\t\t\t\t\t\t\t\t\t{$user_condition}\r\n\t\t\t\t\t\t\t\t\t\t\t{$is_member_child}\r\n\t\t\t\t\t\t\tORDER BY created_on DESC LIMIT 100";
     $m_id_rows = array_flat(DB::executeAll($member_logs_sql));
     $id_rows = array_filter(array_merge($id_rows, $m_id_rows));
     $logs = array();
     if (count($id_rows) > 0) {
         $logs = ApplicationLogs::findAll(array("condition" => "id IN (" . implode(',', $id_rows) . ")", "order" => "created_on DESC"));
     }
     return $logs;
 }
Esempio n. 15
0
/**
 * Make Array Flat
 */
function array_flat($array)
{
    $out = array();
    foreach ($array as $k => $v) {
        if (is_array($array[$k])) {
            $out = array_merge($out, array_flat($array[$k]));
        } else {
            $out[] = $v;
        }
    }
    return $out;
}
Esempio n. 16
0
function render_single_member_selector(Dimension $dimension, $genid = null, $selected_member_ids = null, $options = array(), $default_view = true)
{
    if (is_null($genid)) {
        $genid = gen_id();
    }
    $dim_info = array('dimension_id' => $dimension->getId(), 'dimension_code' => $dimension->getCode(), 'dimension_name' => $dimension->getName(), 'is_manageable' => $dimension->getIsManageable(), 'is_required' => array_var($options, 'is_required'), 'is_multiple' => array_var($options, 'is_multiple'));
    $dimensions = array($dim_info);
    if (!is_array($selected_member_ids)) {
        $selected_member_ids = array();
    }
    foreach ($selected_member_ids as $k => &$v) {
        if (!is_numeric($v)) {
            unset($selected_member_ids[$k]);
        }
    }
    if (count($selected_member_ids) > 0) {
        $sql = "SELECT m.id FROM " . TABLE_PREFIX . "members m WHERE m.id IN (" . implode(',', $selected_member_ids) . ") AND m.dimension_id=" . $dimension->getId();
        $clean_sel_member_ids = array_flat(DB::executeAll($sql));
        $selected_member_ids = $clean_sel_member_ids;
    }
    $content_object_type_id = array_var($options, 'content_object_type_id');
    $initial_selected_members = $selected_member_ids;
    if (is_null($selected_member_ids)) {
        $selected_member_ids = array();
    }
    // Set view variables
    $selected_members = count($selected_member_ids) > 0 ? Members::findAll(array('conditions' => 'id IN (' . implode(',', $selected_member_ids) . ')')) : array();
    $selected_members_json = "[" . implode(',', $selected_member_ids) . "]";
    $component_id = "{$genid}-member-selectors-panel-{$content_object_type_id}";
    $listeners = array_var($options, 'listeners', array());
    $allowed_member_type_ids = array_var($options, 'allowedMemberTypes', null);
    $hide_label = array_var($options, 'hide_label', false);
    if (isset($options['label'])) {
        $label = $options['label'];
    }
    // Render view
    include get_template_path("components/multiple_dimension_selector", "dimension");
}
Esempio n. 17
0
 /**
  * @abstract Unarchives the member and its submembers (including content objects)
  * @param user Contact
  * @return Returns the total number of unarchived objects 
  * @author Alvaro Torterola - alvaro.torterola@fengoffice.com
  */
 function unarchive($user)
 {
     if (!$user instanceof Contact) {
         return 0;
     }
     // unarchive this member's objects
     $sql = "SELECT om.object_id FROM " . TABLE_PREFIX . "object_members om INNER JOIN " . TABLE_PREFIX . "objects o ON o.id=om.object_id  \n\t\t\t\tWHERE om.member_id=" . $this->getId() . " AND o.archived_by_id>0";
     $object_ids = DB::executeAll($sql);
     $count = 0;
     foreach ($object_ids as $row) {
         $content_object = Objects::findObject($row['object_id']);
         if ($content_object instanceof ContentDataObject) {
             $content_object->unarchive();
             $count++;
         }
     }
     // Log unarchived objects
     DB::execute("INSERT INTO " . TABLE_PREFIX . "application_logs (taken_by_id, rel_object_id, object_name, created_on, created_by_id, action, is_private, is_silent, log_data)\n\t\t\tVALUES (" . $user->getId() . "," . $this->getId() . "," . DB::escape($this->getName()) . ",NOW()," . $user->getId() . ",'unarchive',0,1,'" . implode(',', array_flat($object_ids)) . "')");
     $this->setArchivedById(0);
     $this->setArchivedOn(EMPTY_DATETIME);
     $this->save();
     $sub_members = $this->getAllChildren();
     foreach ($sub_members as $sub_member) {
         if ($sub_member->getArchivedById() > 0) {
             $count += $sub_member->unarchive($user);
         }
     }
     return $count;
 }
Esempio n. 18
0
 function related()
 {
     if (gmd() > $this->cached_related_expires_on) {
         $length = ceil($this->post_count / 3);
         $length < 12 && ($length = 12);
         $length > 8760 && ($length = 8760);
         DB::update("tags SET cached_related = ?, cached_related_expires_on = ? WHERE id = ?", implode(",", array_flat($this->calculate_related($this->name))), gmd_math('add', 'T' . $length . 'H'), $this->id);
         $this->reload();
     }
     $related = explode(',', $this->cached_related);
     $i = 0;
     $groups = array();
     foreach ($related as $rel) {
         $group[] = $rel;
         if ($i & 1) {
             $groups[] = $group;
             $group = array();
         }
         $i++;
     }
     return $groups;
 }
$allowed_object_types_json = array_var($permission_parameters, 'allowed_object_types_json');
$permission_groups = array_var($permission_parameters, 'permission_groups');
$member_permissions = array_var($permission_parameters, 'member_permissions');
$pg_condition = " AND EXISTS (SELECT pg.id FROM " . TABLE_PREFIX . "permission_groups pg WHERE pg.type<>'roles' AND pg.id=cmp.permission_group_id)";
$with_perm_pg_ids = array();
if ($member instanceof Member) {
    $with_perm_pg_ids = DB::executeAll("SELECT DISTINCT(cmp.permission_group_id) FROM " . TABLE_PREFIX . "contact_member_permissions cmp where cmp.member_id=" . $member->getId() . " {$pg_condition} AND object_type_id IN (" . implode(',', $allowed_object_types_json) . ")");
} else {
    if (isset($parent_sel) && $parent_sel > 0) {
        $with_perm_pg_ids = DB::executeAll("SELECT DISTINCT(cmp.permission_group_id) FROM " . TABLE_PREFIX . "contact_member_permissions cmp where cmp.member_id=" . $parent_sel . " {$pg_condition} AND object_type_id IN (" . implode(',', $allowed_object_types_json) . ")");
    } else {
        $with_perm_pg_ids = DB::executeAll("SELECT c.permission_group_id FROM " . TABLE_PREFIX . "contacts c where c.user_type IN (SELECT id FROM " . TABLE_PREFIX . "permission_groups WHERE type='roles' AND name IN ('Executive','Manager','Administrator','Super Administrator'));");
    }
}
if (count($with_perm_pg_ids)) {
    $with_perm_pg_ids = array_flat($with_perm_pg_ids);
} else {
    $with_perm_pg_ids = array(0);
}
if (count($with_perm_pg_ids) > 0) {
    $with_perm_pgs = PermissionGroups::instance()->FindAll(array('conditions' => 'id IN (' . implode(',', $with_perm_pg_ids) . ')'));
}
$users_with_perms = array();
$groups_with_perms = array();
foreach ($with_perm_pgs as $pg) {
    if ($pg->getType() == 'user_groups') {
        $groups_with_perms[] = $pg;
    } else {
        $c = Contacts::findById($pg->getContactId());
        if ($c instanceof Contact && !$c->getDisabled() && ($c->getUserType() >= logged_user()->getUserType() || $c->getId() == logged_user()->getId())) {
            // key is to order by role and name
Esempio n. 20
0
	private function upload_file($file, $filename, $path, $members) {
		try {
			if ($file == null) {
				$file = new ProjectFile();
				$file->setFilename($filename);
				$file->setIsVisible(true);
				$file->setCreatedOn(new DateTimeValue(time()));
			}

			$file_dt['name'] = $file->getFilename();
			$file_dt['size'] = filesize($path);
			$file_dt['tmp_name'] = $path;
			$extension = trim(get_file_extension($filename));
			$file_dt['type'] = Mime_Types::instance()->get_type($extension);

			if(!trim($file_dt['type'])) $file_dt['type'] = 'text/html';

			DB::beginWork();
			$file->save();
			$ctrl = new ObjectController() ;
			if (is_array($members)) {
				$ctrl->add_to_members($file, array_flat($members));
			}
			
			$revision = $file->handleUploadedFile($file_dt, true, '');

			ApplicationLogs::createLog($file, ApplicationLogs::ACTION_ADD);
			DB::commit();
			return true;
		} catch (Exception $e) {
			DB::rollback();
			flash_error($e->getMessage());
			ajx_current("empty");
		}
		return false;
	} // upload_extracted_file
Esempio n. 21
0
 function getPermissionGroupIds()
 {
     if (is_null($this->pg_ids_cache)) {
         $this->pg_ids_cache = array_flat(DB::executeAll("SELECT permission_group_id FROM " . TABLE_PREFIX . "contact_permission_groups WHERE contact_id = '" . $this->getId() . "'"));
     }
     return $this->pg_ids_cache;
 }
 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);
 }
 function save_permission_group()
 {
     ajx_current("empty");
     if (!can_manage_dimension_members(logged_user())) {
         flash_error(lang('no access permissions'));
         return;
     }
     $member = Members::findById(array_var($_REQUEST, 'member_id'));
     if (!$member instanceof Member) {
         flash_error(lang('member dnx'));
         return;
     }
     $members = array($member);
     // if apply to submembers is checked get submembers verifying logged user permissions
     if (array_var($_REQUEST, 'apply_submembers') > 0) {
         $dimension = $member->getDimension();
         $pg_ids_str = implode(',', logged_user()->getPermissionGroupIds());
         $extra_conditions = "";
         if (!$dimension->hasAllowAllForContact($pg_ids_str)) {
             $extra_conditions = " AND EXISTS (SELECT cmp.member_id FROM " . TABLE_PREFIX . "contact_member_permissions cmp \r\n\t\t\t\t\tWHERE cmp.member_id=" . TABLE_PREFIX . "members.id AND cmp.permission_group_id IN (" . $pg_ids_str . "))";
         }
         $childs = $member->getAllChildren(true, null, $extra_conditions);
         $members = array_merge($members, $childs);
     }
     $pg_id = array_var($_REQUEST, 'pg_id');
     $permissions = array_var($_REQUEST, 'perms');
     $all_permissions = array();
     foreach ($members as $member) {
         $all_permissions[$member->getId()] = json_decode($permissions);
         foreach ($all_permissions[$member->getId()] as &$perm) {
             $perm->m = $member->getId();
         }
     }
     $all_permissions_str = json_encode(array_flat($all_permissions));
     $_POST['permissions'] = $all_permissions_str;
     try {
         DB::beginWork();
         $_POST['root_perm_genid'] = 'dummy_root_perm_genid';
         save_user_permissions_background(logged_user(), $pg_id, false, array(), true);
         $null = null;
         Hook::fire('after_save_member_permissions_for_pg', $_REQUEST, $null);
         DB::commit();
         flash_success(lang("permissions successfully saved"));
     } catch (Exception $e) {
         DB::rollback();
         flash_error($e->getMessage());
     }
 }
Esempio n. 24
0
 /**
  * Execute query and return all rows
  *
  * @access public
  * @param string $sql
  * @return array
  * @throws DBQueryError
  */
 static function executeAll($sql)
 {
     $arguments = func_get_args();
     array_shift($arguments);
     $arguments = count($arguments) ? array_flat($arguments) : null;
     try {
         $start = microtime(true);
         $result = self::connection()->executeAll($sql, $arguments);
         $end = microtime(true);
         if (Env::isDebuggingDB()) {
             Logger::log(number_format($end - $start, 4) . " - " . DB::prepareString($sql, $arguments));
         }
         if (Env::isDebuggingTime()) {
             TimeIt::add("DB", $end - $start, $start, $end);
         }
     } catch (Exception $e) {
         Logger::log("SQL ERROR: " . $e->getMessage() . " - " . DB::prepareString($sql, $arguments));
         throw $e;
     }
     return $result;
 }
 /**
  * Add contact
  *
  * @access public
  * @param void
  * @return null
  */
 function add()
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $this->setTemplate('edit_contact');
     if (array_var($_GET, 'is_user') || array_var(array_var(array_var($_POST, 'contact'), 'user'), 'create-user')) {
         if (!can_manage_security(logged_user())) {
             flash_error(lang('no access permissions'));
             ajx_current("empty");
             return;
         }
     } else {
         $notAllowedMember = '';
         if (!Contact::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 {
                 trim($notAllowedMember) == "" ? flash_error(lang('you must select where to keep', lang('the contact'))) : flash_error(lang('no context permissions to add', lang("contacts"), $notAllowedMember));
             }
             ajx_current("empty");
             return;
         }
     }
     if (!is_array(array_var($_POST, 'contact'))) {
         // set layout for modal form
         if (array_var($_REQUEST, 'modal')) {
             $this->setLayout("json");
             tpl_assign('modal', true);
         }
     }
     $contact = new Contact();
     $im_types = ImTypes::findAll(array('order' => '`id`'));
     $contact_data = array_var($_POST, 'contact');
     if (!array_var($contact_data, 'company_id')) {
         $contact_data['company_id'] = get_id('company_id');
         $contact_data['timezone'] = logged_user()->getTimezone();
     }
     $redirect_to = get_url('contact');
     // Create contact from mail content, when writing an email...
     $contact_email = array_var($_GET, 'ce');
     if ($contact_email) {
         $contact_data['email'] = $contact_email;
     }
     if (array_var($_GET, 'div_id')) {
         $contact_data['new_contact_from_mail_div_id'] = array_var($_GET, 'div_id');
         $contact_data['hf_contacts'] = array_var($_GET, 'hf_contacts');
     }
     if (!array_var($_GET, 'is_user')) {
         tpl_assign('contact_mail', true);
     } else {
         if (isset($_GET['user_type'])) {
             tpl_assign('user_type', array_var($_GET, 'user_type'));
         }
         tpl_assign('contact_mail', false);
     }
     $contact_data['all_phones'] = array();
     $contact_data['all_addresses'] = array();
     $contact_data['all_webpages'] = array();
     $contact_data['all_emails'] = array();
     //User From Contact
     if (array_var($_REQUEST, 'create_user_from_contact')) {
         $contact_old = Contacts::findById(get_id());
         if (!$contact_old instanceof Contact) {
             flash_error(lang('contact dnx'));
             ajx_current("empty");
             return;
         }
         // if
         if (!$contact_old->canEdit(logged_user())) {
             flash_error(lang('no access permissions'));
             ajx_current("empty");
             return;
         }
         // if
         if (array_var($_REQUEST, 'create_user_from_contact')) {
             $contact_data = $this->get_contact_data_from_contact($contact_old);
             tpl_assign('userFromContactId', get_id());
             $contact_old->setNew(true);
             // to keep custom properties and linked objects
             tpl_assign('object', $contact_old);
         }
     }
     if (array_var($_REQUEST, 'user_from_contact_id') > 0) {
         $contact = Contacts::findById(array_var($_REQUEST, 'user_from_contact_id'));
     }
     //END User From Contact
     tpl_assign('contact', $contact);
     tpl_assign('contact_data', $contact_data);
     tpl_assign('im_types', $im_types);
     // telephone types
     $all_telephone_types = TelephoneTypes::getAllTelephoneTypesInfo();
     tpl_assign('all_telephone_types', $all_telephone_types);
     // address types
     $all_address_types = AddressTypes::getAllAddressTypesInfo();
     tpl_assign('all_address_types', $all_address_types);
     // webpage types
     $all_webpage_types = WebpageTypes::getAllWebpageTypesInfo();
     tpl_assign('all_webpage_types', $all_webpage_types);
     // email types
     $all_email_types = EmailTypes::getAllEmailTypesInfo();
     tpl_assign('all_email_types', $all_email_types);
     // Submit
     if (is_array(array_var($_POST, 'contact'))) {
         foreach ($contact_data as $k => &$v) {
             $v = remove_scripts($v);
         }
         ajx_current("empty");
         try {
             //when creating user from contact remove classification from contact first
             if (array_var($_REQUEST, 'user_from_contact_id') > 0) {
                 $members_to_remove = array_flat(DB::executeAll("SELECT m.id FROM " . TABLE_PREFIX . "members m INNER JOIN " . TABLE_PREFIX . "dimensions d ON d.id=m.dimension_id WHERE d.defines_permissions=1"));
                 $removedMemebersIds = ObjectMembers::removeObjectFromMembers($contact, logged_user(), null, $members_to_remove, false);
             }
             DB::beginWork();
             $contact_data['email'] = trim($contact_data['email']);
             $newCompany = false;
             if (array_var($contact_data, 'isNewCompany') == 'true' && is_array(array_var($_POST, 'company'))) {
                 $company_data = array_var($_POST, 'company');
                 $company = new Contact();
                 $company->setFromAttributes($company_data);
                 $company->setIsCompany(true);
                 $company->setObjectName();
                 $company->save();
                 // save phones, addresses and webpages
                 $this->save_phones_addresses_webpages($company_data, $company);
                 if ($company_data['email'] != "") {
                     $company->addEmail($company_data['email'], 'work', true);
                 }
                 $newCompany = true;
             }
             $contact_data['birthday'] = getDateValue($contact_data["birthday"]);
             $contact_data['name'] = $contact_data['first_name'] . " " . $contact_data['surname'];
             $contact->setFromAttributes($contact_data);
             if ($newCompany) {
                 $contact->setCompanyId($company->getId());
             }
             $contact->setObjectName();
             $contact->save();
             // save phones, addresses and webpages
             $this->save_phones_addresses_webpages($contact_data, $contact);
             // main email
             if ($contact_data['email'] != "") {
                 $contact->addEmail($contact_data['email'], 'personal', true);
             }
             // save additional emails
             $this->save_non_main_emails($contact_data, $contact);
             // autodetect timezone
             $autotimezone = array_var($contact_data, 'autodetect_time_zone', null);
             if ($autotimezone !== null) {
                 set_user_config_option('autodetect_time_zone', $autotimezone, $contact->getId());
             }
             //link it!
             $object_controller = new ObjectController();
             $member_ids = json_decode(array_var($_POST, 'members'));
             if (!is_null($member_ids) && !array_var(array_var($contact_data, 'user'), 'create_user')) {
                 $object_controller->add_to_members($contact, $member_ids);
             }
             $no_perm_members_ids = json_decode(array_var($_POST, 'no_perm_members'));
             if (count($no_perm_members_ids)) {
                 $object_controller->add_to_members($contact, $no_perm_members_ids);
             }
             if ($newCompany) {
                 $object_controller->add_to_members($company, $member_ids);
             }
             $object_controller->link_to_new_object($contact);
             $object_controller->add_subscribers($contact);
             $object_controller->add_custom_properties($contact);
             foreach ($im_types as $im_type) {
                 $value = trim(array_var($contact_data, 'im_' . $im_type->getId()));
                 if ($value != '') {
                     $contact_im_value = new ContactImValue();
                     $contact_im_value->setContactId($contact->getId());
                     $contact_im_value->setImTypeId($im_type->getId());
                     $contact_im_value->setValue($value);
                     $contact_im_value->setIsMain(array_var($contact_data, 'default_im') == $im_type->getId());
                     $contact_im_value->save();
                 }
                 // if
             }
             // foreach
             //NEW ! User data in the same form
             $user = array_var(array_var($_POST, 'contact'), 'user');
             if (isset($contact_data['specify_username'])) {
                 if ($contact_data['user']['username'] != "") {
                     $user['username'] = $contact_data['user']['username'];
                 } else {
                     $user['username'] = str_replace(" ", "", strtolower($contact_data['name']));
                 }
             } else {
                 $user['username'] = str_replace(" ", "", strtolower($contact_data['name']));
             }
             if (isset($_POST['notify-user'])) {
                 set_user_config_option("sendEmailNotification", 1, logged_user()->getId());
             } else {
                 set_user_config_option("sendEmailNotification", 0, logged_user()->getId());
             }
             if ($user) {
                 $user_data = $this->createUserFromContactForm($user, $contact->getId(), $contact_data['email'], isset($_POST['notify-user']), false);
                 // add user groups
                 if (isset($_REQUEST['user_groups'])) {
                     $insert_values = "";
                     $group_ids = explode(',', $_REQUEST['user_groups']);
                     foreach ($group_ids as $gid) {
                         if (trim($gid) == "" || !is_numeric($gid)) {
                             continue;
                         }
                         $insert_values .= ($insert_values == "" ? "" : ",") . "(" . $contact->getId() . ", {$gid})";
                     }
                     if ($insert_values != "") {
                         DB::execute("INSERT INTO " . TABLE_PREFIX . "contact_permission_groups VALUES {$insert_values} ON DUPLICATE KEY UPDATE contact_id=contact_id;");
                     }
                 }
                 if (array_var($contact_data, 'isNewCompany') == 'true' && is_array(array_var($_POST, 'company'))) {
                     ApplicationLogs::createLog($company, ApplicationLogs::ACTION_ADD);
                 }
                 ApplicationLogs::createLog($contact, ApplicationLogs::ACTION_ADD);
                 if (isset($contact_data['new_contact_from_mail_div_id'])) {
                     $combo_val = trim($contact->getFirstName() . ' ' . $contact->getSurname() . ' <' . $contact->getEmailAddress('personal') . '>');
                     evt_add("contact added from mail", array("div_id" => $contact_data['new_contact_from_mail_div_id'], "combo_val" => $combo_val, "hf_contacts" => $contact_data['hf_contacts']));
                 }
                 $contact = Contacts::findById($contact->getId());
                 ContactMemberCaches::updateContactMemberCacheAllMembers($contact);
                 evt_add("new user added", $contact->getArrayInfo());
             }
             $null = null;
             Hook::fire('after_add_contact', $contact, $null);
             DB::commit();
             // save user permissions
             if ($user) {
                 DB::beginWork();
                 $contact = Contacts::findById($contact->getId());
                 save_user_permissions_background(logged_user(), $contact->getPermissionGroupId(), $contact->isGuest());
                 DB::commit();
             }
             flash_success(lang('success add contact', $contact->getObjectName()));
             ajx_current("back");
             if (array_var($_REQUEST, 'modal')) {
                 evt_add("reload current panel");
             }
             // Error...
         } catch (Exception $e) {
             DB::rollback();
             flash_error($e->getMessage());
             mark_dao_validation_error_fields($e);
             return;
         }
         // try
         try {
             if ($user) {
                 // Send notification
                 send_notification($user_data, $contact->getId());
             }
         } catch (Exception $e) {
             flash_error($e->getMessage());
         }
     }
     // if
 }
 private function getMailProperties($msg, $i = 0)
 {
     $text = $msg->getTextBody();
     // plain body is already converted to UTF-8 (when mail was saved)
     if (strlen_utf($text) > 150) {
         $text = substr_utf($text, 0, 150) . "...";
     }
     $show_as_conv = user_config_option('show_emails_as_conversations');
     if ($show_as_conv) {
         $conv_total = MailContents::countMailsInConversation($msg);
         $conv_unread = MailContents::countUnreadMailsInConversation($msg);
         $conv_hasatt = MailContents::conversationHasAttachments($msg);
     }
     //if the variable is not set, make the query and set it.
     //seba
     // Comented by php TODO: Feng 2 context/members
     /*
     		if(!isset($this->user_workspaces_ids)){
     			$sql = logged_user()->getWorkspacesQuery();
     			$rows = DB::executeAll($sql);
     			if (count($rows)== 0) $this->user_workspaces_ids = "0";
     			else{
     				foreach ($rows as $row){
     						if ($this->user_workspaces_ids != "") $this->user_workspaces_ids .= ",";
     						$this->user_workspaces_ids .= $row['project_id'];						
     				}
     			}
     		}*/
     /* @var $msg MailContent */
     $persons_dim = Dimensions::findByCode('feng_persons');
     $persons_dim_id = $persons_dim instanceof Dimension ? $persons_dim->getId() : "0";
     $mail_member_ids = array_flat(DB::executeAll("SELECT om.member_id FROM " . TABLE_PREFIX . "object_members om\r\n\t\t\t\tINNER JOIN " . TABLE_PREFIX . "members m ON m.id=om.member_id \r\n\t\t\t\tWHERE om.object_id = '" . $msg->getId() . "' AND om.is_optimization = 0 AND m.dimension_id<>{$persons_dim_id}"));
     $properties = array("id" => $msg->getId(), "ix" => $i, "object_id" => $msg->getId(), "ot_id" => $msg->getObjectTypeId(), "type" => 'email', "hasAttachment" => $msg->getHasAttachments(), "accountId" => $msg->getAccountId(), "accountName" => $msg->getAccount() instanceof MailAccount ? $msg->getAccount()->getName() : lang('n/a'), "subject" => $msg->getSubject(), "text" => $text, "date" => $msg->getReceivedDate() instanceof DateTimeValue ? $msg->getReceivedDate()->isToday() ? format_time($msg->getReceivedDate()) : format_datetime($msg->getReceivedDate()) : lang('n/a'), "userId" => $msg->getAccount() instanceof MailAccount && $msg->getAccount()->getOwner() instanceof Contact ? $msg->getAccount()->getOwner()->getId() : 0, "userName" => $msg->getAccount() instanceof MailAccount && $msg->getAccount()->getOwner() instanceof Contact ? $msg->getAccount()->getOwner()->getObjectName() : lang('n/a'), "isRead" => $show_as_conv ? $conv_unread == 0 : $msg->getIsRead(logged_user()->getId()), "from" => $msg->getFromName() != '' ? $msg->getFromName() : $msg->getFrom(), "from_email" => $msg->getFrom(), "isDraft" => $msg->getIsDraft(), "isSent" => $msg->getIsSent(), "folder" => $msg->getImapFolderName(), "to" => $msg->getTo(), "memPath" => json_encode($msg->getMembersIdsToDisplayPath()), "memberIds" => implode(",", $mail_member_ids));
     if ($show_as_conv) {
         $properties["conv_total"] = $conv_total;
         $properties["conv_unread"] = $conv_unread;
         $properties["conv_hasatt"] = $conv_hasatt;
     }
     return $properties;
 }
Esempio n. 27
0
/**
 * Flattens the array. This function does not preserve keys, it just returns
 * array indexed form 0 .. count - 1
 *
 * @access public
 * @param array $array If this value is not array it will be returned as one
 * @return array
 */
function array_flat($array)
{
    // Not an array
    if (!is_array($array)) {
        return array($array);
    }
    // Prepare result
    $result = array();
    // Loop elemetns
    foreach ($array as $value) {
        // Subelement is array? Flat it
        if (is_array($value)) {
            $value = array_flat($value);
            foreach ($value as $subvalue) {
                $result[] = $subvalue;
            }
        } else {
            $result[] = $value;
        }
        // if
    }
    // if
    // Return result
    return $result;
}
Esempio n. 28
0
/**
 * Flattens the array
 *
 * This function will walk recursivly throug $array and all array values will be appended to $array and removed from
 * subelements. Keys are not preserved (it just returns array indexed form 0 .. count - 1)
 *
 * @param array $array If this value is not array it will be returned as one
 * @return array
 */
function array_flat($array)
{
    if (!is_array($array)) {
        return array($array);
    }
    // if
    $result = array();
    foreach ($array as $value) {
        if (is_array($value)) {
            $value = array_flat($value);
            foreach ($value as $subvalue) {
                $result[] = $subvalue;
            }
            // if
        } else {
            $result[] = $value;
        }
        // if
    }
    // if
    return $result;
}
 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;
     }
 }
Esempio n. 30
0
	static function getLastActivities() {
		$members = active_context_members(false); // Context Members Ids
		$options = explode(",",user_config_option("filters_dashboard",null,null,true));

		$extra_conditions = "action <> 'login' AND action <> 'logout' AND action <> 'subscribe' ";
		if($options[1] == 0){//do not show timeslots
			$extra_conditions .= "AND action <> 'open' AND action <> 'close' AND ((action <> 'add' OR action <> 'edit' OR action <> 'delete') AND object_name NOT LIKE 'Time%')";
		}
		
		// task assignment conditions
		if (!SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) {
			$extra_conditions .= " AND IF((SELECT o.object_type_id FROM ".TABLE_PREFIX."objects o WHERE o.id=rel_object_id)=(SELECT ot.id FROM ".TABLE_PREFIX."object_types ot WHERE ot.name='task'),
				(SELECT t.assigned_to_contact_id FROM ".TABLE_PREFIX."project_tasks t WHERE t.object_id=rel_object_id) = ".logged_user()->getId().",
				true)";
		}

		$members_sql = "";
		if(count($members) > 0){
			$object_ids_rows = DB::executeAll("SELECT object_id FROM " . TABLE_PREFIX . "object_members om
				WHERE member_id IN (" . implode ( ',', $members ) . ")
				GROUP BY object_id HAVING count(member_id) = ".count($members)."");
			
			$object_ids = implode(',', array_flat($object_ids_rows));
			if ($object_ids == "") $object_ids = "0";
			$members_sql = "rel_object_id IN ($object_ids)";
		}

		$permissions_sql = "AND rel_object_id IN (
			SELECT object_id FROM ".TABLE_PREFIX."sharing_table
			WHERE group_id  IN (SELECT permission_group_id FROM ".TABLE_PREFIX."contact_permission_groups WHERE contact_id = ".logged_user()->getId().")
		)";

		$condition = ($members_sql != "" ? $members_sql . " AND " : "") . $extra_conditions . $permissions_sql;
		return ApplicationLogs::findAll(array(
			"condition" => $condition,
			"order" => "created_on DESC",
			"limit" => "100"
		));
	}