Ejemplo n.º 1
0
/**
 * 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>';
}
/**
 * Render select datetime format widget
 *
 * @param array $params
 * @param Smarty $smarty
 * @return string
 */
function smarty_function_select_datetime_format($params, &$smarty)
{
    $e = DIRECTORY_SEPARATOR == '\\' ? '%d' : '%e';
    // Windows does not support %e
    $presets = array('date' => array("%b {$e}. %Y", "%a, %b {$e}. %Y", "{$e} %b %Y", "%Y/%m/{$e}", "%m/{$e}/%Y"), 'time' => array('%I:%M %p', '%H:%M'));
    $mode = 'date';
    if (array_key_exists('mode', $params)) {
        $mode = $params['mode'];
        unset($params['mode']);
    }
    // if
    $value = null;
    if (array_key_exists('value', $params)) {
        $value = $params['value'];
        unset($params['value']);
    }
    // if
    $optional = false;
    if (array_key_exists('optional', $params)) {
        $optional = (bool) $params['optional'];
        unset($params['optional']);
    }
    // if
    $reference_time = new DateTimeValue('2007-11-21 20:45:15');
    $options = array();
    if ($optional) {
        $default_format = ConfigOptions::getValue("format_{$mode}");
        $default_value = strftime($default_format, $reference_time->getTimestamp());
        $options[] = option_tag(lang('-- System Default (:value) --', array('value' => $default_value)), '');
        $options[] = option_tag('', '');
    }
    // if
    foreach ($presets[$mode] as $v) {
        $option_attributes = $v === $value ? array('selected' => true) : null;
        $options[] = option_tag(strftime($v, $reference_time->getTimestamp()), $v, $option_attributes);
    }
    // foreach
    return select_box($options, $params);
}
Ejemplo n.º 3
0
 /**
  * Get recent activity for a repository
  *
  * @param Repository $repository
  * @param int $from_days_before
  * @return array
  */
 function getRecentActivity($repository, $from_days_before = 15)
 {
     $from = new DateTimeValue($from_days_before - 1 . ' days ago');
     $last_commit = $repository->getLastcommit();
     $beginning_of_day = $from->beginningOfDay();
     $max_commits = Commits::count(array("parent_id = ? AND created_on >= ? GROUP BY DAY(created_on) ORDER BY row_count DESC LIMIT 1", $repository->getId(), $beginning_of_day));
     $from_days_before--;
     for ($i = $from_days_before; $i >= 0; $i--) {
         $date = new DateTimeValue($i . 'days ago');
         $this_date_beginning = $date->beginningOfDay();
         $this_date_end = $date->endOfDay();
         $commits_count = Commits::count(array("parent_id = ? AND created_on >= ? AND created_on <= ?", $repository->getId(), $this_date_beginning, $this_date_end));
         $activity[$i]['commits'] = $commits_count;
         $activity[$i]['created_on'] = date('F d, Y', $date->getTimestamp());
         $activity[$i]['percentage'] = round($commits_count * 100 / $max_commits);
     }
     return $activity;
 }
Ejemplo n.º 4
0
 /**
  * Edit timeslot
  *
  * @param void
  * @return null
  */
 function edit()
 {
     $this->setTemplate('add_timeslot');
     $timeslot = Timeslots::findById(get_id());
     if (!$timeslot instanceof Timeslot) {
         flash_error(lang('timeslot dnx'));
         ajx_current("empty");
         return;
     }
     $object = $timeslot->getRelObject();
     if (!$object instanceof ContentDataObject) {
         flash_error(lang('object dnx'));
         ajx_current("empty");
         return;
     }
     if (!$object->canAddTimeslot(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     if (!$timeslot->canEdit(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $timeslot_data = array_var($_POST, 'timeslot');
     if (!is_array($timeslot_data)) {
         $timeslot_data = array('contact_id' => $timeslot->getContactId(), 'description' => $timeslot->getDescription(), 'start_time' => $timeslot->getStartTime(), 'end_time' => $timeslot->getEndTime(), 'is_fixed_billing' => $timeslot->getIsFixedBilling(), 'hourly_billing' => $timeslot->getHourlyBilling(), 'fixed_billing' => $timeslot->getFixedBilling());
     }
     tpl_assign('timeslot_form_object', $object);
     tpl_assign('timeslot', $timeslot);
     tpl_assign('timeslot_data', $timeslot_data);
     tpl_assign('show_billing', BillingCategories::count() > 0);
     if (is_array(array_var($_POST, 'timeslot'))) {
         try {
             $this->percent_complete_delete($timeslot);
             $timeslot->setContactId(array_var($timeslot_data, 'contact_id', logged_user()->getId()));
             $timeslot->setDescription(array_var($timeslot_data, 'description'));
             $st = getDateValue(array_var($timeslot_data, 'start_value'), DateTimeValueLib::now());
             $st->setHour(array_var($timeslot_data, 'start_hour'));
             $st->setMinute(array_var($timeslot_data, 'start_minute'));
             $et = getDateValue(array_var($timeslot_data, 'end_value'), DateTimeValueLib::now());
             $et->setHour(array_var($timeslot_data, 'end_hour'));
             $et->setMinute(array_var($timeslot_data, 'end_minute'));
             $st = new DateTimeValue($st->getTimestamp() - logged_user()->getTimezone() * 3600);
             $et = new DateTimeValue($et->getTimestamp() - logged_user()->getTimezone() * 3600);
             $timeslot->setStartTime($st);
             $timeslot->setEndTime($et);
             if ($timeslot->getStartTime() > $timeslot->getEndTime()) {
                 flash_error(lang('error start time after end time'));
                 ajx_current("empty");
                 return;
             }
             $seconds = array_var($timeslot_data, 'subtract_seconds', 0);
             $minutes = array_var($timeslot_data, 'subtract_minutes', 0);
             $hours = array_var($timeslot_data, 'subtract_hours', 0);
             $subtract = $seconds + 60 * $minutes + 3600 * $hours;
             if ($subtract < 0) {
                 flash_error(lang('pause time cannot be negative'));
                 ajx_current("empty");
                 return;
             }
             $testEndTime = new DateTimeValue($timeslot->getEndTime()->getTimestamp());
             $testEndTime->add('s', -$subtract);
             if ($timeslot->getStartTime() > $testEndTime) {
                 flash_error(lang('pause time cannot exceed timeslot time'));
                 ajx_current("empty");
                 return;
             }
             $timeslot->setSubtract($subtract);
             if ($timeslot->getUser()->getDefaultBillingId()) {
                 $timeslot->setIsFixedBilling(array_var($timeslot_data, 'is_fixed_billing', false));
                 $timeslot->setHourlyBilling(array_var($timeslot_data, 'hourly_billing', 0));
                 if ($timeslot->getIsFixedBilling()) {
                     $timeslot->setFixedBilling(array_var($timeslot_data, 'fixed_billing', 0));
                 } else {
                     $timeslot->setFixedBilling($timeslot->getHourlyBilling() * $timeslot->getMinutes() / 60);
                 }
                 if ($timeslot->getBillingId() == 0 && ($timeslot->getHourlyBilling() > 0 || $timeslot->getFixedBilling() > 0)) {
                     $timeslot->setBillingId($timeslot->getUser()->getDefaultBillingId());
                 }
             }
             DB::beginWork();
             $timeslot->save();
             $timeslot_time = ($timeslot->getEndTime()->getTimestamp() - ($timeslot->getStartTime()->getTimestamp() + $timeslot->getSubtract())) / 3600;
             $task = ProjectTasks::findById($timeslot->getRelObjectId());
             if ($task->getTimeEstimate() > 0) {
                 $timeslot_percent = round($timeslot_time * 100 / ($task->getTimeEstimate() / 60));
                 $total_percentComplete = $timeslot_percent + $task->getPercentCompleted();
                 if ($total_percentComplete < 0) {
                     $total_percentComplete = 0;
                 }
                 $task->setPercentCompleted($total_percentComplete);
                 $task->save();
             }
             $this->notifier_work_estimate($task);
             DB::commit();
             flash_success(lang('success edit timeslot'));
             ajx_current("back");
         } catch (Exception $e) {
             DB::rollback();
             Logger::log($e->getTraceAsString());
             flash_error(lang('error edit timeslot') . ": " . $e->getMessage());
             ajx_current("empty");
         }
     }
 }
Ejemplo n.º 5
0
	static function FormatTimeDiff(DateTimeValue $dt1, DateTimeValue $dt2=null, $format='yfwdhms', $modulus = 1, $subtract = 0){
		$t1 = $dt1->getTimestamp();
		if ($dt2)
			$t2 = $dt2->getTimestamp();
		else
			$t2 = time();
		$s = abs($t2 - $t1);
		$s -= $subtract;
		$s = $s - ($s % $modulus);
		$sign = $t2 > $t1 ? 1 : -1;
		$out = array();
		$left = $s;
		$format = array_unique(str_split(preg_replace('`[^yfwdhms]`', '', strtolower($format))));
		$format_count = count($format);
		$a = array('y'=>31556926, 'f'=>2629744, 'w'=>604800, 'd'=>86400, 'h'=>3600, 'm'=>60, 's'=>1);
		$i = 0;
		foreach($a as $k=>$v){
			if(in_array($k, $format)){
				++$i;
				if($i != $format_count){
					$out[$k] = $sign * (int)($left / $v);
					$left = $left % $v;
				}else{
					$out[$k] = $sign * ($left / $v);
				}
			}else{
				$out[$k] = 0;
			}
		}
		$result = '';
		if ($out['y'] > 0)
			$result .= ($result != ''? ', ':'') . ($out['y'] > 1 ? lang("x years", $out['y']) : lang("1 year"));
		if ($out['f'] > 0)
			$result .= ($result != ''? ', ':'') . ($out['f'] > 1 ? lang("x months", $out['f']) : lang("1 month"));
		if ($out['w'] > 0)
			$result .= ($result != ''? ', ':'') . ($out['w'] > 1 ? lang("x weeks", $out['w']) : lang("1 week"));
		if ($out['d'] > 0)
			$result .= ($result != ''? ', ':'') . ($out['d'] > 1 ? lang("x days", $out['d']) : lang("1 day"));
		if ($out['h'] > 0)
			$result .= ($result != ''? ', ':'') . ($out['h'] > 1 ? lang("x hours", $out['h']) : lang("1 hour"));
		if ($out['m'] > 0)
			$result .= ($result != ''? ', ':'') . ($out['m'] > 1 ? lang("x minutes", $out['m']) : lang("1 minute"));
		if ($out['s'] > 0)
			$result .= ($result != ''? ', ':'') . ($out['s'] > 1 ? lang("x seconds", $out['s']) : lang("1 second"));
			
		if ($result == '')
			$result = '< ' . lang("1 minute");
		return $result;
	}
Ejemplo n.º 6
0
 /**
  * Return formated time
  *
  * @access public
  * @param DateTimeValue $date
  * @param float $timezone Timezone offset in hours
  * @return string
  */
 function formatTime(DateTimeValue $date, $timezone = 0)
 {
     $lang_time_format = $this->langs->get('time format', null);
     $time_format = $lang_time_format ? $lang_time_format : $this->time_format;
     return $this->date_lang($time_format, $date->getTimestamp() + $timezone * 3600);
 }
Ejemplo n.º 7
0
            ?>
 
		  </td>
		  <?php 
        }
        ?>
		
		  
		  <?php 
        if (array_var($draw_options, 'show_end_dates')) {
            ?>
		  <td class="task-date-container">
		    <?php 
            if (array_var($task, 'dueDate')) {
                $date = new DateTimeValue(array_var($task, 'dueDate'));
                $due_date_late = $date->getTimestamp() < DateTimeValueLib::now()->getTimestamp();
                ?>
		     <?php 
                if ($due_date_late) {
                    ?>
		     <span class="nobr" style='font-size: 9px;font-weight:bold;color: #F00;'><?php 
                    echo format_datetime($date, null, 0);
                    ?>
</span>  
		     <?php 
                } else {
                    ?>
		     <span class="nobr" style='font-size: 9px;color: #888;'><?php 
                    echo format_datetime($date, null, 0);
                    ?>
</span>
 /**
  * Return Day milestones
  *
  * @access public
  * @param DateTimeValue $date_start in user gmt
  * @param DateTimeValue $date_end	in user gmt	 * 
  */
 function getRangeMilestones(DateTimeValue $date_start, DateTimeValue $date_end, $archived = false)
 {
     $from_date = new DateTimeValue($date_start->getTimestamp());
     $from_date = $from_date->beginningOfDay();
     $to_date = new DateTimeValue($date_end->getTimestamp());
     $to_date = $to_date->endOfDay();
     //set dates to gmt 0 for sql
     $from_date->advance(-logged_user()->getTimezone() * 3600);
     $to_date->advance(-logged_user()->getTimezone() * 3600);
     $archived_cond = " AND `archived_on` " . ($archived ? "<>" : "=") . " 0";
     $conditions = DB::prepareString(' AND `is_template` = false AND `completed_on` = ? AND (`due_date` >= ? AND `due_date` < ?) ' . $archived_cond, array(EMPTY_DATETIME, $from_date, $to_date));
     $result = self::instance()->listing(array("extra_conditions" => $conditions));
     return $result->objects;
 }
Ejemplo n.º 9
0
 /**
  * Difference to another DateTime
  *
  * @param void
  * @param integer $input 
  * @return integer $seconds
  */
 function difference(DateTimeValue $input)
 {
     return $this->getTimestamp() - $input->getTimestamp();
 }
 function cron_events()
 {
     if (!can_manage_configuration(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     // if
     $events = CronEvents::getUserEvents();
     tpl_assign("events", $events);
     $cron_events = array_var($_POST, 'cron_events');
     if (is_array($cron_events)) {
         try {
             DB::beginWork();
             foreach ($cron_events as $id => $data) {
                 $event = CronEvents::findById($id);
                 $date = getDateValue($data['date']);
                 if ($date instanceof DateTimeValue) {
                     $this->parseTime($data['time'], $hour, $minute);
                     $date->add("m", $minute);
                     $date->add("h", $hour);
                     $date = new DateTimeValue($date->getTimestamp() - logged_user()->getTimezone() * 3600);
                     $event->setDate($date);
                 }
                 $delay = $data['delay'];
                 if (is_numeric($delay)) {
                     $event->setDelay($delay);
                 }
                 $enabled = array_var($data, 'enabled') == 'checked';
                 $event->setEnabled($enabled);
                 $event->save();
             }
             DB::commit();
             flash_success(lang("success update cron events"));
             ajx_current("back");
         } catch (Exception $ex) {
             DB::rollback();
             flash_error($ex->getMessage());
         }
     }
 }
 function total_task_times_vs_estimate_comparison($report_data = null, $task = null)
 {
     $this->setTemplate('report_wrapper');
     if (!$report_data) {
         $report_data = array_var($_POST, 'report');
     }
     $workspace = Projects::findById(array_var($report_data, 'project_id'));
     if ($workspace instanceof Project) {
         if (array_var($report_data, 'include_subworkspaces')) {
             $workspacesCSV = $workspace->getAllSubWorkspacesQuery(false);
         } else {
             $workspacesCSV = $workspace->getId();
         }
     } else {
         $workspacesCSV = null;
     }
     $start = getDateValue(array_var($report_data, 'start_value'));
     $end = getDateValue(array_var($report_data, 'end_value'));
     $st = $start->beginningOfDay();
     $et = $end->endOfDay();
     $st = new DateTimeValue($st->getTimestamp() - logged_user()->getTimezone() * 3600);
     $et = new DateTimeValue($et->getTimestamp() - logged_user()->getTimezone() * 3600);
     $timeslots = Timeslots::getTimeslotsByUserWorkspacesAndDate($st, $et, 'ProjectTasks', null, $workspacesCSV, array_var($report_data, 'task_id', 0));
     tpl_assign('timeslots', $timeslots);
     tpl_assign('workspace', $workspace);
     tpl_assign('start_time', $st);
     tpl_assign('end_time', $et);
     tpl_assign('user', $user);
     tpl_assign('post', $report_data);
     tpl_assign('template_name', 'total_task_times');
     tpl_assign('title', lang('task time report'));
 }
Ejemplo n.º 12
0
 function getRangeContactsByBirthday($from, $to, $tags = '', $project = null)
 {
     if (!$from instanceof DateTimeValue || !$to instanceof DateTimeValue || $from->getTimestamp() > $to->getTimestamp()) {
         return array();
     }
     $from = new DateTimeValue($from->getTimestamp());
     $from->beginningOfDay();
     $to = new DateTimeValue($to->getTimestamp());
     $to->endOfDay();
     $year1 = $from->getYear();
     $year2 = $to->getYear();
     if ($year1 == $year2) {
         $condition = 'DAYOFYEAR(`birthday`) >= DAYOFYEAR(' . DB::escape($from) . ')' . ' AND DAYOFYEAR(`birthday`) <= DAYOFYEAR(' . DB::escape($to) . ')';
     } else {
         if ($year2 - $year1 == 1) {
             $condition = 'DAYOFYEAR(`birthday`) >= DAYOFYEAR(' . DB::escape($from) . ')' . ' OR DAYOFYEAR(`birthday`) <= DAYOFYEAR(' . DB::escape($to) . ')';
         } else {
             $condition = "`birthday` <> '0000-00-00 00:00:00'";
         }
     }
     return $this->getAllowedContacts($condition);
 }
Ejemplo n.º 13
0
 function instantiate()
 {
     $selected_members = array();
     $id = get_id();
     $template = COTemplates::findById($id);
     if (!$template instanceof COTemplate) {
         flash_error(lang("template dnx"));
         ajx_current("empty");
         return;
     }
     $parameters = TemplateParameters::getParametersByTemplate($id);
     $parameterValues = array_var($_POST, 'parameterValues');
     if (count($parameters) > 0 && !isset($parameterValues)) {
         ajx_current("back");
         return;
     }
     if (array_var($_POST, 'members')) {
         $selected_members = json_decode(array_var($_POST, 'members'));
     } else {
         $context = active_context();
         foreach ($context as $selection) {
             if ($selection instanceof Member) {
                 $selected_members[] = $selection->getId();
             }
         }
     }
     $objects = $template->getObjects();
     $controller = new ObjectController();
     if (count($selected_members > 0)) {
         $selected_members_instances = Members::findAll(array('conditions' => 'id IN (' . implode($selected_members) . ')'));
     } else {
         $selected_members_instances = array();
     }
     DB::beginWork();
     $active_context = active_context();
     foreach ($objects as $object) {
         if (!$object instanceof ContentDataObject) {
             continue;
         }
         // copy object
         $copy = $object->copy();
         if ($copy->columnExists('is_template')) {
             $copy->setColumnValue('is_template', false);
         }
         if ($copy instanceof ProjectTask) {
             // don't copy parent task and milestone
             $copy->setMilestoneId(0);
             $copy->setParentId(0);
         }
         $copy->save();
         /*		if (!can_write(logged_user(), $selected_members_instances, $copy->getObjectTypeId()) ) {
         				flash_error(lang('no context permissions to add', $copy instanceof ProjectTask ? lang("tasks") : ($copy instanceof ProjectMilestone ? lang('milestones') : '')));
         				DB::rollback();
         				ajx_current("empty");
         				return;
         			}*/
         // Copy members from origial object, if it doesn't have then use active context members
         /*	$template_object_members = $object->getMemberIds();
         			if (count($template_object_members) == 0) {
         				$object_member_ids = active_context_members(false);
         				if (count($object_member_ids) > 0) {
         					$template_object_members = Members::findAll(array("id" => true, "conditions" => "id IN (".implode(",", $object_member_ids).")"));
         				}
         			}*/
         /* Set instantiated object members:
          * foreach dimension:
          * 		if no member is active then the instantiated object is put in the same members as the original for current dimension
          * 		if a member is selected in current dimension then the instantiated object will be put in that member  
          */
         $template_object_members = $object->getMembers();
         $object_members = array();
         foreach ($active_context as $selection) {
             if ($selection instanceof Member) {
                 // member selected
                 $object_members[] = $selection->getId();
             } else {
                 if ($selection instanceof Dimension) {
                     // no member selected
                     foreach ($template_object_members as $tom) {
                         if ($tom->getDimensionId() == $selection->getId()) {
                             $object_members[] = $tom->getId();
                         }
                     }
                 }
             }
         }
         $controller->add_to_members($copy, $object_members);
         // copy linked objects
         $copy->copyLinkedObjectsFrom($object);
         // copy subtasks if applicable
         if ($copy instanceof ProjectTask) {
             ProjectTasks::copySubTasks($object, $copy, false);
             foreach ($copy->getOpenSubTasks(false) as $m_task) {
                 $controller->add_to_members($m_task, $object_members);
             }
             $manager = $copy->manager();
         } else {
             if ($copy instanceof ProjectMilestone) {
                 ProjectMilestones::copyTasks($object, $copy, false);
                 foreach ($copy->getTasks(false) as $m_task) {
                     $controller->add_to_members($m_task, $object_members);
                 }
                 $manager = $copy->manager();
             }
         }
         // copy custom properties
         $copy->copyCustomPropertiesFrom($object);
         // set property values as defined in template
         $objProp = TemplateObjectProperties::getPropertiesByTemplateObject($id, $object->getId());
         foreach ($objProp as $property) {
             $propName = $property->getProperty();
             $value = $property->getValue();
             if ($manager->getColumnType($propName) == DATA_TYPE_STRING || $manager->getColumnType($propName) == DATA_TYPE_INTEGER) {
                 if (is_array($parameterValues)) {
                     foreach ($parameterValues as $param => $val) {
                         if (strpos($value, '{' . $param . '}') !== FALSE) {
                             $value = str_replace('{' . $param . '}', $val, $value);
                         }
                     }
                 }
             } else {
                 if ($manager->getColumnType($propName) == DATA_TYPE_DATE || $manager->getColumnType($propName) == DATA_TYPE_DATETIME) {
                     $operator = '+';
                     if (strpos($value, '+') === false) {
                         $operator = '-';
                     }
                     $opPos = strpos($value, $operator);
                     if ($opPos !== false) {
                         // Is parametric
                         $dateParam = substr($value, 1, strpos($value, '}') - 1);
                         $date = $parameterValues[$dateParam];
                         $dateUnit = substr($value, strlen($value) - 1);
                         // d, w or m (for days, weeks or months)
                         if ($dateUnit == 'm') {
                             $dateUnit = 'M';
                             // make month unit uppercase to call DateTimeValue::add with correct parameter
                         }
                         $dateNum = (int) substr($value, strpos($value, $operator), strlen($value) - 2);
                         $date = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $date);
                         $date = new DateTimeValue($date->getTimestamp() - logged_user()->getTimezone() * 3600);
                         // set date to GMT 0
                         $value = $date->add($dateUnit, $dateNum);
                     } else {
                         $value = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $value);
                     }
                 }
             }
             if ($value != '') {
                 if (!$copy->setColumnValue($propName, $value)) {
                     $copy->object->setColumnValue($propName, $value);
                 }
                 $copy->save();
             }
         }
         // subscribe assigned to
         if ($copy instanceof ProjectTask) {
             foreach ($copy->getOpenSubTasks(false) as $m_task) {
                 if ($m_task->getAssignedTo() instanceof Contact) {
                     $m_task->subscribeUser($copy->getAssignedTo());
                 }
             }
             if ($copy->getAssignedTo() instanceof Contact) {
                 $copy->subscribeUser($copy->getAssignedTo());
             }
         } else {
             if ($copy instanceof ProjectMilestone) {
                 foreach ($copy->getTasks(false) as $m_task) {
                     if ($m_task->getAssignedTo() instanceof Contact) {
                         $m_task->subscribeUser($copy->getAssignedTo());
                     }
                 }
             }
         }
         // copy reminders
         $reminders = ObjectReminders::getByObject($object);
         foreach ($reminders as $reminder) {
             $copy_reminder = new ObjectReminder();
             $copy_reminder->setContext($reminder->getContext());
             $reminder_date = $copy->getColumnValue($reminder->getContext());
             if ($reminder_date instanceof DateTimeValue) {
                 $reminder_date = new DateTimeValue($reminder_date->getTimestamp());
                 $reminder_date->add('m', -$reminder->getMinutesBefore());
             }
             $copy_reminder->setDate($reminder_date);
             $copy_reminder->setMinutesBefore($reminder->getMinutesBefore());
             $copy_reminder->setObject($copy);
             $copy_reminder->setType($reminder->getType());
             $copy_reminder->setUserId($reminder->getUserId());
             $copy_reminder->save();
         }
     }
     DB::commit();
     if (is_array($parameters) && count($parameters) > 0) {
         ajx_current("back");
     } else {
         if (!$choose_ctx) {
             ajx_current("back");
         } else {
             ajx_current("reload");
         }
     }
 }
 function move_event()
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $event = ProjectEvents::findById(get_id());
     if (!$event->canEdit(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $is_read = $event->getIsRead(logged_user()->getId());
     $year = array_var($_GET, 'year', $event->getStart()->getYear());
     $month = array_var($_GET, 'month', $event->getStart()->getMonth());
     $day = array_var($_GET, 'day', $event->getStart()->getDay());
     $hour = array_var($_GET, 'hour', 0);
     $min = array_var($_GET, 'min', 0);
     if ($hour == -1) {
         $hour = format_date($event->getStart(), 'H', logged_user()->getTimezone());
     }
     if ($min == -1) {
         $min = format_date($event->getStart(), 'i', logged_user()->getTimezone());
     }
     if ($event->isRepetitive()) {
         $orig_date = DateTimeValueLib::dateFromFormatAndString('Y-m-d H:i:s', array_var($_GET, 'orig_date'));
         $diff = DateTimeValueLib::get_time_difference($orig_date->getTimestamp(), mktime($hour, $min, 0, $month, $day, $year));
         $new_start = new DateTimeValue($event->getStart()->getTimestamp());
         $new_start->add('d', $diff['days']);
         $new_start->add('h', $diff['hours']);
         $new_start->add('m', $diff['minutes']);
         if ($event->getRepeatH()) {
             $event->setRepeatDow(date("w", mktime($hour, $min, 0, $month, $day, $year)) + 1);
             $wnum = 0;
             $tmp_day = $new_start->getDay();
             while ($tmp_day > 0) {
                 $tmp_day -= 7;
                 $wnum++;
             }
             $event->setRepeatWnum($wnum);
         }
     } else {
         $new_start = new DateTimeValue(mktime($hour, $min, 0, $month, $day, $year) - logged_user()->getTimezone() * 3600);
     }
     $diff = DateTimeValueLib::get_time_difference($event->getStart()->getTimestamp(), $event->getDuration()->getTimestamp());
     $new_duration = new DateTimeValue($new_start->getTimestamp());
     $new_duration->add('d', $diff['days']);
     $new_duration->add('h', $diff['hours']);
     $new_duration->add('m', $diff['minutes']);
     // see if we have to reload
     $os = format_date($event->getStart(), 'd', logged_user()->getTimezone());
     $od = format_date($event->getDuration(), 'd', logged_user()->getTimezone());
     $ohm = format_date($event->getDuration(), 'H:i', logged_user()->getTimezone());
     $nd = format_date($new_duration, 'd', logged_user()->getTimezone());
     $nhm = format_date($new_duration, 'H:i', logged_user()->getTimezone());
     $different_days = $os != $od && $ohm != '00:00' || $day != $nd && $nhm != '00:00';
     DB::beginWork();
     $event->setStart($new_start->format("Y-m-d H:i:s"));
     $event->setDuration($new_duration->format("Y-m-d H:i:s"));
     $event->save();
     if (!$is_read) {
         $event->setIsRead(logged_user()->getId(), false);
     }
     DB::commit();
     ajx_extra_data($this->get_updated_event_data($event));
     if ($different_days || $event->isRepetitive()) {
         ajx_current("reload");
     } else {
         ajx_current("empty");
     }
 }
Ejemplo n.º 15
0
 /**
  * Return fromated time
  *
  * @access public
  * @param DateTimeValue $date
  * @param float $timezone Timezone offset in hours
  * @return string
  */
 function formatTime(DateTimeValue $date, $timezone = 0)
 {
     return date($this->time_format, $date->getTimestamp() + $timezone * 3600);
 }
Ejemplo n.º 16
0
 function move_event()
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $event = ProjectEvents::findById(get_id());
     if (!$event->canEdit(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $is_read = $event->getIsRead(logged_user()->getId());
     $year = array_var($_GET, 'year', $event->getStart()->getYear());
     $month = array_var($_GET, 'month', $event->getStart()->getMonth());
     $day = array_var($_GET, 'day', $event->getStart()->getDay());
     $hour = array_var($_GET, 'hour', 0);
     $min = array_var($_GET, 'min', 0);
     if ($hour == -1) {
         $hour = format_date($event->getStart(), 'H', logged_user()->getTimezone());
     }
     if ($min == -1) {
         $min = format_date($event->getStart(), 'i', logged_user()->getTimezone());
     }
     if ($event->isRepetitive()) {
         $orig_date = DateTimeValueLib::dateFromFormatAndString('Y-m-d H:i:s', array_var($_GET, 'orig_date'));
         $diff = DateTimeValueLib::get_time_difference($orig_date->getTimestamp(), mktime($hour, $min, 0, $month, $day, $year));
         $new_start = new DateTimeValue($event->getStart()->getTimestamp());
         $new_start->add('d', $diff['days']);
         $new_start->add('h', $diff['hours']);
         $new_start->add('m', $diff['minutes']);
         if ($event->getRepeatH()) {
             $event->setRepeatDow(date("w", mktime($hour, $min, 0, $month, $day, $year)) + 1);
             $wnum = 0;
             $tmp_day = $new_start->getDay();
             while ($tmp_day > 0) {
                 $tmp_day -= 7;
                 $wnum++;
             }
             $event->setRepeatWnum($wnum);
         }
     } else {
         $new_start = new DateTimeValue(mktime($hour, $min, 0, $month, $day, $year) - logged_user()->getTimezone() * 3600);
     }
     $diff = DateTimeValueLib::get_time_difference($event->getStart()->getTimestamp(), $event->getDuration()->getTimestamp());
     $new_duration = new DateTimeValue($new_start->getTimestamp());
     $new_duration->add('d', $diff['days']);
     $new_duration->add('h', $diff['hours']);
     $new_duration->add('m', $diff['minutes']);
     // see if we have to reload
     $os = format_date($event->getStart(), 'd', logged_user()->getTimezone());
     $od = format_date($event->getDuration(), 'd', logged_user()->getTimezone());
     $ohm = format_date($event->getDuration(), 'H:i', logged_user()->getTimezone());
     $nd = format_date($new_duration, 'd', logged_user()->getTimezone());
     $nhm = format_date($new_duration, 'H:i', logged_user()->getTimezone());
     $different_days = $os != $od && $ohm != '00:00' || $day != $nd && $nhm != '00:00';
     DB::beginWork();
     $event->setStart($new_start->format("Y-m-d H:i:s"));
     $event->setDuration($new_duration->format("Y-m-d H:i:s"));
     $event->save();
     $old_reminders = ObjectReminders::getByObject($event);
     if ($old_reminders != null) {
         $object_controller = new ObjectController();
         $object_controller->update_reminders($event, $old_reminders);
         //updating the old ones
     } else {
         if (user_config_option("add_event_autoreminder")) {
             $reminder = new ObjectReminder();
             $def = explode(",", user_config_option("reminders_events"));
             $minutes = array_var($def, 2) * array_var($def, 1);
             $reminder->setMinutesBefore($minutes);
             $reminder->setType(array_var($def, 0));
             $reminder->setContext("start");
             $reminder->setObject($event);
             $reminder->setUserId(0);
             $date = $event->getStart();
             if ($date instanceof DateTimeValue) {
                 $rdate = new DateTimeValue($date->getTimestamp() - $minutes * 60);
                 $reminder->setDate($rdate);
             }
             $reminder->save();
         }
     }
     if (!$is_read) {
         $event->setIsRead(logged_user()->getId(), false);
     }
     DB::commit();
     if ($event->getSpecialID() != "") {
         $externalCalendarController = new ExternalCalendarController();
         $externalCalendarController->sync_event_on_extern_calendar($event);
     }
     ajx_extra_data($this->get_updated_event_data($event));
     if ($different_days || $event->isRepetitive()) {
         ajx_current("reload");
     } else {
         ajx_current("empty");
     }
 }
Ejemplo n.º 17
0
    /**
     * Return Day tasks this user have access on 
     *
     * @access public
     * @param DateTimeValue $date_start in user gmt
     * @param DateTimeValue $date_end	in user gmt 
     * @return array
     */
    function getRangeTasksByUser(DateTimeValue $date_start, DateTimeValue $date_end, $assignedUser, $task_filter = null, $archived = false, $raw_data = false)
    {
        $from_date = new DateTimeValue($date_start->getTimestamp());
        $from_date = $from_date->beginningOfDay();
        $to_date = new DateTimeValue($date_end->getTimestamp());
        $to_date = $to_date->endOfDay();
        //set dates to gmt 0 for sql
        $from_date->advance(-logged_user()->getTimezone() * 3600);
        $to_date->advance(-logged_user()->getTimezone() * 3600);
        $assignedFilter = '';
        if ($assignedUser instanceof Contact) {
            $assignedFilter = ' AND (`assigned_to_contact_id` = ' . $assignedUser->getId() . ' OR `assigned_to_contact_id` = \'' . $assignedUser->getCompanyId() . '\') ';
        }
        $rep_condition = " (`repeat_forever` = 1 OR `repeat_num` > 0 OR (`repeat_end` > 0 AND `repeat_end` >= '" . $from_date->toMySQL() . "')) ";
        $archived_cond = " AND `archived_on` " . ($archived ? '<>' : '=') . " 0";
        $conditions = DB::prepareString(' AND `is_template` = false AND `completed_on` ' . ($task_filter == 'complete' ? '<>' : '=') . ' ? AND 
			(IF(due_date>0,(`due_date` >= ? AND `due_date` < ?),false) OR IF(start_date>0,(`start_date` >= ? AND `start_date` < ?),false) OR ' . $rep_condition . ') ' . $archived_cond . $assignedFilter, array(EMPTY_DATETIME, $from_date, $to_date, $from_date, $to_date));
        $other_perm_conditions = SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks');
        if (!$other_perm_conditions) {
            $conditions = " AND (`assigned_to_contact_id` = " . logged_user()->getId() . " OR `created_by_id` = " . logged_user()->getId() . ")";
        }
        $result = self::instance()->listing(array("extra_conditions" => $conditions, "raw_data" => $raw_data));
        return $result->objects;
    }
Ejemplo n.º 18
0
 /**
  * Return fromated time
  *
  * @access public
  * @param DateTimeValue $date
  * @param float $timezone Timezone offset in hours
  * @return string
  */
 function formatTime(DateTimeValue $date, $timezone = 0)
 {
     return $this->dateByLocalization($this->time_format, $date->getTimestamp(), $timezone);
 }
Ejemplo n.º 19
0
	function generateICalInfo($events, $calendar_name, $user = null) {
		if ($user == null) $user = logged_user();
		$ical_info = '';
		$ical_info .= "BEGIN:VCALENDAR\r\n";
		$ical_info .= "VERSION:2.0\r\n";
		$ical_info .= "PRODID:PHP\r\n";
		$ical_info .= "METHOD:REQUEST\r\n";
		$ical_info .= "X-WR-CALNAME:$calendar_name\r\n";
		
		// timezone info
		$tz = ($user->getTimezone() < 0 ? "-":"+").str_pad(abs($user->getTimezone())*100, 4, '0', STR_PAD_LEFT);
		$tz_desc = $user->getTimezone() > 0 ? lang("timezone gmt +".$user->getTimezone()) : lang("timezone gmt ".$user->getTimezone());
		$ical_info .= "BEGIN:VTIMEZONE\r\n";
		$ical_info .= "TZID:$tz_desc\r\n";
		$ical_info .= "BEGIN:STANDARD\r\n";
		$ical_info .= "TZOFFSETFROM:$tz\r\n";
		$ical_info .= "TZOFFSETTO:$tz\r\n";
		$ical_info .= "END:STANDARD\r\n";
		$ical_info .= "END:VTIMEZONE\r\n";
		
		foreach ($events as $event) {
			$ical_info .= "BEGIN:VEVENT\r\n";
			
			$event_start = new DateTimeValue($event->getStart()->getTimestamp() + 3600 * $user->getTimezone());
			$event_duration = new DateTimeValue($event->getDuration()->getTimestamp() + 3600 * $user->getTimezone());
			
			$startNext = new DateTimeValue($event_start->getTimestamp());
			$startNext->add('d', 1);
			if ($event->getTypeId() == 2) $ical_info .= "DTSTART;VALUE=DATE:" . $event_start->format('Ymd') ."\r\n";
			else $ical_info .= "DTSTART:" . $event_start->format('Ymd') ."T". $event_start->format('His') ."\r\n";
			if ($event->getTypeId() == 2) $ical_info .= "DTEND;VALUE=DATE:" . $startNext->format('Ymd') ."\r\n";
			else $ical_info .= "DTEND:" . $event_duration->format('Ymd') ."T". $event_duration->format('His') ."\r\n";

			$uid = $event->getId() . "@";
			$url = str_replace('http://', '', ROOT_URL);
			$uid .= str_replace('www.', '', $url);
			
			$description = str_replace(array(chr(13).chr(10), chr(13), chr(10)),'\n', $event->getDescription());
			$ical_info .= "DESCRIPTION:$description\r\n";
            $ical_info .= "SUMMARY:" . $event->getSubject() . "\r\n";
		    $ical_info .= "UID:$uid\r\n";
		    $ical_info .= "SEQUENCE:0\r\n";
		    $ical_info .= "DTSTAMP:".$event->getUpdatedOn()->format('Ymd').'T'.$event->getUpdatedOn()->format('His')."\r\n";
			
		    $invitations = $event->getInvitations();
			if (is_array($invitations) && array_var($invitations, $user->getId())) {
				$inv = array_var($invitations, $user->getId());
		    	$inv->getInvitationState();
		    	if ($inv->getInvitationState() == 1) $ical_info .= "STATUS:CONFIRMED\r\n"; 
		    	else if ($inv->getInvitationState() == 2) $ical_info .= "STATUS:CANCELLED\r\n";
		    	else $ical_info .= "STATUS:TENTATIVE\r\n";
			}
			$rrule = '';
			if ($event->getRepeatD() > 0 || $event->getRepeatM() > 0 || $event->getRepeatY() > 0 || $event->getRepeatForever() > 0) {
				$rrule_ok = true;
				if ($event->getRepeatD() > 0) {
					if ($event->getRepeatD() % 7 == 0) {
						$freq = "FREQ=WEEKLY;";
						$interval = "INTERVAL=".($event->getRepeatD() / 7);
					} else {
						$freq = "FREQ=DAILY;";
						$interval = "INTERVAL=".$event->getRepeatD();
					}
				} else if ($event->getRepeatM() > 0) {
					$freq = "FREQ=MONTHLY;";
					$interval = "INTERVAL=".$event->getRepeatM();
				} else if ($event->getRepeatY() > 0) {
					$freq = "FREQ=YEARLY;";
					$interval = "INTERVAL=".$event->getRepeatY();
				} else {
					$rrule_ok = false;
				}
				$until = '';
				$count = '';
				if (!$event->getRepeatForever() && $event->getRepeatNum() > 0) $count = ";COUNT=".$event->getRepeatNum();
				else if (!$event->getRepeatForever() && $event->getRepeatEnd()) $until = ";UNTIL=".$event->getRepeatEnd()->format('Ymd').'T'.$event->getRepeatEnd()->format('His');
				
				if ($rrule_ok) $rrule = "RRULE:$freq$interval$count$until\r\n";
			}
			if ($event->getRepeatH() > 0) {
				"RRULE:FREQ=MONTHLY;INTERVAL=1;BYDAY=1TU";
				$interval = "INTERVAL=".$event->getRepeatMjump();
				switch ($event->getRepeatDow()) {
					case 1: $day = "SU"; break;
					case 2: $day = "MO"; break;
					case 3: $day = "TU"; break;
					case 4: $day = "WE"; break;
					case 5: $day = "TH"; break;
					case 6: $day = "FR"; break;
					case 7: $day = "SA"; break;
					default: $day = "MO"; break;
				}
				$byday = "BYDAY=" . $event->getRepeatWnum() . $day;
				
				$rrule = "RRULE:FREQ=MONTHLY;$interval;$byday\r\n";
			}
		    $ical_info .= $rrule;
		    
		    $ical_info .= "END:VEVENT\r\n";
		}
		
		$ical_info .= "END:VCALENDAR\r\n";
		
		return $ical_info;
	}
 /**
  * Returns all events for the given range, tag and considers the active project
  *
  * @param DateTimeValue $date
  * @param String $tags
  * @return unknown
  */
 static function getRangeProjectEvents(DateTimeValue $start_date, DateTimeValue $end_date, $user_filter = null, $inv_state = null)
 {
     $start_year = date("Y", mktime(0, 0, 1, $start_date->getMonth(), $start_date->getDay(), $start_date->getYear()));
     $start_month = date("m", mktime(0, 0, 1, $start_date->getMonth(), $start_date->getDay(), $start_date->getYear()));
     $start_day = date("d", mktime(0, 0, 1, $start_date->getMonth(), $start_date->getDay(), $start_date->getYear()));
     $end_year = date("Y", mktime(0, 0, 1, $end_date->getMonth(), $end_date->getDay(), $end_date->getYear()));
     $end_month = date("m", mktime(0, 0, 1, $end_date->getMonth(), $end_date->getDay(), $end_date->getYear()));
     $end_day = date("d", mktime(0, 0, 1, $end_date->getMonth(), $end_date->getDay(), $end_date->getYear()));
     if (!is_numeric($start_day) or !is_numeric($start_month) or !is_numeric($start_year) or !is_numeric($end_day) or !is_numeric($end_month) or !is_numeric($end_year)) {
         return NULL;
     }
     $user = null;
     if ($user_filter > 0) {
         $user = Contacts::findById($user_filter);
     }
     if ($user_filter != -1 && !$user instanceof Contact) {
         $user = logged_user();
     }
     $invited = "";
     if ($user instanceof Contact) {
         $invited = " AND o.`id` IN (SELECT `event_id` FROM `" . TABLE_PREFIX . "event_invitations` WHERE `contact_id` = " . $user->getId() . ")";
     }
     $tz_hm = "'" . floor(logged_user()->getTimezone()) . ":" . abs(logged_user()->getTimezone()) % 1 * 60 . "'";
     $s_date = new DateTimeValue($start_date->getTimestamp() - logged_user()->getTimezone() * 3600);
     $e_date = new DateTimeValue($end_date->getTimestamp() - logged_user()->getTimezone() * 3600);
     $e_date->add("d", 1);
     $start_date_str = $s_date->format("Y-m-d H:i:s");
     $end_date_str = $e_date->format("Y-m-d H:i:s");
     $first_d = $start_day;
     while ($first_d > 7) {
         $first_d -= 7;
     }
     $week_of_first_day = date("W", mktime(0, 0, 0, $start_month, $first_d, $start_year));
     $conditions = "\r\n\t\t\tAND (type_id=2 OR type_id=1 AND `duration` > `start`)\r\n\t\t\tAND \r\n\t\t\t(\r\n\t\t\t  (\r\n\t\t\t\t(\r\n\t\t\t\t\t`repeat_h` = 0\r\n\t\t\t\t\tAND `duration` >= '{$start_date_str}' \r\n\t\t\t\t\tAND `start` < '{$end_date_str}' \r\n\t\t\t\t) \r\n\t\t\t\tOR \r\n\t\t\t\t(\r\n\t\t\t\t\toriginal_event_id = 0\r\n\t\t\t\t\tAND\r\n\t\t\t\t\t`repeat_h` = 0 \r\n\t\t\t\t\tAND\r\n\t\t\t\t\tDATE(`start`) < '{$end_date_str}'\r\n\t\t\t\t\tAND\r\n\t\t\t\t\t(\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t(\r\n\t\t\t\t\t\t\tDATE_ADD(`start`, INTERVAL (`repeat_num`-1)*`repeat_d` DAY) >= '{$start_date_str}' \r\n\t\t\t\t\t\t\tOR\r\n\t\t\t\t\t\t\trepeat_forever = 1\r\n\t\t\t\t\t\t\tOR\r\n\t\t\t\t\t\t\trepeat_end >= '{$start_year}-{$start_month}-{$start_day}'\r\n\t\t\t\t\t\t)\r\n\t\t\t\t\t\tOR\r\n\t\t\t\t\t\t(\r\n\t\t\t\t\t\t\tDATE_ADD(`start`, INTERVAL (`repeat_num`-1)*`repeat_m` MONTH) >= '{$start_date_str}' \r\n\t\t\t\t\t\t\tOR\r\n\t\t\t\t\t\t\trepeat_forever = 1\r\n\t\t\t\t\t\t\tOR\r\n\t\t\t\t\t\t\trepeat_end >= '{$start_year}-{$start_month}-{$start_day}'\r\n\t\t\t\t\t\t)\r\n\t\t\t\t\t\tOR\r\n\t\t\t\t\t\t(\r\n\t\t\t\t\t\t\tDATE_ADD(`start`, INTERVAL (`repeat_num`-1)*`repeat_y` YEAR) >= '{$start_date_str}' \r\n\t\t\t\t\t\t\tOR\r\n\t\t\t\t\t\t\trepeat_forever = 1\r\n\t\t\t\t\t\t\tOR\r\n\t\t\t\t\t\t\trepeat_end >= '{$start_year}-{$start_month}-{$start_day}'\r\n\t\t\t\t\t\t)\r\n\t\t\t\t\t)\t\t\r\n\t\t\t\t)\r\n\t\t\t\tOR\r\n\t\t\t\t(\r\n\t\t\t\t\toriginal_event_id = 0\r\n\t\t\t\t\tAND\r\n\t\t\t\t\tDATE(`start`) <= '{$end_date_str}'\r\n\t\t\t\t\tAND\r\n\t\t\t\t\t`repeat_h` = 1 \t\t\t\t\t\r\n\t\t\t\t\tAND\r\n\t\t\t\t\tMOD( ABS(PERIOD_DIFF(DATE_FORMAT(`start`, '%Y%m'), DATE_FORMAT('{$start_date_str}', '%Y%m'))), `repeat_mjump`) = 0\t\t\t\t\t\r\n\t\t\t\t)\r\n\t\t\t  )\r\n\t\t\t  {$invited}\r\n\t\t\t)";
     $result_events = self::instance()->listing(array("order" => 'start', "order_dir" => 'ASC', "extra_conditions" => $conditions))->objects;
     // Find invitations for events and logged user
     if (!($user_filter == null && $inv_state == null) && $user_filter != -1) {
         ProjectEvents::addInvitations($result_events, $user->getId());
         foreach ($result_events as $k => $event) {
             $inv = $event->getInvitations();
             if (!is_array($inv)) {
                 if ($inv == null || trim($inv_state) != '-1' && !strstr($inv_state, '' . $inv->getInvitationState()) && $inv->getContactId() == logged_user()->getId()) {
                     unset($result_events[$k]);
                 }
             } else {
                 if (count($inv) > 0) {
                     foreach ($inv as $key => $v) {
                         if ($v == null || trim($inv_state) != '-1' && !strstr($inv_state, '' . $v->getInvitationState()) && $v->getContactId() == logged_user()->getId()) {
                             unset($result_events[$k]);
                             break;
                         }
                     }
                 } else {
                     unset($result_events[$k]);
                 }
             }
         }
     }
     return $result_events;
 }
Ejemplo n.º 21
0
	/**
	 * Return Day tasks this user have access on
	 *
	 * @access public
	 * @param void
	 * @return array
	 */
	function getRangeTasksByUser(DateTimeValue $date_start, DateTimeValue $date_end, $assignedUser, $task_filter = null, $archived = false) {
		
		$from_date = new DateTimeValue ( $date_start->getTimestamp () - logged_user()->getTimezone() * 3600 );
		$from_date = $from_date->beginningOfDay ();
		$to_date = new DateTimeValue ( $date_end->getTimestamp () - logged_user()->getTimezone() * 3600);
		$to_date = $to_date->endOfDay ();
		
		$assignedFilter = '';
		if ($assignedUser instanceof Contact) {
			$assignedFilter = ' AND (`assigned_to_contact_id` = ' . $assignedUser->getId () . ' OR `assigned_to_contact_id` = \'' . $assignedUser->getCompanyId () . '\') ';
		}
		$rep_condition = " (`repeat_forever` = 1 OR `repeat_num` > 0 OR (`repeat_end` > 0 AND `repeat_end` >= '" . $from_date->toMySQL () . "')) ";
		
		if ($archived)
			$archived_cond = " AND `archived_on` <> 0";
		else
			$archived_cond = " AND `archived_on` = 0";
		
		switch($task_filter){
			case 'complete':
				$conditions = DB::prepareString(' AND `completed_on` <> ?', array(EMPTY_DATETIME));
				break;
			case 'pending':
			default:
				$conditions = DB::prepareString(' AND `is_template` = false AND `completed_on` = ? AND (IF(due_date>0,(`due_date` >= ? AND `due_date` < ?),false) OR IF(start_date>0,(`start_date` >= ? AND `start_date` < ?),false) OR ' . $rep_condition . ') ' . $archived_cond . $assignedFilter, array(EMPTY_DATETIME,$from_date, $to_date, $from_date, $to_date));
				break;
		}
                
		$result = self::instance()->listing(array(
			"extra_conditions" => $conditions
		));
		
		return $result->objects;
	} // getDayTasksByUser
 function cloneTask($new_st_date = '', $new_due_date = '', $copy_status = false, $copy_repeat_options = true, $parent_subtask = 0)
 {
     $new_task = new TemplateTask();
     if ($parent_subtask != 0) {
         $new_task->setParentId($parent_subtask);
     } else {
         $new_task->setParentId($this->getParentId());
     }
     $new_task->setObjectName($this->getObjectName());
     $new_task->setText($this->getText());
     $new_task->setAssignedToContactId($this->getAssignedToContactId());
     $new_task->setAssignedOn($this->getAssignedOn());
     $new_task->setAssignedById($this->getAssignedById());
     $new_task->setTimeEstimate($this->getTimeEstimate());
     $new_task->setStartedOn($this->getStartedOn());
     $new_task->setStartedById($this->getStartedById());
     $new_task->setPriority($this->getPriority());
     $new_task->setState($this->getState());
     $new_task->setOrder($this->getOrder());
     $new_task->setMilestoneId($this->getMilestoneId());
     $new_task->setFromTemplateId($this->getFromTemplateId());
     $new_task->setUseStartTime($this->getUseStartTime());
     $new_task->setUseDueTime($this->getUseDueTime());
     $new_task->setTypeContent($this->getTypeContent());
     if ($this->getParentId() == 0) {
         //if not subtask
         if ($this->getOriginalTaskId() == 0) {
             $new_task->setOriginalTaskId($this->getObjectId());
         } else {
             $new_task->setOriginalTaskId($this->getOriginalTaskId());
         }
     }
     if ($this->getDueDate() instanceof DateTimeValue) {
         $new_task->setDueDate(new DateTimeValue($this->getDueDate()->getTimestamp()));
     }
     if ($this->getStartDate() instanceof DateTimeValue) {
         $new_task->setStartDate(new DateTimeValue($this->getStartDate()->getTimestamp()));
     }
     if ($copy_status) {
         $new_task->setCompletedById($this->getCompletedById());
         $new_task->setCompletedOn($this->getCompletedOn());
     }
     if ($copy_repeat_options) {
         $new_task->setRepeatEnd($this->getRepeatEnd());
         $new_task->setRepeatForever($this->getRepeatForever());
         $new_task->setRepeatNum($this->getRepeatNum());
         $new_task->setRepeatBy($this->getRepeatBy());
         $new_task->setRepeatD($this->getRepeatD());
         $new_task->setRepeatM($this->getRepeatM());
         $new_task->setRepeatY($this->getRepeatY());
     }
     if ($new_st_date != "") {
         if ($new_task->getStartDate() instanceof DateTimeValue) {
             $new_task->setStartDate($new_st_date);
         }
     }
     if ($new_due_date != "") {
         if ($new_task->getDueDate() instanceof DateTimeValue) {
             $new_task->setDueDate($new_due_date);
         }
     }
     $new_task->save();
     if (is_array($this->getAllLinkedObjects())) {
         foreach ($this->getAllLinkedObjects() as $lo) {
             $new_task->linkObject($lo);
         }
     }
     $sub_tasks = $this->getAllSubTasks();
     foreach ($sub_tasks as $st) {
         $new_dates = $this->getNextRepetitionDatesSubtask($st, $new_task, $new_st_date, $new_due_date);
         if ($st->getParentId() == $this->getId()) {
             $new_st = $st->cloneTask(array_var($new_dates, 'st'), array_var($new_dates, 'due'), $copy_status, $copy_repeat_options, $new_task->getId());
             if ($copy_status) {
                 $new_st->setCompletedById($st->getCompletedById());
                 $new_st->setCompletedOn($st->getCompletedOn());
                 $new_st->save();
             }
             $new_task->attachTask($new_st);
         }
     }
     foreach ($this->getAllComments() as $com) {
         $new_com = new Comment();
         $new_com->setAuthorEmail($com->getAuthorEmail());
         $new_com->setAuthorName($com->getAuthorName());
         $new_com->setAuthorHomepage($com->getAuthorHomepage());
         $new_com->setCreatedById($com->getCreatedById());
         $new_com->setCreatedOn($com->getCreatedOn());
         $new_com->setUpdatedById($com->getUpdatedById());
         $new_com->setUpdatedOn($com->getUpdatedOn());
         $new_com->setText($com->getText());
         $new_com->setRelObjectId($new_task->getId());
         $new_com->save();
     }
     $_POST['subscribers'] = array();
     foreach ($this->getSubscribers() as $sub) {
         $_POST['subscribers']["user_" . $sub->getId()] = "checked";
     }
     $obj_controller = new ObjectController();
     $obj_controller->add_to_members($new_task, $this->getMemberIds());
     $obj_controller->add_subscribers($new_task);
     foreach ($this->getCustomProperties() as $prop) {
         $new_prop = new ObjectProperty();
         $new_prop->setRelObjectId($new_task->getId());
         $new_prop->setPropertyName($prop->getPropertyName());
         $new_prop->setPropertyValue($prop->getPropertyValue());
         $new_prop->save();
     }
     $custom_props = CustomProperties::getAllCustomPropertiesByObjectType("TemplateTasks");
     foreach ($custom_props as $c_prop) {
         $values = CustomPropertyValues::getCustomPropertyValues($this->getId(), $c_prop->getId());
         if (is_array($values)) {
             foreach ($values as $val) {
                 $cp = new CustomPropertyValue();
                 $cp->setObjectId($new_task->getId());
                 $cp->setCustomPropertyId($val->getCustomPropertyId());
                 $cp->setValue($val->getValue());
                 $cp->save();
             }
         }
     }
     $reminders = ObjectReminders::getByObject($this);
     foreach ($reminders as $reminder) {
         $copy_reminder = new ObjectReminder();
         $copy_reminder->setContext($reminder->getContext());
         $reminder_date = $new_task->getColumnValue($reminder->getContext());
         if ($reminder_date instanceof DateTimeValue) {
             $reminder_date = new DateTimeValue($reminder_date->getTimestamp());
             $reminder_date->add('m', -$reminder->getMinutesBefore());
         }
         $copy_reminder->setDate($reminder_date);
         $copy_reminder->setMinutesBefore($reminder->getMinutesBefore());
         $copy_reminder->setObject($new_task);
         $copy_reminder->setType($reminder->getType());
         $copy_reminder->setUserId($reminder->getUserId());
         $copy_reminder->save();
     }
     return $new_task;
 }
Ejemplo n.º 23
0
 /**
  * Returns all events for the given range, tag and considers the active project
  *
  * @param DateTimeValue $date
  * @param String $tags
  * @return unknown
  */
 static function getRangeProjectEvents(DateTimeValue $start_date, DateTimeValue $end_date, $tags = '', $project = null, $archived = false)
 {
     $start_year = date("Y", mktime(0, 0, 1, $start_date->getMonth(), $start_date->getDay(), $start_date->getYear()));
     $start_month = date("m", mktime(0, 0, 1, $start_date->getMonth(), $start_date->getDay(), $start_date->getYear()));
     $start_day = date("d", mktime(0, 0, 1, $start_date->getMonth(), $start_date->getDay(), $start_date->getYear()));
     $end_year = date("Y", mktime(0, 0, 1, $end_date->getMonth(), $end_date->getDay(), $end_date->getYear()));
     $end_month = date("m", mktime(0, 0, 1, $end_date->getMonth(), $end_date->getDay(), $end_date->getYear()));
     $end_day = date("d", mktime(0, 0, 1, $end_date->getMonth(), $end_date->getDay(), $end_date->getYear()));
     if (!is_numeric($start_day) or !is_numeric($start_month) or !is_numeric($start_year) or !is_numeric($end_day) or !is_numeric($end_month) or !is_numeric($end_year)) {
         return NULL;
     }
     //permission check
     $permissions = ' AND ( ' . permissions_sql_for_listings(ProjectEvents::instance(), ACCESS_LEVEL_READ, logged_user()) . ')';
     if ($project instanceof Project) {
         $pids = $project->getAllSubWorkspacesQuery(!$archived);
         $wsstring = " AND " . self::getWorkspaceString($pids);
     } else {
         $wsstring = "";
     }
     if (isset($tags) && $tags && $tags != '') {
         $tag_str = " AND EXISTS (SELECT * FROM `" . TABLE_PREFIX . "tags` `t` WHERE `tag` IN (" . DB::escape($tags) . ") AND `" . TABLE_PREFIX . "project_events`.`id` = `t`.`rel_object_id` AND `t`.`rel_object_manager` = 'ProjectEvents') ";
     } else {
         $tag_str = "";
     }
     $invited = " AND `id` IN (SELECT `event_id` FROM `" . TABLE_PREFIX . "event_invitations` WHERE `user_id` = " . logged_user()->getId() . ")";
     if ($archived) {
         $archived_cond = " AND `archived_by_id` <> 0";
     } else {
         $archived_cond = " AND `archived_by_id` = 0";
     }
     $tz_hm = "'" . floor(logged_user()->getTimezone()) . ":" . abs(logged_user()->getTimezone()) % 1 * 60 . "'";
     $s_date = new DateTimeValue($start_date->getTimestamp() - logged_user()->getTimezone() * 3600);
     $e_date = new DateTimeValue($end_date->getTimestamp() - logged_user()->getTimezone() * 3600);
     $e_date->add("d", 1);
     $start_date_str = $s_date->format("Y-m-d H:i:s");
     $end_date_str = $e_date->format("Y-m-d H:i:s");
     $first_d = $start_day;
     while ($first_d > 7) {
         $first_d -= 7;
     }
     $week_of_first_day = date("W", mktime(0, 0, 0, $start_month, $first_d, $start_year));
     $conditions = "\t((\n\t\t\t\t-- \n\t\t\t\t-- THIS RETURNS EVENTS ON THE ACTUAL DAY IT'S SET FOR (ONE TIME EVENTS)\n\t\t\t\t-- \n\t\t\t\t(\n\t\t\t\t\t`repeat_h` = 0 \n\t\t\t\t\tAND `duration` >= '{$start_date_str}' \n\t\t\t\t\tAND `start` < '{$end_date_str}' \n\t\t\t\t) \n\t\t\t\t-- \n\t\t\t\t-- THIS RETURNS REGULAR REPEATING EVENTS - DAILY, WEEKLY, MONTHLY, OR YEARLY.\n\t\t\t\t-- \n\t\t\t\tOR \n\t\t\t\t(\n\t\t\t\t\t`repeat_h` = 0 \n\t\t\t\t\tAND\n\t\t\t\t\tDATE(`start`) < '{$end_date_str}'\n\t\t\t\t\tAND\n\t\t\t\t\t(\t\t\t\t\t\t\t\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tDATE_ADD(`start`, INTERVAL (`repeat_num`-1)*`repeat_d` DAY) >= '{$start_date_str}' \n\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\trepeat_forever = 1\n\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\trepeat_end >= '{$start_year}-{$start_month}-{$start_day}'\n\t\t\t\t\t\t)\n\t\t\t\t\t\tOR\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tDATE_ADD(`start`, INTERVAL (`repeat_num`-1)*`repeat_m` MONTH) >= '{$start_date_str}' \n\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\trepeat_forever = 1\n\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\trepeat_end >= '{$start_year}-{$start_month}-{$start_day}'\n\t\t\t\t\t\t)\n\t\t\t\t\t\tOR\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tDATE_ADD(`start`, INTERVAL (`repeat_num`-1)*`repeat_y` YEAR) >= '{$start_date_str}' \n\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\trepeat_forever = 1\n\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\trepeat_end >= '{$start_year}-{$start_month}-{$start_day}'\n\t\t\t\t\t\t)\n\t\t\t\t\t)\t\t\n\t\t\t\t)\n\t\t\t\t-- \n\t\t\t\t-- THIS RETURNS EVENTS SET TO BE A CERTAIN DAY OF THE WEEK IN A CERTAIN WEEK EVERY CERTAIN AMOUNT OF MONTHS\n\t\t\t\t-- \n\t\t\t\tOR\n\t\t\t\t(\n\t\t\t\t\tDATE(`start`) <= '{$start_date_str}'\n\t\t\t\t\tAND\n\t\t\t\t\t`repeat_h` = 1 \n\t\t\t\t\tAND\n\t\t\t\t\t`repeat_dow` = DAYOFWEEK('{$start_date_str}') \n\t\t\t\t\tAND\n\t\t\t\t\t`repeat_wnum` + {$week_of_first_day} - 1 = WEEK('{$start_date_str}', 3) \n\t\t\t\t\tAND\n\t\t\t\t\tMOD( PERIOD_DIFF(DATE_FORMAT(`start`, '%Y%m'), DATE_FORMAT('{$start_date_str}', '%Y%m')), `repeat_mjump`) = 0\n\t\t\t\t)\t\t\t\t\n\t\t\t)\n\t\t\t{$wsstring}\n\t\t\t{$permissions} {$invited}\n\t\t\t{$tag_str} {$archived_cond} )";
     $result_events = self::findAll(array('conditions' => $conditions, 'order' => '`start`'));
     // Find invitations for events and logged user
     ProjectEvents::addInvitations($result_events);
     return $result_events;
 }
Ejemplo n.º 24
0
 private function forwardRepDate($min_date)
 {
     if ($this->isRepetitive()) {
         if (!$this->getStart() instanceof DateTimeValue || !$min_date instanceof DateTimeValue) {
             return array('date' => $min_date, 'count' => 0);
             //This should not happen...
         }
         $date = new DateTimeValue($this->getStart()->getTimestamp());
         $count = 0;
         if ($date->getTimestamp() >= $min_date->getTimestamp()) {
             return array('date' => $date, 'count' => $count);
         }
         while ($date->getTimestamp() < $min_date->getTimestamp()) {
             if ($this->getRepeatD() > 0) {
                 $date = $date->add('d', $this->getRepeatD());
             } else {
                 if ($this->getRepeatM() > 0) {
                     $date = $date->add('M', $this->getRepeatM());
                 } else {
                     if ($this->getRepeatY() > 0) {
                         $date = $date->add('y', $this->getRepeatY());
                     } else {
                         if ($this->getRepeatH() > 0) {
                             $date = $date->add('M', $this->getRepeatMjump());
                         }
                     }
                 }
             }
             $count++;
         }
         return array('date' => $date, 'count' => $count);
     } else {
         return array('date' => $min_date, 'count' => 0);
     }
 }
 /**
  * Return number of new objects in $project_ids since $since
  *
  * @param DateTimeValue $since
  * @param array $project_ids
  * @param array $exclude
  * @param integer $min_state
  * @param integer $min_visibility
  * @return integer
  */
 function countNew($user)
 {
     $type_filter = ProjectUsers::getVisibleTypesFilter($user, array(PROJECT_STATUS_ACTIVE, PROJECT_STATUS_PAUSED, PROJECT_STATUS_CANCELED, PROJECT_STATUS_COMPLETED));
     if ($type_filter) {
         $exclude = ProjectObjectViews::findViewedObjectIds($user);
         $last_visit_on = $user->getLastVisitOn();
         if (!instance_of($last_visit_on, 'DateTimeValue')) {
             $last_visit_on = new DateTimeValue(filemtime(ENVIRONMENT_PATH . '/config/config.php'));
         }
         // if
         $month_ago = new DateTimeValue('-30 days');
         // Last visit or last month
         $since = $last_visit_on->getTimestamp() > $month_ago->getTimestamp() ? $last_visit_on : $month_ago;
         if ($exclude) {
             return ProjectObjects::count(array($type_filter . ' AND state >= ? AND visibility >= ? AND created_on >= ? AND created_by_id != ? AND id NOT IN (?)', STATE_VISIBLE, $user->getVisibility(), $since, $user->getId(), $exclude));
         } else {
             return ProjectObjects::count(array($type_filter . ' AND state >= ? AND visibility >= ? AND created_on >= ? AND created_by_id != ? ', STATE_VISIBLE, $user->getVisibility(), $since, $user->getid()));
         }
         // if
     } else {
         return 0;
     }
     // if
 }
 function instantiate()
 {
     $id = get_id();
     $template = COTemplates::findById($id);
     if (!$template instanceof COTemplate) {
         flash_error(lang("template dnx"));
         ajx_current("empty");
         return;
     }
     $parameters = TemplateParameters::getParametersByTemplate($id);
     $parameterValues = array_var($_POST, 'parameterValues');
     if (count($parameters) > 0 && !isset($parameterValues)) {
         ajx_current("back");
         return;
     }
     $objects = $template->getObjects();
     foreach ($objects as $object) {
         if (!$object instanceof ProjectDataObject) {
             continue;
         }
         // copy object
         $copy = $object->copy();
         if ($copy->columnExists('is_template')) {
             $copy->setColumnValue('is_template', false);
         }
         if ($copy instanceof ProjectTask) {
             // don't copy parent task and milestone
             $copy->setMilestoneId(0);
             $copy->setParentId(0);
         }
         $copy->save();
         $wsId = array_var($_POST, 'project_id', active_or_personal_project()->getId());
         // if specified, set workspace
         $workspace = Projects::findById($wsId);
         if (!$workspace instanceof Project) {
             $workspace = active_or_personal_project();
         }
         $copy->addToWorkspace($workspace);
         // add object tags and specified tags
         $tags = implode(',', $object->getTagNames());
         $copy->setTagsFromCSV($tags . "," . array_var($_POST, 'tags'));
         // copy linked objects
         $copy->copyLinkedObjectsFrom($object);
         // copy subtasks if applicable
         if ($copy instanceof ProjectTask) {
             ProjectTasks::copySubTasks($object, $copy, false);
             $manager = new ProjectTask();
         } else {
             if ($copy instanceof ProjectMilestone) {
                 ProjectMilestones::copyTasks($object, $copy, false);
                 $manager = new ProjectMilestone();
             }
         }
         // copy custom properties
         $copy->copyCustomPropertiesFrom($object);
         // set property values as defined in template
         $objProp = TemplateObjectProperties::getPropertiesByTemplateObject($id, $object->getId());
         foreach ($objProp as $property) {
             $propName = $property->getProperty();
             $value = $property->getValue();
             if ($manager->getColumnType($propName) == DATA_TYPE_STRING) {
                 if (is_array($parameterValues)) {
                     foreach ($parameterValues as $param => $val) {
                         $value = str_replace('{' . $param . '}', $val, $value);
                     }
                 }
             } else {
                 if ($manager->getColumnType($propName) == DATA_TYPE_DATE || $manager->getColumnType($propName) == DATA_TYPE_DATETIME) {
                     $operator = '+';
                     if (strpos($value, '+') === false) {
                         $operator = '-';
                     }
                     $opPos = strpos($value, $operator);
                     if ($opPos !== false) {
                         $dateParam = substr($value, 1, strpos($value, '}') - 1);
                         $dateUnit = substr($value, strlen($value) - 1);
                         // d, w or m (for days, weeks or months)
                         if ($dateUnit == 'm') {
                             $dateUnit = 'M';
                             // make month unit uppercase to call DateTimeValue::add with correct parameter
                         }
                         $dateNum = (int) substr($value, strpos($value, $operator), strlen($value) - 2);
                         $date = $parameterValues[$dateParam];
                         $date = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $date);
                         $value = $date->add($dateUnit, $dateNum);
                     }
                 } else {
                     if ($manager->getColumnType($propName) == DATA_TYPE_INTEGER) {
                         if (is_array($parameterValues)) {
                             foreach ($parameterValues as $param => $val) {
                                 $value = str_replace('{' . $param . '}', $val, $value);
                             }
                         }
                     }
                 }
             }
             if ($value != '') {
                 $copy->setColumnValue($propName, $value);
                 $copy->save();
             }
         }
         //copy assigned to company if applicable
         if ($copy->getAssignedToUserId() != 0) {
             $copy->setAssignedToCompanyId($copy->getAssignedTo()->getCompanyId());
             $copy->save();
         }
         // copy reminders
         $reminders = ObjectReminders::getByObject($object);
         foreach ($reminders as $reminder) {
             $copy_reminder = new ObjectReminder();
             $copy_reminder->setContext($reminder->getContext());
             $reminder_date = $copy->getColumnValue($reminder->getContext());
             if ($reminder_date instanceof DateTimeValue) {
                 $reminder_date = new DateTimeValue($reminder_date->getTimestamp());
                 $reminder_date->add('m', -$reminder->getMinutesBefore());
             }
             $copy_reminder->setDate($reminder_date);
             $copy_reminder->setMinutesBefore($reminder->getMinutesBefore());
             $copy_reminder->setObject($copy);
             $copy_reminder->setType($reminder->getType());
             $copy_reminder->setUserId($reminder->getUserId());
             $copy_reminder->save();
         }
     }
     if (is_array($parameters) && count($parameters) > 0) {
         ajx_current("back");
     } else {
         ajx_current("reload");
     }
 }
Ejemplo n.º 27
0
function friendly_date(DateTimeValue $date, $timezone = null)
{
    if ($timezone == null) {
        $timezone = logged_user()->getTimezone();
    }
    //TODO: 7 days before: "Dom at 13:43", older: "Oct, 06 at 15:20"
    if ($date->isToday()) {
        $now = DateTimeValueLib::now();
        $diff = DateTimeValueLib::get_time_difference($date->getTimestamp(), $now->getTimestamp());
        if ($diff['hours'] == 0) {
            if ($diff['minutes'] >= 0) {
                return lang('minutes ago', $diff['minutes']);
            } else {
                return format_descriptive_date($date);
            }
        } else {
            if ($diff['hours'] > 0) {
                return lang('about hours ago', round($diff['hours'] + ($diff['minutes'] > 30 ? 1 : 0)));
            } else {
                return format_descriptive_date($date);
            }
        }
    } else {
        if ($date->isYesterday()) {
            return lang('yesterday at', format_time($date));
        } else {
            $now = DateTimeValueLib::now();
            $diff = DateTimeValueLib::get_time_difference($date->getTimestamp(), $now->getTimestamp());
            if ($diff['days'] < 7) {
                return lang('day at', Localization::dateByLocalization("D", $date->getTimestamp()), format_time($date));
            } else {
                if ($now->getYear() != $date->getYear()) {
                    return lang('day at', Localization::dateByLocalization("M d, Y", $date->getTimestamp()), format_time($date));
                } else {
                    return lang('day at', Localization::dateByLocalization("M, d", $date->getTimestamp()), format_time($date));
                }
            }
        }
    }
}
 function snoozereminder()
 {
     $snooze = $this->request->post('snooze');
     $link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
     mysql_select_db(DB_NAME);
     if ($snooze) {
         /*mysql_query("update healingcrystals_project_object_misc set snooze_duration='" . (int)$snooze['duration'] . "', snooze_unit='" . $snooze['unit'] . "' where object_id='" . $this->active_task->getId() . "'");
         		$query = "select reminder_date from healingcrystals_project_object_misc where object_id='" . $this->active_task->getId() . "'";
         		$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'){
         				$base_date = strtotime($info['reminder_date']);
         				$modified_date = '';
         				if ($snooze['duration']>0){
         					switch($snooze['unit']){
         						case 'H':
         							$modified_date = strtotime('+ ' . $snooze['duration'] . ' hours', $base_date);
         							break;
         						case 'D':
         							$modified_date = strtotime('+ ' . $snooze['duration'] . ' days', $base_date);
         							break;
         						case 'W':
         							$modified_date = strtotime('+ ' . $snooze['duration'] . ' weeks', $base_date);
         							break;
         						case 'M':
         							$modified_date = strtotime('+ ' . $snooze['duration'] . ' months', $base_date);
         							break;
         					}
         					if (!empty($modified_date)){
         						mysql_query("update healingcrystals_project_object_misc set reminder_date='" . date('Y-m-d H:i:s', $modified_date) . "' where object_id='" . $this->active_task->getId() . "'");
         					}
         				}
         			}
         		}*/
         //$query = mysql_query("select now() as cur_time");
         //$info = mysql_fetch_assoc($query);
         //$base_date = strtotime($info['cur_time']);
         $base_date = new DateTimeValue();
         $base_date->advance(get_system_gmt_offset($this->logged_user), true);
         //$base_date->advance(get_user_gmt_offset($this->logged_user), true);
         $modified_date = '';
         if ($snooze['duration'] > 0) {
             switch ($snooze['unit']) {
                 case 'I':
                     $modified_date = strtotime('+ ' . $snooze['duration'] . ' minutes', $base_date->getTimestamp());
                     break;
                 case 'H':
                     $modified_date = strtotime('+ ' . $snooze['duration'] . ' hours', $base_date->getTimestamp());
                     break;
                 case 'D':
                     $modified_date = strtotime('+ ' . $snooze['duration'] . ' days', $base_date->getTimestamp());
                     break;
                 case 'W':
                     $modified_date = strtotime('+ ' . $snooze['duration'] . ' weeks', $base_date->getTimestamp());
                     break;
                 case 'M':
                     $modified_date = strtotime('+ ' . $snooze['duration'] . ' months', $base_date->getTimestamp());
                     break;
             }
             if (!empty($modified_date)) {
                 $sql = "select object_id from " . TABLE_PREFIX . "project_object_misc where object_id='" . $this->active_task->getId() . "'";
                 $result = mysql_query($sql);
                 if (mysql_num_rows($result)) {
                     mysql_query("update healingcrystals_project_object_misc set last_modified=now(),  snooze_datetime='" . date('Y-m-d H:i:s', $modified_date) . "' where object_id='" . $this->active_task->getId() . "'");
                 } else {
                     mysql_query("insert into " . TABLE_PREFIX . "project_object_misc (object_id, date_added, snooze_datetime) values ('" . $this->active_task->getId() . "', now(), '" . date('Y-m-d H:i:s', $modified_date) . "')");
                 }
             }
         }
         $this->redirectToUrl($this->active_task->getViewUrl() . '#task' . $this->active_task->getId());
     } else {
         /*$snooze = array('duration' => '', 'unit' => '');
         		$result = mysql_query("select snooze_duration, snooze_unit from healingcrystals_project_object_misc where object_id='" . $this->active_task->getId() . "'");
         		if (mysql_num_rows($result)){
         			$info = mysql_fetch_assoc($result);
         			if (!empty($info['snooze_duration'])) $snooze['duration'] = $info['snooze_duration'];
         			if (!empty($info['snooze_unit'])) $snooze['unit'] = $info['snooze_unit'];
         		}*/
         $snooze_date = 'Not Set';
         $result = mysql_query("select snooze_datetime from healingcrystals_project_object_misc where object_id='" . $this->active_task->getId() . "'");
         if (mysql_num_rows($result)) {
             $info = mysql_fetch_assoc($result);
             if (!empty($info['snooze_datetime'])) {
                 $snooze_date = date('m-d-Y H:i', strtotime($info['snooze_datetime']));
             }
         }
     }
     mysql_close($link);
     $this->smarty->assign(array('form_action_url' => assemble_url('project_task_snoozereminder', array('project_id' => $this->active_project->getId(), 'task_id' => $this->active_task->getId())), 'snooze_date' => $snooze_date));
 }
 /**
  * Return difference between specific datetime and due date time in seconds
  *
  * @access public
  * @param DateTime $diff_to
  * @return integer
  */
 private function getDueDateDiff(DateTimeValue $diff_to)
 {
     return $this->getDueDate()->getTimestamp() - $diff_to->getTimestamp();
 }
Ejemplo n.º 30
0
        function import_google_calendar() {
                ajx_current("empty");
                $users = ExternalCalendarUsers::findByContactId();  
                if($users){
                    $calendars = ExternalCalendars::findByExtCalUserId($users->getId());

                    require_once 'Zend/Loader.php';

                    Zend_Loader::loadClass('Zend_Gdata');
                    Zend_Loader::loadClass('Zend_Gdata_AuthSub');
                    Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
                    Zend_Loader::loadClass('Zend_Gdata_Calendar');

                    $user = $users->getAuthUser();
                    $pass = $users->getAuthPass();
                    $service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;

                    try
                    {
                            $client = Zend_Gdata_ClientLogin::getHttpClient($user,$pass,$service);                                                       
                            $gdataCal = new Zend_Gdata_Calendar($client);

                            //update or insert events for calendars                        
                            foreach ($calendars as $calendar){

                                //check the deleted calendars
                                $delete_calendar = false;
                                $calFeed = $gdataCal->getCalendarListFeed();        
                                foreach ($calFeed as $calF){
                                    $cal_src = explode("/",$calF->content->src);
                                    array_pop($cal_src);
                                    $calendar_visibility = end($cal_src);
                                    array_pop($cal_src);
                                    $calendar_user = end($cal_src); 

                                    if($calendar_user == $calendar->getCalendarUser()){
                                        $delete_calendar = true;
                                    }
                                }

                                if($delete_calendar){
                                    $calendar_user = $calendar->getCalendarUser();
                                    $calendar_visibility = $calendar->getCalendarVisibility();
                                    $start_sel = date('Y-m-d', strtotime('-1 week'));
                                    $end_sel = date('Y-m-d', strtotime('+2 year'));

                                    $query = $gdataCal->newEventQuery();
                                    $query->setUser($calendar_user);
                                    $query->setVisibility($calendar_visibility);
                                    $query->setSingleEvents(true);
                                    $query->setProjection('full');
                                    $query->setOrderby('starttime');
                                    $query->setSortOrder('ascending'); 
                                    $query->setStartMin($start_sel);
                                    $query->setStartMax($end_sel);
                                    $query->setMaxResults(50);
                                    // execute and get results
                                    $event_list = $gdataCal->getCalendarEventFeed($query);

                                    $array_events_google = array();
                                    foreach ($event_list as $event){                                        
                                        $event_id = explode("/",$event->id->text);
                                        $special_id = end($event_id); 
                                        $event_name = lang("untitle event");
                                        if($event->title->text != ""){
                                            $event_name = $event->title->text;
                                        }
                                        $array_events_google[] = $special_id;
                                        $new_event = ProjectEvents::findBySpecialId($special_id);
                                        if($new_event){
                                            if(strtotime(ProjectEvents::date_google_to_sql($event->updated)) > $new_event->getUpdateSync()->getTimestamp()){
                                                $start = strtotime(ProjectEvents::date_google_to_sql($event->when[0]->startTime));
                                                $fin = strtotime(ProjectEvents::date_google_to_sql($event->when[0]->endTime));
                                                if(($fin - $start) == 86400){
                                                    $new_event->setStart(date("Y-m-d H:i:s",$start));
                                                    $new_event->setDuration(date("Y-m-d H:i:s",$start));
                                                    $new_event->setTypeId(2);
                                                }elseif(($fin - $start) > 86400){                                                
                                                    $t_s = explode(' ', date("Y-m-d H:i:s",$start));
                                                    $t_f = explode(' ', date("Y-m-d H:i:s",$fin));

                                                    $date_s = new DateTimeValue(strtotime($t_s[0]."00:00:00") - logged_user()->getTimezone() * 3600);
                                                    $date_f = new DateTimeValue(strtotime($t_f[0]."23:59:59 -1 day") - logged_user()->getTimezone() * 3600);

                                                    $new_event->setStart(date("Y-m-d H:i:s",$date_s->getTimestamp()));
                                                    $new_event->setDuration(date("Y-m-d H:i:s",$date_f->getTimestamp()));
                                                    $new_event->setTypeId(2);
                                                }else{
                                                    $new_event->setStart(ProjectEvents::date_google_to_sql($event->when[0]->startTime));
                                                    $new_event->setDuration(ProjectEvents::date_google_to_sql($event->when[0]->endTime));
                                                }

                                                $new_event->setObjectName($event_name);
                                                $new_event->setDescription($event->content->text);
                                                $new_event->setUpdateSync(ProjectEvents::date_google_to_sql($event->updated));
                                                $new_event->setExtCalId($calendar->getId());
                                                $new_event->save(); 
                                            }
                                        }else{
                                            $new_event = new ProjectEvent();
                                            
                                            $start = strtotime(ProjectEvents::date_google_to_sql($event->when[0]->startTime));
                                            $fin = strtotime(ProjectEvents::date_google_to_sql($event->when[0]->endTime));
                                            if(($fin - $start) == 86400){
                                                $new_event->setStart(date("Y-m-d H:i:s",$start));
                                                $new_event->setDuration(date("Y-m-d H:i:s",$start));
                                                $new_event->setTypeId(2);
                                            }elseif(($fin - $start) > 86400){
                                                $t_s = explode(' ', date("Y-m-d H:i:s",$start));
                                                $t_f = explode(' ', date("Y-m-d H:i:s",$fin));
                                                
                                                $date_s = new DateTimeValue(strtotime($t_s[0]."00:00:00") - logged_user()->getTimezone() * 3600);
                                                $date_f = new DateTimeValue(strtotime($t_f[0]."23:59:59 -1 day") - logged_user()->getTimezone() * 3600);
                                                
                                                $new_event->setStart(date("Y-m-d H:i:s",$date_s->getTimestamp()));
                                                $new_event->setDuration(date("Y-m-d H:i:s",$date_f->getTimestamp()));
                                                $new_event->setTypeId(2);
                                            }else{
                                                $new_event->setStart(ProjectEvents::date_google_to_sql($event->when[0]->startTime));
                                                $new_event->setDuration(ProjectEvents::date_google_to_sql($event->when[0]->endTime));
                                                $new_event->setTypeId(1);
                                            }
                                            
                                            $new_event->setObjectName($event_name);
                                            $new_event->setDescription($event->content->text);
                                            $new_event->setSpecialID($special_id);
                                            $new_event->setUpdateSync(ProjectEvents::date_google_to_sql($event->updated));
                                            $new_event->setExtCalId($calendar->getId());                                            
                                            $new_event->save(); 
                                            
                                            $conditions = array('event_id' => $new_event->getId(), 'contact_id' => logged_user()->getId());
                                            //insert only if not exists 
                                            if (EventInvitations::findById($conditions) == null) { 
                                                $invitation = new EventInvitation();
                                                $invitation->setEventId($new_event->getId());
                                                $invitation->setContactId(logged_user()->getId());
                                                $invitation->setInvitationState(1);
                                                $invitation->save();
                                            }
                                            
                                            //insert only if not exists 
                                            if (ObjectSubscriptions::findBySubscriptions($new_event->getId()) == null) { 
                                                $subscription = new ObjectSubscription();
                                                $subscription->setObjectId($new_event->getId());
                                                $subscription->setContactId(logged_user()->getId());
                                                $subscription->save();
                                            }

                                            if($users->getRelatedTo()){
                                                $member = array();
                                                $member_ids = explode(",",$users->getRelatedTo());
                                                foreach ($member_ids as $member_id){
                                                    $member[] = $member_id;
                                                }
                                                $object_controller = new ObjectController();
                                                $object_controller->add_to_members($new_event, $member); 
                                            }else{
                                                $member_ids = array();
                                                $context = active_context();
                                                foreach ($context as $selection) {
                                                    if ($selection instanceof Member) $member_ids[] = $selection->getId();
                                                }		        
                                                $object_controller = new ObjectController();
                                                $object_controller->add_to_members($new_event, $member_ids); 
                                            }                                            
                                        }           
                                    }// foreach event list 

                                    //check the deleted events
                                    $events_delete = ProjectEvents::findByExtCalId($calendar->getId());
                                    if($events_delete){
                                        foreach($events_delete as $event_delete){  
                                            if(!in_array($event_delete->getSpecialID(), $array_events_google)){
                                                $event_delete->trash();

                                                $event_delete->setSpecialID("");
                                                $event_delete->setExtCalId(0);
                                                $event_delete->save();    
                                            }                                        
                                        }  
                                    }
                                }else{                
                                    $events = ProjectEvents::findByExtCalId($calendar->getId());
                                    if($calendar->delete()){
                                        if($events){
                                            foreach($events as $event){                            
                                                $event->trash();

                                                $event->setSpecialID("");
                                                $event->setExtCalId(0);
                                                $event->save();
                                            }  
                                        }
                                    }
                                }
                            }//foreach calendars
                    }
                    catch(Exception $e)
                    {
                    		Logger::log($e->getMessage());
                            flash_error(lang('could not connect to calendar'));
                            ajx_current("empty");
                    }
                }
	}