Merge branch 'saas' of github.com:sourcefabric/Airtime into saas

Conflicts:
	airtime_mvc/application/modules/rest/controllers/MediaController.php
This commit is contained in:
Albert Santoni 2014-10-29 18:01:31 -04:00
commit 359727fc66
11 changed files with 797 additions and 261 deletions

View file

@ -10,7 +10,7 @@ class CORSHelper
//Chrome sends the Origin header for all requests, so we whitelist the webserver's hostname as well.
$response = $response->setHeader('Access-Control-Allow-Origin', '*');
$origin = $request->getHeader('Origin');
if (($origin != "") &&
if ((!(preg_match("/https?:\/\/localhost/", $origin) === 1)) && ($origin != "") &&
(!in_array($origin,
array("http://www.airtime.pro",
"https://www.airtime.pro",

View file

@ -312,6 +312,86 @@ class Application_Common_DateHelper
}
}
/**
* Convert the columns given in the array $columnsToConvert in the
* database result $rows to local timezone.
*
* @param array $rows arrays of arrays containing database query result
* @param array $columnsToConvert array of column names to convert
* @param string $timezone convert to the given timezone.
* @param string $format time format to convert to
*/
public static function convertTimestampsToTimezone(&$rows, $columnsToConvert, $timezone, $format="Y-m-d H:i:s")
{
$timezone = strtolower($timezone);
// Check that the timezone is valid and rows is an array
if (!is_array($rows)) {
return;
}
foreach ($rows as &$row) {
if (is_array($row)) {
foreach ($columnsToConvert as $column) {
if (array_key_exists($column, $row)) {
$newTimezone = new DateTimeZone($timezone);
$utcTimezone = new DateTimeZone("UTC");
$d = new DateTime($row[$column], $utcTimezone);
$d->setTimezone($newTimezone);
$row[$column] = $d->format($format);
}
}
self::convertTimestampsToTimezone($row, $columnsToConvert, $timezone, $format);
}
}
}
/**
* Return the end date time in the given timezone
*
* @return DateTime
*/
public static function getEndDateTime($timezoneString, $days)
{
$timezone = new DateTimeZone($timezoneString);
$now = new DateTime("now", $timezone);
$now->add(new DateInterval("P".$days."D"));
$now->setTime(0, 0, 0);
return $now;
}
/**
* Return a formatted string representing the
* given datetime in the given timezone
*
* @param unknown $datetime the time to convert
* @param unknown $timezone the timezone to convert to
* @param string $format the formatted string
*/
public static function UTCStringToTimezoneString($datetime, $timezone, $format="Y-m-d H:i:s") {
$d = new DateTime($datetime, new DateTimeZone("UTC"));
$timezone = strtolower($timezone);
$newTimezone = new DateTimeZone($timezone);
$d->setTimezone($newTimezone);
return $d->format($format);
}
/**
* Return the timezone offset in seconds for the given timezone
*
* @param unknown $userDefinedTimezone the timezone used to determine the offset
*/
public static function getTimezoneOffset($userDefinedTimezone) {
$now = new DateTimeZone($userDefinedTimezone);
$d = new DateTime("now", $now);
return $d->format("Z");
}
/**
* This function is used for calculations! Don't modify for display purposes!
*

View file

@ -80,4 +80,17 @@ class Application_Common_OsPath{
return $baseUrl;
}
public static function formatDirectoryWithDirectorySeparators($dir)
{
if ($dir[0] != "/") {
$dir = "/".$dir;
}
if ($dir[strlen($dir) -1] != "/") {
$dir = $dir."/";
}
return $dir;
}
}

View file

@ -5,7 +5,8 @@ class ApiController extends Zend_Controller_Action
public function init()
{
$ignoreAuth = array("live-info", "week-info");
$ignoreAuth = array("live-info", "live-info-v2", "week-info",
"station-metadata", "station-logo", "show-logo");
$params = $this->getRequest()->getParams();
if (!in_array($params['action'], $ignoreAuth)) {
@ -246,70 +247,74 @@ class ApiController extends Zend_Controller_Action
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$request = $this->getRequest();
$utcTimeNow = gmdate("Y-m-d H:i:s");
$utcTimeEnd = ""; // if empty, getNextShows will use interval instead of end of day
$request = $this->getRequest();
// default to the station timezone
$timezone = Application_Model_Preference::GetDefaultTimezone();
$userDefinedTimezone = strtolower($request->getParam('timezone'));
$upcase = false; // only upcase the timezone abbreviations
$this->checkTimezone($userDefinedTimezone, $timezone, $upcase);
$type = $request->getParam('type');
/* This is some *extremely* lazy programming that needs to bi fixed. For some reason
* we are using two entirely different codepaths for very similar functionality (type = endofday
* vs type = interval). Needs to be fixed for 2.3 - MK */
if ($type == "endofday") {
$limit = $request->getParam('limit');
if ($limit == "" || !is_numeric($limit)) {
$limit = "5";
}
/* This is some *extremely* lazy programming that needs to be fixed. For some reason
* we are using two entirely different codepaths for very similar functionality (type = endofday
* vs type = interval). Needs to be fixed for 2.3 - MK */
if ($type == "endofday") {
// make getNextShows use end of day
$end = Application_Common_DateHelper::getTodayStationEndDateTime();
$end->setTimezone(new DateTimeZone("UTC"));
$utcTimeEnd = $end->format("Y-m-d H:i:s");
$result = array(
"env" => APPLICATION_ENV,
"schedulerTime" => $utcTimeNow,
"currentShow" => Application_Model_Show::getCurrentShow($utcTimeNow),
"nextShow" => Application_Model_Show::getNextShows($utcTimeNow, $limit, $utcTimeEnd)
);
}
else {
$result = Application_Model_Schedule::GetPlayOrderRange();
// XSS exploit prevention
$result["previous"]["name"] = htmlspecialchars($result["previous"]["name"]);
$result["current"]["name"] = htmlspecialchars($result["current"]["name"]);
$result["next"]["name"] = htmlspecialchars($result["next"]["name"]);
} else {
$result = Application_Model_Schedule::GetPlayOrderRangeOld($limit);
}
// XSS exploit prevention
foreach ($result["currentShow"] as &$current) {
$current["name"] = htmlspecialchars($current["name"]);
}
foreach ($result["nextShow"] as &$next) {
$next["name"] = htmlspecialchars($next["name"]);
}
//For consistency, all times here are being sent in the station timezone, which
//seems to be what we've normalized everything to.
//Convert the UTC scheduler time ("now") to the station timezone.
$result["schedulerTime"] = Application_Common_DateHelper::UTCStringToStationTimezoneString($result["schedulerTime"]);
$result["timezone"] = Application_Common_DateHelper::getStationTimezoneAbbreviation();
$result["timezoneOffset"] = Application_Common_DateHelper::getStationTimezoneOffset();
//Convert from UTC to station time for Web Browser.
Application_Common_DateHelper::convertTimestamps($result["currentShow"],
$this->convertSpecialChars($result, array("name", "url"));
// apply user-defined timezone, or default to station
Application_Common_DateHelper::convertTimestampsToTimezone(
$result['currentShow'],
array("starts", "ends", "start_timestamp","end_timestamp"),
"station");
Application_Common_DateHelper::convertTimestamps($result["nextShow"],
$timezone
);
Application_Common_DateHelper::convertTimestampsToTimezone(
$result['nextShow'],
array("starts", "ends", "start_timestamp","end_timestamp"),
"station");
$timezone
);
//Convert the UTC scheduler time ("now") to the user-defined timezone.
$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;
header("Content-Type: application/json");
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'].'('.json_encode($result).')' : json_encode($result);
echo isset($_GET['callback']) ? $_GET['callback'].'('.$js.')' : $js;
} else {
header('HTTP/1.0 401 Unauthorized');
print _('You are not allowed to access this resource. ');
@ -317,6 +322,127 @@ class ApiController extends Zend_Controller_Action
}
}
/**
* Retrieve the currently playing show as well as upcoming shows.
* Number of shows returned and the time interval in which to
* get the next shows can be configured as GET parameters.
*
* Possible parameters:
* days - How many days to retrieve.
* Default is 2 (today + tomorrow).
* shows - How many shows to retrieve
* Default is 5.
* timezone - The timezone to send the times in
* Defaults to the station timezone
*/
public function liveInfoV2Action()
{
if (Application_Model_Preference::GetAllow3rdPartyApi()) {
// disable the view and the layout
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$request = $this->getRequest();
$utcTimeNow = gmdate("Y-m-d H:i:s");
$utcTimeEnd = ""; // if empty, getNextShows will use interval instead of end of day
// default to the station timezone
$timezone = Application_Model_Preference::GetDefaultTimezone();
$userDefinedTimezone = strtolower($request->getParam('timezone'));
$upcase = false; // only upcase the timezone abbreviations
$this->checkTimezone($userDefinedTimezone, $timezone, $upcase);
$daysToRetrieve = $request->getParam('days');
$showsToRetrieve = $request->getParam('shows');
if ($daysToRetrieve == "" || !is_numeric($daysToRetrieve)) {
$daysToRetrieve = "2";
}
if ($showsToRetrieve == "" || !is_numeric($showsToRetrieve)) {
$showsToRetrieve = "5";
}
// set the end time to the day's start n days from now.
// days=1 will return shows until the end of the current day,
// days=2 will return shows until the end of tomorrow, etc.
$end = Application_Common_DateHelper::getEndDateTime($timezone, $daysToRetrieve);
$end->setTimezone(new DateTimeZone("UTC"));
$utcTimeEnd = $end->format("Y-m-d H:i:s");
$result = Application_Model_Schedule::GetPlayOrderRange($utcTimeEnd, $showsToRetrieve);
// XSS exploit prevention
$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;
header("Content-Type: application/json");
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 {
header('HTTP/1.0 401 Unauthorized');
print _('You are not allowed to access this resource. ');
exit;
}
}
/**
* Check that the value for the timezone the user gave is valid.
* If it is, override the default (station) timezone.
* If it's an abbreviation (pst, edt) we upcase the output.
*
* @param string $userDefinedTimezone the requested timezone value
* @param string $timezone the default timezone
* @param boolean $upcase whether the timezone output should be upcased
*/
private function checkTimezone($userDefinedTimezone, &$timezone, &$upcase)
{
$delimiter = "/";
// if the user passes in a timezone in standard form ("Continent/City")
// we need to fix the downcased string by upcasing each word delimited by a /
if (strpos($userDefinedTimezone, $delimiter) !== false) {
$userDefinedTimezone = implode($delimiter, array_map('ucfirst', explode($delimiter, $userDefinedTimezone)));
}
// if the timezone defined by the user exists, use that
if (array_key_exists($userDefinedTimezone, timezone_abbreviations_list())) {
$timezone = $userDefinedTimezone;
$upcase = true;
} else if (in_array($userDefinedTimezone, timezone_identifiers_list())) {
$timezone = $userDefinedTimezone;
}
}
/**
* If the user passed in a timezone parameter, adjust timezone-dependent
* variables in the result to reflect the given timezone.
*
* @param object $result reference to the object to send back to the user
* @param string $timezone the user's timezone parameter value
* @param boolean $upcase whether the timezone output should be upcased
*/
private function applyLiveTimezoneAdjustments(&$result, $timezone, $upcase)
{
Application_Common_DateHelper::convertTimestampsToTimezone(
$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;
}
public function weekInfoAction()
{
if (Application_Model_Preference::GetAllow3rdPartyApi()) {
@ -332,15 +458,21 @@ class ApiController extends Zend_Controller_Action
"nextthursday", "nextfriday", "nextsaturday", "nextsunday");
$result = array();
// default to the station timezone
$timezone = Application_Model_Preference::GetDefaultTimezone();
$userDefinedTimezone = strtolower($this->getRequest()->getParam("timezone"));
// if the timezone defined by the user exists, use that
if (array_key_exists($userDefinedTimezone, timezone_abbreviations_list())) {
$timezone = $userDefinedTimezone;
}
$utcTimezone = new DateTimeZone("UTC");
$stationTimezone = new DateTimeZone(Application_Model_Preference::GetDefaultTimezone());
$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($stationTimezone);
$weekStartDateTime->setTimezone(new DateTimeZone($timezone));
$weekStartDateTime->add(new DateInterval('P1D'));
//convert back to UTC to get the actual timestamp used for search.
@ -350,28 +482,179 @@ class ApiController extends Zend_Controller_Action
$shows = Application_Model_Show::getNextShows($utcDayStart, "ALL", $utcDayEnd);
$utcDayStart = $utcDayEnd;
Application_Common_DateHelper::convertTimestamps(
// convert to user-defined timezone, or default to station
Application_Common_DateHelper::convertTimestampsToTimezone(
$shows,
array("starts", "ends", "start_timestamp","end_timestamp"),
"station"
$timezone
);
$result[$dow[$i]] = $shows;
}
// XSS exploit prevention
foreach ($dow as $d) {
foreach ($result[$d] as &$show) {
$show["name"] = htmlspecialchars($show["name"]);
$show["url"] = htmlspecialchars($show["url"]);
}
}
$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");
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'].'('.json_encode($result).')' : json_encode($result);
echo isset($_GET['callback']) ? $_GET['callback'].'('.$js.')' : $js;
} else {
header('HTTP/1.0 401 Unauthorized');
print _('You are not allowed to access this resource. ');
exit;
}
}
/**
* 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
*/
private function convertSpecialChars(&$arr, $keys)
{
foreach ($arr as &$a) {
if (is_array($a)) {
foreach ($keys as &$key) {
if (array_key_exists($key, $a)) {
$a[$key] = htmlspecialchars($a[$key]);
}
}
$this->convertSpecialChars($a, $keys);
}
}
}
/**
* 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
*/
public function stationMetadataAction()
{
if (Application_Model_Preference::GetAllow3rdPartyApi()) {
// disable the view and the layout
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$CC_CONFIG = Config::getConfig();
$baseDir = Application_Common_OsPath::formatDirectoryWithDirectorySeparators($CC_CONFIG['baseDir']);
$path = 'http://'.$_SERVER['HTTP_HOST'].$baseDir."api/station-logo";
$result["name"] = Application_Model_Preference::GetStationName();
$result["logo"] = $path;
$result["description"] = Application_Model_Preference::GetStationDescription();
$result["timezone"] = Application_Model_Preference::GetDefaultTimezone();
$result["locale"] = Application_Model_Preference::GetDefaultLocale();
// 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");
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 {
header('HTTP/1.0 401 Unauthorized');
print _('You are not allowed to access this resource. ');
exit;
}
}
/**
* API endpoint to display the current station logo
*/
public function stationLogoAction()
{
if (Application_Model_Preference::GetAllow3rdPartyApi()) {
// disable the view and the layout
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$logo = Application_Model_Preference::GetStationLogo();
// if there's no logo, just die - redirects to a 404
if (!$logo || $logo === '') {
return;
}
// we're passing this as an image instead of using it in a data uri, so decode it
$blob = base64_decode($logo);
// use finfo to get the mimetype from the decoded blob
$f = finfo_open();
$mime_type = finfo_buffer($f, $blob, FILEINFO_MIME_TYPE);
finfo_close($f);
header("Content-type: " . $mime_type);
echo $blob;
} else {
header('HTTP/1.0 401 Unauthorized');
print _('You are not allowed to access this resource. ');
@ -394,6 +677,13 @@ class ApiController extends Zend_Controller_Action
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);
@ -936,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

View file

@ -297,7 +297,7 @@ class ScheduleController extends Zend_Controller_Action
public function getCurrentPlaylistAction()
{
$range = Application_Model_Schedule::GetPlayOrderRange();
$range = Application_Model_Schedule::GetPlayOrderRangeOld();
$show = Application_Model_Show::getCurrentShow();
/* Convert all UTC times to localtime before sending back to user. */

View file

@ -56,14 +56,11 @@ SQL;
return $real_streams;
}
/**
* Returns data related to the scheduled items.
*
* @param int $p_prev
* @param int $p_next
* @return date
*/
public static function GetPlayOrderRange($p_prev = 1, $p_next = 1)
public static function GetPlayOrderRange($utcTimeEnd = null, $showsToRetrieve = 5)
{
//Everything in this function must be done in UTC. You will get a swift kick in the pants if you mess that up.
@ -74,15 +71,62 @@ SQL;
return array();
}
// when timeEnd is unspecified, return to the default behaviour - set a range of 48 hours from current time
if (!$utcTimeEnd) {
$end = new DateTime();
$end->add(new DateInterval("P2D")); // Add 2 days
$end->setTimezone(new DateTimeZone("UTC"));
$utcTimeEnd = $end->format("Y-m-d H:i:s");
}
$utcNow = new DateTime("now", new DateTimeZone("UTC"));
$shows = Application_Model_Show::getPrevCurrentNext($utcNow);
$shows = Application_Model_Show::getPrevCurrentNext($utcNow, $utcTimeEnd, $showsToRetrieve);
$previousShowID = count($shows['previousShow'])>0?$shows['previousShow'][0]['instance_id']:null;
$currentShowID = count($shows['currentShow'])>0?$shows['currentShow']['instance_id']:null;
$nextShowID = count($shows['nextShow'])>0?$shows['nextShow'][0]['instance_id']:null;
$results = self::GetPrevCurrentNext($previousShowID, $currentShowID, $nextShowID, $utcNow);
$range = array(
"station" => array (
"env" => APPLICATION_ENV,
"schedulerTime" => $utcNow->format("Y-m-d H:i:s")
),
//Previous, current, next songs!
"tracks" => array(
"previous" => $results['previous'],
"current" => $results['current'],
"next" => $results['next']
),
//Current and next shows
"shows" => array (
"previous" => $shows['previousShow'],
"current" => $shows['currentShow'],
"next" => $shows['nextShow']
)
);
return $range;
}
/**
* Old version of the function for backwards compatibility
* @deprecated
*/
public static function GetPlayOrderRangeOld()
{
// Everything in this function must be done in UTC. You will get a swift kick in the pants if you mess that up.
$utcNow = new DateTime("now", new DateTimeZone("UTC"));
$shows = Application_Model_Show::getPrevCurrentNextOld($utcNow);
$previousShowID = count($shows['previousShow'])>0?$shows['previousShow'][0]['instance_id']:null;
$currentShowID = count($shows['currentShow'])>0?$shows['currentShow'][0]['instance_id']:null;
$nextShowID = count($shows['nextShow'])>0?$shows['nextShow'][0]['instance_id']:null;
$results = self::GetPrevCurrentNext($previousShowID, $currentShowID, $nextShowID, $utcNow);
$range = array("env"=>APPLICATION_ENV,
$range = array(
"env" => APPLICATION_ENV,
"schedulerTime" => $utcNow->format("Y-m-d H:i:s"),
//Previous, current, next songs!
"previous"=>$results['previous'] !=null?$results['previous']:(count($shows['previousShow'])>0?$shows['previousShow'][0]:null),
@ -90,7 +134,7 @@ SQL;
"next"=> $results['next'] !=null?$results['next']:(count($shows['nextShow'])>0?$shows['nextShow'][0]:null),
//Current and next shows
"currentShow"=>$shows['currentShow'],
"nextShow"=>$shows['nextShow'],
"nextShow"=>$shows['nextShow']
);
return $range;

View file

@ -1111,6 +1111,95 @@ SQL;
return $rows;
}
/**
* Gets the current show, previous and next with an n-day window from
* the given timeNow, so timeNow-2days and timeNow+$daysToRetrieve days.
*
* @param $utcNow A DateTime object containing the current time in UTC.
* @return An array containing the previous show,
* current show, and next show.
*/
public static function getPrevCurrentNext($utcNow, $utcEndStr, $showsToRetrieve)
{
$timeZone = new DateTimeZone("UTC"); //This function works entirely in UTC.
assert(get_class($utcNow) === "DateTime");
assert($utcNow->getTimeZone() == $timeZone);
$CC_CONFIG = Config::getConfig();
$con = Propel::getConnection();
// This will fetch the currently playing show first, then any
// upcoming shows within our interval, and finally move on to
// previous shows in the past 2 days.
$sql = <<<SQL
SELECT s.name,
s.description,
s.genre,
s.id,
si.id AS instance_id,
si.description AS instance_description,
si.record,
s.url,
s.image_path,
starts,
ends
FROM cc_show_instances si
LEFT JOIN cc_show s
ON si.show_id = s.id
WHERE si.show_id = s.id
AND si.starts >= :timeNow::timestamp - INTERVAL '2 days'
AND si.starts < :timeEnd::timestamp
AND modified_instance != TRUE
ORDER BY
CASE
WHEN si.ends > :timeNow::timestamp
AND si.starts < :timeNow::timestamp THEN 1
WHEN si.starts > :timeNow::timestamp THEN 2
ELSE 3
END
LIMIT :lim
SQL;
$stmt = $con->prepare($sql);
$utcNowStr = $utcNow->format("Y-m-d H:i:s");
$stmt->bindValue(':timeNow', $utcNowStr);
$stmt->bindValue(':timeEnd', $utcEndStr);
$stmt->bindValue(':lim', $showsToRetrieve);
if ($stmt->execute()) {
// use PDO::FETCH_ASSOC to only get the associative values
// note that fetchAll() defaults to PDO::FETCH_BOTH, which we don't want
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
$msg = implode(',', $stmt->errorInfo());
throw new Exception("Error: $msg");
}
$numberOfRows = count($rows);
$results['previousShow'] = array();
$results['currentShow'] = null;
$results['nextShow'] = array();
for ($i = 0; $i < $numberOfRows; ++$i) {
// all shows start/end times are stored in the database as UTC.
$showStartTime = new DateTime($rows[$i]['starts'], $timeZone);
$showEndTime = new DateTime($rows[$i]['ends'], $timeZone);
// Find the show that is within the current time.
if (($showStartTime <= $utcNow) && ($showEndTime > $utcNow)) {
$results['currentShow'] = $rows[$i];
} else if ($showEndTime < $utcNow ) {
array_push($results['previousShow'], $rows[$i]);
} else if ($showStartTime > $utcNow) {
array_push($results['nextShow'], $rows[$i]);
}
}
return $results;
}
/**
* Gets the current show, previous and next with an 2day window from
* the given timeNow, so timeNow-2days and timeNow+2days.
@ -1118,8 +1207,9 @@ SQL;
* @param $utcNow A DateTime object containing the current time in UTC.
* @return An array (with stupid sub-arrays) containing the previous show id,
* current show id, and next show id.
* @deprecated
*/
public static function getPrevCurrentNext($utcNow)
public static function getPrevCurrentNextOld($utcNow)
{
$timeZone = new DateTimeZone("UTC"); //This function works entirely in UTC.
assert(get_class($utcNow) === "DateTime");
@ -1159,7 +1249,7 @@ SQL;
$stmt->bindValue(':timeNow2', $utcNowStr);
if ($stmt->execute()) {
$rows = $stmt->fetchAll();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
$msg = implode(',', $stmt->errorInfo());
throw new Exception("Error: $msg");

View file

@ -1291,27 +1291,36 @@ SQL;
return $updateIsScheduled;
}
/**
*
* Updates the is_scheduled flag to false for tracks that are no longer
* scheduled in the future. We do this by checking the difference between
* all files scheduled in the future and all files with is_scheduled = true.
* The difference of the two result sets is what we need to update.
*/
public static function updatePastFilesIsScheduled()
{
/* Set the is_scheduled flag to false where it was true in the
* past, and where tracks are not scheduled in the future and do
* not belong to a show that has not ended yet. We need to check
* for show end times in case a track is overbooked, which would
* indicate it is still scheduled in the future
*/
$sql = <<<SQL
UPDATE cc_files SET is_scheduled = false
WHERE is_scheduled = true
AND id NOT IN (
SELECT s.file_id FROM cc_schedule AS s
LEFT JOIN cc_show_instances AS i
ON s.instance_id = i.id
WHERE s.ends > now() at time zone 'UTC'
AND i.ends > now() at time zone 'UTC'
)
SQL;
Application_Common_Database::prepareAndExecute($sql, array(),
Application_Common_Database::EXECUTE);
$futureScheduledFilesSelectCriteria = new Criteria();
$futureScheduledFilesSelectCriteria->addSelectColumn(CcSchedulePeer::FILE_ID);
$futureScheduledFilesSelectCriteria->setDistinct();
$futureScheduledFilesSelectCriteria->add(CcSchedulePeer::ENDS, gmdate("Y-m-d H:i:s"), Criteria::GREATER_THAN);
$stmt = CcSchedulePeer::doSelectStmt($futureScheduledFilesSelectCriteria);
$filesScheduledInFuture = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
$filesCurrentlySetWithIsScheduledSelectCriteria = new Criteria();
$filesCurrentlySetWithIsScheduledSelectCriteria->addSelectColumn(CcFilesPeer::ID);
$filesCurrentlySetWithIsScheduledSelectCriteria->add(CcFilesPeer::IS_SCHEDULED, true);
$stmt = CcFilesPeer::doSelectStmt($filesCurrentlySetWithIsScheduledSelectCriteria);
$filesCurrentlySetWithIsScheduled = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
$diff = array_diff($filesCurrentlySetWithIsScheduled, $filesScheduledInFuture);
$con = Propel::getConnection(CcFilesPeer::DATABASE_NAME);
$selectCriteria = new Criteria();
$selectCriteria->add(CcFilesPeer::ID, $diff, Criteria::IN);
$updateCriteria = new Criteria();
$updateCriteria->add(CcFilesPeer::IS_SCHEDULED, false);
BasePeer::doUpdate($selectCriteria, $updateCriteria, $con);
}
}

View file

@ -129,6 +129,15 @@ class Rest_MediaController extends Zend_Rest_Controller
public function postAction()
{
/* If the user presents a valid API key, we don't check CSRF tokens.
CSRF tokens are only used for session based authentication.
*/
if(!$this->verifyAPIKey()){
if(!$this->verifyCSRFToken($this->_getParam('csrf_token'))){
return;
}
}
if (!$this->verifyAuth(true, true))
{
return;
@ -295,6 +304,18 @@ class Rest_MediaController extends Zend_Rest_Controller
return $id;
}
private function verifyCSRFToken($token){
$current_namespace = new Zend_Session_Namespace('csrf_namespace');
$observed_csrf_token = $token;
$expected_csrf_token = $current_namespace->authtoken;
if($observed_csrf_token == $expected_csrf_token){
return true;
}else{
return false;
}
}
private function verifyAuth($checkApiKey, $checkSession)
{
// Session takes precedence over API key for now:
@ -321,18 +342,6 @@ class Rest_MediaController extends Zend_Rest_Controller
return false;
}
private function verifyCSRFToken($token){
$current_namespace = new Zend_Session_Namespace('csrf_namespace');
$observed_csrf_token = $token;
$expected_csrf_token = $current_namespace->authtoken;
if($observed_csrf_token == $expected_csrf_token){
return true;
}else{
return false;
}
}
private function verifyAPIKey()
{
//The API key is passed in via HTTP "basic authentication":

View file

@ -2,7 +2,6 @@
#plupload_files input[type="file"] {
font-size: 200px !important;
}
<<<<<<< HEAD
</style>
<?php if ($this->quotaLimitReached) { ?>
<div class="errors quota-reached">

View file

@ -354,6 +354,8 @@ function setAddShowEvents(form) {
startTimeField.val(json.start.time);
endDateField.val(json.end.date);
endTimeField.val(json.end.time);
// Change the timezone now that we've updated the times
currentTimezone = newTimezone;
});
});