2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // $Id: make_link.php,v 1.28 2005/06/27 14:18:07 henoheno Exp $
5 // 2003-2005 PukiWiki Developers Team
6 // 2001-2002 Originally written by yu-ji
7 // License: GPL v2 or (at your option) any later version
9 // Hyperlink-related functions
11 // Hyperlink decoration
12 function make_link($string, $page = '')
17 if (! isset($converter)) $converter = new InlineConverter();
19 $clone = $converter->get_clone($converter);
21 return $clone->convert($string, ($page != '') ? $page : $vars['page']);
24 // Converters of inline element
27 var $converters; // as array()
32 function get_clone($obj) {
35 if (! isset($clone_func)) {
36 if (version_compare(PHP_VERSION, '5.0.0', '<')) {
37 $clone_func = create_function('$a', 'return $a;');
39 $clone_func = create_function('$a', 'return clone $a;');
42 return $clone_func($obj);
46 $converters = array();
47 foreach ($this->converters as $key=>$converter) {
48 $converters[$key] = $this->get_clone($converter);
50 $this->converters = $converters;
53 function InlineConverter($converters = NULL, $excludes = NULL)
55 if ($converters === NULL) {
57 'plugin', // Inline plugins
60 'url_interwiki', // URLs (interwiki definition)
61 'mailto', // mailto: URL schemes
62 'interwikiname', // InterWikiNames
63 'autolink', // AutoLinks
64 'bracketname', // BracketNames
65 'wikiname', // WikiNames
66 'autolink_a', // AutoLinks(alphabet)
70 if ($excludes !== NULL)
71 $converters = array_diff($converters, $excludes);
73 $this->converters = $patterns = array();
76 foreach ($converters as $name) {
77 $classname = 'Link_' . $name;
78 $converter = new $classname($start);
79 $pattern = $converter->get_pattern();
80 if ($pattern === FALSE) continue;
82 $patterns[] = '(' . "\n" . $pattern . "\n" . ')';
83 $this->converters[$start] = $converter;
84 $start += $converter->get_count();
87 $this->pattern = join('|', $patterns);
90 function convert($string, $page)
93 $this->result = array();
95 $string = preg_replace_callback('/' . $this->pattern . '/x',
96 array(& $this, 'replace'), $string);
98 $arr = explode("\x08", make_line_rules(htmlspecialchars($string)));
100 while (! empty($arr)) {
101 $retval .= array_shift($arr) . array_shift($this->result);
106 function replace($arr)
108 $obj = $this->get_converter($arr);
110 $this->result[] = ($obj !== NULL && $obj->set($arr, $this->page) !== FALSE) ?
111 $obj->toString() : make_line_rules(htmlspecialchars($arr[0]));
113 return "\x08"; // Add a mark into latest processed part
116 function get_objects($string, $page)
118 $matches = $arr = array();
119 preg_match_all('/' . $this->pattern . '/x', $string, $matches, PREG_SET_ORDER);
120 foreach ($matches as $match) {
121 $obj = $this->get_converter($match);
122 if ($obj->set($match, $page) !== FALSE) {
123 $arr[] = $this->get_clone($obj);
124 if ($obj->body != '')
125 $arr = array_merge($arr, $this->get_objects($obj->body, $page));
131 function & get_converter(& $arr)
133 foreach (array_keys($this->converters) as $start) {
134 if ($arr[$start] == $arr[0])
135 return $this->converters[$start];
141 // Base class of inline elements
144 var $start; // Origin number of parentheses (0 origin)
145 var $text; // Matched string
154 function Link($start)
156 $this->start = $start;
159 // Return a regex pattern to match
160 function get_pattern() {}
162 // Return number of parentheses (except (?:...) )
163 function get_count() {}
165 // Set pattern that matches
166 function set($arr, $page) {}
168 function toString() {}
170 // Private: Get needed parts from a matched array()
171 function splice($arr)
173 $count = $this->get_count() + 1;
174 $arr = array_pad(array_splice($arr, $this->start, $count), $count, '');
175 $this->text = $arr[0];
179 // Set basic parameters
180 function setParam($page, $name, $body, $type = '', $alias = '')
182 static $converter = NULL;
188 if (! PKWK_DISABLE_INLINE_IMAGE_FROM_URI &&
189 is_url($alias) && preg_match('/\.(gif|png|jpe?g)$/i', $alias)) {
190 $alias = '<img src="' . htmlspecialchars($alias) . '" alt="' . $name . '" />';
191 } else if ($alias != '') {
192 if ($converter === NULL)
193 $converter = new InlineConverter(array('plugin'));
195 $alias = make_line_rules($converter->convert($alias, $page));
197 // BugTrack/669: A hack removing anchor tags added by AutoLink
198 $alias = preg_replace('#</?a[^>]*>#i', '', $alias);
200 $this->alias = $alias;
207 class Link_plugin extends Link
212 function Link_plugin($start)
214 parent::Link($start);
217 function get_pattern()
219 $this->pattern = <<<EOD
222 (\w+) # (2) plugin name
225 ((?:(?!\)[;{]).)*) # (3) parameter
234 ((?:(?R)|(?!};).)*) # (4) body
246 function set($arr, $page)
248 list($all, $this->plain, $name, $this->param, $body) = $this->splice($arr);
250 // Re-get true plugin name and patameters (for PHP 4.1.2)
252 if (preg_match('/^' . $this->pattern . '/x', $all, $matches)
253 && $matches[1] != $this->plain)
254 list(, $this->plain, $name, $this->param) = $matches;
256 return parent::setParam($page, $name, $body, 'plugin');
261 $body = ($this->body == '') ? '' : make_link($this->body);
264 // Try to call the plugin
265 if (exist_plugin_inline($this->name))
266 $str = do_plugin_inline($this->name, $this->param, $body);
268 if ($str !== FALSE) {
269 return $str; // Succeed
271 // No such plugin, or Failed
272 $body = (($body == '') ? '' : '{' . $body . '}') . ';';
273 return make_line_rules(htmlspecialchars('&' . $this->plain) . $body);
279 class Link_note extends Link
281 function Link_note($start)
283 parent::Link($start);
286 function get_pattern()
290 ((?:(?R)|(?!\)\)).)*) # (1) note body
300 function set($arr, $page)
302 global $foot_explain, $vars;
305 list(, $body) = $this->splice($arr);
308 if (! PKWK_ALLOW_RELATIVE_FOOTNOTE_ANCHOR)
309 $script = get_script_uri() . '?' . $page;
312 $note = make_link($body);
313 $page = isset($vars['page']) ? rawurlencode($vars['page']) : '';
316 $foot_explain[$id] = '<a id="notefoot_' . $id . '" href="' .
317 $script . '#notetext_' . $id . '" class="note_super">*' .
318 $id . '</a>' . "\n" .
319 '<span class="small">' . $note . '</span><br />';
321 // A hyperlink, content-body to footnote
322 $name = '<a id="notetext_' . $id . '" href="' . $script .
323 '#notefoot_' . $id . '" class="note_super" title="' .
324 strip_tags($note) . '">*' . $id . '</a>';
326 return parent::setParam($page, $name, $body);
336 class Link_url extends Link
338 function Link_url($start)
340 parent::Link($start);
343 function get_pattern()
345 $s1 = $this->start + 1;
347 (\[\[ # (1) open bracket
348 ((?:(?!\]\]).)+) # (2) alias
352 (?:(?:https?|ftp|news):\/\/|mailto:)[\w\/\@\$()!?&%#:;.,~'=*+-]+
354 (?($s1)\]\]) # close bracket
363 function set($arr, $page)
365 list(, , $alias, $name) = $this->splice($arr);
366 return parent::setParam($page, htmlspecialchars($name),
367 '', 'url', $alias == '' ? $name : $alias);
375 $rel = ' rel="nofollow"';
377 return '<a href="' . $this->name . '"' . $rel . '>' . $this->alias . '</a>';
381 // URLs (InterWiki definition on "InterWikiName")
382 class Link_url_interwiki extends Link
384 function Link_url_interwiki($start)
386 parent::Link($start);
389 function get_pattern()
394 (?:(?:https?|ftp|news):\/\/|\.\.?\/)[!~*'();\/?:\@&=+\$,%#\w.-]*
407 function set($arr, $page)
409 list(, $name, $alias) = $this->splice($arr);
410 return parent::setParam($page, htmlspecialchars($name), '', 'url', $alias);
415 return '<a href="' . $this->name . '" rel="nofollow">' . $this->alias . '</a>';
419 // mailto: URL schemes
420 class Link_mailto extends Link
422 var $is_image, $image;
424 function Link_mailto($start)
426 parent::Link($start);
429 function get_pattern()
431 $s1 = $this->start + 1;
435 ((?:(?!\]\]).)+)(?:>|:) # (1) alias
437 ([\w.-]+@[\w-]+\.[\w.-]+) # (2) mailto
438 (?($s1)\]\]) # close bracket if (1)
447 function set($arr, $page)
449 list(, $alias, $name) = $this->splice($arr);
450 return parent::setParam($page, $name, '', 'mailto', $alias == '' ? $name : $alias);
455 return '<a href="mailto:' . $this->name . '" rel="nofollow">' . $this->alias . '</a>';
459 // InterWikiName-rendered URLs
460 class Link_interwikiname extends Link
466 function Link_interwikiname($start)
468 parent::Link($start);
471 function get_pattern()
473 $s2 = $this->start + 2;
474 $s5 = $this->start + 5;
478 ((?:(?!\]\]).)+)> # (1) alias
480 (\[\[)? # (2) open bracket
481 ((?:(?!\s|:|\]\]).)+) # (3) InterWiki
482 (?<! > | >\[\[ ) # not '>' or '>[['
485 (\[\[)? # (5) open bracket
487 (?($s5)\]\]) # close bracket if (5)
489 (?($s2)\]\]) # close bracket if (2)
499 function set($arr, $page)
503 list(, $alias, , $name, $this->param) = $this->splice($arr);
506 if (preg_match('/^([^#]+)(#[A-Za-z][\w-]*)$/', $this->param, $matches))
507 list(, $this->param, $this->anchor) = $matches;
509 $url = get_interwiki_url($name, $this->param);
510 $this->url = ($url === FALSE) ?
511 $script . '?' . rawurlencode('[[' . $name . ':' . $this->param . ']]') :
512 htmlspecialchars($url);
514 return parent::setParam(
516 htmlspecialchars($name . ':' . $this->param),
519 $alias == '' ? $name . ':' . $this->param : $alias
525 return '<a href="' . $this->url . $this->anchor . '" title="' .
526 $this->name . '" rel="nofollow">' . $this->alias . '</a>';
531 class Link_bracketname extends Link
535 function Link_bracketname($start)
537 parent::Link($start);
540 function get_pattern()
542 global $WikiName, $BracketName;
544 $s2 = $this->start + 2;
547 (?:((?:(?!\]\]).)+)>)? # (1) Alias
548 (\[\[)? # (2) Open bracket
554 (\#(?:[a-zA-Z][\w-]*)?)? # (4) Anchor
555 (?($s2)\]\]) # Close bracket if (2)
565 function set($arr, $page)
569 list(, $alias, , $name, $this->anchor) = $this->splice($arr);
570 if ($name == '' && $this->anchor == '') return FALSE;
572 if ($name == '' || ! preg_match('/^' . $WikiName . '$/', $name)) {
573 if ($alias == '') $alias = $name . $this->anchor;
575 $name = get_fullname($name, $page);
576 if (! is_pagename($name)) return FALSE;
580 return parent::setParam($page, $name, '', 'pagename', $alias);
585 return make_pagelink(
595 class Link_wikiname extends Link
597 function Link_wikiname($start)
599 parent::Link($start);
602 function get_pattern()
604 global $WikiName, $nowikiname;
606 return $nowikiname ? FALSE : '(' . $WikiName . ')';
614 function set($arr, $page)
616 list($name) = $this->splice($arr);
617 return parent::setParam($page, $name, '', 'pagename', $name);
622 return make_pagelink(
632 class Link_autolink extends Link
634 var $forceignorepages = array();
636 var $auto_a; // alphabet only
638 function Link_autolink($start)
642 parent::Link($start);
644 if (! $autolink || ! file_exists(CACHE_DIR . 'autolink.dat'))
647 @list($auto, $auto_a, $forceignorepages) = file(CACHE_DIR . 'autolink.dat');
649 $this->auto_a = $auto_a;
650 $this->forceignorepages = explode("\t", trim($forceignorepages));
653 function get_pattern()
655 return isset($this->auto) ? '(' . $this->auto . ')' : FALSE;
663 function set($arr, $page)
667 list($name) = $this->splice($arr);
669 // Ignore pages listed, or Expire ones not found
670 if (in_array($name, $this->forceignorepages) || ! is_page($name))
673 return parent::setParam($page, $name, '', 'pagename', $name);
678 return make_pagelink($this->name, $this->alias, '', $this->page, TRUE);
682 class Link_autolink_a extends Link_autolink
684 function Link_autolink_a($start)
686 parent::Link_autolink($start);
689 function get_pattern()
691 return isset($this->auto_a) ? '(' . $this->auto_a . ')' : FALSE;
695 // Make hyperlink for the page
696 function make_pagelink($page, $alias = '', $anchor = '', $refer = '', $isautolink = FALSE)
698 global $script, $vars, $link_compact, $related, $_symbol_noexists;
700 $s_page = htmlspecialchars(strip_bracket($page));
701 $s_alias = ($alias == '') ? $s_page : $alias;
703 if ($page == '') return '<a href="' . $anchor . '">' . $s_alias . '</a>';
705 $r_page = rawurlencode($page);
706 $r_refer = ($refer == '') ? '' : '&refer=' . rawurlencode($refer);
708 if (! isset($related[$page]) && $page != $vars['page'] && is_page($page))
709 $related[$page] = get_filetime($page);
711 if ($isautolink || is_page($page)) {
712 // Hyperlink to the page
716 $title = ' title="' . $s_page . get_pg_passage($page, FALSE) . '"';
721 $al_left = '<!--autolink-->';
722 $al_right = '<!--/autolink-->';
724 $al_left = $al_right = '';
727 return $al_left . '<a ' . 'href="' . $script . '?' . $r_page . $anchor .
728 '"' . $title . '>' . $s_alias . '</a>' . $al_right;
731 if (PKWK_READONLY) return $s_alias; // No dacorations
733 $retval = $s_alias . '<a href="' .
734 $script . '?cmd=edit&page=' . $r_page . $r_refer . '">' .
735 $_symbol_noexists . '</a>';
740 return '<span class="noexists">' . $retval . '</span>';
745 // Resolve relative / (Unix-like)absolute path of the page
746 function get_fullname($name, $refer)
751 if ($name == '' || $name == './') return $refer;
754 if ($name{0} == '/') {
755 $name = substr($name, 1);
756 return ($name == '') ? $defaultpage : $name;
759 // Relative path from 'Here'
760 if (substr($name, 0, 2) == './') {
761 $arrn = preg_split('#/#', $name, -1, PREG_SPLIT_NO_EMPTY);
763 return join('/', $arrn);
766 // Relative path from dirname()
767 if (substr($name, 0, 3) == '../') {
768 $arrn = preg_split('#/#', $name, -1, PREG_SPLIT_NO_EMPTY);
769 $arrp = preg_split('#/#', $refer, -1, PREG_SPLIT_NO_EMPTY);
771 while (! empty($arrn) && $arrn[0] == '..') {
775 $name = ! empty($arrp) ? join('/', array_merge($arrp, $arrn)) :
776 (! empty($arrn) ? $defaultpage . '/' . join('/', $arrn) : $defaultpage);
782 // Render an InterWiki into a URL
783 function get_interwiki_url($name, $param)
785 global $WikiName, $interwiki;
786 static $interwikinames;
787 static $encode_aliases = array('sjis'=>'SJIS', 'euc'=>'EUC-JP', 'utf8'=>'UTF-8');
789 if (! isset($interwikinames)) {
790 $interwikinames = $matches = array();
791 foreach (get_source($interwiki) as $line)
792 if (preg_match('/\[(' . '(?:(?:https?|ftp|news):\/\/|\.\.?\/)' .
793 '[!~*\'();\/?:\@&=+\$,%#\w.-]*)\s([^\]]+)\]\s?([^\s]*)/',
795 $interwikinames[$matches[2]] = array($matches[1], $matches[3]);
798 if (! isset($interwikinames[$name])) return FALSE;
800 list($url, $opt) = $interwikinames[$name];
805 case '': /* FALLTHROUGH */
806 case 'std': // Simply URL-encode the string, whose base encoding is the internal-encoding
807 $param = rawurlencode($param);
810 case 'asis': /* FALLTHROUGH */
811 case 'raw' : // Truly as-is
814 case 'yw': // YukiWiki
815 if (! preg_match('/' . $WikiName . '/', $param))
816 $param = '[[' . mb_convert_encoding($param, 'SJIS', SOURCE_ENCODING) . ']]';
819 case 'moin': // MoinMoin
820 $param = str_replace('%', '_', rawurlencode($param));
824 // Alias conversion of $opt
825 if (isset($encode_aliases[$opt])) $opt = & $encode_aliases[$opt];
827 // Encoding conversion into specified encode, and URLencode
828 $param = rawurlencode(mb_convert_encoding($param, $opt, SOURCE_ENCODING));
831 // Replace or Add the parameter
832 if (strpos($url, '$1') !== FALSE) {
833 $url = str_replace('$1', $param, $url);
839 if ($len > 512) die_message('InterWiki URL too long: ' . $len . ' characters');