static function getTimeOptions($date = '0000-00-00 00:00:00') { // Get time (not including the final secons) $time = substr($date, 11, 5); $html = ''; $config = new JXConfig(); $tz = $config->getTimezone() != '' ? $config->getTimezone() : JText::_('JXLIB_DEFAULT_TIMEZONE'); $tz = new DateTimeZone($tz); /* create a date for every hour */ for ($i = 0; $i < 24; $i++) { $newDate = new JDate(mktime($i, 0, 0, 7, 1, 2000), $tz); $newDate->format(JText::_('H:i'), false); /* if the selected is in hours */ $selected = $time == $newDate->format(JText::_('H:i'), true) ? 'selected="selected"' : ''; /* add the options */ $html .= '<option ' . $selected . 'value="' . $newDate->format(JText::_('H:i'), true) . '" >' . $newDate->format(JText::_('JXLIB_TIME_SHORT_FORMAT'), true) . '</option>'; /* and modify for 30 mins between these hours */ $newDate->modify('+30 minute'); /* check again to see if its in 30 mins interval */ $selected = $time == $newDate->format(JText::_('H:i'), true) ? 'selected="selected"' : ''; /* add the options */ $html .= '<option ' . $selected . 'value="' . $newDate->format(JText::_('H:i'), true) . '" >' . $newDate->format(JText::_('JXLIB_TIME_SHORT_FORMAT'), true) . '</option>'; } return $html; }
/** * This method should handle any login logic and report back to the subject * * @param array $options Array holding options (remember, return, entry_url, action, user, responseType) * * @return boolean True on success */ public function onUserAfterLogin($options) { if (!$this->app->isAdmin() or !JComponentHelper::isEnabled("com_identityproof")) { return true; } // Get the number of days after the system have to remove records. $days = $this->params->get("days", 14); if (!empty($days)) { $today = new JDate(); $today->modify("- " . (int) $days . " days"); $date = $today->format("Y-m-d"); $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select("a.filename")->from($db->quoteName("#__identityproof_files", "a"))->where("a.record_date <= " . $db->quote($date)); $db->setQuery($query); $results = $db->loadColumn(); if (!empty($results)) { $params = JComponentHelper::getParams("com_identityproof"); /** @var $params Joomla\Registry\Registry */ // Remove old key files jimport("joomla.filesystem.file"); foreach ($results as $filename) { $file = JPath::clean($params->get("files_path") . DIRECTORY_SEPARATOR . $filename); if (JFile::exists($file)) { JFile::delete($file); } } // Remove old records. $query = $db->getQuery(true); $query->delete($db->quoteName("#__identityproof_files"))->where($db->quoteName("record_date") . " <= " . $db->quote($date)); $db->setQuery($query); $db->execute(); } } return true; }
/** * Return standardized formatted date * NOTE: FOR TEMPLATE DISPLAY PURPOSE ONLY!!! DO NOT USE FOR DB QUERIES * Also use only for server generated time, NOT */ static function formatDate($date, $long = self::LONG_DATE_FORMAT, $user = null) { // return original input date that cannot be processed if (strtotime($date) === false) { return $date; } $config = new JXConfig(); // First load account setting (if any) timezone to override timezone in language file $defaultTz = $config->getTimezone() != '' ? $config->getTimezone() : JText::_('JXLIB_DEFAULT_TIMEZONE'); $my = !$user instanceof JUser && !$user instanceof JXUser ? JXFactory::getUser() : $user; $timeZoneStr = $my->getParam('timezone'); // Second load user personalize timezone (if any) to override system default timezone $timeZoneStr = empty($timeZoneStr) ? $defaultTz : $timeZoneStr; $tz = new DateTimeZone($timeZoneStr); if ($date instanceof JDate) { $date = $date->format('Y-m-d h:i:s'); } $datenow = new JDate('now', $tz); $offset = $datenow->getOffset() / 3600; $date = new JDate($date); $date->setOffset($offset); $dateStr = $long == self::LONG_DATE_FORMAT ? $date->format(JText::_('JXLIB_DATE_FORMAT'), true) : $date->format(JText::_('JXLIB_DATE_SHORT_FORMAT'), true); if ($long == self::LONG_DATE_FORMAT) { // Test for today $dmy = $datenow->format(JText::_('JXLIB_DATE_DMY'), true); $dateStr = str_replace($dmy, JText::_('JXLIB_DATE_TODAY'), $dateStr); // Test for yesterday $datenow->modify('-1 day'); $dmy = $datenow->format(JText::_('JXLIB_DATE_DMY'), true); $dateStr = str_replace($dmy, JText::_('JXLIB_DATE_YESTERDAY'), $dateStr); } return $dateStr; }
<!-- Pagina di riassunto delle recensioni --> <?php /* recupero i dati dell'ordine se viene passato*/ $showForm = true; $name = $user->name; $email = $user->email; $ratingError = 0; $merchantId = $this->item->MerchantId; $jdate = new JDate('now'); // 3:20 PM, December 1st, 2012 $endjdate = new JDate('now -1 year'); // 3:20 PM, December 1st, 2012 $listDateArray = array(); while ($jdate > $endjdate) { $listDateArray[$jdate->format('Ym01')] = $jdate->toFormat('%B %Y'); $jdate->modify('-1 month'); } $selectdate = true; if (!empty($hashorder)) { // controllo se ho un ordine $orderid = BFCHelper::decrypt($hashorder); // controllo se è un ordine numerico if (is_numeric($orderid)) { // controllo se esiste già una recensione per quell'ordine altrimenti no la faccio vedere $ratingCount = BFCHelper::getTotalRatingsByOrderId($orderid); if ($ratingCount > 0) { //ordine con già una recensione $ratingError = 2; $showForm = false; } else { $order = BFCHelper::getSingleOrderFromService($orderid);
$checkin = new JDate($pars['checkin']->format('Y-m-d')); } if (!empty($pars['checkout'])) { $checkout = new JDate($pars['checkout']->format('Y-m-d')); } if (!empty($pars['paxes'])) { $paxes = $pars['paxes']; } if (!empty($pars['merchantCategoryId'])) { $merchantCategoryId = $pars['merchantCategoryId']; } if (!empty($pars['paxages'])) { $paxages = $pars['paxages']; } if ($pars['checkout'] == null) { $checkout->modify($checkoutspan); } } $allStaysToView = array(); $allstaysuggested = array(); //used in form to get all data function pushStay($arr, $resourceid, $resStay, $defaultResource = null, &$staysuggesteds) { $selected = array_values(array_filter($arr, function ($itm) use($resourceid) { return $itm->ResourceId == $resourceid; })); $index = 0; if (count($selected) == 0) { $obj = new stdClass(); $obj->ResourceId = $resourceid; if (isset($defaultResource) && $defaultResource->ResourceId == $resourceid) {
/** * Save stream */ public function save() { // Store stream $message_id = JRequest::getInt('message_id'); $streamModel = StreamFactory::getModel('stream'); $stream = JTable::getInstance('Stream', 'StreamTable'); $stream->load($message_id); $my = JXFactory::getUser(); if (!$my->authorise('stream.message.edit', $stream)) { exit; } /* update the activity records */ $activity = new StreamActivity(); $activity->update($my->id, $stream->type); // Update attachement there might be addition and removals $oldFiles = $stream->getFiles(); $oldMilestone = isset($stream->getData()->milestone) ? $stream->getData()->milestone : null; $stream->bind(JRequest::get('POST', JREQUEST_ALLOWRAW)); // Checking on invalid data type if (JRequest::getVar('type') == 'event') { /* this rarely happen but will do if somehow javascript validation is skipped */ $eventModel = StreamFactory::getModel('events'); $fallbackEventDuration = $eventModel->determinedEventDuration(JRequest::getVar('start_date'), JRequest::getVar('end_date')); $stream->start_date = strpos(JRequest::getVar('start_date'), '0000-00-00 00:00') === false ? JRequest::getVar('start_date') : $fallbackEventDuration['startDate']->format('Y-m-d h:i'); $stream->end_date = strpos(JRequest::getVar('end_date'), '0000-00-00 00:00') === false ? JRequest::getVar('end_date') : $fallbackEventDuration['endDate']->format('Y-m-d h:i'); } // edit should re-save the linkable link $stream->setParam('linkable_link', JRequest::getVar('linkable_link')); // Custom filtering $this->_filterVideoURL($stream); $this->_filterSlideShare($stream); // If location is specified, validate them $stream->setParam('loc_valid', 0); if (JRequest::getVar('location')) { jimport('joomla.utilities.map'); if (JMap::validateAddress(JRequest::getVar('location'))) { $stream->setParam('loc_valid', 1); } $stream->setParam('hide_map', JRequest::getVar('hide_map', '0')); } else { $rawData = json_decode($stream->raw); $rawData->location = ""; $stream->raw = json_encode($rawData); $stream->store(); } // When edit the stream message, also need to process the tags $hashtags = StreamMessage::getHashtags($stream->message); $rawData = json_decode($stream->raw); foreach ($hashtags as $tag) { $unsupportedChars = array(','); $tag = str_replace($unsupportedChars, '', $tag); $hashedTag = '#' . trim($tag) . '#'; if (!JXUtility::csvExist($rawData->tags, $hashedTag)) { $tagsTrend = new StreamTag(); $tagsTrend->updateTrending($tag, $stream->group_id, true); $rawData->tags = JXUtility::csvInsert($rawData->tags, $hashedTag); // only update the hit if it is a newly added tag $hashtag = JTable::getInstance('Hashtag', 'StreamTable'); $hashtag->load(array('hashtag' => $tag)); $hashtag->hit(); $hashtag->store(); } } $stream->raw = json_encode($rawData); $pinTill = JRequest::getString('pinned', 0); if ($pinTill) { // Update pin to top status $pinTillDate = new JDate($stream->created); $pinTillDate->modify('+' . $pinTill); $stream->updated = $pinTillDate->toMySQL(); $stream->store(true); } else { // If save is done within 5 mins of last edit, do not update the 'updated' time $now = new JDate(); $updated = new JDate($stream->updated); $timediff = JXDate::timeDifference($updated->toUnix(), $now->toUnix()); $stream->pinned = 0; $stream->store($timediff['days'] == 0 && $timediff['hours'] == 0 && $timediff['minutes'] < STREAM_EDIT_INTERVAL); } // Delete file attachment that are no longer used $newFiles = $stream->getFiles(); $requestFiles = JRequest::getVar('attachment', array()); foreach ($oldFiles as $file) { if (!in_array($file->id, $requestFiles)) { $file->delete(); } } if (JRequest::getVar('group_id')) { $group = JTable::getInstance('Group', 'StreamTable'); $group->load(JRequest::getVar('group_id')); if ($group) { // the parameter need to be updated otherwise stream will be visible when moved to private group $stream->setParam('group_id', $group->id); $stream->access = $group->access; $stream->store(true); // Upgrade group stats if necessary $group->setParam('last_message', $stream->id); $group->setParam('message_count', $streamModel->countStream(array('group_id' => $group->id))); $group->setParam($stream->type . '_count', $streamModel->countStream(array('group_id' => $group->id, 'type' => $stream->type))); $group->store(); } } // For all new attachment, we need to set their owner $fileModel = StreamFactory::getModel('files'); $fileModel->updateOwner($stream); // Update related milestone $this->_updateMilestone($stream, $oldMilestone); $data = array(); $data['html'] = $stream->getHTML(); $data['id'] = $message_id; header('Content-Type: text/json'); echo json_encode($data); exit; }
public static function getData($profile, array $dimensions, array $metrics, JDate $startDate = null, JDate $endDate = null, array $sort = null, $filter = null, $max = 1000, $offset = 1) { if ($startDate == null) { $startDate = new JDate(); $startDate->modify('-1 month'); } if ($endDate == null) { $endDate = new JDate(); $endDate->modify('-1 day'); } if ($endDate < $startDate) { $endDate = $startDate; } $newDimensions = ''; foreach ($dimensions as $dimension) { if (strpos($dimension, 'ga:') === 0) { $newDimensions .= $dimension . ','; } else { $newDimensions .= 'ga:' . $dimension . ','; } } $newDimensions = trim($newDimensions, ','); $newMetrics = ''; foreach ($metrics as $metric) { if (strpos($metric, 'ga:') === 0) { $newMetrics .= $metric . ','; } else { $newMetrics .= 'ga:' . $metric . ','; } } $newMetrics = trim($newMetrics, ','); $newSort = null; if ($sort !== null) { $newSort = implode(',', $sort); } try { if (GAnalyticsHelper::isPROMode()) { $data = GAnalyticsProUtil::getFromCache($profile, $newDimensions, $newMetrics, $startDate, $endDate, $newSort, $filter, $max, $offset); } else { $client = self::getClient(); $client->refreshToken($profile->token); $service = new apiAnalyticsService($client); $options = array('dimensions' => $newDimensions, 'start-index' => $offset, 'max-results' => $max); if (!empty($filter)) { $options['filters'] = $filter; } if (!empty($newSort)) { $options['sort'] = $newSort; } $data = $service->data_ga->get('ga:' . $profile->profileID, $startDate->format('Y-m-d'), $endDate->format('Y-m-d'), $newMetrics, $options); } if ($data != null && $data->getRows() == null) { $data->setRows(array()); } return $data; } catch (Exception $e) { if (!JFactory::getLanguage()->hasKey('COM_GANALYTICS')) { JFactory::getLanguage()->load('com_ganalytics', JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_ganalytics'); } JError::raiseWarning(500, JText::_('COM_GANALYTICS_IMPORT_VIEW_MODEL_FEED_ERROR') . ' ' . $e->getMessage()); return null; } }
protected function specificDate($data, $fromDate, $toDate) { $from = strtotime($fromDate) / 86400; $to = strtotime($toDate) / 86400; // 86400 = (60*60*24)s = 1 day; $range = intval($to - $from); if ($range <= 0) { JFactory::getApplication()->enqueueMessage(JText::_('COM_BOOKPRO_FROM_DATE_GREATER_THAN_TO_DATE'), 'error'); return false; } if ($range > 60) { JFactory::getApplication()->enqueueMessage(JText::_('COM_BOOKPRO_TIME_IS_TOO_LONG'), 'error'); return false; } foreach ($data as $item) { $day = new JDate($item->created); $item->created = $day->format('Y-m-d'); } $dStart = new JDate($fromDate); $dTo = new JDate($toDate); $dTo->modify('+1 day'); $newData = array(); $i = 0; while ($dStart != $dTo) { $newData[$i]['date'] = $dStart->format('Y-m-d'); $newData[$i]['total'] = 0; $i++; $dStart->modify('+1 day'); } foreach ($data as $row) { foreach ($newData as $i => $value) { if ($value['date'] == $row->created) { $newData[$i]['total'] += $row->total; } } } return $newData; }
public function jsonFormat($object, $time = 'week', $label = '') { $count = 0; $now = new JDate(); $arrayData = array(); $dateFormat = 'd/m'; switch ($time) { case 'week': $startDate = new JDate(strtotime('this week', time())); $endDate = new JDate(strtotime('+1 week', strtotime($startDate->format('Y-m-d')))); break; case 'lastweek': $startDate = $now->modify('-1 week'); $endDate = new JDate(strtotime('+1 week', strtotime($startDate->format('Y-m-d')))); break; case 'month': $startDate = $now->modify('first day of this month'); $endDate = new JDate(strtotime('+1 month', strtotime($startDate->format('Y-m-d')))); $dateFormat = 'd'; break; case 'lastmonth': $startDate = $now->modify('first day of last month'); $endDate = new JDate(strtotime('+1 month', strtotime($startDate->format('Y-m-d')))); $dateFormat = 'd'; break; } $interval = $startDate->diff($endDate); $intervalDays = $interval->days + 1; for ($i = 0; $i <= $intervalDays; $i++) { if (count($object)) { foreach ($object as $key => $data) { $date = new JDate($data->created); if ($startDate->format('Y-m-d') === $date->format('Y-m-d') && $data->count > 0) { $arrayData[$i] = '[\'' . $date->format($dateFormat) . '\',' . $data->count . ']'; $count += $data->count; } else { if (empty($arrayData[$i])) { $arrayData[$i] = '[\'' . $startDate->format($dateFormat) . '\',0]'; } } } } else { $arrayData[$i] = '[\'' . $startDate->format($dateFormat) . '\',0]'; } $startDate = $startDate->modify('+1 day'); } $string = '[' . implode(',', $arrayData) . ']'; $obj = new stdClass(); $obj->json = $string; $obj->count = $count; $obj->label = $label; return $obj; }
/** * takes care of the recurrence of events */ static function generate_events($table, $exdates = false, $holidays = false) { # include route require_once JPATH_COMPONENT_SITE . '/helpers/route.php'; $jemsettings = JemHelper::config(); $weekstart = $jemsettings->weekdaystart; $anticipation = $jemsettings->recurrence_anticipation; ##################### ## Reference table ## ##################### # this is the events-table and will be used as base # define variables $id = $table->id; $times = $table->times; $endtimes = $table->endtimes; $dates = $table->dates; $enddates = $table->enddates; $recurrence_count = $table->recurrence_count; $recurrence_freq = $table->recurrence_freq; $recurrence_interval = $table->recurrence_interval; $recurrence_until = $table->recurrence_until; $recurrence_weekday = $table->recurrence_weekday; $recurrence_group = $table->recurrence_group; # select all the data from the event and make an array of it # this info will be used for the generated events. $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('*'); $query->from($db->quoteName('#__jem_events')); $query->where('id = ' . $table->id); $db->setQuery($query); $reference = $db->loadAssoc(); $rruledatetime1 = new DateTime($dates); $rruledatetime2 = new DateTime($recurrence_until); $rruleinterval = $rruledatetime1->diff($rruledatetime2); $rruleDiff = $rruleinterval->format('%a'); if ($anticipation <= $rruleDiff) { $jdate2 = new JDate($dates); $var9 = '+' . $anticipation . ' days'; $anticipationDate = $jdate2->modify($var9); $rruleUntilLimit = $anticipationDate; } else { $rruleUntilLimit = $recurrence_until; } # Check if startdate is before limitdate if (strtotime($dates) <= strtotime($rruleUntilLimit)) { # combine startdate + time if (empty($times)) { $times = '00:00:00'; } $startDateTime = $dates . ' ' . $times; if (empty($enddates)) { $enddates = $dates; } # combine enddate + time if (empty($endtimes)) { $endtimes = '00:00:00'; } $endDateTime = $enddates . ' ' . $endtimes; # Calculate time difference, for enddate $datetime1 = new DateTime($startDateTime); $datetime2 = new DateTime($endDateTime); $interval = $datetime1->diff($datetime2); $diffYear = $interval->format('%y'); $diffMonth = $interval->format('%m'); $diffDay = $interval->format('%d'); $diffHour = $interval->format('%h'); $diffMinutes = $interval->format('%i'); $diffSeconds = $interval->format('%s'); $diffDays = $interval->format('days'); $formatDifference = 'P' . $diffYear . 'Y' . $diffMonth . 'M' . $diffDay . 'DT' . $diffHour . 'H' . $diffMinutes . 'M' . $diffSeconds . 'S'; $jdate1 = new JDate($rruleUntilLimit); $year1 = $jdate1->format('Y'); $month1 = $jdate1->format('m'); $day1 = $jdate1->format('d'); $hour1 = $jdate1->format('H'); $minutes1 = $jdate1->format('i'); $seconds1 = $jdate1->format('s'); $limit_date2 = $year1 . $month1 . $day1 . 'T235959Z'; # Define FREQ switch ($recurrence_freq) { case "1": $freq = 'DAILY'; break; case "2": $freq = 'WEEKLY'; break; case "3": $freq = 'MONTHLY'; break; case "4": $freq = 'YEARLY'; break; default: $freq = ''; } # let's check if the user did select a weekday if ($recurrence_weekday) { $rrule = 'FREQ=' . $freq . ';INTERVAL=' . $recurrence_interval . ';UNTIL=' . $limit_date2 . ';BYDAY=' . $recurrence_weekday; } else { $rrule = 'FREQ=' . $freq . ';INTERVAL=' . $recurrence_interval . ';UNTIL=' . $limit_date2; } # Get new dates $timezone = JemHelper::getTimeZoneName(); $startDate = new DateTime($startDateTime, new DateTimeZone($timezone)); #################### ## RECURR - CLASS ## #################### $rule = new RecurrenceRule($rrule, $startDate, $timezone); $transformer = new RecurrenceRuleTransformer($rule); # here we've the new dates $newEventArray = $transformer->getComputedArray(); # output is like: # # array # - public 'Date' # - public 'timezone_type' # - public 'timezone' ######### ## END ## ######### $newArray = array(); foreach ($newEventArray as $newEvent) { $date = $newEvent->format('Y-m-d'); $enddate = new DateTime($date); $enddate->add(new DateInterval($formatDifference)); $var2 = $enddate->format('Y-m-d'); if ($date != $dates) { $item = array('startDate' => $date, 'endDate' => $var2); $newArray[] = $item; } } $newArray2 = array(); foreach ($newEventArray as $newEvent2) { $date2 = $newEvent2->format('Y-m-d'); $enddate2 = new DateTime($date2); $enddate2->add(new DateInterval($formatDifference)); $var22 = $enddate2->format('Y-m-d'); if ($date2 != $dates) { $newArray2[] = $date2; } } # retrieve first+last startdate of the array $date_first_calculated_occurrence = reset($newArray2); $date_last_calculated_occurrence = end($newArray2); ########################### ## IGNORE DATES: HOLIDAY ## ########################### /* $currenttime = new JDate(); $year = $currenttime->format('Y'); */ if ($holidays) { $currenttime = new JDate(); $year = $currenttime->format('Y'); $format = 'd-m-Y'; $holiday_array = array(); foreach ($holidays as $holiday) { $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('*'); $query->from($db->quoteName('#__jem_dates')); $query->where(array('id = ' . $holiday, 'holiday =' . $db->quote('1'))); $db->setQuery($query); $reference2 = $db->loadAssoc(); if ($reference2['date_startdate_range']) { # If we're dealing with a range we've to calculate things $start_range_input = $reference2['date_startdate_range']; $end_range_input = $reference2['date_enddate_range']; $start_range_parsed = date_parse($start_range_input); $end_range_parsed = date_parse($end_range_input); if (checkdate($start_range_parsed["month"], $start_range_parsed["day"], $start_range_parsed["year"]) && !$start_range_parsed["errors"] && checkdate($end_range_parsed["month"], $end_range_parsed["day"], $end_range_parsed["year"]) && !$end_range_parsed["errors"]) { # at this point we made sure we're dealing with valid start+enddates # now we're making a DateTimeperiod $begin2 = new DateTime($start_range_input); $end2 = new DateTime($end_range_input); $end2 = $end2->modify('+1 day'); $interval2 = new DateInterval('P1D'); $daterange2 = new DatePeriod($begin2, $interval2, $end2); foreach ($daterange2 as $exdate2) { $holiday_array[] = $exdate2->format("Y-m-d"); } } } else { # If we're dealing with a single_date we can use the date supplied $holiday_array[] = $reference2['date']; } } // end foreach # it's possible to have duplicates so we've to make the array Unique $holiday_array = array_unique($holiday_array); } // end holiday-check #################################################### ## IGNORE DATES: FORM FIELD (exdates), NO HOLIDAY ## #################################################### # basically we add all occurrences of the set to the database but the unneeded ones will # get a 1 in the ignore field. Those events will get an exdate in the iCal RRULE output # dates provided in the exdate field if ($exdates) { # remove white space $exdates = preg_replace('/\\s+/', '', $exdates); # put the dates into an array $form_exdates_array = explode(",", $exdates); $form_exdate_output = array(); foreach ($form_exdates_array as $form_exdate) { $form_exdate_splits = explode(":", $form_exdate); $form_exdate_splits2 = array(); foreach ($form_exdate_splits as $ignoredate) { $form_exdate_splits2[] = date("Y-m-d", strtotime($ignoredate)); } foreach ($form_exdate_splits2 as $form_exdate_split) { $date = date_parse($form_exdate_split); if (checkdate($date["month"], $date["day"], $date["year"]) && !$date["errors"]) { # retrieve first+last value of the created array $first_form_exdate = reset($form_exdate_splits2); $last_form_exdate = end($form_exdate_splits2); # now we're making a DateTimeperiod $begin = new DateTime($first_form_exdate); $end = new DateTime($last_form_exdate); $end = $end->modify('+1 day'); $interval = new DateInterval('P1D'); $daterange = new DatePeriod($begin, $interval, $end); foreach ($daterange as $exdate) { $form_exdate_output[] = $exdate->format("Y-m-d"); } } } } # check for duplicates $form_exdate_output = array_unique($form_exdate_output); } // end check exdates ##################################### ## IGNORE-DATES: TABLE, NO HOLIDAY ## ##################################### ## select dates from the date-table, within the calculated range $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('date'); $query->from($db->quoteName('#__jem_dates')); $query->where(array('enabled = 1', 'holiday <> 1', 'date >= ' . $db->Quote($date_first_calculated_occurrence), 'date <= ' . $db->Quote($date_last_calculated_occurrence))); $db->setQuery($query); $dateTable = $db->loadColumn(); if ($dateTable) { $excluded_dates = $dateTable; } else { $excluded_dates = array(); } ########################################### ## IGNORE-DATES: CREATE ARRAY, INTERSECT ## ########################################### ## $newArray2 = generated values // Y-m-d ## $excluded_dates = single-dates from table, no holiday # we will be making an array that contains the values that are present in exluded_dates + generated_dates # this makes sure that the excluded dates are actually in the range of the generating part $exclude_date_array = array_intersect($newArray2, $excluded_dates); # if the exdate form is field we will do a second round if ($exdates) { $exclude_exdate_form = array_intersect($newArray2, $form_exdate_output); } else { $exclude_exdate_form = false; } # If a holiday has been selected we will even do a third round if ($holidays) { $exclude_exdate_holiday = array_intersect($newArray2, $holiday_array); } else { $exclude_exdate_holiday = false; } ###################################### ## IGNORE-DATES: CREATE ARRAY, DIFF ## ###################################### # create array with only the dates we want to have $array_input = $newArray2; $array_to_remove = $exclude_date_array; $array_output = array_diff($array_input, $array_to_remove); if ($exdates && !$holidays) { # exdate field has been filled $array_input_form = $array_output; $array_to_remove_form = $exclude_exdate_form; $generating_array = array_diff($array_input_form, $array_to_remove_form); } if (!$exdates && $holidays) { # holiday field has been filled $array_input_form = $array_output; $array_to_remove_form = $exclude_exdate_holiday; $generating_array = array_diff($array_input_form, $array_to_remove_form); } if ($exdates && $holidays) { # both fields have been filled # in this case we've to merge both arrays and check for duplicates $exdates_holidays_combined = array_merge($exclude_exdate_holiday, $exclude_exdate_form); $exdates_holidays_combined_unique = array_unique($exdates_holidays_combined); $array_input_form = $array_output; $array_to_remove_form = $exdates_holidays_combined_unique; $generating_array = array_diff($array_input_form, $array_to_remove_form); } if (!$exdates && !$holidays) { # no fields have been filled $generating_array = $array_output; } $new_generating_array = array(); foreach ($generating_array as $generated) { $generated_enddate = new DateTime($generated); $generated_enddate->add(new DateInterval($formatDifference)); $var2a = $generated_enddate->format('Y-m-d'); $item2 = array('startDate' => $generated, 'endDate' => $var2a); $new_generating_array[] = $item2; } ############# ## EXDATES ## ############# # do we have an array with dates to ignore? # if yes we need to input the dates as exdate value in the master-table if ($exclude_date_array) { $exdate_date_array = $exclude_date_array; } else { $exdate_date_array = array(); } if ($exclude_exdate_form) { $exdate_exdate_form = $exclude_exdate_form; } else { $exdate_exdate_form = array(); } if ($exclude_exdate_holiday) { $exdate_exdate_holiday = $exclude_exdate_holiday; } else { $exdate_exdate_holiday = array(); } $exdates_input = array_merge($exdate_date_array, $exdate_exdate_form, $exdate_exdate_holiday); $exdates_unique = array_unique($exdates_input); if ($exdates_unique) { $exdates = json_encode($exdates_unique); } else { $exdates = ''; } ####################################################### ## Store the first occurence to the Recurrence table ## ####################################################### $first_event_recurrence = JTable::getInstance('Recurrence', 'JEMTable'); $first_event_recurrence->itemid = $table->id; $first_event_recurrence->groupid = $table->recurrence_group; $first_event_recurrence->groupid_ref = $table->recurrence_group; $first_event_recurrence->interval = $table->recurrence_interval; $first_event_recurrence->freq = $freq; $first_event_recurrence->startdate_org = $startDateTime; $first_event_recurrence->enddate_org = $endDateTime; $first_event_recurrence->wholeday = $table->wholeday; $var2 = $first_event_recurrence->startdate_org; $var3 = new JDate($var2); $var4 = $var3->format('Ymd\\THis\\Z'); $first_event_recurrence->recurrence_id = $var4; $first_event_recurrence->store(); ############################################################## ## Store the first occurence to the Recurrence-Master table ## ############################################################## # define link $master_link = JRoute::_(JURI::root() . JemHelperRoute::getEventRoute($table->id . ':' . $table->alias)); # Retrieve venue + countryname $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('l.venue, l.city, l.state, l.url, l.street,ct.name AS countryname'); $query->from($db->quoteName('#__jem_events', 'a')); $query->join('LEFT', '#__jem_venues AS l ON l.id = a.locid'); $query->join('LEFT', '#__jem_countries AS ct ON ct.iso2 = l.country'); $query->join('LEFT', '#__jem_cats_event_relations AS rel ON rel.itemid = a.id'); $query->join('LEFT', '#__jem_categories AS c ON c.id = rel.catid'); $query->where(array('a.id =' . $table->id)); $db->setQuery($query); $event_venuecountry = $db->loadObject(); # define location array $location = array(); if (isset($event_venuecountry->venue) && !empty($event_venuecountry->venue)) { $location[] = $event_venuecountry->venue; } if (isset($event_venuecountry->city) && !empty($event_venuecountry->city)) { $location[] = $event_venuecountry->city; } if (isset($event_venuecountry->state) && !empty($event_venuecountry->state)) { $location[] = $event_venuecountry->state; } if (isset($event_venuecountry->url) && !empty($event_venuecountry->url)) { $location[] = $event_venuecountry->url; } if (isset($event_venuecountry->street) && !empty($event_venuecountry->street)) { $location[] = $event_venuecountry->street; } if (isset($event_venuecountry->countryname) && !empty($event_venuecountry->countryname)) { $exp = explode(",", $event_venuecountry->countryname); $location[] = $exp[0]; } $location = implode(",", $location); # retrieve categories $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('c.id,c.catname'); $query->from($db->quoteName('#__jem_events', 'a')); $query->join('LEFT', '#__jem_venues AS l ON l.id = a.locid'); $query->join('LEFT', '#__jem_countries AS ct ON ct.iso2 = l.country'); $query->join('LEFT', '#__jem_cats_event_relations AS rel ON rel.itemid = a.id'); $query->join('LEFT', '#__jem_categories AS c ON c.id = rel.catid'); $query->where(array('a.id =' . $table->id)); $db->setQuery($query); $event_categories = $db->loadObjectList(); # create array with category id's $categories = array(); foreach ($event_categories as $c) { $categories[] = $c->id; } # define fields $rec_master = JTable::getInstance('Recurrence_master', 'JEMTable'); $rec_master->itemid = $table->id; $rec_master->groupid = $table->recurrence_group; $rec_master->groupid_ref = $table->recurrence_group; $rec_master->interval = $table->recurrence_interval; $rec_master->freq = $freq; $rec_master->startdate_org = $startDateTime; $rec_master->enddate_org = $endDateTime; $rec_master->exdates = $exdates; $rec_master->store(); ####################################### ## Bind & Store the generated values ## ####################################### foreach ($new_generating_array as $value) { # load tables $new_event = JTable::getInstance('Events', 'JEMTable'); $new_event_recurrence = JTable::getInstance('Recurrence', 'JEMTable'); # bind reference-values + strip out individual fields $new_event->bind($reference, array('id', 'hits', 'dates', 'enddates', 'checked_out_time', 'checked_out')); # define new startdate + enddate $new_event->dates = $value['startDate']; $new_event->enddates = $value['endDate']; # define ical settings $new_event->recurrence_until = $rruleUntilLimit; $new_event->recurrence_count = $recurrence_count; $new_event->recurrence_interval = $recurrence_interval; $new_event->recurrence_freq = $freq; if ($recurrence_weekday) { $new_event->recurrence_weekday = $recurrence_weekday; } # store event if ($new_event->store()) { # combine startdate+time if (empty($new_event->times)) { $new_event->times = '00:00:00'; } $newevent_startDateTime = $new_event->dates . ' ' . $new_event->times; if (empty($new_event->enddates)) { $new_event->enddates = $new_event->dates; } # combine enddate + time if (empty($new_event->endtimes)) { $new_event->endtimes = '00:00:00'; } $newevent_endDateTime = $new_event->enddates . ' ' . $new_event->endtimes; # store generated event-info into recurrence_table $new_event_recurrence->itemid = $new_event->id; $new_event_recurrence->groupid = $recurrence_group; $new_event_recurrence->groupid_ref = $recurrence_group; $new_event_recurrence->interval = $recurrence_interval; $new_event_recurrence->startdate_org = $newevent_startDateTime; $new_event_recurrence->enddate_org = $newevent_endDateTime; $new_event_recurrence->freq = $freq; $new_event_recurrence->wholeday = $new_event->wholeday; $var5 = $new_event_recurrence->startdate_org; $var6 = new JDate($var5); $var7 = $var3->format('Ymd\\THis\\Z'); $new_event_recurrence->recurrence_id = $var7; $new_event_recurrence->store(); $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select(array('catid')); $query->from($db->quoteName('#__jem_cats_event_relations')); $query->where('itemid = ' . $table->id); $db->setQuery($query); $cats = $db->loadColumn(0); foreach ($cats as $cat) { $db = JFactory::getDbo(); $query = $db->getQuery(true); // Insert columns. $columns = array('catid', 'itemid'); // Insert values. $values = array($cat, $new_event->id); // Prepare the insert query. $query->insert($db->quoteName('#__jem_cats_event_relations'))->columns($db->quoteName($columns))->values(implode(',', $values)); // Reset the query using our newly populated query object. $db->setQuery($query); $db->execute(); } } } } // end adding new Events }
/** * Process payment transaction. * * @param string $context * @param object $item * @param Joomla\Registry\Registry $params * * @return null|array */ public function onPaymentsCheckout($context, &$item, &$params) { if (strcmp("com_crowdfunding.payments.checkout.paypal", $context) != 0) { return null; } if ($this->app->isAdmin()) { return null; } $doc = JFactory::getDocument(); /** @var $doc JDocumentHtml */ // Check document type $docType = $doc->getType(); if (strcmp("html", $docType) != 0) { return null; } $output = array(); $notifyUrl = $this->getCallbackUrl(); $cancelUrl = $this->getCancelUrl($item->slug, $item->catslug); $returnUrl = $this->getReturnUrl($item->slug, $item->catslug); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_NOTIFY_URL"), $this->debugType, $notifyUrl) : null; JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_RETURN_URL"), $this->debugType, $returnUrl) : null; JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_CANCEL_URL"), $this->debugType, $cancelUrl) : null; // Get country and locale code. $countryId = $this->params->get("paypal_country"); $country = new Crowdfunding\Country(JFactory::getDbo()); $country->load($countryId); // Create transport object. $options = new Joomla\Registry\Registry(); /** @var $options Joomla\Registry\Registry */ $transport = new JHttpTransportCurl($options); $http = new JHttp($options, $transport); // Create payment object. $options = new Joomla\Registry\Registry(); /** @var $options Joomla\Registry\Registry */ $options->set("urls.cancel", $cancelUrl); $options->set("urls.return", $returnUrl); $options->set("urls.notify", $notifyUrl); $this->prepareCredentials($options); // Get server IP address. /*$serverIP = $this->app->input->server->get("SERVER_ADDR"); $options->set("credentials.ip_address", $serverIP);*/ // Prepare starting and ending date. if (!$this->params->get("paypal_starting_date", 0)) { // End date of the campaign. $startingDate = new JDate(); // Today $startingDate->setTime(0, 0, 0); // At 00:00:00 } else { $startingDate = new JDate($item->ending_date); $startingDate->modify("+1 day"); $startingDate->setTime(0, 0, 0); // At 00:00:00 } $endingDate = new JDate($item->ending_date); $endingDate->modify("+10 days"); $options->set("payment.starting_date", $startingDate->format(DATE_ATOM)); $options->set("payment.ending_date", $endingDate->format(DATE_ATOM)); $options->set("payment.max_amount", $item->amount); $options->set("payment.max_total_amount", $item->amount); $options->set("payment.number_of_payments", 1); $options->set("payment.currency_code", $item->currencyCode); $options->set("payment.fees_payer", $this->params->get("paypal_fees_payer")); $options->set("payment.ping_type", "NOT_REQUIRED"); $title = JText::sprintf($this->textPrefix . "_INVESTING_IN_S", htmlentities($item->title, ENT_QUOTES, "UTF-8")); $options->set("payment.memo", $title); $options->set("request.envelope", $this->envelope); // Get payment session. $paymentSessionContext = Crowdfunding\Constants::PAYMENT_SESSION_CONTEXT . $item->id; $paymentSessionLocal = $this->app->getUserState($paymentSessionContext); $paymentSession = $this->getPaymentSession(array("session_id" => $paymentSessionLocal->session_id)); // Get API url. $apiUrl = $this->getApiUrl(); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_PAYPAL_ADAPTIVE_OPTIONS"), $this->debugType, $options->toArray()) : null; $adaptive = new Prism\Payment\PayPal\Adaptive($apiUrl, $options); $adaptive->setTransport($http); $response = $adaptive->doPreppproval(); // DEBUG DATA JDEBUG ? $this->log->add(JText::_($this->textPrefix . "_DEBUG_PAYPAL_ADAPTIVE_RESPONSE"), $this->debugType, $response) : null; $preapprovalKey = $response->getPreApprovalKey(); if (!$preapprovalKey) { return null; } // Store token to the payment session. $paymentSession->setUniqueKey($preapprovalKey); $paymentSession->storeUniqueKey(); // Get paypal checkout URL. if (!$this->params->get('paypal_sandbox', 1)) { $output["redirect_url"] = $this->params->get("paypal_url") . "?cmd=_ap-preapproval&preapprovalkey=" . rawurlencode($preapprovalKey); } else { $output["redirect_url"] = $this->params->get("paypal_sandbox_url") . "?cmd=_ap-preapproval&preapprovalkey=" . rawurlencode($preapprovalKey); } return $output; }