We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 24489
    • 60 Posts
    Вот хочу создать модуль для оптимизации ссылок, нужны функции:
    - работать только при генерации страницы onWebPagePrerender
    - искать слова в content-е и сопоставлять их с pagetitle страниц и делать на них ссылки типа <a href="[~[*id*]~]" title="[*pagetitle*]">
    у кого какие идеи ?
      Плагин для ресайза картинок AutoResizer
      Сниппет для вывода полей документа DocInfo

      Создание ТВ типа checkbox/dropdown из списка дочерних документов tvsLinks
      • 1477
      • 515 Posts
      СЕО - зло wink
        Shopkeeper - сниппет и модуль для создания интернет-магазина.
        TVimageResizer - плагин для изменения размеров (а также наложения водяных знаков и скругления углов) картинок TV при создании документа.
        PickDocsInTree - плагин для выбора документов из дерева.
        Paykeeper 1.5 - Сниппет для онлайн-оплаты в интернет-магазине MODx + Shopkeeper (Webmoney и Robokassa).
        • 6272
        • 95 Posts
        Посмотри это. Англоязычная ветка тут. Сам пока не разбирался...
          • 6272
          • 95 Posts
          Поставил Autolink, работает отлично, устанавливается/настраивается элементарно. С русскими буквами только не работает rolleyes Как сделать чтоб работал, не знаю - в пхп шарю крайне плохо. Но думаю дописать нужно всего пару строк. Чем и стоит заняться, нежели изобретать подобный велик с нуля.
            • 24489
            • 60 Posts
            там несколько строк с регулярными выражениями, вот они кирилицу не понимают, я не силён в регулярных выражениях

            <?php
            /** 
             * Autolink plugin
             * 
             * Author: Garry Nutting
             * Original Code and Concept: phpGiggle by Biermana
             * 
             * Version: 1.1
             * Date: 03/05/06
             * 
             * CSS Styles:
             * 
             * autolink_highlight
             * autolink_link
             * autolink_abbr
             * autolink_acro
             * autolink (for Google, CPAN etc. - can be changed in respective function)
             * 
             * updated: support for accented characters
             */
            
            //-- set the template function target
            //-- use with externalLinks js function to open template function links in new window
            //-- http://pure-essence.net/archives/2006/02/02/relexternal/
            define('autolink_target', 'rel="external"');
            
            $e = & $modx->Event;
            switch ($e->name) {
            	case "OnWebPagePrerender" :
            		//-- get current template value
            		$table = $modx->getFullTableName('site_content');
            		$sql = $modx->db->select('template', $table, 'id="' . $modx->documentIdentifier . '"');
            		$row = $modx->db->getRow($sql);
            		//-- do not run if on blank template (so it doesn't interfere with RSS feeds)
            		if ($row['template'] <> 0) {
            			$pg = & $modx->documentOutput;
            			$pg = autolink($pg);
            		} else {
            			return $modx->documentOutput;
            		}
            		break;
            	default :
            		return;
            		break;
            }
            
            /**
             * Main autolink function - replaces keywords with desired values
             */
            function autolink($string) {
            	global $modx;
            
            	//-- replace with match (1) or value entered in table (0)
            	$match_replace = 1;
            
            	//-- blocked tags ie. those that the tokenizer will ignore
            	$blocked_tags = 'code|pre';
            	$pagetitle_r = array (); //-- stores the link values
            	$autolinkTitle = array (); //-- stores the title attribute values
            	$autolinkDefault = array (); //-- will store the abbreviation/acronym value
            
            	//-- setup db table name
            	$autolinkTable = $modx->getFullTableName('site_content');
            
            	//-- get keywords from db
            	$rs = $modx->db->select('*', $autolinkTable);
            
            	while ($row = $modx->db->getRow($rs)) {
            		$pagetitle_r[$row['id']] = $row['pagetitle'];		
            	}
            
            	//-- get the body tags
            	preg_match('/(<body.*?>)/', $string, $open);
            	preg_match('/(<\/body.*?>)/', $string, $close);
            	$body_open = $open[1];
            	$body_close = $close[1];
            
            	unset ($open);
            	unset ($close);
            
            	//-- get only body html - will add head and footer back in later
            	$temp = explode("$body_open", $string);
            	$head = $temp[0];
            	$string = $temp[1];
            	$temp = explode("$body_close", $string);
            	$string = $temp[0];
            	$footer = $temp[1];
            
            	//-- ensure that first autolink match will always be second entry in array
            	$text = " $string ";
            
            	//-- split the content around the <autolink> tags
            	$textarr = preg_split("/<autolink>(.*)<\/autolink>/Us", $text, -1, PREG_SPLIT_DELIM_CAPTURE);
            	//-- setup output string
            	$out = '';
            
            	//-- start main loop of content array
            	for ($i = 0; $i < count($textarr); $i++) {
            		$text = $textarr[$i];
            
            		//-- skip the entries outside autolink tags
            		if ($i % 2 == 0) {
            			$out .= $text;
            			continue;
            		}
            
            		//-- loop through each keyword in the array
            		foreach ($pagetitle_r as $id => $pagetitle) {
            
            	
            		
            		
            			//-- setup the tokenizer variables
            			$anchor_level = 0;
            			$tag_level = 0;
            			$must_tokenize = TRUE; //-- will perform basic tokenization
            			$tokens = NULL; //-- two kinds of tokens: markup and text
            
            			$filtered = ''; //-- will filter text token by token
            			$match = "/\b" . preg_quote($pagetitle, "/") . "\b/i"; //-- check for encoded match
            			$match_noencode = "/\b" . preg_quote($pagetitle, "/") . "\b/i"; //-- check for non-encoded match
            
            			$substitute = '<a class="autolink_link" href="index.php?id=' . $id. '" title="' . $pagetitle . '">' . $pagetitle . '</a>';
            		
            			
            		
            			if ($must_tokenize) // for efficiency only tokenize if forced to do so
            				{
            				//-- this regexp is taken from PHP Markdown by Michel Fortin:
            				//-- http://www.michelf.com/projects/php-markdown/
            				$comment = '(?s:<!(?:--.*?--\s*)+>)|';
            				$processing_instruction = '(?s:<\?.*?\?>)|';
            				$tag = '(?:<[/!$]?[-a-zA-Z0-9:]+\b(?>[^"\'>]+|"[^"]*"|\'[^\']*\')*>)';
            				$markup = $comment . $processing_instruction . $tag;
            				$flags = PREG_SPLIT_DELIM_CAPTURE;
            				$tokens = preg_split("{($markup)}", $text, -1, $flags);
            				$must_tokenize = FALSE;
            			}
            
            			//-- there should always be at least one token, but check just in case
            			if (isset ($tokens) && is_array($tokens) && count($tokens) > 0) {
            				$j = 0;
            				foreach ($tokens as $token) {
            					if (++ $j % 2 && $token != '') //-- this token is (non-markup) text
            						{
            						if ($anchor_level == 0 && $tag_level == 0) // linkify if not inside anchor tags
            							{
            							
            
            // ----------------- ВОТ от сюда по регулярным выражениям не сравнивается $token
            							//-- test for encoded keyword
            							if (preg_match("/\b" .$pagetitle. "\b/", $token, $kmatch)) {
            								//-- ensure that the substitute replaces value with the case-sensitive match
            								if ($match_replace == 1) {
            									$substitute = preg_replace('/\b' . $pagetitle . '\b/', $kmatch[0], $substitute);
            								}
            								//-- replace keyword with the substitute
            								$token = preg_replace("/\b" .$pagetitle. "\b/", $substitute, $token);
            								$must_tokenize = TRUE; //-- re-tokenize next time around						
            
            								//-- test for non-encoded keyword
            							}
            							
            						}
            
            					} 
            					$filtered .= $token; //-- this token has now been filtered
            					
            					
            				}
            			}
            			$text = $filtered; //-- filtering completed for this link
            		
            		}
            		//-- add section to the output
            		$out .= $text;
            	}
            	//-- return the compiled output to the browser
            	return $head . $body_open . trim($out) . $body_close . $footer;
            	}
            
            /******************************************************************
             * 
             * Template Functions
             * 
             */
            
            /*
                template function for search.cpan.org
            */
            
            function autolink_cpan($autolink_it) {
            	return "<a " . autolink_target . " class=\"autolink\" title=\"Search CPAN for '" .
            	$autolink_it . "' !\" href=\"http://search.cpan.org/search?query=" . urlencode($autolink_it) . "\">" .
            	$autolink_it . "</a>";
            }
            
            /*
                template function for google.com
            */
            function autolink_google($autolink_it) {
            	return "<a " . autolink_target . " class=\"autolink\" title=\"Google.com search for '" .
            	$autolink_it . "' !\" href=\"http://www.google.com/search?q=" . $autolink_it . "\">" .
            	$autolink_it . "</a>";
            }
            
            /*
                template function for dictionary.com
            */
            function autolink_dictionary($autolink_it) {
            	return "<a " . autolink_target . " class=\"autolink\" title=\"Dictionary.com definition for '" .
            	$autolink_it . "' !\" href=\"http://dictionary.reference.com/search?q=" . $autolink_it . "\">" .
            	$autolink_it . "</a>";
            }
            
            /*
                template function for freshmeat.net
            */
            function autolink_freshmeat($autolink_it) {
            	return "<a " . autolink_target . " class=\"autolink\" title=\"Freshmeat.net search projects for '" .
            	$autolink_it . "' !\" href=\"http://freshmeat.net/search/?q=" . urlencode($autolink_it) . "\">" .
            	$autolink_it . "</a>";
            }
            
            /*
                template function for vivisimo.com
            */
            function autolink_vivisimo($autolink_it) {
            	return "<a " . autolink_target . " class=\"autolink\" title=\"Vivisimo.com document cluster for '" .
            	$autolink_it . "' !\" href=\"http://www.vivisimo.com/search?query=" . urlencode($autolink_it) . "\">" .
            	$autolink_it . "</a>";
            }
            
            /*
                template function for webopedia.com
                note:  no gaurantee the webopedia page exists - better to manually check it first
            */
            function autolink_webopedia($autolink_it) {
            	return "<a " . autolink_target . " class=\"autolink\" title=\"Webopedia.com definition for '" .
            	$autolink_it . "' !\" href=\"http://www.webopedia.com/TERM/" . substr($autolink_it, 0, 1) . "/" . str_replace(" ", "_", $autolink_it) . ".html" . "\">" .
            	$autolink_it . "</a>";
            }
            
            ?>
            

            работеат без модуля, и то что мне нужно, но русский не понимает...
              Плагин для ресайза картинок AutoResizer
              Сниппет для вывода полей документа DocInfo

              Создание ТВ типа checkbox/dropdown из списка дочерних документов tvsLinks