Esempio n. 1
0
 /**
  * @group shopobjects
  */
 function testCreateDateAsString()
 {
     // GIVEN
     $validString = "2016-10-25T14:56:18.000Z";
     // WHEN
     $date = new Date($validString);
     // THEN
     $this->assertFalse($date->error());
     $this->assertEquals($date->getTimestamp(), 1477407378);
     $this->assertEquals($date->asReadable(), "2016-10-25T14:56:18.000Z");
 }
 /**
  * loads info about the first day of log
  * 
  * @return object
  */
 function loadMinDay()
 {
     $firstDate = getDateFromTimestamp(time());
     $db =& Db::getInstance();
     if (!$db->isReady() || !$db->areAllTablesInstalled()) {
         $this->minDay = new Date($firstDate);
         return false;
     }
     $siteFirstDate = array();
     $fileAdress = INCLUDE_PATH . "/config/site_first_date.php";
     if (is_file($fileAdress)) {
         require $fileAdress;
     }
     if (!isset($siteFirstDate[$this->id])) {
         $r = query("SELECT date1\n\t\t\t\t\t\tFROM " . T_ARCHIVES . "\n\t\t\t\t\t\tWHERE period = " . DB_ARCHIVES_PERIOD_DAY . "\n\t\t\t\t  \t\tAND idsite = " . $this->getId() . "\n\t\t\t\t\t\tORDER BY date1 ASC\n\t\t\t\t\t\tLIMIT 1\n\t\t\t\t\t\t");
         if (mysql_num_rows($r) === 0) {
             $r2 = query("SELECT server_date" . " FROM " . T_VISIT . "\n\t\t\t\t  WHERE idsite = " . $this->getId() . " LIMIT 1");
             if (mysql_num_rows($r2) === 0) {
                 if (!isset($GLOBALS['sitePrinted'][$this->id])) {
                     //print($GLOBALS['lang']['generique_aucune_visite_bdd'] .
                     //		"<br><b>Site: ".$this->getName()." (id=".$this->id.")</b><br><br>");
                     $GLOBALS['sitePrinted'][$this->id] = true;
                 }
             } else {
                 $l = mysql_fetch_assoc($r2);
                 $firstDate = $l['server_date'];
             }
         } else {
             $l = mysql_fetch_assoc($r);
             $firstDate = $l['date1'];
         }
         $o_firstDate = new Date($firstDate);
         if ($o_firstDate->getTimestamp() > time()) {
             $firstDate = getDateFromTimestamp(time());
         }
         $siteFirstDate[$this->id] = $firstDate;
         // save new info in config file
         saveConfigFile($fileAdress, $siteFirstDate, 'siteFirstDate');
     } else {
         $firstDate = $siteFirstDate[$this->id];
     }
     $this->minDay = new Date($firstDate);
     return true;
 }
/**
 * returns an array containing the days between the 2 days
 * 
 * @param string $s_date1
 * @param string $s_date2
 * 
 * @return array 
 */
function getDaysBetween($s_date1, $s_date2)
{
    $date1 = new Date($s_date1);
    $date2 = new Date($s_date2);
    $ts1 = $date1->getTimestamp();
    $ts2 = $date2->getTimestamp();
    //print("(".$date1->get()." > ".$date2->get().")");
    if ($ts1 > $ts2) {
        trigger_error("For the period statistic, Day 1 is AFTER Day 2 (" . $date1->get() . " > " . $date2->get() . "). It's impossible, sorry.", E_USER_ERROR);
    }
    $return = array();
    while ($ts1 <= $ts2) {
        $return[] = getDateFromTimestamp($ts1);
        $ts1 = mktime(23, 59, 59, date("m", $ts1), date("d", $ts1) + 1, date("Y", $ts1));
    }
    return $return;
}
 /**
  * Actualiza los datos de la tarea duplicada.
  * @version 26-02-09
  * @author Ana Martín
  */
 protected function updateDuplicarTareaFromRequest()
 {
     $tarea = $this->getRequestParameter('tarea');
     $value = sfContext::getInstance()->getI18N()->getTimestampForCulture($tarea['fecha_inicio']['date'], $this->getUser()->getCulture());
     $mi_date = new Date($value);
     $mi_date->setHours(isset($tarea['fecha_inicio']['hour']) ? $tarea['fecha_inicio']['hour'] : 0);
     $mi_date->setMinutes(isset($tarea['fecha_inicio']['minute']) ? $tarea['fecha_inicio']['minute'] : 0);
     $this->nueva_tarea->setFechaInicio($mi_date->getTimestamp());
     if (isset($tarea['fecha_vencimiento'])) {
         $value = sfContext::getInstance()->getI18N()->getTimestampForCulture($tarea['fecha_vencimiento']['date'], $this->getUser()->getCulture());
         $mi_date = new Date($value);
         $mi_date->setHours(isset($tarea['fecha_vencimiento']['hour']) ? $tarea['fecha_vencimiento']['hour'] : 0);
         $mi_date->setMinutes(isset($tarea['fecha_vencimiento']['minute']) ? $tarea['fecha_vencimiento']['minute'] : 0);
         $this->nueva_tarea->setFechaVencimiento($mi_date->getTimestamp());
     } else {
         if (isset($tarea['duracion'])) {
             $duracion_minutos = $tarea['duracion'];
             $fecha_vencimiento = mktime($mi_date->getHours(), $mi_date->getMinutes() + $duracion_minutos, 0, $mi_date->getMonth(), $mi_date->getDay(), $mi_date->getYear());
             $this->nueva_tarea->setFechaVencimiento(date('Y-m-d H:i', $fecha_vencimiento));
         } else {
             $this->nueva_tarea->setFechaVencimiento($mi_date->getTimestamp());
         }
     }
     if (isset($tarea['id_usuario'])) {
         $this->nueva_tarea->setIdUsuario($tarea['id_usuario']);
     }
 }
Esempio n. 5
0
             $valor_fecha = $fecha->getTimestamp();
             break;
         case 5:
             $fecha = new Date();
             $fecha->setLastDayOfMonth();
             $valor_fecha = $fecha->getTimestamp();
             break;
         case 6:
             $fecha = new Date();
             $fecha->setFirstDayOfYear();
             $valor_fecha = $fecha->getTimestamp();
             break;
         case 7:
             $fecha = new Date();
             $fecha->setLastDayOfYear();
             $valor_fecha = $fecha->getTimestamp();
             break;
     }
 } else {
     $valor_fecha = $valor->getFecha();
 }
 $value .= input_date_tag($control_name, $valor_fecha, array('control_name' => $control_name, 'rich' => true, 'calendar_button_img' => '/images/icons/date.png'));
 if ($campo->getMostrarEnPadre()) {
     use_helper('Javascript');
     if ($valor == null) {
         $valor_sino = false;
     } else {
         $valor_sino = $valor->getSiNo();
     }
     $value .= " " . __("Configurar alarma") . ": " . checkbox_tag($campo_name . '[tiene_alarma]', '', $valor_sino, array('control_name' => $campo_name . '[tiene_alarma]', 'onclick' => 'if (this.checked) document.getElementById(\'capa_campo_' . $campo->getIdCampo() . '\').style.display = \'block\'; else document.getElementById(\'capa_campo_' . $campo->getIdCampo() . '\').style.display = \'none\';'));
     if (!$valor_sino) {
             $smarty->display('error.tpl');
             return;
         }
         //check password meets standards
         if (!preg_match("/((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9\\s]).{8,})/", $password)) {
             $smarty->display('error.tpl');
             return;
         }
         $transaction = new Transaction(new MySqlDB());
         $transaction->start();
         $user = Factory::createView(new UserKey());
         $date = new Date();
         $user->setUsername($username);
         $user->setPassword($password);
         $user->setActive(true);
         $user->setCreatedDate($date->getTimestamp());
         $user->setLastLoginDate($date->getTimestamp());
         $user->setNumberOfAttempts(1);
         $user->setFirstName($firstname);
         $user->setLastName($lastname);
         $transaction->commit();
         $access = new Access();
         if ($access->authenticate($username, $password)) {
             header("Location: dashboard.php");
             exit;
         } else {
             throw new Exception("Unable to login after creating account.");
         }
     }
 } catch (AccessDeniedException $e) {
     header('HTTP/1.1 401 Access Denied');
function getTemplateArrayCalendar($o_minDay, $s_date, $period)
{
    // today
    $today = new Date(getDateFromTimestamp(time()));
    $tsToday = $today->getTimestamp();
    // date asked for statistics
    $dateAsked = new Date($s_date);
    // used for going througt the month
    $date = new Date($s_date);
    $month = $date->getMonth();
    $year = $date->getYear();
    $prefixDay = $year . "-" . $month . "-";
    $date->setDate($prefixDay . '01');
    $week = $date->getWeek();
    $day = 1;
    $ts = $date->getTimestamp();
    while ($date->getMonth() == $month) {
        // day exists in stats, isn't it too old or in the future ?
        if ($date->getTimestamp() >= $o_minDay->getTimestamp() && $date->getTimestamp() <= $tsToday) {
            $exists = 1;
        } else {
            $exists = 0;
        }
        // day selected for stats view ?
        if ($period == DB_ARCHIVES_PERIOD_DAY && $date->getDay() == $dateAsked->getDay() || $period == DB_ARCHIVES_PERIOD_WEEK && $date->getWeek() == $dateAsked->getWeek() || $period == DB_ARCHIVES_PERIOD_MONTH || $period == DB_ARCHIVES_PERIOD_YEAR) {
            $selected = 1;
        } else {
            $selected = 0;
        }
        $weekNo = $date->getWeek() - $week;
        if (defined('MONDAY_FIRST') && MONDAY_FIRST == 'no' && date("w", $ts) == 0) {
            $weekNo += 1;
        }
        $dayOfWeek = (int) (!defined('MONDAY_FIRST') || MONDAY_FIRST == 'yes' ? date("w", $ts) == 0 ? 6 : date("w", $ts) - 1 : date("w", $ts));
        $return[$weekNo][$dayOfWeek] = array('day' => substr($date->getDay(), 0, 1) === '0' ? substr($date->getDay(), 1, 2) : $date->getDay(), 'date' => $date->get(), 'exists' => $exists, 'selected' => $selected);
        $date->addDays(1);
        //these 2 lines useless? to check
        $ts = $date->getTimeStamp();
        $date->setTimestamp($ts);
    }
    foreach ($return as $key => $r) {
        $row =& $return[$key];
        for ($i = 0; $i < 7; $i++) {
            if (!isset($row[$i])) {
                $row[$i] = "-";
            }
        }
        ksort($row);
    }
    return $return;
}
 /**
  * Big job, assign all vars... 
  * Too much vars, those tasks should be splitted into more atomic methods
  * 
  * @param object o_site
  * @param object o_data
  * @param object request
  * 
  * @return void
  */
 function processDatas(&$o_site, &$o_data, $request = null)
 {
     $ctrl =& ApplicationController::getInstance();
     if (is_null($request)) {
         $o_request =& $ctrl->getRequest();
     } else {
         $o_request =& $request;
     }
     $o_lang =& $ctrl->getLang();
     if (!is_a($o_data, "DataModel")) {
         //trigger_error("\$o_data is not an object DataModel! Maybe its because this is not a
         //ViewModule and so you don't really need DataModel, you have to do without it...");
     }
     printTime('Begin Smarty display');
     /*
      * @todo , extact this from method!!
      */
     $ajax_views = array("common/data_array_details.tpl", "common/data_array_interest.tpl", "common/data_array.tpl");
     // Add path to theme
     $this->assign("PMV_THEME", $this->template_dir[0]);
     $this->assign("PMV_THEME_DEFAULT", $this->template_dir[1]);
     $this->assign("PMV_STAT_ID_SITE", PMV_STAT_ID_SITE);
     $this->assign("PMV_STAT_SAVE_USER", PMV_STAT_SAVE_USER);
     // case we load a subtemplate with AJAX
     if (in_array($this->template, $ajax_views)) {
         $this->mainTemplate = $this->template;
     } elseif ($o_request->isCategoryZoom()) {
         $this->mainTemplate = "common/viewpages_details.tpl";
         //	printDebug($this->get_template_vars( "zoom"));
         $t = $this->get_template_vars("zoomsorted");
         //printDebug($t);
         $this->assign("zoom", $t);
     } else {
         // case there are no visit for this period
         if (is_a($o_data, "DataModel") && $o_request->getModuleName() !== 'view_sites_summary' && $o_data->getContent('nb_vis') == 0) {
             $this->setTemplate("common/error.tpl");
             if ($o_request->getModuleName() !== 'view_visits_rss') {
                 $this->assign("error_message_bis", sprintf($GLOBALS['lang']['generique_help_novisits'], "<a href='index.php?mod=admin_site_javascript_code'>", "</a>"));
             }
         }
         // assign period, used in pages table to print the period text
         $this->assign("period", $o_request->getPeriod());
         if (is_a($o_site, 'Site')) {
             // compute and assign calendar
             $o_dasked = new Date($o_request->getDate());
             $o_minDay = $o_site->getMinDay();
             if ($o_dasked->getTimestamp() < $o_minDay->getTimestamp()) {
                 $s_dateAsked = $o_minDay->get();
             } else {
                 $s_dateAsked = $o_dasked->get();
             }
             $a_calendar = getTemplateArrayCalendar($o_minDay, $s_dateAsked, $o_request->getPeriod());
             $this->assign("calendar", $a_calendar);
             // first day letters for calendar first line
             if (!defined('MONDAY_FIRST') || MONDAY_FIRST == 'yes') {
                 $dayFirstLetter = $GLOBALS['lang']['calendrier_jours'];
             } else {
                 for ($i = 0; $i < 7; $i++) {
                     $dayFirstLetter[$i == 6 ? 0 : $i + 1] = $GLOBALS['lang']['calendrier_jours'][$i];
                 }
                 ksort($dayFirstLetter);
             }
             $this->assign("day_first_letter", $dayFirstLetter);
             // litteral date for display below the menu
             $this->assign("date_litteral", getLiteralDate($o_request->getPeriod(), $s_dateAsked));
             $this->assign("date_ask", $s_dateAsked);
             // months info for SELECT months generation
             $months_info = getTemplateArrayMonth($o_site->getMinDay(), $o_request);
             $this->assign("months_available", $months_info[0]);
             $this->assign("month_selected", $months_info[1]);
             // sites info for SELECT sites generation
             $this->assign("sites_view_available", $o_site->getAllowedSites('view'));
             $this->assign("sites_admin_available", $o_site->getAllowedSites('admin'));
             $this->assign("site_selected", $o_request->getSiteId(false));
             $this->assign("site_selected_name", $o_site->getName());
             // pdf list
             $pdfConf = new PdfConfigDb($o_request->getSiteId(false), true);
             $this->assign("site_pdf_list", $pdfConf->getListPdf());
         }
         // langs info for SELECT langs generation
         $this->assign("langs_available", $o_lang->getArrayLangs());
         $this->assign("lang_selected", $o_lang->getFileName());
         // require menu definition and assign for menu display
         $menu = array();
         if (is_file(INCLUDE_PATH . '/themes/' . THEME . '/datas/MenuDefinition.php')) {
             require INCLUDE_PATH . '/themes/' . THEME . '/datas/MenuDefinition.php';
         } else {
             require INCLUDE_PATH . '/themes/' . THEME_DEFAULT . '/datas/MenuDefinition.php';
         }
         //require INCLUDE_PATH . "/core/include/MenuDefinition.php";
         // Add plugin menus
         $installedPlugin = new PmvConfig("plugin.php", false);
         foreach ($installedPlugin->content as $key => $value) {
             // Load lang for plugin
             if (isset($value['langPath']) && $value['langPath'] != "") {
                 Lang::addPluginLangFile($key . "/" . $value['langPath'], $value['defaultLang']);
             }
             if ($value['type'] == "menu") {
                 // Set plugin in menu list
                 $menuModName = $value['menuModName'];
                 for ($i = 0; $i < count($menu); $i++) {
                     if ($menu[$i]['modname'] == $menuModName) {
                         $menu[$i]['plugins'][$key] = $value;
                     }
                 }
             }
         }
         $this->assign("menu", $menu);
         // To select menu
         $this->assign("page", $o_request->getModuleName());
     }
     // interest sorting info
     if (is_a($o_data, "DataModel")) {
         //printDebug($o_request->getArrayInfoSort( $o_data->arraySumInfo));
         $this->assign("info_sort", $o_request->getArrayInfoSort($o_data->arraySumInfo));
     }
     /**
      * display a previous assigned template variable
      */
     //printDebug($this->get_template_vars( "countries"));
     // url with main variables
     $this->assign("url", $o_request->getUrl());
     // current exact url
     $this->assign("url_current", $o_request->getCurrentUrl());
     // url without offset info
     $this->assign("url_offset", $o_request->getUrl('offset'));
     // url without interest info
     $this->assign("url_a_int_sort", $o_request->getUrl('a_int_sort'));
     $this->assign("url_a_exit_sort", $o_request->getUrl('a_exit_sort'));
     $this->assign("url_a_entry_sort", $o_request->getUrl('a_entry_sort'));
     // url without module
     $this->assign("url_mod", $o_request->getUrl(array('mod', 'a_int_sort')));
     // url without site
     $this->assign("url_site", $o_request->getUrl('site'));
     // url without date
     $this->assign("url_date", $o_request->getUrl('date'));
     // url without period
     $this->assign("url_period", $o_request->getUrl('period'));
     // url without lang
     //		$this->assign("url_lang", Request::getCurrentCompleteUrl());
     $this->assign("url_lang", $o_request->getUrl('lang'));
     // url without mod & site, used for summary SELECT choice (because we change mod=viewsummary and site=-1)
     $this->assign("url_mod_site", $o_request->getUrl(array('mod', 'a_int_sort', 'site')));
     $this->assign("url_pages_details", $o_request->getUrl('mod_sort_means_details'));
     // if there is an "error" message to print in red
     if (isset($GLOBALS['content_message_tpl'])) {
         // assign the message
         $this->assign("content_message", $GLOBALS['content_message_tpl']);
         // and the content template, error.tpl which will print in red the message
         $this->setTemplate('common/error.tpl');
     }
     // assign an header message (archive ok, archive temp, etc.)
     $this->assign("header_message", $GLOBALS['header_message_tpl']);
     // assign an error header message
     $this->assign("header_error_message", $GLOBALS['header_error_message_tpl']);
     // assign text direction info (rtl, ltr)
     $this->assign("dir", $GLOBALS['lang']['text_dir']);
     // assign footer info
     //$time =  getMicrotime()-$GLOBALS['time_start'];
     //$this->assign("generation_time", $time);
     //$this->assign("query_count", $GLOBALS['query_count']);
     // image dir
     //$this->assign("img_dir", DIR_IMG_THEMES);
     $this->assign("img_dir", $this->template_dir . "images/");
     // links for the documentation
     $this->assign("link_doc", array(HREF_DOC_OPEN, HREF_DOC_CLOSE));
     // phpmyvisites version to print in meta and footer
     $this->assign("PHPMV_VERSION", PHPMV_VERSION);
     $this->assign("PHP_VERSION_NEEDED", PHP_VERSION_NEEDED);
     $this->assign("PARAM_URL_NEWSLETTER", PARAM_URL_NEWSLETTER);
     $this->assign("PARAM_URL_PARTNER", PARAM_URL_PARTNER);
     //should we include internal stats in the application footer
     if (defined('INTERNAL_STATS') && INTERNAL_STATS == 1) {
         $this->assign('internal_stats', true);
     }
     $user =& User::getInstance();
     $this->assign('user_alias', $user->getAlias());
     $this->assign('user_login', $user->getLogin());
     $this->assign('user_is_su', $user->suPermission);
     $this->assign('user_is_admin_site', $user->isSiteAllowedAdmin($o_request->getSiteId(false)));
     $this->assign("rss_hash", $user->getRssHash());
     $this->assign('a_link_phpmv', array('<a class="bleu" link="web statistics" href="http://www.phpmyvisites.us/">', '</a>'));
     $this->assign("contentpage", $this->template);
     printTime('After Smarty pre computing');
 }
 function getLastArchives($n, $boolOnlyGetPeriodNMinus = 0, $dateTextType = DATE_NORMAL, $o_site = false)
 {
     //var_dump($this->archive->date->get());
     $date = new Date($this->archive->date->get());
     //var_dump($date->get());
     if ($o_site) {
         $o_siteToUse = $o_site;
     } else {
         $o_siteToUse = $this->archive->site;
     }
     $toArchive = array();
     switch ($this->archive->periodType) {
         case DB_ARCHIVES_PERIOD_DAY:
             $ts = $date->getTimestamp() + 86400;
             while (sizeof($toArchive) < $n) {
                 $toArchive[] = getDateFromTimestamp($ts -= 86400);
             }
             $typeDateDisplay = 2;
             $typeDateDisplayGraph = 8;
             $typeDateDisplayGraphLongAxis = 13;
             // only take N - x, only for page views comparisons
             if ($boolOnlyGetPeriodNMinus === 1) {
                 $date0 = $toArchive[0];
                 $date1 = $toArchive[7];
                 $date2 = $toArchive[14];
                 unset($toArchive);
                 $toArchive[] = $date0;
                 $toArchive[] = $date1;
                 $toArchive[] = $date2;
                 $typeDateDisplay = 7;
                 //print("date1 $date1 date2 $date2 ");
             }
             break;
         case DB_ARCHIVES_PERIOD_WEEK:
             $ts = $date->getTimestamp();
             $ts += 86400 * 7;
             while (sizeof($toArchive) < $n) {
                 $toArchive[] = getDateFromTimestamp($ts -= 86400 * 7);
             }
             $typeDateDisplay = 6;
             $typeDateDisplayGraph = 6;
             $typeDateDisplayGraphLongAxis = 13;
             break;
         case DB_ARCHIVES_PERIOD_MONTH:
             $s_date1 = getDateFromTimestamp(mktime(23, 59, 59, $date->getMonth() - $n % 12, 15, $date->getYear() - floor($n / 12)));
             $s_date2 = $date->get();
             $toArchive = array_reverse(getDayOfMonthBetween($s_date1, $s_date2));
             $typeDateDisplay = 5;
             $typeDateDisplayGraph = 10;
             $typeDateDisplayGraphLongAxis = 10;
             break;
         case DB_ARCHIVES_PERIOD_YEAR:
             for ($i = 0; $i < $n; $i++) {
                 $a = $date->getYear() - $i;
                 $toArchive[] = $a . "-01-01";
             }
             $typeDateDisplay = 11;
             $typeDateDisplayGraph = 12;
             break;
     }
     //var_dump($this->archive->date->get());
     $return = array();
     foreach ($toArchive as $dateToArchive) {
         //print("boucle :");
         // if day, and IF current date asked is today, then take current archive
         if ($dateToArchive == $this->archive->date->get() && $this->archive->periodType === DB_ARCHIVES_PERIOD_DAY && $o_siteToUse->getId() === $this->archive->site->getId()) {
             $a = $this->archive;
             // erreur possible ici ?
         } else {
             $a = $this->getArchive($o_siteToUse, $dateToArchive, $this->archive->periodType);
         }
         if ($dateTextType == DATE_GRAPH) {
             $dateToDisplay = getDateDisplay($typeDateDisplayGraph, new Date($dateToArchive));
             $dateComputed = getDateDisplay($typeDateDisplayGraph, $a->date);
         } else {
             if ($dateTextType == DATE_NORMAL) {
                 $dateToDisplay = getDateDisplay($typeDateDisplay, new Date($dateToArchive));
                 $dateComputed = getDateDisplay($typeDateDisplay, $a->date);
             } else {
                 if ($dateTextType == DATE_GRAPH_LONG_AXIS) {
                     $dateToDisplay = getDateDisplay($typeDateDisplayGraphLongAxis, new Date($dateToArchive));
                     $dateComputed = getDateDisplay($typeDateDisplayGraphLongAxis, $a->date);
                 }
             }
         }
         if ($this->archive->periodType === DB_ARCHIVES_PERIOD_WEEK) {
             $firstDayOfWeek = new Date(getFirstDayOfWeek(new Date($dateToArchive)));
             $minDay = $o_siteToUse->getMinDay();
             if ($firstDayOfWeek->getTimestamp() >= $minDay->getTimestamp()) {
                 $dateToDisplay = getDateDisplay($typeDateDisplay, $firstDayOfWeek);
             }
         }
         if ($dateComputed == $dateToDisplay) {
             //				print("$dateToDisplay is correctly computed ($dateComputed)<br>");
             $return[$dateComputed] = $a;
         } else {
             //				print("$dateToDisplay is not correctly computed ($dateComputed) ==> empty archive<br>");
             $return[$dateToDisplay] = $this->getEmptyArchive($o_siteToUse, $dateToArchive, $this->archive->periodType);
         }
     }
     //print("\n\n");exit;
     return $return;
 }
Esempio n. 10
0
 /**
  * @param Date $date
  * @return int a timestamp
  */
 public function exportDateWithTime($date)
 {
     return $this->exportInteger($date->getTimestamp());
 }
Esempio n. 11
0
File: Cms.php Progetto: schpill/thin
 public static function dispatch()
 {
     $query = dm('page');
     $url = substr($_SERVER['REQUEST_URI'], 1);
     $homeUrl = null !== static::getOption('home_page_url') ? static::getOption('home_page_url') : 'home';
     $url = !strlen($url) ? $homeUrl : $url;
     if ('home' == $url) {
         container()->setCmsIsHomePage(true);
     } else {
         container()->setCmsIsHomePage(false);
     }
     $pages = static::getPages();
     $routes = array();
     if (count($pages)) {
         foreach ($pages as $pageTmp) {
             $routes[$pageTmp->getUrl()] = $pageTmp;
         }
     }
     $found = Arrays::exists($url, $routes);
     if (false === $found) {
         $found = static::match($routes);
     }
     if (true === $found) {
         $page = $routes[$url];
         $displaymode = Inflector::lower($page->getDisplaymode()->getName());
         $datePub = $page->getDateIn();
         $dateDepub = $page->getDateOut();
         if (strlen($datePub)) {
             list($d, $m, $y) = explode('-', $datePub, 3);
             $datePub = "{$y}-{$m}-{$d}";
             $datePub = new Date($datePub);
         }
         if (strlen($dateDepub)) {
             list($d, $m, $y) = explode('-', $dateDepub, 3);
             $dateDepub = "{$y}-{$m}-{$d}";
             $dateDepub = new Date($dateDepub);
         }
         $now = time();
         if ('online' == $displaymode) {
             container()->setCmsPage($page);
         } elseif ('offline' == $displaymode || 'brouillon' == $displaymode) {
             container()->setCmsPage(404);
         } else {
             container()->setCmsPage($displaymode);
         }
         if ($datePub instanceof Date) {
             $ts = $datePub->getTimestamp();
             if ($ts > $now) {
                 container()->setCmsPage(404);
             }
         }
         if ($dateDepub instanceof Date) {
             $ts = $dateDepub->getTimestamp();
             if ($ts < $now) {
                 container()->setCmsPage(404);
             }
         }
     } else {
         container()->setCmsPage(404);
     }
 }
Esempio n. 12
0
 /**
  * Get a relative date string, e.g., 3 days ago.
  *
  * @param  FTV_Date  $compare
  * @return string
  */
 public function getRelativeDate($compare = null)
 {
     if (!$compare) {
         $compare = new Date(null, $this->getTimezone());
     }
     $units = array('second', 'minute', 'hour', 'day', 'week', 'month', 'year');
     $values = array(60, 60, 24, 7, 4.35, 12);
     // Get the difference between the two timestamps. We'll use this to calculate the actual time remaining.
     $difference = abs($compare->getTimestamp() - $this->getTimestamp());
     for ($i = 0; $i < count($values) && $difference >= $values[$i]; $i++) {
         $difference = $difference / $values[$i];
     }
     // Round the difference to the nearest whole number.
     $difference = round($difference);
     if ($compare->getTimestamp() < $this->getTimestamp()) {
         $suffix = 'from now';
     } else {
         $suffix = 'ago';
     }
     // Get the unit of time we are measuring. We'll then check the difference, if it is not equal to exactly 1 then it's a multiple of the given unit so we'll append an 's'.
     $unit = $units[$i];
     if ($difference != 1) {
         $unit .= 's';
     }
     return $difference . ' ' . $unit . ' ' . $suffix;
 }
Esempio n. 13
0
 public function updateMensajeFromRequest()
 {
     $mensaje = $this->getRequestParameter('mensaje');
     if (isset($mensaje['asunto'])) {
         $this->mensaje->setAsunto($mensaje['asunto'] ? $mensaje['asunto'] : null);
     }
     if (isset($mensaje['cuerpo'])) {
         $this->mensaje->setCuerpo($mensaje['cuerpo'] ? $mensaje['cuerpo'] : null);
     }
     if (isset($mensaje['es_programado'])) {
         if (isset($mensaje['fecha']['date'])) {
             if ($mensaje['fecha']['date']) {
                 try {
                     $value = sfContext::getInstance()->getI18N()->getTimestampForCulture($mensaje['fecha']['date'], $this->getUser()->getCulture());
                     $mi_date = new Date($value);
                     $mi_date->setHours(isset($mensaje['fecha']['hour']) ? $mensaje['fecha']['hour'] : 0);
                     $mi_date->setMinutes(isset($mensaje['fecha']['minute']) ? $mensaje['fecha']['minute'] : 0);
                     $this->mensaje->setFecha($mi_date->getTimestamp());
                 } catch (sfException $e) {
                     // not a date
                 }
             } else {
                 $this->mensaje->setFecha(time());
             }
         }
     } else {
         $this->mensaje->setFecha(time());
     }
 }
function nombre_periodo($duracion_periodo_meses = 1, $numero_periodo = null, $anio = null)
{
    $resultado = null;
    if (isset($anio)) {
        if ($duracion_periodo_meses == 1) {
            if ($numero_periodo) {
                $mi_date = new Date();
                $mi_date->setMonth($numero_periodo);
                $mi_date->setYear($anio);
                $resultado = format_date($mi_date->getTimestamp(), 'MMMM yyyy');
            } else {
                $resultado = $anio;
            }
        } else {
            $lista_posiciones = array('1' => __('primer'), '2' => __('segundo'), '3' => __('tercer'), '4' => __('cuarto'), '5' => __('quinto'), '6' => __('sexto'));
            $tipos_periodo = CampoPeer::getTiposPeriodo();
            $periodo = __('%posicion% %periodo%', array('%posicion%' => isset($lista_posiciones[$numero_periodo]) ? $lista_posiciones[$numero_periodo] : '', '%periodo%' => isset($tipos_periodo[$duracion_periodo_meses]) ? $tipos_periodo[$duracion_periodo_meses] : ''));
            if (isset($numero_periodo) && $numero_periodo != '') {
                $resultado = __('%periodo% de %year%', array('%periodo%' => $periodo, '%year%' => $anio));
            } else {
                $resultado = $anio;
            }
        }
    }
    return $resultado;
}
Esempio n. 15
0
 protected function getFechaFromRequest($param_fecha, $param_horas = null, $param_minutos = null, $param_segundos = null)
 {
     $value = null;
     if (isset($param_fecha)) {
         if ($param_fecha) {
             try {
                 $timestamp_fecha = sfContext::getInstance()->getI18N()->getTimestampForCulture($param_fecha, $this->getUser()->getCulture());
                 $fecha = new Date($timestamp_fecha);
                 if (isset($param_horas)) {
                     $fecha->setHours($param_horas);
                 }
                 if (isset($param_minutos)) {
                     $fecha->setMinutes($param_minutos);
                 }
                 if (isset($param_segundos)) {
                     $fecha->setSeconds($param_segundos);
                 }
                 $value = $fecha->getTimestamp();
             } catch (sfException $e) {
                 //no es una fecha
                 $value = null;
             }
         }
     }
     return $value;
 }
Esempio n. 16
0
 public function testConstructingWithString()
 {
     $date = new Date('1983-07-04 12:30:00');
     return $this->assertEqual($date->getTimestamp(), 426166200);
 }