]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/PageType.php
cache map
[SourceForge/phpwiki.git] / lib / PageType.php
1 <?php // -*-php-*-
2 rcs_id('$Id: PageType.php,v 1.44 2005-04-23 11:07:34 rurban Exp $');
3 /*
4  Copyright 1999,2000,2001,2002,2003,2004,2005 $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
19  along with PhpWiki; if not, write to the Free Software
20  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 require_once('lib/CachedMarkup.php');
24
25 /** A cacheable formatted wiki page.
26  */
27 class TransformedText extends CacheableMarkup {
28     /** Constructor.
29      *
30      * @param WikiDB_Page $page
31      * @param string $text  The packed page revision content.
32      * @param hash $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 TransformedText($page, $text, $meta, $type_override=false) {
37         $pagetype = false;
38         if ($type_override)
39             $pagetype = $type_override;
40         elseif (isset($meta['pagetype']))
41             $pagetype = $meta['pagetype'];
42         $this->_type = PageType::GetPageType($pagetype);
43         $this->CacheableMarkup($this->_type->transform($page, $text, $meta),
44                                $page->getName());
45     }
46
47     function getType() {
48         return $this->_type;
49     }
50 }
51
52 /**
53  * A page type descriptor.
54  *
55  * Encapsulate information about page types.
56  *
57  * Currently the only information encapsulated is how to format
58  * the specific page type.  In the future or capabilities may be
59  * added, e.g. the abilities to edit different page types (differently.)
60  * e.g. Support for the javascript htmlarea editor, which can only edit 
61  * pure HTML.
62  *
63  * IMPORTANT NOTE: Since the whole PageType class gets stored (serialized)
64  * as of the cached marked-up page, it is important that the PageType classes
65  * not have large amounts of class data.  (No class data is even better.)
66  */
67 class PageType {
68     /**
69      * Get a page type descriptor.
70      *
71      * This is a static member function.
72      *
73      * @param string $pagetype  Name of the page type.
74      * @return PageType  An object which is a subclass of PageType.
75      */
76     function GetPageType ($name=false) {
77         if (!$name)
78             $name = 'wikitext';
79         $class = "PageType_" . (string)$name;
80         if (class_exists($class))
81             return new $class;
82         trigger_error(sprintf("PageType '%s' unknown", (string)$name),
83                       E_USER_WARNING);
84         return new PageType_wikitext;
85     }
86
87     /**
88      * Get the name of this page type.
89      *
90      * @return string  Page type name.
91      */
92     function getName() {
93         if (!preg_match('/^PageType_(.+)$/i', get_class($this), $m))
94             trigger_error("Bad class name for formatter(?)", E_USER_ERROR);
95         return $m[1];
96     }
97
98     /**
99      * Transform page text.
100      *
101      * @param WikiDB_Page $page
102      * @param string $text
103      * @param hash $meta Version meta-data
104      * @return XmlContent The transformed page text.
105      */
106     function transform(&$page, &$text, $meta) {
107         $fmt_class = 'PageFormatter_' . $this->getName();
108         $formatter = new $fmt_class($page, $meta);
109         return $formatter->format($text);
110     }
111 }
112
113 class PageType_wikitext extends PageType {}
114 class PageType_html extends PageType {}
115 class PageType_pdf extends PageType {}
116
117 class PageType_wikiblog extends PageType {}
118 class PageType_comment extends PageType {}
119 class PageType_wikiforum extends PageType {}
120
121 /* To prevent from PHP5 Fatal error: Using $this when not in object context */
122 function getInterwikiMap ($pagetext = false) {
123     static $map;
124     if (empty($map))
125     $map = new PageType_interwikimap($pagetext);
126     return $map;
127 }
128
129 class PageType_interwikimap extends PageType
130 {
131     function PageType_interwikimap($pagetext = false) {
132         if (!$pagetext) {
133             $dbi = $GLOBALS['request']->getDbh();
134             $page = $dbi->getPage(_("InterWikiMap"));
135             if ($page->get('locked')) {
136                 $current = $page->getCurrentRevision();
137                 $pagetext = $current->getPackedContent();
138                 $intermap = $this->_getMapFromWikiText($pagetext);
139             } elseif ($page->exists()) {
140                 trigger_error(_("WARNING: InterWikiMap page is unlocked, so not using those links."));
141                 $intermap = false;
142             }
143             else 
144                 $intermap = false;
145         } else {
146             $intermap = $this->_getMapFromWikiText($pagetext);
147         }
148         if (!$intermap && defined('INTERWIKI_MAP_FILE'))
149             $intermap = $this->_getMapFromFile(INTERWIKI_MAP_FILE);
150
151         $this->_map = $this->_parseMap($intermap);
152         $this->_regexp = $this->_getRegexp();
153     }
154
155     function GetMap ($pagetext = false) {
156         /*PHP5 Fatal error: Using $this when not in object context */
157         if (empty($this->_map)) {
158             $map = new PageType_interwikimap($pagetext);
159             return $map;
160         } else {
161             return $this;
162         }
163     }
164
165     function getRegexp() {
166         return $this->_regexp;
167     }
168
169     function link ($link, $linktext = false) {
170         list ($moniker, $page) = split (":", $link, 2);
171         
172         if (!isset($this->_map[$moniker])) {
173             return HTML::span(array('class' => 'bad-interwiki'),
174                               $linktext ? $linktext : $link);
175         }
176
177         $url = $this->_map[$moniker];
178         
179         // Urlencode page only if it's a query arg.
180         // FIXME: this is a somewhat broken heuristic.
181         $page_enc = strstr($url, '?') ? rawurlencode($page) : $page;
182
183         if (strstr($url, '%s'))
184             $url = sprintf($url, $page_enc);
185         else
186             $url .= $page_enc;
187
188         $link = HTML::a(array('href' => $url));
189
190         if (!$linktext) {
191             $link->pushContent(PossiblyGlueIconToText('interwiki', "$moniker:"),
192                                HTML::span(array('class' => 'wikipage'), $page));
193             $link->setAttr('class', 'interwiki');
194         }
195         else {
196             $link->pushContent(PossiblyGlueIconToText('interwiki', $linktext));
197             $link->setAttr('class', 'named-interwiki');
198         }
199         
200         return $link;
201     }
202
203
204     function _parseMap ($text) {
205         if (!preg_match_all("/^\s*(\S+)\s+(\S+)/m",
206                             $text, $matches, PREG_SET_ORDER))
207             return false;
208
209         foreach ($matches as $m) {
210             $map[$m[1]] = $m[2];
211         }
212
213         // Add virtual monikers: Upload:, Talk:, User:
214         // Upload: Should be expanded later to user-specific upload dirs. 
215         // In the Upload plugin, not here: Upload:ReiniUrban/uploaded-file.png
216         if (empty($map['Upload']))
217             $map['Upload'] = getUploadDataPath();
218         if (empty($map["Talk"])) {
219             $pagename = $GLOBALS['request']->getArg('pagename');
220             if (string_ends_with($pagename, SUBPAGE_SEPARATOR._("Discussion")))
221                 $map["Talk"] = "%s";
222             else
223                 $map["Talk"] = "%s".SUBPAGE_SEPARATOR._("Discussion");
224         }
225         // User:ReiniUrban => ReiniUrban or Users/ReiniUrban
226         // Can be easily overriden by a customized InterWikiMap: 
227         //   User Users/%s
228         if (empty($map["User"])) {
229             $map["User"] = "%s";
230         }
231
232         // Maybe add other monikers also (SemanticWeb link predicates?)
233         // Should they be defined in a RDF? (strict mode)
234         // Or should the SemanticWeb lib add it by itself? 
235         // (adding only a subset dependent on the context = model)
236         return $map;
237     }
238
239     function _getMapFromWikiText ($pagetext) {
240         if (preg_match('|^<verbatim>\n(.*)^</verbatim>|ms', $pagetext, $m)) {
241             return $m[1];
242         }
243         return false;
244     }
245
246     function _getMapFromFile ($filename) {
247         if (defined('WARN_NONPUBLIC_INTERWIKIMAP') and WARN_NONPUBLIC_INTERWIKIMAP) {
248             $error_html = sprintf(_("Loading InterWikiMap from external file %s."), $filename);
249             trigger_error( $error_html, E_USER_NOTICE );
250         }
251         if (!file_exists($filename)) {
252             $finder = new FileFinder();
253             $filename = $finder->findFile(INTERWIKI_MAP_FILE);
254         }
255         @$fd = fopen ($filename, "rb");
256         @$data = fread ($fd, filesize($filename));
257         @fclose ($fd);
258
259         return $data;
260     }
261
262     function _getRegexp () {
263         if (!$this->_map)
264             return '(?:(?!a)a)'; //  Never matches.
265         
266         foreach (array_keys($this->_map) as $moniker)
267             $qkeys[] = preg_quote($moniker, '/');
268         return "(?:" . join("|", $qkeys) . ")";
269     }
270 }
271
272
273 /** How to transform text.
274  */
275 class PageFormatter {
276     /** Constructor.
277      *
278      * @param WikiDB_Page $page
279      * @param hash $meta Version meta-data.
280      */
281     function PageFormatter(&$page, $meta) {
282         $this->_page = $page;
283         $this->_meta = $meta;
284         if (!empty($meta['markup']))
285             $this->_markup = $meta['markup'];
286         else
287             $this->_markup = 1; // dump used old-markup as empty. 
288         // to be able to restore it we must keep markup 1 as default.
289         // new policy: default = new markup (old crashes quite often)
290     }
291
292     function _transform(&$text) {
293         include_once('lib/BlockParser.php');
294         return TransformText($text, $this->_markup);
295     }
296
297     /** Transform the page text.
298      *
299      * @param string $text  The raw page content (e.g. wiki-text).
300      * @return XmlContent   Transformed content.
301      */
302     function format($text) {
303         trigger_error("pure virtual", E_USER_ERROR);
304     }
305 }
306
307 class PageFormatter_wikitext extends PageFormatter 
308 {
309     function format(&$text) {
310         return HTML::div(array('class' => 'wikitext'),
311                          $this->_transform($text));
312     }
313 }
314
315 class PageFormatter_interwikimap extends PageFormatter
316 {
317     function format($text) {
318         return HTML::div(array('class' => 'wikitext'),
319                          $this->_transform($this->_getHeader($text)),
320                          $this->_formatMap($text),
321                          $this->_transform($this->_getFooter($text)));
322     }
323
324     function _getHeader($text) {
325         return preg_replace('/<verbatim>.*/s', '', $text);
326     }
327
328     function _getFooter($text) {
329         return preg_replace('@.*?(</verbatim>|\Z)@s', '', $text, 1);
330     }
331     
332     function _getMap($pagetext) {
333         $map = getInterwikiMap($pagetext);
334         return $map->_map;
335     }
336     
337     function _formatMap($pagetext) {
338         $map = $this->_getMap($pagetext);
339         if (!$map)
340             return HTML::p("<No interwiki map found>"); // Shouldn't happen.
341
342         $mon_attr = array('class' => 'interwiki-moniker');
343         $url_attr = array('class' => 'interwiki-url');
344         
345         $thead = HTML::thead(HTML::tr(HTML::th($mon_attr, _("Moniker")),
346                                       HTML::th($url_attr, _("InterWiki Address"))));
347         foreach ($map as $moniker => $interurl) {
348             $rows[] = HTML::tr(HTML::td($mon_attr, new Cached_WikiLinkIfKnown($moniker)),
349                                HTML::td($url_attr, HTML::tt($interurl)));
350         }
351         
352         return HTML::table(array('class' => 'interwiki-map'),
353                            $thead,
354                            HTML::tbody(false, $rows));
355     }
356 }
357
358 class FakePageRevision {
359     function FakePageRevision($meta) {
360         $this->_meta = $meta;
361     }
362
363     function get($key) {
364         if (empty($this->_meta[$key]))
365             return false;
366         return $this->_meta[$key];
367     }
368 }
369
370 // abstract base class
371 class PageFormatter_attach extends PageFormatter
372 {
373     var $type, $prefix;
374     
375     // Display templated contents for wikiblog, comment and wikiforum
376     function format($text) {
377         if (empty($this->type))
378             trigger_error('PageFormatter_attach->format: $type missing');
379         include_once('lib/Template.php');
380         global $request;
381         $tokens['CONTENT'] = $this->_transform($text);
382         $tokens['page'] = $this->_page;
383         $tokens['rev'] = new FakePageRevision($this->_meta);
384
385         $name = new WikiPageName($this->_page->getName());
386         $tokens[$this->prefix."_PARENT"] = $name->getParent();
387
388         $meta = $this->_meta[$this->type];
389         foreach(array('ctime', 'creator', 'creator_id') as $key)
390             $tokens[$this->prefix . "_" . strtoupper($key)] = $meta[$key];
391         
392         return new Template($this->type, $request, $tokens);
393     }
394 }
395
396 class PageFormatter_wikiblog extends PageFormatter_attach {
397     var $type = 'wikiblog', $prefix = "BLOG";
398 }
399 class PageFormatter_comment extends PageFormatter_attach {
400     var $type = 'comment', $prefix = "COMMENT";
401 }
402 class PageFormatter_wikiforum extends PageFormatter_attach {
403     var $type = 'wikiforum', $prefix = "FORUM";
404 }
405
406 /** wikiabuse for htmlarea editing. not yet used.  
407  *
408  * Warning! Once a page is edited with a htmlarea like control it is
409  * stored in HTML and cannot be converted back to WikiText as long as
410  * we have no HTML => WikiText or any other interim format (WikiExchangeFormat e.g. XML) 
411  * converter. See lib/HtmlParser.php for ongoing work on that. 
412  * So it has a viral effect and certain plugins will not work anymore.
413  * But a lot of wikiusers seem to like it.
414  */
415 class PageFormatter_html extends PageFormatter
416 {
417     function _transform($text) {
418         return $text;
419     }
420     function format($text) {
421         return $text;
422     }
423 }
424
425 /**
426  *  FIXME. not yet used
427  */
428 class PageFormatter_pdf extends PageFormatter
429 {
430
431     function _transform($text) {
432         include_once('lib/BlockParser.php');
433         return TransformText($text, $this->_markup);
434     }
435
436     // one page or set of pages?
437     // here we try to format only a single page
438     function format($text) {
439         include_once('lib/Template.php');
440         global $request;
441         $tokens['page']    = $this->_page;
442         $tokens['CONTENT'] = $this->_transform($text);
443         $pagename = $this->_page->getName();
444
445         // This is a XmlElement tree, which must be converted to PDF
446
447         // We can make use of several pdf extensions. This one - fpdf
448         // - is pure php and very easy, but looks quite ugly and has a
449         // terrible interface, as terrible as most of the othes. 
450         // The closest to HTML is htmldoc which needs an external cgi
451         // binary.
452         // We use a custom HTML->PDF class converter from PHPWebthings
453         // to be able to use templates for PDF.
454         require_once('lib/fpdf.php');
455         require_once('lib/pdf.php');
456
457         $pdf = new PDF();
458         $pdf->SetTitle($pagename);
459         $pdf->SetAuthor($this->_page->get('author'));
460         $pdf->SetCreator(WikiURL($pagename,false,1));
461         $pdf->AliasNbPages();
462         $pdf->AddPage();
463         //TODO: define fonts
464         $pdf->SetFont('Times','',12);
465         //$pdf->SetFont('Arial','B',16);
466
467         // PDF pagelayout from a special template
468         $template = new Template('pdf', $request, $tokens);
469         $pdf->ConvertFromHTML($template);
470
471         // specify filename, destination
472         $pdf->Output($pagename.".pdf",'I'); // I for stdin or D for download
473
474         // Output([string name [, string dest]])
475         return $pdf;
476     }
477 }
478 // $Log: not supported by cvs2svn $
479 // Revision 1.43  2005/02/02 20:40:12  rurban
480 // fix Talk: and User: names and links
481 //
482 // Revision 1.42  2005/02/02 19:36:56  rurban
483 // more plans
484 //
485 // Revision 1.41  2005/02/02 19:34:09  rurban
486 // more maps: Talk, User
487 //
488 // Revision 1.40  2005/01/31 12:15:08  rurban
489 // avoid some cornercase intermap warning. Thanks to Stefan <sonstiges@bayern-mail.de>
490 //
491 // Revision 1.39  2005/01/25 06:59:35  rurban
492 // fix bogus InterWikiMap warning
493 //
494 // Revision 1.38  2004/12/26 17:10:44  rurban
495 // just docs or whitespace
496 //
497 // Revision 1.37  2004/12/06 19:49:55  rurban
498 // enable action=remove which is undoable and seeable in RecentChanges: ADODB ony for now.
499 // renamed delete_page to purge_page.
500 // enable action=edit&version=-1 to force creation of a new version.
501 // added BABYCART_PATH config
502 // fixed magiqc in adodb.inc.php
503 // and some more docs
504 //
505
506 // Local Variables:
507 // mode: php
508 // tab-width: 8
509 // c-basic-offset: 4
510 // c-hanging-comment-ender-p: nil
511 // indent-tabs-mode: nil
512 // End:
513 ?>