Exemplo n.º 1
0
/**
 * Выбирает из строки подстроку, принимая в исходной строке все совпадения по заданному шаблону за N символов.
 * Пример: substr_quasi('ABC"D EF', 4, 3) вернет 'D E'
 *
 * @param $str          string    исходная строка.
 * @param $offset       integer   >=0, начальная позиция (отсчет позиции с учетом N).
 * @param $len          integer   false|>0, длина подстроки (с учетом N). Если false, то от $offset до конца исходной строки.
 * @param $quasi_len    integer   возвращает количество символов в получившейся подстроке с учетом N. Может
 *                                понадобится, если $len неизвестно (false).
 * @param $exact_len    integer   возвращает реальную длину получившейся подстроки (то же, что strlen).
 * @param $symbols_cnt  integer   N -- за сколько символов считать шаблон.
 * @param $pattern      string    шаблон, совпадения по которому считать за N символов. По умолчанию, HTML-сущность.
 * @return $string                подстрока.
 */
function substr_quasi($str, $offset, $len = false, &$quasi_len = 0, &$exact_len = 0, $symbols_cnt = 1, $pattern = '/&(?:[a-z]{2,6}|#(?:\\d{2,4}|x[\\da-f]{2,4}));/i')
{
    $sub = '';
    if ($offset > 0) {
        substr_quasi($str, 0, $offset, $u, $olen, $symbols_cnt, $pattern);
        $str = substr($str, $olen);
    }
    if ($len === false) {
        $len = strlen($str);
    }
    if ($len > 0) {
        $parts = preg_split($pattern, $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
        foreach ($parts as $p) {
            if ($p[1]) {
                if (($xl = $quasi_len + $symbols_cnt) > $len) {
                    break;
                }
                $sub .= substr($str, $exact_len, $p[1] - $exact_len);
                $quasi_len = $xl;
                $exact_len = $p[1];
            }
            $quasi_len += $xl = strlen($p[0]);
            $exact_len += $xl;
            if (($ex = $quasi_len - $len) >= 0) {
                $exact_len -= $ex;
                $quasi_len -= $ex;
                $sub .= substr($p[0], 0, $xl - $ex);
                break;
            }
            $sub .= $p[0];
        }
    }
    return $sub;
}
Exemplo n.º 2
0
 /**
  * Возвращает все непрочитанные сообщения пользователя.
  *
  * @see messages::getNewMessages()
  * 
  * @return array
  */
 protected function x____getNewMessages()
 {
     require_once ABS_PATH . '/classes/messages.php';
     $uid = $this->_sess->_uid;
     $messages = new messages();
     if ($msgs = $messages->getNewMessages($uid)) {
         foreach ($msgs as $key => $m) {
             $m['msg_text'] = preg_replace('/%USER_NAME%/', $this->_sess->uname, $m['msg_text']);
             $m['msg_text'] = preg_replace('/%USER_SURNAME%/', $this->_sess->usurname, $m['msg_text']);
             $m['msg_text'] = preg_replace('/%USER_LOGIN%/', $this->_sess->login, $m['msg_text']);
             $row = $this->pg2exRow($this->_mCfg['fields'], $m);
             if ($this->_mCfg['msg_text_length'] > 0) {
                 $row['msg_text'] = substr_quasi($row['msg_text'], 0, $this->_mCfg['msg_text_length']);
             }
             $result[$key] = $row;
         }
     }
     return $result;
 }
Exemplo n.º 3
0
/**
 * Вспомогательная callback-функция для обрамления URI тегами <a>.
 * Убирает с конца ссылки "лишние" символы, обрезает текст с добавлением в конец '...'.
 * Если это внутренний адрес сервиса или переменная $_SESSION['direct_external_links'] установлена,
 * то ссылка прямая, иначе в href формируется адрес промежуточной страницы.
 * Обрабатывает компонент гипер-ссылки.
 * @see reformat()
 *
 * @param $matches         array     массив компонентов исходного адреса.
 * @return string                    тег <a> с заключенным в него адресом.
 */
function reformat_callback($matches)
{
    static $host;
    $max_link_len = $GLOBALS['reformat.max_link_len'];
    $can_hyper = $GLOBALS['reformat.can_hyper'];
    if ($matches[1] == "https://") {
        $http = "https://";
    } else {
        $http = "http://";
    }
    if (!$host) {
        $host = preg_quote(preg_replace('~^(http://|https://)?(www\\.)?~', '', $GLOBALS['host']), '/');
    }
    preg_match('/^(.*?)((?:&lt;|&quot;|&#039|[,.!<])*)$/i', $matches[4], $x);
    // обязательно точки убираем, чтобы '...' от тега <cut> не попали в ссылку.
    $www = $matches[1] == 'www.' ? 'www.' . $x[1] : $x[1];
    $end = $x[2];
    $classCut = "";
    if ($can_hyper) {
        $hyper = $matches[3];
    }
    // если была передана ссылка в теге <a>, то $text берем из нее
    if (preg_match('~^<a[^>]*>(.+?)</a>$~i', $matches[0], $textMatch)) {
        $text = $textMatch[1];
        if (strlen(strip_tags($text)) >= $max_link_len) {
            //                close_tags($text , 's,i,b,h1,h2,h3,h4,h5,h6,strong,strike,em', $max_link_len);
            //                $text .= "...";
            $classCut = "b-post__link_width_200";
        }
    } elseif ($hyper) {
        $text = $hyper;
    } else {
        $links = $GLOBALS[LINK_INSTANCE_NAME];
        if ($links && $links instanceof links) {
            if (preg_match('/^(www\\.)?' . $host . '/i', $www)) {
                $link = $links->save_find($matches, $is_found, $max_link_len);
                if ($is_found) {
                    return $link;
                }
            }
        }
        $text = substr_quasi($www, 0, $max_link_len, $qlen, $tlen);
        if ($qlen >= $max_link_len && strlen($www) > $tlen) {
            $text .= '...';
            $end = preg_replace('/^\\.{1,3}(?!\\.)/', '', $end);
        }
        $text = str_replace(array('<', '>'), array('&lt;', '&gt;'), $text);
    }
    $bNoAphp = $_SESSION['uid'] ? $_SESSION['direct_external_links'] == 1 : $_COOKIE['no_a_php'] == 1;
    if (preg_match('/^([a-z\\d-]+\\.)*' . $host . '/i', $www, $domain) || $GLOBALS['PDA'] || $hyper || $bNoAphp) {
        $img = '';
        $link = '<noindex><a href="' . ($domain[0] ? HTTP_PREFIX : $http) . $www . '" rel="nofollow" title="' . $http . $www . '" class="b-post__link  ' . $classCut . '" target="_blank">' . $text . '</a></noindex>' . $end;
        if ($GLOBALS['PDA']) {
            if ($domain[0]) {
                // в рамках основного домена
                if (strtolower($domain[1]) != 'p.') {
                    // любой поддомен кроме pda
                    $img = '<a href="' . $http . $www . '" target="_blank"><img src="/images/lnk.png" width="16" height="16" alt="" /></a>';
                }
            } else {
                // куда-то на сторону
                $img = '<a href="' . $http . $www . '" target="_blank"><img src="/images/out_lnk.png" width="16" height="16" alt="" /></a>';
            }
        }
        return $img . $link;
    }
    preg_match('@^(?:http://)?([^/\\?]+)@i', $www, $matches);
    $thost = $matches[1];
    preg_match('/[^.]+\\.[^.]+$/', $thost, $matches);
    if ($GLOBALS['disable_link_processing'] || in_array($matches[0], $GLOBALS['white_list'])) {
        // есть в белом списке - даем прямую ссылку
        $sOut = '<noindex><a href="' . $http . htmlspecialchars_decode($www) . '" class="b-post__link b-post__link_ellipsis ' . $classCut . '" target="_blank" rel="nofollow" title="' . $http . $www . '">' . $text . '</a></noindex>' . $end;
    } else {
        // куда-то на сторону - заворачиваем на a.php
        $scheme = is_https() ? "https" : "http";
        // временный хак, пока не переехали на новый домен
        $hs = $scheme . '://' . preg_replace("/https?:\\/\\//i", '', str_replace('old.www.fl.ru', 'www.fl.ru', $GLOBALS['host']));
        $sOut = '<noindex><a href="' . $hs . '/a.php?href=' . urlencode($http . htmlspecialchars_decode($www)) . '" class="b-post__link b-post__link_ellipsis ' . $classCut . '" target="_blank" rel="nofollow" title="' . $http . $www . '">' . $text . '</a></noindex>' . $end;
    }
    return $sOut;
}