4 * Class Videos_model models videos information from the DB
7 * @author Călin-Andrei Burloiu
9 class Videos_model extends CI_Model {
12 public function __construct()
14 parent::__construct();
16 if ($this->db === NULL)
18 $this->load->library('singleton_db');
19 $this->db = $this->singleton_db->connect();
24 * Retrieves a set of videos information which can be used for displaying
25 * that videos as a list with few details.
27 * @param int $category_id DB category ID; pass NULL for all
29 * @param mixed $user an user_id (as int) or an username
30 * (as string); pass NULL for all users
32 * @param int $count number of videos to retrieve; if set to TRUE this
33 * method will retrieve the number of videos that satisfy condition
34 * @param string $ordering control videos ording by these
37 * <li><strong>'hottest':</strong> newest most appreciated first. An
38 * appreciated video is one which has a bigger
39 * score = views + likes - dislikes.</li>
40 * <li><strong>'newest':</strong> newest first.</li>
41 * <li><strong>'alphabetically':</strong> sort alphabetically.</li>
43 * @param bool $unactivated whether to retrieve or not ingested unactivated
44 * videos; typically only administrators should see this kind of assets
45 * @return array a list of videos, each one being an assoc array with:
47 * <li>id, name, title, duration, thumbs_count, default_thumb, views => from DB</li>
48 * <li>shorted_title => ellipsized title</li>
49 * <li>video_url => P2P-Tube video URl</li>
50 * <li>user_id, user_name</li>
51 * <li>thumbs => thumbnail images' URLs</li>
54 public function get_videos_summary($category_id, $user, $offset, $count,
55 $ordering = 'hottest', $unactivated = FALSE)
57 $this->load->helper('text');
59 $order_statement = "";
66 $order_statement = "ORDER BY date DESC, score DESC, RAND()";
69 $order_statement = "ORDER BY date DESC";
71 case 'alphabetically':
72 $order_statement = "ORDER BY title";
76 $order_statement = "";
80 // Show unactivated videos.
81 $cond_unactivated = ($unactivated
82 ? '(a.activation_code IS NULL OR a.activation_code IS NOT NULL
83 AND a.content_ingested = 1)'
84 : 'a.activation_code IS NULL');
87 if ($category_id === NULL)
91 $category_id = intval($category_id);
92 $cond_category = "category_id = $category_id";
101 $cond_user = "v.user_id = $user";
102 else if (is_string($user))
103 $cond_user = "u.username = '$user'";
107 $fields = "COUNT(*) count";
109 $fields = "v.id, name, title, duration, user_id, u.username, views,
110 thumbs_count, default_thumb,
111 (views + likes - dislikes) AS score,
112 a.activation_code, a.content_ingested";
114 $query = $this->db->query(
117 LEFT JOIN `videos_unactivated` a ON (id = a.video_id),
119 WHERE v.user_id = u.id AND $cond_category AND $cond_user
120 AND $cond_unactivated
122 LIMIT $offset, $count");
124 if ($query->num_rows() > 0)
127 return $query->row()->count;
129 $videos = $query->result_array();
134 foreach ($videos as & $video)
136 // P2P-Tube Video URL
137 $video['video_url'] = site_url(sprintf("watch/%d/%s",
138 $video['id'], $video['name']));
141 $video['thumbs'] = $this->get_thumbs($video['name'],
142 $video['thumbs_count']);
145 //$video['shorted_title'] = ellipsize($video['title'], 45, 0.75);
146 $video['shorted_title'] = character_limiter($video['title'], 50);
153 * Returns the number of videos from database from a specific category or
155 * NULL parameters count videos from all categories and / or all users.
157 * @param int $category_id
158 * @param mixed $user an user_id (as int) or an username (as string)
159 * @return int number of videos or FALSE if an error occured
161 public function get_videos_count($category_id = NULL, $user = NULL,
162 $unactivated = FALSE)
164 return $this->get_videos_summary($category_id, $user, 0, TRUE, NULL,
169 * Retrieves information about a video.
171 * If $name does not match with the video's `name` from the DB an error is
172 * marked in the key 'err'. If it's NULL it is ignored.
175 * @param string $id video's `id` column from `videos` DB table
176 * @param string $name video's `name` column from `videos` DB
177 * table. NULL means there is no name provided.
178 * @return array an associative list with information about a video
179 * with the following keys:
181 * <li>all columns form DB with some exceptions that are overwritten or new</li>
182 * <li>content is moved in assets</li>
183 * <li>assets => list of associative lists where each one represents a</li>
184 * video asset having keys: "src", "res", "par" and "ext". Value of key
185 * "src" is the video torrent formated as
186 * {name}_{format}.{video_ext}.{default_torrent_ext}</li>
187 * <li>username => user name from `users` table</li>
188 * <li>category_title => a human-friendly category name</li>
189 * <li>tags => associative list of "tag => score"</li>
190 * <li>date => date and time when the video was created</li>
191 * <li>thumbs => thumbnail images' URLs</li>
194 public function get_video($id, $name = NULL)
196 $this->load->helper('video');
197 $this->load->helper('text');
199 $query = $this->db->query("SELECT v.*, u.username,
200 a.activation_code, a.content_ingested
202 LEFT JOIN `videos_unactivated` a ON (v.id = a.video_id),
204 WHERE v.user_id = u.id AND v.id = $id");
207 if ($query->num_rows() > 0)
209 $video = $query->row_array();
210 if ($name !== NULL && $video['name'] != $name)
211 $video['err'] = 'INVALID_NAME';
218 // Convert JSON encoded string to arrays.
219 $video['assets'] = json_decode($video['formats'], TRUE);
220 unset($video['formats']);
221 $video['tags'] = json_decode($video['tags'], TRUE);
222 asort($video['tags']);
223 $video['tags'] = array_reverse($video['tags'], TRUE);
225 // Sort assets by their megapixels number.
226 function access_function($a) { return $a['res']; }
227 function assets_cmp($a, $b)
228 { return megapixels_cmp($a, $b, "access_function"); }
229 usort($video['assets'], "assets_cmp");
232 $video['url'] = array();
233 foreach ($video['assets'] as & $asset)
235 $def = substr($asset['res'], strpos($asset['res'], 'x') + 1) . 'p';
236 $asset['def'] = $def;
237 $asset['src'] = site_url('data/torrents/'. $video['name'] . '_'
238 . $def . '.'. $asset['ext']
239 . '.'. $this->config->item('default_torrent_ext'));
243 $categories = $this->config->item('categories');
244 $category_name = $categories[ intval($video['category_id']) ];
245 $video['category_title'] = $category_name ?
246 $this->lang->line("ui_categ_$category_name") : $category_name;
249 $video['thumbs'] = $this->get_thumbs($video['name'], $video['thumbs_count']);
251 // Shorted description
252 $video['shorted_description'] = character_limiter(
253 $video['description'], 128);
259 * Adds a new uploaded video to the DB.
261 * @param string $name
262 * @param string $title
263 * @param string $description
264 * @param string $tags comma separated tags
265 * @param string $duration video duration formatted [HH:]mm:ss
266 * @param array $formats a dictionary corresponding to `formats` JSON
267 * column from `videos` table
268 * @param int $category_id
269 * @param int $user_id
270 * @param string $uploaded_file the raw video file uploaded by the user
271 * @return mixed returns an activation code on success or FALSE otherwise
273 public function add_video($name, $title, $description, $tags, $duration,
274 $formats, $category_id, $user_id, $uploaded_file)
277 $json_tags = array();
278 $tok = strtok($tags, ',');
279 while ($tok != FALSE)
281 $json_tags[trim($tok)] = 0;
285 $json_tags = json_encode($json_tags);
288 $json_formats = json_encode($formats);
290 $query = $this->db->query("INSERT INTO `videos`
291 (name, title, description, duration, formats, category_id,
293 VALUES ('$name', '$title', '$description', '$duration',
294 '$json_formats', $category_id,
295 $user_id, '$json_tags', utc_timestamp())");
296 if ($query === FALSE)
299 // Find out the id of the new video added.
300 $query = $this->db->query("SELECT id from `videos`
301 WHERE name = '$name'");
302 if ($query->num_rows() === 0)
304 $video_id = $query->row()->id;
307 $activation_code = Videos_model::gen_activation_code();
309 $query = $this->db->query("INSERT INTO `videos_unactivated`
310 (video_id, activation_code, uploaded_file)
311 VALUES ($video_id, '$activation_code', '$uploaded_file')");
313 return $activation_code;
316 public function set_content_ingested($activation_code)
318 return $this->db->query("UPDATE `videos_unactivated`
319 SET content_ingested = 1
320 WHERE activation_code = '$activation_code'");
324 * Activates a video by deleting its entry from `videos_unactivated`.
326 * @param mixed $code_or_id use type string for activation_code or type
328 * @return boolean TRUE on success, FALSE otherwise
330 public function activate_video($code_or_id)
332 if (is_string($code_or_id))
333 $query = $this->db->query("SELECT uploaded_file from `videos_unactivated`
334 WHERE activation_code = '$code_or_id'");
335 else if (is_int($code_or_id))
336 $query = $this->db->query("SELECT uploaded_file from `videos_unactivated`
337 WHERE video_id = '$code_or_id'");
341 if ($query->num_rows() > 0)
342 $uploaded_file = $query->row()->uploaded_file;
346 if (is_string($code_or_id))
347 $query = $this->db->query("DELETE FROM `videos_unactivated`
348 WHERE activation_code = '$code_or_id'");
349 else if (is_int($code_or_id))
350 $query = $this->db->query("DELETE FROM `videos_unactivated`
351 WHERE video_id = '$code_or_id'");
358 return unlink("data/upload/$uploaded_file");
361 public function get_unactivated_videos()
363 $query = $this->db->query("SELECT a.video_id, v.name, a.content_ingested
364 FROM `videos_unactivated` a, `videos` v
365 WHERE a.video_id = v.id AND a.content_ingested = 1");
367 if ($query->num_rows() > 0)
368 return $query->result_array();
374 * Retrieves comments for a video.
376 * @param int $video_id
379 * @param string $ordering control comments ording by these possibilities:
381 * <li><strong>'hottest':</strong> newest most appreciated first. An
382 * appreciated comment is one which has a bigger
383 * score = likes - dislikes.</li>
384 * <li><strong>'newest':</strong> newest first.</li>
386 * @return array an array with comments
388 public function get_video_comments($video_id, $offset, $count,
389 $ordering = 'newest')
391 $this->load->helper('date');
398 $order_statement = "ORDER BY time DESC";
401 $order_statement = "ORDER BY score DESC, time DESC";
402 $cond_hottest = "AND c.likes + c.dislikes > 0";
406 $order_statement = "";
409 $query = $this->db->query(
410 "SELECT c.*, u.username, u.time_zone, (c.likes + c.dislikes) AS score
411 FROM `videos_comments` c, `users` u
412 WHERE c.user_id = u.id AND video_id = $video_id $cond_hottest
414 LIMIT $offset, $count");
416 if ($query->num_rows() == 0)
419 $comments = $query->result_array();
421 foreach ($comments as & $comment)
423 $comment['local_time'] = human_gmt_to_human_local($comment['time'],
424 $comment['time_zone']);
430 public function get_video_comments_count($video_id)
432 $query = $this->db->query(
433 "SELECT COUNT(*) count
434 FROM `videos_comments`
435 WHERE video_id = $video_id");
437 if ($query->num_rows() == 0)
440 return $query->row()->count;
444 * Insert in DB a comment for a video.
446 * @param int $video_id
447 * @param int $user_id
448 * @param string $content
450 public function comment_video($video_id, $user_id, $content)
453 $content = substr($content, 0, 512);
454 $content = htmlspecialchars($content);
455 $content = nl2br($content);
457 return $query = $this->db->query(
458 "INSERT INTO `videos_comments` (video_id, user_id, content, time)
459 VALUES ($video_id, $user_id, '$content', UTC_TIMESTAMP())");
463 * Increments views count for a video.
465 * @param int $id DB video id
468 public function inc_views($id)
470 return $this->db->query('UPDATE `videos` '
471 . 'SET `views`=`views`+1 '
475 public function vote($video_id, $user_id, $like = TRUE)
488 $query = $this->db->query("SELECT * FROM `users_actions`
489 WHERE user_id = $user_id
490 AND target_id = $video_id
491 AND target_type = 'video'
492 AND action = '$action'
493 AND date = CURDATE()");
494 // User already voted today
495 if ($query->num_rows() > 0)
498 $this->db->query("UPDATE `videos`
500 WHERE id = $video_id");
502 // Mark this action so that the user cannot repeat it today.
503 $this->db->query("INSERT INTO `users_actions`
504 (user_id, action, target_type, target_id, date)
505 VALUES ( $user_id, '$action', 'video', $video_id, CURDATE() )");
507 $query = $this->db->query("SELECT $col FROM `videos`
508 WHERE id = $video_id");
510 if ($query->num_rows() === 1)
512 $row = $query->row_array();
520 public function vote_comment($comment_id, $user_id, $like = TRUE)
533 $query = $this->db->query("SELECT * FROM `users_actions`
534 WHERE user_id = $user_id
535 AND target_id = $comment_id
536 AND target_type = 'vcomment'
537 AND action = '$action'
538 AND date = CURDATE()");
539 // User already voted today
540 if ($query->num_rows() > 0)
543 $this->db->query("UPDATE `videos_comments`
545 WHERE id = $comment_id");
547 // Mark this action so that the user cannot repeat it today.
548 $this->db->query("INSERT INTO `users_actions`
549 (user_id, action, target_type, target_id, date)
550 VALUES ( $user_id, '$action', 'vcomment', $comment_id, CURDATE() )");
552 $query = $this->db->query("SELECT $col FROM `videos_comments`
553 WHERE id = $comment_id");
555 if ($query->num_rows() === 1)
557 $row = $query->row_array();
565 public function get_thumbs($name, $count)
569 for ($i=0; $i < $count; $i++)
570 $thumbs[] = site_url(sprintf("data/thumbs/%s_t%02d.jpg", $name, $i));
576 * Searches videos in DB based on a search query string and returns an
577 * associative array of results.
578 * If count is zero the function only return the number of results.
579 * @param string $search_query
582 * @param int $category_id if NULL, all categories are searched
583 * @return array an associative array with the same keys as that from
584 * get_videos_summary's result, but with two additional keys:
585 * description and date.
587 public function search_videos($search_query, $offset = 0, $count = 0,
590 $search_query = trim($search_query);
591 $search_query = str_replace("'", " ", $search_query);
593 // Search word fragments.
594 // sfc = search fragment condition
596 // sfr = search fragment relevance
599 $fragm = strtok($search_query, $sep);
600 while ($fragm !== FALSE)
602 $sfc .= "(title LIKE '%$fragm%'
603 OR description LIKE '%$fragm%'
604 OR tags LIKE '%$fragm%') OR ";
606 // Frament relevances are half of boolean relevances such
607 // that they will appear at the end of the results.
608 $sfr .= "0.25 * (title LIKE '%$fragm%')
609 + 0.1 * (description LIKE '%$fragm%')
610 + 0.15 * (tags LIKE '%$fragm%') + ";
612 $fragm = strtok($sep);
614 $sfc = substr($sfc, 0, -4) . " )";
615 $sfr = substr($sfr, 0, -3) . " )";
617 if (! $this->is_advanced_search_query($search_query))
619 $search_cond = "MATCH (title, description, tags)
620 AGAINST ('$search_query') OR $sfc";
621 $relevance = "( MATCH (title, description, tags)
622 AGAINST ('$search_query') + $sfr ) AS relevance";
627 $against = "AGAINST ('$search_query' IN BOOLEAN MODE)";
628 $search_cond = "( MATCH (title, description, tags)
630 $relevance = "( 0.5 * (MATCH(title) $against)
631 + 0.3 * (MATCH(tags) $against)
632 + 0.2 * (MATCH(description) $against)
633 + $sfr) AS relevance";
638 $selected_columns = "COUNT(*) count";
644 // TODO select data, description if details are needed
645 $selected_columns = "v.id, name, title, duration, user_id, views,
646 thumbs_count, default_thumb, u.username,
647 (views + likes - dislikes) AS score,
649 $order = "ORDER BY relevance DESC, score DESC";
650 $limit = "LIMIT $offset, $count";
653 if ($category_id !== NULL)
654 $category_cond = "category_id = '$category_id' AND ";
658 $str_query = "SELECT $selected_columns
659 FROM `videos` v, `users` u
660 WHERE v.user_id = u.id AND $category_cond ( $search_cond )
663 // echo "<p>$str_query</p>";
664 $query = $this->db->query($str_query);
666 if ($query->num_rows() > 0)
669 return $query->row()->count;
671 $videos = $query->result_array();
676 $this->load->helper('text');
678 foreach ($videos as & $video)
680 // P2P-Tube Video URL
681 $video['video_url'] = site_url(sprintf("watch/%d/%s",
682 $video['id'], $video['name']));
685 $video['thumbs'] = $this->get_thumbs($video['name'],
686 $video['thumbs_count']);
689 //$video['shorted_title'] = ellipsize($video['title'], 45, 0.75);
690 $video['shorted_title'] = character_limiter($video['title'], 50);
692 // TODO: user information
693 $video['user_name'] = 'TODO';
699 public function decode_search_query($search_query)
701 $search_query = urldecode($search_query);
703 $search_query = str_replace('_AST_', '*', $search_query);
704 $search_query = str_replace('_AND_', '+', $search_query);
705 $search_query = str_replace('_GT_', '>', $search_query);
706 $search_query = str_replace('_LT_', '<', $search_query);
707 $search_query = str_replace('_PO_', '(', $search_query);
708 $search_query = str_replace('_PC_', ')', $search_query);
709 $search_query = str_replace('_LOW_', '~', $search_query);
710 $search_query = str_replace('_QUO_', '"', $search_query);
712 return $search_query;
715 public function encode_search_query($search_query)
717 $search_query = str_replace('*', '_AST_', $search_query);
718 $search_query = str_replace('+', '_AND_', $search_query);
719 $search_query = str_replace('>', '_GT_', $search_query);
720 $search_query = str_replace('<', '_LT_', $search_query);
721 $search_query = str_replace('(', '_PO_', $search_query);
722 $search_query = str_replace(')', '_PC_', $search_query);
723 $search_query = str_replace('~', '_LOW_', $search_query);
724 $search_query = str_replace('"', '_QUO_', $search_query);
726 $search_query = urlencode($search_query);
728 return $search_query;
732 * Return TRUE if it contains any special caracter from an advanced search
734 * @param string $search_query
737 public function is_advanced_search_query($search_query)
739 return (preg_match('/\*|\+|\-|>|\<|\(|\)|~|"/', $search_query) == 0
743 public static function gen_activation_code()
745 $ci =& get_instance();
747 $activation_code = substr(
748 sha1($ci->config->item('encryption_key')
753 return $activation_code;
757 /* End of file videos_model.php */
758 /* Location: ./application/models/videos_model.php */