Exemplo n.º 1
0
function twig_localized_date_filter(Twig_Environment $env, $date, $dateFormat = 'medium', $timeFormat = 'medium', $locale = null, $timezone = null, $format = null, $calendar = 'gregorian')
{
    $date = twig_date_converter($env, $date, $timezone);
    $formatValues = array('none' => IntlDateFormatter::NONE, 'short' => IntlDateFormatter::SHORT, 'medium' => IntlDateFormatter::MEDIUM, 'long' => IntlDateFormatter::LONG, 'full' => IntlDateFormatter::FULL);
    $formatter = IntlDateFormatter::create($locale, $formatValues[$dateFormat], $formatValues[$timeFormat], PHP_VERSION_ID >= 50500 ? $date->getTimezone() : $date->getTimezone()->getName(), 'gregorian' === $calendar ? IntlDateFormatter::GREGORIAN : IntlDateFormatter::TRADITIONAL, $format);
    return $formatter->format($date->getTimestamp());
}
Exemplo n.º 2
0
function twig_localized_date_filter(Twig_Environment $env, $date, $dateFormat = 'medium', $timeFormat = 'medium', $locale = null, $timezone = null, $format = null)
{
    $date = twig_date_converter($env, $date, $timezone);
    $formatValues = array('none' => IntlDateFormatter::NONE, 'short' => IntlDateFormatter::SHORT, 'medium' => IntlDateFormatter::MEDIUM, 'long' => IntlDateFormatter::LONG, 'full' => IntlDateFormatter::FULL);
    $formatter = IntlDateFormatter::create($locale, $formatValues[$dateFormat], $formatValues[$timeFormat], $date->getTimezone()->getName(), IntlDateFormatter::GREGORIAN, $format);
    return $formatter->format($date->getTimestamp());
}
Exemplo n.º 3
0
 public function getAvailableTimes()
 {
     $holidays = $this->manager->getRepository(Holiday::class)->findAll();
     $result = array();
     $formatter = \IntlDateFormatter::create('fr_FR', \IntlDateFormatter::FULL, \IntlDateFormatter::NONE);
     $current = new \DateTime('+2 days');
     $max = new \DateTime('+3 weeks');
     while ($current < $max) {
         if ($this->isClosed($current, $holidays)) {
             continue;
         }
         $day = $current->format('N');
         $date = $formatter->format($current);
         if ($day == 6 || $day == 7) {
             $hours = $this->weekEndHours;
         } else {
             $hours = $this->workDayHours;
         }
         $vals = array_map(function ($val) use($date) {
             return $date . ' // ' . $val;
         }, $hours);
         $result[$date] = array_combine($vals, $vals);
         $current->modify('+1 day');
     }
     return $result;
 }
Exemplo n.º 4
0
 /**
  * {@inheritdoc}
  */
 public function buildView(SearchFieldView $view, FieldConfigInterface $config, array $options)
 {
     if (is_string($options['format'])) {
         $format = $options['format'];
     } else {
         $format = \IntlDateFormatter::create(\Locale::getDefault(), is_int($options['format']) ? $options['format'] : self::DEFAULT_FORMAT, \IntlDateFormatter::NONE, null, \IntlDateFormatter::GREGORIAN)->getPattern();
     }
     $view->vars['format'] = $format;
 }
 public function localedate($date, $dateFormat = 'medium', $timeFormat = 'medium', $locale = null)
 {
     $formatValues = array('none' => \IntlDateFormatter::NONE, 'short' => \IntlDateFormatter::SHORT, 'medium' => \IntlDateFormatter::MEDIUM, 'long' => \IntlDateFormatter::LONG, 'full' => \IntlDateFormatter::FULL);
     $formatter = \IntlDateFormatter::create($locale != null ? $locale : $this->translator->getLocale(), $formatValues[$dateFormat], $formatValues[$timeFormat]);
     if ($date instanceof \DateTime) {
         return $formatter->format($date);
     }
     return $formatter->format(new \DateTime($date));
 }
 /**
  * A date formatting filter for Twig, renders the date using the specified parameters.
  *
  * @param mixed  $date     Unix timestamp to format
  * @param string $locale   The locale
  * @param string $dateType The date type
  * @param string $timeType The time type
  * @param string $pattern  The pattern to use
  *
  * @return string
  */
 public static function localeDateFilter($date, $locale = "nl", $dateType = 'medium', $timeType = 'none', $pattern = null)
 {
     $values = array('none' => DateFormatter::NONE, 'short' => DateFormatter::SHORT, 'medium' => DateFormatter::MEDIUM, 'long' => DateFormatter::LONG, 'full' => DateFormatter::FULL);
     if (is_null($pattern)) {
         $dateFormatter = DateFormatter::create($locale, $values[$dateType], $values[$timeType], 'Europe/Brussels');
     } else {
         $dateFormatter = DateFormatter::create($locale, $values[$dateType], $values[$timeType], 'Europe/Brussels', DateFormatter::GREGORIAN, $pattern);
     }
     return $dateFormatter->format($date);
 }
Exemplo n.º 7
0
 public function testIntlDate()
 {
     $date = new \DateTime('2000-02-03 04:05', new \DateTimeZone('UTC'));
     $formatter1 = \IntlDateFormatter::create('en@calendar=islamic-umalqura', \IntlDateFormatter::FULL, \IntlDateFormatter::FULL, "Europe/Berlin", \IntlDateFormatter::TRADITIONAL);
     $formatter2 = \IntlDateFormatter::create('@calendar=islamic-civil', \IntlDateFormatter::FULL, \IntlDateFormatter::FULL, "Europe/Berlin", \IntlDateFormatter::TRADITIONAL);
     // TODO investigate failure, probably because of different ICU version
     //$this->assertEquals('AH 1420 Shawwal 27, Thu 05:05:00 GMT+01:00', $formatter1->format($date), 'islamic-umalqura' . self::INTLinfo());
     //$this->assertEquals('AH 1420 Shawwal 127, Thu 05:05:00 GMT+01:00', $formatter2->format($date), 'islamic-civil' .  self::INTLinfo('@calendar=islamic-civil'));
     $formatter = \IntlDateFormatter::create('@calendar=japanese', \IntlDateFormatter::FULL, \IntlDateFormatter::FULL, "Europe/Berlin", \IntlDateFormatter::TRADITIONAL);
     //$this->assertEquals('Heisei 12 M02 3, Thu 05:05:00 GMT+01:00', $formatter->format($date), 'islamic-civil' .  self::INTLinfo('@calendar=japanese'));
 }
Exemplo n.º 8
0
function twig_localized_date_filter($date, $dateFormat = 'medium', $timeFormat = 'medium', $locale = null)
{
    $formatValues = array('none' => IntlDateFormatter::NONE, 'short' => IntlDateFormatter::SHORT, 'medium' => IntlDateFormatter::MEDIUM, 'long' => IntlDateFormatter::LONG, 'full' => IntlDateFormatter::FULL);
    $formatter = IntlDateFormatter::create($locale !== null ? $locale : Locale::getDefault(), $formatValues[$dateFormat], $formatValues[$timeFormat]);
    if (!$date instanceof DateTime) {
        if (ctype_digit((string) $date)) {
            $date = new DateTime('@' . $date);
            $date->setTimezone(new DateTimeZone(date_default_timezone_get()));
        } else {
            $date = new DateTime($date);
        }
    }
    return $formatter->format($date->getTimestamp());
}
Exemplo n.º 9
0
 public function filterLocalizedDatePattern($date, $pattern, $locale = null)
 {
     if (!class_exists('IntlDateFormatter')) {
         throw new \RuntimeException('The intl extension is needed to use intl-based filters.');
     }
     $formatter = \IntlDateFormatter::create($locale !== null ? $locale : \Locale::getDefault(), \IntlDateFormatter::NONE, \IntlDateFormatter::NONE, date_default_timezone_get());
     $formatter->setPattern($pattern);
     if (!$date instanceof \DateTime) {
         if (\ctype_digit((string) $date)) {
             $date = new \DateTime('@' . $date);
             $date->setTimezone(new \DateTimeZone(date_default_timezone_get()));
         } else {
             $date = new \DateTime($date);
         }
     }
     return $formatter->format($date->getTimestamp());
 }
 /**
  * Handles DateTime fields
  * 
  * @param DataEvent $event
  */
 public function onDataReady(DataEvent $event)
 {
     $data = array();
     foreach ($event->getData() as $key => $row) {
         foreach ($row as $field => $value) {
             if ($value instanceof \DateTime) {
                 $formatter = \IntlDateFormatter::create($this->locale, static::$formats[$this->dateFormat], static::$formats[$this->timeFormat], $this->timezone, IntlDateFormatter::GREGORIAN, $this->format);
                 if (!$formatter) {
                     $formatter = IntlDateFormatter::create('en', static::$formats[$this->dateFormat], static::$formats[$this->timeFormat], $this->timezone, \IntlDateFormatter::GREGORIAN, $this->format);
                 }
                 $value = $formatter->format($value->getTimestamp());
             }
             $data[$key][$field] = $value;
         }
     }
     $event->setData($data);
 }
    /**
     * Translate a timestamp to a localized string representation.
     * Parameters dateType and timeType defines a kind of format. Allowed values are (none|short|medium|long|full).
     * Default is medium for the date and no time.
     * @param mixed $date
     * @param string $dateType
     * @param string $timeType
     * @return string The string representation
     */
    public static function localeDateFilter($date, $dateType = 'medium', $timeType = 'none')
    {
        $values = array(
            'none'   => \IntlDateFormatter::NONE,
            'short'  => \IntlDateFormatter::SHORT,
            'medium' => \IntlDateFormatter::MEDIUM,
            'long'   => \IntlDateFormatter::LONG,
            'full'   => \IntlDateFormatter::FULL,
        );
        $dateFormater = \IntlDateFormatter::create(\Locale::getDefault(), $values[$dateType], $values[$timeType]);
        
        if (!defined('PHP_VERSION_ID') || PHP_VERSION_ID < 50304) {
            $date = $date->getTimestamp();
        }

        return $dateFormater->format($date);
    }
Exemplo n.º 12
0
 public function api_registros_por_ano()
 {
     $this->autoRender = false;
     // dados do Angular
     $dados = (array) json_decode(file_get_contents('php://input'), true);
     // dados do usuário logado
     $admin_logged = $this->getAdminLogged();
     // busca aulas do usuário logado que a data seja pertencente ao ano selecionado
     $lessons_table = TableRegistry::get("Lessons");
     $user_id = empty($admin_logged['clinical_condition']) ? $admin_logged['user_id'] : $admin_logged['id'];
     $where = ['user_id' => $user_id];
     // executa a consulta
     $lessons = $lessons_table->find()->where($where)->order(['Lessons.date' => 'DESC'])->contain(['LessonEntries' => function ($q) {
         // join para buscar as entradas desta aula somente do usuário logado e para incluir os inputs tb
         $admin_logged = $this->getAdminLogged();
         $user_id = empty($admin_logged['clinical_condition']) ? $admin_logged['user_id'] : $admin_logged['id'];
         $where2 = ['LessonEntries.user_id' => $user_id];
         if (!empty($admin_logged['clinical_condition'])) {
             $where2 = ['LessonEntries.user_id' => $admin_logged['id'], 'LessonEntries.model' => 'Users', 'LessonEntries.model_id' => $admin_logged['id']];
         }
         return $q->contain(['Inputs'])->where($where2);
     }, 'LessonThemes' => function ($q) {
         return $q->contain(['Themes']);
     }, 'LessonHashtags' => function ($q) {
         return $q->contain(['Hashtags']);
     }])->all();
     $meses = ["01" => 0, "02" => 0, "03" => 0, "04" => 0, "05" => 0, "06" => 0, "07" => 0, "08" => 0, "09" => 0, "10" => 0, "11" => 0, "12" => 0];
     // inclui um campo com o mes do registro
     foreach ($lessons as $l) {
         $dateFormatter = \IntlDateFormatter::create(\Locale::getDefault(), \IntlDateFormatter::NONE, \IntlDateFormatter::NONE, \date_default_timezone_get(), \IntlDateFormatter::GREGORIAN, 'EEEE');
         $l->mes = $l->date->format("m");
         $l->year = $l->date->format("Y");
         $l->dia = ucfirst($dateFormatter->format($l->date));
         $l->created = null;
         $l->modified = null;
         $l->date = $l->date->format("d/m");
         $meses[$l->mes] = $meses[$l->mes] + 1;
     }
     $return = ['lessons' => $lessons, 'meses' => $meses];
     echo json_encode($return);
 }
Exemplo n.º 13
0
 /**
  * @param Request $request
  * @param Pool    $pool
  *
  * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
  */
 private function handlePoolCreation(Request $request, Pool $pool)
 {
     $form = $this->createForm(PoolType::class, $pool);
     if ('POST' === $request->getMethod()) {
         $form->handleRequest($request);
         if ($form->isValid()) {
             foreach ($pool->getEntries() as $entry) {
                 $entry->setPool($pool);
             }
             $dateFormatter = \IntlDateFormatter::create($request->getLocale(), \IntlDateFormatter::MEDIUM, \IntlDateFormatter::NONE);
             $message = $this->get('translator')->trans('emails.created.message', ['%amount%' => $pool->getAmount(), '%eventdate%' => $dateFormatter->format($pool->getEventdate()->getTimestamp()), '%location%' => $pool->getLocation(), '%message%' => $pool->getMessage()]);
             $pool->setCreationDate(new \DateTime());
             $pool->setMessage($message);
             $pool->setLocale($request->getLocale());
             $this->get('doctrine.orm.entity_manager')->persist($pool);
             $this->get('doctrine.orm.entity_manager')->flush();
             return $this->redirect($this->generateUrl('pool_exclude', ['listUrl' => $pool->getListurl()]));
         }
     }
     return ['form' => $form->createView()];
 }
Exemplo n.º 14
0
 /**
  * @Route("/", name="pool_create")
  * @Template()
  */
 public function createAction(Request $request)
 {
     $pool = new Pool();
     $form = $this->createForm(new PoolType(), $pool);
     if ('POST' === $request->getMethod()) {
         $form->handleRequest($request);
         if ($form->isValid()) {
             foreach ($pool->getEntries() as $entry) {
                 $entry->setPool($pool);
             }
             $em = $this->getDoctrine()->getManager();
             $dateFormatter = \IntlDateFormatter::create($request->getLocale(), \IntlDateFormatter::MEDIUM, \IntlDateFormatter::NONE);
             $translator = $this->get('translator');
             $message = $translator->trans('emails.created.message', array('%amount%' => $pool->getAmount(), '%date%' => $dateFormatter->format($pool->getDate()->getTimestamp()), '%message%' => $pool->getMessage()));
             $pool->setMessage($message);
             $pool->setLocale($request->getLocale());
             $em->persist($pool);
             $em->flush();
             return $this->redirect($this->generateUrl('pool_exclude', array('listUrl' => $pool->getListurl())));
         }
     }
     return array('form' => $form->createView());
 }
Exemplo n.º 15
0
 /**
  * Parse a string representation of a date to a timestamp.
  * 
  * @param string $date
  * @param string $locale
  * @return int Timestamp
  * 
  * @throws \Exception If fails parsing the string
  */
 private function parseTimestamp($date, $locale = null)
 {
     // try time default formats
     foreach ($this->formats as $timeFormat) {
         // try date default formats
         foreach ($this->formats as $dateFormat) {
             $dateFormater = \IntlDateFormatter::create($locale ?: \Locale::getDefault(), $dateFormat, $timeFormat, date_default_timezone_get());
             $timestamp = $dateFormater->parse($date);
             if ($dateFormater->getErrorCode() == 0) {
                 return $timestamp;
             }
         }
     }
     // try other custom formats
     $formats = array('MMMM yyyy');
     foreach ($formats as $format) {
         $dateFormater = \IntlDateFormatter::create($locale ?: \Locale::getDefault(), $this->formats['none'], $this->formats['none'], date_default_timezone_get(), \IntlDateFormatter::GREGORIAN, $format);
         $timestamp = $dateFormater->parse($date);
         if ($dateFormater->getErrorCode() == 0) {
             return $timestamp;
         }
     }
     throw new \Exception('"' . $date . '" could not be converted to \\DateTime');
 }
Exemplo n.º 16
0
 /**
  * Formatea (convierte en una representación de texto) una fecha.
  */
 public function tapir_fecha($date, $dateFormat = 'full', $timeFormat = 'medium', $emptyMessage = '')
 {
     if ($date == null) {
         return $emptyMessage;
     } elseif (!$date instanceof \DateTime) {
         $date = str_replace(['ene', 'abr', 'ago', 'dic'], ['jan', 'apr', 'aug', 'dec'], strtolower($date));
         if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/", $date)) {
             $transformer = new DateTimeToStringTransformer(null, null, 'Y-m-d H:i:s');
             $date = $transformer->reverseTransform($date);
         } elseif (preg_match("/^(0[1-9]|[1-2][0-9]|3[0-1])-(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)-[0-9]{2}\$/", $date)) {
             $transformer = new DateTimeToStringTransformer(null, null, 'd-M-y');
             $date = $transformer->reverseTransform($date);
         } elseif (preg_match("/^(0[1-9]|[1-2][0-9]|3[0-1])-[0-9]{4}\$/", $date)) {
             $transformer = new DateTimeToStringTransformer(null, null, 'm-Y');
             $date = $transformer->reverseTransform($date);
         }
     }
     $formatValues = array('none' => \IntlDateFormatter::NONE, 'short' => \IntlDateFormatter::SHORT, 'medium' => \IntlDateFormatter::MEDIUM, 'long' => \IntlDateFormatter::LONG, 'full' => \IntlDateFormatter::FULL);
     $dateFormatValue = \IntlDateFormatter::NONE;
     switch ($dateFormat) {
         case 'none':
             $dateFormatValue = \IntlDateFormatter::NONE;
             $patrn = '';
             break;
         case 'month':
         case 'shortmonth':
             $dateFormatValue = \IntlDateFormatter::SHORT;
             $patrn = 'MM/yyyy';
             break;
         case 'mediummonth':
             $dateFormatValue = \IntlDateFormatter::SHORT;
             $patrn = 'MMM/yyyy';
             break;
         case 'fullmonth':
             $dateFormatValue = \IntlDateFormatter::SHORT;
             $patrn = "MMMM 'de' yyyy";
             break;
         case 'short':
             $dateFormatValue = \IntlDateFormatter::SHORT;
             $patrn = 'dd/MM/yy';
             break;
         case 'medium':
             $dateFormatValue = \IntlDateFormatter::MEDIUM;
             $patrn = 'dd/MM/yyyy';
             break;
         case 'long':
             $dateFormatValue = \IntlDateFormatter::LONG;
             $patrn = "d 'de' MMMM 'de' yyyy";
             break;
         case 'full':
             $dateFormatValue = \IntlDateFormatter::FULL;
             $patrn = "EEEE, d 'de' MMMM 'de' yyyy";
             break;
         default:
             $dateFormatValue = \IntlDateFormatter::SHORT;
             $patrn = 'dd/MM/yy';
             break;
     }
     switch ($timeFormat) {
         case 'none':
             break;
         case 'short':
         case 'medium':
             $patrn .= ' HH:mm';
             break;
         case 'long':
         case 'full':
         default:
             $patrn .= ' HH:mm:ss';
             break;
     }
     $formatter = \IntlDateFormatter::create('es_AR', $dateFormatValue, $formatValues[$timeFormat], $date->getTimezone()->getName(), \IntlDateFormatter::GREGORIAN, trim($patrn));
     return ucfirst(str_replace(',', '', $formatter->format($date->getTimestamp())));
 }
Exemplo n.º 17
0
 public static function relativeDate($time, $messages, $shortestForm = false)
 {
     $crtYear = date('Y');
     $today = strtotime(date('M j, Y'));
     $reldays = ($time - $today) / 86400;
     $relTime = date($messages['date_relative_time_format'], $time);
     if ($reldays >= 0 && $reldays < 1) {
         return str_replace("TIME", $relTime, $messages['date_relative_today']);
     } else {
         if ($reldays >= 1 && $reldays < 2) {
             return str_replace("TIME", $relTime, $messages['date_relative_tomorrow']);
         } else {
             if ($reldays >= -1 && $reldays < 0) {
                 return str_replace("TIME", $relTime, $messages['date_relative_yesterday']);
             }
         }
     }
     if (abs($reldays) < 7) {
         if ($reldays > 0) {
             $reldays = floor($reldays);
             return str_replace("%s", $reldays, $messages['date_relative_days_ahead']);
             //return 'In ' . $reldays . ' day' . ($reldays != 1 ? 's' : '');
         } else {
             $reldays = abs(floor($reldays));
             return str_replace("%s", $reldays, $messages['date_relative_days_ago']);
             //return $reldays . ' day' . ($reldays != 1 ? 's' : '') . ' ago';
         }
     }
     $finalDate = date($messages["date_relative_date_format"], $time ? $time : time());
     if (strpos($messages["date_relative_date_format"], "F") !== false && isset($messages["date_intl_locale"]) && extension_loaded("intl")) {
         $intl = IntlDateFormatter::create($messages["date_intl_locale"], IntlDateFormatter::FULL, IntlDateFormatter::FULL, null, null, "MMMM");
         $localizedMonth = $intl->format($time ? $time : time());
         $dateFuncMonth = date("F", $time ? $time : time());
         $finalDate = str_replace($dateFuncMonth, $localizedMonth, $finalDate);
     }
     if (!$shortestForm || strpos($finalDate, $crtYear) !== false) {
         $finalDate = str_replace($crtYear, '', $finalDate);
         return str_replace("DATE", $finalDate, $messages["date_relative_date"]);
     } else {
         return $finalDate = date("M Y", $time ? $time : time());
     }
 }
Exemplo n.º 18
0
 /**
  * Registra una nueva compra de la oferta indicada por parte del usuario logueado
  *
  * @param string $ciudad El slug de la ciudad a la que pertenece la oferta
  * @param string $slug El slug de la oferta
  */
 public function comprarAction($ciudad, $slug)
 {
     $em = $this->getDoctrine()->getEntityManager();
     $usuario = $this->get('security.context')->getToken()->getUser();
     // Solo pueden comprar los usuarios registrados y logueados
     if (null == $usuario || !$this->get('security.context')->isGranted('ROLE_USUARIO')) {
         $this->get('session')->setFlash('info', 'Antes de comprar debes registrarte o conectarte con tu usuario y contraseña.');
         return $this->redirect($this->generateUrl('usuario_login'));
     }
     // Comprobar que existe la ciudad indicada
     $ciudad = $em->getRepository('CiudadBundle:Ciudad')->findOneBySlug($ciudad);
     if (!$ciudad) {
         throw $this->createNotFoundException('La ciudad indicada no está disponible');
     }
     // Comprobar que existe la oferta indicada
     $oferta = $em->getRepository('OfertaBundle:Oferta')->findOneBy(array('ciudad' => $ciudad->getId(), 'slug' => $slug));
     if (!$oferta) {
         throw $this->createNotFoundException('La oferta indicada no está disponible');
     }
     // Un mismo usuario no puede comprar dos veces la misma oferta
     $venta = $em->getRepository('OfertaBundle:Venta')->findOneBy(array('oferta' => $oferta->getId(), 'usuario' => $usuario->getId()));
     if (null != $venta) {
         $fechaVenta = $venta->getFecha();
         $formateador = \IntlDateFormatter::create($this->get('translator')->getLocale(), \IntlDateFormatter::LONG, \IntlDateFormatter::NONE);
         $this->get('session')->setFlash('error', 'No puedes volver a comprar la misma oferta (la compraste el ' . $formateador->format($fechaVenta) . ').');
         return $this->redirect($this->getRequest()->headers->get('Referer', $this->generateUrl('portada')));
     }
     // Guardar la nueva venta e incrementar el contador de compras de la oferta
     $venta = new Venta();
     $venta->setOferta($oferta);
     $venta->setUsuario($usuario);
     $venta->setFecha(new \DateTime());
     $em->persist($venta);
     $oferta->setCompras($oferta->getCompras() + 1);
     $em->flush();
     return $this->render('UsuarioBundle:Default:comprar.html.twig', array('oferta' => $oferta, 'usuario' => $usuario));
 }
Exemplo n.º 19
0
 /**
  * Default date pattern is short date pattern with 4 digit year
  * 
  * @param int $calendar
  * @return string
  */
 protected function getDefaultDatePattern($calendar = \IntlDateFormatter::GREGORIAN)
 {
     return preg_replace('/\\byy?\\b/', 'yyyy', \IntlDateFormatter::create(\Locale::getDefault(), \IntlDateFormatter::SHORT, \IntlDateFormatter::NONE, null, $calendar)->getPattern());
 }
Exemplo n.º 20
0
 /**
  * Returns a textual representation of a date range
  *
  * @param \DateTime $startDate
  * @param \DateTime $endDate
  * @param string    $locale
  *
  * @return string
  */
 public function dateRange($startDate, $endDate, $locale = null)
 {
     if (!$locale) {
         $locale = $this->locale;
     }
     $defaultDateFormatter = \IntlDateFormatter::create($locale, \IntlDateFormatter::LONG, \IntlDateFormatter::NONE);
     if ($startDate == $endDate) {
         return $defaultDateFormatter->format($startDate);
     }
     $startDateInfos = date_parse($startDate->format('Y-m-d'));
     $endDateInfos = date_parse($endDate->format('Y-m-d'));
     if ($startDateInfos['month'] == $endDateInfos['month'] && $startDateInfos['year'] == $endDateInfos['year']) {
         // ex.: 2 au 5 février 2012
         if ($locale == 'fr') {
             $range = $startDateInfos['day'] . ' au ' . $defaultDateFormatter->format($endDate);
             // ex.: February 2 to 5, 2012
         } else {
             $dateFormatterStart = \IntlDateFormatter::create($locale, \IntlDateFormatter::LONG, \IntlDateFormatter::NONE, null, null, 'MMMM d');
             $dateFormatterEnd = \IntlDateFormatter::create($locale, \IntlDateFormatter::LONG, \IntlDateFormatter::NONE, null, null, 'd, Y');
             $range = $dateFormatterStart->format($startDate) . ' to ' . $dateFormatterEnd->format($endDate);
         }
     } elseif ($startDateInfos['year'] == $endDateInfos['year']) {
         // ex.: 2 février au 5 mai 2012
         if ($locale == 'fr') {
             $dateFormatterStart = \IntlDateFormatter::create($locale, \IntlDateFormatter::LONG, \IntlDateFormatter::NONE, null, null, 'd MMMM');
             $range = $dateFormatterStart->format($startDate) . ' au ' . $defaultDateFormatter->format($endDate);
             // ex.: February 2 to May 5, 2012
         } else {
             $dateFormatter = \IntlDateFormatter::create($locale, \IntlDateFormatter::LONG, \IntlDateFormatter::NONE, null, null, 'MMMM d');
             $range = $dateFormatter->format($startDate) . ' to ' . $dateFormatter->format($endDate) . ', ' . $endDateInfos['year'];
         }
     } else {
         $range = $defaultDateFormatter->format($startDate);
         $range .= $locale == 'fr' ? ' au ' : ' to ';
         $range .= $defaultDateFormatter->format($endDate);
     }
     if ($locale == 'fr') {
         $range = preg_replace(array('/^1 /', '/au 1 /'), array('1er ', 'au 1er '), $range);
     }
     return $range;
 }
Exemplo n.º 21
0
 /**
  * Returns an array :
  * datetime => array('date' => datetime object,
  * 'user' => user name,
  * 'changes' => array(array ('fieldname', 'oldvalue', 'newvalue'))
  * )
  *
  * @param Application\Entity\Event $event            
  */
 public function getHistory($event)
 {
     $history = array();
     $repo = $this->em->getRepository('Application\\Entity\\Log');
     $formatter = \IntlDateFormatter::create(\Locale::getDefault(), \IntlDateFormatter::FULL, \IntlDateFormatter::FULL, 'UTC', \IntlDateFormatter::GREGORIAN, 'dd LLL, HH:mm');
     // history of event
     $logentries = $repo->getLogEntries($event);
     if (count($logentries) >= 1 && $logentries[count($logentries) - 1]->getAction() == "create") {
         $ref = null;
         foreach (array_reverse($logentries) as $logentry) {
             if (!$ref) {
                 // set up reference == "create" entry
                 if (!array_key_exists($logentry->getLoggedAt()->format(DATE_RFC2822), $history)) {
                     $ref = $logentry->getData();
                     $entry = array();
                     $entry['date'] = $logentry->getLoggedAt();
                     $entry['user'] = $logentry->getUsername();
                     $history[$logentry->getLoggedAt()->format(DATE_RFC2822)] = $entry;
                 }
                 $historyentry = array();
                 $historyentry['fieldname'] = 'create';
                 $history[$logentry->getLoggedAt()->format(DATE_RFC2822)]['changes'][] = $historyentry;
             } else {
                 foreach ($logentry->getData() as $key => $value) {
                     // sometimes log stores values that didn't changed
                     if ($ref[$key] != $value) {
                         if (!array_key_exists($logentry->getLoggedAt()->format(DATE_RFC2822), $history)) {
                             $entry = array();
                             $entry['date'] = $logentry->getLoggedAt();
                             $entry['changes'] = array();
                             $entry['user'] = $logentry->getUsername();
                             $history[$logentry->getLoggedAt()->format(DATE_RFC2822)] = $entry;
                         }
                         $historyentry = array();
                         $historyentry['fieldname'] = $key;
                         if ($key == 'enddate' || $key == 'startdate') {
                             if ($key == 'enddate') {
                                 $historyentry['fieldname'] = "Fin";
                             } elseif ($key == 'startdate') {
                                 $historyentry['fieldname'] = "Début";
                             }
                             $historyentry['oldvalue'] = $ref[$key] ? $formatter->format($ref[$key]) : '';
                             $historyentry['newvalue'] = $value ? $formatter->format($value) : null;
                         } else {
                             if ($key == 'punctual') {
                                 $historyentry['oldvalue'] = $ref[$key] ? "Oui" : "Non";
                                 $historyentry['newvalue'] = $value ? "Oui" : "Non";
                             } elseif ($key == 'status') {
                                 $old = $this->em->getRepository('Application\\Entity\\Status')->find($ref[$key]['id']);
                                 $new = $this->em->getRepository('Application\\Entity\\Status')->find($value['id']);
                                 $historyentry['oldvalue'] = $old->getName();
                                 $historyentry['newvalue'] = $new->getName();
                             } elseif ($key == 'impact') {
                                 $old = $this->em->getRepository('Application\\Entity\\Impact')->find($ref[$key]['id']);
                                 $new = $this->em->getRepository('Application\\Entity\\Impact')->find($value['id']);
                                 $historyentry['oldvalue'] = $old->getName();
                                 $historyentry['newvalue'] = $new->getName();
                             } else {
                                 $historyentry['oldvalue'] = $ref[$key];
                                 $historyentry['newvalue'] = $value;
                             }
                         }
                         $history[$logentry->getLoggedAt()->format(DATE_RFC2822)]['changes'][] = $historyentry;
                         // update ref
                         $ref[$key] = $value;
                     }
                 }
             }
         }
     }
     // history of customfields
     foreach ($this->em->getRepository('Application\\Entity\\CustomFieldValue')->findBy(array('event' => $event->getId())) as $customfieldvalue) {
         $fieldlogentries = $repo->getLogEntries($customfieldvalue);
         if (count($fieldlogentries) > 1 && $fieldlogentries[count($fieldlogentries) - 1]->getAction() == "create") {
             $ref = null;
             foreach (array_reverse($fieldlogentries) as $fieldlogentry) {
                 if (!$ref) {
                     $ref = $fieldlogentry->getData();
                 } else {
                     foreach ($fieldlogentry->getData() as $key => $value) {
                         if ($ref[$key] != $value) {
                             if (!array_key_exists($fieldlogentry->getLoggedAt()->format(DATE_RFC2822), $history)) {
                                 $entry = array();
                                 $entry['date'] = $fieldlogentry->getLoggedAt();
                                 $entry['changes'] = array();
                                 $entry['user'] = $fieldlogentry->getUsername();
                                 $history[$fieldlogentry->getLoggedAt()->format(DATE_RFC2822)] = $entry;
                             }
                             $historyentry = array();
                             $historyentry['fieldname'] = $customfieldvalue->getCustomField()->getName();
                             $historyentry['oldvalue'] = $this->sm->get('CustomFieldService')->getFormattedValue($customfieldvalue->getCustomField(), $ref[$key]);
                             $historyentry['newvalue'] = $this->sm->get('CustomFieldService')->getFormattedValue($customfieldvalue->getCustomField(), $value);
                             $history[$fieldlogentry->getLoggedAt()->format(DATE_RFC2822)]['changes'][] = $historyentry;
                             // update ref
                             $ref[$key] = $value;
                         }
                     }
                 }
             }
         }
     }
     // updates
     foreach ($event->getUpdates() as $update) {
         if (!array_key_exists($update->getCreatedOn()->format(DATE_RFC2822), $history)) {
             $entry = array();
             $entry['date'] = $update->getCreatedOn();
             $entry['changes'] = array();
             $entry['user'] = $this->getUpdateAuthor($update);
             $history[$update->getCreatedOn()->format(DATE_RFC2822)] = $entry;
         }
         $historyentry = array();
         $historyentry['fieldname'] = 'note';
         $historyentry['oldvalue'] = '';
         $historyentry['newvalue'] = $update->getText();
         $history[$update->getCreatedOn()->format(DATE_RFC2822)]['changes'][] = $historyentry;
     }
     // fiche reflexe
     foreach ($event->getChildren() as $child) {
         if ($child->getCategory() instanceof \Application\Entity\ActionCategory && !$child->getStatus()->isOpen()) {
             if (!array_key_exists($child->getLastModifiedOn()->format(DATE_RFC2822), $history)) {
                 $entry = array();
                 $entry['date'] = $child->getLastModifiedOn();
                 $entry['changes'] = array();
                 $entry['user'] = $this->getLastUpdateAuthorName($child);
                 $history[$child->getLastModifiedOn()->format(DATE_RFC2822)] = $entry;
             }
             $historyentry = array();
             $historyentry['fieldname'] = 'action';
             $historyentry['oldvalue'] = '';
             $historyentry['newvalue'] = $this->getName($child);
             $historyentry['status'] = $child->getStatus();
             $history[$child->getLastModifiedOn()->format(DATE_RFC2822)]['changes'][] = $historyentry;
         }
     }
     // alertes
     foreach ($event->getChildren() as $child) {
         if ($child->getCategory() instanceof \Application\Entity\AlarmCategory && !$child->getStatus()->isOpen()) {
             if (!array_key_exists($child->getLastModifiedOn()->format(DATE_RFC2822), $history)) {
                 $entry = array();
                 $entry['date'] = $child->getLastModifiedOn();
                 $entry['changes'] = array();
                 $entry['user'] = $this->getLastUpdateAuthorName($child);
                 $history[$child->getLastModifiedOn()->format(DATE_RFC2822)] = $entry;
             }
             $historyentry = array();
             $historyentry['fieldname'] = 'alarm';
             $historyentry['oldvalue'] = '';
             $historyentry['newvalue'] = $this->getName($child);
             $historyentry['status'] = $child->getStatus();
             $history[$child->getLastModifiedOn()->format(DATE_RFC2822)]['changes'][] = $historyentry;
         }
     }
     uksort($history, array($this, "sortbydate"));
     return $history;
 }
Exemplo n.º 22
0
 /**
  * Export a report in ODF
  */
 public function exportAction()
 {
     $em = $this->getServiceLocator()->get('Doctrine\\ORM\\EntityManager');
     $eventservice = $this->getServiceLocator()->get('EventService');
     $customfieldservice = $this->getServiceLocator()->get('CustomFieldService');
     $id = $this->params()->fromQuery('id', null);
     if ($this->zfcUserAuthentication()->hasIdentity() && $id !== null) {
         $tbs = new TBS();
         $tbs->LoadTemplate('data/templates/cr_ipo_model_v1.odt', OPENTBS_ALREADY_UTF8);
         $org_id = $this->zfcUserAuthentication()->getIdentity()->getOrganisation()->getId();
         $org = $em->getRepository('Application\\Entity\\Organisation')->find($org_id);
         $report = $em->getRepository('IPO\\Entity\\Report')->find($id);
         $startdate = $report->getStartDate();
         $categories = array();
         foreach ($report->getElements() as $element) {
             if ($element->getCategory() !== null) {
                 $categories[$element->getCategory()->getId()][] = $element->getEvent();
             }
         }
         $formatter = \IntlDateFormatter::create(\Locale::getDefault(), \IntlDateFormatter::FULL, \IntlDateFormatter::FULL, 'UTC', \IntlDateFormatter::GREGORIAN, 'EEEE d MMMM');
         $formatterYear = \IntlDateFormatter::create(\Locale::getDefault(), \IntlDateFormatter::FULL, \IntlDateFormatter::FULL, 'UTC', \IntlDateFormatter::GREGORIAN, 'EEEE d MMMM Y');
         $formatterHour = \IntlDateFormatter::create(\Locale::getDefault(), \IntlDateFormatter::FULL, \IntlDateFormatter::FULL, 'UTC', \IntlDateFormatter::GREGORIAN, 'HH:mm');
         $formatterDayHour = \IntlDateFormatter::create(\Locale::getDefault(), \IntlDateFormatter::FULL, \IntlDateFormatter::FULL, 'UTC', \IntlDateFormatter::GREGORIAN, 'dd/MM HH:mm');
         // pour chaque catégorie
         foreach ($em->getRepository('IPO\\Entity\\ReportCategory')->findAll() as $cat) {
             $catevents = array();
             // pour chaque jour de la semaine
             for ($i = 0; $i <= 6; $i++) {
                 $tempdate0 = clone $startdate;
                 $tempdate0->modify('+' . $i . ' days');
                 $tempdate1 = clone $startdate;
                 $tempdate1->modify('+' . ($i + 1) . ' days');
                 $date = $formatter->format($tempdate0);
                 $events = array();
                 // pour chaque évènement de la catégorie
                 if (isset($categories[$cat->getId()])) {
                     foreach ($categories[$cat->getId()] as $event) {
                         // on l'ajoute à la liste du jour si l'évènement intersecte le jour
                         if ($this->intersectDates($event, $tempdate0, $tempdate1)) {
                             $newevent = array();
                             $newevent['name'] = $eventservice->getName($event);
                             $newevent['start'] = $formatterDayHour->format($event->getStartdate());
                             $newevent['end'] = $event->getEnddate() !== null ? $formatterDayHour->format($event->getEnddate()) : '';
                             $newevent['author'] = $event->getAuthor()->getDisplayName();
                             $newevent['fields'] = array();
                             foreach ($event->getCustomFieldsValues() as $value) {
                                 $val = array();
                                 $val['name'] = $value->getCustomfield()->getName();
                                 $val['value'] = $customfieldservice->getFormattedValue($value->getCustomField(), $value->getValue());
                                 $newevent['fields'][] = $val;
                             }
                             $newevent['updates'] = array();
                             foreach ($event->getUpdates() as $update) {
                                 $up = array();
                                 $up['hour'] = $formatterDayHour->format($update->getCreatedOn());
                                 $up['author'] = $eventservice->getUpdateAuthor($update);
                                 $up['note'] = $update->getText();
                                 $newevent['updates'][] = $up;
                             }
                             $newevent['isupdates'] = count($newevent['updates']) > 0 ? 1 : 0;
                             $events[] = $newevent;
                         }
                     }
                 }
                 $catevents[] = array('day' => $date, 'event' => $events);
             }
             $tbs->MergeBlock($cat->getShortname(), $catevents);
         }
         $tbs->MergeField('general', array('week_number' => $report->getWeek() . '/' . $report->getYear(), 'start_date' => $formatter->format($report->getStartDate()), 'end_date' => $formatterYear->format($report->getEndDate())));
         // fields in Header
         $tbs->PlugIn(OPENTBS_SELECT_FILE, 'styles.xml');
         $tbs->MergeField('general', array('organisation_name' => $org->getLongname(), 'export_date' => $formatterYear->format(new \DateTime('NOW'))));
         // send the file
         $tbs->Show(OPENTBS_DOWNLOAD, 'rapport_IPO_semaine' . $report->getWeek() . '_' . $report->getYear() . '.odt');
     } else {
     }
 }
Exemplo n.º 23
0
 /**
  * Change la date de début d'un evt et
  * - vérifie la cohérence des évènements fils
  * - vérifie la cohérence du statut
  * 
  * @param \Application\Entity\Event $event            
  * @param \DateTime $startdate            
  * @param
  *            array Messages
  * @return true Si tout s'est bien passé
  */
 private function changeStartDate(Event $event, \DateTime $startdate, &$messages = null)
 {
     $objectManager = $this->getServiceLocator()->get('Doctrine\\ORM\\EntityManager');
     $formatter = \IntlDateFormatter::create(\Locale::getDefault(), \IntlDateFormatter::FULL, \IntlDateFormatter::FULL, 'UTC', \IntlDateFormatter::GREGORIAN, 'dd LLL, HH:mm');
     if ($event->setStartdate($startdate)) {
         if (is_array($messages)) {
             $messages['success'][] = "Date et heure de début modifiées au " . $formatter->format($event->getStartdate());
         }
         // passage au statut confirmé si pertinent, droits ok et heure de début proche de l'heure actuelle
         if ($this->isGranted('events.confirme')) {
             $now = new \DateTime('now');
             $now->setTimezone(new \DateTimeZone('UTC'));
             $status = $objectManager->getRepository('Application\\Entity\\Status')->findOneBy(array('open' => true, 'defaut' => false));
             if ($event->getStatus()->getId() == 1 && ($event->getStartDate()->format('U') - $now->format('U')) / 60 < 15) {
                 $event->setStatus($status);
                 if (is_array($messages)) {
                     $messages['success'][] = "Evènement passé au statut : confirmé.";
                 }
             }
         }
         // changement de l'heure de début des évènements fils si pertinent
         foreach ($event->getChildren() as $child) {
             if ($child->getCategory() instanceof FrequencyCategory) {
                 $child->setStartdate($startdate);
                 $objectManager->persist($child);
             }
         }
         $event->updateAlarms();
         $objectManager->persist($event);
     } else {
         if (is_array($messages)) {
             $messages['error'][] = "Impossible de changer l'heure de début.";
         }
     }
 }
Exemplo n.º 24
0
<?php

$intlDateFormatter = IntlDateFormatter::create(null, null, null);
$intlDateFormatter->setTimeZoneId('Europe/Paris');
Exemplo n.º 25
0
 /**
  * Formatea la fecha indicada según las características del locale seleccionado.
  * Se utiliza para mostrar correctamente las fechas en el idioma de cada usuario.
  *
  * @param string $fecha Objeto que representa la fecha original
  * @param string $formatoFecha Formato con el que se muestra la fecha
  * @param string $formatoHora  Formato con el que se muestra la hora
  * @param string $locale El locale al que se traduce la fecha
  */
 public function fecha($fecha, $formatoFecha = 'medium', $formatoHora = 'none', $locale = null)
 {
     // Código copiado de
     //   https://github.com/thaberkern/symfony/blob
     //   /b679a23c331471961d9b00eb4d44f196351067c8
     //   /src/Symfony/Bridge/Twig/Extension/TranslationExtension.php
     // Formatos: http://www.php.net/manual/en/class.intldateformatter.php#intl.intldateformatter-constants
     $formatos = array('none' => \IntlDateFormatter::NONE, 'short' => \IntlDateFormatter::SHORT, 'medium' => \IntlDateFormatter::MEDIUM, 'long' => \IntlDateFormatter::LONG, 'full' => \IntlDateFormatter::FULL);
     $formateador = \IntlDateFormatter::create($locale != null ? $locale : $this->getTranslator()->getLocale(), $formatos[$formatoFecha], $formatos[$formatoHora]);
     if ($fecha instanceof \DateTime) {
         return $formateador->format($fecha);
     } else {
         return $formateador->format(new \DateTime($fecha));
     }
 }
Exemplo n.º 26
0
 /**
  * Format a rule in a human readable string
  * intl extension is required.
  *
  * @param array  $opt
  *
  * @return string
  */
 public function humanReadable(array $opt = array())
 {
     if (self::$intl_loaded === null) {
         self::$intl_loaded = extension_loaded('intl');
     }
     // attempt to detect default locale
     if (self::$intl_loaded) {
         $locale = \Locale::getDefault();
     } else {
         $locale = setlocale(LC_MESSAGES, 0);
         if ($locale == 'C') {
             $locale = 'en';
         }
     }
     $default_opt = array('locale' => $locale, 'date_formatter' => null, 'fallback' => 'en');
     if (self::$intl_loaded) {
         $default_opt['date_format'] = \IntlDateFormatter::SHORT;
         if ($this->freq >= self::SECONDLY || not_empty($this->rule['BYSECOND'])) {
             $default_opt['time_format'] = \IntlDateFormatter::LONG;
         } elseif ($this->freq >= self::HOURLY || not_empty($this->rule['BYHOUR']) || not_empty($this->rule['BYMINUTE'])) {
             $default_opt['time_format'] = \IntlDateFormatter::SHORT;
         } else {
             $default_opt['time_format'] = \IntlDateFormatter::NONE;
         }
     }
     $opt = array_merge($default_opt, $opt);
     if ($opt['date_formatter'] && !is_callable($opt['date_formatter'])) {
         throw new \InvalidArgumentException('The option date_formatter must callable');
     }
     if (!$opt['date_formatter']) {
         if (self::$intl_loaded) {
             $formatter = \IntlDateFormatter::create($opt['locale'], $opt['date_format'], $opt['time_format'], $this->dtstart->getTimezone()->getName());
             $opt['date_formatter'] = function ($date) use($formatter) {
                 return $formatter->format($date);
             };
         } else {
             $opt['date_formatter'] = function ($date) {
                 return $date->format('Y-m-d H:i:s');
             };
         }
     }
     $i18n = self::i18nLoad($opt['locale'], $opt['fallback']);
     $parts = array('freq' => '', 'byweekday' => '', 'bymonth' => '', 'byweekno' => '', 'byyearday' => '', 'bymonthday' => '', 'byhour' => '', 'byminute' => '', 'bysecond' => '', 'bysetpos' => '');
     // Every (INTERVAL) FREQ...
     $freq_str = strtolower(array_search($this->freq, self::$frequencies));
     $parts['freq'] = strtr(self::i18nSelect($i18n[$freq_str], $this->interval), array('%{interval}' => $this->interval));
     // BYXXX rules
     if (not_empty($this->rule['BYMONTH'])) {
         $tmp = $this->bymonth;
         foreach ($tmp as &$value) {
             $value = $i18n['months'][$value];
         }
         $parts['bymonth'] = strtr(self::i18nSelect($i18n['bymonth'], count($tmp)), array('%{months}' => self::i18nList($tmp, $i18n['and'])));
     }
     if (not_empty($this->rule['BYWEEKNO'])) {
         // XXX negative week number are not great here
         $tmp = $this->byweekno;
         foreach ($tmp as &$value) {
             $value = strtr($i18n['nth_weekno'], array('%{n}' => $value));
         }
         $parts['byweekno'] = strtr(self::i18nSelect($i18n['byweekno'], count($this->byweekno)), array('%{weeks}' => self::i18nList($tmp, $i18n['and'])));
     }
     if (not_empty($this->rule['BYYEARDAY'])) {
         $tmp = $this->byyearday;
         foreach ($tmp as &$value) {
             $value = strtr(self::i18nSelect($i18n[$value > 0 ? 'nth_yearday' : '-nth_yearday'], $value), array('%{n}' => abs($value)));
         }
         $tmp = strtr(self::i18nSelect($i18n['byyearday'], count($tmp)), array('%{yeardays}' => self::i18nList($tmp, $i18n['and'])));
         // ... of the month
         $tmp = strtr(self::i18nSelect($i18n['x_of_the_y'], 'yearly'), array('%{x}' => $tmp));
         $parts['byyearday'] = $tmp;
     }
     if (not_empty($this->rule['BYMONTHDAY'])) {
         $parts['bymonthday'] = array();
         if ($this->bymonthday) {
             $tmp = $this->bymonthday;
             foreach ($tmp as &$value) {
                 $value = strtr(self::i18nSelect($i18n['nth_monthday'], $value), array('%{n}' => $value));
             }
             $tmp = strtr(self::i18nSelect($i18n['bymonthday'], count($tmp)), array('%{monthdays}' => self::i18nList($tmp, $i18n['and'])));
             // ... of the month
             $tmp = strtr(self::i18nSelect($i18n['x_of_the_y'], 'monthly'), array('%{x}' => $tmp));
             $parts['bymonthday'][] = $tmp;
         }
         if ($this->bymonthday_negative) {
             $tmp = $this->bymonthday_negative;
             foreach ($tmp as &$value) {
                 $value = strtr(self::i18nSelect($i18n['-nth_monthday'], $value), array('%{n}' => -$value));
             }
             $tmp = strtr(self::i18nSelect($i18n['bymonthday'], count($tmp)), array('%{monthdays}' => self::i18nList($tmp, $i18n['and'])));
             // ... of the month
             $tmp = strtr(self::i18nSelect($i18n['x_of_the_y'], 'monthly'), array('%{x}' => $tmp));
             $parts['bymonthday'][] = $tmp;
         }
         $parts['bymonthday'] = implode(' ' . $i18n['and'], $parts['bymonthday']);
     }
     if (not_empty($this->rule['BYDAY'])) {
         $parts['byweekday'] = array();
         if ($this->byweekday) {
             $tmp = $this->byweekday;
             foreach ($tmp as &$value) {
                 $value = $i18n['weekdays'][$value];
             }
             $parts['byweekday'][] = strtr(self::i18nSelect($i18n['byweekday'], count($tmp)), array('%{weekdays}' => self::i18nList($tmp, $i18n['and'])));
         }
         if ($this->byweekday_nth) {
             $tmp = $this->byweekday_nth;
             foreach ($tmp as &$value) {
                 list($day, $n) = $value;
                 $value = strtr(self::i18nSelect($i18n[$n > 0 ? 'nth_weekday' : '-nth_weekday'], $n), array('%{weekday}' => $i18n['weekdays'][$day], '%{n}' => abs($n)));
             }
             $tmp = strtr(self::i18nSelect($i18n['byweekday'], count($tmp)), array('%{weekdays}' => self::i18nList($tmp, $i18n['and'])));
             // ... of the year|month
             $tmp = strtr(self::i18nSelect($i18n['x_of_the_y'], $freq_str), array('%{x}' => $tmp));
             $parts['byweekday'][] = $tmp;
         }
         $parts['byweekday'] = implode(' ' . $i18n['and'], $parts['byweekday']);
     }
     if (not_empty($this->rule['BYHOUR'])) {
         $tmp = $this->byhour;
         foreach ($tmp as &$value) {
             $value = strtr($i18n['nth_hour'], array('%{n}' => $value));
         }
         $parts['byhour'] = strtr(self::i18nSelect($i18n['byhour'], count($tmp)), array('%{hours}' => self::i18nList($tmp, $i18n['and'])));
     }
     if (not_empty($this->rule['BYMINUTE'])) {
         $tmp = $this->byminute;
         foreach ($tmp as &$value) {
             $value = strtr($i18n['nth_minute'], array('%{n}' => $value));
         }
         $parts['byminute'] = strtr(self::i18nSelect($i18n['byminute'], count($tmp)), array('%{minutes}' => self::i18nList($tmp, $i18n['and'])));
     }
     if (not_empty($this->rule['BYSECOND'])) {
         $tmp = $this->bysecond;
         foreach ($tmp as &$value) {
             $value = strtr($i18n['nth_second'], array('%{n}' => $value));
         }
         $parts['bysecond'] = strtr(self::i18nSelect($i18n['bysecond'], count($tmp)), array('%{seconds}' => self::i18nList($tmp, $i18n['and'])));
     }
     if ($this->bysetpos) {
         $tmp = $this->bysetpos;
         foreach ($tmp as &$value) {
             $value = strtr(self::i18nSelect($i18n[$value > 0 ? 'nth_setpos' : '-nth_setpos'], $value), array('%{n}' => abs($value)));
         }
         $tmp = strtr(self::i18nSelect($i18n['bysetpos'], count($tmp)), array('%{setpos}' => self::i18nList($tmp, $i18n['and'])));
         $parts['bysetpos'] = $tmp;
     }
     // from X
     $parts['start'] = strtr($i18n['dtstart'], array('%{date}' => $opt['date_formatter']($this->dtstart)));
     // to X, or N times, or indefinitely
     if (!$this->until && !$this->count) {
         $parts['end'] = $i18n['infinite'];
     } elseif ($this->until) {
         $parts['end'] = strtr($i18n['until'], array('%{date}' => $opt['date_formatter']($this->until)));
     } elseif ($this->count) {
         $parts['end'] = strtr(self::i18nSelect($i18n['count'], $this->count), array('%{count}' => $this->count));
     }
     // $str = strtr('%{frequency}%{byday}%{start}%{end}', array(
     // 	'%{frequency}' => $parts['frequency'],
     // 	'%{start}' => $parts['start'],
     // 	'%{end}' => $parts['end'],
     // 	'%{byday}' => $parts['byday'],
     // ));
     $parts = array_filter($parts);
     $str = implode('', $parts);
     return $str;
 }
Exemplo n.º 27
0
 private function getDateFormatter($locale, $format)
 {
     if (!isset($this->dateFormatters[$locale . '.' . $format])) {
         $this->dateFormatters[$locale . '.' . $format] = IntlDateFormatter::create($locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, null, null, $format);
     }
     return $this->dateFormatters[$locale . '.' . $format];
 }
Exemplo n.º 28
0
 /**
  * Creates the formatter.
  *
  * @param string $timezone Timezone to use.
  * @param int    $dateType Type of the formatted date.
  * @param int    $timeType Type of the formatted time.
  *
  * @return \IntlDateFormatter
  */
 private function createFormatter($timezone, $dateType = null, $timeType = null)
 {
     return \IntlDateFormatter::create($this->locale, $dateType, $timeType, $timezone);
 }
Exemplo n.º 29
0
 public function getalarmsAction()
 {
     $formatter = \IntlDateFormatter::create(\Locale::getDefault(), \IntlDateFormatter::FULL, \IntlDateFormatter::FULL, 'UTC', \IntlDateFormatter::GREGORIAN, 'HH:mm');
     $alarms = array();
     if ($this->zfcUserAuthentication()->hasIdentity()) {
         $organisation = $this->zfcUserAuthentication()->getIdentity()->getOrganisation()->getId();
         $lastupdate = $this->params()->fromQuery('lastupdate', null);
         $objectManager = $this->getServiceLocator()->get('Doctrine\\ORM\\EntityManager');
         $eventservice = $this->getServiceLocator()->get('EventService');
         $userroles = array();
         foreach ($this->zfcUserAuthentication()->getIdentity()->getRoles() as $role) {
             $userroles[] = $role->getId();
         }
         $qbEvents = $objectManager->createQueryBuilder();
         $qbEvents->select(array('e', 'cat', 'roles'))->from('Application\\Entity\\Event', 'e')->innerJoin('e.category', 'cat')->innerJoin('cat.readroles', 'roles')->andWhere($qbEvents->expr()->eq('e.organisation', $organisation))->andWhere('cat INSTANCE OF Application\\Entity\\AlarmCategory')->andWhere($qbEvents->expr()->in('e.status', '?2'))->andWhere($qbEvents->expr()->in('roles.id', '?3'));
         if ($lastupdate && $lastupdate != 'undefined') {
             $from = new \DateTime($lastupdate);
             $from->setTimezone(new \DateTimeZone("UTC"));
             // uniquement les alarmes créés et modifiées à partir de lastupdate
             $qbEvents->andWhere($qbEvents->expr()->gte('e.last_modified_on', '?1'))->setParameters(array(2 => array(1, 2, 3, 4), 1 => $from->format('Y-m-d H:i:s'), 3 => $userroles));
         } else {
             $now = new \DateTime('NOW');
             $now->setTimezone(new \DateTimeZone("UTC"));
             $interval = new \DateInterval("PT60M");
             $interval->invert = 1;
             $now->add($interval);
             // toutes les alarmes non acquittées vielles de moins d'une heure
             // afin de ne pas perdre les alarmes non acquittées en cas de refresh
             $qbEvents->andWhere($qbEvents->expr()->gte('e.startdate', '?1'))->setParameters(array(1 => $now->format('Y-m-d H:i:s'), 2 => array(1, 2), 3 => $userroles));
         }
         $result = $qbEvents->getQuery()->getResult();
         foreach ($result as $alarm) {
             $alarm = $objectManager->getRepository('Application\\Entity\\Event')->find($alarm->getId());
             if ($alarm->getParent()) {
                 // les alarmes ont forcément un parent
                 $deltaend = "";
                 $alarmcomment = "";
                 foreach ($alarm->getCustomFieldsValues() as $value) {
                     if ($value->getCustomField()->getId() === $alarm->getCategory()->getDeltaEndField()->getId()) {
                         $deltaend = $value->getValue();
                     } else {
                         if ($value->getCustomField()->getId() == $alarm->getCategory()->getTextfield()->getId()) {
                             $alarmcomment = nl2br($value->getValue());
                         }
                     }
                 }
                 if (strlen(trim($deltaend)) > 0 && !$alarm->getParent()->getEnddate()) {
                     // do nothing : start date inaccurate
                 } else {
                     $startdate = $alarm->getStartDate();
                     $alarmjson = array();
                     $alarmjson['id'] = $alarm->getId();
                     $alarmjson['datetime'] = $startdate->format(DATE_RFC2822);
                     $alarmjson['status'] = $alarm->getStatus()->getId();
                     $parentname = $eventservice->getName($alarm->getParent());
                     $alarmname = $eventservice->getName($alarm);
                     $alarmjson['text'] = "<div id=\"alarmnoty-" . $alarm->getId() . "\" class=\"noty_big\"><b>" . $formatter->format($alarm->getStartDate()) . " : Mémo</b> pour <b>" . $parentname . "</b><br />" . $alarmname . (strlen($alarmcomment) > 0 ? " : <br />" . $alarmcomment : "");
                     $alarms[] = $alarmjson;
                 }
             }
         }
     }
     if (empty($alarms)) {
         $this->getResponse()->setStatusCode(304);
         return new JsonModel();
     }
     $this->getResponse()->getHeaders()->addHeaderLine('Last-Modified', gmdate('D, d M Y H:i:s', time()) . ' GMT');
     return new JsonModel($alarms);
 }
Exemplo n.º 30
0
    /**
     * Process filters
     *
     * @return void
     */
    protected function processFilters()
    {
        if ($this->generator->filter->fields && is_array($this->generator->filter->fields)) {
            $counter = 0;
            foreach ($this->generator->filter->fields as $fieldName => $field) {
                if (isset($field['type'])) {
                    switch($field['type']) {

                        case 'daterange':

                            $dateFormaterEn = \IntlDateFormatter::create('en', \IntlDateFormatter::MEDIUM, \IntlDateFormatter::NONE);
                            if (isset($this->query[$fieldName .'_from']) && $this->query[$fieldName .'_from'] != '') {
                                $counter++;
                                $this->queryBuilder->andWhere("e.{$fieldName} >= ?{$counter}");
                                $dateFrom = date('Y-m-d', $dateFormaterEn->parse($this->query[$fieldName .'_from'])) . ' 00:00:00';
                                $this->queryBuilder->setParameter($counter, $dateFrom);
                            }
                            if (isset($this->query[$fieldName .'_to']) && $this->query[$fieldName .'_to'] != '') {
                                $counter++;
                                $this->queryBuilder->andWhere("e.{$fieldName} <= ?{$counter}");
                                $dateTo = date('Y-m-d', $dateFormaterEn->parse($this->query[$fieldName .'_to'])) . ' 23:59:59';
                                $this->queryBuilder->setParameter($counter, $dateTo);
                            }
                            break;

                        case 'entity':
                            if (isset($this->query[$fieldName]) && $this->query[$fieldName] != '') {
                                try {
                                    $entity = $this->doctrineRegistry->getEntityManager()
                                            ->getRepository($field['options']['class'])
                                            ->find($this->query[$fieldName]);
                                } catch (Exception $exc) {
                                    $entity =  false;
                                }

                                if ($entity) {
                                    $counter++;
                                    $compare = $this->getCompare(isset($field['compare']) ? $field['compare'] : null);
                                    $this->queryBuilder->andWhere(
                                        $this->queryBuilder->expr()->$compare("e.{$fieldName} ", "?{$counter}")
                                    );
                                    $this->queryBuilder->setParameter($counter, $entity);
                                }

                            }
                            break;

                        case 'checkbox':
                            if (isset($this->query[$fieldName]) && $this->query[$fieldName] == true) {
                                $counter++;
                                $this->queryBuilder->andWhere(
                                    $this->queryBuilder->expr()->eq("e.{$fieldName} ", "?{$counter}")
                                );
                                $this->queryBuilder->setParameter($counter, true);
                            }
                            break;

                        case 'text':
                        default:
                            if (isset($this->query[$fieldName])) {
                                $counter++;
                                $compare = $this->getCompare(isset($field['compare']) ? $field['compare'] : null);
                                $this->queryBuilder->andWhere(
                                    $this->queryBuilder->expr()->$compare("e.{$fieldName} ", "?{$counter}")
                                );
                                if ($compare == 'like') {
                                    $this->query[$fieldName] = "%{$this->query[$fieldName]}%";
                                }
                                $this->queryBuilder->setParameter($counter, $this->query[$fieldName]);
                            }
                            break;
                    }
                }
            }
        }
    }