Guest User

Untitled

a guest
Jan 17th, 2012
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 29.61 KB | None | 0 0
  1. <?php
  2. /*
  3. * SAPE.ru -- Интеллектуальная система купли-продажи ссылок
  4. *
  5. * PHP-клиент, версия 1.0.7 от 16.02.2010
  6. *
  7. * По всем вопросам обращайтесь на [email protected]
  8. *
  9. * Вебмастеры! Не нужно ничего менять в этом файле! Все настройки - через параметры при вызове кода.
  10. * Читайте: http://help.sape.ru/
  11. *
  12. */
  13.  
  14. // Основной класс, выполняющий всю рутину
  15. class SAPE_base {
  16.  
  17. var $_version = '1.0.7';
  18.  
  19. var $_verbose = false;
  20.  
  21. var $_charset = ''; // http://www.php.net/manual/en/function.iconv.php
  22.  
  23. var $_sape_charset = '';
  24.  
  25. var $_server_list = array('dispenser-01.sape.ru', 'dispenser-02.sape.ru');
  26.  
  27. var $_cache_lifetime = 3600; // Пожалейте наш сервер :о)
  28.  
  29. // Если скачать базу ссылок не удалось, то следующая попытка будет через столько секунд
  30. var $_cache_reloadtime = 600;
  31.  
  32. var $_error = '';
  33.  
  34. var $_host = '';
  35.  
  36. var $_request_uri = '';
  37.  
  38. var $_multi_site = false;
  39.  
  40. var $_fetch_remote_type = ''; // Способ подключения к удалённому серверу [file_get_contents|curl|socket]
  41.  
  42. var $_socket_timeout = 6; // Сколько ждать ответа
  43.  
  44. var $_force_show_code = false;
  45.  
  46. var $_is_our_bot = false; // Если наш робот
  47.  
  48. var $_debug = false;
  49.  
  50. var $_db_file = ''; // Путь к файлу с данными
  51.  
  52. function SAPE_base($options = null) {
  53.  
  54. // Поехали :o)
  55.  
  56. $host = '';
  57.  
  58. if (is_array($options)) {
  59. if (isset($options['host'])) {
  60. $host = $options['host'];
  61. }
  62. } elseif (strlen($options)) {
  63. $host = $options;
  64. $options = array();
  65. } else {
  66. $options = array();
  67. }
  68.  
  69. // Какой сайт?
  70. if (strlen($host)) {
  71. $this->_host = $host;
  72. } else {
  73. $this->_host = $_SERVER['HTTP_HOST'];
  74. }
  75.  
  76. $this->_host = preg_replace('/^http:\/\//', '', $this->_host);
  77. $this->_host = preg_replace('/^www\./', '', $this->_host);
  78.  
  79. // Какая страница?
  80. if (isset($options['request_uri']) && strlen($options['request_uri'])) {
  81. $this->_request_uri = $options['request_uri'];
  82. } else {
  83. $this->_request_uri = $_SERVER['REQUEST_URI'];
  84. }
  85.  
  86. // На случай, если хочется много сайтов в одной папке
  87. if (isset($options['multi_site']) && $options['multi_site'] == true) {
  88. $this->_multi_site = true;
  89. }
  90.  
  91. // Сообщать об ошибках
  92. if (isset($options['verbose']) && $options['verbose'] == true) {
  93. $this->_verbose = true;
  94. }
  95.  
  96. // Кодировка
  97. if (isset($options['charset']) && strlen($options['charset'])) {
  98. $this->_charset = $options['charset'];
  99. } else {
  100. $this->_charset = 'windows-1251';
  101. }
  102.  
  103. if (isset($options['fetch_remote_type']) && strlen($options['fetch_remote_type'])) {
  104. $this->_fetch_remote_type = $options['fetch_remote_type'];
  105. }
  106.  
  107. if (isset($options['socket_timeout']) && is_numeric($options['socket_timeout']) && $options['socket_timeout'] > 0) {
  108. $this->_socket_timeout = $options['socket_timeout'];
  109. }
  110.  
  111. // Всегда выводить чек-код
  112. if (isset($options['force_show_code']) && $options['force_show_code'] == true) {
  113. $this->_force_show_code = true;
  114. }
  115.  
  116. // Выводить информацию о дебаге
  117. if (isset($options['debug']) && $options['debug'] == true) {
  118. $this->_debug = true;
  119. }
  120.  
  121. if (!defined('_SAPE_USER')) {
  122. return $this->raise_error('Не задана константа _SAPE_USER');
  123. }
  124.  
  125. // Определяем наш ли робот
  126. if (isset($_COOKIE['sape_cookie']) && ($_COOKIE['sape_cookie'] == _SAPE_USER)) {
  127. $this->_is_our_bot = true;
  128. if (isset($_COOKIE['sape_debug']) && ($_COOKIE['sape_debug'] == 1)){
  129. $this->_debug = true;
  130. }
  131. } else {
  132. $this->_is_our_bot = false;
  133. }
  134. }
  135.  
  136.  
  137. /*
  138. * Функция для подключения к удалённому серверу
  139. */
  140. function fetch_remote_file($host, $path) {
  141.  
  142. $user_agent = $this->_user_agent.' '.$this->_version;
  143.  
  144. @ini_set('allow_url_fopen', 1);
  145. @ini_set('default_socket_timeout', $this->_socket_timeout);
  146. @ini_set('user_agent', $user_agent);
  147. if (
  148. $this->_fetch_remote_type == 'file_get_contents'
  149. ||
  150. (
  151. $this->_fetch_remote_type == ''
  152. &&
  153. function_exists('file_get_contents')
  154. &&
  155. ini_get('allow_url_fopen') == 1
  156. )
  157. ) {
  158. $this->_fetch_remote_type = 'file_get_contents';
  159. if ($data = @file_get_contents('http://' . $host . $path)) {
  160. return $data;
  161. }
  162.  
  163. } elseif (
  164. $this->_fetch_remote_type == 'curl'
  165. ||
  166. (
  167. $this->_fetch_remote_type == ''
  168. &&
  169. function_exists('curl_init')
  170. )
  171. ) {
  172. $this->_fetch_remote_type = 'curl';
  173. if ($ch = @curl_init()) {
  174.  
  175. @curl_setopt($ch, CURLOPT_URL, 'http://' . $host . $path);
  176. @curl_setopt($ch, CURLOPT_HEADER, false);
  177. @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  178. @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->_socket_timeout);
  179. @curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
  180.  
  181. if ($data = @curl_exec($ch)) {
  182. return $data;
  183. }
  184.  
  185. @curl_close($ch);
  186. }
  187.  
  188. } else {
  189. $this->_fetch_remote_type = 'socket';
  190. $buff = '';
  191. $fp = @fsockopen($host, 80, $errno, $errstr, $this->_socket_timeout);
  192. if ($fp) {
  193. @fputs($fp, "GET {$path} HTTP/1.0\r\nHost: {$host}\r\n");
  194. @fputs($fp, "User-Agent: {$user_agent}\r\n\r\n");
  195. while (!@feof($fp)) {
  196. $buff .= @fgets($fp, 128);
  197. }
  198. @fclose($fp);
  199.  
  200. $page = explode("\r\n\r\n", $buff);
  201.  
  202. return $page[1];
  203. }
  204.  
  205. }
  206.  
  207. return $this->raise_error('Не могу подключиться к серверу: ' . $host . $path.', type: '.$this->_fetch_remote_type);
  208. }
  209.  
  210. /*
  211. * Функция чтения из локального файла
  212. */
  213. function _read($filename) {
  214.  
  215. $fp = @fopen($filename, 'rb');
  216. @flock($fp, LOCK_SH);
  217. if ($fp) {
  218. clearstatcache();
  219. $length = @filesize($filename);
  220. $mqr = @get_magic_quotes_runtime();
  221. @set_magic_quotes_runtime(0);
  222. if ($length) {
  223. $data = @fread($fp, $length);
  224. } else {
  225. $data = '';
  226. }
  227. @set_magic_quotes_runtime($mqr);
  228. @flock($fp, LOCK_UN);
  229. @fclose($fp);
  230.  
  231. return $data;
  232. }
  233.  
  234. return $this->raise_error('Не могу считать данные из файла: ' . $filename);
  235. }
  236.  
  237. /*
  238. * Функция записи в локальный файл
  239. */
  240. function _write($filename, $data) {
  241.  
  242. $fp = @fopen($filename, 'ab');
  243. if ($fp) {
  244. if (flock($fp, LOCK_EX|LOCK_NB)) {
  245. $length = strlen($data);
  246. ftruncate($fp, 0);
  247. @fwrite($fp, $data, $length);
  248. @flock($fp, LOCK_UN);
  249. @fclose($fp);
  250.  
  251. if (md5($this->_read($filename)) != md5($data)) {
  252. @unlink($filename);
  253. return $this->raise_error('Нарушена целостность данных при записи в файл: ' . $filename);
  254. }
  255. } else {
  256. return false;
  257. }
  258.  
  259. return true;
  260. }
  261.  
  262. return $this->raise_error('Не могу записать данные в файл: ' . $filename);
  263. }
  264.  
  265. /*
  266. * Функция обработки ошибок
  267. */
  268. function raise_error($e) {
  269.  
  270. $this->_error = '<p style="color: red; font-weight: bold;">SAPE ERROR: ' . $e . '</p>';
  271.  
  272. if ($this->_verbose == true) {
  273. print $this->_error;
  274. }
  275.  
  276. return false;
  277. }
  278.  
  279. function load_data() {
  280. $this->_db_file = $this->_get_db_file();
  281.  
  282. if (!is_file($this->_db_file)) {
  283. // Пытаемся создать файл.
  284. if (@touch($this->_db_file)) {
  285. @chmod($this->_db_file, 0666); // Права доступа
  286. } else {
  287. return $this->raise_error('Нет файла ' . $this->_db_file . '. Создать не удалось. Выставите права 777 на папку.');
  288. }
  289. }
  290.  
  291. if (!is_writable($this->_db_file)) {
  292. return $this->raise_error('Нет доступа на запись к файлу: ' . $this->_db_file . '! Выставите права 777 на папку.');
  293. }
  294.  
  295. @clearstatcache();
  296.  
  297. $data = $this->_read($this->_db_file);
  298. if (
  299. !$this->_is_our_bot
  300. &&
  301. (
  302. filemtime($this->_db_file) < (time()-$this->_cache_lifetime)
  303. ||
  304. filesize($this->_db_file) == 0
  305. ||
  306. @unserialize($data) == false
  307. )
  308. ) {
  309. // Чтобы не повесить площадку клиента и чтобы не было одновременных запросов
  310. @touch($this->_db_file, (time() - $this->_cache_lifetime + $this->_cache_reloadtime));
  311.  
  312. $path = $this->_get_dispenser_path();
  313. if (strlen($this->_charset)) {
  314. $path .= '&charset=' . $this->_charset;
  315. }
  316.  
  317. foreach ($this->_server_list as $i => $server){
  318. if ($data = $this->fetch_remote_file($server, $path)) {
  319. if (substr($data, 0, 12) == 'FATAL ERROR:') {
  320. $this->raise_error($data);
  321. } else {
  322. // [псевдо]проверка целостности:
  323. $hash = @unserialize($data);
  324. if ($hash != false) {
  325. // попытаемся записать кодировку в кеш
  326. $hash['__sape_charset__'] = $this->_charset;
  327. $hash['__last_update__'] = time();
  328. $hash['__multi_site__'] = $this->_multi_site;
  329. $hash['__fetch_remote_type__'] = $this->_fetch_remote_type;
  330. $hash['__php_version__'] = phpversion();
  331. $hash['__server_software__'] = $_SERVER['SERVER_SOFTWARE'];
  332.  
  333. $data_new = @serialize($hash);
  334. if ($data_new) {
  335. $data = $data_new;
  336. }
  337.  
  338. $this->_write($this->_db_file, $data);
  339. break;
  340. }
  341. }
  342. }
  343. }
  344. }
  345.  
  346. // Убиваем PHPSESSID
  347. if (strlen(session_id())) {
  348. $session = session_name() . '=' . session_id();
  349. $this->_request_uri = str_replace(array('?'.$session,'&'.$session), '', $this->_request_uri);
  350. }
  351.  
  352. $this->set_data(@unserialize($data));
  353. }
  354. }
  355.  
  356. class SAPE_client extends SAPE_base {
  357.  
  358. var $_links_delimiter = '';
  359. var $_links = array();
  360. var $_links_page = array();
  361. var $_user_agent = 'SAPE_Client PHP';
  362.  
  363. function SAPE_client($options = null) {
  364. parent::SAPE_base($options);
  365. $this->load_data();
  366. }
  367.  
  368. /*
  369. * Ccылки можно показывать по частям
  370. */
  371. function return_links($n = null, $offset = 0) {
  372.  
  373. if (is_array($this->_links_page)) {
  374.  
  375. $total_page_links = count($this->_links_page);
  376.  
  377. if (!is_numeric($n) || $n > $total_page_links) {
  378. $n = $total_page_links;
  379. }
  380.  
  381. $links = array();
  382.  
  383. for ($i = 1; $i <= $n; $i++) {
  384. if ($offset > 0 && $i <= $offset) {
  385. array_shift($this->_links_page);
  386. } else {
  387. $links[] = array_shift($this->_links_page);
  388. }
  389. }
  390.  
  391. $html = join($this->_links_delimiter, $links);
  392.  
  393. // если запрошена определенная кодировка, и известна кодировка кеша, и они разные, конвертируем в заданную
  394. if (
  395. strlen($this->_charset) > 0
  396. &&
  397. strlen($this->_sape_charset) > 0
  398. &&
  399. $this->_sape_charset != $this->_charset
  400. &&
  401. function_exists('iconv')
  402. ) {
  403. $new_html = @iconv($this->_sape_charset, $this->_charset, $html);
  404. if ($new_html) {
  405. $html = $new_html;
  406. }
  407. }
  408.  
  409. if ($this->_is_our_bot) {
  410. $html = '<sape_noindex>' . $html . '</sape_noindex>';
  411. }
  412.  
  413. return $html;
  414.  
  415. } else {
  416. return $this->_links_page;
  417. }
  418.  
  419. }
  420.  
  421. function _get_db_file() {
  422. if ($this->_multi_site) {
  423. return dirname(__FILE__) . '/' . $this->_host . '.links.db';
  424. } else {
  425. return dirname(__FILE__) . '/links.db';
  426. }
  427. }
  428.  
  429. function _get_dispenser_path() {
  430. return '/code.php?user=' . _SAPE_USER . '&host=' . $this->_host;
  431. }
  432.  
  433. function set_data($data) {
  434. $this->_links = $data;
  435. if (isset($this->_links['__sape_delimiter__'])) {
  436. $this->_links_delimiter = $this->_links['__sape_delimiter__'];
  437. }
  438. // определяем кодировку кеша
  439. if (isset($this->_links['__sape_charset__'])) {
  440. $this->_sape_charset = $this->_links['__sape_charset__'];
  441. } else {
  442. $this->_sape_charset = '';
  443. }
  444. if (@array_key_exists($this->_request_uri, $this->_links) && is_array($this->_links[$this->_request_uri])) {
  445. $this->_links_page = $this->_links[$this->_request_uri];
  446. } else {
  447. if (isset($this->_links['__sape_new_url__']) && strlen($this->_links['__sape_new_url__'])) {
  448. if ($this->_is_our_bot || $this->_force_show_code){
  449. $this->_links_page = $this->_links['__sape_new_url__'];
  450. }
  451. }
  452. }
  453. }
  454. }
  455.  
  456.  
  457. class SAPE_context extends SAPE_base {
  458.  
  459. var $_words = array();
  460. var $_words_page = array();
  461. var $_user_agent = 'SAPE_Context PHP';
  462. var $_filter_tags = array('a', 'textarea', 'select', 'script', 'style', 'label', 'noscript' , 'noindex', 'button');
  463.  
  464. function SAPE_context($options = null) {
  465. parent::SAPE_base($options);
  466. $this->load_data();
  467. }
  468.  
  469. /*
  470. * Замена слов в куске текста и обрамляет его тегами sape_index
  471. *
  472. */
  473.  
  474. function replace_in_text_segment($text){
  475. $debug = '';
  476. if ($this->_debug){
  477. $debug .= "<!-- argument for replace_in_text_segment: \r\n".base64_encode($text)."\r\n -->";
  478. }
  479. if (count($this->_words_page) > 0) {
  480.  
  481. $source_sentence = array();
  482. if ($this->_debug) {
  483. $debug .= '<!-- sentences for replace: ';
  484. }
  485. //Создаем массив исходных текстов для замены
  486. foreach ($this->_words_page as $n => $sentence){
  487. //Заменяем все сущности на символы
  488. $special_chars = array(
  489. '&amp;' => '&',
  490. '&quot;' => '"',
  491. '&#039;' => '\'',
  492. '&lt;' => '<',
  493. '&gt;' => '>'
  494. );
  495. $sentence = strip_tags($sentence);
  496. foreach ($special_chars as $from => $to){
  497. str_replace($from, $to, $sentence);
  498. }
  499. //Преобразуем все спец символы в сущности
  500. $sentence = htmlspecialchars($sentence);
  501. //Квотируем
  502. $sentence = preg_quote($sentence, '/');
  503. $replace_array = array();
  504. if (preg_match_all('/(&[#a-zA-Z0-9]{2,6};)/isU', $sentence, $out)){
  505. for ($i=0; $i<count($out[1]); $i++){
  506. $unspec = $special_chars[$out[1][$i]];
  507. $real = $out[1][$i];
  508. $replace_array[$unspec] = $real;
  509. }
  510. }
  511. //Заменяем сущности на ИЛИ (сущность|символ)
  512. foreach ($replace_array as $unspec => $real){
  513. $sentence = str_replace($real, '(('.$real.')|('.$unspec.'))', $sentence);
  514. }
  515. //Заменяем пробелы на переносы или сущности пробелов
  516. $source_sentences[$n] = str_replace(' ','((\s)|(&nbsp;))+',$sentence);
  517.  
  518. if ($this->_debug) {
  519. $debug .= $source_sentences[$n]."\r\n\r\n";
  520. }
  521. }
  522.  
  523. if ($this->_debug) {
  524. $debug .= '-->';
  525. }
  526.  
  527. //если это первый кусок, то не будем добавлять <
  528. $first_part = true;
  529. //пустая переменная для записи
  530.  
  531. if (count($source_sentences) > 0){
  532.  
  533. $content = '';
  534. $open_tags = array(); //Открытые забаненые тэги
  535. $close_tag = ''; //Название текущего закрывающего тэга
  536.  
  537. //Разбиваем по символу начала тега
  538. $part = strtok(' '.$text, '<');
  539.  
  540. while ($part !== false){
  541. //Определяем название тэга
  542. if (preg_match('/(?si)^(\/?[a-z0-9]+)/', $part, $matches)){
  543. //Определяем название тега
  544. $tag_name = strtolower($matches[1]);
  545. //Определяем закрывающий ли тэг
  546. if (substr($tag_name,0,1) == '/'){
  547. $close_tag = substr($tag_name, 1);
  548. if ($this->_debug) {
  549. $debug .= '<!-- close_tag: '.$close_tag.' -->';
  550. }
  551. } else {
  552. $close_tag = '';
  553. if ($this->_debug) {
  554. $debug .= '<!-- open_tag: '.$tag_name.' -->';
  555. }
  556. }
  557. $cnt_tags = count($open_tags);
  558. //Если закрывающий тег совпадает с тегом в стеке открытых запрещенных тегов
  559. if (($cnt_tags > 0) && ($open_tags[$cnt_tags-1] == $close_tag)){
  560. array_pop($open_tags);
  561. if ($this->_debug) {
  562. $debug .= '<!-- '.$tag_name.' - deleted from open_tags -->';
  563. }
  564. if ($cnt_tags-1 ==0){
  565. if ($this->_debug) {
  566. $debug .= '<!-- start replacement -->';
  567. }
  568. }
  569. }
  570.  
  571. //Если нет открытых плохих тегов, то обрабатываем
  572. if (count($open_tags) == 0){
  573. //если не запрещенный тэг, то начинаем обработку
  574. if (!in_array($tag_name, $this->_filter_tags)){
  575. $split_parts = explode('>', $part, 2);
  576. //Перестраховываемся
  577. if (count($split_parts) == 2){
  578. //Начинаем перебор фраз для замены
  579. foreach ($source_sentences as $n => $sentence){
  580. if (preg_match('/'.$sentence.'/', $split_parts[1]) == 1){
  581. $split_parts[1] = preg_replace('/'.$sentence.'/', str_replace('$','\$', $this->_words_page[$n]), $split_parts[1], 1);
  582. if ($this->_debug) {
  583. $debug .= '<!-- '.$sentence.' --- '.$this->_words_page[$n].' replaced -->';
  584. }
  585.  
  586. //Если заменили, то удаляем строчку из списка замены
  587. unset($source_sentences[$n]);
  588. unset($this->_words_page[$n]);
  589. }
  590. }
  591. $part = $split_parts[0].'>'.$split_parts[1];
  592. unset($split_parts);
  593. }
  594. } else {
  595. //Если у нас запрещеный тэг, то помещаем его в стек открытых
  596. $open_tags[] = $tag_name;
  597. if ($this->_debug) {
  598. $debug .= '<!-- '.$tag_name.' - added to open_tags, stop replacement -->';
  599. }
  600. }
  601. }
  602. } else {
  603. //Если нет названия тега, то считаем, что перед нами текст
  604. foreach ($source_sentences as $n => $sentence){
  605. if (preg_match('/'.$sentence.'/', $part) == 1){
  606. $part = preg_replace('/'.$sentence.'/', str_replace('$','\$', $this->_words_page[$n]), $part, 1);
  607.  
  608. if ($this->_debug) {
  609. $debug .= '<!-- '.$sentence.' --- '.$this->_words_page[$n].' replaced -->';
  610. }
  611.  
  612. //Если заменили, то удаляем строчку из списка замены,
  613. //чтобы было можно делать множественный вызов
  614. unset($source_sentences[$n]);
  615. unset($this->_words_page[$n]);
  616. }
  617. }
  618. }
  619.  
  620. //Если у нас режим дебагинга, то выводим
  621. if ($this->_debug) {
  622. $content .= $debug;
  623. $debug = '';
  624. }
  625. //Если это первая часть, то не выводим <
  626. if ($first_part ){
  627. $content .= $part;
  628. $first_part = false;
  629. } else {
  630. $content .= $debug.'<'.$part;
  631. }
  632. //Получаем следующу часть
  633. unset($part);
  634. $part = strtok('<');
  635. }
  636. $text = ltrim($content);
  637. unset($content);
  638. }
  639. } else {
  640. if ($this->_debug) {
  641. $debug .= '<!-- No word`s for page -->';
  642. }
  643. }
  644.  
  645. if ($this->_debug) {
  646. $debug .= '<!-- END: work of replace_in_text_segment() -->';
  647. }
  648.  
  649. if ($this->_is_our_bot || $this->_force_show_code || $this->_debug) {
  650. $text = '<sape_index>'.$text.'</sape_index>';
  651. if (isset($this->_words['__sape_new_url__']) && strlen($this->_words['__sape_new_url__'])){
  652. $text .= $this->_words['__sape_new_url__'];
  653. }
  654. }
  655.  
  656. if ($this->_debug) {
  657. if (count($this->_words_page) > 0) {
  658. $text .= '<!-- Not replaced: '."\r\n";
  659. foreach ($this->_words_page as $n => $value){
  660. $text .= $value."\r\n\r\n";
  661. }
  662. $text .= '-->';
  663. }
  664.  
  665. $text .= $debug;
  666. }
  667. return $text;
  668. }
  669.  
  670. /*
  671. * Замена слов
  672. *
  673. */
  674. function replace_in_page(&$buffer) {
  675.  
  676. if (count($this->_words_page) > 0) {
  677. //разбиваем строку по sape_index
  678. //Проверяем есть ли теги sape_index
  679. $split_content = preg_split('/(?smi)(<\/?sape_index>)/', $buffer, -1);
  680. $cnt_parts = count($split_content);
  681. if ($cnt_parts > 1){
  682. //Если есть хоть одна пара sape_index, то начинаем работу
  683. if ($cnt_parts >= 3){
  684. for ($i =1; $i < $cnt_parts; $i = $i + 2){
  685. $split_content[$i] = $this->replace_in_text_segment($split_content[$i]);
  686. }
  687. }
  688. $buffer = implode('', $split_content);
  689. if ($this->_debug){
  690. $buffer .= '<!-- Split by Sape_index cnt_parts='.$cnt_parts.'-->';
  691. }
  692. } else {
  693. //Если не нашли sape_index, то пробуем разбить по BODY
  694. $split_content = preg_split('/(?smi)(<\/?body[^>]*>)/', $buffer, -1, PREG_SPLIT_DELIM_CAPTURE);
  695. //Если нашли содержимое между body
  696. if (count($split_content) == 5){
  697. $split_content[0] = $split_content[0].$split_content[1];
  698. $split_content[1] = $this->replace_in_text_segment($split_content[2]);
  699. $split_content[2] = $split_content[3].$split_content[4];
  700. unset($split_content[3]);
  701. unset($split_content[4]);
  702. $buffer = $split_content[0].$split_content[1].$split_content[2];
  703. if ($this->_debug){
  704. $buffer .= '<!-- Split by BODY -->';
  705. }
  706. } else {
  707. //Если не нашли sape_index и не смогли разбить по body
  708. if ($this->_debug){
  709. $buffer .= '<!-- Can`t split by BODY -->';
  710. }
  711. }
  712. }
  713.  
  714. } else {
  715. if (!$this->_is_our_bot && !$this->_force_show_code && !$this->_debug){
  716. $buffer = preg_replace('/(?smi)(<\/?sape_index>)/','', $buffer);
  717. } else {
  718. if (isset($this->_words['__sape_new_url__']) && strlen($this->_words['__sape_new_url__'])){
  719. $buffer .= $this->_words['__sape_new_url__'];
  720. }
  721. }
  722. if ($this->_debug){
  723. $buffer .= '<!-- No word`s for page -->';
  724. }
  725. }
  726. return $buffer;
  727. }
  728.  
  729. function _get_db_file() {
  730. if ($this->_multi_site) {
  731. return dirname(__FILE__) . '/' . $this->_host . '.words.db';
  732. } else {
  733. return dirname(__FILE__) . '/words.db';
  734. }
  735. }
  736.  
  737. function _get_dispenser_path() {
  738. return '/code_context.php?user=' . _SAPE_USER . '&host=' . $this->_host;
  739. }
  740.  
  741. function set_data($data) {
  742. $this->_words = $data;
  743. if (@array_key_exists($this->_request_uri, $this->_words) && is_array($this->_words[$this->_request_uri])) {
  744. $this->_words_page = $this->_words[$this->_request_uri];
  745. }
  746. }
  747. }
  748.  
  749. ?>
Add Comment
Please, Sign In to add comment