]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/WikiBlog.php
isa --> is_a
[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         // allow empty pagenames for ADMIN_USER style blogs: "Blog/day"
99         //if (!$args['pagename'])
100         //    return $this->error(_("No pagename specified"));
101
102         // Get our form args.
103         $blog = $request->getArg("edit");
104         $request->setArg("edit", false);
105
106         if ($request->isPost() and !empty($blog['save'])) {
107             $this->add($request, $blog, 'wikiblog', $basepage); // noreturn
108         }
109         //TODO: preview
110
111         // Now we display previous comments and/or provide entry box
112         // for new comments
113         $html = HTML();
114         foreach (explode(',', $args['mode']) as $show) {
115             if (!empty($seen[$show]))
116                 continue;
117             $seen[$show] = 1;
118
119             switch ($show) {
120                 case 'show':
121                     $html->pushContent($this->showAll($request, $args));
122                     break;
123                 case 'add':
124                     $html->pushContent($this->showForm($request, $args));
125                     break;
126                 default:
127                     return $this->error(sprintf("Bad mode (ā€œ%sā€)", $show));
128             }
129         }
130         return $html;
131     }
132
133     /**
134      * posted: required: pagename, content. optional: summary
135      */
136     function add(&$request, $posted, $type = 'wikiblog')
137     {
138         // This is similar to editpage. Shouldn't we use just this for preview?
139         $parent = $posted['pagename'];
140         if (empty($parent)) {
141             $prefix = ""; // allow empty parent for default "Blog/day"
142             $parent = HOME_PAGE;
143         } elseif (($parent == 'Blog' or $parent == 'WikiBlog') and $type == 'wikiblog') { // avoid Blog/Blog/2003-01-11/14:03:02+00:00
144             $prefix = "";
145             $parent = ''; // 'Blog';
146         } elseif ($parent == 'Comment' and $type == "comment") {
147             $prefix = "";
148             $parent = ''; // 'Comment';
149         } elseif ($parent == 'Forum' and $type == "wikiforum") {
150             $prefix = "";
151             $parent = ''; // 'Forum';
152         } else {
153             $prefix = $parent . SUBPAGE_SEPARATOR;
154         }
155         //$request->finish(fmt("No pagename specified for %s",$type));
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) $parent = HOME_PAGE;
222                 require_once 'lib/loadsave.php';
223                 $pageinfo = array('pagename' => $redirected,
224                     'content' => '<<RedirectTo page="' . $parent . '">>',
225                     'pagedata' => array(),
226                     'versiondata' => array('author' => $blog_meta['creator'], 'is_minor_edit' => 1),
227                 );
228                 SavePage($request, $pageinfo, '', '');
229             }
230             $redirected = $prefix . $pagename . SUBPAGE_SEPARATOR . preg_replace("/T.*/", "", "$time");
231             if (!$dbi->isWikiPage($redirected)) {
232                 if (!$parent) $parent = HOME_PAGE;
233                 require_once 'lib/loadsave.php';
234                 $pageinfo = array('pagename' => $redirected,
235                     'content' => '<<RedirectTo page="' . $parent . '">>',
236                     'pagedata' => array(),
237                     'versiondata' => array('author' => $blog_meta['creator'], 'is_minor_edit' => 1),
238                 );
239                 SavePage($request, $pageinfo, '', '');
240             }
241
242             $p = $dbi->getPage($prefix . $pagename . SUBPAGE_SEPARATOR
243                 . str_replace("T", SUBPAGE_SEPARATOR, "$time"));
244             $pr = $p->getCurrentRevision();
245
246             // Version should be zero.  If not, page already exists
247             // so increment timestamp and try again.
248             if ($pr->getVersion() > 0) {
249                 $now++;
250                 continue;
251             }
252
253             // FIXME: there's a slight, but currently unimportant
254             // race condition here.  If someone else happens to
255             // have just created a blog with the same name,
256             // we'll have locked it before we discover that the name
257             // is taken.
258             $saved = $p->save($body, 1, $version_meta);
259
260             $now++;
261         }
262
263         $dbi->touch();
264         $request->setArg("mode", "show");
265         $request->redirect($request->getURLtoSelf()); // noreturn
266
267         // FIXME: when submit a comment from preview mode,
268         // adds the comment properly but jumps to browse mode.
269         // Any way to jump back to preview mode???
270     }
271
272     function showAll(&$request, $args, $type = "wikiblog")
273     {
274         // FIXME: currently blogSearch uses WikiDB->titleSearch to
275         // get results, so results are in alphabetical order.
276         // When PageTypes fully implemented, could have smarter
277         // blogSearch implementation / naming scheme.
278
279         $dbi = $request->getDbh();
280         $basepage = $args['pagename'];
281         $blogs = $this->findBlogs($dbi, $basepage, $type);
282         $html = HTML();
283         if ($blogs) {
284             // First reorder
285             usort($blogs, array("WikiPlugin_WikiBlog",
286                 "cmp"));
287             if ($args['order'] == 'reverse')
288                 $blogs = array_reverse($blogs);
289
290             $name = $this->blogPrefix($type);
291             if (!$args['noheader'])
292                 $html->pushContent(HTML::h4(array('class' => "$type-heading"),
293                     fmt("%s on %s:", $name, WikiLink($basepage))));
294             foreach ($blogs as $rev) {
295                 if (!$rev->get($type)) {
296                     // Ack! this is an old-style blog with data ctime in page meta-data.
297                     $content = $this->transformOldFormatBlog($rev, $type);
298                 } else {
299                     $content = $rev->getTransformedContent($type);
300                 }
301                 $html->pushContent($content);
302             }
303
304         }
305         return $html;
306     }
307
308     // Subpage for the basepage. All Blogs/Forum/Comment entries are
309     // Subpages under this pagename, to find them faster.
310     protected function blogPrefix($type = 'wikiblog')
311     {
312         if ($type == 'wikiblog')
313             $basepage = "Blog";
314         elseif ($type == 'comment')
315             $basepage = "Comment";
316         elseif ($type == 'wikiforum')
317             // $basepage = substr($summary, 0, 12);
318             $basepage = _("Message"); // FIXME: we use now the first 12 chars of the summary
319         return $basepage;
320     }
321
322     private function transformOldFormatBlog($rev, $type = 'wikiblog')
323     {
324         $page = $rev->getPage();
325         $metadata = array();
326         foreach (array('ctime', 'creator', 'creator_id') as $key)
327             $metadata[$key] = $page->get($key);
328         if (empty($metadata) and $type != 'wikiblog')
329             $metadata[$key] = $page->get('wikiblog');
330         $meta = $rev->getMetaData();
331         $meta[$type] = $metadata;
332         return new TransformedText($page, $rev->getPackedContent(), $meta, $type);
333     }
334
335     function findBlogs(&$dbi, $basepage = '', $type = 'wikiblog')
336     {
337         $prefix = (empty($basepage)
338             ? ""
339             : $basepage . SUBPAGE_SEPARATOR) . $this->blogPrefix($type);
340         $pages = $dbi->titleSearch(new TextSearchQuery('"' . $prefix . '"', true, 'none'));
341
342         $blogs = array();
343         while ($page = $pages->next()) {
344             if (!string_starts_with($page->getName(), $prefix))
345                 continue;
346             $current = $page->getCurrentRevision();
347             if ($current->get('pagetype') == $type) {
348                 $blogs[] = $current;
349             }
350         }
351         return $blogs;
352     }
353
354     function cmp($a, $b)
355     {
356         return (strcmp($a->get('mtime'),
357             $b->get('mtime')));
358     }
359
360     function showForm(&$request, $args, $template = 'blogform')
361     {
362         // Show blog-entry form.
363         $args = array('PAGENAME' => $args['pagename'],
364             'HIDDEN_INPUTS' =>
365             HiddenInputs($request->getArgs()));
366         if (ENABLE_EDIT_TOOLBAR and !ENABLE_WYSIWYG and ($template != 'addcomment')) {
367             include_once 'lib/EditToolbar.php';
368             $toolbar = new EditToolbar();
369             $args = array_merge($args, $toolbar->getTokens());
370         }
371         return new Template($template, $request, $args);
372     }
373
374     // "2004-12" => "December 2004"
375     protected function monthTitle($month)
376     {
377         if (!$month) $month = strftime("%Y-%m");
378         //list($year,$mon) = explode("-",$month);
379         return strftime("%B %Y", strtotime($month . "-01"));
380     }
381
382     // "UserName/Blog/2004-12-13/12:28:50+01:00" => array('month' => "2004-12", ...)
383     protected function _blog($rev_or_page)
384     {
385         $pagename = $rev_or_page->getName();
386         if (preg_match("/^(.*Blog)\/(\d\d\d\d-\d\d)-(\d\d)\/(.*)/", $pagename, $m))
387             list(, $prefix, $month, $day, $time) = $m;
388         return array('pagename' => $pagename,
389             // page (list pages per month) or revision (list months)?
390             //'title' => is_a($rev_or_page,'WikiDB_PageRevision') ? $rev_or_page->get('summary') : '',
391             //'monthtitle' => $this->monthTitle($month),
392             'month' => $month,
393             'day' => $day,
394             'time' => $time,
395             'prefix' => $prefix);
396     }
397
398     protected function nonDefaultArgs($args)
399     {
400         return array_diff_assoc($args, $this->getDefaultArguments());
401     }
402
403 }
404
405 // Local Variables:
406 // mode: php
407 // tab-width: 8
408 // c-basic-offset: 4
409 // c-hanging-comment-ender-p: nil
410 // indent-tabs-mode: nil
411 // End: