/** * @param modX $modx * @param array $config */ public function __construct(modX &$modx, $config = array()) { $this->modx =& $modx; $config = array_merge(array('firstClass' => 'first', 'lastClass' => 'last', 'hereClass' => 'active', 'parentClass' => '', 'rowClass' => '', 'outerClass' => '', 'innerClass' => '', 'levelClass' => '', 'selfClass' => '', 'webLinkClass' => '', 'limit' => 0, 'hereId' => 0), $config, array('return' => 'data')); if (empty($config['tplInner']) && !empty($config['tplOuter'])) { $config['tplInner'] = $config['tplOuter']; } if (empty($config['hereId']) && !empty($modx->resource)) { $config['hereId'] = $modx->resource->id; } $fqn = $modx->getOption('pdoFetch.class', null, 'pdotools.pdofetch', true); if ($pdoClass = $modx->loadClass($fqn, '', false, true)) { $this->pdoTools = new $pdoClass($modx, $config); } elseif ($pdoClass = $modx->loadClass($fqn, MODX_CORE_PATH . 'components/pdotools/model/', false, true)) { $this->pdoTools = new $pdoClass($modx, $config); } else { $this->modx->log(modX::LOG_LEVEL_ERROR, 'Could not load pdoFetch from "MODX_CORE_PATH/components/pdotools/model/".'); return false; } if ($config['hereId'] && ($currentResource = $this->pdoTools->getObject('modResource', $config['hereId']))) { $tmp = $modx->getParentIds($currentResource['id'], 100, array('context' => $currentResource['context_key'])); $tmp[] = $config['hereId']; $this->parentTree = array_flip($tmp); } $modx->lexicon->load('pdotools:pdomenu'); return true; }
/** * Validates a partial array. Some data may be missing from the given $array, then it will be taken from the * full array. * * Since the array can be incomplete, this method does not validate required parameters. * * @param array $array * @param array $fullArray * * @return bool */ public function validatePartial(array $array, array $fullArray) { $unvalidatedFields = array_flip(array_keys($array)); // field validators foreach ($this->validators as $field => $validator) { unset($unvalidatedFields[$field]); // if the value is present if (isset($array[$field])) { // validate it if a validator is given, skip it otherwise if ($validator && !$validator->validate($array[$field])) { $this->setError($validator->getError()); return false; } } } // check if any unsupported fields remain if ($unvalidatedFields) { reset($unvalidatedFields); $field = key($unvalidatedFields); $this->error($this->messageUnsupported, $field); return false; } // post validators foreach ($this->postValidators as $validator) { if (!$validator->validatePartial($array, $fullArray)) { $this->setError($validator->getError()); return false; } } return true; }
public static function widgetsHandler($type, $disable = '') { $wtype = 'widgets_' . $type; $GLOBALS['core']->blog->settings->addNameSpace('widgets'); $widgets = $GLOBALS['core']->blog->settings->widgets->{$wtype}; if (!$widgets) { // If widgets value is empty, get defaults $widgets = self::defaultWidgets($type); } else { // Otherwise, load widgets $widgets = dcWidgets::load($widgets); } if ($widgets->isEmpty()) { // Widgets are empty, don't show anything return; } $disable = preg_split('/\\s*,\\s*/', $disable, -1, PREG_SPLIT_NO_EMPTY); $disable = array_flip($disable); foreach ($widgets->elements() as $k => $w) { if (isset($disable[$w->id()])) { continue; } echo $w->call($k); } }
/** * This method will return a native type that corresponds to the specified * Creole (JDBC-like) type. Remember that this is really only for "hint" purposes * as SQLite is typeless. * * If there is more than one matching native type, then the LAST defined * native type will be returned. * * @param int $creoleType * @return string Native type string. */ public static function getNativeType($creoleType) { if (self::$reverseMap === null) { self::$reverseMap = array_flip(self::$typeMap); } return @self::$reverseMap[$creoleType]; }
public function initialize($content = array(), $identifier = '') { // check for template if (isset($content['template'])) { $this->_template = $content['template']; unset($content['template']); } if (isset($identifier)) { $this->_identifier = $identifier; } if (count($content)) { $renderItems = array(); foreach ($content as $key => $item) { if (is_array($item)) { $usedItem = array_intersect_key($item, array_flip($this->_allowAttributes)); $usedItem['active'] = false; // if language, than replace the url if ($this->_page->config['use_language']) { $usedItem['url'] = $this->_page->currentLanguage . "/" . $usedItem['url']; } // check active if ($usedItem['url'] == $this->_page->uri) { $usedItem['active'] = true; } $usedItem['url'] = $this->_page->config['url'] . $usedItem['url']; $renderItems[] = $usedItem; } else { echo "Menu Item must have title and url, please provide!"; } } $this->_renderItems = $renderItems; } }
/** * Get the fillable attributes of a given array. * * @param array $attributes * * @return array */ protected function fillableFromArray(array $attributes) { if (count($this->getFillable()) > 0 && !static::$unguarded) { return array_intersect_key($attributes, array_flip($this->getFillable())); } return $attributes; }
/** * Generate query expression for a Criterion this handler accepts * * accept() must be called before calling this method. * * @param \eZ\Publish\Core\Search\Legacy\Content\Common\Gateway\CriteriaConverter $converter * @param \eZ\Publish\Core\Persistence\Database\SelectQuery $query * @param \eZ\Publish\API\Repository\Values\Content\Query\Criterion $criterion * @param array $fieldFilters * * @return \eZ\Publish\Core\Persistence\Database\Expression */ public function handle(CriteriaConverter $converter, SelectQuery $query, Criterion $criterion, array $fieldFilters) { $languages = array_flip($criterion->value); /** @var $criterion \eZ\Publish\API\Repository\Values\Content\Query\Criterion\LanguageCode */ $languages['always-available'] = $criterion->matchAlwaysAvailable; return $query->expr->gt($query->expr->bitAnd($this->dbHandler->quoteColumn('language_mask', 'ezcontentobject'), $this->maskGenerator->generateLanguageMask($languages)), 0); }
function checkIndividually() { #---------------------------------------------------------------------- global $competitionCondition, $chosenWhich; echo "<hr /><p>Checking <b>" . $chosenWhich . " individual results</b>... (wait for the result message box at the end)</p>\n"; #--- Get all results (id, values, format, round). $dbResult = mysql_query("\n SELECT\n result.id, formatId, roundId, personId, competitionId, eventId, result.countryId,\n value1, value2, value3, value4, value5, best, average\n FROM Results result, Competitions competition\n WHERE competition.id = competitionId\n {$competitionCondition}\n ORDER BY formatId, competitionId, eventId, roundId, result.id\n ") or die("<p>Unable to perform database query.<br/>\n(" . mysql_error() . ")</p>\n"); #--- Build id sets $countryIdSet = array_flip(getAllIDs(dbQuery("SELECT id FROM Countries"))); $competitionIdSet = array_flip(getAllIDs(dbQuery("SELECT id FROM Competitions"))); $eventIdSet = array_flip(getAllIDs(dbQuery("SELECT id FROM Events"))); $formatIdSet = array_flip(getAllIDs(dbQuery("SELECT id FROM Formats"))); $roundIdSet = array_flip(getAllIDs(dbQuery("SELECT id FROM Rounds"))); #--- Process the results. $badIds = array(); echo "<pre>\n"; while ($result = mysql_fetch_array($dbResult)) { if ($error = checkResult($result, $countryIdSet, $competitionIdSet, $eventIdSet, $formatIdSet, $roundIdSet)) { extract($result); echo "Error: {$error}\nid:{$id} format:{$formatId} round:{$roundId}"; echo " ({$value1},{$value2},{$value3},{$value4},{$value5}) best+average({$best},{$average})\n"; echo "{$personId} {$countryId} {$competitionId} {$eventId}\n\n"; $badIds[] = $id; } } echo "</pre>"; #--- Free the results. mysql_free_result($dbResult); #--- Tell the result. noticeBox2(!count($badIds), "All checked results pass our checking procedure successfully.<br />" . wcaDate(), count($badIds) . " errors found. Get them with this:<br /><br />SELECT * FROM Results WHERE id in (" . implode(', ', $badIds) . ")"); }
public function writeUntouched() { $touched = array_flip($this->getTouchedFiles()); $untouched = array(); $this->getUntouchedFiles($untouched, $touched, '.', '.'); $this->includeUntouchedFiles($untouched); }
/** The constructor * @access public * @param array $options * @return void */ public function __construct(array $options = null) { $finds = new Findspots(); $schema = $finds->info(); $fields = array_flip($schema['cols']); $remove = array('updated', 'created', 'updatedBy', 'createdBy', 'institution', 'findID', 'address', 'fourFigure', 'gridlen', 'postcode', 'easting', 'northing', 'declong', 'declat', 'fourFigureLat', 'fourFigureLon', 'woeid', 'geonamesID', 'osmNode', 'elevation', 'geohash', 'country', 'map25k', 'map10k', 'soiltype', 'smrref', 'otherref', 'id', 'accuracy', 'secuid', 'old_occupierid', 'occupier', 'old_findspotid', 'date'); foreach ($remove as $rem) { unset($fields[$rem]); } $labels = array('gridrefcert' => 'Grid reference certainty', 'gridref' => 'Grid reference', 'knownas' => 'Known as', 'disccircum' => 'Discovery circumstances', 'gridrefsrc' => 'Grid reference source', 'landusevalue' => 'Land use value', 'landusecode' => 'Land use code', 'depthdiscovery' => 'Depth of discovery', 'Highsensitivity' => 'High sensitivity'); parent::__construct($options); $this->setName('configureFindSpotCopy'); $elements = array(); foreach (array_keys($fields) as $field) { $label = $field; $field = new Zend_Form_Element_Checkbox($field); if (array_key_exists($label, $labels)) { $clean = ucfirst($labels[$label]); } else { $clean = ucfirst($label); } $field->setLabel($clean)->setRequired(false)->addValidator('NotEmpty', 'boolean'); $elements[] = $field; $this->addElement($field); } $this->addDisplayGroup($elements, 'details'); //Submit button $submit = new Zend_Form_Element_Submit('submit'); $submit->setLabel('Submit find spot configuration'); $this->addElement($submit); $this->details->setLegend('Choose fields: '); parent::init(); }
/** * Return the views output * * @return string The output of the view */ public function render() { $rows = ''; $columns = array(); $rowset = $this->getModel()->getRowset(); // Get the columns foreach ($rowset as $row) { $data = $row->toArray(); $columns = array_merge($columns + array_flip(array_keys($data))); } // Empty the column values foreach ($columns as $key => $value) { $columns[$key] = ''; } //Create the rows foreach ($rowset as $row) { $data = $row->toArray(); $data = array_merge($columns, $data); $rows .= $this->_arrayToString(array_values($data)) . $this->eol; } // Create the header $header = $this->_arrayToString(array_keys($columns)) . $this->eol; // Set the content $this->setContent($header . $rows); return parent::render(); }
/** * Get materials count grouped by structure selectors * @param mixed $selectors Collection of structures selectors to group materials * @param string $selector Selector to find structures, [Url] is used by default * @param callable $handler External handler * * @return \integer[] Collection where key is structure selector and value is materials count */ public static function getMaterialsCountByStructures($selectors, $selector = 'Url', $handler = null) { // If not array is passed if (!is_array($selectors)) { // convert it to array $selectors = array($selectors); } /** @var integer[] $results Collection of materials count grouped by selectors as array keys */ $results = array_flip($selectors); /** @var Navigation[] $countData */ $countData = null; $query = dbQuery('structure')->cond($selector, $selectors)->add_field('Count(material.materialid)', '__Count', false)->join('structurematerial')->join('material')->cond('material_Active', 1)->cond('material_Published', 1)->cond('material_Draft', 0)->group_by('structureid'); if (is_callable($handler)) { call_user_func($handler, array(&$query)); } // Perform db request to get materials count by passed structure selectors if ($query->exec($countData)) { foreach ($countData as $result) { // Check if we have this structure in results array if (isset($results[$result->Url])) { // Store materials count $results[$result->Url . 'Count'] = $result->__Count; } } } foreach ($selectors as $select) { unset($results[$select]); } return $results; }
public function dump_export_data() { if ($this->exporter->get('viewexportmode') == PluginExport::EXPORT_LIST_OF_VIEWS && $this->exporter->get('artefactexportmode') == PluginExport::EXPORT_ARTEFACTS_FOR_VIEWS) { // Dont' care about profile information in this case return; } $smarty = $this->exporter->get_smarty('../../', 'internal'); $smarty->assign('page_heading', get_string('profilepage', 'artefact.internal')); // Profile page $profileviewid = $this->exporter->get('user')->get_profile_view()->get('id'); foreach ($this->exporter->get('views') as $viewid => $view) { if ($profileviewid == $viewid) { $smarty->assign('breadcrumbs', array(array('text' => 'Profile page', 'path' => 'profilepage.html'))); $view = $this->exporter->get('user')->get_profile_view(); $outputfilter = new HtmlExportOutputFilter('../../'); $smarty->assign('view', $outputfilter->filter($view->build_columns())); $content = $smarty->fetch('export:html/internal:profilepage.tpl'); if (!file_put_contents($this->fileroot . 'profilepage.html', $content)) { throw new SystemException("Unable to write profile page"); } $this->profileviewexported = true; break; } } // Generic profile information $smarty->assign('page_heading', get_string('profileinformation', 'artefact.internal')); $smarty->assign('breadcrumbs', array(array('text' => 'Profile information', 'path' => 'index.html'))); // Organise profile information by sections, ordered how it's ordered // on the 'edit profile' page $sections = array('aboutme' => array(), 'contact' => array(), 'messaging' => array(), 'general' => array()); $elementlist = call_static_method('ArtefactTypeProfile', 'get_all_fields'); $elementlistlookup = array_flip(array_keys($elementlist)); $profilefields = get_column_sql('SELECT id FROM {artefact} WHERE owner=? AND artefacttype IN (' . join(",", array_map(create_function('$a', 'return db_quote($a);'), array_keys($elementlist))) . ")", array($this->exporter->get('user')->get('id'))); foreach ($profilefields as $id) { $artefact = artefact_instance_from_id($id); $rendered = $artefact->render_self(array('link' => true)); if ($artefact->get('artefacttype') == 'introduction') { $outputfilter = new HtmlExportOutputFilter('../../'); $rendered['html'] = $outputfilter->filter($rendered['html']); } $sections[$this->get_category_for_artefacttype($artefact->get('artefacttype'))][$artefact->get('artefacttype')] = array('html' => $rendered['html'], 'weight' => $elementlistlookup[$artefact->get('artefacttype')]); } // Sort the data and then drop the weighting information foreach ($sections as &$section) { uasort($section, create_function('$a, $b', 'return $a["weight"] > $b["weight"];')); foreach ($section as &$data) { $data = $data['html']; } } $smarty->assign('sections', $sections); $iconid = $this->exporter->get('user')->get('profileicon'); if ($iconid) { $icon = artefact_instance_from_id($iconid); $smarty->assign('icon', '<img src="../../static/profileicons/200px-' . PluginExportHtml::sanitise_path($icon->get('title')) . '" alt="Profile Icon">'); } $content = $smarty->fetch('export:html/internal:index.tpl'); if (!file_put_contents($this->fileroot . 'index.html', $content)) { throw new SystemException("Unable to write profile information page"); } }
function loadCharset($charset) { $charset = preg_replace(array('/^WINDOWS-*125([0-8])$/', '/^CP-/'), array('CP125\\1', 'CP'), $charset); if (isset($aliases[$charset])) { $charset = $aliases[$charset]; } $this->charset = $charset; if (empty($this->ascMap[$charset])) { $file = UTF8_MAP_DIR . '/' . $charset . '.map'; if (!is_file($file)) { $this->onError(ERR_OPEN_MAP_FILE, "Failed to open map file for {$charset}"); return; } $lines = file_get_contents($file); $lines = preg_replace("/#.*\$/m", "", $lines); $lines = preg_replace("/\n\n/", "", $lines); $lines = explode("\n", $lines); foreach ($lines as $line) { $parts = explode('0x', $line); if (count($parts) == 3) { $asc = hexdec(substr($parts[1], 0, 2)); $utf = hexdec(substr($parts[2], 0, 4)); $this->ascMap[$charset][$asc] = $utf; } } $this->utfMap = array_flip($this->ascMap[$charset]); } }
public function run() { $app = $this->xtr->getApplication(); /** @var $matcher RedirectableUrlMatcher */ $context = $app['request_context']; $matched = false; $path = $this->xtr->getRequest()->getPathInfo(); $lastException = null; // matching fallback route groups: foreach ($this->xtr['routes'] as $fallback => $routes) { $routes = RouteCollection::FromArray($routes)->flat(); $matcher = new RedirectableUrlMatcher($routes->toSilexCollection(), $context); try { $matcher->match($path); $matched = $fallback; break; } catch (ResourceNotFoundException $e) { // not found: silent continue $lastException = $e; } } if ($matched === false) { throw $lastException; } // configuring distinct service: $allow = [$matched]; $fallbacks = array_flip(array_keys($this->xtr['routes'])); unset($fallbacks[$matched]); $deny = array_keys($fallbacks); $this->xtr['@distinct.settings'] = ['allow' => $allow, 'deny' => $deny]; }
/** * Constructor. * * @param \TokenReflection\IReflection $reflection Inspected reflection * @param \ApiGen\Generator $generator ApiGen generator */ public function __construct(IReflection $reflection = null, Generator $generator = null) { $this->reflectionType = get_class($this); if (!isset(self::$reflectionMethods[$this->reflectionType])) { self::$reflectionMethods[$this->reflectionType] = array_flip(get_class_methods($this)); } }
/** * When the user clicks the Search button, the form is posted back here and this action sets the * search parameters in the session. Once this call returns, the tabs will then call RetrieveSource to load * the data that was saved in the session. * */ function action_SetSearch() { if (empty($_REQUEST)) { return; } $this->view = 'ajax'; require_once 'include/connectors/utils/ConnectorUtils.php'; $searchdefs = ConnectorUtils::getSearchDefs(); $merge_module = $_REQUEST['merge_module']; $record_id = $_REQUEST['record']; $searchDefs = isset($searchdefs) ? $searchdefs : array(); unset($_SESSION['searchDefs'][$merge_module][$record_id]); $sMap = array(); $search_source = $_REQUEST['source_id']; $source_instance = ConnectorFactory::getInstance($search_source); $source_map = $source_instance->getModuleMapping($merge_module); $module_fields = array(); foreach ($_REQUEST as $search_term => $val) { if (!empty($source_map[$search_term])) { $module_fields[$source_map[$search_term]] = $val; } } foreach ($module_fields as $search_term => $val) { foreach ($searchDefs as $source => $modules) { if (empty($sMap[$source])) { $instance = ConnectorFactory::getInstance($source); $sMap[$source] = array_flip($instance->getModuleMapping($merge_module)); } if (!empty($sMap[$source][$search_term])) { $source_key = $sMap[$source][$search_term]; $_SESSION['searchDefs'][$merge_module][$record_id][$source][$source_key] = $val; } } } }
/** * Escape strings for safe use in an LDAP filter or DN * * @see RFC2254 define how string search filters must be represented * @see For PHP >= 5.6.0, ldap_escape() is a core function * * @author Chris Wright * @see https://github.com/DaveRandom/LDAPi/blob/master/src/global_functions.php * * @return String */ private function escape($value, $ignore = '', $flags = 0) { if (function_exists('ldap_escape')) { return ldap_escape($value, $ignore, $flags); } $value = (string) $value; $ignore = (string) $ignore; $flags = (int) $flags; if ($value === '') { return ''; } $char_list = array(); if ($flags & self::LDAP_ESCAPE_FILTER) { $char_list = array("\\", "*", "(", ")", ""); } if ($flags & self::LDAP_ESCAPE_DN) { $char_list = array_merge($char_list, array("\\", ",", "=", "+", "<", ">", ";", "\"", "#")); } if (!$char_list) { for ($i = 0; $i < 256; $i++) { $char_list[] = chr($i); } } $char_list = array_flip($char_list); for ($i = 0; isset($ignore[$i]); $i++) { unset($char_list[$ignore[$i]]); } foreach ($char_list as $k => &$v) { $v = sprintf('\\%02x', ord($k)); } return strtr($value, $char_list); }
/** * Returns all of the attributes in the collection * * If an optional mask array is passed, this only * returns the keys that match the mask * * @param array $mask The parameter mask array * @access public * @return array */ public function all($mask = null) { if (null !== $mask) { // Support a more "magical" call if (!is_array($mask)) { $mask = func_get_args(); } /* * Remove all of the keys from the attributes * that aren't in the passed mask */ $attributes = array_intersect_key($this->attributes, array_flip($mask)); /* * Make sure that each key in the mask has at least a * null value, since the user will expect the key to exist */ foreach ($mask as $key) { if (!isset($attributes[$key])) { $attributes[$key] = null; } } return $attributes; } return $this->attributes; }
public static function get_tests($root_file, $root_class, $add_skip = null) { $tests = array(); if (!isset($root_file) || !isset($root_class)) { return $tests; } $skip = array('.', '..', 'all.php'); if (is_array($add_skip)) { $skip = array_merge($skip, $add_skip); } $skip = array_flip($skip); $path_parts = pathinfo($root_file); $tests_dir = dir($path_parts['dirname']); $prefix = str_replace('_all', '', $root_class); while (($testfile = $tests_dir->read()) !== false) { if (array_key_exists($testfile, $skip)) { continue; } $path_parts = pathinfo($testfile); $test_name = str_replace('.php', '', $path_parts['filename']); $test_name = str_replace('Test', '', $test_name); if ($test_name != '') { require_once realpath(dirname($root_file)) . "/{$testfile}"; $tests[] = "{$prefix}_{$test_name}"; } } return $tests; }
public function call() { $propName = $this->callName; $arguments = $this->callArguments; if (empty($arguments)) { return false; } if (!isset($this->model->{$propName})) { $propName[0] = strtolower($propName[0]); } $collection = $this->model->{$propName}; if (!empty($collection) && is_array($collection)) { $ids = $arguments; if (count($arguments) == 1 && is_array($arguments[0])) { $ids = $arguments[0]; } $idsToDelete = array_flip($ids); foreach ($collection as $item) { if (isset($idsToDelete[$item->id])) { $item->markForDeletion(); $this->model->setDirty(); } } return true; } return false; }
public function execute() { $params = $this->extractRequestParams(); $prop = array_flip($params['prop']); $this->fld_displayname = isset($prop['displayname']); $this->fld_description = isset($prop['description']); $this->fld_hitcount = isset($prop['hitcount']); $this->limit = $params['limit']; $this->result = $this->getResult(); $this->addTables('change_tag'); $this->addFields('ct_tag'); $this->addFieldsIf(array('hitcount' => 'COUNT(*)'), $this->fld_hitcount); $this->addOption('LIMIT', $this->limit + 1); $this->addOption('GROUP BY', 'ct_tag'); $this->addWhereRange('ct_tag', 'newer', $params['continue'], null); $res = $this->select(__METHOD__); $ok = true; foreach ($res as $row) { if (!$ok) { break; } $ok = $this->doTag($row->ct_tag, $this->fld_hitcount ? $row->hitcount : 0); } // include tags with no hits yet foreach (ChangeTags::listDefinedTags() as $tag) { if (!$ok) { break; } $ok = $this->doTag($tag, 0); } $this->result->setIndexedTagName_internal(array('query', $this->getModuleName()), 'tag'); }
/** * @see EventListener::execute() */ public function execute($eventObj, $className, $eventName) { if ($eventName == 'readFormParameters') { if (isset($_POST['usedQuotes']) && is_array($_POST['usedQuotes'])) { $this->usedQuotes = $_POST['usedQuotes']; } } else { if ($eventName == 'saved') { if (count($this->usedQuotes) > 0) { require_once WCF_DIR . 'lib/data/message/multiQuote/MultiQuoteManager.class.php'; foreach ($this->usedQuotes as $quoteID) { MultiQuoteManager::removeQuote($quoteID); } MultiQuoteManager::saveStorage(); } } else { if ($eventName == 'assignVariables') { require_once WCF_DIR . 'lib/data/message/multiQuote/MultiQuoteManager.class.php'; $quotes = MultiQuoteManager::getStorage(); $usedQuotes = array_flip($this->usedQuotes); foreach ($quotes as $quoteID => $quote) { $quote['used'] = isset($usedQuotes[$quoteID]) ? 1 : 0; $quotes[$quoteID] = $quote; } WCF::getTPL()->assign('quotes', $quotes); WCF::getTPL()->append(array('additionalTabs' => '<li id="multiQuoteTab"><a onclick="tabbedPane.openTab(\'multiQuote\');"><span>' . WCF::getLanguage()->get('wcf.multiQuote.title') . '</span></a></li>', 'additionalSubTabs' => WCF::getTPL()->fetch('messageFormMultiQuote'))); } } } }
/** * {@inheritdoc} */ public function preprocessElement(Element $element, Variables $variables) { $variables->addClass(['image-widget', 'js-form-managed-file', 'form-managed-file', 'clearfix']); $data =& $variables->offsetGet('data', []); foreach ($element->children() as $key => $child) { // Modify the label to be a placeholder instead. if ($key === 'alt') { $child->setProperty('form_group', FALSE); $placeholder = (string) $child->getAttribute('placeholder'); if (!$placeholder) { $label = ['#theme' => 'form_element_label']; $label += array_intersect_key($child->getArray(), array_flip(['#id', '#required', '#title', '#title_display'])); $child->setProperty('title_display', 'invisible'); $placeholder = trim(strip_tags(Element::create($label)->render())); if ($child->getProperty('required')) { $child->setProperty('description', t('@description (Required)', ['@description' => $child->getProperty('description')])); } } if ($placeholder) { $child->setAttribute('placeholder', $placeholder); } } $data[$key] = $child->getArray(); } }
public function __construct() { $logPath = CoreHelper::loadConfig("log_path", "config"); $logFileExtension = CoreHelper::loadConfig("log_file_extension", "config"); $logThreshold = CoreHelper::loadConfig("log_threshold", "config"); $logDateFormat = CoreHelper::loadConfig("log_date_format", "config"); $logFilePermissions = CoreHelper::loadConfig("log_file_permissions", "config"); $this->_log_path = $logPath !== '' ? $logPath : APPPATH . 'logs/'; $this->_file_ext = isset($logFileExtension) && $logFileExtension !== '' ? ltrim($logFileExtension, '.') : 'php'; file_exists($this->_log_path) || mkdir($this->_log_path, 0755, true); if (!is_dir($this->_log_path) || !CoreHelper::isWriteable($this->_log_path)) { $this->_enabled = false; } if (is_numeric($logThreshold)) { $this->_threshold = (int) $logThreshold; } elseif (is_array($logThreshold)) { $this->_threshold = 0; $this->_threshold_array = array_flip($logThreshold); } if (!empty($logDateFormat)) { $this->_date_fmt = $logDateFormat; } if (!empty($logFilePermissions) && is_int($logFilePermissions)) { $this->_file_permissions = $logFilePermissions; } }
protected function _setSlugOptions() { foreach (Set::normalize($this->options['slugs']) as $slug => $options) { $defaultBySlug = array('display' => $slug); $this->_slugOptions[$slug] = Set::merge(array_intersect_key($this->options, array_flip(array('model', 'urlencode'))), $defaultBySlug, self::$defaultSlugOptions, $options); } }
/** * Show truncated long text and hide full version for flyout * * When there is a lot of text for a small area, this shows just the * truncated lead. The full text is in an element that is hidden. * Javascript or css can implement a flyout to show the full thing. * * Attributes: * $filed.leadPlus => * div // div containing the hidden full text * p // div > p containg the full text * span // div + span containg truncated text * truncate // [truncate][limit] charcter count in truncated text * * @param type $helper */ public function leadPlus($field) { if (!$this->hasUuid()) { $uuid = new Uuid(); } else { $uuid = $this->helper->entity->_uuid; } // established passed and default attributes $passed_attributes = $this->helper->attributes("{$field}.leadPlus"); $default = new \Cake\Collection\Collection(['full_text' => ['span' => ['id' => $uuid->uuid('full'), 'class' => 'full_text', 'style' => 'cursor: pointer; display: none;', 'onclick' => 'var id = this.id.replace("full", "truncated"); this.style.display = "none"; document.getElementById(id).style.display = "inline-block";']], 'truncated_text' => ['span' => ['id' => $uuid->uuid('truncated'), 'class' => 'truncated_text', 'style' => 'cursor: pointer; display: inline-block;', 'onclick' => 'var id = this.id.replace("truncated", "full"); this.style.display = "none"; document.getElementById(id).style.display = "inline-block";']], 'truncate' => ['limit' => [100]], 'p' => []]); // intermediary values for calculations $key_template = $default->map(function ($value, $key) { return null; }); // this yeilds array with all keys. values will be int if passed in, null if default $attribute_keys = array_flip(array_keys($passed_attributes)) + $key_template->toArray(); // get attributes to use during rendering $attribute = $default->map(function ($value, $key) use($attribute_keys, $passed_attributes) { if (is_null($attribute_keys[$key])) { return $value; } else { return array_merge($value, $passed_attributes[$key]); } })->toArray(); // output // SOMEONE SORT THIS OUT TO MAKE IT HAVE DEFAULT out-of-the-box BEHAVIOR $hidden = $this->helper->Html->tag('span', $this->helper->entity->{$field}, $attribute['full_text']['span']); $text = $this->helper->Html->tag('span', Text::truncate($this->helper->entity->{$field}, $attribute['truncate']['limit']), $attribute['truncated_text']['span']); return $this->helper->Html->tag('p', $text . $hidden, $attribute['p']); }
function SIEM_trends_week($param = "") { global $tz; $tzc = Util::get_tzc($tz); $data = array(); $plugins = $plugins_sql = ""; require_once 'ossim_db.inc'; $db = new ossim_db(); $dbconn = $db->connect(); $sensor_where = make_sensor_filter($dbconn); if ($param != "") { require_once "classes/Plugin.inc"; $oss_p_id_name = Plugin::get_id_and_name($dbconn, "WHERE name LIKE '{$param}'"); $plugins = implode(",", array_flip($oss_p_id_name)); $plugins_sql = "AND acid_event.plugin_id in ({$plugins})"; } $sqlgraph = "SELECT COUNT(acid_event.sid) as num_events, day(convert_tz(timestamp,'+00:00','{$tzc}')) as intervalo, monthname(convert_tz(timestamp,'+00:00','{$tzc}')) as suf FROM snort.acid_event LEFT JOIN ossim.plugin ON acid_event.plugin_id=plugin.id WHERE timestamp BETWEEN '" . gmdate("Y-m-d 00:00:00", gmdate("U") - 604800) . "' AND '" . gmdate("Y-m-d 23:59:59") . "' {$plugins_sql} {$sensor_where} GROUP BY suf,intervalo ORDER BY suf,intervalo"; if (!($rg =& $dbconn->Execute($sqlgraph))) { print $dbconn->ErrorMsg(); } else { while (!$rg->EOF) { $hours = $rg->fields["intervalo"] . " " . substr($rg->fields["suf"], 0, 3); $data[$hours] = $rg->fields["num_events"]; $rg->MoveNext(); } } $db->close($dbconn); return $param != "" ? array($data, $oss_plugin_id) : $data; }
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); } } }
function createFile($imgURL) { $remImgURL = urldecode($imgURL); $urlParced = pathinfo($remImgURL); $remImgURLFilename = $urlParced['basename']; $imgData = wp_remote_get($remImgURL); if (is_wp_error($imgData)) { $badOut['Error'] = print_r($imgData, true) . " - ERROR"; return $badOut; } $imgData = $imgData['body']; $tmp = array_search('uri', @array_flip(stream_get_meta_data($GLOBALS[mt_rand()] = tmpfile()))); if (!is_writable($tmp)) { return "Your temporary folder or file (file - " . $tmp . ") is not witable. Can't upload images to Flickr"; } rename($tmp, $tmp .= '.png'); register_shutdown_function(create_function('', "unlink('{$tmp}');")); file_put_contents($tmp, $imgData); if (!$tmp) { return 'You must specify a path to a file'; } if (!file_exists($tmp)) { return 'File path specified does not exist'; } if (!is_readable($tmp)) { return 'File path specified is not readable'; } // $data['name'] = basename($tmp); return "@{$tmp}"; }