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
33 * @param string $ordering control videos ording by these
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>
42 * @return array a list of videos, each one being an assoc array with:
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>
51 public function get_videos_summary($category_id, $user, $offset, $count,
52 $ordering = 'hottest')
54 $this->load->helper('text');
60 $order_statement = "ORDER BY date DESC, score DESC, RAND()";
63 $order_statement = "ORDER BY date DESC";
65 case 'alphabetically':
66 $order_statement = "ORDER BY title";
70 $order_statement = "";
74 if ($category_id === NULL)
78 $category_id = intval($category_id);
79 $cond_category = "category_id = $category_id";
88 $cond_user = "v.user_id = $user";
89 else if (is_string($user))
90 $cond_user = "u.username = '$user'";
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
100 LIMIT $offset, $count");
102 if ($query->num_rows() > 0)
103 $videos = $query->result_array();
107 foreach ($videos as & $video)
109 // P2P-Tube Video URL
110 $video['video_url'] = site_url(sprintf("watch/%d/%s",
111 $video['id'], $video['name']));
114 $video['thumbs'] = $this->get_thumbs($video['name'],
115 $video['thumbs_count']);
118 //$video['shorted_title'] = ellipsize($video['title'], 45, 0.75);
119 $video['shorted_title'] = character_limiter($video['title'], 50);
126 * Returns the number of videos from database from a specific category or
128 * NULL parameters count videos from all categories and / or all users.
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
134 public function get_videos_count($category_id = NULL, $user = NULL)
136 if ($category_id === NULL)
137 $cond_category = "1";
139 $cond_category = "category_id = $category_id";
146 $cond_user = "v.user_id = $user";
147 else if(is_string($user))
148 $cond_user = "u.username = '$user'";
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");
156 if ($query->num_rows() > 0)
157 return $query->row()->count;
164 * Retrieves information about a video.
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.
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:
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>
189 public function get_video($id, $name = NULL)
191 $this->load->helper('video');
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");
198 if ($query->num_rows() > 0)
200 $video = $query->row_array();
201 if ($name !== NULL && $video['name'] != $name)
202 $video['err'] = 'INVALID_NAME';
206 $video['err'] = 'INVALID_ID';
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);
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");
224 $video['url'] = array();
225 foreach ($video['assets'] as & $asset)
227 $def = substr($asset['res'], strpos($asset['res'], 'x') + 1) . 'p';
228 $asset['def'] = $def;
229 $asset['src'] = site_url('data/torrents/'. $video['name'] . '_'
230 . $def . '.'. $asset['ext']
231 . '.'. $this->config->item('default_torrent_ext'));
235 $categories = $this->config->item('categories');
236 $category_name = $categories[ intval($video['category_id']) ];
237 $video['category_title'] = $category_name ?
238 $this->lang->line("ui_categ_$category_name") : $category_name;
241 $video['thumbs'] = $this->get_thumbs($video['name'], $video['thumbs_count']);
247 * Retrieves comments for a video.
249 * @param int $video_id
252 * @param string $ordering control comments ording by these possibilities:
254 * <li><strong>'hottest':</strong> newest most appreciated first. An
255 * appreciated comment is one which has a bigger
256 * score = likes - dislikes.</li>
257 * <li><strong>'newest':</strong> newest first.</li>
259 * @return array an array with comments
261 public function get_video_comments($video_id, $offset, $count,
262 $ordering = 'newest')
264 $this->load->helper('date');
271 $order_statement = "ORDER BY time DESC";
274 $order_statement = "ORDER BY score DESC, time DESC";
275 $cond_hottest = "AND c.likes + c.dislikes > 0";
279 $order_statement = "";
282 $query = $this->db->query(
283 "SELECT c.*, u.username, u.time_zone, (c.likes + c.dislikes) AS score
284 FROM `videos_comments` c, `users` u
285 WHERE c.user_id = u.id AND video_id = $video_id $cond_hottest
287 LIMIT $offset, $count");
289 if ($query->num_rows() == 0)
292 $comments = $query->result_array();
294 foreach ($comments as & $comment)
296 $comment['local_time'] = human_gmt_to_human_local($comment['time'],
297 $comment['time_zone']);
303 public function get_video_comments_count($video_id)
305 $query = $this->db->query(
306 "SELECT COUNT(*) count
307 FROM `videos_comments`
308 WHERE video_id = $video_id");
310 if ($query->num_rows() == 0)
313 return $query->row()->count;
317 * Insert in DB a comment for a video.
319 * @param int $video_id
320 * @param int $user_id
321 * @param string $content
323 public function comment_video($video_id, $user_id, $content)
326 $content = substr($content, 0, 512);
327 $content = htmlspecialchars($content);
328 $content = nl2br($content);
330 return $query = $this->db->query(
331 "INSERT INTO `videos_comments` (video_id, user_id, content, time)
332 VALUES ($video_id, $user_id, '$content', UTC_TIMESTAMP())");
336 * Increments views count for a video.
338 * @param int $id DB video id
341 public function inc_views($id)
343 return $this->db->query('UPDATE `videos` '
344 . 'SET `views`=`views`+1 '
348 public function vote($video_id, $user_id, $like = TRUE)
361 $query = $this->db->query("SELECT * FROM `users_actions`
362 WHERE user_id = $user_id
363 AND target_id = $video_id
364 AND target_type = 'video'
365 AND action = '$action'
366 AND date = CURDATE()");
367 // User already voted today
368 if ($query->num_rows() > 0)
371 $this->db->query("UPDATE `videos`
373 WHERE id = $video_id");
375 // Mark this action so that the user cannot repeat it today.
376 $this->db->query("INSERT INTO `users_actions`
377 (user_id, action, target_type, target_id, date)
378 VALUES ( $user_id, '$action', 'video', $video_id, CURDATE() )");
380 $query = $this->db->query("SELECT $col FROM `videos`
381 WHERE id = $video_id");
383 if ($query->num_rows() === 1)
385 $row = $query->row_array();
393 public function vote_comment($comment_id, $user_id, $like = TRUE)
406 $query = $this->db->query("SELECT * FROM `users_actions`
407 WHERE user_id = $user_id
408 AND target_id = $comment_id
409 AND target_type = 'vcomment'
410 AND action = '$action'
411 AND date = CURDATE()");
412 // User already voted today
413 if ($query->num_rows() > 0)
416 $this->db->query("UPDATE `videos_comments`
418 WHERE id = $comment_id");
420 // Mark this action so that the user cannot repeat it today.
421 $this->db->query("INSERT INTO `users_actions`
422 (user_id, action, target_type, target_id, date)
423 VALUES ( $user_id, '$action', 'vcomment', $comment_id, CURDATE() )");
425 $query = $this->db->query("SELECT $col FROM `videos_comments`
426 WHERE id = $comment_id");
428 if ($query->num_rows() === 1)
430 $row = $query->row_array();
438 public function get_thumbs($name, $count)
442 for ($i=0; $i < $count; $i++)
443 $thumbs[] = site_url(sprintf("data/thumbs/%s_t%02d.jpg", $name, $i));
449 * Searches videos in DB based on a search query string and returns an
450 * associative array of results.
451 * If count is zero the function only return the number of results.
452 * @param string $search_query
455 * @param int $category_id if NULL, all categories are searched
456 * @return array an associative array with the same keys as that from
457 * get_videos_summary's result, but with two additional keys:
458 * description and date.
460 public function search_videos($search_query, $offset = 0, $count = 0,
463 $search_query = trim($search_query);
464 $search_query = str_replace("'", " ", $search_query);
466 // Search word fragments.
467 // sfc = search fragment condition
469 // sfr = serach fragment relevation
472 $fragm = strtok($search_query, $sep);
473 while ($fragm !== FALSE)
475 $sfc .= "(title LIKE '%$fragm%'
476 OR description LIKE '%$fragm%'
477 OR tags LIKE '%$fragm%') OR ";
479 // Frament relevations are half of boolean relevations such
480 // that they will appear at the end of the results.
481 $sfr .= "0.25 * (title LIKE '%$fragm%')
482 + 0.1 * (description LIKE '%$fragm%')
483 + 0.15 * (tags LIKE '%$fragm%') + ";
485 $fragm = strtok($sep);
487 $sfc = substr($sfc, 0, -4) . " )";
488 $sfr = substr($sfr, 0, -3) . " )";
490 if (! $this->is_advanced_search_query($search_query))
492 $search_cond = "MATCH (title, description, tags)
493 AGAINST ('$search_query') OR $sfc";
494 $relevance = "( MATCH (title, description, tags)
495 AGAINST ('$search_query') + $sfr ) AS relevance";
500 $against = "AGAINST ('$search_query' IN BOOLEAN MODE)";
501 $search_cond = "( MATCH (title, description, tags)
503 $relevance = "( 0.5 * (MATCH(title) $against)
504 + 0.3 * (MATCH(tags) $against)
505 + 0.2 * (MATCH(description) $against)
506 + $sfr) AS relevance";
511 $selected_columns = "COUNT(*) count";
517 // TODO select data, description if details are needed
518 $selected_columns = "id, name, title, duration, user_id, views,
519 thumbs_count, default_thumb,
520 (views + likes - dislikes) AS score,
522 $order = "ORDER BY relevance DESC, score DESC";
523 $limit = "LIMIT $offset, $count";
526 if ($category_id !== NULL)
527 $category_cond = "category_id = '$category_id' AND ";
531 $str_query = "SELECT $selected_columns
533 WHERE $category_cond ( $search_cond )
536 // echo "<p>$str_query</p>";
537 $query = $this->db->query($str_query);
539 if ($query->num_rows() > 0)
542 return $query->row()->count;
544 $videos = $query->result_array();
549 $this->load->helper('text');
551 foreach ($videos as & $video)
553 // P2P-Tube Video URL
554 $video['video_url'] = site_url(sprintf("watch/%d/%s",
555 $video['id'], $video['name']));
558 $video['thumbs'] = $this->get_thumbs($video['name'],
559 $video['thumbs_count']);
562 //$video['shorted_title'] = ellipsize($video['title'], 45, 0.75);
563 $video['shorted_title'] = character_limiter($video['title'], 50);
565 // TODO: user information
566 $video['user_name'] = 'TODO';
572 public function decode_search_query($search_query)
574 $search_query = urldecode($search_query);
576 $search_query = str_replace('_AST_', '*', $search_query);
577 $search_query = str_replace('_AND_', '+', $search_query);
578 $search_query = str_replace('_GT_', '>', $search_query);
579 $search_query = str_replace('_LT_', '<', $search_query);
580 $search_query = str_replace('_PO_', '(', $search_query);
581 $search_query = str_replace('_PC_', ')', $search_query);
582 $search_query = str_replace('_LOW_', '~', $search_query);
583 $search_query = str_replace('_QUO_', '"', $search_query);
585 return $search_query;
588 public function encode_search_query($search_query)
590 $search_query = str_replace('*', '_AST_', $search_query);
591 $search_query = str_replace('+', '_AND_', $search_query);
592 $search_query = str_replace('>', '_GT_', $search_query);
593 $search_query = str_replace('<', '_LT_', $search_query);
594 $search_query = str_replace('(', '_PO_', $search_query);
595 $search_query = str_replace(')', '_PC_', $search_query);
596 $search_query = str_replace('~', '_LOW_', $search_query);
597 $search_query = str_replace('"', '_QUO_', $search_query);
599 $search_query = urlencode($search_query);
601 return $search_query;
605 * Return TRUE if it contains any special caracter from an advanced search
607 * @param string $search_query
610 public function is_advanced_search_query($search_query)
612 return (preg_match('/\*|\+|\-|>|\<|\(|\)|~|"/', $search_query) == 0
617 /* End of file videos_model.php */
618 /* Location: ./application/models/videos_model.php */