Exemplo n.º 1
0
 /**
  * Get locale to be used for currency creation
  * Will default to locale_get_default() if not set
  *
  * @return StringType
  */
 public static function getLocale()
 {
     if (empty(self::$locale)) {
         self::$locale = new StringType(locale_get_default());
     }
     return self::$locale;
 }
Exemplo n.º 2
0
 /**
  * @param string $locale locale to be used for spelling out the number.
  */
 public function __construct($locale = null)
 {
     if (!extension_loaded('intl')) {
         throw new RuntimeException('A extensão intl não está instalada.');
     }
     $this->locale = $locale ?: locale_get_default();
 }
Exemplo n.º 3
0
 /**
  * Constructor
  * Will set locale to current default locale
  *
  * @param numeric $value Value of currency
  * @param string $code Code of currency
  * @param string $symbol Symbol for currency
  * @param int $precision number of digits of precision (or exponent) for this currency
  * @param string $name Long name of currency
  * @param string $displayFormat additional user defined display format for currency
  */
 public function __construct($value, $code, $symbol, $precision = 2, $name = null, $displayFormat = '%s')
 {
     $this->setPrecision(new IntType($precision))->setAsFloat($value)->setCode(new StringType($code))->setSymbol(new StringType($symbol))->setDisplayFormat(new StringType($displayFormat))->setLocale(new StringType(locale_get_default()));
     if (!is_null($name)) {
         $this->setName(new StringType($name));
     }
 }
Exemplo n.º 4
0
 protected function setUp()
 {
     $this->saveLocale = locale_get_default();
     locale_set_default('en_GB');
     $this->rootDir = vfsStream::setup('foo');
     $this->sut = new CurrencyDirector(new StringType('GBP'), new StringType('foo\\bar'), new StringType($this->rootDir->url()));
 }
Exemplo n.º 5
0
 public function onBootstrap($event)
 {
     // Gerenciador de Serviços
     $serviceManager = $event->getApplication()->getServiceManager();
     // Tradução
     $translator = $serviceManager->get('MvcTranslator');
     // Configuração
     $translator->setLocale(locale_get_default())->addTranslationFilePattern('phpArray', call_user_func(['Zend\\I18n\\Translator\\Resources', 'getBasePath']), call_user_func(['Zend\\I18n\\Translator\\Resources', 'getPatternForValidator']));
     call_user_func(['Zend\\Validator\\AbstractValidator', 'setDefaultTranslator'], $translator);
     // Banco de Dados e Time Zone
     $serviceManager->get('db')->query(sprintf("SET TIME ZONE '%s'", date_default_timezone_get()))->execute();
 }
Exemplo n.º 6
0
 public function onBootstrap($event)
 {
     // Gerenciador de Serviços
     $serviceManager = $event->getApplication()->getServiceManager();
     // Tradução
     $translator = $serviceManager->get('MvcTranslator');
     // Configuração
     $translator->setLocale(locale_get_default())->addTranslationFile('phpArray', './vendor/zendframework/zend-i18n-resources/languages/' . locale_get_default() . '/Zend_Validate.php', 'default', locale_get_default());
     call_user_func(array('Zend\\Validator\\AbstractValidator', 'setDefaultTranslator'), $translator);
     // Banco de Dados e Time Zone
     $serviceManager->get('db')->query(sprintf("SET TIME ZONE '%s'", date_default_timezone_get()))->execute();
 }
Exemplo n.º 7
0
 public function onBootstrap(MvcEvent $e)
 {
     Paginator::setDefaultItemCountPerPage(30);
     ini_set('html_errors', 'Off');
     $eventManager = $e->getApplication()->getEventManager();
     $moduleRouteListener = new ModuleRouteListener();
     $moduleRouteListener->attach($eventManager);
     $sm = $e->getApplication()->getServiceManager();
     $em = $sm->get('doctrine.entitymanager.orm_default');
     $auth = $sm->get('Zend\\Authentication\\AuthenticationService');
     if (Cons::isConsole()) {
         $locale = locale_get_default();
     } else {
         /* @var $al \Zend\Http\Header\Accept */
         $al = $e->getRequest()->getHeaders('accept-language');
         if ($al) {
             $locales = $al->getPrioritized();
             $locale = reset($locales)->getTypeString();
             \Locale::acceptFromHttp($locale);
         } else {
             $locale = locale_get_default();
         }
     }
     /** @var Translator $translator */
     $translator = $sm->get('MvcTranslator');
     $translator->setLocale(mb_substr($locale, 0, 2));
     //        $translator->getEventManager()->attach('missingTranslation', array($this, 'translationListener'));
     AbstractValidator::setDefaultTranslator($translator);
     //
     // Narediti session tako, da se virtual hosti ne bodo med seboj mešali
     // da se avtentikacija ne prenaša med vhosti
     // poskrbim za identiteto uporabnika
     if ($e->getRequest() instanceof Request) {
         // handling autorizacij preko konzole
         $this->setIdentity('*****@*****.**', $auth, $em);
     } else {
         /* @var $request Request2 */
         $request = $e->getRequest();
         $header = $request->getHeader('Authorization');
         if ($header instanceof Authorization && strlen($header->getFieldValue()) > 10) {
             $this->tryHttpAuth($auth, $em, $e);
         }
     }
     $identity = $auth->getIdentity();
     $evm = $em->getEventManager();
     $evm->addEventSubscriber(new RevisionsListener($sm, $identity));
     $config = $sm->get('entity.metadata.factory')->getAllEntityConfig();
     $evm->addEventSubscriber(new PrePersistListener($config));
 }
Exemplo n.º 8
0
function has_locale($locale)
{
    setlocale(LC_TIME, $locale);
    $set_locale_month = strftime('%B', strtotime('01/01/2001'));
    setlocale(LC_TIME, locale_get_default());
    if (strtolower(substr($locale, 0, 2)) === 'en') {
        if (strtolower($set_locale_month) === 'january') {
            return TRUE;
        } else {
            return FALSE;
        }
    } else {
        if (strtolower($set_locale_month) !== 'january') {
            return TRUE;
        } else {
            return FALSE;
        }
    }
}
Exemplo n.º 9
0
 /**
  * Return textual and translated error messages
  *
  * @param mixed $errors found
  *
  * @return mixed error messages
  */
 public function fullMessages($errors = null)
 {
     if (!function_exists("yaml_parse") || is_null(self::$yaml_file) || !file_exists(self::$yaml_file)) {
         return array();
     }
     $rtn = array();
     $parsed = yaml_parse(file_get_contents(self::$yaml_file));
     $errors = is_null($errors) ? $this->errors : $errors;
     $locale = function_exists("locale_get_default") ? locale_get_default() : "en-US";
     if (!array_key_exists($locale, $parsed) || !array_key_exists("errors", $parsed[$locale]) || !array_key_exists("messages", $parsed[$locale]["errors"])) {
         return $this->errorMessages();
     }
     $msgs = $parsed[$locale]["errors"]["messages"];
     $cls = strtolower(get_called_class());
     foreach ($errors as $key => $values) {
         $attr = array_key_exists("attributes", $parsed[$locale]) && array_key_exists($cls, $parsed[$locale]["attributes"]) && array_key_exists($key, $parsed[$locale]["attributes"][$cls]) ? $parsed[$locale]["attributes"][$cls][$key] : $key;
         foreach ($values as $value) {
             $msg = array_key_exists($value, $msgs) ? $msgs[$value] : ":{$value}";
             array_push($rtn, "{$attr} {$msg}");
         }
     }
     return $rtn;
 }
Exemplo n.º 10
0
/**
 * Try to guess the locale.
 *
 * For command line, try to get the locale from intl extension or locale command.
 * For http requests, try to get the locale from lang cookie, then locale cookie, 
 * if not found in any cookie, then try to guess it from the HTTP_ACCEPT_LANGUAGE header
 *
 * @author Jack
 * @date Mon Feb 23 11:38:29 2015
 */
function get_locale()
{
    if (is_cli()) {
        // For command line, using the machine's locale
        if (\extension_loaded('intl')) {
            // Try intl extension first
            $locale = \locale_get_default();
            $locale = explode('_', $locale);
            if (count($locale) > 2) {
                array_pop($locale);
            }
            // Pop the encoding
            return implode('-', $locale);
        }
        switch (PHP_OS) {
            case 'Linux':
            case 'Darwin':
            case 'Unix':
                $locale = str_replace('"', '', exec("locale | grep LANG | awk -F= '{print \$2}'"));
                $locale = explode('.', $locale);
                $locale = $locale[0];
                return str_replace('_', '-', $locale);
        }
        return 'en-US';
        // Return en-US as default
    } else {
        // For web requests
        $controller = context('controller');
        if ($controller) {
            // If we do have controller here
            // Try lang cookie first
            $locale = $controller->request->cookie('lang');
            if (!$locale) {
                // There is no lang cookie, then let's try locale cookie
                $locale = $controller->request->cookie('locale');
            }
            if (!$locale) {
                // There is no locale cookie either, let's try accept language
                $locale = $controller->request->server('HTTP_ACCEPT_LANGUAGE');
                if ($locale) {
                    $langs = array();
                    // break up string into pieces (languages and q factors)
                    preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\\s*(;\\s*q\\s*=\\s*(1|0\\.[0-9]+))?/i', $locale, $lang_parse);
                    if (count($lang_parse[1])) {
                        // create a list like "en" => 0.8
                        $langs = array_combine($lang_parse[1], $lang_parse[4]);
                        // set default to 1 for any without q factor
                        foreach ($langs as $lang => $val) {
                            if ($val === '') {
                                $langs[$lang] = 1;
                                if (strpos($lang, '-')) {
                                    $data = explode('-', $lang);
                                    $data[1] = strtoupper($data[1]);
                                    $locale = implode('-', $data);
                                } else {
                                    $locale = $lang;
                                }
                            }
                        }
                        // sort list based on value
                        arsort($langs, SORT_NUMERIC);
                        context('langs', $langs);
                    }
                }
            }
            return $locale;
        }
        return 'en-US';
        // Return en-US as default
    }
}
Exemplo n.º 11
0
 protected function setUp()
 {
     $this->sut = new Currency(1200.26, 'GBP', '£');
     $this->saveLocale = locale_get_default();
     $this->sut->setLocale(new StringType('en_GB'));
 }
 public function endTestSuite(\PHPUnit_Framework_TestSuite $suite)
 {
     if (RoxClientException::exceptionOccured()) {
         $this->roxClientLog .= "ROX - WARNING RESULTS WERE NOT SENT TO ROX CENTER.\nThis is due to previously logged errors.\n";
         return;
     } else {
         if (empty($this->currentTestSuite)) {
             // nothing to do
             return;
         }
     }
     try {
         $payload = array();
         // set test run UID
         $payload['u'] = $this->testsRunUid;
         // set test run duration
         $endTime = intval(microtime(true) * 1000);
         // UNIX timestamp in ms
         $payload['d'] = $endTime - $this->testSuiteStartTime;
         // set project infos
         $payload['r'] = array(array());
         // set project API identifier
         if (isset($this->config['project']['apiId'])) {
             $payload['r'][0]['j'] = $this->config['project']['apiId'];
         } else {
             throw new RoxClientException("ROX - ERROR missing apiId for project in config files.");
         }
         // set project version
         if (isset($this->config['project']['version'])) {
             $payload['r'][0]['v'] = $this->config['project']['version'];
         } else {
             throw new RoxClientException("ROX - ERROR missing version for project in config files.");
         }
         // set test results
         $payload['r'][0]['t'] = $this->currentTestSuite;
         // convert payload in UTF-8
         $utf8Payload = $this->convertEncoding($payload, self::PAYLOAD_ENCODING);
         // publish payload
         if ($this->config['payload']['publish']) {
             $jsonPayload = json_encode($utf8Payload);
             $request = $this->httpClient->post($this->testsPayloadUrl, null, $jsonPayload, array("exceptions" => false));
             try {
                 $response = $request->send();
             } catch (GuzzleException $e) {
                 throw new RoxClientException("ROX - ERROR: Unable to post results to ROX server: {$e->getMessage()}");
             }
             if ($response->getStatusCode() == 202) {
                 $this->nbOfPayloadsSent += 1;
                 $coverageRatio = $this->nbOfRoxableTests / $this->nbOfTests;
                 $formatter = new \NumberFormatter(locale_get_default(), \NumberFormatter::PERCENT);
                 $this->roxClientLog .= "ROX - INFO {$this->nbOfRoxableTests} test results successfully sent (payload {$this->nbOfPayloadsSent}) out of {$this->nbOfTests} ({$formatter->format($coverageRatio)}) tests in {$suite->getName()}.\n";
                 // save cache, if cache is used
                 if ($this->config['payload']['cache']) {
                     foreach ($this->cache as $key => $hash) {
                         $this->cacheFile[$this->config['project']['apiId']][$key] = $hash;
                     }
                     $utf8cache = $this->convertEncoding($this->cacheFile, self::PAYLOAD_ENCODING);
                     $jsonCache = json_encode($utf8cache);
                     $cacheDirPath = "{$this->config['workspace']}/phpunit/servers/{$this->config['server']}";
                     if (!file_exists($cacheDirPath)) {
                         mkdir($cacheDirPath, 0755, true);
                     }
                     if (!file_put_contents($cacheDirPath . "/cache.json", $jsonCache)) {
                         throw new RoxClientException("ROX - ERROR unable to save cache in workspace");
                     }
                 }
             } else {
                 $this->roxClientLog .= "ROX - ERROR ROX server ({$this->testsPayloadUrl}) returned an HTTP {$response->getStatusCode()} error:\n{$response->getBody(true)}\n";
             }
         } else {
             $this->roxClientLog .= "ROX - WARNING RESULTS WERE NOT SENT TO ROX CENTER.\nThis is due to 'publish' parameters in config file or to ROX_PUBLISH environment variable.\n";
         }
         // save payload
         if (isset($this->config['payload']['save']) && $this->config['payload']['save']) {
             if (!isset($this->config['workspace'])) {
                 throw new RoxClientException("ROX - ERROR no 'workspace' parameter in config files. Could not save payload.");
             }
             $payloadDirPath = "{$this->config['workspace']}/phpunit/servers/{$this->config['server']}";
             if (!file_exists($payloadDirPath)) {
                 mkdir($payloadDirPath, 0755, true);
             }
             if (file_put_contents($payloadDirPath . "/payload.json", $jsonPayload)) {
                 $this->roxClientLog .= "ROX - INFO payload saved in workspace.\n";
             } else {
                 throw new RoxClientException("ROX - ERROR unable to save payload in workspace");
             }
         }
         // print payload for DEBUG purpose
         if (isset($this->config['payload']['print']) && $this->config['payload']['print']) {
             $jsonPretty = new \Camspiers\JsonPretty\JsonPretty();
             $jsonPrettyPayload = $jsonPretty->prettify($utf8Payload);
             $this->roxClientLog .= "ROX - DEBUG generated JSON payload:\n{$jsonPrettyPayload}\n";
         }
         // empty currentTestSuite to avoid double transmission of it.
         $this->currentTestSuite = null;
     } catch (RoxClientException $e) {
         $this->roxClientLog .= $e->getMessage() . "\n";
     }
 }
Exemplo n.º 13
0
/**
 * Translate a language using INTL extension
 * 
 * @param string $locale
 * @param string $language
 */
function translate_locale($locale, $language)
{
    if (is_null($language)) {
        return null;
    } elseif (is_array($language)) {
        foreach ($language as $lang) {
            $out = translate_locale($locale, $lang);
            if (!empty($out)) {
                return $out;
            }
        }
    } elseif (is_string($language)) {
        $languageName = locale_get_display_language($locale, $language);
        $languageName = trim($languageName);
        if (empty($languageName) || strcasecmp($languageName, $locale) === 0) {
            return null;
        }
        if (strcasecmp($language, 'en') !== 0) {
            $englishName = locale_get_display_language($locale, 'en');
            if (empty($englishName) || strcasecmp($englishName, $locale) === 0 || strcasecmp($englishName, $languageName) === 0) {
                return null;
            }
        }
        $defaultLanguage = locale_get_primary_language(__DEFAULT_LOCALE__);
        if (strcasecmp($language, $defaultLanguage) !== 0) {
            $defaultName = locale_get_display_language($locale, __DEFAULT_LOCALE__);
            if (empty($defaultName) || strcasecmp($defaultName, $locale) === 0 || strcasecmp($defaultName, $languageName) === 0) {
                return null;
            }
        }
        $defaultLocale = locale_get_default();
        $defaultLanguage = locale_get_primary_language($defaultLocale);
        if (strcasecmp($language, $defaultLanguage) !== 0) {
            $defaultName = locale_get_display_language($locale, $defaultLocale);
            if (empty($defaultName) || strcasecmp($defaultName, $locale) === 0 || strcasecmp($defaultName, $languageName) === 0) {
                return null;
            }
        }
        return $languageName;
    } else {
        echo "Error: \$language must be a string or array.\n";
        exit(1);
    }
    return null;
}
Exemplo n.º 14
0
 /**
  * Captura de Localização para Javascript
  *
  * @return string Valor Solicitado
  */
 protected function getLocale()
 {
     return strtolower(str_replace('_', '-', locale_get_default()));
 }
Exemplo n.º 15
0
 public function getLocale()
 {
     return $this->locale = locale_get_default();
 }
Exemplo n.º 16
0
 public function up()
 {
     //We replaced the sessions library in CI and no longer need this table.
     if ($this->db->table_exists('sessions')) {
         $this->dbforge->drop_table('sessions');
     }
     //rename postcode_required from orders tbale
     if ($this->db->field_exists('postcode_required', 'countries')) {
         $fields = array('postcode_required' => array('name' => 'zip_required', 'type' => 'int', 'constraint' => 1));
         $this->dbforge->modify_column('countries', $fields);
     }
     //if the banner_collections table does not exist, run the migration
     if (!$this->db->table_exists('banner_collections')) {
         //create banner collections
         $this->dbforge->add_field(array('banner_collection_id' => array('type' => 'INT', 'constraint' => 4, 'unsigned' => TRUE, 'auto_increment' => TRUE), 'name' => array('type' => 'varchar', 'constraint' => 32)));
         $this->dbforge->add_key('banner_collection_id', TRUE);
         $this->dbforge->create_table('banner_collections', TRUE);
         //create 2 collections to replace the current Banners & Boxes
         $records = array(array('name' => 'Homepage Banners'), array('name' => 'Homepage Boxes'));
         $this->db->insert_batch('banner_collections', $records);
     }
     if (!$this->db->table_exists('banners')) {
         $this->dbforge->add_field(array('banner_id' => array('type' => 'int', 'constraint' => 9, 'unsigned' => true, 'auto_increment' => true), 'banner_collection_id' => array('type' => 'int', 'constraint' => 9, 'unsigned' => true, 'null' => false), 'name' => array('type' => 'varchar', 'constraint' => 128, 'null' => false), 'enable_date' => array('type' => 'date', 'null' => false), 'disable_date' => array('type' => 'date', 'null' => false), 'image' => array('type' => 'varchar', 'constraint' => 64, 'null' => false), 'link' => array('type' => 'varchar', 'constraint' => 128, 'null' => true), 'new_window' => array('type' => 'tinyint', 'constraint' => 1, 'null' => false, 'default' => 0), 'sequence' => array('type' => 'int', 'constraint' => 11, 'null' => false, 'default' => 0)));
         $this->dbforge->add_key('banner_id', true);
         $this->dbforge->create_table('banners', true);
     }
     if ($this->db->field_exists('id', 'banners')) {
         //update banner table
         //individual banners
         $fields = array('id' => array('name' => 'banner_id', 'type' => 'INT', 'constraint' => 9, 'unsigned' => TRUE, 'auto_increment' => TRUE), 'title' => array('name' => 'name', 'type' => 'varchar', 'constraint' => 128), 'enable_on' => array('name' => 'enable_date', 'type' => 'date', 'null' => TRUE), 'disable_on' => array('name' => 'disable_date', 'type' => 'date', 'null' => TRUE), 'link' => array('type' => 'varchar', 'constraint' => 255));
         $this->dbforge->modify_column('banners', $fields);
         //add the new column
         $fields = array('banner_collection_id' => array('type' => 'INT', 'constraint' => 4, 'unsigned' => TRUE));
         $this->dbforge->add_column('banners', $fields);
         //put them all in the homepage banners collection
         $this->db->where('banner_id !=', 0)->update('banners', array('banner_collection_id' => 1));
     }
     if ($this->db->table_exists('boxes')) {
         //move boxes over and delete the field.
         $boxes = $this->db->get('boxes')->result();
         if ($boxes) {
             foreach ($boxes as $b) {
                 $new_box = array('name' => $b->title, 'enable_date' => $b->enable_on, 'disable_date' => $b->disable_on, 'banner_collection_id' => 2, 'link' => $b->link, 'image' => $b->image, 'sequence' => $b->sequence, 'new_window' => $b->new_window);
                 //put the old boxes into the updated banners table with a foreign key pointing at the homepage box collection
                 $this->db->insert('banners', $new_box);
             }
         }
         //drop the boxes table
         $this->dbforge->drop_table('boxes');
     }
     if (!$this->db->field_exists('enabled', 'categories')) {
         // Add the enabled field to categories
         $fields = array('enabled' => array('type' => 'tinyint', 'constraint' => 1, 'default' => 1));
         $this->dbforge->add_column('categories', $fields);
     }
     //add username field to admin table
     if (!$this->db->field_exists('username', 'admin')) {
         // Add the enabled field to categories
         $fields = array('username' => array('type' => 'varchar', 'constraint' => 32, 'default' => '', 'null' => false));
         $this->dbforge->add_column('admin', $fields);
         //set the username to be the email by default so people can continue to login
         $admins = $this->db->get('admin')->result();
         foreach ($admins as $admin) {
             $admin->username = $admin->email;
             $this->db->where('id', $admin->id)->update('admin', $admin);
         }
     }
     //move config to the database if it exists, otherwise enter default information
     //load in the settings model
     $this->load->model('settings_model');
     $settings = $this->settings_model->get_settings('gocart');
     if (empty($settings)) {
         if (file_exists(FCPATH . 'gocart/config/gocart.php')) {
             include FCPATH . 'gocart/config/gocart.php';
             $config['order_statuses'] = json_encode($config['order_statuses']);
             //set locale to default
             $config['locale'] = locale_get_default();
             $config['currency_iso'] = $config['currency'];
             unset($config['currency']);
             unset($config['currency_symbol']);
             unset($config['currency_symbol_side']);
             unset($config['currency_decimal']);
             unset($config['currency_thousands_separator']);
         } else {
             $config['theme'] = 'default';
             $config['ssl_support'] = false;
             $config['company_name'] = '';
             $config['address1'] = '';
             $config['address2'] = '';
             $config['country'] = '';
             $config['country_id'] = '';
             $config['city'] = '';
             $config['zone_id'] = '';
             $config['state'] = '';
             $config['zip'] = '';
             $config['email'] = '';
             $config['locale'] = locale_get_default();
             $config['currency_iso'] = 'USD';
             $config['weight_unit'] = 'LB';
             $config['dimension_unit'] = 'IN';
             $config['require_shipping'] = true;
             $config['site_logo'] = '/images/logo.png';
             $config['admin_folder'] = 'admin';
             $config['new_customer_status'] = true;
             $config['require_login'] = false;
             $config['order_status'] = 'Order Placed';
             $config['order_statuses'] = json_encode(array('Order Placed' => 'Order Placed', 'Pending' => 'Pending', 'Processing' => 'Processing', 'Shipped' => 'Shipped', 'On Hold' => 'On Hold', 'Cancelled' => 'Cancelled', 'Delivered' => 'Delivered'));
             $config['inventory_enabled'] = false;
             $config['allow_os_purchase'] = true;
             $config['tax_address'] = 'ship';
             $config['tax_shipping'] = false;
         }
         //submit the settings
         $this->settings_model->save_settings('gocart', $config);
         //kill the config var
         unset($config);
     }
 }
Exemplo n.º 17
0
 /**
  * Initializes the default configuration for the object
  *
  * Called from {@link __construct()} as a first step of object instantiation.
  *
  * @param  ObjectConfig $config  An optional ObjectConfig object with configuration options.
  * @return void
  */
 protected function _initialize(ObjectConfig $config)
 {
     $config->append(array('query' => array(), 'data' => array(), 'format' => 'html', 'user' => array(), 'language' => locale_get_default(), 'timezone' => date_default_timezone_get()));
     parent::_initialize($config);
 }
Exemplo n.º 18
0
 /**
  * @runInSeparateProcess
  */
 public function testCreateWillDefaultToCurrentDefaultLocaleIfNotSet()
 {
     $this->assertEquals(locale_get_default(), (string) Factory::getLocale());
 }
Exemplo n.º 19
0
 /**
  * Initializes the options for the object
  *
  * Called from {@link __construct()} as a first step of object instantiation.
  *
  * @param   ObjectConfig $config Configuration options.
  * @return  void
  */
 protected function _initialize(ObjectConfig $config)
 {
     $config->append(array('language' => locale_get_default(), 'language_fallback' => 'en-GB', 'cache' => \Kodekit::getInstance()->isCache(), 'cache_namespace' => 'kodekit', 'catalogue' => 'default'));
     parent::_initialize($config);
 }
Exemplo n.º 20
0
 /**
  * @param string $locale
  */
 public function __construct($locale = null)
 {
     $this->locale = $locale ?: locale_get_default();
 }
Exemplo n.º 21
0
 public function index()
 {
     \CI::load()->helper('form');
     \CI::load()->library('form_validation');
     //set defaults
     $data = ['company_name' => '', 'theme' => 'default', 'homepage' => '', 'products_per_page' => '24', 'default_meta_keywords' => '', 'default_meta_description' => '', 'sendmail_path' => '/usr/sbin/sendmail -bs', 'email_from' => '', 'email_to' => '', 'email_method' => 'Mail', 'smtp_server' => '', 'smtp_username' => '', 'smtp_password' => '', 'smtp_port' => '25', 'country_id' => '', 'city' => '', 'address1' => '', 'address2' => '', 'zone_id' => '', 'zip' => '', 'locale' => locale_get_default(), 'timezone' => date_default_timezone_get(), 'currency_iso' => 'USD', 'ssl_support' => '', 'stage_username' => '', 'stage_password' => '', 'require_login' => '', 'new_customer_status' => '1', 'weight_unit' => 'LB', 'dimension_unit' => 'IN', 'order_status' => '', 'inventory_enabled' => '', 'allow_os_purchase' => '', 'tax_address' => '', 'tax_shipping' => ''];
     \CI::form_validation()->set_rules('company_name', 'lang:company_name', 'required');
     \CI::form_validation()->set_rules('default_meta_keywords', 'lang:default_meta_keywords', 'trim|strip_tags');
     \CI::form_validation()->set_rules('default_meta_description', 'lang:default_meta_description', 'trim|strip_tags');
     \CI::form_validation()->set_rules('theme', 'lang:theme', 'required');
     \CI::form_validation()->set_rules('homepage', 'lang:select_homepage');
     \CI::form_validation()->set_rules('products_per_page', 'lang:products_per_page');
     \CI::form_validation()->set_rules('email_from', 'lang:email_from', 'required|valid_email');
     \CI::form_validation()->set_rules('email_to', 'lang:email_to', 'required|valid_email');
     \CI::form_validation()->set_rules('email_method', 'lang:email_method', 'required');
     if (\CI::input()->post('email_method') == 'smtp') {
         \CI::form_validation()->set_rules('smtp_server', 'lang:smtp_server', 'required');
         \CI::form_validation()->set_rules('smtp_username', 'lang:smtp_username', 'required');
         \CI::form_validation()->set_rules('smtp_password', 'lang:smtp_password', 'required');
         \CI::form_validation()->set_rules('smtp_port', 'lang:smtp_port', 'required');
     } elseif (\CI::input()->post('email_method') == 'sendmail') {
         \CI::form_validation()->set_rules('sendmail_path', 'lang:sendmail_path', 'required');
     }
     \CI::form_validation()->set_rules('country_id', 'lang:country');
     \CI::form_validation()->set_rules('address1', 'lang:address');
     \CI::form_validation()->set_rules('address2', 'lang:address');
     \CI::form_validation()->set_rules('zone_id', 'lang:state');
     \CI::form_validation()->set_rules('zip', 'lang:zip');
     \CI::form_validation()->set_rules('locale', 'lang:locale', 'required');
     \CI::form_validation()->set_rules('timezone', 'lang:timezone', 'required');
     \CI::form_validation()->set_rules('currency_iso', 'lang:currency', 'required');
     \CI::form_validation()->set_rules('ssl_support', 'lang:ssl_support');
     \CI::form_validation()->set_rules('stage', 'lang:stage');
     \CI::form_validation()->set_rules('stage_username', 'lang:stage_username');
     \CI::form_validation()->set_rules('stage_password', 'lang:stage_password');
     \CI::form_validation()->set_rules('require_login', 'lang:require_login');
     \CI::form_validation()->set_rules('new_customer_status', 'lang:new_customer_status');
     \CI::form_validation()->set_rules('weight_unit', 'lang:weight_unit');
     \CI::form_validation()->set_rules('order_status', 'lang:order_status');
     \CI::form_validation()->set_rules('inventory_enabled', 'lang:inventory_enabled');
     \CI::form_validation()->set_rules('allow_os_purchase', 'lang:allow_os_purchase');
     \CI::form_validation()->set_rules('tax_address', 'lang:tax_address');
     \CI::form_validation()->set_rules('tax_shipping', 'lang:tax_shipping');
     // get the values from the DB
     $data = array_merge($data, \CI::Settings()->get_settings('gocart'));
     $data['config'] = $data;
     //break out order statuses to an array
     //get installed themes
     $data['themes'] = [];
     $themePath = FCPATH . 'themes/';
     if ($handle = opendir($themePath)) {
         while (false !== ($entry = readdir($handle))) {
             if ($entry != "." && $entry != ".." && is_dir($themePath . $entry)) {
                 $data['themes'][$entry] = $entry;
             }
         }
         closedir($handle);
     }
     asort($data['themes']);
     //get locales
     $locales = \ResourceBundle::getLocales('');
     $data['locales'] = [];
     foreach ($locales as $locale) {
         $data['locales'][$locale] = locale_get_display_name($locale);
     }
     asort($data['locales']);
     //get ISO 4217 codes
     $data['iso_4217'] = [];
     $iso_4217 = json_decode(json_encode(simplexml_load_file(FCPATH . 'ISO_4217.xml')));
     $iso_4217 = $iso_4217->CcyTbl->CcyNtry;
     foreach ($iso_4217 as $iso_code) {
         if (isset($iso_code->Ccy)) {
             $data['iso_4217'][$iso_code->Ccy] = $iso_code->Ccy;
         }
     }
     asort($data['iso_4217']);
     $data['countries_menu'] = \CI::Locations()->get_countries_menu();
     if (!empty($data['country_id'])) {
         $data['zones_menu'] = \CI::Locations()->get_zones_menu($data['country_id']);
     } else {
         $countries_menu = array_keys($data['countries_menu']);
         $data['zones_menu'] = \CI::Locations()->get_zones_menu(array_shift($countries_menu));
     }
     $data['page_title'] = lang('common_gocart_configuration');
     $pages = \CI::Pages()->get_pages_tiered();
     $data['pages'] = [];
     foreach ($pages['all'] as $page) {
         if (empty($page->url)) {
             $data['pages'][$page->id] = $page->title;
         }
     }
     if (\CI::form_validation()->run() == FALSE) {
         $data['error'] = validation_errors();
         $this->view('settings', $data);
     } else {
         \CI::session()->set_flashdata('message', lang('config_updated_message'));
         $save = \CI::input()->post();
         //fix boolean values
         $save['ssl_support'] = (bool) \CI::input()->post('ssl_support');
         $save['require_login'] = (bool) \CI::input()->post('require_login');
         $save['new_customer_status'] = \CI::input()->post('new_customer_status');
         $save['allow_os_purchase'] = (bool) \CI::input()->post('allow_os_purchase');
         $save['tax_shipping'] = (bool) \CI::input()->post('tax_shipping');
         $save['homepage'] = \CI::input()->post('homepage');
         \CI::Settings()->save_settings('gocart', $save);
         redirect('admin/settings');
     }
 }
Exemplo n.º 22
0
 /**
  * @param null $locale
  */
 public function __construct($locale = null)
 {
     $this->locale = is_null($locale) ? locale_get_default() : $locale;
     $this->formatter = new \NumberFormatter($this->locale, $this->style);
 }
/**
 * Sets/gets the default internal value of the locale id (for the intl extension, ICU).
 * @param string $locale (optional)	The locale id to be set. When it is omitted, the function returns (gets, reads) the default internal value.
 * @return mixed						When the function sets the default value, it returns TRUE on success or FALSE on error. Otherwise the function returns as string the current default value.
 */
function _api_set_default_locale($locale = null)
{
    static $default_locale = 'en';
    if (!empty($locale)) {
        $default_locale = $locale;
        if (INTL_INSTALLED) {
            return @locale_set_default($locale);
        }
        return true;
    } else {
        if (INTL_INSTALLED) {
            $default_locale = @locale_get_default();
        }
    }
    return $default_locale;
}
Exemplo n.º 24
0
 protected function setUp()
 {
     $this->saveLocale = \locale_get_default();
     locale_set_default('en_GB');
     $this->sut = new CurrencyBuilder(new StringType('GBP'));
 }
Exemplo n.º 25
0
array_shift($argv);
//remove program name
$argc--;
if ($argc == 3) {
    list($code, $namespace, $destDir) = $argv;
    $useLocale = false;
} else {
    list($code, $namespace, $destDir, $locale) = $argv;
    $useLocale = true;
}
if (!file_exists($destDir)) {
    echo "Invalid destination directory: {$destDir}\n";
    exit(-2);
}
$code = strtoupper($code);
if ($useLocale) {
    $saveLocale = locale_get_default();
    locale_set_default($locale);
}
try {
    $director = new CurrencyDirector(new StringType($code), new StringType($namespace), new StringType($destDir));
    $director->build();
    echo "Finished. {$code}.php written to {$destDir}\n";
} catch (\InvalidArgumentException $e) {
    echo $e->getMessage() . PHP_EOL;
    exit(-3);
}
if ($useLocale) {
    locale_set_default($saveLocale);
}
exit(0);
 public function endTestSuite(\PHPUnit_Framework_TestSuite $suite)
 {
     if (ProbeDockPHPUnitException::exceptionOccured()) {
         $this->probeLog .= "Probe Dock - WARNING RESULTS WERE NOT SENT TO PROBE DOCK.\nThis is due to previously logged errors.\n";
         return;
     } else {
         if (empty($this->currentTestSuite)) {
             // nothing to do
             return;
         }
     }
     try {
         $payload = array();
         // set test run UID
         $payload['reports'] = array(array('uid' => $this->testsRunUid));
         // set test run duration
         $endTime = intval(microtime(true) * 1000);
         // UNIX timestamp in ms
         $payload['duration'] = $endTime - $this->testSuiteStartTime;
         // set project infos
         $payload['results'] = array(array());
         // set project API identifier
         if (isset($this->config['project']['apiId'])) {
             $payload['projectId'] = $this->config['project']['apiId'];
         } else {
             throw new ProbeDockPHPUnitException("Probe Dock - ERROR missing apiId for project in config files.");
         }
         // set project version
         if (isset($this->config['project']['version'])) {
             $payload['version'] = $this->config['project']['version'];
         } else {
             throw new ProbeDockPHPUnitException("Probe Dock - ERROR missing version for project in config files.");
         }
         // set test results
         $payload['results'] = $this->currentTestSuite;
         // convert payload in UTF-8
         $utf8Payload = $this->convertEncoding($payload, self::PAYLOAD_ENCODING);
         // publish payload
         if ($this->config['payload']['publish']) {
             $jsonPayload = json_encode($utf8Payload);
             try {
                 $response = $this->httpClient->post($this->testsPayloadUrl, ['headers' => ['Content-Type' => 'application/json'], 'body' => $jsonPayload]);
             } catch (RequestException $e) {
                 throw new ProbeDockPHPUnitException("Probe Dock - ERROR: Unable to post results to Probe Dock server: {$e->getMessage()}");
             }
             if ($response->getStatusCode() == 202) {
                 $this->nbOfPayloadsSent += 1;
                 $coverageRatio = $this->nbOfProbeDockTests / $this->nbOfTests;
                 $formatter = new \NumberFormatter(locale_get_default(), \NumberFormatter::PERCENT);
                 $this->probeLog .= "Probe Dock - INFO {$this->nbOfProbeDockTests} test results successfully sent (payload {$this->nbOfPayloadsSent}) out of {$this->nbOfTests} ({$formatter->format($coverageRatio)}) tests in {$suite->getName()}.\n";
             } else {
                 $this->probeLog .= "Probe Dock - ERROR Probe Dock server ({$this->testsPayloadUrl}) returned an HTTP {$response->getStatusCode()} error:\n{$response->getBody(true)}\n";
             }
         } else {
             $this->probeLog .= "Probe Dock - WARNING RESULTS WERE NOT SENT TO PROBE DOCK.\nThis is due to 'publish' parameters in config file or to PROBEDOCK_PUBLISH environment variable.\n";
         }
         // save payload
         if (isset($this->config['payload']['save']) && $this->config['payload']['save']) {
             if (!isset($this->config['workspace'])) {
                 throw new ProbeDockPHPUnitException("Probe Dock - ERROR no 'workspace' parameter in config files. Could not save payload.");
             }
             $payloadDirPath = "{$this->config['workspace']}/phpunit/servers/{$this->config['server']}";
             if (!file_exists($payloadDirPath)) {
                 mkdir($payloadDirPath, 0755, true);
             }
             if (file_put_contents($payloadDirPath . "/payload.json", $jsonPayload)) {
                 $this->probeLog .= "Probe Dock - INFO payload saved in workspace.\n";
             } else {
                 throw new ProbeDockPHPUnitException("Probe Dock - ERROR unable to save payload in workspace");
             }
         }
         // print payload for DEBUG purpose
         if (isset($this->config['payload']['print']) && $this->config['payload']['print']) {
             $jsonPretty = new \Camspiers\JsonPretty\JsonPretty();
             $jsonPrettyPayload = $jsonPretty->prettify($utf8Payload);
             $this->probeLog .= "Probe Dock - DEBUG generated JSON payload:\n{$jsonPrettyPayload}\n";
         }
         // empty currentTestSuite to avoid double transmission of it.
         $this->currentTestSuite = array();
     } catch (ProbeDockPHPUnitException $e) {
         $this->probeLog .= $e->getMessage() . "\n";
     }
 }