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