<commit_before><?php

class Application_Model_Schedule {

    /**
     * Return true if there is nothing in the schedule for the given start time
     * up to the length of time after that.
     *
     * @param string $p_datetime
     *    In the format YYYY-MM-DD HH:MM:SS.mmmmmm
     * @param string $p_length
     *    In the format HH:MM:SS.mmmmmm
     * @return boolean|PEAR_Error
     */
    public static function isScheduleEmptyInRange($p_datetime, $p_length) {
        global $CC_CONFIG, $CC_DBC;
        if (empty($p_length)) {
            return new PEAR_Error("Application_Model_Schedule::isSchedulerEmptyInRange: param p_length is empty.");
        }
        $sql = "SELECT COUNT(*) FROM ".$CC_CONFIG["scheduleTable"]
        ." WHERE (starts >= '$p_datetime') "
        ." AND (ends <= (TIMESTAMP '$p_datetime' + INTERVAL '$p_length'))";
        //$_SESSION["debug"] = $sql;
        //echo $sql;
        $count = $CC_DBC->GetOne($sql);
        //var_dump($count);
        return ($count == '0');
    }

    /**
     * Return TRUE if file is going to be played in the future.
     *
     * @param string $p_fileId
     */
    public function IsFileScheduledInTheFuture($p_fileId)
    {
        global $CC_CONFIG, $CC_DBC;
        $sql = "SELECT COUNT(*) FROM ".$CC_CONFIG["scheduleTable"]
        ." WHERE file_id = {$p_fileId} AND starts > NOW()";
        $count = $CC_DBC->GetOne($sql);
        if (is_numeric($count) && ($count != '0')) {
            return TRUE;
        } else {
            return FALSE;
        }
    }


    /**
     * Returns array indexed by:
     *    "playlistId"/"playlist_id" (aliases to the same thing)
     *    "start"/"starts" (aliases to the same thing) as YYYY-MM-DD HH:MM:SS.nnnnnn
     *    "end"/"ends" (aliases to the same thing) as YYYY-MM-DD HH:MM:SS.nnnnnn
     *    "group_id"/"id" (aliases to the same thing)
     *    "clip_length" (for audio clips this is the length of the audio clip,
     *                   for playlists this is the length of the entire playlist)
     *    "name" (playlist only)
     *    "creator" (playlist only)
     *    "file_id" (audioclip only)
     *    "count" (number of items in the playlist, always 1 for audioclips.
     *      Note that playlists with one item will also have count = 1.
     *
     * @param string $p_fromDateTime
     *    In the format YYYY-MM-DD HH:MM:SS.nnnnnn
     * @param string $p_toDateTime
     *    In the format YYYY-MM-DD HH:MM:SS.nnnnnn
     * @param boolean $p_playlistsOnly
     *    Retrieve playlists as a single item.
     * @return array
     *      Returns empty array if nothing found
     */

    public static function GetItems($p_currentDateTime, $p_toDateTime, $p_playlistsOnly = true)
    {
        global $CC_CONFIG, $CC_DBC;
        $rows = array();
        if (!$p_playlistsOnly) {
            $sql = "SELECT * FROM ".$CC_CONFIG["scheduleTable"]
            ." WHERE (starts >= TIMESTAMP '$p_currentDateTime') "
            ." AND (ends <= TIMESTAMP '$p_toDateTime')";
            $rows = $CC_DBC->GetAll($sql);
            foreach ($rows as &$row) {
                $row["count"] = "1";
                $row["playlistId"] = $row["playlist_id"];
                $row["start"] = $row["starts"];
                $row["end"] = $row["ends"];
                $row["id"] = $row["group_id"];
            }
        } else {
            $sql = "SELECT MIN(pt.creator) AS creator,"
            ." st.group_id,"
            ." SUM(st.clip_length) AS clip_length,"
            ." MIN(st.file_id) AS file_id,"
            ." COUNT(*) as count,"
            ." MIN(st.playlist_id) AS playlist_id,"
            ." MIN(st.starts) AS starts,"
            ." MAX(st.ends) AS ends,"
            ." MIN(sh.name) AS show_name,"
            ." MIN(si.starts) AS show_start,"
            ." MAX(si.ends) AS show_end"
            ." FROM $CC_CONFIG[scheduleTable] as st"
            ." LEFT JOIN $CC_CONFIG[playListTable] as pt"
            ." ON st.playlist_id = pt.id"
            ." LEFT JOIN $CC_CONFIG[showInstances] as si"
            ." ON st.instance_id = si.id"
            ." LEFT JOIN $CC_CONFIG[showTable] as sh"
            ." ON si.show_id = sh.id"
            //The next line ensures we only get songs that haven't ended yet
            ." WHERE (st.ends >= TIMESTAMP '$p_currentDateTime')"
            ." AND (st.ends <= TIMESTAMP '$p_toDateTime')"
            //next line makes sure that we aren't returning items that
            //are past the show's scheduled timeslot.
            ." AND (st.starts < si.ends)"
            ." GROUP BY st.group_id"
            ." ORDER BY starts";

            $rows = $CC_DBC->GetAll($sql);
            if (!PEAR::isError($rows)) {
                foreach ($rows as &$row) {
                    $row["playlistId"] = $row["playlist_id"];
                    $row["start"] = $row["starts"];
                    $row["end"] = $row["ends"];
                    $row["id"] = $row["group_id"];
                }
            }
        }
        return $rows;
    }

    /**
     * Returns data related to the scheduled items.
     *
     * @param int $prev
     * @param int $next
     * @return date
     */
    public static function GetPlayOrderRange($prev = 1, $next = 1)
    {
        if (!is_int($prev) || !is_int($next)){
            //must enter integers to specify ranges
            return array();
        }

        global $CC_CONFIG;

        $date = new Application_Model_DateHelper;
        $timeNow = $date->getTimestamp();
        $utcTimeNow = $date->getUtcTimestamp();
        $currentShow = Application_Model_Show::GetCurrentShow($utcTimeNow);
        $results = Application_Model_Schedule::GetPrevCurrentNext($utcTimeNow);
        
        $range = array("env"=>APPLICATION_ENV,
            "schedulerTime"=>$timeNow,
            "previous"=>$results['previous'],
            "current"=>$results['current'],
            "next"=>$results['next'],
            "currentShow"=>$currentShow,
            "nextShow"=>"",//Application_Model_Show::GetNextShows($utcTimeNow, 1),
            "timezone"=> date("T"),
            "timezoneOffset"=> date("Z"));
                     
        return $range;
    }
    
    /**
     * Queries the database for the set of schedules one hour before and after the given time.
     * If a show starts and ends within that time that is considered the current show. Then the
     * scheduled item before it is the previous show, and the scheduled item after it is the next
     * show. This way the dashboard getCurrentPlaylist is very fast. But if any one of the three
     * show types are not found through this mechanism a call is made to the old way of querying
     * the database to find the track info.
    **/
    public static function GetPrevCurrentNext($p_timeNow)
    {
        global $CC_CONFIG, $CC_DBC;
        
        
        $sql = "Select ft.artist_name, ft.track_title, st.starts as starts, st.ends as ends, st.media_item_played as media_item_played
                FROM cc_schedule st LEFT JOIN cc_files ft ON st.file_id = ft.id LEFT JOIN cc_show_instances sit ON st.instance_id = sit.id
                WHERE st.starts > (TIMESTAMP '$p_timeNow'-INTERVAL '1 hours') AND st.starts < (TIMESTAMP '$p_timeNow'+INTERVAL '1 hours') AND st.starts < sit.ends
                ORDER BY st.starts";
        $row = $CC_DBC->GetAll($sql);
        
        $numberOfRows = count($row);
        $results;
        
        $timeNowAsMillis = strtotime($p_timeNow);
        for( $i = 0; $i < $numberOfRows && !isset($results); ++$i ){
            if ((strtotime($row[$i]['starts']) <= $timeNowAsMillis) && (strtotime($row[$i]['ends']) >= $timeNowAsMillis)){
                if ( $i - 1 >= 0){
                    $results['previous'] = array("name"=>$row[$i-1]["artist_name"]." - ".$row[$i-1]["track_title"],
                            "starts"=>$row[$i-1]["starts"],
                            "ends"=>$row[$i-1]["ends"]);
                }
                $results['current'] =  array("name"=>$row[$i]["artist_name"]." - ".$row[$i]["track_title"],
                            "starts"=>$row[$i]["starts"],
                            "ends"=>$row[$i]["ends"],
                            "media_item_played"=>$row[0]["media_item_played"],
                            "record"=>0);
                if ( $i +1 <= $numberOfRows){
                    $results['next'] =  array("name"=>$row[$i+1]["artist_name"]." - ".$row[$i+1]["track_title"],
                            "starts"=>$row[$i+1]["starts"],
                            "ends"=>$row[$i+1]["ends"]);
                }<commit_msg>CC-3337: Optimize Schedule/get-current-playlist/format/json - I've updated the time interval used to search for the next, current and previously secheduled shows to 24 hours before and after from 1 hour.<commit_after><?php

class Application_Model_Schedule {

    /**
     * Return true if there is nothing in the schedule for the given start time
     * up to the length of time after that.
     *
     * @param string $p_datetime
     *    In the format YYYY-MM-DD HH:MM:SS.mmmmmm
     * @param string $p_length
     *    In the format HH:MM:SS.mmmmmm
     * @return boolean|PEAR_Error
     */
    public static function isScheduleEmptyInRange($p_datetime, $p_length) {
        global $CC_CONFIG, $CC_DBC;
        if (empty($p_length)) {
            return new PEAR_Error("Application_Model_Schedule::isSchedulerEmptyInRange: param p_length is empty.");
        }
        $sql = "SELECT COUNT(*) FROM ".$CC_CONFIG["scheduleTable"]
        ." WHERE (starts >= '$p_datetime') "
        ." AND (ends <= (TIMESTAMP '$p_datetime' + INTERVAL '$p_length'))";
        //$_SESSION["debug"] = $sql;
        //echo $sql;
        $count = $CC_DBC->GetOne($sql);
        //var_dump($count);
        return ($count == '0');
    }

    /**
     * Return TRUE if file is going to be played in the future.
     *
     * @param string $p_fileId
     */
    public function IsFileScheduledInTheFuture($p_fileId)
    {
        global $CC_CONFIG, $CC_DBC;
        $sql = "SELECT COUNT(*) FROM ".$CC_CONFIG["scheduleTable"]
        ." WHERE file_id = {$p_fileId} AND starts > NOW()";
        $count = $CC_DBC->GetOne($sql);
        if (is_numeric($count) && ($count != '0')) {
            return TRUE;
        } else {
            return FALSE;
        }
    }


    /**
     * Returns array indexed by:
     *    "playlistId"/"playlist_id" (aliases to the same thing)
     *    "start"/"starts" (aliases to the same thing) as YYYY-MM-DD HH:MM:SS.nnnnnn
     *    "end"/"ends" (aliases to the same thing) as YYYY-MM-DD HH:MM:SS.nnnnnn
     *    "group_id"/"id" (aliases to the same thing)
     *    "clip_length" (for audio clips this is the length of the audio clip,
     *                   for playlists this is the length of the entire playlist)
     *    "name" (playlist only)
     *    "creator" (playlist only)
     *    "file_id" (audioclip only)
     *    "count" (number of items in the playlist, always 1 for audioclips.
     *      Note that playlists with one item will also have count = 1.
     *
     * @param string $p_fromDateTime
     *    In the format YYYY-MM-DD HH:MM:SS.nnnnnn
     * @param string $p_toDateTime
     *    In the format YYYY-MM-DD HH:MM:SS.nnnnnn
     * @param boolean $p_playlistsOnly
     *    Retrieve playlists as a single item.
     * @return array
     *      Returns empty array if nothing found
     */

    public static function GetItems($p_currentDateTime, $p_toDateTime, $p_playlistsOnly = true)
    {
        global $CC_CONFIG, $CC_DBC;
        $rows = array();
        if (!$p_playlistsOnly) {
            $sql = "SELECT * FROM ".$CC_CONFIG["scheduleTable"]
            ." WHERE (starts >= TIMESTAMP '$p_currentDateTime') "
            ." AND (ends <= TIMESTAMP '$p_toDateTime')";
            $rows = $CC_DBC->GetAll($sql);
            foreach ($rows as &$row) {
                $row["count"] = "1";
                $row["playlistId"] = $row["playlist_id"];
                $row["start"] = $row["starts"];
                $row["end"] = $row["ends"];
                $row["id"] = $row["group_id"];
            }
        } else {
            $sql = "SELECT MIN(pt.creator) AS creator,"
            ." st.group_id,"
            ." SUM(st.clip_length) AS clip_length,"
            ." MIN(st.file_id) AS file_id,"
            ." COUNT(*) as count,"
            ." MIN(st.playlist_id) AS playlist_id,"
            ." MIN(st.starts) AS starts,"
            ." MAX(st.ends) AS ends,"
            ." MIN(sh.name) AS show_name,"
            ." MIN(si.starts) AS show_start,"
            ." MAX(si.ends) AS show_end"
            ." FROM $CC_CONFIG[scheduleTable] as st"
            ." LEFT JOIN $CC_CONFIG[playListTable] as pt"
            ." ON st.playlist_id = pt.id"
            ." LEFT JOIN $CC_CONFIG[showInstances] as si"
            ." ON st.instance_id = si.id"
            ." LEFT JOIN $CC_CONFIG[showTable] as sh"
            ." ON si.show_id = sh.id"
            //The next line ensures we only get songs that haven't ended yet
            ." WHERE (st.ends >= TIMESTAMP '$p_currentDateTime')"
            ." AND (st.ends <= TIMESTAMP '$p_toDateTime')"
            //next line makes sure that we aren't returning items that
            //are past the show's scheduled timeslot.
            ." AND (st.starts < si.ends)"
            ." GROUP BY st.group_id"
            ." ORDER BY starts";

            $rows = $CC_DBC->GetAll($sql);
            if (!PEAR::isError($rows)) {
                foreach ($rows as &$row) {
                    $row["playlistId"] = $row["playlist_id"];
                    $row["start"] = $row["starts"];
                    $row["end"] = $row["ends"];
                    $row["id"] = $row["group_id"];
                }
            }
        }
        return $rows;
    }

    /**
     * Returns data related to the scheduled items.
     *
     * @param int $prev
     * @param int $next
     * @return date
     */
    public static function GetPlayOrderRange($prev = 1, $next = 1)
    {
        if (!is_int($prev) || !is_int($next)){
            //must enter integers to specify ranges
            return array();
        }

        global $CC_CONFIG;

        $date = new Application_Model_DateHelper;
        $timeNow = $date->getTimestamp();
        $utcTimeNow = $date->getUtcTimestamp();
        $currentShow = Application_Model_Show::GetCurrentShow($utcTimeNow);
        $results = Application_Model_Schedule::GetPrevCurrentNext($utcTimeNow);
        
        $range = array("env"=>APPLICATION_ENV,
            "schedulerTime"=>$timeNow,
            "previous"=>$results['previous'],
            "current"=>$results['current'],
            "next"=>$results['next'],
            "currentShow"=>$currentShow,
            "nextShow"=>"",//Application_Model_Show::GetNextShows($utcTimeNow, 1),
            "timezone"=> date("T"),
            "timezoneOffset"=> date("Z"));
                     
        return $range;
    }
    
    /**
     * Queries the database for the set of schedules one hour before and after the given time.
     * If a show starts and ends within that time that is considered the current show. Then the
     * scheduled item before it is the previous show, and the scheduled item after it is the next
     * show. This way the dashboard getCurrentPlaylist is very fast. But if any one of the three
     * show types are not found through this mechanism a call is made to the old way of querying
     * the database to find the track info.
    **/
    public static function GetPrevCurrentNext($p_timeNow)
    {
        global $CC_CONFIG, $CC_DBC;
        
        
        $sql = "Select ft.artist_name, ft.track_title, st.starts as starts, st.ends as ends, st.media_item_played as media_item_played
                FROM cc_schedule st LEFT JOIN cc_files ft ON st.file_id = ft.id LEFT JOIN cc_show_instances sit ON st.instance_id = sit.id
                WHERE st.starts > (TIMESTAMP '$p_timeNow'-INTERVAL '24 hours') AND st.starts < (TIMESTAMP '$p_timeNow'+INTERVAL '24 hours') AND st.starts < sit.ends
                ORDER BY st.starts";
        $row = $CC_DBC->GetAll($sql);
        
        $numberOfRows = count($row);
        $results;
        
        $timeNowAsMillis = strtotime($p_timeNow);
        for( $i = 0; $i < $numberOfRows && !isset($results); ++$i ){
            if ((strtotime($row[$i]['starts']) <= $timeNowAsMillis) && (strtotime($row[$i]['ends']) >= $timeNowAsMillis)){
                if ( $i - 1 >= 0){
                    $results['previous'] = array("name"=>$row[$i-1]["artist_name"]." - ".$row[$i-1]["track_title"],
                            "starts"=>$row[$i-1]["starts"],
                            "ends"=>$row[$i-1]["ends"]);
                }
                $results['current'] =  array("name"=>$row[$i]["artist_name"]." - ".$row[$i]["track_title"],
                            "starts"=>$row[$i]["starts"],
                            "ends"=>$row[$i]["ends"],
                            "media_item_played"=>$row[0]["media_item_played"],
                            "record"=>0);
                if ( $i +1 <= $numberOfRows){
                    $results['next'] =  array("name"=>$row[$i+1]["artist_name"]." - ".$row[$i+1]["track_title"],
                            "starts"=>$row[$i+1]["starts"],
                            "ends"=>$row[$i+1]["ends"]);
                }
{'fraction_non_alphanumeric': 0.14163509013664025, 'fraction_numerical': 0.003272476748191526, 'mean_word_length': 1.925104953820319, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 71, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5618061', 'n_tokens_mistral': 5438, 'n_tokens_neox': 5271, 'n_words': 1355}