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