Example #1
1
 /**
  * (non-PHPdoc)
  * @see CPortlet::renderContent()
  */
 protected function renderContent()
 {
     $themesList = array_combine(Yii::app()->themeManager->themeNames, Yii::app()->themeManager->themeNames);
     echo CHtml::form('', 'post', array());
     echo CHtml::dropDownList('themeSelector', Yii::app()->theme->name, $themesList, $this->dropDownOptions);
     echo CHtml::endForm();
 }
Example #2
0
 /**
  * format a monetary string
  *
  * Format a monetary string basing on the amount provided,
  * ISO currency code provided and a format string consisting of:
  *
  * %a - the formatted amount
  * %C - the currency ISO code (e.g., 'USD') if provided
  * %c - the currency symbol (e.g., '$') if available
  *
  * @param float  $amount    the monetary amount to display (1234.56)
  * @param string $currency  the three-letter ISO currency code ('USD')
  * @param string $format    the desired currency format
  *
  * @return string  formatted monetary string
  *
  * @static
  */
 static function format($amount, $currency = null, $format = null)
 {
     if (CRM_Utils_System::isNull($amount)) {
         return '';
     }
     $config =& CRM_Core_Config::singleton();
     if (!self::$_currencySymbols) {
         require_once "CRM/Core/PseudoConstant.php";
         $currencySymbolName = CRM_Core_PseudoConstant::currencySymbols('name');
         $currencySymbol = CRM_Core_PseudoConstant::currencySymbols();
         self::$_currencySymbols = array_combine($currencySymbolName, $currencySymbol);
     }
     if (!$currency) {
         $currency = $config->defaultCurrency;
     }
     if (!$format) {
         $format = $config->moneyformat;
     }
     // money_format() exists only in certain PHP install (CRM-650)
     if (is_numeric($amount) and function_exists('money_format')) {
         $amount = money_format($config->moneyvalueformat, $amount);
     }
     $replacements = array('%a' => $amount, '%C' => $currency, '%c' => CRM_Utils_Array::value($currency, self::$_currencySymbols, $currency));
     return strtr($format, $replacements);
 }
Example #3
0
 /**
  * {@inheritdoc}
  */
 public function form(array $form, FormStateInterface $form_state)
 {
     $form = parent::form($form, $form_state);
     $type = $this->entity;
     if ($this->operation == 'add') {
         $form['#title'] = $this->t('Add log type');
         $fields = $this->entityManager->getBaseFieldDefinitions('log');
         // Create a node with a fake bundle using the type's UUID so that we can
         // get the default values for workflow settings.
         // @todo Make it possible to get default values without an entity.
         //   https://www.drupal.org/node/2318187
         $node = $this->entityManager->getStorage('log')->create(array('type' => $type->uuid()));
     } else {
         $form['#title'] = $this->t('Edit %label log type', array('%label' => $type->label()));
         $fields = $this->entityManager->getFieldDefinitions('log', $type->id());
         // Create a node to get the current values for workflow settings fields.
         $node = $this->entityManager->getStorage('log')->create(array('type' => $type->id()));
     }
     $form['name'] = array('#title' => t('Name'), '#type' => 'textfield', '#default_value' => $type->label(), '#description' => t('The human-readable name of this log type. This text will be displayed as part of the list on the <em>Add content</em> page. This name must be unique.'), '#required' => TRUE, '#size' => 30);
     $form['type'] = array('#type' => 'machine_name', '#default_value' => $type->id(), '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH, '#machine_name' => array('exists' => ['Drupal\\node\\Entity\\LogType', 'load'], 'source' => array('name')), '#description' => t('A unique machine-readable name for this content type. It must only contain lowercase letters, numbers, and underscores. This name will be used for constructing the URL of the %log-add page, in which underscores will be converted into hyphens.', array('%log-add' => t('Add content'))));
     $form['description'] = array('#title' => t('Description'), '#type' => 'textarea', '#default_value' => $type->getDescription(), '#description' => t('This text will be displayed on the <em>Add new content</em> page.'));
     $form['additional_settings'] = array('#type' => 'vertical_tabs', '#attached' => array('library' => array('node/drupal.content_types')));
     $form['submission'] = array('#type' => 'details', '#title' => t('Submission form settings'), '#group' => 'additional_settings', '#open' => TRUE);
     $form['submission']['preview_mode'] = array('#type' => 'radios', '#title' => t('Preview before submitting'), '#default_value' => $type->getPreviewMode(), '#options' => array(DRUPAL_DISABLED => t('Disabled'), DRUPAL_OPTIONAL => t('Optional'), DRUPAL_REQUIRED => t('Required')));
     $form['submission']['help'] = array('#type' => 'textarea', '#title' => t('Explanation or submission guidelines'), '#default_value' => $type->getHelp(), '#description' => t('This text will be displayed at the top of the page when creating or editing content of this type.'));
     $form['workflow'] = array('#type' => 'details', '#title' => t('Publishing options'), '#group' => 'additional_settings');
     $workflow_options = array('status' => $node->status->value, 'promote' => $node->promote->value, 'sticky' => $node->sticky->value, 'revision' => $type->isNewRevision());
     // Prepare workflow options to be used for 'checkboxes' form element.
     $keys = array_keys(array_filter($workflow_options));
     $workflow_options = array_combine($keys, $keys);
     $form['workflow']['options'] = array('#type' => 'checkboxes', '#title' => t('Default options'), '#default_value' => $workflow_options, '#options' => array('status' => t('Published'), 'promote' => t('Promoted to front page'), 'sticky' => t('Sticky at top of lists'), 'revision' => t('Create new revision')), '#description' => t('Users with the <em>Administer content</em> permission will be able to override these options.'));
     $form['display'] = array('#type' => 'details', '#title' => t('Display settings'), '#group' => 'additional_settings');
     $form['display']['display_submitted'] = array('#type' => 'checkbox', '#title' => t('Display author and date information'), '#default_value' => $type->displaySubmitted(), '#description' => t('Author username and publish date will be displayed.'));
     return $this->protectBundleIdElement($form);
 }
 public function getWidgetOptionsForColumn($column)
 {
     $options = array();
     $withEmpty = sprintf('\'with_empty\' => %s', $column->isNotNull() ? 'false' : 'true');
     switch ($column->getDoctrineType()) {
         case 'boolean':
             $options[] = "'choices' => array('' => dm::getI18n()->__('yes or no', array(), 'dm'), 1 => dm::getI18n()->__('yes', array(), 'dm'), 0 => dm::getI18n()->__('no', array(), 'dm'))";
             break;
         case 'date':
         case 'datetime':
         case 'timestamp':
             $widget = 'new sfWidgetFormInputText(array(), array("class" => "datepicker_me"))';
             $options[] = "'from_date' => {$widget}, 'to_date' => {$widget}";
             $options[] = $withEmpty;
             break;
         case 'enum':
             $values = array('' => '');
             $values = array_merge($values, $column['values']);
             $values = array_combine($values, $values);
             $options[] = "'choices' => " . str_replace("\n", '', $this->arrayExport($values));
             break;
     }
     if ($column->isForeignKey()) {
         $options[] = sprintf('\'model\' => \'%s\', \'add_empty\' => true', $column->getForeignTable()->getOption('name'));
     }
     return count($options) ? sprintf('array(%s)', implode(', ', $options)) : '';
 }
function wds_autolinks_settings()
{
    $name = 'wds_autolinks';
    $title = __('Automatic Links', 'wds');
    $description = __('<p>Sometimes you want to always link certain key words to a page on your blog or even a whole new site all together.</p>
	<p>For example, maybe anytime you write the words \'WordPress news\' you want to automatically create a link to the WordPress news blog, wpmu.org. Without this plugin, you would have to manually create these links each time you write the text in your pages and posts - which can be no fun at all.</p>
	<p>This section lets you set those key words and links. First, choose if you want to automatically link key words in posts, pages, or any custom post types you might be using. Usually when you are using automatic links, you will want to check all of the options here.</p>', 'wds');
    $fields = array();
    foreach (get_post_types() as $post_type) {
        if (!in_array($post_type, array('revision', 'nav_menu_item', 'attachment'))) {
            $pt = get_post_type_object($post_type);
            $key = strtolower($pt->name);
            $post_types["l{$key}"] = $pt->labels->name;
            $insert["{$key}"] = $pt->labels->name;
        }
    }
    foreach (get_taxonomies() as $taxonomy) {
        if (!in_array($taxonomy, array('nav_menu', 'link_category', 'post_format'))) {
            $tax = get_taxonomy($taxonomy);
            $key = strtolower($tax->labels->name);
            $taxonomies["l{$key}"] = $tax->labels->name;
        }
    }
    $linkto = array_merge($post_types, $taxonomies);
    $insert['comment'] = __('Comments', 'wds');
    $fields['internal'] = array('title' => '', 'intro' => '', 'options' => array(array('type' => 'checkbox', 'name' => 'insert', 'title' => __('Insert links in', 'wds'), 'items' => $insert), array('type' => 'checkbox', 'name' => 'linkto', 'title' => __('Link to', 'wds'), 'items' => $linkto), array('type' => 'dropdown', 'name' => 'cpt_char_limit', 'title' => __('Minimum post title length', 'wds'), 'description' => __('This is the minimum number of characters your post title has to have to be considered for insertion as auto-link.', 'wds'), 'items' => array_combine(array_merge(array(0), range(1, 25)), array_merge(array(__('Default', 'wds')), range(1, 25)))), array('type' => 'dropdown', 'name' => 'tax_char_limit', 'title' => __('Minimum taxonomy title length', 'wds'), 'description' => __('This is the minimum number of characters your taxonomy title has to have to be considered for insertion as auto-link.', 'wds'), 'items' => array_combine(array_merge(array(0), range(1, 25)), array_merge(array(__('Default', 'wds')), range(1, 25)))), array('type' => 'checkbox', 'name' => 'allow_empty_tax', 'title' => __('Empty taxonomies', 'wds'), 'items' => array('allow_empty_tax' => __('Allow autolinks to empty taxonomies', 'wds'))), array('type' => 'checkbox', 'name' => 'excludeheading', 'title' => __('Exclude Headings', 'wds'), 'items' => array('excludeheading' => __('Prevent linking in heading tags', 'wds'))), array('type' => 'text', 'name' => 'ignorepost', 'title' => __('Ignore posts and pages', 'wds'), 'description' => __('Paste in the IDs, slugs or titles for the post/pages you wish to exclude and separate them by commas', 'wds')), array('type' => 'text', 'name' => 'ignore', 'title' => __('Ignore keywords', 'wds'), 'description' => __('Paste in the keywords you wish to exclude and separate them by commas', 'wds')), array('type' => 'dropdown', 'name' => 'link_limit', 'title' => __('Maximum autolinks number limit', 'wds'), 'description' => __('This is the maximum number of autolinks that will be added to your posts.', 'wds'), 'items' => array_combine(array_merge(array(0), range(1, 20)), array_merge(array(__('Unlimited', 'wds')), range(1, 20)))), array('type' => 'dropdown', 'name' => 'single_link_limit', 'title' => __('Maximum single autolink occurrence', 'wds'), 'description' => __('This is a number of single link replacement occurrences.', 'wds'), 'items' => array_combine(array_merge(array(0), range(1, 10)), array_merge(array(__('Unlimited', 'wds')), range(1, 10)))), array('type' => 'textarea', 'name' => 'customkey', 'title' => __('Custom Keywords', 'wds'), 'description' => __('Paste in the extra keywords you want to automaticaly link. Use comma to seperate keywords and add target url at the end. Use a new line for new url and set of keywords.
				<br />Example:<br />
				<code>WPMU DEV, plugins, themes, http://premium.wpmudev.org/<br />
				WordPress News, http://wpmu.org/<br /></code>', 'wds')), array('type' => 'checkbox', 'name' => 'reduceload', 'title' => __('Other settings', 'wds'), 'items' => array('onlysingle' => __('Process only single posts and pages', 'wds'), 'allowfeed' => __('Process RSS feeds', 'wds'), 'casesens' => __('Case sensitive matching', 'wds'), 'customkey_preventduplicatelink' => __('Prevent duplicate links', 'wds'), 'target_blank' => __('Open links in new tab/window', 'wds'), 'rel_nofollow' => __('Autolinks <code>nofollow</code>', 'wds')))));
    $contextual_help = '';
    if (wds_is_wizard_step('5')) {
        $settings = new WDS_Core_Admin_Tab($name, $title, $description, $fields, 'wds', $contextual_help);
    }
}
Example #6
0
 /**
  * @group mapper
  * @covers \PHPExif\Mapper\Native::mapRawData
  */
 public function testMapRawDataMapsFieldsCorrectly()
 {
     $reflProp = new \ReflectionProperty(get_class($this->mapper), 'map');
     $reflProp->setAccessible(true);
     $map = $reflProp->getValue($this->mapper);
     // ignore custom formatted data stuff:
     unset($map[\PHPExif\Mapper\Native::DATETIMEORIGINAL]);
     unset($map[\PHPExif\Mapper\Native::EXPOSURETIME]);
     unset($map[\PHPExif\Mapper\Native::FOCALLENGTH]);
     unset($map[\PHPExif\Mapper\Native::XRESOLUTION]);
     unset($map[\PHPExif\Mapper\Native::YRESOLUTION]);
     unset($map[\PHPExif\Mapper\Native::GPSLATITUDE]);
     unset($map[\PHPExif\Mapper\Native::GPSLONGITUDE]);
     // create raw data
     $keys = array_keys($map);
     $values = array();
     $values = array_pad($values, count($keys), 'foo');
     $rawData = array_combine($keys, $values);
     $mapped = $this->mapper->mapRawData($rawData);
     $i = 0;
     foreach ($mapped as $key => $value) {
         $this->assertEquals($map[$keys[$i]], $key);
         $i++;
     }
 }
Example #7
0
 public function getDocs()
 {
     if (!isset($this->meta['keyword'], $this->meta['docs'])) {
         return [];
     }
     return array_combine($this->meta['keyword'], $this->meta['docs']);
 }
 function buildSchema($id)
 {
     $notInput = array('fieldset', 'textonly');
     App::import('Model', 'Cforms.Cform');
     $this->Cform = new Cform();
     $cform = $this->Cform->find('first', array('conditions' => array('Cform.id' => $id), 'contain' => array('FormField', 'FormField.ValidationRule')));
     $schema = array();
     $validate = array();
     foreach ($cform['FormField'] as &$field) {
         if (!in_array($field['type'], $notInput)) {
             $schema[$field['name']] = array('type' => 'string', 'length' => $field['length'], 'null' => null, 'default' => $field['default']);
             if (!empty($field['ValidationRule'])) {
                 foreach ($field['ValidationRule'] as $rule) {
                     $validate[$field['name']][$rule['rule']] = array('rule' => $rule['rule'], 'message' => $rule['message'], 'allowEmpty' => $field['required'] ? false : true);
                 }
             } elseif ($field['required']) {
                 $validate[$field['name']] = array('notBlank');
             }
             if (!empty($field['depends_on']) && !empty($field['depends_value'])) {
                 $dependsOn[$field['name']] = array('field' => $field['depends_on'], 'value' => $field['depends_value']);
             }
             $field['options'] = str_replace(', ', ',', $field['options']);
             $options = explode(',', $field['options']);
             $field['options'] = array_combine($options, $options);
         }
     }
     $this->validate = $validate;
     $this->_schema = $schema;
     $this->dependsOn = isset($dependsOn) ? $dependsOn : array();
     return $cform;
 }
Example #9
0
 /**
  * List all user groups of a single backend
  */
 public function listAction()
 {
     $this->assertPermission('config/authentication/groups/show');
     $this->createListTabs()->activate('group/list');
     $backendNames = array_map(function ($b) {
         return $b->getName();
     }, $this->loadUserGroupBackends('Icinga\\Data\\Selectable'));
     if (empty($backendNames)) {
         return;
     }
     $this->view->backendSelection = new Form();
     $this->view->backendSelection->setAttrib('class', 'backend-selection');
     $this->view->backendSelection->setUidDisabled();
     $this->view->backendSelection->setMethod('GET');
     $this->view->backendSelection->setTokenDisabled();
     $this->view->backendSelection->addElement('select', 'backend', array('autosubmit' => true, 'label' => $this->translate('Usergroup Backend'), 'multiOptions' => array_combine($backendNames, $backendNames), 'value' => $this->params->get('backend')));
     $backend = $this->getUserGroupBackend($this->params->get('backend'));
     if ($backend === null) {
         $this->view->backend = null;
         return;
     }
     $query = $backend->select(array('group_name'));
     $filterEditor = Widget::create('filterEditor')->setQuery($query)->setSearchColumns(array('group', 'user'))->preserveParams('limit', 'sort', 'dir', 'view', 'backend')->ignoreParams('page')->handleRequest($this->getRequest());
     $query->applyFilter($filterEditor->getFilter());
     $this->setupFilterControl($filterEditor);
     $this->view->groups = $query;
     $this->view->backend = $backend;
     $this->setupPaginationControl($query);
     $this->setupLimitControl();
     $this->setupSortControl(array('group_name' => $this->translate('Group'), 'created_at' => $this->translate('Created at'), 'last_modified' => $this->translate('Last modified')), $query);
 }
Example #10
0
/**
 * @param  array $words   ๆŠฝๅ‡บๅฏพ่ฑกใฎ้…ๅˆ—($weightsใจ่ฆ็ด ๆ•ฐใฏๅŒๆ•ฐ)
 * @param  array $weights ้‡ใฟใฎ้…ๅˆ—(่ฆ็ด ใฏintๅž‹)
 *
 * @return mixed $word    ๆŠฝๅ‡บใ•ใ‚ŒใŸ่ฆ็ด 
 *
 * @throws Exception      Validationใ‚จใƒฉใƒผๆ™‚ใซๆŠ•ใ’ใ‚‰ใ‚Œใ‚‹ไพ‹ๅค–
 */
function lotteryWeighted($words, $weights)
{
    //Validation.
    try {
        foreach ($weights as $weight) {
            if (!is_int($weight)) {
                throw new Exception("Weights only type int.");
            }
        }
        $targets = array_combine($words, $weights);
        if (!$targets) {
            throw new Exception("The number of elements does not match.");
        }
    } catch (Exception $e) {
        echo $e->getMessage();
        exit;
    }
    //ๆŠฝๅ‡บ
    $sum = array_sum($targets);
    $judgeVal = rand(1, $sum);
    foreach ($targets as $word => $weight) {
        if (($sum -= $weight) < $judgeVal) {
            return $word;
        }
    }
}
Example #11
0
/**
 * Delete all objects from SubClass
 *
 * @param int SubClassID
 */
function SubClassClear($SubClassID)
{
    global $nc_core, $db, $MODULE_FOLDER;
    // full info about this subclass
    $SubClassID = intval($SubClassID);
    $res = $db->get_row("SELECT `Catalogue_ID`, `Subdivision_ID`, `Class_ID` FROM `Sub_Class` WHERE `Sub_Class_ID` = '" . $SubClassID . "'", ARRAY_A);
    if (nc_module_check_by_keyword("comments")) {
        include_once $MODULE_FOLDER . "comments/function.inc.php";
        // delete comment rules
        nc_comments::dropRuleSubClass($db, $SubClassID);
        // delete comments
        nc_comments::dropComments($db, $SubClassID, "Sub_Class");
    }
    DeleteSubClassFiles($SubClassID, $res['Class_ID']);
    // delete from message
    $messages_id = $db->get_col("SELECT `Message_ID` FROM `Message" . $res['Class_ID'] . "` WHERE `Subdivision_ID` = '" . $res['Subdivision_ID'] . "' AND `Sub_Class_ID` = '" . $SubClassID . "'");
    if (!empty($messages_id)) {
        if ($db->query("SELECT * FROM `Message" . $res['Class_ID'] . "` WHERE `Message_ID` IN (" . join(", ", $messages_id) . ")")) {
            $messages_data = array_combine($db->get_col(NULL, 0), $db->get_results(NULL));
        }
        // execute core action
        $nc_core->event->execute("dropMessagePrep", $res['Catalogue_ID'], $res['Subdivision_ID'], $SubClassID, $res['Class_ID'], $messages_id, $messages_data);
        $db->query("DELETE FROM `Message" . $res['Class_ID'] . "` WHERE `Message_ID` IN (" . join(", ", $messages_id) . ")");
        // execute core action
        $nc_core->event->execute("dropMessage", $res['Catalogue_ID'], $res['Subdivision_ID'], $SubClassID, $res['Class_ID'], $messages_id, $messages_data);
    }
    return;
}
 /**
  * Builds the form.
  *
  * This method is called for each type in the hierarchy starting form the
  * top most type. Type extensions can further modify the form.
  *
  * @see FormTypeExtensionInterface::buildForm()
  *
  * @param FormBuilderInterface $builder The form builder
  * @param array                $options The options
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $entityId = $this->entityId;
     $menu = $this->menu;
     $menuItemclass = $this->menuItemClass;
     $builder->add('parent', EntityType::class, array('class' => $menuItemclass, 'choice_label' => 'displayTitle', 'query_builder' => function (EntityRepository $er) use($entityId, $menu) {
         $qb = $er->createQueryBuilder('mi')->where('mi.menu = :menu')->setParameter('menu', $menu)->orderBy('mi.lft', 'ASC');
         if ($entityId) {
             $qb->andWhere('mi.id != :id')->setParameter('id', $entityId);
         }
         return $qb;
     }, 'attr' => array('class' => 'js-advanced-select', 'data-placeholder' => 'Select the parent menu item...'), 'multiple' => false, 'expanded' => false, 'required' => false, 'label' => 'Parent menu item'));
     $builder->add('type', ChoiceType::class, array('choices' => array_combine(MenuItem::$types, MenuItem::$types), 'placeholder' => false, 'required' => true));
     $locale = $this->locale;
     $rootNode = $this->rootNode;
     $builder->add('nodeTranslation', EntityType::class, array('class' => 'KunstmaanNodeBundle:NodeTranslation', 'choice_label' => 'title', 'query_builder' => function (EntityRepository $er) use($locale, $rootNode) {
         $qb = $er->createQueryBuilder('nt')->innerJoin('nt.publicNodeVersion', 'nv')->innerJoin('nt.node', 'n')->where('n.deleted = 0')->andWhere('nt.lang = :lang')->setParameter('lang', $locale)->andWhere('nt.online = 1')->orderBy('nt.title', 'ASC');
         if ($rootNode) {
             $qb->andWhere('n.lft >= :left')->andWhere('n.rgt <= :right')->setParameter('left', $rootNode->getLeft())->setParameter('right', $rootNode->getRight());
         }
         return $qb;
     }, 'attr' => array('class' => 'js-advanced-select', 'data-placeholder' => 'Select the page to link to...'), 'multiple' => false, 'expanded' => false, 'required' => true, 'label' => 'Link page'));
     $builder->add('title', TextType::class, array('required' => false));
     $builder->add('url', TextType::class, array('required' => true));
     $builder->add('newWindow');
 }
 /**
  * Initializes the FTL Manager.
  * 
  * @return void
  */
 public static function init()
 {
     if (self::$_inited) {
         return;
     }
     self::$_inited = TRUE;
     self::$ci =& get_instance();
     self::$context = new FTL_ArrayContext();
     // Inlude array of module definition. This file is generated by module installation in Ionize.
     // This file contains definition for installed modules only.
     include APPPATH . 'config/modules.php';
     // Put modules arrays keys to lowercase
     if (!empty($modules)) {
         self::$module_folders = array_combine(array_map('strtolower', array_values($modules)), array_values($modules));
     }
     // Loads automatically all installed modules tags
     foreach (self::$module_folders as $module) {
         self::autoload_module_tags($module . '_Tags');
     }
     // Load automatically all TagManagers defined in /libraries/Tagmanager
     $tagmanagers = glob(APPPATH . 'libraries/Tagmanager/*' . EXT);
     foreach ($tagmanagers as $tagmanager) {
         self::autoload(array_pop(explode('/', $tagmanager)));
     }
     self::add_globals('TagManager');
     self::add_tags();
     self::add_module_tags();
 }
Example #14
0
 /**
  * Get Cache Value
  *
  * @param mixed $id
  * @return mixed
  */
 public function get($id)
 {
     if (is_string($id)) {
         return $this->conn->get($id);
     }
     return array_combine($id, $this->conn->mGet($id));
 }
Example #15
0
 public function getMargins($list = null)
 {
     if (!$list) {
         return $this->margins;
     }
     return array_intersect_key($this->margins, array_combine($list, $list));
 }
Example #16
0
 protected function __createHeader($header, $keys)
 {
     $header = array_combine($keys, $header);
     foreach ($header as $key => $vo) {
         $this->excelObj->setActiveSheetIndex(0)->setCellValue("{$key}1", $vo);
     }
 }
Example #17
0
 function current()
 {
     $fpLoc = ftell($this->fp);
     $data = $this->fgetcsv();
     fseek($this->fp, $fpLoc);
     return array_combine($this->map, $data);
 }
Example #18
0
 private function _format_stock_list($stock_list = array())
 {
     //ๅกซๅ……ไป“ๅบ“ๅ
     $warehouse_list = $this->_get_warehouses();
     $warehouse_ids = array_column($warehouse_list, 'warehouse_id');
     $warehouse_names = array_column($warehouse_list, 'warehouse_name');
     $warehouse_map = array_combine($warehouse_ids, $warehouse_names);
     $sku_numbers = array_column($stock_list, 'sku_number');
     $skus = $this->MSku->get_lists('*', array('in' => array('sku_number' => $sku_numbers)));
     $sku_numbers = array_column($skus, 'sku_number');
     $sku_map = array_combine($sku_numbers, $skus);
     //print_r($warehouse_map);
     foreach ($stock_list as &$item) {
         $warehouse_id = $item['warehouse_id'];
         $item['warehouse_name'] = isset($warehouse_map[$warehouse_id]) ? $warehouse_map[$warehouse_id] : '';
         //ๅฏๅ”ฎๅบ“ๅญ˜
         $item['sellable'] = $item['in_stock'] - $item['stock_locked'];
         $sku_number = $item['sku_number'];
         $item['sku_name'] = $sku_map[$sku_number]['name'];
         //print_r($warehouse_map[$warehouse_id]);
         //
         //้™่ดญๅ€ผ้œ€่ฆๅŽปredisๅ–
     }
     unset($item);
     return $stock_list;
 }
Example #19
0
function season($indoor)
{
    // The configuration settings values have "0" for the year, to facilitate form input
    $today = date('0-m-d');
    $today_wrap = date('1-m-d');
    // Build the list of applicable seasons
    $seasons = Configure::read('options.season');
    unset($seasons['None']);
    if (empty($seasons)) {
        return 'None';
    }
    foreach (array_keys($seasons) as $season) {
        $season_indoor = Configure::read("season_is_indoor.{$season}");
        if ($indoor != $season_indoor) {
            unset($seasons[$season]);
        }
    }
    // Create array of which season follows which
    $seasons = array_values($seasons);
    $seasons_shift = $seasons;
    array_push($seasons_shift, array_shift($seasons_shift));
    $next = array_combine($seasons, $seasons_shift);
    // Look for the season that has started without the next one starting
    foreach ($next as $a => $b) {
        $start = Configure::read('organization.' . Inflector::slug(low($a)) . '_start');
        $end = Configure::read('organization.' . Inflector::slug(low($b)) . '_start');
        // Check for a season that wraps past the end of the year
        if ($start > $end) {
            $end[0] = '1';
        }
        if ($today >= $start && $today < $end || $today_wrap >= $start && $today_wrap < $end) {
            return $a;
        }
    }
}
 /**
  * Function to convert csv data into an
  * associative array. Sourced from
  * http://pastebin.com/LtmGzpxF
  * @param $filename
  * @param string $delimiter
  * @return array|bool
  */
 protected function csv_to_array($filename, $delimiter = ',')
 {
     // If the file doesn't exist, or isn't readable,
     // return false. The seeding will fail at this point.
     if (!file_exists($filename) || !is_readable($filename)) {
         return false;
     }
     $header = NULL;
     $data = array();
     if (($handle = fopen($filename, 'r')) !== FALSE) {
         // While there are still rows in the file
         while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
             // Below conditional forms the associated array,
             // filling each array within with data from each
             // row.
             if (!$header) {
                 $header = $row;
             } else {
                 $data[] = array_combine($header, $row);
             }
         }
         // Close access to the file.
         fclose($handle);
     }
     return $data;
 }
 public function definition()
 {
     $mform = $this->_form;
     $hiddenofvisible = array(question_display_options::HIDDEN => get_string('notshown', 'question'), question_display_options::VISIBLE => get_string('shown', 'question'));
     $mform->addElement('header', 'optionsheader', get_string('changeoptions', 'question'));
     $behaviours = question_engine::get_behaviour_options($this->_customdata['quba']->get_preferred_behaviour());
     $mform->addElement('select', 'behaviour', get_string('howquestionsbehave', 'question'), $behaviours);
     $mform->addHelpButton('behaviour', 'howquestionsbehave', 'question');
     $mform->addElement('text', 'maxmark', get_string('markedoutof', 'question'), array('size' => '5'));
     $mform->setType('maxmark', PARAM_NUMBER);
     if ($this->_customdata['maxvariant'] > 1) {
         $variants = range(1, $this->_customdata['maxvariant']);
         $mform->addElement('select', 'variant', get_string('questionvariant', 'question'), array_combine($variants, $variants));
     }
     $mform->setType('maxmark', PARAM_INT);
     $mform->addElement('select', 'correctness', get_string('whethercorrect', 'question'), $hiddenofvisible);
     $marksoptions = array(question_display_options::HIDDEN => get_string('notshown', 'question'), question_display_options::MAX_ONLY => get_string('showmaxmarkonly', 'question'), question_display_options::MARK_AND_MAX => get_string('showmarkandmax', 'question'));
     $mform->addElement('select', 'marks', get_string('marks', 'question'), $marksoptions);
     $mform->addElement('select', 'markdp', get_string('decimalplacesingrades', 'question'), question_engine::get_dp_options());
     $mform->addElement('select', 'feedback', get_string('specificfeedback', 'question'), $hiddenofvisible);
     $mform->addElement('select', 'generalfeedback', get_string('generalfeedback', 'question'), $hiddenofvisible);
     $mform->addElement('select', 'rightanswer', get_string('rightanswer', 'question'), $hiddenofvisible);
     $mform->addElement('select', 'history', get_string('responsehistory', 'question'), $hiddenofvisible);
     $mform->addElement('submit', 'submit', get_string('restartwiththeseoptions', 'question'), $hiddenofvisible);
 }
 public function getDetails($cate)
 {
     $model = $this->findAllByAttributes(array('opt_category' => $cate));
     $result = CHtml::listData($model, 'id', 'details');
     $value = array_values($result);
     return array_combine($value, $value);
 }
 public function importMotorsDataAction()
 {
     $helper = Mage::helper('M2ePro/Component_Ebay_Motors');
     $motorsType = $this->getRequest()->getPost('motors_type');
     if (!$motorsType || empty($_FILES['source']['tmp_name'])) {
         $this->getSession()->addError(Mage::helper('M2ePro')->__('Some of required fields are not filled up.'));
         return $this->_redirect('*/*/index');
     }
     $csvParser = new Varien_File_Csv();
     $tempCsvData = $csvParser->getData($_FILES['source']['tmp_name']);
     $csvData = array();
     $headers = array_shift($tempCsvData);
     foreach ($tempCsvData as $csvRow) {
         $csvData[] = array_combine($headers, $csvRow);
     }
     $added = 0;
     $existedItems = $this->getExistedMotorsItems();
     $connWrite = Mage::getSingleton('core/resource')->getConnection('core/write');
     $tableName = $helper->getDictionaryTable($motorsType);
     foreach ($csvData as $csvRow) {
         if (!($insertsData = $this->getPreparedInsertData($csvRow, $existedItems))) {
             continue;
         }
         $added++;
         $connWrite->insert($tableName, $insertsData);
     }
     $this->_getSession()->addSuccess("Successfully added '{$added}' compatibility records.");
     return $this->_redirect('*/*/index');
 }
 /**
  * Handles form submission
  * @param array $data
  * @return bool|\SS_HTTPResponse
  */
 public function addtocart(array $data)
 {
     $groupedProduct = $this->getController()->data();
     if (empty($data) || empty($data['Product']) || !is_array($data['Product'])) {
         $this->sessionMessage(_t('GroupedCartForm.EMPTY', 'Please select at least one product.'), 'bad');
         $this->extend('updateErrorResponse', $this->request, $response, $groupedProduct, $data, $this);
         return $response ? $response : $this->controller->redirectBack();
     }
     $cart = ShoppingCart::singleton();
     foreach ($data['Product'] as $id => $prodReq) {
         if (!empty($prodReq['Quantity']) && $prodReq['Quantity'] > 0) {
             $prod = Product::get()->byID($id);
             if ($prod && $prod->exists()) {
                 $saveabledata = !empty($this->saveablefields) ? Convert::raw2sql(array_intersect_key($data, array_combine($this->saveablefields, $this->saveablefields))) : $prodReq;
                 $buyable = $prod;
                 if (isset($prodReq['Attributes'])) {
                     $buyable = $prod->getVariationByAttributes($prodReq['Attributes']);
                     if (!$buyable || !$buyable->exists()) {
                         $this->sessionMessage("{$prod->InternalItemID} is not available with the selected options.", "bad");
                         $this->extend('updateErrorResponse', $this->request, $response, $groupedProduct, $data, $this);
                         return $response ? $response : $this->controller->redirectBack();
                     }
                 }
                 if (!$cart->add($buyable, (int) $prodReq['Quantity'], $saveabledata)) {
                     $this->sessionMessage($cart->getMessage(), $cart->getMessageType());
                     $this->extend('updateErrorResponse', $this->request, $response, $groupedProduct, $data, $this);
                     return $response ? $response : $this->controller->redirectBack();
                 }
             }
         }
     }
     $this->extend('updateGroupCartResponse', $this->request, $response, $groupedProduct, $data, $this);
     return $response ? $response : ShoppingCart_Controller::direct($cart->getMessageType());
 }
Example #25
0
function tom_validate_create_options($input)
{
    /* If have value from new group */
    if (!empty($input['new-group']['name'])) {
        $idFromName = sanitize_title_with_dashes($input['new-group']['name']);
        $input[$idFromName]['name'] = $input['new-group']['name'];
        $input[$idFromName]['type'] = 'heading';
        $input[$idFromName]['desc'] = $input['new-group']['desc'];
        unset($input['new-group']);
    } else {
        if (isset($input['new-group'])) {
            unset($input['new-group']);
        }
    }
    $value['options'] = array();
    $haveoptions = array();
    /* Parse input options */
    foreach ($input as $key => $value) {
        if (!empty($value['options'])) {
            /* combine input value key and input value to one array as key => value */
            $combine[$key]['options'] = array_combine($value['options']['opt-key'], $value['options']['opt-val']);
            /* get other field like name, type */
            $org[$key] = $value;
            /* Merge options field */
            $haveoptions[$key] = array_merge($org[$key], $combine[$key]);
        }
        $input = array_merge($input, $haveoptions);
    }
    /* Merge with main input */
    $input = array_merge($input, $haveoptions);
    return json_encode($input);
}
Example #26
0
 public function getWelcomeTemplateOptions()
 {
     $codes = array_keys(MailTemplate::listAllTemplates());
     $result = ['' => '- ' . Lang::get('rainlab.user::lang.settings.no_mail_template') . ' -'];
     $result += array_combine($codes, $codes);
     return $result;
 }
Example #27
0
 public function select($name, $options = array())
 {
     $options += array('name' => $name, 'options' => array(), 'value' => null, 'empty' => false);
     $select_options = array_unset($options, 'options');
     $select_value = array_unset($options, 'value');
     if (($empty = array_unset($options, 'empty')) !== false) {
         $keys = array_keys($select_options);
         if (is_array($empty)) {
             $empty_keys = array_keys($empty);
             $key = $empty_keys[0];
             $values = array_merge($empty, $select_options);
         } else {
             $key = $empty;
             $values = array_merge(array($empty), $select_options);
         }
         array_unshift($keys, $key);
         $select_options = array_combine($keys, $values);
     }
     $content = '';
     foreach ($select_options as $key => $value) {
         $option = array('value' => $key);
         if ((string) $key === (string) $select_value) {
             $option['selected'] = true;
         }
         $content .= $this->html->tag('option', $value, $option);
     }
     return $this->html->tag('select', $content, $options);
 }
 protected function addressFromIP($ip)
 {
     $geocoder = AddressGeocoding::get_geocoder();
     $geodata = array();
     try {
         if ($ip) {
             $geodata = $geocoder->geocode($ip)->toArray();
         }
     } catch (Exception $e) {
         SS_Log::log($e, SS_Log::ERR);
     }
     $geodata = array_filter($geodata);
     $datamap = array('Country' => 'countryCode', 'County' => 'county', 'State' => 'region', 'PostalCode' => 'zipcode', 'Latitude' => 'latitude', 'Longitude' => 'longitude');
     $mappeddata = array();
     foreach ($datamap as $addressfield => $geofield) {
         if (is_array($geofield)) {
             if ($data = implode(" ", array_intersect_key($geodata, array_combine($geofield, $geofield)))) {
                 $mappeddata[$addressfield] = $data;
             }
         } elseif (isset($geodata[$geofield])) {
             $mappeddata[$addressfield] = $geodata[$geofield];
         }
     }
     return $mappeddata;
 }
 /**
  * Convert a freely formatted query string to a query array
  *
  * @param string $string
  * @return array query converted to array of real fieldname => value
  */
 public function convert($string, $array = array())
 {
     $string = trim((string) $string);
     if (empty($string) && empty($array)) {
         return null;
     }
     $result = array();
     if (!empty($string)) {
         if (strpos($string, ':') === false) {
             $result = $this->_guess($string);
         } else {
             $pattern = '/([^,:]+){1}:([^,:]+){1}/';
             $foundAnything = preg_match_all($pattern, $string, $matches);
             if (!$foundAnything) {
                 throw new \Exception('Not valid query');
             }
             $result = $this->_replaceFields(array_combine($matches[1], $matches[2]));
         }
     }
     if (!empty($array)) {
         $array = $this->_replaceFields($array);
         $result = array_merge($array, $result);
     }
     return $result;
 }
Example #30
-1
 public function init()
 {
     \kartik\base\InputWidget::init();
     $this->pluginOptions['theme'] = $this->theme;
     if (!empty($this->addon) || empty($this->pluginOptions['width'])) {
         $this->pluginOptions['width'] = '100%';
     }
     $multiple = ArrayHelper::getValue($this->pluginOptions, 'multiple', false);
     unset($this->pluginOptions['multiple']);
     $multiple = ArrayHelper::getValue($this->options, 'multiple', $multiple);
     $this->options['multiple'] = $multiple;
     if ($this->hideSearch) {
         $css = ArrayHelper::getValue($this->pluginOptions, 'dropdownCssClass', '');
         $css .= ' kv-hide-search';
         $this->pluginOptions['dropdownCssClass'] = $css;
     }
     $this->initPlaceholder();
     if ($this->data == null) {
         if (!isset($this->value) && !isset($this->initValueText)) {
             $this->data = [];
         } else {
             $key = isset($this->value) ? $this->value : ($multiple ? [] : '');
             $val = isset($this->initValueText) ? $this->initValueText : $key;
             $this->data = $multiple ? array_combine($key, $val) : [$key => $val];
         }
     }
     Html::addCssClass($this->options, 'form-control');
     $this->initLanguage('language', true);
     $this->registerAssets();
     $this->renderInput();
 }