]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/RateIt.php
added wikilens libs (not yet merged good enough, some work for DanFr)
[SourceForge/phpwiki.git] / lib / plugin / RateIt.php
1 <?php // -*-php-*-
2 rcs_id('$Id: RateIt.php,v 1.10 2004-06-18 14:42:17 rurban Exp $');
3 /*
4  Copyright 2004 $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
19  along with PhpWiki; if not, write to the Free Software
20  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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:    <?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 ?>
73  *
74  * @author:  Dan Frankowski (wikilens author), Reini Urban (as plugin)
75  *
76  * TODO: 
77  * - fix RATING_STORAGE = WIKIPAGE
78  * - fix smart caching
79  * - finish mysuggest.c (external engine with data from mysql)
80  * - add php_prediction
81  */
82
83 require_once("lib/WikiPlugin.php");
84 require_once("lib/wikilens/RatingsDb.php");
85
86 class WikiPlugin_RateIt
87 extends WikiPlugin
88 {
89     function getName() {
90         return _("RateIt");
91     }
92     function getDescription() {
93         return _("Rating system. Store user ratings per page");
94     }
95     function getVersion() {
96         return preg_replace("/[Revision: $]/", '',
97                             "\$Revision: 1.10 $");
98     }
99
100     function RatingWidgetJavascript() {
101         global $WikiTheme;
102         $img   = substr($WikiTheme->_findData("images/RateItNk0.png"),0,-7);
103         $urlprefix = WikiURL("",0,1);
104         $js = "
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     if (pred)
111       document[imgName].title = '"._("Predicted rating ")."'+ratingvalue;
112     else    
113       document[imgName].title = '"._("Your rating ")."'+ratingvalue;
114     if (i<=(ratingvalue*2)) {
115       if (pred)
116         document[imgName].src = imgSrc + ((i%2) ? 'Rk1' : 'Rk0') + '.png';
117       else
118         document[imgName].src = imgSrc + ((i%2) ? 'Ok1' : 'Ok0') + '.png';
119     } else {
120       document[imgName].src = imgSrc + ((i%2) ? 'Nk1' : 'Nk0') + '.png';
121     }
122   }
123   if ((pred == 0) && (ratingvalue > 0))
124     document[cancel].src = imgSrc + 'Cancel.png';
125   else
126     document[cancel].src = imgSrc + 'CancelN.png';
127 }
128 function click(actionImg, pagename, version, imgPrefix, dimension, rating) {
129   if (rating == 'X') {
130     deleteRating(actionImg, pagename, dimension);
131     displayRating(imgPrefix, 0, 0);
132   } else {
133     submitRating(actionImg, pagename, version, dimension, rating);
134     displayRating(imgPrefix, rating, 0);
135   }
136 }
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;
142 }
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;
148 }
149 ";
150         return JavaScript($js);
151     }
152
153     function actionImgPath() {
154         global $WikiTheme;
155         return $WikiTheme->_findFile("images/RateItAction.png");
156     }
157
158     /**
159      * Take a string and quote it sufficiently to be passed as a Javascript
160      * string between ''s
161      */
162     function _javascript_quote_string($s) {
163         return str_replace("'", "\'", $s);
164     }
165
166     function getDefaultArguments() {
167         return array( 'pagename'  => '[pagename]',
168                       'version'   => false,
169                       'id'        => 'rateit',
170                       'imgPrefix' => '',
171                       'dimension' => false,
172                       'small'     => false,
173                       'show'      => false,
174                       'mode'      => false,
175                       );
176     }
177
178     function head() { // early side-effects (before body)
179         global $WikiTheme;
180         $WikiTheme->addMoreHeaders($this->RatingWidgetJavascript());
181     }
182
183     // todo: only for signed users
184     // todo: set rating dbi for external rating database
185     function run($dbi, $argstr, $request, $basepage) {
186         global $WikiTheme;
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;
196         }
197         if ($args['pagename']) {
198             // Expand relative page names.
199             $page = new WikiPageName($args['pagename'], $basepage);
200             $args['pagename'] = $page->name;
201         }
202         if (empty($args['pagename'])) {
203             return $this->error(_("no page specified"));
204         }
205         $this->pagename = $args['pagename'];
206
207         if (RATING_STORAGE == 'SQL') {
208             $rdbi = new RatingsDb();
209             $this->_rdbi =& $rdbi;
210         }
211
212         if ($args['mode'] === 'add') {
213             if (!$user->isSignedIn())
214                 return $this->error(_("You must sign in"));
215             global $WikiTheme;
216             $actionImg = $WikiTheme->_path . $this->actionImgPath();
217             $rdbi->addRating($request->getArg('rating'));
218             ob_end_clean();  // discard any previous output
219             // delete the cache
220             $page = $request->getPage();
221             $page->set('_cached_html', false);
222             $request->cacheControl('MUST-REVALIDATE');
223             $dbi->touch();
224             //fake validators without args
225             $request->appendValidators(array('wikiname' => WIKI_NAME,
226                                              'args'     => hash('')));
227             header('Content-type: image/png');
228             readfile($actionImg);
229             exit();
230         } elseif ($args['mode'] === 'delete') {
231             if (!$user->isSignedIn())
232                 return $this->error(_("You must sign in"));
233             global $WikiTheme;
234             $actionImg = $WikiTheme->_path . $this->actionImgPath();
235             $rdbi->deleteRating();
236             ob_end_clean();  // discard any previous output
237             // delete the cache
238             $page = $request->getPage();
239             $page->set('_cached_html', false);
240             $request->cacheControl('MUST-REVALIDATE');
241             $dbi->touch();
242             //fake validators without args
243             $request->appendValidators(array('wikiname' => WIKI_NAME,
244                                              'args'     => hash('')));
245             header('Content-type: image/png');
246             readfile($actionImg);
247             exit();
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.
252
253             //Todo: add a validator based on the users last rating mtime
254             $rating = $rdbi->getRating();
255             /*
256                 static $validated = 0;
257                 if (!$validated) {
258                 //$page = $request->getPage();
259                 //$page->set('_cached_html', false);
260                   $request->cacheControl('REVALIDATE');
261                   $validated = 1;
262                 }
263             */
264             $args['rating'] = $rating;
265             return $this->RatingWidgetHtml($args);
266         } else {
267             if (!$user->isSignedIn())
268                 return $this->error(_("You must sign in"));
269             extract($args);
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)),
274                             HTML::br());
275             if ($rating !== false)
276                 $html->pushContent(sprintf(_("Your rating was %.1f"),
277                                            $rating));
278             else {
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"),
282                                                WIKI_NAME, $pred));
283                 elseif ($pred)
284                     $html->pushContent(sprintf(_("%s prediction for you is %.1f stars"),
285                                                WIKI_NAME, $pred));
286             }
287             $html->pushContent(HTML::p());
288             $html->pushContent(HTML::em("(Experimental: This is entirely bogus data)"));
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         if (!$request) $request =& $GLOBALS['request'];
296         if (!$request->_user->isSignedIn()) return;
297         if (!isset($args)) $args = array();
298         $args['small'] = 1;
299         $argstr = '';
300         foreach ($args as $key => $value)
301             $argstr .= $key."=".$value;
302         $widget = $this->run($request->_dbi, $argstr, $request, $basepage);
303
304         return $this->makeBox(WikiLink(_("RateIt"),'',_("Rate It")),
305                               $widget);
306     }
307
308     /**
309      * HTML widget display
310      *
311      * This needs to be put in the <body> section of the page.
312      *
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
320      *
321      * Limitations: Currently this can only print the current users ratings.
322      *              And only the widget, but no value (for buddies) also.
323      */
324     function RatingWidgetHtml($args) {
325         global $WikiTheme, $request;
326         extract($args);
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;
333
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";
339     
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");
344         }
345         if (!$small) {
346             $html->pushContent(Button(_("RateIt"),_("RateIt"), $pagename));
347             $html->pushContent(HTML::raw('&nbsp;'));
348         }
349        
350
351         $user = $request->getUser();
352         $userid = $user->getId();
353         if (!isset($args['rating']))
354             $rating = $rdbi->getRating($userid, $pagename, $dimension);
355         if (!$rating) {
356             $pred = $rdbi->getPrediction($userid,$pagename,$dimension);
357         }
358         for ($i = 1; $i <= 10; $i++) {
359             $a1 = HTML::a(array('href' => 'javascript:click(\'' . $reActionImgName . '\',\'' . $rePagename . '\',\'' . $version . '\',\'' . $reImgPrefix . '\',\'' . $dimension . '\',' . ($i/2) . ')'));
360             $img_attr = array();
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(' ');
371         }
372         $html->pushContent(HTML::Raw('&nbsp;'));
373         $a0 = HTML::a(array('href' => 'javascript:click(\'' . $reActionImgName . '\',\'' . $rePagename . '\',\'' . $version . '\',\'' . $reImgPrefix . '\',\'' . $dimension . '\',\'X\')'));
374         if ($rating) {
375             $msg = _("Cancel rating");
376             $a0->pushContent(HTML::img(array('src' => $WikiTheme->getImageUrl("RateItCancel"),
377                                              'name'=> $imgPrefix.'Cancel',
378                                              'alt' => $msg)));
379             $a0->addToolTip($msg);
380             $html->pushContent($a0);
381         } elseif ($pred) {
382             $msg = _("No opinion");
383             $html->pushContent(HTML::img(array('src' => $WikiTheme->getImageUrl("RateItCancelN"),
384                                                'name'=> $imgPrefix.'Cancel',
385                                                'alt' => $msg)));
386             //$a0->addToolTip($msg);
387             //$html->pushContent($a0);
388         }
389         $img_attr = array();
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
396         if ($rating) 
397             $html->pushContent(JavaScript('displayRating(\'' . $reImgPrefix . '\','.$rating .',0)'));
398         elseif ($pred)
399             $html->pushContent(JavaScript('displayRating(\'' . $reImgPrefix . '\','.$pred .',1)'));
400         else 
401             $html->pushContent(JavaScript('displayRating(\'' . $reImgPrefix . '\',0,0)'));    
402         return $html;
403     }
404
405 };
406
407
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
416 //
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
421 //
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.
425 //
426 // Revision 1.7  2004/04/21 04:29:50  rurban
427 // write WikiURL consistently (not WikiUrl)
428 //
429 // Revision 1.6  2004/04/12 14:07:12  rurban
430 // more docs
431 //
432 // Revision 1.5  2004/04/11 10:42:02  rurban
433 // pgsrc/CreatePagePlugin
434 //
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
443 //
444 // Revision 1.3  2004/04/01 06:29:51  rurban
445 // better wording
446 // RateIt also for ADODB
447 //
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)
453 //
454 // Revision 1.1  2004/03/30 02:38:06  rurban
455 // RateIt support (currently no recommendation engine yet)
456 //
457
458 // For emacs users
459 // Local Variables:
460 // mode: php
461 // tab-width: 8
462 // c-basic-offset: 4
463 // c-hanging-comment-ender-p: nil
464 // indent-tabs-mode: nil
465 // End:
466 ?>