public function execute(PhutilArgumentParser $args)
 {
     $console = PhutilConsole::getConsole();
     $ids = $args->getArg('id');
     if (!$ids) {
         throw new PhutilArgumentUsageException(pht("Use the '%s' flag to specify one or more SMS messages to show.", '--id'));
     }
     $messages = id(new PhabricatorSMS())->loadAllWhere('id IN (%Ld)', $ids);
     if ($ids) {
         $ids = array_fuse($ids);
         $missing = array_diff_key($ids, $messages);
         if ($missing) {
             throw new PhutilArgumentUsageException(pht('Some specified SMS messages do not exist: %s', implode(', ', array_keys($missing))));
         }
     }
     $last_key = last_key($messages);
     foreach ($messages as $message_key => $message) {
         $info = array();
         $info[] = pht('PROPERTIES');
         $info[] = pht('ID: %d', $message->getID());
         $info[] = pht('Status: %s', $message->getSendStatus());
         $info[] = pht('To: %s', $message->getToNumber());
         $info[] = pht('From: %s', $message->getFromNumber());
         $info[] = null;
         $info[] = pht('BODY');
         $info[] = $message->getBody();
         $info[] = null;
         $console->writeOut('%s', implode("\n", $info));
         if ($message_key != $last_key) {
             $console->writeOut("\n%s\n\n", str_repeat('-', 80));
         }
     }
 }
예제 #2
0
 /**
  * Returns a list of image style replacement options.
  *
  * @return array
  *   An option list suitable for the form select '#options'.
  */
 protected function getReplacementOptions()
 {
     if (!isset($this->replacementOptions)) {
         $this->replacementOptions = array_diff_key(image_style_options(), [$this->getEntity()->id() => '']);
     }
     return $this->replacementOptions;
 }
예제 #3
0
 /**
  * Returns a DataObjectSet containing the subscribers who have never been sent this Newsletter
  *
  */
 function UnsentSubscribers()
 {
     // Get a list of everyone who has been sent this newsletter
     $sent_recipients = DataObject::get("Newsletter_SentRecipient", "ParentID='" . $this->ID . "'");
     // If this Newsletter has not been sent to anyone yet, $sent_recipients will be null
     if ($sent_recipients != null) {
         $sent_recipients_array = $sent_recipients->toNestedArray('MemberID');
     } else {
         $sent_recipients_array = array();
     }
     // Get a list of all the subscribers to this newsletter
     $subscribers = DataObject::get('Member', "`GroupID`='" . $this->Parent()->GroupID . "'", null, "INNER JOIN `Group_Members` ON `MemberID`=`Member`.`ID`");
     // If this Newsletter has no subscribers, $subscribers will be null
     if ($subscribers != null) {
         $subscribers_array = $subscribers->toNestedArray();
     } else {
         $subscribers_array = array();
     }
     // Get list of subscribers who have not been sent this newsletter:
     $unsent_subscribers_array = array_diff_key($subscribers_array, $sent_recipients_array);
     // Create new data object set containing the subscribers who have not been sent this newsletter:
     $unsent_subscribers = new DataObjectSet();
     foreach ($unsent_subscribers_array as $key => $data) {
         $unsent_subscribers->push(new ArrayData($data));
     }
     return $unsent_subscribers;
 }
 public function __construct($name, array $cd = array())
 {
     $this->setPhpName($name);
     // elementary key verification
     $illegalKeys = array_diff_key($cd, array_flip(array('columns', 'tableName', 'inheritance', 'i18n', 'indexes', 'options')));
     if ($illegalKeys) {
         throw new sfDoctrineSchemaException(sprintf('Invalid key "%s" in description of class "%s"', array_shift(array_keys($illegalKeys)), $name));
     }
     if (isset($cd['inheritance'])) {
         $this->setInheritance($cd['inheritance']);
     }
     // set i18n
     if (isset($cd['i18n'])) {
         $this->setI18n($cd['i18n']);
     }
     // add indexes
     if (isset($cd['indexes'])) {
         $this->addIndexes($cd['indexes']);
     }
     // add options
     if (isset($cd['options'])) {
         $this->addOptions($cd['options']);
     }
     // add columns
     if (isset($cd['columns'])) {
         foreach ($cd['columns'] as $colName => $column) {
             $docCol = new sfDoctrineColumnSchema($colName, $column);
             $this->addColumn($docCol);
         }
     }
 }
예제 #5
0
 /**
  * @SuppressWarnings(PHPMD.ElseExpression)
  * {@inheritDoc}
  */
 public function loadVariationByFallback(Product $parentProduct, array $attributes)
 {
     $variation = false;
     if ($this->isProductHasSwatch($parentProduct) && $parentProduct->getDocumentSource() !== null) {
         $documentSource = $parentProduct->getDocumentSource();
         $childrenIds = isset($documentSource['children_ids']) ? $documentSource['children_ids'] : [];
         if (!empty($childrenIds)) {
             $childrenIds = array_map('intval', $childrenIds);
             $productCollection = $this->productCollectionFactory->create();
             $productCollection->addIdFilter($childrenIds);
             $configurableAttributes = $this->getAttributesFromConfigurable($parentProduct);
             $allAttributesArray = [];
             foreach ($configurableAttributes as $attribute) {
                 foreach ($attribute->getOptions() as $option) {
                     $allAttributesArray[$attribute['attribute_code']][] = (int) $option->getValue();
                 }
             }
             $resultAttributesToFilter = array_merge($attributes, array_diff_key($allAttributesArray, $attributes));
             $this->addFilterByAttributes($productCollection, $resultAttributesToFilter);
             $variationProduct = $productCollection->getFirstItem();
             if ($variationProduct && $variationProduct->getId()) {
                 $variation = $this->productRepository->getById($variationProduct->getId());
             }
         }
     } else {
         $variation = parent::loadVariationByFallback($parentProduct, $attributes);
     }
     return $variation;
 }
 public function save()
 {
     if (!$this->object) {
         throw new Exception('Call setObject() before save()!');
     }
     $actor = $this->requireActor();
     $src = $this->object->getPHID();
     if ($this->implicitSubscribePHIDs) {
         $unsub = PhabricatorEdgeQuery::loadDestinationPHIDs($src, PhabricatorEdgeConfig::TYPE_OBJECT_HAS_UNSUBSCRIBER);
         $unsub = array_fill_keys($unsub, true);
         $this->implicitSubscribePHIDs = array_diff_key($this->implicitSubscribePHIDs, $unsub);
     }
     $add = $this->implicitSubscribePHIDs + $this->explicitSubscribePHIDs;
     $del = $this->unsubscribePHIDs;
     // If a PHID is marked for both subscription and unsubscription, treat
     // unsubscription as the stronger action.
     $add = array_diff_key($add, $del);
     if ($add || $del) {
         $u_type = PhabricatorEdgeConfig::TYPE_OBJECT_HAS_UNSUBSCRIBER;
         $s_type = PhabricatorEdgeConfig::TYPE_OBJECT_HAS_SUBSCRIBER;
         $editor = new PhabricatorEdgeEditor();
         foreach ($add as $phid => $ignored) {
             $editor->removeEdge($src, $u_type, $phid);
             $editor->addEdge($src, $s_type, $phid);
         }
         foreach ($del as $phid => $ignored) {
             $editor->removeEdge($src, $s_type, $phid);
             $editor->addEdge($src, $u_type, $phid);
         }
         $editor->save();
     }
 }
 public function LinkWithSearch($extraParamStr = '')
 {
     $params = array_diff_key($this->request->getVars(), array('url' => null));
     parse_str($extraParamStr, $extraParams);
     $params = array_merge($params, (array) $extraParams);
     return Controller::join_links($this->Link(), '?' . http_build_query($params));
 }
 function check_setup_settings(&$settings = array())
 {
     if (isset($settings['show_on'])) {
         $invalid_settings = array_diff_key($settings['show_on'], $this->settings['show_on']);
         if (!empty($invalid_settings)) {
             throw new Resume_Exception('Invalid show_on settings supplied to setup(): "' . implode('", "', array_keys($invalid_settings)) . '"');
         }
     }
     if (isset($settings['show_on']['post_formats'])) {
         $settings['show_on']['post_formats'] = (array) $settings['show_on']['post_formats'];
     }
     if (isset($settings['show_on']['post_path'])) {
         $page = get_page_by_path($settings['show_on']['post_path']);
         if ($page) {
             $settings['show_on']['page_id'] = $page->ID;
         } else {
             $settings['show_on']['page_id'] = -1;
         }
     }
     // Transform category slug to taxonomy + term slug + term id
     if (isset($settings['show_on']['category'])) {
         $term = get_term_by('slug', $settings['show_on']['category'], 'category');
         if ($term) {
             $settings['show_on']['tax_slug'] = $term->taxonomy;
             $settings['show_on']['tax_term'] = $term->slug;
             $settings['show_on']['tax_term_id'] = $term->term_id;
         }
     }
     return parent::check_setup_settings($settings);
 }
예제 #9
0
 /**
  * initUserAcl() - Bind user specific ACL with user session.
  *
  * @return Zend_Acl
  */
 protected function initUserAcl()
 {
     $authContent = Zend_Auth::getInstance()->getStorage()->read();
     if (!is_array($authContent)) {
         self::getLogger()->debug('Fresh visitor');
         $remoteAcl = new Zend_Session_Namespace('remoteAcl');
         if (!isset($remoteAcl->userInfo)) {
             $remoteAcl->redirectedFrom = array_intersect_key($this->getRequest()->getParams(), $this->getRequest()->getUserParams());
             $remoteAcl->redirectedParams = array_diff_key($this->getRequest()->getParams(), $this->getRequest()->getUserParams());
             self::getLogger()->debug('Redirecting to "' . self::AUTH_URL . '", redirecting from');
             self::getLogger()->debug($remoteAcl->redirectedFrom);
             $this->getResponse()->setRedirect(self::AUTH_URL, 303);
             return;
         } else {
             Zend_Registry::get('logger')->debug('User has logged in auth module');
         }
         $commonAcl = self::getCache()->load('commonAcl');
         if ($commonAcl === false) {
             $commonAcl = self::initAcl();
         } else {
             Zend_Registry::get('logger')->debug('Common ACL from Cache.');
         }
         $acl = $commonAcl['acl'];
         $userInfo = $remoteAcl->userInfo;
         $userRoles = array_intersect($userInfo['roles'], $commonAcl['dbRoles']);
         Zend_Registry::get('logger')->debug('Module Roles of ' . $userInfo['identity']);
         Zend_Registry::get('logger')->debug($userRoles);
         $acl->addRole($userInfo['identity'], $userRoles);
         $userInfo['acl'] = $acl;
         Zend_Auth::getInstance()->getStorage()->write($userInfo);
         Zend_Registry::get('logger')->debug($userInfo['identity'] . ' specific ACL saved in session.');
     }
 }
 /**
  *
  * @param array $options_array keys: {
  *	@type EEM_Base $model
  *	@type EE_Base_Class $model_object
  *	@type array $subsection_args array keys should be subsection names (that either do or will exist), and values are the arrays as you would pass them to that subsection
  * }
  * @throws EE_Error
  */
 public function __construct($options_array = array())
 {
     if (isset($options_array['model']) && $options_array['model'] instanceof EEM_Base) {
         $this->_model = $options_array['model'];
     }
     if (!$this->_model || !$this->_model instanceof EEM_Base) {
         throw new EE_Error(sprintf(__("Model Form Sections must first specify the _model property to be a subclass of EEM_Base", "event_espresso")));
     }
     if (isset($options_array['subsection_args'])) {
         $subsection_args = $options_array['subsection_args'];
     } else {
         $subsection_args = array();
     }
     //gather fields and relations to convert to inputs
     //but if they're just going to exclude a field anyways, don't bother converting it to an input
     $exclude = $this->_subsections;
     if (isset($options_array['exclude'])) {
         $exclude = array_merge($exclude, array_flip($options_array['exclude']));
     }
     $model_fields = array_diff_key($this->_model->field_settings(), $exclude);
     $model_relations = array_diff_key($this->_model->relation_settings(), $exclude);
     //convert fields and relations to inputs
     $this->_subsections = array_merge($this->_convert_model_fields_to_inputs($model_fields), $this->_convert_model_relations_to_inputs($model_relations, $subsection_args), $this->_subsections);
     parent::__construct($options_array);
     if (isset($options_array['model_object']) && $options_array['model_object'] instanceof EE_Base_Class) {
         $this->populate_model_obj($options_array['model_object']);
     }
 }
예제 #11
0
 /**
  * [s2Member-Summary] Shortcode.
  *
  * @package s2Member\Shortcodes
  * @since 150712
  *
  * @attaches-to ``add_shortcode('s2Member-Summary');``
  *
  * @param array  $attr An array of Attributes.
  * @param string $content Content inside the Shortcode.
  * @param string $shortcode The actual Shortcode name itself.
  *
  * @return string Summary widget.
  */
 public static function shortcode($attr_args_options = array(), $content = '', $shortcode = '')
 {
     foreach (array_keys(get_defined_vars()) as $__v) {
         $__refs[$__v] =& ${$__v};
     }
     do_action('c_ws_plugin__s2member_pro_before_sc_summary', get_defined_vars());
     unset($__refs, $__v);
     // Housekeeping.
     $attr_args_options = (array) $attr_args_options;
     $default_attr = array('show_login_if_not_logged_in' => '0');
     $attr = array_merge($default_attr, $attr_args_options);
     $attr = array_intersect_key($attr, $default_attr);
     $default_args = array('before_widget' => '', 'before_title' => '<h3>', 'after_title' => '</h3>', 'after_widget' => '');
     $args = array_merge($default_args, $attr_args_options);
     $args = array_intersect_key($args, $default_args);
     $options = array_diff_key($attr_args_options, $attr, $args);
     if (!is_user_logged_in() && !filter_var($attr['show_login_if_not_logged_in'], FILTER_VALIDATE_BOOLEAN)) {
         $summary = '';
     } else {
         ob_start();
         // Begin output buffering.
         c_ws_plugin__s2member_pro_login_widget::___static_widget___($args, $options);
         $summary = ob_get_clean();
     }
     if ($summary) {
         // Wrapper for CSS styling.
         $summary = '<div class="ws-plugin--s2member-sc-summary">' . $summary . '</div>';
     }
     return apply_filters('c_ws_plugin__s2member_pro_sc_summary', $summary, get_defined_vars());
 }
예제 #12
0
 /**
  * Syncronise all file templates to the database.
  * @return void
  */
 public static function syncAll()
 {
     $templates = self::make()->listRegisteredTemplates();
     $dbTemplates = self::lists('is_custom', 'code');
     $newTemplates = array_diff_key($templates, $dbTemplates);
     /*
      * Clean up non-customized templates
      */
     foreach ($dbTemplates as $code => $is_custom) {
         if ($is_custom) {
             continue;
         }
         if (!array_key_exists($code, $templates)) {
             self::whereCode($code)->delete();
         }
     }
     /*
      * Create new templates
      */
     foreach ($newTemplates as $code => $description) {
         $sections = self::getTemplateSections($code);
         $layoutCode = array_get($sections, 'settings.layout', 'default');
         $template = self::make();
         $template->code = $code;
         $template->description = $description;
         $template->is_custom = 0;
         $template->layout_id = MailLayout::getIdFromCode($layoutCode);
         $template->forceSave();
     }
 }
예제 #13
0
 private function setup_posted_data()
 {
     $posted_data = (array) $_POST;
     $posted_data = array_diff_key($posted_data, array('_wpnonce' => ''));
     $posted_data = $this->sanitize_posted_data($posted_data);
     $tags = $this->contact_form->form_scan_shortcode();
     foreach ((array) $tags as $tag) {
         if (empty($tag['name'])) {
             continue;
         }
         $name = $tag['name'];
         $value = '';
         if (isset($posted_data[$name])) {
             $value = $posted_data[$name];
         }
         $pipes = $tag['pipes'];
         if (WPCF7_USE_PIPE && $pipes instanceof WPCF7_Pipes && !$pipes->zero()) {
             if (is_array($value)) {
                 $new_value = array();
                 foreach ($value as $v) {
                     $new_value[] = $pipes->do_pipe(wp_unslash($v));
                 }
                 $value = $new_value;
             } else {
                 $value = $pipes->do_pipe(wp_unslash($value));
             }
         }
         $posted_data[$name] = $value;
     }
     $this->posted_data = apply_filters('wpcf7_posted_data', $posted_data);
     return $this->posted_data;
 }
예제 #14
0
 /**
  * Store new messages in database and remove outdated messages
  *
  * @return $this|\Magento\Framework\Model\ModelResource\Db\AbstractDb
  */
 public function _afterLoad()
 {
     $messages = $this->_messageList->asArray();
     $persisted = [];
     $unread = [];
     foreach ($messages as $message) {
         if ($message->isDisplayed()) {
             foreach ($this->_items as $persistedKey => $persistedMessage) {
                 if ($message->getIdentity() == $persistedMessage->getIdentity()) {
                     $persisted[$persistedKey] = $persistedMessage;
                     continue 2;
                 }
             }
             $unread[] = $message;
         }
     }
     $removed = array_diff_key($this->_items, $persisted);
     foreach ($removed as $removedItem) {
         $removedItem->delete();
     }
     foreach ($unread as $unreadItem) {
         $item = $this->getNewEmptyItem();
         $item->setIdentity($unreadItem->getIdentity())->setSeverity($unreadItem->getSeverity())->save();
     }
     if (count($removed) || count($unread)) {
         $this->_unreadMessages = $unread;
         $this->clear();
         $this->load();
     } else {
         parent::_afterLoad();
     }
     return $this;
 }
예제 #15
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $jobId = $input->getArgument('job-id');
     $stats = $this->getBeanstalk()->statsJob($jobId);
     $output->writeln("<info>[Job ID: {$jobId}]</info>");
     $table = new Table($output);
     $table->setStyle('compact');
     $details = array_intersect_key($stats, array_flip(['tube', 'state']));
     foreach ($details as $detail => $value) {
         if ($detail == 'state' && $value == 'buried') {
             $value = "<error>{$value}</error>";
         }
         $table->addRow([$detail, $value]);
     }
     $table->render();
     $created = time();
     $table = new Table($output);
     $stats = array_diff_key($stats, array_flip(['id', 'tube', 'state']));
     $table->setHeaders(['Stat', 'Value']);
     foreach ($stats as $stat => $value) {
         if ($stat == 'age') {
             $created = time() - (int) $value;
             $dt = date('Y-m-d H:i:s', $created);
             $table->addRow(['created', $dt]);
         } elseif ($stat == 'delay') {
             $dt = date('Y-m-d H:i:s', $created + (int) $value);
             $table->addRow(['scheduled', $dt]);
         }
         $table->addRow([$stat, $value]);
     }
     $table->render();
 }
예제 #16
0
 public function deleteOnClick($sender)
 {
     $item = $sender->owner->getDataItem();
     // unset($this->_itemlist[$item->item_id]);
     $this->_itemlist = array_diff_key($this->_itemlist, array($item->item_id => $this->_itemlist[$item->item_id]));
     $this->docform->detail->Reload();
 }
예제 #17
0
 public function getQuery()
 {
     $words = implode('&', $this->searchWords);
     $sub = clone $this->qb;
     $this->qb->addSelect("ts_rank(bsearch.document, to_tsquery('" . $words . "')) as score");
     $sub->select('*');
     $select = [];
     $fieldsToSearch = $this->config->getConfig($this->contentType);
     $joins = $this->config->getJoins($this->contentType);
     $fieldsToSearch = array_diff_key($fieldsToSearch, array_flip($joins));
     $from = $this->qb->getQueryPart('from');
     if (isset($from[0]['alias'])) {
         $alias = $from[0]['alias'];
     } else {
         $alias = $from[0]['table'];
     }
     foreach ($fieldsToSearch as $fieldName => $config) {
         $weight = $this->getWeight($config['weight']);
         $select[] = "setweight(to_tsvector({$alias}.{$fieldName}), '{$weight}')";
     }
     $sub->select('*, ' . implode(' || ', $select) . ' AS document');
     $sub->groupBy("{$alias}.id");
     $this->qb->from('(' . $sub->getSQL() . ')', 'bsearch');
     $this->qb->where("bsearch.document @@ to_tsquery('" . $words . "')");
     $this->qb->orderBy('score', 'DESC');
     return $this->qb;
 }
예제 #18
0
파일: Arrays.php 프로젝트: kitsunet/form
 /**
  * Validates the given $arrayToTest by checking if an element is not in $allowedArrayKeys.
  *
  * @param array $arrayToTest
  * @param array $allowedArrayKeys
  * @return void
  * @throws \TYPO3\Form\Exception\TypeDefinitionNotValidException if an element in $arrayToTest is not in $allowedArrayKeys
  */
 public static function assertAllArrayKeysAreValid(array $arrayToTest, array $allowedArrayKeys)
 {
     $notAllowedArrayKeys = array_keys(array_diff_key($arrayToTest, array_flip($allowedArrayKeys)));
     if (count($notAllowedArrayKeys) !== 0) {
         throw new \TYPO3\Form\Exception\TypeDefinitionNotValidException(sprintf('The options "%s" were not allowed (allowed were: "%s")', implode(', ', $notAllowedArrayKeys), implode(', ', $allowedArrayKeys)), 1325697085);
     }
 }
예제 #19
0
 /**
  * Returns a link to a calendar page without the given arguments; does not
  * otherwise disturb current page state.
  *
  * @param array $args           Current arguments to the calendar
  * @param array $args_to_remove Names of arguments to remove from current args
  *
  * @return string
  */
 public function generate_href_without_arguments(array $args, array $args_to_remove)
 {
     $args_to_remove = array_flip($args_to_remove);
     $args = array_diff_key($args, $args_to_remove);
     $href = $this->_registry->get('html.element.href', $args);
     return $href->generate_href();
 }
예제 #20
0
 public static function sync($source, $destination, $syncTaskId = 0)
 {
     // Stats
     $stats = array('links' => 0);
     // Get source data
     $links = BackupsModel::all(array('user_id' => $source['username']['id'], 'sync_task_id' => $syncTaskId, 'entity_type' => static::$kind['link']))->toArray();
     $syncedLinks = MigratedDataModel::all(array('source_id' => $source['username']['id'], 'destination_id' => $destination['username']['id'], 'kind' => static::$kind['link']))->column('identifier');
     if ($links) {
         foreach ($links as $link) {
             if (!in_array($link['entity_id'], $syncedLinks)) {
                 $link['entity'] = json_decode($link['entity'], true);
                 $newLink = array_diff_key($link['entity'], array_flip(static::$skip['link']));
                 $newLink = \Rest::postJSON(static::$endpoints['link'], $newLink, $destination);
                 if (isset($newLink['result']['error'])) {
                     d($newLink);
                 }
                 $stats['links']++;
                 $syncedCalendar = MigratedDataModel::create();
                 $syncedCalendar->source_id = $source['username']['id'];
                 $syncedCalendar->destination_id = $destination['username']['id'];
                 $syncedCalendar->kind = static::$kind['link'];
                 $syncedCalendar->identifier = $link['entity_id'];
                 $syncedCalendar->created = date(DATE_TIME);
                 $syncedCalendar->save();
             }
         }
     }
     return $stats;
 }
예제 #21
0
 /**
  * Return a paginated list of projects
  * 
  * @return \Dingo\Api\Http\Response
  */
 public function index()
 {
     $projects = Project::paginate(app('request')->get('per_page', 10));
     $queryParams = array_diff_key($_GET, array_flip(['page']));
     $projects->appends($queryParams);
     return $this->response->paginator($projects, new ProjectTransformer());
 }
예제 #22
0
 /**
  * Constructor.
  *
  * @param array $params The fields to initialise the renderable.
  */
 public function __construct(array $params)
 {
     global $OUTPUT;
     $diff = array_diff_key($params, array_flip(self::$required));
     if (count($diff) > 0) {
         throw new coding_exception('Missing, or unexpected, properties');
     }
     // Assigning the properties.
     foreach ($params as $key => $value) {
         if (in_array($key, self::$required)) {
             $this->{$key} = $value;
         }
     }
     // Has next level.
     if (!empty($this->nextlevelxp) && $this->nextlevelxp > $this->xp) {
         $this->hasnextlevel = true;
         $this->nextlevel = $this->level + 1;
         // Percentage.
         $this->xpinlevel = $this->xp - $this->levelxp;
         $this->xpforlevel = $this->nextlevelxp - $this->levelxp;
         $this->percentage = round($this->xpinlevel / $this->xpforlevel * 100);
     } else {
         $this->nextlevel = null;
         $this->hasnextlevel = true;
         $this->xpforlevel = $this->xp;
         $this->xpinlevel = $this->xp;
         $this->percentage = 100;
     }
     // Image URL.
     $this->levelimgsrc = moodle_url::make_pluginfile_url(context_course::instance($this->courseid)->id, 'block_xp', 'badges', 0, '/', $this->level);
 }
 /**
  * Gets the site config
  *
  * @param STDClass $C the config variable
  *
  * @returns the config object
  * @since ADD MVC 0.0
  */
 static function config(STDClass $C = null)
 {
     if ($C) {
         $config_array = (array) $C;
         $full_default_config_array = (array) self::default_config();
         $default_config_array = array_diff_key($full_default_config_array, $config_array);
         $merge_config_array = array_intersect_key($config_array, $full_default_config_array);
         $config_array = array_merge($default_config_array, $config_array);
         foreach ($merge_config_array as $key => $value) {
             if (is_object($value)) {
                 $value = (array) $value;
             }
             if (is_array($value)) {
                 $config_array[$key] = array_merge((array) $value, (array) $full_default_config_array[$key]);
             } else {
                 $config_array[$key] = $value;
             }
         }
         self::$C = $GLOBALS[self::CONFIG_VARNAME] = (object) $config_array;
         self::$environment_status = self::$C->environment_status;
         # Convert to object
         foreach (self::$C as &$var) {
             if (is_array($var)) {
                 $var = (object) $var;
             }
         }
     }
     return self::$C;
 }
예제 #24
0
 /**
  * [ENG]Simple method, exclude specific index value from array
  * [CHS]简单的排除某些索引
  * @param array $data 
  * [ENG]Input data
  * [CHS]要过滤的数组
  * @param array|string $cond 
  * [ENG]Specific index string or array that would exclude. If it is string, use comma delimiter(,) between index
  * [CHS]要剔除的索引键。如果是字符串,每个索引键必须使用半角逗号(,)。如果为空,将原样返回不做处理
  * @param bool $cond_flipped 
  * [ENG]Param $cond has been processed with function array_flip? Default is false
  * [CHS]$cond参数是否经过了预先array_flip?默认为false
  * @return mixed|array
  */
 public function exclude_index($data, $cond, $cond_flipped = false)
 {
     if (!is_array($data) || empty($data) || empty($cond)) {
         return $data;
     }
     if (!is_array($cond)) {
         $cond = explode(',', $cond);
     }
     return array_diff_key($data, $cond_flipped ? $cond : array_flip($cond));
     /*
     //[ENG]another method
     //[CHS]另一种方法
     $cond = $cond_flipped ? $cond : array_flip($cond);
     reset($data);
     
     //[ENG]reset has been triggered copy on write, now use while for avoiding re-triggering
     //[CHS]reset已触发copy on write,此处用while是防止再次触发该机制
     //http://horseluke-code.googlecode.com/svn/trunk/draftCode/for_foreach.php        
     while($row = each($data)) {
         if(isset($cond[$row[0]]) && isset($data[$row[0]])){
             unset($data[$row[0]]);
             continue;
         }
     }
     
     return $data;
     */
 }
 public function getKeys(array $keys)
 {
     $remaining = array_fuse($keys);
     $results = array();
     $missed = array();
     try {
         foreach ($this->cachesForward as $cache) {
             $result = $cache->getKeys($remaining);
             $remaining = array_diff_key($remaining, $result);
             $results += $result;
             if (!$remaining) {
                 while ($cache = array_pop($missed)) {
                     // TODO: This sets too many results in the closer caches, although
                     // it probably isn't a big deal in most cases; normally we're just
                     // filling the request cache.
                     $cache->setKeys($result, $this->nextTTL);
                 }
                 break;
             }
             $missed[] = $cache;
         }
         $this->nextTTL = null;
     } catch (Exception $ex) {
         $this->nextTTL = null;
         throw $ex;
     }
     return $results;
 }
예제 #26
0
 function executeEditPermiso()
 {
     // estos son los permisos que tiene el rol
     $c = new Criteria();
     $c->add(RolPermisoPeer::FK_ROL_ID, $this->getRequestParameter('id'));
     $c->addAscendingOrderByColumn(PermisoPeer::NOMBRE);
     $rolPermisos = RolPermisoPeer::doSelectJoinPermiso($c);
     // esto puede ser descartado usando en el select_tag, objects_for_select
     $optionsRolPermisos = array();
     foreach ($rolPermisos as $rolPermiso) {
         $optionsRolPermisos[$rolPermiso->getFkPermisoId()] = sprintf("%s (%s)", $rolPermiso->getPermiso()->getNombre(), $rolPermiso->getPermiso()->getDescripcion());
     }
     //estos son todos los permisos existentes
     $permisos = PermisoPeer::doSelect(new Criteria());
     $todosLosPermisos = array();
     foreach ($permisos as $permiso) {
         $todosLosPermisos[$permiso->getId()] = $permiso->getNombre();
     }
     // estos son los permisos existentes menos los del usuario
     $this->optionsPermisos = array_diff_key($todosLosPermisos, $optionsRolPermisos);
     $c = new Criteria();
     $c->add(RolPeer::ACTIVO, 1);
     $roles = RolPeer::doSelect($c);
     $optionsRol = array();
     foreach ($roles as $rol) {
         $optionsRol[$rol->getId()] = $rol->getNombre();
     }
     $this->optionsRol = $optionsRol;
     $this->optionsRolPermisos = $optionsRolPermisos;
 }
예제 #27
0
 /**
  * Add site preferences
  */
 public function __addPreferences($context)
 {
     // Get selected languages
     $selection = Symphony::Configuration()->get('datetime');
     if (empty($selection)) {
         $selection = array();
     }
     // Build default options
     $options = array();
     foreach ($this->languages as $name => $codes) {
         $options[$name] = array($name . '::' . $codes, array_key_exists($name, $selection) ? true : false, __(ucfirst($name)));
     }
     // Add custom options
     foreach (array_diff_key($selection, $this->languages) as $name => $codes) {
         $options[$name] = array($name . '::' . $codes, true, __(ucfirst($name)));
     }
     // Sort options
     ksort($options);
     // Add fieldset
     $group = new XMLElement('fieldset', '<legend>' . __('Date and Time') . '</legend>', array('class' => 'settings'));
     $select = Widget::Select('settings[datetime][]', $options, array('multiple' => 'multiple'));
     $label = Widget::Label('Languages included in the Date and Time Data Source', $select);
     $group->appendChild($label);
     $help = new XMLElement('p', __('You can add more languages in you configuration file.'), array('class' => 'help'));
     $group->appendChild($help);
     $context['wrapper']->appendChild($group);
 }
예제 #28
0
 /**
  * {@inheritdoc}
  */
 public function merge(array $changeSet, array $localData, array $remoteData, $strategy = TwoWaySyncConnectorInterface::REMOTE_WINS, array $additionalFields = [])
 {
     if (!in_array($strategy, $this->supportedStrategies, true)) {
         throw new \InvalidArgumentException(sprintf('Strategy "%s" is not supported, expected one of "%s"', $strategy, implode(',', $this->supportedStrategies)));
     }
     if (!$changeSet) {
         return $remoteData;
     }
     $remoteData = $this->normalize($remoteData);
     $oldValues = $this->getChangeSetValues($changeSet, 'old');
     $oldValues = $this->fillEmptyValues($oldValues, $this->getChangeSetValues($changeSet, 'new'));
     $snapshot = $this->getSnapshot($localData, $oldValues);
     $localChanges = $this->getDiff($localData, $snapshot);
     $remoteChanges = $this->getDiff($remoteData, $snapshot);
     $conflicts = array_keys(array_intersect_key($remoteChanges, $localChanges));
     foreach (array_merge($conflicts, $additionalFields) as $conflict) {
         if (!array_key_exists($conflict, $remoteData)) {
             continue;
         }
         if (!array_key_exists($conflict, $localData)) {
             continue;
         }
         if ($strategy === TwoWaySyncConnectorInterface::LOCAL_WINS) {
             $remoteData[$conflict] = $localData[$conflict];
         }
     }
     $localDataForUpdate = array_diff_key(array_keys($localChanges), $conflicts);
     foreach ($localDataForUpdate as $property) {
         $remoteData[$property] = $localData[$property];
     }
     return $remoteData;
 }
예제 #29
0
 protected function _castArray($object, $val, $pathKey, $options, $defaults)
 {
     $isArray = $this->is('array', $pathKey) && !$object instanceof $this->_classes['set'];
     $isObject = $this->type($pathKey) == 'object';
     $valIsArray = is_array($val);
     $numericArray = false;
     $class = 'entity';
     if (!$valIsArray && !$isArray) {
         return $this->_castType($val, $pathKey);
     }
     if ($valIsArray) {
         $numericArray = !$val || array_keys($val) === range(0, count($val) - 1);
     }
     if ($isArray || $numericArray && !$isObject) {
         $val = $valIsArray ? $val : array($val);
         $class = 'set';
     }
     if ($options['wrap']) {
         $config = array('data' => $val, 'parent' => $options['parent'], 'model' => $options['model'], 'schema' => $this);
         $config += compact('pathKey') + array_diff_key($options, $defaults);
         $val = $this->_instance($class, $config);
     } elseif ($class == 'set') {
         $val = $val ?: array();
         foreach ($val as &$value) {
             $value = $this->_castType($value, $pathKey);
         }
     }
     return $val;
 }
예제 #30
0
 /**
  * Save the given preferences
  *
  * @param   Preferences     $preferences    The preferences to save
  */
 public function save(Preferences $preferences)
 {
     $preferences = $preferences->toArray();
     $this->update(array_merge(array_diff_key($preferences, $this->preferences), array_intersect_key($preferences, $this->preferences)));
     $this->delete(array_keys(array_diff_key($this->preferences, $preferences)));
     $this->write();
 }