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: <<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
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");
94 function RatingWidgetJavascript() {
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))
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")."';
108 $WikiTheme->addMoreHeaders
110 array('src' => $WikiTheme->_findData('themes/wikilens/wikilens.js'))));
111 return JavaScript($js_globals);
114 function actionImgPath() {
116 return $WikiTheme->_findFile("images/RateItAction.png", 1);
120 * Take a string and quote it sufficiently to be passed as a Javascript
123 function _javascript_quote_string($s) {
124 return str_replace("'", "\'", $s);
127 function getDefaultArguments() {
128 return array( 'pagename' => '[pagename]',
131 'imgPrefix' => '', // '' or BStar or Star
132 'dimension' => false,
139 function head() { // early side-effects (before body)
142 if (!empty($_already)) return;
144 $WikiTheme->addMoreHeaders(JavaScript(
145 "var prediction = new Array; var rating = new Array;
146 var avg = new Array; var numusers = new Array;
147 var msg_rating_votes = '"._("Rating: %.1f (%d votes)")."';
148 var msg_curr_rating = '"._("Your current rating: ")."';
149 var msg_curr_prediction = '"._("Your current prediction: ")."';
150 var msg_chg_rating = '"._("Change your rating from ")."';
151 var msg_to = '"._(" to ")."';
152 var msg_add_rating = '"._("Add your rating: ")."';
153 var msg_thanks = '"._("Thanks!")."';
154 var msg_rating_deleted = '"._("Rating deleted!")."';
156 $WikiTheme->addMoreHeaders($this->RatingWidgetJavascript());
159 function displayActionImg ($mode) {
160 global $WikiTheme, $request;
161 if (!empty($request->_is_buffering_output))
162 ob_end_clean(); // discard any previous output
164 $page = $request->getPage();
165 //$page->set('_cached_html', false);
166 $request->cacheControl('MUST-REVALIDATE');
167 $dbi = $request->getDbh();
169 //fake validators without args
170 $request->appendValidators(array('wikiname' => WIKI_NAME,
171 'args' => wikihash('')));
172 $request->discardOutput();
173 $actionImg = $WikiTheme->_path . $this->actionImgPath();
174 if (file_exists($actionImg)) {
175 header('Content-type: image/png');
176 readfile($actionImg);
178 header('Content-type: image/png');
179 echo base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAIAAAACAQMAAABIeJ9nAAAAA1BMVEX///'
180 .'+nxBvIAAAAAXRSTlMAQObYZgAAABNJREFUeF4NwAEBAAAAgJD+r5YGAAQAAXHhfPAAAAAASUVORK5CYII=');
185 // Only for signed users done in template only yet.
186 function run($dbi, $argstr, &$request, $basepage) {
188 //$this->_request = & $request;
189 //$this->_dbi = & $dbi;
190 $user = $request->getUser();
191 //FIXME: fails on test with DumpHtml:RateIt
192 if (!is_object($user)) {
193 return HTML::raw('');
195 $this->userid = $user->getId();
196 if (!$this->userid) {
197 return HTML::raw('');
199 $args = $this->getArgs($argstr, $request);
200 $this->dimension = $args['dimension'];
201 $this->imgPrefix = $args['imgPrefix'];
202 if ($this->dimension == '') {
203 $this->dimension = 0;
204 $args['dimension'] = 0;
206 if ($args['pagename']) {
207 // Expand relative page names.
208 $page = new WikiPageName($args['pagename'], $basepage);
209 $args['pagename'] = $page->name;
211 if (empty($args['pagename'])) {
212 return $this->error(_("no page specified"));
214 $this->pagename = $args['pagename'];
216 $rdbi = RatingsDb::getTheRatingsDb();
217 $this->_rdbi =& $rdbi;
219 if ($args['mode'] === 'add') {
220 //if (!$user->isSignedIn()) return $this->error(_("You must sign in"));
221 $this->rating = $request->getArg('rating');
222 $rdbi->addRating($this->rating, $this->userid, $this->pagename, $this->dimension);
223 $this->displayActionImg('add');
225 } elseif ($args['mode'] === 'delete') {
226 //if (!$user->isSignedIn()) return $this->error(_("You must sign in"));
227 $rdbi->deleteRating($this->userid, $this->pagename, $this->dimension);
228 unset($this->rating);
229 $this->displayActionImg('delete');
230 } elseif (! $args['show'] ) {
231 return $this->RatingWidgetHtml($args['pagename'], $args['version'], $args['imgPrefix'],
232 $args['dimension'], $args['small']);
234 //if (!$user->isSignedIn()) return $this->error(_("You must sign in"));
236 $this->rating = $rdbi->getRating($this->userid, $this->pagename, $this->dimension);
237 $this->avg = $rdbi->getAvg($this->pagename, $this->dimension);
238 $this->numusers = $rdbi->getNumUsers($this->pagename, $this->dimension);
239 // Update this text on rateit in javascript. needed: NumUsers, Avg
242 HTML::span(array('class' => 'rateit'),
243 sprintf(_("Rating: %.1f (%d votes)"),
244 $this->avg, $this->numusers)));
245 if ($args['show'] == 'top') {
246 if (ENABLE_PAGE_PUBLIC) {
247 $page = $dbi->getPage($this->pagename);
248 if ($page->get('public'))
249 $html->setAttr('class', "public");
251 $html->setAttr('id', "rateit-widget-top");
252 $html->pushContent(HTML::br(),
253 $this->RatingWidgetHtml($args['pagename'], $args['version'],
255 $args['dimension'], $args['small']));
256 } elseif ($args['show'] == 'text') {
257 if (!$WikiTheme->DUMP_MODE)
258 $html->pushContent(HTML::br(),
259 sprintf(_("Your rating was %.1f"),
261 } elseif ($this->rating) {
262 $html->pushContent(HTML::br(),
263 sprintf(_("Your rating was %.1f"),
266 $this->pred = $rdbi->getPrediction($this->userid, $this->pagename, $this->dimension);
267 if (is_string($this->pred))
268 $html->pushContent(HTML::br(),
269 sprintf(_("Prediction: %s"),
272 $html->pushContent(HTML::br(),
273 sprintf(_("Prediction: %.1f"),
276 //$html->pushContent(HTML::p());
277 //$html->pushContent(HTML::em("(Experimental: This might be entirely bogus data)"));
282 // box is used to display a fixed-width, narrow version with common header
283 function box($args=false, $request=false, $basepage=false) {
284 if (!$request) $request =& $GLOBALS['request'];
285 if (!$request->_user->isSignedIn()) return;
286 if (!isset($args)) $args = array();
289 foreach ($args as $key => $value)
290 $argstr .= $key."=".$value;
291 $widget = $this->run($request->_dbi, $argstr, $request, $basepage);
293 return $this->makeBox(WikiLink(_("RateIt"),'',_("Rate It")),
298 * HTML widget display
300 * This needs to be put in the <body> section of the page.
302 * @param pagename Name of the page to rate
303 * @param version Version of the page to rate (may be "" for current)
304 * @param imgPrefix Prefix of the names of the images that display the rating
305 * You can have two widgets for the same page displayed at
306 * once iff the imgPrefix-s are different.
307 * @param dimension Id of the dimension to rate
308 * @param small Makes a smaller ratings widget if non-false
310 * Limitations: Currently this can only print the current users ratings.
311 * And only the widget, but no value (for buddies) also.
313 function RatingWidgetHtml($pagename, $version, $imgPrefix, $dimension, $small = false) {
314 global $WikiTheme, $request;
316 $dbi =& $request->_dbi;
317 $version = $dbi->_backend->get_latest_version($pagename);
318 $pageid = sprintf("%u",crc32($pagename)); // MangleXmlIdentifier($pagename)
319 $imgId = 'RateIt' . $pageid;
320 $actionImgName = 'RateIt'.$pageid.'Action';
322 //$rdbi =& $this->_rdbi;
323 $rdbi = RatingsDb::getTheRatingsDb();
325 // check if the imgPrefix icons exist.
326 if (! $WikiTheme->_findData("images/RateIt".$imgPrefix."Nk0.png", true))
329 // Protect against \'s, though not \r or \n
330 $reImgPrefix = $this->_javascript_quote_string($imgPrefix);
331 $reImgId = $this->_javascript_quote_string($imgId);
332 $reActionImgName = $this->_javascript_quote_string($actionImgName);
333 $rePagename = $this->_javascript_quote_string($pagename);
334 //$dimension = $args['pagename'] . "rat";
336 $html = HTML::span(array("class" => "rateit-widget", "id" => $imgId));
337 for ($i=0; $i < 2; $i++) {
338 $ok[$i] = $WikiTheme->_findData("images/RateIt".$imgPrefix."Ok".$i.".png"); // empty
339 $nk[$i] = $WikiTheme->_findData("images/RateIt".$imgPrefix."Nk".$i.".png"); // rated
340 $rk[$i] = $WikiTheme->_findData("images/RateIt".$imgPrefix."Rk".$i.".png"); // pred
343 if (empty($this->userid)) {
344 $user = $request->getUser();
345 $this->userid = $user->getId();
347 if (empty($this->rating)) {
348 $this->rating = $rdbi->getRating($this->userid, $pagename, $dimension);
349 if (!$this->rating and empty($this->pred)) {
350 $this->pred = $rdbi->getPrediction($this->userid, $pagename, $dimension);
354 for ($i = 1; $i <= 10; $i++) {
356 $a1 = HTML::a(array('href' => "javascript:clickRating('$reImgPrefix','$rePagename','$version',"
357 ."'$reImgId','$dimension',$j)"));
359 $img_attr['src'] = $nk[$i%2];
361 $img_attr['src'] = $ok[$i%2];
362 $img_attr['onmouseover'] = "displayRating('$reImgId','$reImgPrefix',$j,0,1)";
363 $img_attr['onmouseout'] = "displayRating('$reImgId','$reImgPrefix',$this->rating,0,1)";
365 else if (!$this->rating and $this->pred) {
366 $img_attr['src'] = $rk[$i%2];
367 $img_attr['onmouseover'] = "displayRating('$reImgId','$reImgPrefix',$j,1,1)";
368 $img_attr['onmouseout'] = "displayRating('$reImgId','$reImgPrefix',$this->pred,1,1)";
371 $img_attr['onmouseover'] = "displayRating('$reImgId','$reImgPrefix',$j,0,1)";
372 $img_attr['onmouseout'] = "displayRating('$reImgId','$reImgPrefix',0,0,1)";
374 //$imgName = 'RateIt'.$reImgId.$i;
375 $img_attr['id'] = $imgId . $i;
376 $img_attr['alt'] = $img_attr['id'];
377 $a1->pushContent(HTML::img($img_attr));
378 //$a1->addToolTip(_("Rate the topic of this page"));
379 $html->pushContent($a1);
381 //This adds a space between the rating smilies:
382 //if (($i%2) == 0) $html->pushContent("\n");
384 $html->pushContent(HTML::Raw(" "));
386 $a0 = HTML::a(array('href' => "javascript:clickRating('$reImgPrefix','$rePagename','$version',"
387 ."'$reImgId','$dimension','X')"));
388 $msg = _("Cancel your rating");
389 $imgprops = array('src' => $WikiTheme->getImageUrl("RateIt".$imgPrefix."Cancel"),
390 'id' => $imgId.$imgPrefix.'Cancel',
394 $imgprops['style'] = 'display:none';
395 $a0->pushContent(HTML::img($imgprops));
396 $a0->addToolTip($msg);
397 $html->pushContent($a0);
400 $msg = _("No opinion");
401 $html->pushContent(HTML::img(array('src' => $WikiTheme->getImageUrl("RateItCancelN"),
402 'id' => $imgPrefix.'Cancel',
404 //$a0->addToolTip($msg);
405 //$html->pushContent($a0);
408 $img_attr['src'] = $WikiTheme->_findData("images/spacer.png");
409 $img_attr['id'] = $actionImgName;
410 $img_attr['alt'] = $img_attr['id'];
411 $img_attr['height'] = 15;
412 $img_attr['width'] = 20;
413 $html->pushContent(HTML::img($img_attr));
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;
419 if (!empty($this->avg))
420 $js .= "avg['$reImgId']=$this->avg; numusers['$reImgId']=$this->numusers;\n";
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);"));
430 $js .= "rating['$reImgId']=0; prediction['$reImgId']=0;\n";
431 $html->pushContent(JavaScript($js
432 ."displayRating('$reImgId','$reImgPrefix',0,0,1);"));
443 // c-hanging-comment-ender-p: nil
444 // indent-tabs-mode: nil