OSDN Git Service

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