uploading works, but AV info is not automatically detected and video activation featu...
[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          * Adds a new uploaded video to the DB.
253          * 
254          * @param string $name
255          * @param string $title
256          * @param string $description
257          * @param string $tags comma separated tags
258          * @param string $duration video duration formatted [HH:]mm:ss
259          * @param array $formats a dictionary corresponding to `formats` JSON
260          * column from `videos` table
261          * @param int $category_id
262          * @param int $user_id
263          * @return mixed returns an activation code on success or FALSE otherwise
264          */
265         public function add_video($name, $title, $description, $tags, $duration,
266                         $formats, $category_id, $user_id)
267         {
268                 // Tags.
269                 $json_tags = array();
270                 $tok = strtok($tags, ',');
271                 while ($tok != FALSE)
272                 {
273                         $json_tags[trim($tok)] = 0;
274                         
275                         $tok = strtok(',');
276                 }
277                 $json_tags = json_encode($json_tags);
278                 
279                 // TODO formats
280                 $json_formats = json_encode($formats);
281                 
282                 $query = $this->db->query("INSERT INTO `videos`
283                                 (name, title, description, duration, formats, category_id,
284                                                 user_id, tags, date)
285                                 VALUES ('$name', '$title', '$description', '$duration',
286                                                 '$json_formats', $category_id,
287                                                 $user_id, '$json_tags', utc_timestamp())");
288                 if ($query === FALSE)
289                         return FALSE;
290                 
291                 // Find out the id of the new video added.
292                 $query = $this->db->query("SELECT id from `videos`
293                                 WHERE name = '$name'");
294                 if ($query->num_rows() === 0)
295                         return FALSE;
296                 $video_id = $query->row()->id;
297                 
298                 // Activation code.
299                 $activation_code = Videos_model::gen_activation_code();
300                 
301                 $query = $this->db->query("INSERT INTO `videos_unactivated`
302                                 (video_id, activation_code)
303                                 VALUES ($video_id, '$activation_code')");
304                 
305                 return $activation_code;
306         }
307         
308         /**
309          * Retrieves comments for a video.
310          * 
311          * @param int $video_id
312          * @param int $offset
313          * @param int $count
314          * @param string $ordering      control comments ording by these possibilities:
315          * <ul>
316          *   <li><strong>'hottest':</strong> newest most appreciated first. An
317          *   appreciated comment is one which has a bigger
318          *   score = likes - dislikes.</li>
319          *   <li><strong>'newest':</strong> newest first.</li>
320          * </ul>
321          * @return array        an array with comments
322          */
323         public function get_video_comments($video_id, $offset, $count,
324                         $ordering = 'newest')
325         {
326                 $this->load->helper('date');
327                 $cond_hottest = '';
328                 
329                 // Ordering
330                 switch ($ordering)
331                 {
332                 case 'newest':
333                         $order_statement = "ORDER BY time DESC";
334                         break;
335                 case 'hottest':
336                         $order_statement = "ORDER BY score DESC, time DESC";
337                         $cond_hottest = "AND c.likes + c.dislikes > 0";
338                         break;
339                                 
340                 default:
341                         $order_statement = "";
342                 }
343                 
344                 $query = $this->db->query(
345                         "SELECT c.*, u.username, u.time_zone, (c.likes + c.dislikes) AS score
346                                 FROM `videos_comments` c, `users` u
347                                 WHERE c.user_id = u.id AND video_id = $video_id $cond_hottest
348                                 $order_statement
349                                 LIMIT $offset, $count");
350                 
351                 if ($query->num_rows() == 0)
352                         return array();
353                 
354                 $comments = $query->result_array();
355                 
356                 foreach ($comments as & $comment)
357                 {
358                         $comment['local_time'] = human_gmt_to_human_local($comment['time'],
359                                 $comment['time_zone']);
360                 }
361                 
362                 return $comments;
363         }
364         
365         public function get_video_comments_count($video_id)
366         {
367                 $query = $this->db->query(
368                                         "SELECT COUNT(*) count
369                                                 FROM `videos_comments`
370                                                 WHERE video_id = $video_id");
371                                 
372                 if ($query->num_rows() == 0)
373                         return FALSE;
374                 
375                 return $query->row()->count;
376         }
377         
378         /**
379          * Insert in DB a comment for a video.
380          * 
381          * @param int $video_id
382          * @param int $user_id
383          * @param string $content
384          */
385         public function comment_video($video_id, $user_id, $content)
386         {
387                 // Prepping content.
388                 $content = substr($content, 0, 512);
389                 $content = htmlspecialchars($content);
390                 $content = nl2br($content);
391                 
392                 return $query = $this->db->query(
393                         "INSERT INTO `videos_comments` (video_id, user_id, content, time)
394                         VALUES ($video_id, $user_id, '$content', UTC_TIMESTAMP())");
395         }
396         
397         /**
398          * Increments views count for a video.
399          * 
400          * @param int $id       DB video id
401          * @return void
402          */
403         public function inc_views($id)
404         {
405                 return $this->db->query('UPDATE `videos` '
406                                                 . 'SET `views`=`views`+1 '
407                                                 . 'WHERE id='. $id); 
408         }
409         
410         public function vote($video_id, $user_id, $like = TRUE)
411         {
412                 if ($like)
413                 {
414                         $col = 'likes';
415                         $action = 'like';
416                 }
417                 else
418                 {
419                         $col = 'dislikes';
420                         $action = 'dislike';
421                 }
422                 
423                 $query = $this->db->query("SELECT * FROM `users_actions`
424                         WHERE user_id = $user_id
425                                 AND target_id = $video_id
426                                 AND target_type = 'video'
427                                 AND action = '$action'
428                                 AND date = CURDATE()");
429                 // User already voted today
430                 if ($query->num_rows() > 0)
431                         return -1;
432                 
433                 $this->db->query("UPDATE `videos`
434                         SET $col = $col + 1
435                         WHERE id = $video_id");
436                 
437                 // Mark this action so that the user cannot repeat it today.
438                 $this->db->query("INSERT INTO `users_actions`
439                                 (user_id, action, target_type, target_id, date)
440                         VALUES ( $user_id, '$action', 'video', $video_id, CURDATE() )");
441                 
442                 $query = $this->db->query("SELECT $col FROM `videos`
443                         WHERE id = $video_id");
444                 
445                 if ($query->num_rows() === 1)
446                 {
447                         $row = $query->row_array();
448                         return $row[ $col ];
449                 }
450                 
451                 // Error
452                 return FALSE;
453         }
454         
455         public function vote_comment($comment_id, $user_id, $like = TRUE)
456         {
457                 if ($like)
458                 {
459                         $col = 'likes';
460                         $action = 'like';
461                 }
462                 else
463                 {
464                         $col = 'dislikes';
465                         $action = 'dislike';
466                 }
467         
468                 $query = $this->db->query("SELECT * FROM `users_actions`
469                                 WHERE user_id = $user_id
470                                         AND target_id = $comment_id
471                                         AND target_type = 'vcomment'
472                                         AND action = '$action'
473                                         AND date = CURDATE()");
474                 // User already voted today
475                 if ($query->num_rows() > 0)
476                         return -1;
477         
478                 $this->db->query("UPDATE `videos_comments`
479                                 SET $col = $col + 1
480                                 WHERE id = $comment_id");
481         
482                 // Mark this action so that the user cannot repeat it today.
483                 $this->db->query("INSERT INTO `users_actions`
484                                         (user_id, action, target_type, target_id, date)
485                                 VALUES ( $user_id, '$action', 'vcomment', $comment_id, CURDATE() )");
486         
487                 $query = $this->db->query("SELECT $col FROM `videos_comments`
488                                 WHERE id = $comment_id");
489         
490                 if ($query->num_rows() === 1)
491                 {
492                         $row = $query->row_array();
493                         return $row[ $col ];
494                 }
495         
496                 // Error
497                 return FALSE;
498         }
499         
500         public function get_thumbs($name, $count)
501         {
502                 $thumbs = array();
503                 
504                 for ($i=0; $i < $count; $i++)
505                         $thumbs[] = site_url(sprintf("data/thumbs/%s_t%02d.jpg", $name, $i));
506                 
507                 return $thumbs;
508         }
509
510         /**
511          * Searches videos in DB based on a search query string and returns an
512          * associative array of results.
513          * If count is zero the function only return the number of results.
514          * @param string $search_query
515          * @param int $offset
516          * @param int $count
517          * @param int $category_id      if NULL, all categories are searched
518          * @return array        an associative array with the same keys as that from
519          * get_videos_summary's result, but with two additional keys: 
520          * description and date.
521          */
522         public function search_videos($search_query, $offset = 0, $count = 0, 
523                                                                         $category_id = NULL)
524         {
525                 $search_query = trim($search_query);
526                 $search_query = str_replace("'", " ", $search_query);
527                 
528                 // Search word fragments.
529                 // sfc = search fragment condition
530                 $sfc = "( ";
531                 // sfr = search fragment relevance
532                 $sfr = "( ";
533                 $sep = ' +-*<>()~"';
534                 $fragm = strtok($search_query, $sep);
535                 while ($fragm !== FALSE)
536                 {
537                         $sfc .= "(title LIKE '%$fragm%'
538                                         OR description LIKE '%$fragm%'
539                                         OR tags LIKE '%$fragm%') OR ";
540                         
541                         // Frament relevances are half of boolean relevances such
542                         // that they will appear at the end of the results.
543                         $sfr .= "0.25 * (title LIKE '%$fragm%')
544                                         + 0.1 * (description LIKE '%$fragm%')
545                                         + 0.15 * (tags LIKE '%$fragm%') + ";
546                         
547                         $fragm = strtok($sep);
548                 }
549                 $sfc = substr($sfc, 0, -4) . " )";
550                 $sfr = substr($sfr, 0, -3) . " )";
551                 
552                 if (! $this->is_advanced_search_query($search_query))
553                 {
554                         $search_cond = "MATCH (title, description, tags)
555                                         AGAINST ('$search_query') OR $sfc";
556                         $relevance = "( MATCH (title, description, tags)
557                                         AGAINST ('$search_query') + $sfr ) AS relevance";
558                 }
559                 // boolean mode
560                 else
561                 {
562                         $against = "AGAINST ('$search_query' IN BOOLEAN MODE)";
563                         $search_cond = "( MATCH (title, description, tags)
564                                         $against) OR $sfc";
565                         $relevance = "( 0.5 * (MATCH(title) $against)
566                                         + 0.3 * (MATCH(tags) $against)
567                                         + 0.2 * (MATCH(description) $against)
568                                         + $sfr) AS relevance";
569                 }
570                 
571                 if ($count === 0)
572                 {
573                         $selected_columns = "COUNT(*) count";
574                         $order = "";
575                         $limit = "";
576                 }
577                 else
578                 {
579                         // TODO select data, description if details are needed
580                         $selected_columns = "v.id, name, title, duration, user_id, views,
581                                         thumbs_count, default_thumb, u.username,
582                                         (views + likes - dislikes) AS score, 
583                                         $relevance";
584                         $order = "ORDER BY relevance DESC, score DESC";
585                         $limit = "LIMIT $offset, $count";
586                 }
587                 
588                 if ($category_id !== NULL)
589                         $category_cond = "category_id = '$category_id' AND ";
590                 else
591                         $category_cond = "";
592
593                 $str_query = "SELECT $selected_columns
594                         FROM `videos` v, `users` u
595                         WHERE  v.user_id = u.id AND $category_cond ( $search_cond )
596                         $order
597                         $limit";
598 //              echo "<p>$str_query</p>";
599                 $query = $this->db->query($str_query);
600                 
601                 if ($query->num_rows() > 0)
602                 {
603                         if ($count === 0)
604                                 return $query->row()->count;
605                         else
606                                 $videos = $query->result_array();
607                 }
608                 else
609                         return NULL;
610                 
611                 $this->load->helper('text');
612                 
613                 foreach ($videos as & $video)
614                 {
615                         // P2P-Tube Video URL
616                         $video['video_url'] = site_url(sprintf("watch/%d/%s",
617                                 $video['id'], $video['name']));
618                         
619                         // Thumbnails
620                         $video['thumbs'] = $this->get_thumbs($video['name'], 
621                                 $video['thumbs_count']);
622                                 
623                         // Ellipsized title
624                         //$video['shorted_title'] = ellipsize($video['title'], 45, 0.75);
625                         $video['shorted_title'] = character_limiter($video['title'], 50);
626                         
627                         // TODO: user information
628                         $video['user_name'] = 'TODO';
629                 }
630                 
631                 return $videos;
632         }
633         
634         public function decode_search_query($search_query)
635         {
636                 $search_query = urldecode($search_query);
637                 
638                 $search_query = str_replace('_AST_', '*', $search_query);
639                 $search_query = str_replace('_AND_', '+', $search_query);
640                 $search_query = str_replace('_GT_', '>', $search_query);
641                 $search_query = str_replace('_LT_', '<', $search_query);
642                 $search_query = str_replace('_PO_', '(', $search_query);
643                 $search_query = str_replace('_PC_', ')', $search_query);
644                 $search_query = str_replace('_LOW_', '~', $search_query);
645                 $search_query = str_replace('_QUO_', '"', $search_query);
646                 
647                 return $search_query;
648         }
649         
650         public function encode_search_query($search_query)
651         {
652                 $search_query = str_replace('*', '_AST_', $search_query);
653                 $search_query = str_replace('+', '_AND_', $search_query);
654                 $search_query = str_replace('>', '_GT_', $search_query);
655                 $search_query = str_replace('<', '_LT_', $search_query);
656                 $search_query = str_replace('(', '_PO_', $search_query);
657                 $search_query = str_replace(')', '_PC_', $search_query);
658                 $search_query = str_replace('~', '_LOW_', $search_query);
659                 $search_query = str_replace('"', '_QUO_', $search_query);
660                 
661                 $search_query = urlencode($search_query);
662         
663                 return $search_query;
664         }
665         
666         /**
667          * Return TRUE if it contains any special caracter from an advanced search
668          * query.
669          * @param string $search_query
670          * @return boolean
671          */
672         public function is_advanced_search_query($search_query)
673         {
674                 return (preg_match('/\*|\+|\-|>|\<|\(|\)|~|"/', $search_query) == 0
675                         ? FALSE : TRUE);
676         }
677         
678         public static function gen_activation_code()
679         {
680                 $ci =& get_instance();
681                 
682                 $activation_code = substr(
683                         sha1($ci->config->item('encryption_key')
684                                 . mt_rand()),
685                         0,
686                         16);
687                 
688                 return $activation_code;
689         }
690 }
691
692 /* End of file videos_model.php */
693 /* Location: ./application/models/videos_model.php */