/**
  * 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;
 }
 /**
  * Prepares return object for a list of emails and messages
  *
  * @param array $totMsg
  * @param integer $start
  * @param integer $limit
  * @return array
  */
 private function prepareObject($totMsg, $start, $limit, $total)
 {
     $object = array("totalCount" => $total, "start" => $start, "messages" => array());
     $custom_properties = CustomProperties::getAllCustomPropertiesByObjectType(ProjectMessages::instance()->getObjectTypeId());
     $ids = array();
     for ($i = 0; $i < $limit; $i++) {
         if (isset($totMsg[$i])) {
             $msg = $totMsg[$i];
             if ($msg instanceof ProjectMessage) {
                 $text = $msg->getText();
                 if (strlen($text) > 100) {
                     $text = substr_utf($text, 0, 100) . "...";
                 }
                 $object["messages"][$i] = array("id" => $i, "ix" => $i, "object_id" => $msg->getId(), "ot_id" => $msg->getObjectTypeId(), "type" => $msg->getObjectTypeName(), "name" => $msg->getObjectName(), "text" => html_to_text($text), "date" => $msg->getUpdatedOn() instanceof DateTimeValue ? $msg->getUpdatedOn()->isToday() ? format_time($msg->getUpdatedOn()) : format_datetime($msg->getUpdatedOn()) : '', "is_today" => $msg->getUpdatedOn() instanceof DateTimeValue ? $msg->getUpdatedOn()->isToday() : 0, "userId" => $msg->getCreatedById(), "userName" => $msg->getCreatedByDisplayName(), "updaterId" => $msg->getUpdatedById() ? $msg->getUpdatedById() : $msg->getCreatedById(), "updaterName" => $msg->getUpdatedById() ? $msg->getUpdatedByDisplayName() : $msg->getCreatedByDisplayName(), "memPath" => json_encode($msg->getMembersIdsToDisplayPath()));
                 $ids[] = $msg->getId();
                 foreach ($custom_properties as $cp) {
                     $object["messages"][$i]['cp_' . $cp->getId()] = get_custom_property_value_for_listing($cp, $msg);
                 }
             }
         }
     }
     $read_objects = ReadObjects::getReadByObjectList($ids, logged_user()->getId());
     foreach ($object["messages"] as &$data) {
         $data['isRead'] = isset($read_objects[$data['object_id']]);
     }
     return $object;
 }
 function list_files()
 {
     ajx_current("empty");
     // get query parameters
     $start = (int) array_var($_GET, 'start');
     $limit = (int) array_var($_GET, 'limit');
     if (!$start) {
         $start = 0;
     }
     if (!$limit) {
         $limit = config_option('files_per_page');
     }
     $order = array_var($_GET, 'sort');
     $order_dir = array_var($_GET, 'dir');
     $page = (int) ($start / $limit) + 1;
     $hide_private = !logged_user()->isMemberOfOwnerCompany();
     $type = array_var($_GET, 'type');
     $user = array_var($_GET, 'user');
     // if there's an action to execute, do so
     if (array_var($_GET, 'action') == 'delete') {
         $ids = explode(',', array_var($_GET, 'objects'));
         $succ = 0;
         $err = 0;
         foreach ($ids as $id) {
             $file = ProjectFiles::findById($id);
             if (isset($file) && $file->canDelete(logged_user())) {
                 try {
                     DB::beginWork();
                     $file->trash();
                     DB::commit();
                     ApplicationLogs::createLog($file, ApplicationLogs::ACTION_TRASH);
                     $succ++;
                 } catch (Exception $e) {
                     DB::rollback();
                     $err++;
                 }
             } else {
                 if (!$file instanceof ProjectFile) {
                     evt_add("popup", array('title' => lang('error'), 'message' => lang("file dnx")));
                 } else {
                     if (!$file->canDelete(logged_user())) {
                         evt_add("popup", array('title' => lang('error'), 'message' => lang("cannot delete file", $file->getObjectName())));
                     }
                 }
                 $err++;
             }
         }
         if ($succ > 0) {
             flash_success(lang("success delete files", $succ));
         } else {
             flash_error(lang("error delete files", $err));
         }
     } else {
         if (array_var($_GET, 'action') == 'markasread') {
             $ids = explode(',', array_var($_GET, 'objects'));
             $succ = 0;
             $err = 0;
             foreach ($ids as $id) {
                 $file = ProjectFiles::findById($id);
                 try {
                     $file->setIsRead(logged_user()->getId(), true);
                     $succ++;
                 } catch (Exception $e) {
                     $err++;
                 }
                 // try
             }
             //for
             if ($succ <= 0) {
                 flash_error(lang("error markasread files", $err));
             }
         } else {
             if (array_var($_GET, 'action') == 'markasunread') {
                 $ids = explode(',', array_var($_GET, 'objects'));
                 $succ = 0;
                 $err = 0;
                 foreach ($ids as $id) {
                     $file = ProjectFiles::findById($id);
                     try {
                         $file->setIsRead(logged_user()->getId(), false);
                         $succ++;
                     } catch (Exception $e) {
                         $err++;
                     }
                     // try
                 }
                 //for
                 if ($succ <= 0) {
                     flash_error(lang("error markasunread files", $err));
                 }
             } else {
                 if (array_var($_GET, 'action') == 'zip_add') {
                     $this->zip_add();
                 } else {
                     if (array_var($_GET, 'action') == 'archive') {
                         $ids = explode(',', array_var($_GET, 'ids'));
                         $succ = 0;
                         $err = 0;
                         foreach ($ids as $id) {
                             $file = ProjectFiles::findById($id);
                             if (isset($file) && $file->canEdit(logged_user())) {
                                 try {
                                     DB::beginWork();
                                     $file->archive();
                                     DB::commit();
                                     ApplicationLogs::createLog($file, ApplicationLogs::ACTION_ARCHIVE);
                                     $succ++;
                                 } catch (Exception $e) {
                                     DB::rollback();
                                     $err++;
                                 }
                             } else {
                                 $err++;
                             }
                         }
                         if ($succ > 0) {
                             flash_success(lang("success archive objects", $succ));
                         } else {
                             flash_error(lang("error archive objects", $err));
                         }
                     }
                 }
             }
         }
     }
     Hook::fire('classify_action', null, $ret);
     $join_params = null;
     $select_columns = null;
     $extra_conditions = "";
     if (strpos($order, 'p_') == 1) {
         $cpId = substr($order, 3);
         $order = 'customProp';
     }
     if ($order == ProjectFiles::ORDER_BY_POSTTIME) {
         $order = '`created_on`';
     } else {
         if ($order == ProjectFiles::ORDER_BY_MODIFYTIME) {
             $order = '`updated_on`';
         } else {
             if ($order == ProjectFiles::ORDER_BY_SIZE) {
                 $order = '`jt`.`filesize`';
                 $join_params = array('table' => ProjectFileRevisions::instance()->getTableName(), 'jt_field' => 'file_id', 'e_field' => 'object_id');
                 $extra_conditions .= " AND `jt`.`object_id` = (SELECT max(`x`.`object_id`) FROM " . TABLE_PREFIX . "project_file_revisions `x` WHERE `x`.`file_id` = `e`.`object_id`)";
             } else {
                 if ($order == 'customProp') {
                     $order = 'IF(ISNULL(jt.value),1,0),jt.value';
                     $join_params['join_type'] = "LEFT ";
                     $join_params['table'] = "" . TABLE_PREFIX . "custom_property_values";
                     $join_params['jt_field'] = "object_id";
                     $join_params['e_field'] = "object_id";
                     $join_params['on_extra'] = "AND custom_property_id = " . $cpId;
                     $extra_conditions .= " AND ( custom_property_id = " . $cpId . " OR custom_property_id IS NULL)";
                     $select_columns = array("DISTINCT o.*", "e.*");
                 } else {
                     $order = '`name`';
                 }
             }
         }
     }
     // if
     $extra_conditions .= $hide_private ? 'AND `is_visible` = 1' : '';
     // filter attachments of other people if not filtering
     $tmp_mids = array();
     foreach (active_context() as $selection) {
         if ($selection instanceof Member) {
             $d = $selection->getDimension();
             if ($d instanceof Dimension && $d->getIsManageable()) {
                 $tmp_mids[] = $selection->getId();
             }
         }
     }
     if (count($tmp_mids) == 0) {
         if (Plugins::instance()->isActivePlugin('mail')) {
             $extra_conditions .= " AND IF(e.mail_id=0, true, EXISTS (SELECT mac.contact_id FROM " . TABLE_PREFIX . "mail_account_contacts mac \r\n\t\t\t\t\tWHERE mac.contact_id=o.created_by_id AND mac.account_id=(SELECT mc.account_id FROM " . TABLE_PREFIX . "mail_contents mc WHERE mc.object_id=e.mail_id)))";
         }
     }
     Hook::fire("listing_extra_conditions", null, $extra_conditions);
     $only_count_result = array_var($_GET, 'only_result', false);
     $context = active_context();
     $objects = ProjectFiles::instance()->listing(array("order" => $order, "order_dir" => $order_dir, "extra_conditions" => $extra_conditions, "show_only_member_objects" => user_config_option('show_only_member_files'), 'count_results' => false, 'only_count_results' => $only_count_result, "join_params" => $join_params, "start" => $start, "limit" => $limit, "select_columns" => $select_columns));
     $custom_properties = CustomProperties::getAllCustomPropertiesByObjectType(ProjectFiles::instance()->getObjectTypeId());
     // prepare response object
     $listing = array("totalCount" => $objects->total, "start" => $start, "objType" => ProjectFiles::instance()->getObjectTypeId(), "files" => array());
     if (is_array($objects->objects)) {
         $index = 0;
         $ids = array();
         foreach ($objects->objects as $o) {
             $coName = "";
             $coId = $o->getCheckedOutById();
             if ($coId != 0) {
                 if ($coId == logged_user()->getId()) {
                     $coName = "self";
                 } else {
                     $coUser = Contacts::findById($coId);
                     if ($coUser instanceof Contact) {
                         $coName = $coUser->getObjectName();
                     } else {
                         $coName = "";
                     }
                 }
             }
             if ($o->isMP3()) {
                 $songname = $o->getProperty("songname");
                 $artist = $o->getProperty("songartist");
                 $album = $o->getProperty("songalbum");
                 $track = $o->getProperty("songtrack");
                 $year = $o->getProperty("songyear");
                 $duration = $o->getProperty("songduration");
                 $songInfo = json_encode(array($songname, $artist, $album, $track, $year, $duration, $o->getDownloadUrl(), $o->getFilename(), $o->getId()));
             } else {
                 $songInfo = array();
             }
             $ids[] = $o->getId();
             $values = array("id" => $o->getId(), "ix" => $index++, "object_id" => $o->getId(), "ot_id" => $o->getObjectTypeId(), "name" => $o->getObjectName(), "type" => $o->getTypeString(), "mimeType" => $o->getTypeString(), "createdBy" => clean($o->getCreatedByDisplayName()), "createdById" => $o->getCreatedById(), "dateCreated" => $o->getCreatedOn() instanceof DateTimeValue ? $o->getCreatedOn()->isToday() ? format_time($o->getCreatedOn()) : format_datetime($o->getCreatedOn()) : '', "dateCreated_today" => $o->getCreatedOn() instanceof DateTimeValue ? $o->getCreatedOn()->isToday() : 0, "updatedBy" => clean($o->getUpdatedByDisplayName()), "updatedById" => $o->getUpdatedById(), "dateUpdated" => $o->getUpdatedOn() instanceof DateTimeValue ? $o->getUpdatedOn()->isToday() ? format_time($o->getUpdatedOn()) : format_datetime($o->getUpdatedOn()) : '', "dateUpdated_today" => $o->getUpdatedOn() instanceof DateTimeValue ? $o->getUpdatedOn()->isToday() : 0, "icon" => $o->getTypeIconUrl(), "size" => format_filesize($o->getFileSize()), "url" => $o->getOpenUrl(), "manager" => get_class($o->manager()), "checkedOutByName" => $coName, "checkedOutById" => $coId, "isModifiable" => $o->isModifiable() && $o->canEdit(logged_user()), "modifyUrl" => $o->getModifyUrl(), "songInfo" => $songInfo, "ftype" => $o->getType(), "url" => $o->getUrl(), "memPath" => json_encode($o->getMembersIdsToDisplayPath()), "genid" => gen_id());
             if ($o->isMP3()) {
                 $values['isMP3'] = true;
             }
             Hook::fire('add_classification_value', $o, $values);
             foreach ($custom_properties as $cp) {
                 $values['cp_' . $cp->getId()] = get_custom_property_value_for_listing($cp, $o);
             }
             $listing["files"][] = $values;
         }
         $read_objects = ReadObjects::getReadByObjectList($ids, logged_user()->getId());
         foreach ($listing["files"] as &$data) {
             $data['isRead'] = isset($read_objects[$data['object_id']]);
         }
         ajx_extra_data($listing);
         tpl_assign("listing", $listing);
     } else {
         throw new Error("Not array", $code);
     }
 }
 /**
  * Prepares return object for a list of emails and messages
  *
  * @param array $totMsg
  * @param integer $start
  * @param integer $limit
  * @return array
  */
 private function prepareObject($objects, $count, $start = 0, $attributes = null)
 {
     $object = array("totalCount" => $count, "start" => $start, "contacts" => array());
     $custom_properties = CustomProperties::getAllCustomPropertiesByObjectType(Contacts::instance()->getObjectTypeId());
     for ($i = 0; $i < count($objects); $i++) {
         if (isset($objects[$i])) {
             $c = $objects[$i];
             if ($c instanceof Contact && !$c->isCompany()) {
                 $company = $c->getCompany();
                 $companyName = '';
                 if (!is_null($company)) {
                     $companyName = $company->getObjectName();
                 }
                 $personal_emails = $c->getContactEmails('personal');
                 $w_address = $c->getAddress('work');
                 $h_address = $c->getAddress('home');
                 if (user_config_option("listingContactsBy")) {
                     $name = $c->getDisplayName();
                 } else {
                     $name = $c->getReverseDisplayName();
                 }
                 $object["contacts"][$i] = array("id" => $i, "ix" => $i, "object_id" => $c->getId(), "ot_id" => $c->getObjectTypeId(), "type" => $c->getUserType() > 0 ? 'user' : 'contact', "name" => $name, "picture" => $c->getPictureUrl(), "email" => $c->getEmailAddress('personal', true), "companyId" => $c->getCompanyId(), "companyName" => $companyName, "website" => $c->getWebpage('personal') ? cleanUrl($c->getWebpageUrl('personal'), false) : '', "jobTitle" => $c->getJobTitle(), "department" => $c->getDepartment(), "email2" => !is_null($personal_emails) && isset($personal_emails[0]) ? $personal_emails[0]->getEmailAddress() : '', "email3" => !is_null($personal_emails) && isset($personal_emails[1]) ? $personal_emails[1]->getEmailAddress() : '', "workWebsite" => $c->getWebpage('work') ? cleanUrl($c->getWebpageUrl('work'), false) : '', "workAddress" => $w_address ? $c->getFullAddress($w_address) : '', "workPhone1" => $c->getPhone('work', true) ? $c->getPhoneNumber('work', true) : '', "workPhone2" => $c->getPhone('work') ? $c->getPhoneNumber('work') : '', "homeWebsite" => $c->getWebpage('personal') ? cleanUrl($c->getWebpageUrl('personal'), false) : '', "homeAddress" => $h_address ? $c->getFullAddress($h_address) : '', "homePhone1" => $c->getPhone('home', true) ? $c->getPhoneNumber('home', true) : '', "homePhone2" => $c->getPhone('home') ? $c->getPhoneNumber('home') : '', "mobilePhone" => $c->getPhone('mobile') ? $c->getPhoneNumber('mobile') : '', "createdOn" => $c->getCreatedOn() instanceof DateTimeValue ? $c->getCreatedOn()->isToday() ? format_time($c->getCreatedOn()) : format_datetime($c->getCreatedOn()) : '', "createdOn_today" => $c->getCreatedOn() instanceof DateTimeValue ? $c->getCreatedOn()->isToday() : 0, "createdBy" => $c->getCreatedByDisplayName(), "createdById" => $c->getCreatedById(), "updatedOn" => $c->getUpdatedOn() instanceof DateTimeValue ? $c->getUpdatedOn()->isToday() ? format_time($c->getUpdatedOn()) : format_datetime($c->getUpdatedOn()) : '', "updatedOn_today" => $c->getUpdatedOn() instanceof DateTimeValue ? $c->getUpdatedOn()->isToday() : 0, "updatedBy" => $c->getUpdatedByDisplayName(), "updatedById" => $c->getUpdatedById(), "memPath" => json_encode($c->getMembersIdsToDisplayPath()), "userType" => $c->getUserType());
             } else {
                 if ($c instanceof Contact) {
                     $w_address = $c->getAddress('work');
                     $object["contacts"][$i] = array("id" => $i, "ix" => $i, "object_id" => $c->getId(), "ot_id" => $c->getObjectTypeId(), "type" => 'company', 'name' => $c->getObjectName(), 'email' => $c->getEmailAddress(), 'website' => $c->getWebpage('work') ? cleanUrl($c->getWebpageUrl('work'), false) : '', 'workPhone1' => $c->getPhone('work', true) ? $c->getPhoneNumber('work', true) : '', 'workPhone2' => $c->getPhone('fax', true) ? $c->getPhoneNumber('fax', true) : '', 'workAddress' => $w_address ? $c->getFullAddress($w_address) : '', "companyId" => $c->getId(), "companyName" => $c->getObjectName(), "jobTitle" => '', "department" => lang('company'), "email2" => '', "email3" => '', "workWebsite" => $c->getWebpage('work') ? cleanUrl($c->getWebpageUrl('work'), false) : '', "homeWebsite" => '', "homeAddress" => '', "homePhone1" => '', "homePhone2" => '', "mobilePhone" => '', "createdOn" => $c->getCreatedOn() instanceof DateTimeValue ? $c->getCreatedOn()->isToday() ? format_time($c->getCreatedOn()) : format_datetime($c->getCreatedOn()) : '', "createdOn_today" => $c->getCreatedOn() instanceof DateTimeValue ? $c->getCreatedOn()->isToday() : 0, "createdBy" => $c->getCreatedByDisplayName(), "createdById" => $c->getCreatedById(), "updatedOn" => $c->getUpdatedOn() instanceof DateTimeValue ? $c->getUpdatedOn()->isToday() ? format_time($c->getUpdatedOn()) : format_datetime($c->getUpdatedOn()) : '', "updatedOn_today" => $c->getUpdatedOn() instanceof DateTimeValue ? $c->getUpdatedOn()->isToday() : 0, "updatedBy" => $c->getUpdatedByDisplayName(), "updatedById" => $c->getUpdatedById(), "memPath" => json_encode($c->getMembersIdsToDisplayPath()), "contacts" => $c->getContactsByCompany(), "users" => $c->getUsersByCompany());
                 }
             }
             $columns = array();
             Hook::fire('object_definition', 'Contact', $columns);
             foreach ($columns as $col => $type) {
                 $object["contacts"][$i][$col] = $c->getColumnValue($col);
             }
             foreach ($custom_properties as $cp) {
                 $object["contacts"][$i]['cp_' . $cp->getId()] = get_custom_property_value_for_listing($cp, $c);
             }
         }
     }
     return $object;
 }
 /**
  * Prepares return object for a list of emails and messages
  *
  * @param array $totMsg
  * @param integer $start
  * @param integer $limit
  * @return array
  */
 private function prepareObject($emails, $start, $limit, $total, $attributes = null)
 {
     $object = array("totalCount" => intval($total), "start" => $start, "messages" => array());
     $custom_properties = CustomProperties::getAllCustomPropertiesByObjectType(MailContents::instance()->getObjectTypeId());
     $i = 0;
     foreach ($emails as $email) {
         if ($email instanceof MailContent) {
             $properties = $this->getMailProperties($email, $i);
             $object["messages"][$i] = $properties;
         }
         foreach ($custom_properties as $cp) {
             $object["messages"][$i]['cp_' . $cp->getId()] = get_custom_property_value_for_listing($cp, $email);
         }
         $i++;
     }
     //set columns to show for this folder
     if (isset($attributes)) {
         $string = user_config_option("folder_" . $attributes["stateType"] . "_columns");
         $columns = explode(",", $string);
         foreach ($columns as $col) {
             $object["folder_columns"][] = $col;
         }
         $object["folder_name"] = $attributes["stateType"];
         //if you want to add a column add their name here too
         $object["folder_columns_all"] = array("from", "to", "subject", "account", "date", "folder", "actions");
     }
     return $object;
 }
 function list_all()
 {
     ajx_current("empty");
     $context = active_context();
     $start = array_var($_GET, 'start', 0);
     $limit = array_var($_GET, 'limit', config_option('files_per_page'));
     $order = array_var($_GET, 'sort');
     if ($order == "updatedOn" || $order == "updated" || $order == "date" || $order == "dateUpdated") {
         $order = "updated_on";
     }
     $order_dir = array_var($_GET, 'dir');
     $page = (int) ($start / $limit) + 1;
     $hide_private = !logged_user()->isMemberOfOwnerCompany();
     if (array_var($_GET, 'action') == 'delete') {
         $ids = explode(',', array_var($_GET, 'webpages'));
         $succ = 0;
         $err = 0;
         foreach ($ids as $id) {
             $web_page = ProjectWebpages::findById($id);
             if (isset($web_page) && $web_page->canDelete(logged_user())) {
                 try {
                     DB::beginWork();
                     $web_page->trash();
                     DB::commit();
                     ApplicationLogs::createLog($web_page, ApplicationLogs::ACTION_TRASH);
                     $succ++;
                 } catch (Exception $e) {
                     DB::rollback();
                     $err++;
                 }
             } else {
                 $err++;
             }
         }
         if ($succ > 0) {
             flash_success(lang("success delete objects", $succ));
         }
         if ($err > 0) {
             flash_error(lang("error delete objects", $err));
         }
     } else {
         if (array_var($_GET, 'action') == 'markasread') {
             $ids = explode(',', array_var($_GET, 'ids'));
             $succ = 0;
             $err = 0;
             foreach ($ids as $id) {
                 $webpage = ProjectWebpages::findById($id);
                 try {
                     $webpage->setIsRead(logged_user()->getId(), true);
                     $succ++;
                 } catch (Exception $e) {
                     $err++;
                 }
             }
             if ($succ <= 0) {
                 flash_error(lang("error markasread files", $err));
             }
         } else {
             if (array_var($_GET, 'action') == 'markasunread') {
                 $ids = explode(',', array_var($_GET, 'ids'));
                 $succ = 0;
                 $err = 0;
                 foreach ($ids as $id) {
                     $webpage = ProjectWebpages::findById($id);
                     try {
                         $webpage->setIsRead(logged_user()->getId(), false);
                         $succ++;
                     } catch (Exception $e) {
                         $err++;
                     }
                 }
                 if ($succ <= 0) {
                     flash_error(lang("error markasunread files", $err));
                 }
             } else {
                 if (array_var($_GET, 'action') == 'archive') {
                     $ids = explode(',', array_var($_GET, 'webpages'));
                     $succ = 0;
                     $err = 0;
                     foreach ($ids as $id) {
                         $web_page = ProjectWebpages::findById($id);
                         if (isset($web_page) && $web_page->canEdit(logged_user())) {
                             try {
                                 DB::beginWork();
                                 $web_page->archive();
                                 DB::commit();
                                 ApplicationLogs::createLog($web_page, ApplicationLogs::ACTION_ARCHIVE);
                                 $succ++;
                             } catch (Exception $e) {
                                 DB::rollback();
                                 $err++;
                             }
                         } else {
                             $err++;
                         }
                     }
                     if ($succ > 0) {
                         flash_success(lang("success archive objects", $succ));
                     }
                     if ($err > 0) {
                         flash_error(lang("error archive objects", $err));
                     }
                 }
             }
         }
     }
     $extra_conditions = "";
     Hook::fire("listing_extra_conditions", null, $extra_conditions);
     $only_count_result = array_var($_GET, 'only_result', false);
     $res = ProjectWebpages::instance()->listing(array("start" => $start, "limit" => $limit, "order" => $order, "order_dir" => $order_dir, "extra_conditions" => $extra_conditions, 'count_results' => false, 'only_count_results' => $only_count_result));
     $object = array("totalCount" => $res->total, "start" => $start, "webpages" => array());
     $custom_properties = CustomProperties::getAllCustomPropertiesByObjectType(ProjectWebpages::instance()->getObjectTypeId());
     if (isset($res->objects)) {
         $index = 0;
         $ids = array();
         foreach ($res->objects as $w) {
             $ids[] = $w->getId();
             $object["webpages"][$index] = array("ix" => $index, "id" => $w->getId(), "object_id" => $w->getObjectId(), "ot_id" => $w->getObjectTypeId(), "name" => $w->getObjectName(), "description" => $w->getDescription(), "url" => $w->getUrl(), "updatedOn" => $w->getUpdatedOn() instanceof DateTimeValue ? $w->getUpdatedOn()->isToday() ? format_time($w->getUpdatedOn()) : format_datetime($w->getUpdatedOn()) : '', "updatedOn_today" => $w->getUpdatedOn() instanceof DateTimeValue ? $w->getUpdatedOn()->isToday() : 0, "updatedBy" => $w->getUpdatedByDisplayName(), "updatedById" => $w->getUpdatedById(), "memPath" => json_encode($w->getMembersIdsToDisplayPath()));
             foreach ($custom_properties as $cp) {
                 $object["webpages"][$index]['cp_' . $cp->getId()] = get_custom_property_value_for_listing($cp, $w);
             }
             $index++;
         }
         $read_objects = ReadObjects::getReadByObjectList($ids, logged_user()->getId());
         foreach ($object["webpages"] as &$data) {
             $data['isRead'] = isset($read_objects[$data['object_id']]);
         }
     }
     ajx_extra_data($object);
 }