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 milestones from active context and parent members of the active context * * @param User $user * @return array */ static function getActiveMilestonesByUser(Contact $user, $context = null) { if (is_null($context)) { $context = active_context(); } $parents = array(); foreach ($context as $k => $member) { if ($member instanceof Member) { $tmp = $member->getParentMember(); while ($tmp != null) { $parents[] = $tmp->getId(); $tmp = $tmp->getParentMember(); } } } $extra_conditions = ""; /* if (count($parents) > 0) { $extra_conditions = "OR EXISTS (SELECT `aux`.`object_id` FROM ".ObjectMembers::instance()->getTableName(true)." `aux` WHERE `aux`.`is_optimization` = 0 AND `aux`.`object_id`=`om`.`object_id` AND `aux`.`member_id` IN (".implode(",",$parents)."))"; } $result = ProjectMilestones::getContentObjects($context, ObjectTypes::findById(ProjectMilestones::instance()->getObjectTypeId()), null, null, $extra_conditions); */ $result = ProjectMilestones::instance()->listing(array("extra_conditions" => $extra_conditions, "extra_member_ids" => $parents)); $milestones = $result->objects; return $milestones; }
/** * Returns milestones from active context and parent members of the active context * * @param User $user * @return array */ static function getActiveMilestonesByUser(Contact $user, $context = null) { if (is_null($context)) { $context = active_context(); } $members = array(); $parents = array(); foreach ($context as $k => $member) { if ($member instanceof Member) { if ($member->getDimension()->getCode() == 'tags') continue; $members[] = $member->getId(); $tmp = $member->getParentMember(); while ($tmp != null){ $parents[] = $tmp->getId(); $tmp = $tmp->getParentMember(); } } } $result = ProjectMilestones::instance()->listing(array( "ignore_context" => true, "member_ids" => $members, "extra_member_ids" => $parents )); $milestones = $result->objects; return $milestones; } // getActiveMilestonesByUser
function core_dimensions_after_add_to_members($object, &$ignored) { if ($object instanceof Report || $object instanceof Timeslot) { return; } // Add to persons and users dimensions $user_ids = array(); if (logged_user() instanceof Contact) { $user_ids[] = logged_user()->getId(); } if ($object instanceof ProjectTask) { /* @var $object ProjectTask */ if ($object->getAssignedById() > 0) { $user_ids[] = $object->getAssignedById(); } if ($object->getAssignedToContactId() > 0) { $user_ids[] = $object->getAssignedToContactId(); } } if ($object instanceof ProjectEvent) { /* @var $object ProjectEvent */ $invitations = EventInvitations::findAll(array("conditions" => "`event_id` = " . $object->getId())); foreach ($invitations as $inv) { $user_ids[] = $inv->getContactId(); } } if ($object instanceof Contact && !$object->isUser()) { $member = Members::findOne(array("conditions" => "`object_id` = (" . $object->getId() . ") AND `dimension_id` = (SELECT `id` FROM `" . TABLE_PREFIX . "dimensions` WHERE `code` = 'feng_persons')")); if ($member instanceof Member) { $object->addToMembers(array($member)); } } $context = active_context(); if (count($context) > 0) { foreach ($context as $selection) { if ($selection instanceof Member && $selection->getDimension()->getCode() == 'feng_persons') { $object->addToMembers(array($selection)); } } } core_dim_add_to_person_user_dimensions($object, $user_ids); }
/** * Returns milestones from active context and parent members of the active context * * @param User $user * @return array */ static function getActiveMilestonesByUser(Contact $user, $context = null) { if (is_null($context)) { $context = active_context(); } $filter_option = config_option('milestone_selector_filter'); $members = array(); $parents = array(); if ($filter_option == 'current_and_parents' || $filter_option == 'current') { foreach ($context as $k => $member) { if ($member instanceof Member) { if ($member->getDimension()->getCode() == 'tags') { continue; } $members[] = $member->getId(); if ($filter_option == 'current_and_parents') { $tmp = $member->getParentMember(); while ($tmp != null) { $parents[] = $tmp->getId(); $tmp = $tmp->getParentMember(); } } } } } $members = array_merge($members, $parents); $pgs = logged_user()->getPermissionGroupIds(); if (count($pgs) == 0) { $pgs[] = 0; } $permission_conditions = "EXISTS(SELECT sh.object_id FROM " . TABLE_PREFIX . "sharing_table sh WHERE sh.object_id=o.id AND sh.group_id IN (" . implode(',', $pgs) . "))"; if ($filter_option != 'all' && count($members) > 0) { $member_conditions = " AND EXISTS(SELECT om.object_id FROM " . TABLE_PREFIX . "object_members om WHERE om.object_id=o.id AND om.member_id IN (" . implode(',', $members) . "))"; } else { $member_conditions = ""; } $conditions = "trashed_by_id = 0 AND archived_by_id = 0 AND {$permission_conditions} {$member_conditions}"; $milestones = ProjectMilestones::findAll(array('conditions' => $conditions, 'order' => 'name')); return $milestones; }
function get_member_childs() { $mem_id = array_var($_GET, 'member'); $offset = array_var($_REQUEST, 'offset', 0); $limit = array_var($_REQUEST, 'limit', 100); $new_limit = $limit + 1; if (function_exists('logged_user') && logged_user() instanceof Contact && ContactMemberPermissions::contactCanAccessMemberAll(implode(',', logged_user()->getPermissionGroupIds()), $mem_id, logged_user(), ACCESS_LEVEL_READ)) { $mem = Members::getMemberById($mem_id); if ($mem instanceof Member) { //Do not use contact member cache for superadmins if (!logged_user()->isAdministrator()) { //use the contact member cache $dimension = $mem->getDimension(); $params = array("dimension" => $dimension, "contact_id" => logged_user()->getId(), "parent_member_id" => $mem->getId(), "extra_condition" => " AND m.archived_by_id=0 ", "start" => $offset, "limit" => $new_limit, "order" => '`name`', "order_dir" => 'ASC'); $childs = $member_cache_list = ContactMemberCaches::getAllMembersWithCachedParentId($params); } else { $childs = Members::getSubmembers($mem, false, "", null, null, $offset, $new_limit); } $more_nodes_left = false; if (count($childs) > $limit) { $more_nodes_left = true; array_pop($childs); } // filter $childs by other dimension associations $context = active_context(); $filter_by_members = array(); foreach ($context as $selection) { if ($selection instanceof Member) { $filter_by_members[] = $selection; } } // build resultant member list $members = $this->buildMemberList($childs, $mem->getDimension(), null, null, null, null); ajx_extra_data(array("members" => $members, "dimension" => $mem->getDimensionId(), "member_id" => $mem->getId(), "more_nodes_left" => $more_nodes_left)); } } ajx_current("empty"); }
$w = $day_of_month - $lastday; } $day_tmp = isset($w) && is_numeric($w) ? $w : 0; $dates[$day_of_week] = new DateTimeValue(mktime(0, 0, 0, $month_aux, $day_tmp, $year_aux)); $today_style[$day_of_week] = ''; if ($currentyear == $dates[$day_of_week]->getYear() && $currentmonth == $dates[$day_of_week]->getMonth() && $currentday == $dates[$day_of_week]->getday()) { // Today $drawHourLine = true; $today_style[$day_of_week] = 'background-color:#FFFF88;opacity:0.4;filter: alpha(opacity = 40);z-index=0;'; } else { if ($year == $year_aux && $month == $month_aux && $day == $day_of_month) { // Selected day $today_style[$day_of_week] = 'background-color:#E4EEEE;opacity:0.4;filter: alpha(opacity = 40);z-index=0;'; } } $results[$day_of_week] = ProjectEvents::getDayProjectEvents($dates[$day_of_week], active_context(), $user_filter, $status_filter); if (!$results[$day_of_week]) { $results[$day_of_week] = array(); } foreach ($results[$day_of_week] as $key => $event) { if ($event->getTypeId() > 1) { $alldayevents[$day_of_week][] = $event; unset($results[$day_of_week][$key]); } } if (is_array($milestones)) { foreach ($milestones as $milestone) { $due_date = new DateTimeValue($milestone->getDueDate()->getTimestamp() + logged_user()->getTimezone() * 3600); if ($dates[$day_of_week]->getTimestamp() == mktime(0, 0, 0, $due_date->getMonth(), $due_date->getDay(), $due_date->getYear())) { $alldayevents[$day_of_week][] = $milestone; }
<?php require_javascript('og/modules/addMessageForm.js'); ?> <form id="<?php echo $genid . 'add-User-Form'?>" class="internalForm" style="height: 100%;width: 100%; overflow: auto;" action="<?php echo get_url("object","add_subscribers_from_object_view",array('object_id'=>$object->getId()))?>" method="post"> <div class="og-add-subscribers"> <?php if (!isset($genid)) $genid = gen_id(); if (!is_array($subscriberIds)) $subscriberIds = array(logged_user()->getId()); // build context to retrieve allowed users, exclude users and persons dimensions $context_tmp = active_context(); $members = $object->getMembers(); $context = array(); foreach ($context_tmp as $selection) { $dimension = ($selection instanceof Member ? $selection->getDimension() : $selection); if (in_array($dimension->getCode(), array('feng_persons', 'feng_users'))) continue; $replace_with = null; foreach ($members as $member) { if ($dimension->getId() == $member->getDimensionId()) { if (is_null($replace_with)) $replace_with = array(); $replace_with[] = $member; } } if (!is_null($replace_with)) { foreach ($replace_with as $rw) $context[] = $rw; } else $context[] = $dimension; } $allowed_users = allowed_users_in_context($object->getObjectTypeId(), $context, ACCESS_LEVEL_READ);
<?php $genid = gen_id(); $selectedPage = user_config_option('custom_report_tab'); $customReports = Reports::getAllReportsByObjectType(); $report = new Report(); $can_add_reports = $report->canAdd(logged_user(), active_context()); $reportPages = array(); $object_types = ObjectTypes::getAvailableObjectTypes(); foreach ($object_types as $ot) { $reportPages[$ot->getId()] = array("name" => $ot->getName(), "display_name" => lang($ot->getName())); } $ignored = null; Hook::fire('modify_report_pages', $ignored, $reportPages); // To add, edit or remove report pages $default_reports = array('task' => array('task time report' => array('url' => get_url('reporting', 'total_task_times_p'), 'name' => lang('task time report'), 'description' => lang('task time report description')))); Hook::fire('modify_default_reports', $ignored, $default_reports); // To add, edit or remove default reports require_javascript("og/ReportingFunctions.js"); ?> <div style="padding:7px"> <table width=100% id="reportingMenu"> <tr> <td style="height:2px;width:140px"></td><td width=12></td><td style="line-height:2px;"> </td><td width=12></td> </tr> <tr> <td height=12></td> <td rowspan=<?php echo count($reportPages) + 2; ?>
if ($use_24_hours) { $timeformat = 'G:i'; } else { $timeformat = 'g:i A'; } echo stylesheet_tag('event/day.css'); //today in gmt 0 $today = DateTimeValueLib::now(); //user today // $today->add('h', logged_user()->getTimezone()); $currentday = $today->format("j"); $currentmonth = $today->format("n"); $currentyear = $today->format("Y"); $drawHourLine = $day == $currentday && $month == $currentmonth && $year == $currentyear; $dtv = DateTimeValueLib::make(0, 0, 0, $month, $day, $year); $result = ProjectEvents::getDayProjectEvents($dtv, active_context(), $user_filter, $status_filter); if (!$result) { $result = array(); } $alldayevents = array(); $milestones = ProjectMilestones::getRangeMilestones($dtv, $dtv); if ($task_filter != "hide") { $tasks = ProjectTasks::getRangeTasksByUser($dtv, $dtv, $user_filter != -1 ? $user : null, $task_filter); } if (user_config_option('show_birthdays_in_calendar')) { $birthdays = Contacts::instance()->getRangeContactsByBirthday($dtv, $dtv, active_context_members(false)); } else { $birthdays = array(); } foreach ($result as $key => $event) { if ($event->getTypeId() > 1) {
} 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(); if (is_array($context)) { foreach ($context as $selection) { if ($selection instanceof Member && $selection->getDimensionId() == $ws_dimension->getId()) { $parent = $selection; break; } } } $ws_ot_id = ObjectTypes::findByName('workspace')->getId(); $pg_array = logged_user()->getPermissionGroupIds(); $current_member_cond = $parent instanceof Member ? "AND parent_member_id=" . $parent->getId() : ""; $members = Members::findAll(array('limit' => $limit, 'order' => "depth, name", 'conditions' => "object_type_id={$ws_ot_id} {$current_member_cond} AND archived_by_id=0 AND EXISTS (\r\n\t\t\tSELECT cmp.member_id FROM " . TABLE_PREFIX . "contact_member_permissions cmp WHERE cmp.member_id=" . TABLE_PREFIX . "members.id AND cmp.permission_group_id IN (" . implode(',', $pg_array) . "))")); if ($parent instanceof Member && count($members) < $limit) { $tmp_ids = array(); foreach ($members as $m) {
<?php set_page_title(lang('milestones')); project_tabbed_navigation(PROJECT_TAB_MILESTONES); project_crumbs(lang('milestones')); if(ProjectMilestone::canAdd(logged_user(), active_context())) { add_page_action(lang('add milestone'), get_url('milestone', 'add'), 'ico-milestone'); } // if ?> <?php if($late_milestones || $today_milestones || $upcoming_milestones) { ?> <div id="milestones"> <?php if(is_array($late_milestones) && count($late_milestones)) { ?> <div id="lateMilestones"> <h2><?php echo lang('late milestones') ?></h2> <?php foreach($late_milestones as $milestone) { $this->assign('milestone', $milestone); $this->includeTemplate(get_template_path('view_milestone', 'milestone')); } // foreach ?> </div> <?php } // if ?> <?php if(is_array($today_milestones) && count($today_milestones)) { ?> <div id="todayMilestones"> <h2><?php echo lang('today milestones') ?></h2> <?php foreach($today_milestones as $milestone) { $this->assign('milestone', $milestone); $this->includeTemplate(get_template_path('view_milestone', 'milestone'));
function instantiate() { $selected_members = array(); $id = get_id(); $template = COTemplates::findById($id); if (!$template instanceof COTemplate) { flash_error(lang("template dnx")); ajx_current("empty"); return; } $parameters = TemplateParameters::getParametersByTemplate($id); $parameterValues = array_var($_POST, 'parameterValues'); if (count($parameters) > 0 && !isset($parameterValues)) { ajx_current("back"); return; } if (array_var($_POST, 'members')) { $selected_members = json_decode(array_var($_POST, 'members')); } else { $context = active_context(); foreach ($context as $selection) { if ($selection instanceof Member) { $selected_members[] = $selection->getId(); } } } $objects = $template->getObjects(); $controller = new ObjectController(); if (count($selected_members > 0)) { $selected_members_instances = Members::findAll(array('conditions' => 'id IN (' . implode($selected_members) . ')')); } else { $selected_members_instances = array(); } DB::beginWork(); $active_context = active_context(); foreach ($objects as $object) { if (!$object instanceof ContentDataObject) { continue; } // copy object $copy = $object->copy(); if ($copy->columnExists('is_template')) { $copy->setColumnValue('is_template', false); } if ($copy instanceof ProjectTask) { // don't copy parent task and milestone $copy->setMilestoneId(0); $copy->setParentId(0); } $copy->save(); /* if (!can_write(logged_user(), $selected_members_instances, $copy->getObjectTypeId()) ) { flash_error(lang('no context permissions to add', $copy instanceof ProjectTask ? lang("tasks") : ($copy instanceof ProjectMilestone ? lang('milestones') : ''))); DB::rollback(); ajx_current("empty"); return; }*/ // Copy members from origial object, if it doesn't have then use active context members /* $template_object_members = $object->getMemberIds(); if (count($template_object_members) == 0) { $object_member_ids = active_context_members(false); if (count($object_member_ids) > 0) { $template_object_members = Members::findAll(array("id" => true, "conditions" => "id IN (".implode(",", $object_member_ids).")")); } }*/ /* Set instantiated object members: * foreach dimension: * if no member is active then the instantiated object is put in the same members as the original for current dimension * if a member is selected in current dimension then the instantiated object will be put in that member */ $template_object_members = $object->getMembers(); $object_members = array(); foreach ($active_context as $selection) { if ($selection instanceof Member) { // member selected $object_members[] = $selection->getId(); } else { if ($selection instanceof Dimension) { // no member selected foreach ($template_object_members as $tom) { if ($tom->getDimensionId() == $selection->getId()) { $object_members[] = $tom->getId(); } } } } } $controller->add_to_members($copy, $object_members); // copy linked objects $copy->copyLinkedObjectsFrom($object); // copy subtasks if applicable if ($copy instanceof ProjectTask) { ProjectTasks::copySubTasks($object, $copy, false); foreach ($copy->getOpenSubTasks(false) as $m_task) { $controller->add_to_members($m_task, $object_members); } $manager = $copy->manager(); } else { if ($copy instanceof ProjectMilestone) { ProjectMilestones::copyTasks($object, $copy, false); foreach ($copy->getTasks(false) as $m_task) { $controller->add_to_members($m_task, $object_members); } $manager = $copy->manager(); } } // copy custom properties $copy->copyCustomPropertiesFrom($object); // set property values as defined in template $objProp = TemplateObjectProperties::getPropertiesByTemplateObject($id, $object->getId()); foreach ($objProp as $property) { $propName = $property->getProperty(); $value = $property->getValue(); if ($manager->getColumnType($propName) == DATA_TYPE_STRING || $manager->getColumnType($propName) == DATA_TYPE_INTEGER) { if (is_array($parameterValues)) { foreach ($parameterValues as $param => $val) { if (strpos($value, '{' . $param . '}') !== FALSE) { $value = str_replace('{' . $param . '}', $val, $value); } } } } else { if ($manager->getColumnType($propName) == DATA_TYPE_DATE || $manager->getColumnType($propName) == DATA_TYPE_DATETIME) { $operator = '+'; if (strpos($value, '+') === false) { $operator = '-'; } $opPos = strpos($value, $operator); if ($opPos !== false) { // Is parametric $dateParam = substr($value, 1, strpos($value, '}') - 1); $date = $parameterValues[$dateParam]; $dateUnit = substr($value, strlen($value) - 1); // d, w or m (for days, weeks or months) if ($dateUnit == 'm') { $dateUnit = 'M'; // make month unit uppercase to call DateTimeValue::add with correct parameter } $dateNum = (int) substr($value, strpos($value, $operator), strlen($value) - 2); $date = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $date); $date = new DateTimeValue($date->getTimestamp() - logged_user()->getTimezone() * 3600); // set date to GMT 0 $value = $date->add($dateUnit, $dateNum); } else { $value = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $value); } } } if ($value != '') { if (!$copy->setColumnValue($propName, $value)) { $copy->object->setColumnValue($propName, $value); } $copy->save(); } } // subscribe assigned to if ($copy instanceof ProjectTask) { foreach ($copy->getOpenSubTasks(false) as $m_task) { if ($m_task->getAssignedTo() instanceof Contact) { $m_task->subscribeUser($copy->getAssignedTo()); } } if ($copy->getAssignedTo() instanceof Contact) { $copy->subscribeUser($copy->getAssignedTo()); } } else { if ($copy instanceof ProjectMilestone) { foreach ($copy->getTasks(false) as $m_task) { if ($m_task->getAssignedTo() instanceof Contact) { $m_task->subscribeUser($copy->getAssignedTo()); } } } } // copy reminders $reminders = ObjectReminders::getByObject($object); foreach ($reminders as $reminder) { $copy_reminder = new ObjectReminder(); $copy_reminder->setContext($reminder->getContext()); $reminder_date = $copy->getColumnValue($reminder->getContext()); if ($reminder_date instanceof DateTimeValue) { $reminder_date = new DateTimeValue($reminder_date->getTimestamp()); $reminder_date->add('m', -$reminder->getMinutesBefore()); } $copy_reminder->setDate($reminder_date); $copy_reminder->setMinutesBefore($reminder->getMinutesBefore()); $copy_reminder->setObject($copy); $copy_reminder->setType($reminder->getType()); $copy_reminder->setUserId($reminder->getUserId()); $copy_reminder->save(); } } DB::commit(); if (is_array($parameters) && count($parameters) > 0) { ajx_current("back"); } else { if (!$choose_ctx) { ajx_current("back"); } else { ajx_current("reload"); } } }
$not_overdue_limit = 5; $overdue_limit = 20; $show_more = false; // Not due tasks $not_due_tasks = ProjectTasks::getUpcomingWithoutDate($not_overdue_limit + 1); if (count($not_due_tasks) > $not_overdue_limit) { $show_more = true; array_pop($not_due_tasks); } // Due Tasks $overdue_upcoming_objects = ProjectTasks::getOverdueAndUpcomingObjects($overdue_limit + 1); // FIXME: performance Killer if (count($overdue_upcoming_objects) > $overdue_limit) { $show_more = true; array_pop($overdue_upcoming_objects); } $overdue_upcoming_objects = array_merge($not_due_tasks, $overdue_upcoming_objects); $users = array(); // Render only when the context isnt 'all' and you have perms $render_add = active_context_members(false) && ProjectTask::canAdd(logged_user(), active_context()); if ($render_add) { $users[] = array(0, lang('dont assign')); foreach (allowed_users_to_assign() as $company) { foreach ($company['users'] as $user) { $name = logged_user()->getId() == $user['id'] ? lang('me') : $user['name']; $users[] = array($user['id'], $name); } } } include_once 'template.php';
function list_objects() { //alert("debugging. remove this line");ajx_current('empty'); return array() ; //TODO remove this line /* get query parameters */ $filesPerPage = config_option('files_per_page'); $start = array_var($_GET, 'start') ? (int) array_var($_GET, 'start') : 0; $limit = array_var($_GET, 'limit') ? array_var($_GET, 'limit') : $filesPerPage; $order = array_var($_GET, 'sort'); $ignore_context = (bool) array_var($_GET, 'ignore_context'); if ($order == "dateUpdated") { $order = "updated_on"; } elseif ($order == "dateArchived") { $order = "archived_on"; } elseif ($order == "dateDeleted") { $order = "trashed_on"; } $orderdir = array_var($_GET, 'dir'); $page = (int) ($start / $limit) + 1; $hide_private = !logged_user()->isMemberOfOwnerCompany(); $typeCSV = array_var($_GET, 'type'); $types = null; if ($typeCSV) { $types = explode(",", $typeCSV); } $name_filter = mysql_escape_string(array_var($_GET, 'name')); $linked_obj_filter = array_var($_GET, 'linkedobject'); $object_ids_filter = ''; if (!is_null($linked_obj_filter)) { $linkedObject = Objects::findObject($linked_obj_filter); $objs = $linkedObject->getLinkedObjects(); foreach ($objs as $obj) { $object_ids_filter .= ($object_ids_filter == '' ? '' : ',') . $obj->getId(); } } $filters = array(); if (!is_null($types)) { $filters['types'] = $types; } if (!is_null($name_filter)) { $filters['name'] = $name_filter; } if ($object_ids_filter != '') { $filters['object_ids'] = $object_ids_filter; } $user = array_var($_GET, 'user'); $trashed = array_var($_GET, 'trashed', false); $archived = array_var($_GET, 'archived', false); /* if there's an action to execute, do so */ if (array_var($_GET, 'action') == 'delete') { $ids = explode(',', array_var($_GET, 'objects')); $result = ContentDataObjects::listing(array("extra_conditions" => " AND o.id IN (" . implode(",", $ids) . ") ", "include_deleted" => true)); $objects = $result->objects; list($succ, $err) = $this->do_delete_objects($objects); if ($err > 0) { flash_error(lang('error delete objects', $err)); } else { Hook::fire('after_object_delete_permanently', $ids, $ignored); flash_success(lang('success delete objects', $succ)); } } else { if (array_var($_GET, 'action') == 'delete_permanently') { $ids = explode(',', array_var($_GET, 'objects')); //$result = Objects::getObjectsFromContext(active_context(), null, null, true, false, array('object_ids' => implode(",",$ids))); $objects = Objects::instance()->findAll(array("conditions" => "id IN (" . implode(",", $ids) . ")")); list($succ, $err) = $this->do_delete_objects($objects, true); if ($err > 0) { flash_error(lang('error delete objects', $err)); } if ($succ > 0) { Hook::fire('after_object_delete_permanently', $ids, $ignored); flash_success(lang('success delete objects', $succ)); } } else { if (array_var($_GET, 'action') == 'markasread') { $ids = explode(',', array_var($_GET, 'objects')); list($succ, $err) = $this->do_mark_as_read_unread_objects($ids, true); } else { if (array_var($_GET, 'action') == 'markasunread') { $ids = explode(',', array_var($_GET, 'objects')); list($succ, $err) = $this->do_mark_as_read_unread_objects($ids, false); } else { if (array_var($_GET, 'action') == 'empty_trash_can') { $result = Objects::getObjectsFromContext(active_context(), 'trashed_on', 'desc', true); $objects = $result->objects; list($succ, $err) = $this->do_delete_objects($objects, true); if ($err > 0) { flash_error(lang('error delete objects', $err)); } if ($succ > 0) { flash_success(lang('success delete objects', $succ)); } } else { if (array_var($_GET, 'action') == 'archive') { $ids = explode(',', array_var($_GET, 'objects')); list($succ, $err) = $this->do_archive_unarchive_objects($ids, 'archive'); if ($err > 0) { flash_error(lang('error archive objects', $err)); } else { flash_success(lang('success archive objects', $succ)); } } else { if (array_var($_GET, 'action') == 'unarchive') { $ids = explode(',', array_var($_GET, 'objects')); list($succ, $err) = $this->do_archive_unarchive_objects($ids, 'unarchive'); if ($err > 0) { flash_error(lang('error unarchive objects', $err)); } else { flash_success(lang('success unarchive objects', $succ)); } } else { if (array_var($_GET, 'action') == 'unclassify') { $ids = explode(',', array_var($_GET, 'objects')); $err = 0; $succ = 0; foreach ($ids as $id) { $split = explode(":", $id); $type = $split[0]; if (Plugins::instance()->isActivePlugin('mail') && $type == 'MailContents') { $email = MailContents::findById($split[1]); if (isset($email) && !$email->isDeleted() && $email->canEdit(logged_user())) { if (MailController::do_unclassify($email)) { $succ++; } else { $err++; } } else { $err++; } } } if ($err > 0) { flash_error(lang('error unclassify emails', $err)); } else { flash_success(lang('success unclassify emails', $succ)); } } else { if (array_var($_GET, 'action') == 'restore') { $errorMessage = null; $ids = explode(',', array_var($_GET, 'objects')); $success = 0; $error = 0; foreach ($ids as $id) { $obj = Objects::findObject($id); if ($obj->canDelete(logged_user())) { try { $obj->untrash($errorMessage); if ($obj->getObjectTypeId() == 11) { $event = ProjectEvents::findById($obj->getId()); if ($event->getExtCalId() != "") { $this->created_event_google_calendar($obj, $event); } } ApplicationLogs::createLog($obj, ApplicationLogs::ACTION_UNTRASH); $success++; } catch (Exception $e) { $error++; } } else { $error++; } } if ($success > 0) { flash_success(lang("success untrash objects", $success)); } if ($error > 0) { $errorString = is_null($errorMessage) ? lang("error untrash objects", $error) : $errorMessage; flash_error($errorString); } } } } } } } } } } $filterName = array_var($_GET, 'name'); $result = null; $context = active_context(); $obj_type_types = array('content_object', 'dimension_object'); if (array_var($_GET, 'include_comments')) { $obj_type_types[] = 'comment'; } $type_condition = ""; if ($types) { $type_condition = " AND name IN ('" . implode("','", $types) . "')"; } $res = DB::executeAll("SELECT id from " . TABLE_PREFIX . "object_types WHERE type IN ('" . implode("','", $obj_type_types) . "') AND name <> 'file revision' {$type_condition} "); $type_ids = array(); foreach ($res as $row) { if (ObjectTypes::isListableObjectType($row['id'])) { $types_ids[] = $row['id']; } } //Hook::fire('list_objects_type_ids', null, $types_ids); $type_ids_csv = implode(',', $types_ids); $extra_conditions = array(); $extra_conditions[] = "object_type_id in ({$type_ids_csv})"; if ($name_filter) { $extra_conditions[] = "name LIKE '%{$name_filter}%'"; } //$pagination = Objects::getObjects($context,$start,$limit,$order,$orderdir,$trashed,$archived, $filters,$start, $limit, $obj_type_types); $pagination = ContentDataObjects::listing(array("start" => $start, "limit" => $limit, "order" => $order, "order_dir" => $orderdir, "trashed" => $trashed, "archived" => $archived, "types" => $types, "count_results" => false, "extra_conditions" => " AND " . implode(" AND ", $extra_conditions), "ignore_context" => $ignore_context)); $result = $pagination->objects; $total_items = $pagination->total; if (!$result) { $result = array(); } /* prepare response object */ $info = array(); foreach ($result as $obj) { $info_elem = $obj->getArrayInfo($trashed, $archived); $instance = Objects::instance()->findObject($info_elem['object_id']); $info_elem['url'] = $instance->getViewUrl(); /* @var $instance Contact */ if ($instance instanceof Contact) { if ($instance->isCompany()) { $info_elem['icon'] = 'ico-company'; $info_elem['type'] = 'company'; } } else { if ($instance instanceof ProjectFile) { $info_elem['mimeType'] = $instance->getTypeString(); } } $info_elem['isRead'] = $instance->getIsRead(logged_user()->getId()); $info_elem['manager'] = get_class($instance->manager()); $info_elem['memPath'] = json_encode($instance->getMembersToDisplayPath()); $info[] = $info_elem; } $listing = array("totalCount" => $total_items, "start" => $start, "objects" => $info); ajx_extra_data($listing); tpl_assign("listing", $listing); if (isset($reload) && $reload) { ajx_current("reload"); } else { ajx_current("empty"); } }
/** * Add message * * @access public * @param void * @return null */ function add() { $this->setTemplate('add_message'); if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current('empty'); return; } $notAllowedMember = ''; if (!ProjectMessage::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 message'))) : flash_error(lang('no context permissions to add', lang("messages"), $notAllowedMember)); } ajx_current("empty"); return; } // if $message = new ProjectMessage(); tpl_assign('message', $message); $message_data = array_var($_POST, 'message'); if (!is_array($message_data)) { // set layout for modal form if (array_var($_REQUEST, 'modal')) { $this->setLayout("json"); tpl_assign('modal', true); } $message_data = array(); } // if tpl_assign('message_data', $message_data); if (is_array(array_var($_POST, 'message'))) { foreach ($message_data as $k => &$v) { $v = remove_scripts($v); } try { if (config_option('untitled_notes')) { if (!array_var($message_data, "name")) { $message_data["name"] = lang("untitled note"); } } // Aliases if (config_option("wysiwyg_messages")) { $message_data['type_content'] = "html"; $message_data['text'] = preg_replace("/[\n|\r|\n\r]/", '', array_var($message_data, 'text')); } else { $message_data['type_content'] = "text"; } $message->setFromAttributes($message_data); DB::beginWork(); $message->save(); $object_controller = new ObjectController(); $member_ids = json_decode(array_var($_POST, 'members')); $object_controller->add_to_members($message, $member_ids); $object_controller->add_subscribers($message); $object_controller->link_to_new_object($message); $object_controller->add_custom_properties($message); DB::commit(); ApplicationLogs::createLog($message, ApplicationLogs::ACTION_ADD); flash_success(lang('success add message', $message->getObjectName())); if (array_var($_POST, 'popup', false)) { ajx_current("reload"); } else { ajx_current("back"); } if (array_var($_REQUEST, 'modal')) { evt_add("reload current panel"); } ajx_add("overview-panel", "reload"); // Error... } catch (Exception $e) { DB::rollback(); $message->setNew(true); flash_error($e->getMessage()); ajx_current("empty"); } // try } // if }
/** * @param unknown_type $content_object_type_id * @param unknown_type $genid * @param unknown_type $selected_members * @param unknown_type $options * @param unknown_type $skipped_dimensions * @param unknown_type $simulate_required */ function render_dimension_trees($content_object_type_id, $genid = null, $selected_members = null, $options = array(), $skipped_dimensions = null, $simulate_required = null) { if (is_numeric($content_object_type_id)) { if (is_null($genid)) $genid = gen_id(); $user_dimensions = get_user_dimensions_ids(); // User allowed dimensions $dimensions = array() ; if ( $all_dimensions = Dimensions::getAllowedDimensions($content_object_type_id) ) { // Diemsions for this content type foreach ($all_dimensions as $dimension){ // A kind of intersection... if ( isset($user_dimensions[$dimension['dimension_id']] ) ){ if( $dimension_options = json_decode($dimension['dimension_options'])){ if (isset($dimension_options->useLangs) && $dimension_options->useLangs ) { $dimension['dimension_name'] = lang($dimension['dimension_code']); } } $dimensions[] = $dimension ; } } } $object_is_new = is_null($selected_members); if ($dimensions!= null && count($dimensions)) { if (is_null($selected_members) && array_var($options, 'select_current_context')) { $context = active_context(); $selected_members = array(); foreach ($context as $selection) { if ($selection instanceof Member) $selected_members[] = $selection->getId(); } } $selected_members_json = json_encode($selected_members); $component_id = "$genid-member-chooser-panel-$content_object_type_id" ; if (isset($options['layout']) && in_array($options['layout'], array('horizontal', 'column'))) { $layout = $options['layout']; } else { //$layout = count($dimensions) > 5 ? "horizontal" : "column"; $layout = "column"; } ?> <?php if (!$object_is_new) : ?> <input id='<?php echo $genid; ?>trees_not_loaded' name='trees_not_loaded' type='hidden' value="1"></input> <?php endif;?> <input id='<?php echo $genid; ?>members' name='members' type='hidden' value="<?php echo str_replace('"', "'", $selected_members_json); ?>"></input> <div id='<?php echo $component_id ?>-container' class="member-chooser-container" ></div> <script> var memberChooserPanel = new og.MemberChooserPanel({ renderTo: '<?php echo $component_id ?>-container', id: '<?php echo $component_id ?>', selectedMembers: <?php echo $selected_members_json?>, layout: '<?php echo $layout; ?>' }) ; <?php foreach ($dimensions as $dimension) : $dimension_id = $dimension['dimension_id']; if (is_array($skipped_dimensions) && in_array($dimension_id, $skipped_dimensions)) continue; if ( is_array(array_var($options, 'allowedDimensions')) && array_search($dimension_id, $options['allowedDimensions']) === false ){ continue; } if (!$dimension['is_manageable']) continue; $is_required = $dimension['is_required']; $dimension_name = $dimension['dimension_name'] ; if ($is_required) $dimension_name.= " *" ; if (is_array($simulate_required) && in_array($dimension_id, $simulate_required)) $is_required = true; if (!isset($id)) $id = gen_id(); ?> var config = { title: '<?php echo $dimension_name ?>', dimensionId: <?php echo $dimension_id ?>, objectTypeId: <?php echo $content_object_type_id ?>, required: <?php echo $is_required ?>, reloadDimensions: <?php echo json_encode( DimensionMemberAssociations::instance()->getDimensionsToReload($dimension_id) ) ; ?>, isMultiple: <?php echo $dimension['is_multiple'] ?>, selModel: <?php echo ($dimension['is_multiple'])? 'new Ext.tree.MultiSelectionModel()': 'new Ext.tree.DefaultSelectionModel()'?> }; <?php if( isset ($options['allowedMemberTypes'])) : ?> config.allowedMemberTypes = <?php echo json_encode($options['allowedMemberTypes']) ?> ; <?php endif; ?> <?php if( isset ($options['collapsible'])) : ?> config.collapsible = <?php echo (int)$options['collapsible'] ?> ; <?php endif; ?> <?php if( isset ($options['collapsed'])) : ?> config.collapsed = <?php echo (int) $options['collapsed'] ?> ; <?php endif; ?> config.listeners = { 'tree rendered': function(tree) { if (!tree.ownerCt.rendered_trees) tree.ownerCt.rendered_trees = 0; tree.ownerCt.rendered_trees++; if (tree.ownerCt.rendered_trees == tree.ownerCt.items.length) tree.ownerCt.fireEvent('all trees rendered', tree.ownerCt); } }; var tree = new og.MemberChooserTree ( config ); memberChooserPanel.add(tree); <?php endforeach; ?> og.can_submit_members = false; memberChooserPanel.on('all trees rendered', function(panel) { og.can_submit_members = true; var trees_to_reload = []; panel.items.each(function(item, index, length) { var checked = item.getLastChecked(); if (checked != 0 && item.filterOnChange) trees_to_reload.push(item); }); if (trees_to_reload.length > 0) { for (var i=0; i<trees_to_reload.length; i++) { trees_to_reload[i].dont_update_form = true; tree = trees_to_reload[i]; setTimeout(function() { tree.dont_update_form = false; }, 2500); } for (var i=1; i<trees_to_reload.length; i++) { var next = trees_to_reload[i]; trees_to_reload[i-1].on('all trees updated', function(){ next.fireEvent('checkchange', next.getNodeById(next.getLastChecked()), true); next.expand(); }); } var t = trees_to_reload[0]; t.fireEvent('checkchange', t.getNodeById(t.getLastChecked()), true); t.expand(); } }); memberChooserPanel.doLayout(); </script> <?php } } }
function list_files() { ajx_current("empty"); // get query parameters $start = (integer)array_var($_GET,'start'); $limit = (integer)array_var($_GET,'limit'); if (! $start) { $start = 0; } if (! $limit) { $limit = config_option('files_per_page'); } $order = array_var($_GET,'sort'); $order_dir = array_var($_GET,'dir'); $page = (integer) ($start / $limit)+1; $hide_private = !logged_user()->isMemberOfOwnerCompany(); $type = array_var($_GET,'type'); $user = array_var($_GET,'user'); // if there's an action to execute, do so if (array_var($_GET, 'action') == 'delete') { $ids = explode(',', array_var($_GET, 'objects')); $succ = 0; $err = 0; foreach ($ids as $id) { $file = ProjectFiles::findById($id); if (isset($file) && $file->canDelete(logged_user())) { try{ DB::beginWork(); $file->trash(); ApplicationLogs::createLog($file, ApplicationLogs::ACTION_TRASH); DB::commit(); $succ++; } catch(Exception $e){ DB::rollback(); $err++; } } else { $err++; } } if ($succ > 0) { flash_success(lang("success delete files", $succ)); } else { flash_error(lang("error delete files", $err)); } } else if (array_var($_GET, 'action') == 'markasread') { $ids = explode(',', array_var($_GET, 'objects')); $succ = 0; $err = 0; foreach ($ids as $id) { $file = ProjectFiles::findById($id); try { $file->setIsRead(logged_user()->getId(),true); $succ++; } catch(Exception $e) { $err ++; } // try }//for if ($succ <= 0) { flash_error(lang("error markasread files", $err)); } }else if (array_var($_GET, 'action') == 'markasunread') { $ids = explode(',', array_var($_GET, 'objects')); $succ = 0; $err = 0; foreach ($ids as $id) { $file = ProjectFiles::findById($id); try { $file->setIsRead(logged_user()->getId(),false); $succ++; } catch(Exception $e) { $err ++; } // try }//for if ($succ <= 0) { flash_error(lang("error markasunread files", $err)); } } else if (array_var($_GET, 'action') == 'zip_add') { $this->zip_add(); } else if (array_var($_GET, 'action') == 'archive') { $ids = explode(',', array_var($_GET, 'ids')); $succ = 0; $err = 0; foreach ($ids as $id) { $file = ProjectFiles::findById($id); if (isset($file) && $file->canEdit(logged_user())) { try{ DB::beginWork(); $file->archive(); ApplicationLogs::createLog($file, ApplicationLogs::ACTION_ARCHIVE); DB::commit(); $succ++; } catch(Exception $e){ DB::rollback(); $err++; } } else { $err++; } } if ($succ > 0) { flash_success(lang("success archive objects", $succ)); } else { flash_error(lang("error archive objects", $err)); } } Hook::fire('classify_action', null, $ret); $join_params = null; if ($order == ProjectFiles::ORDER_BY_POSTTIME) { $order = '`created_on`'; } else if ($order == ProjectFiles::ORDER_BY_MODIFYTIME) { $order = '`updated_on`'; } else if ($order == ProjectFiles::ORDER_BY_SIZE) { $order = '`jt`.`filesize`'; $join_params = array( 'table' => ProjectFileRevisions::instance()->getTableName(), 'jt_field' => 'object_id', 'j_sub_q' => "SELECT max(`x`.`object_id`) FROM ".ProjectFileRevisions::instance()->getTableName()." `x` WHERE `x`.`file_id` = `e`.`object_id`" ); } else { $order = '`name`'; } // if $extra_conditions = $hide_private ? 'AND `is_visible` = 1' : ''; $context = active_context(); $objects = ProjectFiles::instance()->listing(array( "order"=>$order, "order_dir" => $order_dir, "extra_conditions"=> $extra_conditions, "join_params"=> $join_params, "start"=> $start, "limit"=> $limit )); $custom_properties = CustomProperties::getAllCustomPropertiesByObjectType(ProjectFiles::instance()->getObjectTypeId()); // prepare response object $listing = array( "totalCount" => $objects->total, "start" => $start, "objType" => ProjectFiles::instance()->getObjectTypeId(), "files" => array(), ); if (is_array($objects->objects)) { $index = 0; $ids = array(); foreach ($objects->objects as $o) { $coName = ""; $coId = $o->getCheckedOutById(); if ($coId != 0) { if ($coId == logged_user()->getId()) { $coName = "self"; } else { $coUser = Contacts::findById($coId); if ($coUser instanceof Contact) { $coName = $coUser->getUsername(); } else { $coName = ""; } } } if ($o->isMP3()) { $songname = $o->getProperty("songname"); $artist = $o->getProperty("songartist"); $album = $o->getProperty("songalbum"); $track = $o->getProperty("songtrack"); $year = $o->getProperty("songyear"); $duration = $o->getProperty("songduration"); $songInfo = json_encode(array($songname, $artist, $album, $track, $year, $duration, $o->getDownloadUrl(), $o->getFilename(), $o->getId())); } else { $songInfo = array(); } $ids[] = $o->getId(); $values = array( "id" => $o->getId(), "ix" => $index++, "object_id" => $o->getId(), "ot_id" => $o->getObjectTypeId(), "name" => $o->getObjectName(), "type" => $o->getTypeString(), "mimeType" => $o->getTypeString(), "createdBy" => clean($o->getCreatedByDisplayName()), "createdById" => $o->getCreatedById(), "dateCreated" => $o->getCreatedOn() instanceof DateTimeValue ? ($o->getCreatedOn()->isToday() ? format_time($o->getCreatedOn()) : format_datetime($o->getCreatedOn())) : '', "dateCreated_today" => $o->getCreatedOn() instanceof DateTimeValue ? $o->getCreatedOn()->isToday() : 0, "updatedBy" => clean($o->getUpdatedByDisplayName()), "updatedById" => $o->getUpdatedById(), "dateUpdated" => $o->getUpdatedOn() instanceof DateTimeValue ? ($o->getUpdatedOn()->isToday() ? format_time($o->getUpdatedOn()) : format_datetime($o->getUpdatedOn())) : '', "dateUpdated_today" => $o->getUpdatedOn() instanceof DateTimeValue ? $o->getUpdatedOn()->isToday() : 0, "icon" => $o->getTypeIconUrl(), "size" => format_filesize($o->getFileSize()), "url" => $o->getOpenUrl(), "manager" => get_class($o->manager()), "checkedOutByName" => $coName, "checkedOutById" => $coId, "isModifiable" => $o->isModifiable() && $o->canEdit(logged_user()), "modifyUrl" => $o->getModifyUrl(), "songInfo" => $songInfo, "ftype" => $o->getType(), "url" => $o->getUrl(), "memPath" => json_encode($o->getMembersToDisplayPath()), ); if ($o->isMP3()) { $values['isMP3'] = true; } Hook::fire('add_classification_value', $o, $values); foreach ($custom_properties as $cp) { $cp_value = CustomPropertyValues::getCustomPropertyValue($o->getId(), $cp->getId()); $values['cp_'.$cp->getId()] = $cp_value instanceof CustomPropertyValue ? $cp_value->getValue() : ''; } $listing["files"][] = $values; } $read_objects = ReadObjects::getReadByObjectList($ids, logged_user()->getId()); foreach($listing["files"] as &$data) { $data['isRead'] = isset($read_objects[$data['object_id']]); } ajx_extra_data($listing); tpl_assign("listing", $listing); }else{ throw new Error("Not array", $code); } }
/** * 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; }
<?php if (isset($milestone) && $milestone instanceof ProjectMilestone) { if (!$milestone->isTrashed()){ if (!$milestone->isCompleted() && $milestone->canEdit(logged_user())) { add_page_action(lang('complete milestone'), $milestone->getCompleteUrl(rawurlencode(get_url('milestone', 'view', array('id'=>$milestone->getId())))) , 'ico-complete', null, null, true); } // if if ($milestone->isCompleted() && $milestone->canEdit(logged_user())) { add_page_action(lang('open milestone'), $milestone->getOpenUrl(rawurlencode(get_url('milestone', 'view', array('id'=>$milestone->getId())))) , 'ico-reopen', null, null, true); } if (!$milestone->isCompleted()) { $m_members = $milestone->getMembers(); if(array_var($m_members, 0) instanceof Member && $milestone->canAddToMember(logged_user(), array_var($m_members, 0), active_context())) { add_page_action(lang('add task list'), $milestone->getAddTaskUrl(), 'ico-task'); } } // if if ($milestone->canEdit(logged_user())) { add_page_action(lang('edit'), $milestone->getEditUrl(), 'ico-edit', null, null, true); if (!$milestone->isArchived()) { add_page_action(lang('archive'), "javascript:if(confirm(lang('confirm archive object'))) og.openLink('" . $milestone->getArchiveUrl() ."');", 'ico-archive-obj'); } else { add_page_action(lang('unarchive'), "javascript:if(confirm(lang('confirm unarchive object'))) og.openLink('" . $milestone->getUnarchiveUrl() ."');", 'ico-unarchive-obj'); } } // if } if ($milestone->canDelete(logged_user())) { if ($milestone->isTemplate()) { add_page_action(lang('delete'), "javascript:if(confirm(lang('confirm delete milestone'))) og.openLink('" . $milestone->getDeletePermanentlyUrl() ."');", 'ico-delete', null, null, true); } else if ($milestone->isTrashed()) { add_page_action(lang('restore from trash'), "javascript:if(confirm(lang('confirm restore objects'))) og.openLink('" . $milestone->getUntrashUrl() ."');", 'ico-restore', null, null, true); add_page_action(lang('delete permanently'), "javascript:if(confirm(lang('confirm delete permanently'))) og.openLink('" . $milestone->getDeleteUrl() ."');", 'ico-delete', null, null, true);
<div class="coInputMainBlock"> <div> <table><tbody> <?php foreach($parameters as $parameter) {?> <tr style='height:30px;'> <td style="padding:3px 10px 0 10px;"><b><?php echo $parameter['name']; ?></b></td> <td align="left"> <?php if($parameter['type'] == 'string'){ ?> <input id="parameterValues[<?php echo $parameter['name'] ?>]" name="parameterValues[<?php echo $parameter['name'] ?>]" /> <?php }else if($parameter['type'] == 'date'){ ?> <?php echo pick_date_widget2('parameterValues['.$parameter['name'].']')?> <?php }else{ ?> <select name="<?php echo 'parameterValues['.$parameter['name'].']'; ?>"> <?php $companies = allowed_users_to_assign(active_context()); foreach ($companies as $c) {?> <option value="<?php echo $c['id']; ?>"> <?php echo $c['name']; ?></option> <?php $users = $c['users']; if ( count($users) ) { foreach ($users as $usr) {?> <option value="<?php echo $usr['id'] ?>"> <?php echo $usr['name'] ?></option> <?php } } } ?> </select> <?php } ?>
} } } // 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; ?> </td>
/** * Fermormance FIX: getContentObjects replacement * @param array $args * order = null - may be performance killer depending on the order criteria * order_dir = null * extra_conditions = null : extra sql 'inyection' - may be performance killer depending on the injected query * join_params = null : extra join table * trashed = false * archived = false * start = 0 * limit = null * ignore_context * include_deleted * count_results : if true calc found rows else show 'many' * extra_member_ids : Search also objects in this slist of members * member_ids : force to search objects in this list of members (strinct) * */ public function listing($args = array()) { $result = new stdClass(); $result->objects = array(); $result->total = array(); $type_id = self::getObjectTypeId(); $SQL_BASE_JOIN = ''; $SQL_EXTRA_JOINS = ''; $SQL_TYPE_CONDITION = 'true'; $SQL_FOUND_ROWS = ''; if (isset($args['count_results'])) { $count_results = $args['count_results']; } else { $count_results = defined('INFINITE_PAGING') ? !INFINITE_PAGING : false; } //get only the number of results without limit not data if (isset($args['only_count_results'])) { $only_count_results = $args['only_count_results']; } else { $only_count_results = false; } $return_raw_data = array_var($args, 'raw_data'); $start = array_var($args, 'start'); $limit = array_var($args, 'limit'); $member_ids = array_var($args, 'member_ids'); $extra_member_ids = array_var($args, 'extra_member_ids'); $ignore_context = array_var($args, 'ignore_context'); $include_deleted = (bool) array_var($args, 'include_deleted'); $select_columns = array_var($args, 'select_columns'); if (empty($select_columns)) { $select_columns = array('*'); } //template objects $template_objects = (bool) array_var($args, 'template_objects', false); $handler_class = "Objects"; if ($type_id) { // If isset type, is a concrete instance linsting. Otherwise is a generic listing of objects $type = ObjectTypes::findById($type_id); /* @var $object_type ObjectType */ $handler_class = $type->getHandlerClass(); $table_name = self::getTableName(); // Extra Join statements if ($this instanceof ContentDataObjects && $this->object_type_name == 'timeslot') { // if object is a timeslot and is related to a content object => check for members of the related content object. $SQL_BASE_JOIN = " INNER JOIN {$table_name} e ON IF(e.rel_object_id > 0, e.rel_object_id, e.object_id) = o.id "; $SQL_TYPE_CONDITION = "o.object_type_id = IF(e.rel_object_id > 0, (SELECT z.object_type_id FROM " . TABLE_PREFIX . "objects z WHERE z.id = e.rel_object_id), {$type_id})"; } else { $SQL_BASE_JOIN = " INNER JOIN {$table_name} e ON e.object_id = o.id "; $SQL_TYPE_CONDITION = "o.object_type_id = {$type_id}"; } $SQL_EXTRA_JOINS = self::prepareJoinConditions(array_var($args, 'join_params')); } if (!$ignore_context && !$member_ids) { $members = active_context_members(false); // Context Members Ids } elseif (count($member_ids)) { $members = $member_ids; } if (is_array($extra_member_ids)) { if (isset($members)) { $members = array_merge($members, $extra_member_ids); } else { $members = $extra_member_ids; } } // Order statement $SQL_ORDER = self::prepareOrderConditions(array_var($args, 'order'), array_var($args, 'order_dir')); // Prepare Limit SQL if (is_numeric(array_var($args, 'limit')) && array_var($args, 'limit') > 0) { $SQL_LIMIT = "LIMIT " . array_var($args, 'start', 0) . " , " . array_var($args, 'limit'); } else { $SQL_LIMIT = ''; } // Prepare Group By SQL $group_by = array_var($args,'group_by'); if (array_var($args, 'group_by')) { $SQL_GROUP_BY = "GROUP BY " . array_var($args, 'group_by'); } else { $SQL_GROUP_BY = ''; } $SQL_CONTEXT_CONDITION = " true "; //show only objects that are on this members by classification not by hierarchy $show_only_member_objects = array_var($args, 'show_only_member_objects', false); $exclusive_in_member = ''; if ($show_only_member_objects) { $exclusive_in_member = " AND om.`is_optimization` = 0"; } if (!empty($members) && count($members)) { $SQL_CONTEXT_CONDITION = "(EXISTS (SELECT om.object_id\r\n\t\t\t\t\tFROM " . TABLE_PREFIX . "object_members om\r\n\t\t\t\t\tWHERE\tom.member_id IN (" . implode(',', $members) . ") AND o.id = om.object_id {$exclusive_in_member}\r\n\t\t\t\t\tGROUP BY object_id\r\n\t\t\t\t\tHAVING count(member_id) = " . count($members) . "\r\n\t\t\t))"; } else { //show only objects that are on root if ($show_only_member_objects) { if (is_array(active_context())) { $active_dims_ids = array(); foreach (active_context() as $ctx) { if ($ctx instanceof Dimension) { $active_dims_ids[] = $ctx->getId(); } } if (count($active_dims_ids) > 0) { $SQL_CONTEXT_CONDITION = "(NOT EXISTS (SELECT om.object_id\r\n\t\t\t\t\t\t\tFROM " . TABLE_PREFIX . "object_members om\r\n\t\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "members mem ON mem.id = om.member_id AND mem.dimension_id IN (" . implode(",", $active_dims_ids) . ")\r\n\t\t\t\t\t\t\tWHERE\to.id = om.object_id\r\n\t\t\t\t\t\t\t))"; } } } } // Trash && Archived CONDITIONS $trashed_archived_conditions = self::prepareTrashandArchivedConditions(array_var($args, 'trashed'), array_var($args, 'archived')); $SQL_TRASHED_CONDITION = $include_deleted ? ' TRUE ' : $trashed_archived_conditions[0]; $SQL_ARCHIVED_CONDITION = $include_deleted ? ' AND TRUE ' : $trashed_archived_conditions[1]; // Extra CONDITIONS if (array_var($args, 'extra_conditions')) { $SQL_EXTRA_CONDITIONS = array_var($args, 'extra_conditions'); } else { $SQL_EXTRA_CONDITIONS = ''; } $SQL_COLUMNS = implode(',', $select_columns); if (logged_user() instanceof Contact) { $uid = logged_user()->getId(); // Build Main SQL $logged_user_pgs = implode(',', logged_user()->getPermissionGroupIds()); $permissions_condition = "o.id IN (\r\n\t\t\t\t\tSELECT sh.object_id FROM " . TABLE_PREFIX . "sharing_table sh\r\n\t\t\t\t\tWHERE o.id = sh.object_id\r\n\t\t\t\t\tAND sh.group_id IN ({$logged_user_pgs})\r\n\t\t\t)"; /* * Check that the objects to list does not belong only to a non-manageable dimension that defines permissions * Object can be shown if: * 1 - It belongs to at least a member in a dimension that defines permissions and is manageable * 2 - Or it belongs to at least a member in a dimension that does not defines permissions * 3 - Or user has permissions to read objects without classification */ if (!$type instanceof ObjectType || !$type->getName() == 'mail') { $without_perm_dim_ids = Dimensions::findAll(array('id' => true, 'conditions' => "defines_permissions=0")); $no_perm_dims_cond = ""; if (count($without_perm_dim_ids) > 0) { $no_perm_dims_cond = " OR EXISTS (\r\n\t\t\t\t\tselect * from " . TABLE_PREFIX . "object_members omems\r\n\t\t\t\t\t inner join " . TABLE_PREFIX . "members mems on mems.id = omems.member_id\r\n\t\t\t\t\t WHERE omems.object_id=o.id AND mems.dimension_id IN (" . implode(',', $without_perm_dim_ids) . ")\r\n\t\t\t\t)"; } $permissions_condition .= " AND (\r\n\t\t\t\tEXISTS (\r\n\t\t\t\t\tSELECT cmp.permission_group_id FROM " . TABLE_PREFIX . "contact_member_permissions cmp \r\n\t\t\t\t\tWHERE cmp.member_id=0 AND cmp.permission_group_id=" . logged_user()->getPermissionGroupId() . " AND cmp.object_type_id = o.object_type_id\r\n\t\t\t\t)\r\n\t\t\t\tOR\r\n\t\t\t\tEXISTS (\r\n\t\t\t\t\tselect * from " . TABLE_PREFIX . "object_members omems\r\n\t\t\t\t\t\tinner join " . TABLE_PREFIX . "members mems on mems.id = omems.member_id\r\n\t\t\t\t\t\tinner join " . TABLE_PREFIX . "dimensions dims on dims.id = mems.dimension_id\r\n\t\t\t\t\tWHERE omems.object_id=o.id and dims.defines_permissions=1 and dims.is_manageable=1\r\n\t\t\t\t) {$no_perm_dims_cond}\r\n\t\t\t)"; } /********************************************************************************************************/ if (!$this instanceof MailContents && logged_user()->isAdministrator() || $this instanceof Contacts && $this->object_type_name == 'contact' && can_manage_contacts(logged_user())) { $permissions_condition = "true"; } if ($this instanceof ProjectFiles && logged_user()->isAdministrator() && Plugins::instance()->isActivePlugin('mail')) { $permissions_condition = "IF(e.mail_id > 0,\r\n\t\t\t\t\t e.mail_id IN (\r\n\t\t\t\t\t\t\t\t\t\tSELECT sh.object_id FROM " . TABLE_PREFIX . "sharing_table sh\r\n\t\t\t\t\t\t\t\t\t\tWHERE e.mail_id = sh.object_id\r\n\t\t\t\t\t\t\t\t\t\tAND sh.group_id IN ({$logged_user_pgs})\r\n\t\t\t\t\t ),\r\n\t\t\t\t\t true\r\n\t\t\t\t\t)"; } if ($template_objects) { $permissions_condition = "true"; $SQL_BASE_JOIN .= " INNER JOIN " . TABLE_PREFIX . "template_tasks temob ON temob.object_id = o.id "; } $sql = "\r\n\t\t\t\tSELECT {$SQL_FOUND_ROWS} {$SQL_COLUMNS} FROM " . TABLE_PREFIX . "objects o\r\n\t\t\t\t{$SQL_BASE_JOIN}\r\n\t\t\t\t{$SQL_EXTRA_JOINS}\r\n\t\t\t\tWHERE\r\n\t\t\t\t\t{$permissions_condition}\r\n\t\t\t\t\tAND\t{$SQL_CONTEXT_CONDITION}\r\n\t\t\t\t\tAND {$SQL_TYPE_CONDITION}\r\n\t\t\t\t\tAND {$SQL_TRASHED_CONDITION} {$SQL_ARCHIVED_CONDITION} {$SQL_EXTRA_CONDITIONS}\r\n\t\t\t\t{$SQL_GROUP_BY}\r\n\t\t\t\t{$SQL_ORDER}\r\n\t\t\t\t{$SQL_LIMIT}"; if (isset($args['query_wraper_start'])) { $query_wraper_start = $args['query_wraper_start']; $query_wraper_end = $args['query_wraper_end']; $sql = $query_wraper_start . $sql . $query_wraper_end; } $sql_total = "\r\n\t\t\t\tSELECT count(o.id) as total FROM " . TABLE_PREFIX . "objects o\r\n\t\t\t\t{$SQL_BASE_JOIN}\r\n\t\t\t\t{$SQL_EXTRA_JOINS}\r\n\t\t\t\tWHERE\r\n\t\t\t\t\t{$permissions_condition}\r\n\t\t\t\t\tAND\t{$SQL_CONTEXT_CONDITION}\r\n\t\t\t\t\tAND {$SQL_TYPE_CONDITION}\r\n\t\t\t\t\tAND {$SQL_TRASHED_CONDITION} {$SQL_ARCHIVED_CONDITION} {$SQL_EXTRA_CONDITIONS}\r\n\t\t\t\t{$SQL_GROUP_BY}\t\t\t\r\n\t\t\t"; if (!$only_count_results) { // Execute query and build the resultset $rows = DB::executeAll($sql); if ($return_raw_data) { $result->objects = $rows; } else { if ($rows && is_array($rows)) { foreach ($rows as $row) { if ($handler_class) { $phpCode = '$co = ' . $handler_class . '::instance()->loadFromRow($row);'; eval($phpCode); } if ($co) { $result->objects[] = $co; } } } } if ($count_results) { $total = DB::executeOne($sql_total); $result->total = $total['total']; } else { if (count($result->objects) >= $limit) { $result->total = 10000000; } else { $result->total = $start + count($result->objects); } } } else { $total = DB::executeOne($sql_total); $result->total = $total['total']; } } else { $result->objects = array(); $result->total = 0; } return $result; }
function list_all() { ajx_current("empty"); $context = active_context(); $start = array_var($_GET, 'start', 0); $limit = array_var($_GET, 'limit', config_option('files_per_page')); $order = array_var($_GET, 'sort'); if ($order == "updatedOn" || $order == "updated" || $order == "date" || $order == "dateUpdated") { $order = "updated_on"; } $order_dir = array_var($_GET, 'dir'); $page = (int) ($start / $limit) + 1; $hide_private = !logged_user()->isMemberOfOwnerCompany(); if (array_var($_GET, 'action') == 'delete') { $ids = explode(',', array_var($_GET, 'webpages')); $succ = 0; $err = 0; foreach ($ids as $id) { $web_page = ProjectWebpages::findById($id); if (isset($web_page) && $web_page->canDelete(logged_user())) { try { DB::beginWork(); $web_page->trash(); ApplicationLogs::createLog($web_page, ApplicationLogs::ACTION_TRASH); DB::commit(); $succ++; } catch (Exception $e) { DB::rollback(); $err++; } } else { $err++; } } if ($succ > 0) { flash_success(lang("success delete objects", $succ)); } if ($err > 0) { flash_error(lang("error delete objects", $err)); } } else { if (array_var($_GET, 'action') == 'markasread') { $ids = explode(',', array_var($_GET, 'ids')); $succ = 0; $err = 0; foreach ($ids as $id) { $webpage = ProjectWebpages::findById($id); try { $webpage->setIsRead(logged_user()->getId(), true); $succ++; } catch (Exception $e) { $err++; } } if ($succ <= 0) { flash_error(lang("error markasread files", $err)); } } else { if (array_var($_GET, 'action') == 'markasunread') { $ids = explode(',', array_var($_GET, 'ids')); $succ = 0; $err = 0; foreach ($ids as $id) { $webpage = ProjectWebpages::findById($id); try { $webpage->setIsRead(logged_user()->getId(), false); $succ++; } catch (Exception $e) { $err++; } } if ($succ <= 0) { flash_error(lang("error markasunread files", $err)); } } else { if (array_var($_GET, 'action') == 'archive') { $ids = explode(',', array_var($_GET, 'webpages')); $succ = 0; $err = 0; foreach ($ids as $id) { $web_page = ProjectWebpages::findById($id); if (isset($web_page) && $web_page->canEdit(logged_user())) { try { DB::beginWork(); $web_page->archive(); ApplicationLogs::createLog($web_page, ApplicationLogs::ACTION_ARCHIVE); DB::commit(); $succ++; } catch (Exception $e) { DB::rollback(); $err++; } } else { $err++; } } if ($succ > 0) { flash_success(lang("success archive objects", $succ)); } if ($err > 0) { flash_error(lang("error archive objects", $err)); } } } } } $res = ProjectWebpages::instance()->listing(array("order" => $order, "order_dir" => $order_dir)); $object = array("totalCount" => $res->total, "start" => $start, "webpages" => array()); if (isset($res->objects)) { $index = 0; $ids = array(); foreach ($res->objects as $w) { $ids[] = $w->getId(); $object["webpages"][] = array("ix" => $index++, "id" => $w->getId(), "object_id" => $w->getObjectId(), "ot_id" => $w->getObjectTypeId(), "name" => $w->getObjectName(), "description" => $w->getDescription(), "url" => $w->getUrl(), "updatedOn" => $w->getUpdatedOn() instanceof DateTimeValue ? $w->getUpdatedOn()->isToday() ? format_time($w->getUpdatedOn()) : format_datetime($w->getUpdatedOn()) : '', "updatedOn_today" => $w->getUpdatedOn() instanceof DateTimeValue ? $w->getUpdatedOn()->isToday() : 0, "updatedBy" => $w->getUpdatedByDisplayName(), "updatedById" => $w->getUpdatedById(), "memPath" => json_encode($w->getMembersToDisplayPath())); } $read_objects = ReadObjects::getReadByObjectList($ids, logged_user()->getId()); foreach ($object["webpages"] as &$data) { $data['isRead'] = isset($read_objects[$data['object_id']]); } } ajx_extra_data($object); }
/** * Add company * * @param void * @return null */ function add_company() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $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 flash_error(lang('no context permissions to add',lang("contacts"), $notAllowedMember)); ajx_current("empty"); return; } // if $company = new Contact(); $company->setIsCompany(1); $company_data = array_var($_POST, 'company'); if(!is_array($company_data)) { $company_data = array( 'timezone' => logged_user()->getTimezone(), ); // array } // if tpl_assign('company', $company); tpl_assign('company_data', $company_data); if (is_array(array_var($_POST, 'company'))) { $company->setFromAttributes($company_data); $company->setObjectName(); try { Contacts::validate($company_data); DB::beginWork(); $company->save(); if($company_data['address'] != "") $company->addAddress($company_data['address'], $company_data['city'], $company_data['state'], $company_data['country'], $company_data['zipcode'], 'work', true); if($company_data['phone_number'] != "") $company->addPhone($company_data['phone_number'], 'work', true); if($company_data['fax_number'] != "") $company->addPhone($company_data['fax_number'], 'fax', true); if($company_data['homepage'] != "") $company->addWebpage($company_data['homepage'], 'work'); if($company_data['email'] != "") $company->addEmail($company_data['email'], 'work' , true); $object_controller = new ObjectController(); $object_controller->add_subscribers($company); $member_ids = json_decode(array_var($_POST, 'members')); if (!is_null($member_ids)) { $object_controller->add_to_members($company, $member_ids); } $object_controller->link_to_new_object($company); $object_controller->add_custom_properties($company); ApplicationLogs::createLog($company, ApplicationLogs::ACTION_ADD); DB::commit(); flash_success(lang('success add client', $company->getObjectName())); evt_add("company added", array("id" => $company->getObjectId(), "name" => $company->getObjectName())); ajx_current("back"); } catch(Exception $e) { DB::rollback(); ajx_current("empty"); flash_error($e->getMessage()); } // try } // if } // add_company
/** * 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()); } }
/** * Add comment * * Through this controller only logged users can post (no anonymous comments here) * * @param void * @return null */ function add() { $this->setTemplate('add_comment'); $object_id = get_id('object_id'); $object = Objects::findObject($object_id); if (!$object instanceof ContentDataObject) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } // if $comment = new Comment(); $comment_data = array_var($_POST, 'comment'); tpl_assign('comment_form_object', $object); tpl_assign('comment', $comment); tpl_assign('comment_data', $comment_data); if (is_array($comment_data)) { try { try { $attached_files = ProjectFiles::handleHelperUploads(active_context()); } catch (Exception $e) { $attached_files = null; } // try $comment->setFromAttributes($comment_data); $comment->setRelObjectId($object_id); $comment->setObjectName(substr_utf($comment->getText(), 0, 250)); DB::beginWork(); $comment->save(); $comment->addToMembers($object->getMembers()); if (is_array($attached_files)) { foreach ($attached_files as $attached_file) { $comment->attachFile($attached_file); } // foreach } // if // Subscribe user to object if (!$object->isSubscriber(logged_user())) { $object->subscribeUser(logged_user()); } // if if (strlen($comment->getText()) < 100) { $comment_head = $comment->getText(); } else { $lastpos = strpos($comment->getText(), " ", 100); if ($lastpos === false) { $comment_head = $comment->getText(); } else { $comment_head = substr($comment->getText(), 0, $lastpos) . "..."; } } $comment_head = html_to_text($comment_head); ApplicationLogs::createLog($comment, ApplicationLogs::ACTION_COMMENT, false, false, true, $comment_head); DB::commit(); flash_success(lang('success add comment')); ajx_current("reload"); } catch (Exception $e) { DB::rollback(); ajx_current("empty"); flash_error($e->getMessage()); } // try } // if }
private static function getPersonLinkFromEmailAddress($email, $addr_name, $clean = true, $add_contact_link = true) { $name = $email; $url = ""; if (trim($email) == "") { return ""; } if (!is_valid_email($email)) { return $email; } $contact = Contacts::getByEmail($email); if ($contact instanceof Contact && $contact->canView(logged_user())) { $name = $clean ? clean($contact->getObjectName()) : $contact->getObjectName(); $url = $contact->getCardUrl(); } if ($url != "") { return '<a class="internalLink" href="' . $url . '" title="' . $email . '">' . $name . " <{$email}></a>"; } else { $null = null; if (!Contact::canAdd(logged_user(), active_context(), $null)) { return $email; } else { if (trim($email) == "") { return ""; } $url = get_url('contact', 'add', array('ce' => $email)); $to_show = $addr_name == '' ? $email : $addr_name . " <{$email}>"; return $to_show . ($add_contact_link ? ' <a class="internalLink link-ico ico-add" style="padding-left:12px;" href="' . $url . '" title="' . lang('add contact') . '"> </a>' : ''); } } }
/** * Create a new template * */ function new_template() { 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; } // if $id = get_id(); $task = ProjectTasks::findById($id); if (!$task instanceof ProjectTask) { $task_data = array('is_template' => true); } else { $task_data = array('milestone_id' => $task->getMilestoneId(), 'title' => $task->getObjectName(), 'assigned_to' => $task->getAssignedToContactId(), 'parent_id' => $task->getParentId(), 'priority' => $task->getPriority(), 'time_estimate' => $task->getTimeEstimate(), 'text' => $task->getText(), 'is_template' => true, 'copyId' => $task->getId()); // array if ($task->getStartDate() instanceof DateTimeValue) { $task_data['start_date'] = $task->getStartDate()->getTimestamp(); } if ($task->getDueDate() instanceof DateTimeValue) { $task_data['due_date'] = $task->getDueDate()->getTimestamp(); } } $task = new ProjectTask(); tpl_assign('task_data', $task_data); tpl_assign('task', $task); $this->setTemplate("add_task"); }
function list_files() { ajx_current("empty"); // get query parameters $start = (int) array_var($_GET, 'start'); $limit = (int) array_var($_GET, 'limit'); if (!$start) { $start = 0; } if (!$limit) { $limit = config_option('files_per_page'); } $order = array_var($_GET, 'sort'); $order_dir = array_var($_GET, 'dir'); $page = (int) ($start / $limit) + 1; $hide_private = !logged_user()->isMemberOfOwnerCompany(); $type = array_var($_GET, 'type'); $user = array_var($_GET, 'user'); // if there's an action to execute, do so if (array_var($_GET, 'action') == 'delete') { $ids = explode(',', array_var($_GET, 'objects')); $succ = 0; $err = 0; foreach ($ids as $id) { $file = ProjectFiles::findById($id); if (isset($file) && $file->canDelete(logged_user())) { try { DB::beginWork(); $file->trash(); DB::commit(); ApplicationLogs::createLog($file, ApplicationLogs::ACTION_TRASH); $succ++; } catch (Exception $e) { DB::rollback(); $err++; } } else { if (!$file instanceof ProjectFile) { evt_add("popup", array('title' => lang('error'), 'message' => lang("file dnx"))); } else { if (!$file->canDelete(logged_user())) { evt_add("popup", array('title' => lang('error'), 'message' => lang("cannot delete file", $file->getObjectName()))); } } $err++; } } if ($succ > 0) { flash_success(lang("success delete files", $succ)); } else { flash_error(lang("error delete files", $err)); } } else { if (array_var($_GET, 'action') == 'markasread') { $ids = explode(',', array_var($_GET, 'objects')); $succ = 0; $err = 0; foreach ($ids as $id) { $file = ProjectFiles::findById($id); try { $file->setIsRead(logged_user()->getId(), true); $succ++; } catch (Exception $e) { $err++; } // try } //for if ($succ <= 0) { flash_error(lang("error markasread files", $err)); } } else { if (array_var($_GET, 'action') == 'markasunread') { $ids = explode(',', array_var($_GET, 'objects')); $succ = 0; $err = 0; foreach ($ids as $id) { $file = ProjectFiles::findById($id); try { $file->setIsRead(logged_user()->getId(), false); $succ++; } catch (Exception $e) { $err++; } // try } //for if ($succ <= 0) { flash_error(lang("error markasunread files", $err)); } } else { if (array_var($_GET, 'action') == 'zip_add') { $this->zip_add(); } else { if (array_var($_GET, 'action') == 'archive') { $ids = explode(',', array_var($_GET, 'ids')); $succ = 0; $err = 0; foreach ($ids as $id) { $file = ProjectFiles::findById($id); if (isset($file) && $file->canEdit(logged_user())) { try { DB::beginWork(); $file->archive(); DB::commit(); ApplicationLogs::createLog($file, ApplicationLogs::ACTION_ARCHIVE); $succ++; } catch (Exception $e) { DB::rollback(); $err++; } } else { $err++; } } if ($succ > 0) { flash_success(lang("success archive objects", $succ)); } else { flash_error(lang("error archive objects", $err)); } } } } } } Hook::fire('classify_action', null, $ret); $join_params = null; $select_columns = null; $extra_conditions = ""; if (strpos($order, 'p_') == 1) { $cpId = substr($order, 3); $order = 'customProp'; } if ($order == ProjectFiles::ORDER_BY_POSTTIME) { $order = '`created_on`'; } else { if ($order == ProjectFiles::ORDER_BY_MODIFYTIME) { $order = '`updated_on`'; } else { if ($order == ProjectFiles::ORDER_BY_SIZE) { $order = '`jt`.`filesize`'; $join_params = array('table' => ProjectFileRevisions::instance()->getTableName(), 'jt_field' => 'file_id', 'e_field' => 'object_id'); $extra_conditions .= " AND `jt`.`object_id` = (SELECT max(`x`.`object_id`) FROM " . TABLE_PREFIX . "project_file_revisions `x` WHERE `x`.`file_id` = `e`.`object_id`)"; } else { if ($order == 'customProp') { $order = 'IF(ISNULL(jt.value),1,0),jt.value'; $join_params['join_type'] = "LEFT "; $join_params['table'] = "" . TABLE_PREFIX . "custom_property_values"; $join_params['jt_field'] = "object_id"; $join_params['e_field'] = "object_id"; $join_params['on_extra'] = "AND custom_property_id = " . $cpId; $extra_conditions .= " AND ( custom_property_id = " . $cpId . " OR custom_property_id IS NULL)"; $select_columns = array("DISTINCT o.*", "e.*"); } else { $order = '`name`'; } } } } // if $extra_conditions .= $hide_private ? 'AND `is_visible` = 1' : ''; // filter attachments of other people if not filtering $tmp_mids = array(); foreach (active_context() as $selection) { if ($selection instanceof Member) { $d = $selection->getDimension(); if ($d instanceof Dimension && $d->getIsManageable()) { $tmp_mids[] = $selection->getId(); } } } if (count($tmp_mids) == 0) { if (Plugins::instance()->isActivePlugin('mail')) { $extra_conditions .= " AND IF(e.mail_id=0, true, EXISTS (SELECT mac.contact_id FROM " . TABLE_PREFIX . "mail_account_contacts mac \r\n\t\t\t\t\tWHERE mac.contact_id=o.created_by_id AND mac.account_id=(SELECT mc.account_id FROM " . TABLE_PREFIX . "mail_contents mc WHERE mc.object_id=e.mail_id)))"; } } Hook::fire("listing_extra_conditions", null, $extra_conditions); $only_count_result = array_var($_GET, 'only_result', false); $context = active_context(); $objects = ProjectFiles::instance()->listing(array("order" => $order, "order_dir" => $order_dir, "extra_conditions" => $extra_conditions, "show_only_member_objects" => user_config_option('show_only_member_files'), 'count_results' => false, 'only_count_results' => $only_count_result, "join_params" => $join_params, "start" => $start, "limit" => $limit, "select_columns" => $select_columns)); $custom_properties = CustomProperties::getAllCustomPropertiesByObjectType(ProjectFiles::instance()->getObjectTypeId()); // prepare response object $listing = array("totalCount" => $objects->total, "start" => $start, "objType" => ProjectFiles::instance()->getObjectTypeId(), "files" => array()); if (is_array($objects->objects)) { $index = 0; $ids = array(); foreach ($objects->objects as $o) { $coName = ""; $coId = $o->getCheckedOutById(); if ($coId != 0) { if ($coId == logged_user()->getId()) { $coName = "self"; } else { $coUser = Contacts::findById($coId); if ($coUser instanceof Contact) { $coName = $coUser->getObjectName(); } else { $coName = ""; } } } if ($o->isMP3()) { $songname = $o->getProperty("songname"); $artist = $o->getProperty("songartist"); $album = $o->getProperty("songalbum"); $track = $o->getProperty("songtrack"); $year = $o->getProperty("songyear"); $duration = $o->getProperty("songduration"); $songInfo = json_encode(array($songname, $artist, $album, $track, $year, $duration, $o->getDownloadUrl(), $o->getFilename(), $o->getId())); } else { $songInfo = array(); } $ids[] = $o->getId(); $values = array("id" => $o->getId(), "ix" => $index++, "object_id" => $o->getId(), "ot_id" => $o->getObjectTypeId(), "name" => $o->getObjectName(), "type" => $o->getTypeString(), "mimeType" => $o->getTypeString(), "createdBy" => clean($o->getCreatedByDisplayName()), "createdById" => $o->getCreatedById(), "dateCreated" => $o->getCreatedOn() instanceof DateTimeValue ? $o->getCreatedOn()->isToday() ? format_time($o->getCreatedOn()) : format_datetime($o->getCreatedOn()) : '', "dateCreated_today" => $o->getCreatedOn() instanceof DateTimeValue ? $o->getCreatedOn()->isToday() : 0, "updatedBy" => clean($o->getUpdatedByDisplayName()), "updatedById" => $o->getUpdatedById(), "dateUpdated" => $o->getUpdatedOn() instanceof DateTimeValue ? $o->getUpdatedOn()->isToday() ? format_time($o->getUpdatedOn()) : format_datetime($o->getUpdatedOn()) : '', "dateUpdated_today" => $o->getUpdatedOn() instanceof DateTimeValue ? $o->getUpdatedOn()->isToday() : 0, "icon" => $o->getTypeIconUrl(), "size" => format_filesize($o->getFileSize()), "url" => $o->getOpenUrl(), "manager" => get_class($o->manager()), "checkedOutByName" => $coName, "checkedOutById" => $coId, "isModifiable" => $o->isModifiable() && $o->canEdit(logged_user()), "modifyUrl" => $o->getModifyUrl(), "songInfo" => $songInfo, "ftype" => $o->getType(), "url" => $o->getUrl(), "memPath" => json_encode($o->getMembersIdsToDisplayPath()), "genid" => gen_id()); if ($o->isMP3()) { $values['isMP3'] = true; } Hook::fire('add_classification_value', $o, $values); foreach ($custom_properties as $cp) { $values['cp_' . $cp->getId()] = get_custom_property_value_for_listing($cp, $o); } $listing["files"][] = $values; } $read_objects = ReadObjects::getReadByObjectList($ids, logged_user()->getId()); foreach ($listing["files"] as &$data) { $data['isRead'] = isset($read_objects[$data['object_id']]); } ajx_extra_data($listing); tpl_assign("listing", $listing); } else { throw new Error("Not array", $code); } }