]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/PageType.php
Let us put some abstraction
[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     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         foreach (array_keys($this->_map) as $moniker)
355             $qkeys[] = preg_quote($moniker, '/');
356         return "(?:" . join("|", $qkeys) . ")";
357     }
358 }
359
360 /** How to transform text.
361  */
362 abstract class PageFormatter
363 {
364     /**
365      * @param WikiDB_Page $page
366      * @param hash        $meta Version meta-data.
367      */
368     function __construct(&$page, $meta)
369     {
370         $this->_page = $page;
371         $this->_meta = $meta;
372     }
373
374     function _transform($text)
375     {
376         include_once 'lib/BlockParser.php';
377         return TransformText($text);
378     }
379
380     /** Transform the page text.
381      *
382      * @param  string     $text The raw page content (e.g. wiki-text).
383      * @return XmlContent Transformed content.
384      */
385     abstract function format($text);
386 }
387
388 class PageFormatter_wikitext extends PageFormatter
389 {
390     function format($text)
391     {
392         return HTML::div(array('class' => 'wikitext'),
393             $this->_transform($text));
394     }
395 }
396
397 class PageFormatter_interwikimap extends PageFormatter
398 {
399     function format($text)
400     {
401         return HTML::div(array('class' => 'wikitext'),
402             $this->_transform($this->_getHeader($text)),
403             $this->_formatMap($text),
404             $this->_transform($this->_getFooter($text)));
405     }
406
407     function _getHeader($text)
408     {
409         return preg_replace('/<verbatim>.*/s', '', $text);
410     }
411
412     function _getFooter($text)
413     {
414         return preg_replace('@.*?(</verbatim>|\Z)@s', '', $text, 1);
415     }
416
417     function _getMap($pagetext)
418     {
419         $map = getInterwikiMap($pagetext, 'force');
420         return $map->_map;
421     }
422
423     function _formatMap($pagetext)
424     {
425         $map = $this->_getMap($pagetext);
426         if (!$map)
427             return HTML::p("<No interwiki map found>"); // Shouldn't happen.
428
429         $mon_attr = array('class' => 'interwiki-moniker');
430         $url_attr = array('class' => 'interwiki-url');
431
432         $thead = HTML::thead(HTML::tr(HTML::th($mon_attr, _("Moniker")),
433             HTML::th($url_attr, _("InterWiki Address"))));
434         foreach ($map as $moniker => $interurl) {
435             $rows[] = HTML::tr(HTML::td($mon_attr, new Cached_WikiLinkIfKnown($moniker)),
436                 HTML::td($url_attr, HTML::samp($interurl)));
437         }
438
439         return HTML::table(array('class' => 'interwiki-map'),
440             $thead,
441             HTML::tbody(false, $rows));
442     }
443 }
444
445 class FakePageRevision
446 {
447     function FakePageRevision($meta)
448     {
449         $this->_meta = $meta;
450     }
451
452     function get($key)
453     {
454         if (empty($this->_meta[$key]))
455             return false;
456         return $this->_meta[$key];
457     }
458 }
459
460 // abstract base class
461 class PageFormatter_attach extends PageFormatter
462 {
463     public $type, $prefix;
464
465     // Display templated contents for wikiblog, comment and wikiforum
466     function format($text)
467     {
468         if (empty($this->type))
469             trigger_error('PageFormatter_attach->format: $type missing');
470         include_once 'lib/Template.php';
471         global $request;
472         $tokens['CONTENT'] = $this->_transform($text);
473         $tokens['page'] = $this->_page;
474         $tokens['rev'] = new FakePageRevision($this->_meta);
475
476         $name = new WikiPageName($this->_page->getName());
477         $tokens[$this->prefix . "_PARENT"] = $name->getParent();
478
479         $meta = $this->_meta[$this->type];
480         foreach (array('ctime', 'creator', 'creator_id') as $key)
481             $tokens[$this->prefix . "_" . strtoupper($key)] = $meta[$key];
482
483         return new Template($this->type, $request, $tokens);
484     }
485 }
486
487 class PageFormatter_wikiblog extends PageFormatter_attach
488 {
489     public $type = 'wikiblog', $prefix = "BLOG";
490 }
491
492 class PageFormatter_comment extends PageFormatter_attach
493 {
494     public $type = 'comment', $prefix = "COMMENT";
495 }
496
497 class PageFormatter_wikiforum extends PageFormatter_attach
498 {
499     public $type = 'wikiforum', $prefix = "FORUM";
500 }
501
502 /** wikiabuse for htmlarea editing. not yet used.
503  *
504  * Warning! Once a page is edited with a htmlarea like control it is
505  * stored in HTML and cannot be converted back to WikiText as long as
506  * we have no HTML => WikiText or any other interim format (WikiExchangeFormat e.g. XML)
507  * converter. See lib/HtmlParser.php for ongoing work on that.
508  * So it has a viral effect and certain plugins will not work anymore.
509  * But a lot of wikiusers seem to like it.
510  */
511 class PageFormatter_html extends PageFormatter
512 {
513     function _transform($text)
514     {
515         return $text;
516     }
517
518     function format($text)
519     {
520         return $text;
521     }
522 }
523
524 /**
525  *  FIXME. not yet used
526  */
527 class PageFormatter_pdf extends PageFormatter
528 {
529
530     function _transform($text)
531     {
532         include_once 'lib/BlockParser.php';
533         return TransformText($text);
534     }
535
536     // one page or set of pages?
537     // here we try to format only a single page
538     function format($text)
539     {
540         include_once 'lib/Template.php';
541         global $request;
542         $tokens['page'] = $this->_page;
543         $tokens['CONTENT'] = $this->_transform($text);
544         $pagename = $this->_page->getName();
545
546         // This is a XmlElement tree, which must be converted to PDF
547
548         // We can make use of several pdf extensions. This one - fpdf
549         // - is pure php and very easy, but looks quite ugly and has a
550         // terrible interface, as terrible as most of the othes.
551         // The closest to HTML is htmldoc which needs an external cgi
552         // binary.
553         // We use a custom HTML->PDF class converter from PHPWebthings
554         // to be able to use templates for PDF.
555         require_once 'lib/fpdf.php';
556         require_once 'lib/pdf.php';
557
558         $pdf = new PDF();
559         $pdf->SetTitle($pagename);
560         $pdf->SetAuthor($this->_page->get('author'));
561         $pdf->SetCreator(WikiURL($pagename, array(), 1));
562         $pdf->AliasNbPages();
563         $pdf->AddPage();
564         //TODO: define fonts
565         $pdf->SetFont('Times', '', 12);
566         //$pdf->SetFont('Arial','B',16);
567
568         // PDF pagelayout from a special template
569         $template = new Template('pdf', $request, $tokens);
570         $pdf->ConvertFromHTML($template);
571
572         // specify filename, destination
573         $pdf->Output($pagename . ".pdf", 'I'); // I for stdin or D for download
574
575         // Output([string name [, string dest]])
576         return $pdf;
577     }
578 }
579
580 class PageFormatter_MediaWiki extends PageFormatter
581 {
582     function _transform($text)
583     {
584         include_once 'lib/BlockParser.php';
585         // Expand leading tabs.
586         $text = expand_tabs($text);
587
588         $input = new BlockParser_Input($text);
589         $output = $this->ParsedBlock($input);
590         return new XmlContent($output->getContent());
591     }
592
593     function format($text)
594     {
595         return HTML::div(array('class' => 'wikitext'),
596             $this->_transform($text));
597     }
598 }
599
600 // Local Variables:
601 // mode: php
602 // tab-width: 8
603 // c-basic-offset: 4
604 // c-hanging-comment-ender-p: nil
605 // indent-tabs-mode: nil
606 // End: