]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/PageType.php
Remove FPDF
[SourceForge/phpwiki.git] / lib / PageType.php
1 <?php
2
3 /*
4  * Copyright 1999,2000,2001,2002,2003,2004,2005,2006 $ThePhpWikiProgrammingTeam
5  *
6  * This file is part of PhpWiki.
7  *
8  * PhpWiki is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * PhpWiki is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 require_once 'lib/CachedMarkup.php';
24
25 /** A cacheable formatted wiki page.
26  */
27 class TransformedText extends CacheableMarkup
28 {
29     /**
30      * @param WikiDB_Page $page
31      * @param string      $text          The packed page revision content.
32      * @param array       $meta          The version meta-data.
33      * @param string      $type_override For markup of page using a different
34      *        pagetype than that specified in its version meta-data.
35      */
36     function __construct($page, $text, $meta, $type_override = '')
37     {
38         $pagetype = false;
39         if ($type_override)
40             $pagetype = $type_override;
41         elseif (isset($meta['pagetype']))
42             $pagetype = $meta['pagetype'];
43         $this->_type = PageType::GetPageType($pagetype);
44         parent::__construct($this->_type->transform($page, $text, $meta),
45                             $page->getName());
46     }
47
48     function getType()
49     {
50         return $this->_type;
51     }
52 }
53
54 /**
55  * A page type descriptor.
56  *
57  * Encapsulate information about page types.
58  *
59  * Currently the only information encapsulated is how to format
60  * the specific page type.  In the future or capabilities may be
61  * added, e.g. the abilities to edit different page types (differently.)
62  * e.g. Support for the javascript htmlarea editor, which can only edit
63  * pure HTML.
64  *
65  * IMPORTANT NOTE: Since the whole PageType class gets stored (serialized)
66  * as of the cached marked-up page, it is important that the PageType classes
67  * not have large amounts of class data.  (No class data is even better.)
68  */
69 class PageType
70 {
71     /**
72      * Get a page type descriptor.
73      *
74      * This is a static member function.
75      *
76      * @param  string   $name Name of the page type.
77      * @return PageType An object which is a subclass of PageType.
78      */
79     static function GetPageType($name = '')
80     {
81         if (!$name)
82             $name = 'wikitext';
83         $class = "PageType_" . (string)$name;
84         if (class_exists($class))
85             return new $class;
86         trigger_error(sprintf("PageType ā€œ%sā€ unknown", (string)$name),
87             E_USER_WARNING);
88         return new PageType_wikitext;
89     }
90
91     /**
92      * Get the name of this page type.
93      *
94      * @return string Page type name.
95      */
96     function getName()
97     {
98         if (!preg_match('/^PageType_(.+)$/i', get_class($this), $m))
99             trigger_error("Bad class name for formatter(?)", E_USER_ERROR);
100         return $m[1];
101     }
102
103     /**
104      * Transform page text.
105      *
106      * @param  WikiDB_Page $page
107      * @param  string      $text
108      * @param  array       $meta Version meta-data
109      * @return XmlContent  The transformed page text.
110      */
111     function transform(&$page, &$text, $meta)
112     {
113         $fmt_class = 'PageFormatter_' . $this->getName();
114         $formatter = new $fmt_class($page, $meta);
115         return $formatter->format($text);
116     }
117 }
118
119 class PageType_wikitext extends PageType
120 {
121 }
122
123 class PageType_html extends PageType
124 {
125 }
126
127 class PageType_pdf extends PageType
128 {
129 }
130
131 class PageType_wikiblog extends PageType
132 {
133 }
134
135 class PageType_comment extends PageType
136 {
137 }
138
139 class PageType_wikiforum extends PageType
140 {
141 }
142
143 class PageType_MediaWiki extends PageType
144 {
145 }
146
147 /* To prevent from PHP5 Fatal error: Using $this when not in object context */
148 function getInterwikiMap($pagetext = false, $force = false)
149 {
150     static $map;
151     if (empty($map) or $force)
152         $map = new PageType_interwikimap($pagetext);
153     return $map;
154 }
155
156 class PageType_interwikimap extends PageType
157 {
158     function PageType_interwikimap($pagetext = false)
159     {
160         if (!$pagetext) {
161             $dbi = $GLOBALS['request']->getDbh();
162             $page = $dbi->getPage(__("InterWikiMap"));
163             if ($page->get('locked')) {
164                 $current = $page->getCurrentRevision();
165                 $pagetext = $current->getPackedContent();
166                 $intermap = $this->_getMapFromWikiText($pagetext);
167             } elseif ($page->exists()) {
168                 trigger_error(_("WARNING: InterWikiMap page is unlocked, so not using those links."));
169                 $intermap = false;
170             } else
171                 $intermap = false;
172         } else {
173             $intermap = $this->_getMapFromWikiText($pagetext);
174         }
175         if (!$intermap && defined('INTERWIKI_MAP_FILE'))
176             $intermap = $this->_getMapFromFile(INTERWIKI_MAP_FILE);
177
178         $this->_map = $this->_parseMap($intermap);
179         $this->_regexp = $this->_getRegexp();
180     }
181
182     function GetMap($pagetext = false)
183     {
184         /*PHP5 Fatal error: Using $this when not in object context */
185         if (empty($this->_map)) {
186             $map = new PageType_interwikimap($pagetext);
187             return $map;
188         } else {
189             return $this;
190         }
191     }
192
193     function getRegexp()
194     {
195         return $this->_regexp;
196     }
197
198     function link($link, $linktext = false)
199     {
200         global $WikiTheme;
201         list ($moniker, $page) = explode(":", $link, 2);
202
203         if (!isset($this->_map[$moniker])) {
204             return HTML::span(array('class' => 'bad-interwiki'),
205                 $linktext ? $linktext : $link);
206         }
207
208         $url = $this->_map[$moniker];
209         // localize Upload:links for WIKIDUMP
210         if (!empty($WikiTheme->DUMP_MODE) and $moniker == 'Upload') {
211             global $request;
212             include_once 'lib/config.php';
213             $url = getUploadFilePath();
214             // calculate to a relative local path to /uploads for pdf images.
215             $doc_root = $request->get("DOCUMENT_ROOT");
216             $ldir = NormalizeLocalFileName($url);
217             $wikiroot = NormalizeLocalFileName('');
218             if (isWindows()) {
219                 $ldir = strtolower($ldir);
220                 $doc_root = strtolower($doc_root);
221                 $wikiroot = strtolower($wikiroot);
222             }
223             if (string_starts_with($ldir, $doc_root)) {
224                 $link_prefix = substr($url, strlen($doc_root));
225             } elseif (string_starts_with($ldir, $wikiroot)) {
226                 $link_prefix = NormalizeWebFileName(substr($url, strlen($wikiroot)));
227             }
228         }
229
230         // Urlencode page only if it's a query arg.
231         // FIXME: this is a somewhat broken heuristic.
232         if ($moniker == 'Upload') {
233             $page_enc = $page;
234             $page = rawurldecode($page);
235         } else {
236             $page_enc = strstr($url, '?') ? rawurlencode($page) : $page;
237         }
238         if (strstr($url, '%s'))
239             $url = sprintf($url, $page_enc);
240         else
241             $url .= $page_enc;
242
243         // Encode spaces in '[[Help:Reini Urban]]'
244         // but not in '[[Upload:logo.jpg size=40x25 align=center]]'
245         if ($moniker != 'Upload') {
246             $url = str_replace(' ', '%20', $url);
247         }
248
249         $link = HTML::a(array('href' => $url));
250
251         if (!$linktext) {
252             $link->pushContent(PossiblyGlueIconToText('interwiki', "$moniker:"),
253                 HTML::span(array('class' => 'wikipage'), $page));
254             $link->setAttr('class', 'interwiki');
255         } else {
256             $link->pushContent(PossiblyGlueIconToText('interwiki', $linktext));
257             $link->setAttr('class', 'named-interwiki');
258         }
259
260         return $link;
261     }
262
263     function _parseMap($text)
264     {
265         if (!preg_match_all("/^\s*(\S+)\s+(.+)$/m",
266             $text, $matches, PREG_SET_ORDER)
267         )
268             return false;
269
270         foreach ($matches as $m) {
271             $map[$m[1]] = $m[2];
272         }
273
274         // Add virtual monikers: "Upload:" "Talk:" "User:", ":"
275         // and expand special variables %u, %b, %d
276
277         // Upload: Should be expanded later to user-specific upload dirs.
278         // In the Upload plugin, not here: Upload:ReiniUrban/uploaded-file.png
279         if (empty($map['Upload'])) {
280             $map['Upload'] = getUploadDataPath();
281         }
282         // User:ReiniUrban => ReiniUrban or Users/ReiniUrban
283         // Can be easily overriden by a customized InterWikiMap:
284         //   User Users/%s
285         if (empty($map["User"])) {
286             $map["User"] = "%s";
287         }
288         // Talk:UserName => UserName/Discussion
289         // Talk:PageName => PageName/Discussion as default, which might be overridden
290         if (empty($map["Talk"])) {
291             $pagename = $GLOBALS['request']->getArg('pagename');
292             // against PageName/Discussion/Discussion
293             if (string_ends_with($pagename, SUBPAGE_SEPARATOR . _("Discussion")))
294                 $map["Talk"] = "%s";
295             else
296                 $map["Talk"] = "%s" . SUBPAGE_SEPARATOR . _("Discussion");
297         }
298
299         foreach (array('Upload', 'User', 'Talk') as $special) {
300             // Expand special variables:
301             //   %u => username
302             //   %b => wikibaseurl
303             //   %d => iso8601 DateTime
304             // %s is expanded later to the pagename
305             if (strstr($map[$special], '%u'))
306                 $map[$special] = str_replace($map[$special],
307                     '%u',
308                     $GLOBALS['request']->_user->_userid);
309             if (strstr($map[$special], '%b'))
310                 $map[$special] = str_replace($map[$special],
311                     '%b',
312                     PHPWIKI_BASE_URL);
313             if (strstr($map[$special], '%d'))
314                 $map[$special] = str_replace($map[$special],
315                     '%d',
316                     // such as 2003-01-11T14:03:02+00:00
317                     Iso8601DateTime());
318         }
319
320         return $map;
321     }
322
323     function _getMapFromWikiText($pagetext)
324     {
325         if (preg_match('|^<verbatim>\n(.*)^</verbatim>|ms', $pagetext, $m)) {
326             return $m[1];
327         }
328         return false;
329     }
330
331     function _getMapFromFile($filename)
332     {
333         if (defined('WARN_NONPUBLIC_INTERWIKIMAP') and WARN_NONPUBLIC_INTERWIKIMAP) {
334             $error_html = sprintf(_("Loading InterWikiMap from external file %s."),
335                 $filename);
336             trigger_error($error_html, E_USER_NOTICE);
337         }
338         if (!file_exists($filename)) {
339             $finder = new FileFinder();
340             $filename = $finder->findFile(INTERWIKI_MAP_FILE);
341         }
342         @$fd = fopen($filename, "rb");
343         @$data = fread($fd, filesize($filename));
344         @fclose($fd);
345
346         return $data;
347     }
348
349     function _getRegexp()
350     {
351         if (!$this->_map)
352             return '(?:(?!a)a)'; //  Never matches.
353
354         $qkeys = array();
355         foreach (array_keys($this->_map) as $moniker)
356             $qkeys[] = preg_quote($moniker, '/');
357         return "(?:" . join("|", $qkeys) . ")";
358     }
359 }
360
361 /** How to transform text.
362  */
363 abstract class PageFormatter
364 {
365     /**
366      * @param WikiDB_Page $page
367      * @param array       $meta Version meta-data hash.
368      */
369     function __construct(&$page, $meta)
370     {
371         $this->_page = $page;
372         $this->_meta = $meta;
373     }
374
375     function _transform($text)
376     {
377         include_once 'lib/BlockParser.php';
378         return TransformText($text);
379     }
380
381     /** Transform the page text.
382      *
383      * @param  string     $text The raw page content (e.g. wiki-text).
384      * @return XmlContent Transformed content.
385      */
386     abstract function format($text);
387 }
388
389 class PageFormatter_wikitext extends PageFormatter
390 {
391     function format($text)
392     {
393         return HTML::div(array('class' => 'wikitext'),
394             $this->_transform($text));
395     }
396 }
397
398 class PageFormatter_interwikimap extends PageFormatter
399 {
400     function format($text)
401     {
402         return HTML::div(array('class' => 'wikitext'),
403             $this->_transform($this->_getHeader($text)),
404             $this->_formatMap($text),
405             $this->_transform($this->_getFooter($text)));
406     }
407
408     function _getHeader($text)
409     {
410         return preg_replace('/<verbatim>.*/s', '', $text);
411     }
412
413     function _getFooter($text)
414     {
415         return preg_replace('@.*?(</verbatim>|\Z)@s', '', $text, 1);
416     }
417
418     function _getMap($pagetext)
419     {
420         $map = getInterwikiMap($pagetext, 'force');
421         return $map->_map;
422     }
423
424     function _formatMap($pagetext)
425     {
426         $map = $this->_getMap($pagetext);
427         if (!$map)
428             return HTML::p("No interwiki map found"); // Shouldn't happen.
429
430         $mon_attr = array('class' => 'interwiki-moniker');
431         $url_attr = array('class' => 'interwiki-url');
432
433         $thead = HTML::thead(HTML::tr(HTML::th($mon_attr, _("Moniker")),
434             HTML::th($url_attr, _("InterWiki Address"))));
435         $rows = array();
436         foreach ($map as $moniker => $interurl) {
437             $rows[] = HTML::tr(HTML::td($mon_attr, new Cached_WikiLinkIfKnown($moniker)),
438                 HTML::td($url_attr, HTML::samp($interurl)));
439         }
440
441         return HTML::table(array('class' => 'interwiki-map'),
442             $thead,
443             HTML::tbody(false, $rows));
444     }
445 }
446
447 class FakePageRevision
448 {
449     function FakePageRevision($meta)
450     {
451         $this->_meta = $meta;
452     }
453
454     function get($key)
455     {
456         if (empty($this->_meta[$key]))
457             return false;
458         return $this->_meta[$key];
459     }
460 }
461
462 // abstract base class
463 class PageFormatter_attach extends PageFormatter
464 {
465     public $type, $prefix;
466
467     // Display templated contents for wikiblog, comment and wikiforum
468     function format($text)
469     {
470         if (empty($this->type))
471             trigger_error('PageFormatter_attach->format: $type missing');
472         include_once 'lib/Template.php';
473         global $request;
474         $tokens['CONTENT'] = $this->_transform($text);
475         $tokens['page'] = $this->_page;
476         $tokens['rev'] = new FakePageRevision($this->_meta);
477
478         $name = new WikiPageName($this->_page->getName());
479         $tokens[$this->prefix . "_PARENT"] = $name->getParent();
480
481         $meta = $this->_meta[$this->type];
482         foreach (array('ctime', 'creator', 'creator_id') as $key)
483             $tokens[$this->prefix . "_" . strtoupper($key)] = $meta[$key];
484
485         return new Template($this->type, $request, $tokens);
486     }
487 }
488
489 class PageFormatter_wikiblog extends PageFormatter_attach
490 {
491     public $type = 'wikiblog', $prefix = "BLOG";
492 }
493
494 class PageFormatter_comment extends PageFormatter_attach
495 {
496     public $type = 'comment', $prefix = "COMMENT";
497 }
498
499 class PageFormatter_wikiforum extends PageFormatter_attach
500 {
501     public $type = 'wikiforum', $prefix = "FORUM";
502 }
503
504 /** wikiabuse for htmlarea editing. not yet used.
505  *
506  * Warning! Once a page is edited with a htmlarea like control it is
507  * stored in HTML and cannot be converted back to WikiText as long as
508  * we have no HTML => WikiText or any other interim format (WikiExchangeFormat e.g. XML)
509  * converter. See lib/HtmlParser.php for ongoing work on that.
510  * So it has a viral effect and certain plugins will not work anymore.
511  * But a lot of wikiusers seem to like it.
512  */
513 class PageFormatter_html extends PageFormatter
514 {
515     function _transform($text)
516     {
517         return $text;
518     }
519
520     function format($text)
521     {
522         return $text;
523     }
524 }
525
526 class PageFormatter_MediaWiki extends PageFormatter
527 {
528     function _transform($text)
529     {
530         include_once 'lib/BlockParser.php';
531         // Expand leading tabs.
532         $text = expand_tabs($text);
533
534         $input = new BlockParser_Input($text);
535         $output = $this->ParsedBlock($input);
536         return new XmlContent($output->getContent());
537     }
538
539     function format($text)
540     {
541         return HTML::div(array('class' => 'wikitext'),
542             $this->_transform($text));
543     }
544 }
545
546 // Local Variables:
547 // mode: php
548 // tab-width: 8
549 // c-basic-offset: 4
550 // c-hanging-comment-ender-p: nil
551 // indent-tabs-mode: nil
552 // End: