public static function getAgo($timestamp) { if ($timestamp === null) { return ''; } $diffdays = Date_Calc::dateDiff(date('j', $timestamp), date('n', $timestamp), date('Y', $timestamp), date('j'), date('n'), date('Y')); /* An error occured. */ if ($diffdays == -1) { return; } $ago = $diffdays * Date_Calc::compareDates(date('j', $timestamp), date('n', $timestamp), date('Y', $timestamp), date('j'), date('n'), date('Y')); if ($ago < -1) { return sprintf(Horde_Model_Translation::t(" (%s days ago)"), $diffdays); } elseif ($ago == -1) { return Horde_Model_Translation::t(" (yesterday)"); } elseif ($ago == 0) { return Horde_Model_Translation::t(" (today)"); } elseif ($ago == 1) { return Horde_Model_Translation::t(" (tomorrow)"); } else { return sprintf(Horde_Model_Translation::t(" (in %s days)"), $diffdays); } }
/** * Constructor. * * @param object $event Event object */ public function __construct($event) { global $_EV_CONF; $this->event = $event; // Initialize array of events to be loaded $this->events = array(); $this->freq = isset($event->rec_data['freq']) ? (int) $event->rec_data['freq'] : 1; if ($this->freq < 1) { $this->freq = 1; } $this->skip = isset($event->rec_data['skip']) ? (int) $event->rec_data['skip'] : 0; $this->dt_start = $this->event->date_start1 != '' ? $this->event->date_start1 : $_EV_CONF['_today']; $this->dt_end = $this->event->date_end1 > $this->event->date_start1 ? $this->event->date_end1 : $this->event->date_start1; if ($this->dt_start != $this->dt_end) { list($syear, $smonth, $sday) = explode('-', $this->dt_start); list($eyear, $emonth, $eday) = explode('-', $this->dt_end); // Need to get the number of days the event lasts $this->duration = Date_Calc::dateDiff($eday, $emonth, $eyear, $sday, $smonth, $syear); } else { $this->duration = 0; // single day event } }
/** * Creates the edit form * @param integer $id Optional ID, current record used if zero * @return string HTML for edit form */ public function Edit($eid = '', $rp_id = 0, $saveaction = '') { global $_CONF, $_EV_CONF, $_TABLES, $_USER, $LANG_EVLIST, $LANG_ADMIN, $_GROUPS, $LANG_ACCESS, $_SYSTEM; // If an eid is specified and this is an object, then read the // event data- UNLESS a repeat ID is given in which case we're // editing a repeat and already have the info we need. // This probably needs to change, since we should always read event // data during construction. if (!$this->isSubmitter) { // At least submit privilege required COM_404(); } elseif ($eid != '' && $rp_id == 0 && is_object($this)) { // If an id is passed in, then read that record if (!$this->Read($eid)) { return 'Invalid object ID'; } } elseif (isset($_POST['eid']) && !empty($_POST['eid'])) { // Returning to an existing form, probably due to errors $this->SetVars($_POST); // Make sure the current user has access to this event. if (!$this->hasAccess(3)) { COM_404(); } } $T = new Template($_CONF['path'] . 'plugins/evlist/templates/'); if ($_SYSTEM['disable_jquery_slimbox']) { $T->set_file('editor', 'editor.uikit.thtml'); } else { $T->set_file('editor', 'editor.thtml'); } // Basic tabs for editing both events and instances, show up on // all edit forms //$tabs = array('ev_info', 'ev_schedule', 'ev_location', 'ev_contact',); $tabs = array('ev_info', 'ev_location', 'ev_contact'); $rp_id = (int) $rp_id; if ($rp_id > 0) { // Make sure the current user has access to this event. if (!$this->hasAccess(3)) { COM_404(); } if ($saveaction == 'savefuturerepeat') { $alert_msg = EVLIST_alertMessage($LANG_EVLIST['editing_future'], 'warning'); } else { $alert_msg = EVLIST_alertMessage($LANG_EVLIST['editing_instance'], 'info'); } //$T->clear_var('contact_section'); $T->clear_var('category_section'); $T->clear_var('permissions_editor'); // Set the static calendar name for the edit form. Can't // change it for a single instance. $cal_name = DB_getItem($_TABLES['evlist_calendars'], 'cal_name', "cal_id='" . (int) $this->cal_id . "'"); $T->set_var(array('contact_section' => 'true', 'is_repeat' => 'true', 'cal_name' => $cal_name)); // Override our dates & times with those from the repeat. // $rp_id is passed when this is called from class evRepeat. // Maybe that should pass in the repeat's data instead to avoid // another DB lookup. An array of values could be used. $Rep = DB_fetchArray(DB_query("SELECT * \n FROM {$_TABLES['evlist_repeat']}\n WHERE rp_id='{$rp_id}'"), false); if ($Rep) { $this->date_start1 = $Rep['rp_date_start']; $this->date_end1 = $Rep['rp_date_end']; $this->time_start1 = $Rep['rp_time_start1']; $this->time_end1 = $Rep['rp_time_end1']; $this->time_start2 = $Rep['rp_time_start2']; $this->time_end2 = $Rep['rp_time_end2']; } } else { // Editing the main event record if ($this->id != '' && $this->recurring == 1) { $alert_msg = EVLIST_alertMessage($LANG_EVLIST['editing_series'], 'error'); } if ($this->isAdmin) { $tabs[] = 'ev_perms'; // Add permissions tab, event edit only $T->set_var('permissions_editor', 'true'); } $T->set_var(array('contact_section' => 'true', 'category_section' => 'true', 'upcoming_chk' => $this->show_upcoming ? EVCHECKED : '')); } $action_url = EVLIST_URL . '/event.php'; $delaction = 'delevent'; if (isset($_GET['from']) && $_GET['from'] == 'admin') { $cancel_url = EVLIST_ADMIN_URL . '/index.php'; } else { $cancel_url = EVLIST_URL . '/index.php'; } switch ($saveaction) { case 'saverepeat': case 'savefuturerepeat': case 'saveevent': break; case 'moderate': // Approving a submission $saveaction = 'approve'; $delaction = 'disapprove'; $action_url = EVLIST_ADMIN_URL . '/index.php'; $cancel_url = $_CONF['site_admin_url'] . '/moderation.php'; break; default: $saveaction = 'saveevent'; break; } $retval = ''; //$recinterval = ''; $recweekday = ''; $ownerusername = DB_getItem($_TABLES['users'], 'username', "uid='{$this->owner_id}'"); $retval .= COM_startBlock($LANG_EVLIST['event_editor']); $summary = $this->Detail->summary; $full_description = $this->Detail->full_description; $location = $this->Detail->location; if (($this->isAdmin || $_EV_CONF['allow_html'] == '1' && $_USER['uid'] > 1) && $A['postmode'] == 'html') { $postmode = '2'; //html } else { $postmode = '1'; //plaintext $summary = htmlspecialchars(COM_undoClickableLinks(COM_undoSpecialChars($this->Detail->summary))); $full_description = htmlspecialchars(COM_undoClickableLinks(COM_undoSpecialChars($this->Detail->full_description))); $location = htmlspecialchars(COM_undoClickableLinks(COM_undoSpecialChars($this->Detail->location))); } $starthour2 = ''; $startminute2 = ''; $endhour2 = ''; $endminute2 = ''; if ($this->date_end1 == '' || $this->date_end1 == '0000-00-00') { $this->date_end1 = $this->date_start1; } if ($this->date_start1 != '' && $this->date_start1 != '0000-00-00') { list($startmonth1, $startday1, $startyear1, $starthour1, $startminute1) = $this->DateParts($this->date_start1, $this->time_start1); } else { list($startmonth1, $startday1, $startyear1, $starthour1, $startminute1) = $this->DateParts(date('Y-m-d', time()), date('H:i:s', time())); } // The end date can't be before the start date if ($this->date_end1 >= $this->date_start1) { list($endmonth1, $endday1, $endyear1, $endhour1, $endminute1) = $this->DateParts($this->date_end1, $this->time_end1); $days_interval = Date_Calc::dateDiff($endday1, $endmonth1, $endyear1, $startday1, $startmonth1, $startyear1); } else { $days_interval = 0; $endmonth1 = $startmonth1; $endday1 = $startday1; $endyear1 = $startyear1; $endhour1 = $starthour1; $endminute1 = $startminute1; } if ($this->recurring != '1') { $T->set_var(array('recurring_show' => ' style="display:none;"', 'format_opt' => '0')); //for ($i = 1; $i <= 6; $i++) { // $T->set_var('format' . $i . 'show', ' style="display:none;"'); //} } else { $option = empty($this->rec_data['type']) ? '0' : (int) $this->rec_data['type']; $T->set_var(array('recurring_show' => '', 'recurring_checked' => EVCHECKED, 'format_opt' => $option)); } if (isset($this->rec_data['stop']) && !empty($this->rec_data['stop'])) { $T->set_var(array('stopdate' => $this->rec_data['stop'], 'd_stopdate' => EVLIST_formattedDate($this->rec_data['stop']))); } if (!empty($this->rec_data['skip'])) { $T->set_var("skipnext{$this->rec_data['skip']}_checked", EVCHECKED); } if (!empty($this->rec_data['freq'])) { $freq = (int) $this->rec_data['freq']; if ($freq < 1) { $freq = 1; } } else { $freq = 1; } $T->set_var(array('freq_text' => $LANG_EVLIST['rec_periods'][$this->rec_data['type']] . '(s)', 'rec_freq' => $freq)); foreach ($LANG_EVLIST['rec_intervals'] as $key => $str) { $T->set_var('dom_int_txt_' . $key, $str); if (is_array($this->rec_data['interval'])) { if (in_array($key, $this->rec_data['interval'])) { $T->set_var('dom_int_chk_' . $key, EVCHECKED); } } } // Set up the recurring options needed for the current event switch ($option) { case 0: break; case EV_RECUR_MONTHLY: if (is_array($this->rec_data['listdays'])) { foreach ($this->rec_data['listdays'] as $mday) { $T->set_var('mdchk' . $mday, EVCHECKED); } } break; case EV_RECUR_WEEKLY: $T->set_var('listdays_val', COM_stripslashes($rec_data[0])); if (is_array($this->rec_data['listdays']) && !empty($this->rec_data['listdays'])) { foreach ($this->rec_data['listdays'] as $day) { $day = (int) $day; if ($day > 0 && $day < 8) { $T->set_var('daychk' . $day, EVCHECKED); } } } break; case EV_RECUR_DOM: $recweekday = $this->rec_data['weekday']; break; case EV_RECUR_DATES: $T->set_var(array('stopshow' => 'style="display:none;"', 'custom_val' => implode(',', $this->rec_data['custom']))); break; } $start1 = EVLIST_TimeSelect('start1', $this->time_start1); $start2 = EVLIST_TimeSelect('start2', $this->time_start2); $end1 = EVLIST_TimeSelect('end1', $this->time_end1); $end2 = EVLIST_TimeSelect('end2', $this->time_end2); $cal_select = COM_optionList($_TABLES['evlist_calendars'], 'cal_id,cal_name', $this->cal_id, 1, 'cal_status = 1 ' . COM_getPermSQL('AND', 0, 2)); USES_class_navbar(); $navbar = new navbar(); $cnt = 0; foreach ($tabs as $id) { $navbar->add_menuitem($LANG_EVLIST[$id], 'showhideEventDiv("' . $id . '",' . $cnt . ');return false;', true); $cnt++; } $navbar->set_selected($LANG_EVLIST['ev_info']); if ($this->AdminMode) { $action_url .= '?admin=true'; } $T->set_var(array('action_url' => $action_url, 'navbar' => $navbar->generate(), 'alert_msg' => $alert_msg, 'cancel_url' => $cancel_url, 'eid' => $this->id, 'rp_id' => $rp_id, 'title' => $this->Detail->title, 'summary' => $summary, 'description' => $full_description, 'location' => $location, 'status_checked' => $this->status == 1 ? EVCHECKED : '', 'url' => $this->Detail->url, 'street' => $this->Detail->street, 'city' => $this->Detail->city, 'province' => $this->Detail->province, 'country' => $this->Detail->country, 'postal' => $this->Detail->postal, 'contact' => $this->Detail->contact, 'email' => $this->Detail->email, 'phone' => $this->Detail->phone, 'startdate1' => $this->date_start1, 'enddate1' => $this->date_end1, 'd_startdate1' => EVLIST_formattedDate($this->date_start1), 'd_enddate1' => EVLIST_formattedDate($this->date_end1), 'start_hour_options1' => $start1['hour'], 'start_minute_options1' => $start1['minute'], 'startdate1_ampm' => $start1['ampm'], 'end_hour_options1' => $end1['hour'], 'end_minute_options1' => $end1['minute'], 'enddate1_ampm' => $end1['ampm'], 'start_hour_options2' => $start2['hour'], 'start_minute_options2' => $start2['minute'], 'startdate2_ampm' => $start2['ampm'], 'end_hour_options2' => $end2['hour'], 'end_minute_options2' => $end2['minute'], 'enddate2_ampm' => $end2['ampm'], 'recurring_format_options' => EVLIST_GetOptions($LANG_EVLIST['rec_formats'], $option), 'recurring_weekday_options' => EVLIST_GetOptions(Date_Calc::getWeekDays(), $recweekday, 1), 'dailystop_label' => sprintf($LANG_EVLIST['stop_label'], $LANG_EVLIST['day_by_date'], ''), 'monthlystop_label' => sprintf($LANG_EVLIST['stop_label'], $LANG_EVLIST['year_and_month'], $LANG_EVLIST['if_any']), 'yearlystop_label' => sprintf($LANG_EVLIST['stop_label'], $LANG_EVLIST['year'], $LANG_EVLIST['if_any']), 'listdays_label' => sprintf($LANG_EVLIST['custom_label'], $LANG_EVLIST['days_of_week'], ''), 'listdaystop_label' => sprintf($LANG_EVLIST['stop_label'], $LANG_EVLIST['date_l'], $LANG_EVLIST['if_any']), 'intervalstop_label' => sprintf($LANG_EVLIST['stop_label'], $LANG_EVLIST['year_and_month'], $LANG_EVLIST['if_any']), 'custom_label' => sprintf($LANG_EVLIST['custom_label'], $LANG_EVLIST['dates'], ''), 'datestart_note' => $LANG_EVLIST['datestart_note'], 'src' => isset($_GET['src']) && $_GET['src'] == 'a' ? '1' : '0', 'rem_status_checked' => $this->enable_reminders == 1 ? EVCHECKED : '', 'del_button' => $this->id == '' ? '' : 'true', 'saveaction' => $saveaction, 'delaction' => $delaction, 'owner_id' => $this->owner_id, 'enable_reminders' => $_EV_CONF['enable_reminders'], 'iso_lang' => EVLIST_getIsoLang(), 'hour_mode' => $_CONF['hour_mode'], 'days_interval' => $days_interval, 'display_format' => $_CONF['shortdate'], 'ts_start' => strtotime($this->date_start1), 'ts_end' => strtotime($this->date_end1), 'cal_select' => $cal_select, 'contactlink_chk' => $this->options['contactlink'] == 1 ? EVCHECKED : '', 'lat' => $this->Detail->lat, 'lng' => $this->Detail->lng, 'perm_msg' => $LANG_ACCESS['permmsg'], 'last' => $LANG_EVLIST['rec_intervals'][5], 'doc_url' => EVLIST_getDocURL('event.html'), 'mootools' => $_SYSTEM['disable_mootools'] ? '' : 'true')); if ($_EV_CONF['enable_rsvp']) { USES_evlist_class_tickettype(); $TickTypes = evTicketType::GetTicketTypes(); //$T->set_block('editor', 'Tickets', 'tTypes'); $tick_opts = ''; foreach ($TickTypes as $tick_id => $tick_obj) { // Check enabled tickets. Ticket type 1 enabled by default if (isset($this->options['tickets'][$tick_id]) || $tick_id == 1) { $checked = 'checked="checked"'; $fee = (double) $this->options['tickets'][$tick_id]['fee']; } else { $checked = ''; $fee = 0; } $tick_opts .= '<tr><td><input name="tickets[' . $tick_id . ']" type="checkbox" ' . $checked . ' value="' . $tick_id . '" /></td>' . '<td>' . $tick_obj->description . '</td>' . '<td><input type="text" name="tick_fees[' . $tick_id . ']" value="' . $fee . '" size="8" /></td></tr>' . LB; /*$T->set_var(array( 'tick_id' => $tic['id'], 'tick_desc' => $tic['description'], 'tick_fee' => $fee, 'tick_enabled' => $enabled ? 'checked="checked"' : '', ) ) ; //$T->parse('tTypes', 'Tickets', true);*/ } if ($_EV_CONF['rsvp_print'] > 0) { $rsvp_print_chk = 'rsvp_print_chk' . $this->options['rsvp_print']; $rsvp_print = 'true'; } else { $rsvp_print = ''; $rsvp_print_chk = 'no_rsvp_print'; } $T->set_var(array('enable_rsvp' => 'true', 'reg_chk' . $this->options['use_rsvp'] => EVCHECKED, 'rsvp_wait_chk' => $this->options['rsvp_waitlist'] == 1 ? EVCHECKED : '', 'max_rsvp' => $this->options['max_rsvp'], 'max_user_rsvp' => $this->options['max_user_rsvp'], 'rsvp_cutoff' => $this->options['rsvp_cutoff'], 'use_rsvp' => $this->options['use_rsvp'], 'rsvp_waitlist' => $this->options['rsvp_waitlist'], 'tick_opts' => $tick_opts, 'rsvp_print' => $rsvp_print, $rsvp_print_chk => 'checked="checked"')); } // if rsvp_enabled // Split & All-Day settings if ($this->allday == 1) { // allday, can't be split, no times $T->set_var(array('starttime1_show' => 'style="display:none;"', 'endtime1_show' => 'style="display:none;"', 'datetime2_show' => 'style="display:none;"', 'allday_checked' => EVCHECKED, 'split_checked' => '', 'split_show' => 'style="display:none;"')); } elseif ($this->split == '1') { $T->set_var(array('split_checked' => EVCHECKED, 'allday_checked' => '', 'allday_show' => 'style="display:none"')); } else { $T->set_var(array('datetime2_show' => 'style="display:none;"')); } // Category fields. If $_POST['categories'] is set, then this is a // form re-entry due to an error saving. Populate checkboxes from the // submitted form. Include the user-added category, if any. // If not from a form re-entry, get the checked categories from the // evlist_lookup table. if ($_EV_CONF['enable_categories'] == '1') { $cresult = DB_query("SELECT tc.id, tc.name\n FROM {$_TABLES['evlist_categories']} tc \n WHERE tc.status='1' ORDER BY tc.name"); while ($A = DB_fetchArray($cresult, false)) { if (isset($_POST['categories']) && is_array($_POST['categories'])) { // Coming from a form re-entry $chk = in_array($A['id'], $_POST['categories']) ? EVCHECKED : ''; } else { $chk = in_array($A['id'], $this->categories) ? EVCHECKED : ''; } $catlist .= '<input type="checkbox" name="categories[]" ' . 'value="' . $A['id'] . '" ' . $chk . ' />' . ' ' . $A['name'] . ' '; } $T->set_var('catlist', $catlist); if (isset($_POST['newcat'])) { $T->set_var('newcat', $_POST['newcat']); } if ($_USER['uid'] > 1 && $rp_id == 0) { $T->set_var('category_section', 'true'); $T->set_var('add_cat_input', 'true'); } } // Enable the post mode selector if we allow HTML and the user is // logged in, or if this user is an authorized editor if ($this->isAdmin || $_EV_CONF['allow_html'] == '1' && $_USER['uid'] > 1) { $T->set_var(array('postmode_options' => EVLIST_GetOptions($LANG_EVLIST['postmodes'], $postmode), 'allowed_html' => COM_allowedHTML('evlist.submit'))); if ($postmode == 'plaintext') { // plaintext, hide postmode selector $T->set_var('postmode_show', ' style="display:none"'); } $T->parse('event_postmode', 'edit_postmode'); } if ($this->isAdmin) { $T->set_var(array('owner_username' => COM_stripslashes($ownerusername), 'owner_dropdown' => COM_optionList($_TABLES['users'], 'uid,username', $this->owner_id, 1, "uid <> 1"), 'group_dropdown' => SEC_getGroupDropdown($this->group_id, 3))); if ($rp_id == 0) { // can only change permissions on main event $T->set_var('permissions_editor', SEC_getPermissionsHTML($this->perm_owner, $this->perm_group, $this->perm_members, $this->perm_anon)); } } else { $T->set_var('group_id', $this->group_id); } // Latitude & Longitude part of location, if Location plugin is used if ($_EV_CONF['use_locator']) { $T->set_var(array('use_locator' => 'true', 'loc_selection' => GEO_optionList())); } $T->parse('output', 'editor'); $retval .= $T->finish($T->get_var('output')); $retval .= COM_endBlock(); return $retval; }
function importMatching($importedTransaction, $accountId) { global $us; global $badgerDb; static $dateDelta = null; static $amountDelta = null; static $textSimilarity = null; static $categories = null; if (is_null($dateDelta)) { try { $dateDelta = $us->getProperty('matchingDateDelta'); } catch (BadgerException $ex) { $dateDelta = 5; } try { $amountDelta = $us->getProperty('matchingAmountDelta'); } catch (BadgerException $ex) { $amountDelta = 0.1; } try { $textSimilarity = $us->getProperty('matchingTextSimilarity'); } catch (BadgerException $ex) { $textSimilarity = 0.25; } $categoryManager = new CategoryManager($badgerDb); while ($currentCategory = $categoryManager->getNextCategory()) { $categories[$currentCategory->getId()] = preg_split('/[\\n]+/', $currentCategory->getKeywords(), -1, PREG_SPLIT_NO_EMPTY); } } if (!$importedTransaction['valutaDate']) { return $importedTransaction; } $minDate = new Date($importedTransaction['valutaDate']); $minDate->subtractSeconds($dateDelta * 24 * 60 * 60); $maxDate = new Date($importedTransaction['valutaDate']); $maxDate->addSeconds($dateDelta * 24 * 60 * 60); if (!$importedTransaction['amount']) { return $importedTransaction; } $minAmount = new Amount($importedTransaction['amount']); $minAmount->mul(1 - $amountDelta); $maxAmount = new Amount($importedTransaction['amount']); $maxAmount->mul(1 + $amountDelta); $accountManager = new AccountManager($badgerDb); $account = $accountManager->getAccountById($accountId); $account->setFilter(array(array('key' => 'valutaDate', 'op' => 'ge', 'val' => $minDate), array('key' => 'valutaDate', 'op' => 'le', 'val' => $maxDate), array('key' => 'amount', 'op' => 'ge', 'val' => $minAmount), array('key' => 'amount', 'op' => 'le', 'val' => $maxAmount))); $similarTransactions = array(); while ($currentTransaction = $account->getNextTransaction()) { $titleSimilarity = getSimilarity($importedTransaction['title'], $currentTransaction->getTitle(), $textSimilarity); $descriptionSimilarity = getSimilarity($importedTransaction['description'], $currentTransaction->getDescription(), $textSimilarity); $transactionPartnerSimilarity = getSimilarity($importedTransaction['transactionPartner'], $currentTransaction->getTransactionPartner(), $textSimilarity); $currDate = $currentTransaction->getValutaDate(); $impDate = $importedTransaction['valutaDate']; $dateSimilarity = 1 - abs(Date_Calc::dateDiff($currDate->getDay(), $currDate->getMonth(), $currDate->getYear(), $impDate->getDay(), $impDate->getMonth(), $impDate->getYear())) / $dateDelta; $cmpAmount = new Amount($currentTransaction->getAmount()); $impAmount = new Amount($importedTransaction['amount']); $cmpAmount->sub($impAmount); $cmpAmount->abs(); $impAmount->mul($amountDelta); $impAmount->abs(); $amountSimilarity = 1 - $cmpAmount->div($impAmount)->get(); $currentTextSimilarity = ($titleSimilarity + $descriptionSimilarity + $transactionPartnerSimilarity) / 3; // if ($currentTextSimilarity >= $textSimilarity) { $overallSimilarity = ($titleSimilarity + $descriptionSimilarity + $transactionPartnerSimilarity + $dateSimilarity + $amountSimilarity) / 5; //$similarTransactions["$overallSimilarity t:$titleSimilarity d:$descriptionSimilarity tp:$transactionPartnerSimilarity vd:$dateSimilarity a:$amountSimilarity"] = $currentTransaction; $similarTransactions[$overallSimilarity] = $currentTransaction; // } } krsort($similarTransactions); if (count($similarTransactions)) { $importedTransaction['similarTransactions'] = $similarTransactions; return $importedTransaction; } if ($importedTransaction['categoryId']) { return $importedTransaction; } $transactionStrings = array($importedTransaction['title'], $importedTransaction['description'], $importedTransaction['transactionPartner']); foreach ($transactionStrings as $currentTransactionString) { foreach ($categories as $currentCategoryId => $keywords) { foreach ($keywords as $keyword) { if (stripos($currentTransactionString, trim($keyword)) !== false) { $importedTransaction['categoryId'] = $currentCategoryId; break 3; } //if keyword found } //foreach keywords } //foreach categories } //foreach transactionStrings return $importedTransaction; }
private function computeSubscriptionDays($p_publication, $p_subscriptionTime) { $startDate = new Date(); if ($p_publication->getTimeUnit() == 'D') { return $p_subscriptionTime; } elseif ($p_publication->getTimeUnit() == 'W') { return 7 * $p_subscriptionTime; } elseif ($p_publication->getTimeUnit() == 'M') { $endDate = new Date(); $months = $p_subscriptionTime + $endDate->getMonth(); $years = (int)($months / 12); $months = $months % 12; $endDate->setYear($endDate->getYear() + $years); $endDate->setMonth($months); } elseif ($p_publication->getTimeUnit() == 'Y') { $endDate = new Date(); $endDate->setYear($endDate->getYear() + $p_subscriptionTime); } $dateCalc = new Date_Calc(); return $dateCalc->dateDiff($endDate->getDay(), $endDate->getMonth(), $endDate->getYear(), $startDate->getDay(), $startDate->getMonth(), $startDate->getYear()); }
compare('20050126', Date_Calc::NWeekdayOfMonth('last', 3, 1, 2005), 'NWeekdayOfMonth l31'); compare('20050125', Date_Calc::NWeekdayOfMonth('last', 2, 1, 2005), 'NWeekdayOfMonth l21'); compare('20050331', Date_Calc::NWeekdayOfMonth('last', 4, 3, 2005), 'NWeekdayOfMonth l43'); compare('20050330', Date_Calc::NWeekdayOfMonth('last', 3, 3, 2005), 'NWeekdayOfMonth l33'); compare('20050329', Date_Calc::NWeekdayOfMonth('last', 2, 3, 2005), 'NWeekdayOfMonth l23'); compare('20050328', Date_Calc::NWeekdayOfMonth('last', 1, 3, 2005), 'NWeekdayOfMonth l13'); compare('20050327', Date_Calc::NWeekdayOfMonth('last', 0, 3, 2005), 'NWeekdayOfMonth l03'); compare('20050326', Date_Calc::NWeekdayOfMonth('last', 6, 3, 2005), 'NWeekdayOfMonth l63'); compare('20050325', Date_Calc::NWeekdayOfMonth('last', 5, 3, 2005), 'NWeekdayOfMonth l53'); compare(false, Date_Calc::isValidDate(29, 2, 1900), 'isValidDate 1'); compare(true, Date_Calc::isValidDate(29, 2, 2000), 'isValidDate 2'); compare(true, Date_Calc::isValidDate('29', '02', '2000'), 'isValidDate 2 str'); compare(false, Date_Calc::isLeapYear(1900), 'isLeapYear 1'); compare(true, Date_Calc::isLeapYear(1996), 'isLeapYear 2'); compare(true, Date_Calc::isLeapYear(2000), 'isLeapYear 3'); compare(false, Date_Calc::isLeapYear(2001), 'isLeapYear 4'); compare(false, Date_Calc::isLeapYear('2001'), 'isLeapYear 4 str'); compare(false, Date_Calc::isFutureDate('22', '11', '2000'), 'isFutureDate 1 str'); compare(false, Date_Calc::isFutureDate(22, 11, 2000), 'isFutureDate 1'); compare(true, Date_Calc::isFutureDate(22, 11, date('Y') + 1), 'isFutureDate 2'); compare(false, Date_Calc::isPastDate(22, 11, date('Y') + 1), 'isPastDate 1'); compare(true, Date_Calc::isPastDate(22, 11, 2000), 'isPastDate 2'); compare(true, Date_Calc::isPastDate('22', '11', '2000'), 'isPastDate 2 str'); compare(10, Date_Calc::dateDiff(22, 11, 2000, 12, 11, 2000), 'dateDiff 1'); compare(10, Date_Calc::dateDiff(12, 11, 2000, 22, 11, 2000), 'dateDiff 2'); compare(61, Date_Calc::dateDiff(22, 11, 2000, 22, 1, 2001), 'dateDiff 3'); compare(61, Date_Calc::dateDiff('22', '11', '2000', '22', '01', '2001'), 'dateDiff 3 str'); compare(-1, Date_Calc::compareDates(12, 11, 2000, 22, 11, 2000), 'compareDates 1'); compare(0, Date_Calc::compareDates(22, 11, 2000, 22, 11, 2000), 'compareDates 2'); compare(1, Date_Calc::compareDates(22, 11, 2000, 12, 11, 2000), 'compareDates 3'); compare(1, Date_Calc::compareDates('22', '11', '2000', '12', '11', '2000'), 'compareDates 3 str');
/** * Utility function to return an array of events with a period * @param Date Start date of the period * @param Date End date of the period * @return array A list of events */ function getEventsForPeriod($start_date, $end_date, $filter = 'all', $user_id = null, $project_id = 0) { global $AppUI; // the event times are stored as unix time stamps, just to be different // convert to default db time stamp $db_start = $start_date->format(FMT_DATETIME_MYSQL); $db_end = $end_date->format(FMT_DATETIME_MYSQL); if (!isset($user_id)) { $user_id = $AppUI->user_id; } $project =& new CProject(); if ($project_id) { $p =& $AppUI->acl(); if ($p->checkModuleItem('projects', 'view', $project_id, $user_id)) { $allowedProjects = array('p.project_id = ' . $project_id); } else { $allowedProjects = array('1=0'); } } else { $allowedProjects = $project->getAllowedSQL($user_id, 'event_project'); } //do similiar actions for recurring and non-recurring events $queries = array('q' => 'q', 'r' => 'r'); foreach ($queries as $query_set) { ${$query_set} = new DBQuery(); ${$query_set}->addTable('events', 'e'); ${$query_set}->addQuery('e.*'); ${$query_set}->addOrder('e.event_start_date, e.event_end_date ASC'); ${$query_set}->addJoin('projects', 'p', 'p.project_id = e.event_project'); if ($AppUI->getState('CalIdxCompany')) { ${$query_set}->addWhere('project_company = ' . $AppUI->getState('CalIdxCompany')); } if (count($allowedProjects)) { ${$query_set}->addWhere('((' . implode(' AND ', $allowedProjects) . ') ' . ($AppUI->getState('CalIdxCompany') ? '' : $project_id ? '' : ' OR event_project = 0 ') . ')'); } switch ($filter) { case 'my': ${$query_set}->addJoin('user_events', 'ue', 'ue.event_id = e.event_id AND ue.user_id =' . $user_id); ${$query_set}->addWhere('(ue.user_id = ' . $user_id . ') AND (event_private=0 OR event_owner=' . $user_id . ')'); break; case 'own': ${$query_set}->addWhere('event_owner =' . $user_id); break; case 'all': ${$query_set}->addWhere('(event_private=0 OR event_owner=' . $user_id . ')'); break; } if ($query_set == 'q') { // assemble query for non-recursive events ${$query_set}->addWhere('(event_recurs <= 0)'); // following line is only good for *non-recursive* events ${$query_set}->addWhere("(event_start_date <= '{$db_end}' AND event_end_date >= '{$db_start}' " . "OR event_start_date BETWEEN '{$db_start}' AND '{$db_end}')"); $eventList = ${$query_set}->loadList(); } else { if ($query_set == 'r') { // assemble query for recursive events ${$query_set}->addWhere('(event_recurs > 0)'); $eventListRec = ${$query_set}->loadList(); } } } //Calculate the Length of Period (Daily, Weekly, Monthly View) setlocale(LC_TIME, 'en_AU'); $periodLength = Date_Calc::dateDiff($start_date->getDay(), $start_date->getMonth(), $start_date->getYear(), $end_date->getDay(), $end_date->getMonth(), $end_date->getYear()); setlocale(LC_ALL, $AppUI->user_lang); // AJD: Should this be going off the end of the array? I don't think so. // If it should then a comment to that effect would be nice. // for ($i=0; $i < sizeof($eventListRec)+1; $i++) { for ($i = 0, $sz = sizeof($eventListRec); $i < $sz; $i++) { //note from merlinyoda: j=0 is the original event according to getRecurrentEventforPeriod // So, since the event is *recurring* x times, the loop condition should be j <= x, not j < x. // This way the original and all recurrances are covered. //for ($j=0; $j < intval($eventListRec[$i]['event_times_recuring']); $j++) { for ($j = 0, $end = intval($eventListRec[$i]['event_times_recuring']); $j < $end; $j++) { if ($periodLength == 1) { // Daily View: show all $recEventDate = CEvent::getRecurrentEventforPeriod($start_date, $end_date, $eventListRec[$i]['event_start_date'], $eventListRec[$i]['event_end_date'], $eventListRec[$i]['event_recurs'], $eventListRec[$i]['event_times_recuring'], $j); } elseif ($periodLength > 1 && $eventListRec[$i]['event_recurs'] == 1 && $j == 0) { // Weekly or Monthly View and Hourly Recurrent Events: show one time and add string 'hourly' $recEventDate = CEvent::getRecurrentEventforPeriod($start_date, $end_date, $eventListRec[$i]['event_start_date'], $eventListRec[$i]['event_end_date'], $eventListRec[$i]['event_recurs'], $eventListRec[$i]['event_times_recuring'], $j); $eventListRec[$i]['event_title'] = $eventListRec[$i]['event_title'] . ' (' . $AppUI->_('Hourly') . ')'; } elseif ($periodLength > 1 && $eventListRec[$i]['event_recurs'] > 1) { //Weekly and Monthly View and higher recurrence mode: show all events of recurrence > 1 $recEventDate = CEvent::getRecurrentEventforPeriod($start_date, $end_date, $eventListRec[$i]['event_start_date'], $eventListRec[$i]['event_end_date'], $eventListRec[$i]['event_recurs'], $eventListRec[$i]['event_times_recuring'], $j); } //add values to the eventsArray if check for recurrent event was positive if (sizeof($recEventDate) > 0) { $eList[0] = $eventListRec[$i]; $eList[0]['event_start_date'] = $recEventDate[0]->format(FMT_DATETIME_MYSQL); $eList[0]['event_end_date'] = $recEventDate[1]->format(FMT_DATETIME_MYSQL); $eventList = array_merge($eventList, $eList); } // clear array of positive recurrent events for the case that next loop recEventDate is empty in order to avoid double display $recEventDate = array(); } } //return a list of non-recurrent and recurrent events return $eventList; }
/** * How many whole days are covered by the range? * * @return int The number of whole days covered by the range. */ function countDays() { $start = $this->getStartDate(); $end = $this->getEndDate(); $days = Date_Calc::dateDiff($start->getDay(), $start->getMonth(), $start->getYear(), $end->getDay(), $end->getMonth(), $end->getYear()); return $days; }
/** * * @param Horde_Date $date The date to list alarms for * @param boolean $fullevent Return the full event objects? * * @return array An array of event ids, or Kronolith_Event objects * @throws Kronolith_Exception */ public function listAlarms($date, $fullevent = false) { $allevents = $this->listEvents($date, null, array('has_alarm' => true)); $events = array(); foreach ($allevents as $dayevents) { foreach ($dayevents as $event) { if (!$event->recurs()) { $start = new Horde_Date($event->start); $start->min -= $event->alarm; if ($start->compareDateTime($date) <= 0 && $date->compareDateTime($event->end) <= -1) { $events[] = $fullevent ? $event : $event->id; } } else { // Need to start at the beginning of the day to catch the // case where we might be within the event's timespan // when we call this, hence nextRecurrence() would miss the // current event. $start = clone $date; $start->min = 0; $start->hour = 0; $start->sec = 0; if ($next = $event->recurrence->nextRecurrence($start)) { if ($event->recurrence->hasException($next->year, $next->month, $next->mday)) { continue; } $start = new Horde_Date($next); $start->min -= $event->alarm; $diff = Date_Calc::dateDiff($event->start->mday, $event->start->month, $event->start->year, $event->end->mday, $event->end->month, $event->end->year); if ($diff == -1) { $diff = 0; } $end = new Horde_Date(array('year' => $next->year, 'month' => $next->month, 'mday' => $next->mday + $diff, 'hour' => $event->end->hour, 'min' => $event->end->min, 'sec' => $event->end->sec)); if ($start->compareDateTime($date) <= 0 && $date->compareDateTime($end) <= -1) { if ($fullevent) { $event->start = $next; $event->end = $end; $events[] = $event; } else { $events[] = $event->id; } } } } } } return $events; }
/** */ protected function _content() { global $page_output; $page_output->addScriptFile('tooltips.js', 'horde'); $now = new Horde_Date($_SERVER['REQUEST_TIME']); $today = date('j'); $current_month = ''; $startDate = new Horde_Date(array('year' => date('Y'), 'month' => date('n'), 'mday' => date('j'))); $endDate = new Horde_Date(array('year' => date('Y'), 'month' => date('n') + $this->_params['months'], 'mday' => date('j') - 1)); try { if (isset($this->_params['calendar']) && $this->_params['calendar'] != '__all') { $calendars = Kronolith::listCalendars(); if (!isset($calendars[$this->_params['calendar']])) { return _("Calendar not found"); } if (!$calendars[$this->_params['calendar']]->hasPermission(Horde_Perms::READ)) { return _("Permission Denied"); } list($type, $calendar) = explode('_', $this->_params['calendar'], 2); $driver = Kronolith::getDriver($type, $calendar); $all_events = $driver->listEvents($startDate, $endDate, array('show_recurrence' => true, 'has_alarm' => !empty($this->_params['alarms']), 'cover_dates' => false)); } else { $all_events = Kronolith::listEvents($startDate, $endDate, $GLOBALS['calendar_manager']->get(Kronolith::DISPLAY_CALENDARS), array('has_alarm' => !empty($this->_params['alarms']), 'cover_dates' => false)); } } catch (Exception $e) { return '<em>' . $e->getMessage() . '</em>'; } /* How many days do we need to check. */ $days = Date_Calc::dateDiff($startDate->mday, $startDate->month, $startDate->year, $endDate->mday, $endDate->month, $endDate->year); /* Loop through the days. */ $totalevents = 0; $html = ''; for ($i = 0; $i < $days; ++$i) { $day = new Kronolith_Day($startDate->month, $today + $i); $date_stamp = $day->dateString(); if (empty($all_events[$date_stamp])) { continue; } if (!empty($this->_params['maxevents']) && $totalevents >= $this->_params['maxevents']) { break; } /* Output month header. */ if ($current_month != $day->month) { $html .= '<tr><td colspan="4" class="control"><strong>' . $day->strftime('%B') . '</strong></td></tr>'; } $firstevent = true; $tomorrow = $day->getTomorrow(); foreach ($all_events[$date_stamp] as $event) { $isMultiDay = false; if ($event->start->compareDate($day) < 0) { $event->start = new Horde_Date($day); } if ($event->end->compareDate($tomorrow) >= 1) { $isMultiDay = true; } if ($event->end->compareDate($now) < 0 && !$event->isAllDay() || !empty($this->_params['alarms']) && !$event->alarm) { continue; } if ($firstevent || $isMultiDay) { $html .= '<tr'; if ($current_month == $day->month) { $html .= ' class="upcomingday"'; } $html .= '><td class="text" valign="top" align="right"><strong>'; if ($day->isToday()) { $html .= _("Today"); } elseif ($day->isTomorrow()) { $html .= _("Tomorrow"); } else { $html .= $day->mday; } if ($isMultiDay) { $endDay = new Kronolith_Day($event->end->month, $event->end->mday); $html .= ' - '; if ($endDay->isTomorrow()) { $html .= _("Tomorrow"); } else { $html .= $event->end->mday; } } $html .= '</strong> </td>'; $firstevent = $isMultiDay; } else { $html .= '<tr><td class="text"> </td>'; } $html .= '<td class="text" nowrap="nowrap" valign="top">'; if ($event->start->compareDate($now) < 0 && $event->end->compareDate($now) > 0) { $html .= '<strong>' . htmlspecialchars($event->getLocation()) . '</strong>'; } else { $html .= htmlspecialchars($event->getLocation()); } if ($event->start->compareDate($now) < 0 && $event->end->compareDate($now) > 0) { $html .= '<strong>'; } $html .= $event->getLink(null, true, null, true); if ($event->start->compareDate($now) < 0 && $event->end->compareDate($now) > 0) { $html .= '</strong>'; } $html .= '</td></tr>'; $totalevents++; } $current_month = $day->strftime('%m'); } if (empty($html)) { return '<em>' . _("No events to display") . '</em>'; } return '<table cellspacing="0" width="100%">' . $html . '</table>'; }
public function diff($other = null) { $day2 = new Kronolith_Day(); return Date_Calc::dateDiff($this->mday, $this->month, $this->year, $day2->mday, $day2->month, $day2->year); }
/** * New method to get the difference in days the stored date * @author Andrew Eddie <*****@*****.**> * * @param $when * @return bool|int */ public function dateDiff($when) { if (!is_object($when)) { return false; } $date_calc = new Date_Calc(); return $date_calc->dateDiff($this->getDay(), $this->getMonth(), $this->getYear(), $when->getDay(), $when->getMonth(), $when->getYear()); }
/** * Sets the span from the elapsed time between two dates * * The time span is unsigned, so the date's order is not important. * * @param object $date1 first Date * @param object $date2 second Date * * @return bool true on success * @access public * @see Date_Span::set() */ function setFromDateDiff($date1, $date2) { if (!is_a($date1, 'date') or !is_a($date2, 'date')) { return false; } // create a local copy of instance, in order avoid changes the object // reference when its object has converted to UTC due PHP5 is always // passed the object by reference. $tdate1 = new Date($date1); $tdate2 = new Date($date2); // convert to UTC $tdate1->toUTC(); $tdate2->toUTC(); if ($tdate1->after($tdate2)) { list($tdate1, $tdate2) = array($tdate2, $tdate1); } $days = Date_Calc::dateDiff($tdate1->getDay(), $tdate1->getMonth(), $tdate1->getYear(), $tdate2->getDay(), $tdate2->getMonth(), $tdate2->getYear()); $hours = $tdate2->getHour() - $tdate1->getHour(); $mins = $tdate2->getMinute() - $tdate1->getMinute(); $secs = $tdate2->getSecond() - $tdate1->getSecond(); $this->setFromSeconds($days * 86400 + $hours * 3600 + $mins * 60 + $secs); return true; }
/** * A method to update the summary table from the intermediate tables. * * @param PEAR::Date $oStartDate The start date/time to update from. * @param PEAR::Date $oEndDate The end date/time to update to. * @param array $aActions An array of data types to summarise. Contains * two array, the first containing the data types, * and the second containing the connection type * values associated with those data types, if * appropriate. For example: * array( * 'types' => array( * 0 => 'request', * 1 => 'impression', * 2 => 'click' * ), * 'connections' => array( * 1 => MAX_CONNECTION_AD_IMPRESSION, * 2 => MAX_CONNECTION_AD_CLICK * ) * ) * Note that the order of the items must match * the order of the items in the database tables * (e.g. in data_intermediate_ad and * data_summary_ad_hourly for the above example). * @param string $fromTable The name of the intermediate table to summarise * from (e.g. 'data_intermediate_ad'). * @param string $toTable The name of the summary table to summarise to * (e.g. 'data_summary_ad_hourly'). */ function saveSummary($oStartDate, $oEndDate, $aActions, $fromTable, $toTable) { $aConf = $GLOBALS['_MAX']['CONF']; // Check that there are types to summarise if (empty($aActions['types']) || empty($aActions['connections'])) { return; } // How many days does the start/end period span? $days = Date_Calc::dateDiff($oStartDate->getDay(), $oStartDate->getMonth(), $oStartDate->getYear(), $oEndDate->getDay(), $oEndDate->getMonth(), $oEndDate->getYear()); if ($days == 0) { // Save the data $this->_saveSummary($oStartDate, $oEndDate, $aActions, $fromTable, $toTable); } else { // Save each day's data separately for ($counter = 0; $counter <= $days; $counter++) { if ($counter == 0) { // This is the first day $oInternalStartDate = new Date(); $oInternalStartDate->copy($oStartDate); $oInternalEndDate = new Date($oStartDate->format('%Y-%m-%d') . ' 23:59:59'); } elseif ($counter == $days) { // This is the last day $oInternalStartDate = new Date($oEndDate->format('%Y-%m-%d') . ' 00:00:00'); $oInternalEndDate = new Date(); $oInternalEndDate->copy($oEndDate); } else { // This is a day in the middle $oDayDate = new Date(); $oDayDate->copy($oStartDate); $oDayDate->addSeconds(SECONDS_PER_DAY * $counter); $oInternalStartDate = new Date($oDayDate->format('%Y-%m-%d') . ' 00:00:00'); $oInternalEndDate = new Date($oDayDate->format('%Y-%m-%d') . ' 23:59:59'); } $this->_saveSummary($oInternalStartDate, $oInternalEndDate, $aActions, $fromTable, $toTable); } } }
/** * Utility function to return an array of events with a period * @param Date Start date of the period * @param Date End date of the period * @return array A list of events */ function getEventsForPeriod($start_date, $end_date, $filter = 'all', $user_id = null, $project_id = 0) { global $AppUI; // the event times are stored as unix time stamps, just to be different // convert to default db time stamp $db_start = $start_date->format(FMT_DATETIME_MYSQL); $db_end = $end_date->format(FMT_DATETIME_MYSQL); if (!isset($user_id)) { $user_id = $AppUI->user_id; } $project = new CProject(); if ($project_id) { $p =& $AppUI->acl(); if ($p->checkModuleItem('projects', 'view', $project_id, $user_id)) { $allowedProjects = array('p.project_id = ' . $project_id); } else { $allowedProjects = array('1=0'); } } else { $allowedProjects = $project->getAllowedSQL($user_id, 'event_project'); } //do similiar actions for recurring and non-recurring events $queries = array('q' => 'q', 'r' => 'r'); foreach ($queries as $query_set) { ${$query_set} = new DBQuery(); ${$query_set}->addTable('events', 'e'); ${$query_set}->addQuery('DISTINCT e.*'); ${$query_set}->addOrder('e.event_start_date, e.event_end_date ASC'); ${$query_set}->addJoin('projects', 'p', 'p.project_id = e.event_project'); if ($AppUI->getState('CalIdxCompany')) { ${$query_set}->addWhere('p.project_company = ' . $AppUI->getState('CalIdxCompany')); } if (count($allowedProjects)) { ${$query_set}->addWhere('((' . implode(' AND ', $allowedProjects) . ') ' . ($AppUI->getState('CalIdxCompany') || $project_id ? '' : ' OR event_project = 0 ') . ')'); } switch ($filter) { case 'my': ${$query_set}->addJoin('user_events', 'ue', 'ue.event_id = e.event_id AND ue.user_id =' . $user_id); ${$query_set}->addWhere('(ue.user_id = ' . $user_id . ') AND (event_private=0 OR event_owner=' . $user_id . ')'); break; case 'own': ${$query_set}->addWhere('e.event_owner =' . $user_id); break; case 'all': ${$query_set}->addWhere('(e.event_private=0 OR e.event_owner=' . $user_id . ')'); break; } if ($query_set == 'q') { // assemble query for non-recursive events // following line is only good for *non-recursive* events ${$query_set}->addWhere('(event_recurs <= 0)'); ${$query_set}->addWhere("(event_start_date < '{$db_end}'" . " AND event_end_date > '{$db_start}')"); $eventList = ${$query_set}->loadList(); } else { if ($query_set == 'r') { // assemble query for recursive events ${$query_set}->addWhere('(event_recurs > 0)'); $eventListRec = ${$query_set}->loadList(); } } } //Calculate the Length of Period (Daily, Weekly, Monthly View) setlocale(LC_ALL, 'en_AU' . ($locale_char_set ? '.' . $locale_char_set : '.utf8')); $periodLength = Date_Calc::dateDiff($end_date->getDay(), $end_date->getMonth(), $end_date->getYear(), $start_date->getDay(), $start_date->getMonth(), $start_date->getYear()); setlocale(LC_ALL, $AppUI->user_lang); foreach ($eventListRec as $key => $ia) { $end = intval($ia['event_times_recuring']); for ($j = 0; $j < $end; $j++) { $recEventDate = array(); if ($periodLength <= 1) { // Daily View or clash check: show all $recEventDate = CEvent::getRecurrentEventforPeriod($start_date, $end_date, $ia['event_start_date'], $ia['event_end_date'], $ia['event_recurs'], $ia['event_times_recuring'], $j); } else { if ($ia['event_recurs'] == 1 && $j == 0) { // Weekly or Monthly View and Hourly Recurrent Events //show one time and add string 'hourly' $recEventDate = CEvent::getRecurrentEventforPeriod($start_date, $end_date, $ia['event_start_date'], $ia['event_end_date'], $ia['event_recurs'], $ia['event_times_recuring'], $j); $eventListRec[$key]['event_title'] = $ia['event_title'] . ' (' . $AppUI->_('Hourly') . ')'; } else { if ($ia['event_recurs'] > 1) { //Weekly and Monthly View and higher recurrence mode //show all events of recurrence > 1 $recEventDate = CEvent::getRecurrentEventforPeriod($start_date, $end_date, $ia['event_start_date'], $ia['event_end_date'], $ia['event_recurs'], $ia['event_times_recuring'], $j); } } } //add values to the eventsArray if check for recurrent event was positive if (!empty($recEventDate)) { $display_start = $recEventDate[0]->format(FMT_DATETIME_MYSQL); $display_end = $recEventDate[1]->format(FMT_DATETIME_MYSQL); $eventListRec[$key]['event_start_date'] = $display_start; $eventListRec[$key]['event_end_date'] = $display_end; $eventList = array_merge($eventList, array($eventListRec[$key])); } } } //return a list of non-recurrent and recurrent events return $eventList; }
/** * Utility function to return an array of events with a period * @param Date Start date of the period * @param Date End date of the period * @return array A list of events */ function getEventsForPeriod($start_date, $end_date, $filter = 'all', $user_id = null) { global $AppUI; // the event times are stored as unix time stamps, just to be different // convert to default db time stamp $db_start = $start_date->format(FMT_DATETIME_MYSQL); $db_end = $end_date->format(FMT_DATETIME_MYSQL); if (!isset($user_id)) { $user_id = $AppUI->user_id; } $project =& new CProject(); $allowedProjects = $project->getAllowedSQL($user_id, 'event_project'); $q = new DBQuery(); $q->addTable('events', 'e'); $q->addQuery('e.*'); if (count($allowedProjects)) { $q->addWhere('( ( ' . implode(' AND ', $allowedProjects) . ") OR event_project = 0 )"); $q->addJoin('projects', 'p', 'p.project_id = e.event_project'); } switch ($filter) { case 'my': $q->addJoin('user_events', 'ue', 'ue.event_id = e.event_id AND ue.user_id =' . $user_id); $q->addWhere("( ( event_private = 0 AND ue.user_id = {$user_id} )\n\t\t\t\t\t\tOR event_owner={$user_id} )"); break; case 'own': $q->addWhere("( event_owner = {$user_id} )"); break; case 'all': $q->addWhere("( event_private=0 OR (event_private=1 AND event_owner={$user_id}) )"); break; } $q->addWhere("( event_start_date <= '{$db_end}' AND event_end_date >= '{$db_start}'\n\t\t\t\tOR event_start_date BETWEEN '{$db_start}' AND '{$db_end}')"); // duplicate query object for recursive events; $r = $q; // assemble query for non-recursive events $q->addWhere('( event_recurs <= 0 )'); $eventList = $q->loadList(); // assemble query for recursive events $r->addWhere('( event_recurs > 0 )'); $eventListRec = $r->loadList(); //Calculate the Length of Period (Daily, Weekly, Monthly View) $periodLength = Date_Calc::dateDiff($start_date->getDay(), $start_date->getMonth(), $start_date->getYear(), $end_date->getDay(), $end_date->getMonth(), $end_date->getYear()); // AJD: Should this be going off the end of the array? I don't think so. // If it should then a comment to that effect would be nice. // for ($i=0; $i < sizeof($eventListRec)+1; $i++) { for ($i = 0; $i < sizeof($eventListRec); $i++) { for ($j = 0; $j < intval($eventListRec[$i]['event_times_recuring']); $j++) { //Daily View //show all if ($periodLength == 1) { $recEventDate = CEvent::getRecurrentEventforPeriod($start_date, $end_date, $eventListRec[$i]['event_start_date'], $eventListRec[$i]['event_end_date'], $eventListRec[$i]['event_recurs'], $eventListRec[$i]['event_times_recuring'], $j); } elseif ($periodLength > 1 && $eventListRec[$i]['event_recurs'] == 1 && $j == 0) { $recEventDate = CEvent::getRecurrentEventforPeriod($start_date, $end_date, $eventListRec[$i]['event_start_date'], $eventListRec[$i]['event_end_date'], $eventListRec[$i]['event_recurs'], $eventListRec[$i]['event_times_recuring'], $j); $eventListRec[$i]['event_title'] = $eventListRec[$i]['event_title'] . " (" . $AppUI->_('Hourly') . ")"; } elseif ($periodLength > 1 && $eventListRec[$i]['event_recurs'] > 1) { $recEventDate = CEvent::getRecurrentEventforPeriod($start_date, $end_date, $eventListRec[$i]['event_start_date'], $eventListRec[$i]['event_end_date'], $eventListRec[$i]['event_recurs'], $eventListRec[$i]['event_times_recuring'], $j); } //add values to the eventsArray if check for recurrent event was positive if (sizeof($recEventDate) > 0) { $eList[0] = $eventListRec[$i]; $eList[0]['event_start_date'] = $recEventDate[0]->format(FMT_DATETIME_MYSQL); $eList[0]['event_end_date'] = $recEventDate[1]->format(FMT_DATETIME_MYSQL); $eventList = array_merge($eventList, $eList); } // clear array of positive recurrent events for the case that next loop recEventDate is empty in order to avoid double display $recEventDate = array(); } } //return a list of non-recurrent and recurrent events return $eventList; }
function _excelDate($iso) { if (!strlen(trim($iso))) { return ''; } $bits = explode('-', $iso); require_once 'Date/Calc.php'; //? should this be //print_r($bits); $r = Date_Calc::dateDiff(30, 12, 1899, $bits[2], $bits[1], $bits[0]); //echo "$iso => $r";exit; return $r; }
public function getDuration() { if (isset($this->_duration)) { return $this->_duration; } if ($this->start && $this->end) { $dur_day_match = Date_Calc::dateDiff($this->start->mday, $this->start->month, $this->start->year, $this->end->mday, $this->end->month, $this->end->year); $dur_hour_match = $this->end->hour - $this->start->hour; $dur_min_match = $this->end->min - $this->start->min; while ($dur_min_match < 0) { $dur_min_match += 60; --$dur_hour_match; } while ($dur_hour_match < 0) { $dur_hour_match += 24; --$dur_day_match; } } else { $dur_day_match = 0; $dur_hour_match = 1; $dur_min_match = 0; } $this->_duration = new stdClass(); $this->_duration->day = $dur_day_match; $this->_duration->hour = $dur_hour_match; $this->_duration->min = $dur_min_match; $this->_duration->wholeDay = $this->isAllDay(); return $this->_duration; }
/** * Utility function to return an array of events with a period * @param Date Start date of the period * @param Date End date of the period * @return array A list of events */ public function getEventsForPeriod($start_date, $end_date, $filter = 'all', $user_id = null, $project_id = 0, $company_id = 0) { global $AppUI; // convert to default db time stamp $db_start = $start_date->format(FMT_DATETIME_MYSQL); $db_start = $AppUI->convertToSystemTZ($db_start); $db_end = $end_date->format(FMT_DATETIME_MYSQL); $db_end = $AppUI->convertToSystemTZ($db_end); if (!isset($user_id)) { $user_id = $AppUI->user_id; } $project = new CProject(); if ($project_id) { $p =& $AppUI->acl(); if ($p->checkModuleItem('projects', 'view', $project_id, $user_id)) { $allowedProjects = array('p.project_id = ' . (int) $project_id); } else { $allowedProjects = array('1=0'); } } else { $allowedProjects = $project->getAllowedSQL($user_id ? $user_id : $AppUI->user_id, 'event_project'); } //do similiar actions for recurring and non-recurring events $queries = array('q' => 'q', 'r' => 'r'); foreach ($queries as $query_set) { ${$query_set} = new w2p_Database_Query(); ${$query_set}->addTable('events', 'e'); ${$query_set}->addQuery('e.*'); ${$query_set}->addOrder('e.event_start_date, e.event_end_date ASC'); ${$query_set}->leftJoin('projects', 'p', 'p.project_id = e.event_project'); ${$query_set}->leftJoin('project_departments', 'project_departments', 'p.project_id = project_departments.project_id OR project_departments.project_id IS NULL'); ${$query_set}->leftJoin('departments', 'departments', 'departments.dept_id = project_departments.department_id OR dept_id IS NULL'); if ($company_id) { ${$query_set}->addWhere('project_company = ' . (int) $company_id); } else { if ($AppUI->getState('CalIdxCompany')) { ${$query_set}->addWhere('project_company = ' . $AppUI->getState('CalIdxCompany')); } } if (count($allowedProjects)) { ${$query_set}->addWhere('( ( ' . implode(' AND ', $allowedProjects) . ' ) ' . ($AppUI->getState('CalIdxCompany') ? '' : ($project_id ? '' : ' OR event_project = 0 ')) . ')'); } switch ($filter) { case 'my': ${$query_set}->addJoin('user_events', 'ue', 'ue.event_id = e.event_id AND ue.user_id =' . $user_id); ${$query_set}->addWhere('(ue.user_id = ' . (int) $user_id . ') AND (event_private = 0 OR event_owner=' . (int) $user_id . ')'); break; case 'own': ${$query_set}->addWhere('event_owner =' . (int) $user_id); break; case 'all': ${$query_set}->addWhere('(event_private = 0 OR event_owner=' . (int) $user_id . ')'); break; default: ${$query_set}->addWhere('(event_private = 0 OR event_owner=' . (int) $user_id . ')'); } if ($query_set == 'q') { // assemble query for non-recursive events ${$query_set}->addWhere('(event_recurs <= 0)'); // following line is only good for *non-recursive* events ${$query_set}->addWhere('(event_start_date <= \'' . $db_end . '\' AND event_end_date >= \'' . $db_start . '\' OR event_start_date BETWEEN \'' . $db_start . '\' AND \'' . $db_end . '\')'); $eventList = ${$query_set}->loadList(); } elseif ($query_set == 'r') { // assemble query for recursive events ${$query_set}->addWhere('(event_recurs > 0)'); $eventListRec = ${$query_set}->loadList(); } } //Calculate the Length of Period (Daily, Weekly, Monthly View) setlocale(LC_TIME, 'en'); $periodLength = Date_Calc::dateDiff($start_date->getDay(), $start_date->getMonth(), $start_date->getYear(), $end_date->getDay(), $end_date->getMonth(), $end_date->getYear()); setlocale(LC_ALL, $AppUI->user_lang); // AJD: Should this be going off the end of the array? I don't think so. // If it should then a comment to that effect would be nice. for ($i = 0, $i_cmp = sizeof($eventListRec); $i < $i_cmp; $i++) { //note from merlinyoda: j=0 is the original event according to getRecurrentEventforPeriod // So, since the event is *recurring* x times, the loop condition should be j <= x, not j < x. // This way the original and all recurrances are covered. for ($j = 0, $j_cmp = intval($eventListRec[$i]['event_times_recuring']); $j <= $j_cmp; $j++) { //Daily View //show all if ($periodLength <= 1) { $recEventDate = CEvent::getRecurrentEventforPeriod($start_date, $end_date, $eventListRec[$i]['event_start_date'], $eventListRec[$i]['event_end_date'], $eventListRec[$i]['event_recurs'], $eventListRec[$i]['event_times_recuring'], $j); } elseif ($periodLength > 1 && $eventListRec[$i]['event_recurs'] == 1 && $j == 0) { $recEventDate = CEvent::getRecurrentEventforPeriod($start_date, $end_date, $eventListRec[$i]['event_start_date'], $eventListRec[$i]['event_end_date'], $eventListRec[$i]['event_recurs'], $eventListRec[$i]['event_times_recuring'], $j); $eventListRec[$i]['event_title'] = $eventListRec[$i]['event_title'] . ' (' . $AppUI->_('Hourly') . ')'; } elseif ($periodLength > 1 && $eventListRec[$i]['event_recurs'] > 1) { $recEventDate = CEvent::getRecurrentEventforPeriod($start_date, $end_date, $eventListRec[$i]['event_start_date'], $eventListRec[$i]['event_end_date'], $eventListRec[$i]['event_recurs'], $eventListRec[$i]['event_times_recuring'], $j); } //add values to the eventsArray if check for recurrent event was positive if (sizeof($recEventDate) > 0) { $eList[0] = $eventListRec[$i]; $eList[0]['event_start_date'] = $recEventDate[0]->format(FMT_DATETIME_MYSQL); $eList[0]['event_end_date'] = $recEventDate[1]->format(FMT_DATETIME_MYSQL); $eventList = array_merge($eventList, $eList); } // clear array of positive recurrent events for the case that next loop recEventDate is empty in order to avoid double display $recEventDate = array(); } } $i = 0; foreach ($eventList as $event) { $eventList[$i]['event_start_date'] = $AppUI->formatTZAwareTime($event['event_start_date'], '%Y-%m-%d %H:%M:%S'); $eventList[$i]['event_end_date'] = $AppUI->formatTZAwareTime($event['event_end_date'], '%Y-%m-%d %H:%M:%S'); $i++; } //echo '<pre>'; print_r($eventList); echo '</pre>'; //return a list of non-recurrent and recurrent events return $eventList; }
/** * Set the span from the elapsed time between two dates * * The time span is unsigned, so the date's order is not important. * * @param object $date1 first Date * @param object $date2 second Date * * @return bool true on success * @access public */ function setFromDateDiff($date1, $date2) { if (!is_a($date1, 'date') or !is_a($date2, 'date')) { return false; } $date1->toUTC(); $date2->toUTC(); if ($date1->after($date2)) { list($date1, $date2) = array($date2, $date1); } $days = Date_Calc::dateDiff($date1->getDay(), $date1->getMonth(), $date1->getYear(), $date2->getDay(), $date2->getMonth(), $date2->getYear()); $hours = $date2->getHour() - $date1->getHour(); $mins = $date2->getMinute() - $date1->getMinute(); $secs = $date2->getSecond() - $date1->getSecond(); $this->setFromSeconds($days * 86400 + $hours * 3600 + $mins * 60 + $secs); return true; }
/** * Upgrades an old install of PostCalendar * * This function is used to upgrade an old version * of PostCalendar. It is accessed via the PostNuke * Admin interface and should not be called directly. * * @return boolean true/false * @param string $oldversion Version we're upgrading * @access public * @author Roger Raymond <*****@*****.**> * @copyright The PostCalendar Team 2002 */ function postcalendar_upgrade($oldversion) { /** * Until PostNuke fixes the bugs * with the module upgrade we are * going to have to do it ourselves. * * Please do not use the Modules admin * to upgrade PostCalendar. Use the * link provided in the PostCalendar * Admin section. */ $pcModInfo = pnModGetInfo(pnModGetIDFromName(__POSTCALENDAR__)); $pcDir = pnVarPrepForOS($pcModInfo['directory']); list($dbconn) = pnDBGetConn(); $pntable = pnDBGetTables(); $events_table = $pntable['postcalendar_events']; $cat_table = $pntable['postcalendar_categories']; switch ($oldversion) { case '3.0': case '3.01': case '3.02': case '3.03': case '3.04': // we need the Date_Calc class require_once "modules/{$pcDir}/pnincludes/Date/Calc.php"; // Update PostCalendar Variables pnModSetVar(__POSTCALENDAR__, 'pcTime24Hours', pnModGetVar(__POSTCALENDAR__, 'time24hours')); pnModSetVar(__POSTCALENDAR__, 'pcEventsOpenInNewWindow', pnModGetVar(__POSTCALENDAR__, 'eventsopeninnewwindow')); pnModSetVar(__POSTCALENDAR__, 'pcUseInternationalDates', pnModGetVar(__POSTCALENDAR__, 'useinternationaldates')); pnModSetVar(__POSTCALENDAR__, 'pcFirstDayOfWeek', pnModGetVar(__POSTCALENDAR__, 'firstdayofweek')); pnModSetVar(__POSTCALENDAR__, 'pcDayHighlightColor', pnModGetVar(__POSTCALENDAR__, 'dayhighlightcolor')); pnModSetVar(__POSTCALENDAR__, 'pcUsePopups', pnModGetVar(__POSTCALENDAR__, 'usepopups')); pnModSetVar(__POSTCALENDAR__, 'pcDisplayTopics', pnModGetVar(__POSTCALENDAR__, 'displaytopics')); pnModSetVar(__POSTCALENDAR__, 'pcAllowDirectSubmit', '0'); pnModSetVar(__POSTCALENDAR__, 'pcListHowManyEvents', pnModGetVar(__POSTCALENDAR__, 'listhowmanyevents')); pnModSetVar(__POSTCALENDAR__, 'pcTimeIncrement', '15'); pnModSetVar(__POSTCALENDAR__, 'pcAllowSiteWide', '0'); pnModSetVar(__POSTCALENDAR__, 'pcAllowUserCalendar', '1'); pnModSetVar(__POSTCALENDAR__, 'pcEventDateFormat', '%Y-%m-%d'); pnModSetVar(__POSTCALENDAR__, 'pcTemplate', 'default'); pnModSetVar(__POSTCALENDAR__, 'pcUseCache', '1'); pnModSetVar(__POSTCALENDAR__, 'pcCacheLifetime', '3600'); pnModSetVar(__POSTCALENDAR__, 'pcDefaultView', 'month'); pnModSetVar(__POSTCALENDAR__, 'pcSafeMode', '0'); // alter the events table and change some old columns $sql = "ALTER TABLE {$events_table}\n ADD pc_catid int(11) default '0' NOT NULL,\n\t\t\t\t\tADD pc_duration bigint(20) default '0' NOT NULL,\n ADD pc_sharing int(11) default '0' NOT NULL,\n ADD pc_language varchar(30) default '',\n\t\t\t\t\tCHANGE pc_eid pc_eid int(11) unsigned NOT NULL auto_increment,\n CHANGE pc_location pc_location text,\n CHANGE pc_conttel pc_conttel varchar(50),\n CHANGE pc_contname pc_contname varchar(150),\n CHANGE pc_contemail pc_contemail varchar(255),\n CHANGE pc_website pc_website varchar(255),\n CHANGE pc_fee pc_fee varchar(50),\n CHANGE pc_recurrspec pc_recurrspec text default ''\n "; $dbconn->Execute($sql); if ($dbconn->ErrorNo() != 0) { die('event table alter error : ' . $dbconn->ErrorMsg()); return false; } // create the new categories table $sql = "CREATE TABLE {$cat_table} (\n pc_catid int(11) unsigned NOT NULL auto_increment,\n pc_catname varchar(100) NOT NULL default 'Undefined',\n pc_catcolor varchar(50) NOT NULL default '#EEEEEE',\n pc_catdesc text default '',\n PRIMARY KEY(pc_catid)\n )"; $dbconn->Execute($sql); if ($dbconn->ErrorNo() != 0) { die('cat table create error : ' . $dbconn->ErrorMsg()); return false; } // insert the current hardcoded categories into the new categories table $category1 = pnVarPrepForStore(pnModGetVar(__POSTCALENDAR__, 'category1')); $category2 = pnVarPrepForStore(pnModGetVar(__POSTCALENDAR__, 'category2')); $category3 = pnVarPrepForStore(pnModGetVar(__POSTCALENDAR__, 'category3')); $category4 = pnVarPrepForStore(pnModGetVar(__POSTCALENDAR__, 'category4')); $category5 = pnVarPrepForStore(pnModGetVar(__POSTCALENDAR__, 'category5')); $inserts = array("INSERT INTO {$cat_table} (pc_catid,pc_catname,pc_catcolor) VALUES ('1','{$category1}','#EEEEEE')", "INSERT INTO {$cat_table} (pc_catid,pc_catname,pc_catcolor) VALUES ('2','{$category2}','#00ff00')", "INSERT INTO {$cat_table} (pc_catid,pc_catname,pc_catcolor) VALUES ('3','{$category3}','#0000ff')", "INSERT INTO {$cat_table} (pc_catid,pc_catname,pc_catcolor) VALUES ('4','{$category4}','#ffffff')", "INSERT INTO {$cat_table} (pc_catid,pc_catname,pc_catcolor) VALUES ('5','{$category5}','#ffcc00')"); foreach ($inserts as $insert) { $dbconn->Execute($insert); if ($dbconn->ErrorNo() != 0) { die('cat table insert error : ' . $dbconn->ErrorMsg()); return false; } } // update the current events to reflect the category system change $updates = array("UPDATE {$events_table} SET pc_catid = 1 WHERE pc_barcolor = 'r' ", "UPDATE {$events_table} SET pc_catid = 2 WHERE pc_barcolor = 'g' ", "UPDATE {$events_table} SET pc_catid = 3 WHERE pc_barcolor = 'b' ", "UPDATE {$events_table} SET pc_catid = 4 WHERE pc_barcolor = 'w' ", "UPDATE {$events_table} SET pc_catid = 5 WHERE pc_barcolor = 'y' "); foreach ($updates as $update) { $dbconn->Execute($update); if ($dbconn->ErrorNo() != 0) { die('event table update error : ' . $dbconn->ErrorMsg()); return false; } } // alter the events table and drop the old barcolor column $sql = "ALTER TABLE {$events_table} DROP pc_barcolor"; $dbconn->Execute($sql); if ($dbconn->ErrorNo() != 0) { die('cat table alter error : ' . $dbconn->ErrorMsg()); return false; } // remove the old vars as they are no longer needed pnModDelVar(__POSTCALENDAR__, 'category1'); pnModDelVar(__POSTCALENDAR__, 'category2'); pnModDelVar(__POSTCALENDAR__, 'category3'); pnModDelVar(__POSTCALENDAR__, 'category4'); pnModDelVar(__POSTCALENDAR__, 'category5'); pnModDelVar(__POSTCALENDAR__, 'time24hours'); pnModDelVar(__POSTCALENDAR__, 'eventsopeninnewwindow'); pnModDelVar(__POSTCALENDAR__, 'useinternationaldates'); pnModDelVar(__POSTCALENDAR__, 'firstdayofweek'); pnModDelVar(__POSTCALENDAR__, 'dayhighlightcolor'); pnModDelVar(__POSTCALENDAR__, 'displaytopics'); pnModDelVar(__POSTCALENDAR__, 'usepopups'); pnModDelVar(__POSTCALENDAR__, 'listhowmanyevents'); pnModDelVar(__POSTCALENDAR__, 'allowdirectsubmit'); pnModDelVar(__POSTCALENDAR__, 'showeventsinyear'); //====================================================== // now, ideally, we will convert old events to the new // style. this consists of reconfiguring the repeating // events vars. // // we need to establish the current repeating // conditions and convert them to the new system //====================================================== // old repeating defines //====================================================== @define('_EVENT_NONE', -1); @define('_EVENT_DAILY', 0); @define('_EVENT_WEEKLY', 1); @define('_EVENT_MONTHLY', 2); @define('_EVENT_YEARLY', 3); @define('_RECUR_SAME_DAY', 0); @define('_RECUR_SAME_DATE', 1); //====================================================== // new repeating defines // $recurrspec['event_repeat'] //====================================================== @define('NO_REPEAT', 0); @define('REPEAT', 1); @define('REPEAT_ON', 2); //====================================================== // $recurrspec['event_repeat_freq'] //====================================================== @define('REPEAT_EVERY', 1); @define('REPEAT_EVERY_OTHER', 2); @define('REPEAT_EVERY_THIRD', 3); @define('REPEAT_EVERY_FOURTH', 4); //====================================================== // $recurrspec['event_repeat_freq_type'] //====================================================== @define('REPEAT_EVERY_DAY', 0); @define('REPEAT_EVERY_WEEK', 1); @define('REPEAT_EVERY_MONTH', 2); @define('REPEAT_EVERY_YEAR', 3); //====================================================== // $recurrspec['event_repeat_on_num'] //====================================================== @define('REPEAT_ON_1ST', 1); @define('REPEAT_ON_2ND', 2); @define('REPEAT_ON_3RD', 3); @define('REPEAT_ON_4TH', 4); @define('REPEAT_ON_LAST', 5); //====================================================== // $recurrspec['event_repeat_on_day'] //====================================================== @define('REPEAT_ON_SUN', 0); @define('REPEAT_ON_MON', 1); @define('REPEAT_ON_TUE', 2); @define('REPEAT_ON_WED', 3); @define('REPEAT_ON_THU', 4); @define('REPEAT_ON_FRI', 5); @define('REPEAT_ON_SAT', 6); //====================================================== // $recurrspec['event_repeat_on_freq'] //====================================================== @define('REPEAT_ON_MONTH', 1); @define('REPEAT_ON_2MONTH', 2); @define('REPEAT_ON_3MONTH', 3); @define('REPEAT_ON_4MONTH', 4); @define('REPEAT_ON_6MONTH', 6); @define('REPEAT_ON_YEAR', 12); //====================================================== // Set Sharing Paramaters //====================================================== @define('SHARING_PRIVATE', 0); @define('SHARING_PUBLIC', 1); @define('SHARING_BUSY', 2); @define('SHARING_GLOBAL', 3); //====================================================== // Here's some psuedo-code for the conversion // // if _EVENT_NONE // $rtype = NO_REPEAT // $rspec = 0 for all; // $duration = endTime - startTime // // if _EVENT_DAILY // $rtype = REPEAT // $rspec = REPEAT_EVERY|REPEAT_EVERY_DAY // $duration = endTime - startTime // // if _EVENT_WEEKLY // $rtype = REPEAT // $rspec = REPEAT_EVERY|REPEAT_EVERY_WEEK // $duration = endTime - startTime // // if _EVENT_MONTHLY // if _RECUR_SAME_DAY // $rtype = REPEAT_ON // $rspec = REPEAT_ON_NUM|REPEAT_ON_DAY|REPEAT_ON_FREQ // if _RECUR_SAME_DATE // $rtype = REPEAT // $rspec = REPEAT_EVERY|REPEAT_EVERY_MONTH // $duration = endTime - startTime // // if _EVENT_YEARLY // if _RECUR_SAME_DAY // $rtype = REPEAT_ON // $rspec = REPEAT_ON_NUM|REPEAT_ON_DAY|REPEAT_ON_FREQ // if _RECUR_SAME_DATE // $rtype = REPEAT // $rspec = REPEAT_EVERY|REPEAT_EVERY_YEAR // $duration = endTime - startTime //====================================================== // attempt reconfiguration //====================================================== $sql = "SELECT pc_eid, pc_eventDate, pc_startTime, pc_endTime, pc_recurrtype, pc_recurrfreq\n FROM {$events_table}"; $result = $dbconn->Execute($sql); if ($dbconn->ErrorNo() != 0) { die($dbconn->ErrorMsg()); return false; } if (!isset($result)) { return false; } // grab the results and start the conversion for (; !$result->EOF; $result->MoveNext()) { $recurrspec = array(); list($eid, $eventdate, $start, $end, $rtype, $rfreq) = $result->fields; if ($rtype == null) { $rtype = _EVENT_NONE; } switch ($rtype) { case _EVENT_NONE: $recurrtype = NO_REPEAT; $recurrspec['event_repeat_freq'] = 0; $recurrspec['event_repeat_freq_type'] = 0; $recurrspec['event_repeat_on_num'] = 0; $recurrspec['event_repeat_on_day'] = 0; $recurrspec['event_repeat_on_freq'] = 0; break; case _EVENT_DAILY: $recurrtype = REPEAT; $recurrspec['event_repeat_freq'] = REPEAT_EVERY; $recurrspec['event_repeat_freq_type'] = REPEAT_EVERY_DAY; $recurrspec['event_repeat_on_num'] = 0; $recurrspec['event_repeat_on_day'] = 0; $recurrspec['event_repeat_on_freq'] = 0; break; case _EVENT_WEEKLY: $recurrtype = REPEAT; $recurrspec['event_repeat_freq'] = REPEAT_EVERY; $recurrspec['event_repeat_freq_type'] = REPEAT_EVERY_WEEK; $recurrspec['event_repeat_on_num'] = 0; $recurrspec['event_repeat_on_day'] = 0; $recurrspec['event_repeat_on_freq'] = 0; break; case _EVENT_MONTHLY: if ($rfreq == _RECUR_SAME_DATE) { $recurrtype = REPEAT; $recurrspec['event_repeat_freq'] = REPEAT_EVERY; $recurrspec['event_repeat_freq_type'] = REPEAT_EVERY_MONTH; $recurrspec['event_repeat_on_num'] = 0; $recurrspec['event_repeat_on_day'] = 0; $recurrspec['event_repeat_on_freq'] = 0; } elseif ($rfreq == _RECUR_SAME_DAY) { $recurrtype = REPEAT_ON; list($y, $m, $d) = explode('-', $eventdate); $recurrspec['event_repeat_freq'] = 0; $recurrspec['event_repeat_freq_type'] = 0; // event day of week $edow = Date_Calc::dayOfWeek($d, $m, $y); // date of first event day of week $firstDay = Date_Calc::NWeekdayOfMonth(1, $edow, $m, $y, '%Y-%m-%d'); // find difference between 1st day and event day list($y2, $m2, $d2) = explode('-', $firstDay); $diff = Date_Calc::dateDiff($d, $m, $y, $d2, $m2, $y2); // assuming $diff is going to be a multiple of 7 if ($diff > 0) { $diff /= 7; } if ($diff > REPEAT_ON_4TH) { $diff = REPEAT_ON_LAST; } $recurrspec['event_repeat_on_num'] = $diff; $recurrspec['event_repeat_on_day'] = $edow; $recurrspec['event_repeat_on_freq'] = REPEAT_ON_MONTH; } break; case _EVENT_YEARLY: if ($rfreq == _RECUR_SAME_DATE) { $recurrtype = REPEAT; $recurrspec['event_repeat_freq'] = REPEAT_EVERY; $recurrspec['event_repeat_freq_type'] = REPEAT_EVERY_YEAR; $recurrspec['event_repeat_on_num'] = 0; $recurrspec['event_repeat_on_day'] = 0; $recurrspec['event_repeat_on_freq'] = 0; } elseif ($rfreq == _RECUR_SAME_DAY) { $recurrtype = REPEAT_ON; list($y, $m, $d) = explode('-', $eventdate); $recurrspec['event_repeat_freq'] = 0; $recurrspec['event_repeat_freq_type'] = 0; // event day of week $edow = Date_Calc::dayOfWeek($d, $m, $y); // date of first event day of week $firstDay = Date_Calc::NWeekdayOfMonth(1, $edow, $m, $y, '%Y-%m-%d'); // find difference between 1st day and event day list($y2, $m2, $d2) = explode('-', $firstDay); $diff = Date_Calc::dateDiff($d, $m, $y, $d2, $m2, $y2); // assuming $diff is going to be a multiple of 7 if ($diff > 0) { $diff /= 7; } if ($diff > REPEAT_ON_4TH) { $diff = REPEAT_ON_LAST; } $recurrspec['event_repeat_on_num'] = $diff; $recurrspec['event_repeat_on_day'] = $edow; $recurrspec['event_repeat_on_freq'] = REPEAT_ON_YEAR; } break; } // ok, figure out the event's duration list($sh, $sm, $ss) = explode(':', $start); list($eh, $em, $es) = explode(':', $end); $stime = mktime($sh, $sm, $ss, 1, 1, 1970); // if the ending hour is less than the starting hour // assume that the event spans to the next day if ($eh < $sh) { $etime = mktime($eh, $em, $es, 1, 2, 1970); } else { $etime = mktime($eh, $em, $es, 1, 1, 1970); } $duration = $etime - $stime; // prep the vars for the sql statement $eid = pnVarPrepForStore($eid); $recurrtype = pnVarPrepForStore($recurrtype); $recurrspec = pnVarPrepForStore(serialize($recurrspec)); // create our sql statement $updatesql = "UPDATE {$events_table} SET \n pc_aid = '0',\n\t\t\t\t\t\t\t pc_recurrtype = {$recurrtype},\n pc_recurrspec = '{$recurrspec}',\n pc_duration = {$duration},\n\t\t\t\t\t\t\t pc_sharing = " . SHARING_GLOBAL . "\n WHERE pc_eid = {$eid}"; // execute our sql statement $dbconn->Execute($updatesql); if ($dbconn->ErrorNo() != 0) { die($dbconn->ErrorMsg()); return false; } // next event please } // all done, proceed with next upgrade step if available/necessary return postcalendar_upgrade('3.1'); break; case '3.1': case '3.1.1': case '3.1.2': case '3.1.3': case '3.1.4': return postcalendar_upgrade('3.9.0'); break; case '3.9.0': case '3.9.1': case '3.9.2': // ading pcSafeMode pnModSetVar(__POSTCALENDAR__, 'pcSafeMode', '0'); return postcalendar_upgrade('3.9.3'); break; case '3.9.3': case '3.9.3.1': // adding indexes $sql = "ALTER TABLE {$events_table} \n\t\t\t\t\tADD INDEX basic_event (pc_catid,pc_aid,pc_eventDate,pc_endDate,pc_eventstatus,pc_sharing,pc_topic)"; $dbconn->Execute($sql); if ($dbconn->ErrorNo() != 0) { die($dbconn->ErrorMsg()); return false; } // adding indexes $sql = "ALTER TABLE {$cat_table} \n\t\t\t\t\tADD INDEX basic_cat (pc_catname, pc_catcolor)"; $dbconn->Execute($sql); if ($dbconn->ErrorNo() != 0) { die($dbconn->ErrorMsg()); return false; } return postcalendar_upgrade('3.9.4'); break; case '3.9.4': case '3.9.5': case '3.9.6': case '3.9.7': return postcalendar_upgrade('3.9.8'); break; case '3.9.8': pnModDelVar(__POSTCALENDAR__, 'pcSafeMode'); pnModSetVar(__POSTCALENDAR__, 'pcNotifyAdmin', '0'); pnModSetVar(__POSTCALENDAR__, 'pcNotifyEmail', pnConfigGetVar('adminmail')); break; case '3.9.9': break; } // if we get this far - load the userapi and clear the cache if (!pnModAPILoad(__POSTCALENDAR__, 'user')) { return false; } $tpl =& new pcSmarty(); $tpl->clear_all_cache(); $tpl->clear_compiled_tpl(); return true; }