function wp_generate_product_tag_cloud($tags, $args = '')
{
    global $wp_rewrite;
    $defaults = array('smallest' => 8, 'largest' => 22, 'unit' => 'pt', 'number' => 45, 'format' => 'flat', 'orderby' => 'name', 'order' => 'ASC');
    $args = wp_parse_args($args, $defaults);
    extract($args);
    if (!$tags) {
        return;
    }
    $counts = $tag_links = array();
    foreach ((array) $tags as $tag) {
        $counts[$tag->name] = $tag->count;
        $tag_links[$tag->name] = get_product_tag_link($tag->term_id);
        if (is_wp_error($tag_links[$tag->name])) {
            return $tag_links[$tag->name];
        }
        $tag_ids[$tag->name] = $tag->term_id;
    }
    $min_count = min($counts);
    $spread = max($counts) - $min_count;
    if ($spread <= 0) {
        $spread = 1;
    }
    $font_spread = $largest - $smallest;
    if ($font_spread <= 0) {
        $font_spread = 1;
    }
    $font_step = $font_spread / $spread;
    // SQL cannot save you; this is a second (potentially different) sort on a subset of data.
    if ('name' == $orderby) {
        uksort($counts, 'strnatcasecmp');
    } else {
        asort($counts);
    }
    if ('DESC' == $order) {
        $counts = array_reverse($counts, true);
    }
    $a = array();
    $rel = is_object($wp_rewrite) && $wp_rewrite->using_permalinks() ? ' rel="tag"' : '';
    foreach ($counts as $tag => $count) {
        $tag_id = $tag_ids[$tag];
        $tag_link = clean_url($tag_links[$tag]);
        $tag = str_replace(' ', '&nbsp;', wp_specialchars($tag));
        $a[] = "<a href='{$tag_link}' class='tag-link-{$tag_id}' title='" . attribute_escape(sprintf(__('%d topics'), $count)) . "'{$rel} style='font-size: " . ($smallest + ($count - $min_count) * $font_step) . "{$unit};'>{$tag}</a>";
    }
    switch ($format) {
        case 'array':
            $return =& $a;
            break;
        case 'list':
            $return = "<ul class='product_tag_cloud'>\n\t<li>";
            $return .= join("</li>\n\t<li>", $a);
            $return .= "</li>\n</ul>\n";
            break;
        default:
            $return = join("\n", $a);
            break;
    }
    return apply_filters('wp_generate_product_tag_cloud', $return, $tags, $args);
}
Пример #2
1
 /**
  * @param bool $isMultiselect
  * @return array
  */
 public function toOptionArray($isMultiselect = false)
 {
     if (!$this->_options) {
         $countriesArray = $this->_countryCollectionFactory->create()->load()->toOptionArray(false);
         $this->_countries = [];
         foreach ($countriesArray as $a) {
             $this->_countries[$a['value']] = $a['label'];
         }
         $countryRegions = [];
         $regionsCollection = $this->_regionCollectionFactory->create()->load();
         foreach ($regionsCollection as $region) {
             $countryRegions[$region->getCountryId()][$region->getId()] = $region->getDefaultName();
         }
         uksort($countryRegions, [$this, 'sortRegionCountries']);
         $this->_options = [];
         foreach ($countryRegions as $countryId => $regions) {
             $regionOptions = [];
             foreach ($regions as $regionId => $regionName) {
                 $regionOptions[] = ['label' => $regionName, 'value' => $regionId];
             }
             $this->_options[] = ['label' => $this->_countries[$countryId], 'value' => $regionOptions];
         }
     }
     $options = $this->_options;
     if (!$isMultiselect) {
         array_unshift($options, ['value' => '', 'label' => '']);
     }
     return $options;
 }
 /**
  * Generate OAuth signature, see server-side method here:
  *
  * @link https://github.com/WIC/woocommerce/blob/master/includes/api/class-wc-api-authentication.php#L196-L252
  *
  * @since 2.0
  *
  * @param array $params query parameters (including oauth_*)
  * @param string $http_method, e.g. GET
  * @return string signature
  */
 public function generate_oauth_signature($params, $http_method)
 {
     $base_request_uri = rawurlencode($this->url);
     if (isset($params['filter'])) {
         $filters = $params['filter'];
         unset($params['filter']);
         foreach ($filters as $filter => $filter_value) {
             $params['filter[' . $filter . ']'] = $filter_value;
         }
     }
     // normalize parameter key/values and sort them
     // Make a waring if param is an array
     $params = @$this->normalize_parameters($params);
     uksort($params, 'strcmp');
     // form query string
     $query_params = array();
     foreach ($params as $param_key => $param_value) {
         $query_params[] = $param_key . '%3D' . $param_value;
         // join with equals sign
     }
     $query_string = implode('%26', $query_params);
     // join with ampersand
     // form string to sign (first key)
     $string_to_sign = $http_method . '&' . $base_request_uri . '&' . $query_string;
     $secret = $this->consumer_secret;
     if (preg_match('/wc-api\\/v3/', $this->url)) {
         // @see https://stackoverflow.com/questions/31976059/woocommerce-api-v3-authentication-issue
         $secret .= '&';
     }
     return base64_encode(hash_hmac(self::HASH_ALGORITHM, $string_to_sign, $secret, true));
 }
 protected function sortKeys()
 {
     switch (strtoupper($this->getOption('key_sort'))) {
         case 'NONE':
             break;
         case 'SORT_REGULAR':
             ksort($this->value, SORT_REGULAR);
             break;
         case 'SORT_NUMERIC':
             ksort($this->value, SORT_NUMERIC);
             break;
         case 'SORT_STRING':
             ksort($this->value, SORT_STRING);
             break;
         case 'SORT_STRING_CASE':
             uksort($this->value, "strcasecmp");
             //ksort($this->value,SORT_STRING | SORT_FLAG_CASE); php 5.4
             break;
         case 'SORT_LOCAL_STRING':
             ksort($this->value, SORT_LOCALE_STRING);
             break;
         case 'SORT_NATURAL':
             uksort($this->value, "strnatcasecmp");
             // ksort($this->value,SORT_NATURAL); php 5.4
             break;
         default:
         case 'SORT_NATURAL_CASE':
             uksort($this->value, "strnatcasecmp");
             //ksort($this->value,SORT_NATURAL | SORT_FLAG_CASE);  php 5.4
             break;
     }
 }
 function prepare_items()
 {
     global $ct;
     $ct = current_theme_info();
     $themes = get_allowed_themes();
     if (!empty($_REQUEST['s'])) {
         $search = strtolower(stripslashes($_REQUEST['s']));
         $this->search = array_merge($this->search, array_filter(array_map('trim', explode(',', $search))));
         $this->search = array_unique($this->search);
     }
     if (!empty($_REQUEST['features'])) {
         $this->features = $_REQUEST['features'];
         $this->features = array_map('trim', $this->features);
         $this->features = array_map('sanitize_title_with_dashes', $this->features);
         $this->features = array_unique($this->features);
     }
     if ($this->search || $this->features) {
         foreach ($themes as $key => $theme) {
             if (!$this->search_theme($theme)) {
                 unset($themes[$key]);
             }
         }
     }
     unset($themes[$ct->name]);
     uksort($themes, "strnatcasecmp");
     $per_page = 24;
     $page = $this->get_pagenum();
     $start = ($page - 1) * $per_page;
     $this->items = array_slice($themes, $start, $per_page);
     $this->set_pagination_args(array('total_items' => count($themes), 'per_page' => $per_page));
 }
Пример #6
0
 public static function build_http_query($params = array())
 {
     if (empty($params)) {
         return "";
     }
     // Urlencode both keys and values
     $keys = Utility::urlencode_rfc3986(array_keys($params));
     $values = Utility::urlencode_rfc3986(array_values($params));
     $params = array_combine($keys, $values);
     // params are sorted by name, using lexicographical byte value ordering.
     // Ref: Spec: 9.1.1 (1)
     uksort($params, 'strcmp');
     $pairs = array();
     foreach ($params as $parameter => $value) {
         if (is_array($value)) {
             // If two or more params share the same name, they are sorted by their value
             // Ref: Spec: 9.1.1 (1)
             natsort($value);
             foreach ($value as $duplicate_value) {
                 $pairs[] = $parameter . '=' . $duplicate_value;
             }
         } else {
             $pairs[] = $parameter . '=' . $value;
         }
     }
     // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
     // Each name-value pair is separated by an '&' character (ASCII code 38)
     return implode('&', $pairs);
 }
Пример #7
0
 /**
  * @param $params
  *
  * @return string
  */
 public static function buildHttpQuery($params)
 {
     if (!$params) {
         return '';
     }
     // Urlencode both keys and values
     $keys = Util::urlencodeRfc3986(array_keys($params));
     $values = Util::urlencodeRfc3986(array_values($params));
     $params = array_combine($keys, $values);
     // Parameters are sorted by name, using lexicographical byte value ordering.
     // Ref: Spec: 9.1.1 (1)
     uksort($params, 'strcmp');
     $pairs = array();
     foreach ($params as $parameter => $value) {
         if (is_array($value)) {
             // If two or more parameters share the same name, they are sorted by their value
             // Ref: Spec: 9.1.1 (1)
             // June 12th, 2010 - changed to sort because of issue 164 by hidetaka
             sort($value, SORT_STRING);
             foreach ($value as $duplicateValue) {
                 $pairs[] = $parameter . '=' . $duplicateValue;
             }
         } else {
             $pairs[] = $parameter . '=' . $value;
         }
     }
     // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
     // Each name-value pair is separated by an '&' character (ASCII code 38)
     return implode('&', $pairs);
 }
Пример #8
0
 /**
  * @param array $map (location => weight)
  */
 public function __construct(array $map)
 {
     $map = array_filter($map, function ($w) {
         return $w > 0;
     });
     if (!count($map)) {
         throw new UnexpectedValueException("Ring is empty or all weights are zero.");
     }
     $this->sourceMap = $map;
     // Sort the locations based on the hash of their names
     $hashes = array();
     foreach ($map as $location => $weight) {
         $hashes[$location] = sha1($location);
     }
     uksort($map, function ($a, $b) use($hashes) {
         return strcmp($hashes[$a], $hashes[$b]);
     });
     // Fit the map to weight-proportionate one with a space of size RING_SIZE
     $sum = array_sum($map);
     $standardMap = array();
     foreach ($map as $location => $weight) {
         $standardMap[$location] = (int) floor($weight / $sum * self::RING_SIZE);
     }
     // Build a ring of RING_SIZE spots, with each location at a spot in location hash order
     $index = 0;
     foreach ($standardMap as $location => $weight) {
         // Location covers half-closed interval [$index,$index + $weight)
         $this->ring[$location] = array($index, $index + $weight);
         $index += $weight;
     }
     // Make sure the last location covers what is left
     end($this->ring);
     $this->ring[key($this->ring)][1] = self::RING_SIZE;
 }
 function refresh()
 {
     // create basic files if missing
     self::$_archive_file = $this->_create(FILE_ARCHIVE);
     self::$_trash_file = $this->_create(FILE_TRASH);
     $paths = glob(self::$_data_dir . "*" . EXT);
     // what if only trash and archive exist?  Create a default task file
     if (count($paths) <= 2) {
         self::_create(self::$_default_file);
         $paths[] = self::$_data_dir . self::$_default_file . EXT;
     }
     $names = str_replace(array(EXT, self::$_data_dir), '', $paths);
     self::$_names = $names;
     $modified = array_map(function ($path) {
         return filemtime($path);
     }, $paths);
     self::$_files = array();
     $count = count($paths);
     for ($i = 0; $i < $count; $i++) {
         $name = $names[$i];
         if ($name == self::$_archive_file) {
             $type = TAB_ARCHIVE;
         } elseif ($name == self::$_trash_file) {
             $type = TAB_TRASH;
         } else {
             $type = TAB_NORMAL;
         }
         self::$_files[$name] = new File($i, $name, $paths[$i], $modified[$i], $type);
     }
     // Basic initial sort: case insensitive, with symbol first (i.e. '_')
     uksort(self::$_files, 'strcasecmp');
 }
Пример #10
0
/**
 * Translate strings to the current locale
 *
 * When using get_lang(), try to put entire sentences and strings in
 * one get_lang() call. This makes it easier for translators.
 *
 * @code
 *  $msg = get_lang('Hello %name',array('%name' => $username))
 * @endcode
 *
 * @param $name
 *   A string containing the English string to translate.
 * @param $var_to_replace
 *   An associative array of replacements to make after translation. Incidences
 *   of any key in this array are replaced with the corresponding value.
 * @return
 *   The translated string.
 */
function get_lang($name, $var_to_replace = null)
{
    global $_lang;
    $translation = '';
    if (isset($_lang[$name])) {
        $translation = $_lang[$name];
    } else {
        // missing translation
        $translation = $name;
    }
    if (!empty($var_to_replace) && is_array($var_to_replace)) {
        if (claro_debug_mode()) {
            foreach (array_keys($var_to_replace) as $signature) {
                if (false === strpos($translation, $signature)) {
                    if (is_numeric($signature) && isset($var_to_replace[$signature + 1])) {
                        pushClaroMessage($signature . ' not in varlang.<br>
"<b>' . $var_to_replace[$signature] . '</b>" is probably the key of "<b>' . $var_to_replace[$signature + 1] . '</b>"', 'translation');
                    } else {
                        pushClaroMessage($signature . ' not in varlang.', 'translation');
                    }
                }
            }
        }
        uksort($var_to_replace, 'cmp_string_by_length');
        return strtr($translation, $var_to_replace);
    } else {
        // return translation
        return $translation;
    }
}
Пример #11
0
 public function match(Route $route)
 {
     uksort($this->map, function ($path1, $path2) {
         $path1Length = strlen($path1);
         $path2Length = strlen($path2);
         return $path1Length == $path2Length ? 0 : ($path1Length < $path2Length ? 1 : -1);
     });
     $missingPath = $route->getMissingPath();
     foreach ($this->map as $path => $parameters) {
         if (stripos($missingPath, $path) !== 0) {
             continue;
         }
         if (!$this->allowPartialMatches && strtolower(trim($path, '/')) != strtolower(trim($missingPath, '/'))) {
             continue;
         }
         $route->matchPath($path);
         foreach ($parameters as $key => $value) {
             $route->setParameter($key, $value);
         }
         if (trim($route->getMissingPath(), '/') == '') {
             $route->found();
         }
         break;
     }
 }
Пример #12
0
 /**
  * Constructor - Parse the /config/comics.php config file and store
  * the results in $comic.  Also tries to validate all the data it can
  * and adjust case, etc., to more predictible consistency than humans
  * editing config files can give. :)
  *
  * @param integer $sort         Sorting method to use
  */
 function Klutz($sort = KLUTZ_SORT_NAME)
 {
     $this->sort = $sort;
     // Load the list of comics from the config file.
     include_once KLUTZ_BASE . '/config/comics.php';
     if (isset($comics)) {
         $this->comics = $comics;
     }
     if ($this->sort != KLUTZ_SORT_NOSORT) {
         uksort($this->comics, array($this, '_sortComics'));
     }
     foreach (array_keys($this->comics) as $index) {
         if (empty($this->comics[$index]['days'])) {
             $this->comics[$index]['days'] = array_unique($this->days);
         } else {
             if (!is_array($this->comics[$index]['days'])) {
                 if (Horde_String::lower($this->comics[$index]['days']) == 'random') {
                     $this->comics[$index]['days'] = 'random';
                 } else {
                     $this->comics[$index]['days'] = array($this->comics[$index]['days']);
                 }
             }
             if (is_array($this->comics[$index]['days'])) {
                 $this->comics[$index]['days'] = array_map(array($this, '_convertDay'), $this->comics[$index]['days']);
             }
         }
         if (empty($this->comics[$index]['nohistory'])) {
             $this->comics[$index]['nohistory'] = false;
         }
     }
 }
Пример #13
0
 protected function _buildQuery($params, $separator = '&', $noQuotes = true, $subList = false)
 {
     if (empty($params)) {
         return '';
     }
     //encode both keys and values
     $keys = $this->_encode(array_keys($params));
     $values = $this->_encode(array_values($params));
     $params = array_combine($keys, $values);
     // Parameters are sorted by name, using lexicographical byte value ordering.
     // http://oauth.net/core/1.0/#rfc.section.9.1.1
     uksort($params, 'strcmp');
     // Turn params array into an array of "key=value" strings
     foreach ($params as $key => $value) {
         if (is_array($value)) {
             // If two or more parameters share the same name,
             // they are sorted by their value. OAuth Spec: 9.1.1 (1)
             natsort($value);
             $params[$key] = $this->_buildQuery($value, $separator, $noQuotes, true);
             continue;
         }
         if (!$noQuotes) {
             $value = '"' . $value . '"';
         }
         $params[$key] = $value;
     }
     if ($subList) {
         return $params;
     }
     foreach ($params as $key => $value) {
         $params[$key] = $key . '=' . $value;
     }
     return implode($separator, $params);
 }
Пример #14
0
/**
 * Get a map between smiley codes and templates representing the HTML-image-code for this smiley. The smilies present of course depend on the forum involved.
 *
 * @param  object			Link to the real forum driver
 * @param  ?MEMBER		Only emoticons the given member can see (NULL: don't care)
 * @return array			The map
 */
function _helper_apply_emoticons($this_ref, $member_id = NULL)
{
    global $IN_MINIKERNEL_VERSION;
    if ($IN_MINIKERNEL_VERSION == 1) {
        return array();
    }
    $extra = '';
    if (is_null($member_id)) {
        global $EMOTICON_CACHE, $EMOTICON_LEVELS;
        if (!is_null($EMOTICON_CACHE)) {
            return $EMOTICON_CACHE;
        }
    } else {
        $extra = has_specific_permission(get_member(), 'use_special_emoticons') ? '' : ' AND e_is_special=0';
    }
    $EMOTICON_CACHE = array();
    $EMOTICON_LEVELS = array();
    $query = 'SELECT e_code,e_theme_img_code,e_relevance_level FROM ' . $this_ref->connection->get_table_prefix() . 'f_emoticons WHERE e_relevance_level<4' . $extra;
    if (strpos(get_db_type(), 'mysql') !== false) {
        $query .= ' ORDER BY LENGTH(e_code) DESC';
    }
    $rows = $this_ref->connection->query($query);
    foreach ($rows as $myrow) {
        $tpl = 'EMOTICON_IMG_CODE_THEMED';
        $EMOTICON_CACHE[$myrow['e_code']] = array($tpl, $myrow['e_theme_img_code'], $myrow['e_code']);
        $EMOTICON_LEVELS[$myrow['e_code']] = $myrow['e_relevance_level'];
    }
    if (strpos(get_db_type(), 'mysql') === false) {
        uksort($EMOTICON_CACHE, 'strlen_sort');
        $EMOTICON_CACHE = array_reverse($EMOTICON_CACHE);
    }
    return $EMOTICON_CACHE;
}
Пример #15
0
 private function build_http_query_multi($params)
 {
     if (!$params) {
         return '';
     }
     uksort($params, 'strcmp');
     $pairs = array();
     $this->boundary = $boundary = uniqid('------------------');
     $MPboundary = '--' . $boundary;
     $endMPboundary = $MPboundary . '--';
     $multipartbody = '';
     foreach ($params as $parameter => $value) {
         if (in_array($parameter, array('pic', 'image')) && $value[0] == '@') {
             $url = ltrim($value, '@');
             $content = file_get_contents($url);
             $array = explode('?', basename($url));
             $filename = $array[0];
             $body .= $MPboundary . "\r\n";
             $body .= 'Content-Disposition: form-data; name="' . $parameter . '"; filename="' . $filename . '"' . "\r\n";
             $body .= "Content-Type: image/unknown\r\n\r\n";
             $body .= $content . "\r\n";
         } else {
             $body .= $MPboundary . "\r\n";
             $body .= 'content-disposition: form-data; name="' . $parameter . "\"\r\n\r\n";
             $body .= $value . "\r\n";
         }
     }
     $multipartbody .= $endMPboundary;
     return $multipartbody;
 }
Пример #16
0
 /**
  * Constructor.
  */
 public function __construct($idSite = false)
 {
     parent::__construct();
     $this->jsClass = "SegmentSelectorControl";
     $this->cssIdentifier = "segmentEditorPanel";
     $this->cssClass = "piwikTopControl";
     $this->idSite = $idSite ?: Common::getRequestVar('idSite', false, 'int');
     $this->selectedSegment = Common::getRequestVar('segment', false, 'string');
     $segments = APIMetadata::getInstance()->getSegmentsMetadata($this->idSite);
     $segmentsByCategory = $customVariablesSegments = array();
     foreach ($segments as $segment) {
         if ($segment['category'] == Piwik::translate('General_Visit') && ($segment['type'] == 'metric' && $segment['segment'] != 'visitIp')) {
             $metricsLabel = Piwik::translate('General_Metrics');
             $metricsLabel[0] = strtolower($metricsLabel[0]);
             $segment['category'] .= ' (' . $metricsLabel . ')';
         }
         $segmentsByCategory[$segment['category']][] = $segment;
     }
     uksort($segmentsByCategory, array($this, 'sortSegmentCategories'));
     $this->createRealTimeSegmentsIsEnabled = Config::getInstance()->General['enable_create_realtime_segments'];
     $this->segmentsByCategory = $segmentsByCategory;
     $this->nameOfCurrentSegment = '';
     $this->isSegmentNotAppliedBecauseBrowserArchivingIsDisabled = 0;
     $this->availableSegments = API::getInstance()->getAll($this->idSite);
     foreach ($this->availableSegments as &$savedSegment) {
         $savedSegment['name'] = Common::sanitizeInputValue($savedSegment['name']);
         if (!empty($this->selectedSegment) && $this->selectedSegment == $savedSegment['definition']) {
             $this->nameOfCurrentSegment = $savedSegment['name'];
             $this->isSegmentNotAppliedBecauseBrowserArchivingIsDisabled = $this->wouldApplySegment($savedSegment) ? 0 : 1;
         }
     }
     $this->authorizedToCreateSegments = SegmentEditorAPI::getInstance()->isUserCanAddNewSegment($this->idSite);
     $this->isUserAnonymous = Piwik::isUserIsAnonymous();
     $this->segmentTranslations = $this->getTranslations();
 }
 public function toOptionArray($isMultiselect = false)
 {
     if (!$this->_options) {
         $countriesArray = Mage::getResourceModel('directory/country_collection')->load()->toOptionArray(false);
         $this->_countries = array();
         foreach ($countriesArray as $a) {
             $this->_countries[$a['value']] = $a['label'];
         }
         $countryRegions = array();
         $regionsCollection = Mage::getResourceModel('directory/region_collection')->load();
         foreach ($regionsCollection as $region) {
             $countryRegions[$region->getCountryId()][$region->getId()] = $region->getDefaultName();
         }
         uksort($countryRegions, array($this, 'sortRegionCountries'));
         $this->_options = array();
         foreach ($countryRegions as $countryId => $regions) {
             $regionOptions = array();
             foreach ($regions as $regionId => $regionName) {
                 $regionOptions[] = array('label' => $regionName, 'value' => $regionId);
             }
             $this->_options[] = array('label' => $this->_countries[$countryId], 'value' => $regionOptions);
         }
     }
     $options = $this->_options;
     if (!$isMultiselect) {
         array_unshift($options, array('value' => '', 'label' => ''));
     }
     return $options;
 }
Пример #18
0
 /**
  * Get scope variables.
  *
  * @param boolean $showAll Include special variables (e.g. $_).
  *
  * @return array
  */
 protected function getVariables($showAll)
 {
     $scopeVars = $this->context->getAll();
     uksort($scopeVars, function ($a, $b) {
         if ($a === '_e') {
             return 1;
         } elseif ($b === '_e') {
             return -1;
         } elseif ($a === '_') {
             return 1;
         } elseif ($b === '_') {
             return -1;
         } else {
             // TODO: this should be natcasesort
             return strcasecmp($a, $b);
         }
     });
     $ret = array();
     foreach ($scopeVars as $name => $val) {
         if (!$showAll && in_array($name, self::$specialVars)) {
             continue;
         }
         $ret[$name] = $val;
     }
     return $ret;
 }
Пример #19
0
function autocomplete_data($query, $orderCallback)
{
    //Will sort by $orderCallback and then ['name']
    //You may wish to take $user by reference and add ['label'] and ['category'] to it
    //Allows replacement-parameters too.
    $args = func_get_args();
    array_shift($args);
    array_shift($args);
    array_unshift($args, $query);
    $data = call_user_func_array("DB::query", $args);
    $results = array();
    $order = array();
    foreach ($data as &$datum) {
        $order[] = $orderCallback($datum);
        $results[] = $datum;
    }
    uksort($results, function ($ind1, $ind2) use($results, $order) {
        //Sorts with respect to order specified in $order
        if ($order[$ind1] == $order[$ind2]) {
            //Sorts alphabetically within a category
            if (array_key_exists("name", $results[$ind1])) {
                return strcasecmp($results[$ind1]["name"], $results[$ind2]["name"]);
            } else {
                return 0;
            }
        } else {
            //Uses the given ordering numbers to sort categories
            return $order[$ind1] > $order[$ind2] ? 1 : -1;
        }
    });
    return array_values($results);
    //Reassigns keys, since uksort will maintain disordered numerical keys.
}
Пример #20
0
    public function getTagWeights($tags)
    {
        $tagWeights = array();
        if (empty($tags))
            return $tagWeights;

        foreach ($tags as $tag)
        {
            $tagWeights[$tag] = (isset($tagWeights[$tag])) ? $tagWeights[$tag] + 1 : 1;
        }
        // Shuffle the tags
        uksort($tagWeights, function() {
            return rand() > rand();
        });

        $max = max($tagWeights);

        // Max of 5 weights
        $multiplier = ($max > 5) ? 5 / $max : 1;
        foreach ($tagWeights as &$tag)
        {
            $tag = ceil($tag * $multiplier);
        }

        return $tagWeights;
    }
Пример #21
0
	protected function calculateBaseString($method, $url, $parameters) {

		$parameters = is_array($parameters) ? $parameters : array();

		// init var
		$pairs = array();
		$params = array();

		// sort parameters by key
		uksort($parameters, 'strcmp');

		foreach($parameters as $key => $value) {
			// sort by value
			if(is_array($value)) { 
			    $value = natsort($value);
            }

			$params[] = self::urlencode($key) .'='. self::urlencode($value);
		}
		
		// builds base
		$parts = array(
		    strtoupper($method),
		    $url,
		    implode('&', $params)
        );
        
        $parts = self::urlencode($parts);
        $base = implode('&', $parts);
        return $base;
	}
Пример #22
0
    public static function check_license($license)
    {
        $signature = $license['Signature'];
        unset($license['Signature']);
        uksort($license, "strcasecmp");
        $total = '';
        foreach ($license as $value) {
            $total .= $value;
        }
        $key_raw = <<<EOD
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCtl7Dgf4x0fi0lXfws7Cq/lk0d
TIEXnCu8PBMep0mtRia9WEJ8N53d+8gbuAcMzb4sW6MVOzTEKYrmtq/DTbiaXKiJ
o6osz5KgBjbcGrCzKKvk8uQuTZWusqp69LQfTYSwxwJIp45kl0g8yalewGUtpYuu
yWXBBsw7Z909BpTLBQIDAAAD
-----END PUBLIC KEY-----
EOD;
        $key = openssl_get_publickey($key_raw);
        openssl_public_decrypt(base64_decode($signature), $checkDigest, $key);
        $digest = sha1($total, true);
        if ($digest === $checkDigest) {
            return true;
        }
        return false;
    }
Пример #23
0
 protected static function discoverLdapServers($zone)
 {
     $result = array();
     // search for LDAPS servers
     $ldapServers = dns_get_record('_ldaps._tcp.' . $zone, DNS_SRV);
     uksort($ldapServers, array('LdapEnvironment', 'compareDnsRecordPriority'));
     foreach ($ldapServers as $server) {
         $tmp = new stdClass();
         $tmp->hostname = $server['target'];
         $tmp->port = $server['port'];
         $tmp->isSslPort = true;
         $result[] = $tmp;
     }
     // search for non-SSL LDAP servers
     $ldapServers = dns_get_record('_ldap._tcp.' . $zone, DNS_SRV);
     uksort($ldapServers, array('LdapEnvironment', 'compareDnsRecordPriority'));
     foreach ($ldapServers as $server) {
         $tmp = new stdClass();
         $tmp->hostname = $server['target'];
         $tmp->port = $server['port'];
         $tmp->isSslPort = false;
         $result[] = $tmp;
     }
     return $result;
 }
Пример #24
0
function get_browser_local($user_agent = null, $return_array = false, $db = 'browscap.ini', $cache = false)
{
    //http://alexandre.alapetite.fr/doc-alex/php-local-browscap/
    //Get php_browscap.ini on http://browsers.garykeith.com/downloads.asp
    if ($user_agent == null && isset($_SERVER['HTTP_USER_AGENT'])) {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
    }
    global $browscapIni;
    global $browscapPath;
    if (!isset($browscapIni) || !$cache || $browscapPath !== $db) {
        $browscapIni = defined('INI_SCANNER_RAW') ? parse_ini_file($db, true, INI_SCANNER_RAW) : parse_ini_file($db, true);
        $browscapPath = $db;
        uksort($browscapIni, '_sortBrowscap');
        $browscapIni = array_map('_lowerBrowscap', $browscapIni);
    }
    $cap = null;
    foreach ($browscapIni as $key => $value) {
        if ($key != '*' && !array_key_exists('parent', $value)) {
            continue;
        }
        $keyEreg = '^' . str_replace(array('\\', '.', '?', '*', '^', '$', '[', ']', '|', '(', ')', '+', '{', '}', '%'), array('\\\\', '\\.', '.', '.*', '\\^', '\\$', '\\[', '\\]', '\\|', '\\(', '\\)', '\\+', '\\{', '\\}', '\\%'), $key) . '$';
        if (preg_match('%' . $keyEreg . '%i', $user_agent)) {
            $cap = array('browser_name_regex' => strtolower($keyEreg), 'browser_name_pattern' => $key) + $value;
            $maxDeep = 8;
            while (array_key_exists('parent', $value) && array_key_exists($parent = $value['parent'], $browscapIni) && --$maxDeep > 0) {
                $cap += $value = $browscapIni[$parent];
            }
            break;
        }
    }
    if (!$cache) {
        $browscapIni = null;
    }
    return $return_array ? $cap : (object) $cap;
}
Пример #25
0
 function preProcess(Vtiger_Request $request, $display = true)
 {
     parent::preProcess($request, false);
     $viewer = $this->getViewer($request);
     $menuModelsList = Vtiger_Menu_Model::getAll(true);
     $selectedModule = $request->getModule();
     $menuStructure = Vtiger_MenuStructure_Model::getInstanceFromMenuList($menuModelsList, $selectedModule);
     $companyDetails = Vtiger_CompanyDetails_Model::getInstanceById();
     $companyLogo = $companyDetails->getLogo();
     $currentDate = Vtiger_Date_UIType::getDisplayDateValue(date('Y-n-j'));
     $viewer->assign('CURRENTDATE', $currentDate);
     $viewer->assign('MODULE', $selectedModule);
     $viewer->assign('MODULE_NAME', $selectedModule);
     $viewer->assign('QUALIFIED_MODULE', $selectedModule);
     $viewer->assign('PARENT_MODULE', $request->get('parent'));
     $viewer->assign('VIEW', $request->get('view'));
     // Order by pre-defined automation process for QuickCreate.
     uksort($menuModelsList, array('Vtiger_MenuStructure_Model', 'sortMenuItemsByProcess'));
     $viewer->assign('MENUS', $menuModelsList);
     $viewer->assign('MENU_STRUCTURE', $menuStructure);
     $viewer->assign('MENU_SELECTED_MODULENAME', $selectedModule);
     $viewer->assign('MENU_TOPITEMS_LIMIT', $menuStructure->getLimit());
     $viewer->assign('COMPANY_LOGO', $companyLogo);
     $viewer->assign('USER_MODEL', Users_Record_Model::getCurrentUserModel());
     $homeModuleModel = Vtiger_Module_Model::getInstance('Home');
     $viewer->assign('HOME_MODULE_MODEL', $homeModuleModel);
     $viewer->assign('HEADER_LINKS', $this->getHeaderLinks());
     $viewer->assign('ANNOUNCEMENT', $this->getAnnouncement());
     $viewer->assign('SEARCHABLE_MODULES', Vtiger_Module_Model::getSearchableModules());
     if ($display) {
         $this->preProcessDisplay($request);
     }
 }
Пример #26
0
 function prepare_items()
 {
     $iterator = new DirectoryIterator($this->skinsDir);
     $skins = array();
     foreach ($iterator as $item) {
         if (!$item->isDot() and $item->isDir()) {
             $skin = $item->getBasename();
             $neon = $item->getPathname() . "/{$skin}.neon";
             if (file_exists($neon)) {
                 $config = loadConfig($neon);
                 $skins[$skin]['name'] = $config['name'];
                 $skins[$skin]['url'] = "{$this->skinsUrl}/{$skin}";
                 $skins[$skin]['author'] = $config['author'];
                 $skins[$skin]['desc'] = $config['desc'];
                 $skins[$skin]['theme'] = isset($config['theme']) ? $config['theme'] : '';
                 if (file_exists("{$this->skinsDir}/{$skin}/{$skin}-screenshot.png")) {
                     $skins[$skin]['screenshot'] = "{$this->skinsUrl}/{$skin}/{$skin}-screenshot.png";
                 } else {
                     $skins[$skin]['screenshot'] = '';
                 }
             }
         }
     }
     uksort($skins, "strnatcasecmp");
     $per_page = 15;
     $page = $this->get_pagenum();
     $start = ($page - 1) * $per_page;
     $this->items = array_slice($skins, $start, $per_page);
     $this->set_pagination_args(array('total_items' => count($skins), 'per_page' => $per_page));
 }
Пример #27
0
 /**
 * Groups all URLs by host, path and idsite.
 *
 * @param array $urls  An array containing URLs by idsite,
 *                     eg array(array($idSite = 1 => array('apache.piwik', 'apache2.piwik'), 2 => array(), ...))
 *                     as returned by {@link getAllCachedSiteUrls()} and {@link getAllSiteUrls}
 * @return array All urls grouped by host => path => idSites. Path having the most '/' will be listed first
 * array(
     'apache.piwik' => array(
         '/test/two' => $idsite = array(3),
         '/test' => $idsite = array(1),
         '/' => $idsite = array(2),
     ),
     'test.apache.piwik' => array(
         '/test/two' => $idsite = array(3),
         '/test' => $idsite = array(1),
         '/' => $idsite = array(2, 3),
     ),
   );
 */
 public function groupUrlsByHost($siteUrls)
 {
     if (empty($siteUrls)) {
         return array();
     }
     $allUrls = array();
     foreach ($siteUrls as $idSite => $urls) {
         $idSite = (int) $idSite;
         foreach ($urls as $url) {
             $urlParsed = @parse_url($url);
             if ($urlParsed === false || !isset($urlParsed['host'])) {
                 continue;
             }
             $host = $this->toCanonicalHost($urlParsed['host']);
             $path = $this->getCanonicalPathFromParsedUrl($urlParsed);
             if (!isset($allUrls[$host])) {
                 $allUrls[$host] = array();
             }
             if (!isset($allUrls[$host][$path])) {
                 $allUrls[$host][$path] = array();
             }
             if (!in_array($idSite, $allUrls[$host][$path])) {
                 $allUrls[$host][$path][] = $idSite;
             }
         }
     }
     foreach ($allUrls as $host => $paths) {
         uksort($paths, array($this, 'sortByPathDepth'));
         $allUrls[$host] = $paths;
     }
     return $allUrls;
 }
Пример #28
0
function s_http_boundary(&$params, &$header)
{
    if (!is_array($params)) {
        $params = array();
    }
    if (!is_array($header)) {
        $header = array();
    }
    uksort($params, 'strcmp');
    $body = '';
    $boundary = uniqid('------------------');
    foreach ($params as $key => $value) {
        if (in_array($key, array('pic', 'image')) && $value[0] == '@') {
            $content = file_get_contents(ltrim($value, '@'));
            $body .= '--' . $boundary . "\r\n";
            $body .= 'Content-Disposition: form-data; name="' . $key . '"; filename="' . basename($value) . '"' . "\r\n";
            $body .= "Content-Type: image/unknown\r\n\r\n";
            $body .= $content . "\r\n";
        } else {
            $body .= '--' . $boundary . "\r\n";
            $body .= 'content-disposition: form-data; name="' . $key . "\"\r\n\r\n";
            $body .= $value . "\r\n";
        }
    }
    //end
    $body .= '--' . $boundary . '--';
    $header[] = "Content-Type: multipart/form-data; boundary={$boundary}";
    return $body;
}
Пример #29
0
 /**
  * Get our comparison data by scanning our comparison directory
  * @return array
  */
 public function toJson()
 {
     // Add our current directory pointer to the array (can't be done in property definition)
     array_unshift($this->comparisonDir, dirname(__FILE__));
     // Try to do this platform independent
     $comparisonDir = implode(DIRECTORY_SEPARATOR, $this->comparisonDir);
     if (!count($this->comparisonCache)) {
         // Iterate our directory looking for comparison classes
         foreach (new DirectoryIterator($comparisonDir) as $file) {
             // Skip sub-dirs and dot files
             if ($file->isDir() || $file->isDot()) {
                 continue;
             }
             $fileName = $file->getFilename();
             $className = str_replace('.php', '', $fileName);
             $reflectClass = new ReflectionClass('\\Verdict\\Filter\\Comparison\\' . $className);
             // Skip interfaces and abstracts
             if (!$reflectClass->isInstantiable() || !$reflectClass->implementsInterface('\\Verdict\\Filter\\Comparison\\ComparisonInterface') || $className === 'Truth') {
                 continue;
             }
             $reflectMethod = $reflectClass->getMethod('getDisplay');
             $this->comparisonCache[lcfirst($className)] = $reflectMethod->invoke(null);
         }
         // First, lowercase our sort order array
         $sortOrder = array_map('lcfirst', $this->sortOrder);
         // Next, sort our keys based on their position inside our sort order array
         uksort($this->comparisonCache, function ($a, $b) use($sortOrder) {
             return array_search($a, $sortOrder) - array_search($b, $sortOrder);
         });
     }
     return $this->comparisonCache;
 }
Пример #30
0
 public static function htmlAttributes(array $attributes, array $sort_order = null)
 {
     // Optionally sort attributes (for better readability).
     if ($sort_order) {
         uksort($attributes, function ($a, $b) use($sort_order) {
             $a_index = array_search($a, $sort_order);
             $b_index = array_search($b, $sort_order);
             $a_found = is_int($a_index);
             $b_found = is_int($b_index);
             if ($a_found && $b_found) {
                 if ($a_index == $b_index) {
                     return 0;
                 }
                 return $a_index > $b_index ? 1 : -1;
             } elseif ($a_found && !$b_found) {
                 return -1;
             } elseif ($b_found && !$a_found) {
                 return 1;
             }
             return strcmp($a, $b);
         });
     }
     $str = '';
     foreach ($attributes as $name => $value) {
         $value = htmlspecialchars($value, ENT_COMPAT, 'UTF-8', false);
         $str .= " {$name}=\"{$value}\"";
     }
     return $str;
 }