function purge_trash() { Env::useHelper("permissions"); $days = config_option("days_on_trash", 0); $count = 0; if ($days > 0) { $date = DateTimeValueLib::now()->add("d", -$days); $objects = Objects::findAll(array("conditions" => array("`trashed_by_id` > 0 AND `trashed_on` < ?", $date), "limit" => 100)); foreach ($objects as $object) { $concrete_object = Objects::findObject($object->getId()); if (!$concrete_object instanceof ContentDataObject) { continue; } if ($concrete_object instanceof MailContent && $concrete_object->getIsDeleted() > 0) { continue; } try { DB::beginWork(); if ($concrete_object instanceof MailContent) { $concrete_object->delete(false); } else { $concrete_object->delete(); } ApplicationLogs::createLog($concrete_object, ApplicationLogs::ACTION_DELETE); DB::commit(); $count++; } catch (Exception $e) { DB::rollback(); Logger::log("Error delting object in purge_trash: " . $e->getMessage(), Logger::ERROR); } } } return $count; }
public function rebuild($start_date = null, $end_date = null) { if (!$start_date) { $start_date = config_option('last_sharing_table_rebuild'); } if ($start_date instanceof DateTimeValue) { $start_date = $start_date->toMySQL(); } if ($end_date instanceof DateTimeValue) { $end_date = $end_date->toMySQL(); } if ($end_date) { $end_cond = "AND updated_on <= '{$end_date}'"; } try { $object_ids = Objects::instance()->findAll(array('id' => true, "conditions" => "updated_on >= '{$start_date}' {$end_cond}")); $obj_count = 0; DB::beginWork(); foreach ($object_ids as $id) { $obj = Objects::findObject($id); if ($obj instanceof ContentDataObject) { $obj->addToSharingTable(); $obj_count++; } } set_config_option('last_sharing_table_rebuild', DateTimeValueLib::now()->toMySQL()); DB::commit(); } catch (Exception $e) { DB::rollback(); Logger::log("Failed to rebuild sharing table: " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString()); } return $obj_count; }
/** * Check if there is a new version of application available * * @param boolean $force When forced check will always construct the versions feed object * try to fech the data and check for a new version. Version feed object is also returned * @return VersionFeed In case of error this function will return false */ static function check($force = true) { $allow_url_fopen = strtolower(ini_get('allow_url_fopen')); if (function_exists('simplexml_load_file') && ($allow_url_fopen == '1' || $allow_url_fopen == 'on')) { // Execute once a day, if not forced check if we need to execute it now if (!$force) { if (config_option('upgrade_last_check_new_version', false)) { return true; // already have it checked and already have a new version } // if $last_check = config_option('upgrade_last_check_datetime'); if ($last_check instanceof DateTimeValue && $last_check->getTimestamp() + 86400 > DateTimeValueLib::now()->getTimestamp()) { return true; // checked in the last day } // if } // if try { $versions_feed = new VersionsFeed(); set_config_option('upgrade_last_check_datetime', DateTimeValueLib::now()); set_config_option('upgrade_last_check_new_version', $versions_feed->hasNewVersions(product_version())); return $force ? $versions_feed : true; } catch (Exception $e) { return false; } // try } else { set_config_option('upgrade_check_enabled', false); return false; } // if }
function cvs_total_task_times_table($objects, $pad_str, $options, $group_name, &$sub_total = 0) { echo lang('date') . ';'; echo lang('title') . ';'; echo lang('description') . ';'; echo lang('person') . ';'; echo lang('time') .'('.lang('hours').')'. ';'; echo "\n"; $sub_total = 0; foreach ($objects as $ts) { echo $pad_str . format_date($ts->getStartTime()) . ';'; $name = ($ts->getRelObjectId() == 0 ? $ts->getObjectName() : $ts->getRelObject()->getObjectName()); $name = str_replace("\r", " ", str_replace("\n", " ", str_replace("\r\n", " ", $name))); echo $name . ';'; $desc = $ts->getDescription(); $desc = str_replace("\r", " ", str_replace("\n", " ", str_replace("\r\n", " ", $desc))); $desc = '"'.$desc.'"'; echo $desc .';'; echo ($ts->getUser() instanceof Contact ? $ts->getUser()->getObjectName() : '') .';'; $lastStop = $ts->getEndTime() != null ? $ts->getEndTime() : ($ts->isPaused() ? $ts->getPausedOn() : DateTimeValueLib::now()); $mystring = DateTimeValue::FormatTimeDiff($ts->getStartTime(), $lastStop, "m", 60, $ts->getSubtract()); $resultado = ereg_replace("[^0-9]", "", $mystring); $resultado = round(($resultado/60),5); echo $resultado; $sub_total += $resultado; echo "\n"; } }
function getDueReminders($type = null) { if (isset($type)) { $extra = ' AND `type` = ' . DB::escape($type); } else { $extra = ""; } return ObjectReminders::findAll(array('conditions' => array("`date` > '0000-00-00 00:00:00' AND `date` < ?" . $extra, DateTimeValueLib::now()), 'limit' => config_option('cron reminder limit', 100))); }
/** * Returnst true if this application log was made yesterday * * @param void * @return boolean */ function isYesterday() { $created_on = $this->getCreatedOn(); if (!$created_on instanceof DateTimeValue) { return false; } $day_after = $created_on->advance(24 * 60 * 60, false); $now = DateTimeValueLib::now(); return $now->getDay() == $day_after->getDay() && $now->getMonth() == $day_after->getMonth() && $now->getYear() == $day_after->getYear(); }
/** * Return all users that was active in past $active_in minutes (defautl is 15 minutes) * * @access public * @param integer $active_in * @return array */ static function getWhoIsOnline($active_in = 15) { if ((int) $active_in < 1) { $active_in = 15; } $datetime = DateTimeValueLib::now(); $datetime->advance(-1 * $active_in * 60); return Users::findAll(array('conditions' => array('`last_activity` > ?', $datetime))); // findAll }
function total_task_times_print_table($objects, $left, $options, $group_name, &$sub_total = 0, &$sub_total_billing = 0, &$sub_total_estimated = 0) { echo '<div style="padding-left:' . $left . 'px;">'; echo '<table class="reporting-table"><tr class="reporting-table-heading">'; echo '<th>' . lang('date') . '</th>'; echo '<th>' . lang('title') . '</th>'; echo '<th>' . lang('description') . '</th>'; echo '<th>' . lang('person') . '</th>'; if (array_var($options, 'show_billing') == 'checked') { echo '<th class="right">' . lang('billing') . '</th>'; } echo '<th class="right">' . lang('time') . '</th>'; if ((array_var($options, 'timeslot_type') == 0 || array_var($options, 'timeslot_type') == 2) && array_var($options, 'show_estimated_time')) { echo '<th class="right">' . lang('estimated') . '</th>'; } echo '</tr>'; $sub_total = 0; $tasks = array(); $alt_cls = ""; foreach ($objects as $ts) { /* @var $ts Timeslot */ echo "<tr {$alt_cls}>"; echo "<td class='date'>" . format_date($ts->getStartTime()) . "</td>"; echo "<td class='name'>" . ($ts->getRelObjectId() == 0 ? clean($ts->getObjectName()) : clean($ts->getRelObject()->getObjectName())) . "</td>"; echo "<td class='name'>" . nl2br(clean($ts->getDescription())) . "</td>"; echo "<td class='person'>" . clean($ts->getUser() instanceof Contact ? $ts->getUser()->getObjectName() : '') . "</td>"; if (array_var($options, 'show_billing') == 'checked') { if ($ts->getIsFixedBilling()) { echo "<td class='nobr right'>" . config_option('currency_code', '$') . " " . number_format($ts->getFixedBilling(), 2) . "</td>"; $sub_total_billing += $ts->getFixedBilling(); } else { $min = $ts->getMinutes(); echo "<td class='nobr right'>" . config_option('currency_code', '$') . " " . number_format($ts->getHourlyBilling() / 60 * $min, 2) . "</td>"; $sub_total_billing += $ts->getHourlyBilling() / 60 * $min; } } $lastStop = $ts->getEndTime() != null ? $ts->getEndTime() : ($ts->isPaused() ? $ts->getPausedOn() : DateTimeValueLib::now()); echo "<td class='time nobr right'>" . DateTimeValue::FormatTimeDiff($ts->getStartTime(), $lastStop, "hm", 60, $ts->getSubtract()) . "</td>"; if ((array_var($options, 'timeslot_type') == 0 || array_var($options, 'timeslot_type') == 2) && $ts->getRelObject() instanceof ProjectTask && array_var($options, 'show_estimated_time')) { echo "<td class='time nobr right'>" . DateTimeValue::FormatTimeDiff(new DateTimeValue(0), new DateTimeValue($ts->getRelObject()->getTimeEstimate() * 60), 'hm', 60) . "</td>"; $task = $ts->getRelObject(); //check if I have the estimated time of this task if (!in_array($task->getId(), $tasks)) { $sub_total_estimated += $task->getTimeEstimate(); } $tasks[] = $task->getId(); } elseif ((array_var($options, 'timeslot_type') == 0 || array_var($options, 'timeslot_type') == 2) && array_var($options, 'show_estimated_time')) { echo "<td class='time nobr right'> 0 </td>"; } echo "</tr>"; $sub_total += $ts->getMinutes(); $alt_cls = $alt_cls == "" ? 'class="alt-row"' : ""; } echo '</table></div>'; }
function getDueEvents($date = null) { if (!$date instanceof DateTimeValue) { $date = DateTimeValueLib::now(); } $events = self::findAll(array('conditions' => array('`date` <= ?', $date))); if (!is_array($events)) { return array(); } return $events; }
function getDueEvents($date = null) { if (defined('REMOVE_AUTOLOADER_BEFORE_CRON') && REMOVE_AUTOLOADER_BEFORE_CRON) { @unlink(CACHE_DIR . "/autoloader.php"); } if (!$date instanceof DateTimeValue) { $date = DateTimeValueLib::now(); } $events = self::findAll(array('conditions' => array('`date` <= ?', $date))); if (!is_array($events)) { return array(); } return $events; }
/** * Return late tickets from active projects given user has access on. * * @param User $user * @return array or null */ function getOpenTicketsByUser(User $user) { $due_date = DateTimeValueLib::now()->beginningOfDay(); $projects = $user->getActiveProjects(); if (!is_array($projects) || !count($projects)) { return null; } $project_ids = array(); foreach ($projects as $project) { $project_ids[] = $project->getId(); } // foreach return self::findAll(array('conditions' => array('`closed_on` = ? AND `project_id` IN (?)', EMPTY_DATETIME, $project_ids), 'order' => '`priority`')); // findAll }
/** * Set cookie value * * @param string $name Variable name * @param mixed $value * @param integer $expiration Number of seconds from current time when this cookie need to expire * @return null */ static function setValue($name, $value, $expiration = null) { $expiration_time = DateTimeValueLib::now(); if ((int) $expiration > 0) { $expiration_time->advance($expiration); } else { $expiration_time->advance(3600); // one hour } // if $path = defined('COOKIE_PATH') ? COOKIE_PATH : '/'; $domain = defined('COOKIE_DOMAIN') ? COOKIE_DOMAIN : ''; $secure = defined('COOKIE_SECURE') ? COOKIE_SECURE : false; setcookie($name, $value, $expiration_time->getTimestamp(), $path, $domain, $secure); }
/** * Set cookie value * * @param string $name Variable name * @param mixed $value * @param integer $expiration Number of seconds from current time when this cookie need to expire * @return null */ static function setValue($name, $value, $expiration = null) { $expiration_time = DateTimeValueLib::now(); if ((int) $expiration > 0) { $expiration_time->advance($expiration); } else { $expiration_time->advance(3600); // one hour } // if // if $expiration is null, set the cookie to expire when the session is over $expiration_timestamp = is_null($expiration) ? null : $expiration_time->getTimestamp(); $path = defined('COOKIE_PATH') ? COOKIE_PATH : '/'; $domain = defined('COOKIE_DOMAIN') ? COOKIE_DOMAIN : ''; $secure = defined('COOKIE_SECURE') ? COOKIE_SECURE : false; setcookie($name, $value, $expiration_timestamp, $path, $domain, $secure); }
function purge_trash() { Env::useHelper("permissions"); $days = config_option("days_on_trash", 0); $count = 0; if ($days > 0) { $date = DateTimeValueLib::now()->add("d", -$days); $managers = array('Comments', 'Companies', 'Contacts', 'MailContents', 'ProjectCharts', 'ProjectEvents', 'ProjectFiles', 'ProjectFileRevisions', 'ProjectForms', 'ProjectMessages', 'ProjectMilestones', 'ProjectTasks', 'ProjectWebpages'); foreach ($managers as $manager_class) { $manager = new $manager_class(); $prevcount = -1; while ($prevcount != $count) { $prevcount = $count; if ($manager_class == 'MailContents') { $objects = $manager->findAll(array("include_trashed" => true, "conditions" => array("`trashed_by_id` > 0 AND `trashed_on` < ? AND `is_deleted` = 0", $date), "limit" => 100)); } else { $objects = $manager->findAll(array("include_trashed" => true, "conditions" => array("`trashed_by_id` > 0 AND `trashed_on` < ?", $date), "limit" => 100)); } if (is_array($objects)) { // delete one by one because each one knows what else to delete foreach ($objects as $o) { try { DB::beginWork(); $ws = $o->getWorkspaces(); if ($o instanceof MailContent) { $o->delete(false); } else { $o->delete(); } ApplicationLogs::createLog($o, $ws, ApplicationLogs::ACTION_DELETE); DB::commit(); $count++; } catch (Exception $e) { DB::rollback(); Logger::log("Error deleting object in purge_trash: " . $e->getMessage(), Logger::ERROR); } } } } } } return $count; }
function cvs_total_task_times_table($objects, $pad_str, $options, $group_name, &$sub_total = 0) { echo lang('date') . ';'; echo lang('title') . ';'; echo lang('description') . ';'; echo lang('person') . ';'; echo lang('time') . ';'; echo "\n"; $sub_total = 0; foreach ($objects as $ts) { echo $pad_str . format_date($ts->getStartTime()) . ';'; echo ($ts->getRelObjectId() == 0 ? clean($ts->getObjectName()) : clean($ts->getRelObject()->getObjectName())) . ';'; echo clean($ts->getDescription()) . ';'; echo clean($ts->getUser()->getObjectName()) . ';'; $lastStop = $ts->getEndTime() != null ? $ts->getEndTime() : ($ts->isPaused() ? $ts->getPausedOn() : DateTimeValueLib::now()); echo DateTimeValue::FormatTimeDiff($ts->getStartTime(), $lastStop, "hm", 60, $ts->getSubtract()) . ';'; $sub_total += $ts->getMinutes(); echo "\n"; } }
function formatted_date($css_class, $date, $label) { ?> <div class="<?php echo $css_class; ?> "> <span><?php echo lang('start date'); ?> :</span> <?php if ($date->getYear() > DateTimeValueLib::now()->getYear()) { echo format_date($date, null, 0); } else { echo format_descriptive_date($date, 0); } ?> </div> <?php }
function mail_on_page_load() { //check if have outbox mails $usu = logged_user(); $accounts = MailAccounts::instance()->getMailAccountsByUser($usu); $account_ids = array(); foreach ($accounts as $acc) { $account_ids[] = $acc->getId(); } if (count($account_ids) == 0) { return; } $accounts_sql = " AND account_id IN (" . implode(',', $account_ids) . ")"; $user_pg_ids = $usu->getPermissionGroupIds(); if (count($user_pg_ids) == 0) { return; } $permissions_sql = " AND EXISTS (SELECT sh.group_id FROM " . TABLE_PREFIX . "sharing_table sh WHERE sh.object_id=o.id AND sh.group_id IN (" . implode(',', $user_pg_ids) . "))"; $conditions = array("conditions" => array("`state` >= 200 AND (`state`%2 = 0) AND `archived_on`=0 AND `trashed_on`=0 {$accounts_sql} {$permissions_sql} AND `created_by_id` =" . $usu->getId())); $outbox_mails = MailContents::findAll($conditions); if ($outbox_mails != null) { if (count($outbox_mails) >= 1) { $arguments = array("conditions" => array("`context` LIKE 'mails_in_outbox%' AND `contact_id` = " . $usu->getId() . ";")); $exist_reminder = ObjectReminders::find($arguments); if (!(count($exist_reminder) > 0)) { $reminder = new ObjectReminder(); $minutes = 0; $reminder->setMinutesBefore($minutes); $reminder->setType("reminder_popup"); $reminder->setContext("mails_in_outbox " . count($outbox_mails)); $reminder->setObject($usu); $reminder->setUserId($usu->getId()); $reminder->setDate(DateTimeValueLib::now()); $reminder->save(); } } } }
/** * Return late tickets that are assigned to the user * * @param User $user * @param boolean $include_company includes tickets assigned to whole company * @return array */ function getLateTicketsByUser(User $user, $include_company = false) { $due_date = DateTimeValueLib::now()->beginningOfDay(); $projects = $user->getActiveProjects(); if (!is_array($projects) || !count($projects)) { return null; } // if $project_ids = array(); foreach ($projects as $project) { $project_ids[] = $project->getId(); } // foreach // TODO This request contains a hard-coded value for status. Might need to be changed // if ticket properties are made more generic if ($include_company) { return self::findAll(array('conditions' => array('(`assigned_to_user_id` = ? OR (`assigned_to_user_id` = ? AND `assigned_to_company_id` = ?)) AND `project_id` IN (?) AND `state` <> ?', $user->getId(), 0, $user->getCompanyId(), $project_ids, 'closed'), 'order' => '`state` ASC')); // findAll } else { return self::findAll(array('conditions' => array('`assigned_to_user_id` = ? AND `project_id` IN (?) AND `state` <> ?', $user->getId(), $project_ids, 'closed'), 'order' => '`state` ASC')); // findAll } // if }
/** * Return number of days that is left * * @access public * @param void * @return integer */ function getLeftInDays() { $due_date_start = $this->getDueDate()->endOfDay(); return floor(abs($due_date_start->getTimestamp() - DateTimeValueLib::now()->beginningOfDay()->getTimestamp()) / 86400); }
/** * Checck out file * * @param bool $autoCheckOut Is true when the file was automatically checked out on edit * @param User $user If null, logged user is used * @return boolean */ function checkOut($autoCheckOut = false, $user = null) { if (!$user) { $user = logged_user(); } if ($this->getCheckedOutById() != 0 && !$user->isAdministrator()) { return false; } $this->setWasAutoCheckedAuto($autoCheckOut); $this->setCheckedOutById($user->getId()); $this->setCheckedOutOn(DateTimeValueLib::now()); $this->setMarkTimestamps(false); $this->save(); return true; }
if ($milestone->getIsTemplate()) { add_page_action(lang('new milestone from template'), get_url("milestone", "copy_milestone", array("id" => $milestone->getId())), 'ico-copy'); } else { add_page_action(lang('copy milestone'), get_url("milestone", "copy_milestone", array("id" => $milestone->getId())), 'ico-copy'); if (can_manage_templates(logged_user())) { add_page_action(lang('add to a template'), get_url("template", "add_to", array("manager" => 'ProjectMilestones', "id" => $milestone->getId())), 'ico-template'); } } } ?> <div style="padding:7px"> <div class="milestone"> <?php $content = ''; if ($milestone->getDueDate()->getYear() > DateTimeValueLib::now()->getYear()) { $content = '<div class="dueDate"><b>' . lang('due date') . ':</b> ' . format_date($milestone->getDueDate(), null, 0) . '</div>'; } else { $content = '<div class="dueDate"><b>' . lang('due date') . ':</b> ' . format_descriptive_date($milestone->getDueDate(), 0) . '</div>'; } // if if ($milestone->getDescription()) { $content .= '<fieldset><legend>' . lang('description') . '</legend>' . escape_html_whitespace(convert_to_links(clean($milestone->getDescription()))) . '</fieldset>'; } $openSubtasks = $milestone->getOpenSubTasks(); if (is_array($openSubtasks)) { // $content .= '<p>' . lang('task lists') . ':</p><ul>'; //show open sub task list $content .= '<br/><table style="border:1px solid #717FA1;width:100%; padding-left:10px;"><tr><th style="padding-left:10px;padding-top:4px;padding-bottom:4px;background-color:#E8EDF7;font-size:120%;font-weight:bolder;color:#717FA1;width:100%;">' . lang("view open tasks") . '</th></tr><tr><td style="padding-left:10px;"> <div class="openTasks"> <table class="blank">';
function friendly_date(DateTimeValue $date, $timezone = null) { if ($timezone == null) { $timezone = logged_user()->getTimezone(); } //TODO: 7 days before: "Dom at 13:43", older: "Oct, 06 at 15:20" if ($date->isToday()) { $now = DateTimeValueLib::now(); $diff = DateTimeValueLib::get_time_difference($date->getTimestamp(), $now->getTimestamp()); if ($diff['hours'] == 0) { if ($diff['minutes'] >= 0) { return lang('minutes ago', $diff['minutes']); } else { return format_descriptive_date($date); } } else { if ($diff['hours'] > 0) { return lang('about hours ago', round($diff['hours'] + ($diff['minutes'] > 30 ? 1 : 0))); } else { return format_descriptive_date($date); } } } else { if ($date->isYesterday()) { return lang('yesterday at', format_time($date)); } else { $now = DateTimeValueLib::now(); $diff = DateTimeValueLib::get_time_difference($date->getTimestamp(), $now->getTimestamp()); if ($diff['days'] < 7) { return lang('day at', Localization::dateByLocalization("D", $date->getTimestamp()), format_time($date)); } else { if ($now->getYear() != $date->getYear()) { return lang('day at', Localization::dateByLocalization("M d, Y", $date->getTimestamp()), format_time($date)); } else { return lang('day at', Localization::dateByLocalization("M, d", $date->getTimestamp()), format_time($date)); } } } } }
/** * Handle files uploaded using helper forms. This function will return array of uploaded * files when finished * * @param string $files_var_prefix If value of this variable is set only elements in $_FILES * with key starting with $files_var_prefix will be handled * @return array */ static function handleHelperUploads($context, $files_var_prefix = null) { //FIXME return null; if (!isset($_FILES) || !is_array($_FILES) || !count($_FILES)) { return null; // no files to handle } $uploaded_files = array(); foreach ($_FILES as $uploaded_file_name => $uploaded_file) { if (trim($files_var_prefix) != '' && !str_starts_with($uploaded_file_name, $files_var_prefix)) { continue; } if (!isset($uploaded_file['name']) || !isset($uploaded_file['tmp_name']) || !is_file($uploaded_file['tmp_name'])) { continue; } $uploaded_files[$uploaded_file_name] = $uploaded_file; } if (!count($uploaded_file)) { return null; } $result = array(); // we'll put all files here $expiration_time = DateTimeValueLib::now()->advance(1800, false); foreach ($uploaded_files as $uploaded_file) { $file = new ProjectFile(); $file->setProjectId($project->getId()); $file->setFilename($uploaded_file['name']); $file->setIsVisible(false); $file->setExpirationTime($expiration_time); $file->save(); $file->handleUploadedFile($uploaded_file); // initial version $result[] = $file; } return count($result) ? $result : null; }
/** * This function will return true if this day is today * * @param void * @return boolean */ function isToday() { $today = DateTimeValueLib::now(); return $this->getDay() == $today->getDay() && $this->getMonth() == $today->getMonth() && $this->getYear() == $today->getYear(); }
/** * Complete specific milestone * * @access public * @param void * @return null */ function complete() { $milestone = ProjectMilestones::findById(get_id()); if (!$milestone instanceof ProjectMilestone) { flash_error(lang('milestone dnx')); $this->redirectTo('milestone'); } // if if (!$milestone->canChangeStatus(logged_user())) { flash_error(lang('no access permissions')); $this->redirectToReferer(get_url('milestone')); } // if try { $milestone->setCompletedOn(DateTimeValueLib::now()); $milestone->setCompletedById(logged_user()->getId()); DB::beginWork(); $milestone->save(); ApplicationLogs::createLog($milestone, active_project(), ApplicationLogs::ACTION_CLOSE); DB::commit(); flash_success(lang('success complete milestone', $milestone->getName())); } catch (Exception $e) { DB::rollback(); flash_error(lang('error complete milestone')); } // try $this->redirectToReferer($milestone->getViewUrl()); }
$status_filter = $userPreferences['status_filter']; $task_filter = $userPreferences['task_filter']; $user = Contacts::findById(array('id' => $user_filter)); if ($user == null) { $user = logged_user(); } $use_24_hours = user_config_option('time_format_use_24'); $date_format = user_config_option('date_format'); if ($use_24_hours) { $timeformat = 'G:i'; } else { $timeformat = 'g:i A'; } echo stylesheet_tag('event/day.css'); //today in gmt 0 $today = DateTimeValueLib::now(); //user today // $today->add('h', logged_user()->getTimezone()); $currentday = $today->format("j"); $currentmonth = $today->format("n"); $currentyear = $today->format("Y"); $drawHourLine = $day == $currentday && $month == $currentmonth && $year == $currentyear; $dtv = DateTimeValueLib::make(0, 0, 0, $month, $day, $year); $result = ProjectEvents::getDayProjectEvents($dtv, active_context(), $user_filter, $status_filter); if (!$result) { $result = array(); } $alldayevents = array(); $milestones = ProjectMilestones::getRangeMilestones($dtv, $dtv); if ($task_filter != "hide") { $tasks = ProjectTasks::getRangeTasksByUser($dtv, $dtv, $user_filter != -1 ? $user : null, $task_filter);
/** * Empty implementation of static method. Update tag permissions are check by the taggable * object, not tag itself * * @param User $user * @return boolean */ function canEdit(User $user) { $project = $this->getProject(); if (!$project instanceof Project || !$user->isProjectUser($this->getProject())) { return false; } // if $object = $this->getObject(); if ($object instanceof ProjectDataObject) { if ($user->isAdministrator()) { return true; } // if if (!$user->isMemberOfOwnerCompany() && $this->isPrivate()) { return false; // private object } // if $edit_limit = DateTimeValueLib::now(); $edit_limit->advance(180); if ($this->getCreatedById() == $user->getId() && $this->getCreatedOn()->getTimestamp() < $edit_limit->getTimestamp()) { return true; // author withing three minutes } // if } // if return false; }
</td> <td style="padding-right: 10px; width:140px;vertical-align:bottom"> <?php echo label_tag(lang('hours')) ?> </td> <td style="padding-right: 10px; width:140px;vertical-align:bottom"> <?php echo label_tag(lang('minutes')) ?> </td> <td style="padding-right: 10px; width:95%; margin-top: 0px;vertical-align:bottom"> <?php echo label_tag(lang('description')) ?> </td> <td style="padding-left: 10px;text-align:right; vertical-align: middle;"> </td> </tr> <tr> <td style="padding-right: 10px; width:140px;"> <?php echo pick_date_widget2('timeslot[date]', DateTimeValueLib::now(), $genid, 100, false) ?> </td> <td style="padding-right: 10px; width:140px;"> <?php $options = array(); foreach ($users as $user) { $options[] = option_tag($user->getObjectName(), $user->getId(), $selected_user == $user->getId() ? array("selected" => "selected") : null); } echo select_box("timeslot[contact_id]", $options, array('id' => $genid . 'tsUser', 'tabindex' => '150')); ?> </td> <td style="padding-right: 10px; width: 140px;"><?php echo text_field('timeslot[hours]', 0, array('style' => 'width:28px', 'tabindex' => '200', 'id' => $genid . 'tsHours','onkeypress'=>'og.checkEnterPress(event,\''.$genid.'\')')) ?> </td> <td style="padding-right: 10px; width: 140px;">
<div class="commentsTitle"><?php echo lang('latest activity'); ?> </div> <table style="min-width:400px;margin-top:10px;" class='dashActivity'> <tbody> <?php $isAlt = true; if (is_array($logs)) { foreach ($logs as $log) { //FIXME if ($log->getRelObjectManager() == 'Users' && $no_permissions) break; $isAlt = !$isAlt; echo '<tr' . ($isAlt ? ' class="dashAltRow"' : '') . '><td style="padding:5px;padding-right:15px;">'; if ($log->getCreatedOn()->getYear() != DateTimeValueLib::now()->getYear()) { $date = format_time($log->getCreatedOn(), "M d Y, H:i"); } else { if ($log->isToday()) { $date = lang('today') . format_time($log->getCreatedOn(), ", H:i:s"); } else { $date = format_time($log->getCreatedOn(), "M d, H:i"); } } /*FIXME if($log->getRelObjectManager() == 'Timeslots' && ($log->getAction()==ApplicationLogs::ACTION_OPEN || $log->getAction()==ApplicationLogs::ACTION_CLOSE)) echo $date . ' </td><td style="padding:5px;padding-right:15px;"> ' . $log->getText(); else*/ echo $date . ' </td><td style="padding:5px;padding-right:15px;"> ' . $log->getActivityData(); echo '</td></tr>'; } }
/** * 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; }