source: branches/2.6/include/functions_rate.inc.php @ 27295

Last change on this file since 27295 was 27295, checked in by rvelices, 10 years ago

Merged -r27294 from trunk:
feature 3043: Add event to allow calculation of rating score with a different algorithm

  • Property svn:eol-style set to LF
File size: 6.0 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2014 Piwigo Team                  http://piwigo.org |
6// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
7// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
8// +-----------------------------------------------------------------------+
9// | This program is free software; you can redistribute it and/or modify  |
10// | it under the terms of the GNU General Public License as published by  |
11// | the Free Software Foundation                                          |
12// |                                                                       |
13// | This program is distributed in the hope that it will be useful, but   |
14// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
15// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
16// | General Public License for more details.                              |
17// |                                                                       |
18// | You should have received a copy of the GNU General Public License     |
19// | along with this program; if not, write to the Free Software           |
20// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
21// | USA.                                                                  |
22// +-----------------------------------------------------------------------+
23
24/**
25 * @package functions\rate
26 */
27
28
29/**
30 * Rate a picture by the current user.
31 *
32 * @param int $image_id
33 * @param float $rate
34 * @return array as return by update_rating_score()
35 */
36function rate_picture($image_id, $rate)
37{
38  global $conf, $user;
39
40  if (!isset($rate)
41      or !$conf['rate']
42      or !in_array($rate, $conf['rate_items']))
43  {
44    return false;
45  }
46
47  $user_anonymous = is_autorize_status(ACCESS_CLASSIC) ? false : true;
48
49  if ($user_anonymous and !$conf['rate_anonymous'])
50  {
51    return false;
52  }
53
54  $ip_components = explode('.', $_SERVER["REMOTE_ADDR"]);
55  if (count($ip_components) > 3)
56  {
57    array_pop($ip_components);
58  }
59  $anonymous_id = implode ('.', $ip_components);
60
61  if ($user_anonymous)
62  {
63    $save_anonymous_id = pwg_get_cookie_var('anonymous_rater', $anonymous_id);
64
65    if ($anonymous_id != $save_anonymous_id)
66    { // client has changed his IP adress or he's trying to fool us
67      $query = '
68SELECT element_id
69  FROM '.RATE_TABLE.'
70  WHERE user_id = '.$user['id'].'
71    AND anonymous_id = \''.$anonymous_id.'\'
72;';
73      $already_there = array_from_query($query, 'element_id');
74
75      if (count($already_there) > 0)
76      {
77        $query = '
78DELETE
79  FROM '.RATE_TABLE.'
80  WHERE user_id = '.$user['id'].'
81    AND anonymous_id = \''.$save_anonymous_id.'\'
82    AND element_id IN ('.implode(',', $already_there).')
83;';
84         pwg_query($query);
85       }
86
87       $query = '
88UPDATE '.RATE_TABLE.'
89  SET anonymous_id = \'' .$anonymous_id.'\'
90  WHERE user_id = '.$user['id'].'
91    AND anonymous_id = \'' . $save_anonymous_id.'\'
92;';
93       pwg_query($query);
94    } // end client changed ip
95
96    pwg_set_cookie_var('anonymous_rater', $anonymous_id);
97  } // end anonymous user
98
99  $query = '
100DELETE
101  FROM '.RATE_TABLE.'
102  WHERE element_id = '.$image_id.'
103    AND user_id = '.$user['id'].'
104';
105  if ($user_anonymous)
106  {
107    $query.= ' AND anonymous_id = \''.$anonymous_id.'\'';
108  }
109  pwg_query($query);
110  $query = '
111INSERT
112  INTO '.RATE_TABLE.'
113  (user_id,anonymous_id,element_id,rate,date)
114  VALUES
115  ('
116    .$user['id'].','
117    .'\''.$anonymous_id.'\','
118    .$image_id.','
119    .$rate
120    .',NOW())
121;';
122  pwg_query($query);
123
124  return update_rating_score($image_id);
125}
126
127
128/**
129 * Update images.rating_score field.
130 * We use a bayesian average (http://en.wikipedia.org/wiki/Bayesian_average) with
131 *  C = average number of rates per item
132 *  m = global average rate (all rates)
133 *
134 * @param int|false $element_id if false applies to all
135 * @return array (score, average, count) values are null if $element_id is false
136*/
137function update_rating_score($element_id = false)
138{
139  if ( ($alt_result = trigger_event('update_rating_score', false, $element_id)) !== false)
140  {
141    return $alt_result;
142  }
143
144  $query = '
145SELECT element_id,
146    COUNT(rate) AS rcount,
147    SUM(rate) AS rsum
148  FROM '.RATE_TABLE.'
149  GROUP by element_id';
150
151  $all_rates_count = 0;
152  $all_rates_avg = 0;
153  $item_ratecount_avg = 0;
154  $by_item = array();
155
156  $result = pwg_query($query);
157  while ($row = pwg_db_fetch_assoc($result))
158  {
159    $all_rates_count += $row['rcount'];
160    $all_rates_avg += $row['rsum'];
161    $by_item[$row['element_id']] = $row;
162  }
163
164  if ($all_rates_count>0)
165  {
166    $all_rates_avg /= $all_rates_count;
167    $item_ratecount_avg = $all_rates_count / count($by_item);
168  }
169
170  $updates = array();
171  foreach ($by_item as $id => $rate_summary )
172  {
173    $score = ( $item_ratecount_avg * $all_rates_avg + $rate_summary['rsum'] ) / ($item_ratecount_avg + $rate_summary['rcount']);
174    $score = round($score,2);
175    if ($id==$element_id)
176    {
177      $return = array(
178        'score' => $score,
179        'average' => round($rate_summary['rsum'] / $rate_summary['rcount'], 2),
180        'count' => $rate_summary['rcount'],
181        );
182    }
183    $updates[] = array( 'id'=>$id, 'rating_score'=>$score );
184  }
185  mass_updates(
186    IMAGES_TABLE,
187    array(
188      'primary' => array('id'),
189      'update' => array('rating_score')
190      ),
191    $updates
192    );
193
194  //set to null all items with no rate
195  if ( !isset($by_item[$element_id]) )
196  {
197    $query='
198SELECT id FROM '.IMAGES_TABLE .'
199  LEFT JOIN '.RATE_TABLE.' ON id=element_id
200  WHERE element_id IS NULL AND rating_score IS NOT NULL';
201
202    $to_update = array_from_query( $query, 'id');
203
204    if ( !empty($to_update) )
205    {
206      $query='
207UPDATE '.IMAGES_TABLE .'
208  SET rating_score=NULL
209  WHERE id IN (' . implode(',',$to_update) . ')';
210    pwg_query($query);
211    }
212  }
213
214  return isset($return) ? $return : array('score'=>null, 'average'=>null, 'count'=>0 );
215}
216
217?>
Note: See TracBrowser for help on using the repository browser.