public static function rpgAutoload($className)
 {
     switch (true) {
         case StringTool::endsWith($className, 'Tool'):
             $file = 'tools' . DIRECTORY_SEPARATOR . $className . '.class.php';
             break;
         case StringTool::endsWith($className, 'Tracking'):
             $file = 'tracking' . DIRECTORY_SEPARATOR . $className . '.class.php';
             break;
         case StringTool::endsWith($className, 'Connection'):
             $file = 'connection' . DIRECTORY_SEPARATOR . $className . '.class.php';
             break;
         case StringTool::endsWith($className, 'Model'):
         case StringTool::endsWith($className, 'Factory'):
             $file = 'models' . DIRECTORY_SEPARATOR . $className . '.class.php';
             break;
         case StringTool::endsWith($className, 'Exception'):
             $file = 'exceptions' . DIRECTORY_SEPARATOR . $className . '.class.php';
             break;
         case StringTool::startsWith($className, 'Smarty'):
             // Smarty class, uses smarty autoloader
             return;
             break;
         default:
             // Include corresponding file
             $file = 'classes' . DIRECTORY_SEPARATOR . $className . '.class.php';
     }
     try {
         require_once $file;
     } catch (Exception $e) {
     }
 }
예제 #2
0
파일: validate.php 프로젝트: rayful/toolkit
 /**
  * 根据在PHPDoc里面声明的属性(字段)类型,作出自动类型转换。一般用在保存之前,或写在子类的validate方法里面。
  * 注意是trait,不能重写覆盖。
  * @return void
  */
 public function autoConvert()
 {
     $vars = $this->toArray();
     foreach ($vars as $name => $value) {
         if (is_null($value)) {
             continue;
         }
         //通过ReflectionProperty类获取字段的类型
         $PropertyX = new ReflectionPropertyX($this, $name);
         $type = $PropertyX->_var;
         $type = strtolower($type);
         $type = preg_replace("/^\\\\/", "", $type);
         //开始自动转换
         if ($name == "_id" && is_string($value) || $type == "mongoid" && is_string($value)) {
             if ($value) {
                 $this->{$name} = new \MongoId($value);
             } else {
                 $this->{$name} = null;
             }
         } elseif ($type == "mongoid[]") {
             if (!$value) {
                 $this->{$name} = null;
             } elseif (is_string($value)) {
                 $this->{$name} = StringTool::toMongoIds($value);
             } elseif (is_array($value)) {
                 $this->{$name} = array_map(["\\rayful\\Tool\\StringTool", "toMongoId"], $value);
             }
         } elseif ($type == "bool" || $type == "boolean") {
             if ($value === "false") {
                 $value = false;
             }
             $this->{$name} = boolval($value);
         } elseif ($type == "string") {
             $this->{$name} = strval($value);
         } elseif ($type == "float") {
             $this->{$name} = floatval($value);
         } elseif ($type == "int" || $type == "integer") {
             $this->{$name} = intval($value);
         } elseif ($type == "mongodate") {
             //主要针对淘宝传过来的时间是字符串类型
             if (is_int($value)) {
                 $this->{$name} = new \MongoDate($value);
             } elseif (is_object($value) && $value instanceof \MongoDate) {
                 $this->{$name} = $value;
             } elseif ($value) {
                 $this->{$name} = new \MongoDate(strtotime($value));
             }
         } elseif (($type == "array" || strpos($type, "[]") !== false) && is_string($value)) {
             //主要针对使用textarea post过来是字符串类型的字段
             $value = trim($value);
             if ($value) {
                 $value = StringTool::toArray($value);
                 $this->{$name} = $value;
             } else {
                 $this->{$name} = null;
             }
         }
     }
 }
 /**
  * Return the locale of the client browser
  * @param string $language The language of the browser
  * @return string The locale of the client
  */
 public static function getLocaleFromLanguage($language)
 {
     $locale = StringTool::substr($language, 0, 2);
     if (in_array($locale, TranslationTool::$languageList)) {
         return $locale;
     } else {
         return TranslationTool::DEFAULT_LOCALE;
     }
 }
예제 #4
0
/**
 * Upper case the first letter of a word, even if it is a letter with an accent
 *
 * @param $word
 * @author Nicolas Rod
 */
function ucfirst_special($word)
{
    $word = ucfirst($word);
    /*
     * Case of special chars
     */
    $special_chars = array('à' => 'À', 'á' => 'Á', 'â' => 'Â', 'ä' => 'Ä', 'ã' => 'Ã', 'é' => 'É', 'è' => 'È', 'ê' => 'Ê', 'ë' => 'Ë', 'ẽ' => 'Ẽ', 'ì' => 'Ì', 'í' => 'Í', 'î' => 'Î', 'ï' => 'Ï', 'ĩ' => 'Ĩ', 'ò' => 'Ò', 'ó' => 'Ó', 'ô' => 'Ô', 'ö' => 'Ö', 'õ' => 'Õ', 'ù' => 'Ù', 'ú' => 'Ú', 'û' => 'Û', 'ü' => 'Ü', 'ũ' => 'Ũ');
    foreach ($special_chars as $min => $maj) {
        if (StringTool::start_with($word, $min)) {
            $sub_upper_cased = substr($word, 2);
            $word = $maj . $sub_upper_cased;
            break;
        }
    }
    return $word;
}
예제 #5
0
function readDirectory($dirName)
{
    $fileList = array();
    $dir = opendir($dirName);
    while ($file = readdir($dir)) {
        if ($file != '.' && $file != '..' && $file != 'ext') {
            if (is_dir($dirName . '/' . $file)) {
                $fileList = array_merge($fileList, readDirectory($dirName . '/' . $file));
            } else {
                if (StringTool::endsWith($file, '.js')) {
                    $fileList[] = $dirName . '/' . $file;
                }
            }
        }
    }
    return $fileList;
}
예제 #6
0
 /**
  * Convert a color string from hexadecimal to RGB format
  *
  * @param string $color an hexadecimal color (#FFFFFF, #FFF, AAAAAA are available formats)
  * @return array|boolean an array with r,g,b result, or false if color format was not correct
  */
 public static function hexaToRGB($color)
 {
     if ($color[0] == '#') {
         $color = StringTool::substr($color, 1);
     }
     if (StringTool::strlen($color) == 6) {
         list($r, $g, $b) = array($color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5]);
     } elseif (StringTool::strlen($color) == 3) {
         list($r, $g, $b) = array($color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2]);
     } else {
         return false;
     }
     $r = hexdec($r);
     $g = hexdec($g);
     $b = hexdec($b);
     return array($r, $g, $b);
 }
예제 #7
0
 /**
  * Converts a timestamp to a time string
  * @param int $timestamp The timestamp (default is NULL for now)
  * @param string $format The string format
  * @return string The time string
  */
 public static function timestampToString($timestamp, $format = DateTool::FORMAT_MYSQL_DATETIME)
 {
     if (!StringTool::isInt($timestamp)) {
         throw new Exception('Unable to convert timestamp to time string : "' . $timestamp . '" is not an integer');
     }
     return DateTool::getTimeString($format, $timestamp);
 }
예제 #8
0
 /**
  * Property writing accessor
  * @param string $propertyName The property name
  * @param string $value The property value
  */
 public function setProperty($propertyName, $value)
 {
     // Non-null value
     if ($value !== NULL) {
         // Numeric value
         if (StringTool::isInt($value)) {
             $value = StringTool::toInt($value, false);
         } else {
             if (StringTool::isFloat($value, FALSE)) {
                 $value = StringTool::toFloat($value, false);
             } else {
                 if (StringTool::endsWith($propertyName, 'date')) {
                     // Date has a 10 length (YYYY-mm-dd)
                     if (StringTool::strlen($value) == 10) {
                         $value = DateTool::stringToTimestamp($value, DateTool::FORMAT_MYSQL_DATE);
                     } else {
                         $value = DateTool::stringToTimestamp($value);
                     }
                 }
             }
         }
         // Day property type
     }
     // Removes table name at the beginning of field name, not for id fields nor xxx_has_xxx tables
     $tableName = DatabaseFactory::getElementTableName($this->getElementClass());
     if (!StringTool::contains($tableName, ElementFactory::TABLE_JOIN_SEPARATOR)) {
         $tablePrefix = $tableName . '_';
         $tableIdField = $tablePrefix . 'id';
         if (StringTool::startsWith($propertyName, $tablePrefix) && (!StringTool::endsWith($propertyName, '_id') || $propertyName == $tableIdField)) {
             $propertyName = StringTool::truncateFirstChars($propertyName, StringTool::strlen($tablePrefix));
         }
     }
     // Updates original property list
     if (!ArrayTool::array_key_exists($propertyName, $this->propertyList)) {
         // It's the first time this property gets a value, it will be updated (set a null value to original property list)
         $this->originalPropertyList[$propertyName] = NULL;
     } else {
         if (ArrayTool::array_key_exists($propertyName, $this->originalPropertyList)) {
             // Attribute value had already changed (originalPropertyList already has a value for this property)
             // If value has been reset to original value, removes the update of the property
             if ($value == $this->originalPropertyList[$propertyName]) {
                 unset($this->originalPropertyList[$propertyName]);
             }
         } else {
             if ($value !== $this->propertyList[$propertyName]) {
                 // If value has changed, updates original value
                 $this->originalPropertyList[$propertyName] = $this->propertyList[$propertyName];
             }
         }
     }
     // Sets property new value
     $this->propertyList[$propertyName] = $value;
 }
    /**
     * @return array
     */
    public static function getMappingSpe()
    {
        $db = MMDB::instance();
        $cluster = ClusterTool::clusterIdentifier();
        
        
        // ct->label
        $sql = "SELECT t.code, l.label
                FROM mm_taxonomy AS t
                LEFT JOIN mm_taxonomy_translation AS l ON t.id = l.taxonomy_id AND l.cluster_identifier = '$cluster'
                INNER JOIN mm_cluster_has_taxonomy AS cht ON cht.taxonomy_id = t.id AND cht.is_mappable = 1 AND cht.cluster_identifier = '$cluster'
                WHERE t.taxonomy_category_id = 1
                ORDER BY cht.placement, l.label ASC";
        
        if( SolrSafeOperatorHelper::featureIsActive( 'HiddenCustomerTypes' ) ){
            
            $customerTypeFilter = '';
            
            $hiddenCustomerTypes = SolrSafeOperatorHelper::feature( 'HiddenCustomerTypes', 'customerTypes' );
            if(count($hiddenCustomerTypes) > 0){
                for ($i = 0; $i < count($hiddenCustomerTypes); $i++){
                    $customerTypeFilter .= ($i+1 == count($hiddenCustomerTypes)) ? "'".$hiddenCustomerTypes[$i]."'" : "'".$hiddenCustomerTypes[$i]."'," ;
                }
                $sql = "SELECT t.code, l.label
                FROM mm_taxonomy AS t
                LEFT JOIN mm_taxonomy_translation AS l ON t.id = l.taxonomy_id AND l.cluster_identifier = '$cluster'
                INNER JOIN mm_cluster_has_taxonomy AS cht ON cht.taxonomy_id = t.id AND cht.is_mappable = 1 AND cht.cluster_identifier = '$cluster'
                WHERE t.taxonomy_category_id = 1 AND t.code NOT IN (".$customerTypeFilter.")
                ORDER BY cht.placement, l.label ASC";
            }
        }
        
        $results = $db->arrayQuery( $sql );
        $tabCT = array();

        StringTool::sortAlphaValues($results, "label");

        foreach($results as $result){
            $tabCT[$result["code"]] = $result["label"];
        }

        // mapping spe->ct
        $sql = "SELECT group_concat(customer_type_code separator ',') AS ct_codes, user_speciality_code AS uspe_code, tlspe.label AS uspe_label
                FROM mm_customer_type_specialities AS cts
                LEFT JOIN mm_taxonomy AS tspe ON tspe.code = cts.user_speciality_code
                LEFT JOIN mm_taxonomy_translation AS tlspe ON tlspe.taxonomy_id = tspe.id
                INNER JOIN mm_cluster_has_taxonomy AS cht ON cht.taxonomy_id = tspe.id AND cht.is_mappable = 1 AND cht.cluster_identifier = '$cluster'
                WHERE cts.cluster_identifier = '$cluster' AND tlspe.cluster_identifier = '$cluster'
                GROUP BY user_speciality_code
                ORDER BY uspe_label ASC";
        $tabSpe = $db->arrayQuery( $sql );

        StringTool::sortAlphaValues($tabSpe, "uspe_label");

        if(!count($tabSpe))
        {
            $sql = "SELECT group_concat(customer_type_code separator ',') AS ct_codes, user_speciality_code AS uspe_code, tlspe.label AS uspe_label
                    FROM mm_customer_type_specialities AS cts
                    LEFT JOIN mm_taxonomy AS tspe ON tspe.code = cts.user_speciality_code
                    LEFT JOIN mm_taxonomy_translation AS tlspe ON tlspe.taxonomy_id = tspe.id
                    INNER JOIN mm_cluster_has_taxonomy AS cht ON cht.taxonomy_id = tspe.id AND cht.is_mappable = 1 AND cht.cluster_identifier = '$cluster'
                    WHERE cts.cluster_identifier IS NULL AND tlspe.cluster_identifier = '$cluster'
                    GROUP BY user_speciality_code
                    ORDER BY uspe_label ASC";
            $tabSpe = $db->arrayQuery( $sql );
        }


        if( !SolrSafeOperatorHelper::featureIsActive( 'SpecialtySequence' ) )
        {
            $mapping = array();
            foreach($tabSpe as $spe)
            {
                $mapping[$spe["uspe_code"]] = array( "name" => $spe["uspe_label"],
                    "ct"   => explode(',', $spe["ct_codes"]));
            }

            return array("mapping" => $mapping, "ct" => $tabCT);
        }

        $mappingArranged = array();
        $mappingOthers = array();
        // get specialty sequence from feature
        $specialtySequence = SolrSafeOperatorHelper::feature( 'SpecialtySequence', 'Sequence' );
        // iterate through sequence
        foreach($specialtySequence as $position => $specialty){
            foreach($tabSpe as $key => $spe)
            {
                // put user specialty at desired position
                if($spe["uspe_code"] === $specialty){
                    $mappingArranged[$spe["uspe_code"]] = array( "name" => $spe["uspe_label"],
                                                 "ct"   => explode(',', $spe["ct_codes"]));
                    // remove proccessed specialty from base table
                    unset($tabSpe[$key]);
                }
                // get others specialties that are not listed in feature
                if(!in_array($spe["uspe_code"], $specialtySequence)){
                    $mappingOthers[$spe["uspe_code"]] = array( "name" => $spe["uspe_label"],
                                                 "ct"   => explode(',', $spe["ct_codes"]));
                }
            }
        }
        return array("mapping" => array_merge($mappingArranged, $mappingOthers), "ct" => $tabCT);
    }
    /**
     * @see ezfSolrDocumentFieldBase::getData()
     * @return array
     */
    public function getData()
    {
        $data           = parent::getData();
        $content        = $this->ContentObjectAttribute->content();
        
        /* @var $content array */
        foreach ( array_merge( self::taxonomyAttribute(), array_keys($content) ) as $taxonomyIdentifier )
        {
            $taxonomyValues              = isset( $content[$taxonomyIdentifier] ) ? $content[$taxonomyIdentifier] : array(); 
            $subattrSourceIdValues       = array();
            $subattrSourceIdFieldName    = self::getCustomSubattributeFieldName(
                                                $taxonomyIdentifier,
                                                'source_id');
            
            foreach ( $taxonomyValues as $taxonomyValue )
            {
                if( preg_match( '#^symptom_.*$#', $taxonomyValue ) )
                {
                    $sourceKey                  = $taxonomyValue;
                    $subattrSourceIdValues[]    = $sourceKey;
                    
                    // we need a few more things for the symptoms
                    /* @type $node eZContentObjectTreeNode */
                    $contentObject = $this->ContentObjectAttribute->object();
                    $node          = $contentObject->mainNode();
                    $clusters      = NodeTool::getArticleClusters($node);

                    foreach( $clusters as $cluster )
                    {
                        ClusterTool::setCurrentCluster($cluster);

                        $ini = eZINI::fetchFromFile('extension/'.$cluster.'/settings/site.ini');
                        $node->setCurrentLanguage( $ini->variable('RegionalSettings', 'ContentObjectLocale') );

                        $applicationLocalized = CacheApplicationTool::buildLocalizedApplicationByIdentifier( MerckManualShowcase::mainApplicationIdentifier() );
                        if ( !$applicationLocalized )
                            continue;

                        $customSymptomAttributeKey = 'attr_custom_symptom_'.$cluster.'_s';
                        $labelTranslations         = FacetFilteringTool::getTaxonomyTranslation( 'symptom' );
                        $label                     = $labelTranslations[$sourceKey];
                        $url                       = preg_replace( '#^[^/]+#', '', MerckManualFunctionCollection::getMerckManualNodeUrl( 'meck-manual-showcase', $node, $ini->variable('RegionalSettings', 'ContentObjectLocale') ) );

                        ClusterTool::resetCurrentCluster();

                        $customSymptomAttributeValueParts = array(
                            mb_strtolower(mb_substr(StringTool::removeAccents( StringTool::CJK2Pinyin($label) ), 0, 1)),
                            $label,
                            $url
                        );

                        $data[$customSymptomAttributeKey] = implode( '##', $customSymptomAttributeValueParts );
                    }
                }
                else if ( preg_match('#^222\.[0-9]+$#', $taxonomyValue ) )
                {
                    $sourceKey                  = $taxonomyValue;
                    $subattrSourceIdValues[]    = $sourceKey;

                    /* @type $node eZContentObjectTreeNode */
                    /* @type $dataMap eZContentObjectAttribute[] */
                    $contentObject                    = $this->ContentObjectAttribute->object();
                    $node                             = $contentObject->mainNode();
                    $clusters                         = NodeTool::getArticleClusters($node);
                    $customSymptomAttributeValueParts = array(
                        $content['layer_natom'][0],
                        $content['sub_layer_natom'][0],
                    );

                    foreach( $clusters as $cluster )
                    {
                        ClusterTool::setCurrentCluster($cluster);

                        $customSymptomAttributeKey        = 'attr_custom_layer_sublayer_natom_'.$cluster.'_s';
                        $data[$customSymptomAttributeKey] = implode( '##', $customSymptomAttributeValueParts );

                        ClusterTool::resetCurrentCluster();
                    }
                }
                else
                    $subattrSourceIdValues[] = trim( $taxonomyValue );
            }

            $data[$subattrSourceIdFieldName] = empty($subattrSourceIdValues) ? '' : $subattrSourceIdValues;
        }
        
        return $data;
    }
예제 #11
0
 /**
  * Generates a random string (for unique filenames)
  * @param int $length The string length
  * @return string The created string
  */
 public static function generateRandomString($length = 10)
 {
     return StringTool::substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
 }
예제 #12
0
require_once '../init/init.inc.php';
//$smarty->assign('javascript', array('manageQuestion'));
//$smarty->assign('css', array('manageElement'));
$smarty->assign('page', 'index');
if (AuthenticationTool::getInstance()->isPlayerConnected()) {
    OsteoFactory::getElementList('Component');
    $structureList = OsteoFactory::getElementList('Structure', null, 'structure_category_order, structure_order ASC', 'structure LJ player_has_structure, structure_category IJ structure');
    $smarty->assign('structureList', Osteo::elementListToArray($structureList, Structure::FORMAT_PLAYER_STRUCTURE_LIST));
    $componentList = OsteoFactory::getElementList('Component');
    $smarty->assign('componentList', Osteo::elementListToArray($componentList, Component::FORMAT_PLAYER_COMPONENT_LIST));
}
$scoreDataList = Structure::getDatabaseConnection()->selectRequest('SELECT player_name, SUM(is_crafted) AS crafted, SUM(best_score) AS score, SUM(best_time) AS time FROM player INNER JOIN player_has_structure ON player.player_id = player_has_structure.player_id GROUP BY player.player_id ORDER BY crafted DESC, score DESC, time ASC LIMIT 10');
$scoreList = array();
foreach ($scoreDataList as $scoreData) {
    if (!$scoreData['time']) {
        $formattedTime = '-';
    } else {
        $formattedTime = DateTool::timestampToString($scoreData['time'], DateTool::FORMAT_MINUTES);
        if (StringTool::startsWith($formattedTime, '00m')) {
            $formattedTime = StringTool::truncateFirstChars($formattedTime, 4);
        }
        if (StringTool::startsWith($formattedTime, '0')) {
            $formattedTime = StringTool::truncateFirstChars($formattedTime, 1);
        }
    }
    $scoreList[] = array('player_name' => $scoreData['player_name'], 'crafted' => $scoreData['crafted'], 'score' => $scoreData['score'], 'time' => $formattedTime);
}
$smarty->assign('scoreList', $scoreList);
$smarty->display('layout.tpl');
require_once 'init/end.inc.php';
 /**
  * Returns a localized error message corresponding to current exception
  * @return string The localized exception message
  */
 public function getUserLocalizedMessage()
 {
     return TranslationTool::getInstance()->translate(StringTool::upper(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', get_class($this))));
 }
예제 #14
0
파일: Xss.php 프로젝트: HansonHuang/Pyramid
 /**
  * 清理属性
  */
 public function attributes($attributes, $elem = '')
 {
     $return = array();
     $mode = 0;
     $attrname = '';
     $skip = false;
     while (strlen($attributes) != 0) {
         $working = 0;
         switch ($mode) {
             //属性名
             case 0:
                 if (preg_match('/^([-a-zA-Z]+)/', $attributes, $match)) {
                     $working = 1;
                     $mode = 1;
                     $attrname = strtolower($match[1]);
                     $skip = substr($attrname, 0, 2) == 'on';
                     $attributes = preg_replace('/^[-a-zA-Z]+/', '', $attributes);
                 }
                 break;
                 //单个的属性值
             //单个的属性值
             case 1:
                 if (preg_match('/^\\s*=\\s*/', $attributes)) {
                     $working = 1;
                     $mode = 2;
                     $attributes = preg_replace('/^\\s*=\\s*/', '', $attributes);
                     break;
                 }
                 if (preg_match('/^\\s+/', $attributes)) {
                     $working = 1;
                     $mode = 0;
                     if (!$skip) {
                         $return[$attrname] = array();
                     }
                     $attributes = preg_replace('/^\\s+/', '', $attributes);
                 }
                 break;
                 //属性值
             //属性值
             case 2:
                 if (preg_match('/^"([^"]*)"(\\s+|$)/', $attributes, $match)) {
                     $working = 1;
                     $mode = 0;
                     if (!$skip) {
                         $return[$attrname] = array('value' => $match[1], 'delimiter' => '"');
                     }
                     $attributes = preg_replace('/^"[^"]*"(\\s+|$)/', '', $attributes);
                     break;
                 }
                 if (preg_match("/^'([^']*)'(\\s+|\$)/", $attributes, $match)) {
                     $working = 1;
                     $mode = 0;
                     if (!$skip) {
                         $return[$attrname] = array('value' => $match[1], 'delimiter' => "'");
                     }
                     $attributes = preg_replace("/^'[^']*'(\\s+|\$)/", '', $attributes);
                     break;
                 }
                 if (preg_match("%^([^\\s\"']+)(\\s+|\$)%", $attributes, $match)) {
                     $working = 1;
                     $mode = 0;
                     if (!$skip) {
                         $return[$attrname] = array('value' => $match[1], 'delimiter' => '"');
                     }
                     $attributes = preg_replace("%^[^\\s\"']+(\\s+|\$)%", '', $attributes);
                 }
                 break;
         }
         //没有匹配到的,直接过滤
         if ($working == 0) {
             $attributes = preg_replace('/
               ^
               (
               "[^"]*("|$)     # - a string that starts with a double quote, up until the next double quote or the end of the string
               |               # or
               \'[^\']*(\'|$)| # - a string that starts with a quote, up until the next quote or the end of the string
               |               # or
               \\S              # - a non-whitespace character
               )*              # any number of the above three
               \\s*             # any number of whitespaces
               /x', '', $attributes);
             $mode = 0;
         }
     }
     if ($mode == 1 && !$skip) {
         $return[$attrname] = array();
     }
     //执行属性的清理
     $tag = isset($this->allowedTags[$elem]) ? $this->allowedTags[$elem] : array();
     foreach ($return as $name => $info) {
         if (!isset($info['value'])) {
             continue;
         }
         //去掉不允许的
         if (isset($tag['disallowed']) && in_array($name, $tag['disallowed'])) {
             unset($return[$name]);
             continue;
         }
         //只留允许的
         if (isset($tag['allowed']) && !in_array($name, $tag['allowed'])) {
             unset($return[$name]);
             continue;
         }
         //对style深度清理
         if ($name == 'style') {
             $sanitized_properties = array();
             $properties = array_filter(array_map('trim', explode(';', StringTool::decodeEntities($info['value']))));
             foreach ($properties as $property) {
                 if (!preg_match('#^([a-zA-Z][-a-zA-Z]*)\\s*:\\s*(.*)$#', $property, $property_matches)) {
                     continue;
                 }
                 $property_name = strtolower($property_matches[1]);
                 $property_value =& $property_matches[2];
                 if (!isset($this->allowedStyleProperties[$property_name])) {
                     continue;
                 }
                 if (strpos($property_value, 'url(') !== false) {
                     if (!preg_match('`url\\(\\s*(([\'"]?)(?:[^)]|(?<=\\\\)\\))+[\'"]?)\\s*\\)`', $property_value, $url) || empty($url[1])) {
                         continue;
                     }
                     if (!empty($url[2])) {
                         if (substr($url[1], -1) != $url[2]) {
                             continue;
                         }
                         $url[1] = substr($url[1], 1, -1);
                     }
                     $url = preg_replace('`\\\\([(),\'"\\s])`', '\\1', $url[1]);
                     if (StringTool::filterBadProtocol($url) != $url) {
                         continue;
                     }
                     if (!preg_match('`^/[^/]+`', $url)) {
                         $match = false;
                         foreach ($this->allowedStyleDomain as $reg) {
                             if (preg_match($reg, $url)) {
                                 $match = true;
                                 break;
                             }
                         }
                         if (!$match) {
                             continue;
                         }
                     }
                 }
                 $sanitized_properties[] = $property_name . ':' . StringTool::checkPlain($property_value);
             }
             if (empty($sanitized_properties)) {
                 unset($return[$name]);
                 continue;
             }
             $info['value'] = implode('; ', $sanitized_properties);
         } else {
             $info['value'] = StringTool::filterBadProtocol($info['value']);
         }
         $return[$name] = $name . '=' . $info['delimiter'] . $info['value'] . $info['delimiter'];
     }
     return $return;
 }
예제 #15
0
 public static function mb_ucfirst($text)
 {
     if (function_exists('mb_substr') && function_exists('mb_strtoupper')) {
         $letter1 = mb_substr($text, 0, 1);
         $rest = mb_substr($text, 1);
         $letter1_uc = mb_strtoupper($letter1);
         $utext = $letter1_uc . $rest;
         return $utext;
     } else {
         $word = ucfirst($text);
         /*
          * Case of special chars
          */
         $special_chars = array('à' => 'À', 'á' => 'Á', 'â' => 'Â', 'ä' => 'Ä', 'ã' => 'Ã', 'é' => 'É', 'è' => 'È', 'ê' => 'Ê', 'ë' => 'Ë', 'ẽ' => 'Ẽ', 'ì' => 'Ì', 'í' => 'Í', 'î' => 'Î', 'ï' => 'Ï', 'ĩ' => 'Ĩ', 'ò' => 'Ò', 'ó' => 'Ó', 'ô' => 'Ô', 'ö' => 'Ö', 'õ' => 'Õ', 'ù' => 'Ù', 'ú' => 'Ú', 'û' => 'Û', 'ü' => 'Ü', 'ũ' => 'Ũ');
         foreach ($special_chars as $min => $maj) {
             if (StringTool::start_with($text, $min)) {
                 $sub_upper_cased = substr($word, 2);
                 $word = $maj . $sub_upper_cased;
                 break;
             }
         }
         return $word;
     }
 }
    /**
     * @param array $solrResult
     * @return array
     */
    public function facetResult( &$solrResult )
    {
        $translations       = $this->translations();
        $facetResult        = array();
        $this->needsRefresh = false;
        $values             = $this->values;

        if( empty( $values ) && !$this->forcedUnchecked )
            $values = $this->forcedValues;

        foreach( $solrResult['facet_counts']['facet_fields'][$this->facetSolrIdFieldName()] as $id => $count )
        {
            $toRemove = false;
            $id = strval($id);

            if( empty($this->defaultValues) || in_array($id, $this->defaultValues, true) )
            {
                $checked = ( $count && in_array( $id , $values, true ) ) ? 1 : 0;
                if( $this->forcedUnchecked )
                    $checked = 0;

                if ( isset($translations[$id]) )
                {
                    $facetResult[$translations[$id]] = array(
                        'count'    => (int)$count,
                        'id'       => $id,
                        'checked'  => $checked,
                        'forceChecked' => (in_array($id, $this->forcedCheckedTaxonomy) ? $id : false )
                    );
                }

                // a value set for filter returns 0 results => we need to refresh the solr search
                if ( in_array( $id, $values, true ) && $count == 0 )
                {
                    $toRemove = true;
                }
            }
            elseif( in_array( $id, $this->values, true ) )
            {
                $toRemove = true;
            }

            if( $toRemove )
            {
                unset( $values[array_search($id, $values)] );

                $this->values = array_values($values);

                if( empty( $this->values ) )
                    $this->forcedUnchecked = true;

                $this->needsRefresh = true;
            }
        }

        if($this->sort == 'alpha')
        {
            StringTool::sortAlphaKeys($facetResult);
        }
        elseif ( $this->sort == 'count' )
        {
            foreach( $facetResult as $key => $value)
            {
                $facetResult[$key]['key'] = $key;
            }

            uasort ( $facetResult, array(self, 'sortCount' ) );

            foreach( $facetResult as $key => $value)
            {
                unset($facetResult[$key]['key']);
            }
        }

        return $facetResult;
    }
    public function facetResult( &$solrResult )
    {
        $translations       = $this->translations();
        $facetResult        = array();
        $this->needsRefresh = false;
        $values             = $this->values;


        if( empty( $values ) && !$this->forcedUnchecked )
            $values = $this->forcedValues;

        $totalCount = 0;


        foreach( $solrResult['facet_counts']['facet_fields'][$this->facetSolrIdFieldName()] as $id => $count )
        {
            $totalCount += $count;
            $toRemove = false;
            if (!in_array($id, $this->fieldsToShow))
            {
                continue;
            }

            if( empty($this->defaultValues) || in_array($id, $this->defaultValues, true) )
            {

                $checked = ( $count && (in_array( $id , $values, true ) || $this->precheckedValue == $id) ) ? 1 : 0;
                if( $this->forcedUnchecked )
                    $checked = 0;

                if ( isset($translations[$id]) )
                {
                    $facetResult[$translations[$id]] = array(
                        'count'    => (int)$count,
                        'id'       => $id,
                        'checked'  => $checked
                    );
                }
                // a value set for filter returns 0 results => we need to refresh the solr search
                if ( in_array( $id, $values, true ) )
                {
//                    $toRemove = true;
                }
            }
            elseif( in_array( $id, $this->values, true ) )
            {
//                $toRemove = true;
            }

            if( $toRemove )
            {
                unset( $values[array_search($id, $values)] );

                $this->values = array_values($values);

                if( empty( $this->values ) )
                    $this->forcedUnchecked = true;

                $this->needsRefresh = true;
            }
        }


        if($this->sort == 'alpha')
        {
            StringTool::sortAlphaKeys($facetResult);
        }
        elseif ( $this->sort == 'count' )
        {
            foreach( $facetResult as $key => $value)
            {
                $facetResult[$key]['key'] = $key;
            }

            uasort ( $facetResult, array(self, 'sortCount' ) );

            foreach( $facetResult as $key => $value)
            {
                unset($facetResult[$key]['key']);
            }
        }

        $facetResult[$this->allValuesTranslation] = array(
            'checked' => (count($values) == 0 || (count($values) == 1 && $values[0] == 'all')),
            'count' => $totalCount,
            'id' => 'all',
        );
        return $facetResult;
    }
 /**
  * Gets parent element from an element
  * @param Element $element The child element
  * @param string $parentClass The parent element class
  * @param string $conditions The conditions string to apply
  * @param string $orderBy The order string to apply
  * @return Element The parent element
  */
 public static function getParentElement($element, $parentClass, $conditions = NULL, $orderBy = NULL)
 {
     $logInstance = LogTool::getInstance();
     $logInstance->logDebug('Gets ' . $element->getElementClass() . ' parent ' . $parentClass . ' element...');
     // Gets parent element by type and id
     $parentIdFieldName = DatabaseFactory::getParentIdColumnName($parentClass);
     // Split parent class name for search like people_mother, to get mother_people_id field from People table
     $parentClassNameList = StringTool::split(ElementFactory::TABLE_FIELD_SEPARATOR, $parentClass);
     $parentClass = end($parentClassNameList);
     $parentId = $element->{$parentIdFieldName};
     // Parent element id is null
     if ($parentId === NULL) {
         throw new ElementException('Cannot get ' . $parentClass . ' parent for ' . $element->getElementClass() . ' with id #' . $element->id . ': ' . $parentIdFieldName . ' is NULL');
     }
     return ElementFactory::getElement($parentClass, $parentId, $conditions, $orderBy);
 }
예제 #19
0
    /**
     * Add an hover tooltip to the given HTML element id
     *
     * @param string $element_id An HTML element id
     * @param string $content_url The URL that contains the tooltip content to display
     * @param array  $options 	css           true                      => include alaxos tooltip.css
     * 							position      'br', 'bl', 'tl', 'tr'    => bottom right, bottom left, top left, top right (position relative to the hovered element)
     */
    function add_ajax_tooltip($element_id, $content_url, $options = array())
    {
        $this->include_js_jquery();
        $this->include_js_jquery_no_conflict();
        $this->include_js_tooltip();
        if (!empty($options['css']) && $options['css']) {
            /*
             * include CSS needed to show the tooltip
             */
            $this->css('/alaxos/css/tooltip', null, array('inline' => false));
        }
        if (empty($options['position'])) {
            $options['position'] = 'br';
        }
        $element_id = StringTool::ensure_start_with($element_id, '#');
        echo $this->scriptBlock('$j(document).ready(function(){
			register_tool_tip("' . $element_id . '", "' . $this->url($content_url) . '", "' . $options['position'] . '");
		});');
    }
    /**
     * @param string $city
     * @return string[][]
     */
    static public function fetchDistrictsAndHospitalsByCity($city)
    {
        $db = MMDB::instance();
        $table = self::TABLE_NAME_DEFINITION;
        $query = "SELECT DISTINCT district, hospital, adress from $table WHERE city='$city' order by district asc, hospital asc, adress asc";

        $results = $db->arrayQuery($query);

        $tab = self::arrayfy($results, 'district', 'hospital', 'adress');
        foreach($tab as $key=>$value)
        {
            StringTool::sortAlphaValues($tab[$key]);
        }
        return $tab;
    }
    /**
     * @return bool
     */
    public function jsonBuildResult()
    {
        $this->initChannelInformations();

        $editorsChoice = $this->getEditorsChoice();

        $this->resultHandler->parseRequestParams(true);
        $solrResult = $this->resultHandler->contentResultMain();
        if ($this->getCustomParameter('IncludeChildrenInSearch'))
        {
            $this->resultHandler->getChildArticles($solrResult);
        }

        $facets     = array();

        $this->pushResult('num_found', (int)$solrResult['response']['numFound']);
        $this->pushResult('with_feed', $this->resultHandler->withFeed);

        if ( $this->resultHandler->withFacets )
        {
            foreach ( $this->facets as $facet)
            {
                /* @var $facet FacetBase */
                $f = array(
                    'uxtype'    => $facet->uxtype,
                    'list'      => ( $facet->isFiltered() ) ? $this->resultHandler->filteredFacetResult( $facet  ) : $facet->facetResult( $solrResult )
                );

                // JsonBuildResult is called again with facet with no result unchecked (state change via $this->facets)
                if ( $facet->needsRefresh )
                    return $this->jsonBuildResult();

                $facets[$facet->key] = $f;
            }

            $this->pushResult('facets', $facets);
        }

        if (!empty($editorsChoice))
        {
            $editorsChoice = $this->resultHandler->articleResult($editorsChoice, $facets);
            $this->pushResult('editors_choice' , $this->getEditorsChoiceView($editorsChoice));
        }


        $solrReturn = $this->resultHandler->articleResult($solrResult, $facets);

        $this->pushResult('articles', $this->setVariableAndGetTpl($solrReturn));
        if ( isset($solrReturn['all_specialities_informations'] ) )
        {
            $allSpecialitiesInformations = $solrReturn['all_specialities_informations'];
            unset( $solrReturn['all_specialities_informations'] );
            if (SolrSafeOperatorHelper::featureIsActive('SpecialityPopin') && SolrSafeOperatorHelper::feature('SpecialityPopin', 'CustomGroupsEnabled')) {
                $flatSpecialitiesList = array();
                foreach($allSpecialitiesInformations['all_specialities'] as $value) {
                    foreach($value as $name => $data) {
                        $name = StringTool::trim($name);
                        $flatSpecialitiesList[$name] = $data;
                    }
                }

                $customGroups = SolrSafeOperatorHelper::feature('SpecialityPopin', 'Groups');
                $allSpecialities = array();

                foreach ($customGroups as $name => $specialities) {
                    $name = StringTool::trim($name);
                    $allSpecialities[$name] = array();
                    foreach($specialities as $speciality) {
                        $speciality = StringTool::trim($speciality);
                        if (isset($flatSpecialitiesList[$speciality])) {
                            $allSpecialities[$name][$speciality] = $flatSpecialitiesList[$speciality];
                            unset($flatSpecialitiesList[$speciality]);
                        }
                    }
                }

                $allSpecialitiesInformations['all_specialities'] = $allSpecialities;
            }

            foreach ($allSpecialitiesInformations as $templateVariable => $templateValue)
                $this->tpl()->setVariable($templateVariable, $templateValue);

            $this->pushResult('all_specialities', $this->tpl()->fetch('design:'.$this->templateRootDirectory().'/content_service/specialities_list.tpl'));
        }
        
        $t3Facet = array();
        
        if ( isset($solrReturn['t3_facet_informations'] ) )
        {
            if ( count($solrReturn['t3_facet_informations']) > 0 )
            {
                $t3FacetInformations = $solrReturn['t3_facet_informations'];

                foreach ($t3FacetInformations as $templateVariable => $templateValue)
                    $this->tpl()->setVariable($templateVariable, $templateValue);

                $t3Facet[$t3FacetInformations['t3_key']] = $this->tpl()->fetch('design:'.$this->templateRootDirectory().'/content_service/t3_facet_list.tpl');

            }
            unset( $solrReturn['t3_facet_informations'] );
        }
        $this->pushResult('t3_facets', $t3Facet);
        
        foreach ( $solrReturn as $resultVariable => $resultValue )
            $this->pushResult($resultVariable, $resultValue);

        return true;
    }
예제 #22
0
 /**
  * Remove a trailing string from a string if it exists
  * @param $string The string that must be shortened if it ends with a trailing string
  * @param $trailing_string The trailing string
  * @return string
  */
 public static function remove_trailing($string, $trailing_string)
 {
     if (StringTool::end_with($string, $trailing_string)) {
         return substr($string, 0, strlen($string) - strlen($trailing_string));
     } else {
         return $string;
     }
 }
 public static function getFieldNameFromTableName($propertyName, $tableName)
 {
     if (StringTool::contains($tableName, ElementFactory::TABLE_JOIN_SEPARATOR) || StringTool::endsWith($propertyName, '_id')) {
         return $propertyName;
     }
     return $tableName . '_' . $propertyName;
 }
예제 #24
0
require_once '../../config/constants.php';
$globalsDir = '../../globals';
// Creates folder if needed
if (!is_dir($globalsDir)) {
    if (!mkdir($globalsDir)) {
        exit('Le dossier n\'a pas pu �tre cr��');
    }
}
if (!is_writable($globalsDir . '/globals.php')) {
    exit('Le fichier ne peut pas être lu');
}
$globalsFile = fopen($globalsDir . '/globals.php', 'w');
// Adds anchors
fwrite($globalsFile, "<?php\n");
foreach ($constantList as $constantName => $constantValue) {
    if ($constantValue === true) {
        $value = 'true';
    } else {
        if ($constantValue === false) {
            $value = 'false';
        } else {
            $value = StringTool::isFloat($constantValue) || StringTool::isInt($constantValue) ? $constantValue : '\'' . $constantValue . '\'';
        }
    }
    fwrite($globalsFile, 'define(\'' . $constantName . '\', ' . $value . ");\n");
}
// Adds anchors
fwrite($globalsFile, '?>');
fclose($globalsFile);
echo 'Globals generated<br>';
echo '<a href="../game.php">Back to game</a>';
 /**
  * Imports data, creating a table and inserting rows
  * @param string $tablename The destination table's name
  * @param array $head The column headers
  * @param array $data The data to import
  * @param string $mismatchtable Optional table's name to store type mismatch alerts
  * @return boolean TRUE on success or FALSE on failure
  */
 public function importRequest($tablename = null, $head = null, $data = null, $mismatchtable = null)
 {
     if ($tablename === null || $head === null || $data === null) {
         // mandatory params
         return false;
     }
     try {
         $logInstance = LogTool::getInstance();
         $coltype = array();
         // tells int, float or varchar for each column
         $nadata = array();
         // stores type mismatch alerts in a second table
         $nb_lines_to_check = 5;
         $sql = 'CREATE TABLE IF NOT EXISTS ' . $tablename . ' (';
         if ($mismatchtable) {
             $sql2 = 'CREATE TABLE IF NOT EXISTS ' . $mismatchtable . ' (';
         }
         $nb_col_to_check = array_key_exists(0, $head) ? count($head) - 1 : count($head);
         // if columns begin at #1, there's no id and we won't create one ;
         // if they begin at #0, it probably means there's an id, so let's handle it
         if (array_key_exists(0, $head)) {
             // " && $head[0] == 'id' " unnecessary
             $coltype[$head[0]] = 'int(11)';
             $sql .= '`' . $head[0] . '` ' . $coltype[$head[0]] . ', ';
         }
         for ($i = 1; $i <= $nb_col_to_check; $i++) {
             $colindex = StringTool::cleanVarName($head[$i]);
             if ($colindex == SGBD_SDF_MOLSTRUCCOL) {
                 $coltype[$colindex] = 'text';
             } else {
                 $nb_flt = 0;
                 $nb_int = 0;
                 $nb_str = 0;
                 // try the first $nb_lines_to_check lines of data
                 for ($j = 0; $j < $nb_lines_to_check; $j++) {
                     //$logInstance->logDebug("j : ".$j." - colindex : ".$colindex);
                     if (array_key_exists($j, $data)) {
                         // "false" if less than 5 lines in data
                         $temp = $data[$j][$colindex];
                         if (StringTool::isFloat($temp)) {
                             $nb_flt++;
                         } elseif (StringTool::isInt($temp)) {
                             $nb_int++;
                         } else {
                             $nb_str++;
                         }
                     }
                 }
                 if ($nb_flt > 0 && $nb_flt + $nb_int >= $nb_lines_to_check - 1) {
                     // we tolerate 1 line with wrong type
                     $coltype[$colindex] = 'float';
                 } elseif ($nb_int >= $nb_lines_to_check - 1) {
                     $coltype[$colindex] = 'int(11)';
                 } else {
                     $coltype[$colindex] = 'text';
                 }
                 // varchar too short sometimes
                 if ($mismatchtable) {
                     $sql2 .= '`' . $head[$i] . '` varchar(50), ';
                 }
                 // store mismatches directly in this table (not just 0/1/null)
             }
             $sql .= '`' . $head[$i] . '` ' . $coltype[$colindex] . ', ';
         }
         // the line below gets rid of the comma
         $sql = substr($sql, 0, strlen($sql) - 2);
         $sql .= ') ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;';
         $ok = $this->createRequest($sql);
         if (!$ok) {
             return false;
         }
         // ensure it's empty
         $sql = 'TRUNCATE TABLE ' . $tablename . ';';
         $ok = $this->deleteRequest($sql);
         if ($mismatchtable) {
             $sql2 = substr($sql2, 0, strlen($sql2) - 2);
             $sql2 .= ') ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;';
             $ok = $this->createRequest($sql2);
             $sql2 = 'TRUNCATE TABLE ' . $mismatchtable . ';';
             $ok = $this->deleteRequest($sql2);
         }
         // now insert data
         $logInstance->setSilentMode();
         $entry = array();
         if ($mismatchtable) {
             $entry2 = array();
         }
         foreach ($data as $key => $row) {
             $sql = 'INSERT INTO ' . $tablename . ' VALUES (\'';
             foreach ($row as $field => $value) {
                 if ($coltype[$field] == 'float' && !StringTool::isFloat($value) && !StringTool::isInt($value) || $coltype[$field] == 'int(11)' && !StringTool::isInt($value) && !StringTool::isFloat($value)) {
                     if ($mismatchtable) {
                         $entry2[] = $value == "" ? "NULL" : "1:" . $value;
                         // store mismatches directly in this table, with "1:" prefix
                     }
                     $value = "NULL";
                 } elseif ($value !== "" && !is_null($value)) {
                     if ($mismatchtable && $field != SGBD_SDF_MOLSTRUCCOL) {
                         $entry2[] = 0;
                     }
                 } else {
                     $value = "NULL";
                     if ($mismatchtable) {
                         $entry2[] = "NULL";
                     }
                 }
                 $entry[] = $value;
             }
             $sql .= implode("','", $entry);
             $sql .= '\');';
             $sql = str_replace('\'NULL\'', 'NULL', $sql);
             $entry = array();
             $ok = $this->insertRequest($sql);
             if ($mismatchtable) {
                 $sql2 = 'INSERT INTO ' . $mismatchtable . ' VALUES (\'';
                 $sql2 .= implode("','", $entry2);
                 $sql2 .= '\');';
                 $sql2 = str_replace('\'NULL\'', 'NULL', $sql2);
                 $ok = $this->insertRequest($sql2);
                 $entry2 = array();
             }
         }
         $logInstance->unsetSilentMode();
         return true;
     } catch (ParameterException $e) {
         return false;
     }
 }
예제 #26
0
 function startsWith($string, $needle)
 {
     //return (substr($string, 0, strlen($needle)) == $needle);
     return StringTool::start_with($string, $needle);
 }
예제 #27
0
        case "":
            $color = '#5FF';
            // Cyan
            break;
        case "":
            $color = '#F5F';
            // Purple
            break;
        case "":
            $color = '#BBB';
            // White
        // White
        default:
            $color = isset($color) ? $color : '#bbb';
            $truncate = false;
            break;
    }
    ?>
<p id="msg<?php 
    echo $index;
    ?>
" class="chatLine" style="color: <?php 
    echo $color;
    ?>
"><?php 
    echo htmlspecialchars($truncate ? StringTool::truncateFirstChars($logFile[$index], 7) : $logFile[$index]);
    ?>
</p>
<?php 
}
SessionTool::getInstance()->setParameter('startLine', $lineCount);
 public static function fetchSymptomsLetters($related_infos = false)
 {
     if ( is_null(self::$_symptomsLetters) )
     {
         $field = 'attr_custom_symptom_'.ClusterTool::clusterIdentifier().'_s';
         $params = array(
             'indent'       => 'on',
             'q'            => '',
             'start'        => 0,
             'rows'         => 0,
             'fl'           => 'score',
             'qt'           => 'ezpublish',
             'explainOther' => '',
             'hl.fl'        => '',
             'facet'        => 'true',
             'facet.field'  => $field,
             'facet.mincount'    => 1
         );
         $solrResult = self::rawSearch($params);
         
         $translations = FacetFilteringTool::getTaxonomyTranslation( 'symptom' );
         $letters = array();
         foreach( $solrResult['facet_counts']['facet_fields'][$field] as $key => $v) {
             list( $letter, $symptomLabel, $url ) = explode('##', $key);
             
             if( !isset($letters[$letter]) )
                 $letters[$letter] = array();
             $letters[$letter][$symptomLabel] = $url;
         }
         
         ksort($letters);
         foreach ( $letters as $letter => $symptoms)
         {
             uksort($symptoms, function($a, $b) {
                 return strcmp(StringTool::CJK2Pinyin($a), StringTool::CJK2Pinyin($b));
             });
             $letters[$letter] = $symptoms;
         }
         self::$_symptomsLetters = $letters;
     }
     
     return array( 'result' => self::$_symptomsLetters );
 }
 /**
  * Gets current request complete url
  * @param boolean $includeGetParamList if GET params have to be added to URI
  * @return string The url
  */
 public static function getCurrentURL($includeGetParamList = true)
 {
     $url = 'http' . (!ArrayTool::array_key_exists('HTTPS', $_SERVER) || $_SERVER['HTTPS'] == 'off' ? '' : 's') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
     // Gets only string before the "?" if get params are ignored
     if (!$includeGetParamList) {
         list($url) = StringTool::split('\\?', $url);
     }
     return $url;
 }
예제 #30
0
 /**
  * 获取最终关键字(返回用 "," 间隔的关键字)
  *
  * @return string
  */
 public function getFinallyKeywords($num = 10)
 {
     $n = 0;
     // 获取索引hash数组
     $arr = [];
     foreach ($this->finallyResult as $v) {
         if ($this->resultType == 2 && ($v['t'] == 3 || $v['t'] == 5)) {
             continue;
         }
         $w = StringTool::encoding($v['w'], $this->targetCharSet);
         if ($w == ' ') {
             continue;
         }
         if (isset($arr[$w])) {
             $arr[$w]++;
         } else {
             $arr[$w] = 1;
         }
     }
     arsort($arr);
     $finallyString = '';
     foreach ($arr as $k => $v) {
         //排除长度为1的词
         if (strlen($k) == 1) {
             continue;
         } elseif (strlen($k) == 2 && preg_match('/[^0-9a-zA-Z]/', $k)) {
             continue;
         } elseif (strlen($k) < 4 && !preg_match('/[a-zA-Z]/', $k)) {
             continue;
         }
         $finallyString .= $finallyString == '' ? $k : ',' . $k;
         $n++;
         if ($n > $num) {
             break;
         }
     }
     return $finallyString;
 }