Wrapped json_encode call in PHP version check

This commit is contained in:
Duncan Sommerville 2014-10-28 13:29:35 -04:00
parent 1a90184a69
commit 53c4301024
1 changed files with 194 additions and 119 deletions

View File

@ -6,7 +6,7 @@ class ApiController extends Zend_Controller_Action
public function init()
{
$ignoreAuth = array("live-info", "live-info-v2", "week-info",
"station-metadata", "station-logo");
"station-metadata", "station-logo", "show-logo");
$params = $this->getRequest()->getParams();
if (!in_array($params['action'], $ignoreAuth)) {
@ -301,6 +301,8 @@ class ApiController extends Zend_Controller_Action
$result["schedulerTime"] = Application_Common_DateHelper::UTCStringToTimezoneString($result["schedulerTime"], $timezone);
$result["timezone"] = $upcase ? strtoupper($timezone) : $timezone;
$result["timezoneOffset"] = Application_Common_DateHelper::getTimezoneOffset($timezone);
// convert image paths to point to api endpoints
$this->findAndConvertPaths($result);
// used by caller to determine if the airtime they are running or widgets in use is out of date.
$result['AIRTIME_API_VERSION'] = AIRTIME_API_VERSION;
@ -373,6 +375,8 @@ class ApiController extends Zend_Controller_Action
$this->convertSpecialChars($result, array("name", "url"));
// apply user-defined timezone, or default to station
$this->applyLiveTimezoneAdjustments($result, $timezone, $upcase);
// convert image paths to point to api endpoints
$this->findAndConvertPaths($result);
// used by caller to determine if the airtime they are running or widgets in use is out of date.
$result["station"]["AIRTIME_API_VERSION"] = AIRTIME_API_VERSION;
@ -429,14 +433,14 @@ class ApiController extends Zend_Controller_Action
private function applyLiveTimezoneAdjustments(&$result, $timezone, $upcase)
{
Application_Common_DateHelper::convertTimestampsToTimezone(
$result,
array("starts", "ends", "start_timestamp","end_timestamp"),
$timezone
$result,
array("starts", "ends", "start_timestamp","end_timestamp"),
$timezone
);
//Convert the UTC scheduler time ("now") to the user-defined timezone.
$result["station"]["schedulerTime"] = Application_Common_DateHelper::UTCStringToTimezoneString($result["station"]["schedulerTime"], $timezone);
$result["station"]["timezone"] = $upcase ? strtoupper($timezone) : $timezone;
//Convert the UTC scheduler time ("now") to the user-defined timezone.
$result["station"]["schedulerTime"] = Application_Common_DateHelper::UTCStringToTimezoneString($result["station"]["schedulerTime"], $timezone);
$result["station"]["timezone"] = $upcase ? strtoupper($timezone) : $timezone;
}
public function weekInfoAction()
@ -467,7 +471,6 @@ class ApiController extends Zend_Controller_Action
$weekStartDateTime->setTimezone($utcTimezone);
$utcDayStart = $weekStartDateTime->format("Y-m-d H:i:s");
for ($i = 0; $i < 14; $i++) {
//have to be in station timezone when adding 1 day for daylight savings.
$weekStartDateTime->setTimezone(new DateTimeZone($timezone));
$weekStartDateTime->add(new DateInterval('P1D'));
@ -491,12 +494,18 @@ class ApiController extends Zend_Controller_Action
// XSS exploit prevention
$this->convertSpecialChars($result, array("name", "url"));
// convert image paths to point to api endpoints
$this->findAndConvertPaths($result);
//used by caller to determine if the airtime they are running or widgets in use is out of date.
$result['AIRTIME_API_VERSION'] = AIRTIME_API_VERSION;
header("Content-type: text/javascript");
$js = json_encode($result, JSON_PRETTY_PRINT);
if (version_compare(phpversion(), '5.4.0', '<')) {
$js = json_encode($result);
} else {
$js = json_encode($result, JSON_PRETTY_PRINT);
}
// If a callback is not given, then just provide the raw JSON.
echo isset($_GET['callback']) ? $_GET['callback'].'('.$js.')' : $js;
} else {
@ -506,61 +515,12 @@ class ApiController extends Zend_Controller_Action
}
}
public function scheduleAction()
{
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
header("Content-Type: application/json");
$data = Application_Model_Schedule::getSchedule();
echo json_encode($data, JSON_FORCE_OBJECT);
}
public function notifyMediaItemStartPlayAction()
{
$media_id = $this->_getParam("media_id");
Logging::debug("Received notification of new media item start: $media_id");
Application_Model_Schedule::UpdateMediaPlayedStatus($media_id);
try {
$historyService = new Application_Service_HistoryService();
$historyService->insertPlayedItem($media_id);
//set a 'last played' timestamp for media item
//needed for smart blocks
$mediaType = Application_Model_Schedule::GetType($media_id);
if ($mediaType == 'file') {
$file_id = Application_Model_Schedule::GetFileId($media_id);
if (!is_null($file_id)) {
//we are dealing with a file not a stream
$file = Application_Model_StoredFile::RecallById($file_id);
$now = new DateTime("now", new DateTimeZone("UTC"));
$file->setLastPlayedTime($now);
}
} else {
// webstream
$stream_id = Application_Model_Schedule::GetStreamId($media_id);
if (!is_null($stream_id)) {
$webStream = new Application_Model_Webstream($stream_id);
$now = new DateTime("now", new DateTimeZone("UTC"));
$webStream->setLastPlayed($now);
}
}
} catch (Exception $e) {
Logging::info($e);
}
$this->_helper->json->sendJson(array("status"=>1, "message"=>""));
}
/**
* Go through a given array and sanitize any potentially exploitable fields
* by passing them through htmlspecialchars
*
* @param unknown $arr the array to sanitize
* @param unknown $keys indexes of values to be sanitized
* @param unknown $arr the array to sanitize
* @param unknown $keys indexes of values to be sanitized
*/
private function convertSpecialChars(&$arr, $keys)
{
@ -576,6 +536,61 @@ class ApiController extends Zend_Controller_Action
}
}
/**
* Recursively find image_path keys in the various $result subarrays,
* and convert them to point to the show-logo endpoint
*
* @param unknown $arr the array to search
*/
private function findAndConvertPaths(&$arr)
{
$CC_CONFIG = Config::getConfig();
$baseDir = Application_Common_OsPath::formatDirectoryWithDirectorySeparators($CC_CONFIG['baseDir']);
foreach ($arr as &$a) {
if (is_array($a)) {
if (array_key_exists("image_path", $a)) {
$a["image_path"] = $a["image_path"] && $a["image_path"] !== '' ?
"http://".$_SERVER['HTTP_HOST'].$baseDir."api/show-logo?id=".$a["id"] : '';
} else {
$this->findAndConvertPaths($a);
}
}
}
}
/**
* API endpoint to display the show logo
*/
public function showLogoAction()
{
if (Application_Model_Preference::GetAllow3rdPartyApi()) {
$request = $this->getRequest();
$showId = $request->getParam('id');
// if no id is passed, just die - redirects to a 404
if (!$showId || $showId === '') {
return;
}
$show = CcShowQuery::create()->findPk($showId);
// disable the view and the layout
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$path = $show->getDbImagePath();
$mime_type = mime_content_type($path);
header("Content-type: " . $mime_type);
$this->smartReadFile($path, $mime_type);
} else {
header('HTTP/1.0 401 Unauthorized');
print _('You are not allowed to access this resource. ');
exit;
}
}
/**
* API endpoint to provide station metadata
*/
@ -600,7 +615,11 @@ class ApiController extends Zend_Controller_Action
$result['AIRTIME_API_VERSION'] = AIRTIME_API_VERSION;
header("Content-type: text/javascript");
$js = json_encode($result, JSON_PRETTY_PRINT);
if (version_compare(phpversion(), '5.4.0', '<')) {
$js = json_encode($result);
} else {
$js = json_encode($result, JSON_PRETTY_PRINT);
}
// If a callback is not given, then just provide the raw JSON.
echo isset($_GET['callback']) ? $_GET['callback'].'('.$js.')' : $js;
} else {
@ -643,6 +662,62 @@ class ApiController extends Zend_Controller_Action
}
}
public function scheduleAction()
{
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
header("Content-Type: application/json");
$data = Application_Model_Schedule::getSchedule();
echo json_encode($data, JSON_FORCE_OBJECT);
}
public function notifyMediaItemStartPlayAction()
{
$media_id = $this->_getParam("media_id");
// We send a fake media id when playing on-demand ads;
// in this case, simply return
if ($media_id === '0' || $media_id === '-1') {
return;
}
Logging::debug("Received notification of new media item start: $media_id");
Application_Model_Schedule::UpdateMediaPlayedStatus($media_id);
try {
$historyService = new Application_Service_HistoryService();
$historyService->insertPlayedItem($media_id);
//set a 'last played' timestamp for media item
//needed for smart blocks
$mediaType = Application_Model_Schedule::GetType($media_id);
if ($mediaType == 'file') {
$file_id = Application_Model_Schedule::GetFileId($media_id);
if (!is_null($file_id)) {
//we are dealing with a file not a stream
$file = Application_Model_StoredFile::RecallById($file_id);
$now = new DateTime("now", new DateTimeZone("UTC"));
$file->setLastPlayedTime($now);
}
} else {
// webstream
$stream_id = Application_Model_Schedule::GetStreamId($media_id);
if (!is_null($stream_id)) {
$webStream = new Application_Model_Webstream($stream_id);
$now = new DateTime("now", new DateTimeZone("UTC"));
$webStream->setLastPlayed($now);
}
}
} catch (Exception $e) {
Logging::info($e);
}
$this->_helper->json->sendJson(array("status"=>1, "message"=>""));
}
public function recordedShowsAction()
{
$utcTimezone = new DateTimeZone("UTC");
@ -1151,8 +1226,8 @@ class ApiController extends Zend_Controller_Action
//check against show dj auth
$showInfo = Application_Model_Show::getCurrentShow();
// there is current playing show
if (isset($showInfo[0]['id'])) {
$current_show_id = $showInfo[0]['id'];
if (isset($showInfo['id'])) {
$current_show_id = $showInfo['id'];
$CcShow = CcShowQuery::create()->findPK($current_show_id);
// get custom pass info from the show