2 rcs_id('$Id: RateIt.php,v 1.10 2004-06-18 14:42:17 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.10 $");
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."';
111 document[imgName].title = '"._("Predicted rating ")."'+ratingvalue;
113 document[imgName].title = '"._("Your rating ")."'+ratingvalue;
114 if (i<=(ratingvalue*2)) {
116 document[imgName].src = imgSrc + ((i%2) ? 'Rk1' : 'Rk0') + '.png';
118 document[imgName].src = imgSrc + ((i%2) ? 'Ok1' : 'Ok0') + '.png';
120 document[imgName].src = imgSrc + ((i%2) ? 'Nk1' : 'Nk0') + '.png';
123 if ((pred == 0) && (ratingvalue > 0))
124 document[cancel].src = imgSrc + 'Cancel.png';
126 document[cancel].src = imgSrc + 'CancelN.png';
128 function click(actionImg, pagename, version, imgPrefix, dimension, rating) {
130 deleteRating(actionImg, pagename, dimension);
131 displayRating(imgPrefix, 0, 0);
133 submitRating(actionImg, pagename, version, dimension, rating);
134 displayRating(imgPrefix, rating, 0);
137 function submitRating(actionImg, page, version, dimension, rating) {
138 var myRand = Math.round(Math.random()*(1000000));
139 var imgSrc = escape(page) + '?version=' + version + '&action=".urlencode(_("RateIt"))."&mode=add&rating=' + rating + '&dimension=' + dimension + '&nopurge=cache&rand=' + myRand;
140 //alert('submitRating(' + page + ', ' + version + ', ' + dimension + ', ' + rating + ') => '+imgSrc);
141 document[actionImg].src= imgSrc;
143 function deleteRating(actionImg, page, dimension) {
144 var myRand = Math.round(Math.random()*(1000000));
145 var imgSrc = '".$urlprefix."' + escape(page) + '?action=".urlencode(_("RateIt"))."&mode=delete&dimension=' + dimension + '&nopurge=cache&rand=' + myRand;
146 //alert('deleteRating(' + page + ', ' + version + ', ' + dimension + ')');
147 document[actionImg].src= imgSrc;
150 return JavaScript($js);
153 function actionImgPath() {
155 return $WikiTheme->_findFile("images/RateItAction.png");
159 * Take a string and quote it sufficiently to be passed as a Javascript
162 function _javascript_quote_string($s) {
163 return str_replace("'", "\'", $s);
166 function getDefaultArguments() {
167 return array( 'pagename' => '[pagename]',
171 'dimension' => false,
178 function head() { // early side-effects (before body)
180 $WikiTheme->addMoreHeaders($this->RatingWidgetJavascript());
183 // todo: only for signed users
184 // todo: set rating dbi for external rating database
185 function run($dbi, $argstr, $request, $basepage) {
187 $this->_request = & $request;
188 $this->_dbi = & $dbi;
189 $user = & $request->getUser();
190 $this->userid = $user->UserName();
191 $args = $this->getArgs($argstr, $request);
192 $this->dimension = $args['dimension'];
193 if ($this->dimension == '') {
194 $this->dimension = 0;
195 $args['dimension'] = 0;
197 if ($args['pagename']) {
198 // Expand relative page names.
199 $page = new WikiPageName($args['pagename'], $basepage);
200 $args['pagename'] = $page->name;
202 if (empty($args['pagename'])) {
203 return $this->error(_("no page specified"));
205 $this->pagename = $args['pagename'];
207 if (RATING_STORAGE == 'SQL') {
208 $rdbi = new RatingsDb();
209 $this->_rdbi =& $rdbi;
212 if ($args['mode'] === 'add') {
213 if (!$user->isSignedIn())
214 return $this->error(_("You must sign in"));
216 $actionImg = $WikiTheme->_path . $this->actionImgPath();
217 $rdbi->addRating($request->getArg('rating'));
218 ob_end_clean(); // discard any previous output
220 $page = $request->getPage();
221 $page->set('_cached_html', false);
222 $request->cacheControl('MUST-REVALIDATE');
224 //fake validators without args
225 $request->appendValidators(array('wikiname' => WIKI_NAME,
226 'args' => hash('')));
227 header('Content-type: image/png');
228 readfile($actionImg);
230 } elseif ($args['mode'] === 'delete') {
231 if (!$user->isSignedIn())
232 return $this->error(_("You must sign in"));
234 $actionImg = $WikiTheme->_path . $this->actionImgPath();
235 $rdbi->deleteRating();
236 ob_end_clean(); // discard any previous output
238 $page = $request->getPage();
239 $page->set('_cached_html', false);
240 $request->cacheControl('MUST-REVALIDATE');
242 //fake validators without args
243 $request->appendValidators(array('wikiname' => WIKI_NAME,
244 'args' => hash('')));
245 header('Content-type: image/png');
246 readfile($actionImg);
248 } elseif (! $args['show'] ) {
249 // we must use the head method instead, because <body> is already printed.
250 // $WikiTheme->addMoreHeaders($this->RatingWidgetJavascript());
251 // or we change the header in the ob_buffer.
253 //Todo: add a validator based on the users last rating mtime
254 $rating = $rdbi->getRating();
256 static $validated = 0;
258 //$page = $request->getPage();
259 //$page->set('_cached_html', false);
260 $request->cacheControl('REVALIDATE');
264 $args['rating'] = $rating;
265 return $this->RatingWidgetHtml($args);
267 if (!$user->isSignedIn())
268 return $this->error(_("You must sign in"));
270 $rating = $this->getRating();
271 $html = HTML::p(sprintf(_("Rated by %d users | Average rating %.1f stars"),
272 $this->getNumUsers($this->pagename,$this->dimension),
273 $this->getAvg($this->pagename,$this->dimension)),
275 if ($rating !== false)
276 $html->pushContent(sprintf(_("Your rating was %.1f"),
279 $pred = $this->getPrediction($this->userid,$this->pagename,$this->dimension);
280 if (is_string($pred))
281 $html->pushContent(sprintf(_("%s prediction for you is %s stars"),
284 $html->pushContent(sprintf(_("%s prediction for you is %.1f stars"),
287 $html->pushContent(HTML::p());
288 $html->pushContent(HTML::em("(Experimental: This is entirely bogus data)"));
293 // box is used to display a fixed-width, narrow version with common header
294 function box($args=false, $request=false, $basepage=false) {
295 if (!$request) $request =& $GLOBALS['request'];
296 if (!$request->_user->isSignedIn()) return;
297 if (!isset($args)) $args = array();
300 foreach ($args as $key => $value)
301 $argstr .= $key."=".$value;
302 $widget = $this->run($request->_dbi, $argstr, $request, $basepage);
304 return $this->makeBox(WikiLink(_("RateIt"),'',_("Rate It")),
309 * HTML widget display
311 * This needs to be put in the <body> section of the page.
313 * @param pagename Name of the page to rate
314 * @param version Version of the page to rate (may be "" for current)
315 * @param imgPrefix Prefix of the names of the images that display the rating
316 * You can have two widgets for the same page displayed at
317 * once iff the imgPrefix-s are different.
318 * @param dimension Id of the dimension to rate
319 * @param small Makes a smaller ratings widget if non-false
321 * Limitations: Currently this can only print the current users ratings.
322 * And only the widget, but no value (for buddies) also.
324 function RatingWidgetHtml($args) {
325 global $WikiTheme, $request;
327 if (!$request->_user->isSignedIn()) return;
328 $imgPrefix = $pagename . $imgPrefix;
329 $actionImgName = $imgPrefix . 'RateItAction';
330 $dbi =& $GLOBALS['request']->getDbh();
331 $version = $dbi->_backend->get_latest_version($pagename);
332 $rdbi =& $this->_rdbi;
334 // Protect against 's, though not \r or \n
335 $reImgPrefix = $this->_javascript_quote_string($imgPrefix);
336 $reActionImgName = $this->_javascript_quote_string($actionImgName);
337 $rePagename = $this->_javascript_quote_string($pagename);
338 //$dimension = $args['pagename'] . "rat";
340 $html = HTML::span(array("id" => $id));
341 for ($i=0; $i < 2; $i++) {
342 $nk[$i] = $WikiTheme->_findData("images/RateItNk$i.png");
343 $none[$i] = $WikiTheme->_findData("images/RateItRk$i.png");
346 $html->pushContent(Button(_("RateIt"),_("RateIt"), $pagename));
347 $html->pushContent(HTML::raw(' '));
351 $user = $request->getUser();
352 $userid = $user->getId();
353 if (!isset($args['rating']))
354 $rating = $rdbi->getRating($userid, $pagename, $dimension);
356 $pred = $rdbi->getPrediction($userid,$pagename,$dimension);
358 for ($i = 1; $i <= 10; $i++) {
359 $a1 = HTML::a(array('href' => 'javascript:click(\'' . $reActionImgName . '\',\'' . $rePagename . '\',\'' . $version . '\',\'' . $reImgPrefix . '\',\'' . $dimension . '\',' . ($i/2) . ')'));
361 $img_attr['src'] = $nk[$i%2];
362 if (!$rating and !$pred)
363 $img_attr['src'] = $none[$i%2];
364 $img_attr['name'] = $imgPrefix . $i;
365 $img_attr['border'] = 0;
366 $a1->pushContent(HTML::img($img_attr));
367 $a1->addToolTip(_("Rate the topic of this page"));
368 $html->pushContent($a1);
369 //This adds a space between the rating smilies:
370 // if (($i%2) == 0) $html->pushContent(' ');
372 $html->pushContent(HTML::Raw(' '));
373 $a0 = HTML::a(array('href' => 'javascript:click(\'' . $reActionImgName . '\',\'' . $rePagename . '\',\'' . $version . '\',\'' . $reImgPrefix . '\',\'' . $dimension . '\',\'X\')'));
375 $msg = _("Cancel rating");
376 $a0->pushContent(HTML::img(array('src' => $WikiTheme->getImageUrl("RateItCancel"),
377 'name'=> $imgPrefix.'Cancel',
379 $a0->addToolTip($msg);
380 $html->pushContent($a0);
382 $msg = _("No opinion");
383 $html->pushContent(HTML::img(array('src' => $WikiTheme->getImageUrl("RateItCancelN"),
384 'name'=> $imgPrefix.'Cancel',
386 //$a0->addToolTip($msg);
387 //$html->pushContent($a0);
390 $img_attr['src'] = $WikiTheme->_findData("images/RateItAction.png");
391 $img_attr['name'] = $actionImgName;
392 //$img_attr['class'] = 'k' . $i;
393 $img_attr['border'] = 0;
394 $html->pushContent(HTML::img($img_attr));
395 // Display the current rating if there is one
397 $html->pushContent(JavaScript('displayRating(\'' . $reImgPrefix . '\','.$rating .',0)'));
399 $html->pushContent(JavaScript('displayRating(\'' . $reImgPrefix . '\','.$pred .',1)'));
401 $html->pushContent(JavaScript('displayRating(\'' . $reImgPrefix . '\',0,0)'));
408 // $Log: not supported by cvs2svn $
409 // Revision 1.9 2004/06/14 11:31:39 rurban
410 // renamed global $Theme to $WikiTheme (gforge nameclash)
411 // inherit PageList default options from PageList
412 // default sortby=pagename
413 // use options in PageList_Selectable (limit, sortby, ...)
414 // added action revert, with button at action=diff
415 // added option regex to WikiAdminSearchReplace
417 // Revision 1.8 2004/06/01 15:28:01 rurban
418 // AdminUser only ADMIN_USER not member of Administrators
419 // some RateIt improvements by dfrankow
420 // edit_toolbar buttons
422 // Revision _1.2 2004/04/29 17:55:03 dfrankow
423 // Check in escape() changes to protect against leading spaces in pagename.
424 // This is untested with Reini's _("RateIt") additions to this plugin.
426 // Revision 1.7 2004/04/21 04:29:50 rurban
427 // write WikiURL consistently (not WikiUrl)
429 // Revision 1.6 2004/04/12 14:07:12 rurban
432 // Revision 1.5 2004/04/11 10:42:02 rurban
433 // pgsrc/CreatePagePlugin
435 // Revision 1.4 2004/04/06 20:00:11 rurban
436 // Cleanup of special PageList column types
437 // Added support of plugin and theme specific Pagelist Types
438 // Added support for theme specific UserPreferences
439 // Added session support for ip-based throttling
440 // sql table schema change: ALTER TABLE session ADD sess_ip CHAR(15);
441 // Enhanced postgres schema
442 // Added DB_Session_dba support
444 // Revision 1.3 2004/04/01 06:29:51 rurban
446 // RateIt also for ADODB
448 // Revision 1.2 2004/03/31 06:22:22 rurban
449 // shorter javascript,
450 // added prediction buttons and display logic,
451 // empty HTML if not signed in.
452 // fixed deleting (empty dimension => 0)
454 // Revision 1.1 2004/03/30 02:38:06 rurban
455 // RateIt support (currently no recommendation engine yet)
463 // c-hanging-comment-ender-p: nil
464 // indent-tabs-mode: nil