]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/display.php
RateIt text is too small
[SourceForge/phpwiki.git] / lib / display.php
1 <?php
2
3 /* Copyright (C) 2004-2011 $ThePhpWikiProgrammingTeam
4  *
5  * This file is part of PhpWiki.
6  *
7  * PhpWiki is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * PhpWiki is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along
18  * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  */
21
22 // display.php: fetch page or get default content
23
24 require_once 'lib/Template.php';
25
26 /**
27  * Extract keywords from Category* links on page.
28  */
29 function GleanKeywords($page)
30 {
31     if (!defined('KEYWORDS')) return '';
32     require_once 'lib/TextSearchQuery.php';
33     $search = new TextSearchQuery(KEYWORDS, true);
34     $KeywordLinkRegexp = $search->asRegexp();
35     // iterate over the pagelinks (could be a large number) [15ms on PluginManager]
36     // or do a titleSearch and check the categories if they are linked?
37     $links = $page->getPageLinks();
38     $keywords[] = SplitPagename($page->getName());
39     while ($link = $links->next()) {
40         $m = array();
41         if (preg_match($KeywordLinkRegexp, $link->getName(), $m))
42             $keywords[] = SplitPagename($m[0]);
43     }
44     $keywords[] = WIKI_NAME;
45     return join(', ', $keywords);
46 }
47
48 /** Make a link back to redirecting page.
49  *
50  * @param $pagename string  Name of redirecting page.
51  * @return XmlContent Link to the redirecting page.
52  */
53 function RedirectorLink($pagename)
54 {
55     $url = WikiURL($pagename, array('redirectfrom' => ''));
56     return HTML::a(array('class' => 'redirectfrom wiki',
57             'href' => $url),
58         $pagename);
59 }
60
61 /* only on ?action= */
62 function actionPage(&$request, $action)
63 {
64     global $WikiTheme;
65     global $robots;
66
67     $pagename = $request->getArg('pagename');
68     $version = $request->getArg('version');
69
70     $page = $request->getPage();
71     $revision = $page->getCurrentRevision();
72
73     $dbi = $request->getDbh();
74     $actionpage = $dbi->getPage($action);
75     $actionrev = $actionpage->getCurrentRevision();
76
77     $pagetitle = HTML(fmt("%s: %s",
78         $actionpage->getName(),
79         $WikiTheme->linkExistingWikiWord($pagename, false, $version)));
80
81     $request->setValidators(array('pageversion' => $revision->getVersion(),
82         '%mtime' => $revision->get('mtime')));
83     $request->appendValidators(array('pagerev' => $revision->getVersion(),
84         '%mtime' => $revision->get('mtime')));
85     $request->appendValidators(array('actionpagerev' => $actionrev->getVersion(),
86         '%mtime' => $actionrev->get('mtime')));
87
88     $transformedContent = $actionrev->getTransformedContent();
89
90     /* Optionally tell google (and others) not to take notice of action pages.
91        RecentChanges or AllPages might be an exception.
92     */
93     $args = array();
94     if (defined('GOOGLE_LINKS_NOFOLLOW') and GOOGLE_LINKS_NOFOLLOW) {
95         $robots = "noindex,nofollow";
96         $args = array('ROBOTS_META' => $robots);
97     }
98
99     /* Handle other formats: So far we had html only.
100        xml is requested by loaddump, rss is handled by recentchanges,
101        pdf is a special action, but should be a format to dump multiple pages
102        if the actionpage plugin returns a pagelist.
103        rdf and owl are handled by SemanticWeb.
104     */
105     $format = $request->getArg('format');
106
107     /* At first the single page formats: html, xml */
108     if ($pagename == _("LinkDatabase")) {
109         $template = Template('browse', array('CONTENT' => $transformedContent));
110         GeneratePage($template, $pagetitle, $revision, $args);
111     } elseif (!$format or $format == 'html' or $format == 'sidebar' or $format == 'contribs') {
112         $template = Template('browse', array('CONTENT' => $transformedContent));
113         GeneratePage($template, $pagetitle, $revision, $args);
114     } elseif ($format == 'xml') {
115         $request->setArg('format', '');
116         $template = new Template('browse', $request,
117             array('revision' => $revision,
118                 'CONTENT' => $transformedContent,
119             ));
120         $html = GeneratePageAsXML($template, $pagename, $revision /*,
121                   array('VALID_LINKS' => $args['VALID_LINKS'])*/);
122         header("Content-Type: application/xhtml+xml; charset=UTF-8");
123         echo $html;
124     } else {
125         $pagelist = null;
126         require_once 'lib/WikiPlugin.php';
127         // Then the multi-page formats
128         // rss (if not already handled by RecentChanges)
129         // Need the pagelist from the first plugin
130         foreach ($transformedContent->_content as $cached_element) {
131             if (is_a($cached_element, "Cached_PluginInvocation")) {
132                 $loader = new WikiPluginLoader();
133                 $markup = null;
134                 // return the first found pagelist
135                 $pagelist = $loader->expandPI($cached_element->_pi, $request,
136                     $markup, $pagename);
137                 if (is_a($pagelist, 'PageList'))
138                     break;
139             }
140         }
141         if (!$pagelist or !is_a($pagelist, 'PageList')) {
142             if (!in_array($format, array("rss91", "rss2", "rss", "atom", "rdf")))
143                 trigger_error(sprintf("Format %s requires an actionpage returning a pagelist.",
144                     $format)
145                     . "\n" . ("Fall back to single page mode"), E_USER_WARNING);
146             require_once 'lib/PageList.php';
147             $pagelist = new PageList();
148             if ($format == 'pdf')
149                 $pagelist->addPage($page);
150         } else {
151             foreach ($pagelist->_pages as $page) {
152                 $name = $page->getName();
153                 if ($name != $pagename and $page->exists())
154                     $args['VALID_LINKS'][] = $name;
155             }
156         }
157         if ($format == 'pdf') {
158             require_once 'lib/pdf.php';
159             array_unshift($args['VALID_LINKS'], $pagename);
160             ConvertAndDisplayPdfPageList($request, $pagelist);
161         } elseif ($format == 'ziphtml') { // need to fix links
162             require_once 'lib/loadsave.php';
163             array_unshift($args['VALID_LINKS'], $pagename);
164             $request->setArg('zipname', FilenameForPage($pagename) . ".zip");
165             $request->setArg('pages', $args['VALID_LINKS']);
166             $request->setArg('format', '');
167             MakeWikiZipHtml($request);
168         } // time-sorted RDF à la RecentChanges
169         elseif (in_array($format, array("rss91", "rss2", "rss", "atom"))) {
170             $args = $request->getArgs();
171             //$request->setArg('format','');
172             if ($pagename == _("RecentChanges")) {
173                 $template->printExpansion($args);
174             } else {
175                 require_once 'lib/plugin/RecentChanges.php';
176                 $plugin = new WikiPlugin_RecentChanges();
177                 return $plugin->format($plugin->getChanges($request->_dbi, $args), $args);
178             }
179         } elseif ($format == 'json') { // for faster autocompletion on searches
180             $req_args =& $request->args;
181             unset($req_args['format']);
182             $json = array('count' => count($pagelist->_pages),
183                 'list' => $args['VALID_LINKS'],
184                 'args' => $req_args,
185                 'phpwiki-version' => PHPWIKI_VERSION);
186             if (loadPhpExtension('json')) {
187                 $json_enc = json_encode($json);
188             } else {
189                 require_once 'lib/pear/JSON.php';
190                 $j = new Services_JSON();
191                 $json_enc = $j->encode($json);
192             }
193             header("Content-Type: application/json");
194             die($json_enc);
195         } elseif ($format == 'rdf') { // all semantic relations and attributes
196             require_once 'lib/SemanticWeb.php';
197             $rdf = new RdfWriter($request, $pagelist);
198             $rdf->format();
199         } elseif ($format == 'rdfs') {
200             require_once 'lib/SemanticWeb.php';
201             $rdf = new RdfsWriter($request, $pagelist);
202             $rdf->format();
203         } elseif ($format == 'owl') { // or daml?
204             require_once 'lib/SemanticWeb.php';
205             $rdf = new OwlWriter($request, $pagelist);
206             $rdf->format();
207         } else {
208             if (!in_array($pagename, array(_("LinkDatabase"))))
209                 trigger_error(sprintf(_("Unsupported argument: %s=%s"), "format", $format),
210                     E_USER_WARNING);
211             $template = Template('browse', array('CONTENT' => $transformedContent));
212             GeneratePage($template, $pagetitle, $revision, $args);
213         }
214     }
215     $request->checkValidators();
216     flush();
217     return '';
218 }
219
220 /**
221  * @param WikiRequest $request
222  * @param Template $template
223  * @return string
224  */
225 function displayPage(&$request, $template = null)
226 {
227     global $WikiTheme;
228     global $robots;
229     $pagename = $request->getArg('pagename');
230     $version = $request->getArg('version');
231     $page = $request->getPage();
232
233     if ($version) {
234         $revision = $page->getRevision($version);
235         if (!$revision)
236             NoSuchRevision($request, $page, $version);
237         /* Tell Google (and others) to ignore old versions of pages */
238         $robots = "noindex,nofollow";
239         $toks['ROBOTS_META'] = $robots;
240     } else {
241         $revision = $page->getCurrentRevision();
242     }
243     $format = $request->getArg('format');
244     if ($format == 'xml') { // fast ajax: include page content asynchronously
245         header("Content-Type: text/xml");
246         echo "<", "?xml version=\"1.0\" encoding=\"UTF-8\"?", ">\n";
247         // DOCTYPE html needed to allow unencoded entities like &nbsp; without !CDATA[]
248         echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
249   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">', "\n";
250         if ($page->exists()) {
251             header("Last-Modified: " . Rfc1123DateTime($revision->get('mtime')));
252             $request->cacheControl();
253             $request->setArg('format', '');
254             $page_content = $revision->getTransformedContent();
255             $page_content->printXML();
256             $request->_is_buffering_output = false; // avoid wrong Content-Length with errors
257             $request->finish();
258         } else {
259             $request->cacheControl();
260             echo('<div style="display:none;" />');
261             $request->_is_buffering_output = false; // avoid wrong Content-Length with errors
262             $request->finish();
263             exit();
264         }
265     }
266
267     if (isSubPage($pagename)) {
268         $pages = explode('/', $pagename);
269         $last_page = array_pop($pages); // deletes last element from array as side-effect
270         $pageheader = HTML::span(HTML::a(array('href' => WikiURL($pages[0]),
271                 'class' => 'pagetitle'
272             ),
273             $WikiTheme->maybeSplitWikiWord($pages[0] . '/')));
274         $first_pages = $pages[0] . '/';
275         array_shift($pages);
276         foreach ($pages as $p) {
277             $pageheader->pushContent(HTML::a(array('href' => WikiURL($first_pages . $p),
278                     'class' => 'backlinks'),
279                 $WikiTheme->maybeSplitWikiWord($p . '/')));
280             $first_pages .= $p . '/';
281         }
282         $backlink = HTML::a(array('href' => WikiURL($pagename,
283                 array('action' => __("BackLinks"))),
284                 'class' => 'backlinks'),
285             $WikiTheme->maybeSplitWikiWord($last_page));
286         $backlink->addTooltip(sprintf(_("BackLinks for %s"), $pagename));
287         $pageheader->pushContent($backlink);
288     } else {
289         $pageheader = HTML::a(array('href' => WikiURL($pagename,
290                 array('action' => __("BackLinks"))),
291                 'class' => 'backlinks'),
292             $WikiTheme->maybeSplitWikiWord($pagename));
293         $pageheader->addTooltip(sprintf(_("BackLinks for %s"), $pagename));
294     }
295
296     $pagetitle = SplitPagename($pagename);
297     if (($redirect_from = $request->getArg('redirectfrom'))) {
298         $redirect_message = HTML::span(array('class' => 'redirectfrom'),
299             fmt("(Redirected from %s)",
300                 RedirectorLink($redirect_from)));
301         // abuse the $redirected template var for some status update notice
302     } elseif ($request->getArg('errormsg')) {
303         $redirect_message = HTML::p(array('class' => 'error'),
304             $request->getArg('errormsg'));
305         $request->setArg('errormsg', false);
306     } elseif ($request->getArg('warningmsg')) {
307         $redirect_message = HTML::p(array('class' => 'warning_msg'),
308             $request->getArg('warningmsg'));
309         $request->setArg('errormsg', false);
310     }
311
312     $request->appendValidators(array('pagerev' => $revision->getVersion(),
313         '%mtime' => $revision->get('mtime')));
314
315     $toks['TITLE'] = $pagetitle; // <title> tag
316     $toks['HEADER'] = $pageheader; // h1 with backlink
317     $toks['revision'] = $revision;
318
319     // On external searchengine (google) referrer, highlight the searchterm and
320     // pass through the Searchhighlight actionpage.
321     if ($result = isExternalReferrer($request)) {
322         if (!empty($result['query'])) {
323             if (ENABLE_SEARCHHIGHLIGHT) {
324                 $request->_searchhighlight = $result;
325                 $request->appendValidators(array('%mtime' => time())); // force no cache(?)
326                 // Should be changed to check the engine and search term only
327                 // $request->setArg('nocache', 1);
328                 $page_content = new TransformedText($revision->getPage(),
329                     $revision->getPackedContent(),
330                     $revision->getMetaData());
331                 /* Now add the SearchHighlight plugin to the top of the page, in memory only.
332                    You can parametrize this by changing the SearchHighlight action page.
333                 */
334                 if ($actionpage = $request->findActionPage('SearchHighlight')) {
335                     $actionpage = $request->getPage($actionpage);
336                     $actionrev = $actionpage->getCurrentRevision();
337                     $pagetitle = HTML(fmt("%s: %s",
338                         $actionpage->getName(),
339                         $WikiTheme->linkExistingWikiWord($pagename, false, $version)));
340                     $request->appendValidators(array('actionpagerev' => $actionrev->getVersion(),
341                         '%mtime' => $actionrev->get('mtime')));
342                     $toks['SEARCH_ENGINE'] = $result['engine'];
343                     $toks['SEARCH_ENGINE_URL'] = $result['engine_url'];
344                     $toks['SEARCH_TERM'] = $result['query'];
345                     //$toks['HEADER'] = HTML($actionpage->getName(),": ",$pageheader); // h1 with backlink
346                     $actioncontent = new TransformedText($actionrev->getPage(),
347                         $actionrev->getPackedContent(),
348                         $actionrev->getMetaData());
349                     // prepend the actionpage in front of the hightlighted content
350                     $toks['CONTENT'] = HTML($actioncontent, $page_content);
351                 }
352             }
353         } else {
354             $page_content = $revision->getTransformedContent();
355         }
356     } else {
357         $page_content = $revision->getTransformedContent();
358     }
359
360     if ($pagename == _("SandBox")) {
361         $robots = "noindex,nofollow";
362         $toks['ROBOTS_META'] = $robots;
363     } elseif (isActionPage($pagename)) {
364         $robots = "noindex,nofollow";
365         $toks['ROBOTS_META'] = $robots;
366     } elseif (!isset($toks['ROBOTS_META'])) {
367         $robots = "index,follow";
368         $toks['ROBOTS_META'] = $robots;
369     }
370     if (!isset($toks['CONTENT']))
371         $toks['CONTENT'] = new Template('browse', $request, $page_content);
372     if (!empty($redirect_message))
373         $toks['redirected'] = $redirect_message;
374
375     // Massive performance problem parsing at run-time into all xml objects
376     // looking for p's. Should be optional, if not removed at all.
377     //$toks['PAGE_DESCRIPTION'] = $page_content->getDescription();
378     $toks['PAGE_KEYWORDS'] = GleanKeywords($page);
379     if (!$template)
380         $template = new Template('html', $request);
381
382     // Handle other formats: So far we had html only.
383     // xml is requested by loaddump, rss is handled by RecentChanges,
384     // pdf is a special action, but should be a format to dump multiple pages
385     // if the actionpage plugin returns a pagelist.
386     // rdf, owl, kbmodel, daml, ... are handled by SemanticWeb.
387     /* Only single page versions. rss only if not already handled by RecentChanges.
388      */
389     if (!$format or $format == 'html' or $format == 'sidebar' or $format == 'contribs') {
390         $template->printExpansion($toks);
391     } else {
392         // No pagelist here. Single page version only
393         require_once 'lib/PageList.php';
394         $pagelist = new PageList();
395         $pagelist->addPage($page);
396         if ($format == 'pdf') {
397             require_once 'lib/pdf.php';
398             $request->setArg('format', '');
399             ConvertAndDisplayPdfPageList($request, $pagelist);
400             // time-sorted rdf a la RecentChanges
401         } elseif (in_array($format, array("rss91", "rss2", "rss", "atom"))) {
402             //$request->setArg('format','');
403             if ($pagename == _("RecentChanges"))
404                 $template->printExpansion($toks);
405             else {
406                 require_once 'lib/plugin/RecentChanges.php';
407                 $plugin = new WikiPlugin_RecentChanges();
408                 $args = $request->getArgs();
409                 return $plugin->format($plugin->getChanges($request->_dbi, $args), $args);
410             }
411         } elseif ($format == 'rdf') { // all semantic relations and attributes
412             require_once 'lib/SemanticWeb.php';
413             $rdf = new RdfWriter($request, $pagelist);
414             $rdf->format();
415         } elseif ($format == 'owl') { // or daml?
416             require_once 'lib/SemanticWeb.php';
417             $rdf = new OwlWriter($request, $pagelist);
418             $rdf->format();
419         } elseif ($format == 'json') { // include page content asynchronously
420             $request->setArg('format', '');
421             if ($page->exists())
422                 $content = $page_content->asXML();
423             else
424                 $content = '';
425             $req_args = $request->args;
426             unset($req_args['format']);
427             // no meta-data so far, just the content
428             $json = array('content' => $content,
429                 'args' => $req_args,
430                 'phpwiki-version' => PHPWIKI_VERSION);
431             if (loadPhpExtension('json')) {
432                 $json_enc = json_encode($json);
433             } else {
434                 require_once 'lib/pear/JSON.php';
435                 $j = new Services_JSON();
436                 $json_enc = $j->encode($json);
437             }
438             header("Content-Type: application/json");
439             die($json_enc);
440         } else {
441             if (!in_array($pagename, array(_("LinkDatabase"))))
442                 trigger_error(sprintf(_("Unsupported argument: %s=%s"), "format", $format),
443                     E_USER_WARNING);
444             $template->printExpansion($toks);
445         }
446     }
447
448     $page->increaseHitCount();
449
450     if ($request->getArg('action') != 'pdf') {
451         $request->checkValidators();
452         flush();
453     }
454     return '';
455 }
456
457 // Local Variables:
458 // mode: php
459 // tab-width: 8
460 // c-basic-offset: 4
461 // c-hanging-comment-ender-p: nil
462 // indent-tabs-mode: nil
463 // End: