public function rebuild($start_date = null, $end_date = null) { if (!$start_date) { $start_date = config_option('last_sharing_table_rebuild'); } if ($start_date instanceof DateTimeValue) { $start_date = $start_date->toMySQL(); } if ($end_date instanceof DateTimeValue) { $end_date = $end_date->toMySQL(); } if ($end_date) { $end_cond = "AND updated_on <= '{$end_date}'"; } try { $object_ids = Objects::instance()->findAll(array('id' => true, "conditions" => "updated_on >= '{$start_date}' {$end_cond}")); $obj_count = 0; DB::beginWork(); foreach ($object_ids as $id) { $obj = Objects::findObject($id); if ($obj instanceof ContentDataObject) { $obj->addToSharingTable(); $obj_count++; } } set_config_option('last_sharing_table_rebuild', DateTimeValueLib::now()->toMySQL()); DB::commit(); } catch (Exception $e) { DB::rollback(); Logger::log("Failed to rebuild sharing table: " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString()); } return $obj_count; }
/** * Return column type * * @access public * @param string $column_name * @return string */ function getCOColumnType($column_name, $columns) { if(isset($columns[$column_name])) { return $columns[$column_name]; } else { return Objects::instance()->getColumnType($column_name); } }
/** * * */ public function activity_feed() { ajx_set_no_back(true); require_javascript("og/modules/dashboardComments.js"); require_javascript("jquery/jquery.scrollTo-min.js"); $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'); $orderdir = array_var($_GET, 'dir'); $page = (int) ($start / $limit) + 1; $extra_conditions = " AND jt.type IN ('content_object', 'comment')"; $trashed = array_var($_GET, 'trashed', false); $archived = array_var($_GET, 'archived', false); $pagination = ContentDataObjects::listing(array("start" => $start, "limit" => $limit, "order" => $order, "order_dir" => $orderdir, "trashed" => $trashed, "archived" => $archived, "count_results" => false, "extra_conditions" => $extra_conditions, "join_params" => array("jt_field" => "id", "e_field" => "object_type_id", "table" => TABLE_PREFIX . "object_types"))); $result = $pagination->objects; $total_items = $pagination->total; if (!$result) { $result = array(); } $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(); if (method_exists($instance, "getText")) { $info_elem['content'] = $instance->getText(); } $info_elem['picture'] = $instance->getCreatedBy()->getPictureUrl(); $info_elem['friendly_date'] = friendly_date($instance->getCreatedOn()); $info_elem['comment'] = $instance->getComments(); if ($instance instanceof Contact) { if ($instance->isCompany()) { $info_elem['icon'] = 'ico-company'; $info_elem['type'] = 'company'; } } $info_elem['isRead'] = $instance->getIsRead(logged_user()->getId()); $info_elem['manager'] = get_class($instance->manager()); $info[] = $info_elem; } $listing = array("totalCount" => $total_items, "start" => $start, "objects" => $info); tpl_assign("feeds", $listing); }
/** * * */ public function activity_feed() { ajx_set_no_back(true); require_javascript("og/modules/dashboardComments.js"); require_javascript("jquery/jquery.scrollTo-min.js"); /* 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'); $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 = 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 = Objects::getObjectsFromContext(active_context(), null, null, false, false, array('object_ids' => implode(",", $ids))); $objects = $result->objects; list($succ, $err) = $this->do_delete_objects($objects); if ($err > 0) { flash_error(lang('error delete objects', $err)); } else { 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 = $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') == '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 ($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); 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); } } } } } } } } } } /*FIXME else if (array_var($_GET, 'action') == 'move') { $wsid = array_var($_GET, "moveTo"); $destination = Projects::findById($wsid); if (!$destination instanceof Project) { $resultMessage = lang('project dnx'); $resultCode = 1; } else if (!can_add(logged_user(), $destination, 'ProjectMessages')) { $resultMessage = lang('no access permissions'); $resultCode = 1; } else { $ids = explode(',', array_var($_GET, 'objects')); $count = 0; DB::beginWork(); foreach ($ids as $id) { $split = explode(":", $id); $type = $split[0]; $obj = Objects::findObject($split[1]); $mantainWs = array_var($_GET, "mantainWs"); if ($type != 'Projects' && $obj->canEdit(logged_user())) { if ($type == 'MailContents') { $email = MailContents::findById($split[1]); $conversation = MailContents::getMailsFromConversation($email); foreach ($conversation as $conv_email) { $count += MailController::addEmailToWorkspace($conv_email->getId(), $destination, $mantainWs); if (array_var($_GET, 'classify_atts') && $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; } $tags = implode(",", $conv_email->getTagNames()); MailController::classifyFile($classification_data, $conv_email, $parsedEmail, array($destination), $mantainWs, $tags); } } $count++; } else { if (!$mantainWs || $type == 'ProjectTasks' || $type == 'ProjectMilestones') { $removed = ""; $ws = $obj->getWorkspaces(); foreach ($ws as $w) { if (can_add(logged_user(), $w, $type)) { $obj->removeFromWorkspace($w); $removed .= $w->getId() . ","; } } $removed = substr($removed, 0, -1); $log_action = ApplicationLogs::ACTION_MOVE; $log_data = ($removed == "" ? "" : "from:$removed;") . "to:$wsid"; } else { $log_action = ApplicationLogs::ACTION_COPY; $log_data = "to:$wsid"; } $obj->addToWorkspace($destination); ApplicationLogs::createLog($obj, $log_action, false, null, true, $log_data); $count++; } } } if ($count > 0) { $reload = true; DB::commit(); flash_success(lang("success move objects", $count)); } else { DB::rollback(); } } }*/ $filterName = array_var($_GET, 'name'); $result = null; $context = active_context(); $obj_type_types = array('content_object'); if (array_var($_GET, 'include_comments')) { $obj_type_types[] = 'comment'; } $pagination = Objects::getObjects($context, $start, $limit, $order, $orderdir, $trashed, $archived, $filters, $start, $limit, $obj_type_types); $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(); if (method_exists($instance, "getText")) { $info_elem['content'] = $instance->getText(); } $info_elem['picture'] = $instance->getCreatedBy()->getPictureUrl(); $info_elem['friendly_date'] = friendly_date($instance->getCreatedOn()); $info_elem['comment'] = $instance->getComments(); /* @var $instance Contact */ if ($instance instanceof Contact) { if ($instance->isCompany()) { $info_elem['icon'] = 'ico-company'; $info_elem['type'] = 'company'; } } $info_elem['isRead'] = $instance->getIsRead(logged_user()->getId()); $info_elem['manager'] = get_class($instance->manager()); $info[] = $info_elem; } $listing = array("totalCount" => $total_items, "start" => $start, "objects" => $info); tpl_assign("feeds", $listing); }
/** * This function will return paginated result. Result is an array where first element is * array of returned object and second populated pagination object that can be used for * obtaining and rendering pagination data using various helpers. * * Items and pagination array vars are indexed with 0 for items and 1 for pagination * because you can't use associative indexing with list() construct * * @access public * @param array $arguments Query argumens (@see find()) Limit and offset are ignored! * @param integer $items_per_page Number of items per page * @param integer $current_page Current page number * @return array */ function paginate($arguments = null, $items_per_page = 10, $current_page = 1) { if (isset($this) && instance_of($this, 'Objects')) { return parent::paginate($arguments, $items_per_page, $current_page); } else { return Objects::instance()->paginate($arguments, $items_per_page, $current_page); } // if }
/** * Execute a report and return results * * @param $id * @param $params * * @return array */ static function executeReport($id, $params, $order_by_col = '', $order_by_asc = true, $offset=0, $limit=50, $to_print = false) { if (is_null(active_context())) { CompanyWebsite::instance()->setContext(build_context_array(array_var($_REQUEST, 'context'))); } $results = array(); $report = self::getReport($id); if($report instanceof Report){ $conditionsFields = ReportConditions::getAllReportConditionsForFields($id); $conditionsCp = ReportConditions::getAllReportConditionsForCustomProperties($id); $ot = ObjectTypes::findById($report->getReportObjectTypeId()); $table = $ot->getTableName(); eval('$managerInstance = ' . $ot->getHandlerClass() . "::instance();"); eval('$item_class = ' . $ot->getHandlerClass() . '::instance()->getItemClass(); $object = new $item_class();'); $order_by = ''; if (is_object($params)) { $params = get_object_vars($params); } $report_columns = ReportColumns::getAllReportColumns($id); $allConditions = ""; if(count($conditionsFields) > 0){ foreach($conditionsFields as $condField){ $skip_condition = false; $model = $ot->getHandlerClass(); $model_instance = new $model(); $col_type = $model_instance->getColumnType($condField->getFieldName()); $allConditions .= ' AND '; $dateFormat = 'm/d/Y'; if(isset($params[$condField->getId()])){ $value = $params[$condField->getId()]; if ($col_type == DATA_TYPE_DATE || $col_type == DATA_TYPE_DATETIME) $dateFormat = user_config_option('date_format'); } else { $value = $condField->getValue(); } if ($value == '' && $condField->getIsParametrizable()) $skip_condition = true; if (!$skip_condition) { if($condField->getCondition() == 'like' || $condField->getCondition() == 'not like'){ $value = '%'.$value.'%'; } if ($col_type == DATA_TYPE_DATE || $col_type == DATA_TYPE_DATETIME) { $dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value); $value = $dtValue->format('Y-m-d'); } if($condField->getCondition() != '%'){ if ($col_type == DATA_TYPE_INTEGER || $col_type == DATA_TYPE_FLOAT) { $allConditions .= '`'.$condField->getFieldName().'` '.$condField->getCondition().' '.DB::escape($value); } else { if ($condField->getCondition()=='=' || $condField->getCondition()=='<=' || $condField->getCondition()=='>='){ if ($col_type == DATA_TYPE_DATETIME || $col_type == DATA_TYPE_DATE) { $equal = 'datediff('.DB::escape($value).', `'.$condField->getFieldName().'`)=0'; } else { $equal = '`'.$condField->getFieldName().'` '.$condField->getCondition().' '.DB::escape($value); } switch($condField->getCondition()){ case '=': $allConditions .= $equal; break; case '<=': case '>=': $allConditions .= '(`'.$condField->getFieldName().'` '.$condField->getCondition().' '.DB::escape($value).' OR '.$equal.') '; break; } } else { $allConditions .= '`'.$condField->getFieldName().'` '.$condField->getCondition().' '.DB::escape($value); } } } else { $allConditions .= '`'.$condField->getFieldName().'` like '.DB::escape("%$value"); } } else $allConditions .= ' true'; } } if(count($conditionsCp) > 0){ $dateFormat = user_config_option('date_format'); $date_format_tip = date_format_tip($dateFormat); foreach($conditionsCp as $condCp){ $cp = CustomProperties::getCustomProperty($condCp->getCustomPropertyId()); $skip_condition = false; if(isset($params[$condCp->getId()."_".$cp->getName()])){ $value = $params[$condCp->getId()."_".$cp->getName()]; }else{ $value = $condCp->getValue(); } if ($value == '' && $condCp->getIsParametrizable()) $skip_condition = true; if (!$skip_condition) { $current_condition = ' AND '; $current_condition .= 'o.id IN ( SELECT object_id as id FROM '.TABLE_PREFIX.'custom_property_values cpv WHERE '; $current_condition .= ' cpv.custom_property_id = '.$condCp->getCustomPropertyId(); $fieldType = $object->getColumnType($condCp->getFieldName()); if($condCp->getCondition() == 'like' || $condCp->getCondition() == 'not like'){ $value = '%'.$value.'%'; } if ($cp->getType() == 'date') { if ($value == $date_format_tip) continue; $dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value); $value = $dtValue->format('Y-m-d H:i:s'); } if($condCp->getCondition() != '%'){ if ($cp->getType() == 'numeric') { $current_condition .= ' AND cpv.value '.$condCp->getCondition().' '.DB::escape($value); }else if ($cp->getType() == 'boolean') { $current_condition .= ' AND cpv.value '.$condCp->getCondition().' '.$value; if (!$value) { $current_condition .= ') OR o.id NOT IN (SELECT object_id as id FROM '.TABLE_PREFIX.'custom_property_values cpv2 WHERE cpv2.object_id=o.id AND cpv2.value=1 AND cpv2.custom_property_id = '.$condCp->getCustomPropertyId(); } }else{ $current_condition .= ' AND cpv.value '.$condCp->getCondition().' '.DB::escape($value); } }else{ $current_condition .= ' AND cpv.value like '.DB::escape("%$value"); } $current_condition .= ')'; $allConditions .= $current_condition; } } } $select_columns = array('*'); $join_params = null; if ($order_by_col == '') { $order_by_col = $report->getOrderBy(); } if (in_array($order_by_col, self::$external_columns)) { $original_order_by_col = $order_by_col; $order_by_col = 'name_order'; $join_params = array( 'table' => Objects::instance()->getTableName(), 'jt_field' => 'id', 'e_field' => $original_order_by_col, 'join_type' => 'left' ); $select_columns = array(); $tmp_cols = $managerInstance->getColumns(); foreach ($tmp_cols as $col) $select_columns[] = "e.$col"; $tmp_cols = Objects::instance()->getColumns(); foreach ($tmp_cols as $col) $select_columns[] = "o.$col"; $select_columns[] = 'jt.name as name_order'; } if ($order_by_asc == null) $order_by_asc = $report->getIsOrderByAsc(); if ($ot->getName() == 'task' && !SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) { $allConditions .= " AND assigned_to_contact_id = ".logged_user()->getId(); } if ($managerInstance) { $result = $managerInstance->listing(array( "select_columns" => $select_columns, "order" => "$order_by_col", "order_dir" => ($order_by_asc ? "ASC" : "DESC"), "extra_conditions" => $allConditions, "join_params" => $join_params )); }else{ // TODO Performance Killer $result = ContentDataObjects::getContentObjects(active_context(), $ot, $order_by_col, ($order_by_asc ? "ASC" : "DESC"), $allConditions); } $objects = $result->objects; $totalResults = $result->total; $results['pagination'] = Reports::getReportPagination($id, $params, $order_by_col, $order_by_asc, $offset, $limit, $totalResults); $dimensions_cache = array(); foreach($report_columns as $column){ if ($column->getCustomPropertyId() == 0) { $field = $column->getFieldName(); if (str_starts_with($field, 'dim_')) { $dim_id = str_replace("dim_", "", $field); $dimension = Dimensions::getDimensionById($dim_id); $dimensions_cache[$dim_id] = $dimension; $doptions = $dimension->getOptions(true); $column_name = $doptions && isset($doptions->useLangs) && $doptions->useLangs ? lang($dimension->getCode()) : $dimension->getName(); $results['columns'][$field] = $column_name; $results['db_columns'][$column_name] = $field; } else { if ($managerInstance->columnExists($field) || Objects::instance()->columnExists($field)) { $column_name = Localization::instance()->lang('field '.$ot->getHandlerClass().' '.$field); if (is_null($column_name)) $column_name = lang('field Objects '.$field); $results['columns'][$field] = $column_name; $results['db_columns'][$column_name] = $field; } } } else { $results['columns'][$column->getCustomPropertyId()] = $column->getCustomPropertyId(); } } $report_rows = array(); foreach($objects as &$object){/* @var $object Object */ $obj_name = $object->getObjectName(); $icon_class = $object->getIconClass(); $row_values = array('object_type_id' => $object->getObjectTypeId()); if (!$to_print) { $row_values['link'] = '<a class="link-ico '.$icon_class.'" title="' . $obj_name . '" target="new" href="' . $object->getViewUrl() . '"> </a>'; } foreach($report_columns as $column){ if ($column->getCustomPropertyId() == 0) { $field = $column->getFieldName(); if (str_starts_with($field, 'dim_')) { $dim_id = str_replace("dim_", "", $field); if (!array_var($dimensions_cache, $dim_id) instanceof Dimension) { $dimension = Dimensions::getDimensionById($dim_id); $dimensions_cache[$dim_id] = $dimension; } else { $dimension = array_var($dimensions_cache, $dim_id); } $members = ObjectMembers::getMembersByObjectAndDimension($object->getId(), $dim_id, " AND om.is_optimization=0"); $value = ""; foreach ($members as $member) {/* @var $member Member */ $val = $member->getPath(); $val .= ($val == "" ? "" : "/") . $member->getName(); if ($value != "") $val = " - $val"; $value .= $val; } $row_values[$field] = $value; } else { $value = $object->getColumnValue($field); if ($value instanceof DateTimeValue) { $field_type = $managerInstance->columnExists($field) ? $managerInstance->getColumnType($field) : Objects::instance()->getColumnType($field); $value = format_value_to_print($field, $value->toMySQL(), $field_type, $report->getReportObjectTypeId()); } if(in_array($field, $managerInstance->getExternalColumns())){ $value = self::instance()->getExternalColumnValue($field, $value, $managerInstance); } else if ($field != 'link'){ $value = html_to_text($value); } if(self::isReportColumnEmail($value)) { if(logged_user()->hasMailAccounts()){ $value = '<a class="internalLink" href="'.get_url('mail', 'add_mail', array('to' => clean($value))).'">'.clean($value).'</a></div>'; }else{ $value = '<a class="internalLink" target="_self" href="mailto:'.clean($value).'">'.clean($value).'</a></div>'; } } $row_values[$field] = $value; } } else { $colCp = $column->getCustomPropertyId(); $cp = CustomProperties::getCustomProperty($colCp); if ($cp instanceof CustomProperty) { /* @var $cp CustomProperty */ $cp_val = CustomPropertyValues::getCustomPropertyValue($object->getId(), $colCp); $row_values[$cp->getName()] = $cp_val instanceof CustomPropertyValue ? $cp_val->getValue() : ""; $results['columns'][$colCp] = $cp->getName(); $results['db_columns'][$cp->getName()] = $colCp; } } } Hook::fire("report_row", $object, $row_values); $report_rows[] = $row_values; } if (!$to_print) { if (is_array($results['columns'])) { array_unshift($results['columns'], ''); } else { $results['columns'] = array(''); } Hook::fire("report_header", $ot, $results['columns']); } $results['rows'] = $report_rows; } return $results; } // executeReport
/** * Return manager instance * * @access protected * @param void * @return Objects */ function manager() { if (!$this->manager instanceof Objects) { $this->manager = Objects::instance(); } return $this->manager; }
<?php chdir(dirname(__FILE__)); header("Content-type: text/plain"); define("CONSOLE_MODE", true); include "init.php"; Env::useHelper('format'); define('SCRIPT_MEMORY_LIMIT', 1024 * 1024 * 1024); // 1 GB @set_time_limit(0); ini_set('memory_limit', SCRIPT_MEMORY_LIMIT / (1024 * 1024) + 50 . 'M'); $i = 0; $objects_ids = Objects::instance()->findAll(array('columns' => array('id'), 'id' => true)); //,'conditions' => 'object_type_id = 6' echo "\nObjects to process: " . count($objects_ids) . "\n-----------------------------------------------------------------"; foreach ($objects_ids as $object_id) { $object = Objects::findObject($object_id); $i++; if ($object instanceof ContentDataObject) { $members = $object->getMembers(); DB::execute("DELETE FROM " . TABLE_PREFIX . "object_members WHERE object_id = " . $object->getId() . " AND is_optimization = 1;"); ObjectMembers::addObjectToMembers($object->getId(), $members); } else { // } if ($i % 100 == 0) { echo "\n{$i} objects processed. Mem usage: " . format_filesize(memory_get_usage(true)); } }
/** * Add single mail * * @access public * @param void * @return null */ function add_mail() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $this->addHelper('textile'); $mail_accounts = MailAccounts::getMailAccountsByUser(logged_user()); if (count($mail_accounts) < 1) { flash_error(lang('no mail accounts set')); ajx_current("empty"); return; } $this->setTemplate('add_mail'); $mail_data = array_var($_POST, 'mail'); $sendBtnClick = array_var($mail_data, 'sendBtnClick', '') == 'true' ? true : false; $isDraft = array_var($mail_data, 'isDraft', '') == 'true' ? true : false; $isUpload = array_var($mail_data, 'isUpload', '') == 'true' ? true : false; $autosave = array_var($mail_data, 'autosave', '') == 'true'; $id = array_var($mail_data, 'id'); $mail = MailContents::findById($id); $isNew = false; if (!$mail) { $isNew = true; $mail = new MailContent(); } tpl_assign('mail_to', urldecode(array_var($_GET, 'to'))); tpl_assign('link_to_objects', array_var($_GET, 'link_to_objects')); $def_acc_id = $this->getDefaultAccountId(); if ($def_acc_id > 0) { $def_acc = MailAccounts::getAccountById($def_acc_id); if ($def_acc instanceof MailAccount) { tpl_assign('default_account', $def_acc); } } tpl_assign('mail', $mail); tpl_assign('mail_data', $mail_data); tpl_assign('mail_accounts', $mail_accounts); Hook::fire('send_to', array_var($_GET, 'ids'), array_var($_GET, 'me')); // Form is submited if (is_array($mail_data)) { $account = MailAccounts::findById(array_var($mail_data, 'account_id')); if (!$account instanceof MailAccount) { flash_error(lang('mail account dnx')); ajx_current("empty"); return; } $accountUser = MailAccountContacts::getByAccountAndContact($account, logged_user()); if (!$accountUser instanceof MailAccountContact) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } if ($account->getOutgoingTrasnportType() == 'ssl' || $account->getOutgoingTrasnportType() == 'tls') { $available_transports = stream_get_transports(); if (array_search($account->getOutgoingTrasnportType(), $available_transports) === FALSE) { flash_error('The server does not support SSL.'); ajx_current("empty"); return; } } $cp_errs = $this->checkRequiredCustomPropsBeforeSave(array_var($_POST, 'object_custom_properties', array())); if (is_array($cp_errs) && count($cp_errs) > 0) { foreach ($cp_errs as $err) { flash_error($err); } ajx_current("empty"); return; } $subject = array_var($mail_data, 'subject'); $body = array_var($mail_data, 'body'); if (($pre_body_fname = array_var($mail_data, 'pre_body_fname')) != "") { $body = str_replace(lang('content too long not loaded'), '', $body, $count = 1); $tmp_filename = ROOT . "/tmp/{$pre_body_fname}"; if (is_file($tmp_filename)) { $body .= file_get_contents($tmp_filename); if (!$isDraft) { @unlink($tmp_filename); } } } if (array_var($mail_data, 'format') == 'html') { $css = "font-family:sans-serif,Arial,Verdana; font-size:14px; line-height:1.6; color:#222;"; Hook::fire('email_base_css', null, $css); str_replace(array("\r", "\n"), "", $css); $body = '<div style="' . $css . '">' . $body . '</div>'; $body = str_replace('<blockquote>', '<blockquote style="border-left:1px solid #987ADD;padding-left:10px;">', $body); } $type = 'text/' . array_var($mail_data, 'format'); $to = trim(array_var($mail_data, 'to')); if (str_ends_with($to, ",") || str_ends_with($to, ";")) { $to = substr($to, 0, strlen($to) - 1); } $mail_data['to'] = $to; $cc = trim(array_var($mail_data, 'cc')); if (str_ends_with($cc, ",") || str_ends_with($cc, ";")) { $cc = substr($cc, 0, strlen($cc) - 1); } $mail_data['cc'] = $cc; $bcc = trim(array_var($mail_data, 'bcc')); if (str_ends_with($bcc, ",") || str_ends_with($bcc, ";")) { $bcc = substr($bcc, 0, strlen($bcc) - 1); } $mail_data['bcc'] = $bcc; if (!$isDraft && trim($to . $cc . $bcc) == '') { flash_error(lang('recipient must be specified')); ajx_current("empty"); return; } $invalid_to = MailUtilities::validate_email_addresses($to); if (is_array($invalid_to)) { flash_error(lang('error invalid recipients', lang('mail to'), implode(", ", $invalid_to))); ajx_current("empty"); return; } $invalid_cc = MailUtilities::validate_email_addresses($cc); if (is_array($invalid_cc)) { flash_error(lang('error invalid recipients', lang('mail CC'), implode(", ", $invalid_cc))); ajx_current("empty"); return; } $invalid_bcc = MailUtilities::validate_email_addresses($bcc); if (is_array($invalid_bcc)) { flash_error(lang('error invalid recipients', lang('mail BCC'), implode(", ", $invalid_bcc))); ajx_current("empty"); return; } $last_mail_in_conversation = array_var($mail_data, 'last_mail_in_conversation'); $conversation_id = array_var($mail_data, 'conversation_id'); if ($last_mail_in_conversation && $conversation_id) { $new_mail_in_conversation = MailContents::getLastMailIdInConversation($conversation_id, true); if ($new_mail_in_conversation != $last_mail_in_conversation) { ajx_current("empty"); evt_add("new email in conversation", array('id' => $new_mail_in_conversation, 'genid' => array_var($_POST, 'instanceName'))); return; } } $mail->setFromAttributes($mail_data); $mail->setTo($to); $mail->setCc($cc); $mail->setBcc($bcc); $mail->setSubject($mail_data['subject']); $utils = new MailUtilities(); // attachment $linked_attachments = array(); $attachments = array(); $project_files_attachments = array(); $objects = array_var($_POST, 'linked_objects'); $attach_contents = array_var($_POST, 'attach_contents', array()); $original_email = isset($mail_data['original_id']) ? MailContents::findById($mail_data['original_id']) : null; if (is_array($objects)) { $err = 0; $count = -1; foreach ($objects as $objid) { $count++; $split = explode(":", $objid); if (count($split) == 2) { $object = Objects::instance()->findObject($split[1]); } else { if (count($split) == 4) { if ($split[0] == 'FwdMailAttach') { $tmp_filename = ROOT . "/tmp/" . logged_user()->getId() . "_" . ($original_email ? $original_email->getAccountId() : $mail_data['account_id']) . "_FwdMailAttach_" . $split[3]; if (is_file($tmp_filename)) { $attachments[] = array("data" => file_get_contents($tmp_filename), "name" => $split[1], "type" => $split[2]); continue; } } } } if (!isset($object) || !$object) { flash_error(lang('file dnx')); $err++; } else { if (isset($attach_contents[$count])) { if ($split[0] == 'ProjectFiles') { $file = ProjectFiles::findById($object->getId()); if (!$file instanceof ProjectFile) { flash_error(lang('file dnx')); $err++; } // if // if(!$file->canDownload(logged_user())) { // flash_error(lang('no access permissions')); // $err++; // } // if $project_files_attachments[] = $file; $attachments[] = array("data" => $file->getFileContent(), "name" => $file->getFilename(), "type" => $file->getTypeString()); } else { if ($split[0] == 'MailContents') { $email = MailContents::findById($object->getId()); if (!$email instanceof MailContent) { flash_error(lang('email dnx')); $err++; } // if if (!$email->canView(logged_user())) { flash_error(lang('no access permissions')); $err++; } // if $attachments[] = array("data" => $email->getContent(), "name" => $email->getSubject() . ".eml", "type" => 'message/rfc822'); } } } else { $linked_attachments[] = array("data" => $object->getViewUrl(), "name" => clean($object->getObjectName()), "type" => lang($object->getObjectTypeName()), "id" => $object->getId()); } } } if ($err > 0) { flash_error(lang('some objects could not be linked', $err)); ajx_current('empty'); return; } } $to = preg_split('/;|,/', $to); $to = $utils->parse_to($to); if ($body == '') { $body .= ' '; } try { $linked_users = array(); //create contacts from recipients of email if (user_config_option('create_contacts_from_email_recipients') || can_manage_contacts(logged_user())) { foreach ($to as $to_user) { $linked_user = Contacts::getByEmail($to_user[1]); if (!$linked_user instanceof Contact) { try { DB::beginWork(); $linked_user = create_user_from_email($to_user[1], $to_user[0], null, false); DB::commit(); } catch (Exception $e) { Logger::log($e->getMessage()); DB::rollback(); } } if ($linked_user instanceof Contact) { $linked_users[] = $linked_user; } } } if (count($linked_attachments)) { $linked_atts = $type == 'text/html' ? '<div style="font-family:arial;"><br><br><br><span style="font-size:12pt;font-weight:bold;color:#777">' . lang('linked attachments') . '</span><ul>' : "\n\n\n-----------------------------------------\n" . lang('linked attachments') . "\n\n"; foreach ($linked_attachments as $att) { $linked_atts .= $type == 'text/html' ? '<li><a href="' . $att['data'] . '">' . $att['name'] . ' (' . $att['type'] . ')</a></li>' : $att['name'] . ' (' . $att['type'] . '): ' . $att['data'] . "\n"; foreach ($linked_users as $linked_user) { try { $linked_user->giveAccessToObject(Objects::findObject($att['id'])); } catch (Exception $e) { //Logger::log($e->getMessage()); } } } $linked_atts .= $type == 'text/html' ? '</ul></div>' : ''; } else { $linked_atts = ''; } $body .= $linked_atts; if (count($attachments) > 0) { $i = 0; $str = ""; /* foreach ($attachments as $att) { $str .= "--000000000000000000000000000$i\n"; $str .= "Name: ".$att['name'] .";\n"; $str .= "Type: ".$att['type'] .";\n"; //$str .= "Encoding: ".$att['type'] .";\n"; $str .= base64_encode($att['data']) ."\n"; $str .= "--000000000000000000000000000$i--\n"; $i++; } */ $str = "#att_ver 2\n"; foreach ($attachments as $att) { $rep_id = $utils->saveContent($att['data']); if (str_starts_with($att['name'], "#")) { $att['name'] = str_replace_first("#", "@@sharp@@", $att['name']); } $str .= $att['name'] . "|" . $att['type'] . "|" . $rep_id . "\n"; } // save attachments, when mail is sent this file is deleted and full content is saved $repository_id = $utils->saveContent($str); if (!$isNew) { if (FileRepository::isInRepository($mail->getContentFileId())) { // delete old attachments $content = FileRepository::getFileContent($mail->getContentFileId()); if (str_starts_with($content, "#att_ver")) { $lines = explode("\n", $content); foreach ($lines as $line) { if (!str_starts_with($line, "#") && trim($line) !== "") { $data = explode("|", $line); if (isset($data[2]) && FileRepository::isInRepository($data[2])) { FileRepository::deleteFile($data[2]); } } } } FileRepository::deleteFile($mail->getContentFileId()); } } $mail->setContentFileId($repository_id); } $mail->setHasAttachments(is_array($attachments) && count($attachments) > 0 ? 1 : 0); $mail->setAccountEmail($account->getEmailAddress()); $mail->setSentDate(DateTimeValueLib::now()); $mail->setReceivedDate(DateTimeValueLib::now()); DB::beginWork(); $msg_id = MailUtilities::generateMessageId($account->getEmailAddress()); $conversation_id = array_var($mail_data, 'conversation_id'); $in_reply_to_id = array_var($mail_data, 'in_reply_to_id'); if ($conversation_id) { $in_reply_to = MailContents::findById(array_var($mail_data, 'original_id')); if ($in_reply_to instanceof MailContent && $in_reply_to->getSubject() && strpos(strtolower($mail->getSubject()), strtolower($in_reply_to->getSubject())) === false) { $conversation_id = null; $in_reply_to_id = ''; } } if (!$conversation_id) { $conversation_id = MailContents::getNextConversationId($account->getId()); } $mail->setMessageId($msg_id); $mail->setConversationId($conversation_id); $mail->setInReplyToId($in_reply_to_id); $mail->setUid(gen_id()); $mail->setState($isDraft && !$sendBtnClick ? 2 : 200); set_user_config_option('last_mail_format', array_var($mail_data, 'format', 'plain'), logged_user()->getId()); $body = utf8_safe($body); if (array_var($mail_data, 'format') == 'html') { $body = preg_replace("/<body*[^>]*>/i", '<body>', $body); // commented because sometimes brokes the html and leaves the body in blank //$body = convert_to_links(preg_replace("/<body*[^>]*>/i",'<body>', $body)); $mail->setBodyHtml($body); $mail->setBodyPlain(utf8_safe(html_to_text($body))); } else { $mail->setBodyPlain($body); $mail->setBodyHtml(''); } $mail->setFrom($account->getEmailAddress()); if ($accountUser->getIsDefault() && $accountUser->getSenderName() == "") { $mail->setFromName(logged_user()->getObjectName()); } else { $mail->setFromName($accountUser->getSenderName()); } $mail->save(); //$mail->setIsRead(logged_user()->getId(), true); if (Plugins::instance()->isActivePlugin('mail_rules')) { if (array_var($mail_data, 'format') == 'html') { $img = MailTracks::get_track_mark_img($mail->getId()); $body = $body . $img; $mail->setBodyHtml($body); $mail->setBodyPlain(utf8_safe(html_to_text($body))); $mail->save(); } } foreach ($project_files_attachments as $pfatt) { if ($pfatt instanceof ProjectFile) { $pfatt->setMailId($mail->getId()); $pfatt->save(); $pfatt->addToSharingTable(); } } $member_ids = active_context_members(false); // if replying a classified email classify on same workspace $classified_with_conversation = false; if (array_var($mail_data, 'original_id')) { $in_reply_to = MailContents::findById(array_var($mail_data, 'original_id')); if ($in_reply_to instanceof MailContent) { $member_ids = array_merge($member_ids, $in_reply_to->getMemberIds()); $classified_with_conversation = true; } } // autoclassify sent email if not classified if (!$classified_with_conversation) { $acc_mem_ids = explode(',', $account->getMemberId()); foreach ($acc_mem_ids as $acc_mem_id) { $member_ids[] = $acc_mem_id; } } $object_controller = new ObjectController(); foreach ($member_ids as $k => &$mem_id) { if ($mem_id == "") { unset($member_ids[$k]); } } if (count($member_ids) > 0) { //$object_controller->add_to_members($mail, $member_ids); $members = Members::instance()->findAll(array('conditions' => 'id IN (' . implode(',', $member_ids) . ')')); $mail->addToMembers($members, true); $mail->addToSharingTable(); } $object_controller->link_to_new_object($mail); $object_controller->add_subscribers($mail); /* if (array_var($mail_data, 'link_to_objects') != ''){ $lto = explode('|', array_var($mail_data, 'link_to_objects')); foreach ($lto as $object_string){ $split_object = explode('-', $object_string); $object = Objects::findObject($split_object[1]); if ($object instanceof ContentDataObject){ $mail->linkObject($object); } } }*/ //subscribe user $user = Contacts::findById($account->getContactId()); if ($user instanceof Contact) { $mail->subscribeUser($user); } /*if (user_config_option('create_contacts_from_email_recipients') && can_manage_contacts(logged_user())) { // automatically create contacts foreach ($to as $recipient) { $recipient_name = trim($recipient[0]); $recipient_address = trim($recipient[1]); if (!$recipient_address) continue; $contact = Contacts::getByEmail($recipient_address); if (!$contact instanceof Contact) { try { $contact = new Contact(); $contact->addEmail($recipient_address, 'personal'); if ($recipient_name && $recipient_name != $recipient_address) { $contact->setFirstName($recipient_name); } else { $index = strpos($recipient_address, "@"); $recipient_name = substr($recipient_address, 0, $index); $contact->setFirstName($recipient_name); } $contact->save(); } catch (Exception $e) { Logger::log($e->getMessage()); } } } }*/ $mail->addToSharingTable(); $mail->orderConversation(); DB::commit(); ApplicationLogs::createLog($mail, ApplicationLogs::ACTION_ADD, false, true); $mail->setIsRead(logged_user()->getId(), true); if (!$autosave) { if ($isDraft && !$sendBtnClick) { flash_success(lang('success save mail')); ajx_current("empty"); } else { evt_add("must send mails", array("account" => $mail->getAccountId())); //flash_success(lang('mail is being sent')); ajx_current("back"); } evt_add("email saved", array("id" => $mail->getId(), "instance" => array_var($_POST, 'instanceName'))); } else { evt_add("draft mail autosaved", array("id" => $mail->getId(), "hf_id" => $mail_data['hf_id'])); flash_success(lang('success autosave draft')); ajx_current("empty"); } } catch (Exception $e) { DB::rollback(); flash_error($e->getMessage()); ajx_current("empty"); } // try } // if }
include "init.php"; Env::useHelper('format'); define('SCRIPT_MEMORY_LIMIT', 1024 * 1024 * 1024); // 1 GB @set_time_limit(0); ini_set('memory_limit', ((SCRIPT_MEMORY_LIMIT / (1024*1024))+50).'M'); DB::execute("CREATE TABLE IF NOT EXISTS `fixed_objects` ( `object_id` INTEGER UNSIGNED, PRIMARY KEY (`object_id`) ) ENGINE = InnoDB;"); $drop_tmp_table = true; $object_ids = Objects::instance()->findAll(array('id' => true, 'conditions' => 'id NOT IN (SELECT object_id FROM fixed_objects)')); $processed_objects = array(); $i = 0; $msg = ""; echo "\nObjects to process: " . count($object_ids) . "\n-----------------------------------------------------------------"; foreach ($object_ids as $object_id) { $object = Objects::findObject($object_id); if ($object instanceof ContentDataObject) { $object->addToSharingTable(); } $processed_objects[] = $object_id; $i++; $memory_limit_exceeded = memory_get_usage(true) > SCRIPT_MEMORY_LIMIT;
/** * Return manager instance * * @access protected * @param void * @return Objects */ function manager() { if(!($this->manager instanceof Objects)) $this->manager = Objects::instance(); return $this->manager; } // manager
private function processListActions() { $linkedObject = null; 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; foreach ($objects as $object) { $object->setDontMakeCalculations(true); } $real_deleted_ids = array(); list($succ, $err) = $this->do_delete_objects($objects, false, $real_deleted_ids); if ($err > 0) { flash_error(lang('error delete objects', $err)); } else { Hook::fire('after_object_delete_permanently', $real_deleted_ids, $ignored); flash_success(lang('success delete objects', $succ)); } } else { if (array_var($_GET, 'action') == 'delete_permanently') { $ids = explode(',', array_var($_GET, 'objects')); $objects = Objects::instance()->findAll(array("conditions" => "id IN (" . implode(",", $ids) . ")")); $real_deleted_ids = array(); list($succ, $err) = $this->do_delete_objects($objects, true, $real_deleted_ids); if ($err > 0) { flash_error(lang('error delete objects', $err)); } if ($succ > 0) { Hook::fire('after_object_delete_permanently', $real_deleted_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 = ContentDataObjects::listing(array("select_columns" => array('id'), "raw_data" => true, "trashed" => true)); $objects = $result->objects; foreach ($objects as $object) { $object->setDontMakeCalculations(true); } if (count($objects) > 0) { $obj_ids_str = implode(',', array_flat($objects)); $extra_conds = "AND o.id IN ({$obj_ids_str})"; $count = Trash::purge_trash(0, 1000, $extra_conds); flash_success(lang('success delete objects', $count)); } } 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); $obj->setDontMakeCalculations(true); 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); } } } } } } } } } } if (!array_var($_GET, 'only_result')) { $ignored = null; Hook::fire('after_multi_object_action', array('object_ids' => explode(',', array_var($_GET, 'objects')), 'action' => array_var($_GET, 'action')), $ignored); } }
function add_multilple_objects_to_sharing_table($ids_str, $user) { if (substr(php_uname(), 0, 7) == "Windows" || !can_save_permissions_in_background()) { $ids = explode(',', $ids_str); foreach ($ids as $id) { $object = Objects::instance()->findObject($id); if ($object instanceof ContentDataObject) { $object->addToSharingTable(); } } } else { $command = "nice -n19 " . PHP_PATH . " " . ROOT . "/application/helpers/add_object_to_sharing_table.php " . ROOT . " " . $user->getId() . " " . $user->getTwistedToken() . " " . $ids_str; exec("{$command} > /dev/null &"); //Test php command exec(PHP_PATH . " -r 'echo function_exists(\"foo\") ? \"yes\" : \"no\";' 2>&1", $output, $return_var); if ($return_var != 0) { Logger::log(print_r("Error executing php command", true)); Logger::log(print_r($output, true)); Logger::log(print_r("Error code: " . $return_var, true)); } //END Test php command } }
/** * * */ function list_dimension_members($member_id, $context_dimension_id, $object_type_id, $allowed_member_type_ids) { if ($member_id != 0) { $contact_pg_ids = ContactPermissionGroups::getPermissionGroupIdsByContactCSV(logged_user()->getId(), false); $member = members::findById($member_id); $dimension = Dimensions::getDimensionById($context_dimension_id); if ($object_type_id != null) { $dimension_object_type_contents = $dimension->getObjectTypeContent($object_type_id); foreach ($dimension_object_type_contents as $dotc) { $dot_id = $dotc->getDimensionObjectTypeId(); if (is_null($allowed_member_type_ids) || in_array($dot_id, $allowed_member_type_ids)) { $allowed_object_type_ids[] = $dot_id; } } } if ($dimension instanceof Dimension && $member instanceof Member) { if (!$dimension->getDefinesPermissions() || $dimension->hasAllowAllForContact($contact_pg_ids)) { $dimension_members = $dimension->getAllMembers(false, "parent_member_id, name", true); } else { if ($dimension->hasCheckForContact($contact_pg_ids)) { $member_list = $dimension->getAllMembers(false, "parent_member_id, name", true); $allowed_members = array(); foreach ($member_list as $dim_member) { if (ContactMemberPermissions::instance()->contactCanReadMemberAll($contact_pg_ids, $dim_member->getId(), logged_user())) { $allowed_members[] = $dim_member; } } $dimension_members = $allowed_members; } } $members_to_retrieve = array(); $association_ids = DimensionMemberAssociations::getAllAssociationIds($member->getDimensionId(), $context_dimension_id); if (count($association_ids) > 0) { $associated_members_ids_csv = ''; foreach ($association_ids as $id) { $association = DimensionMemberAssociations::findById($id); $children = $member->getAllChildrenInHierarchy(); if ($association->getDimensionId() == $context_dimension_id) { $new_csv = MemberPropertyMembers::getAllMemberIds($id, $member_id); $associated_members_ids_csv .= $new_csv != '' ? $new_csv . "," : ''; foreach ($children as $child) { $new_csv = MemberPropertyMembers::getAllMemberIds($id, $child->getId()); $associated_members_ids_csv .= $new_csv != '' ? $new_csv . "," : ''; } } else { $new_csv = MemberPropertyMembers::getAllPropertyMemberIds($id, $member_id) . ","; $associated_members_ids_csv .= $new_csv != '' ? $new_csv . "," : ''; foreach ($children as $child) { $new_csv = MemberPropertyMembers::getAllPropertyMemberIds($id, $child->getId()); $associated_members_ids_csv .= $new_csv != '' ? $new_csv . "," : ''; } } } $associated_members_ids = explode(',', $associated_members_ids_csv); $associated_members_ids = array_unique($associated_members_ids); } if (isset($associated_members_ids) && count($associated_members_ids) > 0) { foreach ($associated_members_ids as $id) { $associated_member = Members::findById($id); if (in_array($associated_member, $dimension_members)) { $context_hierarchy_members = $associated_member->getAllParentMembersInHierarchy(true); foreach ($context_hierarchy_members as $context_member) { if (!in_array($context_member, $members_to_retrieve) && in_array($context_member, $dimension_members)) { $members_to_retrieve[$context_member->getName()] = $context_member; } } } } // alphabetical order $members_to_retrieve = array_ksort($members_to_retrieve); } else { $members_to_retrieve[] = $dimension_members; } $membersset = array(); foreach ($members_to_retrieve as $m) { $membersset[$m->getId()] = true; } $members = array(); // Todo adapt this code to call "buildMemberList" - (performance and code improvement) foreach ($members_to_retrieve as $m) { if ($m->getArchivedById() > 0) { continue; } if ($object_type_id != null) { $selectable = in_array($m->getObjectTypeId(), $allowed_object_type_ids) ? true : false; } $tempParent = $m->getParentMemberId(); $x = $m; while ($x instanceof Member && !isset($membersset[$tempParent])) { $tempParent = $x->getParentMemberId(); $x = $x->getParentMember(); } if (!$x instanceof Member) { $tempParent = 0; } if ($dot = DimensionObjectTypes::instance()->findOne(array("conditions" => "\n\t\t\t\t\t\tdimension_id = " . $dimension->getId() . " AND\n\t\t\t\t\t\tobject_type_id = " . $m->getObjectTypeId()))) { $memberOptions = $dot->getOptions(true); } else { $memberOptions = ''; } /* @var $m Member */ $member = array("id" => $m->getId(), "name" => clean($m->getName()), "parent" => $tempParent, "realParent" => $m->getParentMemberId(), "object_id" => $m->getObjectId(), "options" => $memberOptions, "depth" => $m->getDepth(), "iconCls" => $m->getIconClass(), "selectable" => isset($selectable) ? $selectable : false, "dimension_id" => $m->getDimensionId(), "object_type_id" => $m->getObjectTypeId(), "allow_childs" => $m->allowChilds()); if ($oid = $m->getObjectId()) { if ($obj = Objects::instance()->findObject($m->getObjectId())) { $editUrl = $obj->getEditUrl(); } } // Member Actions if (can_manage_dimension_members(logged_user())) { if ($oid = $m->getObjectId()) { if ($obj = Objects::instance()->findObject($m->getObjectId())) { $editUrl = $obj->getEditUrl(); } } else { $editUrl = get_url('member', 'edit', array('id' => $m->getId())); } $member['actions'] = array(array('url' => $editUrl, 'text' => '', 'iconCls' => 'ico-edit')); } $members[] = $member; } return $members; } return null; } else { $members = $this->initial_list_dimension_members($context_dimension_id, $object_type_id, $allowed_member_type_ids); return $members; } }
private function get_allowed_columns($object_type) { $fields = array(); if (isset($object_type)) { $customProperties = CustomProperties::getAllCustomPropertiesByObjectType($object_type); $objectFields = array(); foreach ($customProperties as $cp) { if ($cp->getType() == 'table') { continue; } $fields[] = array('id' => $cp->getId(), 'name' => $cp->getName(), 'type' => $cp->getType(), 'values' => $cp->getValues(), 'multiple' => $cp->getIsMultipleValues()); } $ot = ObjectTypes::findById($object_type); eval('$managerInstance = ' . $ot->getHandlerClass() . "::instance();"); $objectColumns = $managerInstance->getColumns(); $objectFields = array(); $objectColumns = array_diff($objectColumns, $managerInstance->getSystemColumns()); foreach ($objectColumns as $column) { $objectFields[$column] = $managerInstance->getColumnType($column); } $common_columns = Objects::instance()->getColumns(false); $common_columns = array_diff_key($common_columns, array_flip($managerInstance->getSystemColumns())); $objectFields = array_merge($objectFields, $common_columns); foreach ($objectFields as $name => $type) { if ($type == DATA_TYPE_FLOAT || $type == DATA_TYPE_INTEGER) { $type = 'numeric'; } else { if ($type == DATA_TYPE_STRING) { $type = 'text'; } else { if ($type == DATA_TYPE_BOOLEAN) { $type = 'boolean'; } else { if ($type == DATA_TYPE_DATE || $type == DATA_TYPE_DATETIME) { $type = 'date'; } } } } $field_name = Localization::instance()->lang('field ' . $ot->getHandlerClass() . ' ' . $name); if (is_null($field_name)) { $field_name = lang('field Objects ' . $name); } $fields[] = array('id' => $name, 'name' => $field_name, 'type' => $type); } $externalFields = $managerInstance->getExternalColumns(); foreach ($externalFields as $extField) { $field_name = Localization::instance()->lang('field ' . $ot->getHandlerClass() . ' ' . $extField); if (is_null($field_name)) { $field_name = lang('field Objects ' . $extField); } $fields[] = array('id' => $extField, 'name' => $field_name, 'type' => 'external', 'multiple' => 0); } if (!array_var($_REQUEST, 'noaddcol')) { Hook::fire('custom_reports_additional_columns', null, $fields); } } usort($fields, array(&$this, 'compare_FieldName')); return $fields; }
private function get_allowed_columns($object_type) { $fields = array(); if (isset($object_type)) { $customProperties = CustomProperties::getAllCustomPropertiesByObjectType($object_type); $objectFields = array(); foreach ($customProperties as $cp) { if ($cp->getType() == 'table') { continue; } $fields[] = array('id' => $cp->getId(), 'name' => $cp->getName(), 'type' => $cp->getType(), 'values' => $cp->getValues(), 'multiple' => $cp->getIsMultipleValues()); } $ot = ObjectTypes::findById($object_type); eval('$managerInstance = ' . $ot->getHandlerClass() . "::instance();"); $objectColumns = $managerInstance->getColumns(); $objectFields = array(); $objectColumns = array_diff($objectColumns, $managerInstance->getSystemColumns()); foreach ($objectColumns as $column) { $objectFields[$column] = $managerInstance->getColumnType($column); } $common_columns = Objects::instance()->getColumns(false); $common_columns = array_diff_key($common_columns, array_flip($managerInstance->getSystemColumns())); $objectFields = array_merge($objectFields, $common_columns); foreach ($objectFields as $name => $type) { if ($type == DATA_TYPE_FLOAT || $type == DATA_TYPE_INTEGER) { $type = 'numeric'; } else { if ($type == DATA_TYPE_STRING) { $type = 'text'; } else { if ($type == DATA_TYPE_BOOLEAN) { $type = 'boolean'; } else { if ($type == DATA_TYPE_DATE || $type == DATA_TYPE_DATETIME) { $type = 'date'; } } } } $field_name = Localization::instance()->lang('field ' . $ot->getHandlerClass() . ' ' . $name); if (is_null($field_name)) { $field_name = lang('field Objects ' . $name); } $fields[] = array('id' => $name, 'name' => $field_name, 'type' => $type); } $externalFields = $managerInstance->getExternalColumns(); foreach ($externalFields as $extField) { $field_name = Localization::instance()->lang('field ' . $ot->getHandlerClass() . ' ' . $extField); if (is_null($field_name)) { $field_name = lang('field Objects ' . $extField); } $fields[] = array('id' => $extField, 'name' => $field_name, 'type' => 'external', 'multiple' => 0); } //if Object type is person $objType = ObjectTypes::findByName('contact'); if ($objType instanceof ObjectType) { if ($object_type == $objType->getId()) { $fields[] = array('id' => 'email_address', 'name' => lang('email address'), 'type' => 'text'); $fields[] = array('id' => 'phone_number', 'name' => lang('phone number'), 'type' => 'text'); $fields[] = array('id' => 'web_url', 'name' => lang('web pages'), 'type' => 'text'); $fields[] = array('id' => 'im_value', 'name' => lang('instant messengers'), 'type' => 'text'); $fields[] = array('id' => 'address', 'name' => lang('address'), 'type' => 'text'); } } } usort($fields, array(&$this, 'compare_FieldName')); return $fields; }
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"); } }
/** * This function sets the selected billing values for all timeslots which lack any type of billing values (value set to 0). * This function is used when users start to use billing in the system. * * @return unknown_type */ static function updateBillingValues() { $timeslots = Timeslots::findAll(array('conditions' => '`end_time` > 0 AND billing_id = 0 AND is_fixed_billing = 0', 'join' => array('table' => Objects::instance()->getTableName(true), 'jt_field' => 'id', 'e_field' => 'rel_object_id'))); $users = Contacts::getAllUsers(); $usArray = array(); foreach ($users as $u) { $usArray[$u->getId()] = $u; } $pbidCache = array(); $count = 0; $categories_cache = array(); foreach ($timeslots as $ts) { /* @var $ts Timeslot */ $user = $usArray[$ts->getContactId()]; if ($user instanceof Contact) { $billing_category_id = $user->getDefaultBillingId(); if ($billing_category_id > 0) { $hours = $ts->getMinutes() / 60; $billing_category = array_var($categories_cache, $billing_category_id); if (!$billing_category instanceof BillingCategory) { $billing_category = BillingCategories::findById($billing_category_id); $categories_cache[$billing_category_id] = $billing_category; } if ($billing_category instanceof BillingCategory) { $hourly_billing = $billing_category->getDefaultValue(); $ts->setBillingId($billing_category_id); $ts->setHourlyBilling($hourly_billing); $ts->setFixedBilling(round($hourly_billing * $hours, 2)); $ts->setIsFixedBilling(false); $ts->save(); $count++; } } } else { $ts->setIsFixedBilling(true); $ts->save(); } } return $count; }
/** * 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; }
private function get_allowed_columns($object_type) { $fields = array(); if (isset($object_type)) { $customProperties = CustomProperties::getAllCustomPropertiesByObjectType($object_type); $objectFields = array(); foreach ($customProperties as $cp) { if ($cp->getType() == 'table') { continue; } $fields[] = array('id' => $cp->getId(), 'name' => $cp->getName(), 'type' => $cp->getType(), 'values' => $cp->getValues(), 'multiple' => $cp->getIsMultipleValues()); } $ot = ObjectTypes::findById($object_type); if (class_exists($ot->getHandlerClass())) { eval('$managerInstance = ' . $ot->getHandlerClass() . "::instance();"); $objectColumns = $managerInstance->getColumns(); } else { $objectColumns = array(); } $objectFields = array(); if (class_exists($ot->getHandlerClass())) { $objectColumns = array_diff($objectColumns, $managerInstance->getSystemColumns()); foreach ($objectColumns as $column) { $objectFields[$column] = $managerInstance->getColumnType($column); } } $common_columns = Objects::instance()->getColumns(false); if (class_exists($ot->getHandlerClass())) { $common_columns = array_diff_key($common_columns, array_flip($managerInstance->getSystemColumns())); } $objectFields = array_merge($objectFields, $common_columns); foreach ($objectFields as $name => $type) { if ($type == DATA_TYPE_FLOAT || $type == DATA_TYPE_INTEGER) { $type = 'numeric'; } else { if ($type == DATA_TYPE_STRING) { $type = 'text'; } else { if ($type == DATA_TYPE_BOOLEAN) { $type = 'boolean'; } else { if ($type == DATA_TYPE_DATE || $type == DATA_TYPE_DATETIME) { $type = 'date'; } } } } $field_name = Localization::instance()->lang('field ' . $ot->getHandlerClass() . ' ' . $name); if (is_null($field_name)) { $field_name = lang('field Objects ' . $name); } $fields_array = array('id' => $name, 'name' => $field_name, 'type' => $type); $task_ot = ObjectTypes::findByName('task'); if ($task_ot instanceof ObjectType && $object_type == $task_ot->getId() && $name == 'priority') { $fields_array = array('id' => 'priority', 'name' => lang('priority'), 'type' => 'list', 'values' => '100,200,300,400'); } $fields[] = $fields_array; } if (class_exists($ot->getHandlerClass())) { $externalFields = $managerInstance->getExternalColumns(); foreach ($externalFields as $extField) { $field_name = Localization::instance()->lang('field ' . $ot->getHandlerClass() . ' ' . $extField); if (is_null($field_name)) { $field_name = lang('field Objects ' . $extField); } $fields[] = array('id' => $extField, 'name' => $field_name, 'type' => 'external', 'multiple' => 0); } } //if Object type is person $contact_ot = ObjectTypes::findByName('contact'); if ($contact_ot instanceof ObjectType && $object_type == $contact_ot->getId()) { $fields[] = array('id' => 'is_user', 'name' => lang('is_user'), 'type' => 'boolean'); $fields[] = array('id' => 'email_address', 'name' => lang('email address'), 'type' => 'text'); $fields[] = array('id' => 'mobile_phone', 'name' => lang('mobile phone'), 'type' => 'text'); $fields[] = array('id' => 'work_phone', 'name' => lang('work phone'), 'type' => 'text'); $fields[] = array('id' => 'home_phone', 'name' => lang('home phone'), 'type' => 'text'); $fields[] = array('id' => 'im_values', 'name' => lang('instant messaging'), 'type' => 'text'); $fields[] = array('id' => 'personal_webpage', 'name' => lang('personal_webpage'), 'type' => 'text'); $fields[] = array('id' => 'work_webpage', 'name' => lang('work_webpage'), 'type' => 'text'); $fields[] = array('id' => 'other_webpage', 'name' => lang('other_webpage'), 'type' => 'text'); $fields[] = array('id' => 'home_address', 'name' => lang('home_address'), 'type' => 'text'); $fields[] = array('id' => 'work_address', 'name' => lang('work_address'), 'type' => 'text'); $fields[] = array('id' => 'other_address', 'name' => lang('other_address'), 'type' => 'text'); } if (!array_var($_REQUEST, 'noaddcol')) { Hook::fire('custom_reports_additional_columns', array('object_type' => $ot), $fields); } } usort($fields, array(&$this, 'compare_FieldName')); return $fields; }