]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/PageType.php
avoid some cornercase intermap warning. Thanks to Stefan <sonstiges@bayern-mail.de>
[SourceForge/phpwiki.git] / lib / PageType.php
1 <?php // -*-php-*-
2 rcs_id('$Id: PageType.php,v 1.40 2005-01-31 12:15:08 rurban Exp $');
3 /*
4  Copyright 1999,2000,2001,2002,2003,2004 $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     $map = new PageType_interwikimap($pagetext);
124     return $map;
125 }
126
127 class PageType_interwikimap extends PageType
128 {
129     function PageType_interwikimap($pagetext = false) {
130         if (!$pagetext) {
131             $dbi = $GLOBALS['request']->getDbh();
132             $page = $dbi->getPage(_("InterWikiMap"));
133             if ($page->get('locked')) {
134                 $current = $page->getCurrentRevision();
135                 $pagetext = $current->getPackedContent();
136                 $intermap = $this->_getMapFromWikiText($pagetext);
137             } elseif ($page->exists()) {
138                 trigger_error(_("WARNING: InterWikiMap page is unlocked, so not using those links."));
139                 $intermap = false;
140             }
141             else 
142                 $intermap = false;
143         } else {
144             $intermap = $this->_getMapFromWikiText($pagetext);
145         }
146         if (!$intermap && defined('INTERWIKI_MAP_FILE'))
147             $intermap = $this->_getMapFromFile(INTERWIKI_MAP_FILE);
148
149         $this->_map = $this->_parseMap($intermap);
150         $this->_regexp = $this->_getRegexp();
151     }
152
153     function GetMap ($pagetext = false) {
154         /*PHP5 Fatal error: Using $this when not in object context */
155         if (empty($this->_map)) {
156             $map = new PageType_interwikimap($pagetext);
157             return $map;
158         } else {
159             return $this;
160         }
161     }
162
163     function getRegexp() {
164         return $this->_regexp;
165     }
166
167     function link ($link, $linktext = false) {
168         list ($moniker, $page) = split (":", $link, 2);
169         
170         if (!isset($this->_map[$moniker])) {
171             return HTML::span(array('class' => 'bad-interwiki'),
172                               $linktext ? $linktext : $link);
173         }
174
175         $url = $this->_map[$moniker];
176         
177         // Urlencode page only if it's a query arg.
178         // FIXME: this is a somewhat broken heuristic.
179         $page_enc = strstr($url, '?') ? rawurlencode($page) : $page;
180
181         if (strstr($url, '%s'))
182             $url = sprintf($url, $page_enc);
183         else
184             $url .= $page_enc;
185
186         $link = HTML::a(array('href' => $url));
187
188         if (!$linktext) {
189             $link->pushContent(PossiblyGlueIconToText('interwiki', "$moniker:"),
190                                HTML::span(array('class' => 'wikipage'), $page));
191             $link->setAttr('class', 'interwiki');
192         }
193         else {
194             $link->pushContent(PossiblyGlueIconToText('interwiki', $linktext));
195             $link->setAttr('class', 'named-interwiki');
196         }
197         
198         return $link;
199     }
200
201
202     function _parseMap ($text) {
203         if (!preg_match_all("/^\s*(\S+)\s+(\S+)/m",
204                             $text, $matches, PREG_SET_ORDER))
205             return false;
206         foreach ($matches as $m) {
207             $map[$m[1]] = $m[2];
208         }
209         // add virtual "Upload:" moniker
210         if (empty($map['Upload'])) $map['Upload'] = getUploadDataPath();
211
212         // maybe add other monikers also (SemanticWeb link predicates?)
213         // Should they be defined in a RDF? (strict mode)
214         // Or should the SemanticWeb lib add it by itself? 
215         // (adding only a subset dependent on the context = model)
216         return $map;
217     }
218
219     function _getMapFromWikiText ($pagetext) {
220         if (preg_match('|^<verbatim>\n(.*)^</verbatim>|ms', $pagetext, $m)) {
221             return $m[1];
222         }
223         return false;
224     }
225
226     function _getMapFromFile ($filename) {
227         if (defined('WARN_NONPUBLIC_INTERWIKIMAP') and WARN_NONPUBLIC_INTERWIKIMAP) {
228             $error_html = sprintf(_("Loading InterWikiMap from external file %s."), $filename);
229             trigger_error( $error_html, E_USER_NOTICE );
230         }
231         if (!file_exists($filename)) {
232             $finder = new FileFinder();
233             $filename = $finder->findFile(INTERWIKI_MAP_FILE);
234         }
235         @$fd = fopen ($filename, "rb");
236         @$data = fread ($fd, filesize($filename));
237         @fclose ($fd);
238
239         return $data;
240     }
241
242     function _getRegexp () {
243         if (!$this->_map)
244             return '(?:(?!a)a)'; //  Never matches.
245         
246         foreach (array_keys($this->_map) as $moniker)
247             $qkeys[] = preg_quote($moniker, '/');
248         return "(?:" . join("|", $qkeys) . ")";
249     }
250 }
251
252
253 /** How to transform text.
254  */
255 class PageFormatter {
256     /** Constructor.
257      *
258      * @param WikiDB_Page $page
259      * @param hash $meta Version meta-data.
260      */
261     function PageFormatter(&$page, $meta) {
262         $this->_page = $page;
263         $this->_meta = $meta;
264         if (!empty($meta['markup']))
265             $this->_markup = $meta['markup'];
266         else
267             $this->_markup = 1; // dump used old-markup as empty. 
268         // to be able to restore it we must keep markup 1 as default.
269         // new policy: default = new markup (old crashes quite often)
270     }
271
272     function _transform(&$text) {
273         include_once('lib/BlockParser.php');
274         return TransformText($text, $this->_markup);
275     }
276
277     /** Transform the page text.
278      *
279      * @param string $text  The raw page content (e.g. wiki-text).
280      * @return XmlContent   Transformed content.
281      */
282     function format($text) {
283         trigger_error("pure virtual", E_USER_ERROR);
284     }
285 }
286
287 class PageFormatter_wikitext extends PageFormatter 
288 {
289     function format(&$text) {
290         return HTML::div(array('class' => 'wikitext'),
291                          $this->_transform($text));
292     }
293 }
294
295 class PageFormatter_interwikimap extends PageFormatter
296 {
297     function format($text) {
298         return HTML::div(array('class' => 'wikitext'),
299                          $this->_transform($this->_getHeader($text)),
300                          $this->_formatMap($text),
301                          $this->_transform($this->_getFooter($text)));
302     }
303
304     function _getHeader($text) {
305         return preg_replace('/<verbatim>.*/s', '', $text);
306     }
307
308     function _getFooter($text) {
309         return preg_replace('@.*?(</verbatim>|\Z)@s', '', $text, 1);
310     }
311     
312     function _getMap($pagetext) {
313         $map = getInterwikiMap($pagetext);
314         return $map->_map;
315     }
316     
317     function _formatMap($pagetext) {
318         $map = $this->_getMap($pagetext);
319         if (!$map)
320             return HTML::p("<No interwiki map found>"); // Shouldn't happen.
321
322         $mon_attr = array('class' => 'interwiki-moniker');
323         $url_attr = array('class' => 'interwiki-url');
324         
325         $thead = HTML::thead(HTML::tr(HTML::th($mon_attr, _("Moniker")),
326                                       HTML::th($url_attr, _("InterWiki Address"))));
327         foreach ($map as $moniker => $interurl) {
328             $rows[] = HTML::tr(HTML::td($mon_attr, new Cached_WikiLinkIfKnown($moniker)),
329                                HTML::td($url_attr, HTML::tt($interurl)));
330         }
331         
332         return HTML::table(array('class' => 'interwiki-map'),
333                            $thead,
334                            HTML::tbody(false, $rows));
335     }
336 }
337
338 class FakePageRevision {
339     function FakePageRevision($meta) {
340         $this->_meta = $meta;
341     }
342
343     function get($key) {
344         if (empty($this->_meta[$key]))
345             return false;
346         return $this->_meta[$key];
347     }
348 }
349
350 // abstract base class
351 class PageFormatter_attach extends PageFormatter
352 {
353     var $type, $prefix;
354     
355     // Display templated contents for wikiblog, comment and wikiforum
356     function format($text) {
357         if (empty($this->type))
358             trigger_error('PageFormatter_attach->format: $type missing');
359         include_once('lib/Template.php');
360         global $request;
361         $tokens['CONTENT'] = $this->_transform($text);
362         $tokens['page'] = $this->_page;
363         $tokens['rev'] = new FakePageRevision($this->_meta);
364
365         $name = new WikiPageName($this->_page->getName());
366         $tokens[$this->prefix."_PARENT"] = $name->getParent();
367
368         $meta = $this->_meta[$this->type];
369         foreach(array('ctime', 'creator', 'creator_id') as $key)
370             $tokens[$this->prefix . "_" . strtoupper($key)] = $meta[$key];
371         
372         return new Template($this->type, $request, $tokens);
373     }
374 }
375
376 class PageFormatter_wikiblog extends PageFormatter_attach {
377     var $type = 'wikiblog', $prefix = "BLOG";
378 }
379 class PageFormatter_comment extends PageFormatter_attach {
380     var $type = 'comment', $prefix = "COMMENT";
381 }
382 class PageFormatter_wikiforum extends PageFormatter_attach {
383     var $type = 'wikiforum', $prefix = "FORUM";
384 }
385
386 /** wikiabuse for htmlarea editing. not yet used.  
387  *
388  * Warning! Once a page is edited with a htmlarea like control it is
389  * stored in HTML and cannot be converted back to WikiText as long as
390  * we have no HTML => WikiText or any other interim format (WikiExchangeFormat e.g. XML) 
391  * converter. See lib/HtmlParser.php for ongoing work on that. 
392  * So it has a viral effect and certain plugins will not work anymore.
393  * But a lot of wikiusers seem to like it.
394  */
395 class PageFormatter_html extends PageFormatter
396 {
397     function _transform($text) {
398         return $text;
399     }
400     function format($text) {
401         return $text;
402     }
403 }
404
405 /**
406  *  FIXME. not yet used
407  */
408 class PageFormatter_pdf extends PageFormatter
409 {
410
411     function _transform($text) {
412         include_once('lib/BlockParser.php');
413         return TransformText($text, $this->_markup);
414     }
415
416     // one page or set of pages?
417     // here we try to format only a single page
418     function format($text) {
419         include_once('lib/Template.php');
420         global $request;
421         $tokens['page']    = $this->_page;
422         $tokens['CONTENT'] = $this->_transform($text);
423         $pagename = $this->_page->getName();
424
425         // This is a XmlElement tree, which must be converted to PDF
426
427         // We can make use of several pdf extensions. This one - fpdf
428         // - is pure php and very easy, but looks quite ugly and has a
429         // terrible interface, as terrible as most of the othes. 
430         // The closest to HTML is htmldoc which needs an external cgi
431         // binary.
432         // We use a custom HTML->PDF class converter from PHPWebthings
433         // to be able to use templates for PDF.
434         require_once('lib/fpdf.php');
435         require_once('lib/pdf.php');
436
437         $pdf = new PDF();
438         $pdf->SetTitle($pagename);
439         $pdf->SetAuthor($this->_page->get('author'));
440         $pdf->SetCreator(WikiURL($pagename,false,1));
441         $pdf->AliasNbPages();
442         $pdf->AddPage();
443         //TODO: define fonts
444         $pdf->SetFont('Times','',12);
445         //$pdf->SetFont('Arial','B',16);
446
447         // PDF pagelayout from a special template
448         $template = new Template('pdf', $request, $tokens);
449         $pdf->ConvertFromHTML($template);
450
451         // specify filename, destination
452         $pdf->Output($pagename.".pdf",'I'); // I for stdin or D for download
453
454         // Output([string name [, string dest]])
455         return $pdf;
456     }
457 }
458 // $Log: not supported by cvs2svn $
459 // Revision 1.39  2005/01/25 06:59:35  rurban
460 // fix bogus InterWikiMap warning
461 //
462 // Revision 1.38  2004/12/26 17:10:44  rurban
463 // just docs or whitespace
464 //
465 // Revision 1.37  2004/12/06 19:49:55  rurban
466 // enable action=remove which is undoable and seeable in RecentChanges: ADODB ony for now.
467 // renamed delete_page to purge_page.
468 // enable action=edit&version=-1 to force creation of a new version.
469 // added BABYCART_PATH config
470 // fixed magiqc in adodb.inc.php
471 // and some more docs
472 //
473
474 // Local Variables:
475 // mode: php
476 // tab-width: 8
477 // c-basic-offset: 4
478 // c-hanging-comment-ender-p: nil
479 // indent-tabs-mode: nil
480 // End:
481 ?>