aboutsummaryrefslogtreecommitdiffstats
path: root/include/functions_rate.inc.php
blob: 3b27f5c8e9baefc075b5fee1459f46c2b7225cc4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
<?php
// +-----------------------------------------------------------------------+
// | Piwigo - a PHP based photo gallery                                    |
// +-----------------------------------------------------------------------+
// | Copyright(C) 2008-2016 Piwigo Team                  http://piwigo.org |
// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
// +-----------------------------------------------------------------------+
// | This program is free software; you can redistribute it and/or modify  |
// | it under the terms of the GNU General Public License as published by  |
// | the Free Software Foundation                                          |
// |                                                                       |
// | This program is distributed in the hope that it will be useful, but   |
// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
// | General Public License for more details.                              |
// |                                                                       |
// | You should have received a copy of the GNU General Public License     |
// | along with this program; if not, write to the Free Software           |
// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
// | USA.                                                                  |
// +-----------------------------------------------------------------------+

/**
 * @package functions\rate
 */


/**
 * Rate a picture by the current user.
 *
 * @param int $image_id
 * @param float $rate
 * @return array as return by update_rating_score()
 */
function rate_picture($image_id, $rate)
{
  global $conf, $user;

  if (!isset($rate)
      or !$conf['rate']
      or !preg_match('/^[0-9]+$/', $rate)
      or !in_array($rate, $conf['rate_items']))
  {
    return false;
  }

  $user_anonymous = is_autorize_status(ACCESS_CLASSIC) ? false : true;

  if ($user_anonymous and !$conf['rate_anonymous'])
  {
    return false;
  }

  $ip_components = explode('.', $_SERVER["REMOTE_ADDR"]);
  if (count($ip_components) > 3)
  {
    array_pop($ip_components);
  }
  $anonymous_id = implode ('.', $ip_components);

  if ($user_anonymous)
  {
    $save_anonymous_id = pwg_get_cookie_var('anonymous_rater', $anonymous_id);

    if ($anonymous_id != $save_anonymous_id)
    { // client has changed his IP adress or he's trying to fool us
      $query = '
SELECT element_id
  FROM '.RATE_TABLE.'
  WHERE user_id = '.$user['id'].'
    AND anonymous_id = \''.$anonymous_id.'\'
;';
      $already_there = array_from_query($query, 'element_id');

      if (count($already_there) > 0)
      {
        $query = '
DELETE
  FROM '.RATE_TABLE.'
  WHERE user_id = '.$user['id'].'
    AND anonymous_id = \''.$save_anonymous_id.'\'
    AND element_id IN ('.implode(',', $already_there).')
;';
         pwg_query($query);
       }

       $query = '
UPDATE '.RATE_TABLE.'
  SET anonymous_id = \'' .$anonymous_id.'\'
  WHERE user_id = '.$user['id'].'
    AND anonymous_id = \'' . $save_anonymous_id.'\'
;';
       pwg_query($query);
    } // end client changed ip

    pwg_set_cookie_var('anonymous_rater', $anonymous_id);
  } // end anonymous user

  $query = '
DELETE
  FROM '.RATE_TABLE.'
  WHERE element_id = '.$image_id.'
    AND user_id = '.$user['id'].'
';
  if ($user_anonymous)
  {
    $query.= ' AND anonymous_id = \''.$anonymous_id.'\'';
  }
  pwg_query($query);
  $query = '
INSERT
  INTO '.RATE_TABLE.'
  (user_id,anonymous_id,element_id,rate,date)
  VALUES
  ('
    .$user['id'].','
    .'\''.$anonymous_id.'\','
    .$image_id.','
    .$rate
    .',NOW())
;';
  pwg_query($query);

  return update_rating_score($image_id);
}


/**
 * Update images.rating_score field.
 * We use a bayesian average (http://en.wikipedia.org/wiki/Bayesian_average) with
 *  C = average number of rates per item
 *  m = global average rate (all rates)
 *
 * @param int|false $element_id if false applies to all
 * @return array (score, average, count) values are null if $element_id is false
*/
function update_rating_score($element_id = false)
{
  if ( ($alt_result = trigger_change('update_rating_score', false, $element_id)) !== false)
  {
    return $alt_result;
  }

  $query = '
SELECT element_id,
    COUNT(rate) AS rcount,
    SUM(rate) AS rsum
  FROM '.RATE_TABLE.'
  GROUP by element_id';

  $all_rates_count = 0;
  $all_rates_avg = 0;
  $item_ratecount_avg = 0;
  $by_item = array();

  $result = pwg_query($query);
  while ($row = pwg_db_fetch_assoc($result))
  {
    $all_rates_count += $row['rcount'];
    $all_rates_avg += $row['rsum'];
    $by_item[$row['element_id']] = $row;
  }

  if ($all_rates_count>0)
  {
    $all_rates_avg /= $all_rates_count;
    $item_ratecount_avg = $all_rates_count / count($by_item);
  }

  $updates = array();
  foreach ($by_item as $id => $rate_summary )
  {
    $score = ( $item_ratecount_avg * $all_rates_avg + $rate_summary['rsum'] ) / ($item_ratecount_avg + $rate_summary['rcount']);
    $score = round($score,2);
    if ($id==$element_id)
    {
      $return = array(
        'score' => $score,
        'average' => round($rate_summary['rsum'] / $rate_summary['rcount'], 2),
        'count' => $rate_summary['rcount'],
        );
    }
    $updates[] = array( 'id'=>$id, 'rating_score'=>$score );
  }
  mass_updates(
    IMAGES_TABLE,
    array(
      'primary' => array('id'),
      'update' => array('rating_score')
      ),
    $updates
    );

  //set to null all items with no rate
  if ( !isset($by_item[$element_id]) )
  {
    $query='
SELECT id FROM '.IMAGES_TABLE .'
  LEFT JOIN '.RATE_TABLE.' ON id=element_id
  WHERE element_id IS NULL AND rating_score IS NOT NULL';

    $to_update = array_from_query( $query, 'id');

    if ( !empty($to_update) )
    {
      $query='
UPDATE '.IMAGES_TABLE .'
  SET rating_score=NULL
  WHERE id IN (' . implode(',',$to_update) . ')';
    pwg_query($query);
    }
  }

  return isset($return) ? $return : array('score'=>null, 'average'=>null, 'count'=>0 );
}

?>