Ejemplo n.º 1
0
 public function CropCharacter($str = '', $len = 0)
 {
     //set default return
     $return = $str;
     if ($len > 0) {
         $str = trim(strip_tags(html_entity_decode($str, ENT_COMPAT, 'utf-8')));
         $maxlen = mb_strlen($str, 'utf-8');
         if ($maxlen > $len) {
             $isMore = true;
             $tmp = mb_substr($str, 0, $len + 1, 'utf-8');
             $rPos = mb_strrpos($tmp, ' ', 0, 'utf-8');
             if ($rPos === false) {
                 $lPos = mb_strpos($str, ' ', 0, 'utf-8');
                 if ($lPos !== false) {
                     $tmp = mb_substr($str, 0, $lPos, 'utf-8');
                 } else {
                     $tmp = $str;
                     $isMore = false;
                 }
                 //end if
             } elseif ($rPos < $len) {
                 $tmp = mb_substr($tmp, 0, $rPos, 'utf-8');
             }
             //end if
             //set return
             $return = rtrim($tmp) . ($isMore ? $this->iconmore : '');
         }
         //end if
     }
     //end if
     //return
     return $return;
 }
Ejemplo n.º 2
0
Archivo: Tt.php Proyecto: norayrx/otms
 private function getMD5($part)
 {
     if (substr($part, 0, 1) != "/") {
         $filename = mb_substr($part, 0, mb_strlen($part) - mb_strrpos($part, DIRECTORY_SEPARATOR));
         $sql = "SELECT `md5`\r\n\t        FROM fm_fs\r\n\t        WHERE `filename` = :filename AND pdirid = 1\r\n\t        LIMIT 1";
         $res = $this->registry['db']->prepare($sql);
         $param = array(":filename" => $filename);
         $res->execute($param);
         $row = $res->fetchAll(PDO::FETCH_ASSOC);
     } else {
         $filename = mb_substr($part, mb_strrpos($part, DIRECTORY_SEPARATOR) + 1, mb_strlen($part) - mb_strrpos($part, DIRECTORY_SEPARATOR));
         $path = mb_substr($part, 0, mb_strrpos($part, DIRECTORY_SEPARATOR));
         if ($path . "/" == $this->registry["rootPublic"] . $this->registry["path"]["upload"]) {
             $sql = "SELECT `md5`\r\n\t\t        FROM fm_fs\r\n\t\t        WHERE `filename` = :filename AND pdirid = 0\r\n\t\t        LIMIT 1";
             $res = $this->registry['db']->prepare($sql);
             $param = array(":filename" => $filename);
             $res->execute($param);
             $row = $res->fetchAll(PDO::FETCH_ASSOC);
         } else {
             $path = mb_substr($path, mb_strrpos($path, DIRECTORY_SEPARATOR) + 1, mb_strlen($path) - mb_strrpos($path, DIRECTORY_SEPARATOR));
             $sql = "SELECT f.md5\r\n\t\t        FROM fm_fs AS f\r\n\t\t        LEFT JOIN fm_dirs AS d ON (f.pdirid = d.id)\r\n\t\t        WHERE f.filename = :filename AND d.name = :path\r\n\t\t        LIMIT 1";
             $res = $this->registry['db']->prepare($sql);
             $param = array(":filename" => $filename, ":path" => $path);
             $res->execute($param);
             $row = $res->fetchAll(PDO::FETCH_ASSOC);
         }
     }
     return $row[0]["md5"];
 }
 public static function buchnamekapitel($eingabe)
 {
     $singularnamen = array_flip(self::$pluralnamen);
     if (isset($singularnamen[$eingabe])) {
         $eingabe = $singularnamen[$eingabe];
     }
     if (isset(self::$versnummern[$eingabe])) {
         if (count(self::$versnummern[$eingabe]) == 1 && key(self::$versnummern[$eingabe]) === 0) {
             return array($eingabe, 0);
         }
         return array($eingabe, false);
     }
     $spacepos = mb_strrpos($eingabe, ' ');
     if ($spacepos !== false) {
         $buchname = mb_substr($eingabe, 0, $spacepos);
         $kapitel = mb_substr($eingabe, $spacepos + 1);
         if (isset($singularnamen[$buchname])) {
             $buchname = $singularnamen[$buchname];
         }
         if (isset(self::$versnummern[$buchname]) && isset(self::$versnummern[$buchname][$kapitel])) {
             return array($buchname, $kapitel);
         }
     }
     return array(false, false);
 }
Ejemplo n.º 4
0
 /**
  * Generate a fake member account
  *
  * @param   array   $values Generator form values
  * @return  string  Progress message
  */
 public function generateSingle(array $values)
 {
     /* Create Member */
     $member = new \IPS\Member();
     $member->name = $values['__generator_message'] = $this->generator->userName();
     $password = isset($values['password']) ? $member->name : $this->generator->password();
     $member->email = $this->generator->email();
     $member->members_pass_salt = $member->generateSalt();
     $member->members_pass_hash = $member->encryptedPassword($password);
     $member->allow_admin_mails = 0;
     $member->member_group_id = $values['member_group'];
     $member->members_bitoptions['view_sigs'] = TRUE;
     if ($values['profile_photo']) {
         $photoUrl = new \IPS\Http\Url($this->generator->photoUrl());
         $response = $photoUrl->request()->get();
         $filename = preg_replace("/(.+?)(\\?|\$)/", "\$1", mb_substr((string) $photoUrl, mb_strrpos((string) $photoUrl, '/') + 1));
         $photoFile = \IPS\File::create('core_Profile', $filename, $response);
         $member->pp_photo_type = 'custom';
         $member->pp_main_photo = NULL;
         $member->pp_main_photo = (string) $photoFile;
         $thumbnail = $photoFile->thumbnail('core_Profile', \IPS\PHOTO_THUMBNAIL_SIZE, \IPS\PHOTO_THUMBNAIL_SIZE, TRUE);
         $member->pp_thumb_photo = (string) $thumbnail;
     }
     $member->save();
     $this->map(static::$activeRecordClass, $member->member_id);
     return \IPS\Member::loggedIn()->language()->addToStack(static::$message, true, array('sprintf' => array($member->name)));
 }
Ejemplo n.º 5
0
function gelSummary($content, $length = 300)
{
    $filter = array("'<script[^>]*?>.*?</script>'si", "'<img.*?>'i", "'<iframe.*?>.*?<\\/iframe>'si", "'<font.*?>.*?<\\/font>'si", "'<strong.*?>.*?<\\/strong>'i", "'<b.*?>.*?<\\/b>'si", "'<[\\/\\!]*?[^<>]*?>'si", "'([\r\n])[\\s]+'", "'&(quot|#34);'i", "'&(amp|#38);'i", "'&(lt|#60);'i", "'&(gt|#62);'i", "'&(nbsp|#160);'i", "'&(iexcl|#161);'i", "'&(cent|#162);'i", "'&(pound|#163);'i", "'&(copy|#169);'i", "'&#(\\d+);'e", "'(nbsp;|ldquo;|rdquo;|<br>|<br/>|<br /|br/|  |    |/pp|p)'i");
    $endMarks = array('.', '。', ';', ';', '?', '?', '!', '!');
    //去掉头尾空格
    //	$content = strip_tags($content);
    //	$content = trim($content);
    //截取前面total个字符
    //	echo $length.'<hr>';
    //	echo $content.'<hr>';
    //去掉过滤字符
    $content = preg_replace($filter, '', $content);
    //	echo 'filter:'.$content.'<hr>';
    $content = strip_tags($content);
    $summary = mb_substr($content, 0, $length, 'utf-8');
    //	echo '截取length:'.$summary.'<hr>';
    $summary = str_replace(array(' ', '\'', '"', '’', '‘', '“', '”'), '', $summary);
    //	echo '去掉空字符:'.$summary.'<hr>';
    //查找终止字符
    $endPos = 0;
    foreach ($endMarks as $endMark) {
        $endIndex = mb_strrpos($summary, $endMark, 'utf-8');
        $endPos = $endIndex > $endPos ? $endIndex : $endPos;
    }
    $summary = mb_substr($summary, 0, $endPos + 1, 'utf-8');
    $summary = str_replace(' ', '', $summary);
    //	echo '寻找结尾:'.$summary.'<hr>';
    return $summary;
}
Ejemplo n.º 6
0
	/**
	 * Copy an image uploaded with HTML form to the specified directory.
	 * In view scripts one should use something like <img src="{$fileBaseDir}/{@return}"/>
	 *
	 * @param string $paramName Parameter name as it passed by a form.
	 * @param string $fileBaseDir A base directory constant for the file (should be used in view scripts as prefix before $filePath from DB table).
	 * @return string New file's name.
	 * @throws CException 
	 */
	public static function uploadFile($paramName, $fileBaseDir)
	{
		if(empty($_FILES[AutoAdmin::INPUT_PREFIX]['tmp_name'][$paramName]) || !empty($_FILES[AutoAdmin::INPUT_PREFIX]['error'][$paramName]))
			throw new AAException(Yii::t('AutoAdmin.errors', 'An error occured with uploading of the file for field "{field}"', array('{field}'=>$paramName)));
		$uploadedFileName =& $_FILES[AutoAdmin::INPUT_PREFIX]['name'][$paramName];

		$newfname = '';
		$toDir = self::srcToPath($fileBaseDir);
		$newfname = mb_strtolower(mb_substr($uploadedFileName, 0, mb_strrpos($uploadedFileName, '.')));
		$newfname = AAHelperText::translite($newfname);
		$newfname = str_replace(' ', '_', $newfname);
		$newfname = preg_replace('/[^a-z\-\_0-9]/ui', '', $newfname);
		if(mb_strlen($newfname)>60)
			$newfname = mb_substr($newfname, 0, 60);
		$ext = mb_substr(mb_strrchr($uploadedFileName, '.'), 1);
		if(!is_dir($toDir))
		{
			if(!mkdir($toDir, 0777, true))
				throw new AAException(Yii::t('AutoAdmin.errors', 'The directory "{dirname}" cannot be created', array('{dirname}'=>$toDir)));
		}
		while(file_exists($toDir.DIRECTORY_SEPARATOR.$newfname.'.'.$ext))
			$newfname .= '_'.rand(0, 9);
		$newfname .= ".{$ext}";
		if(!copy($_FILES[AutoAdmin::INPUT_PREFIX]['tmp_name'][$paramName], $toDir.DIRECTORY_SEPARATOR.$newfname))
			throw new AAException(Yii::t('AutoAdmin.errors', 'The file ({filename}) cannot be copied', array('{filename}'=>$newfname)));
		return $newfname;
	}
Ejemplo n.º 7
0
 /**
  * Cuts off text of desired length
  * @param string $str Input tect
  * @param int $length Desired length
  * @param bool $respectWords Set true so no words are broken
  * @param bool $noEllipsis true if no ellipsis shall be added
  * @param bool $forceEllipsis True if ellipsis shall be added even if text is shorter then desired
  * @param bool $entityDecode True if an entity decode shall be performed
  * @return string 
  */
 static function Shorten($str, $length = 32, $respectWords = false, $noEllipsis = false, $forceEllipsis = false, $entityDecode = false)
 {
     if ($entityDecode) {
         $str = html_entity_decode($str, ENT_COMPAT, 'utf-8');
     }
     $str = String::Trim(strip_tags($str));
     if (strlen($str) <= $length) {
         if ($forceEllipsis) {
             return self::CorrectSpaces($str) . "...";
         } else {
             return self::CorrectSpaces($str);
         }
     }
     $str = mb_substr($str, 0, $length - 3, 'utf-8');
     if ($respectWords) {
         $pos = mb_strrpos($str, " ", -1, 'utf-8');
         if ($pos > $length / 2) {
             $str = mb_substr($str, 0, $pos, 'utf-8');
         }
     }
     $str = self::CorrectSpaces($str);
     if (!$noEllipsis) {
         $str = $str . "...";
     }
     return $str;
 }
 public function getForMap()
 {
     $pageName = $this->request->getVal('title');
     $oTitle = Title::newFromText($pageName);
     if (empty($oTitle) || !$oTitle->exists()) {
         return array();
     }
     $pageId = $oTitle->getArticleId();
     // TODO: getImages() are not cached
     $imageServing = new ImageServing(array($pageId), 100, array('w' => 1, 'h' => 1));
     $images = $imageServing->getImages(1);
     if (!empty($images[$pageId][0]['url'])) {
         $imageUrl = $images[$pageId][0]['url'];
     } else {
         $imageUrl = '';
     }
     $oArticleService = F::Build('ArticleService');
     $oArticleService->setArticleById($pageId);
     $textSnippet = $oArticleService->getTextSnippet(120);
     $strPos = mb_strrpos($textSnippet, ' ');
     $textSnippet = mb_substr($textSnippet, 0, $strPos);
     $textSnippet .= ' ...';
     $this->setVal('title', $oTitle->getText());
     $this->setVal('imgUrl', $imageUrl);
     $this->setVal('articleUrl', $oTitle->getLocalUrl());
     $this->setVal('textSnippet', $textSnippet);
 }
Ejemplo n.º 9
0
function applyTransforms($s, $transforms)
{
    $copy = $s;
    $positions = array();
    for ($i = count($transforms) - 1; $i >= 0; $i--) {
        $t = $transforms[$i];
        $pos = $t->from == '-' ? mb_strlen($copy) : mb_strrpos($copy, $t->from);
        $positions[$i] = $pos;
        $copy = mb_substr($copy, 0, $pos);
    }
    $result = '';
    for ($i = count($transforms) - 1; $i >= 0; $i--) {
        $t = $transforms[$i];
        $pos = $positions[$i];
        $len = mb_strlen($s);
        $afterFrom = $pos + mb_strlen($t->from);
        if ($len > $afterFrom) {
            $result = mb_substr($s, $afterFrom) . $result;
        }
        $result = $t->to . $result;
        $s = mb_substr($s, 0, $pos);
    }
    $result = $s . $result;
    return $result;
}
Ejemplo n.º 10
0
 /**
  * function strchop
  * DESC: Cuts a string to a given length and will also append a specified
  * string on the end. This method truncates to the nearest blank space to
  * avoid words being chopped. Updated to include multibyte char support
  * and error handline where text has no blank space
  *
  * USAGE EXAMPLE: to truncate a string to near 50 characters and
  * append "..." on the end, strchop($string, 50, "...")
  *
  * @param string $string
  * @param int $truncateLength
  * @param string $endString
  * @return string
  */
 public static function strchop($string, $truncateLength, $endString = false)
 {
     $strlen = mb_strlen($string, "UTF-8");
     // check if string length is over the specified truncate value
     // if it isn't simply return the string
     if ($strlen > $truncateLength) {
         //cut the string
         $cutStr = trim(mb_substr($string, 0, $truncateLength, "UTF-8"));
         //search for last blank space character
         $blankPos = mb_strrpos($cutStr, " ", "UTF-8");
         if (!$blankPos) {
             error_log("no blank pos in string of {$truncateLength} character length: " . __METHOD__);
             return $cutStr . "...";
         }
         //cut string again to this new position
         $cutStr = trim(mb_substr($string, 0, $blankPos, "UTF-8"));
         //append endString if it exists
         if (isset($endString)) {
             $cutStr = $cutStr . $endString;
         }
         return $cutStr;
     } else {
         return $string;
     }
 }
Ejemplo n.º 11
0
/**
 * 文本截断+url链接加上gate.baidu.com前缀,自动处理超链接的截断
 * @param  String  $str    原始内容,其中有a 标签
 * @param  integer $len    截取内容长度
 * @param  integer $urllen url截断显示的长度
 * @return String          截断后的文本
 */
function smarty_modifier_cutcontent($str, $len = 1500, $urllen = 30)
{
    //防止br被切割,先转成\n,截取后再fis_addbr中再转回来
    $str = str_replace("<br />", "\n", $str);
    //parse before cut
    $str = fis_parselink($str, $urllen);
    $lenarray = array('34', '50');
    //no need cut
    if (mb_strlen($str) < $len) {
        return fis_addbr($str);
    }
    $str = mb_substr($str, 0, $len, 'utf-8');
    //find last <a and </a> and check if it is ok
    $pos_of_a = mb_strrpos($str, '<a');
    if ($pos_of_a === false) {
        return fis_addbr($str);
    }
    $pos_of_aend = mb_strrpos($str, '</a>');
    //</a> is after <a>
    if ($pos_of_a < $pos_of_aend) {
        return fis_addbr($str);
    }
    //</a> is not after <a>
    $str = mb_substr($str, 0, $pos_of_a, 'utf-8');
    //$str = fis_addpoint($str);
    return fis_addbr($str);
}
Ejemplo n.º 12
0
 /**
  * Normalizes raw files data for the existing files list composing.
  * @param array $rawFiles raw files to process.
  * @return array normalized files data
  * @throws CException on failure.
  */
 protected function normalizeFiles(array $rawFiles)
 {
     $currentRoute = Yii::app()->getController()->getRoute();
     $pos = mb_strrpos($currentRoute, '/');
     if ($pos !== false) {
         $baseRoute = mb_substr($currentRoute, 0, $pos);
     } else {
         $baseRoute = $currentRoute;
     }
     $normalizedFiles = array();
     foreach ($rawFiles as $rawFile) {
         if (is_object($rawFile)) {
             $normalizedFile = array('id' => $rawFile->id, 'name' => $rawFile->name);
         } elseif (is_array($rawFile)) {
             $normalizedFile = $rawFile;
         } else {
             throw new CException('File should either array or object!');
         }
         if (empty($normalizedFile['downloadUrl'])) {
             $normalizedFile['downloadUrl'] = Yii::app()->createUrl($this->baseDownloadUrl, array('id' => $normalizedFile['id']));
         }
         if (empty($normalizedFile['deleteUrl'])) {
             $normalizedFile['deleteUrl'] = Yii::app()->createUrl($this->baseDeleteUrl, array('id' => $normalizedFile['id']));
         }
         $normalizedFiles[] = $normalizedFile;
     }
     return $normalizedFiles;
 }
 /**
  * Returns the extension of the original file name.
  * 
  * @return	string
  */
 public function getFileExtension()
 {
     if (($position = mb_strrpos($this->filename, '.')) !== false) {
         return mb_strtolower(mb_substr($this->filename, $position + 1));
     }
     return '';
 }
Ejemplo n.º 14
0
	function copyImage($var, $uploadDir='/i/other')
	{
		$newFileName = '';
		$newFileName = mb_strtolower(mb_substr($_FILES[$var]['name'], 0, mb_strrpos($_FILES[$var]['name'], '.')));
		$newFileName = AAHelperText::translite($newFileName);
		$newFileName = str_replace(' ', '_', $newFileName);
		$newFileName = preg_replace('/[^a-z\-\_0-9]/ui', '', $newFileName);
		if(mb_strlen($newFileName)>60)
			$newFileName = mb_substr($newFileName, 0, 60);
		$ext = mb_strrchr($_FILES[$var]['name'], '.');
		$newFileName .= $ext;
		$fileLinkDir = $uploadDir;
		$targetPath = Yii::app()->basePath.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.Yii::app()->modules['autoadmin']['wwwDirName'].str_replace('/', DIRECTORY_SEPARATOR, $uploadDir);
		if(!is_dir($targetPath))
		{
			if(!mkdir($targetPath))
				throw new CHttpException(406, "Указанная в настройках директория [{$fileLinkDir}] не существует и не может быть создана.");
		}
		$targetPath .= DIRECTORY_SEPARATOR.$newFileName;
		if(!copy($_FILES[$var]['tmp_name'], $targetPath))
			throw new CHttpException(406, "Файл невозможно сохранить в указанной в настройках директории [{$fileLinkDir}]. Вероятнее всего, проблемы с правами.");
		if(!getimagesize($targetPath))
		{
			throw new CHttpException(406, "Загружаемый файл не является изображением допустимого формата.");
		}
		return $fileLinkDir.'/'.$newFileName;
	}
 /**
  * @covers Patchwork\PHP\Override\Mbstring::mb_strpos
  * @covers Patchwork\PHP\Override\Mbstring::mb_stripos
  * @covers Patchwork\PHP\Override\Mbstring::mb_strrpos
  * @covers Patchwork\PHP\Override\Mbstring::mb_strripos
  */
 function testmb_strpos()
 {
     $this->assertSame(false, @mb_strpos('abc', ''));
     $this->assertSame(false, @mb_strpos('abc', 'a', -1));
     $this->assertSame(false, mb_strpos('abc', 'd'));
     $this->assertSame(false, mb_strpos('abc', 'a', 3));
     $this->assertSame(1, mb_strpos('한국어', '국'));
     $this->assertSame(3, mb_stripos('DÉJÀ', 'à'));
     $this->assertSame(false, mb_strrpos('한국어', ''));
     $this->assertSame(1, mb_strrpos('한국어', '국'));
     $this->assertSame(3, mb_strripos('DÉJÀ', 'à'));
     $this->assertSame(1, mb_stripos('aςσb', 'ΣΣ'));
     $this->assertSame(1, mb_strripos('aςσb', 'ΣΣ'));
     $this->assertSame(false, @p::mb_strpos('abc', ''));
     $this->assertSame(false, @p::mb_strpos('abc', 'a', -1));
     $this->assertSame(false, p::mb_strpos('abc', 'd'));
     $this->assertSame(false, p::mb_strpos('abc', 'a', 3));
     $this->assertSame(1, p::mb_strpos('한국어', '국'));
     $this->assertSame(3, p::mb_stripos('DÉJÀ', 'à'));
     $this->assertSame(false, p::mb_strrpos('한국어', ''));
     $this->assertSame(1, p::mb_strrpos('한국어', '국'));
     $this->assertSame(3, p::mb_strripos('DÉJÀ', 'à'));
     $this->assertSame(1, p::mb_stripos('aςσb', 'ΣΣ'));
     $this->assertSame(1, p::mb_strripos('aςσb', 'ΣΣ'));
 }
Ejemplo n.º 16
0
 public static function lastIndexOf($haystack, $needle, $offset = 0)
 {
     if (String::$multibyte) {
         return mb_strrpos($haystack, $needle, $offset, String::$multibyte_encoding);
     }
     return strrpos($haystack, $needle, $offset);
 }
Ejemplo n.º 17
0
 /** \brief Generate abstract from body text.
     \zfb_read FeedItem..generateAbstract */
 public function generateAbstract($check = false)
 {
     if ($check && $this->abstract != '') {
         return $this;
     }
     $length = $this->_autoAbstractLength;
     $text = strip_tags($this->text);
     if (mb_strlen($text) < $length) {
         $this->abstract = $text;
         return $this;
     }
     $minLenght = $length / 4;
     $abstract = mb_substr($text, 0, $length);
     $split = mb_split('[.!?]', $abstract);
     $splitCnt = count($split);
     $tail = $split[$splitCnt - 1];
     $tailLen = mb_strlen($tail);
     if ($splitCnt == 1 || $tailLen > $length - $minLenght) {
         $abstract = mb_substr($abstract, 0, mb_strrpos($abstract, ' '));
         $abstract .= $this->_autoAbstractDots;
     } else {
         $abstract = mb_substr($abstract, 0, $length - $tailLen);
     }
     $this->abstract = $abstract;
     return $this;
 }
Ejemplo n.º 18
0
function utf8_strrpos($str, $search, $offset = FALSE)
{
    if ($offset === FALSE) {
        # Emulate behaviour of strrpos rather than raising warning
        if (empty($str)) {
            return FALSE;
        }
        if (function_exists('mb_strrpos')) {
            return mb_strrpos($str, $search);
        } else {
            return strrpos($str, $search);
        }
    } else {
        if (!is_int($offset)) {
            trigger_error('utf8_strrpos expects parameter 3 to be long', E_USER_WARNING);
            return FALSE;
        }
        if (function_exists('mb_substr')) {
            $str = mb_substr($str, $offset);
        } else {
            $str = substr($str, $offset);
        }
        if (function_exists('mb_strrpos')) {
            $pos = mb_strrpos($str, $search);
        } else {
            $pos = strrpos($str, $search);
        }
        if (FALSE !== $pos) {
            return $pos + $offset;
        }
        return FALSE;
    }
}
Ejemplo n.º 19
0
Archivo: Html.php Proyecto: bolt/bolt
 /**
  * Trim text to a given length.
  *
  * @param string $str           String to trim
  * @param int    $desiredLength Target string length
  * @param bool   $hellip        Add dots when the string is too long
  * @param int    $cutOffCap     Maximum difference between string length when removing words
  *
  * @return string Trimmed string
  */
 public static function trimText($str, $desiredLength, $hellip = true, $cutOffCap = 10)
 {
     if ($hellip) {
         $ellipseStr = ' …';
         $newLength = $desiredLength - 1;
     } else {
         $ellipseStr = '';
         $newLength = $desiredLength;
     }
     $str = trim(strip_tags($str));
     if (mb_strlen($str) > $desiredLength) {
         $nextChar = mb_substr($str, $newLength, 1);
         $str = mb_substr($str, 0, $newLength);
         if ($nextChar != ' ') {
             if (false !== ($lastSpace = mb_strrpos($str, ' '))) {
                 // Check for to long cutoff
                 if (mb_strlen($str) - $lastSpace >= $cutOffCap) {
                     // Trim the ellipse, as we do not want a space now
                     return $str . trim($ellipseStr);
                 }
                 $str = mb_substr($str, 0, $lastSpace);
             }
         }
         $str .= $ellipseStr;
     }
     return $str;
 }
Ejemplo n.º 20
0
 /**
  * Put or change data of cache item
  *
  * @param string	$item	May contain "/" symbols for cache structure, for example users/<i>user_id</i>
  * @param mixed		$data
  *
  * @return bool
  */
 function set($item, $data)
 {
     $data = @_json_encode($data);
     if (mb_strpos($item, '/') !== false) {
         $path = mb_substr($item, 0, mb_strrpos($item, '/'));
         if (!is_dir(CACHE . "/{$path}")) {
             @mkdir(CACHE . "/{$path}", 0700, true);
         }
         unset($path);
     }
     if (!file_exists(CACHE . "/{$item}") || is_writable(CACHE . "/{$item}")) {
         if ($this->cache_size > 0) {
             $dsize = strlen($data);
             if ($dsize > $this->cache_size) {
                 return false;
             }
             if (file_exists(CACHE . "/{$item}")) {
                 $dsize -= filesize(CACHE . "/{$item}");
             }
             $cache_size_file = fopen(CACHE . '/size', 'c+b');
             $time = microtime(true);
             while (!flock($cache_size_file, LOCK_EX | LOCK_NB)) {
                 if ($time < microtime(true) - 0.5) {
                     fclose($cache_size_file);
                     return false;
                 }
                 usleep(1000);
             }
             unset($time);
             $cache_size = (int) stream_get_contents($cache_size_file);
             $cache_size += $dsize;
             if ($cache_size > $this->cache_size) {
                 $cache_list = get_files_list(CACHE, false, 'f', true, true, 'date|desc');
                 foreach ($cache_list as $file) {
                     $cache_size -= filesize($file);
                     unlink($file);
                     $disk_size = $this->cache_size * 2 / 3;
                     if ($cache_size <= $disk_size * Config::instance()->core['update_ratio'] / 100) {
                         break;
                     }
                 }
                 unset($cache_list, $file);
             }
             if (($return = file_put_contents(CACHE . "/{$item}", $data, LOCK_EX | FILE_BINARY)) !== false) {
                 ftruncate($cache_size_file, 0);
                 fseek($cache_size_file, 0);
                 fwrite($cache_size_file, $cache_size > 0 ? $cache_size : 0);
             }
             flock($cache_size_file, LOCK_UN);
             fclose($cache_size_file);
             return $return;
         } else {
             return file_put_contents(CACHE . "/{$item}", $data, LOCK_EX | FILE_BINARY);
         }
     } else {
         $L = Language::instance();
         trigger_error($L->file . ' ' . CACHE . "/{$item} {$L->not_writable}", E_USER_WARNING);
         return false;
     }
 }
Ejemplo n.º 21
0
function essb_ctt_shorten($input, $length, $ellipsis = true, $strip_html = true)
{
    if ($strip_html) {
        $input = strip_tags($input);
    }
    /*
     * Checks to see if the mbstring php extension is loaded, for optimal
     * truncation. If it's not, it bails and counts the characters based on
     * utf-8. What this means for users is that non-Roman characters will only
     * be counted correctly if that extension is loaded. Contact your server
     * admin to enable the extension.
     */
    if (function_exists('mb_internal_encoding')) {
        if (mb_strlen($input) <= $length) {
            return $input;
        }
        $last_space = mb_strrpos(mb_substr($input, 0, $length), ' ');
        $trimmed_text = mb_substr($input, 0, $last_space);
        if ($ellipsis) {
            $trimmed_text .= '…';
        }
        return $trimmed_text;
    } else {
        if (strlen($input) <= $length) {
            return $input;
        }
        $last_space = strrpos(substr($input, 0, $length), ' ');
        $trimmed_text = substr($input, 0, $last_space);
        if ($ellipsis) {
            $trimmed_text .= '…';
        }
        return $trimmed_text;
    }
}
Ejemplo n.º 22
0
 protected function validateIdentical($input)
 {
     if (is_array($input)) {
         return end($input) === $this->endValue;
     }
     return mb_strrpos($input, $this->endValue, 0, $enc = mb_detect_encoding($input)) === mb_strlen($input, $enc) - mb_strlen($this->endValue, $enc);
 }
Ejemplo n.º 23
0
 public function hot()
 {
     $art = M('article');
     //将所有类型为看一看的查出来查出最新更新的五条
     $arts = $art->where("cid=6")->order('create_time desc')->limit(0, 5)->select();
     //查询出最新更新的标签为电影的三个文章
     $num = $art->where("cid=6 and tags=11")->order('create_time desc')->limit(0, 3)->select();
     //截取文章中指定内容
     foreach ($num as $k => $v) {
         $num[$k]['con'] = mb_substr($v['con'], strpos($v['con'], '<p><span'), mb_strrpos($v['con'], '<strong>', 'utf-8'));
     }
     //查询标枪tags值在数组中的信息每个标签最多10条
     $arr = array(5, 6, 7, 8, 11);
     foreach ($arr as $k => $v) {
         $rank[] = $art->where("cid=6 and tags={$v}")->limit(4)->select();
     }
     //查询tags表
     $tag = M('article_tags');
     $tags = $tag->select();
     //遍历标签
     foreach ($tags as $s) {
         $t[$s['id']] = $s['tag'];
     }
     $this->assign('t', $t);
     $this->assign('rank', $rank);
     $this->assign('arts', $arts);
     $this->assign('num', $num);
     $this->display();
 }
Ejemplo n.º 24
0
function utf8_excerpt($text, $chars, $balance_tags = true, $middle = false)
{
    $len = mb_strlen($text);
    if ($len > $chars) {
        $text = $text . " ";
        if ($middle) {
            $start = (int) ($len - $chars) / 2;
        } else {
            $start = 0;
        }
        $text = mb_substr($text, $start, $chars);
        $last_space = mb_strrpos($text, ' ');
        if ($last_space !== false) {
            $text = mb_substr($text, 0, $last_space);
        }
        if ($middle) {
            $first_space = mb_strpos($text, ' ');
            if ($first_space !== false) {
                $text = mb_substr($text, $first_space);
            }
        }
        if ($balance_tags) {
            $text = balance_tags($text);
        }
        $text = preg_replace("/^[^a-zA-Z0-9]+/", "", $text);
        return $text . ' …';
    }
    return $text;
}
 protected function cleanup()
 {
     parent::cleanup();
     $start = mb_strpos($this->data, $this->partToken) + mb_strlen($this->partToken);
     $end = mb_strrpos($this->data, $this->partToken);
     $this->data = mb_substr($this->data, $start, $end - $start);
 }
Ejemplo n.º 26
0
function set_root()
{
    $b = $_SERVER['REQUEST_URI'];
    $b = substr($b, 0, mb_strrpos($b, "/core/") + 6);
    $root = $_SERVER['DOCUMENT_ROOT'] . $b;
    return $root;
}
Ejemplo n.º 27
0
 protected function parseListOutputLine($line)
 {
     $pieces = explode(': ', $line);
     $lastSpacePos = mb_strrpos($pieces[1], ' ');
     $branch = mb_substr($pieces[1], $lastSpacePos + 1);
     $message = isset($pieces[2]) ? $pieces[2] : null;
     return new \DialoGit\GitStructure\Stash($pieces[0], $branch, $message);
 }
Ejemplo n.º 28
0
 /**
  * LastIndexOf
  */
 public function execute()
 {
     if ($this->isCaseInsensitive()) {
         return mb_strripos($this->getValue(), $this->needle, $this->fromIndex);
     } else {
         return mb_strrpos($this->getValue(), $this->needle, $this->fromIndex);
     }
 }
Ejemplo n.º 29
0
function getClassName($namespaceClass)
{
    $lastSlashPosition = mb_strrpos($namespaceClass, '\\');
    if ($lastSlashPosition !== false) {
        return mb_substr($namespaceClass, $lastSlashPosition + 1);
    }
    return $namespaceClass;
}
Ejemplo n.º 30
0
function twig_extension_filter($value, $case_insensitive = true)
{
    $ext = mb_substr($value, mb_strrpos($value, '.') + 1);
    if ($case_insensitive) {
        $ext = mb_strtolower($ext);
    }
    return $ext;
}