/** * Shortcut function for retrieving single lang value * * @access public * @param string $name * @return string */ function lang($name) { // Get function arguments and remove first one. $args = func_get_args(); if (is_array($args)) { array_shift($args); } // if // Get value and if we have NULL done! if (plugin_active('i18n')) { $value = lang_from_db($name); } else { $value = Localization::instance()->lang($name); } if (is_null($value)) { return $value; } // if // We have args? Replace all %s with arguments if (is_array($args) && count($args)) { foreach ($args as $arg) { $value = str_replace_first('%s', $arg, $value); } // foreach } // if // Done here... return $value; }
function langA($name, $args) { static $base = null; $value = Localization::instance()->lang($name); if (is_null($value)) { if (!Env::isDebugging()) { if (!$base instanceof Localization) { $base = new Localization(); $base->loadSettings("en_us", ROOT . "/language"); } $value = $base->lang($name); } if (is_null($value)) { $value = Localization::instance()->lang(str_replace(" ", "_", $name)); if (is_null($value)) { $value = Localization::instance()->lang(str_replace("_", " ", $name)); if (is_null($value)) { return "Missing lang: {$name}"; } } } } // We have args? Replace all {x} with arguments if (is_array($args) && count($args)) { $i = 0; foreach ($args as $arg) { $value = str_replace('{' . $i . '}', $arg, $value); $i++; } // foreach } // if // Done here... return $value; }
public static function getInstance() { if (!isset(self::$instance)) { $class = __CLASS__; self::$instance = new $class(); } return self::$instance; }
function load_help($template){ $dir = Localization::instance()->getLanguageDirPath().'/'.Localization::instance()->getLocale(); $help_file = $dir.'/help/'.$template.'.html'; if(is_file($help_file)){ return tpl_fetch($help_file); }else{ $default = Localization::instance()->getLanguageDirPath().'/en_us/help/'.$template.'.html'; if(is_file($default)){ return tpl_fetch($default); }else{ $noHelp = Localization::instance()->getLanguageDirPath().'/en_us/help/no_help.html'; if(is_file($noHelp)){ return tpl_fetch($noHelp); }else{ return ''; } } } }
function create_user($user_data, $permissionsString) { $user = new User(); $user->setUsername(array_var($user_data, 'username')); $user->setDisplayName(array_var($user_data, 'display_name')); $user->setEmail(array_var($user_data, 'email')); $user->setCompanyId(array_var($user_data, 'company_id')); $user->setType(array_var($user_data, 'type')); $user->setTimezone(array_var($user_data, 'timezone')); if (!logged_user() instanceof User || can_manage_security(logged_user())) { $user->setCanEditCompanyData(array_var($user_data, 'can_edit_company_data')); $user->setCanManageSecurity(array_var($user_data, 'can_manage_security')); $user->setCanManageWorkspaces(array_var($user_data, 'can_manage_workspaces')); $user->setCanManageConfiguration(array_var($user_data, 'can_manage_configuration')); $user->setCanManageContacts(array_var($user_data, 'can_manage_contacts')); $user->setCanManageTemplates(array_var($user_data, 'can_manage_templates')); $user->setCanManageReports(array_var($user_data, 'can_manage_reports')); $user->setCanManageTime(array_var($user_data, 'can_manage_time')); $user->setCanAddMailAccounts(array_var($user_data, 'can_add_mail_accounts')); $other_permissions = array(); Hook::fire('add_user_permissions', $user, $other_permissions); foreach ($other_permissions as $k => $v) { $user->setColumnValue($k, array_var($user_data, $k)); } } if (array_var($user_data, 'password_generator', 'random') == 'random') { // Generate random password $password = UserPasswords::generateRandomPassword(); } else { // Validate input $password = array_var($user_data, 'password'); if (trim($password) == '') { throw new Error(lang('password value required')); } // if if ($password != array_var($user_data, 'password_a')) { throw new Error(lang('passwords dont match')); } // if } // if $user->setPassword($password); $user->save(); $user_password = new UserPassword(); $user_password->setUserId($user->getId()); $user_password->setPasswordDate(DateTimeValueLib::now()); $user_password->setPassword(cp_encrypt($password, $user_password->getPasswordDate()->getTimestamp())); $user_password->password_temp = $password; $user_password->save(); if (array_var($user_data, 'autodetect_time_zone', 1) == 1) { set_user_config_option('autodetect_time_zone', 1, $user->getId()); } if ($user->getType() == 'admin') { if ($user->getCompanyId() != owner_company()->getId() || logged_user() instanceof User && !can_manage_security(logged_user())) { // external users can't be admins or logged user has no rights to create admins => set as Normal $user->setType('normal'); } else { $user->setAsAdministrator(true); } } /* create contact for this user*/ if (array_var($user_data, 'create_contact', 1)) { // if contact with same email exists take it, else create new $contact = Contacts::getByEmail($user->getEmail(), true); if (!$contact instanceof Contact) { $contact = new Contact(); $contact->setEmail($user->getEmail()); } else { if ($contact->isTrashed()) { $contact->untrash(); } } $contact->setFirstname($user->getDisplayName()); $contact->setUserId($user->getId()); $contact->setTimezone($user->getTimezone()); $contact->setCompanyId($user->getCompanyId()); $contact->save(); } else { $contact_id = array_var($user_data, 'contact_id'); $contact = Contacts::findById($contact_id); if ($contact instanceof Contact) { // user created from a contact $contact->setUserId($user->getId()); $contact->save(); } else { // if contact with same email exists use it as user's contact, without changing it $contact = Contacts::getByEmail($user->getEmail(), true); if ($contact instanceof Contact) { $contact->setUserId($user->getId()); if ($contact->isTrashed()) { $contact->untrash(); } $contact->save(); } } } $contact = $user->getContact(); if ($contact instanceof Contact) { // update contact data with data entered for this user $contact->setCompanyId($user->getCompanyId()); if ($contact->getEmail() != $user->getEmail()) { // make user's email the contact's main email address if ($contact->getEmail2() == $user->getEmail()) { $contact->setEmail2($contact->getEmail()); } else { if ($contact->getEmail3() == $user->getEmail()) { $contact->setEmail3($contact->getEmail()); } else { if ($contact->getEmail2() == "") { $contact->setEmail2($contact->getEmail()); } else { $contact->setEmail3($contact->getEmail()); } } } } $contact->setEmail($user->getEmail()); $contact->save(); } if (!$user->isGuest()) { /* create personal project or assing the selected*/ //if recived a personal project assing this //project as personal project for this user $new_project = null; $personalProjectId = array_var($user_data, 'personal_project', 0); $project = Projects::findById($personalProjectId); if (!$project instanceof Project) { $project = new Project(); $wname = new_personal_project_name($user->getUsername()); $project->setName($wname); $wdesc = Localization::instance()->lang(lang('personal workspace description')); if (!is_null($wdesc)) { $project->setDescription($wdesc); } $project->setCreatedById($user->getId()); $project->save(); //Save to set an ID number $project->setP1($project->getId()); //Set ID number to the first project $project->save(); $new_project = $project; } $user->setPersonalProjectId($project->getId()); $project_user = new ProjectUser(); $project_user->setProjectId($project->getId()); $project_user->setUserId($user->getId()); $project_user->setCreatedById($user->getId()); $project_user->setAllPermissions(true); $project_user->save(); /* end personal project */ } $user->save(); ApplicationLogs::createLog($user, null, ApplicationLogs::ACTION_ADD); //TODO - Make batch update of these permissions if ($permissionsString && $permissionsString != '') { $permissions = json_decode($permissionsString); } else { $permissions = null; } if (is_array($permissions) && (!logged_user() instanceof User || can_manage_security(logged_user()))) { foreach ($permissions as $perm) { if (ProjectUser::hasAnyPermissions($perm->pr, $perm->pc)) { if (!$personalProjectId || $personalProjectId != $perm->wsid) { $relation = new ProjectUser(); $relation->setProjectId($perm->wsid); $relation->setUserId($user->getId()); $relation->setCheckboxPermissions($perm->pc, $user->isGuest() ? false : true); $relation->setRadioPermissions($perm->pr, $user->isGuest() ? false : true); $relation->save(); } } } } // if if ($new_project instanceof Project && logged_user() instanceof User && logged_user()->isProjectUser($new_project)) { evt_add("workspace added", array("id" => $new_project->getId(), "name" => $new_project->getName(), "color" => $new_project->getColor())); } // Send notification... try { if (array_var($user_data, 'send_email_notification')) { Notifier::newUserAccount($user, $password); } // if } catch (Exception $e) { } // try return $user; }
/** * Execute a report and return results * * @param $id * @param $params * * @return array */ static function executeReport($id, $params, $order_by_col = '', $order_by_asc = true, $offset = 0, $limit = 50, $to_print = false) { if (is_null(active_context())) { CompanyWebsite::instance()->setContext(build_context_array(array_var($_REQUEST, 'context'))); } $results = array(); $report = self::getReport($id); $show_archived = false; if ($report instanceof Report) { $conditionsFields = ReportConditions::getAllReportConditionsForFields($id); $conditionsCp = ReportConditions::getAllReportConditionsForCustomProperties($id); $ot = ObjectTypes::findById($report->getReportObjectTypeId()); $table = $ot->getTableName(); if ($ot->getType() == 'dimension_object' || $ot->getType() == 'dimension_group') { $hook_parameters = array('report' => $report, 'params' => $params, 'order_by_col' => $order_by_col, 'order_by_asc' => $order_by_asc, 'offset' => $offset, 'limit' => $limit, 'to_print' => $to_print); $report_result = null; Hook::fire('replace_execute_report_function', $hook_parameters, $report_result); if ($report_result) { return $report_result; } } eval('$managerInstance = ' . $ot->getHandlerClass() . "::instance();"); eval('$item_class = ' . $ot->getHandlerClass() . '::instance()->getItemClass(); $object = new $item_class();'); $order_by = ''; if (is_object($params)) { $params = get_object_vars($params); } $report_columns = ReportColumns::getAllReportColumns($id); $allConditions = ""; $contact_extra_columns = self::get_extra_contact_columns(); if (count($conditionsFields) > 0) { foreach ($conditionsFields as $condField) { if ($condField->getFieldName() == "archived_on") { $show_archived = true; } $skip_condition = false; $model = $ot->getHandlerClass(); $model_instance = new $model(); $col_type = $model_instance->getColumnType($condField->getFieldName()); $allConditions .= ' AND '; $dateFormat = 'm/d/Y'; if (isset($params[$condField->getId()])) { $value = $params[$condField->getId()]; if ($col_type == DATA_TYPE_DATE || $col_type == DATA_TYPE_DATETIME) { $dateFormat = user_config_option('date_format'); } } else { $value = $condField->getValue(); } if ($ot->getHandlerClass() == 'Contacts' && in_array($condField->getFieldName(), $contact_extra_columns)) { $allConditions .= self::get_extra_contact_column_condition($condField->getFieldName(), $condField->getCondition(), $value); } else { if ($value == '' && $condField->getIsParametrizable()) { $skip_condition = true; } if (!$skip_condition) { $field_name = $condField->getFieldName(); if (in_array($condField->getFieldName(), Objects::getColumns())) { $field_name = 'o`.`' . $condField->getFieldName(); } if ($condField->getCondition() == 'like' || $condField->getCondition() == 'not like') { $value = '%' . $value . '%'; } if ($col_type == DATA_TYPE_DATE || $col_type == DATA_TYPE_DATETIME) { if ($value == date_format_tip($dateFormat)) { $value = EMPTY_DATE; } else { $dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value); $value = $dtValue->format('Y-m-d'); } } if ($condField->getCondition() != '%') { if ($col_type == DATA_TYPE_INTEGER || $col_type == DATA_TYPE_FLOAT) { $allConditions .= '`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value); } else { if ($condField->getCondition() == '=' || $condField->getCondition() == '<=' || $condField->getCondition() == '>=') { if ($col_type == DATA_TYPE_DATETIME || $col_type == DATA_TYPE_DATE) { $equal = 'datediff(' . DB::escape($value) . ', `' . $field_name . '`)=0'; } else { $equal = '`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value); } switch ($condField->getCondition()) { case '=': $allConditions .= $equal; break; case '<=': case '>=': $allConditions .= '(`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value) . ' OR ' . $equal . ') '; break; } } else { $allConditions .= '`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value); } } } else { $allConditions .= '`' . $field_name . '` like ' . DB::escape("%{$value}"); } } else { $allConditions .= ' true'; } } } } if (count($conditionsCp) > 0) { $dateFormat = user_config_option('date_format'); $date_format_tip = date_format_tip($dateFormat); foreach ($conditionsCp as $condCp) { $cp = CustomProperties::getCustomProperty($condCp->getCustomPropertyId()); $skip_condition = false; if (isset($params[$condCp->getId() . "_" . $cp->getName()])) { $value = $params[$condCp->getId() . "_" . $cp->getName()]; } else { $value = $condCp->getValue(); } if ($value == '' && $condCp->getIsParametrizable()) { $skip_condition = true; } if (!$skip_condition) { $current_condition = ' AND '; $current_condition .= 'o.id IN ( SELECT object_id as id FROM ' . TABLE_PREFIX . 'custom_property_values cpv WHERE '; $current_condition .= ' cpv.custom_property_id = ' . $condCp->getCustomPropertyId(); $fieldType = $object->getColumnType($condCp->getFieldName()); if ($condCp->getCondition() == 'like' || $condCp->getCondition() == 'not like') { $value = '%' . $value . '%'; } if ($cp->getType() == 'date') { if ($value == $date_format_tip) { continue; } $dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value); $value = $dtValue->format('Y-m-d H:i:s'); } if ($condCp->getCondition() != '%') { if ($cp->getType() == 'numeric') { $current_condition .= ' AND cpv.value ' . $condCp->getCondition() . ' ' . DB::escape($value); } else { if ($cp->getType() == 'boolean') { $current_condition .= ' AND cpv.value ' . $condCp->getCondition() . ' ' . ($value ? '1' : '0'); if (!$value) { $current_condition .= ') OR o.id NOT IN (SELECT object_id as id FROM ' . TABLE_PREFIX . 'custom_property_values cpv2 WHERE cpv2.object_id=o.id AND cpv2.value=1 AND cpv2.custom_property_id = ' . $condCp->getCustomPropertyId(); } } else { $current_condition .= ' AND cpv.value ' . $condCp->getCondition() . ' ' . DB::escape($value); } } } else { $current_condition .= ' AND cpv.value like ' . DB::escape("%{$value}"); } $current_condition .= ')'; $allConditions .= $current_condition; } } } $select_columns = array('*'); $join_params = null; if ($order_by_col == '') { $order_by_col = $report->getOrderBy(); } if ($ot->getHandlerClass() == 'Contacts' && in_array($order_by_col, $contact_extra_columns)) { $join_params = self::get_extra_contact_column_order_by($order_by_col, $order_by_col, $select_columns); } $original_order_by_col = $order_by_col; if (in_array($order_by_col, self::$external_columns)) { $order_by_col = 'name_order'; $join_params = array('table' => Objects::instance()->getTableName(), 'jt_field' => 'id', 'e_field' => $original_order_by_col, 'join_type' => 'left'); $select_columns = array(); $tmp_cols = $managerInstance->getColumns(); foreach ($tmp_cols as $col) { $select_columns[] = "e.{$col}"; } $tmp_cols = Objects::instance()->getColumns(); foreach ($tmp_cols as $col) { $select_columns[] = "o.{$col}"; } $select_columns[] = 'jt.name as name_order'; } if ($order_by_asc == null) { $order_by_asc = $report->getIsOrderByAsc(); } if ($ot->getName() == 'task' && !SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) { $allConditions .= " AND assigned_to_contact_id = " . logged_user()->getId(); } if ($managerInstance) { if ($order_by_col == "order") { $order_by_col = "`{$order_by_col}`"; } $listing_parameters = array("select_columns" => $select_columns, "order" => "{$order_by_col}", "order_dir" => $order_by_asc ? "ASC" : "DESC", "extra_conditions" => $allConditions, "count_results" => true, "join_params" => $join_params); if ($limit > 0) { $listing_parameters["start"] = $offset; $listing_parameters["limit"] = $limit; } if ($show_archived) { $listing_parameters["archived"] = true; } $result = $managerInstance->listing($listing_parameters); } else { // TODO Performance Killer $result = ContentDataObjects::getContentObjects(active_context(), $ot, $order_by_col, $order_by_asc ? "ASC" : "DESC", $allConditions); } $objects = $result->objects; $totalResults = $result->total; $results['pagination'] = Reports::getReportPagination($id, $params, $original_order_by_col, $order_by_asc, $offset, $limit, $totalResults); $dimensions_cache = array(); foreach ($report_columns as $column) { if ($column->getCustomPropertyId() == 0) { $field = $column->getFieldName(); if (str_starts_with($field, 'dim_')) { $dim_id = str_replace("dim_", "", $field); $dimension = Dimensions::getDimensionById($dim_id); $dimensions_cache[$dim_id] = $dimension; $column_name = $dimension->getName(); $results['columns'][$field] = $column_name; $results['db_columns'][$column_name] = $field; } else { if ($managerInstance->columnExists($field) || Objects::instance()->columnExists($field)) { $column_name = Localization::instance()->lang('field ' . $ot->getHandlerClass() . ' ' . $field); if (is_null($column_name)) { $column_name = lang('field Objects ' . $field); } $results['columns'][$field] = $column_name; $results['db_columns'][$column_name] = $field; } else { if ($ot->getHandlerClass() == 'Contacts') { if (in_array($field, $contact_extra_columns)) { $results['columns'][$field] = lang($field); $results['db_columns'][lang($field)] = $field; } } else { if ($ot->getHandlerClass() == 'Timeslots') { if (in_array($field, array('time', 'billing'))) { $results['columns'][$field] = lang('field Objects ' . $field); $results['db_columns'][lang('field Objects ' . $field)] = $field; } } else { if ($ot->getHandlerClass() == 'MailContents') { if (in_array($field, array('to', 'cc', 'bcc', 'body_plain', 'body_html'))) { $results['columns'][$field] = lang('field Objects ' . $field); $results['db_columns'][lang('field Objects ' . $field)] = $field; } } } } } } } else { $results['columns'][$column->getCustomPropertyId()] = $column->getCustomPropertyId(); } } $report_rows = array(); foreach ($objects as &$object) { /* @var $object Object */ $obj_name = $object->getObjectName(); $icon_class = $object->getIconClass(); $row_values = array('object_type_id' => $object->getObjectTypeId()); if (!$to_print) { $row_values['link'] = '<a class="link-ico ' . $icon_class . '" title="' . clean($obj_name) . '" target="new" href="' . $object->getViewUrl() . '"> </a>'; } foreach ($report_columns as $column) { if ($column->getCustomPropertyId() == 0) { $field = $column->getFieldName(); if (str_starts_with($field, 'dim_')) { $dim_id = str_replace("dim_", "", $field); if (!array_var($dimensions_cache, $dim_id) instanceof Dimension) { $dimension = Dimensions::getDimensionById($dim_id); $dimensions_cache[$dim_id] = $dimension; } else { $dimension = array_var($dimensions_cache, $dim_id); } $om_object_id = $object instanceof Timeslot ? $object->getRelObjectId() : $object->getId(); $members = ObjectMembers::getMembersByObjectAndDimension($om_object_id, $dim_id, " AND om.is_optimization=0"); $value = ""; foreach ($members as $member) { /* @var $member Member */ $val = $member->getPath(); $val .= ($val == "" ? "" : "/") . $member->getName(); if ($value != "") { $val = " - {$val}"; } $value .= $val; } $row_values[$field] = $value; } else { if ($object instanceof Timeslot) { if ($field == 'id') { $value = $object->getObjectId(); } else { $value = $object->getColumnValue($field); // if it is a task column if (in_array($field, ProjectTasks::instance()->getColumns())) { $task = ProjectTasks::findById($object->getRelObjectId()); // if task exists if ($task instanceof ProjectTask) { $value = $task->getColumnValue($field); // if it is an external task column if (in_array($field, ProjectTasks::instance()->getExternalColumns())) { $value = self::instance()->getExternalColumnValue($field, $value, ProjectTasks::instance()); } else { // if is a date then use format if (ProjectTasks::instance()->getColumnType($field) == DATA_TYPE_DATETIME && $value instanceof DateTimeValue) { $value = format_value_to_print($field, $value->toMySQL(), DATA_TYPE_DATETIME, $report->getReportObjectTypeId()); } } } $results['columns'][$field] = lang('field ProjectTasks ' . $field); $results['db_columns'][lang('field ProjectTasks ' . $field)] = $field; } } } else { $value = $object->getColumnValue($field); } if ($value instanceof DateTimeValue) { $dateFormat = user_config_option('date_format'); Hook::fire("custom_property_date_format", null, $dateFormat); $tz = logged_user()->getTimezone(); if ($object instanceof ProjectTask) { if ($field == 'due_date' && !$object->getUseDueTime() || $field == 'start_date' && !$object->getUseStartTime()) { $dateFormat = user_config_option('date_format'); $tz = 0; } } $value = format_date($value, $dateFormat, $tz * 3600); } if (in_array($field, $managerInstance->getExternalColumns())) { if ($object instanceof Timeslot && $field == 'time') { $lastStop = $object->getEndTime() != null ? $object->getEndTime() : ($object->isPaused() ? $object->getPausedOn() : DateTimeValueLib::now()); $seconds = $lastStop->getTimestamp() - $object->getStartTime()->getTimestamp(); $hours = number_format($seconds / 3600, 2, ',', '.'); $value = $hours; //$value = DateTimeValue::FormatTimeDiff($object->getStartTime(), $lastStop, "hm", 60, $object->getSubtract()); } else { if ($object instanceof Timeslot && $field == 'billing') { $value = config_option('currency_code', '$') . ' ' . $object->getFixedBilling(); } else { $value = self::instance()->getExternalColumnValue($field, $value, $managerInstance); } } } else { if ($field != 'link') { //$value = html_to_text(html_entity_decode($value)); if ($object->getColumnType($field) == DATA_TYPE_STRING) { // change html block end tags and brs to \n, then remove all other html tags, then replace \n with <br>, to remove all styles and keep the enters $value = str_replace(array("</div>", "</p>", "<br>", "<br />", "<br/>"), "\n", $value); $value = nl2br(strip_tags($value)); } } } if (self::isReportColumnEmail($value)) { if (logged_user()->hasMailAccounts()) { $value = '<a class="internalLink" href="' . get_url('mail', 'add_mail', array('to' => clean($value))) . '">' . clean($value) . '</a></div>'; } else { $value = '<a class="internalLink" target="_self" href="mailto:' . clean($value) . '">' . clean($value) . '</a></div>'; } } $row_values[$field] = $value; if ($ot->getHandlerClass() == 'Contacts') { if ($managerInstance instanceof Contacts) { $contact = Contacts::findOne(array("conditions" => "object_id = " . $object->getId())); if ($field == "email_address") { $row_values[$field] = $contact->getEmailAddress(); } if ($field == "is_user") { $row_values[$field] = $contact->getUserType() > 0 && !$contact->getIsCompany(); } if ($field == "im_values") { $str = ""; foreach ($contact->getAllImValues() as $type => $value) { $str .= ($str == "" ? "" : " | ") . "{$type}: {$value}"; } $row_values[$field] = $str; } if (in_array($field, array("mobile_phone", "work_phone", "home_phone"))) { if ($field == "mobile_phone") { $row_values[$field] = $contact->getPhoneNumber('mobile', null, false); } else { if ($field == "work_phone") { $row_values[$field] = $contact->getPhoneNumber('work', null, false); } else { if ($field == "home_phone") { $row_values[$field] = $contact->getPhoneNumber('home', null, false); } } } } if (in_array($field, array("personal_webpage", "work_webpage", "other_webpage"))) { if ($field == "personal_webpage") { $row_values[$field] = $contact->getWebpageUrl('personal'); } else { if ($field == "work_webpage") { $row_values[$field] = $contact->getWebpageUrl('work'); } else { if ($field == "other_webpage") { $row_values[$field] = $contact->getWebpageUrl('other'); } } } } if (in_array($field, array("home_address", "work_address", "other_address"))) { if ($field == "home_address") { $row_values[$field] = $contact->getStringAddress('home'); } else { if ($field == "work_address") { $row_values[$field] = $contact->getStringAddress('work'); } else { if ($field == "other_address") { $row_values[$field] = $contact->getStringAddress('other'); } } } } } } else { if ($ot->getHandlerClass() == 'MailContents') { if (in_array($field, array('to', 'cc', 'bcc', 'body_plain', 'body_html'))) { $mail_data = MailDatas::findById($object->getId()); $row_values[$field] = $mail_data->getColumnValue($field); if ($field == "body_html") { if (class_exists("DOMDocument")) { $d = new DOMDocument(); $mock = new DOMDocument(); $d->loadHTML(remove_css_and_scripts($row_values[$field])); $body = $d->getElementsByTagName('body')->item(0); foreach ($body->childNodes as $child) { $mock->appendChild($mock->importNode($child, true)); } // if css is inside an html comment => remove it $row_values[$field] = preg_replace('/<!--(.*)-->/Uis', '', remove_css($row_values[$field])); } else { $row_values[$field] = preg_replace('/<!--(.*)-->/Uis', '', remove_css_and_scripts($row_values[$field])); } } } } } if (!$to_print && $field == "name") { $row_values[$field] = '<a target="new-' . $object->getId() . '" href="' . $object->getViewUrl() . '">' . $value . '</a>'; } } } else { $colCp = $column->getCustomPropertyId(); $cp = CustomProperties::getCustomProperty($colCp); if ($cp instanceof CustomProperty) { /* @var $cp CustomProperty */ $row_values[$cp->getName()] = get_custom_property_value_for_listing($cp, $object); $results['columns'][$colCp] = $cp->getName(); $results['db_columns'][$cp->getName()] = $colCp; } } } Hook::fire("report_row", $object, $row_values); $report_rows[] = $row_values; } if (!$to_print) { if (is_array($results['columns'])) { array_unshift($results['columns'], ''); } else { $results['columns'] = array(''); } Hook::fire("report_header", $ot, $results['columns']); } $results['rows'] = $report_rows; } return $results; }
session_start(); error_reporting(E_ALL); if (function_exists('date_default_timezone_set')) { date_default_timezone_set('GMT'); } // if define('UPGRADER_PATH', dirname(__FILE__)); // upgrader is here define('INSTALLATION_PATH', realpath(UPGRADER_PATH . '/../../')); // Feng Office installation that we need to upgrade is here require UPGRADER_PATH . '/library/functions.php'; require UPGRADER_PATH . '/library/classes/ScriptUpgrader.class.php'; require UPGRADER_PATH . '/library/classes/ScriptUpgraderScript.class.php'; require UPGRADER_PATH . '/library/classes/ChecklistItem.class.php'; require UPGRADER_PATH . '/library/classes/Output.class.php'; require UPGRADER_PATH . '/library/classes/Output_Console.class.php'; require UPGRADER_PATH . '/library/classes/Output_Html.class.php'; require UPGRADER_PATH . '/library/classes/Localization.class.php'; require_once UPGRADER_PATH . '/library/classes/Template.class.php'; require_once INSTALLATION_PATH . '/config/config.php'; require_once INSTALLATION_PATH . '/environment/functions/general.php'; require_once INSTALLATION_PATH . '/environment/functions/files.php'; require_once INSTALLATION_PATH . '/environment/functions/utf.php'; require_once INSTALLATION_PATH . '/environment/classes/Error.class.php'; require_once INSTALLATION_PATH . '/environment/classes/errors/filesystem/FileDnxError.class.php'; require_once INSTALLATION_PATH . '/environment/classes/errors/filesystem/DirDnxError.class.php'; require_once INSTALLATION_PATH . '/environment/classes/container/IContainer.class.php'; require_once INSTALLATION_PATH . '/environment/classes/container/Container.class.php'; Localization::instance()->loadSettings(DEFAULT_LOCALIZATION, INSTALLATION_PATH . '/language'); // Set exception handler set_exception_handler('dump_upgrader_exception');
$colname = $context['column_name']; //Check for custom properties if (substr($colname, 0, 8) == 'property') { $property_id = trim(substr($colname, 8)); if (is_numeric($property_id)) { $prop = ObjectProperties::findById($property_id); if ($prop instanceof ObjectProperty) { echo $prop->getPropertyName(); } else { break; } } else { break; } } else { if (Localization::instance()->lang_exists('field ' . $object->getObjectManagerName() . ' ' . $context['column_name'])) { echo lang('field ' . $object->getObjectManagerName() . ' ' . $context['column_name']); } else { echo clean($context['column_name']); } } ?> : </b> <span class='desc'><?php if ($object instanceof ProjectFileRevision) { echo undo_htmlspecialchars($context['context']); } else { echo $context['context']; } ?> </span></td>
function get_javascript_translation() { $content = "/* start */\n"; $fileDir = ROOT . "/language/" . Localization::instance()->getLocale(); //Get Feng Office translation files $filenames = get_files($fileDir, "js"); sort($filenames); foreach ($filenames as $f) { $content .= "\n/* {$f} */\n"; $content .= "try {"; $content .= file_get_contents($f); $content .= "} catch (e) {}"; } $plugins = Plugins::instance()->getActive(); foreach ($plugins as $plugin) { $plg_dir = $plugin->getLanguagePath() . "/" . Localization::instance()->getLocale(); if (is_dir($plg_dir)) { $files = get_files($plg_dir, 'js'); if (is_array($files)) { sort($files); foreach ($files as $file) { $content .= "\n/* {$file} */\n"; $content .= "try {"; /** * The js file can contain PHP code so use include instead of file_get_contents. * To avoid sending headers, use output buffer. * This change help to avoid the need of multiple lang files.. javascripts and phps. * You can create only one php file containing all traslations, * and this will populate client and server side langs datasorces */ ob_start(); include $file; $content .= ob_get_contents(); ob_end_clean(); //!important: Clean output buffer to save memory $content .= "} catch (e) {}"; } } } } $content .= "\n/* end */\n"; $this->setLayout("json"); $this->renderText($content, true); }
/** * Return display description * * @param void * @return string */ function getDisplayDescription() { return Localization::instance()->lang('user ws config option desc ' . $this->getName(), ''); }
/** * Show select country box * * @access public * @param string $name Control name * @param string $value Country code of selected country * @param array $attributes Array of additional select box attributes * @return string */ function select_country_widget($name, $value, $attributes = null) { $country_codes = array_keys(CountryCodes::getAll()); $countries = array(); foreach ($country_codes as $code) { if (Localization::instance()->lang_exists("country {$code}")) { $countries[$code] = lang("country {$code}"); } else { $countries[$code] = CountryCodes::getCountryNameByCode($code); } } // foreach asort($countries); $country_options = array(option_tag(lang('none'), '')); foreach ($countries as $country_code => $country_name) { $option_attributes = $country_code == $value ? array('selected' => true) : null; $country_options[] = option_tag($country_name, $country_code, $option_attributes); } // foreach return select_box($name, $country_options, $attributes); }
private function get_allowed_columns($object_type) { $fields = array(); if (isset($object_type)) { $customProperties = CustomProperties::getAllCustomPropertiesByObjectType($object_type); $objectFields = array(); foreach ($customProperties as $cp) { if ($cp->getType() == 'table') { continue; } $fields[] = array('id' => $cp->getId(), 'name' => $cp->getName(), 'type' => $cp->getType(), 'values' => $cp->getValues(), 'multiple' => $cp->getIsMultipleValues()); } $ot = ObjectTypes::findById($object_type); eval('$managerInstance = ' . $ot->getHandlerClass() . "::instance();"); $objectColumns = $managerInstance->getColumns(); $objectFields = array(); $objectColumns = array_diff($objectColumns, $managerInstance->getSystemColumns()); foreach ($objectColumns as $column) { $objectFields[$column] = $managerInstance->getColumnType($column); } $common_columns = Objects::instance()->getColumns(false); $common_columns = array_diff_key($common_columns, array_flip($managerInstance->getSystemColumns())); $objectFields = array_merge($objectFields, $common_columns); foreach ($objectFields as $name => $type) { if ($type == DATA_TYPE_FLOAT || $type == DATA_TYPE_INTEGER) { $type = 'numeric'; } else { if ($type == DATA_TYPE_STRING) { $type = 'text'; } else { if ($type == DATA_TYPE_BOOLEAN) { $type = 'boolean'; } else { if ($type == DATA_TYPE_DATE || $type == DATA_TYPE_DATETIME) { $type = 'date'; } } } } $field_name = Localization::instance()->lang('field ' . $ot->getHandlerClass() . ' ' . $name); if (is_null($field_name)) { $field_name = lang('field Objects ' . $name); } $fields[] = array('id' => $name, 'name' => $field_name, 'type' => $type); } $externalFields = $managerInstance->getExternalColumns(); foreach ($externalFields as $extField) { $field_name = Localization::instance()->lang('field ' . $ot->getHandlerClass() . ' ' . $extField); if (is_null($field_name)) { $field_name = lang('field Objects ' . $extField); } $fields[] = array('id' => $extField, 'name' => $field_name, 'type' => 'external', 'multiple' => 0); } //if Object type is person $objType = ObjectTypes::findByName('contact'); if ($objType instanceof ObjectType) { if ($object_type == $objType->getId()) { $fields[] = array('id' => 'email_address', 'name' => lang('email address'), 'type' => 'text'); $fields[] = array('id' => 'phone_number', 'name' => lang('phone number'), 'type' => 'text'); $fields[] = array('id' => 'web_url', 'name' => lang('web pages'), 'type' => 'text'); $fields[] = array('id' => 'im_value', 'name' => lang('instant messengers'), 'type' => 'text'); $fields[] = array('id' => 'address', 'name' => lang('address'), 'type' => 'text'); } } } usort($fields, array(&$this, 'compare_FieldName')); return $fields; }
if ($cpv instanceof MemberCustomPropertyValue) { $default_value = $cpv->getValue(); } $name = 'member_custom_properties[' . $customProp->getId() . ']'; echo '<div style="margin-top:12px">'; if ($customProp->getType() == 'boolean') { echo checkbox_field($name, $default_value, array('tabindex' => $startTi + $ti, 'style' => 'margin-right:4px', 'id' => $genid . 'cp' . $customProp->getId())); } $label = clean($customProp->getName()); if ($customProp->getIsSpecial()) { $label = lang(str_replace("_special", "", $customProp->getCode())); } else { if ($customProp->getCode() != '') { $tmp_label = Localization::instance()->lang($customProp->getCode()); if (is_null($tmp_label)) { $tmp_label = Localization::instance()->lang(str_replace("_", " ", $customProp->getCode())); } if (!is_null($tmp_label) && $tmp_label != "") { $label = $tmp_label; } } } echo label_tag($label, $genid . 'cp' . $customProp->getId(), $customProp->getIsRequired(), array('style' => 'display:inline'), $customProp->getType() == 'boolean' ? '' : ':'); echo '</div>'; switch ($customProp->getType()) { case 'text': case 'numeric': case 'memo': if ($customProp->getIsMultipleValues()) { $numeric = $customProp->getType() == "numeric"; echo "<table><tr><td>";
function workEstimate(ProjectTask $task) { tpl_assign('task_assigned', $task); if (!$task->getAssignedTo() instanceof Contact) { return true; // not assigned to user } if (!is_valid_email($task->getAssignedTo()->getEmailAddress())) { return true; } $locale = $task->getAssignedTo()->getLocale(); Localization::instance()->loadSettings($locale, ROOT . '/language'); tpl_assign('title', $task->getObjectName()); tpl_assign('by', $task->getAssignedBy()->getObjectName()); tpl_assign('asigned', $task->getAssignedTo()->getObjectName()); $text = ""; if (config_option("wysiwyg_tasks")) { $text = purify_html(nl2br($task->getDescription())); } else { $text = escape_html_whitespace($task->getDescription()); } tpl_assign('description', $text); //descripction tpl_assign('description_title', lang("new task work estimate to you desc", $task->getObjectName(), $task->getCreatedBy()->getObjectName())); //description_title //priority if ($task->getPriority()) { if ($task->getPriority() >= ProjectTasks::PRIORITY_URGENT) { $priorityColor = "#FF0000"; $priority = lang('urgent priority'); } else { if ($task->getPriority() >= ProjectTasks::PRIORITY_HIGH) { $priorityColor = "#FF9088"; $priority = lang('high priority'); } else { if ($task->getPriority() <= ProjectTasks::PRIORITY_LOW) { $priorityColor = "white"; $priority = lang('low priority'); } else { $priorityColor = "#DAE3F0"; $priority = lang('normal priority'); } } } tpl_assign('priority', array($priority, $priorityColor)); } //context $contexts = array(); if ($task->getMembersToDisplayPath()) { $members = $task->getMembersToDisplayPath(); foreach ($members as $key => $member) { $dim = Dimensions::getDimensionById($key); if ($dim->getCode() == "customer_project") { foreach ($members[$key] as $member) { $obj_type = ObjectTypes::findById($member['ot']); $contexts[$dim->getCode()][$obj_type->getName()][] = '<span style="' . get_workspace_css_properties($member['c']) . '">' . $member['name'] . '</span>'; } } else { foreach ($members[$key] as $member) { $contexts[$dim->getCode()][] = '<span style="' . get_workspace_css_properties($member['c']) . '">' . $member['name'] . '</span>'; } } } } tpl_assign('contexts', $contexts); //workspaces //start date, due date or start if ($task->getStartDate() instanceof DateTimeValue) { $date = Localization::instance()->formatDescriptiveDate($task->getStartDate(), $task->getAssignedTo()->getTimezone()); $time = Localization::instance()->formatTime($task->getStartDate(), $task->getAssignedTo()->getTimezone()); if ($time > 0) { $date .= " " . $time; } tpl_assign('start_date', $date); //start_date } if ($task->getDueDate() instanceof DateTimeValue) { $date = Localization::instance()->formatDescriptiveDate($task->getDueDate(), $task->getAssignedTo()->getTimezone()); $time = Localization::instance()->formatTime($task->getDueDate(), $task->getAssignedTo()->getTimezone()); if ($time > 0) { $date .= " " . $time; } tpl_assign('due_date', $date); //due_date } $attachments = array(); try { $content = FileRepository::getBackend()->getFileContent(owner_company()->getPictureFile()); $file_path = ROOT . "/upload/logo_empresa.png"; $handle = fopen($file_path, 'wb'); fwrite($handle, $content); fclose($handle); if ($content != "") { $attachments['logo'] = array('cid' => gen_id() . substr($task->getAssignedBy()->getEmailAddress(), strpos($task->getAssignedBy()->getEmailAddress(), '@')), 'path' => $file_path, 'type' => 'image/png', 'disposition' => 'inline', 'name' => 'logo_empresa.png'); tpl_assign('attachments', $attachments); // attachments } } catch (FileNotInRepositoryError $e) { // If no logo is set, don't interrupt notifications. } tpl_assign('attachments', $attachments); // attachments self::queueEmail(array(self::prepareEmailAddress($task->getCreatedBy()->getEmailAddress(), $task->getCreatedBy()->getObjectName())), self::prepareEmailAddress($task->getUpdatedBy()->getEmailAddress(), $task->getUpdatedByDisplayName()), lang('work estimate title'), tpl_fetch(get_template_path('work_estimate', 'notifier')), 'text/html', '8bit', $attachments); // send $locale = logged_user() instanceof Contact ? logged_user()->getLocale() : DEFAULT_LOCALIZATION; Localization::instance()->loadSettings($locale, ROOT . '/language'); }
/** * Task has been assigned to the user * * @param ProjectTask $task * @return boolean * @throws NotifierConnectionError */ function taskAssigned(ProjectTask $task) { if ($task->isCompleted()) { return true; // task has been already completed... } // if if (!$task->getAssignedTo() instanceof User) { return true; // not assigned to user } // if /* Checks for assigned to user, to call SMS API */ if ($task->getAssignedTo() instanceof User) { $user = $task->getAssignedTo(); $phone_num = Users::getPhoneNumberCustomProperty($user->getObjectId()); $sms_obj = new SmsController(); $sms_obj->prepareAssignSms($user->getDisplayName(), $task->getTitle(), get_class($task)); $sms_obj->sendSms($phone_num); } else { if ($task->getAssignedTo() instanceof Company) { // Skipping implementation until business requirement is clear } } // GET WS COLOR $workspace_color = $task->getWorkspaceColorsCSV(logged_user()->getWorkspacesQuery()); tpl_assign('task_assigned', $task); tpl_assign('workspace_color', $workspace_color); $locale = $task->getAssignedTo()->getLocale(); Localization::instance()->loadSettings($locale, ROOT . '/language'); if ($task->getDueDate() instanceof DateTimeValue) { $date = Localization::instance()->formatDescriptiveDate($task->getDueDate(), $task->getAssignedTo()->getTimezone()); tpl_assign('date', $date); } self::queueEmail(array(self::prepareEmailAddress($task->getAssignedTo()->getEmail(), $task->getAssignedTo()->getDisplayName())), self::prepareEmailAddress($task->getUpdatedBy()->getEmail(), $task->getUpdatedByDisplayName()), lang('task assigned to you', $task->getTitle(), $task->getProject() instanceof Project ? $task->getProject()->getName() : ''), tpl_fetch(get_template_path('task_assigned', 'notifier'))); // send $locale = logged_user() instanceof User ? logged_user()->getLocale() : DEFAULT_LOCALIZATION; Localization::instance()->loadSettings($locale, ROOT . '/language'); }
/** * Get DB description from lang based on category name * * @param void * @return string */ function getDisplayDescription() { return Localization::instance()->lang('config category desc ' . $this->getName(), ''); } // getDisplayDescription
/** * Return formated time * * @access public * @param DateTime $value If value is not instance of DateTime object new DateTime * object will be created with $value as its constructor param * @param string $format If $format is NULL default time format will be used * @param float $timezone Timezone, if NULL it will be autodetected (by currently logged user if we have it) * @return string */ function format_time($value = null, $format = null, $timezone = null) { if (is_null($timezone) && function_exists('logged_user') && logged_user() instanceof User) { $timezone = logged_user()->getTimezone(); } // if $datetime = $value instanceof DateTimeValue ? $value : new DateTimeValue($value); return Localization::instance()->formatTime($datetime, $timezone); }
/** *Make Mn *@return string */ function MakeMindMap(){ // header xml data freemind $content = "<map version=\"0.9.0\">\n"; $content .= "<!-- To view this file, download free mind mapping software FreeMind from http://freemind.sourceforge.net -->\n"; $mytime = time(); // is logged ? if (!logged_user()->isProjectUser(active_project())) { echo $content; echo "<node CREATED=\"$mytime\" ID=\"Freemind_Link_558888646\" MODIFIED=\"$mytime\" STYLE=\"bubble\" TEXT=\"Disconnected\">\n"; echo "</node>\n"; echo "</map>\n"; die; } // if // is user can view this project ?? if (!ProjectFile::canView(logged_user(), active_project())) { echo $content; echo "<node CREATED=\"$mytime\" ID=\"Freemind_Link_558888646\" MODIFIED=\"$mytime\" STYLE=\"bubble\" TEXT=\"Not Allowed\">\n"; echo "</node>\n"; echo "</map>\n"; die; } //if /* * xml data construction freemind for project */ $project = active_project(); $project_name = $project->getName(); $this->epure($project_name); //Project title $url = externalUrl(get_url('task','index')); $content .= "<node CREATED=\"$mytime\" LINK=\"$url\" MODIFIED=\"$mytime\" STYLE=\"bubble\" TEXT=\"$project_name\">\n"; //milestones $milestones = $project->getMilestones(); $mymilestone = array(); if (is_array($milestones)) { foreach($milestones as $milestone){ $url = externalUrl(get_url('milestone','view',array('id' => $milestone->getId()))); $content .= "<node CREATED=\"$mytime\" LINK=\"$url\" POSITION=\"right\" MODIFIED=\"$mytime\" TEXT=\" [" . $milestone->getName() . ' ' . Localization::instance()->formatDate($milestone->getDueDate()) . "]\">\n"; $content .= "<font NAME=\"SansSerif\" BOLD=\"true\" SIZE=\"12\"/>"; $content .= "<icon BUILTIN=\"messagebox_warning\"/>\n"; $content .= "<icon BUILTIN=\"messagebox_warning\"/>\n"; $content .= "</node>\n"; } } $task_lists = $project->getTaskLists(); if (is_array($task_lists)) { //Tasks lists $positions = array('right','left'); $actualpos = 0; foreach ($task_lists as $task_list) { /* * security access */ //security access User can view this task_list ? if (!ProjectTaskList::canView(logged_user(), $task_list->getId())) continue; // task list name $task_list_name=$task_list->getName(); //Complete or not complete $progress = $this->progress($task_list); $icon = null; $tasklistComplete = false; if ($progress[0] == '100'){ $icon .= "<icon BUILTIN=\"button_ok\"/>\n"; $tasklistComplete = true; } $kt_tl_var = 'tl:' . $task_list_name; $this->epure($kt_tl_var); if (strlen($task_list_name) > 40) $task_list_name = substr($task_list_name,0,40) . "..."; $position = $positions[$actualpos]; $url = externalUrl(get_url('task','view_list',array('id' => $task_list->getId()))); $content .= "<node CREATED=\"$mytime\" LINK=\"$url\" MODIFIED=\"$mytime\" POSITION=\"$position\" TEXT=\"$task_list_name\">\n"; $content .= "$icon"; if ($actualpos == 0){ $actualpos =1; }else{ $actualpos =0; } //if //tasks $tasks = $task_list->getTasks(); if (is_array($tasks)) { foreach($tasks as $task) { /* * security access */ //security access User can view this task ? if (!ProjectTask::canView(logged_user(), $task->getId())) continue; // icon freeming ok | cancel $icon = null; if (!$tasklistComplete){ if ($task->isCompleted()) { //complete : icon ok $icon .= "<icon BUILTIN=\"button_ok\"/>\n"; $dateclose = " []"; }else{ //incomplete : icon cancel $icon .= "<icon BUILTIN=\"button_cancel\"/>\n"; $dateclose = " []"; } //if } //if //task name $task_text = $task->getText(); $this->epure($task_text); if (strlen($task_text) > 40) $task_text = substr($task_text,0,40) . "..."; $url = externalUrl(get_url('task','view_task',array('id' => $task->getId()))); $content .= "<node CREATED=\"$mytime\" LINK=\"$url\" MODIFIED=\"$mytime\" TEXT=\"" . $task_text . "\">\n"; $content .= $icon; $content .= "</node>\n"; } } $content .= "</node>\n"; } // if } // if //footer xml data freemind $content .= "</node>\n"; $content .= "</map>"; //send data $type = "x-freemind/mm"; $name = "projectpier.mm"; $size = strlen($content); header("Content-Type: $type"); header("Content-Disposition: attachment; filename=\"$name\""); header("Content-Length: " . (string) $size); echo $content; die; //end process do not send other informations } //MakeMm
function help_link() { $link = Localization::instance()->lang('wiki help link'); if (is_null($link)) { $link = DEFAULT_HELP_LINK; } return $link; }
FileRepository::setBackend(new FileRepository_Backend_FileSystem(FILES_DIR, TABLE_PREFIX)); } else { FileRepository::setBackend(new FileRepository_Backend_DB(TABLE_PREFIX)); } // if PublicFiles::setRepositoryPath(ROOT . '/public/files'); if (trim(PUBLIC_FOLDER) == '') { PublicFiles::setRepositoryUrl(with_slash(ROOT_URL) . 'files'); } else { PublicFiles::setRepositoryUrl(with_slash(ROOT_URL) . 'public/files'); } // if // Owner company or administrator doen't exist? Let the user create them } catch (OwnerCompanyDnxError $e) { Localization::instance()->loadSettings(DEFAULT_LOCALIZATION, ROOT . '/language'); Env::executeAction('access', 'complete_installation'); } catch (AdministratorDnxError $e) { Localization::instance()->loadSettings(DEFAULT_LOCALIZATION, ROOT . '/language'); Env::executeAction('access', 'complete_installation'); // Other type of error? We need to break here } catch (Exception $e) { Localization::instance()->loadSettings(DEFAULT_LOCALIZATION, ROOT . '/language'); if (Env::isDebugging()) { Env::dumpError($e); } else { Logger::log($e, Logger::FATAL); Env::executeAction('error', 'system'); } // if } // try
/** * Execute a report and return results * * @param $id * @param $params * * @return array */ static function executeReport($id, $params, $order_by_col = '', $order_by_asc = true, $offset=0, $limit=50, $to_print = false) { if (is_null(active_context())) { CompanyWebsite::instance()->setContext(build_context_array(array_var($_REQUEST, 'context'))); } $results = array(); $report = self::getReport($id); if($report instanceof Report){ $conditionsFields = ReportConditions::getAllReportConditionsForFields($id); $conditionsCp = ReportConditions::getAllReportConditionsForCustomProperties($id); $ot = ObjectTypes::findById($report->getReportObjectTypeId()); $table = $ot->getTableName(); eval('$managerInstance = ' . $ot->getHandlerClass() . "::instance();"); eval('$item_class = ' . $ot->getHandlerClass() . '::instance()->getItemClass(); $object = new $item_class();'); $order_by = ''; if (is_object($params)) { $params = get_object_vars($params); } $report_columns = ReportColumns::getAllReportColumns($id); $allConditions = ""; if(count($conditionsFields) > 0){ foreach($conditionsFields as $condField){ $skip_condition = false; $model = $ot->getHandlerClass(); $model_instance = new $model(); $col_type = $model_instance->getColumnType($condField->getFieldName()); $allConditions .= ' AND '; $dateFormat = 'm/d/Y'; if(isset($params[$condField->getId()])){ $value = $params[$condField->getId()]; if ($col_type == DATA_TYPE_DATE || $col_type == DATA_TYPE_DATETIME) $dateFormat = user_config_option('date_format'); } else { $value = $condField->getValue(); } if ($value == '' && $condField->getIsParametrizable()) $skip_condition = true; if (!$skip_condition) { if($condField->getCondition() == 'like' || $condField->getCondition() == 'not like'){ $value = '%'.$value.'%'; } if ($col_type == DATA_TYPE_DATE || $col_type == DATA_TYPE_DATETIME) { $dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value); $value = $dtValue->format('Y-m-d'); } if($condField->getCondition() != '%'){ if ($col_type == DATA_TYPE_INTEGER || $col_type == DATA_TYPE_FLOAT) { $allConditions .= '`'.$condField->getFieldName().'` '.$condField->getCondition().' '.DB::escape($value); } else { if ($condField->getCondition()=='=' || $condField->getCondition()=='<=' || $condField->getCondition()=='>='){ if ($col_type == DATA_TYPE_DATETIME || $col_type == DATA_TYPE_DATE) { $equal = 'datediff('.DB::escape($value).', `'.$condField->getFieldName().'`)=0'; } else { $equal = '`'.$condField->getFieldName().'` '.$condField->getCondition().' '.DB::escape($value); } switch($condField->getCondition()){ case '=': $allConditions .= $equal; break; case '<=': case '>=': $allConditions .= '(`'.$condField->getFieldName().'` '.$condField->getCondition().' '.DB::escape($value).' OR '.$equal.') '; break; } } else { $allConditions .= '`'.$condField->getFieldName().'` '.$condField->getCondition().' '.DB::escape($value); } } } else { $allConditions .= '`'.$condField->getFieldName().'` like '.DB::escape("%$value"); } } else $allConditions .= ' true'; } } if(count($conditionsCp) > 0){ $dateFormat = user_config_option('date_format'); $date_format_tip = date_format_tip($dateFormat); foreach($conditionsCp as $condCp){ $cp = CustomProperties::getCustomProperty($condCp->getCustomPropertyId()); $skip_condition = false; if(isset($params[$condCp->getId()."_".$cp->getName()])){ $value = $params[$condCp->getId()."_".$cp->getName()]; }else{ $value = $condCp->getValue(); } if ($value == '' && $condCp->getIsParametrizable()) $skip_condition = true; if (!$skip_condition) { $current_condition = ' AND '; $current_condition .= 'o.id IN ( SELECT object_id as id FROM '.TABLE_PREFIX.'custom_property_values cpv WHERE '; $current_condition .= ' cpv.custom_property_id = '.$condCp->getCustomPropertyId(); $fieldType = $object->getColumnType($condCp->getFieldName()); if($condCp->getCondition() == 'like' || $condCp->getCondition() == 'not like'){ $value = '%'.$value.'%'; } if ($cp->getType() == 'date') { if ($value == $date_format_tip) continue; $dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value); $value = $dtValue->format('Y-m-d H:i:s'); } if($condCp->getCondition() != '%'){ if ($cp->getType() == 'numeric') { $current_condition .= ' AND cpv.value '.$condCp->getCondition().' '.DB::escape($value); }else if ($cp->getType() == 'boolean') { $current_condition .= ' AND cpv.value '.$condCp->getCondition().' '.$value; if (!$value) { $current_condition .= ') OR o.id NOT IN (SELECT object_id as id FROM '.TABLE_PREFIX.'custom_property_values cpv2 WHERE cpv2.object_id=o.id AND cpv2.value=1 AND cpv2.custom_property_id = '.$condCp->getCustomPropertyId(); } }else{ $current_condition .= ' AND cpv.value '.$condCp->getCondition().' '.DB::escape($value); } }else{ $current_condition .= ' AND cpv.value like '.DB::escape("%$value"); } $current_condition .= ')'; $allConditions .= $current_condition; } } } $select_columns = array('*'); $join_params = null; if ($order_by_col == '') { $order_by_col = $report->getOrderBy(); } if (in_array($order_by_col, self::$external_columns)) { $original_order_by_col = $order_by_col; $order_by_col = 'name_order'; $join_params = array( 'table' => Objects::instance()->getTableName(), 'jt_field' => 'id', 'e_field' => $original_order_by_col, 'join_type' => 'left' ); $select_columns = array(); $tmp_cols = $managerInstance->getColumns(); foreach ($tmp_cols as $col) $select_columns[] = "e.$col"; $tmp_cols = Objects::instance()->getColumns(); foreach ($tmp_cols as $col) $select_columns[] = "o.$col"; $select_columns[] = 'jt.name as name_order'; } if ($order_by_asc == null) $order_by_asc = $report->getIsOrderByAsc(); if ($ot->getName() == 'task' && !SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) { $allConditions .= " AND assigned_to_contact_id = ".logged_user()->getId(); } if ($managerInstance) { $result = $managerInstance->listing(array( "select_columns" => $select_columns, "order" => "$order_by_col", "order_dir" => ($order_by_asc ? "ASC" : "DESC"), "extra_conditions" => $allConditions, "join_params" => $join_params )); }else{ // TODO Performance Killer $result = ContentDataObjects::getContentObjects(active_context(), $ot, $order_by_col, ($order_by_asc ? "ASC" : "DESC"), $allConditions); } $objects = $result->objects; $totalResults = $result->total; $results['pagination'] = Reports::getReportPagination($id, $params, $order_by_col, $order_by_asc, $offset, $limit, $totalResults); $dimensions_cache = array(); foreach($report_columns as $column){ if ($column->getCustomPropertyId() == 0) { $field = $column->getFieldName(); if (str_starts_with($field, 'dim_')) { $dim_id = str_replace("dim_", "", $field); $dimension = Dimensions::getDimensionById($dim_id); $dimensions_cache[$dim_id] = $dimension; $doptions = $dimension->getOptions(true); $column_name = $doptions && isset($doptions->useLangs) && $doptions->useLangs ? lang($dimension->getCode()) : $dimension->getName(); $results['columns'][$field] = $column_name; $results['db_columns'][$column_name] = $field; } else { if ($managerInstance->columnExists($field) || Objects::instance()->columnExists($field)) { $column_name = Localization::instance()->lang('field '.$ot->getHandlerClass().' '.$field); if (is_null($column_name)) $column_name = lang('field Objects '.$field); $results['columns'][$field] = $column_name; $results['db_columns'][$column_name] = $field; } } } else { $results['columns'][$column->getCustomPropertyId()] = $column->getCustomPropertyId(); } } $report_rows = array(); foreach($objects as &$object){/* @var $object Object */ $obj_name = $object->getObjectName(); $icon_class = $object->getIconClass(); $row_values = array('object_type_id' => $object->getObjectTypeId()); if (!$to_print) { $row_values['link'] = '<a class="link-ico '.$icon_class.'" title="' . $obj_name . '" target="new" href="' . $object->getViewUrl() . '"> </a>'; } foreach($report_columns as $column){ if ($column->getCustomPropertyId() == 0) { $field = $column->getFieldName(); if (str_starts_with($field, 'dim_')) { $dim_id = str_replace("dim_", "", $field); if (!array_var($dimensions_cache, $dim_id) instanceof Dimension) { $dimension = Dimensions::getDimensionById($dim_id); $dimensions_cache[$dim_id] = $dimension; } else { $dimension = array_var($dimensions_cache, $dim_id); } $members = ObjectMembers::getMembersByObjectAndDimension($object->getId(), $dim_id, " AND om.is_optimization=0"); $value = ""; foreach ($members as $member) {/* @var $member Member */ $val = $member->getPath(); $val .= ($val == "" ? "" : "/") . $member->getName(); if ($value != "") $val = " - $val"; $value .= $val; } $row_values[$field] = $value; } else { $value = $object->getColumnValue($field); if ($value instanceof DateTimeValue) { $field_type = $managerInstance->columnExists($field) ? $managerInstance->getColumnType($field) : Objects::instance()->getColumnType($field); $value = format_value_to_print($field, $value->toMySQL(), $field_type, $report->getReportObjectTypeId()); } if(in_array($field, $managerInstance->getExternalColumns())){ $value = self::instance()->getExternalColumnValue($field, $value, $managerInstance); } else if ($field != 'link'){ $value = html_to_text($value); } if(self::isReportColumnEmail($value)) { if(logged_user()->hasMailAccounts()){ $value = '<a class="internalLink" href="'.get_url('mail', 'add_mail', array('to' => clean($value))).'">'.clean($value).'</a></div>'; }else{ $value = '<a class="internalLink" target="_self" href="mailto:'.clean($value).'">'.clean($value).'</a></div>'; } } $row_values[$field] = $value; } } else { $colCp = $column->getCustomPropertyId(); $cp = CustomProperties::getCustomProperty($colCp); if ($cp instanceof CustomProperty) { /* @var $cp CustomProperty */ $cp_val = CustomPropertyValues::getCustomPropertyValue($object->getId(), $colCp); $row_values[$cp->getName()] = $cp_val instanceof CustomPropertyValue ? $cp_val->getValue() : ""; $results['columns'][$colCp] = $cp->getName(); $results['db_columns'][$cp->getName()] = $colCp; } } } Hook::fire("report_row", $object, $row_values); $report_rows[] = $row_values; } if (!$to_print) { if (is_array($results['columns'])) { array_unshift($results['columns'], ''); } else { $results['columns'] = array(''); } Hook::fire("report_header", $ot, $results['columns']); } $results['rows'] = $report_rows; } return $results; } // executeReport
/** * Return pick date widget * * @access public * @param string $name Name prefix * @param DateTimeValue $value Can be DateTimeValue object, integer or string * @param integer $year_from Start counting from this year. If NULL this value will be set * to current year - 10 * @param integer $year_to Count to this year. If NULL this value will be set to current * year + 10 * @return null */ function pick_date_widget($name, $value = null, $year_from = null, $year_to = null) { $v = $value; if ($value instanceof DateTimeValue) { $v = $v->format('d.m.Y'); $v = Localization::instance()->formatDate($value, null, null); } /* $month_options = array(); for ($i = 1; $i <= 12; $i++) { $option_attributes = $i == $value->getMonth() ? array('selected' => 'selected') : null; $month_options[] = option_tag(lang("month $i"), $i, $option_attributes); } // for $day_options = array(); for ($i = 1; $i <= 31; $i++) { $option_attributes = $i == $value->getDay() ? array('selected' => 'selected') : null; $day_options[] = option_tag($i, $i, $option_attributes); } // for $year_from = (integer) $year_from < 1 ? $value->getYear() - 10 : (integer) $year_from; $year_to = (integer) $year_to < 1 || ((integer) $year_to < $year_from) ? $value->getYear() + 10 : (integer) $year_to; $year_options = array(); for ($i = $year_from; $i <= $year_to; $i++) { $option_attributes = $i == $value->getYear() ? array('selected' => 'selected') : null; $year_options[] = option_tag($i, $i, $option_attributes); } // if //$v = date('m/d/Y'); //return select_box($name . '_month', $month_options) . select_box($name . '_day', $day_options) . select_box($name . '_year', $year_options); */ return text_field($name, $v, array('class' => 'datepicker')); }
private static function getTaskDateFormatted($object, $date_column, $timezone) { $date = ""; if ($object->columnExists($date_column) && $object->getColumnValue($date_column)) { $date_val = $object->getColumnValue($date_column); if ($date_val instanceof DateTimeValue) { $date = Localization::instance()->formatDescriptiveDate($date_val, $timezone); $time = Localization::instance()->formatTime($date_val, $timezone); if ($time > 0) { $date .= " " . $time; } } } return $date; }
/** * Prepare search conditions string based on input params * * @param string $search_for Search string * @param string $project_csvs Search in this project * @return array */ function getSearchConditions($search_for, $project_csvs = null, $include_private = false, $object_type = '', $columns_csv = null, $user_id = 0) { $otSearch = ''; $columnsSearch = ''; $wsSearch = ''; $search_deep = false; $few_chars = false; if (!is_null($columns_csv)) { $columnsSearch = " AND `column_name` in (" . $columns_csv . ")"; } if ($object_type != '') { $otSearch = " AND `rel_object_manager` = '{$object_type}'"; } if ($project_csvs) { $wsSearch .= " AND "; /*if ($user_id > 0) $wsSearch .= " (`user_id` = " . $user_id . " OR "; else $wsSearch .= " (";*/ if ($object_type == "ProjectFileRevisions") { $wsSearch .= "`rel_object_id` IN (SELECT o.id FROM " . TABLE_PREFIX . "project_file_revisions o where o.file_id IN (SELECT p.`object_id` FROM `" . TABLE_PREFIX . "workspace_objects` p WHERE p.`object_manager` = 'ProjectFiles' && p.`workspace_id` IN ({$project_csvs})))"; } else { $wsSearch .= "`rel_object_id` IN (SELECT `object_id` FROM `" . TABLE_PREFIX . "workspace_objects` WHERE `object_manager` = '{$object_type}' && `workspace_id` IN ({$project_csvs}))"; } //$wsSearch .= ')'; } else { $wsSearch = ""; } //Check for trashed and other permissions $tableName = eval("return {$object_type}::instance()->getTableName();"); $trashed = ''; if ($object_type != 'Projects' && $object_type != 'Users') { $trashed = " and EXISTS(SELECT * FROM {$tableName} co where `rel_object_id` = id and trashed_by_id = 0 "; $trashed .= ' AND ( ' . permissions_sql_for_listings(eval("return {$object_type}::instance();"), ACCESS_LEVEL_READ, logged_user(), '`project_id`', '`co`') . ')'; $trashed .= ')'; } //Check workspace permissions if ($object_type == 'Projects') { $trashed .= " AND `rel_object_id` IN (SELECT `proj`.`id` FROM {$tableName} `proj` WHERE "; $trashed .= ' ( ' . permissions_sql_for_listings(eval("return {$object_type}::instance();"), ACCESS_LEVEL_READ, logged_user(), '`project_id`', '`proj`') . '))'; } // if search criteria is a mail address, remove its domain to avoid matching emails with same domain that are not from this address /* $pos = strpos_utf($search_for, '@'); while ($pos !== FALSE) { $esp = strpos_utf($search_for, ' ', $pos); if ($esp !== FALSE) $search_for = substr_utf($search_for, 0, $pos) . ' ' . substr_utf($search_for, $esp+1); else $search_for = substr_utf($search_for, 0, $pos); $pos = strpos_utf($search_for, '@'); } */ // Commented by pepe if ($include_private) { $privSearch = 'AND `is_private` = 0'; } else { $privSearch = ''; } //in case the string to be looked for contains one to three chars and therefore find no objects with a 'quick search' if (strlen($search_for) <= config_option("min_chars_for_match")) { $few_chars = true; } //in case the user does a deeper search with " or ' if (str_starts_with($search_for, '"') && str_ends_with($search_for, '"')) { $search_deep = true; $search_for = str_replace('"', '', $search_for); } if (user_config_option('search_engine', substr(Localization::instance()->getLocale(), 0, 2) == 'zh' ? 'like' : null) == 'like' || $few_chars == true) { $search_for = str_replace("*", "%", $search_for); if (!$search_deep) { $search_words = explode(" ", $search_for); $search_string = ""; foreach ($search_words as $word) { if ($search_string) { $search_string .= " AND "; } $search_string .= "`content` LIKE '%{$word}%'"; } } else { $search_string .= "`content` LIKE '%{$search_for}%'"; } return DB::prepareString("{$search_string} {$privSearch} {$wsSearch} {$trashed} {$otSearch} {$columnsSearch}"); } else { $search_words = preg_split('/[\\s\\.\\+\\-\\~]/', $search_for); if (!$search_deep) { $search_for = ""; foreach ($search_words as $word) { if ($word != "" && $word[0] != "+" && $word[0] != "-") { $search_for .= " +{$word}"; } } } else { $search_for = "\"" . $search_for . "\""; } //return DB::prepareString("MATCH (`content`) AGAINST ('$search_for' IN BOOLEAN MODE) $privSearch $wsSearch $trashed $otSearch $columnsSearch"); //@pepe - AGAINST() fails with special characters like '@' or '/' if string not scaped return DB::prepareString("MATCH (`content`) AGAINST ('\"" . $search_for . "\"' IN BOOLEAN MODE) {$privSearch} {$wsSearch} {$trashed} {$otSearch} {$columnsSearch}"); } }
$w = idate('d', mktime(0, 0, 0, $month, 0, $year)) + $day_of_month; $dtv = DateTimeValueLib::make(0, 0, 0, $month, $day_of_month, $year); } else { if ($day_of_month == $lastday + 1) { $month++; if ($month == 13) { $month = 1; $year++; } } $p = get_url('event', 'viewdate', array('day' => $day_of_month - $lastday, 'month' => $month, 'year' => $year, 'view_type' => 'viewdate')); $t = get_url('event', 'add', array('day' => $day_of_month - $lastday, 'month' => $month, 'year' => $year)); $w = $day_of_month - $lastday; $dtv = DateTimeValueLib::make(0, 0, 0, $month, $w, $year); } $loc = Localization::instance(); $start_value = $dtv->format(user_config_option('date_format')); $popupTitle = lang('add event'); $output .= "><div style='z-index:0; min-height:100px; height:100%;cursor:pointer' onclick=\"og.EventPopUp.show(null, {caller:'overview-panel', day:'" . $dtv->getDay() . "', month:'" . $dtv->getMonth() . "', year:'" . $dtv->getYear() . "', type_id:1, hour:'9', minute:'0', durationhour:1, durationmin:0, start_value: '{$start_value}', start_time:'9:00', title:'" . format_datetime($dtv, 'l, j F', logged_user()->getTimezone()) . "', view: 'week', title: '{$popupTitle}', time_format: '{$timeformat}', hide_calendar_toolbar: 0, genid:{$genid}, otype:" . $event->manager()->getObjectTypeId() . "},'');\") >\n\t\t\t<div class='{$daytitle}' style='text-align:right'>"; //if($day_of_month >= 1){ $output .= "<a class='internalLink' href=\"{$p}\" onclick=\"og.disableEventPropagation(event);\" style='color:#5B5B5B' >{$w}</a>"; // only display this link if the user has permission to add an event if (!active_project() || ProjectEvent::canAdd(logged_user(), active_project())) { // if single digit, add a zero $dom = $day_of_month; if ($dom < 10) { $dom = "0" . $dom; } // make sure user is allowed to edit the past } //}else $output .= " ";
private function get_allowed_columns($object_type) { $fields = array(); if (isset($object_type)) { $customProperties = CustomProperties::getAllCustomPropertiesByObjectType($object_type); $objectFields = array(); foreach ($customProperties as $cp) { if ($cp->getType() == 'table') { continue; } $fields[] = array('id' => $cp->getId(), 'name' => $cp->getName(), 'type' => $cp->getType(), 'values' => $cp->getValues(), 'multiple' => $cp->getIsMultipleValues()); } $ot = ObjectTypes::findById($object_type); eval('$managerInstance = ' . $ot->getHandlerClass() . "::instance();"); $objectColumns = $managerInstance->getColumns(); $objectFields = array(); $objectColumns = array_diff($objectColumns, $managerInstance->getSystemColumns()); foreach ($objectColumns as $column) { $objectFields[$column] = $managerInstance->getColumnType($column); } $common_columns = Objects::instance()->getColumns(false); $common_columns = array_diff_key($common_columns, array_flip($managerInstance->getSystemColumns())); $objectFields = array_merge($objectFields, $common_columns); foreach ($objectFields as $name => $type) { if ($type == DATA_TYPE_FLOAT || $type == DATA_TYPE_INTEGER) { $type = 'numeric'; } else { if ($type == DATA_TYPE_STRING) { $type = 'text'; } else { if ($type == DATA_TYPE_BOOLEAN) { $type = 'boolean'; } else { if ($type == DATA_TYPE_DATE || $type == DATA_TYPE_DATETIME) { $type = 'date'; } } } } $field_name = Localization::instance()->lang('field ' . $ot->getHandlerClass() . ' ' . $name); if (is_null($field_name)) { $field_name = lang('field Objects ' . $name); } $fields[] = array('id' => $name, 'name' => $field_name, 'type' => $type); } $externalFields = $managerInstance->getExternalColumns(); foreach ($externalFields as $extField) { $field_name = Localization::instance()->lang('field ' . $ot->getHandlerClass() . ' ' . $extField); if (is_null($field_name)) { $field_name = lang('field Objects ' . $extField); } $fields[] = array('id' => $extField, 'name' => $field_name, 'type' => 'external', 'multiple' => 0); } if (!array_var($_REQUEST, 'noaddcol')) { Hook::fire('custom_reports_additional_columns', null, $fields); } } usort($fields, array(&$this, 'compare_FieldName')); return $fields; }
$path = $_SERVER['PHP_SELF']; $path = substr($path, 0, strpos($path, 'index.php')); $installation_root = $path; define('ROOT_URL', $installation_root); // Init flash! Flash::instance(); $language = config_option('installation_base_language', 'en_us'); if (isset($_GET['language'])) { $_SESSION['language'] = $_GET['language']; $_GET['language'] = ''; } if (isset($_SESSION['language'])) { $language = $_SESSION['language']; } if (!plugin_active('i18n')) { Localization::instance()->loadSettings($language, ROOT . '/language'); } try { trace(__FILE__, 'CompanyWebsite::init()'); CompanyWebsite::init(); if (config_option('upgrade_check_enabled', false)) { VersionChecker::check(false); } // if if (config_option('file_storage_adapter', 'mysql') == FILE_STORAGE_FILE_SYSTEM) { trace(__FILE__, 'FileRepository::setBackend() - use file storage'); FileRepository::setBackend(new FileRepository_Backend_FileSystem(FILES_DIR)); } else { trace(__FILE__, 'FileRepository::setBackend() - use mysql storage'); FileRepository::setBackend(new FileRepository_Backend_MySQL(DB::connection()->getLink(), TABLE_PREFIX)); }
function workEstimate(ProjectTask $task) { tpl_assign('task_assigned', $task); if(!($task->getAssignedTo() instanceof Contact)) { return true; // not assigned to user } if (!is_valid_email($task->getAssignedTo()->getEmailAddress())) { return true; } $locale = $task->getAssignedTo()->getLocale(); Localization::instance()->loadSettings($locale, ROOT . '/language'); tpl_assign('title', $task->getObjectName()); tpl_assign('by', $task->getAssignedBy()->getObjectName()); tpl_assign('asigned', $task->getAssignedTo()->getObjectName()); $text = ""; if(config_option("wysiwyg_tasks")){ $text = purify_html(nl2br($task->getDescription())); }else{ $text = escape_html_whitespace($task->getDescription()); } tpl_assign('description', $text);//descripction tpl_assign('description_title', lang("new task work estimate to you desc", $task->getObjectName(),$task->getAssignedBy()->getObjectName()));//description_title //priority if ($task->getPriority()) { if ($task->getPriority() >= ProjectTasks::PRIORITY_URGENT) { $priorityColor = "#FF0000"; $priority = lang('urgent priority'); }else if ($task->getPriority() >= ProjectTasks::PRIORITY_HIGH) { $priorityColor = "#FF9088"; $priority = lang('high priority'); } else if ($task->getPriority() <= ProjectTasks::PRIORITY_LOW) { $priorityColor = "white"; $priority = lang('low priority'); }else{ $priorityColor = "#DAE3F0"; $priority = lang('normal priority'); } tpl_assign('priority', array($priority,$priorityColor)); } //context $contexts = array(); $members = $task->getMembers(); if(count($members)>0){ foreach ($members as $member){ $dim = $member->getDimension(); if($dim->getIsManageable()){ if ($dim->getCode() == "customer_project"){ $obj_type = ObjectTypes::findById($member->getObjectTypeId()); if ($obj_type instanceof ObjectType) { $contexts[$dim->getCode()][$obj_type->getName()][]= '<span style="'.get_workspace_css_properties($member->getMemberColor()).'">'. $member->getName() .'</span>'; } }else{ $contexts[$dim->getCode()][]= '<span style="'.get_workspace_css_properties($member->getMemberColor()).'">'. $member->getName() .'</span>'; } } } } tpl_assign('contexts', $contexts);//workspaces //start date, due date or start if ($task->getStartDate() instanceof DateTimeValue) { $date = Localization::instance()->formatDescriptiveDate($task->getStartDate(), $task->getAssignedTo()->getTimezone()); $time = Localization::instance()->formatTime($task->getStartDate(), $task->getAssignedTo()->getTimezone()); if($time > 0) $date .= " " . $time; tpl_assign('start_date', $date);//start_date } if ($task->getDueDate() instanceof DateTimeValue) { $date = Localization::instance()->formatDescriptiveDate($task->getDueDate(), $task->getAssignedTo()->getTimezone()); $time = Localization::instance()->formatTime($task->getDueDate(), $task->getAssignedTo()->getTimezone()); if($time > 0) $date .= " " . $time; tpl_assign('due_date', $date);//due_date } $attachments = array(); try { $content = FileRepository::getBackend()->getFileContent(owner_company()->getPictureFile()); if ($content) { $file_path = ROOT . "/tmp/logo_empresa.png"; $handle = fopen($file_path, 'wb'); if ($handle) { fwrite($handle, $content); fclose($handle); $attachments['logo'] = array( 'cid' => gen_id() . substr($task->getAssignedBy()->getEmailAddress(), strpos($task->getAssignedBy()->getEmailAddress(), '@')), 'path' => $file_path, 'type' => 'image/png', 'disposition' => 'inline', 'name' => 'logo_empresa.png', ); } } } catch (FileNotInRepositoryError $e) { unset($attachments['logo']); } tpl_assign('attachments', $attachments);// attachments //ALL SUBSCRIBERS if($task->getSubscribers()){ $subscribers = $task->getSubscribers(); $string_subscriber = ''; $total_s = count($subscribers); $c = 0; foreach ($subscribers as $subscriber){ $c++; if($c == $total_s && $total_s > 1){ $string_subscriber .= lang('and'); }else if($c > 1){ $string_subscriber .= ", "; } $string_subscriber .= $subscriber->getFirstName(); if($subscriber->getSurname() != "") $string_subscriber .=" " . $subscriber->getSurname(); } tpl_assign('subscribers', $string_subscriber);// subscribers } if($task->getAssignedById() == $task->getAssignedToContactId()){ $emails[] = array( "to" => array(self::prepareEmailAddress($task->getAssignedBy()->getEmailAddress(), $task->getAssignedBy()->getObjectName())), "from" => self::prepareEmailAddress($task->getUpdatedBy()->getEmailAddress(), $task->getUpdatedByDisplayName()), "subject" => lang('work estimate title'), "body" => tpl_fetch(get_template_path('work_estimate', 'notifier')), "attachments" => $attachments ); }else{ $emails[] = array( "to" => array(self::prepareEmailAddress($task->getAssignedBy()->getEmailAddress(), $task->getAssignedBy()->getObjectName())), "from" => self::prepareEmailAddress($task->getUpdatedBy()->getEmailAddress(), $task->getUpdatedByDisplayName()), "subject" => lang('work estimate title'), "body" => tpl_fetch(get_template_path('work_estimate', 'notifier')), "attachments" => $attachments ); $emails[] = array( "to" => array(self::prepareEmailAddress($task->getAssignedTo()->getEmailAddress(), $task->getAssignedTo()->getObjectName())), "from" => self::prepareEmailAddress($task->getUpdatedBy()->getEmailAddress(), $task->getUpdatedByDisplayName()), "subject" => lang('work estimate title'), "body" => tpl_fetch(get_template_path('work_estimate', 'notifier')), "attachments" => $attachments ); } self::queueEmails($emails); $locale = logged_user() instanceof Contact ? logged_user()->getLocale() : DEFAULT_LOCALIZATION; Localization::instance()->loadSettings($locale, ROOT . '/language'); }
/** * Return formated time * * @access public * @param DateTime $value If value is not instance of DateTime object new DateTime * object will be created with $value as its constructor param * @param string $format If $format is NULL default time format will be used * @param float $timezone Timezone, if NULL it will be autodetected (by currently logged user if we have it) * @return string */ function format_time($value = null, $format = null, $timezone = null) { if (is_null($timezone) && function_exists('logged_user') && logged_user() instanceof Contact) { $timezone = logged_user()->getTimezone(); } // if $datetime = $value instanceof DateTimeValue ? $value : new DateTimeValue($value); //if (!$format) $format = user_config_option('time_format_use_24') ? 'G:i' : 'g:i A'; if ($format) { $l = new Localization(); $l->setTimeFormat($format); } else { $l = Localization::instance(); } return $l->formatTime($datetime, $timezone); }
/** * Renders context help in a view, only if description_key is a valid lang. * If helpTemplate is null, default template is used * * @param $view View where the context help will be placed * @param string $description_key Key of the description to show, if not exists help will not be shown. * @param string $option_name * @param string $helpTemplate */ function render_context_help($view, $description_key, $option_name = null, $helpTemplate = null) { if ($view != null && $description_key != null && Localization::instance()->lang_exists($description_key)) { if ($option_name != null) { tpl_assign('option_name', $option_name); } if ($helpTemplate == null) { tpl_assign('helpDescription', lang($description_key)); } else { tpl_assign('helpTemplate', $helpTemplate); } $view->includeTemplate(get_template_path('context_help', 'help')); } }