2 rcs_id('$Id: RateIt.php,v 1.15 2004-07-09 12:50:50 rurban Exp $');
4 Copyright 2004 $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 ?> to enable rating on this page
68 * Note: The wikilens theme must be enabled, to enable this plugin!
69 * Or use a sidebar based theme with the box method.
70 * <?plugin RateIt show=ratings ?> to show my ratings
71 * <?plugin RateIt show=buddies ?> to show my buddies
72 * <?plugin RateIt show=ratings dimension=1 ?>
74 * @author: Dan Frankowski (wikilens author), Reini Urban (as plugin)
77 * - fix RATING_STORAGE = WIKIPAGE
79 * - finish mysuggest.c (external engine with data from mysql)
80 * - add php_prediction
83 require_once("lib/WikiPlugin.php");
84 require_once("lib/wikilens/RatingsDb.php");
86 class WikiPlugin_RateIt
92 function getDescription() {
93 return _("Rating system. Store user ratings per page");
95 function getVersion() {
96 return preg_replace("/[Revision: $]/", '',
97 "\$Revision: 1.15 $");
100 function RatingWidgetJavascript() {
102 $img = substr($WikiTheme->_findData("images/RateItNk0.png"),0,-7);
103 $urlprefix = WikiURL("",0,1);
105 function displayRating(imgPrefix, ratingvalue, pred) {
106 var cancel = imgPrefix + 'Cancel';
107 for (i=1; i<=10; i++) {
108 var imgName = imgPrefix + i;
109 var imgSrc = '".$img."';
110 document[imgName].title = '"._("Your rating ")."'+ratingvalue;
111 if (i<=(ratingvalue*2)) {
112 document[imgName].src = imgSrc + ((i%2) ? 'Ok1' : 'Ok0') + '.png';
114 document[imgName].src = imgSrc + ((i%2) ? 'Nk1' : 'Nk0') + '.png';
118 //document[cancel].src = imgSrc + 'Cancel.png';
121 function click(actionImg, pagename, version, imgPrefix, dimension, rating) {
123 deleteRating(actionImg, pagename, dimension);
124 displayRating(imgPrefix, 0, 0);
126 submitRating(actionImg, pagename, version, dimension, rating);
127 displayRating(imgPrefix, rating, 0);
130 function submitRating(actionImg, page, version, dimension, rating) {
131 var myRand = Math.round(Math.random()*(1000000));
132 var imgSrc = escape(page) + '?version=' + version + '&action=".urlencode(_("RateIt"))."&mode=add&rating=' + rating + '&dimension=' + dimension + '&nopurge=cache&rand=' + myRand;
133 //alert('submitRating(' + page + ', ' + version + ', ' + dimension + ', ' + rating + ') => '+imgSrc);
134 document[actionImg].src= imgSrc;
136 function deleteRating(actionImg, page, dimension) {
137 var myRand = Math.round(Math.random()*(1000000));
138 var imgSrc = '".$urlprefix."' + escape(page) + '?action=".urlencode(_("RateIt"))."&mode=delete&dimension=' + dimension + '&nopurge=cache&rand=' + myRand;
139 //alert('deleteRating(' + page + ', ' + version + ', ' + dimension + ')');
140 document[actionImg].src= imgSrc;
143 return JavaScript($js);
146 function actionImgPath() {
148 return $WikiTheme->_findFile("images/RateItAction.png");
152 * Take a string and quote it sufficiently to be passed as a Javascript
156 function _javascript_quote_string($s) {
157 return str_replace("'", "\'", $s);
160 function getDefaultArguments() {
161 return array( 'pagename' => '[pagename]',
165 'dimension' => false,
172 function head() { // early side-effects (before body)
174 $WikiTheme->addMoreHeaders($this->RatingWidgetJavascript());
177 // todo: only for signed users
178 // todo: set rating dbi for external rating database
179 function run($dbi, $argstr, &$request, $basepage) {
181 //$this->_request = & $request;
182 //$this->_dbi = & $dbi;
183 $user = $request->getUser();
184 //FIXME: fails on test with DumpHtml:RateIt
185 if (!is_object($user)) return HTML();
186 $this->userid = $user->UserName();
187 $args = $this->getArgs($argstr, $request);
188 $this->dimension = $args['dimension'];
189 if ($this->dimension == '') {
190 $this->dimension = 0;
191 $args['dimension'] = 0;
193 if ($args['pagename']) {
194 // Expand relative page names.
195 $page = new WikiPageName($args['pagename'], $basepage);
196 $args['pagename'] = $page->name;
198 if (empty($args['pagename'])) {
199 return $this->error(_("no page specified"));
201 $this->pagename = $args['pagename'];
203 $rdbi = RatingsDb::getTheRatingsDb();
204 $this->_rdbi =& $rdbi;
206 if ($args['mode'] === 'add') {
207 if (!$user->isSignedIn())
208 return $this->error(_("You must sign in"));
210 $actionImg = $WikiTheme->_path . $this->actionImgPath();
211 $rdbi->addRating($request->getArg('rating'), $user->getId(), $this->pagename, $this->dimension);
212 ob_end_clean(); // discard any previous output
214 $page = $request->getPage();
215 $page->set('_cached_html', false);
216 $request->cacheControl('MUST-REVALIDATE');
218 //fake validators without args
219 $request->appendValidators(array('wikiname' => WIKI_NAME,
220 'args' => hash('')));
221 header('Content-type: image/png');
222 readfile($actionImg);
224 } elseif ($args['mode'] === 'delete') {
225 if (!$user->isSignedIn())
226 return $this->error(_("You must sign in"));
228 $actionImg = $WikiTheme->_path . $this->actionImgPath();
229 $rdbi->deleteRating($user->getId(), $this->pagename, $this->dimension);
230 ob_end_clean(); // discard any previous output
232 $page = $request->getPage();
233 $page->set('_cached_html', false);
234 $request->cacheControl('MUST-REVALIDATE');
236 //fake validators without args
237 $request->appendValidators(array('wikiname' => WIKI_NAME,
238 'args' => hash('')));
239 header('Content-type: image/png');
240 readfile($actionImg);
242 } elseif (! $args['show'] ) {
243 // we must use the head method instead, because <body> is already printed.
244 // $WikiTheme->addMoreHeaders($this->RatingWidgetJavascript());
245 // or we change the header in the ob_buffer.
246 //Todo: add a validator based on the users last rating mtime
247 //$rating = $rdbi->getRating();
249 static $validated = 0;
251 //$page = $request->getPage();
252 //$page->set('_cached_html', false);
253 $request->cacheControl('REVALIDATE');
257 //$args['rating'] = $rating;
258 return $this->RatingWidgetHtml($args['pagename'], $args['version'], $args['imgPrefix'], $args['dimension'], $args['small']);
260 if (!$user->isSignedIn())
261 return $this->error(_("You must sign in"));
263 $rating = $rdbi->getRating();
264 $html = HTML::p(sprintf(_("Rated by %d users | Average rating %.1f stars"),
265 $rdbi->getNumUsers($this->pagename, $this->dimension),
266 $rdbi->getAvg($this->pagename, $this->dimension)),
269 $html->pushContent(sprintf(_("Your rating was %.1f"),
272 $pred = $rdbi->getPrediction($this->userid, $this->pagename, $this->dimension);
273 if (is_string($pred))
274 $html->pushContent(sprintf(_("%s prediction for you is %s stars"),
277 $html->pushContent(sprintf(_("%s prediction for you is %.1f stars"),
280 $html->pushContent(HTML::p());
281 $html->pushContent(HTML::em("(Experimental: This is entirely bogus data)"));
286 // box is used to display a fixed-width, narrow version with common header
287 function box($args=false, $request=false, $basepage=false) {
288 if (!$request) $request =& $GLOBALS['request'];
289 if (!$request->_user->isSignedIn()) return;
290 if (!isset($args)) $args = array();
293 foreach ($args as $key => $value)
294 $argstr .= $key."=".$value;
295 $widget = $this->run($request->_dbi, $argstr, $request, $basepage);
297 return $this->makeBox(WikiLink(_("RateIt"),'',_("Rate It")),
302 * HTML widget display
304 * This needs to be put in the <body> section of the page.
306 * @param pagename Name of the page to rate
307 * @param version Version of the page to rate (may be "" for current)
308 * @param imgPrefix Prefix of the names of the images that display the rating
309 * You can have two widgets for the same page displayed at
310 * once iff the imgPrefix-s are different.
311 * @param dimension Id of the dimension to rate
312 * @param small Makes a smaller ratings widget if non-false
314 * Limitations: Currently this can only print the current users ratings.
315 * And only the widget, but no value (for buddies) also.
317 function RatingWidgetHtml($pagename, $version, $imgPrefix, $dimension, $small = false) {
318 global $WikiTheme, $request;
321 $imgPrefix = $pagename . $imgPrefix;
322 $actionImgName = $imgPrefix . 'RateItAction';
323 $dbi =& $GLOBALS['request']->getDbh();
324 $version = $dbi->_backend->get_latest_version($pagename);
326 //$rdbi =& $this->_rdbi;
327 $rdbi = RatingsDb::getTheRatingsDb();
329 // Protect against 's, though not \r or \n
331 $reImgPrefix = WikiPlugin_RateIt::_javascript_quote_string($imgPrefix);
332 $reActionImgName = WikiPlugin_RateIt::_javascript_quote_string($actionImgName);
333 $rePagename = WikiPlugin_RateIt::_javascript_quote_string($pagename);
334 //$dimension = $args['pagename'] . "rat";
336 $html = HTML::span(array("id" => $id));
337 for ($i=0; $i < 2; $i++) {
338 $nk[$i] = $WikiTheme->_findData("images/RateItNk$i.png");
339 $none[$i] = $WikiTheme->_findData("images/RateItRk$i.png");
343 $user = $request->getUser();
344 $userid = $user->getId();
345 //if (!isset($args['rating']))
346 $rating = $rdbi->getRating($userid, $pagename, $dimension);
348 $pred = $rdbi->getPrediction($userid,$pagename,$dimension);
350 for ($i = 1; $i <= 10; $i++) {
351 $a1 = HTML::a(array('href' => 'javascript:click(\'' . $reActionImgName . '\',\'' . $rePagename . '\',\'' . $version . '\',\'' . $reImgPrefix . '\',\'' . $dimension . '\',' . ($i/2) . ')'));
353 $img_attr['src'] = $nk[$i%2];
354 //if (!$rating and !$pred)
355 // $img_attr['src'] = $none[$i%2];
357 $img_attr['name'] = $imgPrefix . $i;
358 $img_attr['border'] = 0;
359 $a1->pushContent(HTML::img($img_attr));
360 $a1->addToolTip(_("Rate the topic of this page"));
361 $html->pushContent($a1);
363 //This adds a space between the rating smilies:
364 // if (($i%2) == 0) $html->pushContent(' ');
366 $html->pushContent(HTML::Raw(' '));
368 $a0 = HTML::a(array('href' => 'javascript:click(\'' . $reActionImgName . '\',\'' . $rePagename . '\',\'' . $version . '\',\'' . $reImgPrefix . '\',\'' . $dimension . '\',\'X\')'));
370 $msg = _("Cancel rating");
371 $a0->pushContent(HTML::img(array('src' => $WikiTheme->getImageUrl("RateItCancel"),
372 'name'=> $imgPrefix.'Cancel',
374 $a0->addToolTip($msg);
375 $html->pushContent($a0);
377 $msg = _("No opinion");
378 $html->pushContent(HTML::img(array('src' => $WikiTheme->getImageUrl("RateItCancelN"),
379 'name'=> $imgPrefix.'Cancel',
381 //$a0->addToolTip($msg);
382 //$html->pushContent($a0);
385 $img_attr['src'] = $WikiTheme->_findData("images/RateItAction.png");
386 $img_attr['name'] = $actionImgName;
387 //$img_attr['class'] = 'k' . $i;
388 $img_attr['border'] = 0;
389 $html->pushContent(HTML::img($img_attr));
390 // Display the current rating if there is one
392 $html->pushContent(JavaScript('displayRating(\'' . $reImgPrefix . '\','.$rating .',0)'));
394 $html->pushContent(JavaScript('displayRating(\'' . $reImgPrefix . '\','.$pred .',1)'));
396 $html->pushContent(JavaScript('displayRating(\'' . $reImgPrefix . '\',0,0)'));
403 // $Log: not supported by cvs2svn $
404 // Revision 1.14 2004/07/08 20:30:07 rurban
405 // plugin->run consistency: request as reference, added basepage.
406 // encountered strange bug in AllPages (and the test) which destroys ->_dbi
408 // Revision 1.12 2004/06/30 19:59:07 dfrankow
409 // Make changes suitable so that wikilens theme (and wikilens.org) work properly.
410 // + Remove predictions (for now)
411 // + Use new RatingsDb singleton.
412 // + Change RatingWidgetHtml() to use parameters like a normal PHP function
413 // so we can have PHP check that we're passing the right # of them.
414 // + Change RatingWidgetHtml() to be callable static-ally
415 // (without a plugin object)
416 // + Remove the "RateIt" button for now, because we don't use it on wikilens.org.
417 // Maybe if someone wants the button, there can be an arg or flag for it.
418 // + Always show the cancel button, because UI widgets should not hide.
419 // + Remove the "No opinion" button for now, because we don't yet store that.
420 // This is a useful thing, tho, for the future.
422 // Revision 1.11 2004/06/19 10:22:41 rurban
423 // outcomment the pear specific methods to let all pages load
425 // Revision 1.10 2004/06/18 14:42:17 rurban
426 // added wikilens libs (not yet merged good enough, some work for DanFr)
428 // Revision 1.9 2004/06/14 11:31:39 rurban
429 // renamed global $Theme to $WikiTheme (gforge nameclash)
430 // inherit PageList default options from PageList
431 // default sortby=pagename
432 // use options in PageList_Selectable (limit, sortby, ...)
433 // added action revert, with button at action=diff
434 // added option regex to WikiAdminSearchReplace
436 // Revision 1.8 2004/06/01 15:28:01 rurban
437 // AdminUser only ADMIN_USER not member of Administrators
438 // some RateIt improvements by dfrankow
439 // edit_toolbar buttons
441 // Revision _1.2 2004/04/29 17:55:03 dfrankow
442 // Check in escape() changes to protect against leading spaces in pagename.
443 // This is untested with Reini's _("RateIt") additions to this plugin.
445 // Revision 1.7 2004/04/21 04:29:50 rurban
446 // write WikiURL consistently (not WikiUrl)
448 // Revision 1.6 2004/04/12 14:07:12 rurban
451 // Revision 1.5 2004/04/11 10:42:02 rurban
452 // pgsrc/CreatePagePlugin
454 // Revision 1.4 2004/04/06 20:00:11 rurban
455 // Cleanup of special PageList column types
456 // Added support of plugin and theme specific Pagelist Types
457 // Added support for theme specific UserPreferences
458 // Added session support for ip-based throttling
459 // sql table schema change: ALTER TABLE session ADD sess_ip CHAR(15);
460 // Enhanced postgres schema
461 // Added DB_Session_dba support
463 // Revision 1.3 2004/04/01 06:29:51 rurban
465 // RateIt also for ADODB
467 // Revision 1.2 2004/03/31 06:22:22 rurban
468 // shorter javascript,
469 // added prediction buttons and display logic,
470 // empty HTML if not signed in.
471 // fixed deleting (empty dimension => 0)
473 // Revision 1.1 2004/03/30 02:38:06 rurban
474 // RateIt support (currently no recommendation engine yet)
482 // c-hanging-comment-ender-p: nil
483 // indent-tabs-mode: nil