OSDN Git Service

BugTrack2/18: htmlspecialchars() is not needed (Pointed ot by SANO Masatoshi)
[pukiwiki/pukiwiki.git] / lib / make_link.php
1 <?php
2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // $Id: make_link.php,v 1.28 2005/06/27 14:18:07 henoheno Exp $
4 // Copyright (C)
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
8 //
9 // Hyperlink-related functions
10
11 // Hyperlink decoration
12 function make_link($string, $page = '')
13 {
14         global $vars;
15         static $converter;
16
17         if (! isset($converter)) $converter = new InlineConverter();
18
19         $clone = $converter->get_clone($converter);
20
21         return $clone->convert($string, ($page != '') ? $page : $vars['page']);
22 }
23
24 // Converters of inline element
25 class InlineConverter
26 {
27         var $converters; // as array()
28         var $pattern;
29         var $pos;
30         var $result;
31
32         function get_clone($obj) {
33                 static $clone_func;
34
35                 if (! isset($clone_func)) {
36                         if (version_compare(PHP_VERSION, '5.0.0', '<')) {
37                                 $clone_func = create_function('$a', 'return $a;');
38                         } else {
39                                 $clone_func = create_function('$a', 'return clone $a;');
40                         }
41                 }
42                 return $clone_func($obj);
43         }
44
45         function __clone() {
46                 $converters = array();
47                 foreach ($this->converters as $key=>$converter) {
48                         $converters[$key] = $this->get_clone($converter);
49                 }
50                 $this->converters = $converters;
51         }
52
53         function InlineConverter($converters = NULL, $excludes = NULL)
54         {
55                 if ($converters === NULL) {
56                         $converters = array(
57                                 'plugin',        // Inline plugins
58                                 'note',          // Footnotes
59                                 'url',           // URLs
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)
67                         );
68                 }
69
70                 if ($excludes !== NULL)
71                         $converters = array_diff($converters, $excludes);
72
73                 $this->converters = $patterns = array();
74                 $start = 1;
75
76                 foreach ($converters as $name) {
77                         $classname = 'Link_' . $name;
78                         $converter = new $classname($start);
79                         $pattern   = $converter->get_pattern();
80                         if ($pattern === FALSE) continue;
81
82                         $patterns[] = '(' . "\n" . $pattern . "\n" . ')';
83                         $this->converters[$start] = $converter;
84                         $start += $converter->get_count();
85                         ++$start;
86                 }
87                 $this->pattern = join('|', $patterns);
88         }
89
90         function convert($string, $page)
91         {
92                 $this->page   = $page;
93                 $this->result = array();
94
95                 $string = preg_replace_callback('/' . $this->pattern . '/x',
96                         array(& $this, 'replace'), $string);
97
98                 $arr = explode("\x08", make_line_rules(htmlspecialchars($string)));
99                 $retval = '';
100                 while (! empty($arr)) {
101                         $retval .= array_shift($arr) . array_shift($this->result);
102                 }
103                 return $retval;
104         }
105
106         function replace($arr)
107         {
108                 $obj = $this->get_converter($arr);
109
110                 $this->result[] = ($obj !== NULL && $obj->set($arr, $this->page) !== FALSE) ?
111                         $obj->toString() : make_line_rules(htmlspecialchars($arr[0]));
112
113                 return "\x08"; // Add a mark into latest processed part
114         }
115
116         function get_objects($string, $page)
117         {
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));
126                         }
127                 }
128                 return $arr;
129         }
130
131         function & get_converter(& $arr)
132         {
133                 foreach (array_keys($this->converters) as $start) {
134                         if ($arr[$start] == $arr[0])
135                                 return $this->converters[$start];
136                 }
137                 return NULL;
138         }
139 }
140
141 // Base class of inline elements
142 class Link
143 {
144         var $start;   // Origin number of parentheses (0 origin)
145         var $text;    // Matched string
146
147         var $type;
148         var $page;
149         var $name;
150         var $body;
151         var $alias;
152
153         // Constructor
154         function Link($start)
155         {
156                 $this->start = $start;
157         }
158
159         // Return a regex pattern to match
160         function get_pattern() {}
161
162         // Return number of parentheses (except (?:...) )
163         function get_count() {}
164
165         // Set pattern that matches
166         function set($arr, $page) {}
167
168         function toString() {}
169
170         // Private: Get needed parts from a matched array()
171         function splice($arr)
172         {
173                 $count = $this->get_count() + 1;
174                 $arr   = array_pad(array_splice($arr, $this->start, $count), $count, '');
175                 $this->text = $arr[0];
176                 return $arr;
177         }
178
179         // Set basic parameters
180         function setParam($page, $name, $body, $type = '', $alias = '')
181         {
182                 static $converter = NULL;
183
184                 $this->page = $page;
185                 $this->name = $name;
186                 $this->body = $body;
187                 $this->type = $type;
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'));
194
195                         $alias = make_line_rules($converter->convert($alias, $page));
196
197                         // BugTrack/669: A hack removing anchor tags added by AutoLink
198                         $alias = preg_replace('#</?a[^>]*>#i', '', $alias);
199                 }
200                 $this->alias = $alias;
201
202                 return TRUE;
203         }
204 }
205
206 // Inline plugins
207 class Link_plugin extends Link
208 {
209         var $pattern;
210         var $plain,$param;
211
212         function Link_plugin($start)
213         {
214                 parent::Link($start);
215         }
216
217         function get_pattern()
218         {
219                 $this->pattern = <<<EOD
220 &
221 (      # (1) plain
222  (\w+) # (2) plugin name
223  (?:
224   \(
225    ((?:(?!\)[;{]).)*) # (3) parameter
226   \)
227  )?
228 )
229 EOD;
230                 return <<<EOD
231 {$this->pattern}
232 (?:
233  \{
234   ((?:(?R)|(?!};).)*) # (4) body
235  \}
236 )?
237 ;
238 EOD;
239         }
240
241         function get_count()
242         {
243                 return 4;
244         }
245
246         function set($arr, $page)
247         {
248                 list($all, $this->plain, $name, $this->param, $body) = $this->splice($arr);
249
250                 // Re-get true plugin name and patameters (for PHP 4.1.2)
251                 $matches = array();
252                 if (preg_match('/^' . $this->pattern . '/x', $all, $matches)
253                         && $matches[1] != $this->plain) 
254                         list(, $this->plain, $name, $this->param) = $matches;
255
256                 return parent::setParam($page, $name, $body, 'plugin');
257         }
258
259         function toString()
260         {
261                 $body = ($this->body == '') ? '' : make_link($this->body);
262                 $str = FALSE;
263
264                 // Try to call the plugin
265                 if (exist_plugin_inline($this->name))
266                         $str = do_plugin_inline($this->name, $this->param, $body);
267
268                 if ($str !== FALSE) {
269                         return $str; // Succeed
270                 } else {
271                         // No such plugin, or Failed
272                         $body = (($body == '') ? '' : '{' . $body . '}') . ';';
273                         return make_line_rules(htmlspecialchars('&' . $this->plain) . $body);
274                 }
275         }
276 }
277
278 // Footnotes
279 class Link_note extends Link
280 {
281         function Link_note($start)
282         {
283                 parent::Link($start);
284         }
285
286         function get_pattern()
287         {
288                 return <<<EOD
289 \(\(
290  ((?:(?R)|(?!\)\)).)*) # (1) note body
291 \)\)
292 EOD;
293         }
294
295         function get_count()
296         {
297                 return 1;
298         }
299
300         function set($arr, $page)
301         {
302                 global $foot_explain, $vars;
303                 static $note_id = 0;
304
305                 list(, $body) = $this->splice($arr);
306
307                 $script = '';
308                 if (! PKWK_ALLOW_RELATIVE_FOOTNOTE_ANCHOR)
309                         $script = get_script_uri() . '?' . $page;
310
311                 $id   = ++$note_id;
312                 $note = make_link($body);
313                 $page = isset($vars['page']) ? rawurlencode($vars['page']) : '';
314
315                 // Footnote
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 />';
320
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>';
325
326                 return parent::setParam($page, $name, $body);
327         }
328
329         function toString()
330         {
331                 return $this->name;
332         }
333 }
334
335 // URLs
336 class Link_url extends Link
337 {
338         function Link_url($start)
339         {
340                 parent::Link($start);
341         }
342
343         function get_pattern()
344         {
345                 $s1 = $this->start + 1;
346                 return <<<EOD
347 (\[\[             # (1) open bracket
348  ((?:(?!\]\]).)+) # (2) alias
349  (?:>|:)
350 )?
351 (                 # (3) url
352  (?:(?:https?|ftp|news):\/\/|mailto:)[\w\/\@\$()!?&%#:;.,~'=*+-]+
353 )
354 (?($s1)\]\])      # close bracket
355 EOD;
356         }
357
358         function get_count()
359         {
360                 return 3;
361         }
362
363         function set($arr, $page)
364         {
365                 list(, , $alias, $name) = $this->splice($arr);
366                 return parent::setParam($page, htmlspecialchars($name),
367                         '', 'url', $alias == '' ? $name : $alias);
368         }
369
370         function toString()
371         {
372                 if (FALSE) {
373                         $rel = '';
374                 } else {
375                         $rel = ' rel="nofollow"';
376                 }
377                 return '<a href="' . $this->name . '"' . $rel . '>' . $this->alias . '</a>';
378         }
379 }
380
381 // URLs (InterWiki definition on "InterWikiName")
382 class Link_url_interwiki extends Link
383 {
384         function Link_url_interwiki($start)
385         {
386                 parent::Link($start);
387         }
388
389         function get_pattern()
390         {
391                 return <<<EOD
392 \[       # open bracket
393 (        # (1) url
394  (?:(?:https?|ftp|news):\/\/|\.\.?\/)[!~*'();\/?:\@&=+\$,%#\w.-]*
395 )
396 \s
397 ([^\]]+) # (2) alias
398 \]       # close bracket
399 EOD;
400         }
401
402         function get_count()
403         {
404                 return 2;
405         }
406
407         function set($arr, $page)
408         {
409                 list(, $name, $alias) = $this->splice($arr);
410                 return parent::setParam($page, htmlspecialchars($name), '', 'url', $alias);
411         }
412
413         function toString()
414         {
415                 return '<a href="' . $this->name . '" rel="nofollow">' . $this->alias . '</a>';
416         }
417 }
418
419 // mailto: URL schemes
420 class Link_mailto extends Link
421 {
422         var $is_image, $image;
423
424         function Link_mailto($start)
425         {
426                 parent::Link($start);
427         }
428
429         function get_pattern()
430         {
431                 $s1 = $this->start + 1;
432                 return <<<EOD
433 (?:
434  \[\[
435  ((?:(?!\]\]).)+)(?:>|:)  # (1) alias
436 )?
437 ([\w.-]+@[\w-]+\.[\w.-]+) # (2) mailto
438 (?($s1)\]\])              # close bracket if (1)
439 EOD;
440         }
441
442         function get_count()
443         {
444                 return 2;
445         }
446
447         function set($arr, $page)
448         {
449                 list(, $alias, $name) = $this->splice($arr);
450                 return parent::setParam($page, $name, '', 'mailto', $alias == '' ? $name : $alias);
451         }
452         
453         function toString()
454         {
455                 return '<a href="mailto:' . $this->name . '" rel="nofollow">' . $this->alias . '</a>';
456         }
457 }
458
459 // InterWikiName-rendered URLs
460 class Link_interwikiname extends Link
461 {
462         var $url    = '';
463         var $param  = '';
464         var $anchor = '';
465
466         function Link_interwikiname($start)
467         {
468                 parent::Link($start);
469         }
470
471         function get_pattern()
472         {
473                 $s2 = $this->start + 2;
474                 $s5 = $this->start + 5;
475                 return <<<EOD
476 \[\[                  # open bracket
477 (?:
478  ((?:(?!\]\]).)+)>    # (1) alias
479 )?
480 (\[\[)?               # (2) open bracket
481 ((?:(?!\s|:|\]\]).)+) # (3) InterWiki
482 (?<! > | >\[\[ )      # not '>' or '>[['
483 :                     # separator
484 (                     # (4) param
485  (\[\[)?              # (5) open bracket
486  (?:(?!>|\]\]).)+
487  (?($s5)\]\])         # close bracket if (5)
488 )
489 (?($s2)\]\])          # close bracket if (2)
490 \]\]                  # close bracket
491 EOD;
492         }
493
494         function get_count()
495         {
496                 return 5;
497         }
498
499         function set($arr, $page)
500         {
501                 global $script;
502
503                 list(, $alias, , $name, $this->param) = $this->splice($arr);
504
505                 $matches = array();
506                 if (preg_match('/^([^#]+)(#[A-Za-z][\w-]*)$/', $this->param, $matches))
507                         list(, $this->param, $this->anchor) = $matches;
508
509                 $url = get_interwiki_url($name, $this->param);
510                 $this->url = ($url === FALSE) ?
511                         $script . '?' . rawurlencode('[[' . $name . ':' . $this->param . ']]') :
512                         htmlspecialchars($url);
513
514                 return parent::setParam(
515                         $page,
516                         htmlspecialchars($name . ':' . $this->param),
517                         '',
518                         'InterWikiName',
519                         $alias == '' ? $name . ':' . $this->param : $alias
520                 );
521         }
522
523         function toString()
524         {
525                 return '<a href="' . $this->url . $this->anchor . '" title="' .
526                         $this->name . '" rel="nofollow">' . $this->alias . '</a>';
527         }
528 }
529
530 // BracketNames
531 class Link_bracketname extends Link
532 {
533         var $anchor, $refer;
534
535         function Link_bracketname($start)
536         {
537                 parent::Link($start);
538         }
539
540         function get_pattern()
541         {
542                 global $WikiName, $BracketName;
543
544                 $s2 = $this->start + 2;
545                 return <<<EOD
546 \[\[                     # Open bracket
547 (?:((?:(?!\]\]).)+)>)?   # (1) Alias
548 (\[\[)?                  # (2) Open bracket
549 (                        # (3) PageName
550  (?:$WikiName)
551  |
552  (?:$BracketName)
553 )?
554 (\#(?:[a-zA-Z][\w-]*)?)? # (4) Anchor
555 (?($s2)\]\])             # Close bracket if (2)
556 \]\]                     # Close bracket
557 EOD;
558         }
559
560         function get_count()
561         {
562                 return 4;
563         }
564
565         function set($arr, $page)
566         {
567                 global $WikiName;
568
569                 list(, $alias, , $name, $this->anchor) = $this->splice($arr);
570                 if ($name == '' && $this->anchor == '') return FALSE;
571
572                 if ($name == '' || ! preg_match('/^' . $WikiName . '$/', $name)) {
573                         if ($alias == '') $alias = $name . $this->anchor;
574                         if ($name != '') {
575                                 $name = get_fullname($name, $page);
576                                 if (! is_pagename($name)) return FALSE;
577                         }
578                 }
579
580                 return parent::setParam($page, $name, '', 'pagename', $alias);
581         }
582
583         function toString()
584         {
585                 return make_pagelink(
586                         $this->name,
587                         $this->alias,
588                         $this->anchor,
589                         $this->page
590                 );
591         }
592 }
593
594 // WikiNames
595 class Link_wikiname extends Link
596 {
597         function Link_wikiname($start)
598         {
599                 parent::Link($start);
600         }
601
602         function get_pattern()
603         {
604                 global $WikiName, $nowikiname;
605
606                 return $nowikiname ? FALSE : '(' . $WikiName . ')';
607         }
608
609         function get_count()
610         {
611                 return 1;
612         }
613
614         function set($arr, $page)
615         {
616                 list($name) = $this->splice($arr);
617                 return parent::setParam($page, $name, '', 'pagename', $name);
618         }
619
620         function toString()
621         {
622                 return make_pagelink(
623                         $this->name,
624                         $this->alias,
625                         '',
626                         $this->page
627                 );
628         }
629 }
630
631 // AutoLinks
632 class Link_autolink extends Link
633 {
634         var $forceignorepages = array();
635         var $auto;
636         var $auto_a; // alphabet only
637
638         function Link_autolink($start)
639         {
640                 global $autolink;
641
642                 parent::Link($start);
643
644                 if (! $autolink || ! file_exists(CACHE_DIR . 'autolink.dat'))
645                         return;
646
647                 @list($auto, $auto_a, $forceignorepages) = file(CACHE_DIR . 'autolink.dat');
648                 $this->auto   = $auto;
649                 $this->auto_a = $auto_a;
650                 $this->forceignorepages = explode("\t", trim($forceignorepages));
651         }
652
653         function get_pattern()
654         {
655                 return isset($this->auto) ? '(' . $this->auto . ')' : FALSE;
656         }
657
658         function get_count()
659         {
660                 return 1;
661         }
662
663         function set($arr, $page)
664         {
665                 global $WikiName;
666
667                 list($name) = $this->splice($arr);
668
669                 // Ignore pages listed, or Expire ones not found
670                 if (in_array($name, $this->forceignorepages) || ! is_page($name))
671                         return FALSE;
672
673                 return parent::setParam($page, $name, '', 'pagename', $name);
674         }
675
676         function toString()
677         {
678                 return make_pagelink($this->name, $this->alias, '', $this->page, TRUE);
679         }
680 }
681
682 class Link_autolink_a extends Link_autolink
683 {
684         function Link_autolink_a($start)
685         {
686                 parent::Link_autolink($start);
687         }
688
689         function get_pattern()
690         {
691                 return isset($this->auto_a) ? '(' . $this->auto_a . ')' : FALSE;
692         }
693 }
694
695 // Make hyperlink for the page
696 function make_pagelink($page, $alias = '', $anchor = '', $refer = '', $isautolink = FALSE)
697 {
698         global $script, $vars, $link_compact, $related, $_symbol_noexists;
699
700         $s_page = htmlspecialchars(strip_bracket($page));
701         $s_alias = ($alias == '') ? $s_page : $alias;
702
703         if ($page == '') return '<a href="' . $anchor . '">' . $s_alias . '</a>';
704
705         $r_page  = rawurlencode($page);
706         $r_refer = ($refer == '') ? '' : '&amp;refer=' . rawurlencode($refer);
707
708         if (! isset($related[$page]) && $page != $vars['page'] && is_page($page))
709                 $related[$page] = get_filetime($page);
710
711         if ($isautolink || is_page($page)) {
712                 // Hyperlink to the page
713                 if ($link_compact) {
714                         $title   = '';
715                 } else {
716                         $title   = ' title="' . $s_page . get_pg_passage($page, FALSE) . '"';
717                 }
718
719                 // AutoLink marker
720                 if ($isautolink) {
721                         $al_left  = '<!--autolink-->';
722                         $al_right = '<!--/autolink-->';
723                 } else {
724                         $al_left = $al_right = '';
725                 }
726
727                 return $al_left . '<a ' . 'href="' . $script . '?' . $r_page . $anchor .
728                         '"' . $title . '>' . $s_alias . '</a>' . $al_right;
729         } else {
730                 // Dangling link
731                 if (PKWK_READONLY) return $s_alias; // No dacorations
732
733                 $retval = $s_alias . '<a href="' .
734                         $script . '?cmd=edit&amp;page=' . $r_page . $r_refer . '">' .
735                         $_symbol_noexists . '</a>';
736
737                 if ($link_compact) {
738                         return $retval;
739                 } else {
740                         return '<span class="noexists">' . $retval . '</span>';
741                 }
742         }
743 }
744
745 // Resolve relative / (Unix-like)absolute path of the page
746 function get_fullname($name, $refer)
747 {
748         global $defaultpage;
749
750         // 'Here'
751         if ($name == '' || $name == './') return $refer;
752
753         // Absolute path
754         if ($name{0} == '/') {
755                 $name = substr($name, 1);
756                 return ($name == '') ? $defaultpage : $name;
757         }
758
759         // Relative path from 'Here'
760         if (substr($name, 0, 2) == './') {
761                 $arrn    = preg_split('#/#', $name, -1, PREG_SPLIT_NO_EMPTY);
762                 $arrn[0] = $refer;
763                 return join('/', $arrn);
764         }
765
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);
770
771                 while (! empty($arrn) && $arrn[0] == '..') {
772                         array_shift($arrn);
773                         array_pop($arrp);
774                 }
775                 $name = ! empty($arrp) ? join('/', array_merge($arrp, $arrn)) :
776                         (! empty($arrn) ? $defaultpage . '/' . join('/', $arrn) : $defaultpage);
777         }
778
779         return $name;
780 }
781
782 // Render an InterWiki into a URL
783 function get_interwiki_url($name, $param)
784 {
785         global $WikiName, $interwiki;
786         static $interwikinames;
787         static $encode_aliases = array('sjis'=>'SJIS', 'euc'=>'EUC-JP', 'utf8'=>'UTF-8');
788
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]*)/',
794                             $line, $matches))
795                                 $interwikinames[$matches[2]] = array($matches[1], $matches[3]);
796         }
797
798         if (! isset($interwikinames[$name])) return FALSE;
799
800         list($url, $opt) = $interwikinames[$name];
801
802         // Encoding
803         switch ($opt) {
804
805         case '':    /* FALLTHROUGH */
806         case 'std': // Simply URL-encode the string, whose base encoding is the internal-encoding
807                 $param = rawurlencode($param);
808                 break;
809
810         case 'asis': /* FALLTHROUGH */
811         case 'raw' : // Truly as-is
812                 break;
813
814         case 'yw': // YukiWiki
815                 if (! preg_match('/' . $WikiName . '/', $param))
816                         $param = '[[' . mb_convert_encoding($param, 'SJIS', SOURCE_ENCODING) . ']]';
817                 break;
818
819         case 'moin': // MoinMoin
820                 $param = str_replace('%', '_', rawurlencode($param));
821                 break;
822
823         default:
824                 // Alias conversion of $opt
825                 if (isset($encode_aliases[$opt])) $opt = & $encode_aliases[$opt];
826
827                 // Encoding conversion into specified encode, and URLencode
828                 $param = rawurlencode(mb_convert_encoding($param, $opt, SOURCE_ENCODING));
829         }
830
831         // Replace or Add the parameter
832         if (strpos($url, '$1') !== FALSE) {
833                 $url = str_replace('$1', $param, $url);
834         } else {
835                 $url .= $param;
836         }
837
838         $len = strlen($url);
839         if ($len > 512) die_message('InterWiki URL too long: ' . $len . ' characters');
840
841         return $url;
842 }
843 ?>