]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/WikiBlog.php
New Edit Toolbar
[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 getDescription()
65     {
66         return sprintf(_("Show and add blogs for %s."), '[pagename]');
67     }
68
69     // Arguments:
70     // TODO:
71     //
72     // - arguments to allow selection of time range to display
73     // - arguments to display only XX blogs per page (can this 'paging'
74     //    co-exist with the wiki??  difficult)
75     // - arguments to allow comments outside this range to be
76     //    display as e.g. June 2002 archive, July 2002 archive, etc..
77     // - captions for 'show' and 'add' sections
78
79     function getDefaultArguments()
80     {
81         return array('pagename' => '[pagename]',
82             'order' => 'normal',
83             'mode' => 'show,add',
84             'noheader' => false
85         );
86     }
87
88     /**
89      * @param WikiDB $dbi
90      * @param string $argstr
91      * @param WikiRequest $request
92      * @param string $basepage
93      * @return mixed
94      */
95     function run($dbi, $argstr, &$request, $basepage)
96     {
97         $args = $this->getArgs($argstr, $request);
98
99         // Get our form args.
100         $blog = $request->getArg("edit");
101         $request->setArg("edit", false);
102
103         if ($request->isPost() and !empty($blog['save'])) {
104             $this->add($request, $blog, 'wikiblog', $basepage); // noreturn
105         }
106         //TODO: preview
107
108         // Now we display previous comments and/or provide entry box
109         // for new comments
110         $html = HTML();
111         foreach (explode(',', $args['mode']) as $show) {
112             if (!empty($seen[$show]))
113                 continue;
114             $seen[$show] = 1;
115
116             switch ($show) {
117                 case 'show':
118                     $html->pushContent($this->showAll($request, $args));
119                     break;
120                 case 'add':
121                     $html->pushContent($this->showForm($request, $args));
122                     break;
123                 default:
124                     return $this->error(sprintf("Bad mode (ā€œ%sā€)", $show));
125             }
126         }
127         return $html;
128     }
129
130     /**
131      * posted: required: pagename, content. optional: summary
132      *
133      * @param WikiRequest $request
134      * @param array $posted
135      * @param string $type
136      */
137     function add(&$request, $posted, $type = 'wikiblog')
138     {
139         // This is similar to editpage. Shouldn't we use just this for preview?
140         $parent = $posted['pagename'];
141         if (empty($parent)) {
142             $prefix = ''; // allow empty parent for default "Blog/day"
143             $parent = HOME_PAGE;
144         } elseif (($parent == 'Blog' or $parent == 'WikiBlog') and $type == 'wikiblog') { // avoid Blog/Blog/2003-01-11/14:03:02+00:00
145             $prefix = '';
146             $parent = ''; // 'Blog';
147         } elseif ($parent == 'Comment' and $type == "comment") {
148             $prefix = '';
149             $parent = ''; // 'Comment';
150         } elseif ($parent == 'Forum' and $type == "wikiforum") {
151             $prefix = '';
152             $parent = ''; // 'Forum';
153         } else {
154             $prefix = $parent . '/';
155         }
156
157         $now = time();
158         $dbi = $request->getDbh();
159         $user = $request->getUser();
160
161         /*
162          * Page^H^H^H^H Blog meta-data
163          * This method is reused for all attachable pagetypes: wikiblog, comment and wikiforum
164          *
165          * This is info that won't change for each revision.
166          * Nevertheless, it's now stored in the revision meta-data.
167          * Several reasons:
168          *  o It's more convenient to have all information required
169          *    to render a page revision in the revision meta-data.
170          *  o We can avoid a race condition, since version meta-data
171          *    updates are atomic with the version creation.
172          */
173
174         $blog_meta = array('ctime' => $now,
175             'creator' => $user->getId(),
176             'creator_id' => $user->getAuthenticatedId(),
177         );
178
179         // Version meta-data
180         $summary = trim($posted['summary']);
181         // edit: private only
182         $perm = new PagePermission();
183         $perm->perm['edit'] = $perm->perm['remove'];
184         $version_meta = array('author' => $blog_meta['creator'],
185             'author_id' => $blog_meta['creator_id'],
186             'summary' => $summary ? $summary : _("New comment."),
187             'mtime' => $now,
188             'pagetype' => $type,
189             $type => $blog_meta,
190             'perm' => $perm->perm,
191         );
192         if ($type == 'comment')
193             unset($version_meta['summary']);
194
195         // Comment body.
196         $body = trim($posted['content']);
197
198         $saved = false;
199         if ($type != 'wikiforum')
200             $pagename = $this->blogPrefix($type);
201         else {
202             $pagename = substr($summary, 0, 12);
203             if (empty($pagename)) {
204                 $saved = true;
205                 trigger_error("Empty title", E_USER_WARNING);
206             }
207         }
208         while (!$saved) {
209             // Generate the page name.  For now, we use the format:
210             //   Rootname/Blog/2003-01-11/14:03:02+00:00
211             // Rootname = $prefix, Blog = $pagename,
212             // This gives us natural chronological order when sorted
213             // alphabetically. "Rootname/" is optional.
214             // Esp. if Rootname is named Blog, it is omitted.
215
216             $time = Iso8601DateTime();
217             // Check intermediate pages. If not existing they should RedirectTo the parent page.
218             // Maybe add the BlogArchives plugin instead for the new interim subpage.
219             $redirected = $prefix . $pagename;
220             if (!$dbi->isWikiPage($redirected)) {
221                 if (!$parent) {
222                     $parent = HOME_PAGE;
223                 }
224                 require_once 'lib/loadsave.php';
225                 $pageinfo = array('pagename' => $redirected,
226                     'content' => '<<RedirectTo page="' . $parent . '">>',
227                     'pagedata' => array(),
228                     'versiondata' => array('author' => $blog_meta['creator'], 'is_minor_edit' => 1),
229                 );
230                 SavePage($request, $pageinfo, '');
231             }
232             $redirected = $prefix . $pagename . '/' . preg_replace("/T.*/", '', "$time");
233             if (!$dbi->isWikiPage($redirected)) {
234                 if (!$parent) $parent = HOME_PAGE;
235                 require_once 'lib/loadsave.php';
236                 $pageinfo = array('pagename' => $redirected,
237                     'content' => '<<RedirectTo page="' . $parent . '">>',
238                     'pagedata' => array(),
239                     'versiondata' => array('author' => $blog_meta['creator'], 'is_minor_edit' => 1),
240                 );
241                 SavePage($request, $pageinfo, '');
242             }
243
244             $p = $dbi->getPage($prefix . $pagename . '/'
245                 . str_replace("T", '/', "$time"));
246             $pr = $p->getCurrentRevision();
247
248             // Version should be zero.  If not, page already exists
249             // so increment timestamp and try again.
250             if ($pr->getVersion() > 0) {
251                 $now++;
252                 continue;
253             }
254
255             // FIXME: there's a slight, but currently unimportant
256             // race condition here.  If someone else happens to
257             // have just created a blog with the same name,
258             // we'll have locked it before we discover that the name
259             // is taken.
260             $saved = $p->save($body, 1, $version_meta);
261
262             $now++;
263         }
264
265         $dbi->touch();
266         $request->setArg("mode", "show");
267         $request->redirect($request->getURLtoSelf()); // noreturn
268
269         // FIXME: when submit a comment from preview mode,
270         // adds the comment properly but jumps to browse mode.
271         // Any way to jump back to preview mode???
272     }
273
274     /**
275      * @param WikiRequest $request
276      * @param array $args
277      * @param string $type
278      * @return XmlContent
279      */
280     function showAll(&$request, $args, $type = "wikiblog")
281     {
282         // FIXME: currently blogSearch uses WikiDB->titleSearch to
283         // get results, so results are in alphabetical order.
284         // When PageTypes fully implemented, could have smarter
285         // blogSearch implementation / naming scheme.
286
287         $dbi = $request->getDbh();
288         $basepage = $args['pagename'];
289         $blogs = $this->findBlogs($dbi, $basepage, $type);
290         $html = HTML();
291         if ($blogs) {
292             // First reorder
293             usort($blogs, array("WikiPlugin_WikiBlog",
294                 "cmp"));
295             if ($args['order'] == 'reverse')
296                 $blogs = array_reverse($blogs);
297
298             $name = $this->blogPrefix($type);
299             if (!$args['noheader'])
300                 $html->pushContent(HTML::h4(array('class' => "$type-heading"),
301                     fmt("%s on %s:", $name, WikiLink($basepage))));
302             foreach ($blogs as $rev) {
303                 if (!$rev->get($type)) {
304                     // Ack! this is an old-style blog with data ctime in page meta-data.
305                     $content = $this->transformOldFormatBlog($rev, $type);
306                 } else {
307                     $content = $rev->getTransformedContent($type);
308                 }
309                 $html->pushContent($content);
310             }
311
312         }
313         return $html;
314     }
315
316     /**
317      * Subpage for the basepage. All Blogs/Forum/Comment entries are
318      * Subpages under this pagename, to find them faster.
319      *
320      * @param string $type
321      * @return string
322      */
323     protected function blogPrefix($type = 'wikiblog')
324     {
325         if ($type == 'wikiblog')
326             $basepage = "Blog";
327         elseif ($type == 'comment')
328             $basepage = "Comment";
329         elseif ($type == 'wikiforum')
330             // $basepage = substr($summary, 0, 12);
331             $basepage = _("Message"); // FIXME: we use now the first 12 chars of the summary
332         return $basepage;
333     }
334
335     private function transformOldFormatBlog($rev, $type = 'wikiblog')
336     {
337         $page = $rev->getPage();
338         $metadata = array();
339         foreach (array('ctime', 'creator', 'creator_id') as $key)
340             $metadata[$key] = $page->get($key);
341         if (empty($metadata) and $type != 'wikiblog')
342             $metadata[$key] = $page->get('wikiblog');
343         $meta = $rev->getMetaData();
344         $meta[$type] = $metadata;
345         return new TransformedText($page, $rev->getPackedContent(), $meta, $type);
346     }
347
348     function findBlogs(&$dbi, $basepage = '', $type = 'wikiblog')
349     {
350         $prefix = (empty($basepage)
351             ? ''
352             : $basepage . '/') . $this->blogPrefix($type);
353         $pages = $dbi->titleSearch(new TextSearchQuery('"' . $prefix . '"', true, 'none'));
354
355         $blogs = array();
356         while ($page = $pages->next()) {
357             if (!string_starts_with($page->getName(), $prefix))
358                 continue;
359             $current = $page->getCurrentRevision();
360             if ($current->get('pagetype') == $type) {
361                 $blogs[] = $current;
362             }
363         }
364         return $blogs;
365     }
366
367     function cmp($a, $b)
368     {
369         return (strcmp($a->get('mtime'),
370             $b->get('mtime')));
371     }
372
373     function showForm(&$request, $args, $template = 'blogform')
374     {
375         $user = $request->getUser();
376         if (!($user->isSignedIn())) {
377             // Cannot create entry
378             return HTML::p(array('class' => 'warning'),
379                            _('You must be logged in to add blog entries.'));
380         }
381
382         // Show blog-entry form.
383         $args = array('PAGENAME' => $args['pagename'],
384             'HIDDEN_INPUTS' =>
385             HiddenInputs($request->getArgs()));
386         return new Template($template, $request, $args);
387     }
388
389     // "2004-12" => "December 2004"
390     protected function monthTitle($month)
391     {
392         if (!$month) $month = strftime("%Y-%m");
393         //list($year,$mon) = explode("-",$month);
394         return strftime("%B %Y", strtotime($month . "-01"));
395     }
396
397     // "UserName/Blog/2004-12-13/12:28:50+01:00" => array('month' => "2004-12", ...)
398     protected function _blog($rev_or_page)
399     {
400         $pagename = $rev_or_page->getName();
401         if (preg_match("/^(.*Blog)\/(\d\d\d\d-\d\d)-(\d\d)\/(.*)/", $pagename, $m))
402             list(, $prefix, $month, $day, $time) = $m;
403         return array('pagename' => $pagename,
404             // page (list pages per month) or revision (list months)?
405             //'title' => is_a($rev_or_page,'WikiDB_PageRevision') ? $rev_or_page->get('summary') : '',
406             //'monthtitle' => $this->monthTitle($month),
407             'month' => $month,
408             'day' => $day,
409             'time' => $time,
410             'prefix' => $prefix);
411     }
412
413     protected function nonDefaultArgs($args)
414     {
415         return array_diff_assoc($args, $this->getDefaultArguments());
416     }
417
418 }
419
420 // Local Variables:
421 // mode: php
422 // tab-width: 8
423 // c-basic-offset: 4
424 // c-hanging-comment-ender-p: nil
425 // indent-tabs-mode: nil
426 // End: