2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // $Id: make_link.php,v 1.29 2005/07/14 14:45: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);
307 if (PKWK_ALLOW_RELATIVE_FOOTNOTE_ANCHOR) {
310 $script = get_script_uri() . '?' . rawurlencode($page);
314 $note = make_link($body);
315 $page = isset($vars['page']) ? rawurlencode($vars['page']) : '';
318 $foot_explain[$id] = '<a id="notefoot_' . $id . '" href="' .
319 $script . '#notetext_' . $id . '" class="note_super">*' .
320 $id . '</a>' . "\n" .
321 '<span class="small">' . $note . '</span><br />';
323 // A hyperlink, content-body to footnote
324 $name = '<a id="notetext_' . $id . '" href="' . $script .
325 '#notefoot_' . $id . '" class="note_super" title="' .
326 strip_tags($note) . '">*' . $id . '</a>';
328 return parent::setParam($page, $name, $body);
338 class Link_url extends Link
340 function Link_url($start)
342 parent::Link($start);
345 function get_pattern()
347 $s1 = $this->start + 1;
349 (\[\[ # (1) open bracket
350 ((?:(?!\]\]).)+) # (2) alias
354 (?:(?:https?|ftp|news):\/\/|mailto:)[\w\/\@\$()!?&%#:;.,~'=*+-]+
356 (?($s1)\]\]) # close bracket
365 function set($arr, $page)
367 list(, , $alias, $name) = $this->splice($arr);
368 return parent::setParam($page, htmlspecialchars($name),
369 '', 'url', $alias == '' ? $name : $alias);
377 $rel = ' rel="nofollow"';
379 return '<a href="' . $this->name . '"' . $rel . '>' . $this->alias . '</a>';
383 // URLs (InterWiki definition on "InterWikiName")
384 class Link_url_interwiki extends Link
386 function Link_url_interwiki($start)
388 parent::Link($start);
391 function get_pattern()
396 (?:(?:https?|ftp|news):\/\/|\.\.?\/)[!~*'();\/?:\@&=+\$,%#\w.-]*
409 function set($arr, $page)
411 list(, $name, $alias) = $this->splice($arr);
412 return parent::setParam($page, htmlspecialchars($name), '', 'url', $alias);
417 return '<a href="' . $this->name . '" rel="nofollow">' . $this->alias . '</a>';
421 // mailto: URL schemes
422 class Link_mailto extends Link
424 var $is_image, $image;
426 function Link_mailto($start)
428 parent::Link($start);
431 function get_pattern()
433 $s1 = $this->start + 1;
437 ((?:(?!\]\]).)+)(?:>|:) # (1) alias
439 ([\w.-]+@[\w-]+\.[\w.-]+) # (2) mailto
440 (?($s1)\]\]) # close bracket if (1)
449 function set($arr, $page)
451 list(, $alias, $name) = $this->splice($arr);
452 return parent::setParam($page, $name, '', 'mailto', $alias == '' ? $name : $alias);
457 return '<a href="mailto:' . $this->name . '" rel="nofollow">' . $this->alias . '</a>';
461 // InterWikiName-rendered URLs
462 class Link_interwikiname extends Link
468 function Link_interwikiname($start)
470 parent::Link($start);
473 function get_pattern()
475 $s2 = $this->start + 2;
476 $s5 = $this->start + 5;
480 ((?:(?!\]\]).)+)> # (1) alias
482 (\[\[)? # (2) open bracket
483 ((?:(?!\s|:|\]\]).)+) # (3) InterWiki
484 (?<! > | >\[\[ ) # not '>' or '>[['
487 (\[\[)? # (5) open bracket
489 (?($s5)\]\]) # close bracket if (5)
491 (?($s2)\]\]) # close bracket if (2)
501 function set($arr, $page)
505 list(, $alias, , $name, $this->param) = $this->splice($arr);
508 if (preg_match('/^([^#]+)(#[A-Za-z][\w-]*)$/', $this->param, $matches))
509 list(, $this->param, $this->anchor) = $matches;
511 $url = get_interwiki_url($name, $this->param);
512 $this->url = ($url === FALSE) ?
513 $script . '?' . rawurlencode('[[' . $name . ':' . $this->param . ']]') :
514 htmlspecialchars($url);
516 return parent::setParam(
518 htmlspecialchars($name . ':' . $this->param),
521 $alias == '' ? $name . ':' . $this->param : $alias
527 return '<a href="' . $this->url . $this->anchor . '" title="' .
528 $this->name . '" rel="nofollow">' . $this->alias . '</a>';
533 class Link_bracketname extends Link
537 function Link_bracketname($start)
539 parent::Link($start);
542 function get_pattern()
544 global $WikiName, $BracketName;
546 $s2 = $this->start + 2;
549 (?:((?:(?!\]\]).)+)>)? # (1) Alias
550 (\[\[)? # (2) Open bracket
556 (\#(?:[a-zA-Z][\w-]*)?)? # (4) Anchor
557 (?($s2)\]\]) # Close bracket if (2)
567 function set($arr, $page)
571 list(, $alias, , $name, $this->anchor) = $this->splice($arr);
572 if ($name == '' && $this->anchor == '') return FALSE;
574 if ($name == '' || ! preg_match('/^' . $WikiName . '$/', $name)) {
575 if ($alias == '') $alias = $name . $this->anchor;
577 $name = get_fullname($name, $page);
578 if (! is_pagename($name)) return FALSE;
582 return parent::setParam($page, $name, '', 'pagename', $alias);
587 return make_pagelink(
597 class Link_wikiname extends Link
599 function Link_wikiname($start)
601 parent::Link($start);
604 function get_pattern()
606 global $WikiName, $nowikiname;
608 return $nowikiname ? FALSE : '(' . $WikiName . ')';
616 function set($arr, $page)
618 list($name) = $this->splice($arr);
619 return parent::setParam($page, $name, '', 'pagename', $name);
624 return make_pagelink(
634 class Link_autolink extends Link
636 var $forceignorepages = array();
638 var $auto_a; // alphabet only
640 function Link_autolink($start)
644 parent::Link($start);
646 if (! $autolink || ! file_exists(CACHE_DIR . 'autolink.dat'))
649 @list($auto, $auto_a, $forceignorepages) = file(CACHE_DIR . 'autolink.dat');
651 $this->auto_a = $auto_a;
652 $this->forceignorepages = explode("\t", trim($forceignorepages));
655 function get_pattern()
657 return isset($this->auto) ? '(' . $this->auto . ')' : FALSE;
665 function set($arr, $page)
669 list($name) = $this->splice($arr);
671 // Ignore pages listed, or Expire ones not found
672 if (in_array($name, $this->forceignorepages) || ! is_page($name))
675 return parent::setParam($page, $name, '', 'pagename', $name);
680 return make_pagelink($this->name, $this->alias, '', $this->page, TRUE);
684 class Link_autolink_a extends Link_autolink
686 function Link_autolink_a($start)
688 parent::Link_autolink($start);
691 function get_pattern()
693 return isset($this->auto_a) ? '(' . $this->auto_a . ')' : FALSE;
697 // Make hyperlink for the page
698 function make_pagelink($page, $alias = '', $anchor = '', $refer = '', $isautolink = FALSE)
700 global $script, $vars, $link_compact, $related, $_symbol_noexists;
702 $s_page = htmlspecialchars(strip_bracket($page));
703 $s_alias = ($alias == '') ? $s_page : $alias;
705 if ($page == '') return '<a href="' . $anchor . '">' . $s_alias . '</a>';
707 $r_page = rawurlencode($page);
708 $r_refer = ($refer == '') ? '' : '&refer=' . rawurlencode($refer);
710 if (! isset($related[$page]) && $page != $vars['page'] && is_page($page))
711 $related[$page] = get_filetime($page);
713 if ($isautolink || is_page($page)) {
714 // Hyperlink to the page
718 $title = ' title="' . $s_page . get_pg_passage($page, FALSE) . '"';
723 $al_left = '<!--autolink-->';
724 $al_right = '<!--/autolink-->';
726 $al_left = $al_right = '';
729 return $al_left . '<a ' . 'href="' . $script . '?' . $r_page . $anchor .
730 '"' . $title . '>' . $s_alias . '</a>' . $al_right;
733 if (PKWK_READONLY) return $s_alias; // No dacorations
735 $retval = $s_alias . '<a href="' .
736 $script . '?cmd=edit&page=' . $r_page . $r_refer . '">' .
737 $_symbol_noexists . '</a>';
742 return '<span class="noexists">' . $retval . '</span>';
747 // Resolve relative / (Unix-like)absolute path of the page
748 function get_fullname($name, $refer)
753 if ($name == '' || $name == './') return $refer;
756 if ($name{0} == '/') {
757 $name = substr($name, 1);
758 return ($name == '') ? $defaultpage : $name;
761 // Relative path from 'Here'
762 if (substr($name, 0, 2) == './') {
763 $arrn = preg_split('#/#', $name, -1, PREG_SPLIT_NO_EMPTY);
765 return join('/', $arrn);
768 // Relative path from dirname()
769 if (substr($name, 0, 3) == '../') {
770 $arrn = preg_split('#/#', $name, -1, PREG_SPLIT_NO_EMPTY);
771 $arrp = preg_split('#/#', $refer, -1, PREG_SPLIT_NO_EMPTY);
773 while (! empty($arrn) && $arrn[0] == '..') {
777 $name = ! empty($arrp) ? join('/', array_merge($arrp, $arrn)) :
778 (! empty($arrn) ? $defaultpage . '/' . join('/', $arrn) : $defaultpage);
784 // Render an InterWiki into a URL
785 function get_interwiki_url($name, $param)
787 global $WikiName, $interwiki;
788 static $interwikinames;
789 static $encode_aliases = array('sjis'=>'SJIS', 'euc'=>'EUC-JP', 'utf8'=>'UTF-8');
791 if (! isset($interwikinames)) {
792 $interwikinames = $matches = array();
793 foreach (get_source($interwiki) as $line)
794 if (preg_match('/\[(' . '(?:(?:https?|ftp|news):\/\/|\.\.?\/)' .
795 '[!~*\'();\/?:\@&=+\$,%#\w.-]*)\s([^\]]+)\]\s?([^\s]*)/',
797 $interwikinames[$matches[2]] = array($matches[1], $matches[3]);
800 if (! isset($interwikinames[$name])) return FALSE;
802 list($url, $opt) = $interwikinames[$name];
807 case '': /* FALLTHROUGH */
808 case 'std': // Simply URL-encode the string, whose base encoding is the internal-encoding
809 $param = rawurlencode($param);
812 case 'asis': /* FALLTHROUGH */
813 case 'raw' : // Truly as-is
816 case 'yw': // YukiWiki
817 if (! preg_match('/' . $WikiName . '/', $param))
818 $param = '[[' . mb_convert_encoding($param, 'SJIS', SOURCE_ENCODING) . ']]';
821 case 'moin': // MoinMoin
822 $param = str_replace('%', '_', rawurlencode($param));
826 // Alias conversion of $opt
827 if (isset($encode_aliases[$opt])) $opt = & $encode_aliases[$opt];
829 // Encoding conversion into specified encode, and URLencode
830 $param = rawurlencode(mb_convert_encoding($param, $opt, SOURCE_ENCODING));
833 // Replace or Add the parameter
834 if (strpos($url, '$1') !== FALSE) {
835 $url = str_replace('$1', $param, $url);
841 if ($len > 512) die_message('InterWiki URL too long: ' . $len . ' characters');