/**
*
* @param array $params
* @param Smarty $smarty
* @return string
*/
function smarty_function_reminder($params, &$smarty)
{
    $object = array_var($params, 'object');
    $reminder_date = null;
    if (instance_of($object, 'ProjectObject')) {
        if ($object->isCompleted()) {
            return '';
        }
        // if
        $link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
        mysql_select_db(DB_NAME, $link);
        $query = "select reminder_date from healingcrystals_project_object_misc where object_id='" . $object->getId() . "'";
        $result = mysql_query($query);
        if (mysql_num_rows($result)) {
            $info = mysql_fetch_assoc($result);
            if (!empty($info['reminder_date'])) {
                $reminder_date = DateTimeValue::makeFromString($info['reminder_date']);
            }
        }
        mysql_close($link);
    } else {
        return new InvalidParamError('object', $object, '$object is not expected to be an instance of ProjectObject', true);
    }
    // if
    $offset = get_user_gmt_offset();
    if (instance_of($reminder_date, 'DateTimeValue')) {
        require_once SMARTY_PATH . '/plugins/modifier.datetime.php';
        $date = smarty_modifier_datetime($reminder_date, 0);
        // just printing date, offset is 0!
        if ($reminder_date->isToday($offset)) {
            return '<span class="today"><span class="number">Reminder set for: ' . lang('Today') . ' ' . date('h:i A', $reminder_date->getTimestamp()) . '</span></span>';
        } elseif ($reminder_date->isYesterday($offset)) {
            return '<span class="late" title="' . clean($date) . '">Reminder set for: ' . lang('<span class="number">Yesterday ' . date('h:i A', $reminder_date->getTimestamp()) . '</span>') . '</span>';
        } elseif ($reminder_date->isTomorrow($offset)) {
            return '<span class="upcoming" title="' . clean($date) . '">Reminder set for: <span class="number">' . lang('Tomorrow') . ' ' . date('h:i A', $reminder_date->getTimestamp()) . '</span></span>';
        } else {
            $now = new DateTimeValue();
            $now->advance($offset);
            $now = $now->beginningOfDay();
            $reminder_date->beginningOfDay();
            if ($reminder_date->getTimestamp() > $now->getTimestamp()) {
                return '<span class="upcoming" title="' . clean($date) . '">Reminder set for: ' . date('F d, Y h:i A', $reminder_date->getTimestamp()) . lang(' (<span class="number">:days</span> Days)', array('days' => floor(($reminder_date->getTimestamp() - $now->getTimestamp()) / 86400))) . '</span>';
            } else {
                return '<span class="late" title="' . clean($date) . '">Reminder set for: ' . date('F d, Y h:i A', $reminder_date->getTimestamp()) . lang(' (<span class="number">:days</span> Days Late)', array('days' => floor(($now->getTimestamp() - $reminder_date->getTimestamp()) / 86400))) . '</span>';
            }
            // if
        }
        // if
    } else {
        return '';
    }
    // if
}
/**
 * Return '*** ago' message
 *
 * @param DateTimeValue $input
 * @param integer $offset
 * @return string
 */
function smarty_modifier_ago($input, $offset = null)
{
    if (!instance_of($input, 'DateValue')) {
        return '<span class="ago">' . lang('-- Unknown --') . '</span>';
    }
    // if
    if ($offset === null) {
        $offset = get_user_gmt_offset();
    }
    // if
    $datetime = new DateTimeValue($input->getTimestamp() + $offset);
    $reference = new DateTimeValue(time() + $offset);
    $diff = $reference->getTimestamp() - $datetime->getTimestamp();
    // Get exact number of seconds between current time and yesterday morning
    $reference_timestamp = $reference->getTimestamp();
    $yesterday_begins_at = 86400 + date('G', $reference_timestamp) * 3600 + date('i', $reference_timestamp) * 60 + date('s', $reference_timestamp);
    if ($diff < 60) {
        $value = lang('Few seconds ago');
    } elseif ($diff < 120) {
        $value = lang('A minute ago');
    } elseif ($diff < 3600) {
        $value = lang(':num minutes ago', array('num' => floor($diff / 60)));
    } elseif ($diff < 7200) {
        $value = lang('An hour ago');
    } elseif ($diff < 86400) {
        if (date('j', $datetime->getTimestamp()) != date('j', $reference->getTimestamp())) {
            $value = lang('Yesterday');
        } else {
            $mod = $diff % 3600;
            if ($mod < 900) {
                $value = lang(':num hours ago', array('num' => floor($diff / 3600)));
            } elseif ($mod > 2700) {
                $value = lang(':num hours ago', array('num' => ceil($diff / 3600)));
            } else {
                $value = lang(':num and a half hours ago', array('num' => floor($diff / 3600)));
            }
            // if
        }
        // if
    } elseif ($diff <= $yesterday_begins_at) {
        $value = lang('Yesterday');
    } elseif ($diff < 2592000) {
        $value = lang(':num days ago', array('num' => floor($diff / 86400)));
    } else {
        require_once SMARTY_PATH . '/plugins/modifier.date.php';
        require_once SMARTY_PATH . '/plugins/modifier.datetime.php';
        return '<span class="ago" title="' . clean(smarty_modifier_datetime($datetime, 0)) . '">' . lang('On') . ' ' . smarty_modifier_date($datetime, 0) . '</span>';
    }
    // if
    require_once SMARTY_PATH . '/plugins/modifier.datetime.php';
    return '<span class="ago" title="' . clean(smarty_modifier_datetime($datetime, 0)) . '">' . $value . '</span>';
}
 /**
  * Index
  *
  * @param voi
  * @return null
  */
 function index()
 {
     require_once CALENDAR_MODULE_PATH . '/models/generators/ProjectCalendarGenerator.class.php';
     $today = new DateTimeValue(time() + get_user_gmt_offset());
     if ($this->request->get('month') && $this->request->get('year')) {
         $month = $this->request->get('month');
         $year = $this->request->get('year');
     } else {
         $month = $today->getMonth();
         $year = $today->getYear();
     }
     // if
     $first_weekday = UserConfigOptions::getValue('time_first_week_day', $this->logged_user);
     $generator = new ProjectCalendarGenerator($month, $year, $first_weekday);
     $generator->setProject($this->active_project);
     $generator->setData(Calendar::getProjectData($this->logged_user, $this->active_project, $month, $year));
     $this->smarty->assign(array('month' => $month, 'year' => $year, 'calendar' => $generator, 'page_tab' => 'calendar', 'navigation_pattern' => Calendar::getProjectMonthUrl($this->active_project, '-YEAR-', '-MONTH-')));
 }
/**
 * Return formated time
 *
 * @param string $content
 * @param integer $offset
 * @return string
 */
function smarty_modifier_time($content, $offset = null)
{
    if (instance_of($content, 'DateValue')) {
        $timestamp = $content->getTimestamp();
    } else {
        $timestamp = (int) $content;
        if ($timestamp == 0) {
            return lang('unknown time');
        }
        // if
    }
    // if
    if ($offset === null) {
        $offset = get_user_gmt_offset();
    }
    // if
    $format = defined('USER_FORMAT_TIME') && USER_FORMAT_TIME ? USER_FORMAT_TIME : FORMAT_TIME;
    return strftime($format, $timestamp + $offset);
}
/**
 * Return formated date
 *
 * @param string $content
 * @param string $default
 * @return string
 */
function smarty_modifier_date($content, $offset = null)
{
    if (instance_of($content, 'DateValue')) {
        $timestamp = $content->getTimestamp();
    } else {
        $timestamp = (int) $content;
        if ($timestamp == 0) {
            return lang('unknown time');
        }
        // if
    }
    // if
    if ($offset === null) {
        $offset = get_user_gmt_offset();
    }
    // if
    $format = defined('USER_FORMAT_DATE') && USER_FORMAT_DATE ? USER_FORMAT_DATE : FORMAT_DATE;
    if (DIRECTORY_SEPARATOR == "\\") {
        $format = str_replace('%e', '%d', $format);
    }
    // if
    return strftime($format, $timestamp + $offset);
}
/**
 * Show users local time based on his or hers local settings
 * 
 * Parameters:
 * 
 * - user - User, if NULL logged user will be used
 * - datetime - Datetime value that need to be displayed. If NULL request time 
 *   will be used
 *
 * @param array $params
 * @param Smarty $smarty
 * @return string
 */
function smarty_function_user_time($params, &$smarty)
{
    $user = array_var($params, 'user');
    if (!instance_of($user, 'User')) {
        $user = get_logged_user();
    }
    // if
    if (!instance_of($user, 'User')) {
        return lang('Unknown time');
    }
    // if
    $value = array_var($params, 'datetime');
    if (!instance_of($value, 'DateValue')) {
        $value = $smarty->get_template_vars('request_time');
    }
    // if
    if (!instance_of($value, 'DateValue')) {
        return lang('Unknown time');
    }
    // if
    require_once SMARTY_PATH . '/plugins/modifier.time.php';
    return clean(smarty_modifier_time($value, get_user_gmt_offset($user)));
}
 /**
  * Calendar
  *
  * @param void
  * @return null
  */
 function index()
 {
     require_once CALENDAR_MODULE_PATH . '/models/generators/DashboardCalendarGenerator.class.php';
     if ($this->request->get('month') && $this->request->get('year')) {
         $month = $this->request->get('month');
         $year = $this->request->get('year');
     } else {
         $today = new DateTimeValue(time() + get_user_gmt_offset());
         $month = $today->getMonth();
         $year = $today->getYear();
     }
     // if
     $first_weekday = UserConfigOptions::getValue('time_first_week_day', $this->logged_user);
     $generator = new DashboardCalendarGenerator($month, $year, $first_weekday);
     $generator->setData(Calendar::getActiveProjectsData($this->logged_user, $month, $year));
     $this->smarty->assign(array('month' => $month, 'year' => $year, 'calendar' => $generator, 'navigation_pattern' => Calendar::getDashboardMonthUrl('-YEAR-', '-MONTH-')));
     //BOF:mod 20110623
     $tabs = new NamedList();
     $tabs->add('dashboard', array('text' => 'Active Teams', 'url' => assemble_url('dashboard')));
     $tabs->add('home_page', array('text' => 'Home Page', 'url' => assemble_url('goto_home_tab')));
     $this->smarty->assign('page_tabs', $tabs);
     //EOF:mod 20110623
 }
/**
 * 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
}
 /**
  * Return upcoming objects in a given projects
  *
  * @param User $user
  * @param Project $project
  * @param array $types
  * @param integer $page
  * @param integer $per_page
  * @return array
  */
 function findUpcoming($user, $project = null, $types = null, $page = null, $per_page = null)
 {
     if (instance_of($project, 'Project')) {
         $type_filter = ProjectUsers::getVisibleTypesFilterByProject($user, $project, $types);
     } else {
         $type_filter = ProjectUsers::getVisibleTypesFilter($user, array(PROJECT_STATUS_ACTIVE), $types);
     }
     if ($type_filter) {
         $today = new DateTimeValue();
         $today->advance(get_user_gmt_offset());
         $newer_than = $today->endOfDay();
         $conditions = array($type_filter . ' AND due_on > ? AND state >= ? AND visibility >= ? AND completed_on IS NULL', $newer_than, STATE_VISIBLE, $user->getVisibility());
         if ($page !== null && $per_page !== null) {
             return ProjectObjects::paginate(array('conditions' => $conditions, 'order' => 'due_on, priority DESC'), $page, $per_page);
         } else {
             return ProjectObjects::find(array('conditions' => $conditions, 'order' => 'due_on, priority DESC'));
         }
         // if
     }
     // if
     return null;
 }
/**
*
* @param array $params
* @param Smarty $smarty
* @return string
* HISTORY
* 22 May 2012 (SA) Ticket #841: check recurring task reminder script
*/
function smarty_function_reminder($params, &$smarty)
{
    $object = array_var($params, 'object');
    $reminder_date = null;
    if (instance_of($object, 'ProjectObject')) {
        if ($object->isCompleted()) {
            return '';
        }
        // if
        $link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
        mysql_select_db(DB_NAME, $link);
        //BOF:mod 20120904
        /*
        //EOF:mod 20120904
                $query = "select * from healingcrystals_project_object_misc where object_id='" . $object->getId() . "'";
        //BOF:mod 20120904
        */
        $query = "select a.reminder_date, a.recurring_period, a.recurring_period_type, b.completed_on from healingcrystals_project_object_misc a inner join healingcrystals_project_objects b on a.object_id=b.id where a.object_id='" . $object->getId() . "'";
        //EOF:mod 20120904
        $result = mysql_query($query);
        if (mysql_num_rows($result)) {
            $info = mysql_fetch_assoc($result);
            if (!empty($info['reminder_date']) && $info['reminder_date'] != '0000-00-00 00:00:00') {
                $reminder_date = DateTimeValue::makeFromString($info['reminder_date']);
            }
            //BOF:mod 20120904
            if (!empty($info['completed_on'])) {
                //EOF:mod 20120904
                if ($info['recurring_period_type'] != '' && $info['recurring_period'] != '') {
                    $recurring_period = $info['recurring_period'];
                    $recurring_period_type = $info['recurring_period_type'];
                    switch ($recurring_period_type) {
                        case 'D':
                            $recurring_period_type = 'day' . ($recurring_period == 1 ? '' : 's');
                            break;
                        case 'W':
                            $recurring_period_type = 'week' . ($recurring_period == 1 ? '' : 's');
                            break;
                        case 'M':
                            $recurring_period_type = 'month' . ($recurring_period == 1 ? '' : 's');
                            break;
                        case 'Y':
                            $recurring_period_type = 'year' . ($recurring_period == 1 ? '' : 's');
                            break;
                    }
                    $datetime = new DateTime();
                    $datetime->modify('+' . $recurring_period . ' ' . $recurring_period_type);
                    //BOF:mod 20120703
                    if (!empty($reminder_date)) {
                        $temp_date = $reminder_date;
                    }
                    //EOF:mod 20120703
                    $reminder_date = DateTimeValue::makeFromString($datetime->format('Y-m-d H:00'));
                    //BOF:mod 20120703
                    if (!empty($temp_date) && $temp_date->getTimestamp() >= time()) {
                        $reminder_date = $temp_date;
                    }
                    //EOF:mod 20120703
                }
                //BOF:mod 20120904
            }
            //EOF:mod 20120904
        }
        mysql_close($link);
    } else {
        return new InvalidParamError('object', $object, '$object is not expected to be an instance of ProjectObject', true);
    }
    // if
    $offset = get_user_gmt_offset();
    if (instance_of($reminder_date, 'DateTimeValue')) {
        require_once SMARTY_PATH . '/plugins/modifier.datetime.php';
        $date = smarty_modifier_datetime($reminder_date, 0);
        // just printing date, offset is 0!
        if ($reminder_date->isToday($offset)) {
            return '<span class="today"><span class="number">Reminder set for: ' . lang('Today') . ' ' . date('h:i A', $reminder_date->getTimestamp()) . '</span></span>';
        } elseif ($reminder_date->isYesterday($offset)) {
            return '<span class="late" title="' . clean($date) . '">Reminder set for: ' . lang('<span class="number">Yesterday ' . date('h:i A', $reminder_date->getTimestamp()) . '</span>') . '</span>';
        } elseif ($reminder_date->isTomorrow($offset)) {
            return '<span class="upcoming" title="' . clean($date) . '">Reminder set for: <span class="number">' . lang('Tomorrow') . ' ' . date('h:i A', $reminder_date->getTimestamp()) . '</span></span>';
        } else {
            $now = new DateTimeValue();
            $now->advance($offset);
            $now = $now->beginningOfDay();
            $reminder_date->beginningOfDay();
            if ($reminder_date->getTimestamp() > $now->getTimestamp()) {
                return '<span class="upcoming" title="' . clean($date) . '">Reminder set for: ' . date('F d, Y h:i A', $reminder_date->getTimestamp()) . lang(' (<span class="number">:days</span> Days)', array('days' => floor(($reminder_date->getTimestamp() - $now->getTimestamp()) / 86400))) . '</span>';
            } else {
                return '<span class="late" title="' . clean($date) . '">Reminder set for: ' . date('F d, Y h:i A', $reminder_date->getTimestamp()) . lang(' (<span class="number">:days</span> Days Late)', array('days' => floor(($now->getTimestamp() - $reminder_date->getTimestamp()) / 86400))) . '</span>';
            }
            // if
        }
        // if
    } else {
        return '';
    }
    // if
}
 /**
  * Check if this invoice is overdue
  * 
  * @param void
  * @return null
  */
 function isOverdue()
 {
     $today = new DateValue(time() + get_user_gmt_offset());
     $due_on = $this->getDueOn();
     return (bool) ($this->isIssued() && !$this->isBilled() && !$this->isCanceled() && (instance_of($due_on, 'DateValue') && $due_on->getTimestamp() < $today->getTimestamp()));
 }
 /**
  * Render popup content
  *
  * @param void
  * @return null
  */
 function _render_popup_content()
 {
     if (!instance_of($this->active_object, 'ProjectObject')) {
         $this->httpError(HTTP_ERR_NOT_FOUND);
     }
     // if
     if (TimeRecord::canAdd($this->logged_user, $this->active_project)) {
         $add_record_url = timetracking_module_add_record_url($this->active_project, array('for' => $this->active_object->getId(), 'for_popup_dialog' => 1));
     } else {
         $add_record_url = false;
     }
     // if
     $object_time = TimeRecords::sumObjectTime($this->active_object);
     $tasks_time = $this->active_object->can_have_tasks ? TimeRecords::sumTasksTime($this->active_object) : 0;
     $this->smarty->assign(array('selected_user' => $this->logged_user, 'selected_date' => new DateValue(time() + get_user_gmt_offset($this->logged_user)), 'selected_billable_status' => BILLABLE_STATUS_BILLABLE, 'object_time' => float_format($object_time, 2), 'tasks_time' => float_format($tasks_time, 2), 'total_time' => float_format($object_time + $tasks_time, 2), 'add_url' => $add_record_url));
     $this->smarty->display(get_template_path('_popup', null, TIMETRACKING_MODULE));
     die;
 }
 /**
  * Return outstanding invoices (overdue invoices are excluded. If company is provided outstanding invoices for that company are counted)
  *
  * @param Company $company
  * @return array;
  */
 function findOutstanding($company = null)
 {
     $today = new DateValue(time() + get_user_gmt_offset());
     if ($company) {
         return Invoices::find(array('condition' => array('status = ? AND due_on >= ? AND company_id = ?', INVOICE_STATUS_ISSUED, $today, $company->getId()), 'order' => 'due_on DESC'));
     } else {
         return Invoices::find(array('condition' => array('status = ? AND due_on >= ?', INVOICE_STATUS_ISSUED, $today), 'order' => 'due_on DESC'));
     }
     // if
 }
示例#14
0
/**
 * Group objects by given date
 *
 * @param array $objects
 * @param User $user
 * @param string $getter
 * @param boolean $today_yesterday
 * @return array
 */
function group_by_date($objects, $user = null, $getter = 'getCreatedOn', $today_yesterday = true)
{
    $result = array();
    if (is_foreachable($objects)) {
        require_once SMARTY_PATH . '/plugins/modifier.date.php';
        $offset = instance_of($user, 'User') ? get_user_gmt_offset($user) : 0;
        foreach ($objects as $object) {
            $gmt = $object->{$getter}();
            if (instance_of($gmt, 'DateValue')) {
                $date = $gmt->advance($offset, false);
                // advance, but don't mutate
                if ($today_yesterday) {
                    if ($date->isToday($offset)) {
                        $date_string = lang('Today');
                    } elseif ($date->isYesterday($offset)) {
                        $date_string = lang('Yesterday');
                    } else {
                        $date_string = smarty_modifier_date($date);
                    }
                    // if
                } else {
                    $date_string = smarty_modifier_date($date);
                }
                // if
                if (!isset($result[$date_string])) {
                    $result[$date_string] = array();
                }
                // if
                $result[$date_string][] = $object;
            }
            // if
        }
        // foreach
    }
    // if
    return $result;
}
 /**
  * Prepare conditions based on filter settings
  *
  * @param User $user
  * @return string
  */
 function prepareConditions($user)
 {
     $project_objects_table = TABLE_PREFIX . 'project_objects';
     $assignments_table = TABLE_PREFIX . 'assignments';
     $completable_types = get_completable_project_object_types();
     $conditions = array();
     // Selected projects filter
     if ($this->getProjectFilter() == PROJECT_FILTER_SELECTED) {
         $project_ids = $this->getProjectFilterData();
         if ($project_ids) {
             $conditions[] = db_prepare_string("({$project_objects_table}.project_id IN (?))", array($project_ids));
             $types_filter = ProjectUsers::getVisibleTypesFilter($user, null, $completable_types);
             if ($types_filter) {
                 $conditions[] = $types_filter;
             } else {
                 return false;
                 // No access to any of the projects?
             }
             // if
         }
         // if
     }
     // if
     // All projects
     if (count($conditions) == 0) {
         $types_filter = ProjectUsers::getVisibleTypesFilter($user, array(PROJECT_STATUS_ACTIVE), $completable_types);
         if ($types_filter) {
             $conditions[] = $types_filter;
         } else {
             return false;
             // No access to any of the projects?
         }
         // if
     }
     // if
     // User filter
     switch ($this->getUserFilter()) {
         // Not assigned to anyone
         case USER_FILTER_NOT_ASSIGNED:
             $user_id = $user->getId();
             $conditions[] = "({$assignments_table}.user_id IS NULL)";
             break;
             // Logged user
         // Logged user
         case USER_FILTER_LOGGED_USER:
             $user_id = $user->getId();
             $conditions[] = "({$assignments_table}.user_id = {$user_id})";
             break;
             // Logged user is responsible
         // Logged user is responsible
         case USER_FILTER_LOGGED_USER_RESPONSIBLE:
             $user_id = $user->getId();
             $conditions[] = "({$assignments_table}.user_id = {$user_id}) AND ({$assignments_table}.is_owner = 1)";
             break;
             // All members of a specific company
         // All members of a specific company
         case USER_FILTER_COMPANY:
             $visible_user_ids = $user->visibleUserIds();
             if (!is_foreachable($visible_user_ids)) {
                 return false;
             }
             // if
             $company_id = $this->getUserFilterData();
             if ($company_id) {
                 $company = Companies::findById($company_id);
                 if (instance_of($company, 'Company')) {
                     $user_ids = Users::findUserIdsByCompany($company);
                     if (is_foreachable($user_ids)) {
                         foreach ($user_ids as $k => $v) {
                             if (!in_array($v, $visible_user_ids)) {
                                 unset($user_ids[$k]);
                             }
                             // if
                         }
                         // if
                         if (count($user_ids) > 0) {
                             $imploded = implode(', ', $user_ids);
                             $conditions[] = "({$assignments_table}.user_id IN ({$imploded}))";
                         } else {
                             return false;
                         }
                         // if
                     }
                     // if
                 }
                 // if
             }
             // if
             break;
             // Selected users
         // Selected users
         case USER_FILTER_SELECTED:
             $visible_user_ids = $user->visibleUserIds();
             if (!is_foreachable($visible_user_ids)) {
                 return false;
             }
             // if
             $user_ids = $this->getUserFilterData();
             if (is_foreachable($user_ids)) {
                 foreach ($user_ids as $k => $v) {
                     if (!in_array($v, $visible_user_ids)) {
                         unset($user_ids[$k]);
                     }
                     // if
                 }
                 // foreach
                 if (count($user_ids) > 0) {
                     $imploded = implode(', ', $user_ids);
                     $conditions[] = "({$assignments_table}.user_id IN ({$imploded}))";
                 } else {
                     return false;
                 }
                 // if
             }
             // if
             break;
     }
     // switch
     $today = new DateValue(time() + get_user_gmt_offset($user));
     // Calculate user timezone when determining today
     switch ($this->getDateFilter()) {
         // List late assignments
         case DATE_FILTER_LATE:
             $today_str = db_escape($today->toMySQL());
             $conditions[] = "({$project_objects_table}.due_on < {$today_str})";
             break;
             // List today assignments
         // List today assignments
         case DATE_FILTER_TODAY:
             $today_str = db_escape($today->toMySQL());
             $conditions[] = "({$project_objects_table}.due_on = {$today_str})";
             break;
             // List tomorrow assignments
         // List tomorrow assignments
         case DATE_FILTER_TOMORROW:
             $tomorrow = $today->advance(86400, false);
             $tomorrow_str = db_escape($tomorrow->toMySQL());
             $conditions[] = "({$project_objects_table}.due_on = {$tomorrow_str})";
             break;
             // List this week assignments
         // List this week assignments
         case DATE_FILTER_THIS_WEEK:
             $first_day_sunday = UserConfigOptions::getValue('time_first_week_day', $user) == 0;
             $week_start = $today->beginningOfWeek($first_day_sunday);
             $week_end = $today->endOfWeek($first_day_sunday);
             $week_start_str = db_escape($week_start->toMySQL());
             $week_end_str = db_escape($week_end->toMySQL());
             $conditions[] = "({$project_objects_table}.due_on >= {$week_start_str} AND {$project_objects_table}.due_on <= {$week_end_str})";
             break;
             // List next week assignments
         // List next week assignments
         case DATE_FILTER_NEXT_WEEK:
             $first_day_sunday = UserConfigOptions::getValue('time_first_week_day', $user) == 0;
             $next_week = $today->advance(604800, false);
             $week_start = $next_week->beginningOfWeek($first_day_sunday);
             $week_end = $next_week->endOfWeek($first_day_sunday);
             $week_start_str = db_escape($week_start->toMySQL());
             $week_end_str = db_escape($week_end->toMySQL());
             $conditions[] = "({$project_objects_table}.due_on >= {$week_start_str} AND {$project_objects_table}.due_on <= {$week_end_str})";
             break;
             // List this month assignments
         // List this month assignments
         case DATE_FILTER_THIS_MONTH:
             $month_start = DateTimeValue::beginningOfMonth($today->getMonth(), $today->getYear());
             $month_end = DateTimeValue::endOfMonth($today->getMonth(), $today->getYear());
             $month_start_str = db_escape($month_start->toMySQL());
             $month_end_str = db_escape($month_end->toMySQL());
             $conditions[] = "({$project_objects_table}.due_on >= {$month_start_str} AND {$project_objects_table}.due_on <= {$month_end_str})";
             break;
             // List next month assignments
         // List next month assignments
         case DATE_FILTER_NEXT_MONTH:
             $month = $today->getMonth() + 1;
             $year = $today->getYear();
             if ($month == 13) {
                 $month = 1;
                 $year += 1;
             }
             // if
             $month_start = DateTimeValue::beginningOfMonth($month, $year);
             $month_end = DateTimeValue::endOfMonth($month, $year);
             $month_start_str = db_escape($month_start->toMySQL());
             $month_end_str = db_escape($month_end->toMySQL());
             $conditions[] = "({$project_objects_table}.due_on >= {$month_start_str} AND {$project_objects_table}.due_on <= {$month_end_str})";
             break;
             // Specific date
         // Specific date
         case DATE_FILTER_SELECTED_DATE:
             $date_from = $this->getDateFrom();
             if (instance_of($date_from, 'DateTimeValue')) {
                 $date_from_str = db_escape($date_from->toMySql());
                 $conditions[] = "({$project_objects_table}.due_on = {$date_from_str})";
             }
             // if
             break;
             // Specific range
         // Specific range
         case DATE_FILTER_SELECTED_RANGE:
             $date_from = $this->getDateFrom();
             $date_to = $this->getDateTo();
             if (instance_of($date_from, 'DateValue') && instance_of($date_to, 'DateValue')) {
                 $date_from_str = db_escape($date_from->toMySQL());
                 $date_to_str = db_escape($date_to->toMySQL());
                 $conditions[] = "({$project_objects_table}.due_on >= {$date_from_str} AND {$project_objects_table}.due_on <= {$date_to_str})";
             }
             // if
             break;
     }
     // switch
     // Status filter
     switch ($this->getStatusFilter()) {
         case STATUS_FILTER_ACTIVE:
             $conditions[] = "({$project_objects_table}.completed_on IS NULL)";
             break;
         case STATUS_FILTER_COMPLETED:
             $conditions[] = "({$project_objects_table}.completed_on IS NOT NULL)";
             break;
     }
     // if
     // Additional filters
     $state = STATE_VISIBLE;
     $visibility = $user->getVisibility();
     $conditions[] = "({$project_objects_table}.state >= {$state} AND {$project_objects_table}.visibility >= {$visibility})";
     return implode(' AND ', $conditions);
 }
 /**
  * Prepare conditions based on report settings
  *
  * @param User $user
  * @param Project $project
  * @return string
  */
 function prepareConditions($user, $project = null)
 {
     $project_objects_table = TABLE_PREFIX . 'project_objects';
     $conditions = array();
     // Project and type
     if (instance_of($project, 'Project')) {
         $conditions[] = db_prepare_string('project_id = ? AND type = ?', array($project->getId(), 'timerecord'));
     } else {
         $conditions[] = db_prepare_string('type = ?', array('timerecord'));
     }
     // if
     // User filter
     switch ($this->getUserFilter()) {
         // Anyone - This filter used to filter only time tracked from all
         // visible users, but that did not include deleted accounts. Fixed now
         //
         //case USER_FILTER_ANYBODY:
         //  $visible_user_ids = $user->visibleUserIds();
         //  if(is_foreachable($visible_user_ids)) {
         //    $conditions[] = "($project_objects_table.integer_field_1 IN (" . db_escape($visible_user_ids) . '))';
         //  } else {
         //    return false; // not visible users
         //  } // if
         //  break;
         // Logged user
         case USER_FILTER_LOGGED_USER:
             $user_id = $user->getId();
             $conditions[] = "({$project_objects_table}.integer_field_1 = {$user_id})";
             break;
             // All members of a specific company
         // All members of a specific company
         case USER_FILTER_COMPANY:
             $visible_user_ids = $user->visibleUserIds();
             if (!is_foreachable($visible_user_ids)) {
                 return false;
             }
             // if
             $company_id = $this->getUserFilterData();
             if ($company_id) {
                 $company = Companies::findById($company_id);
                 if (instance_of($company, 'Company')) {
                     $user_ids = Users::findUserIdsByCompany($company);
                     if (is_foreachable($user_ids)) {
                         foreach ($user_ids as $k => $v) {
                             if (!in_array($v, $visible_user_ids)) {
                                 unset($user_ids[$k]);
                             }
                             // if
                         }
                         // if
                         if (count($user_ids) > 0) {
                             $imploded = implode(', ', $user_ids);
                             $conditions[] = "({$project_objects_table}.integer_field_1 IN ({$imploded}))";
                         } else {
                             return false;
                         }
                         // if
                     }
                     // if
                 }
                 // if
             }
             // if
             break;
             // Selected users
         // Selected users
         case USER_FILTER_SELECTED:
             $visible_user_ids = $user->visibleUserIds();
             if (!is_foreachable($visible_user_ids)) {
                 return false;
             }
             // if
             $user_ids = $this->getUserFilterData();
             if (is_foreachable($user_ids)) {
                 foreach ($user_ids as $k => $v) {
                     if (!in_array($v, $visible_user_ids)) {
                         unset($user_ids[$k]);
                     }
                     // if
                 }
                 // foreach
                 if (count($user_ids) > 0) {
                     $imploded = implode(', ', $user_ids);
                     $conditions[] = "({$project_objects_table}.integer_field_1 IN ({$imploded}))";
                 } else {
                     return false;
                 }
                 // if
             }
             // if
             break;
     }
     // switch
     $today = new DateValue(time() + get_user_gmt_offset($user));
     // Calculate user timezone when determining today
     switch ($this->getDateFilter()) {
         // List time records posted for today
         case DATE_FILTER_TODAY:
             $today_str = db_escape($today->toMySQL());
             $conditions[] = "({$project_objects_table}.date_field_1 = {$today_str})";
             break;
             // List next week records
         // List next week records
         case DATE_FILTER_LAST_WEEK:
             $first_day_sunday = UserConfigOptions::getValue('time_first_week_day', $user) == 0;
             $last_week = $today->advance(-604800, false);
             $week_start = $last_week->beginningOfWeek($first_day_sunday);
             $week_end = $last_week->endOfWeek($first_day_sunday);
             $week_start_str = db_escape($week_start->toMySQL());
             $week_end_str = db_escape($week_end->toMySQL());
             $conditions[] = "({$project_objects_table}.date_field_1 >= {$week_start_str} AND {$project_objects_table}.date_field_1 <= {$week_end_str})";
             break;
             // List this week records
         // List this week records
         case DATE_FILTER_THIS_WEEK:
             $first_day_sunday = UserConfigOptions::getValue('time_first_week_day', $user) == 0;
             $week_start = $today->beginningOfWeek($first_day_sunday);
             $week_end = $today->endOfWeek($first_day_sunday);
             $week_start_str = db_escape($week_start->toMySQL());
             $week_end_str = db_escape($week_end->toMySQL());
             $conditions[] = "({$project_objects_table}.date_field_1 >= {$week_start_str} AND {$project_objects_table}.date_field_1 <= {$week_end_str})";
             break;
             // List this month time records
         // List this month time records
         case DATE_FILTER_LAST_MONTH:
             $month = $today->getMonth() - 1;
             $year = $today->getYear();
             if ($month == 0) {
                 $month = 12;
                 $year -= 1;
             }
             // if
             $month_start = DateTimeValue::beginningOfMonth($month, $year);
             $month_end = DateTimeValue::endOfMonth($month, $year);
             $month_start_str = db_escape($month_start->toMySQL());
             $month_end_str = db_escape($month_end->toMySQL());
             $conditions[] = "({$project_objects_table}.date_field_1 >= {$month_start_str} AND {$project_objects_table}.date_field_1 <= {$month_end_str})";
             break;
             // Last month
         // Last month
         case DATE_FILTER_THIS_MONTH:
             $month_start = DateTimeValue::beginningOfMonth($today->getMonth(), $today->getYear());
             $month_end = DateTimeValue::endOfMonth($today->getMonth(), $today->getYear());
             $month_start_str = db_escape($month_start->toMySQL());
             $month_end_str = db_escape($month_end->toMySQL());
             $conditions[] = "({$project_objects_table}.date_field_1 >= {$month_start_str} AND {$project_objects_table}.date_field_1 <= {$month_end_str})";
             break;
             // Specific date
         // Specific date
         case DATE_FILTER_SELECTED_DATE:
             $date_from = $this->getDateFrom();
             if (instance_of($date_from, 'DateValue')) {
                 $date_from_str = db_escape($date_from->toMySql());
                 $conditions[] = "({$project_objects_table}.date_field_1 = {$date_from_str})";
             }
             // if
             break;
             // Specific range
         // Specific range
         case DATE_FILTER_SELECTED_RANGE:
             $date_from = $this->getDateFrom();
             $date_to = $this->getDateTo();
             if (instance_of($date_from, 'DateValue') && instance_of($date_to, 'DateValue')) {
                 $date_from_str = db_escape($date_from->toMySQL());
                 $date_to_str = db_escape($date_to->toMySQL());
                 $conditions[] = "({$project_objects_table}.date_field_1 >= {$date_from_str} AND {$project_objects_table}.date_field_1 <= {$date_to_str})";
             }
             // if
             break;
     }
     // switch
     // Billable filter
     switch ($this->getBillableFilter()) {
         case BILLABLE_FILTER_BILLABLE:
             $conditions[] = "({$project_objects_table}.integer_field_2 = '" . BILLABLE_STATUS_BILLABLE . "')";
             break;
         case BILLABLE_FILTER_NOT_BILLABLE:
             $conditions[] = "({$project_objects_table}.integer_field_2 = '" . BILLABLE_STATUS_NOT_BILLABLE . "' OR {$project_objects_table}.integer_field_2 IS NULL)";
             break;
         case BILLABLE_FILTER_BILLABLE_BILLED:
             $conditions[] = "({$project_objects_table}.integer_field_2 >= '" . BILLABLE_STATUS_BILLED . "')";
             break;
         case BILLABLE_FILTER_PENDING_PAYMENT:
             $conditions[] = "({$project_objects_table}.integer_field_2 = '" . BILLABLE_STATUS_PENDING_PAYMENT . "')";
             break;
         case BILLABLE_FILTER_BILLABLE_NOT_BILLED:
             $conditions[] = "({$project_objects_table}.integer_field_2 IN ('" . BILLABLE_STATUS_BILLABLE . "', '" . BILLABLE_STATUS_PENDING_PAYMENT . "'))";
             break;
     }
     // switch
     // Additional filters
     $state = STATE_VISIBLE;
     $visibility = $user->getVisibility();
     $conditions[] = "({$project_objects_table}.state >= {$state} AND {$project_objects_table}.visibility >= {$visibility})";
     return implode(' AND ', $conditions);
 }