afcfd3d93fc755654d5a3eca5d0ae24e25b559f0
[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                 $this->load->helper('text');
193                 
194                 $query = $this->db->query("SELECT v.*, u.username 
195                                                                 FROM `videos` v, `users` u
196                                                                 WHERE v.user_id = u.id AND v.id = $id");
197                 $video = array();
198                 
199                 if ($query->num_rows() > 0)
200                 {
201                         $video = $query->row_array();
202                         if ($name !== NULL && $video['name'] != $name)
203                                 $video['err'] = 'INVALID_NAME';
204                 }
205                 else
206                 {
207                         $video['err'] = 'INVALID_ID';
208                         return $video;
209                 }
210                 
211                 // Convert JSON encoded string to arrays.
212                 $video['assets'] = json_decode($video['formats'], TRUE);
213                 unset($video['formats']);
214                 $video['tags'] = json_decode($video['tags'], TRUE);
215                 asort($video['tags']);
216                 $video['tags'] = array_reverse($video['tags'], TRUE);
217                 
218                 // Sort assets by their megapixels number.
219                 function access_function($a) { return $a['res']; }
220                 function assets_cmp($a, $b) 
221                         { return megapixels_cmp($a, $b, "access_function"); }
222                 usort($video['assets'], "assets_cmp");
223                 
224                 // Torrents
225                 $video['url'] = array();
226                 foreach ($video['assets'] as & $asset)
227                 {
228                         $def = substr($asset['res'], strpos($asset['res'], 'x') + 1) . 'p';
229                         $asset['def'] = $def;
230                         $asset['src'] = site_url('data/torrents/'. $video['name'] . '_'
231                                 . $def . '.'. $asset['ext']
232                                 . '.'. $this->config->item('default_torrent_ext'));
233                 }
234                 
235                 // Category title
236                 $categories = $this->config->item('categories');
237                 $category_name = $categories[ intval($video['category_id']) ];
238                 $video['category_title'] = $category_name ?
239                         $this->lang->line("ui_categ_$category_name") : $category_name;
240                 
241                 // Thumbnails
242                 $video['thumbs'] = $this->get_thumbs($video['name'], $video['thumbs_count']);
243                 
244                 // Shorted description
245                 $video['shorted_description'] = character_limiter(
246                                 $video['description'], 128);
247                 
248                 return $video;
249         }
250         
251         /**
252          * Retrieves comments for a video.
253          * 
254          * @param int $video_id
255          * @param int $offset
256          * @param int $count
257          * @param string $ordering      control comments ording by these possibilities:
258          * <ul>
259          *   <li><strong>'hottest':</strong> newest most appreciated first. An
260          *   appreciated comment is one which has a bigger
261          *   score = likes - dislikes.</li>
262          *   <li><strong>'newest':</strong> newest first.</li>
263          * </ul>
264          * @return array        an array with comments
265          */
266         public function get_video_comments($video_id, $offset, $count,
267                         $ordering = 'newest')
268         {
269                 $this->load->helper('date');
270                 $cond_hottest = '';
271                 
272                 // Ordering
273                 switch ($ordering)
274                 {
275                 case 'newest':
276                         $order_statement = "ORDER BY time DESC";
277                         break;
278                 case 'hottest':
279                         $order_statement = "ORDER BY score DESC, time DESC";
280                         $cond_hottest = "AND c.likes + c.dislikes > 0";
281                         break;
282                                 
283                 default:
284                         $order_statement = "";
285                 }
286                 
287                 $query = $this->db->query(
288                         "SELECT c.*, u.username, u.time_zone, (c.likes + c.dislikes) AS score
289                                 FROM `videos_comments` c, `users` u
290                                 WHERE c.user_id = u.id AND video_id = $video_id $cond_hottest
291                                 $order_statement
292                                 LIMIT $offset, $count");
293                 
294                 if ($query->num_rows() == 0)
295                         return array();
296                 
297                 $comments = $query->result_array();
298                 
299                 foreach ($comments as & $comment)
300                 {
301                         $comment['local_time'] = human_gmt_to_human_local($comment['time'],
302                                 $comment['time_zone']);
303                 }
304                 
305                 return $comments;
306         }
307         
308         public function get_video_comments_count($video_id)
309         {
310                 $query = $this->db->query(
311                                         "SELECT COUNT(*) count
312                                                 FROM `videos_comments`
313                                                 WHERE video_id = $video_id");
314                                 
315                 if ($query->num_rows() == 0)
316                         return FALSE;
317                 
318                 return $query->row()->count;
319         }
320         
321         /**
322          * Insert in DB a comment for a video.
323          * 
324          * @param int $video_id
325          * @param int $user_id
326          * @param string $content
327          */
328         public function comment_video($video_id, $user_id, $content)
329         {
330                 // Prepping content.
331                 $content = substr($content, 0, 512);
332                 $content = htmlspecialchars($content);
333                 $content = nl2br($content);
334                 
335                 return $query = $this->db->query(
336                         "INSERT INTO `videos_comments` (video_id, user_id, content, time)
337                         VALUES ($video_id, $user_id, '$content', UTC_TIMESTAMP())");
338         }
339         
340         /**
341          * Increments views count for a video.
342          * 
343          * @param int $id       DB video id
344          * @return void
345          */
346         public function inc_views($id)
347         {
348                 return $this->db->query('UPDATE `videos` '
349                                                 . 'SET `views`=`views`+1 '
350                                                 . 'WHERE id='. $id); 
351         }
352         
353         public function vote($video_id, $user_id, $like = TRUE)
354         {
355                 if ($like)
356                 {
357                         $col = 'likes';
358                         $action = 'like';
359                 }
360                 else
361                 {
362                         $col = 'dislikes';
363                         $action = 'dislike';
364                 }
365                 
366                 $query = $this->db->query("SELECT * FROM `users_actions`
367                         WHERE user_id = $user_id
368                                 AND target_id = $video_id
369                                 AND target_type = 'video'
370                                 AND action = '$action'
371                                 AND date = CURDATE()");
372                 // User already voted today
373                 if ($query->num_rows() > 0)
374                         return -1;
375                 
376                 $this->db->query("UPDATE `videos`
377                         SET $col = $col + 1
378                         WHERE id = $video_id");
379                 
380                 // Mark this action so that the user cannot repeat it today.
381                 $this->db->query("INSERT INTO `users_actions`
382                                 (user_id, action, target_type, target_id, date)
383                         VALUES ( $user_id, '$action', 'video', $video_id, CURDATE() )");
384                 
385                 $query = $this->db->query("SELECT $col FROM `videos`
386                         WHERE id = $video_id");
387                 
388                 if ($query->num_rows() === 1)
389                 {
390                         $row = $query->row_array();
391                         return $row[ $col ];
392                 }
393                 
394                 // Error
395                 return FALSE;
396         }
397         
398         public function vote_comment($comment_id, $user_id, $like = TRUE)
399         {
400                 if ($like)
401                 {
402                         $col = 'likes';
403                         $action = 'like';
404                 }
405                 else
406                 {
407                         $col = 'dislikes';
408                         $action = 'dislike';
409                 }
410         
411                 $query = $this->db->query("SELECT * FROM `users_actions`
412                                 WHERE user_id = $user_id
413                                         AND target_id = $comment_id
414                                         AND target_type = 'vcomment'
415                                         AND action = '$action'
416                                         AND date = CURDATE()");
417                 // User already voted today
418                 if ($query->num_rows() > 0)
419                         return -1;
420         
421                 $this->db->query("UPDATE `videos_comments`
422                                 SET $col = $col + 1
423                                 WHERE id = $comment_id");
424         
425                 // Mark this action so that the user cannot repeat it today.
426                 $this->db->query("INSERT INTO `users_actions`
427                                         (user_id, action, target_type, target_id, date)
428                                 VALUES ( $user_id, '$action', 'vcomment', $comment_id, CURDATE() )");
429         
430                 $query = $this->db->query("SELECT $col FROM `videos_comments`
431                                 WHERE id = $comment_id");
432         
433                 if ($query->num_rows() === 1)
434                 {
435                         $row = $query->row_array();
436                         return $row[ $col ];
437                 }
438         
439                 // Error
440                 return FALSE;
441         }
442         
443         public function get_thumbs($name, $count)
444         {
445                 $thumbs = array();
446                 
447                 for ($i=0; $i < $count; $i++)
448                         $thumbs[] = site_url(sprintf("data/thumbs/%s_t%02d.jpg", $name, $i));
449                 
450                 return $thumbs;
451         }
452
453         /**
454          * Searches videos in DB based on a search query string and returns an
455          * associative array of results.
456          * If count is zero the function only return the number of results.
457          * @param string $search_query
458          * @param int $offset
459          * @param int $count
460          * @param int $category_id      if NULL, all categories are searched
461          * @return array        an associative array with the same keys as that from
462          * get_videos_summary's result, but with two additional keys: 
463          * description and date.
464          */
465         public function search_videos($search_query, $offset = 0, $count = 0, 
466                                                                         $category_id = NULL)
467         {
468                 $search_query = trim($search_query);
469                 $search_query = str_replace("'", " ", $search_query);
470                 
471                 // Search word fragments.
472                 // sfc = search fragment condition
473                 $sfc = "( ";
474                 // sfr = search fragment relevance
475                 $sfr = "( ";
476                 $sep = ' +-*<>()~"';
477                 $fragm = strtok($search_query, $sep);
478                 while ($fragm !== FALSE)
479                 {
480                         $sfc .= "(title LIKE '%$fragm%'
481                                         OR description LIKE '%$fragm%'
482                                         OR tags LIKE '%$fragm%') OR ";
483                         
484                         // Frament relevances are half of boolean relevances such
485                         // that they will appear at the end of the results.
486                         $sfr .= "0.25 * (title LIKE '%$fragm%')
487                                         + 0.1 * (description LIKE '%$fragm%')
488                                         + 0.15 * (tags LIKE '%$fragm%') + ";
489                         
490                         $fragm = strtok($sep);
491                 }
492                 $sfc = substr($sfc, 0, -4) . " )";
493                 $sfr = substr($sfr, 0, -3) . " )";
494                 
495                 if (! $this->is_advanced_search_query($search_query))
496                 {
497                         $search_cond = "MATCH (title, description, tags)
498                                         AGAINST ('$search_query') OR $sfc";
499                         $relevance = "( MATCH (title, description, tags)
500                                         AGAINST ('$search_query') + $sfr ) AS relevance";
501                 }
502                 // boolean mode
503                 else
504                 {
505                         $against = "AGAINST ('$search_query' IN BOOLEAN MODE)";
506                         $search_cond = "( MATCH (title, description, tags)
507                                         $against) OR $sfc";
508                         $relevance = "( 0.5 * (MATCH(title) $against)
509                                         + 0.3 * (MATCH(tags) $against)
510                                         + 0.2 * (MATCH(description) $against)
511                                         + $sfr) AS relevance";
512                 }
513                 
514                 if ($count === 0)
515                 {
516                         $selected_columns = "COUNT(*) count";
517                         $order = "";
518                         $limit = "";
519                 }
520                 else
521                 {
522                         // TODO select data, description if details are needed
523                         $selected_columns = "v.id, name, title, duration, user_id, views,
524                                         thumbs_count, default_thumb, u.username,
525                                         (views + likes - dislikes) AS score, 
526                                         $relevance";
527                         $order = "ORDER BY relevance DESC, score DESC";
528                         $limit = "LIMIT $offset, $count";
529                 }
530                 
531                 if ($category_id !== NULL)
532                         $category_cond = "category_id = '$category_id' AND ";
533                 else
534                         $category_cond = "";
535
536                 $str_query = "SELECT $selected_columns
537                         FROM `videos` v, `users` u
538                         WHERE  v.user_id = u.id AND $category_cond ( $search_cond )
539                         $order
540                         $limit";
541 //              echo "<p>$str_query</p>";
542                 $query = $this->db->query($str_query);
543                 
544                 if ($query->num_rows() > 0)
545                 {
546                         if ($count === 0)
547                                 return $query->row()->count;
548                         else
549                                 $videos = $query->result_array();
550                 }
551                 else
552                         return NULL;
553                 
554                 $this->load->helper('text');
555                 
556                 foreach ($videos as & $video)
557                 {
558                         // P2P-Tube Video URL
559                         $video['video_url'] = site_url(sprintf("watch/%d/%s",
560                                 $video['id'], $video['name']));
561                         
562                         // Thumbnails
563                         $video['thumbs'] = $this->get_thumbs($video['name'], 
564                                 $video['thumbs_count']);
565                                 
566                         // Ellipsized title
567                         //$video['shorted_title'] = ellipsize($video['title'], 45, 0.75);
568                         $video['shorted_title'] = character_limiter($video['title'], 50);
569                         
570                         // TODO: user information
571                         $video['user_name'] = 'TODO';
572                 }
573                 
574                 return $videos;
575         }
576         
577         public function decode_search_query($search_query)
578         {
579                 $search_query = urldecode($search_query);
580                 
581                 $search_query = str_replace('_AST_', '*', $search_query);
582                 $search_query = str_replace('_AND_', '+', $search_query);
583                 $search_query = str_replace('_GT_', '>', $search_query);
584                 $search_query = str_replace('_LT_', '<', $search_query);
585                 $search_query = str_replace('_PO_', '(', $search_query);
586                 $search_query = str_replace('_PC_', ')', $search_query);
587                 $search_query = str_replace('_LOW_', '~', $search_query);
588                 $search_query = str_replace('_QUO_', '"', $search_query);
589                 
590                 return $search_query;
591         }
592         
593         public function encode_search_query($search_query)
594         {
595                 $search_query = str_replace('*', '_AST_', $search_query);
596                 $search_query = str_replace('+', '_AND_', $search_query);
597                 $search_query = str_replace('>', '_GT_', $search_query);
598                 $search_query = str_replace('<', '_LT_', $search_query);
599                 $search_query = str_replace('(', '_PO_', $search_query);
600                 $search_query = str_replace(')', '_PC_', $search_query);
601                 $search_query = str_replace('~', '_LOW_', $search_query);
602                 $search_query = str_replace('"', '_QUO_', $search_query);
603                 
604                 $search_query = urlencode($search_query);
605         
606                 return $search_query;
607         }
608         
609         /**
610          * Return TRUE if it contains any special caracter from an advanced search
611          * query.
612          * @param string $search_query
613          * @return boolean
614          */
615         public function is_advanced_search_query($search_query)
616         {
617                 return (preg_match('/\*|\+|\-|>|\<|\(|\)|~|"/', $search_query) == 0
618                         ? FALSE : TRUE);
619         }
620 }
621
622 /* End of file videos_model.php */
623 /* Location: ./application/models/videos_model.php */