Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- //Start session handling
- session_start();
- //Require database class
- require_once 'Database.class.php';
- //File info plugin
- require_once '../getid3/getid3.php';
- //Include database variables.
- include 'Conn.php';
- //Assign library variables.
- $movie_library = '../../Media/Movies/';
- $show_library = '../../Media/Shows/';
- //Check if a task was sent
- if (isset($_GET['task']))
- {
- $task = $_GET['task'];
- Execute($task);
- }
- /**
- * Function that executes the requested task if a task is set.
- *
- * @param type $task - Contains the task to be executed.
- */
- function Execute($task)
- {
- switch($task)
- {
- case 'sign_in':
- SignIn();
- break;
- case 'verify_files':
- VerifyFiles();
- break;
- case 'get_movie':
- GetMovie();
- break;
- case 'get_episode':
- GetEpisode();
- break;
- case 'revoke_movie':
- RevokeMovie();
- break;
- case 'revoke_episode':
- RevokeEpisode();
- break;
- case 'grant_movie':
- GrantMovie();
- break;
- case 'grant_episode':
- GrantEpisode();
- break;
- case 'update_or_create':
- UpdateOrCreateUser();
- break;
- }
- }
- /**
- * Function that checks and verifies user data and sets up session variables on user login.
- */
- function SignIn()
- {
- //Grab credentials from the request.
- $user = $_POST['username'];
- $pass = $_POST['password'];
- //Create database connection
- $con = DBConnect();
- $con->Where('username', $user);
- $result = $con->FetchOne('users', 'user_id, password, is_teacher');
- if ($result)
- {
- $result = (object) $result;
- //Verify that passwords match
- if (password_verify($pass, $result->password))
- {
- //Setup session variables
- $_SESSION['user_id'] = $result->user_id;
- $_SESSION['is_teacher'] = $result->is_teacher;
- echo 1;
- }
- else
- {
- echo 2;
- }
- }
- else
- {
- echo 2;
- }
- }
- /**
- * Function that checks all the files before displaying them on page.
- *
- * @global string $movie_library - Path to movie files
- * @global string $show_library - Path to show files
- */
- function VerifyFiles()
- {
- global $movie_library, $show_library;
- //Grab the movies from the folder
- $movies = GetMovies($movie_library);
- if(!CheckMovies($movies))
- {
- echo 2;
- }
- //Grab the shows from the folder
- $shows = GetShows($show_library);
- if(!CheckShows($shows))
- {
- echo 2;
- }
- echo 1;
- }
- /**
- * Helper function that returns all the files in the movie folder.
- *
- * @param string $library - Path to the movie library
- * @return array - Array containing all the files in the Movies folder.
- */
- function GetMovies($library)
- {
- if($handle = opendir($library))
- {
- while (false != ($file = readdir($handle)))
- {
- //Exclude dot files.
- if ($file == '.' || $file == '..') continue;
- $files[] = $file;
- }
- closedir($handle);
- }
- return $files;
- }
- /**
- * Helper function that gets every folder in the show library - Excludes folders that do not contain any files.
- *
- * @param string $library - Path to the show library
- * @return array - Array containing all folders in the show library
- * @throws Exception
- */
- function GetShows($library)
- {
- //Setup array
- $directories = array();
- if(!is_dir($library))
- {
- throw new Exception('Library is not a folder');
- }
- if ($handle = opendir($library))
- {
- while (false != ($file = readdir($handle)))
- {
- //Exclude dot files
- if ($file == '.' || $file == '..') continue;
- //Exclude empty folders
- if (is_dir($library . $file))
- {
- if (count(glob($library . $file . '/*')) != 0)
- {
- $directories[] = $file;
- }
- }
- else
- {
- array_merge($directories, rendertask::getAllSubdirectories($library . $file));
- }
- }
- closedir($handle);
- }
- return $directories;
- }
- /**
- *
- * @global string $show_library - Path to the show library folder.
- * @param string $folder - Folder name for a specific show.
- * @return array - Array containing all the episodes for a show.
- */
- function GetEpisodes($folder)
- {
- global $show_library;
- if($handle = opendir($show_library . $folder . '/'))
- {
- while (false != ($file = readdir($handle)))
- {
- if ($file == '.' || $file == '..') continue;
- $files[] = $file;
- }
- closedir($handle);
- }
- return $files;
- }
- /**
- * Helper function that checks if movies exist in the database.
- *
- * @param array $movies - Array containing every movie file in the library.
- * @return boolean - Returns true once check completes.
- */
- function CheckMovies($movies)
- {
- //Create DB connection
- $con = DBConnect();
- //Loop through movies and check if they exist in the database.
- foreach($movies as $movie)
- {
- $con->Where("file_name", $movie);
- $exists = $con->FetchOne("movies", "file_name");
- if($exists)
- {
- //Do nothing.
- }
- else
- {
- //Add movie
- AddMovie($movie);
- }
- }
- return true;
- }
- /**
- * Helper function that checks if shows exist in the database.
- *
- * @param array $shows - Array containing all folders in the show library
- * @return boolean - Returns true once check has been completed.
- */
- function CheckShows($shows)
- {
- $con = Database::FetchInstance();
- foreach($shows as $show)
- {
- $con->Where("title", $show);
- $exists = $con->FetchOne("shows", "show_id, imdb_id");
- if ($exists)
- {
- //Get episodes for the show.
- $episodes = GetEpisodes($show);
- //Check if all episodes are created
- CheckEpisodes($episodes, $exists['show_id'], $exists['imdb_id']);
- }
- else
- {
- //Add show
- AddShow($show);
- }
- }
- return true;
- }
- /**
- * Helper function that checks episodes in the folder against episodes in the database.
- *
- * @param array $episodes - Array containing every file in a show folder.
- * @param int $show_id - ID of the show the episodes belong to.
- * @param string $imdb_id - imdb ID of the show the episodes belong to.
- */
- function CheckEpisodes($episodes, $show_id, $imdb_id)
- {
- $con = Database::FetchInstance();
- foreach($episodes as $episode)
- {
- //Split the episode title into segments.
- $title_segments = SplitEpisodeTitle($episode);
- //Check if the necessary season for each episode exists and create it if it does not.
- $season_id = CheckSeason($show_id, $title_segments['season'], $imdb_id);
- $con->Where("file_name", $episode);
- $con->Where("season_id", $season_id);
- $exists = $con->FetchOne("episodes", "title");
- if ($exists)
- {
- //Do nothing.
- }
- else
- {
- //Add episode
- AddEpisode($episode, $season_id, $title_segments['title'], $title_segments['episode'], $imdb_id);
- }
- }
- }
- /**
- * Helper function that checks if a season exists, creates it if it does not, and returns the ID.
- *
- * @param int $show_id - ID of the show the season belongs to.
- * @param int $season_number - The season number to be checked.
- * @param string $imdb_id - IMDB ID of the show.
- * @return int - Returns the ID of the season.
- */
- function CheckSeason($show_id, $season_number, $imdb_id)
- {
- $con = Database::FetchInstance();
- $con->Where("show_id", $show_id);
- $con->Where("season_number", $season_number);
- $exists = $con->FetchOne("seasons", "season_id");
- if($exists)
- {
- //Return ID.
- return $exists['season_id'];
- }
- else
- {
- //Add season and return ID.
- return AddSeason($show_id, $season_number, $imdb_id);
- }
- }
- /**
- * Helper function that gets the required data and creates a show in the database.
- *
- * @param string $show - The title of a show.
- */
- function AddShow($show)
- {
- //Get database instance
- $con = Database::FetchInstance();
- //Get the meta data for the show
- $meta = GetShowMetaData($show);
- //Set the prefix 'The' to be stripped to create the sort title.
- $prefix = 'The ';
- //Strip off the prefix if its present.
- if(substr($meta['name'], 0, strlen($prefix)) == $prefix)
- {
- $sort_title = substr($meta['name'], strlen($prefix));
- }
- else
- {
- $sort_title = $meta['name'];
- }
- //Loop through cast and assign to a string.
- foreach ($meta['credits']['cast'] as $castmember)
- {
- $cast .= $castmember['name'] . ',';
- }
- //Loop through genres and assign to a string
- foreach ($meta['genres'] as $genre)
- {
- $genres .= $genre['name'] . ',';
- }
- if ($meta['poster_path'] == null)
- {
- $poster = '';
- }
- else
- {
- $poster = 'http://image.tmdb.org/t/p/original' . $meta['poster_path'] . '?api_key=53e6f37de835a272473c977089ed74f7';
- }
- if ($meta['backdrop_path'] == null)
- {
- $backdrop = '';
- }
- else
- {
- $backdrop = 'http://image.tmdb.org/t/p/original' . $meta['backdrop_path'] . '?api_key=53e6f37de835a272473c977089ed74f7';
- }
- if ($cast == null)
- {
- $cast = "No cast information";
- }
- //Assign data for insertion
- $data = array(
- "title" => $meta['name'],
- "sort_title" => $sort_title,
- "cast" => $cast,
- "summary" => $meta['overview'],
- "genres" => $genres,
- "poster" => $poster,
- "backdrop" => $backdrop,
- "imdb_id" => $meta['id']
- );
- var_dump($data);
- $id = $con->Insert("shows", $data);
- if ($id)
- {
- //Get episodes
- $episodes = GetEpisodes($show);
- //Check episodes
- CheckEpisodes($episodes, $id, $meta['id']);
- }
- }
- /**
- * Helper function that creates a movie if it does not exist.
- *
- * @param string $movie - Name of a movie.
- */
- function AddMovie($movie)
- {
- global $movie_library;
- //Get Database instance
- $con = Database::FetchInstance();
- //Get the movie meta data.
- $meta = GetMovieMetaData($movie);
- //Create ID3 object for pulling file data.
- $getID3 = new getID3;
- //Analyze the movie file.
- $fileinfo = $getID3->analyze($movie_library . $movie);
- getid3_lib::CopyTagsToComments($fileinfo);
- //Set prefix for removal if necessary.
- $prefix = 'The ';
- //Strip prefix if present.
- if(substr($meta['title'], 0, strlen($prefix)) == $prefix)
- {
- $sort_title = substr($meta['title'], strlen($prefix));
- }
- else
- {
- $sort_title = $meta['title'];
- }
- //Find and assign directors and writers
- foreach ($meta['casts']['crew'] as $crew)
- {
- if($crew['job'] == 'Director')
- {
- $director .= $crew['name'] . ',';
- }
- elseif ($crew['job'] == 'Writer' || $crew['job'] == 'Screenplay')
- {
- $writer .= $crew['name'] . ',';
- }
- }
- //Loop through cast and assign to a string.
- foreach ($meta['casts']['cast'] as $castmember)
- {
- $cast .= $castmember['name'] . ',';
- }
- //Loop through genres and assign to a string
- foreach ($meta['genres'] as $genre)
- {
- $genres .= $genre['name'] . ',';
- }
- //If file is too big or info for some reason can't be read - Use the default runtime from metadata.
- if ($fileinfo['playtime_string'] == "")
- {
- $hours = floor((int)$meta['runtime'] / 60);
- $minutes = ((int)$meta['runtime'] - floor((int)$meta['runtime'] / 60) * 60);
- if (strlen($minutes) == 1)
- {
- $minutes = 0 . $minutes;
- }
- $runtime = $hours . ':' . $minutes . ':00';
- }
- else
- {
- $runtime = $fileinfo['playtime_string'];
- }
- //Assign data for insertion
- $data = array(
- "title" => $meta['title'],
- "sort_title" => $sort_title,
- "year" => date('Y', strtotime($meta['release_date'])),
- "runtime" => $runtime,
- "director" => $director,
- "writer" => $writer,
- "cast" => $cast,
- "summary" => $meta['overview'],
- "tagline" => $meta['tagline'],
- "genres" => $genres,
- "poster" => 'http://image.tmdb.org/t/p/original' . $meta['poster_path'] . '?api_key=53e6f37de835a272473c977089ed74f7',
- "backdrop" => 'http://image.tmdb.org/t/p/original' . $meta['backdrop_path'] . '?api_key=53e6f37de835a272473c977089ed74f7',
- "file_name" => $movie,
- "full_path" => $movie_library . $movie,
- "imdb_id" => $meta['imdb_id']
- );
- $con->Insert("movies", $data);
- }
- /**
- * Function that adds an episode to the database.
- *
- * @param string $episode - File name of the episode.
- * @param int $season_id - ID of the season the episode belongs to.
- * @param string $title - Title of the show the episode belongs to.
- * @param int $episode_number - Number of the episode in the season.
- * @param string $imdb_id - IMDB ID of the show.
- */
- function AddEpisode($episode, $season_id, $title, $episode_number, $imdb_id)
- {
- global $show_library;
- //Get database instance.
- $con = Database::FetchInstance();
- //Get the episode meta data.
- $meta = GetEpisodeMetaData($episode, $imdb_id);
- //Create ID3 object
- $getID3 = new getID3;
- //Analyze episode file.
- $fileinfo = $getID3->analyze($show_library . $title . '/' . $episode);
- getid3_lib::CopyTagsToComments($fileinfo);
- //If file is too big or info for some reason can't be read - Use the default runtime from metadata.
- if ($fileinfo['playtime_string'] == "")
- {
- $hours = floor((int)$meta['runtime'] / 60);
- $minutes = ((int)$meta['runtime'] - floor((int)$meta['runtime'] / 60) * 60);
- if (strlen($minutes) == 1)
- {
- $minutes = 0 . $minutes;
- }
- $runtime = $hours . ':' . $minutes . ':00';
- }
- else
- {
- $runtime = $fileinfo['playtime_string'];
- }
- //Assign data to be inserted
- $data = array(
- "title" => $meta['name'],
- "runtime" => $runtime,
- "summary" => $meta['overview'],
- "season_id" => $season_id,
- "episode_number" => $episode_number,
- "still_image" => 'http://image.tmdb.org/t/p/original' . $meta['still_path'] . '?api_key=53e6f37de835a272473c977089ed74f7',
- "file_name" => $episode,
- "full_path" => $show_library . $title . '/' . $episode
- );
- $con->Insert("episodes", $data);
- }
- /**
- * Function that creates a season for a show.
- *
- * @param int $show_id - ID of the show.
- * @param int $season_number - Number of the season
- * @param int $imdb_id - IMDB ID for the show.
- * @return int - ID of the newly created season.
- */
- function AddSeason($show_id, $season_number, $imdb_id)
- {
- //Get database instance
- $con = Database::FetchInstance();
- //Get season meta data.
- $meta = GetSeasonMetaData($imdb_id, $season_number);
- //Assign data to be inserted.
- $data = array(
- "show_id" => $show_id,
- "season_number" => $season_number,
- "poster" => 'http://image.tmdb.org/t/p/original' . $meta['poster_path'] . '?api_key=53e6f37de835a272473c977089ed74f7'
- );
- return $con->Insert("seasons", $data);
- }
- /**
- * Helper function that gets the meta data for a season of a show.
- *
- * @param string $show - Show folder name.
- * @param int $season - Season number of the requested season.
- * @return array - JSON array containing season meta data.
- */
- function GetSeasonMetaData($show, $season)
- {
- //Get the meta data.
- $metadata = file_get_contents('https://api.themoviedb.org/3/tv/' . $show . '/season/' . $season . '?api_key=53e6f37de835a272473c977089ed74f7&language=en-US');
- //Return data.
- return json_decode($metadata, true);
- }
- /**
- * Helper function that gets the meta data for a movie.
- *
- * @param string $movie - Movie file name.
- * @return array - JSON array containing movie meta data.
- */
- function GetMovieMetaData($movie)
- {
- //Split the title into title and year
- $title_segments = SplitMovieTitle($movie);
- //Replace spaces for search purposes.
- $encoded_title = str_replace(" ", "+", $title_segments['title']);
- //Search to find the movie ID.
- $search = file_get_contents('http://api.themoviedb.org/3/search/movie?api_key=53e6f37de835a272473c977089ed74f7&query=' . $encoded_title . '&year=' . $title_segments['year']);
- //Decode the data.
- $search = json_decode($search, true);
- //Get the ID of the best result
- $movie_id = $search['results'][0]['id'];
- //Get the meta data.
- $metadata = file_get_contents('https://api.themoviedb.org/3/movie/' . $movie_id . '?api_key=53e6f37de835a272473c977089ed74f7&append_to_response=casts');
- //Return data
- return json_decode($metadata, true);
- }
- /**
- * Helper function that gets the meta data for a show.
- *
- * @param string $show - Show folder name.
- * @return array - JSON array containing show meta data.
- */
- function GetShowMetaData($show)
- {
- //URL Encode the show folder.
- $encoded_title = str_replace(" ", "+", $show);
- //Search the API for the show.
- $search = file_get_contents('https://api.themoviedb.org/3/search/tv?api_key=53e6f37de835a272473c977089ed74f7&query=' . $encoded_title);
- //Decode the data.
- $search = json_decode($search, true);
- //Get the ID of the best result
- $show_id = $search['results'][0]['id'];
- //Get the Meta data for the show.
- $metadata = file_get_contents('https://api.themoviedb.org/3/tv/' . $show_id . '?api_key=53e6f37de835a272473c977089ed74f7&append_to_response=credits');
- //Return data.
- return json_decode($metadata, true);
- }
- /**
- * Helper function that gets the meta data for an episode of a show.
- *
- * @param string $episode - Episode file name.
- * @param string $imdb_id - IMDB Id of the show.
- * @return array - JSON array containing episode meta data.
- */
- function GetEpisodeMetaData($episode, $imdb_id)
- {
- //Split the title into title, season and episode.
- $title_segments = SplitEpisodeTitle($episode);
- //Grab meta data from the API
- $metadata = file_get_contents('https://api.themoviedb.org/3/tv/' . $imdb_id . '/season/' . $title_segments['season'] . '/episode/' . $title_segments['episode'] . '?api_key=53e6f37de835a272473c977089ed74f7');
- //Return data
- return json_decode($metadata, true);
- }
- /**
- * Helper function that splits a movie filename into title and year.
- *
- * @param string $filename - Filename of a movie
- * @return array - Array containing the segmented title - Title and year.
- */
- function SplitMovieTitle($filename)
- {
- // Get title
- $title = pathinfo($filename, PATHINFO_FILENAME);
- // Split title at spaces
- $explodedTitle = explode(' ', $title);
- // Get title and year
- $year = array_pop($explodedTitle);
- $titleNoYear = implode(' ', $explodedTitle);
- return array(
- 'title' => $titleNoYear,
- 'year' => $year
- );
- }
- /**
- * Helper function that splits an episode filename into title, season and episode.
- *
- * @param string $filename - Filename of an episode.
- * @return array - Array containing the segmented title - Title, Season and Episode.
- */
- function SplitEpisodeTitle($filename)
- {
- // Get title
- $title = pathinfo($filename, PATHINFO_FILENAME);
- // Split title at dash
- $explodedTitle = explode(' - S', $title);
- // Get title
- $titleClean = $explodedTitle[0];
- // Split season and episode data
- $explodedInfo = explode('E', end($explodedTitle));
- //Get Season and Episode
- $season = $explodedInfo[0];
- $episode = end($explodedInfo);
- return array(
- 'title' => $titleClean,
- 'season' => $season,
- 'episode' => $episode
- );
- }
- /**
- * Function that returns the necessary data for the player to play a movie.
- */
- function GetMovie()
- {
- //Get movie ID from ajax.
- $movie_id = $_POST['movie_id'];
- //Connect to the database
- $con = DBConnect();
- $con->Where("movie_id", $movie_id);
- $movie = $con->FetchOne("movies");
- //Return JSON movie data to the player.
- echo json_encode($movie);
- }
- /**
- * Function that returns the necessary data for the player to play an episode.
- */
- function GetEpisode()
- {
- //Get episode ID from Ajax
- $episode_id = $_POST['episode_id'];
- //Connect to the database
- $con = DBConnect();
- $con->Where("episode_id", $episode_id);
- $episode = $con->FetchOne("episodes");
- //Return JSON episode data to the player.
- echo json_encode($episode);
- }
- /**
- * Function that revokes access to a movie.
- */
- function RevokeMovie()
- {
- //Get the ID of the access from Ajax.
- $access_id = $_POST['access'];
- //Connect to the database
- $con = DBConnect();
- $con->Where('access_id', $access_id);
- //Delete the access.
- if ($con->Delete('movie_access'))
- {
- echo 1;
- }
- else
- {
- echo 2;
- }
- }
- /**
- * Function that revokes access to an episode.
- */
- function RevokeEpisode()
- {
- //Get the ID of the access from Ajax.
- $access_id = $_POST['access'];
- //Connect to the database
- $con = DBConnect();
- $con->Where('access_id', $access_id);
- //Delete the access
- if ($con->Delete('show_access'))
- {
- echo 1;
- }
- else
- {
- echo 2;
- }
- }
- /**
- * Function that grants access to a movie to the given usernames.
- */
- function GrantMovie()
- {
- //Connect to database
- $con = DBConnect();
- //Split the data sent from ajax.
- $file = explode(',', $_POST['file']);
- //Get the movie ID
- $movie_id = $file[1];
- //Split users into an array (If multiple).
- $userArr = explode(',', $_POST['users']);
- //create variable for the html
- $html = '';
- //Loop through users.
- foreach ($userArr as $username)
- {
- //Get the user and check if it exists.
- $user = GetUserByUsername($username);
- if($user)
- {
- //Check if the access already exists
- if(CheckAccessExists($user->user_id, $movie_id, 'Movie'))
- {
- //Do nothing.
- }
- else
- {
- //Assign data and create access.
- $access_data = Array (
- 'user_id' => $user->user_id,
- 'movie_id' => $movie_id
- );
- $access = $con->Insert('movie_access', $access_data);
- if ($access)
- {
- //Generate response html.
- $html .= GenerateMovieResponseRow($access);
- }
- }
- }
- else
- {
- //Assign data and create user.
- $data = Array (
- 'username' => $username,
- 'password' => password_hash('1234', PASSWORD_BCRYPT),
- 'is_teacher' => 0
- );
- $id = $con->Insert('users', $data);
- if ($id)
- {
- //Assign data and create access.
- $access_data = Array (
- 'user_id' => $id,
- 'movie_id' => $movie_id
- );
- $access = $con->Insert('movie_access', $access_data);
- if ($access)
- {
- //Generate response html.
- $html .= GenerateMovieResponseRow($access);
- }
- }
- }
- }
- echo $html;
- }
- /**
- * Function that grants access to an episode of a show to the given users.
- */
- function GrantEpisode()
- {
- //Connect to the database
- $con = DBConnect();
- //Split the file data sent from ajax.
- $file = explode(',', $_POST['file']);
- //Get the ID for the episode
- $episode_id = $file[1];
- //Split the users into an array (If multiple).
- $userArr = explode(',', $_POST['users']);
- //create variable for the html
- $html = '';
- //Loop through users.
- foreach ($userArr as $username)
- {
- //Get the user and check if it exists.
- $user = GetUserByUsername($username);
- if($user)
- {
- //Check if user already has the access
- if(CheckAccessExists($user->user_id, $episode_id, 'Show'))
- {
- //Do nothing.
- }
- else
- {
- //Get IDs for show, season and episode.
- $show = (object) GetShowIdsByEpisode($episode_id);
- //Assign data for insertion.
- $access_data = Array (
- 'user_id' => $user->user_id,
- 'show_id' => $show->show_id,
- 'season_id' => $show->season_id,
- 'episode_id' => $show->episode_id
- );
- $access = $con->Insert('show_access', $access_data);
- if ($access)
- {
- //Generate response html.
- $html .= GenerateShowResponseRow($access);
- }
- }
- }
- else
- {
- //Assign data and create user.
- $data = Array (
- 'username' => $username,
- 'password' => password_hash('1234', PASSWORD_BCRYPT),
- 'is_teacher' => 0
- );
- $id = $con->Insert('users', $data);
- if ($id)
- {
- //Get IDs for show, season and episode.
- $show = (object) GetShowIdsByEpisode($episode_id);
- //Assign data for insertion.
- $access_data = Array (
- 'user_id' => $user->user_id,
- 'show_id' => $show->show_id,
- 'season_id' => $show->season_id,
- 'episode_id' => $show->episode_id
- );
- $access = $con->Insert('show_access', $access_data);
- if ($access)
- {
- //Generate response html.
- $html .= GenerateShowResponseRow($access);
- }
- }
- }
- }
- echo $html;
- }
- /**
- * Helper function that creates the database connection.
- *
- * @global type $servername
- * @global type $username
- * @global type $password
- * @global type $database
- * @return Database - Returns database connection variable.
- */
- function DBConnect()
- {
- global $servername, $username, $password, $database;
- return new Database($servername, $username, $password, $database);
- }
- /**
- * Helper function that checks if a user already exists.
- *
- * @param int $username - Variable containing user to be checked.
- * @return boolean / User object - Returns user object if user exists and false if it does not.
- */
- function GetUserByUsername($username)
- {
- $con = Database::FetchInstance();
- $con->Where('username', $username);
- $user = $con->FetchAsObject()->FetchOne('users');
- if($user)
- {
- return $user;
- }
- else
- {
- return false;
- }
- }
- /**
- * Helper function that checks if access has already been granted to the requested file (Helps avoid duplicate entries).
- *
- * @param int $user_id - User ID of the user to be checked
- * @param int $file_id - ID of the file to be granted access to
- * @param string $file_type - Movie or Show.
- * @return boolean - Returns true or false based on if an access already exists.
- */
- function CheckAccessExists($user_id, $file_id, $file_type)
- {
- //Get database instance
- $con = Database::FetchInstance();
- //If the file is a movie
- if ($file_type == "Movie")
- {
- $con->Where('user_id', $user_id);
- $con->Where('movie_id', $file_id);
- if ($con->FetchOne('movie_access'))
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- else
- {
- $con->Where('user_id', $user_id);
- $con->Where('episode_id', $file_id);
- if($con->FetchOne('show_access'))
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- }
- /**
- * Helper function that gets the IDs for the show, season and episode - Used to output the correct data to the user.
- *
- * @param int $episode_id - Int containing the ID of the episode to grant access for.
- * @return array - Array containing IDs for the show, season and episode.
- */
- function GetShowIdsByEpisode($episode_id)
- {
- $con = Database::FetchInstance();
- //Setup show data query.
- $con->Join("seasons se", "e.season_id=se.season_id", "INNER");
- $con->Join("shows s", "se.show_id=s.show_id", "INNER");
- $con->Where("episode_id", $episode_id);
- $data = $con->FetchAsObject()->FetchOne('episodes e', 'e.episode_id, se.season_id, s.show_id');
- return array(
- 'episode_id' => $data->episode_id,
- 'season_id' => $data->season_id,
- 'show_id' => $data->show_id
- );
- }
- /**
- * Helper function that builds the HTML row for a new access - To be output on page upon completion.
- *
- * @param int $access_id - Int value of the newly created access.
- * @return string - html string containing the access row of current user and movie to be inserted on page.
- */
- function GenerateMovieResponseRow($access_id)
- {
- $con = Database::FetchInstance();
- //Setup movie access query.
- $con->Join("movies m", "a.movie_id=m.movie_id", "INNER");
- $con->Join("users u", "a.user_id=u.user_id", "INNER");
- $con->Where('access_id', $access_id);
- $access = $con->FetchAsObject()->FetchOne('movie_access a', 'a.access_id, u.username, m.title, a.created_date');
- $response = '<tr>';
- $response .= '<td>' . $access->username . '</td>';
- $response .= '<td>' . $access->title . '</td>';
- $response .= '<td>' . date("d/m/Y H:i", strtotime($access->created_date)) . '</td>';
- $response .= '<td class="RevokeMovieAccess"><a class="TableButton RevokeMovieAccessButton" data-accessid="' . $access->access_id . '"><i class="fa fa-times" aria-hidden="true"></i></a></td>';
- $response .= '</tr>';
- return $response;
- }
- function GenerateShowResponseRow($access_id)
- {
- $con = Database::FetchInstance();
- //Setup show access query.
- $con->Join("shows s", "a.show_id=s.show_id", "INNER");
- $con->Join("seasons se", "a.season_id=se.season_id", "INNER");
- $con->Join("episodes e", "a.episode_id=e.episode_id", "INNER");
- $con->Join("users u", "a.user_id=u.user_id", "INNER");
- $con->Where('access_id', $access_id);
- $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');
- if ($access->episode_number < 10)
- {
- $episode = '0' . $access->episode_number;
- }
- else
- {
- $episode = $access->episode_number;
- }
- $response .= '<tr>';
- $response .= '<td>' . $access->username . '</td>';
- $response .= '<td>' . $access->show_title . '</td>';
- $response .= '<td>S' . $access->season_number . 'E' . $episode . ' — ' . $access->episode_title . '</td>';
- $response .= '<td>' . date("d/m/Y H:i", strtotime($access->created_date)) . '</td>';
- $response .= '<td class="RevokeMovieAccess"><a class="TableButton RevokeShowAccessButton" data-accessid="' . $access->access_id . '"><i class="fa fa-times" aria-hidden="true"></i></a></td>';
- $response .= '</tr>';
- return $response;
- }
- function UpdateOrCreateUser()
- {
- //Get variables from ajax.
- $username = $_POST['username'];
- $password = $_POST['password'];
- //Create database connection
- $con = DBConnect();
- //Check if the user already exists
- $user = GetUserByUsername($username);
- if ($user)
- {
- //Assign data to be updated
- $data = Array (
- 'password' => password_hash($password, PASSWORD_BCRYPT)
- );
- $con->Where('username', $username);
- if ($con->Update('users', $data))
- {
- echo 1;
- }
- else
- {
- echo 2;
- }
- }
- else
- {
- //Assign data and create user
- $data = Array (
- 'username' => $username,
- 'password' => password_hash($password, PASSWORD_BCRYPT),
- 'is_teacher' => 1
- );
- $id = $con->Insert('users', $data);
- if ($id)
- {
- echo 1;
- }
- else
- {
- echo 2;
- }
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement