]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/PageType.php
New special interwiki link markup [:LinkTo] without storing the backlink
[SourceForge/phpwiki.git] / lib / PageType.php
1 <?php // -*-php-*-
2 rcs_id('$Id: PageType.php,v 1.48 2006-10-08 12:38:11 rurban Exp $');
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
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 ($moniker == '') { // ":LinkName"
191             $link->pushContent(HTML::span(array('class' => 'wikipage'), $page));
192             $link->setAttr('class', $linktext ? 'named-wiki' : 'wiki');
193         }
194         elseif (!$linktext) {
195             $link->pushContent(PossiblyGlueIconToText('interwiki', "$moniker:"),
196                                HTML::span(array('class' => 'wikipage'), $page));
197             $link->setAttr('class', 'interwiki');
198         }
199         else {
200             $link->pushContent(PossiblyGlueIconToText('interwiki', $linktext));
201             $link->setAttr('class', 'named-interwiki');
202         }
203         
204         return $link;
205     }
206
207
208     function _parseMap ($text) {
209         if (!preg_match_all("/^\s*(\S+)\s+(.+)$/m",
210                             $text, $matches, PREG_SET_ORDER))
211             return false;
212
213         foreach ($matches as $m) {
214             $map[$m[1]] = $m[2];
215         }
216
217         // Add virtual monikers: "Upload:" "Talk:" "User:", ":"
218         // and expand special variables %u, %b, %d
219
220         // Upload: Should be expanded later to user-specific upload dirs. 
221         // In the Upload plugin, not here: Upload:ReiniUrban/uploaded-file.png
222         if (empty($map['Upload'])) {
223             $map['Upload'] = getUploadDataPath();
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         // Talk:UserName => UserName/Discussion
232         // Talk:PageName => PageName/Discussion as default, which might be overridden
233         if (empty($map["Talk"])) {
234             $pagename = $GLOBALS['request']->getArg('pagename');
235             // against PageName/Discussion/Discussion
236             if (string_ends_with($pagename, SUBPAGE_SEPARATOR._("Discussion")))
237                 $map["Talk"] = "%s";
238             else
239                 $map["Talk"] = "%s".SUBPAGE_SEPARATOR._("Discussion");
240         }
241         if (empty($map[''])) { // Magic syntax: Don't store links ":PageName" as backlink
242             $map[''] = '%s';
243         }
244
245         foreach (array('Upload','User','Talk') as $special) {
246             // Expand special variables:
247             //   %u => username
248             //   %b => wikibaseurl
249             //   %d => iso8601 DateTime
250             // %s is expanded later to the pagename
251             if (strstr($map[$special], '%u'))
252                 $map[$special] = str_replace($map[$special],
253                                              '%u', 
254                                              $GLOBALS['request']->_user->_userid);
255             if (strstr($map[$special], '%b'))
256                 $map[$special] = str_replace($map[$special],
257                                              '%b', 
258                                              PHPWIKI_BASE_URL);
259             if (strstr($map[$special], '%d'))
260                 $map[$special] = str_replace($map[$special],
261                                              '%d', 
262                                              // such as 2003-01-11T14:03:02+00:00
263                                              Iso8601DateTime());
264         }
265
266         // Maybe add other monikers also - SemanticWeb link predicates
267         // Should they be defined in a RDF? (strict mode)
268         // Or should the SemanticWeb lib add it by itself? 
269         // (adding only a subset dependent on the context = model)
270         return $map;
271     }
272
273     function _getMapFromWikiText ($pagetext) {
274         if (preg_match('|^<verbatim>\n(.*)^</verbatim>|ms', $pagetext, $m)) {
275             return $m[1];
276         }
277         return false;
278     }
279
280     function _getMapFromFile ($filename) {
281         if (defined('WARN_NONPUBLIC_INTERWIKIMAP') and WARN_NONPUBLIC_INTERWIKIMAP) {
282             $error_html = sprintf(_("Loading InterWikiMap from external file %s."), 
283                                   $filename);
284             trigger_error( $error_html, E_USER_NOTICE );
285         }
286         if (!file_exists($filename)) {
287             $finder = new FileFinder();
288             $filename = $finder->findFile(INTERWIKI_MAP_FILE);
289         }
290         @$fd = fopen ($filename, "rb");
291         @$data = fread ($fd, filesize($filename));
292         @fclose ($fd);
293
294         return $data;
295     }
296
297     function _getRegexp () {
298         if (!$this->_map)
299             return '(?:(?!a)a)'; //  Never matches.
300         
301         foreach (array_keys($this->_map) as $moniker)
302             $qkeys[] = preg_quote($moniker, '/');
303         return "(?:" . join("|", $qkeys) . ")";
304     }
305 }
306
307
308 /** How to transform text.
309  */
310 class PageFormatter {
311     /** Constructor.
312      *
313      * @param WikiDB_Page $page
314      * @param hash $meta Version meta-data.
315      */
316     function PageFormatter(&$page, $meta) {
317         $this->_page = $page;
318         $this->_meta = $meta;
319         if (!empty($meta['markup']))
320             $this->_markup = $meta['markup'];
321         else
322             $this->_markup = 2; // dump used old-markup as empty. 
323         // FIXME: To be able to restore old plain-backups we should keep markup 1 as default.
324         // New policy: default = new markup (old crashes quite often)
325     }
326
327     function _transform(&$text) {
328         include_once('lib/BlockParser.php');
329         return TransformText($text, $this->_markup);
330     }
331
332     /** Transform the page text.
333      *
334      * @param string $text  The raw page content (e.g. wiki-text).
335      * @return XmlContent   Transformed content.
336      */
337     function format($text) {
338         trigger_error("pure virtual", E_USER_ERROR);
339     }
340 }
341
342 class PageFormatter_wikitext extends PageFormatter 
343 {
344     function format(&$text) {
345         return HTML::div(array('class' => 'wikitext'),
346                          $this->_transform($text));
347     }
348 }
349
350 class PageFormatter_interwikimap extends PageFormatter
351 {
352     function format($text) {
353         return HTML::div(array('class' => 'wikitext'),
354                          $this->_transform($this->_getHeader($text)),
355                          $this->_formatMap($text),
356                          $this->_transform($this->_getFooter($text)));
357     }
358
359     function _getHeader($text) {
360         return preg_replace('/<verbatim>.*/s', '', $text);
361     }
362
363     function _getFooter($text) {
364         return preg_replace('@.*?(</verbatim>|\Z)@s', '', $text, 1);
365     }
366     
367     function _getMap($pagetext) {
368         $map = getInterwikiMap($pagetext);
369         return $map->_map;
370     }
371     
372     function _formatMap($pagetext) {
373         $map = $this->_getMap($pagetext);
374         if (!$map)
375             return HTML::p("<No interwiki map found>"); // Shouldn't happen.
376
377         $mon_attr = array('class' => 'interwiki-moniker');
378         $url_attr = array('class' => 'interwiki-url');
379         
380         $thead = HTML::thead(HTML::tr(HTML::th($mon_attr, _("Moniker")),
381                                       HTML::th($url_attr, _("InterWiki Address"))));
382         foreach ($map as $moniker => $interurl) {
383             $rows[] = HTML::tr(HTML::td($mon_attr, new Cached_WikiLinkIfKnown($moniker)),
384                                HTML::td($url_attr, HTML::tt($interurl)));
385         }
386         
387         return HTML::table(array('class' => 'interwiki-map'),
388                            $thead,
389                            HTML::tbody(false, $rows));
390     }
391 }
392
393 class FakePageRevision {
394     function FakePageRevision($meta) {
395         $this->_meta = $meta;
396     }
397
398     function get($key) {
399         if (empty($this->_meta[$key]))
400             return false;
401         return $this->_meta[$key];
402     }
403 }
404
405 // abstract base class
406 class PageFormatter_attach extends PageFormatter
407 {
408     var $type, $prefix;
409     
410     // Display templated contents for wikiblog, comment and wikiforum
411     function format($text) {
412         if (empty($this->type))
413             trigger_error('PageFormatter_attach->format: $type missing');
414         include_once('lib/Template.php');
415         global $request;
416         $tokens['CONTENT'] = $this->_transform($text);
417         $tokens['page'] = $this->_page;
418         $tokens['rev'] = new FakePageRevision($this->_meta);
419
420         $name = new WikiPageName($this->_page->getName());
421         $tokens[$this->prefix."_PARENT"] = $name->getParent();
422
423         $meta = $this->_meta[$this->type];
424         foreach(array('ctime', 'creator', 'creator_id') as $key)
425             $tokens[$this->prefix . "_" . strtoupper($key)] = $meta[$key];
426         
427         return new Template($this->type, $request, $tokens);
428     }
429 }
430
431 class PageFormatter_wikiblog extends PageFormatter_attach {
432     var $type = 'wikiblog', $prefix = "BLOG";
433 }
434 class PageFormatter_comment extends PageFormatter_attach {
435     var $type = 'comment', $prefix = "COMMENT";
436 }
437 class PageFormatter_wikiforum extends PageFormatter_attach {
438     var $type = 'wikiforum', $prefix = "FORUM";
439 }
440
441 /** wikiabuse for htmlarea editing. not yet used.  
442  *
443  * Warning! Once a page is edited with a htmlarea like control it is
444  * stored in HTML and cannot be converted back to WikiText as long as
445  * we have no HTML => WikiText or any other interim format (WikiExchangeFormat e.g. XML) 
446  * converter. See lib/HtmlParser.php for ongoing work on that. 
447  * So it has a viral effect and certain plugins will not work anymore.
448  * But a lot of wikiusers seem to like it.
449  */
450 class PageFormatter_html extends PageFormatter
451 {
452     function _transform($text) {
453         return $text;
454     }
455     function format($text) {
456         return $text;
457     }
458 }
459
460 /**
461  *  FIXME. not yet used
462  */
463 class PageFormatter_pdf extends PageFormatter
464 {
465
466     function _transform($text) {
467         include_once('lib/BlockParser.php');
468         return TransformText($text, $this->_markup);
469     }
470
471     // one page or set of pages?
472     // here we try to format only a single page
473     function format($text) {
474         include_once('lib/Template.php');
475         global $request;
476         $tokens['page']    = $this->_page;
477         $tokens['CONTENT'] = $this->_transform($text);
478         $pagename = $this->_page->getName();
479
480         // This is a XmlElement tree, which must be converted to PDF
481
482         // We can make use of several pdf extensions. This one - fpdf
483         // - is pure php and very easy, but looks quite ugly and has a
484         // terrible interface, as terrible as most of the othes. 
485         // The closest to HTML is htmldoc which needs an external cgi
486         // binary.
487         // We use a custom HTML->PDF class converter from PHPWebthings
488         // to be able to use templates for PDF.
489         require_once('lib/fpdf.php');
490         require_once('lib/pdf.php');
491
492         $pdf = new PDF();
493         $pdf->SetTitle($pagename);
494         $pdf->SetAuthor($this->_page->get('author'));
495         $pdf->SetCreator(WikiURL($pagename,false,1));
496         $pdf->AliasNbPages();
497         $pdf->AddPage();
498         //TODO: define fonts
499         $pdf->SetFont('Times','',12);
500         //$pdf->SetFont('Arial','B',16);
501
502         // PDF pagelayout from a special template
503         $template = new Template('pdf', $request, $tokens);
504         $pdf->ConvertFromHTML($template);
505
506         // specify filename, destination
507         $pdf->Output($pagename.".pdf",'I'); // I for stdin or D for download
508
509         // Output([string name [, string dest]])
510         return $pdf;
511     }
512 }
513 // $Log: not supported by cvs2svn $
514 // Revision 1.47  2005/08/07 09:14:38  rurban
515 // fix comments
516 //
517 // Revision 1.46  2005/08/06 13:09:33  rurban
518 // allow spaces in interwiki paths, even implicitly. fixes bug #1218733
519 //
520 // Revision 1.45  2005/05/06 16:48:41  rurban
521 // support %u, %b, %d expansion for Upload: User: and Talk: interwiki monikers
522 //
523 // Revision 1.44  2005/04/23 11:07:34  rurban
524 // cache map
525 //
526 // Revision 1.43  2005/02/02 20:40:12  rurban
527 // fix Talk: and User: names and links
528 //
529 // Revision 1.42  2005/02/02 19:36:56  rurban
530 // more plans
531 //
532 // Revision 1.41  2005/02/02 19:34:09  rurban
533 // more maps: Talk, User
534 //
535 // Revision 1.40  2005/01/31 12:15:08  rurban
536 // avoid some cornercase intermap warning. Thanks to Stefan <sonstiges@bayern-mail.de>
537 //
538 // Revision 1.39  2005/01/25 06:59:35  rurban
539 // fix bogus InterWikiMap warning
540 //
541 // Revision 1.38  2004/12/26 17:10:44  rurban
542 // just docs or whitespace
543 //
544 // Revision 1.37  2004/12/06 19:49:55  rurban
545 // enable action=remove which is undoable and seeable in RecentChanges: ADODB ony for now.
546 // renamed delete_page to purge_page.
547 // enable action=edit&version=-1 to force creation of a new version.
548 // added BABYCART_PATH config
549 // fixed magiqc in adodb.inc.php
550 // and some more docs
551 //
552
553 // Local Variables:
554 // mode: php
555 // tab-width: 8
556 // c-basic-offset: 4
557 // c-hanging-comment-ender-p: nil
558 // indent-tabs-mode: nil
559 // End:
560 ?>