working at video comments
[living-lab-site.git] / application / models / videos_model.php
1 <?php
2
3 /**
4  * Class Videos_model models videos information from the DB
5  *
6  * @category    Model
7  * @author              Călin-Andrei Burloiu
8  */
9 class Videos_model extends CI_Model {
10         public $db = NULL;
11         
12         public function __construct()
13         {
14                 parent::__construct();
15                 
16                 if ($this->db === NULL)
17                 {
18                         $this->load->library('singleton_db');
19                         $this->db = $this->singleton_db->connect();
20                 }
21         }
22         
23         /**
24          * Retrieves a set of videos information which can be used for displaying
25          * that videos as a list with few details.
26          *
27          * @param               int $category_id        DB category ID; pass NULL for all
28          * categories
29          * @param               mixed $user                     an user_id (as int) or an username 
30          * (as string); pass NULL for all users
31          * @param               int $offset
32          * @param               int $count
33          * @param               string $ordering        control videos ording by these
34          * possibilities:
35          * <ul>
36          *   <li><strong>'hottest':</strong> newest most appreciated first. An
37          *   appreciated video is one which has a bigger
38          *   score = views + likes - dislikes.</li>
39          *   <li><strong>'newest':</strong> newest first.</li>
40          *   <li><strong>'alphabetically':</strong> sort alphabetically.</li>
41          * </ul>
42          * @return              array   a list of videos, each one being an assoc array with:
43          * <ul>
44          *   <li>id, name, title, duration, thumbs_count, default_thumb, views => from DB</li>
45          *   <li>shorted_title => ellipsized title</li>
46          *   <li>video_url => P2P-Tube video URl</li>
47          *   <li>user_id, user_name</li>
48          *   <li>thumbs => thumbnail images' URLs</li>
49          * </ul>
50          */
51         public function get_videos_summary($category_id, $user, $offset, $count,
52                 $ordering = 'hottest')
53         {
54                 $this->load->helper('text');
55                 
56                 // Ordering
57                 switch ($ordering)
58                 {
59                 case 'hottest':
60                         $order_statement = "ORDER BY date DESC, score DESC, RAND()";
61                         break;
62                 case 'newest':
63                         $order_statement = "ORDER BY date DESC";
64                         break;
65                 case 'alphabetically':
66                         $order_statement = "ORDER BY title";
67                         break;
68                         
69                 default:
70                         $order_statement = "";
71                 }
72                 
73                 // Category filtering
74                 if ($category_id === NULL)
75                         $cond_category = "1";
76                 else
77                 {
78                         $category_id = intval($category_id);
79                         $cond_category = "category_id = $category_id";
80                 }
81                 
82                 // User filtering
83                 if ($user === NULL)
84                         $cond_user = "1";
85                 else
86                 {
87                         if (is_int($user))
88                                 $cond_user = "v.user_id = $user";
89                         else if (is_string($user))
90                                 $cond_user = "u.username = '$user'";
91                 }
92                 
93                 $query = $this->db->query(
94                         "SELECT v.id, name, title, duration, user_id, u.username, views,
95                                 thumbs_count, default_thumb,
96                                 (views + likes - dislikes) AS score
97                         FROM `videos` v, `users` u
98                         WHERE v.user_id = u.id AND $cond_category AND $cond_user
99                         $order_statement
100                         LIMIT $offset, $count"); 
101                 
102                 if ($query->num_rows() > 0)
103                         $videos = $query->result_array();
104                 else
105                         return array();
106                 
107                 foreach ($videos as & $video)
108                 {
109                         // P2P-Tube Video URL
110                         $video['video_url'] = site_url(sprintf("watch/%d/%s",
111                                 $video['id'], $video['name']));
112                         
113                         // Thumbnails
114                         $video['thumbs'] = $this->get_thumbs($video['name'], 
115                                 $video['thumbs_count']);
116                                 
117                         // Ellipsized title
118                         //$video['shorted_title'] = ellipsize($video['title'], 45, 0.75);
119                         $video['shorted_title'] = character_limiter($video['title'], 50);
120                 }
121                 
122                 return $videos;
123         }
124         
125         /**
126          * Returns the number of videos from database from a specific category or
127          * user.
128          * NULL parameters count videos from all categories and / or all users.
129          * 
130          * @param int $category_id
131          * @param mixed $user   an user_id (as int) or an username (as string)
132          * @return int  number of videos or FALSE if an error occured
133          */
134         public function get_videos_count($category_id = NULL, $user = NULL)
135         {
136                 if ($category_id === NULL)
137                         $cond_category = "1";
138                 else
139                         $cond_category = "category_id = $category_id";
140                 
141                 if ($user === NULL)
142                         $cond_user = "1";
143                 else
144                 {
145                         if (is_int($user))
146                                 $cond_user = "v.user_id = $user";
147                         else if(is_string($user))
148                                 $cond_user = "u.username = '$user'";
149                 }
150                 
151                 $query = $this->db->query(
152                         "SELECT COUNT(*) count
153                         FROM `videos` v, `users` u
154                         WHERE v.user_id = u.id AND $cond_category AND $cond_user");
155                 
156                 if ($query->num_rows() > 0)
157                         return $query->row()->count;
158                 
159                 // Error
160                 return FALSE;
161         }
162         
163         /**
164          * Retrieves information about a video.
165          *
166          * If $name does not match with the video's `name` from the DB an error is
167          * marked in the key 'err'. If it's NULL it is ignored.
168          *
169          * @access              public
170          * @param               string $id      video's `id` column from `videos` DB table
171          * @param               string $name    video's `name` column from `videos` DB
172          * table. NULL means there is no name provided.
173          * @return              array   an associative list with information about a video
174          * with the following keys:
175          * <ul>
176          *   <li>all columns form DB with some exceptions that are overwritten or new</li>
177          *   <li>content is moved in assets</li>
178          *   <li>assets => list of associative lists where each one represents a</li>
179          * video asset having keys: "src", "res", "par" and "ext". Value of key
180          * "src" is the video torrent formated as
181          * {name}_{format}.{video_ext}.{default_torrent_ext}</li>
182          *   <li>username => user name from `users` table</li>
183          *   <li>category_title => a human-friendly category name</li>
184          *   <li>tags => associative list of "tag => score"</li>
185          *   <li>date => date and time when the video was created</li>
186          *   <li>thumbs => thumbnail images' URLs</li>
187          * </ul>
188          */
189         public function get_video($id, $name = NULL)
190         {
191                 $this->load->helper('video');
192                 
193                 $query = $this->db->query("SELECT v.*, u.username 
194                                                                 FROM `videos` v, `users` u
195                                                                 WHERE v.user_id = u.id AND v.id = $id");
196                 $video = array();
197                 
198                 if ($query->num_rows() > 0)
199                 {
200                         $video = $query->row_array();
201                         if ($name !== NULL && $video['name'] != $name)
202                                 $video['err'] = 'INVALID_NAME';
203                 }
204                 else
205                 {
206                         $video['err'] = 'INVALID_ID';
207                         return $video;
208                 }
209                 
210                 // Convert JSON encoded string to arrays.
211                 $video['assets'] = json_decode($video['formats'], TRUE);
212                 unset($video['formats']);
213                 $video['tags'] = json_decode($video['tags'], TRUE);
214                 asort($video['tags']);
215                 $video['tags'] = array_reverse($video['tags'], TRUE);
216                 
217                 // Sort assets by their megapixels number.
218                 function access_function($a) { return $a['res']; }
219                 function assets_cmp($a, $b) 
220                         { return megapixels_cmp($a, $b, "access_function"); }
221                 usort($video['assets'], "assets_cmp");
222                 
223                 // Torrents
224                 $video['url'] = array();
225                 foreach ($video['assets'] as & $asset)
226                 {
227                         $def = substr($asset['res'], strpos($asset['res'], 'x') + 1) . 'p';
228                         $asset['src'] = site_url('data/torrents/'. $video['name'] . '_'
229                                 . $def . '.'. $asset['ext']
230                                 . '.'. $this->config->item('default_torrent_ext'));
231                 }
232                 
233                 // Category title
234                 $categories = $this->config->item('categories');
235                 $category_name = $categories[ intval($video['category_id']) ];
236                 $video['category_title'] = $category_name ?
237                         $this->lang->line("ui_categ_$category_name") : $category_name;
238                 
239                 // Thumbnails
240                 $video['thumbs'] = $this->get_thumbs($video['name'], $video['thumbs_count']);
241                 
242                 return $video;
243         }
244         
245         /**
246          * Retrieves comments for a video.
247          * 
248          * @param int $video_id
249          * @param int $offset
250          * @param int $count
251          * @param string $ordering      control comments ording by these possibilities:
252          * <ul>
253          *   <li><strong>'hottest':</strong> newest most appreciated first. An
254          *   appreciated comment is one which has a bigger
255          *   score = likes - dislikes.</li>
256          *   <li><strong>'newest':</strong> newest first.</li>
257          * </ul>
258          * @return array        an array with comments
259          */
260         public function get_video_comments($video_id, $offset, $count,
261                         $ordering = 'newest')
262         {
263                 // Ordering
264                 switch ($ordering)
265                 {
266                 case 'newest':
267                         $order_statement = "ORDER BY time DESC";
268                         break;
269                 case 'hottest':
270                         $order_statement = "ORDER BY time DESC, score DESC";
271                         break;
272                                 
273                 default:
274                         $order_statement = "";
275                 }
276                 
277                 $query = $this->db->query(
278                         "SELECT c.*, u.username, (c.likes + c.dislikes) AS score
279                                 FROM `videos_comments` c, `users` u
280                                 WHERE c.user_id = u.id AND video_id = $video_id
281                                 $order_statement");
282                 
283                 if ($query->num_rows() == 0)
284                         return array();
285                 
286                 $comments = $query->result_array();
287                 
288                 return $comments;
289         }
290         
291         public function get_video_comments_count($video_id)
292         {
293                 $query = $this->db->query(
294                                         "SELECT COUNT(*) count
295                                                 FROM `videos_comments`
296                                                 WHERE video_id = $video_id");
297                                 
298                 if ($query->num_rows() == 0)
299                         return FALSE;
300                 
301                 return $query->row()->count;
302         }
303         
304         /**
305          * Insert in DB a comment for a video.
306          * 
307          * @param int $video_id
308          * @param int $user_id
309          * @param string $content
310          */
311         public function comment_video($video_id, $user_id, $content)
312         {
313                 return $query = $this->db->query(
314                         "INSERT INTO `videos_comments` (video_id, user_id, content, time)
315                         VALUES ($video_id, $user_id, '$content', UTC_TIMESTAMP())");
316         }
317         
318         /**
319          * Increments views count for a video.
320          * 
321          * @param int $id       DB video id
322          * @return void
323          */
324         public function inc_views($id)
325         {
326                 return $this->db->query('UPDATE `videos` '
327                                                 . 'SET `views`=`views`+1 '
328                                                 . 'WHERE id='. $id); 
329         }
330         
331         public function vote($video_id, $user_id, $like = TRUE)
332         {
333                 if ($like)
334                 {
335                         $col = 'likes';
336                         $action = 'like';
337                 }
338                 else
339                 {
340                         $col = 'dislikes';
341                         $action = 'dislike';
342                 }
343                 
344                 $query = $this->db->query("SELECT * FROM `users_actions`
345                         WHERE user_id = $user_id
346                                 AND target_id = $video_id
347                                 AND target_type = 'video'
348                                 AND action = '$action'
349                                 AND date = CURDATE()");
350                 // User already voted today
351                 if ($query->num_rows() > 0)
352                         return -1;
353                 
354                 $this->db->query("UPDATE `videos`
355                         SET $col = $col + 1
356                         WHERE id = $video_id");
357                 
358                 // Mark this action so that the user cannot repeat it today.
359                 $this->db->query("INSERT INTO `users_actions`
360                                 (user_id, action, target_type, target_id, date)
361                         VALUES ( $user_id, '$action', 'video', $video_id, CURDATE() )");
362                 
363                 $query = $this->db->query("SELECT $col FROM `videos`
364                         WHERE id = $video_id");
365                 
366                 if ($query->num_rows() === 1)
367                 {
368                         $row = $query->row_array();
369                         return $row[ $col ];
370                 }
371                 
372                 // Error
373                 return FALSE;
374         }
375         
376         public function get_thumbs($name, $count)
377         {
378                 $thumbs = array();
379                 
380                 for ($i=0; $i < $count; $i++)
381                         $thumbs[] = site_url(sprintf("data/thumbs/%s_t%02d.jpg", $name, $i));
382                 
383                 return $thumbs;
384         }
385
386         /**
387          * Searches videos in DB based on a search query string and returns an
388          * associative array of results.
389          * If count is zero the function only return the number of results.
390          * @param string $search_query
391          * @param int $offset
392          * @param int $count
393          * @param int $category_id      if NULL, all categories are searched
394          * @return array        an associative array with the same keys as that from
395          * get_videos_summary's result, but with two additional keys: 
396          * description and date.
397          */
398         public function search_videos($search_query, $offset = 0, $count = 0, 
399                                                                         $category_id = NULL)
400         {
401                 $search_query = trim($search_query);
402                 $search_query = str_replace("'", " ", $search_query);
403                 
404                 // Search word fragments.
405                 // sfc = search fragment condition
406                 $sfc = "( ";
407                 // sfr = serach fragment relevation
408                 $sfr = "( ";
409                 $sep = ' +-*<>()~"';
410                 $fragm = strtok($search_query, $sep);
411                 while ($fragm !== FALSE)
412                 {
413                         $sfc .= "(title LIKE '%$fragm%'
414                                         OR description LIKE '%$fragm%'
415                                         OR tags LIKE '%$fragm%') OR ";
416                         
417                         // Frament relevations are half of boolean relevations such
418                         // that they will appear at the end of the results.
419                         $sfr .= "0.25 * (title LIKE '%$fragm%')
420                                         + 0.1 * (description LIKE '%$fragm%')
421                                         + 0.15 * (tags LIKE '%$fragm%') + ";
422                         
423                         $fragm = strtok($sep);
424                 }
425                 $sfc = substr($sfc, 0, -4) . " )";
426                 $sfr = substr($sfr, 0, -3) . " )";
427                 
428                 if (! $this->is_advanced_search_query($search_query))
429                 {
430                         $search_cond = "MATCH (title, description, tags)
431                                         AGAINST ('$search_query') OR $sfc";
432                         $relevance = "( MATCH (title, description, tags)
433                                         AGAINST ('$search_query') + $sfr ) AS relevance";
434                 }
435                 // boolean mode
436                 else
437                 {
438                         $against = "AGAINST ('$search_query' IN BOOLEAN MODE)";
439                         $search_cond = "( MATCH (title, description, tags)
440                                         $against) OR $sfc";
441                         $relevance = "( 0.5 * (MATCH(title) $against)
442                                         + 0.3 * (MATCH(tags) $against)
443                                         + 0.2 * (MATCH(description) $against)
444                                         + $sfr) AS relevance";
445                 }
446                 
447                 if ($count === 0)
448                 {
449                         $selected_columns = "COUNT(*) count";
450                         $order = "";
451                         $limit = "";
452                 }
453                 else
454                 {
455                         // TODO select data, description if details are needed
456                         $selected_columns = "id, name, title, duration, user_id, views,
457                                         thumbs_count, default_thumb,
458                                         (views + likes - dislikes) AS score, 
459                                         $relevance";
460                         $order = "ORDER BY relevance DESC, score DESC";
461                         $limit = "LIMIT $offset, $count";
462                 }
463                 
464                 if ($category_id !== NULL)
465                         $category_cond = "category_id = '$category_id' AND ";
466                 else
467                         $category_cond = "";
468
469                 $str_query = "SELECT $selected_columns
470                         FROM `videos`
471                         WHERE  $category_cond ( $search_cond )
472                         $order
473                         $limit";
474 //              echo "<p>$str_query</p>";
475                 $query = $this->db->query($str_query);
476                 
477                 if ($query->num_rows() > 0)
478                 {
479                         if ($count === 0)
480                                 return $query->row()->count;
481                         else
482                                 $videos = $query->result_array();
483                 }
484                 else
485                         return NULL;
486                 
487                 $this->load->helper('text');
488                 
489                 foreach ($videos as & $video)
490                 {
491                         // P2P-Tube Video URL
492                         $video['video_url'] = site_url(sprintf("watch/%d/%s",
493                                 $video['id'], $video['name']));
494                         
495                         // Thumbnails
496                         $video['thumbs'] = $this->get_thumbs($video['name'], 
497                                 $video['thumbs_count']);
498                                 
499                         // Ellipsized title
500                         //$video['shorted_title'] = ellipsize($video['title'], 45, 0.75);
501                         $video['shorted_title'] = character_limiter($video['title'], 50);
502                         
503                         // TODO: user information
504                         $video['user_name'] = 'TODO';
505                 }
506                 
507                 return $videos;
508         }
509         
510         public function decode_search_query($search_query)
511         {
512                 $search_query = urldecode($search_query);
513                 
514                 $search_query = str_replace('_AST_', '*', $search_query);
515                 $search_query = str_replace('_AND_', '+', $search_query);
516                 $search_query = str_replace('_GT_', '>', $search_query);
517                 $search_query = str_replace('_LT_', '<', $search_query);
518                 $search_query = str_replace('_PO_', '(', $search_query);
519                 $search_query = str_replace('_PC_', ')', $search_query);
520                 $search_query = str_replace('_LOW_', '~', $search_query);
521                 $search_query = str_replace('_QUO_', '"', $search_query);
522                 
523                 return $search_query;
524         }
525         
526         public function encode_search_query($search_query)
527         {
528                 $search_query = str_replace('*', '_AST_', $search_query);
529                 $search_query = str_replace('+', '_AND_', $search_query);
530                 $search_query = str_replace('>', '_GT_', $search_query);
531                 $search_query = str_replace('<', '_LT_', $search_query);
532                 $search_query = str_replace('(', '_PO_', $search_query);
533                 $search_query = str_replace(')', '_PC_', $search_query);
534                 $search_query = str_replace('~', '_LOW_', $search_query);
535                 $search_query = str_replace('"', '_QUO_', $search_query);
536                 
537                 $search_query = urlencode($search_query);
538         
539                 return $search_query;
540         }
541         
542         /**
543          * Return TRUE if it contains any special caracter from an advanced search
544          * query.
545          * @param string $search_query
546          * @return boolean
547          */
548         public function is_advanced_search_query($search_query)
549         {
550                 return (preg_match('/\*|\+|\-|>|\<|\(|\)|~|"/', $search_query) == 0
551                         ? FALSE : TRUE);
552         }
553 }
554
555 /* End of file videos_model.php */
556 /* Location: ./application/models/videos_model.php */