Beispiel #1
1
 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;
                     if ($analytics->getNewSession() == 1) {
                         $totalAnnee += 1;
                         $params[$offset]['moz'] += 1;
                     }
                 } else {
                     if ($morceaux[0] == ' like Gecko') {
                         $totalVisitesAnnee += 1;
                         if ($analytics->getNewSession() == 1) {
                             $totalAnnee += 1;
                             $params[$offset]['div'] += 1;
                         }
                     }
                 }
             } else {
                 $totalVisitesAnnee += 1;
                 if ($analytics->getNewSession() == 1) {
                     $totalAnnee += 1;
                     $params[$offset]['chr'] += 1;
                 }
             }
         }
     }
     $series2 = array(array("name" => "Mozilla", "data" => array($params[1]['moz'], $params[2]['moz'], $params[3]['moz'], $params[4]['moz'], $params[5]['moz'], $params[6]['moz'], $params[7]['moz'], $params[8]['moz'], $params[9]['moz'], $params[10]['moz'], $params[11]['moz'], $params[0]['moz'])), array("name" => "Chrome", "data" => array($params[1]['chr'], $params[2]['chr'], $params[3]['chr'], $params[4]['chr'], $params[5]['chr'], $params[6]['chr'], $params[7]['chr'], $params[8]['chr'], $params[9]['chr'], $params[10]['chr'], $params[11]['chr'], $params[0]['chr'])), array("name" => "Autres", "data" => array($params[1]['div'], $params[2]['div'], $params[3]['div'], $params[4]['div'], $params[5]['div'], $params[6]['div'], $params[7]['div'], $params[8]['div'], $params[9]['div'], $params[10]['div'], $params[11]['div'], $params[0]['div'])));
     $categories2 = array($params[1]['mois'], $params[2]['mois'], $params[3]['mois'], $params[4]['mois'], $params[5]['mois'], $params[6]['mois'], $params[7]['mois'], $params[8]['mois'], $params[9]['mois'], $params[10]['mois'], $params[11]['mois'], $params[0]['mois']);
     $ob2 = new Highchart();
     $ob2->chart->renderTo('linechart2');
     // The #id of the div where to render the chart
     $ob2->title->text('Visites de l\'année entière');
     $ob2->xAxis->categories($categories2);
     $ob2->xAxis->title(array('text' => "Mois"));
     $ob2->yAxis->title(array('text' => "Visites par navigateur"));
     $ob2->series($series2);
     /*fin de*/
     return $this->render('APPAdminBundle:pages:audience.html.twig', array('general' => $generalite, 'inscr' => $inscr, 'desinscr' => $desinscr, 'nbInscr' => $nbInscr, 'nbDesinscr' => $nbDesinscr, 'chart' => $ob, 'chart2' => $ob2, 'totalSemaine' => $totalSemaine, 'totalAnnee' => $totalAnnee, 'totalVisitesSemaine' => $totalVisitesSemaine, 'totalVisitesAnnee' => $totalVisitesAnnee));
 }
 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;
 }
 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());
         }
     }
 }
Beispiel #4
0
 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;
 }
Beispiel #5
0
<?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;
Beispiel #6
0
            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"];
Beispiel #7
0
 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");
 }
Beispiel #8
0
 /**
  * Evaluates the given variable
  *
  * @param   mixed &$subject   Variable to query
  * @param   bool $specialStr  Should this be interpreted as a special string?
  * @return  mixed             Result (both HTML and text modes generate strings)
  */
 protected function evaluate(&$subject, $specialStr = false)
 {
     switch ($type = gettype($subject)) {
         // https://github.com/digitalnature/php-ref/issues/13
         case 'unknown type':
             return $this->fmt->text('unknown');
             // null value
         // null value
         case 'NULL':
             return $this->fmt->text('null');
             // integer/double/float
         // integer/double/float
         case 'integer':
         case 'double':
             return $this->fmt->text($type, $subject, $type);
             // boolean
         // boolean
         case 'boolean':
             $text = $subject ? 'true' : 'false';
             return $this->fmt->text($text, $text, $type);
             // arrays
         // arrays
         case 'array':
             // empty array?
             if (empty($subject)) {
                 $this->fmt->text('array');
                 return $this->fmt->emptyGroup();
             }
             if (isset($subject[static::MARKER_KEY])) {
                 unset($subject[static::MARKER_KEY]);
                 $this->fmt->text('array');
                 $this->fmt->emptyGroup('recursion');
                 return;
             }
             // first recursion level detection;
             // this is optional (used to print consistent recursion info)
             foreach ($subject as $key => &$value) {
                 if (!is_array($value)) {
                     continue;
                 }
                 // save current value in a temporary variable
                 $buffer = $value;
                 // assign new value
                 $value = $value !== 1 ? 1 : 2;
                 // if they're still equal, then we have a reference
                 if ($value === $subject) {
                     $value = $buffer;
                     $value[static::MARKER_KEY] = true;
                     $this->evaluate($value);
                     return;
                 }
                 // restoring original value
                 $value = $buffer;
             }
             $this->fmt->text('array');
             $count = count($subject);
             if (!$this->fmt->startGroup($count)) {
                 return;
             }
             $max = max(array_map('static::strLen', array_keys($subject)));
             $subject[static::MARKER_KEY] = true;
             foreach ($subject as $key => &$value) {
                 // ignore our temporary marker
                 if ($key === static::MARKER_KEY) {
                     continue;
                 }
                 if ($this->hasInstanceTimedOut()) {
                     break;
                 }
                 $keyInfo = gettype($key);
                 if ($keyInfo === 'string') {
                     $encoding = static::$env['mbStr'] ? mb_detect_encoding($key) : '';
                     $keyLen = $encoding && $encoding !== 'ASCII' ? static::strLen($key) . '; ' . $encoding : static::strLen($key);
                     $keyInfo = "{$keyInfo}({$keyLen})";
                 } else {
                     $keyLen = strlen($key);
                 }
                 $this->fmt->startRow();
                 $this->fmt->text('key', $key, "Key: {$keyInfo}");
                 $this->fmt->colDiv($max - $keyLen);
                 $this->fmt->sep('=>');
                 $this->fmt->colDiv();
                 $this->evaluate($value, $specialStr);
                 $this->fmt->endRow();
             }
             unset($subject[static::MARKER_KEY]);
             $this->fmt->endGroup();
             return;
             // resource
         // resource
         case 'resource':
             $meta = array();
             $resType = get_resource_type($subject);
             $this->fmt->text('resource', strval($subject));
             if (!static::$config['showResourceInfo']) {
                 return $this->fmt->emptyGroup($resType);
             }
             // @see: http://php.net/manual/en/resource.php
             // need to add more...
             switch ($resType) {
                 // curl extension resource
                 case 'curl':
                     $meta = curl_getinfo($subject);
                     break;
                 case 'FTP Buffer':
                     $meta = array('time_out' => ftp_get_option($subject, FTP_TIMEOUT_SEC), 'auto_seek' => ftp_get_option($subject, FTP_AUTOSEEK));
                     break;
                     // gd image extension resource
                 // gd image extension resource
                 case 'gd':
                     $meta = array('size' => sprintf('%d x %d', imagesx($subject), imagesy($subject)), 'true_color' => imageistruecolor($subject));
                     break;
                 case 'ldap link':
                     $constants = get_defined_constants();
                     array_walk($constants, function ($value, $key) use(&$constants) {
                         if (strpos($key, 'LDAP_OPT_') !== 0) {
                             unset($constants[$key]);
                         }
                     });
                     // this seems to fail on my setup :(
                     unset($constants['LDAP_OPT_NETWORK_TIMEOUT']);
                     foreach (array_slice($constants, 3) as $key => $value) {
                         if (ldap_get_option($subject, (int) $value, $ret)) {
                             $meta[strtolower(substr($key, 9))] = $ret;
                         }
                     }
                     break;
                     // mysql connection (mysql extension is deprecated from php 5.4/5.5)
                 // mysql connection (mysql extension is deprecated from php 5.4/5.5)
                 case 'mysql link':
                 case 'mysql link persistent':
                     $dbs = array();
                     $query = @mysql_list_dbs($subject);
                     while ($row = @mysql_fetch_array($query)) {
                         $dbs[] = $row['Database'];
                     }
                     $meta = array('host' => ltrim(@mysql_get_host_info($subject), 'MySQL host info: '), 'server_version' => @mysql_get_server_info($subject), 'protocol_version' => @mysql_get_proto_info($subject), 'databases' => $dbs);
                     break;
                     // mysql result
                 // mysql result
                 case 'mysql result':
                     while ($row = @mysql_fetch_object($subject)) {
                         $meta[] = (array) $row;
                         if ($this->hasInstanceTimedOut()) {
                             break;
                         }
                     }
                     break;
                     // stream resource (fopen, fsockopen, popen, opendir etc)
                 // stream resource (fopen, fsockopen, popen, opendir etc)
                 case 'stream':
                     $meta = stream_get_meta_data($subject);
                     break;
             }
             if (!$meta) {
                 return $this->fmt->emptyGroup($resType);
             }
             if (!$this->fmt->startGroup($resType)) {
                 return;
             }
             $max = max(array_map('static::strLen', array_keys($meta)));
             foreach ($meta as $key => $value) {
                 $this->fmt->startRow();
                 $this->fmt->text('resourceProp', ucwords(str_replace('_', ' ', $key)));
                 $this->fmt->colDiv($max - static::strLen($key));
                 $this->fmt->sep(':');
                 $this->fmt->colDiv();
                 $this->evaluate($value);
                 $this->fmt->endRow();
             }
             $this->fmt->endGroup();
             return;
             // string
         // string
         case 'string':
             $length = static::strLen($subject);
             $encoding = static::$env['mbStr'] ? mb_detect_encoding($subject) : false;
             $info = $encoding && $encoding !== 'ASCII' ? $length . '; ' . $encoding : $length;
             if ($specialStr) {
                 $this->fmt->sep('"');
                 $this->fmt->text(array('string', 'special'), $subject, "string({$info})");
                 $this->fmt->sep('"');
                 return;
             }
             $this->fmt->text('string', $subject, "string({$info})");
             // advanced checks only if there are 3 characteres or more
             if (static::$config['showStringMatches'] && $length > 2 && trim($subject) !== '') {
                 $isNumeric = is_numeric($subject);
                 // very simple check to determine if the string could match a file path
                 // @note: this part of the code is very expensive
                 $isFile = $length < 2048 && max(array_map('strlen', explode('/', str_replace('\\', '/', $subject)))) < 128 && !preg_match('/[^\\w\\.\\-\\/\\\\:]|\\..*\\.|\\.$|:(?!(?<=^[a-zA-Z]:)[\\/\\\\])/', $subject);
                 if ($isFile) {
                     try {
                         $file = new \SplFileInfo($subject);
                         $flags = array();
                         $perms = $file->getPerms();
                         if (($perms & 0xc000) === 0xc000) {
                             // socket
                             $flags[] = 's';
                         } elseif (($perms & 0xa000) === 0xa000) {
                             // symlink
                             $flags[] = 'l';
                         } elseif (($perms & 0x8000) === 0x8000) {
                             // regular
                             $flags[] = '-';
                         } elseif (($perms & 0x6000) === 0x6000) {
                             // block special
                             $flags[] = 'b';
                         } elseif (($perms & 0x4000) === 0x4000) {
                             // directory
                             $flags[] = 'd';
                         } elseif (($perms & 0x2000) === 0x2000) {
                             // character special
                             $flags[] = 'c';
                         } elseif (($perms & 0x1000) === 0x1000) {
                             // FIFO pipe
                             $flags[] = 'p';
                         } else {
                             // unknown
                             $flags[] = 'u';
                         }
                         // owner
                         $flags[] = $perms & 0x100 ? 'r' : '-';
                         $flags[] = $perms & 0x80 ? 'w' : '-';
                         $flags[] = $perms & 0x40 ? $perms & 0x800 ? 's' : 'x' : ($perms & 0x800 ? 'S' : '-');
                         // group
                         $flags[] = $perms & 0x20 ? 'r' : '-';
                         $flags[] = $perms & 0x10 ? 'w' : '-';
                         $flags[] = $perms & 0x8 ? $perms & 0x400 ? 's' : 'x' : ($perms & 0x400 ? 'S' : '-');
                         // world
                         $flags[] = $perms & 0x4 ? 'r' : '-';
                         $flags[] = $perms & 0x2 ? 'w' : '-';
                         $flags[] = $perms & 0x1 ? $perms & 0x200 ? 't' : 'x' : ($perms & 0x200 ? 'T' : '-');
                         $size = is_dir($subject) ? '' : sprintf(' %.2fK', $file->getSize() / 1024);
                         $this->fmt->startContain('file', true);
                         $this->fmt->text('file', implode('', $flags) . $size);
                         $this->fmt->endContain();
                     } catch (\Exception $e) {
                         $isFile = false;
                     }
                 }
                 // class/interface/function
                 if (!preg_match('/[^\\w+\\\\]/', $subject) && $length < 96) {
                     $isClass = class_exists($subject, false);
                     if ($isClass) {
                         $this->fmt->startContain('class', true);
                         $this->fromReflector(new \ReflectionClass($subject));
                         $this->fmt->endContain();
                     }
                     if (!$isClass && interface_exists($subject, false)) {
                         $this->fmt->startContain('interface', true);
                         $this->fromReflector(new \ReflectionClass($subject));
                         $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--;
                     }
                     // try to find out if it's a json-encoded string;
                     // only do this for json-encoded arrays or objects, because other types have too generic formats
                     static $decodingJson = 0;
                     $isJson = !$isSerialized && $decodingJson < 3 && in_array($subject[0], array('{', '['), true);
                     if ($isJson) {
                         $decodingJson++;
                         $json = json_decode($subject);
                         if ($isJson = json_last_error() === JSON_ERROR_NONE) {
                             $this->fmt->startContain('json', true);
                             $this->evaluate($json);
                             $this->fmt->endContain();
                         }
                         $decodingJson--;
                     }
                     // attempt to match a regex
                     if ($length < 768) {
                         try {
                             $components = $this->splitRegex($subject);
                             if ($components) {
                                 $regex = '';
                                 $this->fmt->startContain('regex', true);
                                 foreach ($components as $component) {
                                     $this->fmt->text('regex-' . key($component), reset($component));
                                 }
                                 $this->fmt->endContain();
                             }
                         } catch (\Exception $e) {
                             // not a regex
                         }
                     }
                 }
             }
             return;
     }
     // if we reached this point, $subject must be an object
     // track objects to detect recursion
     static $hashes = array();
     // hash ID of this object
     $hash = spl_object_hash($subject);
     $recursion = isset($hashes[$hash]);
     // sometimes incomplete objects may be created from string unserialization,
     // if the class to which the object belongs wasn't included until the unserialization stage...
     if ($subject instanceof \__PHP_Incomplete_Class) {
         $this->fmt->text('object');
         $this->fmt->emptyGroup('incomplete');
         return;
     }
     // check cache at this point
     if (!$recursion && $this->fmt->didCache($hash)) {
         static::$debug['cacheHits']++;
         return;
     }
     $reflector = new \ReflectionObject($subject);
     $this->fmt->startContain('class');
     $this->fromReflector($reflector);
     $this->fmt->text('object', ' object');
     $this->fmt->endContain();
     // already been here?
     if ($recursion) {
         return $this->fmt->emptyGroup('recursion');
     }
     $hashes[$hash] = 1;
     $flags = \ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED;
     if (static::$config['showPrivateMembers']) {
         $flags |= \ReflectionProperty::IS_PRIVATE;
     }
     $props = $reflector->getProperties($flags);
     $methods = array();
     if (static::$config['showMethods']) {
         $flags = \ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED;
         if (static::$config['showPrivateMembers']) {
             $flags |= \ReflectionMethod::IS_PRIVATE;
         }
         $methods = $reflector->getMethods($flags);
     }
     $constants = $reflector->getConstants();
     $interfaces = $reflector->getInterfaces();
     $traits = static::$env['is54'] ? $reflector->getTraits() : array();
     $parents = static::getParentClasses($reflector);
     // work-around for https://bugs.php.net/bug.php?id=49154
     // @see http://stackoverflow.com/questions/15672287/strange-behavior-of-reflectiongetproperties-with-numeric-keys
     if (!static::$env['is54']) {
         $props = array_values(array_filter($props, function ($prop) use($subject) {
             return !$prop->isPublic() || property_exists($subject, $prop->name);
         }));
     }
     // no data to display?
     if (!$props && !$methods && !$constants && !$interfaces && !$traits) {
         unset($hashes[$hash]);
         return $this->fmt->emptyGroup();
     }
     if (!$this->fmt->startGroup()) {
         return;
     }
     // show contents for iterators
     if (static::$config['showIteratorContents'] && $reflector->isIterateable()) {
         $itContents = iterator_to_array($subject);
         $this->fmt->sectionTitle(sprintf('Contents (%d)', count($itContents)));
         foreach ($itContents as $key => $value) {
             $keyInfo = gettype($key);
             if ($keyInfo === 'string') {
                 $encoding = static::$env['mbStr'] ? mb_detect_encoding($key) : '';
                 $length = $encoding && $encoding !== 'ASCII' ? static::strLen($key) . '; ' . $encoding : static::strLen($key);
                 $keyInfo = sprintf('%s(%s)', $keyInfo, $length);
             }
             $this->fmt->startRow();
             $this->fmt->text(array('key', 'iterator'), $key, sprintf('Iterator key: %s', $keyInfo));
             $this->fmt->colDiv();
             $this->fmt->sep('=>');
             $this->fmt->colDiv();
             $this->evaluate($value);
             //$this->evaluate($value instanceof \Traversable ? ((count($value) > 0) ? $value : (string)$value) : $value);
             $this->fmt->endRow();
         }
     }
     // display the interfaces this objects' class implements
     if ($interfaces) {
         $items = array();
         $this->fmt->sectionTitle('Implements');
         $this->fmt->startRow();
         $this->fmt->startContain('interfaces');
         $i = 0;
         $count = count($interfaces);
         foreach ($interfaces as $name => $interface) {
             $this->fromReflector($interface);
             if (++$i < $count) {
                 $this->fmt->sep(', ');
             }
         }
         $this->fmt->endContain();
         $this->fmt->endRow();
     }
     // traits this objects' class uses
     if ($traits) {
         $items = array();
         $this->fmt->sectionTitle('Uses');
         $this->fmt->startRow();
         $this->fmt->startContain('traits');
         $i = 0;
         $count = count($traits);
         foreach ($traits as $name => $trait) {
             $this->fromReflector($trait);
             if (++$i < $count) {
                 $this->fmt->sep(', ');
             }
         }
         $this->fmt->endContain();
         $this->fmt->endRow();
     }
     // class constants
     if ($constants) {
         $this->fmt->sectionTitle('Constants');
         $max = max(array_map('static::strLen', array_keys($constants)));
         foreach ($constants as $name => $value) {
             $meta = null;
             $type = array('const');
             foreach ($parents as $parent) {
                 if ($parent->hasConstant($name)) {
                     if ($parent !== $reflector) {
                         $type[] = 'inherited';
                         $meta = array('sub' => array(array('Prototype defined by', $parent->name)));
                     }
                     break;
                 }
             }
             $this->fmt->startRow();
             $this->fmt->sep('::');
             $this->fmt->colDiv();
             $this->fmt->startContain($type);
             $this->fmt->text('name', $name, $meta, $this->linkify($parent, $name));
             $this->fmt->endContain();
             $this->fmt->colDiv($max - static::strLen($name));
             $this->fmt->sep('=');
             $this->fmt->colDiv();
             $this->evaluate($value);
             $this->fmt->endRow();
         }
     }
     // object/class properties
     if ($props) {
         $this->fmt->sectionTitle('Properties');
         $max = 0;
         foreach ($props as $idx => $prop) {
             if (($propNameLen = static::strLen($prop->name)) > $max) {
                 $max = $propNameLen;
             }
         }
         foreach ($props as $idx => $prop) {
             if ($this->hasInstanceTimedOut()) {
                 break;
             }
             $bubbles = array();
             $sourceClass = $prop->getDeclaringClass();
             $inherited = $reflector->getShortName() !== $sourceClass->getShortName();
             $meta = $sourceClass->isInternal() ? null : static::parseComment($prop->getDocComment());
             if ($meta) {
                 if ($inherited) {
                     $meta['sub'] = array(array('Declared in', $sourceClass->getShortName()));
                 }
                 if (isset($meta['tags']['var'][0])) {
                     $meta['left'] = $meta['tags']['var'][0][0];
                 }
                 unset($meta['tags']);
             }
             if ($prop->isProtected() || $prop->isPrivate()) {
                 $prop->setAccessible(true);
             }
             $value = $prop->getValue($subject);
             $this->fmt->startRow();
             $this->fmt->sep($prop->isStatic() ? '::' : '->');
             $this->fmt->colDiv();
             $bubbles = array();
             if ($prop->isProtected()) {
                 $bubbles[] = array('P', 'Protected');
             }
             if ($prop->isPrivate()) {
                 $bubbles[] = array('!', 'Private');
             }
             $this->fmt->bubbles($bubbles);
             $type = array('prop');
             if ($inherited) {
                 $type[] = 'inherited';
             }
             if ($prop->isPrivate()) {
                 $type[] = 'private';
             }
             $this->fmt->colDiv(2 - count($bubbles));
             $this->fmt->startContain($type);
             $this->fmt->text('name', $prop->name, $meta, $this->linkify($prop));
             $this->fmt->endContain();
             $this->fmt->colDiv($max - static::strLen($prop->name));
             $this->fmt->sep('=');
             $this->fmt->colDiv();
             $this->evaluate($value);
             $this->fmt->endRow();
         }
     }
     // class methods
     if ($methods && !$this->hasInstanceTimedOut()) {
         $this->fmt->sectionTitle('Methods');
         foreach ($methods as $idx => $method) {
             $this->fmt->startRow();
             $this->fmt->sep($method->isStatic() ? '::' : '->');
             $this->fmt->colDiv();
             $bubbles = array();
             if ($method->isAbstract()) {
                 $bubbles[] = array('A', 'Abstract');
             }
             if ($method->isFinal()) {
                 $bubbles[] = array('F', 'Final');
             }
             if ($method->isProtected()) {
                 $bubbles[] = array('P', 'Protected');
             }
             if ($method->isPrivate()) {
                 $bubbles[] = array('!', 'Private');
             }
             $this->fmt->bubbles($bubbles);
             $this->fmt->colDiv(4 - count($bubbles));
             // is this method inherited?
             $inherited = $reflector->getShortName() !== $method->getDeclaringClass()->getShortName();
             $type = array('method');
             if ($inherited) {
                 $type[] = 'inherited';
             }
             if ($method->isPrivate()) {
                 $type[] = 'private';
             }
             $this->fmt->startContain($type);
             $name = $method->name;
             if ($method->returnsReference()) {
                 $name = "&{$name}";
             }
             $this->fromReflector($method, $name, $reflector);
             $paramCom = $method->isInternal() ? array() : static::parseComment($method->getDocComment(), 'tags');
             $paramCom = empty($paramCom['param']) ? array() : $paramCom['param'];
             $paramCount = $method->getNumberOfParameters();
             $this->fmt->sep('(');
             // process arguments
             foreach ($method->getParameters() as $idx => $parameter) {
                 $meta = null;
                 $paramName = "\${$parameter->name}";
                 $optional = $parameter->isOptional();
                 $variadic = static::$env['is56'] && $parameter->isVariadic();
                 if ($parameter->isPassedByReference()) {
                     $paramName = "&{$paramName}";
                 }
                 if ($variadic) {
                     $paramName = "...{$paramName}";
                 }
                 $type = array('param');
                 if ($optional) {
                     $type[] = 'optional';
                 }
                 $this->fmt->startContain($type);
                 // attempt to build meta
                 foreach ($paramCom as $tag) {
                     list($pcTypes, $pcName, $pcDescription) = $tag;
                     if ($pcName !== $paramName) {
                         continue;
                     }
                     $meta = array('title' => $pcDescription);
                     if ($pcTypes) {
                         $meta['left'] = $pcTypes;
                     }
                     break;
                 }
                 try {
                     $paramClass = $parameter->getClass();
                 } catch (\Exception $e) {
                     // @see https://bugs.php.net/bug.php?id=32177&edit=1
                 }
                 if (!empty($paramClass)) {
                     $this->fmt->startContain('hint');
                     $this->fromReflector($paramClass, $paramClass->name);
                     $this->fmt->endContain();
                     $this->fmt->sep(' ');
                 }
                 if ($parameter->isArray()) {
                     $this->fmt->text('hint', 'array');
                     $this->fmt->sep(' ');
                 }
                 $this->fmt->text('name', $paramName, $meta);
                 if ($optional) {
                     $paramValue = $parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : null;
                     $this->fmt->sep(' = ');
                     if (static::$env['is546'] && !$parameter->getDeclaringFunction()->isInternal() && $parameter->isDefaultValueConstant()) {
                         $this->fmt->text('constant', $parameter->getDefaultValueConstantName(), 'Constant');
                     } else {
                         $this->evaluate($paramValue, true);
                     }
                 }
                 $this->fmt->endContain();
                 if ($idx < $paramCount - 1) {
                     $this->fmt->sep(', ');
                 }
             }
             $this->fmt->sep(')');
             $this->fmt->endContain();
             $this->fmt->endRow();
         }
     }
     unset($hashes[$hash]);
     $this->fmt->endGroup();
     $this->fmt->cacheLock($hash);
 }
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;
    }
    $data = trim($line) . "\n";
    foreach ($reports as $row) {
        $line = '';
        foreach ($row as $value) {
            if (!isset($value) || $value == "") {
                $value = ",";
            } else {
                $value = str_replace('"', '""', $value);
                $value = '"' . $value . '"' . ",";
            }
            $line .= $value;
        }
        $data .= trim($line) . "\n";
    }
    $data = str_replace("\r", "", $data);
    if ($data == "") {
        $data = "\nNo Records Found!\n";
    }
    $fileAttachment['content'] = $data;
    $fileAttachment['name'] = 'IndusdivaOrderDailyStatus' . date("d-m-Y") . '.csv';
    $fileAttachment['mime'] = 'text/csv';
    $templateVars = array();
    $templateVars['{today_date}'] = date('d-m-y');
    $templateVars['{report_summary}'] = $smarty->fetch(_PS_THEME_DIR_ . 'order-daily-summary.tpl');
    $templateVars['{report_content}'] = $smarty->fetch(_PS_THEME_DIR_ . 'order-daily-status.tpl');
    $to = array('*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**');
    $subject = "Order Daily Status - " . date('d-m-y');
    @Mail::Send(1, 'order_daily_status', $subject, $templateVars, $to, null, '*****@*****.**', 'Indusdiva.com', $fileAttachment, NULL, _PS_MAIL_DIR_, false);
}
Beispiel #10
0
 /**
  * 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')));
     }
 }
Beispiel #11
0
 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;
 }
Beispiel #12
0
 /**
  * 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;
 }
Beispiel #13
0
 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);
     });
 }
Beispiel #14
0
 /**
  * @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;
 }
Beispiel #15
0
 /**
  * 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']));
     }
 }
             $salaires_joueurs_restant_min += $data['salary'];
         }
         if ($salaires_joueurs_restant_min > $salary_cap - $this_masse_salariale) {
             $selection_ok = FALSE;
             //$str_alert = "alert('Avec ce choix, il ne vous sera pas possible de compléter votre Grand Club avec les joueurs restants. Recommencer votre sélection avec un salaire plus petit...');";
             $str_alert = "Avec ce choix, il ne vous sera pas possible de compléter votre Grand Club avec les joueurs restants. Recommencer votre sélection avec un salaire plus petit...";
         }
     }
 }
 if ($selection_ok) {
     // insertion dans la table draft
     $query = "REPLACE INTO draft (id_pool,saison_id,gerant,draft_pick,draft_overall,round,id_player,pos,draft_overall_team)\n\t                              VALUES ({$id_pool},{$id_saison},{$gerant},{$draft_pick},{$draft_overall},{$ronde_rendue},{$id_player},\"{$pos}\",0)";
     mysql_query($query, $pool->handle);
     // insertion du temps pris pour faire la sélection dans la table correspondante
     $_now = new Datetime(null, new DateTimeZone('America/Montreal'));
     $temps_pris_sel = $_now->diff($_date_compteur)->s;
     $query = "insert into draft_temps_gerant (id_pool,saison_id,id_gerant,ronde,temps)\n          \t                          values ({$id_pool}, {$id_saison}, {$gerant}, {$ronde_rendue}, {$temps_pris_sel})";
     mysql_query($query, $pool->handle);
     // maintenant, il faut passer au gérant suivant dans l'ordre du draft. Si c'était le dernier de la
     // liste, on revient au premier gérant et on augmente de 1 le numéro de la ronde.
     unset($ordre_repechageA, $ordre_repechage_id_gerant);
     // nombre de sélections possibles dans la ronde
     $query = "select count(*) d1\n                                         from draft_repechage\n                                         where\n                                             id_pool = {$id_pool}\n                                             and saison_id = {$id_saison}\n                                             and ronde = {$ronde_rendue}";
     $resultID = mysql_query($query, $pool->handle);
     $data = mysql_fetch_array($resultID);
     $nbre_picks_this_ronde = $data['d1'];
     if ($ordre_repechage_rendu < $nbre_picks_this_ronde) {
         $query = "select id_gerant\n\t                                          from draft_repechage\n\t                                          where\n\t                                             id_pool = {$id_pool}\n\t                                             and saison_id = {$id_saison}\n\t                                             and ronde = {$ronde_rendue}\n\t                                             and ordre_repechage = " . ($ordre_repechage_rendu + 1);
         $resultID = mysql_query($query, $pool->handle);
         $data = mysql_fetch_array($resultID);
         $next_gerant = $data['id_gerant'];
Beispiel #17
0
 public function magasin_sortieAction(ProduitMagasin $pm)
 {
     if ($this->get('security.context')->isGranted('ROLE_GESTIONNAIRE') === false) {
         throw new AccessDeniedHttpException("Accès limité - Vous ne disposez pas d'autorisation necessaire");
     }
     $date = new \Datetime();
     $form = $this->createForm(new ProduitMagasinEditType(), $pm);
     if ($pm === null) {
         throw $this->createNotFoundException('ProduitMagasin[id=' . $id . ']inexistant.');
     }
     $request = $this->get('request');
     if ($request->getMethod() == 'POST') {
         $form->bind($request);
         if ($pm->getVars() > $pm->getQuantite()) {
             $msg = "Erreur: quantité entrée superieure au stock disponible";
             return $this->render('SdzATIBundle:ati:magasin_sortie.html.twig', array('msg' => $msg, 'pm' => $pm, 'form' => $form->createView()));
         }
         if ($form->isValid()) {
             $qd = $pm->getVars();
             $em = $this->getDoctrine()->getManager();
             $pm->setQuantite($pm->getQuantite() - $pm->getVars());
             $pm->setDate(new \Datetime());
             $sortie = new Sortie();
             $sortie->setUser($this->get('security.context')->getToken()->getUser());
             $sortie->setMagasin($pm->getMagasin());
             $sortie->setProduit($pm->getProduit());
             $sortie->setQuantite($qd);
             $sortie->setObservation($pm->getObservation());
             $produit = $em->getRepository('SdzATIBundle:Produit')->findOneById($pm->getProduit()->getId());
             $produit->setQted($produit->getQted() - $qd);
             $statm = $em->getRepository('SdzATIBundle:StatMagasin')->findStatMannee($pm->getMagasin()->getId(), $pm->getProduit()->getId(), $sortie->getDate()->format('Y'));
             if ($statm == null) {
                 $newstat = new Statistique();
                 $newstat->setMois($newstat->getDate()->format('m'));
                 $newstat->setAnnee($newstat->getDate()->format('Y'));
                 $newstat->setEntree(0);
                 $newstat->setSortie($sortie->getQuantite());
                 $newstat->setFreqvente($sortie->getQuantite());
                 $newstat->setProduit($pm->getProduit());
                 $newstatm = new StatMagasin();
                 $newstatm->setMois($newstat->getDate()->format('m'));
                 $newstatm->setAnnee($newstat->getDate()->format('Y'));
                 $newstatm->setEntree(0);
                 $newstatm->setSortie($sortie->getQuantite());
                 $newstatm->setFreqvente($sortie->getQuantite());
                 $newstatm->setProduit($pm->getProduit());
                 $newstatm->setMagasin($pm->getMagasin());
                 $em->persist($newstatm);
                 $em->persist($newstat);
                 $em->persist($produit);
                 $em->persist($pm);
                 $em->persist($sortie);
                 $em->flush();
                 $this->get('session')->getFlashBag()->add('infom', 'Sortie du produit bien effectuée');
                 return $this->redirect($this->generateUrl('sdz_ati_gestion_magasin', array('id' => $pm->getMagasin()->getId())));
             }
             $statm2 = $em->getRepository('SdzATIBundle:StatMagasin')->findStatMmois($pm->getMagasin()->getId(), $pm->getProduit()->getId(), $sortie->getDate()->format('Y'), $sortie->getDate()->format('m'));
             if ($statm2 === null) {
                 $newstat = new Statistique();
                 $newstat->setMois($newstat->getDate()->format('m'));
                 $newstat->setAnnee($newstat->getDate()->format('Y'));
                 $newstat->setEntree(0);
                 $newstat->setSortie($sortie->getQuantite());
                 $newstat->setFreqvente($sortie->getQuantite());
                 $newstat->setProduit($pm->getProduit());
                 $newstatm = new StatMagasin();
                 $newstatm->setMois($newstat->getDate()->format('m'));
                 $newstatm->setAnnee($newstat->getDate()->format('Y'));
                 $newstatm->setEntree(0);
                 $newstatm->setSortie($sortie->getQuantite());
                 $newstatm->setFreqvente($sortie->getQuantite());
                 $newstatm->setProduit($pm->getProduit());
                 $newstatm->setMagasin($pm->getMagasin());
                 $em->persist($newstatm);
                 $em->persist($newstat);
                 $em->persist($produit);
                 $em->persist($pm);
                 $em->persist($sortie);
                 $em->flush();
                 $this->get('session')->getFlashBag()->add('infom', 'Sortie du produit bien effectuée');
                 return $this->redirect($this->generateUrl('sdz_ati_gestion_magasin', array('id' => $pm->getMagasin()->getId())));
             } else {
                 $statm2->setSortie($statm2->getSortie() + $sortie->getQuantite());
                 $stat = $em->getRepository('SdzATIBundle:Statistique')->findStatmois($pm->getProduit()->getId(), $sortie->getDate()->format('Y'), $sortie->getDate()->format('m'));
                 $stat->setSortie($stat->getSortie() + $sortie->getQuantite());
                 $nb = $date->diff($statm2->getDate());
                 $nb = $nb->format('%d');
                 if ($nb == 0) {
                     $statm2->setFreqvente($statm2->getSortie());
                     $stat->setFreqvente($stat->getSortie());
                 } else {
                     $statm2->setFreqvente($statm2->getSortie() / $nb);
                     $stat->setFreqvente($stat->getSortie() / $nb);
                 }
                 $em->persist($statm2);
                 $em->persist($stat);
                 $em->persist($produit);
                 $em->persist($pm);
                 $em->persist($sortie);
                 $em->flush();
                 $this->get('session')->getFlashBag()->add('infom', 'Sortie du produit bien effectuée');
                 return $this->redirect($this->generateUrl('sdz_ati_gestion_magasin', array('id' => $pm->getMagasin()->getId())));
             }
         }
     }
     return $this->render('SdzATIBundle:ati:magasin_sortie.html.twig', array('pm' => $pm, 'form' => $form->createView()));
 }
Beispiel #18
0
 /**
  * Get Pretty Date
  *
  * @param   string $date
  * @param   string $compare_to_date
  *
  * @return  string formatted pretty date
  * @since   1.0.0
  */
 public function getPrettyDate($date, $compare_to_date = null)
 {
     $source_date = new Datetime($date);
     if ($compare_to_date === null) {
         $compare_to_date = new Datetime();
     } else {
         $compare_to_date = new Datetime($compare_to_date);
     }
     $interval = $source_date->diff($compare_to_date);
     $day_difference = $interval->days;
     if ($day_difference === 0) {
         $pretty_date = $this->getPrettyDateToday($interval);
     } else {
         $pretty_date = $this->getPrettyDateNotToday($interval);
     }
     return $pretty_date;
 }
 private function applyICalendarTimes($start, $end, $timezoneID = null)
 {
     $utc = new DateTimezone('UTC');
     $timezone = null;
     $userTimeZone = Phprojekt_User_User::getUserDateTimeZone();
     if ('Z' === substr($start, -1)) {
         $timezone = $utc;
     } else {
         if (!is_null($timezoneID)) {
             $timezone = new DateTimeZone($timezoneID);
         } else {
             $timezone = $userTimeZone;
         }
     }
     // We can't use ->setTimezone with the timezones returned by getUserDateTimeZone, as these are non-standard
     // timezones. Unless we start storing correct timezones, we can't directly set the user timezone, so we go to
     // UTC and convert to usertime from there. Because utcToUser returns a unix timestamp, but ActiveRecords expects
     // a "Y-m-d H:i:s" timestamp, we have to go through Datetime again.
     $start = new Datetime($start, $timezone);
     $start->setTimezone($utc);
     $startTs = Phprojekt_Converter_Time::utcToUser($start->format('Y-m-d H:i:s'));
     $start = new Datetime('@' . $startTs);
     $end = new Datetime($end, $timezone);
     $end->setTimezone($utc);
     $endTs = Phprojekt_Converter_Time::utcToUser($end->format('Y-m-d H:i:s'));
     $end = new Datetime('@' . $endTs);
     if ($start->diff($end)->invert) {
         throw new Sabre_DAV_Exception_BadRequest('Start must be before End');
     }
     $this->_timecard->startDatetime = $start->format('Y-m-d H:i:s');
     if ($start->format('z') == $end->format('z')) {
         // Same day
         $this->_timecard->endTime = $end->format('H:i:s');
     } else {
         $this->_timecard->endTime = '23:59:00';
     }
 }
Beispiel #20
0
 /**
  * Validate the date range
  *
  * @throws Exception
  * @param DateTime $startdate
  * @param DateTime $enddate
  * @return bool
  */
 protected function validateDaterange(\Datetime $startdate, \Datetime $enddate)
 {
     // start date has to be before end date
     if ($startdate > $enddate) {
         throw new \Exception('Start date has to be before end date');
     }
     // start and end date should not be more than 2 weeks apart
     $diff = $startdate->diff($enddate, true);
     if ($diff->format('%a') > 14) {
         throw new \Exception('Period can not be longer than 2 weeks');
     }
     return true;
 }
Beispiel #21
0
function print_content2($checkindate, $locposttext)
{
    $ret = get_content($checkindate, $locposttext);
    $cntr = 0;
    $ajax = '<table><tr class="daterow">';
    $checkindate_mysql = implode('-', array_reverse(explode('/', "{$checkindate}")));
    # Convert to YYYY-MM-DD.
    for ($i = -3; $i < 4; $i++) {
        # Dates.
        // Check in date should not be less than three days from current date
        $i2 = $i + 3;
        $inthreedays = new Datetime("+ {$i2} days", new DateTimeZone('Europe/London'));
        $dayofweek = new DateTime("{$checkindate_mysql} {$i} days", new DateTimeZone('Europe/London'));
        $diff = $inthreedays->diff($dayofweek);
        if ($diff->format('%R%a') <= 0) {
            $dayofweek = $inthreedays;
        }
        // End if.
        $ajax .= '<th>' . substr($dayofweek->format('D '), 0, 1) . ' ' . $dayofweek->format('d') . '</th>';
        #
    }
    // End for.
    $ajax .= '</tr>';
    foreach ($ret as $test => $test2) {
        if ($cntr < 8) {
            # First location.
            if ($cntr == 0) {
                $ajax .= "<tr><th colspan=\"7\">{$test2}</th></tr>";
            }
            # Location.
            if ($cntr > 0 && $cntr < 7) {
                $ajax .= print_amount($test2);
            }
            if ($cntr == 7) {
                # Get second location.
                $test3 = $test2;
                list($lastamount, $secondlocation) = explode('&nbsp;', $test3);
                $ajax .= print_amount($lastamount) . '</tr>';
            }
            // End if first location.
        } else {
            if ($cntr < 15) {
                # Location #2
                list($ajax2, $nextlocation) = get_row(15, $cntr, $secondlocation, $test2);
                $ajax .= $ajax2;
            } else {
                if ($cntr < 22) {
                    # Location #3
                    list($ajax2, $nextlocation) = get_row(22, $cntr, $nextlocation, $test2);
                    $ajax .= $ajax2;
                } else {
                    if ($cntr < 29) {
                        # Location #4
                        list($ajax2, $nextlocation) = get_row(29, $cntr, $nextlocation, $test2);
                        $ajax .= $ajax2;
                    } else {
                        if ($cntr < 36) {
                            # Location #5
                            list($ajax2, $nextlocation) = get_row(36, $cntr, $nextlocation, $test2);
                            $ajax .= $ajax2;
                        } else {
                            if ($cntr < 43) {
                                # Location #6
                                list($ajax2, $nextlocation) = get_row(43, $cntr, $nextlocation, $test2);
                                $ajax .= $ajax2;
                            } else {
                                if ($cntr < 50) {
                                    # Location #7
                                    list($ajax2, $nextlocation) = get_row(50, $cntr, $nextlocation, $test2);
                                    $ajax .= $ajax2;
                                } else {
                                    if ($cntr < 57) {
                                        # Location #8
                                        list($ajax2, $nextlocation) = get_row(57, $cntr, $nextlocation, $test2);
                                        $ajax .= $ajax2;
                                    } else {
                                        if ($cntr < 64) {
                                            # Location #9
                                            list($ajax2, $nextlocation) = get_row(64, $cntr, $nextlocation, $test2);
                                            $ajax .= $ajax2;
                                        } else {
                                            if ($cntr < 71) {
                                                # Location #10
                                                list($ajax2, $nextlocation) = get_row(71, $cntr, $nextlocation, $test2);
                                                $ajax .= $ajax2;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        // End if
        $cntr++;
    }
    // End foreach.
    $ajax .= '</table>';
    return "{$checkindate}==||=={$locposttext}==||==" . $ajax;
    # Output to handle via ajax.
}
 protected function getScheduleDay()
 {
     $scheduleDay = new Datetime($this->StartDate . ' ' . $this->StartTime);
     $now = new Datetime(SS_Datetime::now()->Format(DateTime::ATOM));
     // make sure that the 'day' we start looking from is close to 'now' so our
     // loops don't work through days that don't matter
     if (!$this->day && $now > $scheduleDay) {
         $diff = $now->diff($scheduleDay)->format("%r%a");
         $this->day = abs($diff);
     }
     $scheduleDay->add(new DateInterval("P{$this->day}D"));
     return $scheduleDay->format('Y-m-d');
 }
 /**
  * Get the offset of the updated on time from the provided one.
  *
  * @param \Datetime $from
  *
  * @return bool|\DateInterval
  */
 public function getUpdatedOnOffset(\Datetime $from)
 {
     return $this->updated_on->diff($from);
 }
 /**
  * Set variables up before form is built based on participant ID from URL
  *
  * @return void
  */
 public function preProcess()
 {
     $config = CRM_Core_Config::singleton();
     $session = CRM_Core_Session::singleton();
     $this->_userContext = $session->readUserContext();
     $participant = $values = array();
     $this->_participant_id = CRM_Utils_Request::retrieve('pid', 'Positive', $this, FALSE, NULL, 'REQUEST');
     $params = array('id' => $this->_participant_id);
     $this->_participant = CRM_Event_BAO_Participant::getValues($params, $values, $participant);
     $this->_part_values = $values[$this->_participant_id];
     $this->set('values', $this->_part_values);
     //fetch Event by event_id, verify that this event can still be xferred/cancelled
     $this->_event_id = $this->_part_values['event_id'];
     $url = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_event_id}&noFullMsg=true");
     $this->_contact_id = $this->_part_values['participant_contact_id'];
     $this->assign('action', $this->_action);
     if ($this->_participant_id) {
         $this->assign('participantId', $this->_participant_id);
     }
     $event = array();
     $daoName = 'title';
     $this->_event_title = CRM_Event_BAO_Event::getFieldValue('CRM_Event_DAO_Event', $this->_event_id, $daoName);
     $daoName = 'start_date';
     $this->_event_start_date = CRM_Event_BAO_Event::getFieldValue('CRM_Event_DAO_Event', $this->_event_id, $daoName);
     list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contact_id);
     $this->_contact_name = $displayName;
     $this->_contact_email = $email;
     $details = array();
     $details = CRM_Event_BAO_Participant::participantDetails($this->_participant_id);
     $optionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'participant_role', 'id', 'name');
     $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_participant_id, 'contribution_id', 'participant_id');
     $this->assign('contributionId', $contributionId);
     $query = "\n      SELECT cpst.name as status, cov.name as role, cp.fee_level, cp.fee_amount, cp.register_date, cp.status_id\n      FROM civicrm_participant cp\n      LEFT JOIN civicrm_participant_status_type cpst ON cpst.id = cp.status_id\n      LEFT JOIN civicrm_option_value cov ON cov.value = cp.role_id and cov.option_group_id = {$optionGroupId}\n      WHERE cp.id = {$this->_participant_id}";
     $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
     while ($dao->fetch()) {
         $details['status'] = $dao->status;
         $details['role'] = $dao->role;
         $details['fee_level'] = $dao->fee_level;
         $details['fee_amount'] = $dao->fee_amount;
         $details['register_date'] = $dao->register_date;
     }
     //verify participant status is still Registered
     if ($details['status'] != "Registered") {
         $status = "You are no longer registered for " . $this->_event_title;
         CRM_Core_Session::setStatus($status, ts('Event status error.'), 'alert');
         CRM_Utils_System::redirect($url);
     }
     $query = "select start_date as start, selfcancelxfer_time as time from civicrm_event where id = " . $this->_event_id;
     $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
     while ($dao->fetch()) {
         $time_limit = $dao->time;
         $start_date = $dao->start;
     }
     $start_time = new Datetime($start_date);
     $timenow = new Datetime();
     if (!empty($start_time) && $start_time < $timenow) {
         $status = ts("The event has been started, cannot transfer or cancel this event");
         $session->setStatus($status, ts('Oops.'), 'alert');
         CRM_Utils_System::redirect($url);
     }
     if (!empty($time_limit) && $time_limit > 0) {
         $interval = $timenow->diff($start_time);
         $days = $interval->format('%d');
         $hours = $interval->format('%h');
         if ($hours <= $time_limit && $days < 1) {
             $status = ts("Less than %1 hours to start time, cannot transfer or cancel this event", array(1 => $time_limit));
             $session->setStatus($status, ts('Oops.'), 'alert');
             CRM_Utils_System::redirect($url);
         }
     }
     $this->assign('details', $details);
     $this->selfsvcupdateUrl = CRM_Utils_System::url('civicrm/event/selfsvcupdate', "reset=1&id={$this->_participant_id}&id=0");
     $this->selfsvcupdateText = ts('Update');
     $this->selfsvcupdateButtonText = ts('Update');
     // Based on those ids retrieve event and verify it is eligible
     // for self update (event.start_date > today, event can be 'self_updated'
     // retrieve contact name and email, and let user verify his/her identity
 }
Beispiel #25
0
 /**
  * Retorna a diferenca, em minutos, entre dateTime1 - dateTime2, podendo esta diferenca ser negativa ou positiva
  * 
  * @author Silas dos Santos
  * @version 17 AGO 2012
  * @since 17 AGO 2012 - Silas dos Santos / Desenvolvimento
  * 
  * @param string $dateTime1 no formato Y/m/d hh:mm:ss
  * @param string $dateTime2 no formato Y/m/d hh:mm:ss
  * 
  * @return int
  */
 public static function diffDateTimeMinutes($dateTime1, $dateTime2)
 {
     $date1 = new Datetime($dateTime1);
     $date2 = new Datetime($dateTime2);
     $diff = $date1->diff($date2);
     // 8766 horas no ano
     $diff->y = $diff->y * 8766 * 60;
     // anos para minutos
     $month = $diff->m / 12 * 8766 * 60;
     // meses para minutos
     $diff->d = $diff->d * 24 * 60;
     // dias para minutos
     $diff->h = $diff->h * 60;
     // horas para minutos
     $sec = (double) $diff->s / 60;
     // segundo para minutos
     $tempo = $diff->y + $month + $diff->d + $diff->h + $diff->i + $sec;
     $tempo *= $diff->invert == true ? -1 : 1;
     return $tempo;
 }