Example #1
1
 /**
  * Execute requested action
  */
 public function execute()
 {
     $method = $_SERVER['REQUEST_METHOD'];
     $verbs = $this->verbs();
     if (isset($verbs[$this->requestMethod])) {
         $action = 'action' . ucfirst(mb_strtolower($verbs[$method]));
         $reflectionMethod = new \ReflectionMethod($this, $action);
         $parsePath = array_slice($this->path, count($this->route));
         $args = [];
         $errors = [];
         if ($params = $reflectionMethod->getParameters()) {
             foreach ($params as $key => $param) {
                 if (isset($parsePath[$key])) {
                     $args[$param->name] = $parsePath[$key];
                 } else {
                     $errors[] = ['code' => 'required', 'message' => ucfirst(mb_strtolower(explode('_', $param->name)[0])) . ' cannot be blank.', 'name' => $param->name];
                 }
             }
             if ($errors) {
                 throw new \phantomd\ShopCart\modules\base\HttpException(400, 'Invalid data parameters', 0, null, $errors);
             }
         }
         if (count($parsePath) === count($params)) {
             return call_user_func_array([$this, $action], $args);
         }
     }
     throw new HttpException(404, 'Unable to resolve the request "' . $this->requestPath . '".', 0, null, $errors);
 }
Example #2
0
 /**
  * Build required method if it's in the configuration
  *
  * @param string $method
  * @param array $args
  * @return Route
  */
 public function __call($method, $args)
 {
     // See if we can find the method being referenced
     $called = str_replace('apiresource', '', mb_strtolower($method));
     // Check if this function is in our configuration
     if ($this->config->get('apirouter::router.' . $called)) {
         // Capture config
         $config = $this->config->get('apirouter::router.' . $called);
         // Determine whether to use id or not
         $uri = $this->getResourceUri($args[0]);
         if (isset($config['id']) && $config['id'] == true) {
             $uri .= '/{' . ($args[1] ? $args[1] : 'id') . '}';
         }
         if (isset($config['suffix']) && $config['suffix']) {
             $uri .= '/' . $config['suffix'];
         }
         // Determine the function name
         $function = isset($config['function']) && $config['function'] ? $config['function'] : $called;
         // Get action
         $action = $this->getResourceAction($args[0], $args[2], $called, $args[3], $function);
         // Get method
         $method = isset($config['method']) && $config['method'] ? $config['method'] : 'get';
         // Put it all together
         return $this->{$method}($uri, $action);
     }
 }
 public function __construct($text)
 {
     $this->text = $text;
     $text = (string) $text;
     // преобразуем в строковое значение
     $text = strip_tags($text);
     // убираем HTML-теги
     $text = str_replace(array("\n", "\r"), " ", $text);
     // убираем перевод каретки
     $text = preg_replace("/\\s+/", ' ', $text);
     // удаляем повторяющие пробелы
     $text = trim($text);
     // убираем пробелы в начале и конце строки
     $text = mb_strtolower($text, 'utf-8');
     // переводим строку в нижний регистр
     $text = strtr($text, array('а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'e', 'ж' => 'j', 'з' => 'z', 'и' => 'y', 'і' => 'i', 'ї' => 'і', 'й' => 'y', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c', 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'shch', 'ы' => 'y', 'э' => 'e', 'ю' => 'yu', 'я' => 'ya', 'ъ' => '', 'ь' => ''));
     // в данном случае язык
     //будет укр.(изначально скрипт для русского яз.) поэтому некоторые буквы заменены или удалены, а именно ('и'=>'i')
     $text = preg_replace("/[^0-9a-z-_ ]/i", "", $text);
     // очищаем строку от недопустимых символов
     $text = str_replace(" ", "_", $text);
     // заменяем пробелы нижним подчеркиванием
     $text = str_replace("-", "_", $text);
     //заменяет минус на нижнее подчеркивание
     $this->translit = $text;
 }
Example #4
0
 public function getAttributesByAttributeGroupId($data = array())
 {
     $sql = "SELECT *, (SELECT agd.name FROM " . DB_PREFIX . "attribute_group_description agd WHERE agd.attribute_group_id = a.attribute_group_id AND agd.language_id = '" . (int) $this->config->get('config_language_id') . "') AS attribute_group FROM " . DB_PREFIX . "attribute a LEFT JOIN " . DB_PREFIX . "attribute_description ad ON (a.attribute_id = ad.attribute_id) WHERE ad.language_id = '" . (int) $this->config->get('config_language_id') . "'";
     if (isset($data['filter_name']) && !is_null($data['filter_name'])) {
         $sql .= " AND LCASE(ad.name) LIKE '" . $this->db->escape(mb_strtolower($data['filter_name'], 'UTF-8')) . "%'";
     }
     if (isset($data['filter_attribute_group_id']) && !is_null($data['filter_attribute_group_id'])) {
         $sql .= " AND a.attribute_group_id = '" . $this->db->escape($data['filter_attribute_group_id']) . "'";
     }
     $sort_data = array('ad.name', 'attribute_group', 'a.sort_order');
     if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
         $sql .= " ORDER BY " . $data['sort'];
     } else {
         $sql .= " ORDER BY ad.name";
     }
     if (isset($data['order']) && $data['order'] == 'DESC') {
         $sql .= " DESC";
     } else {
         $sql .= " ASC";
     }
     if (isset($data['start']) || isset($data['limit'])) {
         if ($data['start'] < 0) {
             $data['start'] = 0;
         }
         if ($data['limit'] < 1) {
             $data['limit'] = 20;
         }
         $sql .= " LIMIT " . (int) $data['start'] . "," . (int) $data['limit'];
     }
     $query = $this->db->query($sql);
     return $query->rows;
 }
Example #5
0
 function save(&$data)
 {
     $isNew = Sanitize::getInt($data['FieldOption'], 'optionid') ? false : true;
     $field_id = Sanitize::getInt($data['FieldOption'], 'fieldid');
     if ($isNew) {
         // Remove non alphanumeric characters from option value
         $data['FieldOption']['value'] = Sanitize::translate($data['FieldOption']['value']);
         $data['FieldOption']['value'] = str_replace($this->blackList, '', $data['FieldOption']['value']);
         $data['FieldOption']['value'] = str_replace($this->dashReplacements, '-', $data['FieldOption']['value']);
         $data['FieldOption']['value'] = preg_replace(array('/[-]+/'), array('-'), $data['FieldOption']['value']);
         $data['FieldOption']['value'] = mb_strtolower($data['FieldOption']['value'], 'UTF-8');
         // If is new checks for duplicate value
         $query = "SELECT count(fieldid) FROM #__jreviews_fieldoptions WHERE fieldid = '{$field_id}' AND value = " . $this->_db->Quote($data['FieldOption']['value']);
         $this->_db->setQuery($query);
         if ($this->_db->loadResult()) {
             return 'duplicate';
         }
         // Find last option
         $this->_db->setQuery("select max(ordering) FROM #__jreviews_fieldoptions WHERE fieldid = '" . $field_id . "'");
         $max = $this->_db->loadResult();
         if ($max > 0) {
             $data['FieldOption']['ordering'] = $max + 1;
         } else {
             $data['FieldOption']['ordering'] = 1;
         }
     }
     # store it in the db
     if (!$this->store($data)) {
         return 'db_error';
     }
     return 'success';
 }
 /**
  * @see	\wcf\system\option\IOptionType::getData()
  */
 public function getData(Option $option, $newValue)
 {
     $number = str_replace(WCF::getLanguage()->get('wcf.global.thousandsSeparator'), '', $newValue);
     $number = str_replace(WCF::getLanguage()->get('wcf.global.decimalPoint'), '.', $number);
     if (!preg_match('~^(?:\\d*)\\.?\\d+~', $number, $matches)) {
         return 0;
     }
     $number = $matches[0];
     if (preg_match('/[kmgt]i?b$/i', $newValue, $multiplier)) {
         switch (mb_strtolower($multiplier[0])) {
             case 'tb':
                 $number *= 1000;
             case 'gb':
                 $number *= 1000;
             case 'mb':
                 $number *= 1000;
             case 'kb':
                 $number *= 1000;
                 break;
             case 'tib':
                 $number *= 1024;
             case 'gib':
                 $number *= 1024;
             case 'mib':
                 $number *= 1024;
             case 'kib':
                 $number *= 1024;
                 break;
         }
     }
     return $number;
 }
Example #7
0
 public function Start($string, $language, $count, $F)
 {
     $snippets = array();
     $query = urlencode(mb_strtolower($string, 'UTF-8'));
     $url = "http://www.mysearch.com/search/GGmain.jhtml?searchfor={$query}&lr=lang_{$language}&ie=utf-8&oe=utf-8";
     $html = $F->GetHTML($url, 'www.mysearch.com');
     if (!is_bool($html)) {
         $i = 0;
         foreach ($html->find('div[class="algoLinkBox"]') as $e) {
             $t = 'a[class="pseudolink"]';
             $d = 'span[class="nDesc"]';
             if (isset($e->find($t, 0)->plaintext)) {
                 $title = $e->find($t, 0)->plaintext;
             }
             if (isset($e->find($d, 0)->plaintext)) {
                 $description = $e->find($d, 0)->plaintext;
             }
             if ($i < $count) {
                 if (!empty($title) and !empty($description)) {
                     $snippets[$i]['title'] = trim($title);
                     $snippets[$i]['description'] = trim($description);
                     $i++;
                 }
             }
         }
         $html->clear();
         $html = null;
         $e = null;
         unset($html, $e);
     } else {
         $F->Error("Can't create outgoing request. Please check MySearch snippets plugin.");
     }
     return $snippets;
 }
Example #8
0
 /**
  * Create a version of a string for embedding in a URL
  *
  * @param string $string    A UTF-8 string
  * @param string $separator The character to separate words with
  * @return string
  */
 public static function urlize($string, $separator = '-')
 {
     // Iñtërnâtiônàlizætiøn, AND 日本語!
     // try to force combined chars because the translit map and others expect it
     if (self::hasNormalizerSupport()) {
         $nfc = normalizer_normalize($string);
         if (is_string($nfc)) {
             $string = $nfc;
         }
     }
     // Internationalization, AND 日本語!
     $string = self::transliterateAscii($string);
     // allow HTML tags in titles
     $string = preg_replace('~<([a-zA-Z][^>]*)>~', ' $1 ', $string);
     // more substitutions
     // @todo put these somewhere else
     $string = strtr($string, array("€" => ' E ', "£" => ' GBP '));
     // remove all ASCII except 0-9a-zA-Z, hyphen, underscore, and whitespace
     // note: "x" modifier did not work with this pattern.
     $string = preg_replace('~[' . '\\x00-\\x08' . '\\x0b\\x0c' . '\\x0e-\\x1f' . '\\x21-\\x2c' . '\\x2e\\x2f' . '\\x3a-\\x40' . '\\x5b-\\x5e' . '\\x60' . '\\x7b-\\x7f' . ']~', '', $string);
     $string = strtr($string, '', '');
     // internationalization, and 日本語!
     // note: not using elgg_strtolower to keep this class portable
     $string = is_callable('mb_strtolower') ? mb_strtolower($string, 'UTF-8') : strtolower($string);
     // split by ASCII chars not in 0-9a-zA-Z
     // note: we cannot use [^0-9a-zA-Z] because that matches multibyte chars.
     // note: "x" modifier did not work with this pattern.
     $pattern = '~[' . '\\x00-\\x2f' . '\\x3a-\\x40' . '\\x5b-\\x60' . '\\x7b-\\x7f' . ']+~x';
     // ['internationalization', 'and', '日本語']
     $words = preg_split($pattern, $string, -1, PREG_SPLIT_NO_EMPTY);
     // ['internationalization', 'and', '%E6%97%A5%E6%9C%AC%E8%AA%9E']
     $words = array_map('urlencode', $words);
     // internationalization-and-%E6%97%A5%E6%9C%AC%E8%AA%9E
     return implode($separator, $words);
 }
Example #9
0
 public function aliasOrSlug($title)
 {
     $seo_st = str_replace(' ', '-', $title);
     $seo_alm = str_replace('--', '-', $seo_st);
     $title_seo = str_replace(' ', '', $seo_alm);
     return mb_strtolower($title_seo, 'UTF-8');
 }
 function post_xhr()
 {
     if ($this->checkAuth()) {
         $usernameOrEmail = mb_strtolower($_POST['usernameOrEmail']);
         if (mb_strlen($usernameOrEmail) >= 8 && preg_match('/^[a-zA-Z0-9_\\-]+$/', $usernameOrEmail) || filter_var($usernameOrEmail, FILTER_VALIDATE_EMAIL)) {
             $secondFactor = mb_strtolower($_POST['secondFactor']);
             if (ctype_alnum($secondFactor) || empty($secondFactor)) {
                 $answer = mb_strtolower($_POST['answer']);
                 if (mb_strlen($answer) >= 6 || empty($answer)) {
                     $newPassword = $_POST['passwordForgot'];
                     $newRetypedPassword = $_POST['passwordRetypedForgot'];
                     if ($newPassword == $newRetypedPassword) {
                         $userForgot = new AuthUser();
                         $responseArr = $userForgot->forgotPassword($usernameOrEmail, $secondFactor, $answer, $newPassword);
                         if ($responseArr['continue'] == true) {
                             echo json_encode(StatusReturn::S200($responseArr));
                         } else {
                             echo json_encode(StatusReturn::E400('Unknown Error 5'));
                         }
                     } else {
                         echo json_encode(StatusReturn::E400('Unknown Error 4'));
                     }
                 } else {
                     echo json_encode(StatusReturn::E400('Unknown Error'));
                 }
             } else {
                 echo json_encode(StatusReturn::E400('Unknown Error'));
             }
         } else {
             echo json_encode(StatusReturn::E400('Unknown Error'));
         }
     }
 }
Example #11
0
File: RU.php Project: techart/tao
 /**
  * Возвращает основу слова
  *
  * @param string $word
  *
  * @return string
  */
 public function stem_word($word)
 {
     $word = strtr(mb_strtolower($word), array('ё' => 'е'));
     if ($this->use_cache && isset($this->cache[$word])) {
         return $this->cache[$word];
     }
     list($str, $start, $rv) = Core_Regexps::match_with_results(self::RVRE, $word);
     if (!$rv) {
         return $word;
     }
     // step 1
     if (!Core_Regexps::replace_ref(self::PERFECTIVEGROUND, '', $rv)) {
         $rv = preg_replace(self::REFLEXIVE, '', $rv);
         if (Core_Regexps::replace_ref(self::ADJECTIVE, '', $rv)) {
             $rv = preg_replace(self::PARTICIPLE, '', $rv);
         } else {
             if (!Core_Regexps::replace_ref(self::VERB, '', $rv)) {
                 $rv = preg_replace(self::NOUN, '', $rv);
             }
         }
     }
     // step 2
     $rv = preg_replace('{и$}', '', $rv);
     // step 3
     if (preg_match(self::DERIVATIONAL, $rv)) {
         $rv = preg_replace('{ость?$}', '', $rv);
     }
     // step 4
     if (!Core_Regexps::replace_ref('{ь$}', '', $rv)) {
         $rv = preg_replace(array('{ейше?}', '{нн$}'), array('', 'н'), $rv);
     }
     return $this->use_cache ? $this->cache[$word] = $start . $rv : $start . $rv;
 }
Example #12
0
 /**
  * @param string $fieldName
  * @param FieldDefinition $type
  * @throws InvalidArgumentException
  */
 private function addFieldDefinition(string $fieldName, FieldDefinition $type)
 {
     if (array_key_exists(mb_strtolower($fieldName), $this->definitions)) {
         throw InvalidArgumentException::fieldNameAlreadyExists($fieldName, $this->name);
     }
     $this->definitions[mb_strtolower($fieldName)] = $type;
 }
Example #13
0
	function parse_array ($items, $default = 'Проставьте_теги') {

		if (empty($items)) {
			return array($default);
		}

		if (!is_array($items)) {
			return $this->parse($items);
		}

		$tags = array_unique(array_filter($items));

		foreach ($tags as $key => $tag) {
			$tag = str_replace(array('&amp;'), array('&'), $tag);

			if (preg_match('/(^(:?&lt;|<)\p{L}+(?:&gt;|>)|(?:&lt;|<)\p{L}+(?:&gt;|>)$)/u',$tag,$type)) {
				$tags[$key] = str_replace($type[0],'',$tag);

				$color_key = mb_strtolower(substr($type[0],4,-4),'UTF-8');
				if (isset($this->tag_types[$color_key])) {
					$this->colors[$tags[$key]] = $this->tag_types[$color_key];
				}
			}
		}
		return $tags;
	}
Example #14
0
/**
 * Override this to validate the username in your own way.
 */
function Users_validate_username($params)
{
    // override this to change the rules for validating the username
    extract($params);
    if (empty($username)) {
        return;
    }
    if ($first = mb_substr($username, 0, 1, "UTF-8") and mb_strtolower($first, "UTF-8") != $first) {
        return;
        // first letter is uppercase, this represents an organization
    }
    if (strlen($username) < 4) {
        throw new Q_Exception("usernames are at least 4 characters long", array('username'));
    }
    if (strlen($username) > 16) {
        throw new Q_Exception("usernames are at most 16 characters long", array('username'));
    }
    $match = preg_match('/^[a-zA-Z][a-zA-Z0-9-_]+$/', $username);
    if (!$match) {
        if (preg_match('/^[a-zA-Z0-9-_]+$/', $username)) {
            throw new Q_Exception("usernames must start with a letter", array('username'));
        }
        throw new Q_Exception("please use only A..Z, a..z, 0..9, - and _", array('username'));
    }
}
Example #15
0
 /**
  * Validar::__construct()
  * 
  * Genera las variables correspondientes
  * que se requieren para el proceso de
  * validacion
  * 
  * @param string $namespace
  * @param objetc $peticiones
  * @return void
  */
 function __construct($confgClase = false, $confgMetodo = false, $peticiones = false)
 {
     $this->confgClase = $confgClase;
     $this->confgMetodo = $confgMetodo;
     $this->peticiones = $peticiones;
     $this->metodoPeticion = mb_strtolower($this->confgClase->formulario->metodo);
 }
Example #16
0
/**
 * Returns the html for plugin Tab.
 *
 * @param Array $plugins list
 *
 * @return string
 */
function PMA_getPluginTab($plugins)
{
    $html = '<div id="plugins_plugins">';
    $html .= '<div id="sectionlinks">';
    foreach ($plugins as $plugin_type => $plugin_list) {
        $key = 'plugins-' . preg_replace('/[^a-z]/', '', mb_strtolower($plugin_type));
        $html .= '<a href="#' . $key . '">' . htmlspecialchars($plugin_type) . '</a>' . "\n";
    }
    $html .= '</div>';
    $html .= '<br />';
    foreach ($plugins as $plugin_type => $plugin_list) {
        $key = 'plugins-' . preg_replace('/[^a-z]/', '', mb_strtolower($plugin_type));
        sort($plugin_list);
        $html .= '<table class="data_full_width" id="' . $key . '">';
        $html .= '<caption class="tblHeaders">';
        $html .= htmlspecialchars($plugin_type);
        $html .= '</caption>';
        $html .= '<thead>';
        $html .= '<tr>';
        $html .= '<th>' . __('Plugin') . '</th>';
        $html .= '<th>' . __('Description') . '</th>';
        $html .= '<th>' . __('Version') . '</th>';
        $html .= '<th>' . __('Author') . '</th>';
        $html .= '<th>' . __('License') . '</th>';
        $html .= '</tr>';
        $html .= '</thead>';
        $html .= '<tbody>';
        $html .= PMA_getPluginList($plugin_list);
        $html .= '</tbody>';
        $html .= '</table>';
    }
    $html .= '</div>';
    return $html;
}
Example #17
0
 /**
  * Generate a variable name for a given object. 
  * 
  * 
  * * If $value is an object, the generated variable name
  * will be [$object-class-short-name]_$occurence in lower case e.g. 'point_0',
  * 'assessmenttest_3', ... 
  * 
  * * If $value is a PHP scalar value (not including the null value), the generated
  * variable name will be [gettype($value)]_$occurence e.g. 'string_1', 'boolean_0', ...
  * 
  * * If $value is an array, the generated variable name will be array_$occurence such as
  * 'array_0', 'array_2', ...
  * 
  * * If $value is the null value, the generated variable name will be nullvalue_$occurence
  * such as 'nullvalue_3'.
  * 
  * * Finally, if the $value cannot be handled by this method, an InvalidArgumentException
  * is thrown.
  * 
  * @param mixed $value A value.
  * @param integer $occurence An occurence number.
  * @return string A variable name.
  * @throws InvalidArgumentException If $occurence is not a positive integer or if $value cannot be handled by this method.
  */
 public static function variableName($value, $occurence = 0)
 {
     if (is_int($occurence) === false || $occurence < 0) {
         $msg = "The 'occurence' argument must be a positive integer (>= 0).";
         throw new InvalidArgumentException($msg);
     }
     if (is_object($value) === true) {
         $object = new ReflectionObject($value);
         $className = mb_strtolower($object->getShortName(), 'UTF-8');
         return "{$className}_{$occurence}";
     } else {
         // Is it a PHP scalar value?
         if (is_scalar($value) === true) {
             return gettype($value) . '_' . $occurence;
         } else {
             if (is_array($value) === true) {
                 return 'array_' . $occurence;
             } else {
                 if (is_null($value) === true) {
                     return 'nullvalue_' . $occurence;
                 } else {
                     $msg = "Cannot handle the given value.";
                     throw new InvalidArgumentException($msg);
                 }
             }
         }
     }
 }
Example #18
0
 public static function generateClass()
 {
     //
     $cwd = getcwd();
     // TODO: model_namespace_for_path may have leading '/' - remove it?
     $model_filename = $cwd . DIRECTORY_SEPARATOR . self::$model_namespace_for_path . DIRECTORY_SEPARATOR . self::$model_class_name . '.php';
     $model_tablename = mb_strtolower(self::$model_namespace_for_class . "\\" . self::$model_class_name);
     $model_tablename = preg_replace('@\\W@', '_', $model_tablename);
     //
     // creating model class file
     //
     $class_file = self::getClassTemplate();
     // TODO: use common variable replacemnt method
     $class_file = str_replace('TEMPLATECLASS_CLASSNAME', self::$model_class_name, $class_file);
     $class_file = str_replace('TEMPLATECLASS_NAMESPACE', self::$model_namespace_for_class, $class_file);
     $class_file = str_replace('TEMPLATECLASS_TABLENAME', $model_tablename, $class_file);
     $class_file = str_replace('TEMPLATECLASS_DBID', self::$model_db_id, $class_file);
     self::file_force_contents($model_filename, $class_file);
     echo "\nModel file created: " . $model_filename . "\n";
     //
     // altering database sql file
     //
     $class_sql = self::getClassSQL();
     // TODO: use common variable replacemnt method
     $class_sql = str_replace('TEMPLATECLASS_TABLENAME', $model_tablename, $class_sql);
     CLIExecuteSql::addSqlToRegistry(self::$model_db_id, $class_sql);
     echo "\nSQL registry updated\n";
     echo "\nType ENTER to execute SQL queries, Ctrl+C to exit.\n";
     $command_str = CliUtil::readStdinAnswer();
     if ($command_str == '') {
         CLIExecuteSql::executeSqlScreen();
     }
     return;
 }
Example #19
0
 public function Start($string, $language, $count, $F)
 {
     $snippets = array();
     $query = urlencode(mb_strtolower($string, 'UTF-8'));
     $url = "http://www.nigma.ru/?s={$query}&lang={$language}&ie=utf-8&oe=utf-8";
     $html = $F->GetHTML($url, 'www.nigma.ru');
     if (!is_bool($html)) {
         $i = 0;
         foreach ($html->find('div[id="results"] ol li') as $e) {
             $t = 'div[class="snippet_title"] a';
             $d = 'div[class="snippet_text"]';
             if (isset($e->find($t, 0)->plaintext)) {
                 $title = $e->find($t, 0)->plaintext;
             }
             if (isset($e->find($d, 0)->plaintext)) {
                 $description = $e->find($d, 0)->plaintext;
             }
             if ($i < $count) {
                 if (!empty($title) and !empty($description)) {
                     $snippets[$i]['title'] = trim($title);
                     $snippets[$i]['description'] = trim($description);
                     $i++;
                 }
             }
         }
         $html->clear();
         $html = null;
         $e = null;
         unset($html, $e);
     } else {
         $F->Error("Can't create outgoing request. Please check Nigma snippets plugin.");
     }
     return $snippets;
 }
 /**
  * @param string $string
  *
  * @return string
  */
 public function transform($string)
 {
     $string = preg_replace('/[^\\p{L&}\\p{Lo}\\d]/u', $this->replacement, $string);
     $string = preg_replace('/[' . preg_quote($this->replacement) . ']+/u', $this->replacement, $string);
     $string = trim($string, $this->replacement);
     return $this->lowercase ? mb_strtolower($string) : $string;
 }
 /**
  * Sets an attribute.
  *
  * @param string $key
  * @param mixed  $value
  *
  * @return bool
  */
 protected function setAttribute($key, $value)
 {
     $timezone = new DateTimeZone('UTC');
     switch (mb_strtolower($key)) {
         case 'compression lossless':
             $this->lossless = $value == 'true';
             break;
         case 'compression':
             $this->lossless = $value == 'Uncompressed';
             break;
         case 'height':
         case 'image height':
         case 'tiff:imageheigth':
         case 'tiff:imagelength':
             $this->height = (int) $value;
             break;
         case 'width':
         case 'image width':
         case 'tiff:imagewidth':
             $this->width = (int) $value;
             break;
         default:
             return false;
     }
     return true;
 }
Example #22
0
/**
 * This smarty function is part of "Koch Framework".
 *
 * Name:         messagebox
 * Type:         function
 * Purpose:     This TAG inserts a formatted messagebox (hint, notice, alert).
 *
 * @return string HTML of a messagebox.
 */
function Smarty_block_messagebox($params, $text, $smarty)
{
    $text = stripslashes($text);
    $textbox_type = null;
    $textbox_level = null;
    // set default type of messagebox to "div", if no type was given
    if (empty($params['type']) === true) {
        $textbox_type = 'div';
    } else {
        $textbox_type = $params['type'];
    }
    // whitelist for messagebox levels
    $messagebox_level = ['hint', 'notice', 'alert', 'info'];
    if ($params['level'] !== null and in_array(mb_strtolower($params['level']), $messagebox_level, true)) {
        $textbox_level = mb_strtolower($params['level']);
    } else {
        return trigger_error('Please define a parameter level, e.g. hint, notice, alert, info.');
    }
    $tpl_vars = $smarty->getTemplateVars();
    $sprintfTextboxMessage = '<link rel="stylesheet" type="text/css"' . ' href="' . $tpl_vars['WWW_ROOT_THEMES_CORE'] . 'css/error.css" />';
    switch ($textbox_type) {
        default:
        case 'div':
            $textbox_type = 'div';
            $sprintfTextboxMessage .= '<div class="messagebox %2$s">%3$s</div>';
            break;
        case 'fieldset':
            $sprintfTextboxMessage .= '<fieldset class="error_help %s"><legend>%s</legend><em>%s</em></fieldset>';
            break;
    }
    return sprintf($sprintfTextboxMessage, $textbox_type, $textbox_level, $text);
}
Example #23
0
 private static function toTitleCase($str)
 {
     if (mb_strlen($str) === 0) {
         return $str;
     }
     return mb_strtoupper(mb_substr($str, 0, 1)) . mb_strtolower(mb_substr($str, 1));
 }
Example #24
0
 /**
  * Defined by Zend\Filter\FilterInterface
  *
  * Returns the string $value, converting characters to lowercase as necessary
  *
  * @param  string $value
  * @return string
  */
 public function filter($value)
 {
     if ($this->options['encoding'] !== null) {
         return mb_strtolower((string) $value, $this->options['encoding']);
     }
     return strtolower((string) $value);
 }
 private function _genericReplacements()
 {
     $this->_doc_content = strip_tags($this->_doc_content);
     $this->_doc_content = ltrim(rtrim($this->_doc_content));
     $this->_doc_content = mb_strtolower($this->_doc_content, $this->_charset);
     // Remove dots between chars (for things like urls)
     $this->_doc_content = $this->_my_preg_replace("/([a-z]{1})[\\.]+([a-z]{1})/", "\$1\$2", $this->_doc_content);
     // ? Remove all html entities
     // $this->_doc_content = $this->_my_preg_replace("/&[#|a-z|0-9]+;/", " ", $this->_doc_content);
     // Decode all html entities
     $this->_doc_content = html_entity_decode($this->_doc_content, ENT_COMPAT, $this->_charset);
     // Replace multiple spaces chars with just one space
     $this->_doc_content = $this->_my_preg_replace("/[\\s|\t|\n|\r]+/", " ", $this->_doc_content);
     // Remove dots, dashes and spaces between digits
     $this->_doc_content = $this->_my_preg_replace("/([0-9]{1})[\\.|\\s|\\-]+([0-9]{1})/", "\$1\$2", $this->_doc_content);
     // Remove spaces after sentences and replace multiple dots with just one dot
     $this->_doc_content = $this->_my_preg_replace("/[\\.]+ /", ".", $this->_doc_content);
     // The same for sentences ending with question marks
     $this->_doc_content = $this->_my_preg_replace("/[\\?]+ /", ".", $this->_doc_content);
     // The same for "!"
     $this->_doc_content = $this->_my_preg_replace("/[\\!]+ /", ".", $this->_doc_content);
     // Remove all non-alphanumeric characters except for spaces and dots
     //        $this->_doc_content = $this->_my_preg_replace("/[^a-z|&#1072;-&#1103;|^\.|^\d|^\s|^@]+/i", "", $this->_doc_content);
     return $this;
 }
Example #26
0
 /**
  * Magick get properties
  *
  * @param string $name
  * @return mixed
  */
 public function __get($name)
 {
     $method = 'get' . ucfirst(mb_strtolower($name));
     if (method_exists($this, $method)) {
         return call_user_func([$this, $method]);
     }
 }
/**
 * Converts a title into an alias
 *
 * @param string $title Title
 * @param int $id Page ID
 * @param bool $duplicate TRUE if duplicate alias was previously detected
 * @return string
 */
function autoalias2_convert($title, $id = 0, $duplicate = false)
{
    global $cfg, $cot_translit, $cot_translit_custom;
    if ($cfg['plugin']['autoalias2']['translit'] && file_exists(cot_langfile('translit', 'core'))) {
        include cot_langfile('translit', 'core');
        if (is_array($cot_translit_custom)) {
            $title = strtr($title, $cot_translit_custom);
        } elseif (is_array($cot_translit)) {
            $title = strtr($title, $cot_translit);
        }
    }
    $title = preg_replace('#[^\\p{L}0-9\\-_ ]#u', '', $title);
    $title = str_replace(' ', $cfg['plugin']['autoalias2']['sep'], $title);
    if ($cfg['plugin']['autoalias2']['lowercase']) {
        $title = mb_strtolower($title);
    }
    if ($cfg['plugin']['autoalias2']['prepend_id'] && !empty($id)) {
        $title = $id . $cfg['plugin']['autoalias2']['sep'] . $title;
    } elseif ($duplicate) {
        switch ($cfg['plugin']['autoalias2']['on_duplicate']) {
            case 'ID':
                if (!empty($id)) {
                    $title .= $cfg['plugin']['autoalias2']['sep'] . $id;
                    break;
                }
            default:
                $title .= $cfg['plugin']['autoalias2']['sep'] . rand(2, 99);
                break;
        }
    }
    return $title;
}
Example #28
0
 public function applyCoupon($coupon, $item = [], $global = false)
 {
     if (!empty($coupon) && ((int) $coupon <= 100 && (int) $coupon >= 0)) {
         if (!$global) {
             if (!empty($item)) {
                 if (array_key_exists(mb_strtolower($item), $this->products)) {
                     $percentDiscount = $coupon / 100;
                     $discount = 1;
                     $discount = $discount - $percentDiscount;
                     $this->products[mb_strtolower($item)]['price'] *= $discount;
                     $item['discount'] = 100 - $discount * 100;
                 } else {
                     throw new \Exception('No such item in cart.');
                 }
             } else {
                 throw new \Exception("Item cannot be empty when not applying a global discount.", 995);
             }
         } else {
             // This is a global coupon for every product
             $this->modifier = $this->modifier - $coupon / 100;
             foreach ($this->products['items'] as $key => $item) {
                 $item['price'] *= $this->modifier;
                 $item['discount'] += 100 - $this->modifier * 100;
                 $this->products['global_discount'] = 100 - $this->modifier * 100;
             }
         }
     } else {
         throw new \Exception('Coupon and item cannot be null or empty. Coupons cannot be less than 0 or greater than 100%', 997);
     }
     return $this->products;
 }
Example #29
0
 public static function snakeCase($string)
 {
     preg_match_all("/(^[a-z_][a-z0-9_]*|[A-Z]+(?![a-z])|[A-Z][a-z0-9_]+)/", $string, $matches);
     return join("_", array_map(function ($e) {
         return mb_strtolower($e);
     }, $matches[1]));
 }
 public function Start($string, $language, $count, $F)
 {
     $snippets = array();
     $query = urlencode(mb_strtolower($string, 'UTF-8'));
     $url = "http://www.startsiden.no/sok/index.html?lr=lang_{$language}&q={$query}";
     $html = $F->GetHTML($url, 'www.startsiden.no');
     if (!is_bool($html)) {
         $i = 0;
         foreach ($html->find('ol[class="searchresults mainresults"] li') as $e) {
             $t = 'h3 a';
             $d = 'p[class="description"]';
             if (isset($e->find($t, 0)->plaintext)) {
                 $title = $e->find($t, 0)->plaintext;
             }
             if (isset($e->find($d, 0)->plaintext)) {
                 $description = $e->find($d, 0)->plaintext;
             }
             if ($i < $count) {
                 if (!empty($title) and !empty($description)) {
                     $snippets[$i]['title'] = trim($title);
                     $snippets[$i]['description'] = trim($description);
                     $i++;
                 }
             }
         }
         $html->clear();
         $html = null;
         $e = null;
         unset($html, $e);
     } else {
         $F->Error("Can't create outgoing request. Please check StartSiden snippets plugin.");
     }
     return $snippets;
 }