4 * Copyright 2004,2007,2009 $ThePhpWikiProgrammingTeam
6 * This file is part of PhpWiki.
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.
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.
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
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.
28 * There should be two methods to store ratings:
29 * In a SQL database as in wikilens http://dickens.cs.umn.edu/dfrankow/wikilens
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
36 * wikilens plans several user-centered applications like:
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
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.
54 * For a simple rating system one can also store the rating in the page
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
64 * - Autoclass: simple public domain C library
65 * - MLC++: C++ library http://www.sgi.com/tech/mlc/
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
75 * @author: Dan Frankowski (wikilens author), Reini Urban (as plugin)
78 * - finish mysuggest.c (external engine with data from mysql)
81 require_once("lib/WikiPlugin.php");
82 require_once("lib/wikilens/RatingsDb.php");
84 class WikiPlugin_RateIt
90 function getDescription() {
91 return _("Rating system. Store user ratings per page");
93 function getVersion() {
94 return preg_replace("/[Revision: $]/", '',
98 function RatingWidgetJavascript() {
100 if (!empty($this->imgPrefix))
101 $imgPrefix = $this->imgPrefix;
102 elseif (defined("RATEIT_IMGPREFIX"))
103 $imgPrefix = RATEIT_IMGPREFIX;
104 else $imgPrefix = '';
105 if ($imgPrefix and !$WikiTheme->_findData("images/RateIt".$imgPrefix."Nk0.png",1))
107 $img = substr($WikiTheme->_findData("images/RateIt".$imgPrefix."Nk0.png"),0,-7);
108 $urlprefix = WikiURL("",0,1); // TODO: check actions USE_PATH_INFO=false
109 $js_globals = "var rateit_imgsrc = '".$img."';
110 var rateit_action = '".urlencode("RateIt")."';
112 $WikiTheme->addMoreHeaders
114 array('src' => $WikiTheme->_findData('themes/wikilens/wikilens.js'))));
115 return JavaScript($js_globals);
118 function actionImgPath() {
120 return $WikiTheme->_findFile("images/RateItAction.png", 1);
124 * Take a string and quote it sufficiently to be passed as a Javascript
127 function _javascript_quote_string($s) {
128 return str_replace("'", "\'", $s);
131 function getDefaultArguments() {
132 return array( 'pagename' => '[pagename]',
135 'imgPrefix' => '', // '' or BStar or Star
136 'dimension' => false,
143 function head() { // early side-effects (before body)
145 $WikiTheme->addMoreHeaders(JavaScript(
146 "var prediction = new Array; var rating = new Array;
147 var avg = new Array; var numusers = new Array;
148 var msg_rating_votes = '"._("Rating: %.1f (%d votes)")."';
149 var msg_curr_rating = '"._("Your current rating: ")."';
150 var msg_curr_prediction = '"._("Your current prediction: ")."';
151 var msg_chg_rating = '"._("Change your rating from ")."';
152 var msg_to = '"._(" to ")."';
153 var msg_add_rating = '"._("Add your rating: ")."';
154 var msg_thanks = '"._("Thanks!")."';
155 var msg_rating_deleted = '"._("Rating deleted!")."';
157 $WikiTheme->addMoreHeaders($this->RatingWidgetJavascript());
160 function displayActionImg ($mode) {
161 global $WikiTheme, $request;
162 if (!empty($request->_is_buffering_output))
163 ob_end_clean(); // discard any previous output
165 $page = $request->getPage();
166 //$page->set('_cached_html', false);
167 $request->cacheControl('MUST-REVALIDATE');
168 $dbi = $request->getDbh();
170 //fake validators without args
171 $request->appendValidators(array('wikiname' => WIKI_NAME,
172 'args' => wikihash('')));
173 $request->discardOutput();
174 $actionImg = $WikiTheme->_path . $this->actionImgPath();
175 if (file_exists($actionImg)) {
176 header('Content-type: image/png');
177 readfile($actionImg);
179 header('Content-type: image/png');
183 IHDR
\ 1 \ 1\b\ 6 \1f\15Ä
\89 \14IDATx^
\ 5À
\ 1 Â0í
\1fzçX
\ 1\ 2ÿ7-
\12` IEND®B`
\82';
188 // Only for signed users done in template only yet.
189 function run($dbi, $argstr, &$request, $basepage) {
191 //$this->_request = & $request;
192 //$this->_dbi = & $dbi;
193 $user = $request->getUser();
194 //FIXME: fails on test with DumpHtml:RateIt
195 if (!is_object($user)) {
196 return HTML::raw('');
198 $this->userid = $user->getId();
199 if (!$this->userid) {
200 return HTML::raw('');
202 $args = $this->getArgs($argstr, $request);
203 $this->dimension = $args['dimension'];
204 $this->imgPrefix = $args['imgPrefix'];
205 if ($this->dimension == '') {
206 $this->dimension = 0;
207 $args['dimension'] = 0;
209 if ($args['pagename']) {
210 // Expand relative page names.
211 $page = new WikiPageName($args['pagename'], $basepage);
212 $args['pagename'] = $page->name;
214 if (empty($args['pagename'])) {
215 return $this->error(_("no page specified"));
217 $this->pagename = $args['pagename'];
219 $rdbi = RatingsDb::getTheRatingsDb();
220 $this->_rdbi =& $rdbi;
222 if ($args['mode'] === 'add') {
223 //if (!$user->isSignedIn()) return $this->error(_("You must sign in"));
224 $this->rating = $request->getArg('rating');
225 $rdbi->addRating($this->rating, $this->userid, $this->pagename, $this->dimension);
226 $this->displayActionImg('add');
228 } elseif ($args['mode'] === 'delete') {
229 //if (!$user->isSignedIn()) return $this->error(_("You must sign in"));
230 $rdbi->deleteRating($this->userid, $this->pagename, $this->dimension);
231 unset($this->rating);
232 $this->displayActionImg('delete');
233 } elseif (! $args['show'] ) {
234 return $this->RatingWidgetHtml($args['pagename'], $args['version'], $args['imgPrefix'],
235 $args['dimension'], $args['small']);
237 //if (!$user->isSignedIn()) return $this->error(_("You must sign in"));
239 $this->rating = $rdbi->getRating($this->userid, $this->pagename, $this->dimension);
240 $this->avg = $rdbi->getAvg($this->pagename, $this->dimension);
241 $this->numusers = $rdbi->getNumUsers($this->pagename, $this->dimension);
242 // Update this text on rateit in javascript. needed: NumUsers, Avg
245 HTML::span(array('class' => 'rateit'),
246 sprintf(_("Rating: %.1f (%d votes)"),
247 $this->avg, $this->numusers)));
248 if ($args['show'] == 'top') {
249 if (ENABLE_PAGE_PUBLIC) {
250 $page = $dbi->getPage($this->pagename);
251 if ($page->get('public'))
252 $html->setAttr('class', "public");
254 $html->setAttr('id', "rateit-widget-top");
255 $html->pushContent(HTML::br(),
256 $this->RatingWidgetHtml($args['pagename'], $args['version'],
258 $args['dimension'], $args['small']));
259 } elseif ($args['show'] == 'text') {
260 if (!$WikiTheme->DUMP_MODE)
261 $html->pushContent(HTML::br(),
262 sprintf(_("Your rating was %.1f"),
264 } elseif ($this->rating) {
265 $html->pushContent(HTML::br(),
266 sprintf(_("Your rating was %.1f"),
269 $this->pred = $rdbi->getPrediction($this->userid, $this->pagename, $this->dimension);
270 if (is_string($this->pred))
271 $html->pushContent(HTML::br(),
272 sprintf(_("Prediction: %s"),
275 $html->pushContent(HTML::br(),
276 sprintf(_("Prediction: %.1f"),
279 //$html->pushContent(HTML::p());
280 //$html->pushContent(HTML::em("(Experimental: This might be entirely bogus data)"));
285 // box is used to display a fixed-width, narrow version with common header
286 function box($args=false, $request=false, $basepage=false) {
287 if (!$request) $request =& $GLOBALS['request'];
288 if (!$request->_user->isSignedIn()) return;
289 if (!isset($args)) $args = array();
292 foreach ($args as $key => $value)
293 $argstr .= $key."=".$value;
294 $widget = $this->run($request->_dbi, $argstr, $request, $basepage);
296 return $this->makeBox(WikiLink(_("RateIt"),'',_("Rate It")),
301 * HTML widget display
303 * This needs to be put in the <body> section of the page.
305 * @param pagename Name of the page to rate
306 * @param version Version of the page to rate (may be "" for current)
307 * @param imgPrefix Prefix of the names of the images that display the rating
308 * You can have two widgets for the same page displayed at
309 * once iff the imgPrefix-s are different.
310 * @param dimension Id of the dimension to rate
311 * @param small Makes a smaller ratings widget if non-false
313 * Limitations: Currently this can only print the current users ratings.
314 * And only the widget, but no value (for buddies) also.
316 function RatingWidgetHtml($pagename, $version, $imgPrefix, $dimension, $small = false) {
317 global $WikiTheme, $request;
319 $dbi =& $request->_dbi;
320 $version = $dbi->_backend->get_latest_version($pagename);
321 $pageid = sprintf("%u",crc32($pagename)); // MangleXmlIdentifier($pagename)
322 $imgId = 'RateIt' . $pageid;
323 $actionImgName = 'RateIt'.$pageid.'Action';
325 //$rdbi =& $this->_rdbi;
326 $rdbi = RatingsDb::getTheRatingsDb();
328 // check if the imgPrefix icons exist.
329 if (! $WikiTheme->_findData("images/RateIt".$imgPrefix."Nk0.png", true))
332 // Protect against \'s, though not \r or \n
333 $reImgPrefix = $this->_javascript_quote_string($imgPrefix);
334 $reImgId = $this->_javascript_quote_string($imgId);
335 $reActionImgName = $this->_javascript_quote_string($actionImgName);
336 $rePagename = $this->_javascript_quote_string($pagename);
337 //$dimension = $args['pagename'] . "rat";
339 $html = HTML::span(array("class" => "rateit-widget", "id" => $imgId));
340 for ($i=0; $i < 2; $i++) {
341 $ok[$i] = $WikiTheme->_findData("images/RateIt".$imgPrefix."Ok".$i.".png"); // empty
342 $nk[$i] = $WikiTheme->_findData("images/RateIt".$imgPrefix."Nk".$i.".png"); // rated
343 $rk[$i] = $WikiTheme->_findData("images/RateIt".$imgPrefix."Rk".$i.".png"); // pred
346 if (empty($this->userid)) {
347 $user = $request->getUser();
348 $this->userid = $user->getId();
350 if (empty($this->rating)) {
351 $this->rating = $rdbi->getRating($this->userid, $pagename, $dimension);
352 if (!$this->rating and empty($this->pred)) {
353 $this->pred = $rdbi->getPrediction($this->userid, $pagename, $dimension);
357 for ($i = 1; $i <= 10; $i++) {
359 $a1 = HTML::a(array('href' => "javascript:clickRating('$reImgPrefix','$rePagename','$version',"
360 ."'$reImgId','$dimension',$j)"));
362 $img_attr['src'] = $nk[$i%2];
364 $img_attr['src'] = $ok[$i%2];
365 $img_attr['onMouseOver'] = "displayRating('$reImgId','$reImgPrefix',$j,0,1)";
366 $img_attr['onMouseOut'] = "displayRating('$reImgId','$reImgPrefix',$this->rating,0,1)";
368 else if (!$this->rating and $this->pred) {
369 $img_attr['src'] = $rk[$i%2];
370 $img_attr['onMouseOver'] = "displayRating('$reImgId','$reImgPrefix',$j,1,1)";
371 $img_attr['onMouseOut'] = "displayRating('$reImgId','$reImgPrefix',$this->pred,1,1)";
374 $img_attr['onMouseOver'] = "displayRating('$reImgId','$reImgPrefix',$j,0,1)";
375 $img_attr['onMouseOut'] = "displayRating('$reImgId','$reImgPrefix',0,0,1)";
377 //$imgName = 'RateIt'.$reImgId.$i;
378 $img_attr['name'] = $imgId . $i;
379 $img_attr['alt'] = $img_attr['name'];
380 $img_attr['border'] = 0;
381 $a1->pushContent(HTML::img($img_attr));
382 //$a1->addToolTip(_("Rate the topic of this page"));
383 $html->pushContent($a1);
385 //This adds a space between the rating smilies:
386 //if (($i%2) == 0) $html->pushContent("\n");
388 $html->pushContent(HTML::Raw(" "));
390 $a0 = HTML::a(array('href' => "javascript:clickRating('$reImgPrefix','$rePagename','$version',"
391 ."'$reImgId','$dimension','X')"));
392 $msg = _("Cancel your rating");
393 $imgprops = array('src' => $WikiTheme->getImageUrl("RateIt".$imgPrefix."Cancel"),
394 'name' => $imgId.$imgPrefix.'Cancel',
399 $imgprops['style'] = 'display:none';
400 $a0->pushContent(HTML::img($imgprops));
401 $a0->addToolTip($msg);
402 $html->pushContent($a0);
405 $msg = _("No opinion");
406 $html->pushContent(HTML::img(array('src' => $WikiTheme->getImageUrl("RateItCancelN"),
407 'name'=> $imgPrefix.'Cancel',
409 //$a0->addToolTip($msg);
410 //$html->pushContent($a0);
413 $img_attr['src'] = $WikiTheme->_findData("images/spacer.png");
414 $img_attr['name'] = $actionImgName;
415 $img_attr['alt'] = $img_attr['name'];
416 $img_attr['border'] = 0;
417 $img_attr['height'] = 15;
418 $img_attr['width'] = 20;
419 $html->pushContent(HTML::img($img_attr));
421 // Display your current rating if there is one, or the current prediction
422 // or the empty widget.
423 $pred = empty($this->pred) ? 0 : $this->pred;
425 if (!empty($this->avg))
426 $js .= "avg['$reImgId']=$this->avg; numusers['$reImgId']=$this->numusers;\n";
428 $js .= "rating['$reImgId']=$this->rating; prediction['$reImgId']=$pred;\n";
429 $html->pushContent(JavaScript($js
430 ."displayRating('$reImgId','$reImgPrefix',$this->rating,0,1);"));
431 } elseif (!empty($this->pred)) {
432 $js .= "rating['$reImgId']=0; prediction['$reImgId']=$this->pred;\n";
433 $html->pushContent(JavaScript($js
434 ."displayRating('$reImgId','$reImgPrefix',$this->pred,1,1);"));
436 $js .= "rating['$reImgId']=0; prediction['$reImgId']=0;\n";
437 $html->pushContent(JavaScript($js
438 ."displayRating('$reImgId','$reImgPrefix',0,0,1);"));
450 // c-hanging-comment-ender-p: nil
451 // indent-tabs-mode: nil