本文整理汇总了PHP中Datetime::diff方法的典型用法代码示例。如果您正苦于以下问题:PHP Datetime::diff方法的具体用法?PHP Datetime::diff怎么用?PHP Datetime::diff使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Datetime
的用法示例。
在下文中一共展示了Datetime::diff方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: audienceAccueilAction
public function audienceAccueilAction()
{
$em = $this->getDoctrine()->getManager();
$rep = $em->getRepository('APPCoreBundle:Abonne');
$inscr = $rep->findBy(array('softDelete' => 0), array(), null, null);
$nbInscr = count($inscr);
$desinscr = $rep->findBy(array('softDelete' => 1), array(), null, null);
$nbDesinscr = count($desinscr);
$generalite = $this->general();
/*analytics*/
$rep2 = $em->getRepository('APPAdminBundle:Visite');
/*graphique 1*/
$jour = new \datetime();
$fix = new \Datetime();
$date = $jour->format('D');
$jour2 = $jour->modify('-1 day');
$date2 = $jour2->format('D');
$jour3 = $jour->modify('-1 days');
$date3 = $jour3->format('D');
$jour4 = $jour->modify('-1 days');
$date4 = $jour4->format('D');
$jour5 = $jour->modify('-1 days');
$date5 = $jour5->format('D');
$jour6 = $jour->modify('-1 days');
$date6 = $jour6->format('D');
$jour7 = $jour->modify('-1 days');
$date7 = $jour7->format('D');
$joursDeLaSemaine = array('Mon' => 'Lun', 'Tue' => 'Mar', 'Wed' => 'Mer', 'Thu' => 'Jeu', 'Fri' => 'Ven', 'Sat' => 'Sam', 'Sun' => 'Dim');
$chiffres = array(array('new' => 0, 'ret' => 0), array('new' => 0, 'ret' => 0), array('new' => 0, 'ret' => 0), array('new' => 0, 'ret' => 0), array('new' => 0, 'ret' => 0), array('new' => 0, 'ret' => 0), array('new' => 0, 'ret' => 0));
$visites = $rep2->findAll();
$totalSemaine = 0;
$totalVisitesSemaine = 0;
foreach ($visites as $analytics) {
$newDate = new \datetime($analytics->getDateAjout()->format('Y-m-d'));
$newFix = $newDate->format('Y-m-d');
$diff = $fix->diff($newDate);
$count = $diff->format('%D');
//die((int)$count.' = '.$fix->format('Y-m-d').' et '.$newDate->format('Y-m-d'));
$nb = (int) $count;
if ($nb >= 0 && $nb <= 6) {
$compte = count($rep2->findByIp($analytics->getIp()));
if ($compte == 1) {
$totalVisitesSemaine += 1;
$chiffres[$nb]['new'] += 1;
} else {
$totalVisitesSemaine += 1;
if ($analytics->getNewSession() == 1) {
$totalSemaine += 1;
$chiffres[$nb]['ret'] += 1;
}
}
}
}
$series = array(array("name" => "Nouveau visiteur", "data" => array($chiffres[6]['new'], $chiffres[5]['new'], $chiffres[4]['new'], $chiffres[3]['new'], $chiffres[2]['new'], $chiffres[1]['new'], $chiffres[0]['new'])), array("name" => "Visiteur revenant", "data" => array($chiffres[6]['ret'], $chiffres[5]['ret'], $chiffres[4]['ret'], $chiffres[3]['ret'], $chiffres[2]['ret'], $chiffres[1]['ret'], $chiffres[0]['ret'])));
$categories = array($joursDeLaSemaine[$date7], $joursDeLaSemaine[$date6], $joursDeLaSemaine[$date5], $joursDeLaSemaine[$date4], $joursDeLaSemaine[$date3], $joursDeLaSemaine[$date2], $joursDeLaSemaine[$date]);
$ob = new Highchart();
$ob->chart->renderTo('linechart');
// The #id of the div where to render the chart
$ob->title->text('Visites des 7 derniers jours');
$ob->xAxis->categories($categories);
$ob->xAxis->title(array('text' => "Jours"));
$ob->yAxis->title(array('text' => "Visites"));
$ob->series($series);
/*graphique 2*/
$date = new \datetime();
$mois = $date->format('m');
$annee = $date->format('y');
$jour = $date->format('d');
$visitesan = $rep2->findBy(array(), array('dateAjout' => 'desc'), null, null);
$cpt = 1;
$cptMois = $mois;
$cptAnnee = $annee;
$cptJour = $jour;
$moisArray = array('Jan', 'Fev', 'Mar', 'Avr', 'Mai', 'Jui', 'Jul', 'Aou', 'Sep', 'Oct', 'Nov', 'Dec');
$params = array();
while ($cpt <= 12) {
$params[$cpt - 1] = array('mois' => $moisArray[$mois - 1], 'moz' => 0, 'chr' => 0, 'div' => 0);
if ($mois + 1 == 13) {
$mois = 1;
} else {
$mois++;
}
$cpt++;
}
$totalAnnee = 0;
$totalVisitesAnnee = 0;
foreach ($visitesan as $analytics) {
$newDate = $analytics->getDateAjout();
$newMois = $newDate->format('m');
$newAnnee = $newDate->format('y');
if ($cptAnnee - $newAnnee <= 1) {
$offset = $newMois - $cptMois;
if ($offset < 0) {
$offset = 12 + $offset;
}
$preSplit = explode("0)", $analytics->getNavigateur());
if (!empty($preSplit[1])) {
$morceaux = explode("/", $preSplit[1]);
if ($morceaux[0] == ' Gecko') {
$totalVisitesAnnee += 1;
//.........这里部分代码省略.........
示例2: prepareProgressBarInformations
private function prepareProgressBarInformations(\Datetime $startingDate, \Datetime $endingDate)
{
$progressBar = [];
$now = new \DateTime();
// Between the beginning and the end of the event
$totalIterval = $startingDate->diff($endingDate);
// Between the beginning and now
$alreadyDone = $startingDate->diff($now);
$progressBar['total_interval'] = $totalIterval->invert ? -1 * $totalIterval->format('%a') : $totalIterval->format('%a');
$progressBar['already_done'] = $alreadyDone->invert ? -1 * $alreadyDone->format('%a') : $alreadyDone->format('%a');
$progressBar['current_interval'] = $progressBar['total_interval'] - $progressBar['already_done'];
return $progressBar;
}
示例3: initialize
public function initialize(Controller $controller)
{
$this->controller =& $controller;
if ($this->controller->name != 'Patcher') {
$this->SettingModel = new Setting();
$Mushstats = $this->SettingModel->getOption('Mushstats');
$lastUpdate = new Datetime();
$lastUpdate->setTimestamp($Mushstats);
if ($lastUpdate->diff(new Datetime())->d > 6) {
$this->sendStats();
$this->SettingModel->setOption('Mushstats', time());
}
}
}
示例4: getInactiveTime
public function getInactiveTime($input)
{
$now = new Datetime($this->getCurrentTime());
$last = new Datetime($input);
$result = $last->diff($now);
$years = $result->y;
$months = $result->m;
$days = $result->d;
$hours = $result->h;
$minutes = $result->i;
$seconds = $result->s;
$result = array($years, $months, $days, $hours, $minutes, $seconds);
// Years = 0 - Months = 1 - Days = 2 - Hours = 3 - Minutes = 4 - Seconds = 5
return $result;
}
示例5: date
<?php
// Load Wordpress core
require_once __DIR__ . "/../../../../../wp-load.php";
// Set system params
date_default_timezone_set(get_option("timezone_string"));
// Set params
$classes = \Vividcrestrealestate\Core\Libs\Rets::getPossibleClasses();
// Init Lib
$Exchange = new \Vividcrestrealestate\Core\Administration\Exchange();
// Fetch properties for all classes if it necessary
$current_date = new \Datetime();
foreach ($classes as $class) {
$last_fetch_date = new \Datetime(get_option("rets_exchange_last_fetch_date_{$class}", "2000-01-01"));
$interval = $current_date->diff($last_fetch_date);
if ($interval->format("%d") > 0) {
$Exchange->fetchRawData($class);
} else {
echo date("Y-m-d H:i:s") . " | There is no properties to fetch for class \"{$class}\": Last Fetch Date: " . $last_fetch_date->format("Y-m-d H:i:s") . "; Interval: " . $interval->format("%d") . " days" . PHP_EOL;
}
}
// Process properties
$Exchange->processData(200);
// Get the messages
$messages = array_merge((array) $Exchange->getPositiveMessages(), (array) $Exchange->getNegativeMessages());
// Show messages
echo date("Y-m-d H:i:s") . " | " . implode(PHP_EOL . date("Y-m-d H:i:s") . " | ", $messages) . PHP_EOL;
示例6: Datetime
if ($row["status"] == "sold") {
echo "Mark Unsold";
} else {
echo "Mark Sold";
}
?>
</button><div></div></td>
<td class="renew"><span class="active<?php
if ($row["status"] != "unsold") {
echo " hidden";
}
?>
"><?php
$renew = new Datetime($row["renew"]);
echo $renew->format("F j, Y");
if ($renew->diff(new DateTime())->days <= 30 || $renew < $startTime) {
echo '<br><button type="button" name="renew">Renew</button><div></div>';
}
?>
</span><span class="inactive<?php
if ($row["status"] == "unsold") {
echo " hidden";
}
?>
">Already Sold</span></td>
<td class="title"><?php
echo $row['title'];
?>
</td>
<td class="author"><?php
echo $row["author"];
示例7: checkPermalink
protected function checkPermalink($permalink, \media_subdef $subdef)
{
if (!$subdef->is_physically_present()) {
return;
}
$start = microtime(true);
$this->assertNotNull($subdef->get_permalink());
$this->assertInternalType('array', $permalink);
$this->assertArrayHasKey("created_on", $permalink);
$now = new \Datetime($permalink['created_on']);
$interval = $now->diff($subdef->get_permalink()->get_created_on());
$this->assertTrue(abs($interval->format('U')) < 2);
$this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $permalink['created_on']);
$this->assertDateAtom($permalink['created_on']);
$this->assertArrayHasKey("id", $permalink);
$this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_INT, $permalink['id']);
$this->assertEquals($subdef->get_permalink()->get_id(), $permalink['id']);
$this->assertArrayHasKey("is_activated", $permalink);
$this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_BOOL, $permalink['is_activated']);
$this->assertEquals($subdef->get_permalink()->get_is_activated(), $permalink['is_activated']);
$this->assertArrayHasKey("label", $permalink);
$this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $permalink['label']);
$this->assertArrayHasKey("updated_on", $permalink);
$expected = $subdef->get_permalink()->get_last_modified();
$found = \DateTime::createFromFormat(DATE_ATOM, $permalink['updated_on']);
$this->assertLessThanOrEqual(1, $expected->diff($found)->format('U'));
$this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $permalink['updated_on']);
$this->assertDateAtom($permalink['updated_on']);
$this->assertArrayHasKey("page_url", $permalink);
$this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $permalink['page_url']);
$this->assertEquals($subdef->get_permalink()->get_page(), $permalink['page_url']);
$this->checkUrlCode200($permalink['page_url']);
$this->assertPermalinkHeaders($permalink['page_url'], $subdef);
$this->assertArrayHasKey("url", $permalink);
$this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $permalink['url']);
$this->assertEquals($subdef->get_permalink()->get_url(), $permalink['url']);
$this->checkUrlCode200($permalink['url']);
$this->assertPermalinkHeaders($permalink['url'], $subdef, "url");
$this->assertArrayHasKey("download_url", $permalink);
$this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $permalink['download_url']);
$this->assertEquals($subdef->get_permalink()->get_url() . '&download=1', $permalink['download_url']);
$this->checkUrlCode200($permalink['download_url']);
$this->assertPermalinkHeaders($permalink['download_url'], $subdef, "download_url");
}
示例8: evaluate
//.........这里部分代码省略.........
$this->fmt->endContain('interface');
}
if (function_exists($subject)) {
$this->fmt->startContain('function', true);
$this->fromReflector(new \ReflectionFunction($subject));
$this->fmt->endContain('function');
}
}
// skip serialization/json/date checks if the string appears to be numeric,
// or if it's shorter than 5 characters
if (!$isNumeric && $length > 4) {
// url
if (static::$config['showUrls'] && static::$env['curlActive'] && filter_var($subject, FILTER_VALIDATE_URL)) {
$ch = curl_init($subject);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$nfo = curl_getinfo($ch);
curl_close($ch);
if ($nfo['http_code']) {
$this->fmt->startContain('url', true);
$contentType = explode(';', $nfo['content_type']);
$this->fmt->text('url', sprintf('%s:%d %s %.2fms (%d)', !empty($nfo['primary_ip']) ? $nfo['primary_ip'] : null, !empty($nfo['primary_port']) ? $nfo['primary_port'] : null, $contentType[0], $nfo['total_time'], $nfo['http_code']));
$this->fmt->endContain();
}
}
// date
if ($length < 128 && static::$env['supportsDate'] && !preg_match('/[^A-Za-z0-9.:+\\s\\-\\/]/', $subject)) {
try {
$date = new \DateTime($subject);
$errors = \DateTime::getLastErrors();
if ($errors['warning_count'] < 1 && $errors['error_count'] < 1) {
$now = new \Datetime('now');
$nowUtc = new \Datetime('now', new \DateTimeZone('UTC'));
$diff = $now->diff($date);
$map = array('y' => 'yr', 'm' => 'mo', 'd' => 'da', 'h' => 'hr', 'i' => 'min', 's' => 'sec');
$timeAgo = 'now';
foreach ($map as $k => $label) {
if ($diff->{$k} > 0) {
$timeAgo = $diff->format("%R%{$k}{$label}");
break;
}
}
$tz = $date->getTimezone();
$offs = round($tz->getOffset($nowUtc) / 3600);
if ($offs > 0) {
$offs = "+{$offs}";
}
$timeAgo .= (int) $offs !== 0 ? ' ' . sprintf('%s (UTC%s)', $tz->getName(), $offs) : ' UTC';
$this->fmt->startContain('date', true);
$this->fmt->text('date', $timeAgo);
$this->fmt->endContain();
}
} catch (\Exception $e) {
// not a date
}
}
// attempt to detect if this is a serialized string
static $unserializing = 0;
$isSerialized = $unserializing < 3 && ($subject[$length - 1] === ';' || $subject[$length - 1] === '}') && in_array($subject[0], array('s', 'a', 'O'), true) && ($subject[0] === 's' && $subject[$length - 2] !== '"' || preg_match("/^{$subject[0]}:[0-9]+:/s", $subject)) && ($unserialized = @unserialize($subject)) !== false;
if ($isSerialized) {
$unserializing++;
$this->fmt->startContain('serialized', true);
$this->evaluate($unserialized);
$this->fmt->endContain();
$unserializing--;
}
示例9: sendOrderStatusMail
function sendOrderStatusMail()
{
// Select all Orders which are not in (4,5,6,10) state
// Select id_order, payment and is_queued atleast once
$sql = "select \n o.id_order, \n o.payment, \n position('3' IN group_concat(oh.id_order_state)) as is_queued \n from \n ps_orders o \n inner join ps_order_history oh \n on oh.id_order = o.id_order \n inner join ps_order_history h \n on h.id_order = o.id_order \n inner join \n (select id_order, max(date_add) max_date_add from ps_order_history group by id_order) t2 \n on (h.id_order = t2.id_order and h.date_add = t2.max_date_add) \n where \n h.id_order_state not in (4,5,6,10,20,34) \n group by \n o.id_order";
$total_orders = $not_shipped = $in_sourcing = $in_cust = $on_track = 0;
$result = Db::getInstance()->ExecuteS($sql);
$reports = array();
foreach ($result as $order) {
$total_orders++;
$id_order = (int) $order['id_order'];
$payment = (string) $order['payment'];
$is_queued = (int) $order['is_queued'] === 0 ? false : true;
if ($payment === 'Bank Wire' && $is_queued === false) {
continue;
}
$order = new Order($id_order);
$orderHistory = new OrderHistory();
$orderStateObj = $orderHistory->getLastOrderState($id_order);
$customer = new Customer($order->id_customer);
$cart = new Cart($order->id_cart);
$products = $cart->getProducts();
$order_placed_date = date_create((string) $order->date_add);
$actual_expected_shipping_date = date_create((string) $order->actual_expected_shipping_date);
$current_expected_shipping_date = date_create((string) $order->expected_shipping_date);
$status_updated_date = date_create((string) $orderStateObj->date_add);
$curr_date = new Datetime();
$same_order = false;
foreach ($products as $product) {
$reportObject = array();
$reportObject['id_order'] = $id_order;
$reportObject["name"] = $product['name'];
$reportObject["reference"] = $product['reference'];
$reportObject['customer_name'] = (string) $customer->firstname . ' ' . (string) $customer->lastname;
$reportObject['email'] = (string) $customer->email;
$reportObject['total_paid'] = (double) $order->total_paid;
$reportObject['order_state'] = (string) $orderStateObj->name;
$reportObject['order_placed_date'] = (string) $order_placed_date->format('Y-m-d');
$reportObject['actual_expected_shipping_date'] = (string) $actual_expected_shipping_date->format('Y-m-d');
$reportObject['current_expected_shipping_date'] = (string) $current_expected_shipping_date->format('Y-m-d');
$reportObject['status_updated_date'] = (string) $status_updated_date->format('Y-m-d');
$reportObject['flags'] = array();
if ($actual_expected_shipping_date < $curr_date || $current_expected_shipping_date < $curr_date) {
if (!$same_order) {
$not_shipped++;
}
array_push($reportObject['flags'], "not shipped");
}
if ($reportObject['order_state'] === 'Customization in Progress' && $status_updated_date->add(new DateInterval('P5D')) < $curr_date) {
if (!$same_order) {
$in_cust++;
}
array_push($reportObject['flags'], "> 5days in cust");
}
//(DATEDIFF(o.expected_shipping_date, o.date_add)/2 > DATEDIFF(o.expected_shipping_date, t1.date_add))
if ($reportObject['order_state'] === 'Sourcing in Progress') {
$sourcing_flag = false;
if ($current_expected_shipping_date > $curr_date) {
$total_days_avail = (int) $current_expected_shipping_date->diff($order_placed_date)->days;
$curr_days_avail = (int) $curr_date->diff($current_expected_shipping_date)->days;
if ($total_days_avail / 2 > $curr_days_avail) {
$sourcing_flag = true;
}
} else {
$sourcing_flag = true;
}
if ($sourcing_flag) {
if (!$same_order) {
$in_sourcing++;
}
array_push($reportObject['flags'], "in sourcing");
}
}
if (empty($reportObject['flags'])) {
if (!$same_order) {
$on_track++;
}
$reportObject['flags'] = 'on track';
} else {
$reportObject['flags'] = implode(",", $reportObject['flags']);
}
array_push($reports, $reportObject);
$same_order = true;
}
}
$headers = array(array("order_id", "40px"), array("pname", "100px"), array("pcode", "40px"), array("customer_name", "100px"), array("customer_email", "100px"), array("total_paid", "40px"), array("current_status", "100px"), array("placed_date", "50px"), array("original_shipping_date", "50px"), array("current_shipping_date", "50px"), array("order_status_updated_date", "50px"), array("urgency_level", "40px"));
global $smarty;
$smarty->assign("headers", $headers);
$smarty->assign("total_orders", $total_orders);
$smarty->assign("not_shipped", $not_shipped);
$smarty->assign("in_cust", $in_cust);
$smarty->assign("in_sourcing", $in_sourcing);
$smarty->assign("on_track", $on_track);
$smarty->assign("result", $reports);
$line = '';
foreach ($headers as $header) {
$value = str_replace('"', '""', $header[0]);
$value = '"' . $value . '"' . ",";
$line .= $value;
}
//.........这里部分代码省略.........
示例10: _excludeDate
/**
* Excludes the given date from this series.
* Do not call save() after this, or you might reset the rrule to the old value.
*
* @param Datetime $date The date to remove
*
* @return void
*/
protected function _excludeDate(Datetime $date)
{
// This function distinguishes three cases.
// 1. This is the first event in the series.
// 2. This is the last event in the series.
// 3. Somewhere in between.
if (empty($this->id)) {
throw new Exception('Can only exclude dates from saved events');
}
$series = clone $this;
$series->find($this->id);
$helper = $series->getRruleHelper();
if (!$helper->containsDate($date)) {
throw new Exception('Trying to exclude date that is not part of this series');
}
$start = new Datetime('@' . Phprojekt_Converter_Time::userToUtc($series->start));
$end = new Datetime('@' . Phprojekt_Converter_Time::userToUtc($series->end));
if ($start == $date) {
// If it's the first in it's series, adjust the start date,
// remove excluded dates that we skipped while doing that and
// finally, check if we still need a rrule at all.
$duration = $start->diff($end);
$newStart = $helper->firstOccurrenceAfter($start);
if (is_null($newStart)) {
throw new Exception('$newStart should not be null');
}
$newEnd = clone $newStart;
$newEnd->add($duration);
$series->start = Phprojekt_Converter_Time::utcToUser($newStart->format('Y-m-d H:i:s'));
$series->end = Phprojekt_Converter_Time::utcToUser($newEnd->format('Y-m-d H:i:s'));
// Delete all obsolete excludes
$db = $this->getAdapter();
$where = $db->quoteInto('calendar2_id = ?', $this->id);
$where .= $db->quoteInto('AND date < ?', $newStart->format('Y-m-d H:i:s'));
$db->delete('calendar2_excluded_dates', $where);
// Check if this is still a recurring event
if ($helper->islastOccurrence($newStart)) {
$series->rrule = null;
}
$series->save();
} elseif ($helper->isLastOccurrence($date)) {
// If it's the last in it's series, adjust the Rrule and delete
// now obsolete excludes.
$newLast = $helper->lastOccurrenceBefore($date);
// Check if this is still a recurring event
if ($helper->isFirstOccurrence($newLast)) {
$series->rrule = null;
} else {
// Adjust the rrule
$series->rrule = preg_replace('/UNTIL=[^;]*/', "UNTIL={$newLast->format('Ymd\\THis\\Z')}", $series->rrule);
}
$series->save();
// Delete all obsolete excludes
$db = $this->getAdapter();
$where = $db->quoteInto('calendar2_id = ?', $this->id);
$where .= $db->quoteInto('AND date > ?', $newLast->format('Y-m-d H:i:s'));
$db->delete('calendar2_excluded_dates', $where);
} else {
// If it's somewhere in between, just add it to the list of
// excluded dates.
$this->getAdapter()->insert('calendar2_excluded_dates', array('calendar2_id' => $this->id, 'date' => $date->format('Y-m-d H:i:s')));
}
}
示例11: loadData
public static function loadData($part)
{
// Define coordinates by ip
$coordinates = Libs\Address::recognizeCoordinates();
// Load structures
$Properties = new Structures\Properties();
$FeaturedProperties = new Structures\FeaturedProperties();
// Handle search form
$search = isset($_GET['search_property']) ? (object) Forms::sanitize($_GET['search_property']) : new \stdClass();
// Set default data
$data = (object) ['search' => $search];
// Hidden adding city for main page
if (empty($search->address) && $part == "main") {
$search->address = "Toronto";
//$coordinates->city;
}
// Make criterion
$criterion = self::makeCriterion($search);
// Fetch wp_query
global $wp_query;
// Extract necessary data
switch ($part) {
case "main":
$data->properties = $Properties->get($criterion);
$data->recent_properties = $Properties->get(['orderby' => "publish_date", 'order' => "DESC", 'limit' => 4]);
$data->featured_properties = $FeaturedProperties->getDetailed(['limit' => 3]);
break;
case "map":
// $criterion['limit'] = 10000;
$data->properties = $Properties->get($criterion);
break;
case "properties":
$pagination = new Structures\Pagination($Properties->count($criterion));
$criterion['order'] = $pagination->order;
$criterion['orderby'] = $pagination->orderby;
$criterion['limit'] = $pagination->per_page;
$criterion['limitstart'] = $pagination->current * $pagination->per_page - $pagination->per_page;
$data->properties = $Properties->get($criterion);
$data->pagination = $pagination;
break;
case "compare":
$comparsions = [];
$properties = [];
if (!empty($_COOKIE['comparsions'])) {
$decoded = json_decode(stripcslashes($_COOKIE['comparsions']));
if (!json_last_error()) {
$comparsions = $decoded;
}
}
foreach ($comparsions as $comparsion) {
$properties[] = $Properties->getDetailed((int) $comparsion->id);
}
// TODO: move to admin panel
$data->compare_fields = ['publish_date' => "Publish Date", 'bedrooms' => "Bedrooms", 'bathrooms' => "Bathrooms", 'size' => "Square Feet", 'Extras' => "Extras", 'Gar_type' => "Garage Type", 'Gar_spaces' => "Garage Spaces", 'Bsmt1_out' => "Basement"];
$data->properties = $properties;
break;
case "property":
// Fetch property
$property_id = $wp_query->query_vars['property_id'];
$property = $Properties->getDetailed($property_id);
// Fetch simlar properties
$range = $property->deal_type == "buy" ? 50000 : 300;
$min_price = $property->price - $range;
$max_price = $property->price + $range;
$similar_properties = $Properties->get(['confines' => ["`city`='{$property->city}'", "`price`>={$min_price}", "`price`<={$max_price}"], 'limit' => 4]);
// Assign data
$data->property = $property;
$data->similar_properties = $similar_properties;
break;
case "search_posts":
$search_query = new \WP_Query(['s' => $wp_query->query_vars['s'], 'posts_per_page' => 999]);
$data->posts = $search_query->posts;
$data->search_query = $wp_query->query_vars['s'];
break;
case "content":
$data->post = get_post($wp_query->queried_object_id);
break;
case "rets":
// Fixing start
$start = new \Datetime();
// Do the action
$credentials = Administration\Connection::getStoredOptions();
$Rets = new Libs\Rets($credentials->url, $credentials->login, $credentials->password);
$Rets->login();
$processed_property = $Rets->processProperties(1);
$data->property = $processed_property;
// $data->rets_data = $Rets->synchronizeProperties();
// Fixing end and interval
$end = new \Datetime();
$interval = $start->diff($end);
// Attach info about execution time
$data->execition_time = $interval->format("%s");
break;
}
return $data;
}
示例12: _parseRrule
/**
* Parses a rrule string into a dictionary while working around all
* specialities of iCalendar, so we have values in $this->_rrule that
* a php programmer would expect. See there for exact documentation.
*
* @param string $rrule The rrule.
*
* @return array of string => mixed The properties and their values.
*/
private function _parseRrule($rrule)
{
if (empty($rrule)) {
return array();
}
$ret = array();
$ret['INTERVAL'] = self::_parseInterval($rrule);
$ret['ORIGINAL_FREQ'] = self::_extractFromRrule($rrule, 'FREQ');
$ret['FREQ'] = self::_parseFreq($rrule);
$ret['UNTIL'] = self::_parseUntil($rrule);
$ret['BYDAY'] = self::_parseByDay($rrule);
// Apply FREQ INTERVAL times
$tmp = new Datetime();
$frqint = clone $tmp;
for ($i = 0; $i < $ret['INTERVAL']; $i++) {
$frqint->add($ret['FREQ']);
}
$ret['FREQINTERVAL'] = $tmp->diff($frqint);
return $ret;
}
示例13: processData
public static function processData($batch_size = null)
{
// Check params
if (empty($batch_size) && empty($_POST['batch_size'])) {
self::$negative_messages[] = "Batch size is not defined";
return false;
}
// Pin the time of start
$start = new \Datetime();
// Define vars
$options = self::getStoredOptions();
$batch_size = !empty($batch_size) ? $batch_size : $_POST['batch_size'];
$credentials = Connection::getStoredOptions();
// Define processing progress status
if ($options->is_processing_in_progress) {
self::$negative_messages[] = "Properties is already processing";
return;
} else {
self::storeOptions(['is_processing_in_progress' => true]);
}
// Init Libs
$ProcessingProperties = new Structures\ProcessingProperties();
// Define quantity of processing properties
$unprocecced_qty = $ProcessingProperties->getNumberOfUnprocessed();
$processed_qty = $batch_size >= $unprocecced_qty ? $batch_size : $unprocecced_qty;
$processed_today_qty = $ProcessingProperties->getNumberOfProcessed(date("Y-m-d"));
// Define necessity of processing
if ($unprocecced_qty == 0 || $processed_today_qty >= 10000) {
// Inform if nothing to do
self::$negative_messages[] = $unprocecced_qty == 0 ? "There is no unprocessed properties" : "Daily limit for processing properties is exceeded (limit: 10000, processed: {$processed_today_qty})";
// Remove processing lock
self::storeOptions(['is_processing_in_progress' => false]);
// Stop working
return;
}
// Process properties
try {
$Rets = new Libs\Rets($credentials->url, $credentials->login, $credentials->password);
if (!$Rets->login()) {
self::$negative_messages[] = "Can't connect to RETS server";
return false;
}
$Rets->processProperties($batch_size);
} catch (\Exception $e) {
self::$negative_messages[] = "Error due processing properties: {$e->getMessage()}";
$processed_qty = 0;
}
// Change processing progress status
self::storeOptions(['is_processing_in_progress' => false]);
// Fetch time info
$end = new \Datetime();
$interval = $start->diff($end);
$spent_seconds = $interval->format("%s");
// Add message info about processed properties
self::$positive_messages[] = "{$batch_size} properties has been processed for the {$spent_seconds} seconds";
// Edit info about number of unprocessed properties
$remaining_qty = $ProcessingProperties->getNumberOfUnprocessed();
array_walk(self::$positive_messages, function (&$message) use($remaining_qty) {
$message = preg_replace("/^There is (\\d*) unprocessed properties\$/", "There is {$remaining_qty} unprocessed properties", $message);
});
}
示例14: diffMonths
/**
* @param Datetime $d1
* @param Datetime $d2
* @param boolean $day
* @return int
*/
public static function diffMonths($d1, $d2, $day = true)
{
$interval = $d1->diff($d2);
$result = $interval->y * 12 + $interval->m + ($day ? $interval->d / 30 : 0);
return $result;
}
示例15: _updateLastEnd
/**
* Updates the lastEnd values of all entries
*
* @return void
*/
private function _updateLastEnd()
{
if ($this->_debug) {
Phprojekt::getInstance()->getLog()->debug('_updateLastEnd');
}
$this->_db->query('UPDATE calendar2 SET last_end = end WHERE rrule = ""');
$entries = $this->_db->select()->from('calendar2', array('id', 'start', 'end', 'rrule'))->where('rrule != ""')->query()->fetchAll();
$update = $this->_db->prepare('UPDATE calendar2 SET last_end = :last_end WHERE id = :id');
$x = 0;
foreach ($entries as $key => $e) {
if ($this->_debug && ++$x % 100 == 0) {
Phprojekt::getInstance()->getLog()->debug($x);
}
$start = new Datetime($e['start']);
$end = new Datetime($e['end']);
$duration = $start->diff($end);
$helper = new Calendar2_Helper_Rrule($start, $duration, $e['rrule']);
$update->execute(array(':last_end' => $helper->getUpperTimeBoundary()->format('Y-m-d H:i:s'), ':id' => $e['id']));
}
}