OSDN Git Service

BugTrack/2447 Show page passage by Web browser/JavaScript process
[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         if (!isset($ticket_link_sites) || !is_array($ticket_link_sites)) {
223                 return '';
224         }
225         $is_utf8 = (bool)defined('PKWK_UTF8_ENABLE');
226         // Require: PHP 5.4+
227         $json_enabled = defined('JSON_UNESCAPED_UNICODE');
228         if (!$json_enabled) {
229                 $empty_data = <<<EOS
230 <div id="pukiwiki-site-properties" style="display:none;">
231 </div>
232 EOS;
233                 return $empty_data;
234         }
235         // Site basic Properties
236         $props = array(
237                 'is_utf8' => $is_utf8,
238                 'json_enabled' => $json_enabled,
239                 'base_uri_pathname' => get_base_uri(PKWK_URI_ROOT),
240                 'base_uri_absolute' => get_base_uri(PKWK_URI_ABSOLUTE)
241         );
242         $props_json = htmlsc(json_encode($props, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
243         $site_props = <<<EOS
244 <div data-key="site-props" data-value="$props_json"></div>
245 EOS;
246         $h_plugin = htmlsc($plugin);
247         $plugin_prop = <<<EOS
248 <input type="hidden" class="plugin-name" value="$h_plugin" />
249 EOS;
250
251         // AutoTicketLink
252         $filtered_ticket_link_sites = array();
253         foreach ($ticket_link_sites as $s) {
254                 if (!preg_match('/^([a-zA-Z0-9]+)([\.\-][a-zA-Z0-9]+)*$/', $s['key'])) {
255                         continue;
256                 }
257                 array_push($filtered_ticket_link_sites, $s);
258         }
259         $h_ticket_link_sites = htmlsc(json_encode($filtered_ticket_link_sites,
260                 JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
261         $ticketlink_data = <<<EOS
262 <input type="hidden" class="ticketlink-def" value="$h_ticket_link_sites" />
263 EOS;
264         $data = <<<EOS
265 <div id="pukiwiki-site-properties" style="display:none;">
266 $site_props
267 $plugin_prop
268 $ticketlink_data
269 </div>
270 EOS;
271         return $data;
272 }
273
274 // Show 'edit' form
275 function edit_form($page, $postdata, $digest = FALSE, $b_template = TRUE)
276 {
277         global $vars, $rows, $cols, $hr, $function_freeze;
278         global $_btn_preview, $_btn_repreview, $_btn_update, $_btn_cancel, $_msg_help;
279         global $whatsnew, $_btn_template, $_btn_load, $load_template_func;
280         global $notimeupdate;
281         global $_title_list, $_label_template_pages;
282         global $_msg_edit_cancel_confirm, $_msg_edit_unloadbefore_message;
283         global $rule_page;
284
285         $script = get_base_uri();
286         // Newly generate $digest or not
287         if ($digest === FALSE) $digest = md5(join('', get_source($page)));
288
289         $refer = $template = '';
290
291         // Add plugin
292         $addtag = $add_top = '';
293         if(isset($vars['add'])) {
294                 global $_btn_addtop;
295                 $addtag  = '<input type="hidden" name="add"    value="true" />';
296                 $add_top = isset($vars['add_top']) ? ' checked="checked"' : '';
297                 $add_top = '<input type="checkbox" name="add_top" ' .
298                         'id="_edit_form_add_top" value="true"' . $add_top . ' />' . "\n" .
299                         '  <label for="_edit_form_add_top">' .
300                                 '<span class="small">' . $_btn_addtop . '</span>' .
301                         '</label>';
302         }
303
304         if($load_template_func && $b_template) {
305                 $tpage_names = array(); // Pages marked as template
306                 $template_page = ':config/Templates';
307                 $page_max = 100;
308                 foreach(get_source($template_page) as $_templates) {
309                         $m = array();
310                         if (! preg_match('#\-\s*\[\[([^\[\]]+)\]\]#', $_templates, $m)) continue;
311                         $tpage = preg_replace('#^./#', "$template_page/", $m[1]);
312                         if (! is_page($tpage)) continue;
313                         $tpage_names[] = $tpage;
314                 }
315                 $page_names = array();
316                 foreach(get_existpages() as $_page) {
317                         if ($_page == $whatsnew || check_non_list($_page) ||
318                                 !is_page_readable($_page))
319                                 continue;
320                         if (preg_match('/template/i', $_page)) {
321                                 $tpage_names[] = $_page;
322                         } else {
323                                 if (count($page_names) >= $page_max) continue;
324                                 $page_names[] = $_page;
325                         }
326                 }
327                 $tpage_names2 = array_values(array_unique($tpage_names));
328                 natcasesort($tpage_names2);
329                 natcasesort($page_names);
330                 $tpages = array(); // Template pages
331                 $npages = array(); // Normal pages
332                 foreach($tpage_names2 as $p) {
333                         $ps = htmlsc($p);
334                         $tpages[] = '   <option value="' . $ps . '">' . $ps . '</option>';
335                 }
336                 foreach($page_names as $p) {
337                         $ps = htmlsc($p);
338                         $npages[] = '   <option value="' . $ps . '">' . $ps . '</option>';
339                 }
340                 if (count($page_names) === $page_max) {
341                         $npages[] = '   <option value="">...</option>';
342                 }
343                 $s_tpages  = join("\n", $tpages);
344                 $s_npages  = join("\n", $npages);
345                 $template = <<<EOD
346   <select name="template_page">
347    <option value="">-- $_btn_template --</option>
348    <optgroup label="$_label_template_pages">
349 $s_tpages
350    </optgroup>
351    <optgroup label="$_title_list">
352 $s_npages
353    </optgroup>
354   </select>
355   <input type="submit" name="template" value="$_btn_load" accesskey="r" />
356   <br />
357 EOD;
358
359                 if (isset($vars['refer']) && $vars['refer'] != '')
360                         $refer = '[[' . strip_bracket($vars['refer']) . ']]' . "\n\n";
361         }
362
363         $r_page      = rawurlencode($page);
364         $s_page      = htmlsc($page);
365         $s_digest    = htmlsc($digest);
366         $s_postdata  = htmlsc($refer . $postdata);
367         $s_original  = isset($vars['original']) ? htmlsc($vars['original']) : $s_postdata;
368         $b_preview   = isset($vars['preview']); // TRUE when preview
369         $btn_preview = $b_preview ? $_btn_repreview : $_btn_preview;
370
371         // Checkbox 'do not change timestamp'
372         $add_notimestamp = '';
373         if ($notimeupdate != 0) {
374                 global $_btn_notchangetimestamp;
375                 $checked_time = isset($vars['notimestamp']) ? ' checked="checked"' : '';
376                 // Only for administrator
377                 if ($notimeupdate == 2) {
378                         $add_notimestamp = '   ' .
379                                 '<input type="password" name="pass" size="12" />' . "\n";
380                 }
381                 $add_notimestamp = '<input type="checkbox" name="notimestamp" ' .
382                         'id="_edit_form_notimestamp" value="true"' . $checked_time . ' />' . "\n" .
383                         '   ' . '<label for="_edit_form_notimestamp"><span class="small">' .
384                         $_btn_notchangetimestamp . '</span></label>' . "\n" .
385                         $add_notimestamp .
386                         '&nbsp;';
387         }
388
389         // 'margin-bottom', 'float:left', and 'margin-top'
390         // are for layout of 'cancel button'
391         $h_msg_edit_cancel_confirm = htmlsc($_msg_edit_cancel_confirm);
392         $h_msg_edit_unloadbefore_message = htmlsc($_msg_edit_unloadbefore_message);
393         $body = <<<EOD
394 <div class="edit_form">
395  <form action="$script" method="post" class="_plugin_edit_edit_form" style="margin-bottom:0px;">
396 $template
397   $addtag
398   <input type="hidden" name="cmd"    value="edit" />
399   <input type="hidden" name="page"   value="$s_page" />
400   <input type="hidden" name="digest" value="$s_digest" />
401   <input type="hidden" id="_msg_edit_cancel_confirm" value="$h_msg_edit_cancel_confirm" />
402   <input type="hidden" id="_msg_edit_unloadbefore_message" value="$h_msg_edit_unloadbefore_message" />
403   <textarea name="msg" rows="$rows" cols="$cols">$s_postdata</textarea>
404   <br />
405   <div style="float:left;">
406    <input type="submit" name="preview" value="$btn_preview" accesskey="p" />
407    <input type="submit" name="write"   value="$_btn_update" accesskey="s" />
408    $add_top
409    $add_notimestamp
410   </div>
411   <textarea name="original" rows="1" cols="1" style="display:none">$s_original</textarea>
412  </form>
413  <form action="$script" method="post" class="_plugin_edit_cancel" style="margin-top:0px;">
414   <input type="hidden" name="cmd"    value="edit" />
415   <input type="hidden" name="page"   value="$s_page" />
416   <input type="submit" name="cancel" value="$_btn_cancel" accesskey="c" />
417  </form>
418 </div>
419 EOD;
420
421         $body .= '<ul><li><a href="' .
422                 get_page_uri($rule_page) .
423                 '" target="_blank">' . $_msg_help . '</a></li></ul>';
424         return $body;
425 }
426
427 // Related pages
428 function make_related($page, $tag = '')
429 {
430         global $vars, $rule_related_str, $related_str;
431
432         $script = get_base_uri();
433         prepare_links_related($page);
434         $links = links_get_related($page);
435
436         if ($tag) {
437                 ksort($links, SORT_STRING);             // Page name, alphabetical order
438         } else {
439                 arsort($links, SORT_NUMERIC);   // Last modified date, newer
440         }
441
442         $_links = array();
443         foreach ($links as $page=>$lastmod) {
444                 if (check_non_list($page)) continue;
445                 $page_uri = get_page_uri($page);
446                 $s_page   = htmlsc($page);
447                 if ($tag) {
448                         $attrs = get_page_link_a_attrs($page);
449                         $_links[] = '<a href="' . $page_uri . '" class="' .
450                                 $attrs['class'] . '" data-mtime="' . $attrs['data_mtime'] .
451                                 '">' . $s_page . '</a>';
452                 } else {
453                         $mtime_span = get_passage_mtime_html_span($lastmod + LOCALZONE);
454                         $_links[] = '<a href="' . $page_uri . '">' .
455                         $s_page . '</a>' . $mtime_span;
456                 }
457         }
458         if (empty($_links)) return ''; // Nothing
459
460         if ($tag == 'p') { // From the line-head
461                 $style  = sprintf(pkwk_list_attrs_template(), 1, 1);
462                 $retval =  "\n" . '<ul' . $style . '>' . "\n" .
463                         '<li>' . join($rule_related_str, $_links) . '</li>' . "\n" .
464                         '</ul>' . "\n";
465         } else if ($tag) {
466                 $retval = join($rule_related_str, $_links);
467         } else {
468                 $retval = join($related_str, $_links);
469         }
470
471         return $retval;
472 }
473
474 function _convert_line_rule_to_regex($a)
475 {
476         return '/' . $a . '/';
477 }
478
479 // User-defined rules (convert without replacing source)
480 function make_line_rules($str)
481 {
482         global $line_rules;
483         static $pattern, $replace;
484
485         if (! isset($pattern)) {
486                 $pattern = array_map('_convert_line_rule_to_regex', array_keys($line_rules));
487                 $replace = array_values($line_rules);
488                 unset($line_rules);
489         }
490
491         return preg_replace($pattern, $replace, $str);
492 }
493
494 // Remove all HTML tags(or just anchor tags), and WikiName-speific decorations
495 function strip_htmltag($str, $all = TRUE)
496 {
497         global $_symbol_noexists;
498         static $noexists_pattern;
499
500         if (! isset($noexists_pattern))
501                 $noexists_pattern = '#<span class="noexists">([^<]*)<a[^>]+>' .
502                         preg_quote($_symbol_noexists, '#') . '</a></span>#';
503
504         // Strip Dagnling-Link decoration (Tags and "$_symbol_noexists")
505         $str = preg_replace($noexists_pattern, '$1', $str);
506
507         if ($all) {
508                 // All other HTML tags
509                 return preg_replace('#<[^>]+>#',        '', $str);
510         } else {
511                 // All other anchor-tags only
512                 return preg_replace('#<a[^>]+>|</a>#i', '', $str);
513         }
514 }
515
516 // Remove AutoLink marker with AutLink itself
517 function strip_autolink($str)
518 {
519         return preg_replace('#<!--autolink--><a [^>]+>|</a><!--/autolink-->#', '', $str);
520 }
521
522 // Make a backlink. searching-link of the page name, by the page name, for the page name
523 function make_search($page)
524 {
525         $s_page = htmlsc($page);
526         $r_page = rawurlencode($page);
527         return '<a href="' . get_base_uri() . '?plugin=related&amp;page=' . $r_page .
528                 '">' . $s_page . '</a> ';
529 }
530
531 // Make heading string (remove heading-related decorations from Wiki text)
532 function make_heading(& $str, $strip = TRUE)
533 {
534         global $NotePattern;
535
536         // Cut fixed-heading anchors
537         $id = '';
538         $matches = array();
539         if (preg_match('/^(\*{0,3})(.*?)\[#([A-Za-z][\w-]+)\](.*?)$/m', $str, $matches)) {
540                 $str = $matches[2] . $matches[4];
541                 $id  = & $matches[3];
542         } else {
543                 $str = preg_replace('/^\*{0,3}/', '', $str);
544         }
545
546         // Cut footnotes and tags
547         if ($strip === TRUE)
548                 $str = strip_htmltag(make_link(preg_replace($NotePattern, '', $str)));
549
550         return $id;
551 }
552
553 // Separate a page-name(or URL or null string) and an anchor
554 // (last one standing) without sharp
555 function anchor_explode($page, $strict_editable = FALSE)
556 {
557         $pos = strrpos($page, '#');
558         if ($pos === FALSE) return array($page, '', FALSE);
559
560         // Ignore the last sharp letter
561         if ($pos + 1 == strlen($page)) {
562                 $pos = strpos(substr($page, $pos + 1), '#');
563                 if ($pos === FALSE) return array($page, '', FALSE);
564         }
565
566         $s_page = substr($page, 0, $pos);
567         $anchor = substr($page, $pos + 1);
568
569         if($strict_editable === TRUE &&  preg_match('/^[a-z][a-f0-9]{7}$/', $anchor)) {
570                 return array ($s_page, $anchor, TRUE); // Seems fixed-anchor
571         } else {
572                 return array ($s_page, $anchor, FALSE);
573         }
574 }
575
576 // Check HTTP header()s were sent already, or
577 // there're blank lines or something out of php blocks
578 function pkwk_headers_sent()
579 {
580         if (PKWK_OPTIMISE) return;
581
582         $file = $line = '';
583         if (version_compare(PHP_VERSION, '4.3.0', '>=')) {
584                 if (headers_sent($file, $line))
585                     die('Headers already sent at ' .
586                         htmlsc($file) .
587                         ' line ' . $line . '.');
588         } else {
589                 if (headers_sent())
590                         die('Headers already sent.');
591         }
592 }
593
594 // Output common HTTP headers
595 function pkwk_common_headers()
596 {
597         if (! PKWK_OPTIMISE) pkwk_headers_sent();
598
599         if(defined('PKWK_ZLIB_LOADABLE_MODULE')) {
600                 $matches = array();
601                 if(ini_get('zlib.output_compression') &&
602                     preg_match('/\b(gzip|deflate)\b/i', $_SERVER['HTTP_ACCEPT_ENCODING'], $matches)) {
603                         // Bug #29350 output_compression compresses everything _without header_ as loadable module
604                         // http://bugs.php.net/bug.php?id=29350
605                         header('Content-Encoding: ' . $matches[1]);
606                         header('Vary: Accept-Encoding');
607                 }
608         }
609 }
610
611 // DTD definitions
612 define('PKWK_DTD_XHTML_1_1',              17); // Strict only
613 define('PKWK_DTD_XHTML_1_0',              16); // Strict
614 define('PKWK_DTD_XHTML_1_0_STRICT',       16);
615 define('PKWK_DTD_XHTML_1_0_TRANSITIONAL', 15);
616 define('PKWK_DTD_XHTML_1_0_FRAMESET',     14);
617 define('PKWK_DTD_HTML_4_01',               3); // Strict
618 define('PKWK_DTD_HTML_4_01_STRICT',        3);
619 define('PKWK_DTD_HTML_4_01_TRANSITIONAL',  2);
620 define('PKWK_DTD_HTML_4_01_FRAMESET',      1);
621
622 define('PKWK_DTD_TYPE_XHTML',  1);
623 define('PKWK_DTD_TYPE_HTML',   0);
624
625 // Output HTML DTD, <html> start tag. Return content-type.
626 function pkwk_output_dtd($pkwk_dtd = PKWK_DTD_XHTML_1_1, $charset = CONTENT_CHARSET)
627 {
628         static $called;
629         if (isset($called)) die('pkwk_output_dtd() already called. Why?');
630         $called = TRUE;
631
632         $type = PKWK_DTD_TYPE_XHTML;
633         $option = '';
634         switch($pkwk_dtd){
635         case PKWK_DTD_XHTML_1_1             :
636                 $version = '1.1' ;
637                 $dtd     = 'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd';
638                 break;
639         case PKWK_DTD_XHTML_1_0_STRICT      :
640                 $version = '1.0' ;
641                 $option  = 'Strict';
642                 $dtd     = 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd';
643                 break;
644         case PKWK_DTD_XHTML_1_0_TRANSITIONAL:
645                 $version = '1.0' ;
646                 $option  = 'Transitional';
647                 $dtd     = 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd';
648                 break;
649
650         case PKWK_DTD_HTML_4_01_STRICT      :
651                 $type    = PKWK_DTD_TYPE_HTML;
652                 $version = '4.01';
653                 $dtd     = 'http://www.w3.org/TR/html4/strict.dtd';
654                 break;
655         case PKWK_DTD_HTML_4_01_TRANSITIONAL:
656                 $type    = PKWK_DTD_TYPE_HTML;
657                 $version = '4.01';
658                 $option  = 'Transitional';
659                 $dtd     = 'http://www.w3.org/TR/html4/loose.dtd';
660                 break;
661
662         default: die('DTD not specified or invalid DTD');
663                 break;
664         }
665
666         $charset = htmlsc($charset);
667
668         // Output XML or not
669         if ($type == PKWK_DTD_TYPE_XHTML) echo '<?xml version="1.0" encoding="' . $charset . '" ?>' . "\n";
670
671         // Output doctype
672         echo '<!DOCTYPE html PUBLIC "-//W3C//DTD ' .
673                 ($type == PKWK_DTD_TYPE_XHTML ? 'XHTML' : 'HTML') . ' ' .
674                 $version .
675                 ($option != '' ? ' ' . $option : '') .
676                 '//EN" "' .
677                 $dtd .
678                 '">' . "\n";
679
680         // Output <html> start tag
681         echo '<html';
682         if ($type == PKWK_DTD_TYPE_XHTML) {
683                 echo ' xmlns="http://www.w3.org/1999/xhtml"'; // dir="ltr" /* LeftToRight */
684                 echo ' xml:lang="' . LANG . '"';
685                 if ($version == '1.0') echo ' lang="' . LANG . '"'; // Only XHTML 1.0
686         } else {
687                 echo ' lang="' . LANG . '"'; // HTML
688         }
689         echo '>' . "\n"; // <html>
690
691         // Return content-type (with MIME type)
692         if ($type == PKWK_DTD_TYPE_XHTML) {
693                 // NOTE: XHTML 1.1 browser will ignore http-equiv
694                 return '<meta http-equiv="content-type" content="application/xhtml+xml; charset=' . $charset . '" />' . "\n";
695         } else {
696                 return '<meta http-equiv="content-type" content="text/html; charset=' . $charset . '" />' . "\n";
697         }
698 }
699
700 /**
701  * Get template of List (ul, ol, dl) attributes
702  */
703 function pkwk_list_attrs_template() {
704         return ' class="list%d list-indent%d"';
705 }