/**
  * 
  * 
  */
 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);
 }
 /**
  * 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, 'Contacts')) {
         return parent::paginate($arguments, $items_per_page, $current_page);
     } else {
         return Contacts::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);
     $show_archived = false;
     if ($report instanceof Report) {
         $conditionsFields = ReportConditions::getAllReportConditionsForFields($id);
         $conditionsCp = ReportConditions::getAllReportConditionsForCustomProperties($id);
         $ot = ObjectTypes::findById($report->getReportObjectTypeId());
         $table = $ot->getTableName();
         if ($ot->getType() == 'dimension_object' || $ot->getType() == 'dimension_group') {
             $hook_parameters = array('report' => $report, 'params' => $params, 'order_by_col' => $order_by_col, 'order_by_asc' => $order_by_asc, 'offset' => $offset, 'limit' => $limit, 'to_print' => $to_print);
             $report_result = null;
             Hook::fire('replace_execute_report_function', $hook_parameters, $report_result);
             if ($report_result) {
                 return $report_result;
             }
         }
         eval('$managerInstance = ' . $ot->getHandlerClass() . "::instance();");
         eval('$item_class = ' . $ot->getHandlerClass() . '::instance()->getItemClass(); $object = new $item_class();');
         $order_by = '';
         if (is_object($params)) {
             $params = get_object_vars($params);
         }
         $report_columns = ReportColumns::getAllReportColumns($id);
         $allConditions = "";
         $contact_extra_columns = self::get_extra_contact_columns();
         if (count($conditionsFields) > 0) {
             foreach ($conditionsFields as $condField) {
                 if ($condField->getFieldName() == "archived_on") {
                     $show_archived = true;
                 }
                 $skip_condition = false;
                 $model = $ot->getHandlerClass();
                 $model_instance = new $model();
                 $col_type = $model_instance->getColumnType($condField->getFieldName());
                 $allConditions .= ' AND ';
                 $dateFormat = 'm/d/Y';
                 if (isset($params[$condField->getId()])) {
                     $value = $params[$condField->getId()];
                     if ($col_type == DATA_TYPE_DATE || $col_type == DATA_TYPE_DATETIME) {
                         $dateFormat = user_config_option('date_format');
                     }
                 } else {
                     $value = $condField->getValue();
                 }
                 if ($ot->getHandlerClass() == 'Contacts' && in_array($condField->getFieldName(), $contact_extra_columns)) {
                     $allConditions .= self::get_extra_contact_column_condition($condField->getFieldName(), $condField->getCondition(), $value);
                 } else {
                     if ($value == '' && $condField->getIsParametrizable()) {
                         $skip_condition = true;
                     }
                     if (!$skip_condition) {
                         $field_name = $condField->getFieldName();
                         if (in_array($condField->getFieldName(), Objects::getColumns())) {
                             $field_name = 'o`.`' . $condField->getFieldName();
                         }
                         if ($condField->getCondition() == 'like' || $condField->getCondition() == 'not like') {
                             $value = '%' . $value . '%';
                         }
                         if ($col_type == DATA_TYPE_DATE || $col_type == DATA_TYPE_DATETIME) {
                             if ($value == date_format_tip($dateFormat)) {
                                 $value = EMPTY_DATE;
                             } else {
                                 $dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value);
                                 $value = $dtValue->format('Y-m-d');
                             }
                         }
                         if ($condField->getCondition() != '%') {
                             if ($col_type == DATA_TYPE_INTEGER || $col_type == DATA_TYPE_FLOAT) {
                                 $allConditions .= '`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value);
                             } else {
                                 if ($condField->getCondition() == '=' || $condField->getCondition() == '<=' || $condField->getCondition() == '>=') {
                                     if ($col_type == DATA_TYPE_DATETIME || $col_type == DATA_TYPE_DATE) {
                                         $equal = 'datediff(' . DB::escape($value) . ', `' . $field_name . '`)=0';
                                     } else {
                                         $equal = '`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value);
                                     }
                                     switch ($condField->getCondition()) {
                                         case '=':
                                             $allConditions .= $equal;
                                             break;
                                         case '<=':
                                         case '>=':
                                             $allConditions .= '(`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value) . ' OR ' . $equal . ') ';
                                             break;
                                     }
                                 } else {
                                     $allConditions .= '`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value);
                                 }
                             }
                         } else {
                             $allConditions .= '`' . $field_name . '` like ' . DB::escape("%{$value}");
                         }
                     } else {
                         $allConditions .= ' true';
                     }
                 }
             }
         }
         if (count($conditionsCp) > 0) {
             $dateFormat = user_config_option('date_format');
             $date_format_tip = date_format_tip($dateFormat);
             foreach ($conditionsCp as $condCp) {
                 $cp = CustomProperties::getCustomProperty($condCp->getCustomPropertyId());
                 $skip_condition = false;
                 if (isset($params[$condCp->getId() . "_" . $cp->getName()])) {
                     $value = $params[$condCp->getId() . "_" . $cp->getName()];
                 } else {
                     $value = $condCp->getValue();
                 }
                 if ($value == '' && $condCp->getIsParametrizable()) {
                     $skip_condition = true;
                 }
                 if (!$skip_condition) {
                     $current_condition = ' AND ';
                     $current_condition .= 'o.id IN ( SELECT object_id as id FROM ' . TABLE_PREFIX . 'custom_property_values cpv WHERE ';
                     $current_condition .= ' cpv.custom_property_id = ' . $condCp->getCustomPropertyId();
                     $fieldType = $object->getColumnType($condCp->getFieldName());
                     if ($condCp->getCondition() == 'like' || $condCp->getCondition() == 'not like') {
                         $value = '%' . $value . '%';
                     }
                     if ($cp->getType() == 'date') {
                         if ($value == $date_format_tip) {
                             continue;
                         }
                         $dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value);
                         $value = $dtValue->format('Y-m-d H:i:s');
                     }
                     if ($condCp->getCondition() != '%') {
                         if ($cp->getType() == 'numeric') {
                             $current_condition .= ' AND cpv.value ' . $condCp->getCondition() . ' ' . DB::escape($value);
                         } else {
                             if ($cp->getType() == 'boolean') {
                                 $current_condition .= ' AND cpv.value ' . $condCp->getCondition() . ' ' . ($value ? '1' : '0');
                                 if (!$value) {
                                     $current_condition .= ') OR o.id NOT IN (SELECT object_id as id FROM ' . TABLE_PREFIX . 'custom_property_values cpv2 WHERE cpv2.object_id=o.id AND cpv2.value=1 AND cpv2.custom_property_id = ' . $condCp->getCustomPropertyId();
                                 }
                             } else {
                                 $current_condition .= ' AND cpv.value ' . $condCp->getCondition() . ' ' . DB::escape($value);
                             }
                         }
                     } else {
                         $current_condition .= ' AND cpv.value like ' . DB::escape("%{$value}");
                     }
                     $current_condition .= ')';
                     $allConditions .= $current_condition;
                 }
             }
         }
         $select_columns = array('*');
         $join_params = null;
         if ($order_by_col == '') {
             $order_by_col = $report->getOrderBy();
         }
         if ($ot->getHandlerClass() == 'Contacts' && in_array($order_by_col, $contact_extra_columns)) {
             $join_params = self::get_extra_contact_column_order_by($order_by_col, $order_by_col, $select_columns);
         }
         $original_order_by_col = $order_by_col;
         if (in_array($order_by_col, self::$external_columns)) {
             $order_by_col = 'name_order';
             $join_params = array('table' => Objects::instance()->getTableName(), 'jt_field' => 'id', 'e_field' => $original_order_by_col, 'join_type' => 'left');
             $select_columns = array();
             $tmp_cols = $managerInstance->getColumns();
             foreach ($tmp_cols as $col) {
                 $select_columns[] = "e.{$col}";
             }
             $tmp_cols = Objects::instance()->getColumns();
             foreach ($tmp_cols as $col) {
                 $select_columns[] = "o.{$col}";
             }
             $select_columns[] = 'jt.name as name_order';
         }
         if ($order_by_asc == null) {
             $order_by_asc = $report->getIsOrderByAsc();
         }
         if ($ot->getName() == 'task' && !SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) {
             $allConditions .= " AND assigned_to_contact_id = " . logged_user()->getId();
         }
         if ($managerInstance) {
             if ($order_by_col == "order") {
                 $order_by_col = "`{$order_by_col}`";
             }
             $listing_parameters = array("select_columns" => $select_columns, "order" => "{$order_by_col}", "order_dir" => $order_by_asc ? "ASC" : "DESC", "extra_conditions" => $allConditions, "count_results" => true, "join_params" => $join_params);
             if ($limit > 0) {
                 $listing_parameters["start"] = $offset;
                 $listing_parameters["limit"] = $limit;
             }
             if ($show_archived) {
                 $listing_parameters["archived"] = true;
             }
             $result = $managerInstance->listing($listing_parameters);
         } else {
             // TODO Performance Killer
             $result = ContentDataObjects::getContentObjects(active_context(), $ot, $order_by_col, $order_by_asc ? "ASC" : "DESC", $allConditions);
         }
         $objects = $result->objects;
         $totalResults = $result->total;
         $results['pagination'] = Reports::getReportPagination($id, $params, $original_order_by_col, $order_by_asc, $offset, $limit, $totalResults);
         $dimensions_cache = array();
         foreach ($report_columns as $column) {
             if ($column->getCustomPropertyId() == 0) {
                 $field = $column->getFieldName();
                 if (str_starts_with($field, 'dim_')) {
                     $dim_id = str_replace("dim_", "", $field);
                     $dimension = Dimensions::getDimensionById($dim_id);
                     $dimensions_cache[$dim_id] = $dimension;
                     $column_name = $dimension->getName();
                     $results['columns'][$field] = $column_name;
                     $results['db_columns'][$column_name] = $field;
                 } else {
                     if ($managerInstance->columnExists($field) || Objects::instance()->columnExists($field)) {
                         $column_name = Localization::instance()->lang('field ' . $ot->getHandlerClass() . ' ' . $field);
                         if (is_null($column_name)) {
                             $column_name = lang('field Objects ' . $field);
                         }
                         $results['columns'][$field] = $column_name;
                         $results['db_columns'][$column_name] = $field;
                     } else {
                         if ($ot->getHandlerClass() == 'Contacts') {
                             if (in_array($field, $contact_extra_columns)) {
                                 $results['columns'][$field] = lang($field);
                                 $results['db_columns'][lang($field)] = $field;
                             }
                         } else {
                             if ($ot->getHandlerClass() == 'Timeslots') {
                                 if (in_array($field, array('time', 'billing'))) {
                                     $results['columns'][$field] = lang('field Objects ' . $field);
                                     $results['db_columns'][lang('field Objects ' . $field)] = $field;
                                 }
                             } else {
                                 if ($ot->getHandlerClass() == 'MailContents') {
                                     if (in_array($field, array('to', 'cc', 'bcc', 'body_plain', 'body_html'))) {
                                         $results['columns'][$field] = lang('field Objects ' . $field);
                                         $results['db_columns'][lang('field Objects ' . $field)] = $field;
                                     }
                                 }
                             }
                         }
                     }
                 }
             } else {
                 $results['columns'][$column->getCustomPropertyId()] = $column->getCustomPropertyId();
             }
         }
         $report_rows = array();
         foreach ($objects as &$object) {
             /* @var $object Object */
             $obj_name = $object->getObjectName();
             $icon_class = $object->getIconClass();
             $row_values = array('object_type_id' => $object->getObjectTypeId());
             if (!$to_print) {
                 $row_values['link'] = '<a class="link-ico ' . $icon_class . '" title="' . clean($obj_name) . '" target="new" href="' . $object->getViewUrl() . '">&nbsp;</a>';
             }
             foreach ($report_columns as $column) {
                 if ($column->getCustomPropertyId() == 0) {
                     $field = $column->getFieldName();
                     if (str_starts_with($field, 'dim_')) {
                         $dim_id = str_replace("dim_", "", $field);
                         if (!array_var($dimensions_cache, $dim_id) instanceof Dimension) {
                             $dimension = Dimensions::getDimensionById($dim_id);
                             $dimensions_cache[$dim_id] = $dimension;
                         } else {
                             $dimension = array_var($dimensions_cache, $dim_id);
                         }
                         $om_object_id = $object instanceof Timeslot ? $object->getRelObjectId() : $object->getId();
                         $members = ObjectMembers::getMembersByObjectAndDimension($om_object_id, $dim_id, " AND om.is_optimization=0");
                         $value = "";
                         foreach ($members as $member) {
                             /* @var $member Member */
                             $val = $member->getPath();
                             $val .= ($val == "" ? "" : "/") . $member->getName();
                             if ($value != "") {
                                 $val = " - {$val}";
                             }
                             $value .= $val;
                         }
                         $row_values[$field] = $value;
                     } else {
                         if ($object instanceof Timeslot) {
                             if ($field == 'id') {
                                 $value = $object->getObjectId();
                             } else {
                                 $value = $object->getColumnValue($field);
                                 // if it is a task column
                                 if (in_array($field, ProjectTasks::instance()->getColumns())) {
                                     $task = ProjectTasks::findById($object->getRelObjectId());
                                     // if task exists
                                     if ($task instanceof ProjectTask) {
                                         $value = $task->getColumnValue($field);
                                         // if it is an external task column
                                         if (in_array($field, ProjectTasks::instance()->getExternalColumns())) {
                                             $value = self::instance()->getExternalColumnValue($field, $value, ProjectTasks::instance());
                                         } else {
                                             // if is a date then use format
                                             if (ProjectTasks::instance()->getColumnType($field) == DATA_TYPE_DATETIME && $value instanceof DateTimeValue) {
                                                 $value = format_value_to_print($field, $value->toMySQL(), DATA_TYPE_DATETIME, $report->getReportObjectTypeId());
                                             }
                                         }
                                     }
                                     $results['columns'][$field] = lang('field ProjectTasks ' . $field);
                                     $results['db_columns'][lang('field ProjectTasks ' . $field)] = $field;
                                 }
                             }
                         } else {
                             $value = $object->getColumnValue($field);
                         }
                         if ($value instanceof DateTimeValue) {
                             $dateFormat = user_config_option('date_format');
                             Hook::fire("custom_property_date_format", null, $dateFormat);
                             $tz = logged_user()->getTimezone();
                             if ($object instanceof ProjectTask) {
                                 if ($field == 'due_date' && !$object->getUseDueTime() || $field == 'start_date' && !$object->getUseStartTime()) {
                                     $dateFormat = user_config_option('date_format');
                                     $tz = 0;
                                 }
                             }
                             $value = format_date($value, $dateFormat, $tz * 3600);
                         }
                         if (in_array($field, $managerInstance->getExternalColumns())) {
                             if ($object instanceof Timeslot && $field == 'time') {
                                 $lastStop = $object->getEndTime() != null ? $object->getEndTime() : ($object->isPaused() ? $object->getPausedOn() : DateTimeValueLib::now());
                                 $seconds = $lastStop->getTimestamp() - $object->getStartTime()->getTimestamp();
                                 $hours = number_format($seconds / 3600, 2, ',', '.');
                                 $value = $hours;
                                 //$value = DateTimeValue::FormatTimeDiff($object->getStartTime(), $lastStop, "hm", 60, $object->getSubtract());
                             } else {
                                 if ($object instanceof Timeslot && $field == 'billing') {
                                     $value = config_option('currency_code', '$') . ' ' . $object->getFixedBilling();
                                 } else {
                                     $value = self::instance()->getExternalColumnValue($field, $value, $managerInstance);
                                 }
                             }
                         } else {
                             if ($field != 'link') {
                                 //$value = html_to_text(html_entity_decode($value));
                                 if ($object->getColumnType($field) == DATA_TYPE_STRING) {
                                     // change html block end tags and brs to \n, then remove all other html tags, then replace \n with <br>, to remove all styles and keep the enters
                                     $value = str_replace(array("</div>", "</p>", "<br>", "<br />", "<br/>"), "\n", $value);
                                     $value = nl2br(strip_tags($value));
                                 }
                             }
                         }
                         if (self::isReportColumnEmail($value)) {
                             if (logged_user()->hasMailAccounts()) {
                                 $value = '<a class="internalLink" href="' . get_url('mail', 'add_mail', array('to' => clean($value))) . '">' . clean($value) . '</a></div>';
                             } else {
                                 $value = '<a class="internalLink" target="_self" href="mailto:' . clean($value) . '">' . clean($value) . '</a></div>';
                             }
                         }
                         $row_values[$field] = $value;
                         if ($ot->getHandlerClass() == 'Contacts') {
                             if ($managerInstance instanceof Contacts) {
                                 $contact = Contacts::findOne(array("conditions" => "object_id = " . $object->getId()));
                                 if ($field == "email_address") {
                                     $row_values[$field] = $contact->getEmailAddress();
                                 }
                                 if ($field == "is_user") {
                                     $row_values[$field] = $contact->getUserType() > 0 && !$contact->getIsCompany();
                                 }
                                 if ($field == "im_values") {
                                     $str = "";
                                     foreach ($contact->getAllImValues() as $type => $value) {
                                         $str .= ($str == "" ? "" : " | ") . "{$type}: {$value}";
                                     }
                                     $row_values[$field] = $str;
                                 }
                                 if (in_array($field, array("mobile_phone", "work_phone", "home_phone"))) {
                                     if ($field == "mobile_phone") {
                                         $row_values[$field] = $contact->getPhoneNumber('mobile', null, false);
                                     } else {
                                         if ($field == "work_phone") {
                                             $row_values[$field] = $contact->getPhoneNumber('work', null, false);
                                         } else {
                                             if ($field == "home_phone") {
                                                 $row_values[$field] = $contact->getPhoneNumber('home', null, false);
                                             }
                                         }
                                     }
                                 }
                                 if (in_array($field, array("personal_webpage", "work_webpage", "other_webpage"))) {
                                     if ($field == "personal_webpage") {
                                         $row_values[$field] = $contact->getWebpageUrl('personal');
                                     } else {
                                         if ($field == "work_webpage") {
                                             $row_values[$field] = $contact->getWebpageUrl('work');
                                         } else {
                                             if ($field == "other_webpage") {
                                                 $row_values[$field] = $contact->getWebpageUrl('other');
                                             }
                                         }
                                     }
                                 }
                                 if (in_array($field, array("home_address", "work_address", "other_address"))) {
                                     if ($field == "home_address") {
                                         $row_values[$field] = $contact->getStringAddress('home');
                                     } else {
                                         if ($field == "work_address") {
                                             $row_values[$field] = $contact->getStringAddress('work');
                                         } else {
                                             if ($field == "other_address") {
                                                 $row_values[$field] = $contact->getStringAddress('other');
                                             }
                                         }
                                     }
                                 }
                             }
                         } else {
                             if ($ot->getHandlerClass() == 'MailContents') {
                                 if (in_array($field, array('to', 'cc', 'bcc', 'body_plain', 'body_html'))) {
                                     $mail_data = MailDatas::findById($object->getId());
                                     $row_values[$field] = $mail_data->getColumnValue($field);
                                     if ($field == "body_html") {
                                         if (class_exists("DOMDocument")) {
                                             $d = new DOMDocument();
                                             $mock = new DOMDocument();
                                             $d->loadHTML(remove_css_and_scripts($row_values[$field]));
                                             $body = $d->getElementsByTagName('body')->item(0);
                                             foreach ($body->childNodes as $child) {
                                                 $mock->appendChild($mock->importNode($child, true));
                                             }
                                             // if css is inside an html comment => remove it
                                             $row_values[$field] = preg_replace('/<!--(.*)-->/Uis', '', remove_css($row_values[$field]));
                                         } else {
                                             $row_values[$field] = preg_replace('/<!--(.*)-->/Uis', '', remove_css_and_scripts($row_values[$field]));
                                         }
                                     }
                                 }
                             }
                         }
                         if (!$to_print && $field == "name") {
                             $row_values[$field] = '<a target="new-' . $object->getId() . '" href="' . $object->getViewUrl() . '">' . $value . '</a>';
                         }
                     }
                 } else {
                     $colCp = $column->getCustomPropertyId();
                     $cp = CustomProperties::getCustomProperty($colCp);
                     if ($cp instanceof CustomProperty) {
                         /* @var $cp CustomProperty */
                         $row_values[$cp->getName()] = get_custom_property_value_for_listing($cp, $object);
                         $results['columns'][$colCp] = $cp->getName();
                         $results['db_columns'][$cp->getName()] = $colCp;
                     }
                 }
             }
             Hook::fire("report_row", $object, $row_values);
             $report_rows[] = $row_values;
         }
         if (!$to_print) {
             if (is_array($results['columns'])) {
                 array_unshift($results['columns'], '');
             } else {
                 $results['columns'] = array('');
             }
             Hook::fire("report_header", $ot, $results['columns']);
         }
         $results['rows'] = $report_rows;
     }
     return $results;
 }
 /**
  * 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, 'ProjectMilestones')) {
         return parent::paginate($arguments, $items_per_page, $current_page);
     } else {
         return ProjectMilestones::instance()->paginate($arguments, $items_per_page, $current_page);
         //$instance =& ProjectMilestones::instance();
         //return $instance->paginate($arguments, $items_per_page, $current_page);
     }
     // if
 }
 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 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, $count = null) {		
		if(isset($this) && instance_of($this, 'MailContents')) {
			return parent::paginate($arguments, $items_per_page, $current_page, $count);
		} else {
			return MailContents::instance()->paginate($arguments, $items_per_page, $current_page, $count);
		} // if
	} // paginate
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` (\r\n  `object_id` INTEGER UNSIGNED,\r\n  PRIMARY KEY (`object_id`)\r\n) ENGINE = InnoDB;");
$drop_tmp_table = true;
//$object_ids = Objects::instance()->findAll(array('columns' => array('id','object_type_id'), 'conditions' => 'id NOT IN (SELECT object_id FROM fixed_objects)'));
$objects = DB::executeAll("\r\n\t\tSELECT id, object_type_id, member_id \r\n\t\tFROM " . TABLE_PREFIX . "objects o\r\n\t\t\tLEFT JOIN " . TABLE_PREFIX . "object_members om ON o.id = om.object_id\r\n\t\tWHERE id NOT IN (SELECT object_id FROM fixed_objects)\r\n\t\tGROUP BY o.id\r\n\t\t\r\n\t\t");
$processed_objects = array();
$i = 0;
$msg = "";
echo "\nObjects to process: " . count($objects) . "\n-----------------------------------------------------------------";
foreach ($objects as $key => $object) {
    ContentDataObjects::addObjToSharingTable($object['id'], $object['object_type_id'], !is_null($object['member_id']));
    $processed_objects[] = $object['id'];
    $i++;
    $memory_limit_exceeded = memory_get_usage(true) > SCRIPT_MEMORY_LIMIT;
    if ($i % 100 == 0 || $memory_limit_exceeded) {
        echo "\n{$i} objects processed. Mem usage: " . format_filesize(memory_get_usage(true));
        if (count($processed_objects) > 0) {
            DB::execute("INSERT INTO fixed_objects (object_id) VALUES (" . implode('),(', $processed_objects) . ");");
            $processed_objects = array();
        }
        ob_flush();
        if ($memory_limit_exceeded) {
            $msg = "Memory limit exceeded: " . format_filesize(memory_get_usage(true));
            $drop_tmp_table = false;
            break;
        }
示例#8
0
	/**
	 * Execute a report and return results
	 *
	 * @param $id
	 * @param $params
	 *
	 * @return array
	 */
	static function executeReport($id, $params, $order_by_col = '', $order_by_asc = true, $offset=0, $limit=50, $to_print = false) {
		if (is_null(active_context())) {
			CompanyWebsite::instance()->setContext(build_context_array(array_var($_REQUEST, 'context')));
		}
		$results = array();
		$report = self::getReport($id);
		if($report instanceof Report){
			$conditionsFields = ReportConditions::getAllReportConditionsForFields($id);
			$conditionsCp = ReportConditions::getAllReportConditionsForCustomProperties($id);
			
			$ot = ObjectTypes::findById($report->getReportObjectTypeId());
			$table = $ot->getTableName();
			
			eval('$managerInstance = ' . $ot->getHandlerClass() . "::instance();");
			eval('$item_class = ' . $ot->getHandlerClass() . '::instance()->getItemClass(); $object = new $item_class();');
			
			$order_by = '';
			if (is_object($params)) {
				$params = get_object_vars($params);				
			}
			
			$report_columns = ReportColumns::getAllReportColumns($id);

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

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

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

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

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

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

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

		return $results;
	} //  executeReport
 /**
  * Delete rows that match specific conditions. If $conditions is NULL all rows from table will be deleted
  *
  * @access public
  * @param string $conditions Query conditions
  * @return boolean
  */
 function delete($condition = null)
 {
     if (isset($this) && instance_of($this, 'Workspaces')) {
         return parent::delete($condition);
     } else {
         return Workspaces::instance()->delete($condition);
     }
     // if
 }
 function general_search()
 {
     // Init vars
     $search_dimension = array_var($_GET, 'search_dimension');
     $filteredResults = 0;
     $uid = logged_user()->getId();
     if (!isset($search_dimension)) {
         $members = active_context_members(false);
     } else {
         if ($search_dimension == 0) {
             $members = array();
         } else {
             $members = array($search_dimension);
         }
     }
     // click on search everywhere
     if (array_var($_REQUEST, 'search_all_projects')) {
         $members = array();
     }
     $revisionObjectTypeId = ObjectTypes::findByName("file revision")->getId();
     $members_sql = "";
     if (count($members) > 0) {
         $context_condition = "(EXISTS\r\n\t\t\t\t\t\t\t\t\t\t(SELECT om.object_id\r\n\t\t\t\t\t\t\t\t\t\t\tFROM  " . TABLE_PREFIX . "object_members om\r\n\t\t\t\t\t\t\t\t\t\t\tWHERE\tom.member_id IN (" . implode(',', $members) . ") AND so.rel_object_id = om.object_id\r\n\t\t\t\t\t\t\t\t\t\t\tGROUP BY object_id\r\n\t\t\t\t\t\t\t\t\t\t\tHAVING count(member_id) = " . count($members) . "\r\n\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t)";
         $context_condition_rev = "(EXISTS\r\n\t\t\t\t\t\t\t\t\t\t(SELECT fr.object_id FROM " . TABLE_PREFIX . "object_members om\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "project_file_revisions fr ON om.object_id=fr.file_id\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "objects ob ON fr.object_id=ob.id\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE fr.file_id = so.rel_object_id AND ob.object_type_id = {$revisionObjectTypeId} AND member_id IN (" . implode(',', $members) . ")\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tGROUP BY object_id\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tHAVING count(member_id) = " . count($members) . "\r\n\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t)";
         $members_sql = "AND ( " . $context_condition . " OR  " . $context_condition_rev . ")";
         $this->search_dimension = implode(',', $members);
     } else {
         $this->search_dimension = 0;
     }
     $listableObjectTypeIds = implode(",", ObjectTypes::getListableObjectTypeIds());
     $can_see_all_tasks_cond = "";
     if (!SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) {
         $can_see_all_tasks_cond = " AND IF((SELECT ot.name FROM " . TABLE_PREFIX . "object_types ot WHERE ot.id=o.object_type_id)='task',\r\n\t\t\t (SELECT t.assigned_to_contact_id FROM " . TABLE_PREFIX . "project_tasks t WHERE t.object_id=o.id) = " . logged_user()->getId() . ",\r\n\t\t\t true)";
     }
     $search_string = trim(array_var($_REQUEST, 'query', ''));
     $search_string = mysql_real_escape_string($search_string, DB::connection()->getLink());
     $start = array_var($_REQUEST, 'start', 0);
     $orig_limit = array_var($_REQUEST, 'limit');
     $limit = $orig_limit + 1;
     $useLike = false;
     if (user_config_option("search_engine") == 'like') {
         $useLike = true;
     }
     if (strlen($search_string) < 4) {
         $useLike = true;
     }
     if (strlen($search_string) > 0) {
         $this->search_for = $search_string;
         $logged_user_pgs = implode(',', logged_user()->getPermissionGroupIds());
         $sql = "\r\n\t\t\tSELECT DISTINCT so.rel_object_id AS id, so.content AS text_match, so.column_name AS field_match\r\n\t\t\tFROM " . TABLE_PREFIX . "searchable_objects so\r\n\t\t\tWHERE " . ($useLike ? " so.content LIKE '%{$search_string}%' " : " MATCH (so.content) AGAINST ('\"{$search_string}\"' IN BOOLEAN MODE) ") . "\r\n\t\t\tAND (EXISTS\r\n\t\t\t\t(SELECT o.id\r\n\t\t\t\t FROM  " . TABLE_PREFIX . "objects o\r\n\t\t\t\t\t\t\t WHERE\to.id = so.rel_object_id AND (\r\n\t\t\t\t\t\t\t (o.object_type_id = {$revisionObjectTypeId} AND\r\n\t\t\t\t\t\t\t EXISTS (\r\n\t\t\t\t\t\t\t SELECT group_id FROM " . TABLE_PREFIX . "sharing_table WHERE object_id  = ( SELECT file_id FROM " . TABLE_PREFIX . "project_file_revisions WHERE object_id = o.id )\r\n\t\t\t\t\t\t\t\t\tAND group_id IN ({$logged_user_pgs})\r\n\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tOR (\r\n\t\t\t\t\t\t\t\t\t\t\t\t(EXISTS\r\n\t\t\t\t\t\t\t\t\t\t\t\t(SELECT object_id\r\n\t\t\t\t\t\t\t\t\t\t\t\tFROM  " . TABLE_PREFIX . "sharing_table sh\r\n\t\t\t\t\t\t\t\t\t\tWHERE o.id = sh.object_id\r\n\t\t\t\t\t\t\t\t\t\tAND sh.group_id  IN (\r\n\t\t\t\t\t\t\t\t\t\t\t{$logged_user_pgs}\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t) AND o.object_type_id IN ({$listableObjectTypeIds}) " . $members_sql . $can_see_all_tasks_cond . "\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\tGROUP BY(id)\t\r\n\t\t\t\t\t\tORDER BY(id) DESC\t\t\t\t\t\t\t\r\n\t\t\t\t\t\tLIMIT {$start}, {$limit}";
         $rows = DB::executeAll($sql);
         if (!is_array($rows)) {
             $rows = array();
         }
         // show more
         $show_more = false;
         if (count($rows) > $orig_limit) {
             array_pop($rows);
             $show_more = true;
         }
         if ($show_more) {
             ajx_extra_data(array('show_more' => $show_more));
         }
         $search_results = array();
         $object_ids = array();
         foreach ($rows as $ob_data) {
             // basic data
             $data = array('id' => $ob_data['id'], 'text_match' => $this->highlightOneResult($ob_data['text_match']), 'field_match' => $ob_data['field_match']);
             $object_ids[] = $ob_data['id'];
             $search_results[] = $data;
         }
         if (count($object_ids) > 0) {
             $result = ContentDataObjects::listing(array("extra_conditions" => " AND o.id IN (" . implode(",", $object_ids) . ") ", "include_deleted" => true));
             $objects = $result->objects;
             foreach ($objects as $object) {
                 foreach ($search_results as $key => $search_result) {
                     if ($search_result['id'] == $object->getId()) {
                         $search_results[$key]['name'] = $object->getObjectName();
                         $class = 'ico-' . $object->getObjectTypeName();
                         $search_results[$key]['iconCls'] = $class;
                         $search_results[$key]['url'] = $object->getViewUrl();
                         continue;
                     }
                 }
             }
         }
         $row = "search-result-row-medium";
         ajx_extra_data(array('row_class' => $row));
         ajx_extra_data(array('search_results' => $search_results));
     }
     ajx_current("empty");
 }
 /**
  * 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, 'ProjectFileRevisions')) {
         return parent::paginate($arguments, $items_per_page, $current_page);
     } else {
         return ProjectFileRevisions::instance()->paginate($arguments, $items_per_page, $current_page);
     }
     // if
 }
 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 addToSharingTable()
 {
     $oid = $this->getId();
     $tid = $this->getObjectTypeId();
     $obj_mem_ids = $this->getMemberIds();
     ContentDataObjects::addObjToSharingTable($oid, $tid, count($obj_mem_ids));
 }