]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/RateIt.php
Reformat code
[SourceForge/phpwiki.git] / lib / plugin / RateIt.php
1 <?php
2
3 /*
4  * Copyright 2004,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 /**
24  * RateIt: A recommender system, based on MovieLens and "suggest".
25  * Store user ratings per pagename. The wikilens theme displays a navbar image bar
26  * with some nice javascript magic and this plugin shows various recommendations.
27  *
28  * There should be two methods to store ratings:
29  * In a SQL database as in wikilens http://dickens.cs.umn.edu/dfrankow/wikilens
30  *
31  * The most important fact: A page has more than one rating. There can
32  * be (and will be!) many ratings per page (ratee): different raters
33  * (users), in different dimensions. Are those stored per page
34  * (ratee)? Then what if I wish to access the ratings per rater
35  * (user)?
36  * wikilens plans several user-centered applications like:
37  * a) show my ratings
38  * b) show my buddies' ratings
39  * c) show how my ratings are like my buddies'
40  * d) show where I agree/disagree with my buddy
41  * e) show what this group of people agree/disagree on
42  *
43  * If the ratings are stored in a real DB in a table, we can index the
44  * ratings by rater and ratee, and be confident in
45  * performance. Currently MovieLens has 80,000 users, 7,000 items,
46  * 10,000,000 ratings. This is an average of 1400 ratings/page if each
47  * page were rated equally. However, they're not: the most popular
48  * things have tens of thousands of ratings (e.g., "Pulp Fiction" has
49  * 42,000 ratings). If ratings are stored per page, you would have to
50  * save/read huge page metadata every time someone submits a
51  * rating. Finally, the movie domain has an unusually small number of
52  * items-- I'd expect a lot more in music, for example.
53  *
54  * For a simple rating system one can also store the rating in the page
55  * metadata (default).
56  *
57  * Recommender Engines:
58  * Recommendation/Prediction is a special field of "Data Mining"
59  * For a list of (also free) software see
60  *  http://www.the-data-mine.com/bin/view/Software/WebIndex
61  * - movielens: (Java Server) will be gpl'd in summer 2004 (weighted)
62  * - suggest: is free for non-commercial use, available as compiled library
63  *     (non-weighted)
64  * - Autoclass: simple public domain C library
65  * - MLC++: C++ library http://www.sgi.com/tech/mlc/
66  *
67  * Usage:    <<RateIt >>          just the widget without text
68  *   Note: The wikilens theme or any derivate must be enabled, to enable this plugin!
69  *           <<RateIt show=top >> text plus widget below
70  *           <<RateIt show=ratings >> to show my ratings
71  *   TODO:   <<RateIt show=buddies >> to show my buddies
72  *           <<RateIt show=ratings dimension=1 >>
73  *   TODO:   <<RateIt show=text >> just text, no widget, for dumps
74  *
75  * @author:  Dan Frankowski (wikilens author), Reini Urban (as plugin)
76  *
77  * TODO:
78  * - finish mysuggest.c (external engine with data from mysql)
79  */
80
81 require_once 'lib/WikiPlugin.php';
82 require_once 'lib/wikilens/RatingsDb.php';
83
84 class WikiPlugin_RateIt
85     extends WikiPlugin
86 {
87     function getName()
88     {
89         return _("RateIt");
90     }
91
92     function getDescription()
93     {
94         return _("Rating system. Store user ratings per page");
95     }
96
97     function RatingWidgetJavascript()
98     {
99         global $WikiTheme;
100         if (!empty($this->imgPrefix))
101             $imgPrefix = $this->imgPrefix;
102         elseif (defined("RATEIT_IMGPREFIX"))
103             $imgPrefix = RATEIT_IMGPREFIX; else $imgPrefix = '';
104         if ($imgPrefix and !$WikiTheme->_findData("images/RateIt" . $imgPrefix . "Nk0.png", 1))
105             $imgPrefix = '';
106         $img = substr($WikiTheme->_findData("images/RateIt" . $imgPrefix . "Nk0.png"), 0, -7);
107         $urlprefix = WikiURL("", 0, 1); // TODO: check actions USE_PATH_INFO=false
108         $js_globals = "var rateit_imgsrc = '" . $img . "';
109 var rateit_action = '" . urlencode("RateIt") . "';
110 ";
111         $WikiTheme->addMoreHeaders
112         (JavaScript('',
113             array('src' => $WikiTheme->_findData('themes/wikilens/wikilens.js'))));
114         return JavaScript($js_globals);
115     }
116
117     function actionImgPath()
118     {
119         global $WikiTheme;
120         return $WikiTheme->_findFile("images/RateItAction.png", 1);
121     }
122
123     /**
124      * Take a string and quote it sufficiently to be passed as a Javascript
125      * string between ''s
126      */
127     function _javascript_quote_string($s)
128     {
129         return str_replace("'", "\'", $s);
130     }
131
132     function getDefaultArguments()
133     {
134         return array('pagename' => '[pagename]',
135             'version' => false,
136             'id' => 'rateit',
137             'imgPrefix' => '', // '' or BStar or Star
138             'dimension' => false,
139             'small' => false,
140             'show' => false,
141             'mode' => false,
142         );
143     }
144
145     function head()
146     { // early side-effects (before body)
147         global $WikiTheme;
148         static $_already;
149         if (!empty($_already)) return;
150         $_already = 1;
151         $WikiTheme->addMoreHeaders(JavaScript(
152             "var prediction = new Array; var rating = new Array;
153 var avg = new Array; var numusers = new Array;
154 var msg_rating_votes = '" . _("Rating: %.1f (%d votes)") . "';
155 var msg_curr_rating = '" . _("Your current rating: ") . "';
156 var msg_curr_prediction = '" . _("Your current prediction: ") . "';
157 var msg_chg_rating = '" . _("Change your rating from ") . "';
158 var msg_to = '" . _(" to ") . "';
159 var msg_add_rating = '" . _("Add your rating: ") . "';
160 var msg_thanks = '" . _("Thanks!") . "';
161 var msg_rating_deleted = '" . _("Rating deleted!") . "';
162 "));
163         $WikiTheme->addMoreHeaders($this->RatingWidgetJavascript());
164     }
165
166     function displayActionImg($mode)
167     {
168         global $WikiTheme, $request;
169         if (!empty($request->_is_buffering_output))
170             ob_end_clean(); // discard any previous output
171         // delete the cache
172         $page = $request->getPage();
173         //$page->set('_cached_html', false);
174         $request->cacheControl('MUST-REVALIDATE');
175         $dbi = $request->getDbh();
176         $dbi->touch();
177         //fake validators without args
178         $request->appendValidators(array('wikiname' => WIKI_NAME,
179             'args' => wikihash('')));
180         $request->discardOutput();
181         $actionImg = $WikiTheme->_path . $this->actionImgPath();
182         if (file_exists($actionImg)) {
183             header('Content-type: image/png');
184             readfile($actionImg);
185         } else {
186             header('Content-type: image/png');
187             echo base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAIAAAACAQMAAABIeJ9nAAAAA1BMVEX///'
188                 . '+nxBvIAAAAAXRSTlMAQObYZgAAABNJREFUeF4NwAEBAAAAgJD+r5YGAAQAAXHhfPAAAAAASUVORK5CYII=');
189         }
190         exit;
191     }
192
193     // Only for signed users done in template only yet.
194     function run($dbi, $argstr, &$request, $basepage)
195     {
196         global $WikiTheme;
197         //$this->_request = & $request;
198         //$this->_dbi = & $dbi;
199         $user = $request->getUser();
200         //FIXME: fails on test with DumpHtml:RateIt
201         if (!is_object($user)) {
202             return HTML::raw('');
203         }
204         $this->userid = $user->getId();
205         if (!$this->userid) {
206             return HTML::raw('');
207         }
208         $args = $this->getArgs($argstr, $request);
209         $this->dimension = $args['dimension'];
210         $this->imgPrefix = $args['imgPrefix'];
211         if ($this->dimension == '') {
212             $this->dimension = 0;
213             $args['dimension'] = 0;
214         }
215         if ($args['pagename']) {
216             // Expand relative page names.
217             $page = new WikiPageName($args['pagename'], $basepage);
218             $args['pagename'] = $page->name;
219         }
220         if (empty($args['pagename'])) {
221             return $this->error(_("no page specified"));
222         }
223         $this->pagename = $args['pagename'];
224
225         $rdbi = RatingsDb::getTheRatingsDb();
226         $this->_rdbi =& $rdbi;
227
228         if ($args['mode'] === 'add') {
229             //if (!$user->isSignedIn()) return $this->error(_("You must sign in"));
230             $this->rating = $request->getArg('rating');
231             $rdbi->addRating($this->rating, $this->userid, $this->pagename, $this->dimension);
232             $this->displayActionImg('add');
233
234         } elseif ($args['mode'] === 'delete') {
235             //if (!$user->isSignedIn()) return $this->error(_("You must sign in"));
236             $rdbi->deleteRating($this->userid, $this->pagename, $this->dimension);
237             unset($this->rating);
238             $this->displayActionImg('delete');
239         } elseif (!$args['show']) {
240             return $this->RatingWidgetHtml($args['pagename'], $args['version'], $args['imgPrefix'],
241                 $args['dimension'], $args['small']);
242         } else {
243             //if (!$user->isSignedIn()) return $this->error(_("You must sign in"));
244             //extract($args);
245             $this->rating = $rdbi->getRating($this->userid, $this->pagename, $this->dimension);
246             $this->avg = $rdbi->getAvg($this->pagename, $this->dimension);
247             $this->numusers = $rdbi->getNumUsers($this->pagename, $this->dimension);
248             // Update this text on rateit in javascript. needed: NumUsers, Avg
249             $html = HTML::div
250             (
251                 HTML::span(array('class' => 'rateit'),
252                     sprintf(_("Rating: %.1f (%d votes)"),
253                         $this->avg, $this->numusers)));
254             if ($args['show'] == 'top') {
255                 if (ENABLE_PAGE_PUBLIC) {
256                     $page = $dbi->getPage($this->pagename);
257                     if ($page->get('public'))
258                         $html->setAttr('class', "public");
259                 }
260                 $html->setAttr('id', "rateit-widget-top");
261                 $html->pushContent(HTML::br(),
262                     $this->RatingWidgetHtml($args['pagename'], $args['version'],
263                         $args['imgPrefix'],
264                         $args['dimension'], $args['small']));
265             } elseif ($args['show'] == 'text') {
266                 if (!$WikiTheme->DUMP_MODE)
267                     $html->pushContent(HTML::br(),
268                         sprintf(_("Your rating was %.1f"),
269                             $this->rating));
270             } elseif ($this->rating) {
271                 $html->pushContent(HTML::br(),
272                     sprintf(_("Your rating was %.1f"),
273                         $this->rating));
274             } else {
275                 $this->pred = $rdbi->getPrediction($this->userid, $this->pagename, $this->dimension);
276                 if (is_string($this->pred))
277                     $html->pushContent(HTML::br(),
278                         sprintf(_("Prediction: %s"),
279                             $this->pred));
280                 elseif ($this->pred)
281                     $html->pushContent(HTML::br(),
282                         sprintf(_("Prediction: %.1f"),
283                             $this->pred));
284             }
285             //$html->pushContent(HTML::p());
286             //$html->pushContent(HTML::em("(Experimental: This might be entirely bogus data)"));
287             return $html;
288         }
289     }
290
291     // box is used to display a fixed-width, narrow version with common header
292     function box($args = false, $request = false, $basepage = false)
293     {
294         if (!$request) $request =& $GLOBALS['request'];
295         if (!$request->_user->isSignedIn()) return;
296         if (!isset($args)) $args = array();
297         $args['small'] = 1;
298         $argstr = '';
299         foreach ($args as $key => $value)
300             $argstr .= $key . "=" . $value;
301         $widget = $this->run($request->_dbi, $argstr, $request, $basepage);
302
303         return $this->makeBox(WikiLink(_("RateIt"), '', _("Rate It")),
304             $widget);
305     }
306
307     /**
308      * HTML widget display
309      *
310      * This needs to be put in the <body> section of the page.
311      *
312      * @param pagename    Name of the page to rate
313      * @param version     Version of the page to rate (may be "" for current)
314      * @param imgPrefix   Prefix of the names of the images that display the rating
315      *                    You can have two widgets for the same page displayed at
316      *                    once iff the imgPrefix-s are different.
317      * @param dimension   Id of the dimension to rate
318      * @param small       Makes a smaller ratings widget if non-false
319      *
320      * Limitations: Currently this can only print the current users ratings.
321      *              And only the widget, but no value (for buddies) also.
322      */
323     function RatingWidgetHtml($pagename, $version, $imgPrefix, $dimension, $small = false)
324     {
325         global $WikiTheme, $request;
326
327         $dbi =& $request->_dbi;
328         $version = $dbi->_backend->get_latest_version($pagename);
329         $pageid = sprintf("%u", crc32($pagename)); // MangleXmlIdentifier($pagename)
330         $imgId = 'RateIt' . $pageid;
331         $actionImgName = 'RateIt' . $pageid . 'Action';
332
333         //$rdbi =& $this->_rdbi;
334         $rdbi = RatingsDb::getTheRatingsDb();
335
336         // check if the imgPrefix icons exist.
337         if (!$WikiTheme->_findData("images/RateIt" . $imgPrefix . "Nk0.png", true))
338             $imgPrefix = '';
339
340         // Protect against \'s, though not \r or \n
341         $reImgPrefix = $this->_javascript_quote_string($imgPrefix);
342         $reImgId = $this->_javascript_quote_string($imgId);
343         $reActionImgName = $this->_javascript_quote_string($actionImgName);
344         $rePagename = $this->_javascript_quote_string($pagename);
345         //$dimension = $args['pagename'] . "rat";
346
347         $html = HTML::span(array("class" => "rateit-widget", "id" => $imgId));
348         for ($i = 0; $i < 2; $i++) {
349             $ok[$i] = $WikiTheme->_findData("images/RateIt" . $imgPrefix . "Ok" . $i . ".png"); // empty
350             $nk[$i] = $WikiTheme->_findData("images/RateIt" . $imgPrefix . "Nk" . $i . ".png"); // rated
351             $rk[$i] = $WikiTheme->_findData("images/RateIt" . $imgPrefix . "Rk" . $i . ".png"); // pred
352         }
353
354         if (empty($this->userid)) {
355             $user = $request->getUser();
356             $this->userid = $user->getId();
357         }
358         if (empty($this->rating)) {
359             $this->rating = $rdbi->getRating($this->userid, $pagename, $dimension);
360             if (!$this->rating and empty($this->pred)) {
361                 $this->pred = $rdbi->getPrediction($this->userid, $pagename, $dimension);
362             }
363         }
364
365         for ($i = 1; $i <= 10; $i++) {
366             $j = $i / 2;
367             $a1 = HTML::a(array('href' => "javascript:clickRating('$reImgPrefix','$rePagename','$version',"
368                 . "'$reImgId','$dimension',$j)"));
369             $img_attr = array();
370             $img_attr['src'] = $nk[$i % 2];
371             if ($this->rating) {
372                 $img_attr['src'] = $ok[$i % 2];
373                 $img_attr['onmouseover'] = "displayRating('$reImgId','$reImgPrefix',$j,0,1)";
374                 $img_attr['onmouseout'] = "displayRating('$reImgId','$reImgPrefix',$this->rating,0,1)";
375             } else if (!$this->rating and $this->pred) {
376                 $img_attr['src'] = $rk[$i % 2];
377                 $img_attr['onmouseover'] = "displayRating('$reImgId','$reImgPrefix',$j,1,1)";
378                 $img_attr['onmouseout'] = "displayRating('$reImgId','$reImgPrefix',$this->pred,1,1)";
379             } else {
380                 $img_attr['onmouseover'] = "displayRating('$reImgId','$reImgPrefix',$j,0,1)";
381                 $img_attr['onmouseout'] = "displayRating('$reImgId','$reImgPrefix',0,0,1)";
382             }
383             //$imgName = 'RateIt'.$reImgId.$i;
384             $img_attr['id'] = $imgId . $i;
385             $img_attr['alt'] = $img_attr['id'];
386             $a1->pushContent(HTML::img($img_attr));
387             //$a1->addToolTip(_("Rate the topic of this page"));
388             $html->pushContent($a1);
389
390             //This adds a space between the rating smilies:
391             //if (($i%2) == 0) $html->pushContent("\n");
392         }
393         $html->pushContent(HTML::Raw("&nbsp;"));
394
395         $a0 = HTML::a(array('href' => "javascript:clickRating('$reImgPrefix','$rePagename','$version',"
396             . "'$reImgId','$dimension','X')"));
397         $msg = _("Cancel your rating");
398         $imgprops = array('src' => $WikiTheme->getImageUrl("RateIt" . $imgPrefix . "Cancel"),
399             'id' => $imgId . $imgPrefix . 'Cancel',
400             'alt' => $msg,
401             'title' => $msg);
402         if (!$this->rating)
403             $imgprops['style'] = 'display:none';
404         $a0->pushContent(HTML::img($imgprops));
405         $a0->addToolTip($msg);
406         $html->pushContent($a0);
407
408         /*} elseif ($pred) {
409             $msg = _("No opinion");
410             $html->pushContent(HTML::img(array('src' => $WikiTheme->getImageUrl("RateItCancelN"),
411                                                'id'  => $imgPrefix.'Cancel',
412                                                'alt' => $msg)));
413             //$a0->addToolTip($msg);
414             //$html->pushContent($a0);
415         }*/
416         $img_attr = array();
417         $img_attr['src'] = $WikiTheme->_findData("images/spacer.png");
418         $img_attr['id'] = $actionImgName;
419         $img_attr['alt'] = $img_attr['id'];
420         $img_attr['height'] = 15;
421         $img_attr['width'] = 20;
422         $html->pushContent(HTML::img($img_attr));
423
424         // Display your current rating if there is one, or the current prediction
425         // or the empty widget.
426         $pred = empty($this->pred) ? 0 : $this->pred;
427         $js = '';
428         if (!empty($this->avg))
429             $js .= "avg['$reImgId']=$this->avg; numusers['$reImgId']=$this->numusers;\n";
430         if ($this->rating) {
431             $js .= "rating['$reImgId']=$this->rating; prediction['$reImgId']=$pred;\n";
432             $html->pushContent(JavaScript($js
433                 . "displayRating('$reImgId','$reImgPrefix',$this->rating,0,1);"));
434         } elseif (!empty($this->pred)) {
435             $js .= "rating['$reImgId']=0; prediction['$reImgId']=$this->pred;\n";
436             $html->pushContent(JavaScript($js
437                 . "displayRating('$reImgId','$reImgPrefix',$this->pred,1,1);"));
438         } else {
439             $js .= "rating['$reImgId']=0; prediction['$reImgId']=0;\n";
440             $html->pushContent(JavaScript($js
441                 . "displayRating('$reImgId','$reImgPrefix',0,0,1);"));
442         }
443         return $html;
444     }
445
446 }
447
448 ;
449
450 // Local Variables:
451 // mode: php
452 // tab-width: 8
453 // c-basic-offset: 4
454 // c-hanging-comment-ender-p: nil
455 // indent-tabs-mode: nil
456 // End: