]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/RateIt.php
rcs_id no longer makes sense with Subversion global version number
[SourceForge/phpwiki.git] / lib / plugin / RateIt.php
1 <?php // -*-php-*-
2 // rcs_id('$Id$');
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
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 /**
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:    <?plugin RateIt ?>          just the widget without text
68  *   Note: The wikilens theme or any derivate must be enabled, to enable this plugin!
69  *           <?plugin RateIt show=top ?> text plus widget below
70  *           <?plugin RateIt show=ratings ?> to show my ratings
71  *   TODO:   <?plugin RateIt show=buddies ?> to show my buddies
72  *           <?plugin RateIt show=ratings dimension=1 ?>
73  *   TODO:   <?plugin 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         return _("RateIt");
89     }
90     function getDescription() {
91         return _("Rating system. Store user ratings per page");
92     }
93
94     function RatingWidgetJavascript() {
95         global $WikiTheme;
96         if (!empty($this->imgPrefix))
97             $imgPrefix = $this->imgPrefix;
98         elseif (defined("RATEIT_IMGPREFIX"))
99             $imgPrefix = RATEIT_IMGPREFIX;
100         else $imgPrefix = '';
101         if ($imgPrefix and !$WikiTheme->_findData("images/RateIt".$imgPrefix."Nk0.png",1))
102             $imgPrefix = '';
103         $img   = substr($WikiTheme->_findData("images/RateIt".$imgPrefix."Nk0.png"),0,-7);
104         $urlprefix = WikiURL("",0,1); // TODO: check actions USE_PATH_INFO=false
105         $js_globals = "var rateit_imgsrc = '".$img."';
106 var rateit_action = '".urlencode("RateIt")."';
107 ";
108         $WikiTheme->addMoreHeaders
109                 (JavaScript('',
110                             array('src' => $WikiTheme->_findData('themes/wikilens/wikilens.js'))));
111         return JavaScript($js_globals);
112     }
113
114     function actionImgPath() {
115         global $WikiTheme;
116         return $WikiTheme->_findFile("images/RateItAction.png", 1);
117     }
118
119     /**
120      * Take a string and quote it sufficiently to be passed as a Javascript
121      * string between ''s
122      */
123     function _javascript_quote_string($s) {
124         return str_replace("'", "\'", $s);
125     }
126
127     function getDefaultArguments() {
128         return array( 'pagename'  => '[pagename]',
129                       'version'   => false,
130                       'id'        => 'rateit',
131                       'imgPrefix' => '',      // '' or BStar or Star
132                       'dimension' => false,
133                       'small'     => false,
134                       'show'      => false,
135                       'mode'      => false,
136                       );
137     }
138
139     function head() { // early side-effects (before body)
140         global $WikiTheme;
141         $WikiTheme->addMoreHeaders(JavaScript(
142 "var prediction = new Array; var rating = new Array;
143 var avg = new Array; var numusers = new Array;
144 var msg_rating_votes = '"._("Rating: %.1f (%d votes)")."';
145 var msg_curr_rating = '"._("Your current rating: ")."';
146 var msg_curr_prediction = '"._("Your current prediction: ")."';
147 var msg_chg_rating = '"._("Change your rating from ")."';
148 var msg_to = '"._(" to ")."';
149 var msg_add_rating = '"._("Add your rating: ")."';
150 var msg_thanks = '"._("Thanks!")."';
151 var msg_rating_deleted = '"._("Rating deleted!")."';
152 "));
153         $WikiTheme->addMoreHeaders($this->RatingWidgetJavascript());
154     }
155
156     function displayActionImg ($mode) {
157         global $WikiTheme, $request;
158         if (!empty($request->_is_buffering_output))
159             ob_end_clean();  // discard any previous output
160         // delete the cache
161         $page = $request->getPage();
162         //$page->set('_cached_html', false);
163         $request->cacheControl('MUST-REVALIDATE');
164         $dbi = $request->getDbh();
165         $dbi->touch();
166         //fake validators without args
167         $request->appendValidators(array('wikiname' => WIKI_NAME,
168                                          'args'     => wikihash('')));
169         $request->discardOutput();
170         $actionImg = $WikiTheme->_path . $this->actionImgPath();
171         if (file_exists($actionImg)) {
172             header('Content-type: image/png');
173             readfile($actionImg);
174         } else {
175             header('Content-type: image/png');
176             echo base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAIAAAACAQMAAABIeJ9nAAAAA1BMVEX///'
177                                  .'+nxBvIAAAAAXRSTlMAQObYZgAAABNJREFUeF4NwAEBAAAAgJD+r5YGAAQAAXHhfPAAAAAASUVORK5CYII=');
178         }
179         exit;
180     }
181
182     // Only for signed users done in template only yet.
183     function run($dbi, $argstr, &$request, $basepage) {
184         global $WikiTheme;
185         //$this->_request = & $request;
186         //$this->_dbi = & $dbi;
187         $user = $request->getUser();
188         //FIXME: fails on test with DumpHtml:RateIt
189         if (!is_object($user)) {
190             return HTML::raw('');
191         }
192         $this->userid = $user->getId();
193         if (!$this->userid) {
194             return HTML::raw('');
195         }
196         $args = $this->getArgs($argstr, $request);
197         $this->dimension = $args['dimension'];
198         $this->imgPrefix = $args['imgPrefix'];
199         if ($this->dimension == '') {
200             $this->dimension = 0;
201             $args['dimension'] = 0;
202         }
203         if ($args['pagename']) {
204             // Expand relative page names.
205             $page = new WikiPageName($args['pagename'], $basepage);
206             $args['pagename'] = $page->name;
207         }
208         if (empty($args['pagename'])) {
209             return $this->error(_("no page specified"));
210         }
211         $this->pagename = $args['pagename'];
212
213         $rdbi = RatingsDb::getTheRatingsDb();
214         $this->_rdbi =& $rdbi;
215
216         if ($args['mode'] === 'add') {
217             //if (!$user->isSignedIn()) return $this->error(_("You must sign in"));
218             $this->rating = $request->getArg('rating');
219             $rdbi->addRating($this->rating, $this->userid, $this->pagename, $this->dimension);
220             $this->displayActionImg('add');
221
222         } elseif ($args['mode'] === 'delete') {
223             //if (!$user->isSignedIn()) return $this->error(_("You must sign in"));
224             $rdbi->deleteRating($this->userid, $this->pagename, $this->dimension);
225             unset($this->rating);
226             $this->displayActionImg('delete');
227         } elseif (! $args['show'] ) {
228             return $this->RatingWidgetHtml($args['pagename'], $args['version'], $args['imgPrefix'],
229                                            $args['dimension'], $args['small']);
230         } else {
231             //if (!$user->isSignedIn()) return $this->error(_("You must sign in"));
232             //extract($args);
233             $this->rating   = $rdbi->getRating($this->userid, $this->pagename, $this->dimension);
234             $this->avg      = $rdbi->getAvg($this->pagename, $this->dimension);
235             $this->numusers = $rdbi->getNumUsers($this->pagename, $this->dimension);
236             // Update this text on rateit in javascript. needed: NumUsers, Avg
237             $html = HTML::div
238                 (
239                  HTML::span(array('class' => 'rateit'),
240                             sprintf(_("Rating: %.1f (%d votes)"),
241                                     $this->avg, $this->numusers)));
242             if ($args['show'] == 'top') {
243                 if (ENABLE_PAGE_PUBLIC) {
244                     $page = $dbi->getPage($this->pagename);
245                     if ($page->get('public'))
246                         $html->setAttr('class', "public");
247                 }
248                 $html->setAttr('id', "rateit-widget-top");
249                 $html->pushContent(HTML::br(),
250                                    $this->RatingWidgetHtml($args['pagename'], $args['version'],
251                                                            $args['imgPrefix'],
252                                                            $args['dimension'], $args['small']));
253             } elseif ($args['show'] == 'text') {
254                 if (!$WikiTheme->DUMP_MODE)
255                     $html->pushContent(HTML::br(),
256                                        sprintf(_("Your rating was %.1f"),
257                                                $this->rating));
258             } elseif ($this->rating) {
259                 $html->pushContent(HTML::br(),
260                                    sprintf(_("Your rating was %.1f"),
261                                            $this->rating));
262             } else {
263                     $this->pred = $rdbi->getPrediction($this->userid, $this->pagename, $this->dimension);
264                     if (is_string($this->pred))
265                     $html->pushContent(HTML::br(),
266                                        sprintf(_("Prediction: %s"),
267                                                $this->pred));
268                 elseif ($this->pred)
269                     $html->pushContent(HTML::br(),
270                                        sprintf(_("Prediction: %.1f"),
271                                                $this->pred));
272             }
273             //$html->pushContent(HTML::p());
274             //$html->pushContent(HTML::em("(Experimental: This might be entirely bogus data)"));
275             return $html;
276         }
277     }
278
279     // box is used to display a fixed-width, narrow version with common header
280     function box($args=false, $request=false, $basepage=false) {
281         if (!$request) $request =& $GLOBALS['request'];
282         if (!$request->_user->isSignedIn()) return;
283         if (!isset($args)) $args = array();
284         $args['small'] = 1;
285         $argstr = '';
286         foreach ($args as $key => $value)
287             $argstr .= $key."=".$value;
288         $widget = $this->run($request->_dbi, $argstr, $request, $basepage);
289
290         return $this->makeBox(WikiLink(_("RateIt"),'',_("Rate It")),
291                               $widget);
292     }
293
294     /**
295      * HTML widget display
296      *
297      * This needs to be put in the <body> section of the page.
298      *
299      * @param pagename    Name of the page to rate
300      * @param version     Version of the page to rate (may be "" for current)
301      * @param imgPrefix   Prefix of the names of the images that display the rating
302      *                    You can have two widgets for the same page displayed at
303      *                    once iff the imgPrefix-s are different.
304      * @param dimension   Id of the dimension to rate
305      * @param small       Makes a smaller ratings widget if non-false
306      *
307      * Limitations: Currently this can only print the current users ratings.
308      *              And only the widget, but no value (for buddies) also.
309      */
310     function RatingWidgetHtml($pagename, $version, $imgPrefix, $dimension, $small = false) {
311         global $WikiTheme, $request;
312
313         $dbi =& $request->_dbi;
314         $version = $dbi->_backend->get_latest_version($pagename);
315         $pageid = sprintf("%u",crc32($pagename)); // MangleXmlIdentifier($pagename)
316         $imgId = 'RateIt' . $pageid;
317         $actionImgName = 'RateIt'.$pageid.'Action';
318
319         //$rdbi =& $this->_rdbi;
320         $rdbi = RatingsDb::getTheRatingsDb();
321
322         // check if the imgPrefix icons exist.
323         if (! $WikiTheme->_findData("images/RateIt".$imgPrefix."Nk0.png", true))
324             $imgPrefix = '';
325
326         // Protect against \'s, though not \r or \n
327         $reImgPrefix = $this->_javascript_quote_string($imgPrefix);
328         $reImgId     = $this->_javascript_quote_string($imgId);
329         $reActionImgName = $this->_javascript_quote_string($actionImgName);
330         $rePagename      = $this->_javascript_quote_string($pagename);
331         //$dimension = $args['pagename'] . "rat";
332
333         $html = HTML::span(array("class" => "rateit-widget", "id" => $imgId));
334         for ($i=0; $i < 2; $i++) {
335             $ok[$i] = $WikiTheme->_findData("images/RateIt".$imgPrefix."Ok".$i.".png"); // empty
336             $nk[$i] = $WikiTheme->_findData("images/RateIt".$imgPrefix."Nk".$i.".png"); // rated
337             $rk[$i] = $WikiTheme->_findData("images/RateIt".$imgPrefix."Rk".$i.".png"); // pred
338         }
339
340         if (empty($this->userid)) {
341             $user = $request->getUser();
342             $this->userid = $user->getId();
343         }
344         if (empty($this->rating)) {
345             $this->rating = $rdbi->getRating($this->userid, $pagename, $dimension);
346             if (!$this->rating and empty($this->pred)) {
347                 $this->pred = $rdbi->getPrediction($this->userid, $pagename, $dimension);
348             }
349         }
350
351         for ($i = 1; $i <= 10; $i++) {
352             $j = $i / 2;
353             $a1 = HTML::a(array('href' => "javascript:clickRating('$reImgPrefix','$rePagename','$version',"
354                                 ."'$reImgId','$dimension',$j)"));
355             $img_attr = array();
356             $img_attr['src'] = $nk[$i%2];
357             if ($this->rating) {
358                 $img_attr['src'] = $ok[$i%2];
359                 $img_attr['onmouseover'] = "displayRating('$reImgId','$reImgPrefix',$j,0,1)";
360                 $img_attr['onmouseout']  = "displayRating('$reImgId','$reImgPrefix',$this->rating,0,1)";
361             }
362             else if (!$this->rating and $this->pred) {
363                 $img_attr['src'] = $rk[$i%2];
364                 $img_attr['onmouseover'] = "displayRating('$reImgId','$reImgPrefix',$j,1,1)";
365                 $img_attr['onmouseout']  = "displayRating('$reImgId','$reImgPrefix',$this->pred,1,1)";
366             }
367             else {
368                 $img_attr['onmouseover'] = "displayRating('$reImgId','$reImgPrefix',$j,0,1)";
369                 $img_attr['onmouseout']  = "displayRating('$reImgId','$reImgPrefix',0,0,1)";
370             }
371             //$imgName = 'RateIt'.$reImgId.$i;
372             $img_attr['name'] = $imgId . $i;
373             $img_attr['alt'] = $img_attr['name'];
374             $img_attr['border'] = 0;
375             $a1->pushContent(HTML::img($img_attr));
376             //$a1->addToolTip(_("Rate the topic of this page"));
377             $html->pushContent($a1);
378
379             //This adds a space between the rating smilies:
380             //if (($i%2) == 0) $html->pushContent("\n");
381         }
382         $html->pushContent(HTML::Raw("&nbsp;"));
383
384         $a0 = HTML::a(array('href' => "javascript:clickRating('$reImgPrefix','$rePagename','$version',"
385                             ."'$reImgId','$dimension','X')"));
386         $msg = _("Cancel your rating");
387         $imgprops = array('src'   => $WikiTheme->getImageUrl("RateIt".$imgPrefix."Cancel"),
388                           'name'  => $imgId.$imgPrefix.'Cancel',
389                           'border'=> 0,
390                           'alt'   => $msg,
391                           'title' => $msg);
392         if (!$this->rating)
393             $imgprops['style'] = 'display:none';
394         $a0->pushContent(HTML::img($imgprops));
395         $a0->addToolTip($msg);
396         $html->pushContent($a0);
397
398         /*} elseif ($pred) {
399             $msg = _("No opinion");
400             $html->pushContent(HTML::img(array('src' => $WikiTheme->getImageUrl("RateItCancelN"),
401                                                'name'=> $imgPrefix.'Cancel',
402                                                'alt' => $msg)));
403             //$a0->addToolTip($msg);
404             //$html->pushContent($a0);
405         }*/
406         $img_attr = array();
407         $img_attr['src'] = $WikiTheme->_findData("images/spacer.png");
408         $img_attr['name'] = $actionImgName;
409         $img_attr['alt'] = $img_attr['name'];
410         $img_attr['border'] = 0;
411         $img_attr['height'] = 15;
412         $img_attr['width'] = 20;
413         $html->pushContent(HTML::img($img_attr));
414
415         // Display your current rating if there is one, or the current prediction
416         // or the empty widget.
417         $pred = empty($this->pred) ? 0 : $this->pred;
418         $js = '';
419         if (!empty($this->avg))
420             $js .= "avg['$reImgId']=$this->avg; numusers['$reImgId']=$this->numusers;\n";
421         if ($this->rating) {
422             $js .= "rating['$reImgId']=$this->rating; prediction['$reImgId']=$pred;\n";
423             $html->pushContent(JavaScript($js
424                     ."displayRating('$reImgId','$reImgPrefix',$this->rating,0,1);"));
425         } elseif (!empty($this->pred)) {
426             $js .= "rating['$reImgId']=0; prediction['$reImgId']=$this->pred;\n";
427             $html->pushContent(JavaScript($js
428                     ."displayRating('$reImgId','$reImgPrefix',$this->pred,1,1);"));
429         } else {
430             $js .= "rating['$reImgId']=0; prediction['$reImgId']=0;\n";
431             $html->pushContent(JavaScript($js
432                     ."displayRating('$reImgId','$reImgPrefix',0,0,1);"));
433         }
434         return $html;
435     }
436
437 };
438
439 // For emacs users
440 // Local Variables:
441 // mode: php
442 // tab-width: 8
443 // c-basic-offset: 4
444 // c-hanging-comment-ender-p: nil
445 // indent-tabs-mode: nil
446 // End:
447 ?>