OSDN Git Service

BugTrack/2247 External link cushion page - Control Referer etc.
[pukiwiki/pukiwiki.git] / lib / html.php
1 <?php
2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // html.php
4 // Copyright
5 //   2002-2017 PukiWiki Development 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 $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 $javascript, $nofollow;
18         global $_LANG, $_LINK, $_IMAGE;
19         global $auth_type, $auth_user;
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         $script = get_base_uri();
28         $enable_login = false;
29         $enable_logout = false;
30         if (AUTH_TYPE_FORM === $auth_type || AUTH_TYPE_EXTERNAL === $auth_type ||
31                 AUTH_TYPE_SAML === $auth_type) {
32                 if ($auth_user) {
33                         $enable_logout = true;
34                 } else {
35                         $enable_login = true;
36                 }
37         } else if (AUTH_TYPE_BASIC === $auth_type) {
38                 if ($auth_user) {
39                         $enable_logout = true;
40                 }
41         }
42         if (! file_exists(SKIN_FILE) || ! is_readable(SKIN_FILE))
43                 die_message('SKIN_FILE is not found');
44
45         $_LINK = $_IMAGE = array();
46
47         $_page  = isset($vars['page']) ? $vars['page'] : '';
48         $r_page = pagename_urlencode($_page);
49
50         // Canonical URL
51         $canonical_url = get_page_uri($_page, PKWK_URI_ABSOLUTE);
52
53         // Set $_LINK for skin
54         $_LINK['add']      = "$script?cmd=add&amp;page=$r_page";
55         $_LINK['backup']   = "$script?cmd=backup&amp;page=$r_page";
56         $_LINK['copy']     = "$script?plugin=template&amp;refer=$r_page";
57         $_LINK['diff']     = "$script?cmd=diff&amp;page=$r_page";
58         $_LINK['edit']     = "$script?cmd=edit&amp;page=$r_page";
59         $_LINK['filelist'] = "$script?cmd=filelist";
60         $_LINK['freeze']   = "$script?cmd=freeze&amp;page=$r_page";
61         $_LINK['help']     = get_page_uri($help_page);
62         $_LINK['list']     = "$script?cmd=list";
63         $_LINK['new']      = "$script?plugin=newpage&amp;refer=$r_page";
64         $_LINK['rdf']      = "$script?cmd=rss&amp;ver=1.0";
65         $_LINK['recent']   = get_page_uri($whatsnew);
66         $_LINK['reload']   = get_page_uri($_page);
67         $_LINK['rename']   = "$script?plugin=rename&amp;refer=$r_page";
68         $_LINK['rss']      = "$script?cmd=rss";
69         $_LINK['rss10']    = "$script?cmd=rss&amp;ver=1.0"; // Same as 'rdf'
70         $_LINK['rss20']    = "$script?cmd=rss&amp;ver=2.0";
71         $_LINK['search']   = "$script?cmd=search";
72         $_LINK['top']      = get_page_uri($defaultpage);
73         $_LINK['unfreeze'] = "$script?cmd=unfreeze&amp;page=$r_page";
74         $_LINK['upload']   = "$script?plugin=attach&amp;pcmd=upload&amp;page=$r_page";
75         $_LINK['canonical_url'] = $canonical_url;
76         $login_link = "#LOGIN_ERROR"; // dummy link that is not used
77         switch ($auth_type) {
78                 case AUTH_TYPE_FORM:
79                         $login_link = "$script?plugin=loginform&pcmd=login&page=$r_page";
80                         break;
81                 case AUTH_TYPE_EXTERNAL:
82                 case AUTH_TYPE_SAML:
83                         $login_link = get_auth_external_login_url($_page, $_LINK['reload']);
84                         break;
85         }
86         $_LINK['login']    = htmlsc($login_link);
87         $_LINK['logout']   = "$script?plugin=loginform&amp;pcmd=logout&amp;page=$r_page";
88
89         // Compat: Skins for 1.4.4 and before
90         $link_add       = & $_LINK['add'];
91         $link_new       = & $_LINK['new'];      // New!
92         $link_edit      = & $_LINK['edit'];
93         $link_diff      = & $_LINK['diff'];
94         $link_top       = & $_LINK['top'];
95         $link_list      = & $_LINK['list'];
96         $link_filelist  = & $_LINK['filelist'];
97         $link_search    = & $_LINK['search'];
98         $link_whatsnew  = & $_LINK['recent'];
99         $link_backup    = & $_LINK['backup'];
100         $link_help      = & $_LINK['help'];
101         $link_trackback = ''; // Removed (compat)
102         $link_rdf       = & $_LINK['rdf'];              // New!
103         $link_rss       = & $_LINK['rss'];
104         $link_rss10     = & $_LINK['rss10'];            // New!
105         $link_rss20     = & $_LINK['rss20'];            // New!
106         $link_freeze    = & $_LINK['freeze'];
107         $link_unfreeze  = & $_LINK['unfreeze'];
108         $link_upload    = & $_LINK['upload'];
109         $link_template  = & $_LINK['copy'];
110         $link_refer     = ''; // Removed (compat)
111         $link_rename    = & $_LINK['rename'];
112
113         // Init flags
114         $is_page = (is_pagename($_page) && ! arg_check('backup') && $_page != $whatsnew);
115         $is_read = (arg_check('read') && is_page($_page));
116         $is_freeze = is_freeze($_page);
117
118         // Last modification date (string) of the page
119         $lastmodified = $is_read ?  format_date(get_filetime($_page)) .
120                 get_passage_html_span($_page) : '';
121
122         // List of attached files to the page
123         $show_attaches = $is_read || arg_check('edit');
124         $attaches = ($attach_link && $show_attaches && exist_plugin_action('attach')) ?
125                 attach_filelist() : '';
126
127         // List of related pages
128         $related  = ($related_link && $is_read) ? make_related($_page) : '';
129
130         // List of footnotes
131         ksort($foot_explain, SORT_NUMERIC);
132         $notes = ! empty($foot_explain) ? $note_hr . join("\n", $foot_explain) : '';
133
134         // Tags will be inserted into <head></head>
135         $head_tag = ! empty($head_tags) ? join("\n", $head_tags) ."\n" : '';
136
137         // 1.3.x compat
138         // Last modification date (UNIX timestamp) of the page
139         $fmt = $is_read ? get_filetime($_page) + LOCALZONE : 0;
140
141         // Output nofollow / noindex regardless os skin file
142         if (!$is_read || $nofollow) {
143                 if (!headers_sent()) {
144                         header("X-Robots-Tag: noindex,nofollow");
145                 }
146         }
147
148         // Send Canonical URL for Search Engine Optimization
149         if ($is_read && !headers_sent()) {
150                 header("Link: <$canonical_url>; rel=\"canonical\"");
151         }
152
153         // Search words
154         if ($search_word_color && isset($vars['word'])) {
155                 $body = '<div class="small">' . $_msg_word . htmlsc($vars['word']) .
156                         '</div>' . $hr . "\n" . $body;
157
158                 // BugTrack2/106: Only variables can be passed by reference from PHP 5.0.5
159                 // with array_splice(), array_flip()
160                 $words = preg_split('/\s+/', $vars['word'], -1, PREG_SPLIT_NO_EMPTY);
161                 $words = array_splice($words, 0, 10); // Max: 10 words
162                 $words = array_flip($words);
163
164                 $keys = array();
165                 foreach ($words as $word=>$id) $keys[$word] = strlen($word);
166                 arsort($keys, SORT_NUMERIC);
167                 $keys = get_search_words(array_keys($keys), TRUE);
168                 $id = 0;
169                 $patterns = '';
170                 foreach ($keys as $key=>$pattern) {
171                         if (strlen($patterns) > 0) {
172                                 $patterns .= '|';
173                         }
174                         $patterns .= '(' . $pattern . ')';
175                 }
176                 if ($pattern) {
177                         $whole_pattern  = '/' .
178                                 '<textarea[^>]*>.*?<\/textarea>' .      // Ignore textareas
179                                 '|' . '<[^>]*>' .                       // Ignore tags
180                                 '|' . '&[^;]+;' .                       // Ignore entities
181                                 '|' . '(' . $patterns . ')' .           // $matches[1]: Regex for a search word
182                                 '/sS';
183                         $body  = preg_replace_callback($whole_pattern, '_decorate_Nth_word', $body);
184                         $notes = preg_replace_callback($whole_pattern, '_decorate_Nth_word', $notes);
185                 }
186         }
187         // Embed Scripting data
188         $html_scripting_data = get_html_scripting_data();
189
190         // Compat: 'HTML convert time' without time about MenuBar and skin
191         $taketime = elapsedtime();
192
193         require(SKIN_FILE);
194 }
195
196 function _decorate_Nth_word($matches)
197 {
198         // $matches[0]: including both words to skip and to decorate
199         // $matches[1]: word to decorate
200         // $matches[2+]: indicates which keyword to decorate
201         $index = -1;
202         for ($i = 2; $i < count($matches); $i++) {
203                 if (isset($matches[$i]) && $matches[$i]) {
204                         $index = $i - 2;
205                         break;
206                 }
207         }
208         if (isset($matches[1])) {
209                 // wordN highlight class: N=0...n
210                 return '<strong class="word' . $index . '">' .
211                         $matches[0] . '</strong>';
212         }
213         return $matches[0];
214 }
215
216 /**
217  * Get data used by JavaScript modules
218  */
219 function get_html_scripting_data()
220 {
221         global $ticket_link_sites, $plugin;
222         global $external_link_cushion_page, $external_link_cushion;
223         if (!isset($ticket_link_sites) || !is_array($ticket_link_sites)) {
224                 return '';
225         }
226         $is_utf8 = (bool)defined('PKWK_UTF8_ENABLE');
227         // Require: PHP 5.4+
228         $json_enabled = defined('JSON_UNESCAPED_UNICODE');
229         if (!$json_enabled) {
230                 $empty_data = <<<EOS
231 <div id="pukiwiki-site-properties" style="display:none;">
232 </div>
233 EOS;
234                 return $empty_data;
235         }
236         // Site basic Properties
237         $props = array(
238                 'is_utf8' => $is_utf8,
239                 'json_enabled' => $json_enabled,
240                 'base_uri_pathname' => get_base_uri(PKWK_URI_ROOT),
241                 'base_uri_absolute' => get_base_uri(PKWK_URI_ABSOLUTE)
242         );
243         $h_props = htmlsc(json_encode($props, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
244         $site_props = <<<EOS
245 <input type="hidden" class="site-props" value="$h_props" />
246 EOS;
247         $h_plugin = htmlsc($plugin);
248         $plugin_prop = <<<EOS
249 <input type="hidden" class="plugin-name" value="$h_plugin" />
250 EOS;
251
252         // AutoTicketLink
253         $filtered_ticket_link_sites = array();
254         foreach ($ticket_link_sites as $s) {
255                 if (!preg_match('/^([a-zA-Z0-9]+)([\.\-][a-zA-Z0-9]+)*$/', $s['key'])) {
256                         continue;
257                 }
258                 array_push($filtered_ticket_link_sites, $s);
259         }
260         $h_ticket_link_sites = htmlsc(json_encode($filtered_ticket_link_sites,
261                 JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
262         $ticketlink_data = <<<EOS
263 <input type="hidden" class="ticketlink-def" value="$h_ticket_link_sites" />
264 EOS;
265         // External link cushion page
266         $external_link_cushion_data = '';
267         if ($external_link_cushion_page) {
268                 $h_cushion = htmlsc(json_encode($external_link_cushion,
269                         JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
270                 $external_link_cushion_data = <<<EOS
271 <input type="hidden" class="external-link-cushion" value="$h_cushion" />
272 EOS;
273         }
274         $data = <<<EOS
275 <div id="pukiwiki-site-properties" style="display:none;">
276 $site_props
277 $plugin_prop
278 $ticketlink_data
279 $external_link_cushion_data
280 </div>
281 EOS;
282         return $data;
283 }
284
285 // Show 'edit' form
286 function edit_form($page, $postdata, $digest = FALSE, $b_template = TRUE)
287 {
288         global $vars, $rows, $cols, $hr, $function_freeze;
289         global $_btn_preview, $_btn_repreview, $_btn_update, $_btn_cancel, $_msg_help;
290         global $whatsnew, $_btn_template, $_btn_load, $load_template_func;
291         global $notimeupdate;
292         global $_title_list, $_label_template_pages;
293         global $_msg_edit_cancel_confirm, $_msg_edit_unloadbefore_message;
294         global $rule_page;
295
296         $script = get_base_uri();
297         // Newly generate $digest or not
298         if ($digest === FALSE) $digest = md5(join('', get_source($page)));
299
300         $refer = $template = '';
301
302         // Add plugin
303         $addtag = $add_top = '';
304         if(isset($vars['add'])) {
305                 global $_btn_addtop;
306                 $addtag  = '<input type="hidden" name="add"    value="true" />';
307                 $add_top = isset($vars['add_top']) ? ' checked="checked"' : '';
308                 $add_top = '<input type="checkbox" name="add_top" ' .
309                         'id="_edit_form_add_top" value="true"' . $add_top . ' />' . "\n" .
310                         '  <label for="_edit_form_add_top">' .
311                                 '<span class="small">' . $_btn_addtop . '</span>' .
312                         '</label>';
313         }
314
315         if($load_template_func && $b_template) {
316                 $tpage_names = array(); // Pages marked as template
317                 $template_page = ':config/Templates';
318                 $page_max = 100;
319                 foreach(get_source($template_page) as $_templates) {
320                         $m = array();
321                         if (! preg_match('#\-\s*\[\[([^\[\]]+)\]\]#', $_templates, $m)) continue;
322                         $tpage = preg_replace('#^./#', "$template_page/", $m[1]);
323                         if (! is_page($tpage)) continue;
324                         $tpage_names[] = $tpage;
325                 }
326                 $page_names = array();
327                 foreach(get_existpages() as $_page) {
328                         if ($_page == $whatsnew || check_non_list($_page) ||
329                                 !is_page_readable($_page))
330                                 continue;
331                         if (preg_match('/template/i', $_page)) {
332                                 $tpage_names[] = $_page;
333                         } else {
334                                 if (count($page_names) >= $page_max) continue;
335                                 $page_names[] = $_page;
336                         }
337                 }
338                 $tpage_names2 = array_values(array_unique($tpage_names));
339                 natcasesort($tpage_names2);
340                 natcasesort($page_names);
341                 $tpages = array(); // Template pages
342                 $npages = array(); // Normal pages
343                 foreach($tpage_names2 as $p) {
344                         $ps = htmlsc($p);
345                         $tpages[] = '   <option value="' . $ps . '">' . $ps . '</option>';
346                 }
347                 foreach($page_names as $p) {
348                         $ps = htmlsc($p);
349                         $npages[] = '   <option value="' . $ps . '">' . $ps . '</option>';
350                 }
351                 if (count($page_names) === $page_max) {
352                         $npages[] = '   <option value="">...</option>';
353                 }
354                 $s_tpages  = join("\n", $tpages);
355                 $s_npages  = join("\n", $npages);
356                 $template = <<<EOD
357   <select name="template_page">
358    <option value="">-- $_btn_template --</option>
359    <optgroup label="$_label_template_pages">
360 $s_tpages
361    </optgroup>
362    <optgroup label="$_title_list">
363 $s_npages
364    </optgroup>
365   </select>
366   <input type="submit" name="template" value="$_btn_load" accesskey="r" />
367   <br />
368 EOD;
369
370                 if (isset($vars['refer']) && $vars['refer'] != '')
371                         $refer = '[[' . strip_bracket($vars['refer']) . ']]' . "\n\n";
372         }
373
374         $r_page      = rawurlencode($page);
375         $s_page      = htmlsc($page);
376         $s_digest    = htmlsc($digest);
377         $s_postdata  = htmlsc($refer . $postdata);
378         $s_original  = isset($vars['original']) ? htmlsc($vars['original']) : $s_postdata;
379         $b_preview   = isset($vars['preview']); // TRUE when preview
380         $btn_preview = $b_preview ? $_btn_repreview : $_btn_preview;
381
382         // Checkbox 'do not change timestamp'
383         $add_notimestamp = '';
384         if ($notimeupdate != 0) {
385                 global $_btn_notchangetimestamp;
386                 $checked_time = isset($vars['notimestamp']) ? ' checked="checked"' : '';
387                 // Only for administrator
388                 if ($notimeupdate == 2) {
389                         $add_notimestamp = '   ' .
390                                 '<input type="password" name="pass" size="12" />' . "\n";
391                 }
392                 $add_notimestamp = '<input type="checkbox" name="notimestamp" ' .
393                         'id="_edit_form_notimestamp" value="true"' . $checked_time . ' />' . "\n" .
394                         '   ' . '<label for="_edit_form_notimestamp"><span class="small">' .
395                         $_btn_notchangetimestamp . '</span></label>' . "\n" .
396                         $add_notimestamp .
397                         '&nbsp;';
398         }
399
400         // 'margin-bottom', 'float:left', and 'margin-top'
401         // are for layout of 'cancel button'
402         $h_msg_edit_cancel_confirm = htmlsc($_msg_edit_cancel_confirm);
403         $h_msg_edit_unloadbefore_message = htmlsc($_msg_edit_unloadbefore_message);
404         $body = <<<EOD
405 <div class="edit_form">
406  <form action="$script" method="post" class="_plugin_edit_edit_form" style="margin-bottom:0px;">
407 $template
408   $addtag
409   <input type="hidden" name="cmd"    value="edit" />
410   <input type="hidden" name="page"   value="$s_page" />
411   <input type="hidden" name="digest" value="$s_digest" />
412   <input type="hidden" id="_msg_edit_cancel_confirm" value="$h_msg_edit_cancel_confirm" />
413   <input type="hidden" id="_msg_edit_unloadbefore_message" value="$h_msg_edit_unloadbefore_message" />
414   <textarea name="msg" rows="$rows" cols="$cols">$s_postdata</textarea>
415   <br />
416   <div style="float:left;">
417    <input type="submit" name="preview" value="$btn_preview" accesskey="p" />
418    <input type="submit" name="write"   value="$_btn_update" accesskey="s" />
419    $add_top
420    $add_notimestamp
421   </div>
422   <textarea name="original" rows="1" cols="1" style="display:none">$s_original</textarea>
423  </form>
424  <form action="$script" method="post" class="_plugin_edit_cancel" style="margin-top:0px;">
425   <input type="hidden" name="cmd"    value="edit" />
426   <input type="hidden" name="page"   value="$s_page" />
427   <input type="submit" name="cancel" value="$_btn_cancel" accesskey="c" />
428  </form>
429 </div>
430 EOD;
431
432         $body .= '<ul><li><a href="' .
433                 get_page_uri($rule_page) .
434                 '" target="_blank">' . $_msg_help . '</a></li></ul>';
435         return $body;
436 }
437
438 // Related pages
439 function make_related($page, $tag = '')
440 {
441         global $vars, $rule_related_str, $related_str;
442
443         $script = get_base_uri();
444         prepare_links_related($page);
445         $links = links_get_related($page);
446
447         if ($tag) {
448                 ksort($links, SORT_STRING);             // Page name, alphabetical order
449         } else {
450                 arsort($links, SORT_NUMERIC);   // Last modified date, newer
451         }
452
453         $_links = array();
454         foreach ($links as $page=>$lastmod) {
455                 if (check_non_list($page)) continue;
456                 $page_uri = get_page_uri($page);
457                 $s_page   = htmlsc($page);
458                 if ($tag) {
459                         $attrs = get_page_link_a_attrs($page);
460                         $_links[] = '<a href="' . $page_uri . '" class="' .
461                                 $attrs['class'] . '" data-mtime="' . $attrs['data_mtime'] .
462                                 '">' . $s_page . '</a>';
463                 } else {
464                         $mtime_span = get_passage_mtime_html_span($lastmod + LOCALZONE);
465                         $_links[] = '<a href="' . $page_uri . '">' .
466                         $s_page . '</a>' . $mtime_span;
467                 }
468         }
469         if (empty($_links)) return ''; // Nothing
470
471         if ($tag == 'p') { // From the line-head
472                 $style  = sprintf(pkwk_list_attrs_template(), 1, 1);
473                 $retval =  "\n" . '<ul' . $style . '>' . "\n" .
474                         '<li>' . join($rule_related_str, $_links) . '</li>' . "\n" .
475                         '</ul>' . "\n";
476         } else if ($tag) {
477                 $retval = join($rule_related_str, $_links);
478         } else {
479                 $retval = join($related_str, $_links);
480         }
481
482         return $retval;
483 }
484
485 function _convert_line_rule_to_regex($a)
486 {
487         return '/' . $a . '/';
488 }
489
490 // User-defined rules (convert without replacing source)
491 function make_line_rules($str)
492 {
493         global $line_rules;
494         static $pattern, $replace;
495
496         if (! isset($pattern)) {
497                 $pattern = array_map('_convert_line_rule_to_regex', array_keys($line_rules));
498                 $replace = array_values($line_rules);
499                 unset($line_rules);
500         }
501
502         return preg_replace($pattern, $replace, $str);
503 }
504
505 // Remove all HTML tags(or just anchor tags), and WikiName-speific decorations
506 function strip_htmltag($str, $all = TRUE)
507 {
508         global $_symbol_noexists;
509         static $noexists_pattern;
510
511         if (! isset($noexists_pattern))
512                 $noexists_pattern = '#<span class="noexists">([^<]*)<a[^>]+>' .
513                         preg_quote($_symbol_noexists, '#') . '</a></span>#';
514
515         // Strip Dagnling-Link decoration (Tags and "$_symbol_noexists")
516         $str = preg_replace($noexists_pattern, '$1', $str);
517
518         if ($all) {
519                 // All other HTML tags
520                 return preg_replace('#<[^>]+>#',        '', $str);
521         } else {
522                 // All other anchor-tags only
523                 return preg_replace('#<a[^>]+>|</a>#i', '', $str);
524         }
525 }
526
527 // Remove AutoLink marker with AutLink itself
528 function strip_autolink($str)
529 {
530         return preg_replace('#<!--autolink--><a [^>]+>|</a><!--/autolink-->#', '', $str);
531 }
532
533 // Make a backlink. searching-link of the page name, by the page name, for the page name
534 function make_search($page)
535 {
536         $s_page = htmlsc($page);
537         $r_page = rawurlencode($page);
538         return '<a href="' . get_base_uri() . '?plugin=related&amp;page=' . $r_page .
539                 '">' . $s_page . '</a> ';
540 }
541
542 // Make heading string (remove heading-related decorations from Wiki text)
543 function make_heading(& $str, $strip = TRUE)
544 {
545         global $NotePattern;
546
547         // Cut fixed-heading anchors
548         $id = '';
549         $matches = array();
550         if (preg_match('/^(\*{0,3})(.*?)\[#([A-Za-z][\w-]+)\](.*?)$/m', $str, $matches)) {
551                 $str = $matches[2] . $matches[4];
552                 $id  = & $matches[3];
553         } else {
554                 $str = preg_replace('/^\*{0,3}/', '', $str);
555         }
556
557         // Cut footnotes and tags
558         if ($strip === TRUE)
559                 $str = strip_htmltag(make_link(preg_replace($NotePattern, '', $str)));
560
561         return $id;
562 }
563
564 // Separate a page-name(or URL or null string) and an anchor
565 // (last one standing) without sharp
566 function anchor_explode($page, $strict_editable = FALSE)
567 {
568         $pos = strrpos($page, '#');
569         if ($pos === FALSE) return array($page, '', FALSE);
570
571         // Ignore the last sharp letter
572         if ($pos + 1 == strlen($page)) {
573                 $pos = strpos(substr($page, $pos + 1), '#');
574                 if ($pos === FALSE) return array($page, '', FALSE);
575         }
576
577         $s_page = substr($page, 0, $pos);
578         $anchor = substr($page, $pos + 1);
579
580         if($strict_editable === TRUE &&  preg_match('/^[a-z][a-f0-9]{7}$/', $anchor)) {
581                 return array ($s_page, $anchor, TRUE); // Seems fixed-anchor
582         } else {
583                 return array ($s_page, $anchor, FALSE);
584         }
585 }
586
587 // Check HTTP header()s were sent already, or
588 // there're blank lines or something out of php blocks
589 function pkwk_headers_sent()
590 {
591         if (PKWK_OPTIMISE) return;
592
593         $file = $line = '';
594         if (version_compare(PHP_VERSION, '4.3.0', '>=')) {
595                 if (headers_sent($file, $line))
596                     die('Headers already sent at ' .
597                         htmlsc($file) .
598                         ' line ' . $line . '.');
599         } else {
600                 if (headers_sent())
601                         die('Headers already sent.');
602         }
603 }
604
605 // Output common HTTP headers
606 function pkwk_common_headers()
607 {
608         if (! PKWK_OPTIMISE) pkwk_headers_sent();
609
610         if(defined('PKWK_ZLIB_LOADABLE_MODULE')) {
611                 $matches = array();
612                 if(ini_get('zlib.output_compression') &&
613                     preg_match('/\b(gzip|deflate)\b/i', $_SERVER['HTTP_ACCEPT_ENCODING'], $matches)) {
614                         // Bug #29350 output_compression compresses everything _without header_ as loadable module
615                         // http://bugs.php.net/bug.php?id=29350
616                         header('Content-Encoding: ' . $matches[1]);
617                         header('Vary: Accept-Encoding');
618                 }
619         }
620 }
621
622 // DTD definitions
623 define('PKWK_DTD_XHTML_1_1',              17); // Strict only
624 define('PKWK_DTD_XHTML_1_0',              16); // Strict
625 define('PKWK_DTD_XHTML_1_0_STRICT',       16);
626 define('PKWK_DTD_XHTML_1_0_TRANSITIONAL', 15);
627 define('PKWK_DTD_XHTML_1_0_FRAMESET',     14);
628 define('PKWK_DTD_HTML_4_01',               3); // Strict
629 define('PKWK_DTD_HTML_4_01_STRICT',        3);
630 define('PKWK_DTD_HTML_4_01_TRANSITIONAL',  2);
631 define('PKWK_DTD_HTML_4_01_FRAMESET',      1);
632
633 define('PKWK_DTD_TYPE_XHTML',  1);
634 define('PKWK_DTD_TYPE_HTML',   0);
635
636 // Output HTML DTD, <html> start tag. Return content-type.
637 function pkwk_output_dtd($pkwk_dtd = PKWK_DTD_XHTML_1_1, $charset = CONTENT_CHARSET)
638 {
639         static $called;
640         if (isset($called)) die('pkwk_output_dtd() already called. Why?');
641         $called = TRUE;
642
643         $type = PKWK_DTD_TYPE_XHTML;
644         $option = '';
645         switch($pkwk_dtd){
646         case PKWK_DTD_XHTML_1_1             :
647                 $version = '1.1' ;
648                 $dtd     = 'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd';
649                 break;
650         case PKWK_DTD_XHTML_1_0_STRICT      :
651                 $version = '1.0' ;
652                 $option  = 'Strict';
653                 $dtd     = 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd';
654                 break;
655         case PKWK_DTD_XHTML_1_0_TRANSITIONAL:
656                 $version = '1.0' ;
657                 $option  = 'Transitional';
658                 $dtd     = 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd';
659                 break;
660
661         case PKWK_DTD_HTML_4_01_STRICT      :
662                 $type    = PKWK_DTD_TYPE_HTML;
663                 $version = '4.01';
664                 $dtd     = 'http://www.w3.org/TR/html4/strict.dtd';
665                 break;
666         case PKWK_DTD_HTML_4_01_TRANSITIONAL:
667                 $type    = PKWK_DTD_TYPE_HTML;
668                 $version = '4.01';
669                 $option  = 'Transitional';
670                 $dtd     = 'http://www.w3.org/TR/html4/loose.dtd';
671                 break;
672
673         default: die('DTD not specified or invalid DTD');
674                 break;
675         }
676
677         $charset = htmlsc($charset);
678
679         // Output XML or not
680         if ($type == PKWK_DTD_TYPE_XHTML) echo '<?xml version="1.0" encoding="' . $charset . '" ?>' . "\n";
681
682         // Output doctype
683         echo '<!DOCTYPE html PUBLIC "-//W3C//DTD ' .
684                 ($type == PKWK_DTD_TYPE_XHTML ? 'XHTML' : 'HTML') . ' ' .
685                 $version .
686                 ($option != '' ? ' ' . $option : '') .
687                 '//EN" "' .
688                 $dtd .
689                 '">' . "\n";
690
691         // Output <html> start tag
692         echo '<html';
693         if ($type == PKWK_DTD_TYPE_XHTML) {
694                 echo ' xmlns="http://www.w3.org/1999/xhtml"'; // dir="ltr" /* LeftToRight */
695                 echo ' xml:lang="' . LANG . '"';
696                 if ($version == '1.0') echo ' lang="' . LANG . '"'; // Only XHTML 1.0
697         } else {
698                 echo ' lang="' . LANG . '"'; // HTML
699         }
700         echo '>' . "\n"; // <html>
701
702         // Return content-type (with MIME type)
703         if ($type == PKWK_DTD_TYPE_XHTML) {
704                 // NOTE: XHTML 1.1 browser will ignore http-equiv
705                 return '<meta http-equiv="content-type" content="application/xhtml+xml; charset=' . $charset . '" />' . "\n";
706         } else {
707                 return '<meta http-equiv="content-type" content="text/html; charset=' . $charset . '" />' . "\n";
708         }
709 }
710
711 /**
712  * Get template of List (ul, ol, dl) attributes
713  */
714 function pkwk_list_attrs_template() {
715         return ' class="list%d list-indent%d"';
716 }