/**
  * Gets the Locale from the identifier.
  * 
  * @param string $identifier The identifier of the Locale, such as en_US.
  * 
  * @return \Attibee\Locale\Locale The Locale object, or null if not found.
  */
 public static function getLocale($identifier)
 {
     $resourceDir = __DIR__ . '/../resources/';
     //let's support both formats
     $identifier = str_replace('-', '_', $identifier);
     $file = $resourceDir . $identifier . '.xml';
     //file does not exist, return null
     if (!file_exists($file)) {
         return null;
     }
     $locale = new Locale($identifier);
     //create reader
     $dom = new \DOMDocument();
     $dom->load($file);
     //add reader to locale resources
     $locale->setDom($dom);
     //add parents by successively removing "_suffix"
     //these are added recursively
     $pos = strrpos($identifier, '_');
     if ($pos !== false) {
         $identifier = substr($identifier, 0, $pos);
         $locale->setParentLocale(LocaleFactory::getLocale($identifier));
     }
     return $locale;
 }
示例#2
0
 /**
  * Returns the current locale. This is the default locale if
  * no current lcoale has been set or the set current locale has
  * a language code of "mul".
  *
  * @return \TYPO3\FLOW3\I18n\Locale
  */
 public function getCurrentLocale()
 {
     if (!$this->currentLocale instanceof \TYPO3\FLOW3\I18n\Locale || $this->currentLocale->getLanguage() === 'mul') {
         return $this->defaultLocale;
     }
     return $this->currentLocale;
 }
示例#3
0
function sum_page()
{
    global $gEnv;
    $amp_locale = new Locale('amp_root_menu', AMP_LANG);
    import('com.solarix.ampoliros.module.ModuleConfig');
    $mod_cfg = new ModuleConfig($gEnv['root']['db'], 'ampoliros');
    $hui = new Hui($gEnv['root']['db'], TRUE);
    $hui->LoadWidget('table');
    $hui->LoadWidget('page');
    $hui->LoadWidget('vertgroup');
    $hui->LoadWidget('vertframe');
    $hui->LoadWidget('treemenu');
    $hui_page = new HuiPage('page', array('title' => 'Ampoliros' . (strlen(AMP_HOST) ? ' - ' . AMP_HOST . (strlen(AMP_DOMAIN) ? '.' . AMP_DOMAIN : '') : ''), 'border' => 'false'));
    $hui_page->mArgs['background'] = $hui_page->mThemeHandler->mStyle['menuback'];
    $hui_mainvertgroup = new HuiVertGroup('mainvertgroup');
    $el[1]['groupname'] = 'Ampoliros';
    $cont = 1;
    $query =& $gEnv['root']['db']->Execute('SELECT id FROM sites');
    if ($query->NumRows()) {
        $el[1]['groupelements'][$cont]['name'] = $amp_locale->GetStr('siteadmin');
        $el[1]['groupelements'][$cont]['image'] = $hui_page->mThemeHandler->mStyle['siteaccess'];
        $el[1]['groupelements'][$cont]['action'] = 'admin/';
        $el[1]['groupelements'][$cont]['themesized'] = 'true';
        $cont++;
    }
    $el[1]['groupelements'][$cont]['name'] = $amp_locale->GetStr('rootadmin');
    $el[1]['groupelements'][$cont]['image'] = $hui_page->mThemeHandler->mStyle['rootaccess'];
    $el[1]['groupelements'][$cont]['action'] = 'root/';
    $el[1]['groupelements'][$cont]['themesized'] = 'true';
    if ($mod_cfg->GetKey('ampoliros-link-disabled') != '1') {
        $el[1]['groupelements'][++$cont]['name'] = $amp_locale->GetStr('amphome');
        $el[1]['groupelements'][$cont]['image'] = $hui_page->mThemeHandler->mStyle['ampminilogo'];
        $el[1]['groupelements'][$cont]['action'] = 'http://www.ampoliros.com/';
        $el[1]['groupelements'][$cont]['target'] = 'op';
        $el[1]['groupelements'][$cont]['themesized'] = 'true';
    }
    if ($mod_cfg->GetKey('solarix-link-disabled') != '1') {
        $el[1]['groupelements'][++$cont]['name'] = $amp_locale->GetStr('solarixhome');
        $el[1]['groupelements'][$cont]['image'] = $hui_page->mThemeHandler->mStyle['solarixminilogo'];
        $el[1]['groupelements'][$cont]['action'] = 'http://www.solarix.biz/';
        $el[1]['groupelements'][$cont]['target'] = 'op';
        $el[1]['groupelements'][$cont]['themesized'] = 'true';
    }
    if ($mod_cfg->GetKey('oem-link-disabled') != '1') {
        $oem_link_filename = $mod_cfg->GetKey('oem-link-filename');
        if (strlen($oem_link_filename) and file_exists(CGI_PATH . $oem_link_filename)) {
            $el[1]['groupelements'][++$cont]['name'] = $mod_cfg->GetKey('oem-name');
            $el[1]['groupelements'][$cont]['image'] = CGI_URL . $oem_link_filename;
            $el[1]['groupelements'][$cont]['action'] = $mod_cfg->GetKey('oem-url');
            $el[1]['groupelements'][$cont]['target'] = 'parent';
            $el[1]['groupelements'][$cont]['themesized'] = 'false';
        }
    }
    $hui_vertframe = new HuiVertFrame('vertframe');
    $hui_vertframe->AddChild(new HuiTreeMenu('treemenu', array('elements' => $el, 'width' => '120', 'target' => 'parent', 'allgroupsactive' => 'true')));
    $hui_mainvertgroup->AddChild($hui_vertframe);
    $hui_page->AddChild($hui_mainvertgroup);
    $hui->AddChild($hui_page);
    $hui->Render();
}
  function testGetDayNameSunday()
  {
    $locale = new Locale('en');

    $this->assertEqual($locale->getDayName(6, $short = false), 'Sunday');
    $this->assertEqual($locale->getDayName(6, $short = true), 'Sun');
  }
 /**
  * Gets the Collator for the desired locale.
  *
  * @param   util.Locale locale
  * @return  text.Collator
  */
 public static function getInstance(Locale $locale)
 {
     $id = $locale->hashCode();
     if (!isset(self::$instance[$id])) {
         self::$instance[$id] = new self($locale->toString());
     }
     return self::$instance[$id];
 }
示例#6
0
文件: Module.php 项目: nouron/nouron
 public function onBootstrap($e)
 {
     \Locale::setDefault('de_DE');
     $sm = $e->getApplication()->getServiceManager();
     $translator = $sm->get('translator');
     \Zend\Validator\AbstractValidator::setDefaultTranslator(new \Zend\Mvc\I18n\Translator($translator));
 }
 /**
  * Returns the set locale
  *
  * @return string
  */
 public function getLocale()
 {
     if (null === $this->locale) {
         $this->locale = \Locale::getDefault();
     }
     return $this->locale;
 }
 public function __construct(Dispatcher $dispatcher)
 {
     $request = $this->getDI()->get('request');
     $queryLang = $request->getQuery('lang');
     if (!$queryLang) {
         $lang = $dispatcher->getParam('lang');
     } else {
         $lang = $queryLang;
     }
     switch ($lang) {
         case 'uk':
             define('LANG', 'uk');
             define('LANG_SUFFIX', '_uk');
             define('LANG_URL', '/uk');
             define('LOCALE', 'uk_UA');
             break;
         case 'en':
             define('LANG', 'en');
             define('LANG_SUFFIX', '_en');
             define('LANG_URL', '/en');
             define('LOCALE', 'en_EN');
             break;
         default:
             define('LANG', 'ru');
             define('LANG_SUFFIX', '');
             define('LANG_URL', '/');
             define('LOCALE', 'ru_RU');
     }
     Locale::setDefault(LOCALE);
     $this->getDI()->set('translate', new \Application\Localization\GettextAdapter(array('locale' => LOCALE, 'lang' => LANG, 'file' => 'messages', 'directory' => APPLICATION_PATH . '/lang')));
 }
示例#9
0
 /**
  * Returns the pattern for this locale.
  *
  * The pattern contains the placeholder "{{ widget }}" where the HTML tag should
  * be inserted
  */
 protected static function getPattern($currency)
 {
     if (!$currency) {
         return '{{ widget }}';
     }
     $locale = \Locale::getDefault();
     if (!isset(self::$patterns[$locale])) {
         self::$patterns[$locale] = array();
     }
     if (!isset(self::$patterns[$locale][$currency])) {
         $format = new \NumberFormatter($locale, \NumberFormatter::CURRENCY);
         $pattern = $format->formatCurrency('123', $currency);
         // the spacings between currency symbol and number are ignored, because
         // a single space leads to better readability in combination with input
         // fields
         // the regex also considers non-break spaces (0xC2 or 0xA0 in UTF-8)
         preg_match('/^([^\\s\\xc2\\xa0]*)[\\s\\xc2\\xa0]*123(?:[,.]0+)?[\\s\\xc2\\xa0]*([^\\s\\xc2\\xa0]*)$/u', $pattern, $matches);
         if (!empty($matches[1])) {
             self::$patterns[$locale][$currency] = $matches[1] . ' {{ widget }}';
         } elseif (!empty($matches[2])) {
             self::$patterns[$locale][$currency] = '{{ widget }} ' . $matches[2];
         } else {
             self::$patterns[$locale][$currency] = '{{ widget }}';
         }
     }
     return self::$patterns[$locale][$currency];
 }
示例#10
0
 /**
  * Reads data.
  *
  * Results are aggregated by querying all requested configurations for the requested
  * locale then repeating this process for all locales down the locale cascade. This
  * allows for sparse data which is complemented by data from other sources or for more
  * generic locales. Aggregation can be controlled by either specifying the configurations
  * or a scope to use.
  *
  * Usage:
  * ```
  * Catalog::read(true, 'message', 'zh');
  * Catalog::read('default', 'message', 'zh');
  * Catalog::read('default', 'validation.postalCode', 'en_US');
  * ```
  *
  * @param mixed $name Provide a single configuration name as a string or multiple ones as
  *        an array which will be used to read from. Pass `true` to use all configurations.
  * @param string $category A (dot-delimeted) category.
  * @param string $locale A locale identifier.
  * @param array $options Valid options are:
  *        - `'scope'`: The scope to use.
  *        - `'lossy'`: Whether or not to use the compact and lossy format, defaults to `true`.
  * @return array If available the requested data, else `null`.
  */
 public static function read($name, $category, $locale, array $options = array())
 {
     $defaults = array('scope' => null, 'lossy' => true);
     $options += $defaults;
     $category = strtok($category, '.');
     $id = strtok('.');
     $names = $name === true ? array_keys(static::$_configurations) : (array) $name;
     $results = array();
     foreach (Locale::cascade($locale) as $cascaded) {
         foreach ($names as $name) {
             $adapter = static::adapter($name);
             if ($result = $adapter->read($category, $cascaded, $options['scope'])) {
                 $results += $result;
             }
         }
     }
     if ($options['lossy']) {
         array_walk($results, function (&$value) {
             $value = $value['translated'];
         });
     }
     if ($id) {
         return isset($results[$id]) ? $results[$id] : null;
     }
     return $results ?: null;
 }
 function addItem($args, &$request)
 {
     $this->setupTemplate();
     $pressSettingsDao =& DAORegistry::getDAO('PressSettingsDAO');
     $press =& $request->getPress();
     $index = 'sourceTitle-' . $this->getId();
     $format = $args[$index];
     if (!isset($format)) {
         $json = new JSON('false');
         return $json->getString();
     } else {
         // Make sure the item doesn't already exist
         $formats = $pressSettingsDao->getSetting($press->getId(), 'cataloguingMetadata');
         foreach ($formats as $item) {
             if ($item['name'] == $format) {
                 $json = new JSON('false', Locale::translate('common.listbuilder.itemExists'));
                 return $json->getString();
                 return false;
             }
         }
         $formats[] = array('name' => $format);
         $pressSettingsDao->updateSetting($press->getId(), 'cataloguingMetadata', $formats, 'object');
         // Return JSON with formatted HTML to insert into list
         $row =& $this->getRowInstance();
         $row->setGridId($this->getId());
         $row->setId($format);
         $rowData = array('item' => $format);
         $row->setData($rowData);
         $row->initialize($request);
         $json = new JSON('true', $this->_renderRowInternally($request, $row));
         return $json->getString();
     }
 }
示例#12
0
 /**
  * Validate and save changes to user's profile.
  */
 function saveProfile()
 {
     $this->validate();
     $this->setupTemplate();
     $dataModified = false;
     import('user.form.ProfileForm');
     $profileForm = new ProfileForm();
     $profileForm->readInputData();
     if (Request::getUserVar('uploadProfileImage')) {
         if (!$profileForm->uploadProfileImage()) {
             $profileForm->addError('profileImage', Locale::translate('user.profile.form.profileImageInvalid'));
         }
         $dataModified = true;
     } else {
         if (Request::getUserVar('deleteProfileImage')) {
             $profileForm->deleteProfileImage();
             $dataModified = true;
         }
     }
     if (!$dataModified && $profileForm->validate()) {
         $profileForm->execute();
         Request::redirect(null, null, Request::getRequestedPage());
     } else {
         $profileForm->display();
     }
 }
 function displayPaymentForm($queuedPaymentId, &$queuedPayment)
 {
     if (!$this->isConfigured()) {
         return false;
     }
     $journal =& Request::getJournal();
     $templateMgr =& TemplateManager::getManager();
     $user =& Request::getUser();
     $templateMgr->assign('itemName', $queuedPayment->getName());
     $templateMgr->assign('itemDescription', $queuedPayment->getDescription());
     if ($queuedPayment->getAmount() > 0) {
         $templateMgr->assign('itemAmount', $queuedPayment->getAmount());
         $templateMgr->assign('itemCurrencyCode', $queuedPayment->getCurrencyCode());
     }
     $templateMgr->assign('manualInstructions', $this->getSetting($journal->getJournalId(), 'manualInstructions'));
     $templateMgr->display($this->getTemplatePath() . 'paymentForm.tpl');
     if ($queuedPayment->getAmount() > 0) {
         import('mail.MailTemplate');
         $contactName = $journal->getSetting('contactName');
         $contactEmail = $journal->getSetting('contactEmail');
         $mail =& new MailTemplate('MANUAL_PAYMENT_NOTIFICATION');
         $mail->setFrom($contactEmail, $contactName);
         $mail->addRecipient($contactEmail, $contactName);
         $mail->assignParams(array('journalName' => $journal->getJournalTitle(), 'userFullName' => $user ? $user->getFullName() : '(' . Locale::translate('common.none') . ')', 'userName' => $user ? $user->getUsername() : '(' . Locale::translate('common.none') . ')', 'itemName' => $queuedPayment->getName(), 'itemCost' => $queuedPayment->getAmount(), 'itemCurrencyCode' => $queuedPayment->getCurrencyCode()));
         $mail->send();
     }
 }
示例#14
0
 public function onBootstrap(MvcEvent $e)
 {
     $e->getApplication()->getServiceManager()->get('translator');
     $eventManager = $e->getApplication()->getEventManager();
     $moduleRouteListener = new ModuleRouteListener();
     $moduleRouteListener->attach($eventManager);
     // Add translation
     $translator = $e->getApplication()->getServiceManager()->get('translator');
     if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
         $setLang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
     } else {
         $setLang = '';
     }
     $translator->setLocale(\Locale::acceptFromHttp($setLang))->setFallbackLocale('en_US');
     // Add ACL information to the Navigation view helper
     $sm = $e->getApplication()->getServiceManager();
     $authorize = $sm->get('BjyAuthorize\\Service\\Authorize');
     $acl = $authorize->getAcl();
     $role = $authorize->getIdentity();
     \Zend\View\Helper\Navigation::setDefaultAcl($acl);
     \Zend\View\Helper\Navigation::setDefaultRole($role);
     $e->getApplication()->getEventManager()->getSharedManager()->attach('Zend\\Mvc\\Application', 'dispatch.error', function ($e) use($sm) {
         if ($e->getParam('exception')) {
             $sm->get('Zend\\Log\\Logger')->crit($e->getParam('exception'));
         }
     });
 }
示例#15
0
 /**
  * Create the test locale file.
  */
 function execute()
 {
     Locale::initialize();
     $localeFiles =& Locale::getLocaleFiles();
     $localeFile = array_shift($localeFiles[$this->inLocale]);
     $localeData = LocaleFile::load($localeFile->filename);
     if (!isset($localeData)) {
         printf('Invalid locale \'%s\'', $this->inLocale);
         exit(1);
     }
     $outFile = sprintf('locale/%s/locale.xml', $this->outLocale);
     $fp = fopen($outFile, 'wb');
     if (!$fp) {
         printf('Failed to write to \'%s\'', $outFile);
         exit(1);
     }
     fwrite($fp, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" . "<!DOCTYPE locale SYSTEM \"../locale.dtd\">\n\n" . "<!--\n" . "  * locale.xml\n" . "  *\n" . "  * Copyright (c) 2003-2007 John Willinsky\n" . "  * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.\n" . "  *\n" . sprintf("  * Localization strings for the %s (%s) locale.\n", $this->outLocale, DEFAULT_OUT_LOCALE_NAME) . "  *\n" . "  * \$Id\$\n" . "  -->\n\n" . sprintf("<locale name=\"%s\" full_name=\"%s\">\n", $this->outLocale, DEFAULT_OUT_LOCALE_NAME));
     foreach ($localeData as $key => $message) {
         $outMessage = $this->fancifyString($message);
         if (strstr($outMessage, '<') || strstr($outMessage, '>')) {
             $outMessage = '<![CDATA[' . $outMessage . ']]>';
         }
         fwrite($fp, sprintf("\t<message key=\"%s\">%s</message>\n", $key, $outMessage));
     }
     fwrite($fp, "</locale>\n");
     fclose($fp);
 }
示例#16
0
 /**
  * Save group group.
  * @see Form::execute()
  */
 function execute()
 {
     $groupDao =& DAORegistry::getDAO('GroupDAO');
     $press =& Request::getPress();
     if (!isset($this->group)) {
         $this->group = $groupDao->newDataObject();
     }
     $this->group->setAssocType(ASSOC_TYPE_PRESS);
     $this->group->setAssocId($press->getId());
     $this->group->setTitle($this->getData('title'), Locale::getLocale());
     // Localized
     $this->group->setContext($this->getData('context'));
     // Eventually this will be a general Groups feature; for now,
     // we're just using it to display press team entries in About.
     $this->group->setAboutDisplayed(true);
     // Update or insert group group
     if ($this->group->getId() != null) {
         $groupDao->updateObject($this->group);
     } else {
         $this->group->setSequence(REALLY_BIG_NUMBER);
         $groupDao->insertGroup($this->group);
         // Re-order the groups so the new one is at the end of the list.
         $groupDao->resequenceGroups($this->group->getAssocType(), $this->group->getAssocId());
     }
     return true;
 }
示例#17
0
 /**
  * Display a list of the emails within the current conference.
  */
 function emails()
 {
     $this->validate();
     $this->setupTemplate(true);
     $conference =& Request::getConference();
     $rangeInfo = Handler::getRangeInfo('emails', array());
     $emailTemplateDao =& DAORegistry::getDAO('EmailTemplateDAO');
     $emailTemplatesArray =& $emailTemplateDao->getEmailTemplates(Locale::getLocale(), $conference->getId());
     import('core.ArrayItemIterator');
     if ($rangeInfo && $rangeInfo->isValid()) {
         while (true) {
             $emailTemplates = new ArrayItemIterator($emailTemplatesArray, $rangeInfo->getPage(), $rangeInfo->getCount());
             if ($emailTemplates->isInBounds()) {
                 break;
             }
             unset($rangeInfo);
             $rangeInfo =& $emailTemplates->getLastPageRangeInfo();
             unset($emailTemplates);
         }
     } else {
         $emailTemplates = new ArrayItemIterator($emailTemplatesArray);
     }
     $templateMgr =& TemplateManager::getManager();
     // The bread crumbs depends on whether we're doing scheduled conference or conference
     // management. FIXME: this is going to be a common situation, and this isn't
     // an elegant way of testing for it.
     if (Request::getRequestedPage() === 'manager') {
         $templateMgr->assign('pageHierarchy', array(array(Request::url(null, 'index', 'manager'), 'manager.conferenceSiteManagement')));
     } else {
         $templateMgr->assign('pageHierarchy', array(array(Request::url(null, null, 'manager'), 'manager.schedConfManagement')));
     }
     $templateMgr->assign_by_ref('emailTemplates', $emailTemplates);
     $templateMgr->assign('helpTopicId', 'conference.generalManagement.emails');
     $templateMgr->display('manager/emails/emails.tpl');
 }
示例#18
0
 /**
  * {@inheritdoc}
  */
 public function execute(BlockContextInterface $blockContext, Response $response = null)
 {
     $pages = $this->em->getAllSortBy('updatedAt');
     $draftPageCount = 0;
     $reviewPageCount = 0;
     $publishedPageCount = 0;
     $reviewPages = array();
     $draftPages = array();
     foreach ($pages as $page) {
         /** @var \Networking\InitCmsBundle\Model\PageInterface $page */
         if ($page->hasPublishedVersion()) {
             $publishedPageCount++;
         }
         if ($page->isReview()) {
             $reviewPageCount++;
             $draftPageCount++;
             $reviewPages[\Locale::getDisplayLanguage($page->getLocale())][] = $page;
         }
         if ($page->isDraft()) {
             $draftPageCount++;
             $draftPages[\Locale::getDisplayLanguage($page->getLocale())][] = $page;
         }
     }
     return $this->renderResponse($blockContext->getTemplate(), array('block' => $blockContext->getBlock(), 'draft_pages' => $draftPageCount, 'review_pages' => $reviewPageCount, 'published_pages' => $publishedPageCount, 'pages' => $pages, 'reviewPages' => $reviewPages, 'draftPages' => $draftPages), $response);
 }
 /**
  * Save changes to program settings.
  */
 function saveProgramSettings()
 {
     $this->validate();
     $this->setupTemplate(true);
     $schedConf =& Request::getSchedConf();
     if (!$schedConf) {
         Request::redirect(null, null, 'index');
     }
     import('classes.manager.form.ProgramSettingsForm');
     $settingsForm = new ProgramSettingsForm();
     $settingsForm->readInputData();
     $formLocale = $settingsForm->getFormLocale();
     $programTitle = Request::getUserVar('programFileTitle');
     $editData = false;
     if (Request::getUserVar('uploadProgramFile')) {
         if (!$settingsForm->uploadProgram('programFile', $formLocale)) {
             $settingsForm->addError('programFile', Locale::translate('common.uploadFailed'));
         }
         $editData = true;
     } elseif (Request::getUserVar('deleteProgramFile')) {
         $settingsForm->deleteProgram('programFile', $formLocale);
         $editData = true;
     }
     if (!$editData && $settingsForm->validate()) {
         $settingsForm->execute();
         $templateMgr =& TemplateManager::getManager();
         $templateMgr->assign(array('currentUrl' => Request::url(null, null, null, 'program'), 'pageTitle' => 'schedConf.program', 'message' => 'common.changesSaved', 'backLink' => Request::url(null, null, Request::getRequestedPage()), 'backLinkLabel' => 'manager.conferenceSiteManagement'));
         $templateMgr->display('common/message.tpl');
     } else {
         $settingsForm->display();
     }
 }
示例#20
0
/**
 * Make a timestamp into a relative string
 *
 * @todo Tidy up and move out of this file.
 * Based on Garrett Murray's code from http://graveyard.maniacalrage.net/etc/relative/
 */
function relative_time($posted_date)
{
    $in_seconds = $posted_date;
    $diff = time() - $in_seconds;
    $months = floor($diff / 2592000);
    $diff -= $months * 2419200;
    $weeks = floor($diff / 604800);
    $diff -= $weeks * 604800;
    $days = floor($diff / 86400);
    $diff -= $days * 86400;
    $hours = floor($diff / 3600);
    $diff -= $hours * 3600;
    $minutes = floor($diff / 60);
    $diff -= $minutes * 60;
    $seconds = $diff;
    if ($months > 0) {
        return sprintf(_c('on %s', 'on <date>'), date('N, jS \\o\\f F, Y'));
    }
    switch (true) {
        case $weeks > 0:
            // weeks and days
            $week = sprintf(Locale::ngettext('%d week', '%d weeks', $weeks), $weeks);
            if ($days > 0) {
                $day = sprintf(Locale::ngettext('%d day', '%d days', $days), $days);
                $relative_date = sprintf(_c('%s, %s ago', 'relative time, "x weeks, x days ago"'), $week, $day);
            } else {
                $relative_date = sprintf(_c('%s ago', 'relative time, "x weeks ago"'), $week);
            }
            break;
        case $days > 0:
            // days and hours
            $day = sprintf(Locale::ngettext('%d day', '%d days', $days), $days);
            if ($hours > 0) {
                $hour = sprintf(Locale::ngettext('%d hour', '%d hours', $hours), $hours);
                $relative_date = sprintf(_c('%s, %s ago', 'relative time, "x days, x hours ago"'), $day, $hour);
            } else {
                $relative_date = sprintf(_c('%s ago', 'relative time, "x days ago"'), $day);
            }
            break;
        case $hours > 0:
            // hours and minutes
            $hour = sprintf(Locale::ngettext('%d hour', '%d hours', $hours), $hours);
            if ($minutes > 0) {
                $minute = sprintf(Locale::ngettext('%d minute', '%d minutes', $minutes), $minutes);
                $relative_date = sprintf(_c('%s, %s ago', 'relative time, "x hours, x minutes ago"'), $hour, $minute);
            } else {
                $relative_date = sprintf(_c('%s ago', 'relative time, "x hours ago"'), $hour);
            }
            break;
        case $minutes > 0:
            // minutes only
            return sprintf(Locale::ngettext('%d minute ago', '%d minutes ago', $minutes), $minutes);
            break;
        case $seconds > 0:
            // seconds only
            return sprintf(Locale::ngettext('%d second ago', '%d seconds ago', $seconds), $seconds);
            break;
    }
    return $relative_date;
}
示例#21
0
 protected function setUp()
 {
     parent::setUp();
     // we test against "de_DE", so we need the full implementation
     IntlTestHelper::requireFullIntl($this);
     \Locale::setDefault('de_DE');
 }
示例#22
0
 public function testPassMoneyPatternToView()
 {
     \Locale::setDefault('de_DE');
     $form = $this->factory->create('money');
     $view = $form->createView();
     $this->assertSame('{{ widget }} €', $view->get('money_pattern'));
 }
 function addItem($args, &$request)
 {
     $this->setupTemplate();
     $pressSettingsDao =& DAORegistry::getDAO('PressSettingsDAO');
     $divisionDao =& DAORegistry::getDAO('DivisionDAO');
     $press =& $request->getPress();
     $index = 'sourceTitle-' . $this->getId();
     $divisionTitle = $args[$index];
     if (!isset($divisionTitle)) {
         $json = new JSON('false');
         return $json->getString();
     } else {
         // Make sure the item doesn't already exist
         $divisions = $divisionDao->getByTitle($divisionTitle, $press->getId());
         if (isset($divisions)) {
             $json = new JSON('false', Locale::translate('common.listbuilder.itemExists'));
             return $json->getString();
             return false;
         }
         $division =& $divisionDao->newDataObject();
         $division->setTitle($divisionTitle, Locale::getLocale());
         //FIXME: Get locale from form
         $division->setPressId($press->getId());
         $divisionId = $divisionDao->insertObject($division);
         // Return JSON with formatted HTML to insert into list
         $row =& $this->getRowInstance();
         $row->setGridId($this->getId());
         $row->setId($divisionId);
         $rowData = array('item' => $divisionTitle);
         $row->setData($rowData);
         $row->initialize($request);
         $json = new JSON('true', $this->_renderRowInternally($request, $row));
         return $json->getString();
     }
 }
示例#24
0
    /**
     * Get all authors for a given chapter.
     * @param $chapterId int
     * @param $monographId int
     * @return DAOResultFactory
     */
    function &getAuthors($monographId = null, $chapterId = null)
    {
        $params = array('affiliation', Locale::getPrimaryLocale(), 'affiliation', Locale::getLocale());
        if (isset($monographId)) {
            $params[] = (int) $monographId;
        }
        if (isset($chapterId)) {
            $params[] = (int) $chapterId;
        }
        // get all the monograph_author fields,
        // but replace the primary_contact and seq with monograph_chapter_authors.primary_contact
        $sql = 'SELECT	ma.author_id,
				ma.submission_id,
				mca.chapter_id,
				mca.primary_contact,
				mca.seq,
				ma.first_name,
				ma.middle_name,
				ma.last_name,
				asl.setting_value AS affiliation_l,
				asl.locale,
				aspl.setting_value AS affiliation_pl,
				aspl.locale AS primary_locale,
				ma.country,
				ma.email,
				ma.url,
				ma.user_group_id
			FROM	authors ma
				JOIN monograph_chapter_authors mca ON (ma.author_id = mca.author_id)
				LEFT JOIN author_settings aspl ON (mca.author_id = aspl.author_id AND aspl.setting_name = ? AND aspl.locale = ?)
				LEFT JOIN author_settings asl ON (mca.author_id = asl.author_id AND asl.setting_name = ? AND asl.locale = ?)' . (count($params) > 0 ? ' WHERE' : '') . (isset($monographId) ? ' ma.submission_id = ?' : '') . (isset($monographId) && isset($chapterId) ? ' AND' : '') . (isset($chapterId) ? ' mca.chapter_id = ?' : '') . ' ORDER BY mca.chapter_id, mca.seq';
        $result =& $this->retrieve($sql, $params);
        $returner = new DAOResultFactory($result, $this, '_returnFromRow', array('id'));
        return $returner;
    }
示例#25
0
 function it_should_configure_the_resolver(OptionsResolverInterface $resolver)
 {
     $resolver->setDefaults(array('format' => Argument::any(), 'language' => \Locale::getDefault(), 'leading_zero' => false))->shouldBeCalled();
     $resolver->setOptional(array('placeholder', 'language', 'leading_zero'))->shouldBeCalled();
     $resolver->setAllowedTypes(array('placeholder' => array('string'), 'language' => array('string'), 'leading_zero' => array('bool')))->shouldBeCalled();
     $this->setDefaultOptions($resolver);
 }
 /**
  * Constructor.
  *
  * @param MailLoaderInterface      $loader     The mail loader
  * @param \Twig_Environment        $renderer   The twig environment
  * @param EventDispatcherInterface $dispatcher The event dispatcher
  */
 public function __construct(MailLoaderInterface $loader, \Twig_Environment $renderer, EventDispatcherInterface $dispatcher)
 {
     $this->loader = $loader;
     $this->renderer = $renderer;
     $this->locale = \Locale::getDefault();
     $this->dispatcher = $dispatcher;
 }
示例#27
0
 /**
  * Append objects to the global dependency injection container.
  *
  * @param Pimple\Container $container
  */
 public static function setupDependencyInjection(Container $container)
 {
     parent::setupDependencyInjection($container);
     $locale = $container['session']->get('_locale', 'en');
     $container['request']->setLocale($locale);
     \Locale::setDefault($locale);
 }
 public function testValidateUsingCountrySpecificLocale()
 {
     \Locale::setDefault('fr_FR');
     $existingLanguage = 'en';
     $this->validator->validate($existingLanguage, new Language(array('message' => 'aMessage')));
     $this->assertNoViolation();
 }
示例#29
0
 /**
  * The function sets current locale.
  * 
  * @static
  * @access public
  * @param string $locale The current locale.
  */
 public static function set($locale)
 {
     if (!$locale) {
         $locale = 'en_US';
     }
     return self::$locale = $locale;
 }
示例#30
0
 /**
  * Return string containing the contents of the HTML file.
  * This function performs any necessary filtering, like image URL replacement.
  * @param $baseImageUrl string base URL for image references
  * @return string
  */
 function getHTMLContents()
 {
     import('file.ArticleFileManager');
     $fileManager =& new ArticleFileManager($this->getArticleId());
     $contents = $fileManager->readFile($this->getFileId());
     $journal =& Request::getJournal();
     // Replace media file references
     $images =& $this->getImageFiles();
     foreach ($images as $image) {
         $imageUrl = Request::url(null, 'article', 'viewFile', array($this->getArticleId(), $this->getBestGalleyId($journal), $image->getFileId()));
         $pattern = preg_quote(rawurlencode($image->getOriginalFileName()));
         $contents = preg_replace('/([Ss][Rr][Cc]|[Hh][Rr][Ee][Ff]|[Dd][Aa][Tt][Aa])\\s*=\\s*"([^"]*' . $pattern . ')"/', '\\1="' . $imageUrl . '"', $contents);
         // Replacement for Flowplayer
         $contents = preg_replace('/[Uu][Rr][Ll]\\s*\\:\\s*\'(' . $pattern . ')\'/', 'url:\'' . $imageUrl . '\'', $contents);
         // Replacement for other players (ested with odeo; yahoo and google player won't work w/ OJS URLs, might work for others)
         $contents = preg_replace('/[Uu][Rr][Ll]=([^"]*' . $pattern . ')/', 'url=' . $imageUrl, $contents);
     }
     // Perform replacement for ojs://... URLs
     $contents = String::regexp_replace_callback('/(<[^<>]*")[Oo][Jj][Ss]:\\/\\/([^"]+)("[^<>]*>)/', array(&$this, '_handleOjsUrl'), $contents);
     // Perform variable replacement for journal, issue, site info
     $issueDao =& DAORegistry::getDAO('IssueDAO');
     $issue =& $issueDao->getIssueByArticleId($this->getArticleId());
     $journal =& Request::getJournal();
     $site =& Request::getSite();
     $paramArray = array('issueTitle' => $issue ? $issue->getIssueIdentification() : Locale::translate('editor.article.scheduleForPublication.toBeAssigned'), 'journalTitle' => $journal->getJournalTitle(), 'siteTitle' => $site->getSiteTitle(), 'currentUrl' => Request::getRequestUrl());
     foreach ($paramArray as $key => $value) {
         $contents = str_replace('{$' . $key . '}', $value, $contents);
     }
     return $contents;
 }