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