File: rating.inc.php

package info (click to toggle)
zoph 1.4-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 16,632 kB
  • sloc: php: 28,044; javascript: 10,435; sql: 527; sh: 153; makefile: 4
file content (346 lines) | stat: -rw-r--r-- 10,858 bytes parent folder | download
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
<?php
/**
 * Rating for a photo
 *
 * This file is part of Zoph.
 *
 * Zoph 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; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Zoph 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 Zoph; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @author Jeroen Roos
 * @package Zoph
 */

use db\select;
use db\param;
use db\db;
use db\clause;
use db\selectHelper;

use template\block;
use template\template;
use zoph\app;

/**
 * Photo ratings
 * @author Jeroen Roos
 * @package Zoph
 */
class rating extends zophTable {

    /** @var string The name of the database table */
    protected static $tableName="photo_ratings";
    /** @var array List of primary keys */
    protected static $primaryKeys=array("rating_id");
    /** @var array Fields that may not be empty */
    protected static $notNull=array("photo_id", "rating", "user_id");
    /** @var bool keep keys with insert. In most cases the keys are set by
                  the db with auto_increment */
    protected static $keepKeys = false;
    /** @var string URL for this class */
    protected static $url="rating?rating_id=";

    /**
     * Retrieve ratings from the database
     * @param photo photo to get ratings for
     * @param user user to get ratings for
     * @return rating rating object
     */
    public static function getRatings(photo $photo = null, user $user = null) {
        $constraints=array();

        if ($photo instanceof photo) {
            $constraints["photo_id"] = (int) $photo->getId();
        }

        if ($user instanceof user) {
            $constraints["user_id"] = (int) $user->getId();
            if ($user->get("allow_multirating")) {
                // This user is allowed to rate the same photoe  multiple
                // times, however we will allow only one from the same IP
                $constraints["ipaddress"] = e($_SERVER["REMOTE_ADDR"]);
            }
        }

        return static::getRecords(null, $constraints);
     }

    /**
     * Get average rating for a photo
     * @param photo photo to get rating for
     * @return float average rating
     */
    public static function getAverage(photo $photo) {
        $qry=new select(array("pr" => "photo_ratings"));
        $qry->addFunction(array("average"=>"AVG(rating)"));
        $qry->where(new clause("photo_id=:photoid"));
        $qry->addParam(new param(":photoid", (int) $photo->getId(), PDO::PARAM_INT));
        $qry->addGroupBy("photo_id");

        try {
            $result = db::query($qry);
            $row = $result->fetch(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            log::msg("Rating recalculation failed", log::FATAL, log::DB);
        }

        if ($row === false) {
            $avg = null;
        } else {
            $avg = (round(100 * $row["average"])) / 100.0;
        }

        // Not sure if this still needed
        if ($avg == 0) {
            $avg = null;
        }

        return $avg;

     }

    /**
     * Get the user who made this rating
     * @return user user
     */
    public function getUser() {
        $user=new user($this->get("user_id"));
        $user->lookup();
        return $user;
     }

    /**
     * Add a new rating to the database
     * @param int rating
     * @param photo Photo to rate
     */
    public static function setRating($rating, photo $photo) {
        if ((int) $rating === 0) {
            return;
        }
        $user=user::getCurrent();
        $user->lookup();

        if (!($user->isAdmin() || $user->get("allow_rating"))) {
            return;
        }

        if (isset($_SERVER["REMOTE_ADDR"])) {
            $ip = e($_SERVER["REMOTE_ADDR"]);
        } else {
            // For CLI access
            $host = gethostname();
            $ip = e(gethostbyname($host));
        }

        $currentRatings=static::getRatings($photo, $user);

        if (sizeof($currentRatings) > 0) {
            $curRating=array_pop($currentRatings);

            $curRating->set("rating", (int) $rating);
            $curRating->set("ipaddress", $ip);
            $curRating->update();
        } else {
            $newRating=new rating();
            $newRating->set("photo_id", (int) $photo->getId());
            $newRating->set("user_id", (int) $user->getId());
            $newRating->set("rating", (int) $rating);
            $newRating->set("ipaddress", $ip);
            $newRating->insert();
        }
    }
    /**
     * Get details about rating for a specific photo
     * @param photo photo to get details for
     * @return block template block to display details
     */
    public static function getDetails(photo $photo) {
        $rating=static::getAverage($photo);

        $ratings=static::getRatings($photo);

        return new block("rating_details", array(
            "rating" => $rating,
            "ratings" => $ratings,
            "photo_id" => $photo->getId()
        ));
    }

    /**
     * Get array that shows the distribution of ratings
     * @return array array of rating => count pairs;
     */
    public static function getPhotoCount() {
        $subqry=new select(array("p" => "photos"));
        $subqry->addFields(array("photo_id"));
        $subqry->addFunction(array("rating" => "FLOOR(AVG(pr.rating)+0.5)"));
        $subqry->join(array("pr" => "photo_ratings"), "p.photo_id = pr.photo_id", "LEFT");
        $subqry->addGroupBy("p.photo_id");

        $subqry=selectHelper::expandQueryForUser($subqry);

        $qry=new select(array("avg_rating" => $subqry));
        $qry->addFields(array("rating"));
        $qry->addFunction(array("count"=>"COUNT(*)"));
        $qry->addGroupBy("rating");
        $qry->addOrder("rating");

        try {
            $result = db::query($qry);
        } catch (PDOException $e) {
            log::msg("Rating grouping failed", log::FATAL, log::DB);
        }

        $ratings=array_fill(0, 11, 0);
        while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
            $rating=(int) $row["rating"];
            $ratings[$rating]=(int) $row["count"];
        }
        return $ratings;
    }

    /**
     * Get array that shows the distribution of ratings
     * as given by a specific user
     * @param user the user to get count for
     * @return array array of rating => count pairs;
     */
    public static function getPhotoCountForUser(user $user) {
        $qry = new select(array("pr" => "photo_ratings"));
        $qry->addFunction(array(
            "rating"    => "ROUND(rating)",
            "count"     => "COUNT(*)"
        ));

        $qry->where(new clause("user_id=:userid"));
        $qry->addParam(new param(":userid", (int) $user->getId(), PDO::PARAM_INT));
        $qry->addGroupBy("ROUND(rating)");
        $qry->addOrder("ROUND(rating)");

        try {
            $result = db::query($qry);
        } catch (PDOException $e) {
            log::msg("Rating grouping failed", log::FATAL, log::DB);
        }
        $ratings=array_fill(1, 10, 0);
        while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
            $rating=(int) $row["rating"];
            $ratings[$rating]=(int) $row["count"];
        }
        return $ratings;
    }

    /**
     * Turn the array from `getPhotoCountForUser()` into
     * an array that can be fed to the bar_graph template
     * @param user user to create graph for
     * @return array graph array
     */
    public static function getGraphArrayForUser(user $user) {
        $ratings=static::getPhotoCountForUser($user);
        $max = max($ratings);
        if ($max == 0) {
            // no ratings
            $max=100;
        }

        $link=array(
            "_action" => translate("search"),
            "_userrating_user" => (int) $user->getId()
        );


        foreach ($ratings as $rating => $count) {
            $graph[$rating]=array(
                "count" => (int) $count,
                "width" => round($count / $max * 100, 2),
                "value" => (int) $rating
            );

            if ($count > 0) {
                $link["userrating"]=$rating;
                $graph[$rating]["link"]=app::getBasePath() . "photos?" . http_build_query($link);
            }
        }
        return $graph;
    }


    /**
     * Turn array from `getPhotoCount()` into an array that
     * can be fed to the template
     * @return array graph array
     */
    public static function getGraphArray() {
        $ratings=static::getPhotoCount();
        $max = max($ratings);
        if ($max == 0) {
            // no ratings
            $max=100;
        }

        $link=array(
            "_rating_op" => array(">=","<"),
            "_action" => translate("search")
        );


        foreach ($ratings as $rating => $count) {
            $graph[$rating]=array(
                "count" => (int) $count,
                "width" => round($count / $max * 100, 2),
                "value" => (int) $rating
            );

            if ($count > 0) {
                if ($rating == 0) {
                    $graph[0]["link"] = app::getBasePath() . "photos?rating=null";
                    $graph[0]["value"] = translate("not rated");
                } else {
                    $link["rating"]=array($rating - 0.5, $rating + 0.5);
                    $graph[$rating]["link"]=app::getBasePath() . "photos?" . http_build_query($link);
                }
            }
        }

        return $graph;

    }

    /**
     * Create a dropdown to select ratings
     * @param string name
     * @param int value to make 'selected'
     * @return block dropdown template block
     */
    public static function createDropdown($name = "rating", $val = null) {
        $ratingArray = array(
            "1" => translate("1 - close your eyes", 0),
            "2" => translate("2", 0),
            "3" => translate("3", 0),
            "4" => translate("4", 0),
            "5" => translate("5 - so so", 0),
            "6" => translate("6", 0),
            "7" => translate("7", 0),
            "8" => translate("8", 0),
            "9" => translate("9", 0),
            "10" => translate("10 - museum", 0)
        );
        if (empty($val)) {
            $ratingArray = array("0" => translate("not rated", 0)) + $ratingArray;
        }

        return template::createDropdown($name, $val, $ratingArray, false, "zRating.ratingButton(\"ratingsubmit\", \"rating\")");
    }
}