<commit_before><?php

class ApiController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
        $context = $this->_helper->getHelper('contextSwitch');
        $context->addActionContext('version', 'json')
                ->addActionContext('recorded-shows', 'json')
                ->addActionContext('upload-file', 'json')
                ->addActionContext('upload-recorded', 'json')
                ->addActionContext('media-monitor-setup', 'json')
                ->addActionContext('media-item-status', 'json')
                ->addActionContext('reload-metadata', 'json')
                ->initContext();
    }

    public function indexAction()
    {
        // action body
    }

    /**
     * Returns Airtime version. i.e "1.7.0 alpha"
     *
     * First checks to ensure the correct API key was
     * supplied, then returns AIRTIME_VERSION as defined
     * in application/conf.php
     *
     * @return void
     *
     */
    public function versionAction()
    {
        global $CC_CONFIG;

        // disable the view and the layout
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        $api_key = $this->_getParam('api_key');
        if (!in_array($api_key, $CC_CONFIG["apiKey"]))
        {
            header('HTTP/1.0 401 Unauthorized');
            print 'You are not allowed to access this resource.';
            exit;
        }
        $jsonStr = json_encode(array("version"=>AIRTIME_VERSION));
        echo $jsonStr;
    }

    /**
     * Allows remote client to download requested media file.
     *
     * @return void
     *
     */
    public function getMediaAction()
    {
        global $CC_CONFIG;

        // disable the view and the layout
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        $api_key = $this->_getParam('api_key');
        $download = ("true" == $this->_getParam('download'));

        if(!in_array($api_key, $CC_CONFIG["apiKey"]))
        {
            header('HTTP/1.0 401 Unauthorized');
            print 'You are not allowed to access this resource.';
            exit;
        }

        $filename = $this->_getParam("file");
        $file_id = substr($filename, 0, strpos($filename, "."));
        if (ctype_alnum($file_id) && strlen($file_id) == 32) {
          $media = StoredFile::RecallByGunid($file_id);
          if ($media != null && !PEAR::isError($media)) {
            $filepath = $media->getFilePath();
            if(!is_file($filepath))
            {
                header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
                //print 'Resource in database, but not in storage. Sorry.';
                exit;
            }

            // possibly use fileinfo module here in the future.
            // http://www.php.net/manual/en/book.fileinfo.php
            $ext = pathinfo($filename, PATHINFO_EXTENSION);
            if ($ext == "ogg")
                header("Content-Type: audio/ogg");
            else if ($ext == "mp3")
                header("Content-Type: audio/mpeg");
            if ($download){
                //path_info breaks up a file path into seperate pieces of informaiton.
                //We just want the basename which is the file name with the path
                //information stripped away. We are using Content-Disposition to specify
                //to the browser what name the file should be saved as.
                $path_parts = pathinfo($media->getPropelOrm()->getDbFilepath());
                header('Content-Disposition: attachment; filename="'.$path_parts['basename'].'"');
            }
            header("Content-Length: " . filesize($filepath));

            // !! binary mode !!
            $fp = fopen($filepath, 'rb');

            //We can have multiple levels of output buffering. Need to
            //keep looping until all have been disabled!!!
            //http://www.php.net/manual/en/function.ob-end-flush.php
            while (@ob_end_flush());

            fpassthru($fp);
            fclose($fp);

            return;
          }
      }
      header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
      exit;
    }

    public function liveInfoAction()
    {
        if (Application_Model_Preference::GetAllow3rdPartyApi()){
            // disable the view and the layout
            $this->view->layout()->disableLayout();
            $this->_helper->viewRenderer->setNoRender(true);

            $date = new DateHelper;
            $timeNow = $date->getTimestamp();
            $result = array("env"=>APPLICATION_ENV,
                "schedulerTime"=>gmdate("Y-m-d H:i:s"),
                "currentShow"=>Show_DAL::GetCurrentShow($timeNow),<commit_msg>added logging to ApiController::getMediaAction<commit_after><?php

class ApiController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
        $context = $this->_helper->getHelper('contextSwitch');
        $context->addActionContext('version', 'json')
                ->addActionContext('recorded-shows', 'json')
                ->addActionContext('upload-file', 'json')
                ->addActionContext('upload-recorded', 'json')
                ->addActionContext('media-monitor-setup', 'json')
                ->addActionContext('media-item-status', 'json')
                ->addActionContext('reload-metadata', 'json')
                ->initContext();
    }

    public function indexAction()
    {
        // action body
    }

    /**
     * Returns Airtime version. i.e "1.7.0 alpha"
     *
     * First checks to ensure the correct API key was
     * supplied, then returns AIRTIME_VERSION as defined
     * in application/conf.php
     *
     * @return void
     *
     */
    public function versionAction()
    {
        global $CC_CONFIG;

        // disable the view and the layout
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        $api_key = $this->_getParam('api_key');
        if (!in_array($api_key, $CC_CONFIG["apiKey"]))
        {
            header('HTTP/1.0 401 Unauthorized');
            print 'You are not allowed to access this resource.';
            exit;
        }
        $jsonStr = json_encode(array("version"=>AIRTIME_VERSION));
        echo $jsonStr;
    }

    /**
     * Allows remote client to download requested media file.
     *
     * @return void
     *
     */
    public function getMediaAction()
    {
        global $CC_CONFIG;

        // disable the view and the layout
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        $api_key = $this->_getParam('api_key');
        $download = ("true" == $this->_getParam('download'));

        $logger = Logging::getLogger();

        if(!in_array($api_key, $CC_CONFIG["apiKey"]))
        {
            header('HTTP/1.0 401 Unauthorized');
            print 'You are not allowed to access this resource.';
            $logger->info("401 Unauthorized");
            return;
        }

        $filename = $this->_getParam("file");
        $file_id = substr($filename, 0, strpos($filename, "."));
        if (ctype_alnum($file_id) && strlen($file_id) == 32) {
          $media = StoredFile::RecallByGunid($file_id);
          if ($media != null && !PEAR::isError($media)) {
            $filepath = $media->getFilePath();
            if(is_file($filepath)){
                // possibly use fileinfo module here in the future.
                // http://www.php.net/manual/en/book.fileinfo.php
                $ext = pathinfo($filename, PATHINFO_EXTENSION);
                if ($ext == "ogg")
                    header("Content-Type: audio/ogg");
                else if ($ext == "mp3")
                    header("Content-Type: audio/mpeg");
                if ($download){
                    //path_info breaks up a file path into seperate pieces of informaiton.
                    //We just want the basename which is the file name with the path
                    //information stripped away. We are using Content-Disposition to specify
                    //to the browser what name the file should be saved as.
                    $path_parts = pathinfo($media->getPropelOrm()->getDbFilepath());
                    header('Content-Disposition: attachment; filename="'.$path_parts['basename'].'"');
                }
                header("Content-Length: " . filesize($filepath));

                // !! binary mode !!
                $fp = fopen($filepath, 'rb');

                //We can have multiple levels of output buffering. Need to
                //keep looping until all have been disabled!!!
                //http://www.php.net/manual/en/function.ob-end-flush.php
                while (@ob_end_flush());

                fpassthru($fp);
                fclose($fp);

                //make sure to exit here so that no other output is sent.
                exit;                
            } else {
                $logger->err('Resource in database, but not in storage: '.$filepath.' '.is_file($filepath));
            }
          } else {
            $logger->err('$media != null && !PEAR::isError($media)');
          }
      } else {
        $logger->err('ctype_alnum($file_id) && strlen($file_id) == 32');
      }
      header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
      $logger->info("404 Not Found");
      return;
    }

    public function liveInfoAction()
    {
        if (Application_Model_Preference::GetAllow3rdPartyApi()){
            // disable the view and the layout
            $this->view->layout()->disableLayout();
            $this->_helper->viewRenderer->setNoRender(true);

            $date = new DateHelper;
            $timeNow = $date->getTimestamp();
            $result = array("env"=>APPLICATION_ENV,
                "schedulerTime"=>gmdate("Y-m-d H:i:s"),
                "currentShow"=>Show_DAL::GetCurrentShow($timeNow),
{'fraction_non_alphanumeric': 0.13731729143879884, 'fraction_numerical': 0.005269961221040072, 'mean_word_length': 1.8844278749641525, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 88, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1884239', 'n_tokens_mistral': 2803, 'n_tokens_neox': 2658, 'n_words': 629}