/**
  * chack if $content is spam
  *
  * @param string $content
  */
 function isSpam(&$content)
 {
     $tokens = Bayesian::getTokens($content);
     // if there is no tokens, email is most probably not spam
     if (!is_foreachable($tokens)) {
         return false;
     }
     // if
     $table_name = TABLE_PREFIX . BAYESIAN_TOKENS_TABLENAME;
     $total_count_ham = db_execute_one("SELECT count(*) as count FROM `{$table_name}` WHERE `type`='ham'");
     $total_count_ham = array_var($total_count_ham, 'count', 0);
     $total_count_spam = db_execute_one("SELECT count(*) as count FROM `{$table_name}` WHERE `type`='spam'");
     $total_count_spam = array_var($total_count_spam, 'count', 0);
     // there is no learning data
     if (!$total_count_ham || !$total_count_spam) {
     }
     // if
     $database_tokens = db_execute_all("SELECT * FROM `{$table_name}` WHERE `token` IN (" . implode(',', Bayesian::escapeTokens($tokens)) . ")");
     $probabilities = Bayesian::getIndividualProbabilities($tokens, $database_tokens, $total_count_ham, $total_count_spam);
     return Bayesian::getCombinedProbability($probabilities);
     // if we don't have good sample rate, we need to mark all $content as spam so we can learn something
     if ($count_ham + $count_spam < BAYESIAN_INITIAL_THRESHOLD && false) {
         return true;
     }
     // if
 }
/**
 * Render object assignees list
 *
 * @param array $params
 * @param Smarty $smarty
 * @return string
 */
function smarty_function_object_owner($params, &$smarty)
{
    $object = array_var($params, 'object');
    if (!instance_of($object, 'ProjectObject')) {
        return new InvalidParamError('object', $object, '$object is expected to be an instance of ProjectObject class', true);
    }
    // if
    $users_table = TABLE_PREFIX . 'users';
    $assignments_table = TABLE_PREFIX . 'assignments';
    $rows = db_execute_all("SELECT {$assignments_table}.is_owner AS is_assignment_owner, {$users_table}.id AS user_id, {$users_table}.company_id, {$users_table}.first_name, {$users_table}.last_name, {$users_table}.email FROM {$users_table}, {$assignments_table} WHERE {$users_table}.id = {$assignments_table}.user_id AND {$assignments_table}.object_id = ? and {$assignments_table}.is_owner='1' ORDER BY {$assignments_table}.is_owner DESC", $object->getId());
    if (is_foreachable($rows)) {
        $owner = null;
        foreach ($rows as $row) {
            if (empty($row['first_name']) && empty($row['last_name'])) {
                $user_link = '<a href="' . assemble_url('people_company', array('company_id' => $row['company_id'])) . '#user' . $row['user_id'] . '">' . clean($row['email']) . '</a>';
            } else {
                $user_link = '<a href="' . assemble_url('people_company', array('company_id' => $row['company_id'])) . '#user' . $row['user_id'] . '">' . clean($row['first_name']) . '</a>';
            }
            // if
            $owner .= $user_link . '&nbsp;';
        }
        // foreach
    }
    // if
    if (empty($owner)) {
        $owner = '--';
    }
    // if
    return $owner;
}
 /**
  * Return associative array with config option values by name and given 
  * company
  *
  * @param Company $company
  * @return array
  */
 function getValues($names, $company)
 {
     $result = array();
     // lets get option definition instances
     $options = ConfigOptions::findByNames($names, COMPANY_CONFIG_OPTION);
     if (is_foreachable($options)) {
         // Now we need all company specific values we can get
         $values = db_execute_all('SELECT name, value FROM ' . TABLE_PREFIX . 'company_config_options WHERE name IN (?) AND company_id = ?', $names, $company->getId());
         $foreachable = is_foreachable($values);
         // Populate result
         foreach ($options as $name => $option) {
             if ($foreachable) {
                 foreach ($values as $record) {
                     if ($record['name'] == $name) {
                         $result[$name] = trim($record['value']) != '' ? unserialize($record['value']) : null;
                         break;
                     }
                     // if
                 }
                 // foreach
             }
             // if
             if (!isset($result[$name])) {
                 $result[$name] = $option->getValue();
             }
             // if
         }
         // foreach
     }
     // if
     return $result;
 }
 /**
  * Execute report
  *
  * @param User $user
  * @param TimeReport $report
  * @param Project $project
  * @return array
  */
 function executeReport($user, $report, $project = null)
 {
     $conditions = $report->prepareConditions($user, $project);
     if (empty($conditions)) {
         return null;
     }
     // if
     if ($report->getSumByUser()) {
         $rows = db_execute_all('SELECT SUM(float_field_1) AS total_time, integer_field_1 AS user_id FROM ' . TABLE_PREFIX . 'project_objects WHERE ' . $conditions . ' GROUP BY integer_field_1');
         if (is_foreachable($rows)) {
             $result = array();
             foreach ($rows as $row) {
                 $user = Users::findById($row['user_id']);
                 if (instance_of($user, 'User')) {
                     $result[] = array('user' => $user, 'total_time' => float_format($row['total_time'], 2));
                 }
                 // if
             }
             // foreach
             return $result;
         } else {
             return null;
         }
         // if
     } else {
         return TimeRecords::findBySQL('SELECT * FROM ' . TABLE_PREFIX . 'project_objects WHERE ' . $conditions . ' ORDER BY date_field_1');
     }
     // if
 }
 /**
  * Return array of ticket changes
  *
  * @param Ticket $ticket
  * @param integer $count
  * @return array
  */
 function findByTicket($ticket, $count = null)
 {
     $count = (int) $count;
     if ($count < 1) {
         $rows = db_execute_all('SELECT * FROM ' . TABLE_PREFIX . 'ticket_changes WHERE ticket_id = ? ORDER BY version DESC', $ticket->getId());
     } else {
         $rows = db_execute_all('SELECT * FROM ' . TABLE_PREFIX . "ticket_changes WHERE ticket_id = ? ORDER BY version DESC LIMIT 0, {$count}", $ticket->getId());
     }
     // if
     if (is_foreachable($rows)) {
         $changes = array();
         foreach ($rows as $row) {
             $change = new TicketChange();
             $change->setTicketId($ticket->getId());
             $change->setVersion($row['version']);
             $change->changes = unserialize($row['changes']);
             $change->created_on = $row['created_on'] ? new DateTimeValue($row['created_on']) : null;
             $change->created_by_id = (int) $row['created_by_id'];
             $change->created_by_name = $row['created_by_name'];
             $change->created_by_email = $row['created_by_email'];
             $changes[$row['version']] = $change;
         }
         // foreach
         return $changes;
     } else {
         return null;
     }
     // if
 }
 /**
  * Return object of a specific class by SQL
  *
  * @param string $sql
  * @param array $arguments
  * @param boolean $one
  * @param string $table_name
  * @param string $item_class
  * @return array
  */
 function findBySQL($sql, $arguments = null, $one = false, $table_name = null, $item_class = null)
 {
     if ($arguments !== null) {
         $sql = db_prepare_string($sql, $arguments);
     }
     // if
     $rows = db_execute_all($sql);
     if (is_error($rows)) {
         return $rows;
     }
     // if
     if (!is_array($rows) || !count($rows)) {
         return null;
     }
     // if
     if ($one) {
         $item = new $item_class();
         $item->loadFromRow($rows[0], true);
         return $item;
     } else {
         $items = array();
         foreach ($rows as $row) {
             $item = new $item_class();
             $item->loadFromRow($row, true);
             $items[] = $item;
         }
         // foreach
         return count($items) ? $items : null;
     }
     // if
 }
/**
 * Render select project helper
 * 
 * Parametars:
 * 
 *  - value - Id of selected project
 *  - user - Limit only to projects that can be viewed by User
 *  - optional
 * 
 * @param void
 * @return null
 */
function smarty_function_select_project($params, &$smarty)
{
    $user = array_var($params, 'user', null, true);
    if (!instance_of($user, 'User')) {
        return new InvalidParamError('user', $user, '$user is expected to be an instance of User class', true);
    }
    // if
    $show_all = array_var($params, 'show_all', false) && $user->isProjectManager();
    $value = array_var($params, 'value', null, true);
    $projects_table = TABLE_PREFIX . 'projects';
    $project_users_table = TABLE_PREFIX . 'project_users';
    if ($show_all) {
        $projects = db_execute_all("SELECT {$projects_table}.id, {$projects_table}.name, {$projects_table}.status FROM {$projects_table} WHERE {$projects_table}.type = ? ORDER BY {$projects_table}.name", PROJECT_TYPE_NORMAL);
    } else {
        $projects = db_execute_all("SELECT {$projects_table}.id, {$projects_table}.name, {$projects_table}.status FROM {$projects_table}, {$project_users_table} WHERE {$project_users_table}.user_id = ? AND {$project_users_table}.project_id = {$projects_table}.id AND {$projects_table}.type = ? ORDER BY {$projects_table}.name", $user->getId(), PROJECT_TYPE_NORMAL);
    }
    // if
    $exclude = (array) array_var($params, 'exclude', array(), true);
    $active_options = array();
    $archived_options = array();
    if (is_foreachable($projects)) {
        foreach ($projects as $k => $project) {
            if (in_array($project['id'], $exclude)) {
                continue;
            }
            // if
            $option_attributes = $project['id'] == $value ? array('selected' => true) : null;
            if ($project['status'] == PROJECT_STATUS_ACTIVE) {
                $active_options[] = option_tag($project['name'], $project['id'], $option_attributes);
            } else {
                $archived_options[] = option_tag($project['name'], $project['id'], $option_attributes);
            }
            // if
        }
        // if
    }
    // if
    $optional = array_var($params, 'optional', false, true);
    $options = array();
    if ($optional) {
        $options[] = option_tag(lang(array_var($params, 'optional_caption', '-- Select Project --')), '');
        $options[] = option_tag('', '');
    }
    // if
    if (is_foreachable($active_options)) {
        $options[] = option_group_tag(lang('Active'), $active_options);
    }
    // if
    if (is_foreachable($active_options) && is_foreachable($archived_options)) {
        $options[] = option_tag('', '');
    }
    // if
    if (is_foreachable($archived_options)) {
        $options[] = option_group_tag(lang('Archive'), $archived_options);
    }
    // if
    return select_box($options, $params);
}
 /**
  * Render RSS feed for a spcific filter
  *
  * @param void
  * @return null
  */
 function rss()
 {
     if ($this->active_filter->isNew()) {
         $this->httpError(HTTP_ERR_NOT_FOUND);
     }
     // if
     if (!$this->active_filter->canUse($this->logged_user)) {
         $this->httpError(HTTP_ERR_FORBIDDEN);
     }
     // if
     require_once ANGIE_PATH . '/classes/feed/init.php';
     $feed = new Feed($this->owner_company->getName() . ' - ' . $this->active_filter->getName(), $this->active_filter->getUrl());
     $assignments = AssignmentFilters::executeFilter($this->logged_user, $this->active_filter, false);
     if (is_foreachable($assignments)) {
         $project_ids = array();
         foreach ($assignments as $assignment) {
             if (!in_array($assignment->getProjectId(), $project_ids)) {
                 $project_ids[] = $assignment->getProjectId();
             }
             // if
         }
         // foreach
         $projects = array();
         if (is_foreachable($project_ids)) {
             $rows = db_execute_all('SELECT id, name FROM ' . TABLE_PREFIX . 'projects WHERE id IN (?)', $project_ids);
             if (is_foreachable($rows)) {
                 foreach ($rows as $row) {
                     $projects[$row['id']] = $row['name'];
                 }
                 // foreach
             }
             // if
         }
         // if
         foreach ($assignments as $assignment) {
             $title = '[' . array_var($projects, $assignment->getProjectId()) . '] ' . $assignment->getVerboseType() . ' "' . $assignment->getName() . '"';
             $this->smarty->assign('_assignment', $assignment);
             $body = $this->smarty->fetch(get_template_path('_feed_body', 'assignment_filters', RESOURCES_MODULE));
             $item = new FeedItem($title, $assignment->getViewUrl(), $body, $assignment->getCreatedOn());
             $item->setId($assignment->getViewUrl());
             $feed->addItem($item);
         }
         // foreach
     }
     // if
     print render_rss_feed($feed);
     die;
 }
/**
 * Handle on_project_object_moved event
 *
 * @param ProjectObject $object
 * @param Project $source
 * @param Project $destination
 * @return null
 */
function resources_handle_on_project_object_moved(&$object, &$source, &$destination)
{
    if ($object->can_have_subscribers) {
        $subscribers = $object->getSubscribers();
        if (is_foreachable($subscribers)) {
            foreach ($subscribers as $subscriber) {
                if (!$subscriber->isProjectMember($destination)) {
                    Subscriptions::unsubscribe($subscriber, $object);
                }
                // if
            }
            // foreach
        }
        // if
    }
    // if
    $object_ids = array();
    // Relations with milestones are carried out via milestone_id field
    if (instance_of($object, 'Milestone')) {
        db_execute('UPDATE ' . TABLE_PREFIX . 'project_objects SET milestone_id = 0 WHERE milestone_id = ?', $object->getId());
    }
    // if
    $rows = db_execute_all('SELECT id FROM ' . TABLE_PREFIX . 'project_objects WHERE type IN (?) AND parent_id = ?', array('task', 'comment', 'attachment', 'timerecord'), $object->getId());
    if (is_foreachable($rows)) {
        foreach ($rows as $row) {
            $object_ids[] = (int) $row['id'];
        }
        // foreach
        // Sub-objects (attachments for comments, time records for tasks, tasks for tickets)
        $rows = db_execute_all('SELECT id FROM ' . TABLE_PREFIX . 'project_objects WHERE parent_id IN (?)', $object_ids);
        if (is_foreachable($rows)) {
            foreach ($rows as $row) {
                $object_ids[] = (int) $row['id'];
            }
            // foreach
        }
        // if
        // Update objects and activity logs
        db_execute('UPDATE ' . TABLE_PREFIX . 'project_objects SET project_id = ? WHERE id IN (?)', $destination->getId(), $object_ids);
        db_execute('UPDATE ' . TABLE_PREFIX . 'activity_logs SET project_id = ? WHERE object_id IN (?)', $destination->getId(), $object_ids);
        // Clear cache
        cache_remove_by_pattern(TABLE_PREFIX . 'activity_logs_id_*');
        cache_remove_by_pattern(TABLE_PREFIX . 'project_objects_id_*');
    }
    // if
}
 /**
  * Get all commits related to a project object
  *
  * @param integer $object_id
  * @return array
  */
 function findCommitsByObject($object)
 {
     $parent_object_ids = array();
     $parent_object_ids[] = $object->getId();
     /**
      * Try to find commits related to children objects
      */
     $task_ids = array();
     if (instance_of($object, 'Ticket')) {
         $tasks = db_execute_all("SELECT id FROM " . TABLE_PREFIX . "project_objects WHERE parent_id = " . $object->getid() . " AND `type` = 'Task'");
         if (is_foreachable($tasks)) {
             foreach ($tasks as $task) {
                 $task_ids[] = $task['id'];
             }
             // foreach
         }
         // if
     }
     // if
     $objects_ids = array_merge($parent_object_ids, $task_ids);
     $commit_project_objects = CommitProjectObjects::find(array('conditions' => array("object_id IN(" . implode(',', $objects_ids) . ")"), 'order' => 'repository_id ASC, revision DESC'));
     if (is_foreachable($commit_project_objects)) {
         $commits = array();
         $revisions = array();
         foreach ($commit_project_objects as $commit_project_object) {
             if (!in_array($commit_project_object->getRevision(), $revisions)) {
                 // prevent commits from showing more than once
                 $revisions[] = $commit_project_object->getRevision();
                 $commit = Commits::findByRevision($commit_project_object->getRevision(), Repositories::findById($commit_project_object->getRepositoryId()));
                 if (instance_of($commit, 'Commit')) {
                     $commit->repository = Repositories::findById($commit->getProjectId());
                     $commits[] = $commit;
                 }
                 // if
             }
             // if
         }
         // foreach
         return group_by_date($commits);
     } else {
         return false;
     }
     // if
 }
/**
 * Render object assignees list
 *
 * @param array $params
 * @param Smarty $smarty
 * @return string
 */
function smarty_function_object_owner_selector($params, &$smarty)
{
    $object = array_var($params, 'object');
    if (!instance_of($object, 'ProjectObject')) {
        return new InvalidParamError('object', $object, '$object is expected to be an instance of ProjectObject class', true);
    }
    // if
    $language = array_var($params, 'language', $smarty->get_template_vars('current_language'));
    // maybe we need to print this in a specific language?
    $users_table = TABLE_PREFIX . 'users';
    $assignments_table = TABLE_PREFIX . 'assignments';
    $owner_exists = false;
    $rows = db_execute_all("SELECT {$assignments_table}.is_owner AS is_assignment_owner, {$users_table}.id AS user_id, {$users_table}.company_id, {$users_table}.first_name, {$users_table}.last_name, {$users_table}.email FROM {$users_table}, {$assignments_table} WHERE {$users_table}.id = {$assignments_table}.user_id AND {$assignments_table}.object_id = ? ORDER BY {$assignments_table}.is_owner DESC", $object->getId());
    if (is_foreachable($rows)) {
        $owner = null;
        $other_assignees = array();
        $users_dropdown_for_tickets = '';
        foreach ($rows as $row) {
            if ($row['is_assignment_owner']) {
                $owner_exists = true;
            }
            if (empty($users_dropdown_for_tickets)) {
                $users_dropdown_for_tickets = '<select onchange="modify_responsible_status(this);">';
            }
            $users_dropdown_for_tickets .= '<option value="' . $row['user_id'] . '"' . ($row['is_assignment_owner'] ? ' selected ' : '') . '>';
            if (empty($row['first_name']) && empty($row['last_name'])) {
                $users_dropdown_for_tickets .= clean($row['email']);
            } else {
                $users_dropdown_for_tickets .= clean($row['first_name'] . ' ' . $row['last_name']);
            }
            $users_dropdown_for_tickets .= '</option>';
        }
        // foreach
    }
    if ($owner_exists) {
        $users_dropdown_for_tickets .= '</select>';
        $owner = $users_dropdown_for_tickets;
    } else {
        $owner = '--';
    }
    return $owner;
}
 /**
  * Return ID-s of projects pinned by a given user
  *
  * @param User $user
  * @return array
  */
 function findProjectIdsByUser($user, $use_cache = true)
 {
     if ($use_cache) {
         $cache_value = cache_get('user_pinned_projects_' . $user->getId());
         return is_array($cache_value) ? $cache_value : PinnedProjects::rebuildUserCache($user);
     } else {
         $projects_table = TABLE_PREFIX . 'projects';
         $pinned_projects_table = TABLE_PREFIX . 'pinned_projects';
         $ids = array();
         $rows = db_execute_all("SELECT {$projects_table}.id FROM {$projects_table}, {$pinned_projects_table} WHERE {$projects_table}.id = {$pinned_projects_table}.project_id AND {$pinned_projects_table}.user_id = ? AND {$projects_table}.type = ? ORDER BY {$projects_table}.name", $user->getId(), PROJECT_TYPE_NORMAL);
         if (is_foreachable($rows)) {
             foreach ($rows as $row) {
                 $ids[] = (int) $row['id'];
             }
             // foreach
         }
         // if
         return $ids;
     }
     // if
 }
 /**
  * Update time records
  * 
  * Move boolean_field_1 and boolean_field_2 into integer_field_1
  * 
  * - boolean_field_1 - is_billable
  * - boolean_field_2 - is_billed
  * - integer_field_2 - billable status
  *
  * @param void
  * @return boolean
  */
 function updateTimeRecords()
 {
     $rows = db_execute_all('SELECT id, boolean_field_1, boolean_field_2, integer_field_2 FROM ' . TABLE_PREFIX . 'project_objects WHERE type = ?', 'TimeRecord');
     if (is_foreachable($rows)) {
         foreach ($rows as $row) {
             if ($row['integer_field_2'] > 0) {
                 continue;
                 // in case we are running upgrade after some of the time records that use the new system are posted!
             }
             // if
             if ($row['boolean_field_1']) {
                 $new_status = $row['boolean_field_2'] ? 3 : 1;
             } else {
                 $new_status = 0;
             }
             // if
             db_execute('UPDATE ' . TABLE_PREFIX . 'project_objects SET integer_field_2 = ?, boolean_field_1 = NULL, boolean_field_2 = NULL WHERE id = ?', $new_status, $row['id']);
         }
         // foreach
     }
     // if
     return true;
 }
 /**
  * Copy project items into a destination project
  *
  * @param Project $to
  * @return null
  */
 function copyItems(&$to)
 {
     // Prepare time diff
     $source_starts_on = $this->getStartsOn();
     if (!instance_of($source_starts_on, 'DateValue')) {
         $source_starts_on = $this->getCreatedOn();
     }
     // if
     $target_starts_on = $to->getStartsOn();
     if (!instance_of($target_starts_on, 'DateValue')) {
         $target_starts_on = $to->getCreatedOn();
     }
     // if
     $diff = $target_starts_on->getTimestamp() - $source_starts_on->getTimestamp();
     // Migrate project users
     $project_users = ProjectUsers::findByProject($this);
     if (is_foreachable($project_users)) {
         foreach ($project_users as $project_user) {
             if ($to->getLeaderId() != $project_user->getUserId()) {
                 $user = $project_user->getUser();
                 if (instance_of($user, 'User')) {
                     $to->addUser($user, $project_user->getRole(), $project_user->getPermissions());
                 }
                 // if
             }
             // if
         }
         // foreach
     }
     // if
     // We need to move milestones in order to get milestones map
     $milestones_map = null;
     $milestones = Milestones::findAllByProject($this, VISIBILITY_PRIVATE);
     if (is_foreachable($milestones)) {
         $milestones_map = array();
         foreach ($milestones as $milestone) {
             $copied_milestone = $milestone->copyToProject($to);
             if (instance_of($copied_milestone, 'Milestone')) {
                 $copied_milestone->advance($diff, true);
                 $milestones_map[$milestone->getId()] = $copied_milestone;
             }
             // if
         }
         // foreach
     }
     // if
     // Now move categories
     $categories_map = null;
     $categories = Categories::findByProject($this);
     if (is_foreachable($categories)) {
         foreach ($categories as $category) {
             $copied_category = $category->copyToProject($to, null, null, false);
             if (instance_of($copied_category, 'Category')) {
                 $categories_map[$category->getId()] = $copied_category;
             }
             // if
         }
         // foreach
     }
     // if
     // Let the modules to their thing
     event_trigger('on_copy_project_items', array(&$this, &$to, $milestones_map, $categories_map));
     // Now, lets update due dates
     $completable_types = get_completable_project_object_types();
     if (is_foreachable($completable_types)) {
         foreach ($completable_types as $k => $type) {
             if (strtolower($type) == 'milestone') {
                 unset($completable_types[$k]);
             }
             // if
         }
         // foreach
         if (count($completable_types) > 0) {
             $rows = db_execute_all('SELECT id, due_on FROM ' . TABLE_PREFIX . 'project_objects WHERE project_id = ? AND type IN (?) AND due_on IS NOT NULL', $to->getId(), $completable_types);
             if (is_foreachable($rows)) {
                 foreach ($rows as $row) {
                     $id = (int) $row['id'];
                     $new_date = date(DATE_MYSQL, strtotime($row['due_on']) + $diff);
                     db_execute('UPDATE ' . TABLE_PREFIX . 'project_objects SET due_on = ? WHERE id = ?', $new_date, $id);
                     cache_remove("acx_project_objects_id_{$id}");
                 }
                 // foreach
             }
             // if
         }
         // if
     }
     // if
     // Refresh tasks count, just in case...
     $to->refreshTasksCount();
 }
 /**
  * Return ID-s of viewed objects for a given user
  *
  * @param User $user
  * @return array
  */
 function findViewedObjectIds($user)
 {
     $cache_id = 'object_viewed_by_' . $user->getId();
     $cached_value = array();
     $rows = db_execute_all('SELECT DISTINCT object_id FROM ' . TABLE_PREFIX . 'project_object_views WHERE created_by_id = ?', $user->getId());
     if (is_foreachable($rows)) {
         foreach ($rows as $row) {
             $cached_value[] = (int) $row['object_id'];
         }
         // foreach
     }
     // if
     cache_set($cache_id, $cached_value);
     return $cached_value;
 }
 /**
  * Reschedule this milestone
  *
  * @param DateValue $new_start_on
  * @param DateValue $new_due_on
  * @param boolean $reschedule_tasks
  * @return boolean
  */
 function reschedule($new_start_on, $new_due_on, $reschedule_tasks = false)
 {
     $errors = new ValidationErrors();
     if (!instance_of($new_start_on, 'DateValue')) {
         $errors->addError(lang('Start date is not valid'), 'start_on');
     }
     // if
     if (!instance_of($new_due_on, 'DateValue')) {
         $errors->addError(lang('Due date is not valid'), 'start_on');
     }
     // if
     if ($errors->hasErrors()) {
         return $errors;
     }
     // if
     $old_start_on = $this->getStartOn();
     $old_due_on = $this->getDueOn();
     //$this->setStartOn($new_start_on);
     $this->setStartOn(empty($new_start_on->timestamp) ? '' : $new_start_on);
     $this->setDueOn(empty($new_due_on->timestamp) ? '' : $new_due_on);
     $save = $this->save();
     if ($save && !is_error($save)) {
         if ($reschedule_tasks) {
             $diff_days = (int) ceil(($new_due_on->getTimestamp() - $old_due_on->getTimestamp()) / 86400);
             if ($diff_days != 0) {
                 $project_objects_table = TABLE_PREFIX . 'project_objects';
                 $completable_types = get_completable_project_object_types();
                 $rows = db_execute_all("SELECT id FROM {$project_objects_table} WHERE milestone_id = ? AND type IN (?)", $this->getId(), $completable_types);
                 if (is_foreachable($rows)) {
                     $related_object_ids = array();
                     foreach ($rows as $row) {
                         $related_object_ids[] = (int) $row['id'];
                     }
                     // foreach
                     db_execute("UPDATE {$project_objects_table} SET due_on = DATE_ADD(due_on, INTERVAL {$diff_days} DAY) WHERE (id IN (?) OR parent_id IN (?)) AND type IN (?)", $related_object_ids, $related_object_ids, $completable_types);
                 }
                 // if
             }
             // if
         }
         // if
     }
     // if
     return $save;
 }
/**
 * Render object assignees list
 *
 * @param array $params
 * @param Smarty $smarty
 * @return string
 */
function smarty_function_object_action_request($params, &$smarty)
{
    $object = array_var($params, 'object');
    if (!instance_of($object, 'ProjectObject')) {
        return new InvalidParamError('object', $object, '$object is expected to be an instance of ProjectObject class', true);
    }
    // if
    $user = array_var($params, 'user');
    $language = array_var($params, 'language', $smarty->get_template_vars('current_language'));
    // maybe we need to print this in a specific language?
    $users_table = TABLE_PREFIX . 'users';
    $assignments_table = TABLE_PREFIX . 'assignments';
    $action_request_table = TABLE_PREFIX . 'assignments_action_request';
    //BOF:task_1260
    /*
    //EOF:task_1260
    $action_request_user_id = '';
    //BOF:task_1260
    */
    $action_request_user_id = array();
    $resp = '';
    /*
    //EOF:task_1260
    $query = db_execute_all("select $action_request_table.user_id from $action_request_table where $action_request_table.object_id=? and is_action_request='1'", $object->getId());
    //BOF:task_1260
    */
    $query = db_execute_all("select distinct {$action_request_table}.user_id from {$action_request_table} inner join healingcrystals_project_objects on {$action_request_table}.comment_id=healingcrystals_project_objects.id where healingcrystals_project_objects.parent_id=? and {$action_request_table}.selected_by_user_id=? and is_action_request='1'", $object->getId(), $user->getId());
    //EOF:task_1260
    if (is_foreachable($query)) {
        foreach ($query as $entry) {
            //BOF:task_1260
            /*
            //EOF:task_1260
            $action_request_user_id = $entry['user_id'];
            //BOF:task_1260
            */
            $action_request_user_id[] = $entry['user_id'];
            //EOF:task_1260
        }
    }
    $rows = db_execute_all("SELECT {$assignments_table}.is_owner AS is_assignment_owner, {$users_table}.id AS user_id, {$users_table}.company_id, {$users_table}.first_name, {$users_table}.last_name, {$users_table}.email FROM {$users_table}, {$assignments_table} WHERE {$users_table}.id = {$assignments_table}.user_id AND {$assignments_table}.object_id = ? ORDER BY {$assignments_table}.is_owner DESC", $object->getId());
    if (is_foreachable($rows)) {
        //BOF:task_1260
        /*
        		//EOF:task_1260
        $users_dropdown_for_tickets = '';
        //BOF:task_1260
        */
        //EOF:task_1260
        foreach ($rows as $row) {
            //BOF:task_1260
            /*
            //EOF:task_1260
            if (empty($users_dropdown_for_tickets)){
            	        	$users_dropdown_for_tickets = '<select onchange="modify_action_request(this);">';
            	        	if (empty($action_request_user_id)){
            	        		$users_dropdown_for_tickets .= '<option value="0">-- Select --</option>';
            	        	}
            	        }
            	        $users_dropdown_for_tickets .= '<option value="' . $row['user_id'] . '"' . ($row['user_id']==$action_request_user_id ? ' selected ' : '') . '>';
                      	if(empty($row['first_name']) && empty($row['last_name'])) {
                        	$users_dropdown_for_tickets .= clean($row['email']);
                      	} else {
                        	$users_dropdown_for_tickets .= clean($row['first_name'] . ' ' . $row['last_name']);
                      	}
            	        $users_dropdown_for_tickets .= '</option>';
            //BOF:task_1260
            */
            if (in_array($row['user_id'], $action_request_user_id)) {
                if (empty($row['first_name']) && empty($row['last_name'])) {
                    $resp .= '<a href="' . assemble_url('project_people', array('project_id' => $object->getProjectId())) . '">' . clean($row['email']) . '</a>, ';
                } else {
                    $resp .= '<a href="' . assemble_url('project_people', array('project_id' => $object->getProjectId())) . '">' . clean($row['first_name'] . ' ' . $row['last_name']) . '</a>, ';
                }
            }
            //EOF:task_1260
        }
        // foreach
    }
    //BOF:task_1260
    /*
    	//EOF:task_1260
    if (!empty($users_dropdown_for_tickets)){
    	if (!empty($action_request_user_id)){
    		$users_dropdown_for_tickets .= '<option value="-1">Unset</option></select>';
    	}
    		$resp = $users_dropdown_for_tickets;
    } else {
    	$$resp = '--';
    }
    //BOF:task_1260
    */
    if (empty($resp)) {
        $resp = '--';
    } else {
        $resp = substr($resp, 0, -2);
    }
    //EOF:task_1260
    return $resp;
}
 /**
  * Create a new invoice
  *
  * @param void
  * @return null
  */
 function add()
 {
     $this->wireframe->print_button = false;
     if (!Invoice::canAdd($this->logged_user)) {
         $this->httpError(HTTP_ERR_FORBIDDEN);
     }
     // if
     $default_currency = Currencies::findDefault();
     if (!instance_of($default_currency, 'Currency')) {
         $this->httpError(HTTP_ERR_NOT_FOUND, 'Default currency not set');
     }
     // if
     $time_report = null;
     $project = null;
     $timerecord_ids = null;
     $invoice_data = $this->request->post('invoice');
     if (!is_array($invoice_data)) {
         $duplicate_invoice_id = $this->request->getId('duplicate_invoice_id');
         $time_report_id = $this->request->getId('time_report_id');
         $ticket_id = $this->request->getId('ticket_id');
         // ---------------------------------------------------
         //  Duplicate existing invoice
         // ---------------------------------------------------
         if ($duplicate_invoice_id) {
             $duplicate_invoice = Invoices::findById($duplicate_invoice_id);
             if (instance_of($duplicate_invoice, 'Invoice')) {
                 $invoice_data = array('company_id' => $duplicate_invoice->getCompanyId(), 'company_address' => $duplicate_invoice->getCompanyAddress(), 'comment' => $duplicate_invoice->getComment(), 'status' => INVOICE_STATUS_DRAFT, 'project_id' => $duplicate_invoice->getProjectId(), 'note' => $duplicate_invoice->getNote(), 'currency_id' => $duplicate_invoice->getCurrencyId());
                 if (is_foreachable($duplicate_invoice->getItems())) {
                     $invoice_data['items'] = array();
                     foreach ($duplicate_invoice->getItems() as $item) {
                         $invoice_data['items'][] = array('description' => $item->getDescription(), 'unit_cost' => $item->getUnitCost(), 'quantity' => $item->getQuantity(), 'tax_rate_id' => $item->getTaxRateId(), 'total' => $item->getTotal(), 'subtotal' => $item->getSubtotal());
                     }
                     // foreach
                 }
                 // if
             }
             // if
             // ---------------------------------------------------
             //  Create invoice from time report
             // ---------------------------------------------------
         } else {
             if ($time_report_id) {
                 $time_report = TimeReports::findById($time_report_id);
                 if (instance_of($time_report, 'TimeReport')) {
                     $project_id = $this->request->getId('project_id');
                     $client_company_id = null;
                     if ($project_id) {
                         $project = Projects::findById($project_id);
                     }
                     // if
                     $time_report->setBillableFilter(BILLABLE_FILTER_BILLABLE);
                     $conditions = $time_report->prepareConditions($this->logged_user, $project);
                     if ($conditions === false) {
                         $this->httpError(HTTP_ERR_OPERATION_FAILED, 'Failed to prepare time report conditions');
                     }
                     // if
                     $timerecord_ids = array();
                     $total_time = 0;
                     $project_objects_table = TABLE_PREFIX . 'project_objects';
                     $invoice_time_records_table = TABLE_PREFIX . 'invoice_time_records';
                     $rows = db_execute_all("SELECT DISTINCT id,float_field_1 FROM {$project_objects_table} WHERE {$conditions}");
                     if (is_foreachable($rows)) {
                         // find time records ids that needs to be attached to this invoice due to time record
                         foreach ($rows as $row) {
                             $timerecord_ids[] = (int) $row['id'];
                         }
                         // foreach
                         $timerecords_filtered = Invoices::filterAvailableTimerecords($timerecord_ids);
                         // calculate total time, but only if time record is not yet attached to the existing invoice
                         if (is_foreachable($rows) && is_foreachable($timerecord_ids)) {
                             foreach ($rows as $row) {
                                 if (!in_array($row['id'], $timerecord_ids)) {
                                     $total_time += (double) $row['float_field_1'];
                                 }
                                 // if
                             }
                             // foreach
                         }
                         // if
                     }
                     // if
                     if ($total_time == 0) {
                         $this->wireframe->addPageMessage(lang('You don\'t have any billable time records in this time report, or all bilable time records are already attached to existing invoice'), PAGE_MESSAGE_INFO);
                     } else {
                         if ($timerecords_filtered) {
                             $this->wireframe->addPageMessage(lang('One or more billable timerecords in this time report are already attached to the existing invoice. They won\'t be counted in this one'), PAGE_MESSAGE_INFO);
                         }
                     }
                     // if
                     if (count($timerecord_ids) && $total_time) {
                         if (instance_of($project, 'Project')) {
                             $description = lang('Total of :total hours in :project project', array('total' => $total_time, 'project' => $project->getName()));
                         } else {
                             $description = lang('Total of :total hours', array('total' => $total_time));
                         }
                         // if
                         $invoice_data = array('due_on' => new DateValue(), 'currency_id' => $default_currency->getId(), 'project_id' => instance_of($project, 'Project') ? $project->getId() : null, 'company_id' => instance_of($project, 'Project') ? $project->getCompanyId() : null, 'items' => array(array('description' => $description, 'unit_cost' => $default_currency->getDefaultRate(), 'quantity' => $total_time, 'subtotal' => $default_currency->getDefaultRate() * $total_time, 'total' => $default_currency->getDefaultRate() * $total_time, 'tax_rate_id' => null, 'time_record_ids' => $timerecord_ids)));
                     }
                     // if
                 }
                 // if
                 // ---------------------------------------------------
                 //  Create invoice from ticket
                 // ---------------------------------------------------
             } else {
                 if ($ticket_id) {
                     $ticket = Tickets::findById($ticket_id);
                     if (instance_of($ticket, 'Ticket')) {
                         $timerecords_filtered = false;
                         $items = array();
                         if ($ticket->getHasTime()) {
                             $timerecords = TimeRecords::findByParent($ticket, array(BILLABLE_STATUS_BILLABLE), STATE_VISIBLE, $this->logged_user->getVisibility());
                             $timerecord_ids = array();
                             $ticket_total_time = 0;
                             if (is_foreachable($timerecords)) {
                                 foreach ($timerecords as $timerecord) {
                                     if ($timerecord->getValue() > 0) {
                                         $timerecord_ids[] = $timerecord->getId();
                                     }
                                     // if
                                 }
                                 // foreach
                                 $timerecords_filtered = Invoices::filterAvailableTimerecords($timerecord_ids);
                                 foreach ($timerecords as $timerecord) {
                                     if (in_array($timerecord->getId(), $timerecord_ids)) {
                                         $ticket_total_time += $timerecord->getValue();
                                     }
                                     // if
                                 }
                                 // foreach
                                 $items[] = array('description' => lang('Ticket: :ticket_name', array('ticket_name' => $ticket->getName())), 'unit_cost' => $default_currency->getDefaultRate(), 'quantity' => $ticket_total_time, 'subtotal' => $default_currency->getDefaultRate() * $ticket_total_time, 'total' => $default_currency->getDefaultRate() * $ticket_total_time, 'tax_rate_id' => null, 'time_record_ids' => $timerecord_ids);
                             }
                             // if
                         }
                         // if
                         $tasks = $ticket->getTasks();
                         if (is_foreachable($tasks)) {
                             foreach ($tasks as $task) {
                                 if ($task->getHasTime()) {
                                     $timerecords = TimeRecords::findByParent($task, array(BILLABLE_STATUS_BILLABLE), STATE_VISIBLE, $this->logged_user->getVisibility());
                                     $task_total_time = 0;
                                     $timerecord_ids = array();
                                     if (is_foreachable($timerecords)) {
                                         foreach ($timerecords as $timerecord) {
                                             if ($timerecord->getValue() > 0) {
                                                 $timerecord_ids[] = $timerecord->getId();
                                             }
                                             // if
                                         }
                                         // foreach
                                         $timerecords_filtered = $timerecords_filtered || Invoices::filterAvailableTimerecords($timerecord_ids);
                                         foreach ($timerecords as $timerecord) {
                                             if (in_array($timerecord->getId(), $timerecord_ids)) {
                                                 $task_total_time += $timerecord->getValue();
                                             }
                                             // if
                                         }
                                         // foreach
                                         if (is_foreachable($timerecord_ids) && $task_total_time > 0) {
                                             $items[] = array('description' => lang('Task: :task_name', array('task_name' => $task->getName())), 'unit_cost' => $default_currency->getDefaultRate(), 'quantity' => $task_total_time, 'subtotal' => $default_currency->getDefaultRate() * $task_total_time, 'total' => $default_currency->getDefaultRate() * $task_total_time, 'tax_rate_id' => null, 'time_record_ids' => $timerecord_ids);
                                         }
                                         // if
                                     }
                                     // if
                                 }
                                 // if
                             }
                             // foreach
                         }
                         // if
                         $project = $ticket->getProject();
                         $invoice_data = array('due_on' => new DateValue(), 'currency_id' => $default_currency->getId(), 'project_id' => $ticket->getProjectId(), 'company_id' => instance_of($project, 'Project') ? $project->getCompanyId() : null, 'time_record_ids' => $timerecord_ids, 'items' => $items);
                         if ($timerecords_filtered) {
                             $this->wireframe->addPageMessage(lang('One or more billable timerecords in this time report are already attached to the existing invoice. They won\'t be counted in this one'), PAGE_MESSAGE_INFO);
                         }
                         // if
                     }
                     // if
                 }
             }
         }
         // if
         // ---------------------------------------------------
         //  Start blank
         // ---------------------------------------------------
         if (!is_array($invoice_data)) {
             $invoice_data = array('due_on' => new DateValue(), 'currency_id' => $default_currency->getId(), 'project_id' => instance_of($project, 'Project') ? $project->getId() : null, 'time_record_ids' => null);
         }
         // if
     }
     // if
     $invoice_notes = InvoiceNoteTemplates::findAll();
     $invoice_item_templates = InvoiceItemTemplates::findAll();
     $this->smarty->assign(array('invoice_data' => $invoice_data, 'tax_rates' => TaxRates::findAll(), 'invoice_notes' => $invoice_notes, 'invoice_item_templates' => $invoice_item_templates, 'original_note' => $this->active_invoice->getNote()));
     $cleaned_notes = array();
     if (is_foreachable($invoice_notes)) {
         foreach ($invoice_notes as $invoice_note) {
             $cleaned_notes[$invoice_note->getId()] = $invoice_note->getContent();
         }
         // foreach
     }
     // if
     js_assign('invoice_notes', $cleaned_notes);
     js_assign('original_note', $this->active_invoice->getNote());
     $cleaned_item_templates = array();
     if (is_foreachable($invoice_item_templates)) {
         foreach ($invoice_item_templates as $invoice_item_template) {
             $cleaned_item_templates[$invoice_item_template->getId()] = array('description' => $invoice_item_template->getDescription(), 'unit_cost' => $invoice_item_template->getUnitCost(), 'quantity' => $invoice_item_template->getQuantity(), 'tax_rate_id' => $invoice_item_template->getTaxRateId());
         }
         // foreach
     }
     // if
     js_assign('invoice_item_templates', $cleaned_item_templates);
     js_assign('company_details_url', assemble_url('invoice_company_details'));
     js_assign('move_icon_url', get_image_url('move.gif'));
     if ($this->request->isSubmitted()) {
         db_begin_work();
         $this->active_invoice->setAttributes($invoice_data);
         $this->active_invoice->setCreatedBy($this->logged_user);
         $invoice_company = Companies::findById(array_var($invoice_data, 'company_id', null));
         $this->active_invoice->setCompanyName($invoice_company->getName());
         $save = $this->active_invoice->save();
         if ($save && !is_error($save)) {
             $counter = 0;
             if (is_foreachable($invoice_data['items'])) {
                 foreach ($invoice_data['items'] as $invoice_item_data) {
                     $invoice_item = new InvoiceItem();
                     $invoice_item->setAttributes($invoice_item_data);
                     $invoice_item->setInvoiceId($this->active_invoice->getId());
                     $invoice_item->setPosition($counter + 1);
                     $item_save = $invoice_item->save();
                     if ($item_save && !is_error($item_save)) {
                         $invoice_item->setTimeRecordIds(array_var($invoice_item_data, 'time_record_ids'));
                         $counter++;
                     } else {
                         // error in invoice_item_data
                     }
                     // if
                 }
                 // foreach
             }
             // if
             if ($counter > 0) {
                 db_commit();
                 flash_success('Invoice ":number" has been created', array('number' => $this->active_invoice->getName()));
                 $this->redirectToUrl($this->active_invoice->getViewUrl());
             } else {
                 db_rollback();
                 $this->smarty->assign('errors', new ValidationErrors(array('items' => lang('Invoice items data is not valid. All descriptions are required and there need to be at least one unit with cost set per item!'))));
             }
             // if
         } else {
             db_rollback();
             $this->smarty->assign('errors', $save);
         }
         // if
     }
     // if
 }
function smarty_function_recurring_info($params, &$smarty)
{
    $object = array_var($params, 'object');
    if (!instance_of($object, 'ProjectObject')) {
        return new InvalidParamError('object', $object, '$object is expected to be an instance of ProjectObject', true);
    }
    $info = '';
    $sql = "select recurring_period, recurring_period_type, recurring_period_condition, recurring_end_date from healingcrystals_project_object_misc where object_id=?";
    $arguments = array($object->getId());
    $sql = db_prepare_string($sql, $arguments);
    $row = db_execute_all($sql);
    if (!empty($row)) {
        $entry = $row[0];
        $recurring_period = array_var($entry, 'recurring_period');
        $recurring_period_type = array_var($entry, 'recurring_period_type');
        $recurring_period_condition = array_var($entry, 'recurring_period_condition');
        $recurring_end_date = array_var($entry, 'recurring_end_date');
        if (!empty($recurring_period) && !empty($recurring_period_type) && $recurring_period_condition) {
            $info = 'Recurring every ' . $recurring_period . ' ';
            switch ($recurring_period_type) {
                case 'D':
                    $info .= ' day(s) ';
                    break;
                case 'W':
                    $info .= ' week(s) ';
                    break;
                case 'M':
                    $info .= ' month(s) ';
                    break;
            }
            switch ($recurring_period_condition) {
                case 'after_due_date':
                    $info .= 'after Task is Due';
                    break;
                case 'after_task_complete':
                    $info .= 'after Task has been Completed';
                    break;
            }
            $info = '<span class="recurring">' . $info . '</span>';
        }
    }
    return $info;
    if (instance_of($due_date, 'DateValue')) {
        require_once SMARTY_PATH . '/plugins/modifier.date.php';
        $date = smarty_modifier_date($due_date, 0);
        // just printing date, offset is 0!
        $reminder_string_begining = '';
        $reminder_string_end = '';
        $sql = "select auto_email_status, email_reminder_period, email_reminder_unit, email_reminder_time from healingcrystals_project_object_misc where object_id=?";
        $arguments = array($object->getId());
        $sql = db_prepare_string($sql, $arguments);
        $row = db_execute_all($sql);
        if (!empty($row)) {
            $entry = $row[0];
            $auto_email_status = array_var($entry, 'auto_email_status');
            $email_reminder_period = array_var($entry, 'email_reminder_period', '0');
            $email_reminder_unit = array_var($entry, 'email_reminder_unit', 'D');
            $email_reminder_time = array_var($entry, 'email_reminder_time', '06:00');
            $meridian = '';
            list($h, $m) = explode(':', $email_reminder_time);
            $h = (int) $h;
            if ($h > 12) {
                $h -= 12;
                $meridian = 'PM';
            } elseif ($h == 0) {
                $meridian = 'PM';
            } else {
                $meridian = 'AM';
            }
            $email_reminder_time = str_pad($h, 2, '0', STR_PAD_LEFT) . ':' . $m . ' ' . $meridian;
            $reminder_string_begining = 'Reminder set for ' . $email_reminder_period . ' ' . ($email_reminder_unit == 'D' ? 'Day(s)' : ($email_reminder_unit == 'W' ? 'Week(s)' : ($email_reminder_unit == 'M' ? 'Month(s)' : ''))) . " from Due Date: ";
            $reminder_string_end = " at " . $email_reminder_time;
        }
        if ($due_date->isToday($offset)) {
            if (!empty($reminder_string_begining)) {
                return '<span class="today">' . $reminder_string_begining . '<span class="number">' . lang('Today') . '</span>' . $reminder_string_end . '</span>';
            } else {
                return '<span class="today"><span class="number">' . lang('Due Today') . '</span></span>';
            }
        } elseif ($due_date->isYesterday($offset)) {
            if (!empty($reminder_string_begining)) {
                return '<span class="late" title="' . clean($date) . '">' . $reminder_string_begining . lang('<span class="number">1 Day Late</span>') . $reminder_string_end . '</span>';
            } else {
                return '<span class="late" title="' . clean($date) . '">' . lang('<span class="number">1 Day Late</span>') . '</span>';
            }
        } elseif ($due_date->isTomorrow($offset)) {
            if (!empty($reminder_string_begining)) {
                return '<span class="upcoming" title="' . clean($date) . '">' . $reminder_string_begining . '<span class="number">' . lang('Tomorrow') . '</span>' . $reminder_string_end . '</span>';
            } else {
                return '<span class="upcoming" title="' . clean($date) . '"><span class="number">' . lang('Due Tomorrow') . '</span></span>';
            }
        } else {
            $now = new DateTimeValue();
            $now->advance($offset);
            $now = $now->beginningOfDay();
            $due_date->beginningOfDay();
            if ($due_date->getTimestamp() > $now->getTimestamp()) {
                //return '<span class="upcoming" title="' . clean($date) . '">' . lang('Due in <span class="number">:days</span> Days', array('days' => floor(($due_date->getTimestamp() - $now->getTimestamp()) / 86400))) . '</span>';
                //return '<span class="upcoming" title="' . clean($date) . '">' . lang('<span class="number">:days</span> Days', array('days' => floor(($due_date->getTimestamp() - $now->getTimestamp()) / 86400))) . '</span>';
                if (!empty($reminder_string_begining)) {
                    return '<span class="upcoming" title="' . clean($date) . '">' . $reminder_string_begining . date('F d, Y', $due_date->getTimestamp()) . lang(' (<span class="number">:days</span> Days)', array('days' => floor(($due_date->getTimestamp() - $now->getTimestamp()) / 86400))) . $reminder_string_end . '</span>';
                } else {
                    return '<span class="upcoming" title="' . clean($date) . '">Due ' . date('F d, Y', $due_date->getTimestamp()) . lang(' (<span class="number">:days</span> Days)', array('days' => floor(($due_date->getTimestamp() - $now->getTimestamp()) / 86400))) . '</span>';
                }
            } else {
                //return '<span class="late" title="' . clean($date) . '">' . lang('<span class="number">:days</span> Days Late', array('days' => floor(($now->getTimestamp() - $due_date->getTimestamp()) / 86400))) . '</span>';
                if (!empty($reminder_string_begining)) {
                    return '<span class="late" title="' . clean($date) . '">' . $reminder_string_begining . date('F d, Y', $due_date->getTimestamp()) . lang(' (<span class="number">:days</span> Days Late)', array('days' => floor(($now->getTimestamp() - $due_date->getTimestamp()) / 86400))) . $reminder_string_end . '</span>';
                } else {
                    return '<span class="late" title="' . clean($date) . '">Due ' . date('F d, Y', $due_date->getTimestamp()) . lang(' (<span class="number">:days</span> Days Late)', array('days' => floor(($now->getTimestamp() - $due_date->getTimestamp()) / 86400))) . '</span>';
                }
            }
            // if
        }
        // if
    } else {
        //return lang('No Due Date');
        return lang('--');
    }
    // if
}
 /**
  * Return number of hours tracked for tasks attached to $object
  *
  * @param ProjectObject $object
  * @return float
  */
 function sumTasksTime($object)
 {
     $rows = db_execute_all('SELECT id FROM ' . TABLE_PREFIX . 'project_objects WHERE parent_id = ? AND type = ?', $object->getId(), 'Task');
     if (is_foreachable($rows)) {
         $task_ids = array();
         foreach ($rows as $row) {
             $task_ids[] = (int) $row['id'];
         }
         // foreach
         return (double) array_var(db_execute_one("SELECT SUM(float_field_1) AS 'time_sum' FROM " . TABLE_PREFIX . "project_objects WHERE parent_id IN (?) AND state >= ?", $task_ids, STATE_VISIBLE), 'time_sum');
     } else {
         return 0;
     }
     // if
 }
 /**
  * Return object of a specific class by SQL
  *
  * @param string $sql
  * @param array $arguments
  * @param boolean $one
  * @param string $table_name
  * @return array
  */
 function findBySQL($sql, $arguments = null, $one = false)
 {
     if ($arguments !== null) {
         $sql = db_prepare_string($sql, $arguments);
     }
     // if
     $rows = db_execute_all($sql);
     if (is_error($rows)) {
         return $rows;
     }
     // if
     if (!is_foreachable($rows)) {
         return null;
     }
     // if
     if ($one) {
         $row = $rows[0];
         $module_name = array_var($row, 'name');
         $module_class = Inflector::camelize($module_name) . 'Module';
         require_once APPLICATION_PATH . "/modules/{$module_name}/{$module_class}.class.php";
         $module = new $module_class();
         $module->loadFromRow($row);
         return $module;
     } else {
         $modules = array();
         foreach ($rows as $row) {
             $module_name = array_var($row, 'name');
             $module_class = Inflector::camelize($module_name) . 'Module';
             require_once APPLICATION_PATH . "/modules/{$module_name}/{$module_class}.class.php";
             $module = new $module_class();
             $module->loadFromRow($row);
             $modules[] = $module;
         }
         // foreach
         return count($module) ? $modules : null;
     }
     // if
 }
 /**
  * Return users by role, groupped by project
  *
  * @param Role $role
  * @return array
  */
 function findByRole($role)
 {
     $project_users_table = TABLE_PREFIX . 'project_users';
     $projects_table = TABLE_PREFIX . 'projects';
     $rows = db_execute_all("SELECT DISTINCT {$project_users_table}.project_id, {$project_users_table}.user_id FROM {$project_users_table}, {$projects_table} WHERE role_id = ? ORDER BY {$projects_table}.created_on", $role->getId());
     if (is_foreachable($rows)) {
         $result = array();
         foreach ($rows as $row) {
             $project_id = (int) $row['project_id'];
             $user_id = (int) $row['user_id'];
             if (!isset($result[$project_id])) {
                 $project = Projects::findById($project_id);
                 if (!instance_of($project, 'Project')) {
                     continue;
                 }
                 // if
                 $result[$project_id] = array('project' => $project, 'users' => array());
             }
             // if
             $user = Users::findById($user_id);
             if (instance_of($user, 'User')) {
                 $result[$project_id]['users'][] = $user;
             }
             // if
         }
         // foreach
         return $result;
     }
     // if
     return null;
 }
/**
 * Render object assignees list
 *
 * @param array $params
 * @param Smarty $smarty
 * @return string
 */
function smarty_function_object_assignees($params, &$smarty)
{
    $object = array_var($params, 'object');
    if (!instance_of($object, 'ProjectObject')) {
        return new InvalidParamError('object', $object, '$object is expected to be an instance of ProjectObject class', true);
    }
    // if
    $language = array_var($params, 'language', $smarty->get_template_vars('current_language'));
    // maybe we need to print this in a specific language?
    //BOF:mod 20121122
    /*
    //EOF:mod 20121122
        if(instance_of($language, 'Language')) {
          $cache_id = 'object_assignments_' . $object->getId() . '_rendered_' . $language->getId();
          $cached_value = cache_get($cache_id);
        } else {
    //BOF:mod 20121122
    */
    //EOF:mod 20121122
    $cache_id = null;
    $cached_value = null;
    //BOF:mod 20121122
    /*
    //EOF:mod 20121122
        } // if
    //BOF:mod 20121122
    */
    //EOF:mod 20121122
    //if($cached_value) {
    // return $cached_value;
    //} else {
    $users_table = TABLE_PREFIX . 'users';
    $assignments_table = TABLE_PREFIX . 'assignments';
    $rows = db_execute_all("SELECT {$assignments_table}.is_owner AS is_assignment_owner, {$users_table}.id AS user_id, {$users_table}.company_id, {$users_table}.first_name, {$users_table}.last_name, {$users_table}.email FROM {$users_table}, {$assignments_table} WHERE {$users_table}.id = {$assignments_table}.user_id AND {$assignments_table}.object_id = ? ORDER BY {$assignments_table}.is_owner DESC", $object->getId());
    if (is_foreachable($rows)) {
        $owner = null;
        $other_assignees = array();
        $users_dropdown_for_tickets = '';
        foreach ($rows as $row) {
            if (empty($row['first_name']) && empty($row['last_name'])) {
                //$user_link = '<a href="' . assemble_url('people_company', array('company_id' => $row['company_id'])) . '#user' . $row['user_id'] . '">' . clean($row['email'])  . '</a>';
                $user_link = '<a href="' . assemble_url('project_people', array('project_id' => $object->getProjectId())) . '">' . clean($row['email']) . '</a>';
            } else {
                //$user_link = '<a href="' . assemble_url('people_company', array('company_id' => $row['company_id'])) . '#user' . $row['user_id'] . '">' . clean($row['first_name'] . ' ' . $row['last_name'])  . '</a>';
                $user_link = '<a href="' . assemble_url('project_people', array('project_id' => $object->getProjectId())) . '">' . clean($row['first_name'] . ' ' . $row['last_name']) . '</a>';
            }
            // if
            if ($row['is_assignment_owner']) {
                //if(!instance_of($object, 'Ticket')) {
                $owner = $user_link;
                //}
            } else {
                $other_assignees[] = $user_link;
            }
            // if
            /*
            if(instance_of($object, 'Ticket')) {
            	        if (empty($users_dropdown_for_tickets)){
            	        	$users_dropdown_for_tickets = '<select onchange="modify_responsible_status(this);">';
            	        }
            	        $users_dropdown_for_tickets .= '<option value="' . $row['user_id'] . '"' . ($row['is_assignment_owner'] ? ' selected ' : '') . '>';
            	if(empty($row['first_name']) && empty($row['last_name'])) {
              	$users_dropdown_for_tickets .= clean($row['email']);
            	} else {
              	$users_dropdown_for_tickets .= clean($row['first_name'] . ' ' . $row['last_name']);
            	}
            	        $users_dropdown_for_tickets .= '</option>';
            }
            */
        }
        // foreach
        /*
        if (!empty($users_dropdown_for_tickets)){
        	$users_dropdown_for_tickets .= '</select>';
        	$owner = $users_dropdown_for_tickets;
        }
        */
        if ($owner) {
            if (instance_of($object, 'Ticket')) {
                $popup_url = assemble_url('responsible_status_popup', array('project_id' => $object->getProjectId(), 'ticket_id' => $object->getTicketId()));
                if (count($other_assignees) > 0) {
                    //$cached_value = $owner . ' is <a href="' . $popup_url . '" id="is_responsible" href_="' . assemble_url('project_ticket_edit', array('project_id' => $object->getProjectId(), 'ticket_id' => $object->getTicketId())) . '">responsible</a>. ' . lang('Other assignees', null, true, $language) . ': ' . implode(', ', $other_assignees) . '.';
                    //$cached_value = 'Owner: ' .  $owner . '<br/>' . lang('Assignees: ', null, true, $language) . ': ' . implode(', ', $other_assignees);
                    $cached_value = $owner;
                    if (!empty($cached_value)) {
                        $cached_value .= ', ';
                    }
                    $cached_value .= implode(', ', $other_assignees);
                } else {
                    //$cached_value = $owner . ' is <a href="' . $popup_url . '" id="is_responsible" href_="' . assemble_url('project_ticket_edit', array('project_id' => $object->getProjectId(), 'ticket_id' => $object->getTicketId())) . '">responsible</a>.';
                    //$cached_value = 'Owner: ' . $owner;
                    $cached_value = $owner;
                }
                // if
            } else {
                if (count($other_assignees) > 0) {
                    $cached_value = $owner . ' ' . lang('is responsible', null, true, $language) . '. ' . lang('Other assignees', null, true, $language) . ': ' . implode(', ', $other_assignees) . '.';
                } else {
                    $cached_value = $owner . ' ' . lang('is responsible', null, true, $language) . '.';
                }
                // if
            }
        }
        // if
    }
    // if
    //BOF:mod 20121122
    /*
    //EOF:mod 20121122      
          if(empty($cached_value)) {
            $cached_value = lang('Anyone can pick and complete this task', null, true, $language);
          } // if
    //BOF:mod 20121122
    */
    //EOF:mod 20121122
    if (instance_of($language, 'Language') && $cache_id) {
        cache_set($cache_id, $cached_value);
        // cache if we don't have language parameter set
    }
    // if
    return $cached_value;
    //} // if
}
 /**
  * Return paginated status updates for user ids
  *
  * @param array $user_ids
  * @param integer $page
  * @param integer $per_page
  * @return array
  */
 function paginateByUserIds($user_ids = null, $page = 1, $per_page = 30)
 {
     $status_updates_table = TABLE_PREFIX . 'status_updates';
     $status_update_ids = array();
     $rows = db_execute_all("SELECT id, parent_id FROM {$status_updates_table} WHERE created_by_id IN (?)", $user_ids);
     if (is_foreachable($rows)) {
         foreach ($rows as $row) {
             if ($row['parent_id'] == 0) {
                 $status_update_ids[] = (int) $row['id'];
             } else {
                 $parent_id = (int) $row['parent_id'];
                 if (!in_array($parent_id, $status_update_ids)) {
                     $status_update_ids[] = $parent_id;
                 }
                 // if
             }
             // if
         }
         // foreach
     }
     // if
     return StatusUpdates::paginate(array('conditions' => array('id IN (?)', $status_update_ids), 'order' => 'last_update_on DESC'), $page, $per_page);
 }
 /**
  * Return ID => name map
  *
  * @param void
  * @return array
  */
 function getIdNameMap($ids = null)
 {
     // No ID-s
     if ($ids === null) {
         $cached_value = cache_get('companies_id_name');
         if ($cached_value) {
             return $cached_value;
         } else {
             $result = array();
             $rows = db_execute_all('SELECT id, name FROM ' . TABLE_PREFIX . 'companies ORDER BY is_owner DESC, name');
             if (is_foreachable($rows)) {
                 foreach ($rows as $row) {
                     $result[(int) $row['id']] = $row['name'];
                 }
                 // foreach
             }
             // if
             cache_set('companies_id_name', $result);
             return $result;
         }
         // if
         // We have ID-s
     } else {
         $result = array();
         if (is_foreachable($ids)) {
             $rows = db_execute_all('SELECT id, name FROM ' . TABLE_PREFIX . 'companies WHERE id IN (?) ORDER BY is_owner DESC, name', $ids);
             if (is_foreachable($rows)) {
                 foreach ($rows as $row) {
                     $result[(int) $row['id']] = $row['name'];
                 }
                 // foreach
             }
             // if
         }
         // if
         return $result;
     }
     // if
 }
 /**
  * Return projects visible for $user that have $company for client
  *
  * @param User $user
  * @param Company $company
  * @param boolean $all_for_admins_and_pms
  * @return array
  */
 function findByUserAndCompany($user, $company, $all_for_admins_and_pms = false)
 {
     if (!instance_of($user, 'User')) {
         return null;
     }
     // if
     if (instance_of($company, 'Company')) {
         $company_id = $company->getIsOwner() ? 0 : $company->getId();
     } else {
         return null;
     }
     // if
     // Admin or project manager
     if ($all_for_admins_and_pms && ($user->isProjectManager() || $user->isAdministrator())) {
         return Projects::find(array('conditions' => array('company_id = ?', $company_id), 'order' => 'name'));
     }
     // if
     // Clients and other members
     $rows = db_execute_all('SELECT project_id FROM ' . TABLE_PREFIX . 'project_users WHERE user_id = ?', $user->getId());
     if (is_foreachable($rows)) {
         $project_ids = array();
         foreach ($rows as $row) {
             $project_ids[] = (int) $row['project_id'];
         }
         // if
     } else {
         return null;
     }
     // if
     return Projects::find(array('conditions' => array('id IN (?) AND company_id = ?', $project_ids, $company_id), 'order' => 'name'));
 }
 /**
  * Find sums of payments by $company_ids (company_id => currency => sum)
  *
  * @param array $company_ids
  * @param array $statuses
  */
 function sumsByCompanies($company_ids, $statuses)
 {
     $payments_table = TABLE_PREFIX . 'invoice_payments';
     $invoices_table = TABLE_PREFIX . 'invoices';
     $currency_table = TABLE_PREFIX . 'currencies';
     $sums = db_execute_all("SELECT SUM({$payments_table}.amount) AS 'sum',{$invoices_table}.company_id AS 'company_id', {$currency_table}.code AS 'currency' FROM {$payments_table}, {$invoices_table}, {$currency_table} WHERE {$payments_table}.invoice_id = {$invoices_table}.id AND {$invoices_table}.company_id IN (?) AND {$invoices_table}.status IN (?) AND {$currency_table}.id = {$invoices_table}.currency_id GROUP BY {$invoices_table}.company_id, currency", $company_ids, $statuses);
     if (!is_foreachable($sums)) {
         return null;
     }
     // if
     $formatted_sums = array();
     foreach ($sums as $sum) {
         $formatted_sums[$sum['company_id']][$sum['currency']] = $sum['sum'];
     }
     // foreach
     return $formatted_sums;
 }
 /**
  * Return array of related time record ID-s
  *
  * @param void
  * @return array
  */
 function getTimeRecordIds()
 {
     if ($this->time_record_ids === false) {
         $rows = db_execute_all('SELECT time_record_id FROM ' . TABLE_PREFIX . 'invoice_time_records WHERE invoice_id = ?', $this->getId());
         if (is_foreachable($rows)) {
             $this->time_record_ids = array();
             foreach ($rows as $row) {
                 $this->time_record_ids[] = (int) $row['time_record_id'];
             }
             // foreach
         } else {
             $this->time_record_ids = null;
         }
         // if
     }
     // if
     return $this->time_record_ids;
 }
/**
 * Print due on string (due in, due today or late) for a given object
 *
 * @param array $params
 * @param Smarty $smarty
 * @return string
 */
function smarty_function_due($params, &$smarty)
{
    $object = array_var($params, 'object');
    $due_date = null;
    if (instance_of($object, 'ProjectObject')) {
        if ($object->can_be_completed) {
            if ($object->isCompleted()) {
                return lang('Completed');
            }
            // if
            $due_date = $object->getDueOn();
        } else {
            return '--';
        }
        // if
    } elseif (instance_of($object, 'Invoice')) {
        if ($object->getStatus() == INVOICE_STATUS_ISSUED) {
            $due_date = $object->getDueOn();
        } else {
            return '--';
        }
        // if
    } else {
        return new InvalidParamError('object', $object, '$object is not expected to be an instance of ProjectObject or Invoice class', true);
    }
    // if
    $offset = get_user_gmt_offset();
    if (instance_of($due_date, 'DateValue')) {
        require_once SMARTY_PATH . '/plugins/modifier.date.php';
        $date = smarty_modifier_date($due_date, 0);
        // just printing date, offset is 0!
        $reminder_string_begining = '';
        $reminder_string_end = '';
        $sql = "select auto_email_status, email_reminder_period, email_reminder_unit, email_reminder_time from healingcrystals_project_object_misc where object_id=? and auto_email_status='1'";
        $arguments = array($object->getId());
        $sql = db_prepare_string($sql, $arguments);
        $row = db_execute_all($sql);
        if (!empty($row)) {
            $entry = $row[0];
            $auto_email_status = array_var($entry, 'auto_email_status');
            $email_reminder_period = array_var($entry, 'email_reminder_period', '0');
            $email_reminder_unit = array_var($entry, 'email_reminder_unit', 'D');
            $email_reminder_time = array_var($entry, 'email_reminder_time', '06:00');
            $meridian = '';
            list($h, $m) = explode(':', $email_reminder_time);
            $h = (int) $h;
            if ($h > 12) {
                $h -= 12;
                $meridian = 'PM';
            } elseif ($h == 12) {
                $meridian = 'PM';
            } elseif ($h == 0) {
                $meridian = 'AM';
            } else {
                $meridian = 'AM';
            }
            $email_reminder_time = str_pad($h, 2, '0', STR_PAD_LEFT) . ':' . $m . ' ' . $meridian;
            $reminder_string_begining = 'Reminder set for ' . $email_reminder_period . ' ' . ($email_reminder_unit == 'D' ? 'Day(s)' : ($email_reminder_unit == 'W' ? 'Week(s)' : ($email_reminder_unit == 'M' ? 'Month(s)' : ''))) . " from Due Date: ";
            $reminder_string_end = " at " . $email_reminder_time;
        }
        if ($due_date->isToday($offset)) {
            if (!empty($reminder_string_begining)) {
                return '<span class="today">' . $reminder_string_begining . '<span class="number">' . lang('Today') . '</span>' . $reminder_string_end . '</span>';
            } else {
                return '<span class="today"><span class="number">' . lang('Due Today') . '</span></span>';
            }
        } elseif ($due_date->isYesterday($offset)) {
            if (!empty($reminder_string_begining)) {
                return '<span class="late" title="' . clean($date) . '">' . $reminder_string_begining . lang('<span class="number">1 Day Late</span>') . $reminder_string_end . '</span>';
            } else {
                return '<span class="late" title="' . clean($date) . '">' . lang('<span class="number">1 Day Late</span>') . '</span>';
            }
        } elseif ($due_date->isTomorrow($offset)) {
            if (!empty($reminder_string_begining)) {
                return '<span class="upcoming" title="' . clean($date) . '">' . $reminder_string_begining . '<span class="number">' . lang('Tomorrow') . '</span>' . $reminder_string_end . '</span>';
            } else {
                return '<span class="upcoming" title="' . clean($date) . '"><span class="number">' . lang('Due Tomorrow') . '</span></span>';
            }
        } else {
            $now = new DateTimeValue();
            $now->advance($offset);
            $now = $now->beginningOfDay();
            $due_date->beginningOfDay();
            if ($due_date->getTimestamp() > $now->getTimestamp()) {
                //return '<span class="upcoming" title="' . clean($date) . '">' . lang('Due in <span class="number">:days</span> Days', array('days' => floor(($due_date->getTimestamp() - $now->getTimestamp()) / 86400))) . '</span>';
                //return '<span class="upcoming" title="' . clean($date) . '">' . lang('<span class="number">:days</span> Days', array('days' => floor(($due_date->getTimestamp() - $now->getTimestamp()) / 86400))) . '</span>';
                if (!empty($reminder_string_begining)) {
                    return '<span class="upcoming" title="' . clean($date) . '">' . $reminder_string_begining . date('F d, Y', $due_date->getTimestamp()) . lang(' (<span class="number">:days</span> Days)', array('days' => floor(($due_date->getTimestamp() - $now->getTimestamp()) / 86400))) . $reminder_string_end . '</span>';
                } else {
                    return '<span class="upcoming" title="' . clean($date) . '">Due ' . date('F d, Y', $due_date->getTimestamp()) . lang(' (<span class="number">:days</span> Days)', array('days' => floor(($due_date->getTimestamp() - $now->getTimestamp()) / 86400))) . '</span>';
                }
            } else {
                //return '<span class="late" title="' . clean($date) . '">' . lang('<span class="number">:days</span> Days Late', array('days' => floor(($now->getTimestamp() - $due_date->getTimestamp()) / 86400))) . '</span>';
                if (!empty($reminder_string_begining)) {
                    return '<span class="late" title="' . clean($date) . '">' . $reminder_string_begining . date('F d, Y', $due_date->getTimestamp()) . lang(' (<span class="number">:days</span> Days Late)', array('days' => floor(($now->getTimestamp() - $due_date->getTimestamp()) / 86400))) . $reminder_string_end . '</span>';
                } else {
                    return '<span class="late" title="' . clean($date) . '">Due ' . date('F d, Y', $due_date->getTimestamp()) . lang(' (<span class="number">:days</span> Days Late)', array('days' => floor(($now->getTimestamp() - $due_date->getTimestamp()) / 86400))) . '</span>';
                }
            }
            // if
        }
        // if
    } else {
        //return lang('No Due Date');
        return lang('--');
    }
    // if
}
/**
 * Set page properties with following object
 *
 * Parameters:
 *
 * - object - Application object instance
 *
 * @param array $params
 * @param Smarty $smarty
 * @return null
 */
function smarty_function_page_object($params, &$smarty)
{
    static $private_roles = false;
    $object = array_var($params, 'object');
    if (!instance_of($object, 'ApplicationObject')) {
        return new InvalidParamError('object', $object, '$object is expected to be an instance of ApplicationObject class', true);
    }
    // if
    require_once SMARTY_DIR . '/plugins/modifier.datetime.php';
    $wireframe =& Wireframe::instance();
    $logged_user =& get_logged_user();
    $construction =& PageConstruction::instance();
    if ($construction->page_title == '') {
        $construction->setPageTitle($object->getName());
    }
    // if
    if (instance_of($object, 'ProjectObject') && $wireframe->details == '') {
        $in = $object->getParent();
        $created_on = $object->getCreatedOn();
        $created_by = $object->getCreatedBy();
        if (instance_of($created_by, 'User') && instance_of($in, 'ApplicationObject') && instance_of($created_on, 'DateValue')) {
            //BOF:mod 20120913
            /*
            //EOF:mod 20120913
            $wireframe->details = lang('By <a href=":by_url">:by_name</a> in <a href=":in_url">:in_name</a> on <span>:on</span>', array(
            		    //BOF:mod 20120913
            */
            $wireframe->details = lang('Created on <span>:on</span>', array('by_url' => $created_by->getViewUrl(), 'by_name' => $created_by->getDisplayName(), 'in_url' => $in->getViewUrl(), 'in_name' => $in->getName(), 'on' => smarty_modifier_datetime($created_on)));
        } elseif (instance_of($created_by, 'User') && instance_of($created_on, 'DateValue')) {
            //BOF:mod 20120913
            /*
            //EOF:mod 20120913
            $wireframe->details = lang('By <a href=":by_url">:by_name</a> on <span>:on</span>', array(
            		    //BOF:mod 20120913
            */
            $wireframe->details = lang('Created on <span>:on</span>', array('by_url' => $created_by->getViewUrl(), 'by_name' => $created_by->getDisplayName(), 'on' => smarty_modifier_datetime($created_on)));
        } elseif (instance_of($created_by, 'User')) {
            //BOF:mod 20120913
            /*
            //EOF:mod 20120913
            $wireframe->details = lang('By <a href=":by_url">:by_name</a>', array(
            		    //BOF:mod 20120913
            */
            $wireframe->details = lang('Created on <span>:on</span>', array('by_url' => $created_by->getViewUrl(), 'by_name' => $created_by->getDisplayName(), 'on' => smarty_modifier_datetime($created_on)));
        } elseif (instance_of($created_by, 'AnonymousUser') && instance_of($created_on, 'DateValue')) {
            //BOF:mod 20120913
            /*
            //EOF:mod 20120913
            $wireframe->details = lang('By <a href=":by_url">:by_name</a> on <span>:on</span>', array(
            		    //BOF:mod 20120913
            */
            $wireframe->details = lang('Created on <span>:on</span>', array('by_url' => 'mailto:' . $created_by->getEmail(), 'by_name' => $created_by->getName(), 'on' => smarty_modifier_datetime($created_on)));
        } elseif (instance_of($created_by, 'AnonymousUser')) {
            //BOF:mod 20120913
            /*
            //EOF:mod 20120913
            $wireframe->details = lang('By <a href=":by_url">:by_name</a>', array(
            		    //BOF:mod 20120913
            */
            $wireframe->details = lang('Created on <span>:on</span>', array('by_url' => 'mailto:' . $created_by->getEmail(), 'by_name' => $created_by->getName(), 'on' => smarty_modifier_datetime($created_on)));
        }
        // if
    }
    // if
    $smarty->assign('page_object', $object);
    // Need to do a case sensitive + case insensitive search to have PHP4 covered
    $class_methods = get_class_methods($object);
    if (in_array('getOptions', $class_methods) || in_array('getoptions', $class_methods)) {
        $options = $object->getOptions($logged_user);
        if (instance_of($options, 'NamedList') && $options->count()) {
            $wireframe->addPageAction(lang('Options'), '#', $options->data, array('id' => 'project_object_options'), 1000);
        }
        // if
        if (instance_of($object, 'ProjectObject')) {
            if ($object->getState() > STATE_DELETED) {
                if ($object->getVisibility() <= VISIBILITY_PRIVATE) {
                    //Ticket ID #362 - modify Private button (SA) 14March2012 BOF
                    $users_table = TABLE_PREFIX . 'users';
                    $assignments_table = TABLE_PREFIX . 'assignments';
                    $subscription_table = TABLE_PREFIX . 'subscriptions';
                    //					$rows = db_execute_all("SELECT $assignments_table.is_owner AS is_assignment_owner, $users_table.id AS user_id, $users_table.company_id, $users_table.first_name, $users_table.last_name, $users_table.email FROM $users_table, $assignments_table WHERE $users_table.id = $assignments_table.user_id AND $assignments_table.object_id = ? ORDER BY $assignments_table.is_owner DESC", $object->getId());
                    $rows = db_execute_all("SELECT {$assignments_table}.is_owner AS is_assignment_owner, {$users_table}.id AS user_id, {$users_table}.company_id, {$users_table}.first_name, {$users_table}.last_name, {$users_table}.email FROM {$users_table}, {$assignments_table} WHERE {$users_table}.id = {$assignments_table}.user_id AND {$assignments_table}.object_id = " . $object->getId() . " UNION SELECT '0' AS is_assignment_owner, {$users_table}.id AS user_id, {$users_table}.company_id, {$users_table}.first_name, {$users_table}.last_name, {$users_table}.email FROM {$users_table}, {$subscription_table} WHERE {$users_table}.id = {$subscription_table}.user_id AND {$subscription_table}.parent_id = " . $object->getId());
                    if (is_foreachable($rows)) {
                        $owner = null;
                        $other_assignees = array();
                        $users_dropdown_for_tickets = '';
                        foreach ($rows as $row) {
                            if (empty($row['first_name']) && empty($row['last_name'])) {
                                $user_link = clean($row['email']);
                            } else {
                                $user_link = clean($row['first_name'] . ' ' . $row['last_name']);
                            }
                            // if
                            if ($row['is_assignment_owner']) {
                                $owner = $user_link;
                            } else {
                                $other_assignees[] = $user_link;
                            }
                            if ($owner) {
                                if (instance_of($object, 'Ticket')) {
                                    if (count($other_assignees) > 0) {
                                        $users = $owner;
                                        if (!empty($users)) {
                                            $users .= ', ';
                                        }
                                        $users .= implode(', ', $other_assignees);
                                    } else {
                                        $users = $owner;
                                    }
                                    // if
                                } else {
                                    if (count($other_assignees) > 0) {
                                        $users = $owner . ' ' . lang('is responsible', null, true, $language) . '. ' . lang('Other assignees', null, true, $language) . ': ' . implode(', ', $other_assignees) . '.';
                                    } else {
                                        $users = $owner . ' ' . lang('is responsible', null, true, $language) . '.';
                                    }
                                    // if
                                }
                            } elseif (count($other_assignees) > 0) {
                                $users = implode(', ', $other_assignees);
                            }
                        }
                    }
                    $wireframe->addPageMessage(lang('<b>Private</b> - This Ticket has been marked as "Private" and is Visible by these Users:  :users', array('users' => $users)), PAGE_MESSAGE_PRIVATE);
                    //Ticket ID #362 - modify Private button (SA) 14March2012 EOF
                }
                // if
            } else {
                $wireframe->addPageMessage(lang('<b>Trashed</b> - this :type is located in trash.', array('type' => $object->getVerboseType(true))), PAGE_MESSAGE_TRASHED);
            }
            // if
        }
        // if
    }
    // if
    return '';
}