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