]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/WikiBlog.php
private --> protected
[SourceForge/phpwiki.git] / lib / plugin / WikiBlog.php
1 <?php
2
3 /*
4  * Copyright 2002,2003,2007,2009 $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 along
19  * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22 /**
23  * @author: MichaelVanDam, major refactor by JeffDairiki (as AddComment)
24  * @author: Changed as baseclass to AddComment and WikiForum and EditToolbar integration by ReiniUrban.
25  */
26
27 require_once 'lib/TextSearchQuery.php';
28
29 /**
30  * This plugin shows 'blogs' (comments/news) associated with a
31  * particular page and provides an input form for adding a new blog.
32  *
33  * TODO:
34  *
35  * It also works as an action-page if you create a page called 'WikiBlog'
36  * containing this plugin.  This allows adding comments to any page
37  * by linking "PageName?action=WikiBlog".  Maybe a nice feature in
38  * lib/display.php would be to automatically check if there are
39  * blogs for the given page, then provide a link to them somewhere on
40  * the page.  Or maybe this just creates a huge mess...
41  *
42  * Maybe it would be a good idea to ENABLE blogging of only certain
43  * pages by setting metadata or something...?  If a page is non-bloggable
44  * the plugin is ignored (perhaps with a warning message).
45  *
46  * Should blogs be by default filtered out of RecentChanges et al???
47  *
48  * Think of better name for this module: Blog? WikiLog? WebLog? WikiDot?
49  *
50  * Have other 'styles' for the plugin?... e.g. 'quiet'.  Display only
51  * 'This page has 23 associated comments. Click here to view / add.'
52  *
53  * For admin user, put checkboxes beside comments to allow for bulk removal.
54  *
55  * Permissions for who can add blogs?  Display entry box only if
56  * user meets these requirements...?
57  *
58  * Code cleanup: break into functions, use templates (or at least remove CSS)
59  */
60
61 class WikiPlugin_WikiBlog
62     extends WikiPlugin
63 {
64     function getName()
65     {
66         return _("WikiBlog");
67     }
68
69     function getDescription()
70     {
71         return sprintf(_("Show and add blogs for %s."), '[pagename]');
72     }
73
74     // Arguments:
75     // TODO:
76     //
77     // - arguments to allow selection of time range to display
78     // - arguments to display only XX blogs per page (can this 'paging'
79     //    co-exist with the wiki??  difficult)
80     // - arguments to allow comments outside this range to be
81     //    display as e.g. June 2002 archive, July 2002 archive, etc..
82     // - captions for 'show' and 'add' sections
83
84     function getDefaultArguments()
85     {
86         return array('pagename' => '[pagename]',
87             'order' => 'normal',
88             'mode' => 'show,add',
89             'noheader' => false
90         );
91     }
92
93     function run($dbi, $argstr, &$request, $basepage)
94     {
95         $args = $this->getArgs($argstr, $request);
96         // allow empty pagenames for ADMIN_USER style blogs: "Blog/day"
97         //if (!$args['pagename'])
98         //    return $this->error(_("No pagename specified"));
99
100         // Get our form args.
101         $blog = $request->getArg("edit");
102         $request->setArg("edit", false);
103
104         if ($request->isPost() and !empty($blog['save'])) {
105             $this->add($request, $blog, 'wikiblog', $basepage); // noreturn
106         }
107         //TODO: preview
108
109         // Now we display previous comments and/or provide entry box
110         // for new comments
111         $html = HTML();
112         foreach (explode(',', $args['mode']) as $show) {
113             if (!empty($seen[$show]))
114                 continue;
115             $seen[$show] = 1;
116
117             switch ($show) {
118                 case 'show':
119                     $html->pushContent($this->showAll($request, $args));
120                     break;
121                 case 'add':
122                     $html->pushContent($this->showForm($request, $args));
123                     break;
124                 default:
125                     return $this->error(sprintf("Bad mode (ā€œ%sā€)", $show));
126             }
127         }
128         return $html;
129     }
130
131     /**
132      * posted: required: pagename, content. optional: summary
133      */
134     function add(&$request, $posted, $type = 'wikiblog')
135     {
136         // This is similar to editpage. Shouldn't we use just this for preview?
137         $parent = $posted['pagename'];
138         if (empty($parent)) {
139             $prefix = ""; // allow empty parent for default "Blog/day"
140             $parent = HOME_PAGE;
141         } elseif (($parent == 'Blog' or $parent == 'WikiBlog') and $type == 'wikiblog') { // avoid Blog/Blog/2003-01-11/14:03:02+00:00
142             $prefix = "";
143             $parent = ''; // 'Blog';
144         } elseif ($parent == 'Comment' and $type == "comment") {
145             $prefix = "";
146             $parent = ''; // 'Comment';
147         } elseif ($parent == 'Forum' and $type == "wikiforum") {
148             $prefix = "";
149             $parent = ''; // 'Forum';
150         } else {
151             $prefix = $parent . SUBPAGE_SEPARATOR;
152         }
153         //$request->finish(fmt("No pagename specified for %s",$type));
154
155         $now = time();
156         $dbi = $request->getDbh();
157         $user = $request->getUser();
158
159         /*
160          * Page^H^H^H^H Blog meta-data
161          * This method is reused for all attachable pagetypes: wikiblog, comment and wikiforum
162          *
163          * This is info that won't change for each revision.
164          * Nevertheless, it's now stored in the revision meta-data.
165          * Several reasons:
166          *  o It's more convenient to have all information required
167          *    to render a page revision in the revision meta-data.
168          *  o We can avoid a race condition, since version meta-data
169          *    updates are atomic with the version creation.
170          */
171
172         $blog_meta = array('ctime' => $now,
173             'creator' => $user->getId(),
174             'creator_id' => $user->getAuthenticatedId(),
175         );
176
177         // Version meta-data
178         $summary = trim($posted['summary']);
179         // edit: private only
180         $perm = new PagePermission();
181         $perm->perm['edit'] = $perm->perm['remove'];
182         $version_meta = array('author' => $blog_meta['creator'],
183             'author_id' => $blog_meta['creator_id'],
184             'markup' => 2.0, // assume new markup
185             'summary' => $summary ? $summary : _("New comment."),
186             'mtime' => $now,
187             'pagetype' => $type,
188             $type => $blog_meta,
189             'perm' => $perm->perm,
190         );
191         if ($type == 'comment')
192             unset($version_meta['summary']);
193
194         // Comment body.
195         $body = trim($posted['content']);
196
197         $saved = false;
198         if ($type != 'wikiforum')
199             $pagename = $this->blogPrefix($type);
200         else {
201             $pagename = substr($summary, 0, 12);
202             if (empty($pagename)) {
203                 $saved = true;
204                 trigger_error("Empty title", E_USER_WARNING);
205             }
206         }
207         while (!$saved) {
208             // Generate the page name.  For now, we use the format:
209             //   Rootname/Blog/2003-01-11/14:03:02+00:00
210             // Rootname = $prefix, Blog = $pagename,
211             // This gives us natural chronological order when sorted
212             // alphabetically. "Rootname/" is optional.
213             // Esp. if Rootname is named Blog, it is omitted.
214
215             $time = Iso8601DateTime();
216             // Check intermediate pages. If not existing they should RedirectTo the parent page.
217             // Maybe add the BlogArchives plugin instead for the new interim subpage.
218             $redirected = $prefix . $pagename;
219             if (!$dbi->isWikiPage($redirected)) {
220                 if (!$parent) $parent = HOME_PAGE;
221                 require_once 'lib/loadsave.php';
222                 $pageinfo = array('pagename' => $redirected,
223                     'content' => '<<RedirectTo page="' . $parent . '">>',
224                     'pagedata' => array(),
225                     'versiondata' => array('author' => $blog_meta['creator'], 'is_minor_edit' => 1),
226                 );
227                 SavePage($request, $pageinfo, '', '');
228             }
229             $redirected = $prefix . $pagename . SUBPAGE_SEPARATOR . preg_replace("/T.*/", "", "$time");
230             if (!$dbi->isWikiPage($redirected)) {
231                 if (!$parent) $parent = HOME_PAGE;
232                 require_once 'lib/loadsave.php';
233                 $pageinfo = array('pagename' => $redirected,
234                     'content' => '<<RedirectTo page="' . $parent . '">>',
235                     'pagedata' => array(),
236                     'versiondata' => array('author' => $blog_meta['creator'], 'is_minor_edit' => 1),
237                 );
238                 SavePage($request, $pageinfo, '', '');
239             }
240
241             $p = $dbi->getPage($prefix . $pagename . SUBPAGE_SEPARATOR
242                 . str_replace("T", SUBPAGE_SEPARATOR, "$time"));
243             $pr = $p->getCurrentRevision();
244
245             // Version should be zero.  If not, page already exists
246             // so increment timestamp and try again.
247             if ($pr->getVersion() > 0) {
248                 $now++;
249                 continue;
250             }
251
252             // FIXME: there's a slight, but currently unimportant
253             // race condition here.  If someone else happens to
254             // have just created a blog with the same name,
255             // we'll have locked it before we discover that the name
256             // is taken.
257             $saved = $p->save($body, 1, $version_meta);
258
259             $now++;
260         }
261
262         $dbi->touch();
263         $request->setArg("mode", "show");
264         $request->redirect($request->getURLtoSelf()); // noreturn
265
266         // FIXME: when submit a comment from preview mode,
267         // adds the comment properly but jumps to browse mode.
268         // Any way to jump back to preview mode???
269     }
270
271     function showAll(&$request, $args, $type = "wikiblog")
272     {
273         // FIXME: currently blogSearch uses WikiDB->titleSearch to
274         // get results, so results are in alphabetical order.
275         // When PageTypes fully implemented, could have smarter
276         // blogSearch implementation / naming scheme.
277
278         $dbi = $request->getDbh();
279         $basepage = $args['pagename'];
280         $blogs = $this->findBlogs($dbi, $basepage, $type);
281         $html = HTML();
282         if ($blogs) {
283             // First reorder
284             usort($blogs, array("WikiPlugin_WikiBlog",
285                 "cmp"));
286             if ($args['order'] == 'reverse')
287                 $blogs = array_reverse($blogs);
288
289             $name = $this->blogPrefix($type);
290             if (!$args['noheader'])
291                 $html->pushContent(HTML::h4(array('class' => "$type-heading"),
292                     fmt("%s on %s:", $name, WikiLink($basepage))));
293             foreach ($blogs as $rev) {
294                 if (!$rev->get($type)) {
295                     // Ack! this is an old-style blog with data ctime in page meta-data.
296                     $content = $this->transformOldFormatBlog($rev, $type);
297                 } else {
298                     $content = $rev->getTransformedContent($type);
299                 }
300                 $html->pushContent($content);
301             }
302
303         }
304         return $html;
305     }
306
307     // Subpage for the basepage. All Blogs/Forum/Comment entries are
308     // Subpages under this pagename, to find them faster.
309     protected function blogPrefix($type = 'wikiblog')
310     {
311         if ($type == 'wikiblog')
312             $basepage = "Blog";
313         elseif ($type == 'comment')
314             $basepage = "Comment"; elseif ($type == 'wikiforum')
315             $basepage = substr($summary, 0, 12);
316         //$basepage = _("Message"); // FIXME: we use now the first 12 chars of the summary
317         return $basepage;
318     }
319
320     private function transformOldFormatBlog($rev, $type = 'wikiblog')
321     {
322         $page = $rev->getPage();
323         $metadata = array();
324         foreach (array('ctime', 'creator', 'creator_id') as $key)
325             $metadata[$key] = $page->get($key);
326         if (empty($metadata) and $type != 'wikiblog')
327             $metadata[$key] = $page->get('wikiblog');
328         $meta = $rev->getMetaData();
329         $meta[$type] = $metadata;
330         return new TransformedText($page, $rev->getPackedContent(), $meta, $type);
331     }
332
333     function findBlogs(&$dbi, $basepage = '', $type = 'wikiblog')
334     {
335         $prefix = (empty($basepage)
336             ? ""
337             : $basepage . SUBPAGE_SEPARATOR) . $this->blogPrefix($type);
338         $pages = $dbi->titleSearch(new TextSearchQuery('"' . $prefix . '"', true, 'none'));
339
340         $blogs = array();
341         while ($page = $pages->next()) {
342             if (!string_starts_with($page->getName(), $prefix))
343                 continue;
344             $current = $page->getCurrentRevision();
345             if ($current->get('pagetype') == $type) {
346                 $blogs[] = $current;
347             }
348         }
349         return $blogs;
350     }
351
352     function cmp($a, $b)
353     {
354         return (strcmp($a->get('mtime'),
355             $b->get('mtime')));
356     }
357
358     function showForm(&$request, $args, $template = 'blogform')
359     {
360         // Show blog-entry form.
361         $args = array('PAGENAME' => $args['pagename'],
362             'HIDDEN_INPUTS' =>
363             HiddenInputs($request->getArgs()));
364         if (ENABLE_EDIT_TOOLBAR and !ENABLE_WYSIWYG and ($template != 'addcomment')) {
365             include_once 'lib/EditToolbar.php';
366             $toolbar = new EditToolbar();
367             $args = array_merge($args, $toolbar->getTokens());
368         }
369         return new Template($template, $request, $args);
370     }
371
372     // "2004-12" => "December 2004"
373     protected function monthTitle($month)
374     {
375         if (!$month) $month = strftime("%Y-%m");
376         //list($year,$mon) = explode("-",$month);
377         return strftime("%B %Y", strtotime($month . "-01"));
378     }
379
380     // "UserName/Blog/2004-12-13/12:28:50+01:00" => array('month' => "2004-12", ...)
381     protected function _blog($rev_or_page)
382     {
383         $pagename = $rev_or_page->getName();
384         if (preg_match("/^(.*Blog)\/(\d\d\d\d-\d\d)-(\d\d)\/(.*)/", $pagename, $m))
385             list(, $prefix, $month, $day, $time) = $m;
386         return array('pagename' => $pagename,
387             // page (list pages per month) or revision (list months)?
388             //'title' => isa($rev_or_page,'WikiDB_PageRevision') ? $rev_or_page->get('summary') : '',
389             //'monthtitle' => $this->monthTitle($month),
390             'month' => $month,
391             'day' => $day,
392             'time' => $time,
393             'prefix' => $prefix);
394     }
395
396     protected function nonDefaultArgs($args)
397     {
398         return array_diff_assoc($args, $this->getDefaultArguments());
399     }
400
401 }
402
403 // Local Variables:
404 // mode: php
405 // tab-width: 8
406 // c-basic-offset: 4
407 // c-hanging-comment-ender-p: nil
408 // indent-tabs-mode: nil
409 // End: