Advertisement
Guest User

Untitled

a guest
Sep 5th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 34.24 KB | None | 0 0
  1. <?php
  2.  
  3. //Start session handling
  4. session_start();
  5.  
  6. //Require database class
  7. require_once 'Database.class.php';
  8.  
  9. //File info plugin
  10. require_once '../getid3/getid3.php';
  11.  
  12. //Include database variables.
  13. include 'Conn.php';
  14.  
  15. //Assign library variables.
  16. $movie_library = '../../Media/Movies/';
  17. $show_library = '../../Media/Shows/';
  18.  
  19. //Check if a task was sent
  20. if (isset($_GET['task']))
  21. {
  22. $task = $_GET['task'];
  23.  
  24. Execute($task);
  25. }
  26.  
  27. /**
  28. * Function that executes the requested task if a task is set.
  29. *
  30. * @param type $task - Contains the task to be executed.
  31. */
  32. function Execute($task)
  33. {
  34. switch($task)
  35. {
  36. case 'sign_in':
  37. SignIn();
  38. break;
  39. case 'verify_files':
  40. VerifyFiles();
  41. break;
  42. case 'get_movie':
  43. GetMovie();
  44. break;
  45. case 'get_episode':
  46. GetEpisode();
  47. break;
  48. case 'revoke_movie':
  49. RevokeMovie();
  50. break;
  51. case 'revoke_episode':
  52. RevokeEpisode();
  53. break;
  54. case 'grant_movie':
  55. GrantMovie();
  56. break;
  57. case 'grant_episode':
  58. GrantEpisode();
  59. break;
  60. case 'update_or_create':
  61. UpdateOrCreateUser();
  62. break;
  63. }
  64. }
  65.  
  66. /**
  67. * Function that checks and verifies user data and sets up session variables on user login.
  68. */
  69. function SignIn()
  70. {
  71. //Grab credentials from the request.
  72. $user = $_POST['username'];
  73. $pass = $_POST['password'];
  74.  
  75. //Create database connection
  76. $con = DBConnect();
  77.  
  78. $con->Where('username', $user);
  79.  
  80. $result = $con->FetchOne('users', 'user_id, password, is_teacher');
  81.  
  82. if ($result)
  83. {
  84. $result = (object) $result;
  85.  
  86. //Verify that passwords match
  87. if (password_verify($pass, $result->password))
  88. {
  89. //Setup session variables
  90. $_SESSION['user_id'] = $result->user_id;
  91. $_SESSION['is_teacher'] = $result->is_teacher;
  92.  
  93. echo 1;
  94.  
  95. }
  96. else
  97. {
  98. echo 2;
  99. }
  100. }
  101. else
  102. {
  103. echo 2;
  104. }
  105. }
  106.  
  107. /**
  108. * Function that checks all the files before displaying them on page.
  109. *
  110. * @global string $movie_library - Path to movie files
  111. * @global string $show_library - Path to show files
  112. */
  113. function VerifyFiles()
  114. {
  115. global $movie_library, $show_library;
  116.  
  117. //Grab the movies from the folder
  118. $movies = GetMovies($movie_library);
  119.  
  120. if(!CheckMovies($movies))
  121. {
  122. echo 2;
  123. }
  124.  
  125. //Grab the shows from the folder
  126. $shows = GetShows($show_library);
  127.  
  128. if(!CheckShows($shows))
  129. {
  130. echo 2;
  131. }
  132.  
  133. echo 1;
  134.  
  135. }
  136.  
  137. /**
  138. * Helper function that returns all the files in the movie folder.
  139. *
  140. * @param string $library - Path to the movie library
  141. * @return array - Array containing all the files in the Movies folder.
  142. */
  143. function GetMovies($library)
  144. {
  145. if($handle = opendir($library))
  146. {
  147. while (false != ($file = readdir($handle)))
  148. {
  149. //Exclude dot files.
  150. if ($file == '.' || $file == '..') continue;
  151.  
  152. $files[] = $file;
  153. }
  154.  
  155. closedir($handle);
  156. }
  157.  
  158. return $files;
  159. }
  160.  
  161. /**
  162. * Helper function that gets every folder in the show library - Excludes folders that do not contain any files.
  163. *
  164. * @param string $library - Path to the show library
  165. * @return array - Array containing all folders in the show library
  166. * @throws Exception
  167. */
  168. function GetShows($library)
  169. {
  170. //Setup array
  171. $directories = array();
  172.  
  173. if(!is_dir($library))
  174. {
  175. throw new Exception('Library is not a folder');
  176. }
  177.  
  178. if ($handle = opendir($library))
  179. {
  180. while (false != ($file = readdir($handle)))
  181. {
  182. //Exclude dot files
  183. if ($file == '.' || $file == '..') continue;
  184.  
  185. //Exclude empty folders
  186. if (is_dir($library . $file))
  187. {
  188. if (count(glob($library . $file . '/*')) != 0)
  189. {
  190. $directories[] = $file;
  191. }
  192. }
  193. else
  194. {
  195. array_merge($directories, rendertask::getAllSubdirectories($library . $file));
  196. }
  197. }
  198.  
  199. closedir($handle);
  200.  
  201. }
  202.  
  203. return $directories;
  204. }
  205.  
  206. /**
  207. *
  208. * @global string $show_library - Path to the show library folder.
  209. * @param string $folder - Folder name for a specific show.
  210. * @return array - Array containing all the episodes for a show.
  211. */
  212. function GetEpisodes($folder)
  213. {
  214. global $show_library;
  215.  
  216. if($handle = opendir($show_library . $folder . '/'))
  217. {
  218. while (false != ($file = readdir($handle)))
  219. {
  220. if ($file == '.' || $file == '..') continue;
  221.  
  222. $files[] = $file;
  223. }
  224.  
  225. closedir($handle);
  226. }
  227.  
  228. return $files;
  229. }
  230.  
  231. /**
  232. * Helper function that checks if movies exist in the database.
  233. *
  234. * @param array $movies - Array containing every movie file in the library.
  235. * @return boolean - Returns true once check completes.
  236. */
  237. function CheckMovies($movies)
  238. {
  239. //Create DB connection
  240. $con = DBConnect();
  241.  
  242. //Loop through movies and check if they exist in the database.
  243. foreach($movies as $movie)
  244. {
  245. $con->Where("file_name", $movie);
  246.  
  247. $exists = $con->FetchOne("movies", "file_name");
  248.  
  249. if($exists)
  250. {
  251. //Do nothing.
  252. }
  253. else
  254. {
  255. //Add movie
  256. AddMovie($movie);
  257. }
  258.  
  259. }
  260.  
  261. return true;
  262.  
  263. }
  264.  
  265. /**
  266. * Helper function that checks if shows exist in the database.
  267. *
  268. * @param array $shows - Array containing all folders in the show library
  269. * @return boolean - Returns true once check has been completed.
  270. */
  271. function CheckShows($shows)
  272. {
  273. $con = Database::FetchInstance();
  274.  
  275. foreach($shows as $show)
  276. {
  277. $con->Where("title", $show);
  278.  
  279. $exists = $con->FetchOne("shows", "show_id, imdb_id");
  280.  
  281. if ($exists)
  282. {
  283. //Get episodes for the show.
  284. $episodes = GetEpisodes($show);
  285.  
  286. //Check if all episodes are created
  287. CheckEpisodes($episodes, $exists['show_id'], $exists['imdb_id']);
  288. }
  289. else
  290. {
  291. //Add show
  292. AddShow($show);
  293. }
  294. }
  295.  
  296. return true;
  297. }
  298.  
  299. /**
  300. * Helper function that checks episodes in the folder against episodes in the database.
  301. *
  302. * @param array $episodes - Array containing every file in a show folder.
  303. * @param int $show_id - ID of the show the episodes belong to.
  304. * @param string $imdb_id - imdb ID of the show the episodes belong to.
  305. */
  306. function CheckEpisodes($episodes, $show_id, $imdb_id)
  307. {
  308. $con = Database::FetchInstance();
  309.  
  310. foreach($episodes as $episode)
  311. {
  312. //Split the episode title into segments.
  313. $title_segments = SplitEpisodeTitle($episode);
  314.  
  315. //Check if the necessary season for each episode exists and create it if it does not.
  316. $season_id = CheckSeason($show_id, $title_segments['season'], $imdb_id);
  317.  
  318. $con->Where("file_name", $episode);
  319. $con->Where("season_id", $season_id);
  320.  
  321. $exists = $con->FetchOne("episodes", "title");
  322.  
  323. if ($exists)
  324. {
  325. //Do nothing.
  326. }
  327. else
  328. {
  329. //Add episode
  330. AddEpisode($episode, $season_id, $title_segments['title'], $title_segments['episode'], $imdb_id);
  331. }
  332. }
  333. }
  334.  
  335. /**
  336. * Helper function that checks if a season exists, creates it if it does not, and returns the ID.
  337. *
  338. * @param int $show_id - ID of the show the season belongs to.
  339. * @param int $season_number - The season number to be checked.
  340. * @param string $imdb_id - IMDB ID of the show.
  341. * @return int - Returns the ID of the season.
  342. */
  343. function CheckSeason($show_id, $season_number, $imdb_id)
  344. {
  345. $con = Database::FetchInstance();
  346.  
  347. $con->Where("show_id", $show_id);
  348. $con->Where("season_number", $season_number);
  349.  
  350. $exists = $con->FetchOne("seasons", "season_id");
  351.  
  352. if($exists)
  353. {
  354. //Return ID.
  355. return $exists['season_id'];
  356. }
  357. else
  358. {
  359. //Add season and return ID.
  360. return AddSeason($show_id, $season_number, $imdb_id);
  361. }
  362.  
  363. }
  364.  
  365. /**
  366. * Helper function that gets the required data and creates a show in the database.
  367. *
  368. * @param string $show - The title of a show.
  369. */
  370. function AddShow($show)
  371. {
  372. //Get database instance
  373. $con = Database::FetchInstance();
  374.  
  375. //Get the meta data for the show
  376. $meta = GetShowMetaData($show);
  377.  
  378. //Set the prefix 'The' to be stripped to create the sort title.
  379. $prefix = 'The ';
  380.  
  381. //Strip off the prefix if its present.
  382. if(substr($meta['name'], 0, strlen($prefix)) == $prefix)
  383. {
  384. $sort_title = substr($meta['name'], strlen($prefix));
  385. }
  386. else
  387. {
  388. $sort_title = $meta['name'];
  389. }
  390.  
  391. //Loop through cast and assign to a string.
  392. foreach ($meta['credits']['cast'] as $castmember)
  393. {
  394. $cast .= $castmember['name'] . ',';
  395. }
  396.  
  397. //Loop through genres and assign to a string
  398. foreach ($meta['genres'] as $genre)
  399. {
  400. $genres .= $genre['name'] . ',';
  401. }
  402.  
  403. if ($meta['poster_path'] == null)
  404. {
  405. $poster = '';
  406. }
  407. else
  408. {
  409. $poster = 'http://image.tmdb.org/t/p/original' . $meta['poster_path'] . '?api_key=53e6f37de835a272473c977089ed74f7';
  410. }
  411.  
  412. if ($meta['backdrop_path'] == null)
  413. {
  414. $backdrop = '';
  415. }
  416. else
  417. {
  418. $backdrop = 'http://image.tmdb.org/t/p/original' . $meta['backdrop_path'] . '?api_key=53e6f37de835a272473c977089ed74f7';
  419. }
  420.  
  421. if ($cast == null)
  422. {
  423. $cast = "No cast information";
  424. }
  425.  
  426. //Assign data for insertion
  427. $data = array(
  428. "title" => $meta['name'],
  429. "sort_title" => $sort_title,
  430. "cast" => $cast,
  431. "summary" => $meta['overview'],
  432. "genres" => $genres,
  433. "poster" => $poster,
  434. "backdrop" => $backdrop,
  435. "imdb_id" => $meta['id']
  436. );
  437.  
  438. var_dump($data);
  439.  
  440. $id = $con->Insert("shows", $data);
  441.  
  442. if ($id)
  443. {
  444. //Get episodes
  445. $episodes = GetEpisodes($show);
  446.  
  447. //Check episodes
  448. CheckEpisodes($episodes, $id, $meta['id']);
  449. }
  450.  
  451. }
  452.  
  453. /**
  454. * Helper function that creates a movie if it does not exist.
  455. *
  456. * @param string $movie - Name of a movie.
  457. */
  458. function AddMovie($movie)
  459. {
  460. global $movie_library;
  461.  
  462. //Get Database instance
  463. $con = Database::FetchInstance();
  464.  
  465. //Get the movie meta data.
  466. $meta = GetMovieMetaData($movie);
  467.  
  468. //Create ID3 object for pulling file data.
  469. $getID3 = new getID3;
  470.  
  471. //Analyze the movie file.
  472. $fileinfo = $getID3->analyze($movie_library . $movie);
  473.  
  474. getid3_lib::CopyTagsToComments($fileinfo);
  475.  
  476. //Set prefix for removal if necessary.
  477. $prefix = 'The ';
  478.  
  479. //Strip prefix if present.
  480. if(substr($meta['title'], 0, strlen($prefix)) == $prefix)
  481. {
  482. $sort_title = substr($meta['title'], strlen($prefix));
  483. }
  484. else
  485. {
  486. $sort_title = $meta['title'];
  487. }
  488.  
  489. //Find and assign directors and writers
  490. foreach ($meta['casts']['crew'] as $crew)
  491. {
  492. if($crew['job'] == 'Director')
  493. {
  494. $director .= $crew['name'] . ',';
  495. }
  496. elseif ($crew['job'] == 'Writer' || $crew['job'] == 'Screenplay')
  497. {
  498. $writer .= $crew['name'] . ',';
  499. }
  500. }
  501.  
  502. //Loop through cast and assign to a string.
  503. foreach ($meta['casts']['cast'] as $castmember)
  504. {
  505. $cast .= $castmember['name'] . ',';
  506. }
  507.  
  508. //Loop through genres and assign to a string
  509. foreach ($meta['genres'] as $genre)
  510. {
  511. $genres .= $genre['name'] . ',';
  512. }
  513.  
  514. //If file is too big or info for some reason can't be read - Use the default runtime from metadata.
  515. if ($fileinfo['playtime_string'] == "")
  516. {
  517. $hours = floor((int)$meta['runtime'] / 60);
  518. $minutes = ((int)$meta['runtime'] - floor((int)$meta['runtime'] / 60) * 60);
  519.  
  520. if (strlen($minutes) == 1)
  521. {
  522. $minutes = 0 . $minutes;
  523. }
  524.  
  525. $runtime = $hours . ':' . $minutes . ':00';
  526. }
  527. else
  528. {
  529. $runtime = $fileinfo['playtime_string'];
  530. }
  531.  
  532. //Assign data for insertion
  533. $data = array(
  534. "title" => $meta['title'],
  535. "sort_title" => $sort_title,
  536. "year" => date('Y', strtotime($meta['release_date'])),
  537. "runtime" => $runtime,
  538. "director" => $director,
  539. "writer" => $writer,
  540. "cast" => $cast,
  541. "summary" => $meta['overview'],
  542. "tagline" => $meta['tagline'],
  543. "genres" => $genres,
  544. "poster" => 'http://image.tmdb.org/t/p/original' . $meta['poster_path'] . '?api_key=53e6f37de835a272473c977089ed74f7',
  545. "backdrop" => 'http://image.tmdb.org/t/p/original' . $meta['backdrop_path'] . '?api_key=53e6f37de835a272473c977089ed74f7',
  546. "file_name" => $movie,
  547. "full_path" => $movie_library . $movie,
  548. "imdb_id" => $meta['imdb_id']
  549. );
  550.  
  551. $con->Insert("movies", $data);
  552.  
  553. }
  554.  
  555. /**
  556. * Function that adds an episode to the database.
  557. *
  558. * @param string $episode - File name of the episode.
  559. * @param int $season_id - ID of the season the episode belongs to.
  560. * @param string $title - Title of the show the episode belongs to.
  561. * @param int $episode_number - Number of the episode in the season.
  562. * @param string $imdb_id - IMDB ID of the show.
  563. */
  564. function AddEpisode($episode, $season_id, $title, $episode_number, $imdb_id)
  565. {
  566. global $show_library;
  567.  
  568. //Get database instance.
  569. $con = Database::FetchInstance();
  570.  
  571. //Get the episode meta data.
  572. $meta = GetEpisodeMetaData($episode, $imdb_id);
  573.  
  574. //Create ID3 object
  575. $getID3 = new getID3;
  576.  
  577. //Analyze episode file.
  578. $fileinfo = $getID3->analyze($show_library . $title . '/' . $episode);
  579.  
  580. getid3_lib::CopyTagsToComments($fileinfo);
  581.  
  582. //If file is too big or info for some reason can't be read - Use the default runtime from metadata.
  583. if ($fileinfo['playtime_string'] == "")
  584. {
  585. $hours = floor((int)$meta['runtime'] / 60);
  586. $minutes = ((int)$meta['runtime'] - floor((int)$meta['runtime'] / 60) * 60);
  587.  
  588. if (strlen($minutes) == 1)
  589. {
  590. $minutes = 0 . $minutes;
  591. }
  592.  
  593. $runtime = $hours . ':' . $minutes . ':00';
  594. }
  595. else
  596. {
  597. $runtime = $fileinfo['playtime_string'];
  598. }
  599.  
  600. //Assign data to be inserted
  601. $data = array(
  602. "title" => $meta['name'],
  603. "runtime" => $runtime,
  604. "summary" => $meta['overview'],
  605. "season_id" => $season_id,
  606. "episode_number" => $episode_number,
  607. "still_image" => 'http://image.tmdb.org/t/p/original' . $meta['still_path'] . '?api_key=53e6f37de835a272473c977089ed74f7',
  608. "file_name" => $episode,
  609. "full_path" => $show_library . $title . '/' . $episode
  610. );
  611.  
  612. $con->Insert("episodes", $data);
  613.  
  614. }
  615.  
  616. /**
  617. * Function that creates a season for a show.
  618. *
  619. * @param int $show_id - ID of the show.
  620. * @param int $season_number - Number of the season
  621. * @param int $imdb_id - IMDB ID for the show.
  622. * @return int - ID of the newly created season.
  623. */
  624. function AddSeason($show_id, $season_number, $imdb_id)
  625. {
  626. //Get database instance
  627. $con = Database::FetchInstance();
  628.  
  629. //Get season meta data.
  630. $meta = GetSeasonMetaData($imdb_id, $season_number);
  631.  
  632. //Assign data to be inserted.
  633. $data = array(
  634. "show_id" => $show_id,
  635. "season_number" => $season_number,
  636. "poster" => 'http://image.tmdb.org/t/p/original' . $meta['poster_path'] . '?api_key=53e6f37de835a272473c977089ed74f7'
  637. );
  638.  
  639. return $con->Insert("seasons", $data);
  640.  
  641. }
  642.  
  643. /**
  644. * Helper function that gets the meta data for a season of a show.
  645. *
  646. * @param string $show - Show folder name.
  647. * @param int $season - Season number of the requested season.
  648. * @return array - JSON array containing season meta data.
  649. */
  650. function GetSeasonMetaData($show, $season)
  651. {
  652. //Get the meta data.
  653. $metadata = file_get_contents('https://api.themoviedb.org/3/tv/' . $show . '/season/' . $season . '?api_key=53e6f37de835a272473c977089ed74f7&language=en-US');
  654.  
  655. //Return data.
  656. return json_decode($metadata, true);
  657. }
  658.  
  659. /**
  660. * Helper function that gets the meta data for a movie.
  661. *
  662. * @param string $movie - Movie file name.
  663. * @return array - JSON array containing movie meta data.
  664. */
  665. function GetMovieMetaData($movie)
  666. {
  667. //Split the title into title and year
  668. $title_segments = SplitMovieTitle($movie);
  669.  
  670. //Replace spaces for search purposes.
  671. $encoded_title = str_replace(" ", "+", $title_segments['title']);
  672.  
  673. //Search to find the movie ID.
  674. $search = file_get_contents('http://api.themoviedb.org/3/search/movie?api_key=53e6f37de835a272473c977089ed74f7&query=' . $encoded_title . '&year=' . $title_segments['year']);
  675.  
  676. //Decode the data.
  677. $search = json_decode($search, true);
  678.  
  679. //Get the ID of the best result
  680. $movie_id = $search['results'][0]['id'];
  681.  
  682. //Get the meta data.
  683. $metadata = file_get_contents('https://api.themoviedb.org/3/movie/' . $movie_id . '?api_key=53e6f37de835a272473c977089ed74f7&append_to_response=casts');
  684.  
  685. //Return data
  686. return json_decode($metadata, true);
  687.  
  688. }
  689.  
  690. /**
  691. * Helper function that gets the meta data for a show.
  692. *
  693. * @param string $show - Show folder name.
  694. * @return array - JSON array containing show meta data.
  695. */
  696. function GetShowMetaData($show)
  697. {
  698. //URL Encode the show folder.
  699. $encoded_title = str_replace(" ", "+", $show);
  700.  
  701. //Search the API for the show.
  702. $search = file_get_contents('https://api.themoviedb.org/3/search/tv?api_key=53e6f37de835a272473c977089ed74f7&query=' . $encoded_title);
  703.  
  704. //Decode the data.
  705. $search = json_decode($search, true);
  706.  
  707. //Get the ID of the best result
  708. $show_id = $search['results'][0]['id'];
  709.  
  710. //Get the Meta data for the show.
  711. $metadata = file_get_contents('https://api.themoviedb.org/3/tv/' . $show_id . '?api_key=53e6f37de835a272473c977089ed74f7&append_to_response=credits');
  712.  
  713. //Return data.
  714. return json_decode($metadata, true);
  715. }
  716.  
  717. /**
  718. * Helper function that gets the meta data for an episode of a show.
  719. *
  720. * @param string $episode - Episode file name.
  721. * @param string $imdb_id - IMDB Id of the show.
  722. * @return array - JSON array containing episode meta data.
  723. */
  724. function GetEpisodeMetaData($episode, $imdb_id)
  725. {
  726. //Split the title into title, season and episode.
  727. $title_segments = SplitEpisodeTitle($episode);
  728.  
  729. //Grab meta data from the API
  730. $metadata = file_get_contents('https://api.themoviedb.org/3/tv/' . $imdb_id . '/season/' . $title_segments['season'] . '/episode/' . $title_segments['episode'] . '?api_key=53e6f37de835a272473c977089ed74f7');
  731.  
  732. //Return data
  733. return json_decode($metadata, true);
  734.  
  735. }
  736.  
  737. /**
  738. * Helper function that splits a movie filename into title and year.
  739. *
  740. * @param string $filename - Filename of a movie
  741. * @return array - Array containing the segmented title - Title and year.
  742. */
  743. function SplitMovieTitle($filename)
  744. {
  745. // Get title
  746. $title = pathinfo($filename, PATHINFO_FILENAME);
  747.  
  748. // Split title at spaces
  749. $explodedTitle = explode(' ', $title);
  750.  
  751. // Get title and year
  752. $year = array_pop($explodedTitle);
  753. $titleNoYear = implode(' ', $explodedTitle);
  754.  
  755. return array(
  756. 'title' => $titleNoYear,
  757. 'year' => $year
  758. );
  759. }
  760.  
  761. /**
  762. * Helper function that splits an episode filename into title, season and episode.
  763. *
  764. * @param string $filename - Filename of an episode.
  765. * @return array - Array containing the segmented title - Title, Season and Episode.
  766. */
  767. function SplitEpisodeTitle($filename)
  768. {
  769. // Get title
  770. $title = pathinfo($filename, PATHINFO_FILENAME);
  771.  
  772. // Split title at dash
  773. $explodedTitle = explode(' - S', $title);
  774.  
  775. // Get title
  776. $titleClean = $explodedTitle[0];
  777.  
  778. // Split season and episode data
  779. $explodedInfo = explode('E', end($explodedTitle));
  780.  
  781. //Get Season and Episode
  782. $season = $explodedInfo[0];
  783. $episode = end($explodedInfo);
  784.  
  785. return array(
  786. 'title' => $titleClean,
  787. 'season' => $season,
  788. 'episode' => $episode
  789. );
  790. }
  791.  
  792. /**
  793. * Function that returns the necessary data for the player to play a movie.
  794. */
  795. function GetMovie()
  796. {
  797. //Get movie ID from ajax.
  798. $movie_id = $_POST['movie_id'];
  799.  
  800. //Connect to the database
  801. $con = DBConnect();
  802.  
  803. $con->Where("movie_id", $movie_id);
  804.  
  805. $movie = $con->FetchOne("movies");
  806.  
  807. //Return JSON movie data to the player.
  808. echo json_encode($movie);
  809. }
  810.  
  811. /**
  812. * Function that returns the necessary data for the player to play an episode.
  813. */
  814. function GetEpisode()
  815. {
  816. //Get episode ID from Ajax
  817. $episode_id = $_POST['episode_id'];
  818.  
  819. //Connect to the database
  820. $con = DBConnect();
  821.  
  822. $con->Where("episode_id", $episode_id);
  823.  
  824. $episode = $con->FetchOne("episodes");
  825.  
  826. //Return JSON episode data to the player.
  827. echo json_encode($episode);
  828. }
  829.  
  830. /**
  831. * Function that revokes access to a movie.
  832. */
  833. function RevokeMovie()
  834. {
  835. //Get the ID of the access from Ajax.
  836. $access_id = $_POST['access'];
  837.  
  838. //Connect to the database
  839. $con = DBConnect();
  840.  
  841. $con->Where('access_id', $access_id);
  842.  
  843. //Delete the access.
  844. if ($con->Delete('movie_access'))
  845. {
  846. echo 1;
  847. }
  848. else
  849. {
  850. echo 2;
  851. }
  852. }
  853.  
  854. /**
  855. * Function that revokes access to an episode.
  856. */
  857. function RevokeEpisode()
  858. {
  859. //Get the ID of the access from Ajax.
  860. $access_id = $_POST['access'];
  861.  
  862. //Connect to the database
  863. $con = DBConnect();
  864.  
  865. $con->Where('access_id', $access_id);
  866.  
  867. //Delete the access
  868. if ($con->Delete('show_access'))
  869. {
  870. echo 1;
  871. }
  872. else
  873. {
  874. echo 2;
  875. }
  876. }
  877.  
  878. /**
  879. * Function that grants access to a movie to the given usernames.
  880. */
  881. function GrantMovie()
  882. {
  883. //Connect to database
  884. $con = DBConnect();
  885.  
  886. //Split the data sent from ajax.
  887. $file = explode(',', $_POST['file']);
  888.  
  889. //Get the movie ID
  890. $movie_id = $file[1];
  891.  
  892. //Split users into an array (If multiple).
  893. $userArr = explode(',', $_POST['users']);
  894.  
  895. //create variable for the html
  896. $html = '';
  897.  
  898. //Loop through users.
  899. foreach ($userArr as $username)
  900. {
  901. //Get the user and check if it exists.
  902. $user = GetUserByUsername($username);
  903.  
  904. if($user)
  905. {
  906. //Check if the access already exists
  907. if(CheckAccessExists($user->user_id, $movie_id, 'Movie'))
  908. {
  909. //Do nothing.
  910. }
  911. else
  912. {
  913. //Assign data and create access.
  914. $access_data = Array (
  915. 'user_id' => $user->user_id,
  916. 'movie_id' => $movie_id
  917. );
  918.  
  919. $access = $con->Insert('movie_access', $access_data);
  920.  
  921. if ($access)
  922. {
  923. //Generate response html.
  924. $html .= GenerateMovieResponseRow($access);
  925. }
  926. }
  927.  
  928. }
  929. else
  930. {
  931. //Assign data and create user.
  932. $data = Array (
  933. 'username' => $username,
  934. 'password' => password_hash('1234', PASSWORD_BCRYPT),
  935. 'is_teacher' => 0
  936. );
  937.  
  938. $id = $con->Insert('users', $data);
  939.  
  940. if ($id)
  941. {
  942. //Assign data and create access.
  943. $access_data = Array (
  944. 'user_id' => $id,
  945. 'movie_id' => $movie_id
  946. );
  947.  
  948. $access = $con->Insert('movie_access', $access_data);
  949.  
  950. if ($access)
  951. {
  952. //Generate response html.
  953. $html .= GenerateMovieResponseRow($access);
  954. }
  955.  
  956. }
  957. }
  958. }
  959.  
  960. echo $html;
  961. }
  962.  
  963. /**
  964. * Function that grants access to an episode of a show to the given users.
  965. */
  966. function GrantEpisode()
  967. {
  968. //Connect to the database
  969. $con = DBConnect();
  970.  
  971. //Split the file data sent from ajax.
  972. $file = explode(',', $_POST['file']);
  973.  
  974. //Get the ID for the episode
  975. $episode_id = $file[1];
  976.  
  977. //Split the users into an array (If multiple).
  978. $userArr = explode(',', $_POST['users']);
  979.  
  980. //create variable for the html
  981. $html = '';
  982.  
  983. //Loop through users.
  984. foreach ($userArr as $username)
  985. {
  986. //Get the user and check if it exists.
  987. $user = GetUserByUsername($username);
  988.  
  989. if($user)
  990. {
  991. //Check if user already has the access
  992. if(CheckAccessExists($user->user_id, $episode_id, 'Show'))
  993. {
  994. //Do nothing.
  995. }
  996. else
  997. {
  998. //Get IDs for show, season and episode.
  999. $show = (object) GetShowIdsByEpisode($episode_id);
  1000.  
  1001. //Assign data for insertion.
  1002. $access_data = Array (
  1003. 'user_id' => $user->user_id,
  1004. 'show_id' => $show->show_id,
  1005. 'season_id' => $show->season_id,
  1006. 'episode_id' => $show->episode_id
  1007. );
  1008.  
  1009. $access = $con->Insert('show_access', $access_data);
  1010.  
  1011. if ($access)
  1012. {
  1013. //Generate response html.
  1014. $html .= GenerateShowResponseRow($access);
  1015. }
  1016.  
  1017. }
  1018. }
  1019. else
  1020. {
  1021. //Assign data and create user.
  1022. $data = Array (
  1023. 'username' => $username,
  1024. 'password' => password_hash('1234', PASSWORD_BCRYPT),
  1025. 'is_teacher' => 0
  1026. );
  1027.  
  1028. $id = $con->Insert('users', $data);
  1029.  
  1030. if ($id)
  1031. {
  1032. //Get IDs for show, season and episode.
  1033. $show = (object) GetShowIdsByEpisode($episode_id);
  1034.  
  1035. //Assign data for insertion.
  1036. $access_data = Array (
  1037. 'user_id' => $user->user_id,
  1038. 'show_id' => $show->show_id,
  1039. 'season_id' => $show->season_id,
  1040. 'episode_id' => $show->episode_id
  1041. );
  1042.  
  1043. $access = $con->Insert('show_access', $access_data);
  1044.  
  1045. if ($access)
  1046. {
  1047. //Generate response html.
  1048. $html .= GenerateShowResponseRow($access);
  1049. }
  1050.  
  1051. }
  1052. }
  1053. }
  1054.  
  1055. echo $html;
  1056.  
  1057. }
  1058.  
  1059. /**
  1060. * Helper function that creates the database connection.
  1061. *
  1062. * @global type $servername
  1063. * @global type $username
  1064. * @global type $password
  1065. * @global type $database
  1066. * @return Database - Returns database connection variable.
  1067. */
  1068. function DBConnect()
  1069. {
  1070. global $servername, $username, $password, $database;
  1071.  
  1072. return new Database($servername, $username, $password, $database);
  1073. }
  1074.  
  1075. /**
  1076. * Helper function that checks if a user already exists.
  1077. *
  1078. * @param int $username - Variable containing user to be checked.
  1079. * @return boolean / User object - Returns user object if user exists and false if it does not.
  1080. */
  1081. function GetUserByUsername($username)
  1082. {
  1083. $con = Database::FetchInstance();
  1084.  
  1085. $con->Where('username', $username);
  1086.  
  1087. $user = $con->FetchAsObject()->FetchOne('users');
  1088.  
  1089. if($user)
  1090. {
  1091. return $user;
  1092. }
  1093. else
  1094. {
  1095. return false;
  1096. }
  1097. }
  1098.  
  1099. /**
  1100. * Helper function that checks if access has already been granted to the requested file (Helps avoid duplicate entries).
  1101. *
  1102. * @param int $user_id - User ID of the user to be checked
  1103. * @param int $file_id - ID of the file to be granted access to
  1104. * @param string $file_type - Movie or Show.
  1105. * @return boolean - Returns true or false based on if an access already exists.
  1106. */
  1107. function CheckAccessExists($user_id, $file_id, $file_type)
  1108. {
  1109. //Get database instance
  1110. $con = Database::FetchInstance();
  1111.  
  1112. //If the file is a movie
  1113. if ($file_type == "Movie")
  1114. {
  1115. $con->Where('user_id', $user_id);
  1116. $con->Where('movie_id', $file_id);
  1117.  
  1118. if ($con->FetchOne('movie_access'))
  1119. {
  1120. return true;
  1121. }
  1122. else
  1123. {
  1124. return false;
  1125. }
  1126. }
  1127. else
  1128. {
  1129. $con->Where('user_id', $user_id);
  1130. $con->Where('episode_id', $file_id);
  1131.  
  1132. if($con->FetchOne('show_access'))
  1133. {
  1134. return true;
  1135. }
  1136. else
  1137. {
  1138. return false;
  1139. }
  1140. }
  1141. }
  1142.  
  1143. /**
  1144. * Helper function that gets the IDs for the show, season and episode - Used to output the correct data to the user.
  1145. *
  1146. * @param int $episode_id - Int containing the ID of the episode to grant access for.
  1147. * @return array - Array containing IDs for the show, season and episode.
  1148. */
  1149. function GetShowIdsByEpisode($episode_id)
  1150. {
  1151. $con = Database::FetchInstance();
  1152.  
  1153. //Setup show data query.
  1154. $con->Join("seasons se", "e.season_id=se.season_id", "INNER");
  1155. $con->Join("shows s", "se.show_id=s.show_id", "INNER");
  1156. $con->Where("episode_id", $episode_id);
  1157.  
  1158. $data = $con->FetchAsObject()->FetchOne('episodes e', 'e.episode_id, se.season_id, s.show_id');
  1159.  
  1160. return array(
  1161. 'episode_id' => $data->episode_id,
  1162. 'season_id' => $data->season_id,
  1163. 'show_id' => $data->show_id
  1164. );
  1165. }
  1166.  
  1167. /**
  1168. * Helper function that builds the HTML row for a new access - To be output on page upon completion.
  1169. *
  1170. * @param int $access_id - Int value of the newly created access.
  1171. * @return string - html string containing the access row of current user and movie to be inserted on page.
  1172. */
  1173. function GenerateMovieResponseRow($access_id)
  1174. {
  1175. $con = Database::FetchInstance();
  1176.  
  1177. //Setup movie access query.
  1178. $con->Join("movies m", "a.movie_id=m.movie_id", "INNER");
  1179. $con->Join("users u", "a.user_id=u.user_id", "INNER");
  1180. $con->Where('access_id', $access_id);
  1181.  
  1182. $access = $con->FetchAsObject()->FetchOne('movie_access a', 'a.access_id, u.username, m.title, a.created_date');
  1183.  
  1184. $response = '<tr>';
  1185. $response .= '<td>' . $access->username . '</td>';
  1186. $response .= '<td>' . $access->title . '</td>';
  1187. $response .= '<td>' . date("d/m/Y H:i", strtotime($access->created_date)) . '</td>';
  1188. $response .= '<td class="RevokeMovieAccess"><a class="TableButton RevokeMovieAccessButton" data-accessid="' . $access->access_id . '"><i class="fa fa-times" aria-hidden="true"></i></a></td>';
  1189. $response .= '</tr>';
  1190.  
  1191. return $response;
  1192. }
  1193.  
  1194. function GenerateShowResponseRow($access_id)
  1195. {
  1196. $con = Database::FetchInstance();
  1197.  
  1198. //Setup show access query.
  1199. $con->Join("shows s", "a.show_id=s.show_id", "INNER");
  1200. $con->Join("seasons se", "a.season_id=se.season_id", "INNER");
  1201. $con->Join("episodes e", "a.episode_id=e.episode_id", "INNER");
  1202. $con->Join("users u", "a.user_id=u.user_id", "INNER");
  1203. $con->Where('access_id', $access_id);
  1204.  
  1205. $access = $con->FetchAsObject()->FetchOne('show_access a', 'a.access_id, u.username, s.title AS show_title, se.season_number, e.title AS episode_title, e.episode_number, a.created_date');
  1206.  
  1207. if ($access->episode_number < 10)
  1208. {
  1209. $episode = '0' . $access->episode_number;
  1210. }
  1211. else
  1212. {
  1213. $episode = $access->episode_number;
  1214. }
  1215.  
  1216. $response .= '<tr>';
  1217. $response .= '<td>' . $access->username . '</td>';
  1218. $response .= '<td>' . $access->show_title . '</td>';
  1219. $response .= '<td>S' . $access->season_number . 'E' . $episode . ' — ' . $access->episode_title . '</td>';
  1220. $response .= '<td>' . date("d/m/Y H:i", strtotime($access->created_date)) . '</td>';
  1221. $response .= '<td class="RevokeMovieAccess"><a class="TableButton RevokeShowAccessButton" data-accessid="' . $access->access_id . '"><i class="fa fa-times" aria-hidden="true"></i></a></td>';
  1222. $response .= '</tr>';
  1223.  
  1224. return $response;
  1225. }
  1226.  
  1227. function UpdateOrCreateUser()
  1228. {
  1229. //Get variables from ajax.
  1230. $username = $_POST['username'];
  1231. $password = $_POST['password'];
  1232.  
  1233. //Create database connection
  1234. $con = DBConnect();
  1235.  
  1236. //Check if the user already exists
  1237. $user = GetUserByUsername($username);
  1238.  
  1239. if ($user)
  1240. {
  1241. //Assign data to be updated
  1242. $data = Array (
  1243. 'password' => password_hash($password, PASSWORD_BCRYPT)
  1244. );
  1245.  
  1246. $con->Where('username', $username);
  1247.  
  1248. if ($con->Update('users', $data))
  1249. {
  1250. echo 1;
  1251. }
  1252. else
  1253. {
  1254. echo 2;
  1255. }
  1256. }
  1257. else
  1258. {
  1259. //Assign data and create user
  1260. $data = Array (
  1261. 'username' => $username,
  1262. 'password' => password_hash($password, PASSWORD_BCRYPT),
  1263. 'is_teacher' => 1
  1264. );
  1265.  
  1266. $id = $con->Insert('users', $data);
  1267.  
  1268. if ($id)
  1269. {
  1270. echo 1;
  1271. }
  1272. else
  1273. {
  1274. echo 2;
  1275. }
  1276. }
  1277.  
  1278. }
  1279.  
  1280. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement