OSDN Git Service

BugTrack2/171: Added a PCRE modifiers ''S''.
[pukiwiki/pukiwiki.git] / lib / html.php
1 <?php
2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // $Id: html.php,v 1.57 2006/04/15 17:33:35 teanan Exp $
4 // Copyright (C)
5 //   2002-2006 PukiWiki Developers Team
6 //   2001-2002 Originally written by yu-ji
7 // License: GPL v2 or (at your option) any later version
8 //
9 // HTML-publishing related functions
10
11 // Show page-content
12 function catbody($title, $page, $body)
13 {
14         global $script, $vars, $arg, $defaultpage, $whatsnew, $help_page, $hr;
15         global $attach_link, $related_link, $cantedit, $function_freeze;
16         global $search_word_color, $_msg_word, $foot_explain, $note_hr, $head_tags;
17         global $trackback, $trackback_javascript, $referer, $javascript;
18         global $nofollow;
19         global $_LANG, $_LINK, $_IMAGE;
20
21         global $pkwk_dtd;     // XHTML 1.1, XHTML1.0, HTML 4.01 Transitional...
22         global $page_title;   // Title of this site
23         global $do_backup;    // Do backup or not
24         global $modifier;     // Site administrator's  web page
25         global $modifierlink; // Site administrator's name
26
27         if (! file_exists(SKIN_FILE) || ! is_readable(SKIN_FILE))
28                 die_message('SKIN_FILE is not found');
29
30         $_LINK = $_IMAGE = array();
31
32         // Add JavaScript header when ...
33         if ($trackback && $trackback_javascript) $javascript = 1; // Set something If you want
34         if (! PKWK_ALLOW_JAVASCRIPT) unset($javascript);
35
36         $_page  = isset($vars['page']) ? $vars['page'] : '';
37         $r_page = rawurlencode($_page);
38
39         // Set $_LINK for skin
40         $_LINK['add']      = "$script?cmd=add&amp;page=$r_page";
41         $_LINK['backup']   = "$script?cmd=backup&amp;page=$r_page";
42         $_LINK['copy']     = "$script?plugin=template&amp;refer=$r_page";
43         $_LINK['diff']     = "$script?cmd=diff&amp;page=$r_page";
44         $_LINK['edit']     = "$script?cmd=edit&amp;page=$r_page";
45         $_LINK['filelist'] = "$script?cmd=filelist";
46         $_LINK['freeze']   = "$script?cmd=freeze&amp;page=$r_page";
47         $_LINK['help']     = "$script?" . rawurlencode($help_page);
48         $_LINK['list']     = "$script?cmd=list";
49         $_LINK['new']      = "$script?plugin=newpage&amp;refer=$r_page";
50         $_LINK['rdf']      = "$script?cmd=rss&amp;ver=1.0";
51         $_LINK['recent']   = "$script?" . rawurlencode($whatsnew);
52         $_LINK['refer']    = "$script?plugin=referer&amp;page=$r_page";
53         $_LINK['reload']   = "$script?$r_page";
54         $_LINK['rename']   = "$script?plugin=rename&amp;refer=$r_page";
55         $_LINK['rss']      = "$script?cmd=rss";
56         $_LINK['rss10']    = "$script?cmd=rss&amp;ver=1.0"; // Same as 'rdf'
57         $_LINK['rss20']    = "$script?cmd=rss&amp;ver=2.0";
58         $_LINK['search']   = "$script?cmd=search";
59         $_LINK['top']      = "$script?" . rawurlencode($defaultpage);
60         if ($trackback) {
61                 $tb_id = tb_get_id($_page);
62                 $_LINK['trackback'] = "$script?plugin=tb&amp;__mode=view&amp;tb_id=$tb_id";
63         }
64         $_LINK['unfreeze'] = "$script?cmd=unfreeze&amp;page=$r_page";
65         $_LINK['upload']   = "$script?plugin=attach&amp;pcmd=upload&amp;page=$r_page";
66
67         // Compat: Skins for 1.4.4 and before
68         $link_add       = & $_LINK['add'];
69         $link_new       = & $_LINK['new'];      // New!
70         $link_edit      = & $_LINK['edit'];
71         $link_diff      = & $_LINK['diff'];
72         $link_top       = & $_LINK['top'];
73         $link_list      = & $_LINK['list'];
74         $link_filelist  = & $_LINK['filelist'];
75         $link_search    = & $_LINK['search'];
76         $link_whatsnew  = & $_LINK['recent'];
77         $link_backup    = & $_LINK['backup'];
78         $link_help      = & $_LINK['help'];
79         $link_trackback = & $_LINK['trackback'];        // New!
80         $link_rdf       = & $_LINK['rdf'];              // New!
81         $link_rss       = & $_LINK['rss'];
82         $link_rss10     = & $_LINK['rss10'];            // New!
83         $link_rss20     = & $_LINK['rss20'];            // New!
84         $link_freeze    = & $_LINK['freeze'];
85         $link_unfreeze  = & $_LINK['unfreeze'];
86         $link_upload    = & $_LINK['upload'];
87         $link_template  = & $_LINK['copy'];
88         $link_refer     = & $_LINK['refer'];    // New!
89         $link_rename    = & $_LINK['rename'];
90
91         // Init flags
92         $is_page = (is_pagename($_page) && ! arg_check('backup') && $_page != $whatsnew);
93         $is_read = (arg_check('read') && is_page($_page));
94         $is_freeze = is_freeze($_page);
95
96         // Last modification date (string) of the page
97         $lastmodified = $is_read ?  format_date(get_filetime($_page)) .
98                 ' ' . get_pg_passage($_page, FALSE) : '';
99
100         // List of attached files to the page
101         $attaches = ($attach_link && $is_read && exist_plugin_action('attach')) ?
102                 attach_filelist() : '';
103
104         // List of related pages
105         $related  = ($related_link && $is_read) ? make_related($_page) : '';
106
107         // List of footnotes
108         ksort($foot_explain, SORT_NUMERIC);
109         $notes = ! empty($foot_explain) ? $note_hr . join("\n", $foot_explain) : '';
110
111         // Tags will be inserted into <head></head>
112         $head_tag = ! empty($head_tags) ? join("\n", $head_tags) ."\n" : '';
113
114         // 1.3.x compat
115         // Last modification date (UNIX timestamp) of the page
116         $fmt = $is_read ? get_filetime($_page) + LOCALZONE : 0;
117
118         // Search words
119         if ($search_word_color && isset($vars['word'])) {
120                 $body = '<div class="small">' . $_msg_word . htmlspecialchars($vars['word']) .
121                         '</div>' . $hr . "\n" . $body;
122
123                 // BugTrack2/106: Only variables can be passed by reference from PHP 5.0.5
124                 // with array_splice(), array_flip()
125                 $words = preg_split('/\s+/', $vars['word'], -1, PREG_SPLIT_NO_EMPTY);
126                 $words = array_splice($words, 0, 10); // Max: 10 words
127                 $words = array_flip($words);
128
129                 $keys = array();
130                 foreach ($words as $word=>$id) $keys[$word] = strlen($word);
131                 arsort($keys, SORT_NUMERIC);
132                 $keys = get_search_words(array_keys($keys), TRUE);
133                 $id = 0;
134                 foreach ($keys as $key=>$pattern) {
135                         $s_key    = htmlspecialchars($key);
136                         $pattern  = '/' .
137                                 '<textarea[^>]*>.*?<\/textarea>' .      // Ignore textareas
138                                 '|' . '<[^>]*>' .                       // Ignore tags
139                                 '|' . '&[^;]+;' .                       // Ignore entities
140                                 '|' . '(' . $pattern . ')' .            // $matches[1]: Regex for a search word
141                                 '/sS';
142                         $decorate_Nth_word = create_function(
143                                 '$matches',
144                                 'return (isset($matches[1])) ? ' .
145                                         '\'<strong class="word' .
146                                                 $id .
147                                         '">\' . $matches[1] . \'</strong>\' : ' .
148                                         '$matches[0];'
149                         );
150                         $body  = preg_replace_callback($pattern, $decorate_Nth_word, $body);
151                         $notes = preg_replace_callback($pattern, $decorate_Nth_word, $notes);
152                         ++$id;
153                 }
154         }
155
156         $longtaketime = getmicrotime() - MUTIME;
157         $taketime     = sprintf('%01.03f', $longtaketime);
158
159         require(SKIN_FILE);
160 }
161
162 // Show 'edit' form
163 function edit_form($page, $postdata, $digest = FALSE, $b_template = TRUE)
164 {
165         global $script, $vars, $rows, $cols, $hr, $function_freeze;
166         global $_btn_preview, $_btn_repreview, $_btn_update, $_btn_cancel, $_msg_help;
167         global $whatsnew, $_btn_template, $_btn_load, $load_template_func;
168         global $notimeupdate;
169
170         // Newly generate $digest or not
171         if ($digest === FALSE) $digest = md5(join('', get_source($page)));
172
173         $refer = $template = '';
174  
175         // Add plugin
176         $addtag = $add_top = '';
177         if(isset($vars['add'])) {
178                 global $_btn_addtop;
179                 $addtag  = '<input type="hidden" name="add"    value="true" />';
180                 $add_top = isset($vars['add_top']) ? ' checked="checked"' : '';
181                 $add_top = '<input type="checkbox" name="add_top" ' .
182                         'id="_edit_form_add_top" value="true"' . $add_top . ' />' . "\n" .
183                         '  <label for="_edit_form_add_top">' .
184                                 '<span class="small">' . $_btn_addtop . '</span>' .
185                         '</label>';
186         }
187
188         if($load_template_func && $b_template) {
189                 $pages  = array();
190                 foreach(get_existpages() as $_page) {
191                         if ($_page == $whatsnew || check_non_list($_page))
192                                 continue;
193                         $s_page = htmlspecialchars($_page);
194                         $pages[$_page] = '   <option value="' . $s_page . '">' .
195                                 $s_page . '</option>';
196                 }
197                 ksort($pages);
198                 $s_pages  = join("\n", $pages);
199                 $template = <<<EOD
200   <select name="template_page">
201    <option value="">-- $_btn_template --</option>
202 $s_pages
203   </select>
204   <input type="submit" name="template" value="$_btn_load" accesskey="r" />
205   <br />
206 EOD;
207
208                 if (isset($vars['refer']) && $vars['refer'] != '')
209                         $refer = '[[' . strip_bracket($vars['refer']) . ']]' . "\n\n";
210         }
211
212         $r_page      = rawurlencode($page);
213         $s_page      = htmlspecialchars($page);
214         $s_digest    = htmlspecialchars($digest);
215         $s_postdata  = htmlspecialchars($refer . $postdata);
216         $s_original  = isset($vars['original']) ? htmlspecialchars($vars['original']) : $s_postdata;
217         $b_preview   = isset($vars['preview']); // TRUE when preview
218         $btn_preview = $b_preview ? $_btn_repreview : $_btn_preview;
219
220         // Checkbox 'do not change timestamp'
221         $add_notimestamp = '';
222         if ($notimeupdate != 0) {
223                 global $_btn_notchangetimestamp;
224                 $checked_time = isset($vars['notimestamp']) ? ' checked="checked"' : '';
225                 // Only for administrator
226                 if ($notimeupdate == 2) {
227                         $add_notimestamp = '   ' .
228                                 '<input type="password" name="pass" size="12" />' . "\n";
229                 }
230                 $add_notimestamp = '<input type="checkbox" name="notimestamp" ' .
231                         'id="_edit_form_notimestamp" value="true"' . $checked_time . ' />' . "\n" .
232                         '   ' . '<label for="_edit_form_notimestamp"><span class="small">' .
233                         $_btn_notchangetimestamp . '</span></label>' . "\n" .
234                         $add_notimestamp .
235                         '&nbsp;';
236         }
237
238         // 'margin-bottom', 'float:left', and 'margin-top'
239         // are for layout of 'cancel button'
240         $body = <<<EOD
241 <div class="edit_form">
242  <form action="$script" method="post" style="margin-bottom:0px;">
243 $template
244   $addtag
245   <input type="hidden" name="cmd"    value="edit" />
246   <input type="hidden" name="page"   value="$s_page" />
247   <input type="hidden" name="digest" value="$s_digest" />
248   <textarea name="msg" rows="$rows" cols="$cols">$s_postdata</textarea>
249   <br />
250   <div style="float:left;">
251    <input type="submit" name="preview" value="$btn_preview" accesskey="p" />
252    <input type="submit" name="write"   value="$_btn_update" accesskey="s" />
253    $add_top
254    $add_notimestamp
255   </div>
256   <textarea name="original" rows="1" cols="1" style="display:none">$s_original</textarea>
257  </form>
258  <form action="$script" method="post" style="margin-top:0px;">
259   <input type="hidden" name="cmd"    value="edit" />
260   <input type="hidden" name="page"   value="$s_page" />
261   <input type="submit" name="cancel" value="$_btn_cancel" accesskey="c" />
262  </form>
263 </div>
264 EOD;
265
266         if (isset($vars['help'])) {
267                 $body .= $hr . catrule();
268         } else {
269                 $body .= '<ul><li><a href="' .
270                         $script . '?cmd=edit&amp;help=true&amp;page=' . $r_page .
271                         '">' . $_msg_help . '</a></li></ul>';
272         }
273
274         return $body;
275 }
276
277 // Related pages
278 function make_related($page, $tag = '')
279 {
280         global $script, $vars, $rule_related_str, $related_str;
281         global $_ul_left_margin, $_ul_margin, $_list_pad_str;
282
283         $links = links_get_related($page);
284
285         if ($tag) {
286                 ksort($links);
287         } else {
288                 arsort($links);
289         }
290
291         $_links = array();
292         foreach ($links as $page=>$lastmod) {
293                 if (check_non_list($page)) continue;
294
295                 $r_page   = rawurlencode($page);
296                 $s_page   = htmlspecialchars($page);
297                 $passage  = get_passage($lastmod);
298                 $_links[] = $tag ?
299                         '<a href="' . $script . '?' . $r_page . '" title="' .
300                         $s_page . ' ' . $passage . '">' . $s_page . '</a>' :
301                         '<a href="' . $script . '?' . $r_page . '">' .
302                         $s_page . '</a>' . $passage;
303         }
304         if (empty($_links)) return ''; // Nothing
305
306         if ($tag == 'p') { // From the line-head
307                 $margin = $_ul_left_margin + $_ul_margin;
308                 $style  = sprintf($_list_pad_str, 1, $margin, $margin);
309                 $retval =  "\n" . '<ul' . $style . '>' . "\n" .
310                         '<li>' . join($rule_related_str, $_links) . '</li>' . "\n" .
311                         '</ul>' . "\n";
312         } else if ($tag) {
313                 $retval = join($rule_related_str, $_links);
314         } else {
315                 $retval = join($related_str, $_links);
316         }
317
318         return $retval;
319 }
320
321 // User-defined rules (convert without replacing source)
322 function make_line_rules($str)
323 {
324         global $line_rules;
325         static $pattern, $replace;
326
327         if (! isset($pattern)) {
328                 $pattern = array_map(create_function('$a',
329                         'return \'/\' . $a . \'/\';'), array_keys($line_rules));
330                 $replace = array_values($line_rules);
331                 unset($line_rules);
332         }
333
334         return preg_replace($pattern, $replace, $str);
335 }
336
337 // Remove all HTML tags(or just anchor tags), and WikiName-speific decorations
338 function strip_htmltag($str, $all = TRUE)
339 {
340         global $_symbol_noexists;
341         static $noexists_pattern;
342
343         if (! isset($noexists_pattern))
344                 $noexists_pattern = '#<span class="noexists">([^<]*)<a[^>]+>' .
345                         preg_quote($_symbol_noexists, '#') . '</a></span>#';
346
347         // Strip Dagnling-Link decoration (Tags and "$_symbol_noexists")
348         $str = preg_replace($noexists_pattern, '$1', $str);
349
350         if ($all) {
351                 // All other HTML tags
352                 return preg_replace('#<[^>]+>#',        '', $str);
353         } else {
354                 // All other anchor-tags only
355                 return preg_replace('#<a[^>]+>|</a>#i', '', $str);
356         }
357 }
358
359 // Remove AutoLink marker with AutLink itself
360 function strip_autolink($str)
361 {
362         return preg_replace('#<!--autolink--><a [^>]+>|</a><!--/autolink-->#', '', $str);
363 }
364
365 // Make a backlink. searching-link of the page name, by the page name, for the page name
366 function make_search($page)
367 {
368         global $script;
369
370         $s_page = htmlspecialchars($page);
371         $r_page = rawurlencode($page);
372
373         return '<a href="' . $script . '?plugin=related&amp;page=' . $r_page .
374                 '">' . $s_page . '</a> ';
375 }
376
377 // Make heading string (remove heading-related decorations from Wiki text)
378 function make_heading(& $str, $strip = TRUE)
379 {
380         global $NotePattern;
381
382         // Cut fixed-heading anchors
383         $id = '';
384         $matches = array();
385         if (preg_match('/^(\*{0,3})(.*?)\[#([A-Za-z][\w-]+)\](.*?)$/m', $str, $matches)) {
386                 $str = $matches[2] . $matches[4];
387                 $id  = & $matches[3];
388         } else {
389                 $str = preg_replace('/^\*{0,3}/', '', $str);
390         }
391
392         // Cut footnotes and tags
393         if ($strip === TRUE)
394                 $str = strip_htmltag(make_link(preg_replace($NotePattern, '', $str)));
395
396         return $id;
397 }
398
399 // Separate a page-name(or URL or null string) and an anchor
400 // (last one standing) without sharp
401 function anchor_explode($page, $strict_editable = FALSE)
402 {
403         $pos = strrpos($page, '#');
404         if ($pos === FALSE) return array($page, '', FALSE);
405
406         // Ignore the last sharp letter
407         if ($pos + 1 == strlen($page)) {
408                 $pos = strpos(substr($page, $pos + 1), '#');
409                 if ($pos === FALSE) return array($page, '', FALSE);
410         }
411
412         $s_page = substr($page, 0, $pos);
413         $anchor = substr($page, $pos + 1);
414
415         if($strict_editable === TRUE &&  preg_match('/^[a-z][a-f0-9]{7}$/', $anchor)) {
416                 return array ($s_page, $anchor, TRUE); // Seems fixed-anchor
417         } else {
418                 return array ($s_page, $anchor, FALSE);
419         }
420 }
421
422 // Check HTTP header()s were sent already, or
423 // there're blank lines or something out of php blocks
424 function pkwk_headers_sent()
425 {
426         if (PKWK_OPTIMISE) return;
427
428         $file = $line = '';
429         if (version_compare(PHP_VERSION, '4.3.0', '>=')) {
430                 if (headers_sent($file, $line))
431                     die('Headers already sent at ' .
432                         htmlspecialchars($file) .
433                         ' line ' . $line . '.');
434         } else {
435                 if (headers_sent())
436                         die('Headers already sent.');
437         }
438 }
439
440 // Output common HTTP headers
441 function pkwk_common_headers()
442 {
443         if (! PKWK_OPTIMISE) pkwk_headers_sent();
444
445         if(defined('PKWK_ZLIB_LOADABLE_MODULE')) {
446                 $matches = array();
447                 if(ini_get('zlib.output_compression') &&
448                     preg_match('/\b(gzip|deflate)\b/i', $_SERVER['HTTP_ACCEPT_ENCODING'], $matches)) {
449                         // Bug #29350 output_compression compresses everything _without header_ as loadable module
450                         // http://bugs.php.net/bug.php?id=29350
451                         header('Content-Encoding: ' . $matches[1]);
452                         header('Vary: Accept-Encoding');
453                 }
454         }
455 }
456
457 // DTD definitions
458 define('PKWK_DTD_XHTML_1_1',              17); // Strict only
459 define('PKWK_DTD_XHTML_1_0',              16); // Strict
460 define('PKWK_DTD_XHTML_1_0_STRICT',       16);
461 define('PKWK_DTD_XHTML_1_0_TRANSITIONAL', 15);
462 define('PKWK_DTD_XHTML_1_0_FRAMESET',     14);
463 define('PKWK_DTD_HTML_4_01',               3); // Strict
464 define('PKWK_DTD_HTML_4_01_STRICT',        3);
465 define('PKWK_DTD_HTML_4_01_TRANSITIONAL',  2);
466 define('PKWK_DTD_HTML_4_01_FRAMESET',      1);
467
468 define('PKWK_DTD_TYPE_XHTML',  1);
469 define('PKWK_DTD_TYPE_HTML',   0);
470
471 // Output HTML DTD, <html> start tag. Return content-type.
472 function pkwk_output_dtd($pkwk_dtd = PKWK_DTD_XHTML_1_1, $charset = CONTENT_CHARSET)
473 {
474         static $called;
475         if (isset($called)) die('pkwk_output_dtd() already called. Why?');
476         $called = TRUE;
477
478         $type = PKWK_DTD_TYPE_XHTML;
479         $option = '';
480         switch($pkwk_dtd){
481         case PKWK_DTD_XHTML_1_1             :
482                 $version = '1.1' ;
483                 $dtd     = 'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd';
484                 break;
485         case PKWK_DTD_XHTML_1_0_STRICT      :
486                 $version = '1.0' ;
487                 $option  = 'Strict';
488                 $dtd     = 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd';
489                 break;
490         case PKWK_DTD_XHTML_1_0_TRANSITIONAL:
491                 $version = '1.0' ;
492                 $option  = 'Transitional';
493                 $dtd     = 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd';
494                 break;
495
496         case PKWK_DTD_HTML_4_01_STRICT      :
497                 $type    = PKWK_DTD_TYPE_HTML;
498                 $version = '4.01';
499                 $dtd     = 'http://www.w3.org/TR/html4/strict.dtd';
500                 break;
501         case PKWK_DTD_HTML_4_01_TRANSITIONAL:
502                 $type    = PKWK_DTD_TYPE_HTML;
503                 $version = '4.01';
504                 $option  = 'Transitional';
505                 $dtd     = 'http://www.w3.org/TR/html4/loose.dtd';
506                 break;
507
508         default: die('DTD not specified or invalid DTD');
509                 break;
510         }
511
512         $charset = htmlspecialchars($charset);
513
514         // Output XML or not
515         if ($type == PKWK_DTD_TYPE_XHTML) echo '<?xml version="1.0" encoding="' . $charset . '" ?>' . "\n";
516
517         // Output doctype
518         echo '<!DOCTYPE html PUBLIC "-//W3C//DTD ' .
519                 ($type == PKWK_DTD_TYPE_XHTML ? 'XHTML' : 'HTML') . ' ' .
520                 $version .
521                 ($option != '' ? ' ' . $option : '') .
522                 '//EN" "' .
523                 $dtd .
524                 '">' . "\n";
525
526         // Output <html> start tag
527         echo '<html';
528         if ($type == PKWK_DTD_TYPE_XHTML) {
529                 echo ' xmlns="http://www.w3.org/1999/xhtml"'; // dir="ltr" /* LeftToRight */
530                 echo ' xml:lang="' . LANG . '"';
531                 if ($version == '1.0') echo ' lang="' . LANG . '"'; // Only XHTML 1.0
532         } else {
533                 echo ' lang="' . LANG . '"'; // HTML
534         }
535         echo '>' . "\n"; // <html>
536
537         // Return content-type (with MIME type)
538         if ($type == PKWK_DTD_TYPE_XHTML) {
539                 // NOTE: XHTML 1.1 browser will ignore http-equiv
540                 return '<meta http-equiv="content-type" content="application/xhtml+xml; charset=' . $charset . '" />' . "\n";
541         } else {
542                 return '<meta http-equiv="content-type" content="text/html; charset=' . $charset . '" />' . "\n";
543         }
544 }
545 ?>