API
|
-
+
|
-
+ |
">
- /etc/init.d/ ,
-
+ /etc/init.d/ ,
+
systemctl status libretime-api
-
sudo systemctl restart libretime-api
+
sudo systemctl restart libretime-api
@@ -277,7 +285,7 @@ $result = $r1 && $r2;
$first = true;
foreach ($extensions as $ext) {
if (!$first) {
- echo " | ";
+ echo ' | ';
} else {
$first = false;
}
diff --git a/legacy/application/configs/constants.php b/legacy/application/configs/constants.php
index 1857b6e36..f05c5a8ba 100644
--- a/legacy/application/configs/constants.php
+++ b/legacy/application/configs/constants.php
@@ -1,36 +1,36 @@
'podcast',
// 'class' => ''
// );
-$pages[] = array(
- 'label' => _('Radio Page'),
- 'uri' => '/',
- 'resource' => '',
- 'class' => '',
- 'pages' => array(),
- 'visible' => false
-);
-$pages[] = array(
- 'label' => _('Calendar'),
- 'module' => 'default',
+$pages[] = [
+ 'label' => _('Radio Page'),
+ 'uri' => '/',
+ 'resource' => '',
+ 'class' => '',
+ 'pages' => [],
+ 'visible' => false,
+];
+$pages[] = [
+ 'label' => _('Calendar'),
+ 'module' => 'default',
'controller' => 'schedule',
- 'action' => 'index',
- 'resource' => 'schedule',
- 'class' => ''
-);
-$pages[] = array(
- 'label' => _('Widgets'),
- 'module' => 'default',
+ 'action' => 'index',
+ 'resource' => 'schedule',
+ 'class' => '',
+];
+$pages[] = [
+ 'label' => _('Widgets'),
+ 'module' => 'default',
'controller' => 'embeddablewidgets',
- 'action' => 'player',
- 'resource' => 'embeddablewidgets',
- 'class' => '',
+ 'action' => 'player',
+ 'resource' => 'embeddablewidgets',
+ 'class' => '',
'title' => 'Widgets',
- 'pages' => array(
- array(
- 'label' => _('Player'),
- 'module' => 'default',
+ 'pages' => [
+ [
+ 'label' => _('Player'),
+ 'module' => 'default',
'controller' => 'embeddablewidgets',
- 'action' => 'player',
- ),
- array(
- 'label' => _('Weekly Schedule'),
- 'module' => 'default',
+ 'action' => 'player',
+ ],
+ [
+ 'label' => _('Weekly Schedule'),
+ 'module' => 'default',
'controller' => 'embeddablewidgets',
- 'action' => 'schedule',
- )
- )
-);
-$pages[] = array(
- 'label' => _("Settings"),
+ 'action' => 'schedule',
+ ],
+ ],
+];
+$pages[] = [
+ 'label' => _('Settings'),
'action' => 'edit-user',
'module' => 'default',
'controller' => 'user',
'class' => '',
'title' => 'Settings',
- 'pages' => array(
- array(
- 'label' => _('General'),
- 'module' => 'default',
+ 'pages' => [
+ [
+ 'label' => _('General'),
+ 'module' => 'default',
'controller' => 'preference',
- 'resource' => 'preference'
- ),
- array(
+ 'resource' => 'preference',
+ ],
+ [
'label' => _('My Profile'),
'controller' => 'user',
- 'action' => 'edit-user'
- ),
- array(
- 'label' => _('Users'),
- 'module' => 'default',
+ 'action' => 'edit-user',
+ ],
+ [
+ 'label' => _('Users'),
+ 'module' => 'default',
'controller' => 'user',
- 'action' => 'add-user',
- 'resource' => 'user'
- ),array(
- 'label' => _('Track Types'),
- 'module' => 'default',
+ 'action' => 'add-user',
+ 'resource' => 'user',
+ ], [
+ 'label' => _('Track Types'),
+ 'module' => 'default',
'controller' => 'tracktype',
- 'action' => 'add-tracktype',
- 'resource' => 'tracktype'
- ),
- array(
- 'label' => _('Streams'),
- 'module' => 'default',
+ 'action' => 'add-tracktype',
+ 'resource' => 'tracktype',
+ ],
+ [
+ 'label' => _('Streams'),
+ 'module' => 'default',
'controller' => 'preference',
- 'action' => 'stream-setting',
- 'resource' => 'preference'
- ),
- array(
- 'label' => _('Status'),
- 'module' => 'default',
+ 'action' => 'stream-setting',
+ 'resource' => 'preference',
+ ],
+ [
+ 'label' => _('Status'),
+ 'module' => 'default',
'controller' => 'systemstatus',
- 'action' => 'index',
- 'resource' => 'systemstatus'
- ),
- )
-);
-$pages[] = array(
- 'label' => _("Analytics"),
- 'module' => 'default',
+ 'action' => 'index',
+ 'resource' => 'systemstatus',
+ ],
+ ],
+];
+$pages[] = [
+ 'label' => _('Analytics'),
+ 'module' => 'default',
'controller' => 'playouthistory',
- 'action' => 'index',
- 'resource' => 'playouthistory',
- 'class' => '',
+ 'action' => 'index',
+ 'resource' => 'playouthistory',
+ 'class' => '',
'title' => 'Analytics',
- 'pages' => array(
- array(
- 'label' => _('Playout History'),
- 'module' => 'default',
+ 'pages' => [
+ [
+ 'label' => _('Playout History'),
+ 'module' => 'default',
'controller' => 'playouthistory',
- 'action' => 'index',
- 'resource' => 'playouthistory'
- ),
- array(
- 'label' => _('History Templates'),
- 'module' => 'default',
+ 'action' => 'index',
+ 'resource' => 'playouthistory',
+ ],
+ [
+ 'label' => _('History Templates'),
+ 'module' => 'default',
'controller' => 'playouthistorytemplate',
- 'action' => 'index',
- 'resource' => 'playouthistorytemplate'
- ),
- array(
- 'label' => _('Listener Stats'),
- 'module' => 'default',
+ 'action' => 'index',
+ 'resource' => 'playouthistorytemplate',
+ ],
+ [
+ 'label' => _('Listener Stats'),
+ 'module' => 'default',
'controller' => 'listenerstat',
- 'action' => 'index',
- 'resource' => 'listenerstat'
- ),
- array(
- 'label' => _('Show Listener Stats'),
- 'module' => 'default',
+ 'action' => 'index',
+ 'resource' => 'listenerstat',
+ ],
+ [
+ 'label' => _('Show Listener Stats'),
+ 'module' => 'default',
'controller' => 'listenerstat',
- 'action' => 'show',
- 'resource' => 'showlistenerstat'
- ),
-
- )
-);
-$pages[] = array(
- 'label' => _('Help'),
+ 'action' => 'show',
+ 'resource' => 'showlistenerstat',
+ ],
+ ],
+];
+$pages[] = [
+ 'label' => _('Help'),
'controller' => 'dashboard',
- 'action' => 'help',
- 'resource' => 'dashboard',
- 'class' => '',
- 'title' => 'Help',
- 'pages' => array(
- array(
- 'label' => _('Getting Started'),
- 'module' => 'default',
+ 'action' => 'help',
+ 'resource' => 'dashboard',
+ 'class' => '',
+ 'title' => 'Help',
+ 'pages' => [
+ [
+ 'label' => _('Getting Started'),
+ 'module' => 'default',
'controller' => 'dashboard',
- 'action' => 'help',
- 'resource' => 'dashboard'
- ),
- array(
- 'label' => _('User Manual'),
- 'uri' => USER_MANUAL_URL,
- 'target' => "_blank"
- ),
- array(
- 'label' => _('Get Help Online'),
- 'uri' => LIBRETIME_DISCOURSE_URL,
- 'target' => "_blank"
- ),
- array(
- 'label' => _('Contribute to LibreTime'),
- 'uri' => LIBRETIME_CONTRIBUTE_URL,
- 'target' => "_blank"
- ),
- array(
- 'label' => _('What\'s New?'),
- 'uri' => LIBRETIME_WHATS_NEW_URL,
- 'target' => "_blank"
- )
- )
-);
-
+ 'action' => 'help',
+ 'resource' => 'dashboard',
+ ],
+ [
+ 'label' => _('User Manual'),
+ 'uri' => USER_MANUAL_URL,
+ 'target' => '_blank',
+ ],
+ [
+ 'label' => _('Get Help Online'),
+ 'uri' => LIBRETIME_DISCOURSE_URL,
+ 'target' => '_blank',
+ ],
+ [
+ 'label' => _('Contribute to LibreTime'),
+ 'uri' => LIBRETIME_CONTRIBUTE_URL,
+ 'target' => '_blank',
+ ],
+ [
+ 'label' => _('What\'s New?'),
+ 'uri' => LIBRETIME_WHATS_NEW_URL,
+ 'target' => '_blank',
+ ],
+ ],
+];
// Create container from array
$container = new Zend_Navigation($pages);
-$container->id = "nav";
+$container->id = 'nav';
//store it in the registry:
Zend_Registry::set('Zend_Navigation', $container);
diff --git a/legacy/application/controllers/ApiController.php b/legacy/application/controllers/ApiController.php
index 5af7a430b..28789b695 100644
--- a/legacy/application/controllers/ApiController.php
+++ b/legacy/application/controllers/ApiController.php
@@ -2,10 +2,9 @@
class ApiController extends Zend_Controller_Action
{
+ public const DEFAULT_SHOWS_TO_RETRIEVE = '5';
- const DEFAULT_SHOWS_TO_RETRIEVE = "5";
-
- const DEFAULT_DAYS_TO_RETRIEVE = "2";
+ public const DEFAULT_DAYS_TO_RETRIEVE = '2';
public function init()
{
@@ -15,69 +14,70 @@ class ApiController extends Zend_Controller_Action
}
//Ignore API key and session authentication for these APIs:
- $ignoreAuth = array("live-info",
- "live-info-v2",
- "week-info",
- "station-metadata",
- "station-logo",
- "show-history-feed",
- "item-history-feed",
- "shows",
- "show-tracks",
- "show-schedules",
- "show-logo",
- "track",
- "track-types",
- "stream-m3u"
- );
+ $ignoreAuth = ['live-info',
+ 'live-info-v2',
+ 'week-info',
+ 'station-metadata',
+ 'station-logo',
+ 'show-history-feed',
+ 'item-history-feed',
+ 'shows',
+ 'show-tracks',
+ 'show-schedules',
+ 'show-logo',
+ 'track',
+ 'track-types',
+ 'stream-m3u',
+ ];
if (Zend_Session::isStarted()) {
- Logging::error("Session already started for an API request. Check your code because
- this will negatively impact performance.");
+ Logging::error('Session already started for an API request. Check your code because
+ this will negatively impact performance.');
}
$params = $this->getRequest()->getParams();
if (!in_array($params['action'], $ignoreAuth)) {
$this->checkAuth();
}
- /* Initialize action controller here */
+ // Initialize action controller here
$context = $this->_helper->getHelper('contextSwitch');
- $context->addActionContext('version' , 'json')
- ->addActionContext('recorded-shows' , 'json')
- ->addActionContext('calendar-init' , 'json')
- ->addActionContext('upload-file' , 'json')
- ->addActionContext('upload-recorded' , 'json')
- ->addActionContext('media-monitor-setup' , 'json')
- ->addActionContext('media-item-status' , 'json')
- ->addActionContext('reload-metadata' , 'json')
- ->addActionContext('list-all-files' , 'json')
- ->addActionContext('list-all-watched-dirs' , 'json')
- ->addActionContext('add-watched-dir' , 'json')
- ->addActionContext('remove-watched-dir' , 'json')
- ->addActionContext('set-storage-dir' , 'json')
- ->addActionContext('get-stream-setting' , 'json')
- ->addActionContext('status' , 'json')
- ->addActionContext('register-component' , 'json')
- ->addActionContext('update-liquidsoap-status' , 'json')
- ->addActionContext('update-file-system-mount' , 'json')
- ->addActionContext('handle-watched-dir-missing' , 'json')
- ->addActionContext('rabbitmq-do-push' , 'json')
- ->addActionContext('check-live-stream-auth' , 'json')
- ->addActionContext('update-source-status' , 'json')
- ->addActionContext('get-bootstrap-info' , 'json')
- ->addActionContext('get-files-without-replay-gain' , 'json')
- ->addActionContext('get-files-without-silan-value' , 'json')
- ->addActionContext('reload-metadata-group' , 'json')
- ->addActionContext('notify-webstream-data' , 'json')
- ->addActionContext('get-stream-parameters' , 'json')
- ->addActionContext('push-stream-stats' , 'json')
- ->addActionContext('update-stream-setting-table' , 'json')
- ->addActionContext('update-replay-gain-value' , 'json')
- ->addActionContext('update-cue-values-by-silan' , 'json')
- ->addActionContext('get-usability-hint' , 'json')
- ->addActionContext('poll-celery' , 'json')
- ->addActionContext('recalculate-schedule' , 'json') //RKTN-260
- ->initContext();
+ $context->addActionContext('version', 'json')
+ ->addActionContext('recorded-shows', 'json')
+ ->addActionContext('calendar-init', 'json')
+ ->addActionContext('upload-file', 'json')
+ ->addActionContext('upload-recorded', 'json')
+ ->addActionContext('media-monitor-setup', 'json')
+ ->addActionContext('media-item-status', 'json')
+ ->addActionContext('reload-metadata', 'json')
+ ->addActionContext('list-all-files', 'json')
+ ->addActionContext('list-all-watched-dirs', 'json')
+ ->addActionContext('add-watched-dir', 'json')
+ ->addActionContext('remove-watched-dir', 'json')
+ ->addActionContext('set-storage-dir', 'json')
+ ->addActionContext('get-stream-setting', 'json')
+ ->addActionContext('status', 'json')
+ ->addActionContext('register-component', 'json')
+ ->addActionContext('update-liquidsoap-status', 'json')
+ ->addActionContext('update-file-system-mount', 'json')
+ ->addActionContext('handle-watched-dir-missing', 'json')
+ ->addActionContext('rabbitmq-do-push', 'json')
+ ->addActionContext('check-live-stream-auth', 'json')
+ ->addActionContext('update-source-status', 'json')
+ ->addActionContext('get-bootstrap-info', 'json')
+ ->addActionContext('get-files-without-replay-gain', 'json')
+ ->addActionContext('get-files-without-silan-value', 'json')
+ ->addActionContext('reload-metadata-group', 'json')
+ ->addActionContext('notify-webstream-data', 'json')
+ ->addActionContext('get-stream-parameters', 'json')
+ ->addActionContext('push-stream-stats', 'json')
+ ->addActionContext('update-stream-setting-table', 'json')
+ ->addActionContext('update-replay-gain-value', 'json')
+ ->addActionContext('update-cue-values-by-silan', 'json')
+ ->addActionContext('get-usability-hint', 'json')
+ ->addActionContext('poll-celery', 'json')
+ ->addActionContext('recalculate-schedule', 'json') //RKTN-260
+ ->initContext()
+ ;
}
public function checkAuth()
@@ -110,23 +110,21 @@ class ApiController extends Zend_Controller_Action
}
header('HTTP/1.0 401 Unauthorized');
- print _('You are not allowed to access this resource.');
+ echo _('You are not allowed to access this resource.');
+
exit();
}
public function versionAction()
{
$config = Config::getConfig();
- $this->_helper->json->sendJson( array(
- "airtime_version" => $config['airtime_version'],
- "api_version" => AIRTIME_API_VERSION));
+ $this->_helper->json->sendJson([
+ 'airtime_version' => $config['airtime_version'],
+ 'api_version' => AIRTIME_API_VERSION, ]);
}
/**
* Allows remote client to download requested media file.
- *
- * @return void
- *
*/
public function getMediaAction()
{
@@ -134,29 +132,31 @@ class ApiController extends Zend_Controller_Action
// tracks are read for previewing or downloading.
session_write_close();
- $fileId = $this->_getParam("file");
+ $fileId = $this->_getParam('file');
- $inline = !($this->_getParam('download',false) == true);
+ $inline = !($this->_getParam('download', false) == true);
Application_Service_MediaService::streamFileDownload($fileId, $inline);
- $this->_helper->json->sendJson(array());
+ $this->_helper->json->sendJson([]);
}
/**
- * Manually trigger the TaskManager task to poll for completed Celery tasks
+ * Manually trigger the TaskManager task to poll for completed Celery tasks.
*/
- public function pollCeleryAction() {
+ public function pollCeleryAction()
+ {
$taskManager = TaskManager::getInstance();
$taskManager->runTask('CeleryTask');
}
/**
- * TODO: move this function into a more generic analytics REST controller
+ * TODO: move this function into a more generic analytics REST controller.
*
* Update station bandwidth usage based on icecast log data
*/
- public function bandwidthUsageAction() {
- $bandwidthUsage = json_decode($this->getRequest()->getParam("bandwidth_data"));
+ public function bandwidthUsageAction()
+ {
+ $bandwidthUsage = json_decode($this->getRequest()->getParam('bandwidth_data'));
$usageBytes = 0;
if (!empty($bandwidthUsage)) {
foreach ($bandwidthUsage as $entry) {
@@ -171,13 +171,14 @@ class ApiController extends Zend_Controller_Action
Application_Model_Preference::setBandwidthLimitUpdateTimer();
$usage = Application_Model_Preference::getBandwidthLimitCounter();
- if (($usage > Application_Model_Preference::getBandwidthLimit()) &&
- (Application_Model_Preference::getProvisioningStatus() == PROVISIONING_STATUS_ACTIVE)) {
+ if (($usage > Application_Model_Preference::getBandwidthLimit())
+ && (Application_Model_Preference::getProvisioningStatus() == PROVISIONING_STATUS_ACTIVE)) {
$CC_CONFIG = Config::getConfig();
// Hacky way to get the user ID...
- $url = AIRTIMEPRO_API_URL . "/station/" . $CC_CONFIG['rabbitmq']['user'] . "/suspend";
- $user = array('', $CC_CONFIG['apiKey'][0]);
- $data = array('reason' => "Bandwidth limit exceeded");
+ $url = AIRTIMEPRO_API_URL . '/station/' . $CC_CONFIG['rabbitmq']['user'] . '/suspend';
+ $user = ['', $CC_CONFIG['apiKey'][0]];
+ $data = ['reason' => 'Bandwidth limit exceeded'];
+
try {
Application_Common_HTTPHelper::doPost($url, $user, $data);
} catch (Exception $e) {
@@ -193,55 +194,53 @@ class ApiController extends Zend_Controller_Action
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
- $result = array();
- $result["on_air_light"] = false;
- $result["on_air_light_expected_status"] = false;
- $result["station_down"] = false;
- $result["master_stream"] = false;
- $result["live_stream"] = false;
- $result["master_stream_on_air"] = false;
- $result["live_stream_on_air"] = false;
+ $result = [];
+ $result['on_air_light'] = false;
+ $result['on_air_light_expected_status'] = false;
+ $result['station_down'] = false;
+ $result['master_stream'] = false;
+ $result['live_stream'] = false;
+ $result['master_stream_on_air'] = false;
+ $result['live_stream_on_air'] = false;
$range = Application_Model_Schedule::GetPlayOrderRange();
- $isItemCurrentlyScheduled = !is_null($range["tracks"]["current"]) && count($range["tracks"]["current"]) > 0 ? true : false;
+ $isItemCurrentlyScheduled = !is_null($range['tracks']['current']) && count($range['tracks']['current']) > 0 ? true : false;
- $isCurrentItemPlaying = $range["tracks"]["current"]["media_item_played"] ? true : false;
+ $isCurrentItemPlaying = $range['tracks']['current']['media_item_played'] ? true : false;
- if ($isItemCurrentlyScheduled ||
- Application_Model_Preference::GetSourceSwitchStatus("live_dj") == "on" ||
- Application_Model_Preference::GetSourceSwitchStatus("master_dj") == "on")
- {
- $result["on_air_light_expected_status"] = true;
+ if ($isItemCurrentlyScheduled
+ || Application_Model_Preference::GetSourceSwitchStatus('live_dj') == 'on'
+ || Application_Model_Preference::GetSourceSwitchStatus('master_dj') == 'on') {
+ $result['on_air_light_expected_status'] = true;
}
- if (($isItemCurrentlyScheduled && $isCurrentItemPlaying) ||
- Application_Model_Preference::GetSourceSwitchStatus("live_dj") == "on" ||
- Application_Model_Preference::GetSourceSwitchStatus("master_dj") == "on")
- {
- $result["on_air_light"] = true;
+ if (($isItemCurrentlyScheduled && $isCurrentItemPlaying)
+ || Application_Model_Preference::GetSourceSwitchStatus('live_dj') == 'on'
+ || Application_Model_Preference::GetSourceSwitchStatus('master_dj') == 'on') {
+ $result['on_air_light'] = true;
}
- if ($result["on_air_light_expected_status"] != $result["on_air_light"]) {
- $result["station_down"] = true;
+ if ($result['on_air_light_expected_status'] != $result['on_air_light']) {
+ $result['station_down'] = true;
}
- $live_dj_stream = Application_Model_Preference::GetSourceStatus("live_dj");
- $master_dj_stream = Application_Model_Preference::GetSourceStatus("master_dj");
- $live_dj_on_air = Application_Model_Preference::GetSourceSwitchStatus("live_dj");
- $master_dj_on_air = Application_Model_Preference::GetSourceSwitchStatus("master_dj");
+ $live_dj_stream = Application_Model_Preference::GetSourceStatus('live_dj');
+ $master_dj_stream = Application_Model_Preference::GetSourceStatus('master_dj');
+ $live_dj_on_air = Application_Model_Preference::GetSourceSwitchStatus('live_dj');
+ $master_dj_on_air = Application_Model_Preference::GetSourceSwitchStatus('master_dj');
- if($live_dj_stream == true){
- $result["live_stream"] = true;
- if ($live_dj_on_air == "on") {
- $result["live_stream_on_air"] = true;
+ if ($live_dj_stream == true) {
+ $result['live_stream'] = true;
+ if ($live_dj_on_air == 'on') {
+ $result['live_stream_on_air'] = true;
}
}
- if($master_dj_stream == true){
- $result["master_stream"] = true;
- if ($master_dj_on_air == "on") {
- $result["master_stream_on_air"] = true;
+ if ($master_dj_stream == true) {
+ $result['master_stream'] = true;
+ if ($master_dj_on_air == 'on') {
+ $result['master_stream_on_air'] = true;
}
}
@@ -273,7 +272,7 @@ class ApiController extends Zend_Controller_Action
$request = $this->getRequest();
$utcTimeNow = gmdate(DEFAULT_TIMESTAMP_FORMAT);
- $utcTimeEnd = ""; // if empty, getNextShows will use interval instead of end of day
+ $utcTimeEnd = ''; // if empty, getNextShows will use interval instead of end of day
// default to the station timezone
$timezone = Application_Model_Preference::GetDefaultTimezone();
@@ -283,65 +282,64 @@ class ApiController extends Zend_Controller_Action
$type = $request->getParam('type');
$limit = $request->getParam('limit');
- if ($limit == "" || !is_numeric($limit)) {
- $limit = "5";
+ 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") {
-
+ if ($type == 'endofday') {
// make getNextShows use end of day
$end = Application_Common_DateHelper::getTodayStationEndDateTime();
- $end->setTimezone(new DateTimeZone("UTC"));
+ $end->setTimezone(new DateTimeZone('UTC'));
$utcTimeEnd = $end->format(DEFAULT_TIMESTAMP_FORMAT);
- $result = array(
- "env" => APPLICATION_ENV,
- "schedulerTime" => $utcTimeNow,
- "currentShow" => Application_Model_Show::getCurrentShow($utcTimeNow),
- "nextShow" => Application_Model_Show::getNextShows($utcTimeNow, $limit, $utcTimeEnd)
- );
+ $result = [
+ 'env' => APPLICATION_ENV,
+ 'schedulerTime' => $utcTimeNow,
+ 'currentShow' => Application_Model_Show::getCurrentShow($utcTimeNow),
+ 'nextShow' => Application_Model_Show::getNextShows($utcTimeNow, $limit, $utcTimeEnd),
+ ];
} else {
$result = Application_Model_Schedule::GetPlayOrderRangeOld($limit);
}
$stationUrl = Application_Common_HTTPHelper::getStationUrl();
- if (($result["previous"]["type"] != "livestream") && isset($result["previous"]["metadata"])) {
- $previousID = $result["previous"]["metadata"]["id"];
- $get_prev_artwork_url = $stationUrl . 'api/track?id='. $previousID .'&return=artwork';
- $result["previous"]["metadata"]["artwork_url"] = $get_prev_artwork_url;
+ if (($result['previous']['type'] != 'livestream') && isset($result['previous']['metadata'])) {
+ $previousID = $result['previous']['metadata']['id'];
+ $get_prev_artwork_url = $stationUrl . 'api/track?id=' . $previousID . '&return=artwork';
+ $result['previous']['metadata']['artwork_url'] = $get_prev_artwork_url;
}
- if (($result["current"]["type"] != "livestream") && isset($result["current"]["metadata"])) {
- $currID = $result["current"]["metadata"]["id"];
- $get_curr_artwork_url = $stationUrl . 'api/track?id='. $currID .'&return=artwork';
- $result["current"]["metadata"]["artwork_url"] = $get_curr_artwork_url;
+ if (($result['current']['type'] != 'livestream') && isset($result['current']['metadata'])) {
+ $currID = $result['current']['metadata']['id'];
+ $get_curr_artwork_url = $stationUrl . 'api/track?id=' . $currID . '&return=artwork';
+ $result['current']['metadata']['artwork_url'] = $get_curr_artwork_url;
}
- if (($result["next"]["type"] != "livestream") && isset($result["next"]["metadata"])) {
- $nextID = $result["next"]["metadata"]["id"];
- $get_next_artwork_url = $stationUrl . 'api/track?id='. $nextID .'&return=artwork';
- $result["next"]["metadata"]["artwork_url"] = $get_next_artwork_url;
+ if (($result['next']['type'] != 'livestream') && isset($result['next']['metadata'])) {
+ $nextID = $result['next']['metadata']['id'];
+ $get_next_artwork_url = $stationUrl . 'api/track?id=' . $nextID . '&return=artwork';
+ $result['next']['metadata']['artwork_url'] = $get_next_artwork_url;
}
// apply user-defined timezone, or default to station
Application_Common_DateHelper::convertTimestampsToTimezone(
$result['currentShow'],
- array("starts", "ends", "start_timestamp","end_timestamp"),
+ ['starts', 'ends', 'start_timestamp', 'end_timestamp'],
$timezone
);
Application_Common_DateHelper::convertTimestampsToTimezone(
$result['nextShow'],
- array("starts", "ends", "start_timestamp","end_timestamp"),
+ ['starts', 'ends', 'start_timestamp', 'end_timestamp'],
$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);
+ $result['schedulerTime'] = Application_Common_DateHelper::UTCStringToTimezoneString($result['schedulerTime'], $timezone);
+ $result['timezone'] = $upcase ? strtoupper($timezone) : $timezone;
+ $result['timezoneOffset'] = Application_Common_DateHelper::getTimezoneOffset($timezone);
// XSS exploit prevention
SecurityHelper::htmlescape_recursive($result);
@@ -355,7 +353,8 @@ class ApiController extends Zend_Controller_Action
$this->returnJsonOrJsonp($request, $result);
} else {
header('HTTP/1.0 401 Unauthorized');
- print _('You are not allowed to access this resource. ');
+ echo _('You are not allowed to access this resource. ');
+
exit;
}
}
@@ -390,10 +389,10 @@ class ApiController extends Zend_Controller_Action
$daysToRetrieve = $request->getParam('days');
$showsToRetrieve = $request->getParam('shows');
- if ($daysToRetrieve == "" || !is_numeric($daysToRetrieve)) {
+ if ($daysToRetrieve == '' || !is_numeric($daysToRetrieve)) {
$daysToRetrieve = self::DEFAULT_DAYS_TO_RETRIEVE;
}
- if ($showsToRetrieve == "" || !is_numeric($showsToRetrieve)) {
+ if ($showsToRetrieve == '' || !is_numeric($showsToRetrieve)) {
$showsToRetrieve = self::DEFAULT_SHOWS_TO_RETRIEVE;
}
@@ -401,7 +400,7 @@ class ApiController extends Zend_Controller_Action
// 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"));
+ $end->setTimezone(new DateTimeZone('UTC'));
$utcTimeEnd = $end->format(DEFAULT_TIMESTAMP_FORMAT);
$result = Application_Model_Schedule::GetPlayOrderRange($utcTimeEnd, $showsToRetrieve);
@@ -416,21 +415,22 @@ class ApiController extends Zend_Controller_Action
WidgetHelper::findAndConvertPaths($result);
// Expose the live source status
- $live_dj = Application_Model_Preference::GetSourceSwitchStatus('live_dj') ;
- $master_dj = Application_Model_Preference::GetSourceSwitchStatus('master_dj') ;
- $scheduled_play = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play') ;
- $result["sources"] = array();
- $result["sources"]["livedj"] = $live_dj;
- $result["sources"]["masterdj"] = $master_dj;
- $result["sources"]["scheduledplay"] = $scheduled_play;
+ $live_dj = Application_Model_Preference::GetSourceSwitchStatus('live_dj');
+ $master_dj = Application_Model_Preference::GetSourceSwitchStatus('master_dj');
+ $scheduled_play = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play');
+ $result['sources'] = [];
+ $result['sources']['livedj'] = $live_dj;
+ $result['sources']['masterdj'] = $master_dj;
+ $result['sources']['scheduledplay'] = $scheduled_play;
// 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;
+ $result['station']['AIRTIME_API_VERSION'] = AIRTIME_API_VERSION;
$this->returnJsonOrJsonp($request, $result);
} else {
header('HTTP/1.0 401 Unauthorized');
- print _('You are not allowed to access this resource. ');
+ echo _('You are not allowed to access this resource. ');
+
exit;
}
}
@@ -440,13 +440,13 @@ class ApiController extends Zend_Controller_Action
* 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
+ * @param string $userDefinedTimezone the requested timezone value
+ * @param string $timezone the default timezone
+ * @param bool $upcase whether the timezone output should be upcased
*/
private function updateTimezone($userDefinedTimezone, &$timezone, &$upcase)
{
- $delimiter = "/";
+ $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) {
@@ -456,7 +456,7 @@ class ApiController extends Zend_Controller_Action
if (array_key_exists($userDefinedTimezone, timezone_abbreviations_list())) {
$timezone = $userDefinedTimezone;
$upcase = true;
- } else if (in_array($userDefinedTimezone, timezone_identifiers_list())) {
+ } elseif (in_array($userDefinedTimezone, timezone_identifiers_list())) {
$timezone = $userDefinedTimezone;
}
}
@@ -465,21 +465,21 @@ class ApiController extends Zend_Controller_Action
* If the user passed in a timezone parameter, adjust timezone-dependent
* variables in the result to reflect the given timezone.
*
- * @param array $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
+ * @param array $result reference to the object to send back to the user
+ * @param string $timezone the user's timezone parameter value
+ * @param bool $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"),
+ ['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;
+ $result['station']['schedulerTime'] = Application_Common_DateHelper::UTCStringToTimezoneString($result['station']['schedulerTime'], $timezone);
+ $result['station']['timezone'] = $upcase ? strtoupper($timezone) : $timezone;
}
public function weekInfoAction()
@@ -490,7 +490,7 @@ class ApiController extends Zend_Controller_Action
$this->_helper->viewRenderer->setNoRender(true);
$request = $this->getRequest();
- $result = WidgetHelper::getWeekInfo($this->getRequest()->getParam("timezone"));
+ $result = WidgetHelper::getWeekInfo($this->getRequest()->getParam('timezone'));
//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;
@@ -498,13 +498,14 @@ class ApiController extends Zend_Controller_Action
$this->returnJsonOrJsonp($request, $result);
} else {
header('HTTP/1.0 401 Unauthorized');
- print _('You are not allowed to access this resource. ');
+ echo _('You are not allowed to access this resource. ');
+
exit;
}
}
/**
- * API endpoint to display the show logo
+ * API endpoint to display the show logo.
*/
public function showLogoAction()
{
@@ -516,53 +517,55 @@ class ApiController extends Zend_Controller_Action
$request = $this->getRequest();
$showId = $request->getParam('id');
if (empty($showId)) {
- throw new ZendActionHttpException($this, 400, "ERROR: No ID was given.");
+ throw new ZendActionHttpException($this, 400, 'ERROR: No ID was given.');
}
$show = CcShowQuery::create()->findPk($showId);
if (empty($show)) {
- throw new ZendActionHttpException($this, 400, "ERROR: No show with ID $showId exists.");
+ throw new ZendActionHttpException($this, 400, "ERROR: No show with ID {$showId} exists.");
}
$path = $show->getDbImagePath();
+
try {
$mime_type = mime_content_type($path);
if (empty($path)) {
- throw new ZendActionHttpException($this, 400, "ERROR: Show does not have an associated image.");
+ throw new ZendActionHttpException($this, 400, 'ERROR: Show does not have an associated image.');
}
} catch (Exception $e) {
//To avoid broken images on your site, we return the station logo if we can't find the show logo.
$this->_redirect('api/station-logo');
+
return;
}
-
try {
// Sometimes end users may be looking at stale data - if an image is removed
// but has been cached in a client's browser this will throw an exception
Application_Common_FileIO::smartReadFile($path, filesize($path), $mime_type);
- } catch(LibreTimeFileNotFoundException $e) {
+ } catch (LibreTimeFileNotFoundException $e) {
//throw new ZendActionHttpException($this, 404, "ERROR: No image found at $path");
$this->_redirect('api/station-logo');
+
return;
- } catch(Exception $e) {
- throw new ZendActionHttpException($this, 500, "ERROR: " . $e->getMessage());
+ } catch (Exception $e) {
+ throw new ZendActionHttpException($this, 500, 'ERROR: ' . $e->getMessage());
}
} else {
header('HTTP/1.0 401 Unauthorized');
- print _('You are not allowed to access this resource. ');
+ echo _('You are not allowed to access this resource. ');
+
exit;
}
}
/**
- * New API endpoint to display metadata from any single track
+ * New API endpoint to display metadata from any single track.
*
* Find metadata to any track imported (eg. id=1&return=json)
*
- * @param int $id track ID
- * @param string $return json, artwork_data, or artwork
- *
+ * @param int $id track ID
+ * @param string $return json, artwork_data, or artwork
*/
public function trackAction()
{
@@ -571,17 +574,16 @@ class ApiController extends Zend_Controller_Action
$this->_helper->viewRenderer->setNoRender(true);
if (Application_Model_Preference::GetAllow3rdPartyApi() || $this->checkAuth()) {
-
$request = $this->getRequest();
$trackid = $request->getParam('id');
$return = $request->getParam('return');
if (empty($return)) {
- throw new ZendActionHttpException($this, 400, "ERROR: No return was given.");
+ throw new ZendActionHttpException($this, 400, 'ERROR: No return was given.');
}
if (empty($trackid)) {
- throw new ZendActionHttpException($this, 400, "ERROR: No ID was given.");
+ throw new ZendActionHttpException($this, 400, 'ERROR: No ID was given.');
}
$storDir = Application_Model_MusicDir::getStorDir();
@@ -591,57 +593,57 @@ class ApiController extends Zend_Controller_Action
$file = Application_Model_StoredFile::RecallById($trackid);
$md = $file->getMetadata();
- if ($return === "artwork-data") {
+ if ($return === 'artwork-data') {
foreach ($md as $key => $value) {
if ($key == 'MDATA_KEY_ARTWORK' && !is_null($value)) {
FileDataHelper::renderDataURI($fp . $md['MDATA_KEY_ARTWORK']);
}
}
- } elseif ($return === "artwork-data-32") {
+ } elseif ($return === 'artwork-data-32') {
foreach ($md as $key => $value) {
if ($key == 'MDATA_KEY_ARTWORK' && !is_null($value)) {
- FileDataHelper::renderDataURI($fp . $md['MDATA_KEY_ARTWORK']. '-32');
+ FileDataHelper::renderDataURI($fp . $md['MDATA_KEY_ARTWORK'] . '-32');
}
}
- } elseif ($return === "artwork") {
+ } elseif ($return === 'artwork') {
//default
foreach ($md as $key => $value) {
if ($key == 'MDATA_KEY_ARTWORK' && !is_null($value)) {
- FileDataHelper::renderImage($fp . $md['MDATA_KEY_ARTWORK'].'-512.jpg');
+ FileDataHelper::renderImage($fp . $md['MDATA_KEY_ARTWORK'] . '-512.jpg');
}
}
- } elseif ($return === "artwork-32") {
+ } elseif ($return === 'artwork-32') {
foreach ($md as $key => $value) {
if ($key == 'MDATA_KEY_ARTWORK' && !is_null($value)) {
- FileDataHelper::renderImage($fp . $md['MDATA_KEY_ARTWORK'].'-32.jpg');
+ FileDataHelper::renderImage($fp . $md['MDATA_KEY_ARTWORK'] . '-32.jpg');
}
}
- } elseif ($return === "artwork-64") {
+ } elseif ($return === 'artwork-64') {
foreach ($md as $key => $value) {
if ($key == 'MDATA_KEY_ARTWORK' && !is_null($value)) {
- FileDataHelper::renderImage($fp . $md['MDATA_KEY_ARTWORK'].'-64.jpg');
+ FileDataHelper::renderImage($fp . $md['MDATA_KEY_ARTWORK'] . '-64.jpg');
}
}
- } elseif ($return === "artwork-128") {
+ } elseif ($return === 'artwork-128') {
foreach ($md as $key => $value) {
if ($key == 'MDATA_KEY_ARTWORK' && !is_null($value)) {
- FileDataHelper::renderImage($fp . $md['MDATA_KEY_ARTWORK'].'-128.jpg');
+ FileDataHelper::renderImage($fp . $md['MDATA_KEY_ARTWORK'] . '-128.jpg');
}
}
- } elseif ($return === "artwork-512") {
+ } elseif ($return === 'artwork-512') {
foreach ($md as $key => $value) {
if ($key == 'MDATA_KEY_ARTWORK' && !is_null($value)) {
- FileDataHelper::renderImage($fp . $md['MDATA_KEY_ARTWORK'].'-512.jpg');
+ FileDataHelper::renderImage($fp . $md['MDATA_KEY_ARTWORK'] . '-512.jpg');
}
}
- } elseif ($return === "json") {
- $data =json_encode($md);
- echo $data;
+ } elseif ($return === 'json') {
+ $data = json_encode($md);
+ echo $data;
}
-
} else {
header('HTTP/1.0 401 Unauthorized');
- print _('You are not allowed to access this resource. ');
+ echo _('You are not allowed to access this resource. ');
+
exit;
}
}
@@ -657,13 +659,14 @@ class ApiController extends Zend_Controller_Action
$this->_helper->json->sendJson($tracktypes);
} else {
header('HTTP/1.0 401 Unauthorized');
- print _('You are not allowed to access this resource. ');
+ echo _('You are not allowed to access this resource. ');
+
exit;
}
}
/**
- * API endpoint to provide station metadata
+ * API endpoint to provide station metadata.
*/
public function stationMetadataAction()
{
@@ -674,14 +677,14 @@ class ApiController extends Zend_Controller_Action
$CC_CONFIG = Config::getConfig();
$baseDir = Application_Common_OsPath::formatDirectoryWithDirectorySeparators($CC_CONFIG['baseDir']);
- $path = 'http://'.$_SERVER['HTTP_HOST'].$baseDir."api/station-logo";
+ $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();
- $result["stream_data"] = Application_Model_StreamSetting::getEnabledStreamData();
+ $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();
+ $result['stream_data'] = Application_Model_StreamSetting::getEnabledStreamData();
// 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;
@@ -689,13 +692,14 @@ class ApiController extends Zend_Controller_Action
$this->returnJsonOrJsonp($request, $result);
} else {
header('HTTP/1.0 401 Unauthorized');
- print _('You are not allowed to access this resource. ');
+ echo _('You are not allowed to access this resource. ');
+
exit;
}
}
/**
- * API endpoint to display the current station logo
+ * API endpoint to display the current station logo.
*/
public function stationLogoAction()
{
@@ -718,11 +722,12 @@ class ApiController extends Zend_Controller_Action
$mime_type = finfo_buffer($f, $blob, FILEINFO_MIME_TYPE);
finfo_close($f);
- header("Content-Type: " . $mime_type);
+ header('Content-Type: ' . $mime_type);
echo $blob;
} else {
header('HTTP/1.0 401 Unauthorized');
- print _('You are not allowed to access this resource.');
+ echo _('You are not allowed to access this resource.');
+
exit;
}
}
@@ -732,7 +737,7 @@ class ApiController extends Zend_Controller_Action
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
- header("Content-Type: application/json");
+ header('Content-Type: application/json');
$data = Application_Model_Schedule::getSchedule();
@@ -741,7 +746,7 @@ class ApiController extends Zend_Controller_Action
public function notifyMediaItemStartPlayAction()
{
- $media_id = $this->_getParam("media_id");
+ $media_id = $this->_getParam('media_id');
// We send a fake media id when playing on-demand ads;
// in this case, simply return
@@ -749,7 +754,7 @@ class ApiController extends Zend_Controller_Action
return;
}
- Logging::debug("Received notification of new media item start: $media_id");
+ Logging::debug("Received notification of new media item start: {$media_id}");
Application_Model_Schedule::UpdateMediaPlayedStatus($media_id);
try {
@@ -764,7 +769,7 @@ class ApiController extends Zend_Controller_Action
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"));
+ $now = new DateTime('now', new DateTimeZone('UTC'));
$file->setLastPlayedTime($now);
// Push metadata to TuneIn
@@ -780,7 +785,7 @@ class ApiController extends Zend_Controller_Action
$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"));
+ $now = new DateTime('now', new DateTimeZone('UTC'));
$webStream->setLastPlayed($now);
}
}
@@ -788,21 +793,22 @@ class ApiController extends Zend_Controller_Action
Logging::info($e);
}
- $this->_helper->json->sendJson(array("status"=>1, "message"=>""));
+ $this->_helper->json->sendJson(['status' => 1, 'message' => '']);
}
public function recordedShowsAction()
{
- $utcTimezone = new DateTimeZone("UTC");
- $nowDateTime = new DateTime("now", $utcTimezone);
+ $utcTimezone = new DateTimeZone('UTC');
+ $nowDateTime = new DateTime('now', $utcTimezone);
$endDateTime = clone $nowDateTime;
- $endDateTime = $endDateTime->add(new DateInterval("PT2H"));
+ $endDateTime = $endDateTime->add(new DateInterval('PT2H'));
$this->view->shows =
Application_Model_Show::getShows(
$nowDateTime,
$endDateTime,
- $onlyRecord = true);
+ $onlyRecord = true
+ );
$this->view->is_recording = false;
$this->view->server_timezone = Application_Model_Preference::GetDefaultTimezone();
@@ -816,9 +822,9 @@ class ApiController extends Zend_Controller_Action
public function uploadRecordedAction()
{
- $show_instance_id = $this->_getParam('showinstanceid');
- $file_id = $this->_getParam('fileid');
- $this->view->fileid = $file_id;
+ $show_instance_id = $this->_getParam('showinstanceid');
+ $file_id = $this->_getParam('fileid');
+ $this->view->fileid = $file_id;
$this->view->showinstanceid = $show_instance_id;
$this->uploadRecordedActionParam($show_instance_id, $file_id);
}
@@ -835,8 +841,7 @@ class ApiController extends Zend_Controller_Action
try {
$show_inst = new Application_Model_ShowInstance($show_instance_id);
$show_inst->setRecordedFile($file_id);
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
//we've reached here probably because the show was
//cancelled, and therefore the show instance does not exist
//anymore (ShowInstance constructor threw this error). We've
@@ -847,7 +852,7 @@ class ApiController extends Zend_Controller_Action
// TODO : the following is inefficient because it calls save on both
// fields
- $file->setMetadataValue('MDATA_KEY_CREATOR', "Airtime Show Recorder");
+ $file->setMetadataValue('MDATA_KEY_CREATOR', 'Airtime Show Recorder');
$file->setMetadataValue('MDATA_KEY_TRACKNUMBER', $show_instance_id);
}
@@ -856,7 +861,7 @@ class ApiController extends Zend_Controller_Action
$this->view->stor = Application_Model_MusicDir::getStorDir()->getDirectory();
$watchedDirs = Application_Model_MusicDir::getWatchedDirs();
- $watchedDirsPath = array();
+ $watchedDirsPath = [];
foreach ($watchedDirs as $wd) {
$watchedDirsPath[] = $wd->getDirectory();
}
@@ -865,14 +870,15 @@ class ApiController extends Zend_Controller_Action
public function dispatchMetadata($md, $mode)
{
- $return_hash = array();
+ $return_hash = [];
Application_Model_Preference::SetImportTimestamp();
$con = Propel::getConnection(CcFilesPeer::DATABASE_NAME);
$con->beginTransaction();
+
try {
// create also modifies the file if it exists
- if ($mode == "create") {
+ if ($mode == 'create') {
$filepath = $md['MDATA_KEY_FILEPATH'];
$filepath = Application_Common_OsPath::normpath($filepath);
$file = Application_Model_StoredFile::RecallByFilepath($filepath, $con);
@@ -888,14 +894,13 @@ class ApiController extends Zend_Controller_Action
if ($md['is_record'] != 0) {
$this->uploadRecordedActionParam($md['MDATA_KEY_TRACKNUMBER'], $file->getId());
}
-
- } elseif ($mode == "modify") {
+ } elseif ($mode == 'modify') {
$filepath = $md['MDATA_KEY_FILEPATH'];
$file = Application_Model_StoredFile::RecallByFilepath($filepath, $con);
//File is not in database anymore.
if (is_null($file)) {
- $return_hash['error'] = sprintf(_("File does not exist in %s"), PRODUCT_NAME);
+ $return_hash['error'] = sprintf(_('File does not exist in %s'), PRODUCT_NAME);
}
//Updating a metadata change.
else {
@@ -905,14 +910,15 @@ class ApiController extends Zend_Controller_Action
//let's unset it here. Note that on mode == "create", we still
//want media-monitor sending info about cue_out which by default
//will be equal to length of track until silan can take over.
- unset($md['MDATA_KEY_CUE_IN']);
- unset($md['MDATA_KEY_CUE_OUT']);
+ unset($md['MDATA_KEY_CUE_IN'], $md['MDATA_KEY_CUE_OUT']);
$file->setMetadata($md);
}
- } elseif ($mode == "moved") {
+ } elseif ($mode == 'moved') {
$file = Application_Model_StoredFile::RecallByFilepath(
- $md['MDATA_KEY_ORIGINAL_PATH'], $con);
+ $md['MDATA_KEY_ORIGINAL_PATH'],
+ $con
+ );
if (is_null($file)) {
$return_hash['error'] = sprintf(_('File does not exist in %s'), PRODUCT_NAME);
@@ -921,19 +927,19 @@ class ApiController extends Zend_Controller_Action
//$filepath = str_replace("\\", "", $filepath);
$file->setFilePath($filepath);
}
- } elseif ($mode == "delete") {
+ } elseif ($mode == 'delete') {
$filepath = $md['MDATA_KEY_FILEPATH'];
- $filepath = str_replace("\\", "", $filepath);
+ $filepath = str_replace('\\', '', $filepath);
$file = Application_Model_StoredFile::RecallByFilepath($filepath, $con);
if (is_null($file)) {
$return_hash['error'] = sprintf(_('File does not exist in %s'), PRODUCT_NAME);
Logging::warn("Attempt to delete file that doesn't exist.
- Path: '$filepath'");
+ Path: '{$filepath}'");
} else {
$file->deleteByMediaMonitor();
}
- } elseif ($mode == "delete_dir") {
+ } elseif ($mode == 'delete_dir') {
$filepath = $md['MDATA_KEY_FILEPATH'];
//$filepath = str_replace("\\", "", $filepath);
$files = Application_Model_StoredFile::RecallByPartialFilepath($filepath, $con);
@@ -949,11 +955,12 @@ class ApiController extends Zend_Controller_Action
}
$con->commit();
} catch (Exception $e) {
- Logging::warn("rolling back");
+ Logging::warn('rolling back');
Logging::warn($e->getMessage());
$con->rollback();
$return_hash['error'] = $e->getMessage();
}
+
return $return_hash;
}
@@ -963,39 +970,45 @@ class ApiController extends Zend_Controller_Action
// The value is a json encoded hash that has all the information related to this action
// The key(mdXXX) does not have any meaning as of yet but it could potentially correspond
// to some unique id.
- $request = $this->getRequest();
- $responses = array();
- $params = $request->getParams();
- $valid_modes = array('delete_dir', 'delete', 'moved', 'modify', 'create');
+ $request = $this->getRequest();
+ $responses = [];
+ $params = $request->getParams();
+ $valid_modes = ['delete_dir', 'delete', 'moved', 'modify', 'create'];
foreach ($params as $k => $raw_json) {
// Valid requests must start with mdXXX where XXX represents at
// least 1 digit
- if ( !preg_match('/^md\d+$/', $k) ) { continue; }
+ if (!preg_match('/^md\d+$/', $k)) {
+ continue;
+ }
$info_json = json_decode($raw_json, $assoc = true);
// Log invalid requests
- if ( !array_key_exists('mode', $info_json) ) {
- Logging::info("Received bad request(key=$k), no 'mode' parameter. Bad request is:");
- Logging::info( $info_json );
- array_push( $responses, array(
+ if (!array_key_exists('mode', $info_json)) {
+ Logging::info("Received bad request(key={$k}), no 'mode' parameter. Bad request is:");
+ Logging::info($info_json);
+ array_push($responses, [
'error' => _("Bad request. no 'mode' parameter passed."),
- 'key' => $k));
+ 'key' => $k, ]);
+
continue;
- } elseif ( !in_array($info_json['mode'], $valid_modes) ) {
+ }
+ if (!in_array($info_json['mode'], $valid_modes)) {
// A request still has a chance of being invalid even if it
// exists but it's validated by $valid_modes array
$mode = $info_json['mode'];
- Logging::info("Received bad request(key=$k). 'mode' parameter was invalid with value: '$mode'. Request:");
- Logging::info( $info_json );
- array_push( $responses, array(
+ Logging::info("Received bad request(key={$k}). 'mode' parameter was invalid with value: '{$mode}'. Request:");
+ Logging::info($info_json);
+ array_push($responses, [
'error' => _("Bad request. 'mode' parameter is invalid"),
'key' => $k,
- 'mode' => $mode ) );
+ 'mode' => $mode, ]);
+
continue;
}
// Removing 'mode' key from $info_json might not be necessary...
$mode = $info_json['mode'];
- unset( $info_json['mode'] );
+ unset($info_json['mode']);
+
try {
$response = $this->dispatchMetadata($info_json, $mode);
} catch (Exception $e) {
@@ -1014,7 +1027,7 @@ class ApiController extends Zend_Controller_Action
{
$request = $this->getRequest();
$dir_id = $request->getParam('dir_id');
- $all = $request->getParam('all');
+ $all = $request->getParam('all');
$this->view->files =
Application_Model_StoredFile::listAllFiles($dir_id, $all);
@@ -1022,7 +1035,7 @@ class ApiController extends Zend_Controller_Action
public function listAllWatchedDirsAction()
{
- $result = array();
+ $result = [];
$arrWatchedDirs = Application_Model_MusicDir::getWatchedDirs();
$storDir = Application_Model_MusicDir::getStorDir();
@@ -1069,21 +1082,21 @@ class ApiController extends Zend_Controller_Action
public function statusAction()
{
$request = $this->getRequest();
- $getDiskInfo = $request->getParam('diskinfo') == "true";
+ $getDiskInfo = $request->getParam('diskinfo') == 'true';
$config = Config::getConfig();
- $status = array(
- "platform"=>Application_Model_Systemstatus::GetPlatformInfo(),
- "airtime_version"=>$config['airtime_version'],
- "services"=>array(
- "pypo"=>Application_Model_Systemstatus::GetPypoStatus(),
- "liquidsoap"=>Application_Model_Systemstatus::GetLiquidsoapStatus(),
- "media_monitor"=>Application_Model_Systemstatus::GetMediaMonitorStatus()
- )
- );
+ $status = [
+ 'platform' => Application_Model_Systemstatus::GetPlatformInfo(),
+ 'airtime_version' => $config['airtime_version'],
+ 'services' => [
+ 'pypo' => Application_Model_Systemstatus::GetPypoStatus(),
+ 'liquidsoap' => Application_Model_Systemstatus::GetLiquidsoapStatus(),
+ 'media_monitor' => Application_Model_Systemstatus::GetMediaMonitorStatus(),
+ ],
+ ];
if ($getDiskInfo) {
- $status["partitions"] = Application_Model_Systemstatus::GetDiskInfo();
+ $status['partitions'] = Application_Model_Systemstatus::GetDiskInfo();
}
$this->view->status = $status;
@@ -1095,7 +1108,7 @@ class ApiController extends Zend_Controller_Action
$component = $request->getParam('component');
$remoteAddr = Application_Model_ServiceRegister::GetRemoteIpAddr();
- Logging::info("Registered Component: ".$component."@".$remoteAddr);
+ Logging::info('Registered Component: ' . $component . '@' . $remoteAddr);
Application_Model_ServiceRegister::Register($component, $remoteAddr);
}
@@ -1120,18 +1133,22 @@ class ApiController extends Zend_Controller_Action
// on source disconnection sent msg to pypo to turn off the switch
// Added AutoTransition option
- if ($status == "false" && Application_Model_Preference::GetAutoTransition()) {
- $data = array("sourcename"=>$sourcename, "status"=>"off");
- Application_Model_RabbitMq::SendMessageToPypo("switch_source", $data);
- Application_Model_Preference::SetSourceSwitchStatus($sourcename, "off");
- Application_Model_LiveLog::SetEndTime($sourcename == 'scheduled_play'?'S':'L',
- new DateTime("now", new DateTimeZone('UTC')));
- } elseif ($status == "true" && Application_Model_Preference::GetAutoSwitch()) {
- $data = array("sourcename"=>$sourcename, "status"=>"on");
- Application_Model_RabbitMq::SendMessageToPypo("switch_source", $data);
- Application_Model_Preference::SetSourceSwitchStatus($sourcename, "on");
- Application_Model_LiveLog::SetNewLogTime($sourcename == 'scheduled_play'?'S':'L',
- new DateTime("now", new DateTimeZone('UTC')));
+ if ($status == 'false' && Application_Model_Preference::GetAutoTransition()) {
+ $data = ['sourcename' => $sourcename, 'status' => 'off'];
+ Application_Model_RabbitMq::SendMessageToPypo('switch_source', $data);
+ Application_Model_Preference::SetSourceSwitchStatus($sourcename, 'off');
+ Application_Model_LiveLog::SetEndTime(
+ $sourcename == 'scheduled_play' ? 'S' : 'L',
+ new DateTime('now', new DateTimeZone('UTC'))
+ );
+ } elseif ($status == 'true' && Application_Model_Preference::GetAutoSwitch()) {
+ $data = ['sourcename' => $sourcename, 'status' => 'on'];
+ Application_Model_RabbitMq::SendMessageToPypo('switch_source', $data);
+ Application_Model_Preference::SetSourceSwitchStatus($sourcename, 'on');
+ Application_Model_LiveLog::SetNewLogTime(
+ $sourcename == 'scheduled_play' ? 'S' : 'L',
+ new DateTime('now', new DateTimeZone('UTC'))
+ );
}
Application_Model_Preference::SetSourceStatus($sourcename, $status);
}
@@ -1142,8 +1159,8 @@ class ApiController extends Zend_Controller_Action
$request = $this->getRequest();
$params = $request->getParams();
- $added_list = empty($params['added_dir'])?array():explode(',', $params['added_dir']);
- $removed_list = empty($params['removed_dir'])?array():explode(',', $params['removed_dir']);
+ $added_list = empty($params['added_dir']) ? [] : explode(',', $params['added_dir']);
+ $removed_list = empty($params['removed_dir']) ? [] : explode(',', $params['removed_dir']);
// get all watched dirs
$watched_dirs = Application_Model_MusicDir::getWatchedDirs(null, null);
@@ -1186,7 +1203,9 @@ class ApiController extends Zend_Controller_Action
$watchDir = Application_Model_MusicDir::getDirByPath($rd);
// get all the files that is under $dirPath
$files = Application_Model_StoredFile::listAllFiles(
- $dir->getId(),$all=false);
+ $dir->getId(),
+ $all = false
+ );
foreach ($files as $f) {
// if the file is from this mount
$filePaths = $f->getFilePaths();
@@ -1217,9 +1236,9 @@ class ApiController extends Zend_Controller_Action
* out a message to pypo that a potential change has been made. */
public function rabbitmqDoPushAction()
{
- Logging::info("Notifying RabbitMQ to send message to pypo");
+ Logging::info('Notifying RabbitMQ to send message to pypo');
- Application_Model_RabbitMq::SendMessageToPypo("reset_liquidsoap_bootstrap", array());
+ Application_Model_RabbitMq::SendMessageToPypo('reset_liquidsoap_bootstrap', []);
Application_Model_RabbitMq::PushSchedule();
}
@@ -1229,14 +1248,14 @@ class ApiController extends Zend_Controller_Action
$master_dj = Application_Model_Preference::GetSourceSwitchStatus('master_dj');
$scheduled_play = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play');
- $res = array("live_dj"=>$live_dj, "master_dj"=>$master_dj, "scheduled_play"=>$scheduled_play);
+ $res = ['live_dj' => $live_dj, 'master_dj' => $master_dj, 'scheduled_play' => $scheduled_play];
$this->view->switch_status = $res;
$this->view->station_name = Application_Model_Preference::GetStationName();
$this->view->stream_label = Application_Model_Preference::GetStreamLabelFormat();
$this->view->transition_fade = Application_Model_Preference::GetDefaultTransitionFade();
}
- /* This is used but Liquidsoap to check authentication of live streams*/
+ // This is used but Liquidsoap to check authentication of live streams
public function checkLiveStreamAuthAction()
{
$request = $this->getRequest();
@@ -1253,7 +1272,7 @@ class ApiController extends Zend_Controller_Action
} else {
$this->view->msg = false;
}
- } elseif ($djtype == "dj") {
+ } elseif ($djtype == 'dj') {
//check against show dj auth
$showInfo = Application_Model_Show::getCurrentShow();
@@ -1332,7 +1351,7 @@ class ApiController extends Zend_Controller_Action
$file->save();
}
- $this->_helper->json->sendJson(array());
+ $this->_helper->json->sendJson([]);
}
public function updateCueValuesBySilanAction()
@@ -1367,47 +1386,45 @@ class ApiController extends Zend_Controller_Action
$file->setDbSilanCheck(true);
$file->save();
} catch (Exception $e) {
- Logging::info("Failed to update silan values for ".$file->getDbTrackTitle());
- Logging::info("File length analyzed by Silan is: ".$length);
+ Logging::info('Failed to update silan values for ' . $file->getDbTrackTitle());
+ Logging::info('File length analyzed by Silan is: ' . $length);
//set silan_check to true so we don't attempt to re-anaylze again
$file->setDbSilanCheck(true);
$file->save();
}
}
- $this->_helper->json->sendJson(array());
+ $this->_helper->json->sendJson([]);
}
public function notifyWebstreamDataAction()
{
$request = $this->getRequest();
- $data = $request->getParam("data");
- $media_id = intval($request->getParam("media_id"));
+ $data = $request->getParam('data');
+ $media_id = intval($request->getParam('media_id'));
$data_arr = json_decode($data);
//$media_id is -1 sometimes when a stream has stopped playing
if (!is_null($media_id) && $media_id > 0) {
-
if (isset($data_arr->title)) {
-
$data_title = substr($data_arr->title, 0, 1024);
$previous_metadata = CcWebstreamMetadataQuery::create()
->orderByDbStartTime('desc')
->filterByDbInstanceId($media_id)
- ->findOne();
+ ->findOne()
+ ;
$do_insert = true;
if ($previous_metadata) {
if ($previous_metadata->getDbLiquidsoapData() == $data_title) {
- Logging::debug("Duplicate found: ". $data_title);
+ Logging::debug('Duplicate found: ' . $data_title);
$do_insert = false;
}
}
if ($do_insert) {
-
- $startDT = new DateTime("now", new DateTimeZone("UTC"));
+ $startDT = new DateTime('now', new DateTimeZone('UTC'));
$webstream_metadata = new CcWebstreamMetadata();
$webstream_metadata->setDbInstanceId($media_id);
@@ -1425,9 +1442,10 @@ class ApiController extends Zend_Controller_Action
$this->view->media_id = $media_id;
}
- public function getStreamParametersAction() {
- $streams = array("s1", "s2", "s3", "s4");
- $stream_params = array();
+ public function getStreamParametersAction()
+ {
+ $streams = ['s1', 's2', 's3', 's4'];
+ $stream_params = [];
foreach ($streams as $s) {
$stream_params[$s] =
Application_Model_StreamSetting::getStreamDataNormalized($s);
@@ -1435,16 +1453,18 @@ class ApiController extends Zend_Controller_Action
$this->view->stream_params = $stream_params;
}
- public function pushStreamStatsAction() {
+ public function pushStreamStatsAction()
+ {
$request = $this->getRequest();
- $data_blob = $request->getParam("data");
+ $data_blob = $request->getParam('data');
$data = json_decode($data_blob, true);
if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
- $message = "An error occured while decoding the 'data' JSON blob: '$data_blob'";
+ $message = "An error occured while decoding the 'data' JSON blob: '{$data_blob}'";
Logging::error($message);
$this->jsonError(400, $message);
+
return;
}
@@ -1452,26 +1472,28 @@ class ApiController extends Zend_Controller_Action
$this->view->data = $data;
}
- public function updateStreamSettingTableAction() {
+ public function updateStreamSettingTableAction()
+ {
$request = $this->getRequest();
- $data_blob = $request->getParam("data");
+ $data_blob = $request->getParam('data');
$data = json_decode($data_blob, true);
if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
- $message = "An error occured while decoding the 'data' JSON blob: '$data_blob'";
+ $message = "An error occured while decoding the 'data' JSON blob: '{$data_blob}'";
Logging::error($message);
$this->jsonError(400, $message);
+
return;
}
- foreach ($data as $k=>$v) {
+ foreach ($data as $k => $v) {
Application_Model_StreamSetting::SetListenerStatError($k, $v);
}
}
/**
- * display played items for a given time range and show instance_id
+ * display played items for a given time range and show instance_id.
*
* @return json array
*/
@@ -1480,7 +1502,7 @@ class ApiController extends Zend_Controller_Action
try {
$request = $this->getRequest();
$params = $request->getParams();
- $instance = $request->getParam("instance_id", null);
+ $instance = $request->getParam('instance_id', null);
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($request);
@@ -1488,15 +1510,14 @@ class ApiController extends Zend_Controller_Action
$results = $historyService->getPlayedItemData($startsDT, $endsDT, $params, $instance);
$this->_helper->json->sendJson($results['history']);
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
}
}
/**
- * display show schedules for a given time range and show instance_id
+ * display show schedules for a given time range and show instance_id.
*
* @return json array
*/
@@ -1505,7 +1526,7 @@ class ApiController extends Zend_Controller_Action
try {
$request = $this->getRequest();
$params = $request->getParams();
- $userId = $request->getParam("user_id", null);
+ $userId = $request->getParam('user_id', null);
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($request);
@@ -1513,15 +1534,14 @@ class ApiController extends Zend_Controller_Action
$shows = $historyService->getShowList($startsDT, $endsDT, $userId);
$this->_helper->json->sendJson($shows);
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
}
}
/**
- * display show info (without schedule) for given show_id
+ * display show info (without schedule) for given show_id.
*
* @return json array
*/
@@ -1530,12 +1550,12 @@ class ApiController extends Zend_Controller_Action
try {
$request = $this->getRequest();
$params = $request->getParams();
- $showId = $request->getParam("show_id", null);
- $results = array();
+ $showId = $request->getParam('show_id', null);
+ $results = [];
if (empty($showId)) {
$shows = CcShowQuery::create()->find();
- foreach($shows as $show) {
+ foreach ($shows as $show) {
$results[] = $show->getShowInfo();
}
} else {
@@ -1544,15 +1564,14 @@ class ApiController extends Zend_Controller_Action
}
$this->_helper->json->sendJson($results);
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
}
}
/**
- * display show schedule for given show_id
+ * display show schedule for given show_id.
*
* @return json array
*/
@@ -1561,37 +1580,35 @@ class ApiController extends Zend_Controller_Action
try {
$request = $this->getRequest();
$params = $request->getParams();
- $showId = $request->getParam("show_id", null);
+ $showId = $request->getParam('show_id', null);
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($request);
if ((!isset($showId)) || (!is_numeric($showId))) {
- //if (!isset($showId)) {
+ //if (!isset($showId)) {
$this->_helper->json->sendJson(
- array("jsonrpc" => "2.0", "error" => array("code" => 400, "message" => "missing invalid type for required show_id parameter. use type int.".$showId))
+ ['jsonrpc' => '2.0', 'error' => ['code' => 400, 'message' => 'missing invalid type for required show_id parameter. use type int.' . $showId]]
);
}
- $shows = Application_Model_Show::getShows($startsDT, $endsDT, FALSE, $showId);
+ $shows = Application_Model_Show::getShows($startsDT, $endsDT, false, $showId);
// is this a valid show?
if (empty($shows)) {
$this->_helper->json->sendJson(
- array("jsonrpc" => "2.0", "error" => array("code" => 204, "message" => "no content for requested show_id"))
+ ['jsonrpc' => '2.0', 'error' => ['code' => 204, 'message' => 'no content for requested show_id']]
);
}
$this->_helper->json->sendJson($shows);
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
}
-
}
/**
- * displays track listing for given instance_id
+ * displays track listing for given instance_id.
*
* @return json array
*/
@@ -1604,7 +1621,7 @@ class ApiController extends Zend_Controller_Action
if ((!isset($instanceId)) || (!is_numeric($instanceId))) {
$this->_helper->json->sendJson(
- array("jsonrpc" => "2.0", "error" => array("code" => 400, "message" => "missing invalid type for required instance_id parameter. use type int"))
+ ['jsonrpc' => '2.0', 'error' => ['code' => 400, 'message' => 'missing invalid type for required instance_id parameter. use type int']]
);
}
@@ -1614,30 +1631,28 @@ class ApiController extends Zend_Controller_Action
// is this a valid show instance with content?
if (empty($showInstanceContent)) {
$this->_helper->json->sendJson(
- array("jsonrpc" => "2.0", "error" => array("code" => 204, "message" => "no content for requested instance_id"))
+ ['jsonrpc' => '2.0', 'error' => ['code' => 204, 'message' => 'no content for requested instance_id']]
);
}
- $result = array();
+ $result = [];
$position = 0;
foreach ($showInstanceContent as $track) {
-
- $elementMap = array(
- 'title' => isset($track['track_title']) ? $track['track_title'] : "",
- 'artist' => isset($track['creator']) ? $track['creator'] : "",
+ $elementMap = [
+ 'title' => isset($track['track_title']) ? $track['track_title'] : '',
+ 'artist' => isset($track['creator']) ? $track['creator'] : '',
'position' => $position,
'id' => ++$position,
- 'mime' => isset($track['mime'])?$track['mime']:"",
- 'starts' => isset($track['starts']) ? $track['starts'] : "",
- 'length' => isset($track['length']) ? $track['length'] : "",
- 'file_id' => ($track['type'] == 0) ? $track['item_id'] : $track['filepath']
- );
+ 'mime' => isset($track['mime']) ? $track['mime'] : '',
+ 'starts' => isset($track['starts']) ? $track['starts'] : '',
+ 'length' => isset($track['length']) ? $track['length'] : '',
+ 'file_id' => ($track['type'] == 0) ? $track['item_id'] : $track['filepath'],
+ ];
$result[] = $elementMap;
}
$this->_helper->json($result);
-
}
/**
@@ -1649,7 +1664,7 @@ class ApiController extends Zend_Controller_Action
public function updateMetadataOnTuneinAction()
{
if (!Application_Model_Preference::getTuneinEnabled()) {
- $this->_helper->json->sendJson(array(0));
+ $this->_helper->json->sendJson([0]);
}
$lastTuneInMetadataUpdate = Application_Model_Preference::geLastTuneinMetadataUpdate();
@@ -1657,17 +1672,17 @@ class ApiController extends Zend_Controller_Action
$metadata = $metadata = Application_Model_Schedule::getCurrentPlayingTrack();
if (!is_null($metadata)) {
Application_Common_TuneIn::sendMetadataToTunein(
- $metadata["title"],
- $metadata["artist"]
+ $metadata['title'],
+ $metadata['artist']
);
}
}
- $this->_helper->json->sendJson(array(1));
+ $this->_helper->json->sendJson([1]);
}
public function getUsabilityHintAction()
{
- $userPath = $this->_getParam("userPath");
+ $userPath = $this->_getParam('userPath');
$hint = Application_Common_UsabilityHints::getUsabilityHint($userPath);
$this->_helper->json->sendJson($hint);
@@ -1686,7 +1701,7 @@ class ApiController extends Zend_Controller_Action
$streamData = Application_Model_StreamSetting::getEnabledStreamData();
foreach ($streamData as $stream) {
- $m3uFile .= "#EXTINF," . $stationName . " - " . strtoupper($stream['codec']) . "\r\n";
+ $m3uFile .= '#EXTINF,' . $stationName . ' - ' . strtoupper($stream['codec']) . "\r\n";
$m3uFile .= $stream['url'] . "\r\n\r\n";
}
echo $m3uFile;
@@ -1702,28 +1717,30 @@ class ApiController extends Zend_Controller_Action
$scheduler = new Application_Model_Scheduler();
session_write_close();
- $now = new DateTime("now", new DateTimeZone("UTC"));
+ $now = new DateTime('now', new DateTimeZone('UTC'));
- $showInstances = CcShowInstancesQuery::create()
+ $showInstances = CcShowInstancesQuery::create()
->filterByDbStarts($now, Criteria::GREATER_THAN)
//->filterByDbModifiedInstance(false)
->orderByDbStarts()
- ->find();
- //->find($this->con);
+ ->find()
+ ;
+ //->find($this->con);
$total = $showInstances->count();
$progress = 0;
foreach ($showInstances as $instance) {
- echo(round(floatval($progress / $total)*100) . "% - " . $instance->getDbId() . "\n ");
+ echo round(floatval($progress / $total) * 100) . '% - ' . $instance->getDbId() . "\n ";
flush();
ob_flush();
//while(@ob_end_clean());
$scheduler->removeGaps2($instance->getDbId());
- $progress += 1;
+ ++$progress;
}
- echo("Recalculated $total shows.");
+ echo "Recalculated {$total} shows.";
}
- private final function returnJsonOrJsonp($request, $result) {
+ final private function returnJsonOrJsonp($request, $result)
+ {
$callback = $request->getParam('callback');
$response = $this->getResponse();
$response->setHeader('Content-Type', 'application/json');
@@ -1742,15 +1759,19 @@ class ApiController extends Zend_Controller_Action
/**
* Respond with a JSON error message with a custom HTTP status code.
- *
+ *
* This logic should be handled by Zend, but I lack understanding of this
* framework, and prefer not break it or spend too much time on it.
+ *
+ * @param mixed $status
+ * @param mixed $message
*/
- private final function jsonError($status, $message)
+ final private function jsonError($status, $message)
{
$this->getResponse()
->setHttpResponseCode($status)
->setHeader('Content-Type', 'application/json')
- ->setBody(json_encode(['error' => $message]));
+ ->setBody(json_encode(['error' => $message]))
+ ;
}
}
diff --git a/legacy/application/controllers/AudiopreviewController.php b/legacy/application/controllers/AudiopreviewController.php
index bff30e929..50e6f8418 100644
--- a/legacy/application/controllers/AudiopreviewController.php
+++ b/legacy/application/controllers/AudiopreviewController.php
@@ -6,11 +6,12 @@ class AudiopreviewController extends Zend_Controller_Action
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('show-preview', 'json')
- ->addActionContext('audio-preview', 'json')
- ->addActionContext('get-show', 'json')
- ->addActionContext('playlist-preview', 'json')
- ->addActionContext('get-playlist', 'json')
- ->initContext();
+ ->addActionContext('audio-preview', 'json')
+ ->addActionContext('get-show', 'json')
+ ->addActionContext('playlist-preview', 'json')
+ ->addActionContext('get-playlist', 'json')
+ ->initContext()
+ ;
}
/**
@@ -21,50 +22,51 @@ class AudiopreviewController extends Zend_Controller_Action
{
$CC_CONFIG = Config::getConfig();
- $audioFileID = $this->_getParam('audioFileID');
+ $audioFileID = $this->_getParam('audioFileID');
$type = $this->_getParam('type');
$baseUrl = Application_Common_OsPath::getBaseDir();
$this->view->headScript()->appendFile(
- $baseUrl.'js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],
- 'text/javascript');
+ $baseUrl . 'js/airtime/audiopreview/preview_jplayer.js?' . $CC_CONFIG['airtime_version'],
+ 'text/javascript'
+ );
$this->view->headScript()->appendFile(
- $baseUrl.'js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],
- 'text/javascript');
+ $baseUrl . 'js/jplayer/jplayer.playlist.min.js?' . $CC_CONFIG['airtime_version'],
+ 'text/javascript'
+ );
$this->view->headLink()->appendStylesheet(
- $baseUrl.'js/jplayer/skin/jplayer.airtime.audio.preview.css?'.$CC_CONFIG['airtime_version']);
+ $baseUrl . 'js/jplayer/skin/jplayer.airtime.audio.preview.css?' . $CC_CONFIG['airtime_version']
+ );
$this->_helper->layout->setLayout('audioPlayer');
$logo = Application_Model_Preference::GetStationLogo();
if ($logo) {
- $this->view->logo = "data:image/png;base64,$logo";
+ $this->view->logo = "data:image/png;base64,{$logo}";
} else {
- $this->view->logo = $baseUrl."css/images/airtime_logo_jp.png";
+ $this->view->logo = $baseUrl . 'css/images/airtime_logo_jp.png';
}
- if ($type == "audioclip") {
+ if ($type == 'audioclip') {
$media = Application_Model_StoredFile::RecallById($audioFileID);
- $uri = $baseUrl."api/get-media/file/".$audioFileID;
- $mime = $media->getPropelOrm()->getDbMime();
+ $uri = $baseUrl . 'api/get-media/file/' . $audioFileID;
+ $mime = $media->getPropelOrm()->getDbMime();
$this->view->audioFileArtist = htmlspecialchars($media->getPropelOrm()->getDbArtistName());
- $this->view->audioFileTitle = htmlspecialchars($media->getPropelOrm()->getDbTrackTitle());
-
- } elseif ($type == "stream") {
+ $this->view->audioFileTitle = htmlspecialchars($media->getPropelOrm()->getDbTrackTitle());
+ } elseif ($type == 'stream') {
$webstream = CcWebstreamQuery::create()->findPk($audioFileID);
- $uri = $webstream->getDbUrl();
- $mime = $webstream->getDbMime();
- $this->view->audioFileTitle = htmlspecialchars($webstream->getDbName());
-
+ $uri = $webstream->getDbUrl();
+ $mime = $webstream->getDbMime();
+ $this->view->audioFileTitle = htmlspecialchars($webstream->getDbName());
} else {
- throw new Exception("Unknown type for audio preview!.Type=$type");
+ throw new Exception("Unknown type for audio preview!.Type={$type}");
}
- $this->view->uri = $uri;
- $this->view->mime = $mime;
- $this->view->audioFileID = $audioFileID;
+ $this->view->uri = $uri;
+ $this->view->mime = $mime;
+ $this->view->audioFileID = $audioFileID;
- $this->view->type = $type;
+ $this->view->type = $type;
$this->_helper->viewRenderer->setRender('audio-preview');
}
@@ -82,18 +84,18 @@ class AudiopreviewController extends Zend_Controller_Action
$baseUrl = Application_Common_OsPath::getBaseDir();
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headLink()->appendStylesheet($baseUrl.'js/jplayer/skin/jplayer.airtime.audio.preview.css?'.$CC_CONFIG['airtime_version']);
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/audiopreview/preview_jplayer.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/jplayer/jplayer.playlist.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headLink()->appendStylesheet($baseUrl . 'js/jplayer/skin/jplayer.airtime.audio.preview.css?' . $CC_CONFIG['airtime_version']);
$this->_helper->layout->setLayout('audioPlayer');
$logo = Application_Model_Preference::GetStationLogo();
if ($logo) {
- $this->view->logo = "data:image/png;base64,$logo";
+ $this->view->logo = "data:image/png;base64,{$logo}";
} else {
- $this->view->logo = $baseUrl."css/images/airtime_logo_jp.png";
+ $this->view->logo = $baseUrl . 'css/images/airtime_logo_jp.png';
}
- $this->view->playlistIndex= $playlistIndex;
+ $this->view->playlistIndex = $playlistIndex;
$this->view->playlistID = $playlistID;
$this->_helper->viewRenderer->setRender('audio-preview');
@@ -108,22 +110,23 @@ class AudiopreviewController extends Zend_Controller_Action
$baseUrl = Application_Common_OsPath::getBaseDir();
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headLink()->appendStylesheet($baseUrl.'js/jplayer/skin/jplayer.airtime.audio.preview.css?'.$CC_CONFIG['airtime_version']);
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/audiopreview/preview_jplayer.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/jplayer/jplayer.playlist.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headLink()->appendStylesheet($baseUrl . 'js/jplayer/skin/jplayer.airtime.audio.preview.css?' . $CC_CONFIG['airtime_version']);
$this->_helper->layout->setLayout('audioPlayer');
$logo = Application_Model_Preference::GetStationLogo();
if ($logo) {
- $this->view->logo = "data:image/png;base64,$logo";
+ $this->view->logo = "data:image/png;base64,{$logo}";
} else {
- $this->view->logo = $baseUrl."css/images/airtime_logo_jp.png";
+ $this->view->logo = $baseUrl . 'css/images/airtime_logo_jp.png';
}
- $this->view->blockIndex= $blockIndex;
+ $this->view->blockIndex = $blockIndex;
$this->view->blockId = $blockId;
$this->_helper->viewRenderer->setRender('audio-preview');
}
+
public function getBlockAction()
{
// disable the view and the layout
@@ -137,12 +140,13 @@ class AudiopreviewController extends Zend_Controller_Action
}
$bl = new Application_Model_Block($blockId);
- $result = array();
+ $result = [];
foreach ($bl->getContents(true) as $ele) {
$result[] = $this->createElementMap($ele);
}
$this->_helper->json($result);
}
+
/**
*Function will load and return the contents of the requested playlist.
*/
@@ -159,7 +163,7 @@ class AudiopreviewController extends Zend_Controller_Action
}
$pl = new Application_Model_Playlist($playlistID);
- $result = Array();
+ $result = [];
foreach ($pl->getContents(true) as $ele) {
if ($ele['type'] == 2) {
@@ -181,12 +185,12 @@ class AudiopreviewController extends Zend_Controller_Action
{
$baseUrl = Application_Common_OsPath::getBaseDir();
- $elementMap = array( 'element_title' => isset($track['track_title'])?$track['track_title']:"",
- 'element_artist' => isset($track['artist_name'])?$track['artist_name']:"",
- 'element_id' => isset($track['id'])?$track['id']:"",
- 'element_position' => isset($track['position'])?$track['position']:"",
- 'mime' => isset($track['mime'])?$track['mime']:""
- );
+ $elementMap = ['element_title' => isset($track['track_title']) ? $track['track_title'] : '',
+ 'element_artist' => isset($track['artist_name']) ? $track['artist_name'] : '',
+ 'element_id' => isset($track['id']) ? $track['id'] : '',
+ 'element_position' => isset($track['position']) ? $track['position'] : '',
+ 'mime' => isset($track['mime']) ? $track['mime'] : '',
+ ];
/* If the track type is static we know it must be
* a track because static blocks can only contain
@@ -199,13 +203,14 @@ class AudiopreviewController extends Zend_Controller_Action
if ($track['type'] == 0) {
$mime = trim(strtolower($track['mime']));
+
try {
$elementMap['element_' . FileDataHelper::getAudioMimeTypeArray()[$mime]] = $track['item_id'];
} catch (Exception $e) {
- throw new Exception("Unknown file type: $mime");
+ throw new Exception("Unknown file type: {$mime}");
}
- $elementMap['uri'] = $baseUrl."api/get-media/file/".$track['item_id'];
+ $elementMap['uri'] = $baseUrl . 'api/get-media/file/' . $track['item_id'];
} else {
$elementMap['uri'] = $track['path'];
}
@@ -226,16 +231,16 @@ class AudiopreviewController extends Zend_Controller_Action
$baseUrl = Application_Common_OsPath::getBaseDir();
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headLink()->appendStylesheet($baseUrl.'js/jplayer/skin/jplayer.airtime.audio.preview.css?'.$CC_CONFIG['airtime_version']);
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/audiopreview/preview_jplayer.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/jplayer/jplayer.playlist.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headLink()->appendStylesheet($baseUrl . 'js/jplayer/skin/jplayer.airtime.audio.preview.css?' . $CC_CONFIG['airtime_version']);
$this->_helper->layout->setLayout('audioPlayer');
$logo = Application_Model_Preference::GetStationLogo();
if ($logo) {
- $this->view->logo = "data:image/png;base64,$logo";
+ $this->view->logo = "data:image/png;base64,{$logo}";
} else {
- $this->view->logo = $baseUrl."css/images/airtime_logo_jp.png";
+ $this->view->logo = $baseUrl . 'css/images/airtime_logo_jp.png';
}
$this->view->showID = $showID;
@@ -261,28 +266,28 @@ class AudiopreviewController extends Zend_Controller_Action
}
$showInstance = new Application_Model_ShowInstance($showID);
- $result = array();
+ $result = [];
$position = 0;
foreach ($showInstance->getShowListContent() as $track) {
-
- $elementMap = array(
- 'element_title' => isset($track['track_title']) ? $track['track_title'] : "",
- 'element_artist' => isset($track['creator']) ? $track['creator'] : "",
+ $elementMap = [
+ 'element_title' => isset($track['track_title']) ? $track['track_title'] : '',
+ 'element_artist' => isset($track['creator']) ? $track['creator'] : '',
'element_position' => $position,
'element_id' => ++$position,
- 'mime' => isset($track['mime'])?$track['mime']:""
- );
+ 'mime' => isset($track['mime']) ? $track['mime'] : '',
+ ];
$elementMap['type'] = $track['type'];
if ($track['type'] == 0) {
$mime = trim(strtolower($track['mime']));
+
try {
$elementMap['element_' . FileDataHelper::getAudioMimeTypeArray()[$mime]] = $track['item_id'];
} catch (Exception $e) {
- throw new Exception("Unknown file type: $mime");
+ throw new Exception("Unknown file type: {$mime}");
}
- $elementMap['uri'] = $baseUrl."api/get-media/file/".$track['item_id'];
+ $elementMap['uri'] = $baseUrl . 'api/get-media/file/' . $track['item_id'];
} else {
$elementMap['uri'] = $track['filepath'];
}
@@ -290,6 +295,5 @@ class AudiopreviewController extends Zend_Controller_Action
}
$this->_helper->json($result);
-
}
}
diff --git a/legacy/application/controllers/DashboardController.php b/legacy/application/controllers/DashboardController.php
index 5b265fb19..c16abd7ba 100644
--- a/legacy/application/controllers/DashboardController.php
+++ b/legacy/application/controllers/DashboardController.php
@@ -2,13 +2,13 @@
class DashboardController extends Zend_Controller_Action
{
-
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('switch-source', 'json')
- ->addActionContext('disconnect-source', 'json')
- ->initContext();
+ ->addActionContext('disconnect-source', 'json')
+ ->initContext()
+ ;
}
public function indexAction()
@@ -24,17 +24,17 @@ class DashboardController extends Zend_Controller_Action
$user = new Application_Model_User($userInfo->id);
$show = Application_Model_Show::getCurrentShow();
- $show_id = isset($show[0]['id'])?$show[0]['id']:0;
+ $show_id = isset($show[0]['id']) ? $show[0]['id'] : 0;
$source_connected = Application_Model_Preference::GetSourceStatus($sourcename);
if ($user->canSchedule($show_id) && $source_connected) {
- $data = array("sourcename"=>$sourcename);
- Application_Model_RabbitMq::SendMessageToPypo("disconnect_source", $data);
+ $data = ['sourcename' => $sourcename];
+ Application_Model_RabbitMq::SendMessageToPypo('disconnect_source', $data);
} else {
if ($source_connected) {
$this->view->error = _("You don't have permission to disconnect source.");
} else {
- $this->view->error = _("There is no source connected to this input.");
+ $this->view->error = _('There is no source connected to this input.');
}
}
}
@@ -48,33 +48,36 @@ class DashboardController extends Zend_Controller_Action
$user = new Application_Model_User($userInfo->id);
$show = Application_Model_Show::getCurrentShow();
- $show_id = isset($show[0]['id'])?$show[0]['id']:0;
+ $show_id = isset($show[0]['id']) ? $show[0]['id'] : 0;
$source_connected = Application_Model_Preference::GetSourceStatus($sourcename);
- if ($user->canSchedule($show_id) && ($source_connected || $sourcename == 'scheduled_play' || $current_status == "on")) {
+ if ($user->canSchedule($show_id) && ($source_connected || $sourcename == 'scheduled_play' || $current_status == 'on')) {
+ $change_status_to = 'on';
- $change_status_to = "on";
-
- if (strtolower($current_status) == "on") {
- $change_status_to = "off";
+ if (strtolower($current_status) == 'on') {
+ $change_status_to = 'off';
}
- $data = array("sourcename"=>$sourcename, "status"=>$change_status_to);
- Application_Model_RabbitMq::SendMessageToPypo("switch_source", $data);
- if (strtolower($current_status) == "on") {
- Application_Model_Preference::SetSourceSwitchStatus($sourcename, "off");
- $this->view->status = "OFF";
+ $data = ['sourcename' => $sourcename, 'status' => $change_status_to];
+ Application_Model_RabbitMq::SendMessageToPypo('switch_source', $data);
+ if (strtolower($current_status) == 'on') {
+ Application_Model_Preference::SetSourceSwitchStatus($sourcename, 'off');
+ $this->view->status = 'OFF';
//Log table updates
- Application_Model_LiveLog::SetEndTime($sourcename == 'scheduled_play'?'S':'L',
- new DateTime("now", new DateTimeZone('UTC')));
+ Application_Model_LiveLog::SetEndTime(
+ $sourcename == 'scheduled_play' ? 'S' : 'L',
+ new DateTime('now', new DateTimeZone('UTC'))
+ );
} else {
- Application_Model_Preference::SetSourceSwitchStatus($sourcename, "on");
- $this->view->status = "ON";
+ Application_Model_Preference::SetSourceSwitchStatus($sourcename, 'on');
+ $this->view->status = 'ON';
//Log table updates
- Application_Model_LiveLog::SetNewLogTime($sourcename == 'scheduled_play'?'S':'L',
- new DateTime("now", new DateTimeZone('UTC')));
+ Application_Model_LiveLog::SetNewLogTime(
+ $sourcename == 'scheduled_play' ? 'S' : 'L',
+ new DateTime('now', new DateTimeZone('UTC'))
+ );
}
} else {
if ($source_connected) {
@@ -83,7 +86,7 @@ class DashboardController extends Zend_Controller_Action
if ($sourcename == 'scheduled_play') {
$this->view->error = _("You don't have permission to disconnect source.");
} else {
- $this->view->error = _("There is no source connected to this input.");
+ $this->view->error = _('There is no source connected to this input.');
}
}
}
@@ -95,11 +98,11 @@ class DashboardController extends Zend_Controller_Action
$baseUrl = Application_Common_OsPath::getBaseDir();
- $this->view->headLink()->appendStylesheet($baseUrl.'js/jplayer/skin/jplayer.blue.monday.css?'.$CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'js/jplayer/skin/jplayer.blue.monday.css?' . $CC_CONFIG['airtime_version']);
$this->_helper->layout->setLayout('livestream');
$logo = Application_Model_Preference::GetStationLogo();
- $this->view->logo = "data:image/png;base64,".$logo;
+ $this->view->logo = 'data:image/png;base64,' . $logo;
}
public function helpAction()
@@ -124,7 +127,6 @@ class DashboardController extends Zend_Controller_Action
$headScript = $this->view->headScript();
AirtimeTableView::injectTableJavaScriptDependencies($headScript, $baseUrl, $CC_CONFIG['airtime_version']);
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/widgets/table-example.js?'.$CC_CONFIG['airtime_version']);
-
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/widgets/table-example.js?' . $CC_CONFIG['airtime_version']);
}
}
diff --git a/legacy/application/controllers/EmbedController.php b/legacy/application/controllers/EmbedController.php
index f228979ac..2f67b328b 100644
--- a/legacy/application/controllers/EmbedController.php
+++ b/legacy/application/controllers/EmbedController.php
@@ -2,13 +2,15 @@
class EmbedController extends Zend_Controller_Action
{
- public function init() {
+ public function init()
+ {
// translate widgets to station default language
$locale = Application_Model_Preference::GetDefaultLocale();
if ($locale) {
Application_Model_Locale::configureLocalization($locale);
}
}
+
/**
* This is the action that is called to insert the player onto a web page.
* It passes all the js and css files to the view, as well as all the
@@ -25,45 +27,45 @@ class EmbedController extends Zend_Controller_Action
$request = $this->getRequest();
- $this->view->playerhtml5_js = "/js/airtime/player/playerhtml5.js?".$CC_CONFIG['airtime_version'];
- $this->view->jquery = "/js/libs/jquery-1.10.2.min.js";
- $this->view->metadata_api_url = "/api/live-info";
+ $this->view->playerhtml5_js = '/js/airtime/player/playerhtml5.js?' . $CC_CONFIG['airtime_version'];
+ $this->view->jquery = '/js/libs/jquery-1.10.2.min.js';
+ $this->view->metadata_api_url = '/api/live-info';
$this->view->player_title = json_encode($this->view->escape($request->getParam('title')));
- $this->view->jquery_i18n = "/js/i18n/jquery.i18n.js?";
+ $this->view->jquery_i18n = '/js/i18n/jquery.i18n.js?';
$styleParam = $request->getParam('style');
- $player_style = isset($styleParam) ? $styleParam : "basic";
- if ($player_style == "premium") {
- $this->view->css = "/css/radio-page/premium_player.css?".$CC_CONFIG['airtime_version'];
+ $player_style = isset($styleParam) ? $styleParam : 'basic';
+ if ($player_style == 'premium') {
+ $this->view->css = '/css/radio-page/premium_player.css?' . $CC_CONFIG['airtime_version'];
} else {
- $this->view->css = "/css/player.css?".$CC_CONFIG['airtime_version'];
+ $this->view->css = '/css/player.css?' . $CC_CONFIG['airtime_version'];
}
$this->view->player_style = $player_style;
$stream = $request->getParam('stream');
$streamData = Application_Model_StreamSetting::getEnabledStreamData();
- $availableMobileStreams = array();
- $availableDesktopStreams = array();
+ $availableMobileStreams = [];
+ $availableDesktopStreams = [];
- if ($stream == "auto") {
- $this->view->playerMode = "auto";
- $this->view->streamURL = json_encode("");
+ if ($stream == 'auto') {
+ $this->view->playerMode = 'auto';
+ $this->view->streamURL = json_encode('');
foreach ($streamData as $s) {
- if ($s["mobile"]) {
+ if ($s['mobile']) {
array_push($availableMobileStreams, $s);
- } else if (!$s["mobile"]) {
+ } elseif (!$s['mobile']) {
array_push($availableDesktopStreams, $s);
}
}
- } else if ($stream == "file") {
- $this->view->playerMode = "file";
- $this->view->streamURL = json_encode($request->getParam("file_url"));
- $this->view->codec = $request->getParam("file_codec");
+ } elseif ($stream == 'file') {
+ $this->view->playerMode = 'file';
+ $this->view->streamURL = json_encode($request->getParam('file_url'));
+ $this->view->codec = $request->getParam('file_codec');
} elseif (!empty($stream)) {
- $this->view->playerMode = "manual";
+ $this->view->playerMode = 'manual';
$selectedStreamData = $streamData[$stream];
- $this->view->streamURL = json_encode($selectedStreamData["url"]);
- $this->view->codec = $selectedStreamData["codec"];
+ $this->view->streamURL = json_encode($selectedStreamData['url']);
+ $this->view->codec = $selectedStreamData['codec'];
}
$this->view->availableMobileStreams = json_encode($availableMobileStreams);
$this->view->availableDesktopStreams = json_encode($availableDesktopStreams);
@@ -77,23 +79,23 @@ class EmbedController extends Zend_Controller_Action
$request = $this->getRequest();
- $this->view->angular = Application_Common_HTTPHelper::getStationUrl() . 'js/libs/angular.min.js?'.$CC_CONFIG['airtime_version'];
+ $this->view->angular = Application_Common_HTTPHelper::getStationUrl() . 'js/libs/angular.min.js?' . $CC_CONFIG['airtime_version'];
$widgetStyle = $request->getParam('style');
- if ($widgetStyle == "premium") {
- $this->view->widgetStyle = "premium";
- $this->view->css = "/css/embed/weekly-schedule-widget.css?" . $CC_CONFIG['airtime_version'];
+ if ($widgetStyle == 'premium') {
+ $this->view->widgetStyle = 'premium';
+ $this->view->css = '/css/embed/weekly-schedule-widget.css?' . $CC_CONFIG['airtime_version'];
} else {
- $this->view->widgetStyle = "basic";
- $this->view->css = "/css/embed/weekly-schedule-widget-basic.css?" . $CC_CONFIG['airtime_version'];
+ $this->view->widgetStyle = 'basic';
+ $this->view->css = '/css/embed/weekly-schedule-widget-basic.css?' . $CC_CONFIG['airtime_version'];
}
- $this->view->jquery = "/js/libs/jquery-1.8.3.min.js?".$CC_CONFIG['airtime_version'];
+ $this->view->jquery = '/js/libs/jquery-1.8.3.min.js?' . $CC_CONFIG['airtime_version'];
$weeklyScheduleData = WidgetHelper::getWeekInfoV2();
$this->view->schedule_data = json_encode($weeklyScheduleData);
- $currentDay = new DateTime("now", new DateTimeZone(Application_Model_Preference::GetTimezone()));
+ $currentDay = new DateTime('now', new DateTimeZone(Application_Model_Preference::GetTimezone()));
//day of the month without leading zeros (1 to 31)
- $this->view->currentDayOfMonth = $currentDay->format("j");
+ $this->view->currentDayOfMonth = $currentDay->format('j');
}
}
diff --git a/legacy/application/controllers/EmbeddablewidgetsController.php b/legacy/application/controllers/EmbeddablewidgetsController.php
index 8c3e10f34..5ab3cbbc1 100644
--- a/legacy/application/controllers/EmbeddablewidgetsController.php
+++ b/legacy/application/controllers/EmbeddablewidgetsController.php
@@ -2,10 +2,8 @@
class EmbeddableWidgetsController extends Zend_Controller_Action
{
-
public function init()
{
-
}
public function playerAction()
@@ -14,8 +12,8 @@ class EmbeddableWidgetsController extends Zend_Controller_Action
$CC_CONFIG = Config::getConfig();
$baseUrl = Application_Common_OsPath::getBaseDir();
- $this->view->headLink()->appendStylesheet($baseUrl.'css/player-form.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/player/player.js?'.$CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/player-form.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/player/player.js?' . $CC_CONFIG['airtime_version']);
$form = new Application_Form_Player();
@@ -25,9 +23,9 @@ class EmbeddableWidgetsController extends Zend_Controller_Action
if ($numEnabledStreams > 0 && $apiEnabled) {
$this->view->player_form = $form;
} else {
- $this->view->player_error_msg = _("To configure and use the embeddable player you must:
+ $this->view->player_error_msg = _('To configure and use the embeddable player you must:
1. Enable at least one MP3, AAC, or OGG stream under Settings -> Streams
- 2. Enable the Public LibreTime API under Settings -> Preferences");
+ 2. Enable the Public LibreTime API under Settings -> Preferences');
}
}
@@ -38,8 +36,8 @@ class EmbeddableWidgetsController extends Zend_Controller_Action
$apiEnabled = Application_Model_Preference::GetAllow3rdPartyApi();
if (!$apiEnabled) {
- $this->view->weekly_schedule_error_msg = _("To use the embeddable weekly schedule widget you must:
- Enable the Public LibreTime API under Settings -> Preferences");
+ $this->view->weekly_schedule_error_msg = _('To use the embeddable weekly schedule widget you must:
+ Enable the Public LibreTime API under Settings -> Preferences');
}
}
@@ -51,15 +49,15 @@ class EmbeddableWidgetsController extends Zend_Controller_Action
$apiEnabled = Application_Model_Preference::GetAllow3rdPartyApi();
if (!$apiEnabled) {
- $this->view->facebook_error_msg = _("To add the Radio Tab to your Facebook Page, you must first:
- Enable the Public LibreTime API under Settings -> Preferences");
+ $this->view->facebook_error_msg = _('To add the Radio Tab to your Facebook Page, you must first:
+ Enable the Public LibreTime API under Settings -> Preferences');
}
$CC_CONFIG = Config::getConfig();
$baseUrl = Application_Common_OsPath::getBaseDir();
$facebookAppId = $CC_CONFIG['facebook-app-id'];
- $this->view->headScript()->appendScript("var FACEBOOK_APP_ID = " . json_encode($facebookAppId) . ";");
+ $this->view->headScript()->appendScript('var FACEBOOK_APP_ID = ' . json_encode($facebookAppId) . ';');
$this->view->headScript()->appendFile($baseUrl . 'js/airtime/common/facebook.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
}
@@ -78,7 +76,7 @@ class EmbeddableWidgetsController extends Zend_Controller_Action
}
$values = $request->getPost();
- $facebookPageIds = json_decode($values["pages"]);
+ $facebookPageIds = json_decode($values['pages']);
$CC_CONFIG = Config::getConfig();
$facebookMicroserviceUrl = $CC_CONFIG['facebook-app-url'];
@@ -86,14 +84,15 @@ class EmbeddableWidgetsController extends Zend_Controller_Action
//Post the page tab ID and station subdomain to the social microservice so that mapping can be saved
//in a database.
- foreach ($facebookPageIds as $facebookPageId)
- {
- $postfields = array();
- $postfields["facebookPageId"] = $facebookPageId;
- $postfields["stationId"] = $CC_CONFIG['stationId'];
+ foreach ($facebookPageIds as $facebookPageId) {
+ $postfields = [];
+ $postfields['facebookPageId'] = $facebookPageId;
+ $postfields['stationId'] = $CC_CONFIG['stationId'];
- $query_string = "";
- foreach ($postfields as $k => $v) $query_string .= "$k=".urlencode($v)."&";
+ $query_string = '';
+ foreach ($postfields as $k => $v) {
+ $query_string .= "{$k}=" . urlencode($v) . '&';
+ }
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $facebookMicroserviceUrl);
@@ -102,21 +101,18 @@ class EmbeddableWidgetsController extends Zend_Controller_Action
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
- curl_setopt($ch, CURLOPT_USERPWD, ":$facebookMicroserviceApiKey");
+ curl_setopt($ch, CURLOPT_USERPWD, ":{$facebookMicroserviceApiKey}");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$jsondata = curl_exec($ch);
if (curl_error($ch)) {
- throw new Exception("Failed to reach server in " . __FUNCTION__ . ": "
+ throw new Exception('Failed to reach server in ' . __FUNCTION__ . ': '
. curl_errno($ch) . ' - ' . curl_error($ch) . ' - ' . curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
}
curl_close($ch);
-
}
//$arr = json_decode($jsondata, true); # Decode JSON String
-
}
}
-
diff --git a/legacy/application/controllers/ErrorController.php b/legacy/application/controllers/ErrorController.php
index a840da163..9ad9946c0 100644
--- a/legacy/application/controllers/ErrorController.php
+++ b/legacy/application/controllers/ErrorController.php
@@ -1,6 +1,7 @@
_getParam('error_handler');
if ($errors) {
@@ -27,21 +29,27 @@ class ErrorController extends Zend_Controller_Action {
Logging::error($errors->exception->getTraceAsString());
switch ($errors->type) {
- case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE :
- case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER :
+ case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
+ case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
$this->error404Action();
+
break;
- case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION :
+
+ case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
$this->error400Action();
+
break;
- default :
+
+ default:
$this->error500Action();
+
break;
}
} else {
//$exceptions = $this->_getAllParams();
//Logging::error($exceptions);
$this->error404Action();
+
return;
}
@@ -51,7 +59,7 @@ class ErrorController extends Zend_Controller_Action {
$log->crit($this->view->message, $errors->exception);
}*/
//Logging that actually works: -- Albert
- Logging::error($this->view->message . ": " . $errors->exception);
+ Logging::error($this->view->message . ': ' . $errors->exception);
// conditionally display exceptions
if ($this->getInvokeArg('displayExceptions') == true) {
@@ -68,50 +76,51 @@ class ErrorController extends Zend_Controller_Action {
$this->view->headLink()->appendStylesheet($staticBaseDir . 'css/styles.css?' . $CC_CONFIG['airtime_version']);
}
- public function getLog() {
+ public function getLog()
+ {
$bootstrap = $this->getInvokeArg('bootstrap');
if (!$bootstrap->hasPluginResource('Log')) {
return false;
}
- $log = $bootstrap->getResource('Log');
- return $log;
+ return $bootstrap->getResource('Log');
}
/**
- * 404 error - route or controller
+ * 404 error - route or controller.
*/
- public function error404Action() {
+ public function error404Action()
+ {
$this->_helper->viewRenderer('error');
$this->getResponse()->setHttpResponseCode(404);
$this->view->message = _('Page not found.');
}
/**
- * 400 error - no such action
+ * 400 error - no such action.
*/
- public function error400Action() {
+ public function error400Action()
+ {
$this->_helper->viewRenderer('error-400');
$this->getResponse()->setHttpResponseCode(400);
$this->view->message = _('The requested action is not supported.');
-
}
/**
- * 403 error - permission denied
+ * 403 error - permission denied.
*/
- public function error403Action() {
-
+ public function error403Action()
+ {
$this->_helper->viewRenderer('error-403');
$this->getResponse()->setHttpResponseCode(403);
$this->view->message = _('You do not have permission to access this resource.');
}
/**
- * 500 error - internal server error
+ * 500 error - internal server error.
*/
- public function error500Action() {
-
+ public function error500Action()
+ {
$this->_helper->viewRenderer('error-500');
$this->getResponse()->setHttpResponseCode(500);
diff --git a/legacy/application/controllers/FeedsController.php b/legacy/application/controllers/FeedsController.php
index 9d26e4101..c8c1cf406 100644
--- a/legacy/application/controllers/FeedsController.php
+++ b/legacy/application/controllers/FeedsController.php
@@ -11,9 +11,10 @@ class FeedsController extends Zend_Controller_Action
$response = $this->getResponse();
if ((Application_Model_Preference::getStationPodcastPrivacy()
- && $request->getParam("sharing_token") != Application_Model_Preference::getStationPodcastDownloadKey())
+ && $request->getParam('sharing_token') != Application_Model_Preference::getStationPodcastDownloadKey())
&& !RestAuth::verifyAuth(true, false, $this)) {
$response->setHttpResponseCode(401);
+
return;
}
@@ -21,23 +22,23 @@ class FeedsController extends Zend_Controller_Action
$rssData = Application_Service_PodcastService::createStationRssFeed();
- $mimeType = "text/xml";
- header("Content-Type: $mimeType; charset=UTF-8");
+ $mimeType = 'text/xml';
+ header("Content-Type: {$mimeType}; charset=UTF-8");
if (isset($_SERVER['HTTP_RANGE'])) {
header('HTTP/1.1 206 Partial Content');
} else {
header('HTTP/1.1 200 OK');
}
- header("Content-Type: $mimeType");
- header("Content-Transfer-Encoding: binary");
+ header("Content-Type: {$mimeType}");
+ header('Content-Transfer-Encoding: binary');
header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Accept-Ranges: bytes');
$size = strlen($rssData);
$begin = 0;
- $end = $size - 1;
+ $end = $size - 1;
//ob_start(); //Must start a buffer here for these header() functions
@@ -53,10 +54,10 @@ class FeedsController extends Zend_Controller_Action
if ($size > 0) {
header('Content-Length:' . (($end - $begin) + 1));
if (isset($_SERVER['HTTP_RANGE'])) {
- header("Content-Range: bytes $begin-$end/$size");
+ header("Content-Range: bytes {$begin}-{$end}/{$size}");
}
}
echo $rssData;
}
-}
\ No newline at end of file
+}
diff --git a/legacy/application/controllers/IndexController.php b/legacy/application/controllers/IndexController.php
index 619b85bd8..36fbb853a 100644
--- a/legacy/application/controllers/IndexController.php
+++ b/legacy/application/controllers/IndexController.php
@@ -2,10 +2,8 @@
class IndexController extends Zend_Controller_Action
{
-
public function init()
{
-
}
public function indexAction()
@@ -17,20 +15,20 @@ class IndexController extends Zend_Controller_Action
$this->view->headScript()->appendFile($baseUrl . 'js/i18n/jquery.i18n.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'locale/general-translation-table?' . $CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headScript()->appendScript("$.i18n.setDictionary(general_dict)");
- $this->view->headScript()->appendScript("var baseUrl='$baseUrl'");
+ $this->view->headScript()->appendScript('$.i18n.setDictionary(general_dict)');
+ $this->view->headScript()->appendScript("var baseUrl='{$baseUrl}'");
//jplayer
- $this->view->headScript()->appendFile($baseUrl.'js/jplayer/jquery.jplayer.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/jplayer/jquery.jplayer.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/jplayer/jplayer.playlist.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headLink()->setStylesheet($baseUrl.'css/radio-page/radio-page.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/embed/weekly-schedule-widget.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/radio-page/station-podcast.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/bootstrap.css?'.$CC_CONFIG['airtime_version']);
+ $this->view->headLink()->setStylesheet($baseUrl . 'css/radio-page/radio-page.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/embed/weekly-schedule-widget.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/radio-page/station-podcast.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/bootstrap.css?' . $CC_CONFIG['airtime_version']);
//jplayer control buttons
- $this->view->headLink()->appendStylesheet($baseUrl.'css/redmond/jquery-ui-1.8.8.custom.css?'.$CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/redmond/jquery-ui-1.8.8.custom.css?' . $CC_CONFIG['airtime_version']);
$this->_helper->layout->setLayout('radio-page');
@@ -51,7 +49,7 @@ class IndexController extends Zend_Controller_Action
$this->view->stationUrl = Application_Common_HTTPHelper::getStationUrl();
$displayRadioPageLoginButtonValue = Application_Model_Preference::getRadioPageDisplayLoginButton();
- if ($displayRadioPageLoginButtonValue == "") {
+ if ($displayRadioPageLoginButtonValue == '') {
$displayRadioPageLoginButtonValue = true;
}
$this->view->displayLoginButton = $displayRadioPageLoginButtonValue;
@@ -59,21 +57,21 @@ class IndexController extends Zend_Controller_Action
//station feed episodes
$stationPodcastId = Application_Model_Preference::getStationPodcastId();
$podcastEpisodesService = new Application_Service_PodcastEpisodeService();
- $episodes = $podcastEpisodesService->getPodcastEpisodes($stationPodcastId, 0, 0, PodcastEpisodesPeer::PUBLICATION_DATE, "DESC");
+ $episodes = $podcastEpisodesService->getPodcastEpisodes($stationPodcastId, 0, 0, PodcastEpisodesPeer::PUBLICATION_DATE, 'DESC');
foreach ($episodes as $e => $v) {
- $episodes[$e]["CcFiles"]["track_title"] = htmlspecialchars($v["CcFiles"]["track_title"], ENT_QUOTES);
- $episodes[$e]["CcFiles"]["artist_name"] = htmlspecialchars($v["CcFiles"]["artist_name"], ENT_QUOTES);
+ $episodes[$e]['CcFiles']['track_title'] = htmlspecialchars($v['CcFiles']['track_title'], ENT_QUOTES);
+ $episodes[$e]['CcFiles']['artist_name'] = htmlspecialchars($v['CcFiles']['artist_name'], ENT_QUOTES);
- $pubDate = explode(" ", $v["publication_date"]);
- $episodes[$e]["publication_date"] = $pubDate[0];
+ $pubDate = explode(' ', $v['publication_date']);
+ $episodes[$e]['publication_date'] = $pubDate[0];
- $length = explode(".", $v["CcFiles"]["length"]);
- $episodes[$e]["CcFiles"]["length"] = $length[0];
+ $length = explode('.', $v['CcFiles']['length']);
+ $episodes[$e]['CcFiles']['length'] = $length[0];
- $episodes[$e]["mime"] = FileDataHelper::getAudioMimeTypeArray()[$v["CcFiles"]["mime"]];
+ $episodes[$e]['mime'] = FileDataHelper::getAudioMimeTypeArray()[$v['CcFiles']['mime']];
- if (is_null($v["CcFiles"]["description"])) {
- $episodes[$e]["CcFiles"]["description"] = "";
+ if (is_null($v['CcFiles']['description'])) {
+ $episodes[$e]['CcFiles']['description'] = '';
}
}
@@ -87,9 +85,8 @@ class IndexController extends Zend_Controller_Action
$this->view->stationPodcastRssUrl = $url;
$stationName = Application_Model_Preference::GetStationName();
- $this->view->podcastTitle = sprintf(_("%s Podcast"), !empty($stationName) ? $stationName : $CC_CONFIG["stationId"]);
- $this->view->emptyPodcastMessage = _("No tracks have been published yet.");
-
+ $this->view->podcastTitle = sprintf(_('%s Podcast'), !empty($stationName) ? $stationName : $CC_CONFIG['stationId']);
+ $this->view->emptyPodcastMessage = _('No tracks have been published yet.');
}
public function mainAction()
@@ -101,5 +98,4 @@ class IndexController extends Zend_Controller_Action
{
$this->getResponse()->setHttpResponseCode(503);
}
-
}
diff --git a/legacy/application/controllers/LibraryController.php b/legacy/application/controllers/LibraryController.php
index ae00a7b09..34aa3574a 100644
--- a/legacy/application/controllers/LibraryController.php
+++ b/legacy/application/controllers/LibraryController.php
@@ -2,40 +2,40 @@
class LibraryController extends Zend_Controller_Action
{
-
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('contents-feed', 'json')
- ->addActionContext('delete', 'json')
- ->addActionContext('duplicate', 'json')
- ->addActionContext('duplicate-block', 'json')
- ->addActionContext('delete-group', 'json')
- ->addActionContext('context-menu', 'json')
- ->addActionContext('get-file-metadata', 'html')
- ->addActionContext('set-num-entries', 'json')
- ->addActionContext('edit-file-md', 'json')
- ->addActionContext('publish-dialog', 'html')
- ->initContext();
+ ->addActionContext('delete', 'json')
+ ->addActionContext('duplicate', 'json')
+ ->addActionContext('duplicate-block', 'json')
+ ->addActionContext('delete-group', 'json')
+ ->addActionContext('context-menu', 'json')
+ ->addActionContext('get-file-metadata', 'html')
+ ->addActionContext('set-num-entries', 'json')
+ ->addActionContext('edit-file-md', 'json')
+ ->addActionContext('publish-dialog', 'html')
+ ->initContext()
+ ;
}
public function indexAction()
{
- $this->_redirect("showbuilder");
+ $this->_redirect('showbuilder');
}
protected function playlistNotFound($p_type)
{
- $this->view->error = sprintf(_("%s not found"), $p_type);
+ $this->view->error = sprintf(_('%s not found'), $p_type);
- Logging::info("$p_type not found");
+ Logging::info("{$p_type} not found");
Application_Model_Library::changePlaylist(null, $p_type);
$this->createFullResponse(null);
}
protected function playlistUnknownError($e)
{
- $this->view->error = _("Something went wrong.");
+ $this->view->error = _('Something went wrong.');
Logging::info($e->getMessage());
}
@@ -62,9 +62,8 @@ class LibraryController extends Zend_Controller_Action
$this->view->id = $obj->getId();
if ($isJson) {
return $this->view->render($viewPath);
- } else {
- $this->view->html = $this->view->render($viewPath);
}
+ $this->view->html = $this->view->render($viewPath);
} else {
$this->view->obj = $obj;
$this->view->id = $obj->getId();
@@ -84,24 +83,24 @@ class LibraryController extends Zend_Controller_Action
//playlist||timeline
$screen = $this->_getParam('screen');
- $menu = array();
+ $menu = [];
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id);
//Open a jPlayer window and play the audio clip.
- $menu["play"] = array("name"=> _("Preview"), "icon" => "play", "disabled" => false);
+ $menu['play'] = ['name' => _('Preview'), 'icon' => 'play', 'disabled' => false];
- $isAdminOrPM = $user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
+ $isAdminOrPM = $user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER]);
$obj_sess = new Zend_Session_Namespace(UI_PLAYLISTCONTROLLER_OBJ_SESSNAME);
- if ($type === "audioclip") {
+ if ($type === 'audioclip') {
$file = Application_Model_StoredFile::RecallById($id);
- $menu["play"]["mime"] = $file->getPropelOrm()->getDbMime();
+ $menu['play']['mime'] = $file->getPropelOrm()->getDbMime();
- if (isset($obj_sess->id) && $screen == "playlist") {
+ if (isset($obj_sess->id) && $screen == 'playlist') {
// if the user is not admin or pm, check the creator and see if this person owns the playlist or Block
if ($obj_sess->type == 'playlist') {
$obj = new Application_Model_Playlist($obj_sess->id);
@@ -109,16 +108,16 @@ class LibraryController extends Zend_Controller_Action
$obj = new Application_Model_Block($obj_sess->id);
}
if ($isAdminOrPM || $obj->getCreatorId() == $user->getId()) {
- if ($obj_sess->type === "playlist") {
- $menu["pl_add"] = array("name"=> _("Add to Playlist"), "icon" => "add-playlist", "icon" => "copy");
- } elseif ($obj_sess->type === "block" && $obj->isStatic()) {
- $menu["pl_add"] = array("name"=> _("Add to Smart Block"), "icon" => "add-playlist", "icon" => "copy");
+ if ($obj_sess->type === 'playlist') {
+ $menu['pl_add'] = ['name' => _('Add to Playlist'), 'icon' => 'add-playlist', 'icon' => 'copy'];
+ } elseif ($obj_sess->type === 'block' && $obj->isStatic()) {
+ $menu['pl_add'] = ['name' => _('Add to Smart Block'), 'icon' => 'add-playlist', 'icon' => 'copy'];
}
}
}
if ($isAdminOrPM || $file->getFileOwnerId() == $user->getId()) {
- $menu["del"] = array("name"=> _("Delete"), "icon" => "delete", "url" => $baseUrl."library/delete");
- $menu["edit"] = array("name"=> _("Edit..."), "icon" => "edit", "url" => $baseUrl."library/edit-file-md/id/{$id}");
+ $menu['del'] = ['name' => _('Delete'), 'icon' => 'delete', 'url' => $baseUrl . 'library/delete'];
+ $menu['edit'] = ['name' => _('Edit...'), 'icon' => 'edit', 'url' => $baseUrl . "library/edit-file-md/id/{$id}"];
// Disable My podcasts
// See https://github.com/LibreTime/libretime/issues/1320
// $menu["publish"] = array("name"=> _("Publish..."), "url" => $baseUrl."library/publish/id/{$id}");
@@ -128,58 +127,57 @@ class LibraryController extends Zend_Controller_Action
// and not the cloud_file id (if applicable) for track download.
// Our application logic (StoredFile.php) will determine if the track
// is a cloud_file and handle it appropriately.
- $url = $baseUrl."api/get-media/file/$id/download/true";
- $menu["download"] = array("name" => _("Download"), "icon" => "download", "url" => $url);
-
- } elseif ($type === "playlist" || $type === "block") {
+ $url = $baseUrl . "api/get-media/file/{$id}/download/true";
+ $menu['download'] = ['name' => _('Download'), 'icon' => 'download', 'url' => $url];
+ } elseif ($type === 'playlist' || $type === 'block') {
if ($type === 'playlist') {
$obj = new Application_Model_Playlist($id);
- $menu["duplicate"] = array("name" => _("Duplicate Playlist"), "icon" => "edit", "url" => $baseUrl."library/duplicate");
+ $menu['duplicate'] = ['name' => _('Duplicate Playlist'), 'icon' => 'edit', 'url' => $baseUrl . 'library/duplicate'];
} elseif ($type === 'block') {
$obj = new Application_Model_Block($id);
- $menu["duplicate"] = array("name" => _("Duplicate Smartblock"), "icon" => "edit", "url" => $baseUrl."library/duplicate-block");
+ $menu['duplicate'] = ['name' => _('Duplicate Smartblock'), 'icon' => 'edit', 'url' => $baseUrl . 'library/duplicate-block'];
if (!$obj->isStatic()) {
- unset($menu["play"]);
+ unset($menu['play']);
}
- if (($isAdminOrPM || $obj->getCreatorId() == $user->getId()) && $screen == "playlist") {
- if ($obj_sess->type === "playlist") {
- $menu["pl_add"] = array("name"=> _("Add to Playlist"), "icon" => "add-playlist", "icon" => "copy");
+ if (($isAdminOrPM || $obj->getCreatorId() == $user->getId()) && $screen == 'playlist') {
+ if ($obj_sess->type === 'playlist') {
+ $menu['pl_add'] = ['name' => _('Add to Playlist'), 'icon' => 'add-playlist', 'icon' => 'copy'];
}
}
}
- if ($obj_sess->id !== $id && $screen == "playlist") {
+ if ($obj_sess->id !== $id && $screen == 'playlist') {
if ($isAdminOrPM || $obj->getCreatorId() == $user->getId()) {
- $menu["edit"] = array("name"=> _("Edit..."), "icon" => "edit");
+ $menu['edit'] = ['name' => _('Edit...'), 'icon' => 'edit'];
}
}
if ($isAdminOrPM || $obj->getCreatorId() == $user->getId()) {
- $menu["del"] = array("name"=> _("Delete"), "icon" => "delete", "url" => $baseUrl."library/delete");
+ $menu['del'] = ['name' => _('Delete'), 'icon' => 'delete', 'url' => $baseUrl . 'library/delete'];
}
- } elseif ($type == "stream") {
+ } elseif ($type == 'stream') {
$webstream = CcWebstreamQuery::create()->findPK($id);
$obj = new Application_Model_Webstream($webstream);
- $menu["play"]["mime"] = $webstream->getDbMime();
+ $menu['play']['mime'] = $webstream->getDbMime();
- if (isset($obj_sess->id) && $screen == "playlist") {
+ if (isset($obj_sess->id) && $screen == 'playlist') {
if ($isAdminOrPM || $obj->getCreatorId() == $user->getId()) {
- if ($obj_sess->type === "playlist") {
- $menu["pl_add"] = array("name"=> _("Add to Playlist"), "icon" => "add-playlist", "icon" => "copy");
+ if ($obj_sess->type === 'playlist') {
+ $menu['pl_add'] = ['name' => _('Add to Playlist'), 'icon' => 'add-playlist', 'icon' => 'copy'];
}
}
}
if ($isAdminOrPM || $obj->getCreatorId() == $user->getId()) {
- if ($screen == "playlist") {
- $menu["edit"] = array("name"=> _("Edit..."), "icon" => "edit", "url" => $baseUrl."library/edit-file-md/id/{$id}");
+ if ($screen == 'playlist') {
+ $menu['edit'] = ['name' => _('Edit...'), 'icon' => 'edit', 'url' => $baseUrl . "library/edit-file-md/id/{$id}"];
}
- $menu["del"] = array("name"=> _("Delete"), "icon" => "delete", "url" => $baseUrl."library/delete");
+ $menu['del'] = ['name' => _('Delete'), 'icon' => 'delete', 'url' => $baseUrl . 'library/delete'];
}
}
if (empty($menu)) {
- $menu["noaction"] = array("name"=>_("No action available"));
+ $menu['noaction'] = ['name' => _('No action available')];
}
$this->view->items = $menu;
@@ -193,24 +191,23 @@ class LibraryController extends Zend_Controller_Action
$user = Application_Model_User::getCurrentUser();
//$isAdminOrPM = $user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
- $files = array();
- $playlists = array();
- $blocks = array();
- $streams = array();
+ $files = [];
+ $playlists = [];
+ $blocks = [];
+ $streams = [];
$message = null;
$noPermissionMsg = _("You don't have permission to delete selected items.");
foreach ($mediaItems as $media) {
-
- if ($media["type"] === "audioclip") {
- $files[] = intval($media["id"]);
- } elseif ($media["type"] === "playlist") {
- $playlists[] = intval($media["id"]);
- } elseif ($media["type"] === "block") {
- $blocks[] = intval($media["id"]);
- } elseif ($media["type"] === "stream") {
- $streams[] = intval($media["id"]);
+ if ($media['type'] === 'audioclip') {
+ $files[] = intval($media['id']);
+ } elseif ($media['type'] === 'playlist') {
+ $playlists[] = intval($media['id']);
+ } elseif ($media['type'] === 'block') {
+ $blocks[] = intval($media['id']);
+ } elseif ($media['type'] === 'stream') {
+ $streams[] = intval($media['id']);
}
}
@@ -245,11 +242,11 @@ class LibraryController extends Zend_Controller_Action
} catch (FileNoPermissionException $e) {
$message = $noPermissionMsg;
} catch (DeleteScheduledFileException $e) {
- $message = _("Could not delete file because it is scheduled in the future.");
+ $message = _('Could not delete file because it is scheduled in the future.');
} catch (Exception $e) {
//could throw a scheduled in future exception.
- $message = _("Could not delete file(s).");
- Logging::info($message.": ".$e->getMessage());
+ $message = _('Could not delete file(s).');
+ Logging::info($message . ': ' . $e->getMessage());
}
}
}
@@ -260,7 +257,8 @@ class LibraryController extends Zend_Controller_Action
}
// duplicate playlist
- public function duplicateAction(){
+ public function duplicateAction()
+ {
$params = $this->getRequest()->getParams();
$id = $params['id'];
Logging::info($params);
@@ -272,9 +270,9 @@ class LibraryController extends Zend_Controller_Action
foreach ($contents as &$c) {
if ($c['type'] == '0') {
$c[1] = 'audioclip';
- } else if ($c['type'] == '2') {
+ } elseif ($c['type'] == '2') {
$c[1] = 'block';
- } else if ($c['type'] == '1') {
+ } elseif ($c['type'] == '1') {
$c[1] = 'stream';
}
$c[0] = $c['item_id'];
@@ -285,16 +283,17 @@ class LibraryController extends Zend_Controller_Action
$newPl->setCreator(Application_Model_User::getCurrentUser()->getId());
$newPl->setDescription($originalPl->getDescription());
- list($plFadeIn, ) = $originalPl->getFadeInfo(0);
- list(, $plFadeOut) = $originalPl->getFadeInfo($originalPl->getSize()-1);
+ list($plFadeIn) = $originalPl->getFadeInfo(0);
+ list(, $plFadeOut) = $originalPl->getFadeInfo($originalPl->getSize() - 1);
$newPl->setfades($plFadeIn, $plFadeOut);
- $newPl->setName(sprintf(_("Copy of %s"), $originalPl->getName()));
+ $newPl->setName(sprintf(_('Copy of %s'), $originalPl->getName()));
}
// duplicate smartblock
- public function duplicateBlockAction(){
- Logging::info("duplicate smartblock functionality not yet implemented");
+ public function duplicateBlockAction()
+ {
+ Logging::info('duplicate smartblock functionality not yet implemented');
$params = $this->getRequest()->getParams();
$id = $params['id'];
Logging::info($params);
@@ -305,8 +304,7 @@ class LibraryController extends Zend_Controller_Action
$newBl->setDescription($originalBl->getDescription());
if ($originalBl->isStatic()) {
$newBl->saveType('static');
- }
- else {
+ } else {
$newBl->saveType('dynamic');
}
// the issue here is that the format that getCriteria provides is different from the format the saveCriteria
@@ -324,28 +322,27 @@ class LibraryController extends Zend_Controller_Action
$row->setDbBlockId($newBl->getId());
$row->save();
}
- $newBl->setName(sprintf(_("Copy of %s"), $originalBl->getName()));
+ $newBl->setName(sprintf(_('Copy of %s'), $originalBl->getName()));
}
-
public function contentsFeedAction()
{
$params = $this->getRequest()->getParams();
- # terrible name for the method below. it does not only search files.
+ // terrible name for the method below. it does not only search files.
$r = Application_Model_StoredFile::searchLibraryFiles($params);
- $this->view->sEcho = $r["sEcho"];
- $this->view->iTotalDisplayRecords = $r["iTotalDisplayRecords"];
- $this->view->iTotalRecords = $r["iTotalRecords"];
- $this->view->files = SecurityHelper::htmlescape_recursive($r["aaData"]);
+ $this->view->sEcho = $r['sEcho'];
+ $this->view->iTotalDisplayRecords = $r['iTotalDisplayRecords'];
+ $this->view->iTotalRecords = $r['iTotalRecords'];
+ $this->view->files = SecurityHelper::htmlescape_recursive($r['aaData']);
}
public function editFileMdAction()
{
$user = Application_Model_User::getCurrentUser();
- $isAdminOrPM = $user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
- $isAdmin = $user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN));
+ $isAdminOrPM = $user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER]);
+ $isAdmin = $user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN]);
$request = $this->getRequest();
@@ -368,27 +365,26 @@ class LibraryController extends Zend_Controller_Action
}
if ($request->isPost()) {
-
$js = $this->_getParam('data');
- $serialized = array();
+ $serialized = [];
//need to convert from serialized jQuery array.
foreach ($js as $j) {
//on edit, if no artwork is set and audiofile has image, automatically add it
- if ($j["name"] == "artwork") {
- if ($j["value"] == null || $j["value"] == ''){
- $serialized["artwork"] = FileDataHelper::resetArtwork($file_id);
+ if ($j['name'] == 'artwork') {
+ if ($j['value'] == null || $j['value'] == '') {
+ $serialized['artwork'] = FileDataHelper::resetArtwork($file_id);
}
- } elseif ($j["name"] == "set_artwork") {
- if ($j["value"] != null || $j["value"] != ''){
- $serialized["artwork"] = FileDataHelper::setArtwork($file_id, $j["value"] );
+ } elseif ($j['name'] == 'set_artwork') {
+ if ($j['value'] != null || $j['value'] != '') {
+ $serialized['artwork'] = FileDataHelper::setArtwork($file_id, $j['value']);
}
- } elseif ($j["name"] == "remove_artwork") {
- if ($j["value"] == 1){
+ } elseif ($j['name'] == 'remove_artwork') {
+ if ($j['value'] == 1) {
$remove_artwork = true;
- $serialized["artwork"] = FileDataHelper::removeArtwork($file_id);
+ $serialized['artwork'] = FileDataHelper::removeArtwork($file_id);
}
} else {
- $serialized[$j["name"]] = $j["value"];
+ $serialized[$j['name']] = $j['value'];
}
}
@@ -418,7 +414,7 @@ class LibraryController extends Zend_Controller_Action
$type = $this->_getParam('type');
try {
- if ($type == "audioclip") {
+ if ($type == 'audioclip') {
$file = Application_Model_StoredFile::RecallById($id);
$this->view->type = $type;
$md = $file->getMetadata();
@@ -430,35 +426,33 @@ class LibraryController extends Zend_Controller_Action
}
}
- $formatter = new SamplerateFormatter($md["MDATA_KEY_SAMPLERATE"]);
- $md["MDATA_KEY_SAMPLERATE"] = $formatter->format();
+ $formatter = new SamplerateFormatter($md['MDATA_KEY_SAMPLERATE']);
+ $md['MDATA_KEY_SAMPLERATE'] = $formatter->format();
- $formatter = new BitrateFormatter($md["MDATA_KEY_BITRATE"]);
- $md["MDATA_KEY_BITRATE"] = $formatter->format();
+ $formatter = new BitrateFormatter($md['MDATA_KEY_BITRATE']);
+ $md['MDATA_KEY_BITRATE'] = $formatter->format();
- $formatter = new LengthFormatter($md["MDATA_KEY_DURATION"]);
- $md["MDATA_KEY_DURATION"] = $formatter->format();
+ $formatter = new LengthFormatter($md['MDATA_KEY_DURATION']);
+ $md['MDATA_KEY_DURATION'] = $formatter->format();
$this->view->md = $md;
-
- } elseif ($type == "playlist") {
-
+ } elseif ($type == 'playlist') {
$file = new Application_Model_Playlist($id);
$this->view->type = $type;
$md = $file->getAllPLMetaData();
- $formatter = new LengthFormatter($md["dcterms:extent"]);
- $md["dcterms:extent"] = $formatter->format();
+ $formatter = new LengthFormatter($md['dcterms:extent']);
+ $md['dcterms:extent'] = $formatter->format();
$this->view->md = $md;
$this->view->contents = $file->getContents();
- } elseif ($type == "block") {
+ } elseif ($type == 'block') {
$block = new Application_Model_Block($id);
$this->view->type = $type;
$md = $block->getAllPLMetaData();
- $formatter = new LengthFormatter($md["dcterms:extent"]);
- $md["dcterms:extent"] = $formatter->format();
+ $formatter = new LengthFormatter($md['dcterms:extent']);
+ $md['dcterms:extent'] = $formatter->format();
$this->view->md = $md;
if ($block->isStatic()) {
@@ -469,7 +463,7 @@ class LibraryController extends Zend_Controller_Action
$this->view->contents = $block->getCriteria();
}
$this->view->block = $block;
- } elseif ($type == "stream") {
+ } elseif ($type == 'stream') {
$webstream = CcWebstreamQuery::create()->findPK($id);
$ws = new Application_Model_Webstream($webstream);
@@ -483,7 +477,8 @@ class LibraryController extends Zend_Controller_Action
}
}
- public function publishDialogAction() {
+ public function publishDialogAction()
+ {
$this->_helper->layout->disableLayout();
//This just spits out publish-dialog.phtml!
}
diff --git a/legacy/application/controllers/ListenerstatController.php b/legacy/application/controllers/ListenerstatController.php
index 133103f2b..d904add23 100644
--- a/legacy/application/controllers/ListenerstatController.php
+++ b/legacy/application/controllers/ListenerstatController.php
@@ -6,10 +6,11 @@ class ListenerstatController extends Zend_Controller_Action
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext
- ->addActionContext('get-data', 'json')
- ->initContext();
+ ->addActionContext('get-data', 'json')
+ ->initContext()
+ ;
}
-
+
public function indexAction()
{
$CC_CONFIG = Config::getConfig();
@@ -19,14 +20,14 @@ class ListenerstatController extends Zend_Controller_Action
Zend_Layout::getMvcInstance()->assign('parent_page', 'Analytics');
- $this->view->headScript()->appendFile($baseUrl.'js/flot/jquery.flot.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/flot/jquery.flot.crosshair.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/flot/jquery.flot.resize.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/listenerstat/listenerstat.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/timepicker/jquery.ui.timepicker.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/buttons/buttons.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/utilities/utilities.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headLink()->appendStylesheet($baseUrl.'css/jquery.ui.timepicker.css?'.$CC_CONFIG['airtime_version']);
+ $this->view->headScript()->appendFile($baseUrl . 'js/flot/jquery.flot.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/flot/jquery.flot.crosshair.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/flot/jquery.flot.resize.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/listenerstat/listenerstat.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/timepicker/jquery.ui.timepicker.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/buttons/buttons.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/utilities/utilities.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/jquery.ui.timepicker.css?' . $CC_CONFIG['airtime_version']);
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($request);
$userTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
@@ -34,20 +35,20 @@ class ListenerstatController extends Zend_Controller_Action
$endsDT->setTimezone($userTimezone);
$form = new Application_Form_DateRange();
- $form->populate(array(
- 'his_date_start' => $startsDT->format("Y-m-d"),
- 'his_time_start' => $startsDT->format("H:i"),
- 'his_date_end' => $endsDT->format("Y-m-d"),
- 'his_time_end' => $endsDT->format("H:i")
- ));
+ $form->populate([
+ 'his_date_start' => $startsDT->format('Y-m-d'),
+ 'his_time_start' => $startsDT->format('H:i'),
+ 'his_date_end' => $endsDT->format('Y-m-d'),
+ 'his_time_end' => $endsDT->format('H:i'),
+ ]);
$errorStatus = Application_Model_StreamSetting::GetAllListenerStatErrors();
Logging::info($errorStatus);
- $out = array();
+ $out = [];
foreach ($errorStatus as $v) {
$key = explode('_listener_stat_error', $v['keyname']);
if ($v['value'] != 'OK') {
- $v['value'] = _("Please make sure admin user/password is correct on Settings->Streams page.");
+ $v['value'] = _('Please make sure admin user/password is correct on Settings->Streams page.');
}
$out[$key[0]] = $v['value'];
}
@@ -55,7 +56,9 @@ class ListenerstatController extends Zend_Controller_Action
$this->view->errorStatus = $out;
$this->view->date_form = $form;
}
- public function showAction() {
+
+ public function showAction()
+ {
$CC_CONFIG = Config::getConfig();
$request = $this->getRequest();
@@ -63,20 +66,18 @@ class ListenerstatController extends Zend_Controller_Action
$headScript = $this->view->headScript();
AirtimeTableView::injectTableJavaScriptDependencies($headScript, $baseUrl, $CC_CONFIG['airtime_version']);
Zend_Layout::getMvcInstance()->assign('parent_page', 'Analytics');
- $this->view->headScript()->appendFile($baseUrl.'js/timepicker/jquery.ui.timepicker.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/buttons/buttons.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/utilities/utilities.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/listenerstat/showlistenerstat.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/timepicker/jquery.ui.timepicker.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/buttons/buttons.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/utilities/utilities.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/listenerstat/showlistenerstat.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
-
-
- $this->view->headLink()->appendStylesheet($baseUrl.'css/datatables/css/ColVis.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/datatables/css/dataTables.colReorder.min.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/jquery.ui.timepicker.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/show_analytics.css'.$CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/datatables/css/ColVis.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/datatables/css/dataTables.colReorder.min.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/jquery.ui.timepicker.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/show_analytics.css' . $CC_CONFIG['airtime_version']);
$user = Application_Model_User::getCurrentUser();
- if ($user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
+ if ($user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER])) {
$this->view->showAllShows = true;
}
$data = [];
@@ -88,42 +89,56 @@ class ListenerstatController extends Zend_Controller_Action
$userTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
$startsDT->setTimezone($userTimezone);
$endsDT->setTimezone($userTimezone);
- $form->populate(array(
- 'his_date_start' => $startsDT->format("Y-m-d"),
- 'his_time_start' => $startsDT->format("H:i"),
- 'his_date_end' => $endsDT->format("Y-m-d"),
- 'his_time_end' => $endsDT->format("H:i")
- ));
+ $form->populate([
+ 'his_date_start' => $startsDT->format('Y-m-d'),
+ 'his_time_start' => $startsDT->format('H:i'),
+ 'his_date_end' => $endsDT->format('Y-m-d'),
+ 'his_time_end' => $endsDT->format('H:i'),
+ ]);
$this->view->date_form = $form;
}
- public function getDataAction(){
+ public function getDataAction()
+ {
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($this->getRequest());
- $data = Application_Model_ListenerStat::getDataPointsWithinRange($startsDT->format(DEFAULT_TIMESTAMP_FORMAT),
- $endsDT->format(DEFAULT_TIMESTAMP_FORMAT));
+ $data = Application_Model_ListenerStat::getDataPointsWithinRange(
+ $startsDT->format(DEFAULT_TIMESTAMP_FORMAT),
+ $endsDT->format(DEFAULT_TIMESTAMP_FORMAT)
+ );
$this->_helper->json->sendJson($data);
}
- public function getShowDataAction(){
+ public function getShowDataAction()
+ {
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($this->getRequest());
- $show_id = $this->getRequest()->getParam("show_id", null);
- $data = Application_Model_ListenerStat::getShowDataPointsWithinRange($startsDT->format(DEFAULT_TIMESTAMP_FORMAT),
- $endsDT->format(DEFAULT_TIMESTAMP_FORMAT),$show_id);
+ $show_id = $this->getRequest()->getParam('show_id', null);
+ $data = Application_Model_ListenerStat::getShowDataPointsWithinRange(
+ $startsDT->format(DEFAULT_TIMESTAMP_FORMAT),
+ $endsDT->format(DEFAULT_TIMESTAMP_FORMAT),
+ $show_id
+ );
$this->_helper->json->sendJson($data);
}
- public function getAllShowData(){
- list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($this->getRequest());
- $data = Application_Model_ListenerStat::getAllShowDataPointsWithinRange($startsDT->format(DEFAULT_TIMESTAMP_FORMAT),
- $endsDT->format(DEFAULT_TIMESTAMP_FORMAT));
- return $data;
+
+ public function getAllShowData()
+ {
+ list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($this->getRequest());
+
+ return Application_Model_ListenerStat::getAllShowDataPointsWithinRange(
+ $startsDT->format(DEFAULT_TIMESTAMP_FORMAT),
+ $endsDT->format(DEFAULT_TIMESTAMP_FORMAT)
+ );
}
- public function getAllShowDataAction(){
+ public function getAllShowDataAction()
+ {
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($this->getRequest());
- $show_id = $this->getRequest()->getParam("show_id", null);
- $data = Application_Model_ListenerStat::getAllShowDataPointsWithinRange($startsDT->format(DEFAULT_TIMESTAMP_FORMAT),
- $endsDT->format(DEFAULT_TIMESTAMP_FORMAT));
+ $show_id = $this->getRequest()->getParam('show_id', null);
+ $data = Application_Model_ListenerStat::getAllShowDataPointsWithinRange(
+ $startsDT->format(DEFAULT_TIMESTAMP_FORMAT),
+ $endsDT->format(DEFAULT_TIMESTAMP_FORMAT)
+ );
$this->_helper->json->sendJson($data);
}
}
diff --git a/legacy/application/controllers/LocaleController.php b/legacy/application/controllers/LocaleController.php
index fb726b586..fb8d6a46a 100644
--- a/legacy/application/controllers/LocaleController.php
+++ b/legacy/application/controllers/LocaleController.php
@@ -6,499 +6,493 @@ final class LocaleController extends Zend_Controller_Action
{
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
- header("Content-type: text/javascript");
+ header('Content-type: text/javascript');
$locale = Application_Model_Preference::GetLocale();
- echo "var datatables_dict =" .
- file_get_contents(Application_Common_OsPath::join(
+ echo 'var datatables_dict =' .
+ file_get_contents(
+ Application_Common_OsPath::join(
//$_SERVER["DOCUMENT_ROOT"],
- dirname(__FILE__) . "/../../public/", // Fixing this... -- Albert
- "js/datatables/i18n/",
- $locale.".txt")
+ dirname(__FILE__) . '/../../public/', // Fixing this... -- Albert
+ 'js/datatables/i18n/',
+ $locale . '.txt'
+ )
);
}
public function generalTranslationTableAction()
{
- $translations = array (
+ $translations = [
//common/common.js
- "Audio Player" => _("Audio Player"),
- "Something went wrong!" => _("Something went wrong!"),
+ 'Audio Player' => _('Audio Player'),
+ 'Something went wrong!' => _('Something went wrong!'),
//dashboard/dashboard.js
- "Recording:" => _("Recording:"),
- "Master Stream" => _("Master Stream"),
- "Live Stream" => _("Live Stream"),
- "Nothing Scheduled" => _("Nothing Scheduled"),
- "Current Show:" => _("Current Show:"),
- "Current" => _("Current"),
+ 'Recording:' => _('Recording:'),
+ 'Master Stream' => _('Master Stream'),
+ 'Live Stream' => _('Live Stream'),
+ 'Nothing Scheduled' => _('Nothing Scheduled'),
+ 'Current Show:' => _('Current Show:'),
+ 'Current' => _('Current'),
//dashboard/versiontooltip.js
- "You are running the latest version" => _("You are running the latest version"),
- "New version available: " => _("New version available: "),
- "You have a pre-release version of LibreTime intalled." => _("You have a pre-release version of LibreTime intalled."),
- "A patch update for your LibreTime installation is available." => _("A patch update for your LibreTime installation is available."),
- "A feature update for your LibreTime installation is available." => _("A feature update for your LibreTime installation is available."),
- "A major update for your LibreTime installation is available." => _("A major update for your LibreTime installation is available."),
- "Multiple major updates for LibreTime installation are available. Please upgrade as soon as possible." => _("Multiple major updates for LibreTime installation are available. Please upgrade as soon as possible."),
+ 'You are running the latest version' => _('You are running the latest version'),
+ 'New version available: ' => _('New version available: '),
+ 'You have a pre-release version of LibreTime intalled.' => _('You have a pre-release version of LibreTime intalled.'),
+ 'A patch update for your LibreTime installation is available.' => _('A patch update for your LibreTime installation is available.'),
+ 'A feature update for your LibreTime installation is available.' => _('A feature update for your LibreTime installation is available.'),
+ 'A major update for your LibreTime installation is available.' => _('A major update for your LibreTime installation is available.'),
+ 'Multiple major updates for LibreTime installation are available. Please upgrade as soon as possible.' => _('Multiple major updates for LibreTime installation are available. Please upgrade as soon as possible.'),
//library/events/library_playlistbuilder.js
- "Add to current playlist" => _("Add to current playlist"),
- "Add to current smart block" => _("Add to current smart block"),
- "Adding 1 Item" => _("Adding 1 Item"),
- "Adding %s Items" => _("Adding %s Items"),
- "You can only add tracks to smart blocks." => _("You can only add tracks to smart blocks."),
- "You can only add tracks, smart blocks, and webstreams to playlists." => _("You can only add tracks, smart blocks, and webstreams to playlists."),
+ 'Add to current playlist' => _('Add to current playlist'),
+ 'Add to current smart block' => _('Add to current smart block'),
+ 'Adding 1 Item' => _('Adding 1 Item'),
+ 'Adding %s Items' => _('Adding %s Items'),
+ 'You can only add tracks to smart blocks.' => _('You can only add tracks to smart blocks.'),
+ 'You can only add tracks, smart blocks, and webstreams to playlists.' => _('You can only add tracks, smart blocks, and webstreams to playlists.'),
//library/events/library_showbuilder.js
//already in library/events/library_playlistbuilder.js
- "Please select a cursor position on timeline." => _("Please select a cursor position on timeline."),
+ 'Please select a cursor position on timeline.' => _('Please select a cursor position on timeline.'),
"You haven't added any tracks" => _("You haven't added any tracks"),
"You haven't added any playlists" => _("You haven't added any playlists"),
"You haven't added any podcasts" => _("You haven't added any podcasts"),
"You haven't added any smart blocks" => _("You haven't added any smart blocks"),
"You haven't added any webstreams" => _("You haven't added any webstreams"),
- "Learn about tracks" => _("Learn about tracks"),
- "Learn about playlists" => _("Learn about playlists"),
- "Learn about podcasts" => _("Learn about podcasts"),
- "Learn about smart blocks" => _("Learn about smart blocks"),
- "Learn about webstreams" => _("Learn about webstreams"),
+ 'Learn about tracks' => _('Learn about tracks'),
+ 'Learn about playlists' => _('Learn about playlists'),
+ 'Learn about podcasts' => _('Learn about podcasts'),
+ 'Learn about smart blocks' => _('Learn about smart blocks'),
+ 'Learn about webstreams' => _('Learn about webstreams'),
"Click 'New' to create one." => _("Click 'New' to create one."),
//"Adding 1 Item" => _("Adding 1 Item"),
//"Adding %s Items" => _("Adding %s Items"),
//library/library.js
- "Add" => _("Add"),
- "New" => _("New"),
- "Edit" => _("Edit"),
- "Add to Schedule" => _("Add to Schedule"),
- "Add to next show" => _("Add to next show"),
- "Add to current show" => _("Add to current show"),
- "Add after selected items" => _("Add after selected items"),
- "Delete" => _("Delete"),
- "Publish" => _("Publish"),
- "Remove" => _("Remove"),
- "Edit Metadata" => _("Edit Metadata"),
- "Add to selected show" => _("Add to selected show"),
- "Select" => _("Select"),
- "Select this page" => _("Select this page"),
- "Deselect this page" => _("Deselect this page"),
- "Deselect all" => _("Deselect all"),
- "Are you sure you want to delete the selected item(s)?" => _("Are you sure you want to delete the selected item(s)?"),
- "Scheduled" => _("Scheduled"),
- "Tracks" => _("Tracks"),
- "Playlist" => _("Playlist"),
- "Title" => _("Title"),
- "Creator" => _("Creator"),
- "Album" => _("Album"),
- "Bit Rate" => _("Bit Rate"),
- "BPM" => _("BPM"),
- "Composer" => _("Composer"),
- "Conductor" => _("Conductor"),
- "Copyright" => _("Copyright"),
- "Encoded By" => _("Encoded By"),
- "Genre" => _("Genre"),
- "ISRC" => _("ISRC"),
- "Label" => _("Label"),
- "Language" => _("Language"),
- "Last Modified" => _("Last Modified"),
- "Last Played" => _("Last Played"),
- "Length" => _("Length"),
- "Mime" => _("Mime"),
- "Mood" => _("Mood"),
- "Owner" => _("Owner"),
- "Replay Gain" => _("Replay Gain"),
- "Sample Rate" => _("Sample Rate"),
- "Track Number" => _("Track Number"),
- "Uploaded" => _("Uploaded"),
- "Website" => _("Website"),
- "Year" => _("Year"),
- "Loading..." => _("Loading..."),
- "All" => _("All"),
- "Files" => _("Files"),
- "Playlists" => _("Playlists"),
- "Smart Blocks" => _("Smart Blocks"),
- "Web Streams" => _("Web Streams"),
- "Unknown type: " => _("Unknown type: "),
- "Are you sure you want to delete the selected item?" => _("Are you sure you want to delete the selected item?"),
- "Uploading in progress..." => _("Uploading in progress..."),
- "Retrieving data from the server..." => _("Retrieving data from the server..."),
+ 'Add' => _('Add'),
+ 'New' => _('New'),
+ 'Edit' => _('Edit'),
+ 'Add to Schedule' => _('Add to Schedule'),
+ 'Add to next show' => _('Add to next show'),
+ 'Add to current show' => _('Add to current show'),
+ 'Add after selected items' => _('Add after selected items'),
+ 'Delete' => _('Delete'),
+ 'Publish' => _('Publish'),
+ 'Remove' => _('Remove'),
+ 'Edit Metadata' => _('Edit Metadata'),
+ 'Add to selected show' => _('Add to selected show'),
+ 'Select' => _('Select'),
+ 'Select this page' => _('Select this page'),
+ 'Deselect this page' => _('Deselect this page'),
+ 'Deselect all' => _('Deselect all'),
+ 'Are you sure you want to delete the selected item(s)?' => _('Are you sure you want to delete the selected item(s)?'),
+ 'Scheduled' => _('Scheduled'),
+ 'Tracks' => _('Tracks'),
+ 'Playlist' => _('Playlist'),
+ 'Title' => _('Title'),
+ 'Creator' => _('Creator'),
+ 'Album' => _('Album'),
+ 'Bit Rate' => _('Bit Rate'),
+ 'BPM' => _('BPM'),
+ 'Composer' => _('Composer'),
+ 'Conductor' => _('Conductor'),
+ 'Copyright' => _('Copyright'),
+ 'Encoded By' => _('Encoded By'),
+ 'Genre' => _('Genre'),
+ 'ISRC' => _('ISRC'),
+ 'Label' => _('Label'),
+ 'Language' => _('Language'),
+ 'Last Modified' => _('Last Modified'),
+ 'Last Played' => _('Last Played'),
+ 'Length' => _('Length'),
+ 'Mime' => _('Mime'),
+ 'Mood' => _('Mood'),
+ 'Owner' => _('Owner'),
+ 'Replay Gain' => _('Replay Gain'),
+ 'Sample Rate' => _('Sample Rate'),
+ 'Track Number' => _('Track Number'),
+ 'Uploaded' => _('Uploaded'),
+ 'Website' => _('Website'),
+ 'Year' => _('Year'),
+ 'Loading...' => _('Loading...'),
+ 'All' => _('All'),
+ 'Files' => _('Files'),
+ 'Playlists' => _('Playlists'),
+ 'Smart Blocks' => _('Smart Blocks'),
+ 'Web Streams' => _('Web Streams'),
+ 'Unknown type: ' => _('Unknown type: '),
+ 'Are you sure you want to delete the selected item?' => _('Are you sure you want to delete the selected item?'),
+ 'Uploading in progress...' => _('Uploading in progress...'),
+ 'Retrieving data from the server...' => _('Retrieving data from the server...'),
//library/podcast.js
- "Import" => _("Import"),
- "Imported?" => _("Imported?"),
- "View" => _("View"),
- "Error code: " => _("Error code: "),
- "Error msg: " => _("Error msg: "),
- "Input must be a positive number" => _("Input must be a positive number"),
- "Input must be a number" => _("Input must be a number"),
- "Input must be in the format: yyyy-mm-dd" => _("Input must be in the format: yyyy-mm-dd"),
- "Input must be in the format: hh:mm:ss.t" => _("Input must be in the format: hh:mm:ss.t"),
- "My Podcast" => _("My Podcast"),
+ 'Import' => _('Import'),
+ 'Imported?' => _('Imported?'),
+ 'View' => _('View'),
+ 'Error code: ' => _('Error code: '),
+ 'Error msg: ' => _('Error msg: '),
+ 'Input must be a positive number' => _('Input must be a positive number'),
+ 'Input must be a number' => _('Input must be a number'),
+ 'Input must be in the format: yyyy-mm-dd' => _('Input must be in the format: yyyy-mm-dd'),
+ 'Input must be in the format: hh:mm:ss.t' => _('Input must be in the format: hh:mm:ss.t'),
+ 'My Podcast' => _('My Podcast'),
//library/plupload.js
- "You are currently uploading files. %sGoing to another screen will cancel the upload process. %sAre you sure you want to leave the page?"
- => _("You are currently uploading files. %sGoing to another screen will cancel the upload process. %sAre you sure you want to leave the page?"),
+ 'You are currently uploading files. %sGoing to another screen will cancel the upload process. %sAre you sure you want to leave the page?' => _('You are currently uploading files. %sGoing to another screen will cancel the upload process. %sAre you sure you want to leave the page?'),
//library/spl.js
- "Open Media Builder" => _("Open Media Builder"),
+ 'Open Media Builder' => _('Open Media Builder'),
"please put in a time '00:00:00 (.0)'" => _("please put in a time '00:00:00 (.0)'"),
- "Please enter a valid time in seconds. Eg. 0.5'" => _("Please enter a valid time in seconds. Eg. 0.5"),
- "Your browser does not support playing this file type: " => _("Your browser does not support playing this file type: "),
- "Dynamic block is not previewable" => _("Dynamic block is not previewable"),
- "Limit to: " => _("Limit to: "),
- "Playlist saved" => _("Playlist saved"),
- "Playlist shuffled" => _("Playlist shuffled"),
- "Airtime is unsure about the status of this file. This can happen when the file is on a remote drive that is unaccessible or the file is in a directory that isn't 'watched' anymore."
- => _("Airtime is unsure about the status of this file. This can happen when the file is on a remote drive that is unaccessible or the file is in a directory that isn't 'watched' anymore."),
+ "Please enter a valid time in seconds. Eg. 0.5'" => _('Please enter a valid time in seconds. Eg. 0.5'),
+ 'Your browser does not support playing this file type: ' => _('Your browser does not support playing this file type: '),
+ 'Dynamic block is not previewable' => _('Dynamic block is not previewable'),
+ 'Limit to: ' => _('Limit to: '),
+ 'Playlist saved' => _('Playlist saved'),
+ 'Playlist shuffled' => _('Playlist shuffled'),
+ "Airtime is unsure about the status of this file. This can happen when the file is on a remote drive that is unaccessible or the file is in a directory that isn't 'watched' anymore." => _("Airtime is unsure about the status of this file. This can happen when the file is on a remote drive that is unaccessible or the file is in a directory that isn't 'watched' anymore."),
//listenerstat/listenerstat.js
- "Listener Count on %s: %s" => _("Listener Count on %s: %s"),
+ 'Listener Count on %s: %s' => _('Listener Count on %s: %s'),
//nowplaying/register.js
- "Remind me in 1 week" => _("Remind me in 1 week"),
- "Remind me never" => _("Remind me never"),
- "Yes, help Airtime" => _("Yes, help Airtime"),
- "Image must be one of jpg, jpeg, png, or gif" => _("Image must be one of jpg, jpeg, png, or gif"),
+ 'Remind me in 1 week' => _('Remind me in 1 week'),
+ 'Remind me never' => _('Remind me never'),
+ 'Yes, help Airtime' => _('Yes, help Airtime'),
+ 'Image must be one of jpg, jpeg, png, or gif' => _('Image must be one of jpg, jpeg, png, or gif'),
//playlist/smart_blockbuilder.js
- "A static smart block will save the criteria and generate the block content immediately. This allows you to edit and view it in the Library before adding it to a show."
- => _("A static smart block will save the criteria and generate the block content immediately. This allows you to edit and view it in the Library before adding it to a show."),
- "A dynamic smart block will only save the criteria. The block content will get generated upon adding it to a show. You will not be able to view and edit the content in the Library."
- => _("A dynamic smart block will only save the criteria. The block content will get generated upon adding it to a show. You will not be able to view and edit the content in the Library."),
- "The desired block length will not be reached if %s cannot find enough unique tracks to match your criteria. Enable this option if you wish to allow tracks to be added multiple times to the smart block."
- => _("The desired block length will not be reached if %s cannot find enough unique tracks to match your criteria. Enable this option if you wish to allow tracks to be added multiple times to the smart block."),
- "Smart block shuffled" => _("Smart block shuffled"),
- "Smart block generated and criteria saved" => _("Smart block generated and criteria saved"),
- "Smart block saved" => _("Smart block saved"),
- "Processing..." => _("Processing..."),
- "Select modifier" => _("Select modifier"),
- "contains" => _("contains"),
- "does not contain" => _("does not contain"),
- "is" => _("is"),
- "is not" => _("is not"),
- "starts with" => _("starts with"),
- "ends with" => _("ends with"),
- "is greater than" => _("is greater than"),
- "is less than" => _("is less than"),
- "is in the range" => _("is in the range"),
- "Preview" => _("Preview"),
- "Generate" => _("Generate"),
- //preferences/musicdirs.js
- "Choose Storage Folder" => _("Choose Storage Folder"),
- "Choose Folder to Watch" => _("Choose Folder to Watch"),
- "Are you sure you want to change the storage folder?\nThis will remove the files from your Airtime library!"
- => _("Are you sure you want to change the storage folder?\nThis will remove the files from your Airtime library!"),
- "Manage Media Folders" => _("Manage Media Folders"),
- "Are you sure you want to remove the watched folder?" => _("Are you sure you want to remove the watched folder?"),
- "This path is currently not accessible." => _("This path is currently not accessible."),
+ 'A static smart block will save the criteria and generate the block content immediately. This allows you to edit and view it in the Library before adding it to a show.' => _('A static smart block will save the criteria and generate the block content immediately. This allows you to edit and view it in the Library before adding it to a show.'),
+ 'A dynamic smart block will only save the criteria. The block content will get generated upon adding it to a show. You will not be able to view and edit the content in the Library.' => _('A dynamic smart block will only save the criteria. The block content will get generated upon adding it to a show. You will not be able to view and edit the content in the Library.'),
+ 'The desired block length will not be reached if %s cannot find enough unique tracks to match your criteria. Enable this option if you wish to allow tracks to be added multiple times to the smart block.' => _('The desired block length will not be reached if %s cannot find enough unique tracks to match your criteria. Enable this option if you wish to allow tracks to be added multiple times to the smart block.'),
+ 'Smart block shuffled' => _('Smart block shuffled'),
+ 'Smart block generated and criteria saved' => _('Smart block generated and criteria saved'),
+ 'Smart block saved' => _('Smart block saved'),
+ 'Processing...' => _('Processing...'),
+ 'Select modifier' => _('Select modifier'),
+ 'contains' => _('contains'),
+ 'does not contain' => _('does not contain'),
+ 'is' => _('is'),
+ 'is not' => _('is not'),
+ 'starts with' => _('starts with'),
+ 'ends with' => _('ends with'),
+ 'is greater than' => _('is greater than'),
+ 'is less than' => _('is less than'),
+ 'is in the range' => _('is in the range'),
+ 'Preview' => _('Preview'),
+ 'Generate' => _('Generate'),
+ //preferences/musicdirs.js
+ 'Choose Storage Folder' => _('Choose Storage Folder'),
+ 'Choose Folder to Watch' => _('Choose Folder to Watch'),
+ "Are you sure you want to change the storage folder?\nThis will remove the files from your Airtime library!" => _("Are you sure you want to change the storage folder?\nThis will remove the files from your Airtime library!"),
+ 'Manage Media Folders' => _('Manage Media Folders'),
+ 'Are you sure you want to remove the watched folder?' => _('Are you sure you want to remove the watched folder?'),
+ 'This path is currently not accessible.' => _('This path is currently not accessible.'),
//preferences/streamsetting.js
- "Some stream types require extra configuration. Details about enabling %sAAC+ Support%s or %sOpus Support%s are provided." => _("Some stream types require extra configuration. Details about enabling %sAAC+ Support%s or %sOpus Support%s are provided."),
- "Connected to the streaming server" => _("Connected to the streaming server"),
- "The stream is disabled" => _("The stream is disabled"),
- "Getting information from the server..." => _("Getting information from the server..."),
- "Can not connect to the streaming server" => _("Can not connect to the streaming server"),
- "If %s is behind a router or firewall, you may need to configure port forwarding and this field information will be incorrect. In this case you will need to manually update this field so it shows the correct host/port/mount that your DJ's need to connect to. The allowed range is between 1024 and 49151."
- => _("If %s is behind a router or firewall, you may need to configure port forwarding and this field information will be incorrect. In this case you will need to manually update this field so it shows the correct host/port/mount that your DJ's need to connect to. The allowed range is between 1024 and 49151."),
- "For more details, please read the %s%s Manual%s" => _("For more details, please read the %s%s Manual%s"),
- "Check this option to enable metadata for OGG streams (stream metadata is the track title, artist, and show name that is displayed in an audio player). VLC and mplayer have a serious bug when playing an OGG/VORBIS stream that has metadata information enabled: they will disconnect from the stream after every song. If you are using an OGG stream and your listeners do not require support for these audio players, then feel free to enable this option."
- => _("Check this option to enable metadata for OGG streams (stream metadata is the track title, artist, and show name that is displayed in an audio player). VLC and mplayer have a serious bug when playing an OGG/VORBIS stream that has metadata information enabled: they will disconnect from the stream after every song. If you are using an OGG stream and your listeners do not require support for these audio players, then feel free to enable this option."),
- "Check this box to automatically switch off Master/Show source upon source disconnection." => _("Check this box to automatically switch off Master/Show source upon source disconnection."),
- "Check this box to automatically switch on Master/Show source upon source connection." => _("Check this box to automatically switch on Master/Show source upon source connection."),
+ 'Some stream types require extra configuration. Details about enabling %sAAC+ Support%s or %sOpus Support%s are provided.' => _('Some stream types require extra configuration. Details about enabling %sAAC+ Support%s or %sOpus Support%s are provided.'),
+ 'Connected to the streaming server' => _('Connected to the streaming server'),
+ 'The stream is disabled' => _('The stream is disabled'),
+ 'Getting information from the server...' => _('Getting information from the server...'),
+ 'Can not connect to the streaming server' => _('Can not connect to the streaming server'),
+ "If %s is behind a router or firewall, you may need to configure port forwarding and this field information will be incorrect. In this case you will need to manually update this field so it shows the correct host/port/mount that your DJ's need to connect to. The allowed range is between 1024 and 49151." => _("If %s is behind a router or firewall, you may need to configure port forwarding and this field information will be incorrect. In this case you will need to manually update this field so it shows the correct host/port/mount that your DJ's need to connect to. The allowed range is between 1024 and 49151."),
+ 'For more details, please read the %s%s Manual%s' => _('For more details, please read the %s%s Manual%s'),
+ 'Check this option to enable metadata for OGG streams (stream metadata is the track title, artist, and show name that is displayed in an audio player). VLC and mplayer have a serious bug when playing an OGG/VORBIS stream that has metadata information enabled: they will disconnect from the stream after every song. If you are using an OGG stream and your listeners do not require support for these audio players, then feel free to enable this option.' => _('Check this option to enable metadata for OGG streams (stream metadata is the track title, artist, and show name that is displayed in an audio player). VLC and mplayer have a serious bug when playing an OGG/VORBIS stream that has metadata information enabled: they will disconnect from the stream after every song. If you are using an OGG stream and your listeners do not require support for these audio players, then feel free to enable this option.'),
+ 'Check this box to automatically switch off Master/Show source upon source disconnection.' => _('Check this box to automatically switch off Master/Show source upon source disconnection.'),
+ 'Check this box to automatically switch on Master/Show source upon source connection.' => _('Check this box to automatically switch on Master/Show source upon source connection.'),
"If your Icecast server expects a username of 'source', this field can be left blank." => _("If your Icecast server expects a username of 'source', this field can be left blank."),
"If your live streaming client does not ask for a username, this field should be 'source'." => _("If your live streaming client does not ask for a username, this field should be 'source'."),
- "WARNING: This will restart your stream and may cause a short dropout for your listeners!" => _("WARNING: This will restart your stream and may cause a short dropout for your listeners!"),
- "This is the admin username and password for Icecast/SHOUTcast to get listener statistics." => _("This is the admin username and password for Icecast/SHOUTcast to get listener statistics."),
+ 'WARNING: This will restart your stream and may cause a short dropout for your listeners!' => _('WARNING: This will restart your stream and may cause a short dropout for your listeners!'),
+ 'This is the admin username and password for Icecast/SHOUTcast to get listener statistics.' => _('This is the admin username and password for Icecast/SHOUTcast to get listener statistics.'),
//preferences/support-setting.js
- "Image must be one of jpg, jpeg, png, or gif" => _("Image must be one of jpg, jpeg, png, or gif"),
+ 'Image must be one of jpg, jpeg, png, or gif' => _('Image must be one of jpg, jpeg, png, or gif'),
//schedule/add-show.js
- "Warning: You cannot change this field while the show is currently playing" => _("Warning: You cannot change this field while the show is currently playing"),
- "No result found" => _("No result found"),
- "This follows the same security pattern for the shows: only users assigned to the show can connect." => _("This follows the same security pattern for the shows: only users assigned to the show can connect."),
- "Specify custom authentication which will work only for this show." => _("Specify custom authentication which will work only for this show."),
+ 'Warning: You cannot change this field while the show is currently playing' => _('Warning: You cannot change this field while the show is currently playing'),
+ 'No result found' => _('No result found'),
+ 'This follows the same security pattern for the shows: only users assigned to the show can connect.' => _('This follows the same security pattern for the shows: only users assigned to the show can connect.'),
+ 'Specify custom authentication which will work only for this show.' => _('Specify custom authentication which will work only for this show.'),
"If your live streaming client does not ask for a username, this field should be 'source'." => _("If your live streaming client does not ask for a username, this field should be 'source'."),
"The show instance doesn't exist anymore!" => _("The show instance doesn't exist anymore!"),
- "Warning: Shows cannot be re-linked" => _("Warning: Shows cannot be re-linked"),
- "By linking your repeating shows any media items scheduled in any repeat show will also get scheduled in the other repeat shows" => _("By linking your repeating shows any media items scheduled in any repeat show will also get scheduled in the other repeat shows"),
- "Timezone is set to the station timezone by default. Shows in the calendar will be displayed in your local time defined by the Interface Timezone in your user settings." => _("Timezone is set to the station timezone by default. Shows in the calendar will be displayed in your local time defined by the Interface Timezone in your user settings."),
+ 'Warning: Shows cannot be re-linked' => _('Warning: Shows cannot be re-linked'),
+ 'By linking your repeating shows any media items scheduled in any repeat show will also get scheduled in the other repeat shows' => _('By linking your repeating shows any media items scheduled in any repeat show will also get scheduled in the other repeat shows'),
+ 'Timezone is set to the station timezone by default. Shows in the calendar will be displayed in your local time defined by the Interface Timezone in your user settings.' => _('Timezone is set to the station timezone by default. Shows in the calendar will be displayed in your local time defined by the Interface Timezone in your user settings.'),
//schedule/full-calendar-functions
//already in schedule/add-show.js
//"The show instance doesn't exist anymore!" => _("The show instance doesn't exist anymore!"),
- "Show" => _("Show"),
- "Show is empty" => _("Show is empty"),
- "1m" => _("1m"),
- "5m" => _("5m"),
- "10m" => _("10m"),
- "15m" => _("15m"),
- "30m" => _("30m"),
- "60m" => _("60m"),
- "Uploading in progress..." => _("Uploading in progress..."),
- "Retreiving data from the server..." => _("Retreiving data from the server..."),
- "This show has no scheduled content." => _("This show has no scheduled content."),
- "This show is not completely filled with content." => _("This show is not completely filled with content."),
+ 'Show' => _('Show'),
+ 'Show is empty' => _('Show is empty'),
+ '1m' => _('1m'),
+ '5m' => _('5m'),
+ '10m' => _('10m'),
+ '15m' => _('15m'),
+ '30m' => _('30m'),
+ '60m' => _('60m'),
+ 'Uploading in progress...' => _('Uploading in progress...'),
+ 'Retreiving data from the server...' => _('Retreiving data from the server...'),
+ 'This show has no scheduled content.' => _('This show has no scheduled content.'),
+ 'This show is not completely filled with content.' => _('This show is not completely filled with content.'),
//already in schedule/add-show.js
//"The show instance doesn"t exist anymore!" => _("The show instance doesn"t exist anymore!"),
//schedule/schedule.js
- "January" => _("January"),
- "February" => _("February"),
- "March" => _("March"),
- "April" => _("April"),
- "May" => _("May"),
- "June" => _("June"),
- "July" => _("July"),
- "August" => _("August"),
- "September" => _("September"),
- "October" => _("October"),
- "November" => _("November"),
- "December" => _("December"),
- "Jan" => _("Jan"),
- "Feb" => _("Feb"),
- "Mar" => _("Mar"),
- "Apr" => _("Apr"),
- "May" => _("May"),
- "Jun" => _("Jun"),
- "Jul" => _("Jul"),
- "Aug" => _("Aug"),
- "Sep" => _("Sep"),
- "Oct" => _("Oct"),
- "Nov" => _("Nov"),
- "Dec" => _("Dec"),
- "Today" => _("Today"),
- "Day" => _("Day"),
- "Week" => _("Week"),
- "Month" => _("Month"),
- "Sunday" => _("Sunday"),
- "Monday" => _("Monday"),
- "Tuesday" => _("Tuesday"),
- "Wednesday" => _("Wednesday"),
- "Thursday" => _("Thursday"),
- "Friday" => _("Friday"),
- "Saturday" => _("Saturday"),
- "Sun" => _("Sun"),
- "Mon" => _("Mon"),
- "Tue" => _("Tue"),
- "Wed" => _("Wed"),
- "Thu" => _("Thu"),
- "Fri" => _("Fri"),
- "Sat" => _("Sat"),
- "Shows longer than their scheduled time will be cut off by a following show." => _("Shows longer than their scheduled time will be cut off by a following show."),
- "Cancel Current Show?" => _("Cancel Current Show?"),
- "Stop recording current show?" => _("Stop recording current show?"),
- "Ok" => _("Ok"),
- "Contents of Show" => _("Contents of Show"),
+ 'January' => _('January'),
+ 'February' => _('February'),
+ 'March' => _('March'),
+ 'April' => _('April'),
+ 'May' => _('May'),
+ 'June' => _('June'),
+ 'July' => _('July'),
+ 'August' => _('August'),
+ 'September' => _('September'),
+ 'October' => _('October'),
+ 'November' => _('November'),
+ 'December' => _('December'),
+ 'Jan' => _('Jan'),
+ 'Feb' => _('Feb'),
+ 'Mar' => _('Mar'),
+ 'Apr' => _('Apr'),
+ 'May' => _('May'),
+ 'Jun' => _('Jun'),
+ 'Jul' => _('Jul'),
+ 'Aug' => _('Aug'),
+ 'Sep' => _('Sep'),
+ 'Oct' => _('Oct'),
+ 'Nov' => _('Nov'),
+ 'Dec' => _('Dec'),
+ 'Today' => _('Today'),
+ 'Day' => _('Day'),
+ 'Week' => _('Week'),
+ 'Month' => _('Month'),
+ 'Sunday' => _('Sunday'),
+ 'Monday' => _('Monday'),
+ 'Tuesday' => _('Tuesday'),
+ 'Wednesday' => _('Wednesday'),
+ 'Thursday' => _('Thursday'),
+ 'Friday' => _('Friday'),
+ 'Saturday' => _('Saturday'),
+ 'Sun' => _('Sun'),
+ 'Mon' => _('Mon'),
+ 'Tue' => _('Tue'),
+ 'Wed' => _('Wed'),
+ 'Thu' => _('Thu'),
+ 'Fri' => _('Fri'),
+ 'Sat' => _('Sat'),
+ 'Shows longer than their scheduled time will be cut off by a following show.' => _('Shows longer than their scheduled time will be cut off by a following show.'),
+ 'Cancel Current Show?' => _('Cancel Current Show?'),
+ 'Stop recording current show?' => _('Stop recording current show?'),
+ 'Ok' => _('Ok'),
+ 'Contents of Show' => _('Contents of Show'),
//already in schedule/add-show.js
//"The show instance doesn"t exist anymore!" => _("The show instance doesn"t exist anymore!"),
- "Remove all content?" => _("Remove all content?"),
+ 'Remove all content?' => _('Remove all content?'),
//showbuilder/builder.js
- "Delete selected item(s)?" => _("Delete selected item(s)?"),
- "Start" => _("Start"),
- "End" => _("End"),
- "Duration" => _("Duration"),
- "Filtering out " => _("Filtering out "),
- " of " => _(" of "),
- " records" => _(" records"),
- "There are no shows scheduled during the specified time period." => _("There are no shows scheduled during the specified time period."),
+ 'Delete selected item(s)?' => _('Delete selected item(s)?'),
+ 'Start' => _('Start'),
+ 'End' => _('End'),
+ 'Duration' => _('Duration'),
+ 'Filtering out ' => _('Filtering out '),
+ ' of ' => _(' of '),
+ ' records' => _(' records'),
+ 'There are no shows scheduled during the specified time period.' => _('There are no shows scheduled during the specified time period.'),
//already in library/library.js
//"Title" => _("Title"),
//"Creator" => _("Creator"),
//"Album" => _("Album"),
//"Mime" => _("Mime"),
- "Cue In" => _("Cue In"),
- "Cue Out" => _("Cue Out"),
- "Fade In" => _("Fade In"),
- "Fade Out" => _("Fade Out"),
- "Show Empty" => _("Show Empty"),
- "Recording From Line In" => _("Recording From Line In"),
- "Track preview" => _("Track preview"),
+ 'Cue In' => _('Cue In'),
+ 'Cue Out' => _('Cue Out'),
+ 'Fade In' => _('Fade In'),
+ 'Fade Out' => _('Fade Out'),
+ 'Show Empty' => _('Show Empty'),
+ 'Recording From Line In' => _('Recording From Line In'),
+ 'Track preview' => _('Track preview'),
//already in library/spl.js
//"Airtime is unsure about the status of this file. This can happen when the file is on a remote drive that is unaccessible or the file is in a directory that isn"t "watched" anymore."
- //=> _("Airtime is unsure about the status of this file. This can happen when the file is on a remote drive that is unaccessible or the file is in a directory that isn"t "watched" anymore."),
- "Cannot schedule outside a show." => _("Cannot schedule outside a show."),
- "Moving 1 Item" => _("Moving 1 Item"),
- "Moving %s Items" => _("Moving %s Items"),
- "Save" => _("Save"),
- "Cancel" => _("Cancel"),
- "Fade Editor" => _("Fade Editor"),
- "Cue Editor" => _("Cue Editor"),
- "Waveform features are available in a browser supporting the Web Audio API" => _("Waveform features are available in a browser supporting the Web Audio API"),
+ //=> _("Airtime is unsure about the status of this file. This can happen when the file is on a remote drive that is unaccessible or the file is in a directory that isn"t "watched" anymore."),
+ 'Cannot schedule outside a show.' => _('Cannot schedule outside a show.'),
+ 'Moving 1 Item' => _('Moving 1 Item'),
+ 'Moving %s Items' => _('Moving %s Items'),
+ 'Save' => _('Save'),
+ 'Cancel' => _('Cancel'),
+ 'Fade Editor' => _('Fade Editor'),
+ 'Cue Editor' => _('Cue Editor'),
+ 'Waveform features are available in a browser supporting the Web Audio API' => _('Waveform features are available in a browser supporting the Web Audio API'),
//already in library/library.js
//"Select" => _("Select"),
- "Select all" => _("Select all"),
- "Select none" => _("Select none"),
- "Trim overbooked shows" => _("Trim overbooked shows"),
- "Remove selected scheduled items" => _("Remove selected scheduled items"),
- "Jump to the current playing track" => _("Jump to the current playing track"),
- "Jump to Current" => _("Jump to Current"),
- "Cancel current show" => _("Cancel current show"),
+ 'Select all' => _('Select all'),
+ 'Select none' => _('Select none'),
+ 'Trim overbooked shows' => _('Trim overbooked shows'),
+ 'Remove selected scheduled items' => _('Remove selected scheduled items'),
+ 'Jump to the current playing track' => _('Jump to the current playing track'),
+ 'Jump to Current' => _('Jump to Current'),
+ 'Cancel current show' => _('Cancel current show'),
//already in schedule/schedule.js
//"Cancel Current Show?" => _("Cancel Current Show?"),
- "Stop recording current show?" => _("Stop recording current show?"),
+ 'Stop recording current show?' => _('Stop recording current show?'),
//showbuilder/main_builder.js
- "Open library to add or remove content" => _("Open library to add or remove content"),
- "Add / Remove Content" => _("Add / Remove Content"),
+ 'Open library to add or remove content' => _('Open library to add or remove content'),
+ 'Add / Remove Content' => _('Add / Remove Content'),
//status/status.js
- "in use" => _("in use"),
- "Disk" => _("Disk"),
+ 'in use' => _('in use'),
+ 'Disk' => _('Disk'),
//serverbrowse/serverbrowse.js
- "Look in" => _("Look in"),
- "Cancel" => _("Cancel"),
- "Open" => _("Open"),
+ 'Look in' => _('Look in'),
+ 'Cancel' => _('Cancel'),
+ 'Open' => _('Open'),
//user/user.js
- "Admin" => _("Admin"),
- "DJ" => _("DJ"),
- "Program Manager" => _("Program Manager"),
- "Guest" => _("Guest"),
- "Guests can do the following:" => _("Guests can do the following:"),
- "View schedule" => _("View schedule"),
- "View show content" => _("View show content"),
- "DJs can do the following:" => _("DJs can do the following:"),
- "Manage assigned show content" => _("Manage assigned show content"),
- "Import media files" => _("Import media files"),
- "Create playlists, smart blocks, and webstreams" => _("Create playlists, smart blocks, and webstreams"),
- "Manage their own library content" => _("Manage their own library content"),
- "Program Managers can do the following:" => _("Program Managers can do the following:"),
- "View and manage show content" => _("View and manage show content"),
- "Schedule shows" => _("Schedule shows"),
- "Manage all library content" => _("Manage all library content"),
- "Admins can do the following:" => _("Admins can do the following:"),
- "Manage preferences" => _("Manage preferences"),
- "Manage users" => _("Manage users"),
- "Manage watched folders" => _("Manage watched folders"),
- "Send support feedback" => _("Send support feedback"),
- "View system status" => _("View system status"),
- "Access playout history" => _("Access playout history"),
- "View listener stats" => _("View listener stats"),
+ 'Admin' => _('Admin'),
+ 'DJ' => _('DJ'),
+ 'Program Manager' => _('Program Manager'),
+ 'Guest' => _('Guest'),
+ 'Guests can do the following:' => _('Guests can do the following:'),
+ 'View schedule' => _('View schedule'),
+ 'View show content' => _('View show content'),
+ 'DJs can do the following:' => _('DJs can do the following:'),
+ 'Manage assigned show content' => _('Manage assigned show content'),
+ 'Import media files' => _('Import media files'),
+ 'Create playlists, smart blocks, and webstreams' => _('Create playlists, smart blocks, and webstreams'),
+ 'Manage their own library content' => _('Manage their own library content'),
+ 'Program Managers can do the following:' => _('Program Managers can do the following:'),
+ 'View and manage show content' => _('View and manage show content'),
+ 'Schedule shows' => _('Schedule shows'),
+ 'Manage all library content' => _('Manage all library content'),
+ 'Admins can do the following:' => _('Admins can do the following:'),
+ 'Manage preferences' => _('Manage preferences'),
+ 'Manage users' => _('Manage users'),
+ 'Manage watched folders' => _('Manage watched folders'),
+ 'Send support feedback' => _('Send support feedback'),
+ 'View system status' => _('View system status'),
+ 'Access playout history' => _('Access playout history'),
+ 'View listener stats' => _('View listener stats'),
//dataTables/ColVis.js
- "Show / hide columns" => _("Show / hide columns"),
- "Columns" => _("Columns"),
+ 'Show / hide columns' => _('Show / hide columns'),
+ 'Columns' => _('Columns'),
//datatables.columnFilter.js
- "From {from} to {to}" => _("From {from} to {to}"),
- "kbps" => _("kbps"),
- "yyyy-mm-dd" => _("yyyy-mm-dd"),
- "hh:mm:ss.t" => _("hh:mm:ss.t"),
- "kHz" => _("kHz"),
+ 'From {from} to {to}' => _('From {from} to {to}'),
+ 'kbps' => _('kbps'),
+ 'yyyy-mm-dd' => _('yyyy-mm-dd'),
+ 'hh:mm:ss.t' => _('hh:mm:ss.t'),
+ 'kHz' => _('kHz'),
//datepicker
//months are already in schedule/schedule.js
- "Su" => _("Su"),
- "Mo" => _("Mo"),
- "Tu" => _("Tu"),
- "We" => _("We"),
- "Th" => _("Th"),
- "Fr" => _("Fr"),
- "Sa" => _("Sa"),
- "Close" => _("Close"),
+ 'Su' => _('Su'),
+ 'Mo' => _('Mo'),
+ 'Tu' => _('Tu'),
+ 'We' => _('We'),
+ 'Th' => _('Th'),
+ 'Fr' => _('Fr'),
+ 'Sa' => _('Sa'),
+ 'Close' => _('Close'),
//timepicker
- "Hour" => _("Hour"),
- "Minute" => _("Minute"),
- "Done" => _("Done"),
+ 'Hour' => _('Hour'),
+ 'Minute' => _('Minute'),
+ 'Done' => _('Done'),
//plupload ships with translation files but a lot are incomplete
//so we will keep them here to prevent incomplete translations
- "Select files" => _("Select files"),
- "Add files to the upload queue and click the start button." => _("Add files to the upload queue and click the start button."),
- "Filename" => _("Add files to the upload queue and click the start button."),
- "Status" => _("Status"),
- "Size" => _("Status"),
- "Add Files" => _("Add Files"),
- "Stop Upload" => _("Stop Upload"),
- "Start upload" => _("Start upload"),
- "Add files" => _("Add files"),
- "Uploaded %d/%d files"=> _("Uploaded %d/%d files"),
- "N/A" => _("N/A"),
- "Drag files here." => _("Drag files here."),
- "File extension error." => _("File extension error."),
- "File size error." => _("File size error."),
- "File count error." => _("File count error."),
- "Init error." => _("Init error."),
- "HTTP Error." => _("HTTP Error."),
- "Security error." => _("Security error."),
- "Generic error." => _("Generic error."),
- "IO error." => _("IO error."),
- "File: %s" => _("File: %s"),
- "Close" => _("Close"),
- "%d files queued" => _("%d files queued"),
- "File: %f, size: %s, max file size: %m" => _("File: %f, size: %s, max file size: %m"),
+ 'Select files' => _('Select files'),
+ 'Add files to the upload queue and click the start button.' => _('Add files to the upload queue and click the start button.'),
+ 'Filename' => _('Add files to the upload queue and click the start button.'),
+ 'Status' => _('Status'),
+ 'Size' => _('Status'),
+ 'Add Files' => _('Add Files'),
+ 'Stop Upload' => _('Stop Upload'),
+ 'Start upload' => _('Start upload'),
+ 'Add files' => _('Add files'),
+ 'Uploaded %d/%d files' => _('Uploaded %d/%d files'),
+ 'N/A' => _('N/A'),
+ 'Drag files here.' => _('Drag files here.'),
+ 'File extension error.' => _('File extension error.'),
+ 'File size error.' => _('File size error.'),
+ 'File count error.' => _('File count error.'),
+ 'Init error.' => _('Init error.'),
+ 'HTTP Error.' => _('HTTP Error.'),
+ 'Security error.' => _('Security error.'),
+ 'Generic error.' => _('Generic error.'),
+ 'IO error.' => _('IO error.'),
+ 'File: %s' => _('File: %s'),
+ 'Close' => _('Close'),
+ '%d files queued' => _('%d files queued'),
+ 'File: %f, size: %s, max file size: %m' => _('File: %f, size: %s, max file size: %m'),
"Upload URL might be wrong or doesn't exist" => _("Upload URL might be wrong or doesn't exist"),
- "Error: File too large: " => _("Error: File too large: "),
- "Error: Invalid file extension: " => _("Error: Invalid file extension: "),
+ 'Error: File too large: ' => _('Error: File too large: '),
+ 'Error: Invalid file extension: ' => _('Error: Invalid file extension: '),
//history translations
- "Set Default" => _("Set Default"),
- "Create Entry" => _("Create Entry"),
- "Edit History Record" => _("Edit History Record"),
- "No Show" => _("No Show"),
- "All" => _("All"),
- "Copied %s row%s to the clipboard" => _("Copied %s row%s to the clipboard"),
+ 'Set Default' => _('Set Default'),
+ 'Create Entry' => _('Create Entry'),
+ 'Edit History Record' => _('Edit History Record'),
+ 'No Show' => _('No Show'),
+ 'All' => _('All'),
+ 'Copied %s row%s to the clipboard' => _('Copied %s row%s to the clipboard'),
"%sPrint view%sPlease use your browser's print function to print this table. Press escape when finished." => _("%sPrint view%sPlease use your browser's print function to print this table. Press escape when finished."),
- "New Show" => _("New Show"),
- "New Log Entry" => _("New Log Entry"),
+ 'New Show' => _('New Show'),
+ 'New Log Entry' => _('New Log Entry'),
//Datatables:
- "No data available in table" => _("No data available in table"),
- "(filtered from _MAX_ total entries)" => _("(filtered from _MAX_ total entries)"),
- ": activate to sort column ascending",
- ": activate to sort column descending",
+ 'No data available in table' => _('No data available in table'),
+ '(filtered from _MAX_ total entries)' => _('(filtered from _MAX_ total entries)'),
+ ': activate to sort column ascending',
+ ': activate to sort column descending',
//End of datatables
-
- //New entries from .js "" => _(""),
- "First" => _("First"),
- "Last" => _("Last"),
- "Next" => _("Next"),
- "Previous" => _("Previous"),
- "Search:" => _("Search:"),
- "No matching records found" => _("No matching records found"),
- "Drag tracks here from the library" => _("Drag tracks here from the library"),
- "No tracks were played during the selected time period." => _("No tracks were played during the selected time period."),
- "Unpublish" => _("Unpublish"),
- "No matching results found." => _("No matching results found."),
- "Author" => _("Author"),
- "Description" => _("Description"),
- "Link" => _("Link"),
- "Publication Date" => _("Publication Date"),
- "Import Status" => _("Import Status"),
- "Actions" => _("Actions"),
- "Delete from Library" => _("Delete from Library"),
- "Successfully imported" => _("Successfully imported"),
- "No matching records found" => _("No matching records found"),
- "Show _MENU_" => _("Show _MENU_"),
- "Show _MENU_ entries" => _("Show _MENU_ entries"),
- "Showing _START_ to _END_ of _TOTAL_ entries" => _("Showing _START_ to _END_ of _TOTAL_ entries"),
- "Showing _START_ to _END_ of _TOTAL_ tracks" => _("Showing _START_ to _END_ of _TOTAL_ tracks"),
- "Showing _START_ to _END_ of _TOTAL_ track types" => _("Showing _START_ to _END_ of _TOTAL_ track types"),
- "Showing _START_ to _END_ of _TOTAL_ users" => _("Showing _START_ to _END_ of _TOTAL_ users"),
- "Showing 0 to 0 of 0 entries" => _("Showing 0 to 0 of 0 entries"),
- "Showing 0 to 0 of 0 tracks" => _("Showing 0 to 0 of 0 tracks"),
- "Showing 0 to 0 of 0 track types" => _("Showing 0 to 0 of 0 track types"),
- "(filtered from _MAX_ total track types)" => _("(filtered from _MAX_ total track types)"),
- //"This is used for tracks containing music." => _("This is used for tracks containing music."),
- "Are you sure you want to delete this tracktype?" => _("Are you sure you want to delete this tracktype?"),
- "No track types were found." => _("No track types were found."),
- "No track types found" => _("No track types found"),
- "No matching track types found" => _("No matching track types found"),
- "Enabled" => _("Enabled"),
- "Disabled" => _("Disabled"),
- "Cancel upload" => _("Cancel upload"),
- "Type" => _("Type"),
- "Autoloading playlists' contents are added to shows one hour before the show airs. More information" => _("Autoloading playlists' contents are added to shows one hour before the show airs. More information"),
- "Podcast settings saved" => _("Podcast settings saved"),
- "Are you sure you want to delete this user?" => _("Are you sure you want to delete this user?"),
- "Can't delete yourself!" => _("Can't delete yourself!"),
- "You haven't published any episodes!" => _("You haven't published any episodes!"),
- "You can publish your uploaded content from the 'Tracks' view." => _("You can publish your uploaded content from the 'Tracks' view."),
- "Try it now" => _("Try it now"),
- "If this option is unchecked, the smartblock will schedule as many tracks as can be played out in their entirety within the specified duration. This will usually result in audio playback that is slightly less than the specified duration. If this option is checked, the smartblock will also schedule one final track which will overflow the specified duration. This final track may be cut off mid-way if the show into which the smartblock is added finishes. " => _("If this option is unchecked, the smartblock will schedule as many tracks as can be played out in their entirety within the specified duration. This will usually result in audio playback that is slightly less than the specified duration. If this option is checked, the smartblock will also schedule one final track which will overflow the specified duration. This final track may be cut off mid-way if the show into which the smartblock is added finishes. "),
- "Playlist preview" => _("Playlist preview"),
- "Smart Block" => _("Smart Block"),
- "Webstream preview" => _("Webstream preview"),
- "You don't have permission to view the library." => _("You don't have permission to view the library."),
- "Now" => _("Now"),
- "Click 'New' to create one now." => _("Click 'New' to create one now."),
- "Click 'Upload' to add some now." => _("Click 'Upload' to add some now."),
- "Feed URL" => _("Feed URL"),
- "Import Date" => _("Import Date"),
- "Add New Podcast" => _("Add New Podcast"),
- "Cannot schedule outside a show.\nTry creating a show first." => _("Cannot schedule outside a show.\nTry creating a show first."),
- "No files have been uploaded yet." => _("No files have been uploaded yet."),
- //"Value is required and can't be empty" => _("Value is required and can't be empty"),
- //"mute" => _("mute"),
- //"max volume" => _("max volume"),
+
+ //New entries from .js "" => _(""),
+ 'First' => _('First'),
+ 'Last' => _('Last'),
+ 'Next' => _('Next'),
+ 'Previous' => _('Previous'),
+ 'Search:' => _('Search:'),
+ 'No matching records found' => _('No matching records found'),
+ 'Drag tracks here from the library' => _('Drag tracks here from the library'),
+ 'No tracks were played during the selected time period.' => _('No tracks were played during the selected time period.'),
+ 'Unpublish' => _('Unpublish'),
+ 'No matching results found.' => _('No matching results found.'),
+ 'Author' => _('Author'),
+ 'Description' => _('Description'),
+ 'Link' => _('Link'),
+ 'Publication Date' => _('Publication Date'),
+ 'Import Status' => _('Import Status'),
+ 'Actions' => _('Actions'),
+ 'Delete from Library' => _('Delete from Library'),
+ 'Successfully imported' => _('Successfully imported'),
+ 'No matching records found' => _('No matching records found'),
+ 'Show _MENU_' => _('Show _MENU_'),
+ 'Show _MENU_ entries' => _('Show _MENU_ entries'),
+ 'Showing _START_ to _END_ of _TOTAL_ entries' => _('Showing _START_ to _END_ of _TOTAL_ entries'),
+ 'Showing _START_ to _END_ of _TOTAL_ tracks' => _('Showing _START_ to _END_ of _TOTAL_ tracks'),
+ 'Showing _START_ to _END_ of _TOTAL_ track types' => _('Showing _START_ to _END_ of _TOTAL_ track types'),
+ 'Showing _START_ to _END_ of _TOTAL_ users' => _('Showing _START_ to _END_ of _TOTAL_ users'),
+ 'Showing 0 to 0 of 0 entries' => _('Showing 0 to 0 of 0 entries'),
+ 'Showing 0 to 0 of 0 tracks' => _('Showing 0 to 0 of 0 tracks'),
+ 'Showing 0 to 0 of 0 track types' => _('Showing 0 to 0 of 0 track types'),
+ '(filtered from _MAX_ total track types)' => _('(filtered from _MAX_ total track types)'),
+ //"This is used for tracks containing music." => _("This is used for tracks containing music."),
+ 'Are you sure you want to delete this tracktype?' => _('Are you sure you want to delete this tracktype?'),
+ 'No track types were found.' => _('No track types were found.'),
+ 'No track types found' => _('No track types found'),
+ 'No matching track types found' => _('No matching track types found'),
+ 'Enabled' => _('Enabled'),
+ 'Disabled' => _('Disabled'),
+ 'Cancel upload' => _('Cancel upload'),
+ 'Type' => _('Type'),
+ "Autoloading playlists' contents are added to shows one hour before the show airs. More information" => _("Autoloading playlists' contents are added to shows one hour before the show airs. More information"),
+ 'Podcast settings saved' => _('Podcast settings saved'),
+ 'Are you sure you want to delete this user?' => _('Are you sure you want to delete this user?'),
+ "Can't delete yourself!" => _("Can't delete yourself!"),
+ "You haven't published any episodes!" => _("You haven't published any episodes!"),
+ "You can publish your uploaded content from the 'Tracks' view." => _("You can publish your uploaded content from the 'Tracks' view."),
+ 'Try it now' => _('Try it now'),
+ 'If this option is unchecked, the smartblock will schedule as many tracks as can be played out in their entirety within the specified duration. This will usually result in audio playback that is slightly less than the specified duration. If this option is checked, the smartblock will also schedule one final track which will overflow the specified duration. This final track may be cut off mid-way if the show into which the smartblock is added finishes. ' => _('If this option is unchecked, the smartblock will schedule as many tracks as can be played out in their entirety within the specified duration. This will usually result in audio playback that is slightly less than the specified duration. If this option is checked, the smartblock will also schedule one final track which will overflow the specified duration. This final track may be cut off mid-way if the show into which the smartblock is added finishes. '),
+ 'Playlist preview' => _('Playlist preview'),
+ 'Smart Block' => _('Smart Block'),
+ 'Webstream preview' => _('Webstream preview'),
+ "You don't have permission to view the library." => _("You don't have permission to view the library."),
+ 'Now' => _('Now'),
+ "Click 'New' to create one now." => _("Click 'New' to create one now."),
+ "Click 'Upload' to add some now." => _("Click 'Upload' to add some now."),
+ 'Feed URL' => _('Feed URL'),
+ 'Import Date' => _('Import Date'),
+ 'Add New Podcast' => _('Add New Podcast'),
+ "Cannot schedule outside a show.\nTry creating a show first." => _("Cannot schedule outside a show.\nTry creating a show first."),
+ 'No files have been uploaded yet.' => _('No files have been uploaded yet.'),
+ //"Value is required and can't be empty" => _("Value is required and can't be empty"),
+ //"mute" => _("mute"),
+ //"max volume" => _("max volume"),
//embed player
- "On Air" => _("On Air"),
- "Off Air" => _("Off Air"),
- "Offline" => _("Offline"),
- "Nothing scheduled" => _("Nothing scheduled"),
- "Click 'Add' to create one now." => _("Click 'Add' to create one now.")
- );
+ 'On Air' => _('On Air'),
+ 'Off Air' => _('Off Air'),
+ 'Offline' => _('Offline'),
+ 'Nothing scheduled' => _('Nothing scheduled'),
+ "Click 'Add' to create one now." => _("Click 'Add' to create one now."),
+ ];
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
- header("Content-Type: text/javascript");
- echo "var general_dict=" . json_encode($translations);
+ header('Content-Type: text/javascript');
+ echo 'var general_dict=' . json_encode($translations);
}
}
diff --git a/legacy/application/controllers/LoginController.php b/legacy/application/controllers/LoginController.php
index c29c0113a..dc93f9d0f 100644
--- a/legacy/application/controllers/LoginController.php
+++ b/legacy/application/controllers/LoginController.php
@@ -2,35 +2,32 @@
class LoginController extends Zend_Controller_Action
{
-
public function init()
{
$CC_CONFIG = Config::getConfig();
$baseUrl = Application_Common_OsPath::getBaseDir();
- $this->view->headLink(array('rel' => 'icon', 'href' => $baseUrl . 'favicon.ico?' . $CC_CONFIG['airtime_version'], 'type' => 'image/x-icon'), 'PREPEND')
+ $this->view->headLink(['rel' => 'icon', 'href' => $baseUrl . 'favicon.ico?' . $CC_CONFIG['airtime_version'], 'type' => 'image/x-icon'], 'PREPEND')
->appendStylesheet($baseUrl . 'css/bootstrap.css?' . $CC_CONFIG['airtime_version'])
->appendStylesheet($baseUrl . 'css/redmond/jquery-ui-1.8.8.custom.css?' . $CC_CONFIG['airtime_version'])
- ->appendStylesheet($baseUrl . 'css/styles.css?' . $CC_CONFIG['airtime_version']);
-
+ ->appendStylesheet($baseUrl . 'css/styles.css?' . $CC_CONFIG['airtime_version'])
+ ;
}
public function indexAction()
{
$CC_CONFIG = Config::getConfig();
-
+
$request = $this->getRequest();
$response = $this->getResponse();
$stationLocale = Application_Model_Preference::GetDefaultLocale();
-
+
//Enable AJAX requests from www.airtime.pro for the sign-in process.
CORSHelper::enableCrossOriginRequests($request, $response);
-
Application_Model_Locale::configureLocalization($request->getcookie('airtime_locale', $stationLocale));
if (Zend_Session::isStarted()) {
-
//Open the session for writing, because we close it for writing by default in Bootstrap.php as an optimization.
SessionHelper::reopenSessionForWriting();
@@ -46,19 +43,17 @@ class LoginController extends Zend_Controller_Action
$this->_helper->layout->setLayout('login');
$this->view->error = false;
-
+
$baseUrl = Application_Common_OsPath::getBaseDir();
$form = new Application_Form_Login();
- $message = _("Please enter your username and password.");
+ $message = _('Please enter your username and password.');
if ($request->isPost()) {
-
//Open the session for writing, because we close it for writing by default in Bootstrap.php as an optimization.
//session_start();
-
if ($form->isValid($request->getPost())) {
//get the username and password from the form
$username = $form->getValue('username');
@@ -69,8 +64,9 @@ class LoginController extends Zend_Controller_Action
//pass to the adapter the submitted username and password
$authAdapter->setIdentity($username)
- ->setCredential($password);
-
+ ->setCredential($password)
+ ;
+
$result = $auth->authenticate($authAdapter);
if ($result->isValid()) {
Zend_Session::regenerateId();
@@ -142,11 +138,12 @@ class LoginController extends Zend_Controller_Action
if (empty($username)) {
$query->filterByDbEmail($email);
- } else if (empty($email)) {
+ } elseif (empty($email)) {
$query->filterByDbLogin($username);
} else {
$query->filterByDbEmail($email)
- ->filterByDbLogin($username);
+ ->filterByDbLogin($username)
+ ;
}
$user = $query->findOne();
@@ -157,13 +154,13 @@ class LoginController extends Zend_Controller_Action
if ($success) {
$this->_helper->redirector('password-restore-after', 'login');
} else {
- $form->email->addError($this->view->translate(_("Email could not be sent. Check your mail server settings and ensure it has been configured properly.")));
+ $form->email->addError($this->view->translate(_('Email could not be sent. Check your mail server settings and ensure it has been configured properly.')));
}
} else {
- $form->email->addError($this->view->translate(_("That username or email address could not be found.")));
+ $form->email->addError($this->view->translate(_('That username or email address could not be found.')));
}
} else { //Form is not valid
- $form->email->addError($this->view->translate(_("There was a problem with the username or email address you entered.")));
+ $form->email->addError($this->view->translate(_('There was a problem with the username or email address you entered.')));
}
}
@@ -174,7 +171,7 @@ class LoginController extends Zend_Controller_Action
{
$request = $this->getRequest();
$stationLocale = Application_Model_Preference::GetDefaultLocale();
-
+
Application_Model_Locale::configureLocalization($request->getcookie('airtime_locale', $stationLocale));
//uses separate layout without a navigation.
@@ -187,25 +184,24 @@ class LoginController extends Zend_Controller_Action
$this->_helper->layout->setLayout('login');
$request = $this->getRequest();
- $token = $request->getParam("token", false);
- $user_id = $request->getParam("user_id", 0);
+ $token = $request->getParam('token', false);
+ $user_id = $request->getParam('user_id', 0);
$form = new Application_Form_PasswordChange();
$auth = new Application_Model_Auth();
$user = CcSubjsQuery::create()->findPK($user_id);
-
+
$stationLocale = Application_Model_Preference::GetDefaultLocale();
Application_Model_Locale::configureLocalization($request->getcookie('airtime_locale', $stationLocale));
//check validity of token
if (!$auth->checkToken($user_id, $token, 'password.restore')) {
- Logging::debug("token not valid");
+ Logging::debug('token not valid');
$this->_helper->redirector('index', 'login');
}
if ($request->isPost() && $form->isValid($request->getPost())) {
-
$user->setDbPass(md5($form->password->getValue()));
$user->save();
@@ -216,7 +212,8 @@ class LoginController extends Zend_Controller_Action
$authAdapter = Application_Model_Auth::getAuthAdapter();
$authAdapter->setIdentity($user->getDbLogin())
- ->setCredential($form->password->getValue());
+ ->setCredential($form->password->getValue())
+ ;
$zend_auth->authenticate($authAdapter);
@@ -234,18 +231,20 @@ class LoginController extends Zend_Controller_Action
}
/**
- * populates view with results from a login error and adds a new form
+ * populates view with results from a login error and adds a new form.
+ *
+ * @param string $username user that failed to login
*
- * @param String $username user that failed to login
* @return new form
*/
private function loginError($username)
{
- $this->view->message = _("Wrong username or password provided. Please try again.");
+ $this->view->message = _('Wrong username or password provided. Please try again.');
Application_Model_Subjects::increaseLoginAttempts($username);
Application_Model_LoginAttempts::increaseAttempts($_SERVER['REMOTE_ADDR']);
- $form = new Application_Form_Login();
+ $form = new Application_Form_Login();
$this->view->error = true;
+
return $form;
}
}
diff --git a/legacy/application/controllers/PlaylistController.php b/legacy/application/controllers/PlaylistController.php
index 685bfd480..154100dcf 100644
--- a/legacy/application/controllers/PlaylistController.php
+++ b/legacy/application/controllers/PlaylistController.php
@@ -1,37 +1,36 @@
_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('add-items', 'json')
- ->addActionContext('move-items', 'json')
- ->addActionContext('delete-items', 'json')
- ->addActionContext('set-fade', 'json')
- ->addActionContext('set-crossfade', 'json')
- ->addActionContext('set-cue', 'json')
- ->addActionContext('new', 'json')
- ->addActionContext('edit', 'json')
- ->addActionContext('delete', 'json')
- ->addActionContext('close-playlist', 'json')
- ->addActionContext('play', 'json')
- ->addActionContext('set-playlist-fades', 'json')
- ->addActionContext('get-playlist-fades', 'json')
- ->addActionContext('set-playlist-name', 'json')
- ->addActionContext('set-playlist-description', 'json')
- ->addActionContext('playlist-preview', 'json')
- ->addActionContext('get-playlist', 'json')
- ->addActionContext('save', 'json')
- ->addActionContext('smart-block-generate', 'json')
- ->addActionContext('smart-block-shuffle', 'json')
- ->addActionContext('get-block-info', 'json')
- ->addActionContext('shuffle', 'json')
- ->addActionContext('empty-content', 'json')
- ->addActionContext('change-playlist', 'json')
- ->initContext();
+ ->addActionContext('move-items', 'json')
+ ->addActionContext('delete-items', 'json')
+ ->addActionContext('set-fade', 'json')
+ ->addActionContext('set-crossfade', 'json')
+ ->addActionContext('set-cue', 'json')
+ ->addActionContext('new', 'json')
+ ->addActionContext('edit', 'json')
+ ->addActionContext('delete', 'json')
+ ->addActionContext('close-playlist', 'json')
+ ->addActionContext('play', 'json')
+ ->addActionContext('set-playlist-fades', 'json')
+ ->addActionContext('get-playlist-fades', 'json')
+ ->addActionContext('set-playlist-name', 'json')
+ ->addActionContext('set-playlist-description', 'json')
+ ->addActionContext('playlist-preview', 'json')
+ ->addActionContext('get-playlist', 'json')
+ ->addActionContext('save', 'json')
+ ->addActionContext('smart-block-generate', 'json')
+ ->addActionContext('smart-block-shuffle', 'json')
+ ->addActionContext('get-block-info', 'json')
+ ->addActionContext('shuffle', 'json')
+ ->addActionContext('empty-content', 'json')
+ ->addActionContext('change-playlist', 'json')
+ ->initContext()
+ ;
//This controller writes to the session all over the place, so we're going to reopen it for writing here.
SessionHelper::reopenSessionForWriting();
@@ -48,9 +47,10 @@ class PlaylistController extends Zend_Controller_Action
$obj = new $objInfo['className']($obj_sess->id);
$modified = $this->_getParam('modified', null);
- if ($obj->getLastModified("U") !== $modified) {
+ if ($obj->getLastModified('U') !== $modified) {
$this->createFullResponse($obj);
- throw new PlaylistOutDatedException(sprintf(_("You are viewing an older version of %s"), $obj->getName()));
+
+ throw new PlaylistOutDatedException(sprintf(_('You are viewing an older version of %s'), $obj->getName()));
}
}
@@ -71,20 +71,23 @@ class PlaylistController extends Zend_Controller_Action
$this->view->html = $this->view->render('playlist/update.phtml');
$this->view->name = $obj->getName();
$this->view->description = $obj->getDescription();
- $this->view->modified = $obj->getLastModified("U");
+ $this->view->modified = $obj->getLastModified('U');
unset($this->view->obj);
}
- private function createFullResponse($obj = null, $isJson = false,
- $formIsValid = false)
- {
+ private function createFullResponse(
+ $obj = null,
+ $isJson = false,
+ $formIsValid = false
+ ) {
$user = Application_Model_User::getCurrentUser();
- $isAdminOrPM = $user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
+ $isAdminOrPM = $user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER]);
if (!$isAdminOrPM && $obj->getCreatorId() != $user->getId()) {
- $this->view->objType = $obj instanceof Application_Model_Block ? "block" : "playlist";
+ $this->view->objType = $obj instanceof Application_Model_Block ? 'block' : 'playlist';
$this->view->obj = $obj;
$this->view->html = $this->view->render('playlist/permission-denied.phtml');
+
return;
}
@@ -109,26 +112,24 @@ class PlaylistController extends Zend_Controller_Action
if ($isJson) {
return $this->view->render($viewPath);
- } else {
- $this->view->html = $this->view->render($viewPath);
}
+ $this->view->html = $this->view->render($viewPath);
} else {
$this->view->obj = $obj;
//$this->view->type = "pl";
$this->view->id = $obj->getId();
if ($isJson) {
return $this->view->html = $this->view->render($viewPath);
- } else {
- $this->view->html = $this->view->render($viewPath);
}
+ $this->view->html = $this->view->render($viewPath);
+
unset($this->view->obj);
}
} else {
if ($isJson) {
return $this->view->render($viewPath);
- } else {
- $this->view->html = $this->view->render($viewPath);
}
+ $this->view->html = $this->view->render($viewPath);
}
}
@@ -139,22 +140,22 @@ class PlaylistController extends Zend_Controller_Action
private function blockDynamic($obj)
{
- $this->view->error = _("You cannot add tracks to dynamic blocks.");
+ $this->view->error = _('You cannot add tracks to dynamic blocks.');
$this->createFullResponse($obj);
}
private function playlistNotFound($p_type, $p_isJson = false)
{
$p_type = ucfirst($p_type);
- $this->view->error = sprintf(_("%s not found"), $p_type);
+ $this->view->error = sprintf(_('%s not found'), $p_type);
Logging::info("{$p_type} not found");
Application_Model_Library::changePlaylist(null, $p_type);
-
+
if (!$p_isJson) {
$this->createFullResponse(null);
} else {
- $this->_helper->json->sendJson(array("error"=>$this->view->error, "result"=>1, "html"=>$this->createFullResponse(null, $p_isJson)));
+ $this->_helper->json->sendJson(['error' => $this->view->error, 'result' => 1, 'html' => $this->createFullResponse(null, $p_isJson)]);
}
}
@@ -167,19 +168,19 @@ class PlaylistController extends Zend_Controller_Action
private function playlistUnknownError($e)
{
- $this->view->error = _("Something went wrong.");
+ $this->view->error = _('Something went wrong.');
Logging::info($e->getMessage());
}
private function wrongTypeToBlock($obj)
{
- $this->view->error = _("You can only add tracks to smart block.");
+ $this->view->error = _('You can only add tracks to smart block.');
$this->createFullResponse($obj);
}
private function wrongTypeToPlaylist($obj)
{
- $this->view->error = _("You can only add tracks, smart blocks, and webstreams to playlists.");
+ $this->view->error = _('You can only add tracks, smart blocks, and webstreams to playlists.');
$this->createFullResponse($obj);
}
@@ -204,7 +205,8 @@ class PlaylistController extends Zend_Controller_Action
$this->createFullResponse($obj);
}
- public function changePlaylistAction() {
+ public function changePlaylistAction()
+ {
$this->view->layout()->disableLayout(); // Don't inject the standard Now Playing header.
$this->_helper->viewRenderer->setNoRender(true); // Don't use (phtml) templates
@@ -236,30 +238,31 @@ class PlaylistController extends Zend_Controller_Action
public function deleteAction()
{
- $ids = $this->_getParam('ids');
- $ids = (!is_array($ids)) ? array($ids) : $ids;
+ $ids = $this->_getParam('ids');
+ $ids = (!is_array($ids)) ? [$ids] : $ids;
$type = $this->_getParam('type');
- $obj = null;
+ $obj = null;
- $objInfo = Application_Model_Library::getObjInfo($type);
+ $objInfo = Application_Model_Library::getObjInfo($type);
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$obj_sess = new Zend_Session_Namespace(
- UI_PLAYLISTCONTROLLER_OBJ_SESSNAME);
+ UI_PLAYLISTCONTROLLER_OBJ_SESSNAME
+ );
try {
Logging::info("Currently active {$type} {$obj_sess->id}");
if (in_array($obj_sess->id, $ids)) {
Logging::info("Deleting currently active {$type}");
- // Application_Model_Library::changePlaylist(null, $type);
+ // Application_Model_Library::changePlaylist(null, $type);
} else {
Logging::info("Not deleting currently active {$type}");
$obj = new $objInfo['className']($obj_sess->id);
}
- if (strcmp($objInfo['className'], 'Application_Model_Playlist')==0) {
+ if (strcmp($objInfo['className'], 'Application_Model_Playlist') == 0) {
Application_Model_Playlist::deletePlaylists($ids, $userInfo->id);
} else {
Application_Model_Block::deleteBlocks($ids, $userInfo->id);
@@ -276,7 +279,8 @@ class PlaylistController extends Zend_Controller_Action
}
}
- public function closePlaylistAction() {
+ public function closePlaylistAction()
+ {
$type = $this->_getParam('type');
$obj = null;
Application_Model_Library::changePlaylist($obj, $type);
@@ -285,8 +289,8 @@ class PlaylistController extends Zend_Controller_Action
public function addItemsAction()
{
- $ids = $this->_getParam('aItems', array());
- $ids = (!is_array($ids)) ? array($ids) : $ids;
+ $ids = $this->_getParam('aItems', []);
+ $ids = (!is_array($ids)) ? [$ids] : $ids;
$afterItem = $this->_getParam('afterItem', null);
$addType = $this->_getParam('type', 'after');
// this is the obj type of destination
@@ -298,7 +302,7 @@ class PlaylistController extends Zend_Controller_Action
foreach ($ids as $id) {
if (is_array($id) && isset($id[1])) {
if ($id[1] == 'playlist') {
- throw new WrongTypeToPlaylistException;
+ throw new WrongTypeToPlaylistException();
}
}
}
@@ -309,13 +313,13 @@ class PlaylistController extends Zend_Controller_Action
foreach ($ids as $id) {
if (is_array($id) && isset($id[1])) {
if ($id[1] != 'audioclip') {
- throw new WrongTypeToBlockException;
+ throw new WrongTypeToBlockException();
}
}
}
$obj->addAudioClips($ids, $afterItem, $addType);
} else {
- throw new BlockDynamicException;
+ throw new BlockDynamicException();
}
$this->createUpdateResponse($obj);
} catch (PlaylistOutDatedException $e) {
@@ -338,7 +342,7 @@ class PlaylistController extends Zend_Controller_Action
public function moveItemsAction()
{
$ids = $this->_getParam('ids');
- $ids = (!is_array($ids)) ? array($ids) : $ids;
+ $ids = (!is_array($ids)) ? [$ids] : $ids;
$afterItem = $this->_getParam('afterItem', null);
$type = $this->_getParam('obj_type');
@@ -358,7 +362,7 @@ class PlaylistController extends Zend_Controller_Action
public function deleteItemsAction()
{
$ids = $this->_getParam('ids');
- $ids = (!is_array($ids)) ? array($ids) : $ids;
+ $ids = (!is_array($ids)) ? [$ids] : $ids;
$modified = $this->_getParam('modified');
$type = $this->_getParam('obj_type');
@@ -374,10 +378,11 @@ class PlaylistController extends Zend_Controller_Action
$this->playlistUnknownError($e);
}
}
-
+
public function emptyContentAction()
{
$type = $this->_getParam('obj_type');
+
try {
$obj = $this->getPlaylist($type);
if ($type == 'playlist') {
@@ -406,12 +411,12 @@ class PlaylistController extends Zend_Controller_Action
$obj = $this->getPlaylist($type);
$response = $obj->changeClipLength($id, $cueIn, $cueOut);
- if (!isset($response["error"])) {
+ if (!isset($response['error'])) {
$this->view->response = $response;
$this->createUpdateResponse($obj);
} else {
- $this->view->cue_error = $response["error"];
- $this->view->code = $response["type"];
+ $this->view->cue_error = $response['error'];
+ $this->view->code = $response['type'];
}
} catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($e);
@@ -433,11 +438,11 @@ class PlaylistController extends Zend_Controller_Action
$obj = $this->getPlaylist($type);
$response = $obj->changeFadeInfo($id, $fadeIn, $fadeOut);
- if (!isset($response["error"])) {
+ if (!isset($response['error'])) {
$this->createUpdateResponse($obj);
$this->view->response = $response;
} else {
- $this->view->fade_error = $response["error"];
+ $this->view->fade_error = $response['error'];
}
} catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($e);
@@ -447,7 +452,7 @@ class PlaylistController extends Zend_Controller_Action
$this->playlistUnknownError($e);
}
}
-
+
public function setCrossfadeAction()
{
$id1 = $this->_getParam('id1', null);
@@ -456,15 +461,15 @@ class PlaylistController extends Zend_Controller_Action
$fadeIn = $this->_getParam('fadeIn', 0);
$fadeOut = $this->_getParam('fadeOut', 0);
$offset = $this->_getParam('offset', 0);
-
+
try {
$obj = $this->getPlaylist($type);
$response = $obj->createCrossfade($id1, $fadeOut, $id2, $fadeIn, $offset);
-
- if (!isset($response["error"])) {
+
+ if (!isset($response['error'])) {
$this->createUpdateResponse($obj);
} else {
- $this->view->error = $response["error"];
+ $this->view->error = $response['error'];
}
} catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($e);
@@ -478,12 +483,13 @@ class PlaylistController extends Zend_Controller_Action
public function getPlaylistFadesAction()
{
$type = $this->_getParam('type');
+
try {
$obj = $this->getPlaylist($type);
$fades = $obj->getFadeInfo(0);
$this->view->fadeIn = $fades[0];
- $fades = $obj->getFadeInfo($obj->getSize()-1);
+ $fades = $obj->getFadeInfo($obj->getSize() - 1);
$this->view->fadeOut = $fades[1];
} catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($e);
@@ -498,7 +504,7 @@ class PlaylistController extends Zend_Controller_Action
* The playlist fades are stored in the elements themselves.
* The fade in is set to the first elements fade in and
* the fade out is set to the last elements fade out.
- **/
+ */
public function setPlaylistFadesAction()
{
$fadeIn = $this->_getParam('fadeIn', null);
@@ -508,7 +514,7 @@ class PlaylistController extends Zend_Controller_Action
try {
$obj = $this->getPlaylist($type);
$obj->setfades($fadeIn, $fadeOut);
- $this->view->modified = $obj->getLastModified("U");
+ $this->view->modified = $obj->getLastModified('U');
} catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($e);
} catch (PlaylistNotFoundException $e) {
@@ -521,7 +527,7 @@ class PlaylistController extends Zend_Controller_Action
public function setPlaylistNameDescAction()
{
$name = $this->_getParam('name', _('Unknown Playlist'));
- $description = $this->_getParam('description', "");
+ $description = $this->_getParam('description', '');
$type = $this->_getParam('type');
try {
@@ -530,7 +536,7 @@ class PlaylistController extends Zend_Controller_Action
$obj->setDescription($description);
$this->view->description = $description;
$this->view->playlistName = $name;
- $this->view->modified = $obj->getLastModified("U");
+ $this->view->modified = $obj->getLastModified('U');
} catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($e);
} catch (PlaylistNotFoundException $e) {
@@ -544,7 +550,7 @@ class PlaylistController extends Zend_Controller_Action
{
$request = $this->getRequest();
$params = $request->getPost();
- $result = array();
+ $result = [];
if ($params['type'] == 'block') {
try {
@@ -559,9 +565,7 @@ class PlaylistController extends Zend_Controller_Action
$bl->saveSmartBlockCriteria($params['data']);
$this->createUpdateResponse($bl, true);
$this->view->result = 0;
- /*
- $result['html'] = $this->createFullResponse($bl, true, true);
- */
+ // $result['html'] = $this->createFullResponse($bl, true, true);
} else {
$this->view->form = $form;
$this->view->unsavedName = $params['name'];
@@ -575,14 +579,13 @@ class PlaylistController extends Zend_Controller_Action
$this->view->name = $bl->getName();
//$this->view->type = "sb";
$this->view->id = $bl->getId();
- $this->view->modified = $bl->getLastModified("U");
- } else if ($params['type'] == 'playlist') {
+ $this->view->modified = $bl->getLastModified('U');
+ } elseif ($params['type'] == 'playlist') {
$this->setPlaylistNameDescAction();
$this->view->modified = $this->view->modified;
$this->view->name = $params['name'];
}
-
//$this->_helper->json->sendJson($result);
}
@@ -590,18 +593,18 @@ class PlaylistController extends Zend_Controller_Action
{
$request = $this->getRequest();
$params = $request->getPost();
-
+
//make sure block exists
try {
$bl = new Application_Model_Block($params['obj_id']);
-
+
$form = new Application_Form_SmartBlockCriteria();
$form->startForm($params['obj_id']);
if ($form->isValid($params)) {
$result = $bl->generateSmartBlock($params['data']);
$this->view->result = $result['result'];
$this->createUpdateResponse($bl, true);
- #$this->_helper->json->sendJson(array("result"=>0, "html"=>$this->createFullResponse($bl, true, true)));
+ //$this->_helper->json->sendJson(array("result"=>0, "html"=>$this->createFullResponse($bl, true, true)));
} else {
$this->view->obj = $bl;
$this->view->id = $bl->getId();
@@ -620,12 +623,13 @@ class PlaylistController extends Zend_Controller_Action
{
$request = $this->getRequest();
$params = $request->getPost();
+
try {
$bl = new Application_Model_Block($params['obj_id']);
$result = $bl->shuffleSmartBlock();
- $this->view->result = $result["result"];
- $this->createUpdateResponse($bl,true);
+ $this->view->result = $result['result'];
+ $this->createUpdateResponse($bl, true);
/*
if ($result['result'] == 0) {
@@ -643,17 +647,18 @@ class PlaylistController extends Zend_Controller_Action
$this->playlistUnknownError($e);
}
}
-
+
public function shuffleAction()
{
$request = $this->getRequest();
$params = $request->getPost();
+
try {
$pl = new Application_Model_Playlist($params['obj_id']);
$result = $pl->shuffle();
- $this->view->result = $result["result"];
- $this->createUpdateResponse($pl,true);
+ $this->view->result = $result['result'];
+ $this->createUpdateResponse($pl, true);
/*
if ($result['result'] == 0) {
$this->_helper->json->sendJson(array(
@@ -685,6 +690,12 @@ class PlaylistController extends Zend_Controller_Action
$this->_helper->json->sendJson($out);
}
}
-class WrongTypeToBlockException extends Exception {}
-class WrongTypeToPlaylistException extends Exception {}
-class BlockDynamicException extends Exception {}
+class WrongTypeToBlockException extends Exception
+{
+}
+class WrongTypeToPlaylistException extends Exception
+{
+}
+class BlockDynamicException extends Exception
+{
+}
diff --git a/legacy/application/controllers/PlayouthistoryController.php b/legacy/application/controllers/PlayouthistoryController.php
index 441f42168..07352b5ba 100644
--- a/legacy/application/controllers/PlayouthistoryController.php
+++ b/legacy/application/controllers/PlayouthistoryController.php
@@ -16,9 +16,10 @@ class PlayouthistoryController extends Zend_Controller_Action
->addActionContext('delete-list-items', 'json')
->addActionContext('update-list-item', 'json')
->addActionContext('update-file-item', 'json')
- ->initContext();
+ ->initContext()
+ ;
}
-
+
public function indexAction()
{
$CC_CONFIG = Config::getConfig();
@@ -27,48 +28,48 @@ class PlayouthistoryController extends Zend_Controller_Action
Zend_Layout::getMvcInstance()->assign('parent_page', 'Analytics');
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($this->getRequest());
-
+
$userTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
$startsDT->setTimezone($userTimezone);
$endsDT->setTimezone($userTimezone);
$form = new Application_Form_DateRange();
- $form->populate(array(
- 'his_date_start' => $startsDT->format("Y-m-d"),
- 'his_time_start' => $startsDT->format("H:i"),
- 'his_date_end' => $endsDT->format("Y-m-d"),
- 'his_time_end' => $endsDT->format("H:i")
- ));
+ $form->populate([
+ 'his_date_start' => $startsDT->format('Y-m-d'),
+ 'his_time_start' => $startsDT->format('H:i'),
+ 'his_date_end' => $endsDT->format('Y-m-d'),
+ 'his_time_end' => $endsDT->format('H:i'),
+ ]);
$this->view->date_form = $form;
- $this->view->headScript()->appendFile($baseUrl.'js/contextmenu/jquery.contextMenu.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/datatables/js/jquery.dataTables.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/datatables/plugin/dataTables.pluginAPI.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/datatables/plugin/dataTables.fnSetFilteringDelay.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/contextmenu/jquery.contextMenu.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/datatables/js/jquery.dataTables.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/datatables/plugin/dataTables.pluginAPI.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/datatables/plugin/dataTables.fnSetFilteringDelay.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/timepicker/jquery.ui.timepicker.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/bootstrap-datetime/bootstrap-datetimepicker.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/buttons/buttons.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/utilities/utilities.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/libs/CSVexport.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/libs/pdfmake.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/libs/vfs_fonts.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/playouthistory/historytable.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/timepicker/jquery.ui.timepicker.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/bootstrap-datetime/bootstrap-datetimepicker.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/buttons/buttons.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/utilities/utilities.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/libs/CSVexport.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/libs/pdfmake.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/libs/vfs_fonts.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/playouthistory/historytable.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headLink()->appendStylesheet($baseUrl.'css/bootstrap-datetimepicker.min.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/jquery.ui.timepicker.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/playouthistory.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/history_styles.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/jquery.contextMenu.css?'.$CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/bootstrap-datetimepicker.min.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/jquery.ui.timepicker.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/playouthistory.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/history_styles.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/jquery.contextMenu.css?' . $CC_CONFIG['airtime_version']);
//set datatables columns for display of data.
$historyService = new Application_Service_HistoryService();
$columns = json_encode($historyService->getDatatablesLogSheetColumns());
- $script = "localStorage.setItem( 'datatables-historyitem-aoColumns', JSON.stringify($columns) ); ";
+ $script = "localStorage.setItem( 'datatables-historyitem-aoColumns', JSON.stringify({$columns}) ); ";
$columns = json_encode($historyService->getDatatablesFileSummaryColumns());
- $script.= "localStorage.setItem( 'datatables-historyfile-aoColumns', JSON.stringify($columns) );";
+ $script .= "localStorage.setItem( 'datatables-historyfile-aoColumns', JSON.stringify({$columns}) );";
$this->view->headScript()->appendScript($script);
$user = Application_Model_User::getCurrentUser();
@@ -77,109 +78,104 @@ class PlayouthistoryController extends Zend_Controller_Action
public function fileHistoryFeedAction()
{
- try {
- $request = $this->getRequest();
- $params = $request->getParams();
- $instance = $request->getParam("instance_id", null);
-
+ try {
+ $request = $this->getRequest();
+ $params = $request->getParams();
+ $instance = $request->getParam('instance_id', null);
+
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($request);
- $historyService = new Application_Service_HistoryService();
- $r = $historyService->getFileSummaryData($startsDT, $endsDT, $params);
+ $historyService = new Application_Service_HistoryService();
+ $r = $historyService->getFileSummaryData($startsDT, $endsDT, $params);
- $this->view->sEcho = $r["sEcho"];
- $this->view->iTotalDisplayRecords = $r["iTotalDisplayRecords"];
- $this->view->iTotalRecords = $r["iTotalRecords"];
- $this->view->history = $r["history"];
+ $this->view->sEcho = $r['sEcho'];
+ $this->view->iTotalDisplayRecords = $r['iTotalDisplayRecords'];
+ $this->view->iTotalRecords = $r['iTotalRecords'];
+ $this->view->history = $r['history'];
$this->view->history = SecurityHelper::htmlescape_recursive($this->view->history);
- }
- catch (Exception $e) {
- Logging::info($e);
- Logging::info($e->getMessage());
+ } catch (Exception $e) {
+ Logging::info($e);
+ Logging::info($e->getMessage());
}
}
public function itemHistoryFeedAction()
{
- try {
- $request = $this->getRequest();
- $params = $request->getParams();
- $instance = $request->getParam("instance_id", null);
-
+ try {
+ $request = $this->getRequest();
+ $params = $request->getParams();
+ $instance = $request->getParam('instance_id', null);
+
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($request);
-
- $historyService = new Application_Service_HistoryService();
- $r = $historyService->getPlayedItemData($startsDT, $endsDT, $params, $instance);
- $this->view->sEcho = $r["sEcho"];
- $this->view->iTotalDisplayRecords = $r["iTotalDisplayRecords"];
- $this->view->iTotalRecords = $r["iTotalRecords"];
- $this->view->history = $r["history"];
+ $historyService = new Application_Service_HistoryService();
+ $r = $historyService->getPlayedItemData($startsDT, $endsDT, $params, $instance);
+
+ $this->view->sEcho = $r['sEcho'];
+ $this->view->iTotalDisplayRecords = $r['iTotalDisplayRecords'];
+ $this->view->iTotalRecords = $r['iTotalRecords'];
+ $this->view->history = $r['history'];
$this->view->history = SecurityHelper::htmlescape_recursive($this->view->history);
-
+ } catch (Exception $e) {
+ Logging::info($e);
+ Logging::info($e->getMessage());
}
- catch (Exception $e) {
- Logging::info($e);
- Logging::info($e->getMessage());
- }
}
public function showHistoryFeedAction()
{
- try {
- $request = $this->getRequest();
- $params = $request->getParams();
- $instance = $request->getParam("instance_id", null);
-
+ try {
+ $request = $this->getRequest();
+ $params = $request->getParams();
+ $instance = $request->getParam('instance_id', null);
+
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($request);
- $historyService = new Application_Service_HistoryService();
- $shows = $historyService->getShowList($startsDT, $endsDT);
+ $historyService = new Application_Service_HistoryService();
+ $shows = $historyService->getShowList($startsDT, $endsDT);
$shows = SecurityHelper::htmlescape_recursive($shows);
- $this->_helper->json->sendJson($shows);
- }
- catch (Exception $e) {
- Logging::info($e);
- Logging::info($e->getMessage());
- }
+ $this->_helper->json->sendJson($shows);
+ } catch (Exception $e) {
+ Logging::info($e);
+ Logging::info($e->getMessage());
+ }
}
public function editFileItemAction()
{
- $file_id = $this->_getParam('id');
+ $file_id = $this->_getParam('id');
- $historyService = new Application_Service_HistoryService();
- $form = $historyService->makeHistoryFileForm($file_id);
+ $historyService = new Application_Service_HistoryService();
+ $form = $historyService->makeHistoryFileForm($file_id);
- $this->view->form = $form;
- $this->view->dialog = $this->view->render('playouthistory/dialog.phtml');
+ $this->view->form = $form;
+ $this->view->dialog = $this->view->render('playouthistory/dialog.phtml');
- unset($this->view->form);
+ unset($this->view->form);
}
public function createListItemAction()
{
- try {
- $request = $this->getRequest();
- $params = $request->getPost();
- Logging::info($params);
+ try {
+ $request = $this->getRequest();
+ $params = $request->getPost();
+ Logging::info($params);
- $historyService = new Application_Service_HistoryService();
- $json = $historyService->createPlayedItem($params);
+ $historyService = new Application_Service_HistoryService();
+ $json = $historyService->createPlayedItem($params);
- if (isset($json["form"])) {
- $this->view->form = $json["form"];
- $json["form"] = $this->view->render('playouthistory/dialog.phtml');
+ if (isset($json['form'])) {
+ $this->view->form = $json['form'];
+ $json['form'] = $this->view->render('playouthistory/dialog.phtml');
- unset($this->view->form);
- }
+ unset($this->view->form);
+ }
- $this->_helper->json->sendJson($json);
- }
- catch (Exception $e) {
- Logging::info($e);
- Logging::info($e->getMessage());
+ $this->_helper->json->sendJson($json);
+ } catch (Exception $e) {
+ Logging::info($e);
+ Logging::info($e->getMessage());
}
}
@@ -200,43 +196,42 @@ class PlayouthistoryController extends Zend_Controller_Action
public function deleteListItemAction()
{
- $history_id = $this->_getParam('id');
+ $history_id = $this->_getParam('id');
- $historyService = new Application_Service_HistoryService();
- $historyService->deletePlayedItem($history_id);
+ $historyService = new Application_Service_HistoryService();
+ $historyService->deletePlayedItem($history_id);
}
public function deleteListItemsAction()
{
- $history_ids = $this->_getParam('ids');
+ $history_ids = $this->_getParam('ids');
- $historyService = new Application_Service_HistoryService();
- $historyService->deletePlayedItems($history_ids);
+ $historyService = new Application_Service_HistoryService();
+ $historyService->deletePlayedItems($history_ids);
}
public function updateListItemAction()
{
- try {
- $request = $this->getRequest();
- $params = $request->getPost();
- Logging::info($params);
+ try {
+ $request = $this->getRequest();
+ $params = $request->getPost();
+ Logging::info($params);
- $historyService = new Application_Service_HistoryService();
- $json = $historyService->editPlayedItem($params);
+ $historyService = new Application_Service_HistoryService();
+ $json = $historyService->editPlayedItem($params);
- if (isset($json["form"])) {
- $this->view->form = $json["form"];
- $json["form"] = $this->view->render('playouthistory/dialog.phtml');
+ if (isset($json['form'])) {
+ $this->view->form = $json['form'];
+ $json['form'] = $this->view->render('playouthistory/dialog.phtml');
- unset($this->view->form);
- }
+ unset($this->view->form);
+ }
- $this->_helper->json->sendJson($json);
- }
- catch (Exception $e) {
- Logging::info($e);
- Logging::info($e->getMessage());
- }
+ $this->_helper->json->sendJson($json);
+ } catch (Exception $e) {
+ Logging::info($e);
+ Logging::info($e->getMessage());
+ }
}
public function updateFileItemAction()
@@ -245,9 +240,9 @@ class PlayouthistoryController extends Zend_Controller_Action
$params = $request->getPost();
Logging::info($params);
- $historyService = new Application_Service_HistoryService();
- $json = $historyService->editPlayedFile($params);
+ $historyService = new Application_Service_HistoryService();
+ $json = $historyService->editPlayedFile($params);
- $this->_helper->json->sendJson($json);
+ $this->_helper->json->sendJson($json);
}
}
diff --git a/legacy/application/controllers/PlayouthistorytemplateController.php b/legacy/application/controllers/PlayouthistorytemplateController.php
index 72fea97d3..d1ae24bd7 100644
--- a/legacy/application/controllers/PlayouthistorytemplateController.php
+++ b/legacy/application/controllers/PlayouthistorytemplateController.php
@@ -10,138 +10,133 @@ class PlayouthistorytemplateController extends Zend_Controller_Action
->addActionContext('update-template', 'json')
->addActionContext('delete-template', 'json')
->addActionContext('set-template-default', 'json')
- ->initContext();
- }
-
- public function indexAction()
- {
- $CC_CONFIG = Config::getConfig();
- $baseUrl = Application_Common_OsPath::getBaseDir();
+ ->initContext()
+ ;
+ }
- Zend_Layout::getMvcInstance()->assign('parent_page', 'Analytics');
-
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/playouthistory/template.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headLink()->appendStylesheet($baseUrl.'css/history_styles.css?'.$CC_CONFIG['airtime_version']);
-
- $historyService = new Application_Service_HistoryService();
- $this->view->template_list = $historyService->getListItemTemplates();
- $this->view->template_file = $historyService->getFileTemplates();
- $this->view->configured = $historyService->getConfiguredTemplateIds();
- }
-
- public function configureTemplateAction() {
-
- $CC_CONFIG = Config::getConfig();
- $baseUrl = Application_Common_OsPath::getBaseDir();
+ public function indexAction()
+ {
+ $CC_CONFIG = Config::getConfig();
+ $baseUrl = Application_Common_OsPath::getBaseDir();
- Zend_Layout::getMvcInstance()->assign('parent_page', 'Analytics');
-
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/playouthistory/configuretemplate.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headLink()->appendStylesheet($baseUrl.'css/history_styles.css?'.$CC_CONFIG['airtime_version']);
-
- try {
-
- $templateId = $this->_getParam('id');
-
- $historyService = new Application_Service_HistoryService();
- $template = $historyService->loadTemplate($templateId);
-
- $templateType = $template["type"];
- $supportedTypes = $historyService->getSupportedTemplateTypes();
-
- if (!in_array($templateType, $supportedTypes)) {
- throw new Exception("Error: $templateType is not supported.");
- }
-
- $getMandatoryFields = "mandatory".ucfirst($templateType)."Fields";
- $mandatoryFields = $historyService->$getMandatoryFields();
-
- $this->view->template_id = $templateId;
- $this->view->template_name = $template["name"];
- $this->view->template_fields = $template["fields"];
- $this->view->template_type = $templateType;
- $this->view->fileMD = $historyService->getFileMetadataTypes();
- $this->view->fields = $historyService->getFieldTypes();
- $this->view->required_fields = $mandatoryFields;
- $this->view->configured = $historyService->getConfiguredTemplateIds();
- }
- catch (Exception $e) {
- Logging::info("Error?");
- Logging::info($e);
- Logging::info($e->getMessage());
-
- $this->_forward('index', 'playouthistorytemplate');
- }
- }
-
- public function createTemplateAction()
- {
- $templateType = $this->_getParam('type', null);
-
- $request = $this->getRequest();
- $params = $request->getPost();
-
- try {
- $historyService = new Application_Service_HistoryService();
- $supportedTypes = $historyService->getSupportedTemplateTypes();
-
- if (!in_array($templateType, $supportedTypes)) {
- throw new Exception("Error: $templateType is not supported.");
- }
-
- $id = $historyService->createTemplate($params);
-
- $this->view->url = $this->view->baseUrl("Playouthistorytemplate/configure-template/id/{$id}");
- }
- catch (Exception $e) {
- Logging::info($e);
- Logging::info($e->getMessage());
-
- $this->view->error = $e->getMessage();
- }
- }
-
- public function setTemplateDefaultAction()
- {
- $templateId = $this->_getParam('id', null);
-
- try {
- $historyService = new Application_Service_HistoryService();
- $historyService->setConfiguredTemplate($templateId);
- }
- catch (Exception $e) {
- Logging::info($e);
- Logging::info($e->getMessage());
- }
- }
-
- public function updateTemplateAction()
- {
- $templateId = $this->_getParam('id', null);
- $name = $this->_getParam('name', null);
- $fields = $this->_getParam('fields', array());
-
- try {
- $historyService = new Application_Service_HistoryService();
- $historyService->updateItemTemplate($templateId, $name, $fields);
- }
- catch (Exception $e) {
- Logging::info($e);
- Logging::info($e->getMessage());
- }
- }
-
- public function deleteTemplateAction()
- {
- $templateId = $this->_getParam('id');
-
- try {
- $historyService = new Application_Service_HistoryService();
- $historyService->deleteTemplate($templateId);
- }
- catch (Exception $e) {
- Logging::info($e);
- Logging::info($e->getMessage());
- }
- }
-}
\ No newline at end of file
+ Zend_Layout::getMvcInstance()->assign('parent_page', 'Analytics');
+
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/playouthistory/template.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/history_styles.css?' . $CC_CONFIG['airtime_version']);
+
+ $historyService = new Application_Service_HistoryService();
+ $this->view->template_list = $historyService->getListItemTemplates();
+ $this->view->template_file = $historyService->getFileTemplates();
+ $this->view->configured = $historyService->getConfiguredTemplateIds();
+ }
+
+ public function configureTemplateAction()
+ {
+ $CC_CONFIG = Config::getConfig();
+ $baseUrl = Application_Common_OsPath::getBaseDir();
+
+ Zend_Layout::getMvcInstance()->assign('parent_page', 'Analytics');
+
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/playouthistory/configuretemplate.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/history_styles.css?' . $CC_CONFIG['airtime_version']);
+
+ try {
+ $templateId = $this->_getParam('id');
+
+ $historyService = new Application_Service_HistoryService();
+ $template = $historyService->loadTemplate($templateId);
+
+ $templateType = $template['type'];
+ $supportedTypes = $historyService->getSupportedTemplateTypes();
+
+ if (!in_array($templateType, $supportedTypes)) {
+ throw new Exception("Error: {$templateType} is not supported.");
+ }
+
+ $getMandatoryFields = 'mandatory' . ucfirst($templateType) . 'Fields';
+ $mandatoryFields = $historyService->{$getMandatoryFields}();
+
+ $this->view->template_id = $templateId;
+ $this->view->template_name = $template['name'];
+ $this->view->template_fields = $template['fields'];
+ $this->view->template_type = $templateType;
+ $this->view->fileMD = $historyService->getFileMetadataTypes();
+ $this->view->fields = $historyService->getFieldTypes();
+ $this->view->required_fields = $mandatoryFields;
+ $this->view->configured = $historyService->getConfiguredTemplateIds();
+ } catch (Exception $e) {
+ Logging::info('Error?');
+ Logging::info($e);
+ Logging::info($e->getMessage());
+
+ $this->_forward('index', 'playouthistorytemplate');
+ }
+ }
+
+ public function createTemplateAction()
+ {
+ $templateType = $this->_getParam('type', null);
+
+ $request = $this->getRequest();
+ $params = $request->getPost();
+
+ try {
+ $historyService = new Application_Service_HistoryService();
+ $supportedTypes = $historyService->getSupportedTemplateTypes();
+
+ if (!in_array($templateType, $supportedTypes)) {
+ throw new Exception("Error: {$templateType} is not supported.");
+ }
+
+ $id = $historyService->createTemplate($params);
+
+ $this->view->url = $this->view->baseUrl("Playouthistorytemplate/configure-template/id/{$id}");
+ } catch (Exception $e) {
+ Logging::info($e);
+ Logging::info($e->getMessage());
+
+ $this->view->error = $e->getMessage();
+ }
+ }
+
+ public function setTemplateDefaultAction()
+ {
+ $templateId = $this->_getParam('id', null);
+
+ try {
+ $historyService = new Application_Service_HistoryService();
+ $historyService->setConfiguredTemplate($templateId);
+ } catch (Exception $e) {
+ Logging::info($e);
+ Logging::info($e->getMessage());
+ }
+ }
+
+ public function updateTemplateAction()
+ {
+ $templateId = $this->_getParam('id', null);
+ $name = $this->_getParam('name', null);
+ $fields = $this->_getParam('fields', []);
+
+ try {
+ $historyService = new Application_Service_HistoryService();
+ $historyService->updateItemTemplate($templateId, $name, $fields);
+ } catch (Exception $e) {
+ Logging::info($e);
+ Logging::info($e->getMessage());
+ }
+ }
+
+ public function deleteTemplateAction()
+ {
+ $templateId = $this->_getParam('id');
+
+ try {
+ $historyService = new Application_Service_HistoryService();
+ $historyService->deleteTemplate($templateId);
+ } catch (Exception $e) {
+ Logging::info($e);
+ Logging::info($e->getMessage());
+ }
+ }
+}
diff --git a/legacy/application/controllers/PluploadController.php b/legacy/application/controllers/PluploadController.php
index 5515a2cb9..b86739356 100644
--- a/legacy/application/controllers/PluploadController.php
+++ b/legacy/application/controllers/PluploadController.php
@@ -5,9 +5,10 @@ class PluploadController extends Zend_Controller_Action
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
- $ajaxContext->addActionContext('upload', 'json')
- ->addActionContext('recent-uploads', 'json')
- ->initContext();
+ $ajaxContext->addActionContext('upload', 'json')
+ ->addActionContext('recent-uploads', 'json')
+ ->initContext()
+ ;
}
public function indexAction()
@@ -17,16 +18,16 @@ class PluploadController extends Zend_Controller_Action
$baseUrl = Application_Common_OsPath::getBaseDir();
$locale = Application_Model_Preference::GetLocale();
- $this->view->headScript()->appendFile($baseUrl.'js/datatables/js/jquery.dataTables.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/plupload/plupload.full.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/plupload/jquery.plupload.queue.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/library/plupload.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/plupload/i18n/'.$locale.'.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/libs/dropzone.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/datatables/js/jquery.dataTables.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/plupload/plupload.full.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/plupload/jquery.plupload.queue.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/library/plupload.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/plupload/i18n/' . $locale . '.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/libs/dropzone.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headLink()->appendStylesheet($baseUrl.'css/plupload.queue.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/addmedia.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/dashboard.css?'.$CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/plupload.queue.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/addmedia.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/dashboard.css?' . $CC_CONFIG['airtime_version']);
$this->view->quotaLimitReached = false;
if (Application_Model_Systemstatus::isDiskOverQuota()) {
@@ -60,56 +61,56 @@ class PluploadController extends Zend_Controller_Action
$observed_csrf_token = $this->_getParam('csrf_token');
$expected_csrf_token = $current_namespace->authtoken;
- if($observed_csrf_token == $expected_csrf_token){
- $upload_dir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
+ if ($observed_csrf_token == $expected_csrf_token) {
+ $upload_dir = ini_get('upload_tmp_dir') . DIRECTORY_SEPARATOR . 'plupload';
$tempFilePath = Application_Model_StoredFile::uploadFile($upload_dir);
$tempFileName = basename($tempFilePath);
-
- $this->_helper->json->sendJson(array("jsonrpc" => "2.0", "tempfilepath" => $tempFileName));
- }else{
- $this->_helper->json->sendJson(array("jsonrpc" => "2.0", "valid" => false, "error" => "CSRF token did not match."));
+
+ $this->_helper->json->sendJson(['jsonrpc' => '2.0', 'tempfilepath' => $tempFileName]);
+ } else {
+ $this->_helper->json->sendJson(['jsonrpc' => '2.0', 'valid' => false, 'error' => 'CSRF token did not match.']);
}
}
public function recentUploadsAction()
{
- $request = $this->getRequest();
-
- $filter = $request->getParam('uploadFilter', "all");
+ $request = $this->getRequest();
+
+ $filter = $request->getParam('uploadFilter', 'all');
$limit = intval($request->getParam('iDisplayLength', 10));
$rowStart = intval($request->getParam('iDisplayStart', 0));
-
+
$recentUploadsQuery = CcFilesQuery::create();
//old propel 1.5 to reuse this query item (for counts/finds)
$recentUploadsQuery->keepQuery(true);
-
+
//Hide deleted files
$recentUploadsQuery->filterByDbFileExists(true);
-
+
$numTotalRecentUploads = $recentUploadsQuery->count();
$numTotalDisplayUploads = $numTotalRecentUploads;
-
- if ($filter == "pending") {
+
+ if ($filter == 'pending') {
$recentUploadsQuery->filterByDbImportStatus(1);
$numTotalDisplayUploads = $recentUploadsQuery->count();
- } else if ($filter == "failed") {
+ } elseif ($filter == 'failed') {
$recentUploadsQuery->filterByDbImportStatus(2);
$numTotalDisplayUploads = $recentUploadsQuery->count();
//TODO: Consider using array('min' => 200)) or something if we have multiple errors codes for failure.
}
-
+
$recentUploads = $recentUploadsQuery
- ->orderByDbUtime(Criteria::DESC)
- ->offset($rowStart)
- ->limit($limit)
- ->find();
-
- $uploadsArray = array();
- $utcTimezone = new DateTimeZone("UTC");
+ ->orderByDbUtime(Criteria::DESC)
+ ->offset($rowStart)
+ ->limit($limit)
+ ->find()
+ ;
+
+ $uploadsArray = [];
+ $utcTimezone = new DateTimeZone('UTC');
$displayTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
-
- foreach ($recentUploads as $upload)
- {
+
+ foreach ($recentUploads as $upload) {
$upload = $upload->toArray(BasePeer::TYPE_FIELDNAME);
//TODO: $this->sanitizeResponse($upload));
$upload['utime'] = new DateTime($upload['utime'], $utcTimezone);
@@ -119,7 +120,7 @@ class PluploadController extends Zend_Controller_Action
//TODO: Invoke sanitization here (MediaController's removeBlacklist stuff)
array_push($uploadsArray, $upload);
}
-
+
$this->view->sEcho = intval($request->getParam('sEcho'));
$this->view->iTotalDisplayRecords = $numTotalDisplayUploads;
$this->view->iTotalRecords = $numTotalRecentUploads;
@@ -127,7 +128,7 @@ class PluploadController extends Zend_Controller_Action
}
/**
- * get configured upload max size from php
+ * get configured upload max size from php.
*
* Pinched from Drupal: https://github.com/drupal/drupal/blob/4204b0b29a7318008f10765cf88114bf3ed21c32/core/includes/file.inc#L1099
*
@@ -135,10 +136,10 @@ class PluploadController extends Zend_Controller_Action
* way. I'm adding the method here since it's part of their core and I did
* not find an easy way to grab that thrrough composer in an isolated way.
*/
- private function file_upload_max_size() {
+ private function file_upload_max_size()
+ {
static $max_size = -1;
if ($max_size < 0) {
-
// Start with post_max_size.
$max_size = $this->bytes_to_int(ini_get('post_max_size'));
@@ -149,19 +150,23 @@ class PluploadController extends Zend_Controller_Action
$max_size = $upload_max;
}
}
+
return $max_size;
}
/**
- * Pinched from Drupal: https://github.com/drupal/drupal/blob/4204b0b29a7318008f10765cf88114bf3ed21c32/core/lib/Drupal/Component/Utility/Bytes.php#L27
+ * Pinched from Drupal: https://github.com/drupal/drupal/blob/4204b0b29a7318008f10765cf88114bf3ed21c32/core/lib/Drupal/Component/Utility/Bytes.php#L27.
*
* This is the real point of importing the Drupal solution. They have done
* an implementation for figuring out what the user specified in the
* post_max_size and upload_max_size configuration. Sadly php does not
* support a nice way to get at the results of this config after it is
* parsed by the engine, hence the below hack.
+ *
+ * @param mixed $size
*/
- private function bytes_to_int($size) {
+ private function bytes_to_int($size)
+ {
// Remove the non-unit characters from the size.
$unit = preg_replace('/[^bkmgtpezy]/i', '', $size);
// Remove the non-numeric characters from the size.
@@ -170,8 +175,8 @@ class PluploadController extends Zend_Controller_Action
// Find the position of the unit in the ordered string which is the power
// of magnitude to multiply a kilobyte by.
return round($size * pow(1024, stripos('bkmgtpezy', $unit[0])));
- } else {
- return round($size);
}
+
+ return round($size);
}
}
diff --git a/legacy/application/controllers/PodcastController.php b/legacy/application/controllers/PodcastController.php
index 628baf319..7821f5838 100644
--- a/legacy/application/controllers/PodcastController.php
+++ b/legacy/application/controllers/PodcastController.php
@@ -1,36 +1,36 @@
view->headScript();
AirtimeTableView::injectTableJavaScriptDependencies($headScript, $baseUrl, $CC_CONFIG['airtime_version']);
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/library/library.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/library/events/library_showbuilder.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/library/library.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/library/events/library_showbuilder.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/widgets/table.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/library/podcast.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/widgets/table.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/library/podcast.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headLink()->appendStylesheet($baseUrl.'css/datatables/css/ColVis.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/datatables/css/dataTables.colReorder.min.css?'.$CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/datatables/css/ColVis.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/datatables/css/dataTables.colReorder.min.css?' . $CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/station_podcast.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/dashboard.css?'.$CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/station_podcast.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/dashboard.css?' . $CC_CONFIG['airtime_version']);
}
/**
- * Renders the Station podcast view
+ * Renders the Station podcast view.
*/
- public function stationAction() {
-
+ public function stationAction()
+ {
$stationPodcastId = Application_Model_Preference::getStationPodcastId();
$podcast = Application_Service_PodcastService::getPodcastById($stationPodcastId);
$this->view->podcast = json_encode($podcast);
$this->view->form = new Application_Form_StationPodcast();
}
-
}
diff --git a/legacy/application/controllers/PreferenceController.php b/legacy/application/controllers/PreferenceController.php
index 8c7bbd7b7..37df2894f 100644
--- a/legacy/application/controllers/PreferenceController.php
+++ b/legacy/application/controllers/PreferenceController.php
@@ -2,21 +2,21 @@
class PreferenceController extends Zend_Controller_Action
{
-
public function init()
{
- /* Initialize action controller here */
+ // Initialize action controller here
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('server-browse', 'json')
- ->addActionContext('change-stor-directory', 'json')
- ->addActionContext('reload-watch-directory', 'json')
- ->addActionContext('remove-watch-directory', 'json')
- ->addActionContext('is-import-in-progress', 'json')
- ->addActionContext('change-stream-setting', 'json')
- ->addActionContext('get-liquidsoap-status', 'json')
- ->addActionContext('set-source-connection-url', 'json')
- ->addActionContext('get-admin-password-status', 'json')
- ->initContext();
+ ->addActionContext('change-stor-directory', 'json')
+ ->addActionContext('reload-watch-directory', 'json')
+ ->addActionContext('remove-watch-directory', 'json')
+ ->addActionContext('is-import-in-progress', 'json')
+ ->addActionContext('change-stream-setting', 'json')
+ ->addActionContext('get-liquidsoap-status', 'json')
+ ->addActionContext('set-source-connection-url', 'json')
+ ->addActionContext('get-admin-password-status', 'json')
+ ->initContext()
+ ;
}
public function indexAction()
@@ -28,54 +28,53 @@ class PreferenceController extends Zend_Controller_Action
$baseUrl = Application_Common_OsPath::getBaseDir();
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/preferences/preferences.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->statusMsg = "";
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/preferences/preferences.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->statusMsg = '';
$form = new Application_Form_Preferences();
- $values = array();
+ $values = [];
SessionHelper::reopenSessionForWriting();
if ($request->isPost()) {
$values = $request->getPost();
- if ($form->isValid($values))
- {
- Application_Model_Preference::SetHeadTitle($values["stationName"], $this->view);
- Application_Model_Preference::SetStationDescription($values["stationDescription"]);
- Application_Model_Preference::SetTrackTypeDefault($values["tracktypeDefault"]);
- Application_Model_Preference::SetDefaultCrossfadeDuration($values["stationDefaultCrossfadeDuration"]);
- Application_Model_Preference::SetDefaultFadeIn($values["stationDefaultFadeIn"]);
- Application_Model_Preference::SetDefaultFadeOut($values["stationDefaultFadeOut"]);
- Application_Model_Preference::SetPodcastAlbumOverride($values["podcastAlbumOverride"]);
- Application_Model_Preference::SetPodcastAutoSmartblock($values["podcastAutoSmartblock"]);
- Application_Model_Preference::SetIntroPlaylist($values["introPlaylistSelect"]);
- Application_Model_Preference::SetOutroPlaylist($values["outroPlaylistSelect"]);
- Application_Model_Preference::SetAllow3rdPartyApi($values["thirdPartyApi"]);
- Application_Model_Preference::SetAllowedCorsUrls($values["allowedCorsUrls"]);
- Application_Model_Preference::SetDefaultLocale($values["locale"]);
- Application_Model_Preference::SetDefaultTimezone($values["timezone"]);
- Application_Model_Preference::SetWeekStartDay($values["weekStartDay"]);
- Application_Model_Preference::setRadioPageDisplayLoginButton($values["radioPageLoginButton"]);
- Application_Model_Preference::SetFeaturePreviewMode($values["featurePreviewMode"]);
+ if ($form->isValid($values)) {
+ Application_Model_Preference::SetHeadTitle($values['stationName'], $this->view);
+ Application_Model_Preference::SetStationDescription($values['stationDescription']);
+ Application_Model_Preference::SetTrackTypeDefault($values['tracktypeDefault']);
+ Application_Model_Preference::SetDefaultCrossfadeDuration($values['stationDefaultCrossfadeDuration']);
+ Application_Model_Preference::SetDefaultFadeIn($values['stationDefaultFadeIn']);
+ Application_Model_Preference::SetDefaultFadeOut($values['stationDefaultFadeOut']);
+ Application_Model_Preference::SetPodcastAlbumOverride($values['podcastAlbumOverride']);
+ Application_Model_Preference::SetPodcastAutoSmartblock($values['podcastAutoSmartblock']);
+ Application_Model_Preference::SetIntroPlaylist($values['introPlaylistSelect']);
+ Application_Model_Preference::SetOutroPlaylist($values['outroPlaylistSelect']);
+ Application_Model_Preference::SetAllow3rdPartyApi($values['thirdPartyApi']);
+ Application_Model_Preference::SetAllowedCorsUrls($values['allowedCorsUrls']);
+ Application_Model_Preference::SetDefaultLocale($values['locale']);
+ Application_Model_Preference::SetDefaultTimezone($values['timezone']);
+ Application_Model_Preference::SetWeekStartDay($values['weekStartDay']);
+ Application_Model_Preference::setRadioPageDisplayLoginButton($values['radioPageLoginButton']);
+ Application_Model_Preference::SetFeaturePreviewMode($values['featurePreviewMode']);
$logoUploadElement = $form->getSubForm('preferences_general')->getElement('stationLogo');
$logoUploadElement->receive();
$imagePath = $logoUploadElement->getFileName();
// Only update the image logo if the new logo is non-empty
- if (!empty($imagePath) && $imagePath != "") {
+ if (!empty($imagePath) && $imagePath != '') {
Application_Model_Preference::SetStationLogo($imagePath);
}
- Application_Model_Preference::setTuneinEnabled($values["enable_tunein"]);
- Application_Model_Preference::setTuneinStationId($values["tunein_station_id"]);
- Application_Model_Preference::setTuneinPartnerKey($values["tunein_partner_key"]);
- Application_Model_Preference::setTuneinPartnerId($values["tunein_partner_id"]);
+ Application_Model_Preference::setTuneinEnabled($values['enable_tunein']);
+ Application_Model_Preference::setTuneinStationId($values['tunein_station_id']);
+ Application_Model_Preference::setTuneinPartnerKey($values['tunein_partner_key']);
+ Application_Model_Preference::setTuneinPartnerId($values['tunein_partner_id']);
- $this->view->statusMsg = "". _("Preferences updated.")." ";
+ $this->view->statusMsg = "" . _('Preferences updated.') . ' ';
$form = new Application_Form_Preferences();
$this->view->form = $form;
- //$this->_helper->json->sendJson(array("valid"=>"true", "html"=>$this->view->render('preference/index.phtml')));
+ //$this->_helper->json->sendJson(array("valid"=>"true", "html"=>$this->view->render('preference/index.phtml')));
} else {
$this->view->form = $form;
//$this->_helper->json->sendJson(array("valid"=>"false", "html"=>$this->view->render('preference/index.phtml')));
@@ -86,7 +85,8 @@ class PreferenceController extends Zend_Controller_Action
$this->view->form = $form;
}
- public function stationPodcastSettingsAction() {
+ public function stationPodcastSettingsAction()
+ {
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
@@ -101,11 +101,11 @@ class PreferenceController extends Zend_Controller_Action
$stationPodcast = PodcastQuery::create()->findOneByDbId(Application_Model_Preference::getStationPodcastId());
$key = Application_Model_Preference::getStationPodcastDownloadKey();
$url = Application_Common_HTTPHelper::getStationUrl() .
- (((int) $values->stationPodcastPrivacy) ? "feeds/station-rss?sharing_token=$key" : "feeds/station-rss");
+ (((int) $values->stationPodcastPrivacy) ? "feeds/station-rss?sharing_token={$key}" : 'feeds/station-rss');
$stationPodcast->setDbUrl($url)->save();
Application_Model_Preference::setStationPodcastPrivacy($values->stationPodcastPrivacy);
- $this->_helper->json->sendJson(array("url" => $url));
+ $this->_helper->json->sendJson(['url' => $url]);
}
public function directoryConfigAction()
@@ -122,11 +122,12 @@ class PreferenceController extends Zend_Controller_Action
if (!SecurityHelper::verifyCSRFToken($this->_getParam('csrf_token'))) {
Logging::error(__FILE__ . ': Invalid CSRF token');
- $this->_helper->json->sendJson(array("jsonrpc" => "2.0", "valid" => false, "error" => "CSRF token did not match."));
+ $this->_helper->json->sendJson(['jsonrpc' => '2.0', 'valid' => false, 'error' => 'CSRF token did not match.']);
+
return;
}
- Application_Model_Preference::SetStationLogo("");
+ Application_Model_Preference::SetStationLogo('');
}
public function streamSettingAction()
@@ -139,17 +140,17 @@ class PreferenceController extends Zend_Controller_Action
$baseUrl = Application_Common_OsPath::getBaseDir();
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/preferences/streamsetting.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/preferences/streamsetting.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
SessionHelper::reopenSessionForWriting();
- $name_map = array(
- 'ogg' => 'Ogg Vorbis',
- 'fdkaac' => 'AAC+',
- 'aac' => 'AAC',
- 'opus' => 'Opus',
- 'mp3' => 'MP3',
- );
+ $name_map = [
+ 'ogg' => 'Ogg Vorbis',
+ 'fdkaac' => 'AAC+',
+ 'aac' => 'AAC',
+ 'opus' => 'Opus',
+ 'mp3' => 'MP3',
+ ];
$num_of_stream = intval(Application_Model_Preference::GetNumOfStreams());
$form = new Application_Form_StreamSetting();
@@ -160,11 +161,11 @@ class PreferenceController extends Zend_Controller_Action
$form->addElement($csrf_element);
$live_stream_subform = new Application_Form_LiveStreamingPreferences();
- $form->addSubForm($live_stream_subform, "live_stream_subform");
+ $form->addSubForm($live_stream_subform, 'live_stream_subform');
// get predefined type and bitrate from pref table
$temp_types = Application_Model_Preference::GetStreamType();
- $stream_types = array();
+ $stream_types = [];
foreach ($temp_types as $type) {
$type = strtolower(trim($type));
if (isset($name_map[$type])) {
@@ -177,10 +178,10 @@ class PreferenceController extends Zend_Controller_Action
$temp_bitrate = Application_Model_Preference::GetStreamBitrate();
$max_bitrate = intval(Application_Model_Preference::GetMaxBitrate());
- $stream_bitrates = array();
+ $stream_bitrates = [];
foreach ($temp_bitrate as $type) {
if (intval($type) <= $max_bitrate) {
- $stream_bitrates[trim($type)] = strtoupper(trim($type))." kbit/s";
+ $stream_bitrates[trim($type)] = strtoupper(trim($type)) . ' kbit/s';
}
}
@@ -188,7 +189,7 @@ class PreferenceController extends Zend_Controller_Action
$setting = Application_Model_StreamSetting::getStreamSetting();
$form->setSetting($setting);
- for ($i=1; $i<=$num_of_stream; $i++) {
+ for ($i = 1; $i <= $num_of_stream; ++$i) {
$subform = new Application_Form_StreamSettingSubForm();
$subform->setPrefix($i);
$subform->setSetting($setting);
@@ -196,7 +197,7 @@ class PreferenceController extends Zend_Controller_Action
$subform->setStreamBitrates($stream_bitrates);
$subform->startForm();
$subform->toggleState();
- $form->addSubForm($subform, "s".$i."_subform");
+ $form->addSubForm($subform, 's' . $i . '_subform');
}
$live_stream_subform->updateVariables();
@@ -208,36 +209,36 @@ class PreferenceController extends Zend_Controller_Action
* $form->isValid() is expecting it in
*/
$postData = explode('&', $params['data']);
- $s1_data = array();
- $s2_data = array();
- $s3_data = array();
- $s4_data = array();
- $values = array();
- foreach($postData as $k=>$v) {
+ $s1_data = [];
+ $s2_data = [];
+ $s3_data = [];
+ $s4_data = [];
+ $values = [];
+ foreach ($postData as $k => $v) {
$v = explode('=', urldecode($v));
- if (strpos($v[0], "s1_data") !== false) {
+ if (strpos($v[0], 's1_data') !== false) {
/* In this case $v[0] may be 's1_data[enable]' , for example.
* We only want the 'enable' part
*/
preg_match('/\[(.*)\]/', $v[0], $matches);
$s1_data[$matches[1]] = $v[1];
- } elseif (strpos($v[0], "s2_data") !== false) {
+ } elseif (strpos($v[0], 's2_data') !== false) {
preg_match('/\[(.*)\]/', $v[0], $matches);
$s2_data[$matches[1]] = $v[1];
- } elseif (strpos($v[0], "s3_data") !== false) {
- preg_match('/\[(.*)\]/', $v[0], $matches);
+ } elseif (strpos($v[0], 's3_data') !== false) {
+ preg_match('/\[(.*)\]/', $v[0], $matches);
$s3_data[$matches[1]] = $v[1];
- } elseif (strpos($v[0], "s4_data") !== false) {
- preg_match('/\[(.*)\]/', $v[0], $matches);
+ } elseif (strpos($v[0], 's4_data') !== false) {
+ preg_match('/\[(.*)\]/', $v[0], $matches);
$s4_data[$matches[1]] = $v[1];
} else {
$values[$v[0]] = $v[1];
}
}
- $values["s1_data"] = $s1_data;
- $values["s2_data"] = $s2_data;
- $values["s3_data"] = $s3_data;
- $values["s4_data"] = $s4_data;
+ $values['s1_data'] = $s1_data;
+ $values['s2_data'] = $s2_data;
+ $values['s3_data'] = $s3_data;
+ $values['s4_data'] = $s4_data;
if ($form->isValid($values)) {
Application_Model_StreamSetting::setStreamSetting($values);
@@ -245,68 +246,67 @@ class PreferenceController extends Zend_Controller_Action
/* If the admin password values are empty then we should not
* set the pseudo password ('xxxxxx') on the front-end
*/
- $s1_set_admin_pass = !empty($values["s1_data"]["admin_pass"]);
- $s2_set_admin_pass = !empty($values["s2_data"]["admin_pass"]);
- $s3_set_admin_pass = !empty($values["s3_data"]["admin_pass"]);
- $s4_set_admin_pass = !empty($values["s4_data"]["admin_pass"]);
+ $s1_set_admin_pass = !empty($values['s1_data']['admin_pass']);
+ $s2_set_admin_pass = !empty($values['s2_data']['admin_pass']);
+ $s3_set_admin_pass = !empty($values['s3_data']['admin_pass']);
+ $s4_set_admin_pass = !empty($values['s4_data']['admin_pass']);
// this goes into cc_pref table
$this->setStreamPreferences($values);
// compare new values with current value
- $changeRGenabled = Application_Model_Preference::GetEnableReplayGain() != $values["enableReplayGain"];
- $changeRGmodifier = Application_Model_Preference::getReplayGainModifier() != $values["replayGainModifier"];
+ $changeRGenabled = Application_Model_Preference::GetEnableReplayGain() != $values['enableReplayGain'];
+ $changeRGmodifier = Application_Model_Preference::getReplayGainModifier() != $values['replayGainModifier'];
if ($changeRGenabled || $changeRGmodifier) {
- Application_Model_Preference::SetEnableReplayGain($values["enableReplayGain"]);
- Application_Model_Preference::setReplayGainModifier($values["replayGainModifier"]);
- $md = array('schedule' => Application_Model_Schedule::getSchedule());
- Application_Model_RabbitMq::SendMessageToPypo("update_schedule", $md);
+ Application_Model_Preference::SetEnableReplayGain($values['enableReplayGain']);
+ Application_Model_Preference::setReplayGainModifier($values['replayGainModifier']);
+ $md = ['schedule' => Application_Model_Schedule::getSchedule()];
+ Application_Model_RabbitMq::SendMessageToPypo('update_schedule', $md);
//Application_Model_RabbitMq::PushSchedule();
}
// pulling this from the 2.5.x branch
if (!Application_Model_Preference::GetMasterDjConnectionUrlOverride()) {
- $master_connection_url = "http://".$_SERVER['SERVER_NAME'].":".$values["master_source_port"].$values["master_source_mount"];
- if (empty($values["master_source_port"]) || empty($values["master_source_mount"])) {
+ $master_connection_url = 'http://' . $_SERVER['SERVER_NAME'] . ':' . $values['master_source_port'] . $values['master_source_mount'];
+ if (empty($values['master_source_port']) || empty($values['master_source_mount'])) {
Application_Model_Preference::SetMasterDJSourceConnectionURL('N/A');
} else {
Application_Model_Preference::SetMasterDJSourceConnectionURL($master_connection_url);
}
} else {
- Application_Model_Preference::SetMasterDJSourceConnectionURL($values["master_source_host"]);
+ Application_Model_Preference::SetMasterDJSourceConnectionURL($values['master_source_host']);
}
if (!Application_Model_Preference::GetLiveDjConnectionUrlOverride()) {
- $live_connection_url = "http://".$_SERVER['SERVER_NAME'].":".$values["show_source_port"].$values["show_source_mount"];
- if (empty($values["show_source_port"]) || empty($values["show_source_mount"])) {
+ $live_connection_url = 'http://' . $_SERVER['SERVER_NAME'] . ':' . $values['show_source_port'] . $values['show_source_mount'];
+ if (empty($values['show_source_port']) || empty($values['show_source_mount'])) {
Application_Model_Preference::SetLiveDJSourceConnectionURL('N/A');
} else {
Application_Model_Preference::SetLiveDJSourceConnectionURL($live_connection_url);
}
} else {
- Application_Model_Preference::SetLiveDJSourceConnectionURL($values["show_source_host"]);
+ Application_Model_Preference::SetLiveDJSourceConnectionURL($values['show_source_host']);
}
-
- Application_Model_StreamSetting::setMasterLiveStreamPort($values["master_source_port"]);
- Application_Model_StreamSetting::setMasterLiveStreamMountPoint($values["master_source_mount"]);
- Application_Model_StreamSetting::setDjLiveStreamPort($values["show_source_port"]);
- Application_Model_StreamSetting::setDjLiveStreamMountPoint($values["show_source_mount"]);
+ Application_Model_StreamSetting::setMasterLiveStreamPort($values['master_source_port']);
+ Application_Model_StreamSetting::setMasterLiveStreamMountPoint($values['master_source_mount']);
+ Application_Model_StreamSetting::setDjLiveStreamPort($values['show_source_port']);
+ Application_Model_StreamSetting::setDjLiveStreamMountPoint($values['show_source_mount']);
Application_Model_StreamSetting::setOffAirMeta($values['offAirMeta']);
// store stream update timestamp
Application_Model_Preference::SetStreamUpdateTimestamp();
- $data = array();
+ $data = [];
$info = Application_Model_StreamSetting::getStreamSetting();
$data['setting'] = $info;
- for ($i=1; $i<=$num_of_stream; $i++) {
- Application_Model_StreamSetting::setLiquidsoapError($i, "waiting");
+ for ($i = 1; $i <= $num_of_stream; ++$i) {
+ Application_Model_StreamSetting::setLiquidsoapError($i, 'waiting');
}
- Application_Model_RabbitMq::SendMessageToPypo("update_stream_setting", $data);
- $this->view->statusMsg = ""._("Stream Setting Updated.")." ";
+ Application_Model_RabbitMq::SendMessageToPypo('update_stream_setting', $data);
+ $this->view->statusMsg = "" . _('Stream Setting Updated.') . ' ';
}
}
@@ -315,61 +315,61 @@ class PreferenceController extends Zend_Controller_Action
$this->view->form = $form;
if ($request->isPost()) {
if ($form->isValid($values)) {
- $this->_helper->json->sendJson(array(
- "valid" => "true",
- "html" => $this->view->render('preference/stream-setting.phtml'),
- "s1_set_admin_pass" => $s1_set_admin_pass,
- "s2_set_admin_pass" => $s2_set_admin_pass,
- "s3_set_admin_pass" => $s3_set_admin_pass,
- "s4_set_admin_pass" => $s4_set_admin_pass,
- ));
+ $this->_helper->json->sendJson([
+ 'valid' => 'true',
+ 'html' => $this->view->render('preference/stream-setting.phtml'),
+ 's1_set_admin_pass' => $s1_set_admin_pass,
+ 's2_set_admin_pass' => $s2_set_admin_pass,
+ 's3_set_admin_pass' => $s3_set_admin_pass,
+ 's4_set_admin_pass' => $s4_set_admin_pass,
+ ]);
} else {
- $this->_helper->json->sendJson(array("valid" => "false", "html" => $this->view->render('preference/stream-setting.phtml')));
+ $this->_helper->json->sendJson(['valid' => 'false', 'html' => $this->view->render('preference/stream-setting.phtml')]);
}
}
}
/**
- * Set stream settings preferences
+ * Set stream settings preferences.
*
* @param array $values stream setting preference values
*/
- private function setStreamPreferences($values) {
+ private function setStreamPreferences($values)
+ {
Application_Model_Preference::setUsingCustomStreamSettings($values['customStreamSettings']);
Application_Model_Preference::SetStreamLabelFormat($values['streamFormat']);
- Application_Model_Preference::SetLiveStreamMasterUsername($values["master_username"]);
- Application_Model_Preference::SetLiveStreamMasterPassword($values["master_password"]);
- Application_Model_Preference::SetDefaultTransitionFade($values["transition_fade"]);
- Application_Model_Preference::SetAutoTransition($values["auto_transition"]);
- Application_Model_Preference::SetAutoSwitch($values["auto_switch"]);
-
+ Application_Model_Preference::SetLiveStreamMasterUsername($values['master_username']);
+ Application_Model_Preference::SetLiveStreamMasterPassword($values['master_password']);
+ Application_Model_Preference::SetDefaultTransitionFade($values['transition_fade']);
+ Application_Model_Preference::SetAutoTransition($values['auto_transition']);
+ Application_Model_Preference::SetAutoSwitch($values['auto_switch']);
}
public function serverBrowseAction()
{
$request = $this->getRequest();
- $path = $request->getParam("path", null);
+ $path = $request->getParam('path', null);
- $result = array();
+ $result = [];
if (is_null($path)) {
- $element = array();
- $element["name"] = _("path should be specified");
- $element["isFolder"] = false;
- $element["isError"] = true;
+ $element = [];
+ $element['name'] = _('path should be specified');
+ $element['isFolder'] = false;
+ $element['isError'] = true;
$result[$path] = $element;
} else {
- $path = $path.'/';
+ $path = $path . '/';
$handle = opendir($path);
if ($handle !== false) {
while (false !== ($file = readdir($handle))) {
- if ($file != "." && $file != "..") {
+ if ($file != '.' && $file != '..') {
//only show directories that aren't private.
- if (is_dir($path.$file) && substr($file, 0, 1) != ".") {
- $element = array();
- $element["name"] = $file;
- $element["isFolder"] = true;
- $element["isError"] = false;
+ if (is_dir($path . $file) && substr($file, 0, 1) != '.') {
+ $element = [];
+ $element['name'] = $file;
+ $element['isFolder'] = true;
+ $element['isError'] = false;
$result[$file] = $element;
}
}
@@ -383,14 +383,14 @@ class PreferenceController extends Zend_Controller_Action
public function changeStorDirectoryAction()
{
- $chosen = $this->getRequest()->getParam("dir");
- $element = $this->getRequest()->getParam("element");
+ $chosen = $this->getRequest()->getParam('dir');
+ $element = $this->getRequest()->getParam('element');
$watched_dirs_form = new Application_Form_WatchedDirPreferences();
$res = Application_Model_MusicDir::setStorDir($chosen);
if ($res['code'] != 0) {
- $watched_dirs_form->populate(array('storageFolder' => $chosen));
- $watched_dirs_form->getElement($element)->setErrors(array($res['error']));
+ $watched_dirs_form->populate(['storageFolder' => $chosen]);
+ $watched_dirs_form->getElement($element)->setErrors([$res['error']]);
}
$this->view->subform = $watched_dirs_form->render();
@@ -398,14 +398,14 @@ class PreferenceController extends Zend_Controller_Action
public function reloadWatchDirectoryAction()
{
- $chosen = $this->getRequest()->getParam("dir");
- $element = $this->getRequest()->getParam("element");
+ $chosen = $this->getRequest()->getParam('dir');
+ $element = $this->getRequest()->getParam('element');
$watched_dirs_form = new Application_Form_WatchedDirPreferences();
$res = Application_Model_MusicDir::addWatchedDir($chosen);
if ($res['code'] != 0) {
- $watched_dirs_form->populate(array('watchedFolder' => $chosen));
- $watched_dirs_form->getElement($element)->setErrors(array($res['error']));
+ $watched_dirs_form->populate(['watchedFolder' => $chosen]);
+ $watched_dirs_form->getElement($element)->setErrors([$res['error']]);
}
$this->view->subform = $watched_dirs_form->render();
@@ -415,17 +415,17 @@ class PreferenceController extends Zend_Controller_Action
{
$dir_path = $this->getRequest()->getParam('dir');
$dir = Application_Model_MusicDir::getDirByPath($dir_path);
- $data = array( 'directory' => $dir->getDirectory(),
- 'id' => $dir->getId());
+ $data = ['directory' => $dir->getDirectory(),
+ 'id' => $dir->getId(), ];
Application_Model_RabbitMq::SendMessageToMediaMonitor('rescan_watch', $data);
- Logging::info("Unhiding all files belonging to:: $dir_path");
+ Logging::info("Unhiding all files belonging to:: {$dir_path}");
$dir->unhideFiles();
$this->_helper->json->sendJson(null);
}
public function removeWatchDirectoryAction()
{
- $chosen = $this->getRequest()->getParam("dir");
+ $chosen = $this->getRequest()->getParam('dir');
$dir = Application_Model_MusicDir::removeWatchedDir($chosen);
@@ -437,7 +437,7 @@ class PreferenceController extends Zend_Controller_Action
{
$now = time();
$res = false;
- if (Application_Model_Preference::GetImportTimestamp()+10 > $now) {
+ if (Application_Model_Preference::GetImportTimestamp() + 10 > $now) {
$res = true;
}
$this->_helper->json->sendJson($res);
@@ -445,15 +445,15 @@ class PreferenceController extends Zend_Controller_Action
public function getLiquidsoapStatusAction()
{
- $out = array();
+ $out = [];
$num_of_stream = intval(Application_Model_Preference::GetNumOfStreams());
- for ($i=1; $i<=$num_of_stream; $i++) {
+ for ($i = 1; $i <= $num_of_stream; ++$i) {
$status = Application_Model_StreamSetting::getLiquidsoapError($i);
- $status = $status == NULL?_("Problem with Liquidsoap..."):$status;
+ $status = $status == null ? _('Problem with Liquidsoap...') : $status;
if (!Application_Model_StreamSetting::getStreamEnabled($i)) {
- $status = "N/A";
+ $status = 'N/A';
}
- $out[] = array("id"=>$i, "status"=>$status);
+ $out[] = ['id' => $i, 'status' => $status];
}
$this->_helper->json->sendJson($out);
}
@@ -463,9 +463,9 @@ class PreferenceController extends Zend_Controller_Action
SessionHelper::reopenSessionForWriting();
$request = $this->getRequest();
- $type = $request->getParam("type", null);
- $url = urldecode($request->getParam("url", null));
- $override = $request->getParam("override", false);
+ $type = $request->getParam('type', null);
+ $url = urldecode($request->getParam('url', null));
+ $override = $request->getParam('override', false);
if ($type == 'masterdj') {
Application_Model_Preference::SetMasterDJSourceConnectionURL($url);
@@ -482,13 +482,13 @@ class PreferenceController extends Zend_Controller_Action
{
SessionHelper::reopenSessionForWriting();
- $out = array();
+ $out = [];
$num_of_stream = intval(Application_Model_Preference::GetNumOfStreams());
- for ($i=1; $i<=$num_of_stream; $i++) {
- if (Application_Model_StreamSetting::getAdminPass('s'.$i)=='') {
- $out["s".$i] = false;
+ for ($i = 1; $i <= $num_of_stream; ++$i) {
+ if (Application_Model_StreamSetting::getAdminPass('s' . $i) == '') {
+ $out['s' . $i] = false;
} else {
- $out["s".$i] = true;
+ $out['s' . $i] = true;
}
}
$this->_helper->json->sendJson($out);
@@ -501,7 +501,8 @@ class PreferenceController extends Zend_Controller_Action
if (!SecurityHelper::verifyCSRFToken($this->_getParam('csrf_token'))) {
Logging::error(__FILE__ . ': Invalid CSRF token');
- $this->_helper->json->sendJson(array("jsonrpc" => "2.0", "valid" => false, "error" => "CSRF token did not match."));
+ $this->_helper->json->sendJson(['jsonrpc' => '2.0', 'valid' => false, 'error' => 'CSRF token did not match.']);
+
return;
}
@@ -510,8 +511,10 @@ class PreferenceController extends Zend_Controller_Action
$method = $_SERVER['REQUEST_METHOD'];
if (!($method == 'POST')) {
$this->getResponse()
- ->setHttpResponseCode(405)
- ->appendBody(_("Request method not accepted") . ": $method");
+ ->setHttpResponseCode(405)
+ ->appendBody(_('Request method not accepted') . ": {$method}")
+ ;
+
return;
}
@@ -520,16 +523,19 @@ class PreferenceController extends Zend_Controller_Action
$this->deleteStoredFiles();
$this->getResponse()
- ->setHttpResponseCode(200)
- ->appendBody("OK");
+ ->setHttpResponseCode(200)
+ ->appendBody('OK')
+ ;
}
- private function deleteFutureScheduleItems() {
- $utcTimezone = new DateTimeZone("UTC");
- $nowDateTime = new DateTime("now", $utcTimezone);
+ private function deleteFutureScheduleItems()
+ {
+ $utcTimezone = new DateTimeZone('UTC');
+ $nowDateTime = new DateTime('now', $utcTimezone);
$scheduleItems = CcScheduleQuery::create()
->filterByDbEnds($nowDateTime->format(DEFAULT_TIMESTAMP_FORMAT), Criteria::GREATER_THAN)
- ->find();
+ ->find()
+ ;
// Delete all the schedule items
foreach ($scheduleItems as $i) {
@@ -549,20 +555,22 @@ class PreferenceController extends Zend_Controller_Action
}
}
- private function deleteCloudFiles() {
+ private function deleteCloudFiles()
+ {
try {
$CC_CONFIG = Config::getConfig();
- foreach ($CC_CONFIG["supportedStorageBackends"] as $storageBackend) {
+ foreach ($CC_CONFIG['supportedStorageBackends'] as $storageBackend) {
$proxyStorageBackend = new ProxyStorageBackend($storageBackend);
$proxyStorageBackend->deleteAllCloudFileObjects();
}
- } catch(Exception $e) {
+ } catch (Exception $e) {
Logging::info($e->getMessage());
}
}
- private function deleteStoredFiles() {
+ private function deleteStoredFiles()
+ {
// Delete all files from the database
$files = CcFilesQuery::create()->find();
foreach ($files as $file) {
@@ -572,5 +580,4 @@ class PreferenceController extends Zend_Controller_Action
$storedFile->delete(true);
}
}
-
}
diff --git a/legacy/application/controllers/RenderController.php b/legacy/application/controllers/RenderController.php
index be190a963..08e76ed21 100644
--- a/legacy/application/controllers/RenderController.php
+++ b/legacy/application/controllers/RenderController.php
@@ -1,8 +1,9 @@
view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
@@ -12,9 +13,9 @@ class RenderController extends Zend_Controller_Action {
$this->view->csrf = $csrf_element;
}
- public function podcastUrlDialogAction() {
+ public function podcastUrlDialogAction()
+ {
$path = 'podcast/podcast_url_dialog.phtml';
- $this->_helper->json->sendJson(array("html"=>$this->view->render($path)));
+ $this->_helper->json->sendJson(['html' => $this->view->render($path)]);
}
-
-}
\ No newline at end of file
+}
diff --git a/legacy/application/controllers/ScheduleController.php b/legacy/application/controllers/ScheduleController.php
index cc15f8c61..37bf23945 100644
--- a/legacy/application/controllers/ScheduleController.php
+++ b/legacy/application/controllers/ScheduleController.php
@@ -2,43 +2,43 @@
class ScheduleController extends Zend_Controller_Action
{
-
- protected $sched_sess = null;
+ protected $sched_sess;
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('event-feed', 'json')
- ->addActionContext('event-feed-preload', 'json')
- ->addActionContext('make-context-menu', 'json')
- ->addActionContext('add-show-dialog', 'json')
- ->addActionContext('add-show', 'json')
- ->addActionContext('edit-show', 'json')
- ->addActionContext('move-show', 'json')
- ->addActionContext('resize-show', 'json')
- ->addActionContext('delete-show-instance', 'json')
- ->addActionContext('show-content-dialog', 'json')
- ->addActionContext('clear-show', 'json')
- ->addActionContext('get-current-playlist', 'json')
- ->addActionContext('remove-group', 'json')
- ->addActionContext('populate-show-form', 'json')
- ->addActionContext('populate-repeating-show-instance-form', 'json')
- ->addActionContext('delete-show', 'json')
- ->addActionContext('cancel-current-show', 'json')
- ->addActionContext('get-form', 'json')
- ->addActionContext('upload-to-sound-cloud', 'json')
- ->addActionContext('content-context-menu', 'json')
- ->addActionContext('set-time-scale', 'json')
- ->addActionContext('set-time-interval', 'json')
- ->addActionContext('edit-repeating-show-instance', 'json')
- ->addActionContext('dj-edit-show', 'json')
- ->addActionContext('calculate-duration', 'json')
- ->addActionContext('get-current-show', 'json')
- ->addActionContext('update-future-is-scheduled', 'json')
- ->addActionContext('localize-start-end-time', 'json')
- ->initContext();
+ ->addActionContext('event-feed-preload', 'json')
+ ->addActionContext('make-context-menu', 'json')
+ ->addActionContext('add-show-dialog', 'json')
+ ->addActionContext('add-show', 'json')
+ ->addActionContext('edit-show', 'json')
+ ->addActionContext('move-show', 'json')
+ ->addActionContext('resize-show', 'json')
+ ->addActionContext('delete-show-instance', 'json')
+ ->addActionContext('show-content-dialog', 'json')
+ ->addActionContext('clear-show', 'json')
+ ->addActionContext('get-current-playlist', 'json')
+ ->addActionContext('remove-group', 'json')
+ ->addActionContext('populate-show-form', 'json')
+ ->addActionContext('populate-repeating-show-instance-form', 'json')
+ ->addActionContext('delete-show', 'json')
+ ->addActionContext('cancel-current-show', 'json')
+ ->addActionContext('get-form', 'json')
+ ->addActionContext('upload-to-sound-cloud', 'json')
+ ->addActionContext('content-context-menu', 'json')
+ ->addActionContext('set-time-scale', 'json')
+ ->addActionContext('set-time-interval', 'json')
+ ->addActionContext('edit-repeating-show-instance', 'json')
+ ->addActionContext('dj-edit-show', 'json')
+ ->addActionContext('calculate-duration', 'json')
+ ->addActionContext('get-current-show', 'json')
+ ->addActionContext('update-future-is-scheduled', 'json')
+ ->addActionContext('localize-start-end-time', 'json')
+ ->initContext()
+ ;
- $this->sched_sess = new Zend_Session_Namespace("schedule");
+ $this->sched_sess = new Zend_Session_Namespace('schedule');
}
public function indexAction()
@@ -53,66 +53,66 @@ class ScheduleController extends Zend_Controller_Action
$events = json_encode($scheduleController->view->events);
$this->view->headScript()->appendScript(
- "var calendarPref = {};\n".
- "calendarPref.weekStart = ".Application_Model_Preference::GetWeekStartDay().";\n".
- "calendarPref.timestamp = ".time().";\n".
- "calendarPref.timezoneOffset = ".Application_Common_DateHelper::getUserTimezoneOffset().";\n".
- "calendarPref.timeScale = '".Application_Model_Preference::GetCalendarTimeScale()."';\n".
- "calendarPref.timeInterval = ".Application_Model_Preference::GetCalendarTimeInterval().";\n".
- "calendarPref.weekStartDay = ".Application_Model_Preference::GetWeekStartDay().";\n".
- "var calendarEvents = $events;"
+ "var calendarPref = {};\n" .
+ 'calendarPref.weekStart = ' . Application_Model_Preference::GetWeekStartDay() . ";\n" .
+ 'calendarPref.timestamp = ' . time() . ";\n" .
+ 'calendarPref.timezoneOffset = ' . Application_Common_DateHelper::getUserTimezoneOffset() . ";\n" .
+ "calendarPref.timeScale = '" . Application_Model_Preference::GetCalendarTimeScale() . "';\n" .
+ 'calendarPref.timeInterval = ' . Application_Model_Preference::GetCalendarTimeInterval() . ";\n" .
+ 'calendarPref.weekStartDay = ' . Application_Model_Preference::GetWeekStartDay() . ";\n" .
+ "var calendarEvents = {$events};"
);
- $this->view->headScript()->appendFile($baseUrl.'js/contextmenu/jquery.contextMenu.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/contextmenu/jquery.contextMenu.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
//full-calendar-functions.js requires this variable, so that datePicker widget can be offset to server time instead of client time
//this should be as a default, however with our new drop down timezone changing for shows, we should reset this offset then??
- $this->view->headScript()->appendScript("var timezoneOffset = ".Application_Common_DateHelper::getStationTimezoneOffset()."; //in seconds");
+ $this->view->headScript()->appendScript('var timezoneOffset = ' . Application_Common_DateHelper::getStationTimezoneOffset() . '; //in seconds');
//set offset to ensure it loads last
- $this->view->headScript()->offsetSetFile(90, $baseUrl.'js/airtime/schedule/full-calendar-functions.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headScript()->offsetSetFile(90, $baseUrl . 'js/airtime/schedule/full-calendar-functions.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/fullcalendar/fullcalendar.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/timepicker/jquery.ui.timepicker.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/colorpicker/js/colorpicker.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/fullcalendar/fullcalendar.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/timepicker/jquery.ui.timepicker.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/colorpicker/js/colorpicker.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
// This block needs to be added before the add-show.js script
- $this->view->headScript()->appendFile($baseUrl.'js/libs/dayjs.min.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/libs/utc.min.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/libs/timezone.min.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/libs/dayjs.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/libs/utc.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/libs/timezone.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/schedule/add-show.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->offsetSetFile(100, $baseUrl.'js/airtime/schedule/schedule.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/blockui/jquery.blockUI.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/schedule/add-show.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->offsetSetFile(100, $baseUrl . 'js/airtime/schedule/schedule.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/blockui/jquery.blockUI.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headLink()->appendStylesheet($baseUrl.'css/jquery.ui.timepicker.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/fullcalendar.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/colorpicker/css/colorpicker.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/add-show.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/jquery.contextMenu.css?'.$CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/jquery.ui.timepicker.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/fullcalendar.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/colorpicker/css/colorpicker.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/add-show.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/jquery.contextMenu.css?' . $CC_CONFIG['airtime_version']);
//Start Show builder JS/CSS requirements
$headScript = $this->view->headScript();
AirtimeTableView::injectTableJavaScriptDependencies($headScript, $baseUrl, $CC_CONFIG['airtime_version']);
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/utilities/utilities.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/utilities/utilities.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/buttons/buttons.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/library/events/library_showbuilder.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/library/library.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/showbuilder/builder.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/buttons/buttons.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/library/events/library_showbuilder.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/library/library.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/showbuilder/builder.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headLink()->appendStylesheet($baseUrl.'css/media_library.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/jquery.contextMenu.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/datatables/css/ColVis.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/datatables/css/dataTables.colReorder.min.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/showbuilder.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/dashboard.css?'.$CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/media_library.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/jquery.contextMenu.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/datatables/css/ColVis.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/datatables/css/dataTables.colReorder.min.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/showbuilder.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/dashboard.css?' . $CC_CONFIG['airtime_version']);
//End Show builder JS/CSS requirements
$this->createShowFormAction(true);
$user = Application_Model_User::getCurrentUser();
- if ($user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
+ if ($user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER])) {
$this->view->preloadShowForm = true;
}
@@ -127,12 +127,15 @@ class ScheduleController extends Zend_Controller_Action
$userTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
$start = new DateTime($this->_getParam('start', null), $userTimezone);
- $start->setTimezone(new DateTimeZone("UTC"));
+ $start->setTimezone(new DateTimeZone('UTC'));
$end = new DateTime($this->_getParam('end', null), $userTimezone);
- $end->setTimezone(new DateTimeZone("UTC"));
+ $end->setTimezone(new DateTimeZone('UTC'));
- $events = &Application_Model_Show::getFullCalendarEvents($start, $end,
- $currentUser->isAdminOrPM());
+ $events = &Application_Model_Show::getFullCalendarEvents(
+ $start,
+ $end,
+ $currentUser->isAdminOrPM()
+ );
$this->view->events = $events;
}
@@ -141,17 +144,17 @@ class ScheduleController extends Zend_Controller_Action
{
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id);
- $editable = $user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
+ $editable = $user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER]);
$calendar_interval = Application_Model_Preference::GetCalendarTimeScale();
- if ($calendar_interval == "agendaDay") {
+ if ($calendar_interval == 'agendaDay') {
list($start, $end) = Application_Model_Show::getStartEndCurrentDayView();
- } else if ($calendar_interval == "agendaWeek") {
+ } elseif ($calendar_interval == 'agendaWeek') {
list($start, $end) = Application_Model_Show::getStartEndCurrentWeekView();
- } else if ($calendar_interval == "month") {
+ } elseif ($calendar_interval == 'month') {
list($start, $end) = Application_Model_Show::getStartEndCurrentMonthPlusView();
} else {
- Logging::error("Invalid Calendar Interval '$calendar_interval'");
+ Logging::error("Invalid Calendar Interval '{$calendar_interval}'");
}
$events = &Application_Model_Show::getFullCalendarEvents($start, $end, $editable);
@@ -162,7 +165,7 @@ class ScheduleController extends Zend_Controller_Action
{
$currentShow = Application_Model_Show::getCurrentShow();
if (!empty($currentShow)) {
- $this->view->si_id = $currentShow[0]["instance_id"];
+ $this->view->si_id = $currentShow[0]['instance_id'];
$this->view->current_show = true;
} else {
$this->view->current_show = false;
@@ -174,20 +177,22 @@ class ScheduleController extends Zend_Controller_Action
$deltaDay = $this->_getParam('day');
$deltaMin = $this->_getParam('min');
- $log_vars = array();
- $log_vars["url"] = $_SERVER['HTTP_HOST'];
- $log_vars["action"] = "schedule/move-show";
- $log_vars["params"] = array();
- $log_vars["params"]["instance id"] = $this->_getParam('showInstanceId');
- $log_vars["params"]["delta day"] = $deltaDay;
- $log_vars["params"]["delta minute"] = $deltaMin;
+ $log_vars = [];
+ $log_vars['url'] = $_SERVER['HTTP_HOST'];
+ $log_vars['action'] = 'schedule/move-show';
+ $log_vars['params'] = [];
+ $log_vars['params']['instance id'] = $this->_getParam('showInstanceId');
+ $log_vars['params']['delta day'] = $deltaDay;
+ $log_vars['params']['delta minute'] = $deltaMin;
Logging::info($log_vars);
try {
$service_calendar = new Application_Service_CalendarService(
- $this->_getParam('showInstanceId'));
+ $this->_getParam('showInstanceId')
+ );
} catch (Exception $e) {
$this->view->show_error = true;
+
return false;
}
@@ -204,19 +209,19 @@ class ScheduleController extends Zend_Controller_Action
$showId = $this->_getParam('showId');
$instanceId = $this->_getParam('instanceId');
- $log_vars = array();
- $log_vars["url"] = $_SERVER['HTTP_HOST'];
- $log_vars["action"] = "schedule/resize-show";
- $log_vars["params"] = array();
- $log_vars["params"]["instance id"] = $instanceId;
- $log_vars["params"]["delta day"] = $deltaDay;
- $log_vars["params"]["delta minute"] = $deltaMin;
+ $log_vars = [];
+ $log_vars['url'] = $_SERVER['HTTP_HOST'];
+ $log_vars['action'] = 'schedule/resize-show';
+ $log_vars['params'] = [];
+ $log_vars['params']['instance id'] = $instanceId;
+ $log_vars['params']['delta day'] = $deltaDay;
+ $log_vars['params']['delta minute'] = $deltaMin;
Logging::info($log_vars);
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id);
- if ($user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
+ if ($user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER])) {
try {
$show = new Application_Model_Show($showId);
} catch (Exception $e) {
@@ -236,11 +241,11 @@ class ScheduleController extends Zend_Controller_Action
{
$instanceId = $this->_getParam('id');
- $log_vars = array();
- $log_vars["url"] = $_SERVER['HTTP_HOST'];
- $log_vars["action"] = "schedule/delete-show-instance";
- $log_vars["params"] = array();
- $log_vars["params"]["instance id"] = $instanceId;
+ $log_vars = [];
+ $log_vars['url'] = $_SERVER['HTTP_HOST'];
+ $log_vars['action'] = 'schedule/delete-show-instance';
+ $log_vars['params'] = [];
+ $log_vars['params']['instance id'] = $instanceId;
Logging::info($log_vars);
$service_show = new Application_Service_ShowService();
@@ -265,17 +270,18 @@ class ScheduleController extends Zend_Controller_Action
{
$instanceId = $this->_getParam('id');
- $log_vars = array();
- $log_vars["url"] = $_SERVER['HTTP_HOST'];
- $log_vars["action"] = "schedule/clear-show";
- $log_vars["params"] = array();
- $log_vars["params"]["instance id"] = $instanceId;
+ $log_vars = [];
+ $log_vars['url'] = $_SERVER['HTTP_HOST'];
+ $log_vars['action'] = 'schedule/clear-show';
+ $log_vars['params'] = [];
+ $log_vars['params']['instance id'] = $instanceId;
Logging::info($log_vars);
$service_scheduler = new Application_Service_SchedulerService();
if (!$service_scheduler->emptyShowContent($instanceId)) {
$this->view->show_error = true;
+
return false;
}
}
@@ -288,7 +294,7 @@ class ScheduleController extends Zend_Controller_Action
$front = Zend_Controller_Front::getInstance();
$scheduleController = new ScheduleController($front->getRequest(), $front->getResponse());
$scheduleController->getCurrentPlaylistAction();
- echo(json_encode($scheduleController->view));
+ echo json_encode($scheduleController->view);
}
public function getCurrentPlaylistAction()
@@ -297,49 +303,49 @@ class ScheduleController extends Zend_Controller_Action
$show = Application_Model_Show::getCurrentShow();
- /* Convert all UTC times to localtime before sending back to user. */
- $range["schedulerTime"] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range["schedulerTime"]);
+ // Convert all UTC times to localtime before sending back to user.
+ $range['schedulerTime'] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range['schedulerTime']);
- if (isset($range["previous"])) {
- $range["previous"]["starts"] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range["previous"]["starts"]);
- $range["previous"]["ends"] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range["previous"]["ends"]);
+ if (isset($range['previous'])) {
+ $range['previous']['starts'] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range['previous']['starts']);
+ $range['previous']['ends'] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range['previous']['ends']);
}
- if (isset($range["current"])) {
- if (isset($range["current"]["metadata"])) {
- $get_artwork = FileDataHelper::getArtworkData($range["current"]["metadata"]["artwork"], 256);
- $range["current"]["metadata"]["artwork_data"] = $get_artwork;
+ if (isset($range['current'])) {
+ if (isset($range['current']['metadata'])) {
+ $get_artwork = FileDataHelper::getArtworkData($range['current']['metadata']['artwork'], 256);
+ $range['current']['metadata']['artwork_data'] = $get_artwork;
}
- $range["current"]["starts"] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range["current"]["starts"]);
- $range["current"]["ends"] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range["current"]["ends"]);
+ $range['current']['starts'] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range['current']['starts']);
+ $range['current']['ends'] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range['current']['ends']);
}
- if (isset($range["next"])) {
- $range["next"]["starts"] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range["next"]["starts"]);
- $range["next"]["ends"] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range["next"]["ends"]);
+ if (isset($range['next'])) {
+ $range['next']['starts'] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range['next']['starts']);
+ $range['next']['ends'] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range['next']['ends']);
}
Application_Common_DateHelper::convertTimestamps(
- $range["currentShow"],
- array("starts", "ends", "start_timestamp", "end_timestamp"),
- "user"
+ $range['currentShow'],
+ ['starts', 'ends', 'start_timestamp', 'end_timestamp'],
+ 'user'
);
Application_Common_DateHelper::convertTimestamps(
- $range["nextShow"],
- array("starts", "ends", "start_timestamp", "end_timestamp"),
- "user"
+ $range['nextShow'],
+ ['starts', 'ends', 'start_timestamp', 'end_timestamp'],
+ 'user'
);
//TODO: Add timezone and timezoneOffset back into the ApiController's results.
- $range["timezone"] = Application_Common_DateHelper::getUserTimezoneAbbreviation();
- $range["timezoneOffset"] = Application_Common_DateHelper::getUserTimezoneOffset();
+ $range['timezone'] = Application_Common_DateHelper::getUserTimezoneAbbreviation();
+ $range['timezoneOffset'] = Application_Common_DateHelper::getUserTimezoneOffset();
- $source_status = array();
- $switch_status = array();
- $live_dj = Application_Model_Preference::GetSourceStatus("live_dj");
- $master_dj = Application_Model_Preference::GetSourceStatus("master_dj");
+ $source_status = [];
+ $switch_status = [];
+ $live_dj = Application_Model_Preference::GetSourceStatus('live_dj');
+ $master_dj = Application_Model_Preference::GetSourceStatus('master_dj');
- $scheduled_play_switch = Application_Model_Preference::GetSourceSwitchStatus("scheduled_play");
- $live_dj_switch = Application_Model_Preference::GetSourceSwitchStatus("live_dj");
- $master_dj_switch = Application_Model_Preference::GetSourceSwitchStatus("master_dj");
+ $scheduled_play_switch = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play');
+ $live_dj_switch = Application_Model_Preference::GetSourceSwitchStatus('live_dj');
+ $master_dj_switch = Application_Model_Preference::GetSourceSwitchStatus('master_dj');
//might not be the correct place to implement this but for now let's just do it here
$source_status['live_dj_source'] = $live_dj;
@@ -352,12 +358,13 @@ class ScheduleController extends Zend_Controller_Action
$this->view->switch_status = $switch_status;
$this->view->entries = $range;
- $this->view->show_name = isset($show[0])?$show[0]["name"]:"";
+ $this->view->show_name = isset($show[0]) ? $show[0]['name'] : '';
}
public function showContentDialogAction()
{
$showInstanceId = $this->_getParam('id');
+
try {
$show = new Application_Model_ShowInstance($showInstanceId);
} catch (Exception $e) {
@@ -380,14 +387,16 @@ class ScheduleController extends Zend_Controller_Action
//convert from UTC to user's timezone for display.
$displayTimeZone = new DateTimeZone(Application_Model_Preference::GetTimezone());
- $originalDateTime = new DateTime($originalShowStart, new DateTimeZone("UTC"));
+ $originalDateTime = new DateTime($originalShowStart, new DateTimeZone('UTC'));
$originalDateTime->setTimezone($displayTimeZone);
$this->view->additionalShowInfo =
- sprintf(_("Rebroadcast of show %s from %s at %s"),
+ sprintf(
+ _('Rebroadcast of show %s from %s at %s'),
$originalShowName,
- $originalDateTime->format("l, F jS"),
- $originalDateTime->format("G:i"));
+ $originalDateTime->format('l, F jS'),
+ $originalDateTime->format('G:i')
+ );
}
$this->view->showLength = $show->getShowLength();
$this->view->timeFilled = $show->getTimeScheduled();
@@ -409,7 +418,7 @@ class ScheduleController extends Zend_Controller_Action
$service_showForm->delegateShowInstanceFormPopulation($forms);
$this->view->addNewShow = false;
- $this->view->action = "edit-repeating-show-instance";
+ $this->view->action = 'edit-repeating-show-instance';
$this->view->newForm = $this->view->render('schedule/add-show-form.phtml');
}
@@ -434,7 +443,7 @@ class ScheduleController extends Zend_Controller_Action
}
}
- $this->view->action = "edit-show";
+ $this->view->action = 'edit-show';
$this->view->newForm = $this->view->render('schedule/add-show-form.phtml');
$this->view->entries = 5;
}
@@ -451,26 +460,29 @@ class ScheduleController extends Zend_Controller_Action
}
}
- public function editRepeatingShowInstanceAction(){
+ public function editRepeatingShowInstanceAction()
+ {
$js = $this->_getParam('data');
- $data = array();
+ $data = [];
//need to convert from serialized jQuery array.
foreach ($js as $j) {
- $data[$j["name"]] = $j["value"];
+ $data[$j['name']] = $j['value'];
}
- $data['add_show_hosts'] = $this->_getParam('hosts');
+ $data['add_show_hosts'] = $this->_getParam('hosts');
- $log_vars = array();
- $log_vars["url"] = $_SERVER['HTTP_HOST'];
- $log_vars["action"] = "schedule/edit-repeating-show-instance";
- $log_vars["params"] = array();
- $log_vars["params"]["form_data"] = $data;
+ $log_vars = [];
+ $log_vars['url'] = $_SERVER['HTTP_HOST'];
+ $log_vars['action'] = 'schedule/edit-repeating-show-instance';
+ $log_vars['params'] = [];
+ $log_vars['params']['form_data'] = $data;
Logging::info($log_vars);
$service_showForm = new Application_Service_ShowFormService(
- $data["add_show_id"], $data["add_show_instance_id"]);
+ $data['add_show_id'],
+ $data['add_show_instance_id']
+ );
$service_show = new Application_Service_ShowService(null, $data);
$forms = $this->createShowFormAction();
@@ -478,23 +490,28 @@ class ScheduleController extends Zend_Controller_Action
list($data, $validateStartDate, $validateStartTime, $originalShowStartDateTime) =
$service_showForm->preEditShowValidationCheck($data);
- if ($service_showForm->validateShowForms($forms, $data, $validateStartDate,
- $originalShowStartDateTime, true, $data["add_show_instance_id"])) {
-
+ if ($service_showForm->validateShowForms(
+ $forms,
+ $data,
+ $validateStartDate,
+ $originalShowStartDateTime,
+ true,
+ $data['add_show_instance_id']
+ )) {
$service_show->editRepeatingShowInstance($data);
$this->view->addNewShow = true;
$this->view->newForm = $this->view->render('schedule/add-show-form.phtml');
- } else {
+ } else {
if (!$validateStartDate) {
- $this->view->when->getElement('add_show_start_date')->setOptions(array('disabled' => true));
+ $this->view->when->getElement('add_show_start_date')->setOptions(['disabled' => true]);
}
if (!$validateStartTime) {
- $this->view->when->getElement('add_show_start_time')->setOptions(array('disabled' => true));
+ $this->view->when->getElement('add_show_start_time')->setOptions(['disabled' => true]);
}
- $this->view->rr->getElement('add_show_record')->setOptions(array('disabled' => true));
+ $this->view->rr->getElement('add_show_record')->setOptions(['disabled' => true]);
$this->view->addNewShow = false;
- $this->view->action = "edit-repeating-show-instance";
+ $this->view->action = 'edit-repeating-show-instance';
$this->view->form = $this->view->render('schedule/add-show-form.phtml');
}
}
@@ -502,30 +519,31 @@ class ScheduleController extends Zend_Controller_Action
public function editShowAction()
{
$js = $this->_getParam('data');
- $data = array();
+ $data = [];
//need to convert from serialized jQuery array.
foreach ($js as $j) {
- $data[$j["name"]] = $j["value"];
+ $data[$j['name']] = $j['value'];
}
$service_showForm = new Application_Service_ShowFormService(
- $data["add_show_id"]);
+ $data['add_show_id']
+ );
$service_show = new Application_Service_ShowService(null, $data, true);
//TODO: move this to js
- $data['add_show_hosts'] = $this->_getParam('hosts');
- $data['add_show_day_check'] = $this->_getParam('days');
+ $data['add_show_hosts'] = $this->_getParam('hosts');
+ $data['add_show_day_check'] = $this->_getParam('days');
- if ($data['add_show_day_check'] == "") {
+ if ($data['add_show_day_check'] == '') {
$data['add_show_day_check'] = null;
}
- $log_vars = array();
- $log_vars["url"] = $_SERVER['HTTP_HOST'];
- $log_vars["action"] = "schedule/edit-show";
- $log_vars["params"] = array();
- $log_vars["params"]["form_data"] = $data;
+ $log_vars = [];
+ $log_vars['url'] = $_SERVER['HTTP_HOST'];
+ $log_vars['action'] = 'schedule/edit-show';
+ $log_vars['params'] = [];
+ $log_vars['params']['form_data'] = $data;
Logging::info($log_vars);
$forms = $this->createShowFormAction();
@@ -533,24 +551,30 @@ class ScheduleController extends Zend_Controller_Action
list($data, $validateStartDate, $validateStartTime, $originalShowStartDateTime) =
$service_showForm->preEditShowValidationCheck($data);
- if ($service_showForm->validateShowForms($forms, $data, $validateStartDate,
- $originalShowStartDateTime, true, $data["add_show_instance_id"])) {
+ if ($service_showForm->validateShowForms(
+ $forms,
+ $data,
+ $validateStartDate,
+ $originalShowStartDateTime,
+ true,
+ $data['add_show_instance_id']
+ )) {
// Get the show ID from the show service to pass as a parameter to the RESTful ShowImageController
$this->view->showId = $service_show->addUpdateShow($data);
- $this->view->addNewShow = true;
+ $this->view->addNewShow = true;
$this->view->newForm = $this->view->render('schedule/add-show-form.phtml');
} else {
if (!$validateStartDate) {
- $this->view->when->getElement('add_show_start_date')->setOptions(array('disabled' => true));
+ $this->view->when->getElement('add_show_start_date')->setOptions(['disabled' => true]);
}
if (!$validateStartTime) {
- $this->view->when->getElement('add_show_start_time')->setOptions(array('disabled' => true));
+ $this->view->when->getElement('add_show_start_time')->setOptions(['disabled' => true]);
}
//$this->view->rr->getElement('add_show_record')->setOptions(array('disabled' => true));
$this->view->addNewShow = false;
- $this->view->action = "edit-show";
+ $this->view->action = 'edit-show';
$this->view->form = $this->view->render('schedule/add-show-form.phtml');
}
}
@@ -560,63 +584,61 @@ class ScheduleController extends Zend_Controller_Action
$service_showForm = new Application_Service_ShowFormService(null);
$js = $this->_getParam('data');
- $data = array();
+ $data = [];
//need to convert from serialized jQuery array.
foreach ($js as $j) {
- $data[$j["name"]] = $j["value"];
+ $data[$j['name']] = $j['value'];
}
$service_show = new Application_Service_ShowService(null, $data);
// TODO: move this to js
- $data['add_show_hosts'] = $this->_getParam('hosts');
- $data['add_show_day_check'] = $this->_getParam('days');
+ $data['add_show_hosts'] = $this->_getParam('hosts');
+ $data['add_show_day_check'] = $this->_getParam('days');
- if ($data['add_show_day_check'] == "") {
+ if ($data['add_show_day_check'] == '') {
$data['add_show_day_check'] = null;
}
- $log_vars = array();
- $log_vars["url"] = $_SERVER['HTTP_HOST'];
- $log_vars["action"] = "schedule/add-show";
- $log_vars["params"] = array();
- $log_vars["params"]["form_data"] = $data;
+ $log_vars = [];
+ $log_vars['url'] = $_SERVER['HTTP_HOST'];
+ $log_vars['action'] = 'schedule/add-show';
+ $log_vars['params'] = [];
+ $log_vars['params']['form_data'] = $data;
Logging::info($log_vars);
$forms = $this->createShowFormAction();
$this->view->addNewShow = true;
- if ($data['add_show_start_now'] == "now") {
-
+ if ($data['add_show_start_now'] == 'now') {
//have to use the timezone the user has entered in the form to check past/present
- $showTimezone = new DateTimeZone($data["add_show_timezone"]);
- $nowDateTime = new DateTime("now", $showTimezone);
+ $showTimezone = new DateTimeZone($data['add_show_timezone']);
+ $nowDateTime = new DateTime('now', $showTimezone);
//$showStartDateTime = new DateTime($start_time, $showTimezone);
//$showEndDateTime = new DateTime($end_time, $showTimezone);
- $data['add_show_start_time'] = $nowDateTime->format("H:i");
- $data['add_show_start_date'] = $nowDateTime->format("Y-m-d");
+ $data['add_show_start_time'] = $nowDateTime->format('H:i');
+ $data['add_show_start_date'] = $nowDateTime->format('Y-m-d');
}
-
if ($service_showForm->validateShowForms($forms, $data)) {
- // Get the show ID from the show service to pass as a parameter to the RESTful ShowImageController
- $this->view->showId = $service_show->addUpdateShow($data);
+ // Get the show ID from the show service to pass as a parameter to the RESTful ShowImageController
+ $this->view->showId = $service_show->addUpdateShow($data);
//send new show forms to the user
$this->createShowFormAction(true);
$this->view->newForm = $this->view->render('schedule/add-show-form.phtml');
- Logging::debug("Show creation succeeded");
+ Logging::debug('Show creation succeeded');
} else {
- $this->view->form = $this->view->render('schedule/add-show-form.phtml');
- Logging::debug("Show creation failed");
+ $this->view->form = $this->view->render('schedule/add-show-form.phtml');
+ Logging::debug('Show creation failed');
}
}
- public function createShowFormAction($populateDefaults=false)
+ public function createShowFormAction($populateDefaults = false)
{
$service_showForm = new Application_Service_ShowFormService();
@@ -625,19 +647,22 @@ class ScheduleController extends Zend_Controller_Action
// populate forms with default values
if ($populateDefaults) {
$service_showForm->populateNewShowForms(
- $forms["what"], $forms["when"], $forms["repeats"]);
+ $forms['what'],
+ $forms['when'],
+ $forms['repeats']
+ );
}
- $this->view->what = $forms["what"];
- $this->view->autoplaylist = $forms["autoplaylist"];
- $this->view->when = $forms["when"];
- $this->view->repeats = $forms["repeats"];
- $this->view->live = $forms["live"];
- $this->view->rr = $forms["record"];
- $this->view->absoluteRebroadcast = $forms["abs_rebroadcast"];
- $this->view->rebroadcast = $forms["rebroadcast"];
- $this->view->who = $forms["who"];
- $this->view->style = $forms["style"];
+ $this->view->what = $forms['what'];
+ $this->view->autoplaylist = $forms['autoplaylist'];
+ $this->view->when = $forms['when'];
+ $this->view->repeats = $forms['repeats'];
+ $this->view->live = $forms['live'];
+ $this->view->rr = $forms['record'];
+ $this->view->absoluteRebroadcast = $forms['abs_rebroadcast'];
+ $this->view->rebroadcast = $forms['rebroadcast'];
+ $this->view->who = $forms['who'];
+ $this->view->style = $forms['style'];
return $forms;
}
@@ -646,11 +671,11 @@ class ScheduleController extends Zend_Controller_Action
{
$instanceId = $this->_getParam('id');
- $log_vars = array();
- $log_vars["url"] = $_SERVER['HTTP_HOST'];
- $log_vars["action"] = "schedule/delete-show";
- $log_vars["params"] = array();
- $log_vars["params"]["instance id"] = $instanceId;
+ $log_vars = [];
+ $log_vars['url'] = $_SERVER['HTTP_HOST'];
+ $log_vars['action'] = 'schedule/delete-show';
+ $log_vars['params'] = [];
+ $log_vars['params']['instance id'] = $instanceId;
Logging::info($log_vars);
$service_show = new Application_Service_ShowService();
@@ -664,16 +689,16 @@ class ScheduleController extends Zend_Controller_Action
public function cancelCurrentShowAction()
{
- $log_vars = array();
- $log_vars["url"] = $_SERVER['HTTP_HOST'];
- $log_vars["action"] = "schedule/cancel-current-show";
- $log_vars["params"] = array();
- $log_vars["params"]["instance id"] = $this->_getParam('id');
+ $log_vars = [];
+ $log_vars['url'] = $_SERVER['HTTP_HOST'];
+ $log_vars['action'] = 'schedule/cancel-current-show';
+ $log_vars['params'] = [];
+ $log_vars['params']['instance id'] = $this->_getParam('id');
Logging::info($log_vars);
$user = Application_Model_User::getCurrentUser();
- if ($user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
+ if ($user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER])) {
$id = $this->_getParam('id');
try {
@@ -681,8 +706,8 @@ class ScheduleController extends Zend_Controller_Action
$scheduler->cancelShow($id);
Application_Model_StoredFile::updatePastFilesIsScheduled();
// send kick out source stream signal to pypo
- $data = array("sourcename"=>"live_dj");
- Application_Model_RabbitMq::SendMessageToPypo("disconnect_source", $data);
+ $data = ['sourcename' => 'live_dj'];
+ Application_Model_RabbitMq::SendMessageToPypo('disconnect_source', $data);
} catch (Exception $e) {
$this->view->error = $e->getMessage();
Logging::info($e->getMessage());
@@ -705,10 +730,10 @@ class ScheduleController extends Zend_Controller_Action
$file = Application_Model_StoredFile::RecallById($file_id);
$baseUrl = $this->getRequest()->getBaseUrl();
- $url = $file->getRelativeFileUrl($baseUrl).'download/true';
- $menu = array();
- $menu[] = array('action' => array('type' => 'gourl', 'url' => $url),
- 'title' => _('Download'));
+ $url = $file->getRelativeFileUrl($baseUrl) . 'download/true';
+ $menu = [];
+ $menu[] = ['action' => ['type' => 'gourl', 'url' => $url],
+ 'title' => _('Download'), ];
//returns format jjmenu is looking for.
$this->_helper->json->sendJson($menu);
@@ -723,7 +748,7 @@ class ScheduleController extends Zend_Controller_Action
Application_Model_Preference::SetCalendarTimeScale($this->_getParam('timeScale'));
}
- /**
+ /**
* Sets the user specific preference for which time interval to use in Calendar.
* This is only being used by schedule.js at the moment.
*/
@@ -734,14 +759,15 @@ class ScheduleController extends Zend_Controller_Action
public function calculateDurationAction()
{
- $start = $this->_getParam('startTime');
- $end = $this->_getParam('endTime');
- $timezone = $this->_getParam('timezone');
+ $start = $this->_getParam('startTime');
+ $end = $this->_getParam('endTime');
+ $timezone = $this->_getParam('timezone');
$service_showForm = new Application_Service_ShowFormService();
$result = $service_showForm->calculateDuration($start, $end, $timezone);
echo Zend_Json::encode($result);
+
exit();
}
@@ -752,22 +778,29 @@ class ScheduleController extends Zend_Controller_Action
$scheduleService = new Application_Service_SchedulerService();
$redrawLibTable = $scheduleService->updateFutureIsScheduled($schedId, false);
- $this->_helper->json->sendJson(array("redrawLibTable" => $redrawLibTable));
+ $this->_helper->json->sendJson(['redrawLibTable' => $redrawLibTable]);
}
public function localizeStartEndTimeAction()
{
$newTimezone = $this->_getParam('newTimezone');
$oldTimezone = $this->_getParam('oldTimezone');
- $localTime = array();
+ $localTime = [];
- $localTime["start"] = Application_Service_ShowFormService::localizeDateTime(
- $this->_getParam('startDate'), $this->_getParam('startTime'), $newTimezone, $oldTimezone);
+ $localTime['start'] = Application_Service_ShowFormService::localizeDateTime(
+ $this->_getParam('startDate'),
+ $this->_getParam('startTime'),
+ $newTimezone,
+ $oldTimezone
+ );
- $localTime["end"] = Application_Service_ShowFormService::localizeDateTime(
- $this->_getParam('endDate'), $this->_getParam('endTime'), $newTimezone, $oldTimezone);
+ $localTime['end'] = Application_Service_ShowFormService::localizeDateTime(
+ $this->_getParam('endDate'),
+ $this->_getParam('endTime'),
+ $newTimezone,
+ $oldTimezone
+ );
$this->_helper->json->sendJson($localTime);
}
-
}
diff --git a/legacy/application/controllers/SetupController.php b/legacy/application/controllers/SetupController.php
index 24ca9d8fa..97d2a7d17 100644
--- a/legacy/application/controllers/SetupController.php
+++ b/legacy/application/controllers/SetupController.php
@@ -1,7 +1,6 @@
isPost()) {
-
$formData = $request->getPost();
if ($form->isValid($formData)) {
$userService = new Application_Service_UserService();
$currentUser = $userService->getCurrentUser();
$currentUserId = $currentUser->getDbId();
-
- Application_Model_Preference::SetUserTimezone($formData["setup_timezone"], $currentUserId);
- Application_Model_Preference::SetDefaultTimezone($formData["setup_timezone"]);
- Application_Model_Preference::SetUserLocale($formData["setup_language"], $currentUserId);
- Application_Model_Preference::SetDefaultLocale($formData["setup_language"]);
+ Application_Model_Preference::SetUserTimezone($formData['setup_timezone'], $currentUserId);
+ Application_Model_Preference::SetDefaultTimezone($formData['setup_timezone']);
+
+ Application_Model_Preference::SetUserLocale($formData['setup_language'], $currentUserId);
+ Application_Model_Preference::SetDefaultLocale($formData['setup_language']);
Application_Model_Preference::setLangTimezoneSetupComplete(true);
@@ -39,5 +37,4 @@ class SetupController extends Zend_Controller_Action
}
$this->_redirect('/showbuilder');
}
-
-}
\ No newline at end of file
+}
diff --git a/legacy/application/controllers/ShowbuilderController.php b/legacy/application/controllers/ShowbuilderController.php
index fa69c06d8..e6fe39787 100644
--- a/legacy/application/controllers/ShowbuilderController.php
+++ b/legacy/application/controllers/ShowbuilderController.php
@@ -2,18 +2,18 @@
class ShowbuilderController extends Zend_Controller_Action
{
-
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('schedule-move', 'json')
- ->addActionContext('schedule-add', 'json')
- ->addActionContext('schedule-remove', 'json')
- ->addActionContext('builder-dialog', 'json')
- ->addActionContext('check-builder-feed', 'json')
- ->addActionContext('builder-feed', 'json')
- ->addActionContext('context-menu', 'json')
- ->initContext();
+ ->addActionContext('schedule-add', 'json')
+ ->addActionContext('schedule-remove', 'json')
+ ->addActionContext('builder-dialog', 'json')
+ ->addActionContext('check-builder-feed', 'json')
+ ->addActionContext('builder-feed', 'json')
+ ->addActionContext('context-menu', 'json')
+ ->initContext()
+ ;
}
public function indexAction()
@@ -24,46 +24,46 @@ class ShowbuilderController extends Zend_Controller_Action
//$this->_helper->layout->setLayout("showbuilder");
- $this->view->headScript()->appendScript("localStorage.setItem( 'user-type', '$userType' );");
+ $this->view->headScript()->appendScript("localStorage.setItem( 'user-type', '{$userType}' );");
$this->view->headLink()->appendStylesheet($baseUrl . 'css/redmond/jquery-ui-1.8.8.custom.css?' . $CC_CONFIG['airtime_version']);
- $this->view->headScript()->appendFile($baseUrl.'js/contextmenu/jquery.contextMenu.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/contextmenu/jquery.contextMenu.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/blockui/jquery.blockUI.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/buttons/buttons.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/utilities/utilities.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/blockui/jquery.blockUI.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/buttons/buttons.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/utilities/utilities.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headLink()->appendStylesheet($baseUrl.'css/media_library.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/jquery.contextMenu.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/datatables/css/ColVis.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/datatables/css/dataTables.colReorder.min.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/library/library.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/library/events/library_showbuilder.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/media_library.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/jquery.contextMenu.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/datatables/css/ColVis.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/datatables/css/dataTables.colReorder.min.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/library/library.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/library/events/library_showbuilder.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$headScript = $this->view->headScript();
AirtimeTableView::injectTableJavaScriptDependencies($headScript, $baseUrl, $CC_CONFIG['airtime_version']);
// PLUPLOAD
- $this->view->headScript()->appendFile($baseUrl.'js/libs/dropzone.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/libs/dropzone.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/timepicker/jquery.ui.timepicker.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/showbuilder/tabs.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/showbuilder/builder.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/showbuilder/main_builder.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/timepicker/jquery.ui.timepicker.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/showbuilder/tabs.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/showbuilder/builder.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/showbuilder/main_builder.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
// MEDIA BUILDER
- $this->view->headScript()->appendFile($baseUrl.'js/libs/dayjs.min.js','text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/libs/utc.min.js','text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/libs/timezone.min.js','text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/library/spl.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/library/podcast.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/library/publish.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/playlist/smart_blockbuilder.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
- $this->view->headLink()->appendStylesheet($baseUrl.'css/playlist_builder.css?'.$CC_CONFIG['airtime_version']);
+ $this->view->headScript()->appendFile($baseUrl . 'js/libs/dayjs.min.js', 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/libs/utc.min.js', 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/libs/timezone.min.js', 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/library/spl.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/library/podcast.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/library/publish.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/playlist/smart_blockbuilder.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/playlist_builder.css?' . $CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/jquery.ui.timepicker.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/showbuilder.css?'.$CC_CONFIG['airtime_version']);
- $this->view->headLink()->appendStylesheet($baseUrl.'css/dashboard.css?'.$CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/jquery.ui.timepicker.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/showbuilder.css?' . $CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/dashboard.css?' . $CC_CONFIG['airtime_version']);
$csrf_namespace = new Zend_Session_Namespace('csrf_namespace');
$csrf_element = new Zend_Form_Element_Hidden('csrf');
@@ -72,27 +72,27 @@ class ShowbuilderController extends Zend_Controller_Action
$request = $this->getRequest();
//populate date range form for show builder.
- $now = time();
- $from = $request->getParam("from", $now);
- $to = $request->getParam("to", $now + (3*60*60));
+ $now = time();
+ $from = $request->getParam('from', $now);
+ $to = $request->getParam('to', $now + (3 * 60 * 60));
- $utcTimezone = new DateTimeZone("UTC");
+ $utcTimezone = new DateTimeZone('UTC');
$displayTimeZone = new DateTimeZone(Application_Model_Preference::GetTimezone());
- $start = DateTime::createFromFormat("U", $from, $utcTimezone);
+ $start = DateTime::createFromFormat('U', $from, $utcTimezone);
$start->setTimezone($displayTimeZone);
- $end = DateTime::createFromFormat("U", $to, $utcTimezone);
+ $end = DateTime::createFromFormat('U', $to, $utcTimezone);
$end->setTimezone($displayTimeZone);
$this->checkAndShowSetupPopup($request);
$form = new Application_Form_ShowBuilder();
- $form->populate(array(
- 'sb_date_start' => $start->format("Y-m-d"),
- 'sb_time_start' => $start->format("H:i"),
- 'sb_date_end' => $end->format("Y-m-d"),
- 'sb_time_end' => $end->format("H:i")
- ));
+ $form->populate([
+ 'sb_date_start' => $start->format('Y-m-d'),
+ 'sb_time_start' => $start->format('H:i'),
+ 'sb_date_end' => $end->format('Y-m-d'),
+ 'sb_time_end' => $end->format('H:i'),
+ ]);
$this->view->sb_form = $form;
}
@@ -106,15 +106,15 @@ class ShowbuilderController extends Zend_Controller_Action
$previousPage = strtolower($request->getHeader('Referer'));
$userService = new Application_Service_UserService();
$currentUser = $userService->getCurrentUser();
- $previousPageWasLoginScreen = (strpos($previousPage, 'login') !== false) ||
- (strpos($previousPage, SAAS_LOGIN_REFERRER) !== false);
+ $previousPageWasLoginScreen = (strpos($previousPage, 'login') !== false)
+ || (strpos($previousPage, SAAS_LOGIN_REFERRER) !== false);
// If current user is Super Admin, and they came from the login page,
// and they have not seen the setup popup before
if ($currentUser->isSuperAdmin() && $previousPageWasLoginScreen && empty($setupComplete)) {
$lang_tz_popup_form = new Application_Form_SetupLanguageTimezone();
$this->view->lang_tz_popup_form = $lang_tz_popup_form;
- $this->view->headScript()->appendFile($baseUrl.'js/airtime/nowplaying/lang-timezone-setup.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/nowplaying/lang-timezone-setup.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
}
}
@@ -126,22 +126,21 @@ class ShowbuilderController extends Zend_Controller_Action
$now = floatval(microtime(true));
$request = $this->getRequest();
- $menu = array();
+ $menu = [];
$user = Application_Model_User::getCurrentUser();
$item = CcScheduleQuery::create()->findPK($id);
$instance = $item->getCcShowInstances();
- $menu["preview"] = array("name"=> _("Preview"), "icon" => "play");
+ $menu['preview'] = ['name' => _('Preview'), 'icon' => 'play'];
//select the cursor
- $menu["selCurs"] = array("name"=> _("Select cursor"),"icon" => "select-cursor");
- $menu["delCurs"] = array("name"=> _("Remove cursor"),"icon" => "select-cursor");
-
- if ($now < floatval($item->getDbEnds("U.u")) && $user->canSchedule($instance->getDbShowId())) {
+ $menu['selCurs'] = ['name' => _('Select cursor'), 'icon' => 'select-cursor'];
+ $menu['delCurs'] = ['name' => _('Remove cursor'), 'icon' => 'select-cursor'];
+ if ($now < floatval($item->getDbEnds('U.u')) && $user->canSchedule($instance->getDbShowId())) {
//remove/truncate the item from the schedule
- $menu["del"] = array("name"=> _("Delete"), "icon" => "delete", "url" => $baseUrl."showbuilder/schedule-remove");
+ $menu['del'] = ['name' => _('Delete'), 'icon' => 'delete', 'url' => $baseUrl . 'showbuilder/schedule-remove'];
}
$this->view->items = $menu;
@@ -150,12 +149,12 @@ class ShowbuilderController extends Zend_Controller_Action
public function builderDialogAction()
{
$request = $this->getRequest();
- $id = $request->getParam("id");
+ $id = $request->getParam('id');
$instance = CcShowInstancesQuery::create()->findPK($id);
if (is_null($instance)) {
- $this->view->error = _("show does not exist");
+ $this->view->error = _('show does not exist');
return;
}
@@ -176,12 +175,12 @@ class ShowbuilderController extends Zend_Controller_Action
$this->view->end = $end_time;
$form = new Application_Form_ShowBuilder();
- $form->populate(array(
- 'sb_date_start' => $start->format("Y-m-d"),
- 'sb_time_start' => $start->format("H:i"),
- 'sb_date_end' => $end->format("Y-m-d"),
- 'sb_time_end' => $end->format("H:i")
- ));
+ $form->populate([
+ 'sb_date_start' => $start->format('Y-m-d'),
+ 'sb_time_start' => $start->format('H:i'),
+ 'sb_date_end' => $end->format('Y-m-d'),
+ 'sb_time_end' => $end->format('H:i'),
+ ]);
$this->view->sb_form = $form;
@@ -191,41 +190,43 @@ class ShowbuilderController extends Zend_Controller_Action
public function checkBuilderFeedAction()
{
$request = $this->getRequest();
- $show_filter = intval($request->getParam("showFilter", 0));
- $my_shows = intval($request->getParam("myShows", 0));
- $timestamp = intval($request->getParam("timestamp", -1));
- $instances = $request->getParam("instances", array());
+ $show_filter = intval($request->getParam('showFilter', 0));
+ $my_shows = intval($request->getParam('myShows', 0));
+ $timestamp = intval($request->getParam('timestamp', -1));
+ $instances = $request->getParam('instances', []);
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($request);
- $opts = array("myShows" => $my_shows, "showFilter" => $show_filter);
+ $opts = ['myShows' => $my_shows, 'showFilter' => $show_filter];
$showBuilder = new Application_Model_ShowBuilder($startsDT, $endsDT, $opts);
//only send the schedule back if updates have been made.
// -1 default will always call the schedule to be sent back if no timestamp is defined.
$this->view->update = $showBuilder->hasBeenUpdatedSince(
- $timestamp, $instances);
+ $timestamp,
+ $instances
+ );
}
public function builderFeedAction()
{
- $current_time = time();
+ $current_time = time();
$request = $this->getRequest();
- $show_filter = intval($request->getParam("showFilter", 0));
- $show_instance_filter = intval($request->getParam("showInstanceFilter", 0));
- $my_shows = intval($request->getParam("myShows", 0));
+ $show_filter = intval($request->getParam('showFilter', 0));
+ $show_instance_filter = intval($request->getParam('showInstanceFilter', 0));
+ $my_shows = intval($request->getParam('myShows', 0));
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($request);
- $opts = array("myShows" => $my_shows,
- "showFilter" => $show_filter,
- "showInstanceFilter" => $show_instance_filter);
+ $opts = ['myShows' => $my_shows,
+ 'showFilter' => $show_filter,
+ 'showInstanceFilter' => $show_instance_filter, ];
$showBuilder = new Application_Model_ShowBuilder($startsDT, $endsDT, $opts);
$data = $showBuilder->getItems();
- $this->view->schedule = $data["schedule"];
- $this->view->instances = $data["showInstances"];
+ $this->view->schedule = $data['schedule'];
+ $this->view->instances = $data['showInstances'];
$this->view->timestamp = $current_time;
}
@@ -233,15 +234,15 @@ class ShowbuilderController extends Zend_Controller_Action
{
$request = $this->getRequest();
- $mediaItems = $request->getParam("mediaIds", array());
- $scheduledItems = $request->getParam("schedIds", array());
+ $mediaItems = $request->getParam('mediaIds', []);
+ $scheduledItems = $request->getParam('schedIds', []);
- $log_vars = array();
- $log_vars["url"] = $_SERVER['HTTP_HOST'];
- $log_vars["action"] = "showbuilder/schedule-add";
- $log_vars["params"] = array();
- $log_vars["params"]["media_items"] = $mediaItems;
- $log_vars["params"]["scheduled_items"] = $scheduledItems;
+ $log_vars = [];
+ $log_vars['url'] = $_SERVER['HTTP_HOST'];
+ $log_vars['action'] = 'showbuilder/schedule-add';
+ $log_vars['params'] = [];
+ $log_vars['params']['media_items'] = $mediaItems;
+ $log_vars['params']['scheduled_items'] = $scheduledItems;
Logging::info($log_vars);
try {
@@ -259,13 +260,13 @@ class ShowbuilderController extends Zend_Controller_Action
public function scheduleRemoveAction()
{
$request = $this->getRequest();
- $items = $request->getParam("items", array());
+ $items = $request->getParam('items', []);
- $log_vars = array();
- $log_vars["url"] = $_SERVER['HTTP_HOST'];
- $log_vars["action"] = "showbuilder/schedule-remove";
- $log_vars["params"] = array();
- $log_vars["params"]["removed_items"] = $items;
+ $log_vars = [];
+ $log_vars['url'] = $_SERVER['HTTP_HOST'];
+ $log_vars['action'] = 'showbuilder/schedule-remove';
+ $log_vars['params'] = [];
+ $log_vars['params']['removed_items'] = $items;
Logging::info($log_vars);
try {
@@ -283,8 +284,8 @@ class ShowbuilderController extends Zend_Controller_Action
public function scheduleMoveAction()
{
$request = $this->getRequest();
- $selectedItems = $request->getParam("selectedItem");
- $afterItem = $request->getParam("afterItem");
+ $selectedItems = $request->getParam('selectedItem');
+ $afterItem = $request->getParam('afterItem');
/*
$log_vars = array();
@@ -310,7 +311,6 @@ class ShowbuilderController extends Zend_Controller_Action
public function scheduleReorderAction()
{
- throw new Exception("this controller is/was a no-op please fix your code");
+ throw new Exception('this controller is/was a no-op please fix your code');
}
-
}
diff --git a/legacy/application/controllers/SystemstatusController.php b/legacy/application/controllers/SystemstatusController.php
index b219c630b..e9e826a52 100644
--- a/legacy/application/controllers/SystemstatusController.php
+++ b/legacy/application/controllers/SystemstatusController.php
@@ -1,12 +1,14 @@
view->headScript()->appendFile($baseUrl.'js/airtime/status/status.js?'.$config['airtime_version'],'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl . 'js/airtime/status/status.js?' . $config['airtime_version'], 'text/javascript');
$this->version = $config['airtime_version'];
}
@@ -15,7 +17,7 @@ class SystemstatusController extends Zend_Controller_Action
Zend_Layout::getMvcInstance()->assign('parent_page', 'Settings');
$partitions = Application_Model_Systemstatus::GetDiskInfo();
- $this->view->status = new StdClass;
+ $this->view->status = new StdClass();
$this->view->status->partitions = $partitions;
$this->view->version = $this->version;
}
diff --git a/legacy/application/controllers/ThirdPartyController.php b/legacy/application/controllers/ThirdPartyController.php
index a28542d57..11b6cac97 100644
--- a/legacy/application/controllers/ThirdPartyController.php
+++ b/legacy/application/controllers/ThirdPartyController.php
@@ -1,10 +1,10 @@
_baseUrl = Application_Common_HTTPHelper::getStationUrl();
$this->view->layout()->disableLayout(); // Don't inject the standard Now Playing header.
$this->_helper->viewRenderer->setNoRender(true); // Don't use (phtml) templates
}
-
-}
\ No newline at end of file
+}
diff --git a/legacy/application/controllers/TracktypeController.php b/legacy/application/controllers/TracktypeController.php
index 32d22fa56..bd042df7c 100644
--- a/legacy/application/controllers/TracktypeController.php
+++ b/legacy/application/controllers/TracktypeController.php
@@ -2,14 +2,14 @@
class TracktypeController extends Zend_Controller_Action
{
-
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('get-tracktype-data-table-info', 'json')
- ->addActionContext('get-tracktype-data', 'json')
- ->addActionContext('remove-tracktype', 'json')
- ->initContext();
+ ->addActionContext('get-tracktype-data', 'json')
+ ->addActionContext('remove-tracktype', 'json')
+ ->initContext()
+ ;
}
public function addTracktypeAction()
@@ -25,57 +25,58 @@ class TracktypeController extends Zend_Controller_Action
$baseUrl = Application_Common_OsPath::getBaseDir();
- $js_files = array(
+ $js_files = [
'js/datatables/js/jquery.dataTables.js?',
'js/datatables/plugin/dataTables.pluginAPI.js?',
- 'js/airtime/tracktype/tracktype.js?'
- );
+ 'js/airtime/tracktype/tracktype.js?',
+ ];
foreach ($js_files as $js) {
$this->view->headScript()->appendFile(
- $baseUrl.$js.$CC_CONFIG['airtime_version'],'text/javascript');
+ $baseUrl . $js . $CC_CONFIG['airtime_version'],
+ 'text/javascript'
+ );
}
- $this->view->headLink()->appendStylesheet($baseUrl.'css/tracktypes.css?'.$CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/tracktypes.css?' . $CC_CONFIG['airtime_version']);
$form = new Application_Form_AddTracktype();
- $this->view->successMessage = "";
+ $this->view->successMessage = '';
if ($request->isPost()) {
$params = $request->getPost();
$postData = explode('&', $params['data']);
- $formData = array();
- foreach($postData as $k=>$v) {
+ $formData = [];
+ foreach ($postData as $k => $v) {
$v = explode('=', $v);
$formData[$v[0]] = urldecode($v[1]);
}
- if ($form->validateCode($formData)) {
- $tracktype = new Application_Model_Tracktype($formData['tracktype_id']);
- if (empty($formData['tracktype_id'])) {
- $tracktype->setCode($formData['code']);
- }
- $tracktype->setTypeName($formData['type_name']);
- $tracktype->setDescription($formData['description']);
- $tracktype->setVisibility($formData['visibility']);
- $tracktype->save();
+ if ($form->validateCode($formData)) {
+ $tracktype = new Application_Model_Tracktype($formData['tracktype_id']);
+ if (empty($formData['tracktype_id'])) {
+ $tracktype->setCode($formData['code']);
+ }
+ $tracktype->setTypeName($formData['type_name']);
+ $tracktype->setDescription($formData['description']);
+ $tracktype->setVisibility($formData['visibility']);
+ $tracktype->save();
- $form->reset();
- $this->view->form = $form;
+ $form->reset();
+ $this->view->form = $form;
- if (strlen($formData['tracktype_id']) == 0) {
- $this->view->successMessage = ""._("Track Type added successfully!")." ";
- } else {
- $this->view->successMessage = ""._("Track Type updated successfully!")." ";
- }
-
- $this->_helper->json->sendJson(array("valid"=>"true", "html"=>$this->view->render('tracktype/add-tracktype.phtml')));
+ if (strlen($formData['tracktype_id']) == 0) {
+ $this->view->successMessage = "" . _('Track Type added successfully!') . ' ';
} else {
- $this->view->form = $form;
- $this->_helper->json->sendJson(array("valid"=>"false", "html"=>$this->view->render('tracktype/add-tracktype.phtml')));
+ $this->view->successMessage = "" . _('Track Type updated successfully!') . ' ';
}
+ $this->_helper->json->sendJson(['valid' => 'true', 'html' => $this->view->render('tracktype/add-tracktype.phtml')]);
+ } else {
+ $this->view->form = $form;
+ $this->_helper->json->sendJson(['valid' => 'false', 'html' => $this->view->render('tracktype/add-tracktype.phtml')]);
+ }
}
$this->view->form = $form;
@@ -102,8 +103,7 @@ class TracktypeController extends Zend_Controller_Action
$tracktype = new Application_Model_Tracktype($delId);
- # Delete the track type
+ // Delete the track type
$this->view->entries = $tracktype->delete();
}
-
}
diff --git a/legacy/application/controllers/UpgradeController.php b/legacy/application/controllers/UpgradeController.php
index ab457fe19..6d3f7c358 100644
--- a/legacy/application/controllers/UpgradeController.php
+++ b/legacy/application/controllers/UpgradeController.php
@@ -6,7 +6,7 @@ class UpgradeController extends Zend_Controller_Action
{
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
-
+
if (!RestAuth::verifyAuth(true, false, $this)) {
return;
}
@@ -16,23 +16,25 @@ class UpgradeController extends Zend_Controller_Action
if (!$didWePerformAnUpgrade) {
$this->getResponse()
- ->setHttpResponseCode(200)
- ->appendBody("No upgrade was performed. The current schema version is " . Application_Model_Preference::GetSchemaVersion() . ". ");
+ ->setHttpResponseCode(200)
+ ->appendBody('No upgrade was performed. The current schema version is ' . Application_Model_Preference::GetSchemaVersion() . '. ')
+ ;
} else {
$this->getResponse()
- ->setHttpResponseCode(200)
- ->appendBody("Upgrade to Airtime schema version " . Application_Model_Preference::GetSchemaVersion() . " OK ");
+ ->setHttpResponseCode(200)
+ ->appendBody('Upgrade to Airtime schema version ' . Application_Model_Preference::GetSchemaVersion() . ' OK ')
+ ;
}
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
$this->getResponse()
- ->setHttpResponseCode(400)
- ->appendBody($e->getMessage());
+ ->setHttpResponseCode(400)
+ ->appendBody($e->getMessage())
+ ;
}
}
- public function downgradeAction() {
+ public function downgradeAction()
+ {
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
@@ -41,7 +43,7 @@ class UpgradeController extends Zend_Controller_Action
}
$request = $this->getRequest();
- $toVersion = $request->getParam("version");
+ $toVersion = $request->getParam('version');
try {
$downgradePerformed = UpgradeManager::doDowngrade($toVersion);
@@ -49,17 +51,19 @@ class UpgradeController extends Zend_Controller_Action
if (!$downgradePerformed) {
$this->getResponse()
->setHttpResponseCode(200)
- ->appendBody("No downgrade was performed. The current schema version is " . Application_Model_Preference::GetSchemaVersion() . ". ");
+ ->appendBody('No downgrade was performed. The current schema version is ' . Application_Model_Preference::GetSchemaVersion() . '. ')
+ ;
} else {
$this->getResponse()
->setHttpResponseCode(200)
- ->appendBody("Downgrade to Airtime schema version " . Application_Model_Preference::GetSchemaVersion() . " OK ");
+ ->appendBody('Downgrade to Airtime schema version ' . Application_Model_Preference::GetSchemaVersion() . ' OK ')
+ ;
}
} catch (Exception $e) {
$this->getResponse()
->setHttpResponseCode(400)
- ->appendBody($e->getMessage());
+ ->appendBody($e->getMessage())
+ ;
}
}
-
}
diff --git a/legacy/application/controllers/UserController.php b/legacy/application/controllers/UserController.php
index 0e2c5e65e..daf5e3020 100644
--- a/legacy/application/controllers/UserController.php
+++ b/legacy/application/controllers/UserController.php
@@ -2,16 +2,16 @@
class UserController extends Zend_Controller_Action
{
-
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('get-hosts', 'json')
- ->addActionContext('get-user-data-table-info', 'json')
- ->addActionContext('get-user-data', 'json')
- ->addActionContext('remove-user', 'json')
- ->addActionContext('edit-user', 'json')
- ->initContext();
+ ->addActionContext('get-user-data-table-info', 'json')
+ ->addActionContext('get-user-data', 'json')
+ ->addActionContext('remove-user', 'json')
+ ->addActionContext('edit-user', 'json')
+ ->initContext()
+ ;
}
public function addUserAction()
@@ -27,34 +27,35 @@ class UserController extends Zend_Controller_Action
$baseUrl = Application_Common_OsPath::getBaseDir();
- $js_files = array(
+ $js_files = [
'js/datatables/js/jquery.dataTables.js?',
'js/datatables/plugin/dataTables.pluginAPI.js?',
- 'js/airtime/user/user.js?'
- );
+ 'js/airtime/user/user.js?',
+ ];
foreach ($js_files as $js) {
$this->view->headScript()->appendFile(
- $baseUrl.$js.$CC_CONFIG['airtime_version'],'text/javascript');
+ $baseUrl . $js . $CC_CONFIG['airtime_version'],
+ 'text/javascript'
+ );
}
- $this->view->headLink()->appendStylesheet($baseUrl.'css/users.css?'.$CC_CONFIG['airtime_version']);
+ $this->view->headLink()->appendStylesheet($baseUrl . 'css/users.css?' . $CC_CONFIG['airtime_version']);
$form = new Application_Form_AddUser();
- $this->view->successMessage = "";
+ $this->view->successMessage = '';
if ($request->isPost()) {
$params = $request->getPost();
$postData = explode('&', $params['data']);
- $formData = array();
- foreach($postData as $k=>$v) {
+ $formData = [];
+ foreach ($postData as $k => $v) {
$v = explode('=', $v);
$formData[$v[0]] = urldecode($v[1]);
}
if ($form->isValid($formData)) {
-
if ($form->validateLogin($formData)) {
$user = new Application_Model_User($formData['user_id']);
if (empty($formData['user_id'])) {
@@ -65,7 +66,7 @@ class UserController extends Zend_Controller_Action
// We don't allow 6 x's as a password.
// The reason is because we that as a password placeholder
// on the client side.
- if ($formData['password'] != "xxxxxx") {
+ if ($formData['password'] != 'xxxxxx') {
$user->setPassword($formData['password']);
}
if (array_key_exists('type', $formData)) {
@@ -83,19 +84,19 @@ class UserController extends Zend_Controller_Action
$this->view->form = $form;
if (strlen($formData['user_id']) == 0) {
- $this->view->successMessage = ""._("User added successfully!")." ";
+ $this->view->successMessage = "" . _('User added successfully!') . ' ';
} else {
- $this->view->successMessage = ""._("User updated successfully!")." ";
+ $this->view->successMessage = "" . _('User updated successfully!') . ' ';
}
- $this->_helper->json->sendJson(array("valid"=>"true", "html"=>$this->view->render('user/add-user.phtml')));
+ $this->_helper->json->sendJson(['valid' => 'true', 'html' => $this->view->render('user/add-user.phtml')]);
} else {
$this->view->form = $form;
- $this->_helper->json->sendJson(array("valid"=>"false", "html"=>$this->view->render('user/add-user.phtml')));
+ $this->_helper->json->sendJson(['valid' => 'false', 'html' => $this->view->render('user/add-user.phtml')]);
}
} else {
$this->view->form = $form;
- $this->_helper->json->sendJson(array("valid"=>"false", "html"=>$this->view->render('user/add-user.phtml')));
+ $this->_helper->json->sendJson(['valid' => 'false', 'html' => $this->view->render('user/add-user.phtml')]);
}
}
@@ -104,7 +105,7 @@ class UserController extends Zend_Controller_Action
public function getHostsAction()
{
- $search = $this->_getParam('term');
+ $search = $this->_getParam('term');
$this->view->hosts = Application_Model_User::getHosts($search);
}
@@ -121,7 +122,7 @@ class UserController extends Zend_Controller_Action
$id = $this->_getParam('id');
$this->view->entries = Application_Model_User::GetUserData($id);
}
-
+
public function editUserAction()
{
Zend_Layout::getMvcInstance()->assign('parent_page', 'Settings');
@@ -132,16 +133,16 @@ class UserController extends Zend_Controller_Action
$form = new Application_Form_EditUser();
if ($request->isPost()) {
$formData = $request->getPost();
-
- if ($form->isValid($formData) &&
- $form->validateLogin($formData['cu_login'], $formData['cu_user_id'])) {
+
+ if ($form->isValid($formData)
+ && $form->validateLogin($formData['cu_login'], $formData['cu_user_id'])) {
$user = new Application_Model_User($formData['cu_user_id']);
//Stupid hack because our schema enforces non-null first_name
//even though by default the admin user has no first name... (....)
if (Application_Model_User::getCurrentUser()->isSuperAdmin()) {
- if (empty($formData['cu_first_name'])) {
- $formData['cu_first_name'] = "admin";
- $formData['cu_last_name'] = "admin"; //ditto, avoid non-null DB constraint
+ if (empty($formData['cu_first_name'])) {
+ $formData['cu_first_name'] = 'admin';
+ $formData['cu_last_name'] = 'admin'; //ditto, avoid non-null DB constraint
}
}
if (isset($formData['cu_first_name'])) {
@@ -154,8 +155,8 @@ class UserController extends Zend_Controller_Action
// We don't allow 6 x's as a password.
// The reason is because we use that as a password placeholder
// on the client side.
- if (array_key_exists('cu_password', $formData) && ($formData['cu_password'] != "xxxxxx") &&
- (!empty($formData['cu_password']))) {
+ if (array_key_exists('cu_password', $formData) && ($formData['cu_password'] != 'xxxxxx')
+ && (!empty($formData['cu_password']))) {
$user->setPassword($formData['cu_password']);
}
@@ -185,7 +186,7 @@ class UserController extends Zend_Controller_Action
//reinitialize form so language gets translated
$form = new Application_Form_EditUser();
- $this->view->successMessage = ""._("Settings updated successfully!")." ";
+ $this->view->successMessage = "" . _('Settings updated successfully!') . ' ';
}
$this->view->form = $form;
$this->view->html = $this->view->render('user/edit-user.phtml');
@@ -198,49 +199,48 @@ class UserController extends Zend_Controller_Action
{
// action body
$delId = $this->_getParam('id');
- $valid_actions = array("delete_cascade", "reassign_to");
+ $valid_actions = ['delete_cascade', 'reassign_to'];
$files_action = $this->_getParam('deleted_files');
- # TODO : remove this. we only use default for now not to break the UI.
- if (!$files_action) { # set default action
- $files_action = "reassign_to";
- $new_owner = Application_Model_User::getFirstAdmin($delId);
+ // TODO : remove this. we only use default for now not to break the UI.
+ if (!$files_action) { // set default action
+ $files_action = 'reassign_to';
+ $new_owner = Application_Model_User::getFirstAdmin($delId);
}
- # only delete when valid action is selected for the owned files
- if (! in_array($files_action, $valid_actions) ) {
+ // only delete when valid action is selected for the owned files
+ if (!in_array($files_action, $valid_actions)) {
return;
}
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$userId = $userInfo->id;
- # Don't let users delete themselves
+ // Don't let users delete themselves
if ($delId == $userId) {
return;
}
$user = new Application_Model_User($delId);
-
+
// Don't allow super admins to be deleted.
- if ($user->isSuperAdmin())
- {
+ if ($user->isSuperAdmin()) {
return;
}
- # Take care of the user's files by either assigning them to somebody
- # or deleting them all
- if ($files_action == "delete_cascade") {
+ // Take care of the user's files by either assigning them to somebody
+ // or deleting them all
+ if ($files_action == 'delete_cascade') {
$user->deleteAllFiles();
- } elseif ($files_action == "reassign_to") {
+ } elseif ($files_action == 'reassign_to') {
// TODO : fix code to actually use the line below and pick a
// real owner instead of defaulting to the first found admin
//$new_owner_id = $this->_getParam("new_owner");
//$new_owner = new Application_Model_User($new_owner_id);
- $user->donateFilesTo( $new_owner );
+ $user->donateFilesTo($new_owner);
Logging::info("Reassign to user {$new_owner->getDbId()}");
}
- # Finally delete the user
+ // Finally delete the user
$this->view->entries = $user->delete();
}
}
diff --git a/legacy/application/controllers/UsersettingsController.php b/legacy/application/controllers/UsersettingsController.php
index 635a24e40..2c88943b9 100644
--- a/legacy/application/controllers/UsersettingsController.php
+++ b/legacy/application/controllers/UsersettingsController.php
@@ -1,28 +1,29 @@
_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('get-now-playing-screen-settings', 'json')
- ->addActionContext('set-now-playing-screen-settings', 'json')
- ->addActionContext('get-library-datatable', 'json')
- ->addActionContext('set-library-datatable', 'json')
- ->addActionContext('get-timeline-datatable', 'json')
- ->addActionContext('set-timeline-datatable', 'json')
- ->addActionContext('remindme', 'json')
- ->addActionContext('remindme-never', 'json')
- ->addActionContext('donotshowregistrationpopup', 'json')
- ->addActionContext('set-library-screen-settings', 'json')
- ->initContext();
+ ->addActionContext('set-now-playing-screen-settings', 'json')
+ ->addActionContext('get-library-datatable', 'json')
+ ->addActionContext('set-library-datatable', 'json')
+ ->addActionContext('get-timeline-datatable', 'json')
+ ->addActionContext('set-timeline-datatable', 'json')
+ ->addActionContext('remindme', 'json')
+ ->addActionContext('remindme-never', 'json')
+ ->addActionContext('donotshowregistrationpopup', 'json')
+ ->addActionContext('set-library-screen-settings', 'json')
+ ->initContext()
+ ;
}
public function setNowPlayingScreenSettingsAction()
{
$request = $this->getRequest();
- $settings = $request->getParam("settings");
+ $settings = $request->getParam('settings');
Application_Model_Preference::setNowPlayingScreenSettings($settings);
}
@@ -38,7 +39,7 @@ class UsersettingsController extends Zend_Controller_Action
public function setLibraryDatatableAction()
{
$request = $this->getRequest();
- $settings = $request->getParam("settings");
+ $settings = $request->getParam('settings');
Application_Model_Preference::setCurrentLibraryTableSetting($settings);
}
@@ -56,7 +57,7 @@ class UsersettingsController extends Zend_Controller_Action
public function setTimelineDatatableAction()
{
$request = $this->getRequest();
- $settings = $request->getParam("settings");
+ $settings = $request->getParam('settings');
Application_Model_Preference::setTimelineDatatableSetting($settings);
}
@@ -76,7 +77,7 @@ class UsersettingsController extends Zend_Controller_Action
Zend_Session::namespaceUnset('referrer');
Application_Model_Preference::SetRemindMeDate();
}
-
+
public function remindmeNeverAction()
{
SessionHelper::reopenSessionForWriting();
@@ -95,7 +96,7 @@ class UsersettingsController extends Zend_Controller_Action
public function setLibraryScreenSettingsAction()
{
$request = $this->getRequest();
- $settings = $request->getParam("settings");
+ $settings = $request->getParam('settings');
Application_Model_Preference::setLibraryScreenSettings($settings);
}
}
diff --git a/legacy/application/controllers/WebstreamController.php b/legacy/application/controllers/WebstreamController.php
index 6e0b8cf24..8161904e9 100644
--- a/legacy/application/controllers/WebstreamController.php
+++ b/legacy/application/controllers/WebstreamController.php
@@ -6,10 +6,11 @@ class WebstreamController extends Zend_Controller_Action
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('new', 'json')
- ->addActionContext('save', 'json')
- ->addActionContext('edit', 'json')
- ->addActionContext('delete', 'json')
- ->initContext();
+ ->addActionContext('save', 'json')
+ ->addActionContext('edit', 'json')
+ ->addActionContext('delete', 'json')
+ ->initContext()
+ ;
}
public function newAction()
@@ -17,7 +18,8 @@ class WebstreamController extends Zend_Controller_Action
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
if (!$this->isAuthorized(-1)) {
// TODO: this header call does not actually print any error message
- header("Status: 401 Not Authorized");
+ header('Status: 401 Not Authorized');
+
return;
}
@@ -25,20 +27,20 @@ class WebstreamController extends Zend_Controller_Action
//we're not saving this primary key in the DB so it's OK to be -1
$webstream->setDbId(-1);
- $webstream->setDbName(_("Untitled Webstream"));
- $webstream->setDbDescription("");
- $webstream->setDbUrl("http://");
- $webstream->setDbLength("00:30:00");
- $webstream->setDbName(_("Untitled Webstream"));
+ $webstream->setDbName(_('Untitled Webstream'));
+ $webstream->setDbDescription('');
+ $webstream->setDbUrl('http://');
+ $webstream->setDbLength('00:30:00');
+ $webstream->setDbName(_('Untitled Webstream'));
$webstream->setDbCreatorId($userInfo->id);
- $webstream->setDbUtime(new DateTime("now", new DateTimeZone('UTC')));
- $webstream->setDbMtime(new DateTime("now", new DateTimeZone('UTC')));
+ $webstream->setDbUtime(new DateTime('now', new DateTimeZone('UTC')));
+ $webstream->setDbMtime(new DateTime('now', new DateTimeZone('UTC')));
//clear the session in case an old playlist was open: CC-4196
Application_Model_Library::changePlaylist(null, null);
$this->view->obj = new Application_Model_Webstream($webstream);
- $this->view->action = "new";
+ $this->view->action = 'new';
$this->view->html = $this->view->render('webstream/webstream.phtml');
}
@@ -46,57 +48,57 @@ class WebstreamController extends Zend_Controller_Action
{
$request = $this->getRequest();
- $id = $request->getParam("id");
+ $id = $request->getParam('id');
if (is_null($id)) {
throw new Exception("Missing parameter 'id'");
}
$webstream = CcWebstreamQuery::create()->findPK($id);
if ($webstream) {
- Application_Model_Library::changePlaylist($id, "stream");
+ Application_Model_Library::changePlaylist($id, 'stream');
}
$obj = new Application_Model_Webstream($webstream);
$user = Application_Model_User::getCurrentUser();
- $isAdminOrPM = $user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
+ $isAdminOrPM = $user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER]);
if (!$isAdminOrPM && $webstream->getDbCreatorId() != $user->getId()) {
- $this->view->objType = "webstream";
- $this->view->type = "webstream";
+ $this->view->objType = 'webstream';
+ $this->view->type = 'webstream';
$this->view->obj = $obj;
$this->view->id = $id;
$this->view->html = $this->view->render('playlist/permission-denied.phtml');
+
return;
}
$this->view->obj = $obj;
- $this->view->type = "webstream";
+ $this->view->type = 'webstream';
$this->view->id = $id;
- $this->view->action = "edit";
+ $this->view->action = 'edit';
$this->view->html = $this->view->render('webstream/webstream.phtml');
}
public function deleteAction()
{
$request = $this->getRequest();
- $id = $request->getParam("ids");
+ $id = $request->getParam('ids');
if (!$this->isAuthorized($id)) {
- header("Status: 401 Not Authorized");
+ header('Status: 401 Not Authorized');
return;
}
- $type = "stream";
+ $type = 'stream';
Application_Model_Library::changePlaylist(null, $type);
$webstream = CcWebstreamQuery::create()->findPK($id)->delete();
$this->view->obj = null;
- $this->view->action = "delete";
+ $this->view->action = 'delete';
$this->view->html = $this->view->render('webstream/webstream.phtml');
-
}
/*TODO : make a user object be passed a parameter into this function so
@@ -104,7 +106,7 @@ class WebstreamController extends Zend_Controller_Action
public function isAuthorized($webstream_id)
{
$user = Application_Model_User::getCurrentUser();
- if ($user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
+ if ($user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER])) {
return true;
}
@@ -121,9 +123,9 @@ class WebstreamController extends Zend_Controller_Action
/*we are creating a new stream. Don't need to check whether the
DJ/Host owns the stream*/
return true;
- } else {
- Logging::info( $user );
}
+ Logging::info($user);
+
return false;
}
@@ -131,35 +133,36 @@ class WebstreamController extends Zend_Controller_Action
{
$request = $this->getRequest();
- $id = $request->getParam("id");
+ $id = $request->getParam('id');
- $parameters = array();
- foreach (array('id','length','name','description','url') as $p) {
+ $parameters = [];
+ foreach (['id', 'length', 'name', 'description', 'url'] as $p) {
$parameters[$p] = trim($request->getParam($p));
}
if (!$this->isAuthorized($id)) {
- header("Status: 401 Not Authorized");
+ header('Status: 401 Not Authorized');
+
return;
}
-
list($analysis, $mime, $mediaUrl, $di) = Application_Model_Webstream::analyzeFormData($parameters);
+
try {
if (Application_Model_Webstream::isValid($analysis)) {
$streamId = Application_Model_Webstream::save($parameters, $mime, $mediaUrl, $di);
- Application_Model_Library::changePlaylist($streamId, "stream");
+ Application_Model_Library::changePlaylist($streamId, 'stream');
- $this->view->statusMessage = ""._("Webstream saved.")." ";
+ $this->view->statusMessage = "" . _('Webstream saved.') . ' ';
$this->view->streamId = $streamId;
- $this->view->length = $di->format("%Hh %Im");
+ $this->view->length = $di->format('%Hh %Im');
} else {
- throw new Exception("isValid returned false");
+ throw new Exception('isValid returned false');
}
} catch (Exception $e) {
Logging::debug($e->getMessage());
- $this->view->statusMessage = ""._("Invalid form values.")." ";
+ $this->view->statusMessage = "" . _('Invalid form values.') . ' ';
$this->view->streamId = -1;
$this->view->analysis = $analysis;
}
diff --git a/legacy/application/controllers/plugins/Acl_plugin.php b/legacy/application/controllers/plugins/Acl_plugin.php
index 5a6b5dcc5..8cd13f292 100644
--- a/legacy/application/controllers/plugins/Acl_plugin.php
+++ b/legacy/application/controllers/plugins/Acl_plugin.php
@@ -4,31 +4,30 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
{
/**
* @var Zend_Acl
- **/
+ */
protected $_acl;
/**
* @var string
- **/
+ */
protected $_roleName;
/**
* @var array
- **/
+ */
protected $_errorPage;
/**
- * Constructor
+ * Constructor.
*
* @param mixed $aclData
* @param $roleName
- * @return void
- **/
+ */
public function __construct(Zend_Acl $aclData, $roleName = 'G')
{
- $this->_errorPage = array('module' => 'default',
- 'controller' => 'error',
- 'action' => 'error');
+ $this->_errorPage = ['module' => 'default',
+ 'controller' => 'error',
+ 'action' => 'error', ];
$this->_roleName = $roleName;
@@ -38,32 +37,32 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
}
/**
- * Sets the ACL object
+ * Sets the ACL object.
*
- * @param mixed $aclData
- * @return void
- **/
+ * @param mixed $aclData
+ */
public function setAcl(Zend_Acl $aclData)
{
$this->_acl = $aclData;
}
/**
- * Returns the ACL object
+ * Returns the ACL object.
*
* @return Zend_Acl
- **/
+ */
public function getAcl()
{
return $this->_acl;
}
/**
- * Returns the ACL role used
+ * Returns the ACL role used.
*
* @return string
+ *
* @author
- **/
+ */
public function getRoleName()
{
return $this->_roleName;
@@ -75,25 +74,24 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
}
/**
- * Sets the error page
+ * Sets the error page.
*
- * @param string $action
- * @param string $controller
- * @param string $module
- * @return void
- **/
+ * @param string $action
+ * @param string $controller
+ * @param string $module
+ */
public function setErrorPage($action, $controller = 'error', $module = 'default')
{
- $this->_errorPage = array('module' => $module,
- 'controller' => $controller,
- 'action' => $action);
+ $this->_errorPage = ['module' => $module,
+ 'controller' => $controller,
+ 'action' => $action, ];
}
/**
- * Returns the error page
+ * Returns the error page.
*
* @return array
- **/
+ */
public function getErrorPage()
{
return $this->_errorPage;
@@ -102,82 +100,73 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
/**
* Predispatch
* Checks if the current user identified by roleName has rights to the requested url (module/controller/action)
- * If not, it will call denyAccess to be redirected to errorPage
- *
- * @return void
- **/
+ * If not, it will call denyAccess to be redirected to errorPage.
+ */
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$controller = strtolower($request->getControllerName());
- if (in_array($controller, array(
- "index",
- "login",
- "api",
- "auth",
- "error",
- "locale",
- "upgrade",
- "embed",
- "feeds"
- )))
- {
- $this->setRoleName("G");
- }
- elseif (Zend_Session::isStarted() && !Zend_Auth::getInstance()->hasIdentity()) {
-
+ if (in_array($controller, [
+ 'index',
+ 'login',
+ 'api',
+ 'auth',
+ 'error',
+ 'locale',
+ 'upgrade',
+ 'embed',
+ 'feeds',
+ ])) {
+ $this->setRoleName('G');
+ } elseif (Zend_Session::isStarted() && !Zend_Auth::getInstance()->hasIdentity()) {
//The controller uses sessions but we don't have an identity yet.
// If we don't have an identity and we're making a RESTful request,
// we need to do API key verification
- if ($request->getModuleName() == "rest") {
+ if ($request->getModuleName() == 'rest') {
if (!$this->verifyAuth()) {
//$this->denyAccess();
//$this->getResponse()->sendResponse();
//$r->gotoSimpleAndExit('index', 'login', $request->getModuleName());
//die();
- throw new Zend_Controller_Exception("Incorrect API key", 401);
+ throw new Zend_Controller_Exception('Incorrect API key', 401);
}
- }
- else //Non-REST, regular Airtime web app requests
- {
+ } else { //Non-REST, regular Airtime web app requests
// Redirect user to the landing page if they are trying to
// access a resource that requires a valid session.
// Skip the redirection if they are already on the landing page
// or the login page.
if ($controller !== 'index' && $controller !== 'login') {
-
if ($request->isXmlHttpRequest()) {
-
- $url = 'http://'.$request->getHttpHost().'/';
- $json = Zend_Json::encode(array('auth' => false, 'url' => $url));
+ $url = 'http://' . $request->getHttpHost() . '/';
+ $json = Zend_Json::encode(['auth' => false, 'url' => $url]);
// Prepare response
$this->getResponse()
- ->setHttpResponseCode(401)
- ->setBody($json)
- ->sendResponse();
+ ->setHttpResponseCode(401)
+ ->setBody($json)
+ ->sendResponse()
+ ;
//redirectAndExit() cleans up, sends the headers and stops the script
Zend_Controller_Action_HelperBroker::getStaticHelper('redirector')->redirectAndExit();
} else {
$r = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$r->gotoSimpleAndExit('index', 'index', $request->getModuleName());
- }
+ }
}
}
} else { //We have a session/identity.
-
// If we have an identity and we're making a RESTful request,
// we need to check the CSRF token
- if ($_SERVER['REQUEST_METHOD'] != "GET" && $request->getModuleName() == "rest") {
- $token = $request->getParam("csrf_token");
+ if ($_SERVER['REQUEST_METHOD'] != 'GET' && $request->getModuleName() == 'rest') {
+ $token = $request->getParam('csrf_token');
// PUT requests don't parameterize the data in the body, so we can't
// fetch it with getParam or getPost; instead we have to parse the body and
// check for the token in the JSON. (Hopefully we can find a better way to do this) -- Duncan
if (empty($token)) {
- $token = json_decode($this->getRequest()->getRawBody(), true)["csrf_token"];
+ $token = json_decode($this->getRequest()->getRawBody(), true)['csrf_token'];
}
$tokenValid = $this->verifyCSRFToken($token);
@@ -185,15 +174,17 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
$csrf_namespace = new Zend_Session_Namespace('csrf_namespace');
$csrf_namespace->authtoken = sha1(openssl_random_pseudo_bytes(128));
- Logging::warn("Invalid CSRF token: $token");
+ Logging::warn("Invalid CSRF token: {$token}");
$this->getResponse()
- ->setHttpResponseCode(401)
- ->appendBody("ERROR: CSRF token mismatch.")
- ->sendResponse();
- die();
+ ->setHttpResponseCode(401)
+ ->appendBody('ERROR: CSRF token mismatch.')
+ ->sendResponse()
+ ;
+
+ exit();
}
}
-
+
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$this->setRoleName($userInfo->type);
@@ -208,28 +199,32 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
$resourceName .= $controller;
- /** Check if the controller/action can be accessed by the current user */
+ // Check if the controller/action can be accessed by the current user
if (!$this->getAcl()->has($resourceName)) {
$this->setErrorPage('error404');
$this->denyAccess();
- } else if (!$this->getAcl()->isAllowed($this->_roleName,
- $resourceName,
- $request->getActionName())) {
- /** Redirect to access denied page */
+ } elseif (!$this->getAcl()->isAllowed(
+ $this->_roleName,
+ $resourceName,
+ $request->getActionName()
+ )) {
+ // Redirect to access denied page
$this->setErrorPage('error403');
$this->denyAccess();
}
}
}
- private function verifyAuth() {
+ private function verifyAuth()
+ {
if ($this->verifyAPIKey() || $this->isVerifiedDownload()) {
return true;
}
$this->getResponse()
->setHttpResponseCode(401)
- ->appendBody("ERROR: Incorrect API key.");
+ ->appendBody('ERROR: Incorrect API key.')
+ ;
return false;
}
@@ -239,47 +234,50 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
* It should satisfy the following requirements:
* * request path is /rest/media/:id/download
* * download key is correct
- * * requested file belongs to the station podcast
+ * * requested file belongs to the station podcast.
*
* @return bool
*/
- private function isVerifiedDownload() {
+ private function isVerifiedDownload()
+ {
$request = $this->getRequest();
- $fileId = $request->getParam("id");
- $key = $request->getParam("download_key");
+ $fileId = $request->getParam('id');
+ $key = $request->getParam('download_key');
$module = $request->getModuleName();
$controller = $request->getControllerName();
$action = $request->getActionName();
$stationPodcast = StationPodcastQuery::create()
- ->findOneByDbPodcastId(Application_Model_Preference::getStationPodcastId());
- return $module == "rest" && $controller == "media" && $action == "download"
+ ->findOneByDbPodcastId(Application_Model_Preference::getStationPodcastId())
+ ;
+
+ return $module == 'rest' && $controller == 'media' && $action == 'download'
&& $key === Application_Model_Preference::getStationPodcastDownloadKey()
&& $stationPodcast->hasEpisodeForFile($fileId);
}
- private function verifyCSRFToken($token) {
+ private function verifyCSRFToken($token)
+ {
return SecurityHelper::verifyCSRFToken($token);
}
-
- private function verifyAPIKey() {
+
+ private function verifyAPIKey()
+ {
// The API key is passed in via HTTP "basic authentication":
// http://en.wikipedia.org/wiki/Basic_access_authentication
$CC_CONFIG = Config::getConfig();
-
+
// Decode the API key that was passed to us in the HTTP request.
- $authHeader = $this->getRequest()->getHeader("Authorization");
- $encodedRequestApiKey = substr($authHeader, strlen("Basic "));
- $encodedStoredApiKey = base64_encode($CC_CONFIG["apiKey"][0] . ":");
-
- return ($encodedRequestApiKey === $encodedStoredApiKey);
+ $authHeader = $this->getRequest()->getHeader('Authorization');
+ $encodedRequestApiKey = substr($authHeader, strlen('Basic '));
+ $encodedStoredApiKey = base64_encode($CC_CONFIG['apiKey'][0] . ':');
+
+ return $encodedRequestApiKey === $encodedStoredApiKey;
}
/**
* Deny Access Function
- * Redirects to errorPage, this can be called from an action using the action helper
- *
- * @return void
- **/
+ * Redirects to errorPage, this can be called from an action using the action helper.
+ */
public function denyAccess()
{
$this->_request->setModuleName($this->_errorPage['module']);
diff --git a/legacy/application/controllers/plugins/Maintenance.php b/legacy/application/controllers/plugins/Maintenance.php
index f6baf6201..bae6fbe62 100644
--- a/legacy/application/controllers/plugins/Maintenance.php
+++ b/legacy/application/controllers/plugins/Maintenance.php
@@ -2,14 +2,16 @@
class Zend_Controller_Plugin_Maintenance extends Zend_Controller_Plugin_Abstract
{
- public function preDispatch(Zend_Controller_Request_Abstract $request) {
- $maintenanceFile = isset($_SERVER['AIRTIME_BASE']) ? $_SERVER['AIRTIME_BASE']."maintenance.txt" : "/tmp/maintenance.txt";
+ public function preDispatch(Zend_Controller_Request_Abstract $request)
+ {
+ $maintenanceFile = isset($_SERVER['AIRTIME_BASE']) ? $_SERVER['AIRTIME_BASE'] . 'maintenance.txt' : '/tmp/maintenance.txt';
if (file_exists($maintenanceFile)) {
$request->setModuleName('default')
- ->setControllerName('index')
- ->setActionName('maintenance')
- ->setDispatched(true);
+ ->setControllerName('index')
+ ->setActionName('maintenance')
+ ->setDispatched(true)
+ ;
}
}
-}
\ No newline at end of file
+}
diff --git a/legacy/application/controllers/plugins/PageLayoutInitPlugin.php b/legacy/application/controllers/plugins/PageLayoutInitPlugin.php
index f38efce62..2e1bd7b8a 100644
--- a/legacy/application/controllers/plugins/PageLayoutInitPlugin.php
+++ b/legacy/application/controllers/plugins/PageLayoutInitPlugin.php
@@ -7,9 +7,10 @@
*/
class PageLayoutInitPlugin extends Zend_Controller_Plugin_Abstract
{
- protected $_bootstrap = null;
+ protected $_bootstrap;
- public function __construct($boostrap) {
+ public function __construct($boostrap)
+ {
$this->_bootstrap = $boostrap;
}
@@ -17,7 +18,7 @@ class PageLayoutInitPlugin extends Zend_Controller_Plugin_Abstract
* Start the session depending on which controller your request is going to.
* We start the session explicitly here so that we can avoid starting sessions
* needlessly for (stateless) requests to the API.
- * @param Zend_Controller_Request_Abstract $request
+ *
* @throws Zend_Session_Exception
*/
public function routeShutdown(Zend_Controller_Request_Abstract $request)
@@ -27,15 +28,15 @@ class PageLayoutInitPlugin extends Zend_Controller_Plugin_Abstract
//List of controllers where we don't need a session, and we don't need
//all the standard HTML / JS boilerplate.
- if (!in_array($controller, array(
- "index", //Radio Page
- "api",
- "auth",
- "error",
- "upgrade",
- "embed",
- "feeds"
- ))
+ if (!in_array($controller, [
+ 'index', //Radio Page
+ 'api',
+ 'auth',
+ 'error',
+ 'upgrade',
+ 'embed',
+ 'feeds',
+ ])
) {
//Start the session
Zend_Session::start();
@@ -54,7 +55,7 @@ class PageLayoutInitPlugin extends Zend_Controller_Plugin_Abstract
}
// Skip upgrades and task management when running unit tests
- if (getenv("AIRTIME_UNIT_TEST") != 1) {
+ if (getenv('AIRTIME_UNIT_TEST') != 1) {
$taskManager = TaskManager::getInstance();
// Run the upgrade on each request (if it needs to be run)
@@ -66,7 +67,7 @@ class PageLayoutInitPlugin extends Zend_Controller_Plugin_Abstract
// Piggyback the TaskManager onto API calls. This provides guaranteed consistency
// (there is at least one API call made from pypo to Airtime every 7 minutes) and
// greatly reduces the chances of lock contention on cc_pref while the TaskManager runs
- if ($controller == "api") {
+ if ($controller == 'api') {
$taskManager->runTasks();
}
}
@@ -81,29 +82,29 @@ class PageLayoutInitPlugin extends Zend_Controller_Plugin_Abstract
$view = $this->_bootstrap->getResource('view');
$baseUrl = Application_Common_OsPath::getBaseDir();
- $view->headScript()->appendScript("var baseUrl = '$baseUrl';");
+ $view->headScript()->appendScript("var baseUrl = '{$baseUrl}';");
$this->_initTranslationGlobals($view);
$user = Application_Model_User::GetCurrentUser();
if (!is_null($user)) {
$userType = $user->getType();
} else {
- $userType = "";
+ $userType = '';
}
- $view->headScript()->appendScript("var userType = '$userType';");
+ $view->headScript()->appendScript("var userType = '{$userType}';");
// Dropzone also accept file extensions and doesn't correctly extract certain mimetypes (eg. FLAC - try it),
// so we append the file extensions to the list of mimetypes and that makes it work.
$mimeTypes = FileDataHelper::getAudioMimeTypeArray();
$fileExtensions = array_values($mimeTypes);
- foreach($fileExtensions as &$extension) {
+ foreach ($fileExtensions as &$extension) {
$extension = '.' . $extension;
}
- $view->headScript()->appendScript("var acceptedMimeTypes = " . json_encode(array_merge(array_keys($mimeTypes), $fileExtensions)) . ";");
+ $view->headScript()->appendScript('var acceptedMimeTypes = ' . json_encode(array_merge(array_keys($mimeTypes), $fileExtensions)) . ';');
}
/**
- * Create a global namespace to hold a session token for CSRF prevention
+ * Create a global namespace to hold a session token for CSRF prevention.
*/
protected function _initCsrfNamespace()
{
@@ -131,7 +132,7 @@ class PageLayoutInitPlugin extends Zend_Controller_Plugin_Abstract
/**
* Ideally, globals should be written to a single js file once
* from a php init function. This will save us from having to
- * reinitialize them every request
+ * reinitialize them every request.
*/
private function _initTranslationGlobals()
{
@@ -142,18 +143,18 @@ class PageLayoutInitPlugin extends Zend_Controller_Plugin_Abstract
//Each page refresh or tab open has uniqID, not to be used for security
$view->headScript()->appendScript("var UNIQID = '" . uniqid() . "';");
- $track_type_options = array();
+ $track_type_options = [];
$track_types = Application_Model_Tracktype::getTracktypes();
-
- array_multisort(array_map(function($element) {
+
+ array_multisort(array_map(function ($element) {
return $element['type_name'];
}, $track_types), SORT_ASC, $track_types);
-
+
foreach ($track_types as $key => $tt) {
$track_type_options[$tt['code']] = $tt['type_name'];
}
$ttarr = json_encode($track_type_options, JSON_FORCE_OBJECT);
- $view->headScript()->appendScript("var TRACKTYPES = " . $ttarr . ";");
+ $view->headScript()->appendScript('var TRACKTYPES = ' . $ttarr . ';');
}
protected function _initHeadLink()
@@ -164,14 +165,15 @@ class PageLayoutInitPlugin extends Zend_Controller_Plugin_Abstract
$baseUrl = Application_Common_OsPath::getBaseDir();
- $view->headLink(array('rel' => 'icon', 'href' => $baseUrl . 'favicon.ico?' . $CC_CONFIG['airtime_version'], 'type' => 'image/x-icon'), 'PREPEND')
+ $view->headLink(['rel' => 'icon', 'href' => $baseUrl . 'favicon.ico?' . $CC_CONFIG['airtime_version'], 'type' => 'image/x-icon'], 'PREPEND')
->appendStylesheet($baseUrl . 'css/bootstrap.css?' . $CC_CONFIG['airtime_version'])
->appendStylesheet($baseUrl . 'css/redmond/jquery-ui-1.8.8.custom.css?' . $CC_CONFIG['airtime_version'])
->appendStylesheet($baseUrl . 'css/pro_dropdown_3.css?' . $CC_CONFIG['airtime_version'])
->appendStylesheet($baseUrl . 'css/qtip/jquery.qtip.min.css?' . $CC_CONFIG['airtime_version'])
->appendStylesheet($baseUrl . 'css/styles.css?' . $CC_CONFIG['airtime_version'])
->appendStylesheet($baseUrl . 'css/masterpanel.css?' . $CC_CONFIG['airtime_version'])
- ->appendStylesheet($baseUrl . 'css/tipsy/jquery.tipsy.css?' . $CC_CONFIG['airtime_version']);
+ ->appendStylesheet($baseUrl . 'css/tipsy/jquery.tipsy.css?' . $CC_CONFIG['airtime_version'])
+ ;
}
protected function _initHeadScript()
@@ -200,20 +202,21 @@ class PageLayoutInitPlugin extends Zend_Controller_Plugin_Abstract
->appendFile($baseUrl . 'locale/general-translation-table?' . $CC_CONFIG['airtime_version'], 'text/javascript')
->appendFile($baseUrl . 'locale/datatables-translation-table?' . $CC_CONFIG['airtime_version'], 'text/javascript')
- ->appendScript("$.i18n.setDictionary(general_dict)")
- ->appendScript("var baseUrl='$baseUrl'");
+ ->appendScript('$.i18n.setDictionary(general_dict)')
+ ->appendScript("var baseUrl='{$baseUrl}'")
+ ;
//These timezones are needed to adjust javascript Date objects on the client to make sense to the user's set timezone
//or the server's set timezone.
$serverTimeZone = new DateTimeZone(Application_Model_Preference::GetDefaultTimezone());
- $now = new DateTime("now", $serverTimeZone);
- $offset = $now->format("Z") * -1;
+ $now = new DateTime('now', $serverTimeZone);
+ $offset = $now->format('Z') * -1;
$view->headScript()->appendScript("var serverTimezoneOffset = {$offset}; //in seconds");
- if (class_exists("Zend_Auth", false) && Zend_Auth::getInstance()->hasIdentity()) {
+ if (class_exists('Zend_Auth', false) && Zend_Auth::getInstance()->hasIdentity()) {
$userTimeZone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
- $now = new DateTime("now", $userTimeZone);
- $offset = $now->format("Z") * -1;
+ $now = new DateTime('now', $userTimeZone);
+ $offset = $now->format('Z') * -1;
$view->headScript()->appendScript("var userTimezoneOffset = {$offset}; //in seconds");
}
@@ -225,16 +228,17 @@ class PageLayoutInitPlugin extends Zend_Controller_Plugin_Abstract
->appendFile($baseUrl . 'js/tipsy/jquery.tipsy.js?' . $CC_CONFIG['airtime_version'], 'text/javascript')
->appendFile($baseUrl . 'js/airtime/common/common.js?' . $CC_CONFIG['airtime_version'], 'text/javascript')
- ->appendFile($baseUrl . 'js/airtime/common/audioplaytest.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
+ ->appendFile($baseUrl . 'js/airtime/common/audioplaytest.js?' . $CC_CONFIG['airtime_version'], 'text/javascript')
+ ;
$user = Application_Model_User::getCurrentUser();
if (!is_null($user)) {
$userType = $user->getType();
} else {
- $userType = "";
+ $userType = '';
}
- $view->headScript()->appendScript("var userType = '$userType';");
+ $view->headScript()->appendScript("var userType = '{$userType}';");
}
protected function _initViewHelpers()
diff --git a/legacy/application/controllers/plugins/RabbitMqPlugin.php b/legacy/application/controllers/plugins/RabbitMqPlugin.php
index 3084db4ed..b9f46d303 100644
--- a/legacy/application/controllers/plugins/RabbitMqPlugin.php
+++ b/legacy/application/controllers/plugins/RabbitMqPlugin.php
@@ -5,15 +5,15 @@ class RabbitMqPlugin extends Zend_Controller_Plugin_Abstract
public function dispatchLoopShutdown()
{
if (Application_Model_RabbitMq::$doPush) {
- $md = array('schedule' => Application_Model_Schedule::getSchedule());
- Application_Model_RabbitMq::SendMessageToPypo("update_schedule", $md);
+ $md = ['schedule' => Application_Model_Schedule::getSchedule()];
+ Application_Model_RabbitMq::SendMessageToPypo('update_schedule', $md);
}
- if (memory_get_peak_usage() > 30*pow(2, 20)) {
- Logging::debug("Peak memory usage: "
- .(memory_get_peak_usage()/1000000)
- ." MB while accessing URI ".$_SERVER['REQUEST_URI']);
- Logging::debug("Should try to keep memory footprint under 25 MB");
+ if (memory_get_peak_usage() > 30 * pow(2, 20)) {
+ Logging::debug('Peak memory usage: '
+ . (memory_get_peak_usage() / 1000000)
+ . ' MB while accessing URI ' . $_SERVER['REQUEST_URI']);
+ Logging::debug('Should try to keep memory footprint under 25 MB');
}
}
}
diff --git a/legacy/application/forms/AddShowAbsoluteRebroadcastDates.php b/legacy/application/forms/AddShowAbsoluteRebroadcastDates.php
index 4c43000c0..3625318eb 100644
--- a/legacy/application/forms/AddShowAbsoluteRebroadcastDates.php
+++ b/legacy/application/forms/AddShowAbsoluteRebroadcastDates.php
@@ -2,30 +2,28 @@
class Application_Form_AddShowAbsoluteRebroadcastDates extends Zend_Form_SubForm
{
-
public function init()
{
- $this->setDecorators(array(
- array('ViewScript', array('viewScript' => 'form/add-show-rebroadcast-absolute.phtml'))
- ));
+ $this->setDecorators([
+ ['ViewScript', ['viewScript' => 'form/add-show-rebroadcast-absolute.phtml']],
+ ]);
- for ($i=1; $i<=10; $i++) {
-
- $text = new Zend_Form_Element_Text("add_show_rebroadcast_date_absolute_$i");
+ for ($i = 1; $i <= 10; ++$i) {
+ $text = new Zend_Form_Element_Text("add_show_rebroadcast_date_absolute_{$i}");
$text->setAttrib('class', 'input_text');
$text->addFilter('StringTrim');
- $text->addValidator('date', false, array('YYYY-MM-DD'));
+ $text->addValidator('date', false, ['YYYY-MM-DD']);
$text->setRequired(false);
- $text->setDecorators(array('ViewHelper'));
+ $text->setDecorators(['ViewHelper']);
$this->addElement($text);
- $text = new Zend_Form_Element_Text("add_show_rebroadcast_time_absolute_$i");
+ $text = new Zend_Form_Element_Text("add_show_rebroadcast_time_absolute_{$i}");
$text->setAttrib('class', 'input_text');
$text->addFilter('StringTrim');
- $text->addValidator('date', false, array('HH:mm'));
- $text->addValidator('regex', false, array('/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')));
+ $text->addValidator('date', false, ['HH:mm']);
+ $text->addValidator('regex', false, ['/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')]);
$text->setRequired(false);
- $text->setDecorators(array('ViewHelper'));
+ $text->setDecorators(['ViewHelper']);
$this->addElement($text);
}
}
@@ -35,63 +33,64 @@ class Application_Form_AddShowAbsoluteRebroadcastDates extends Zend_Form_SubForm
$elements = $this->getElements();
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
- $element->setAttrib('disabled','disabled');
+ $element->setAttrib('disabled', 'disabled');
}
}
}
- public function isValid($formData) {
+ public function isValid($formData)
+ {
if (parent::isValid($formData)) {
- return $this->checkReliantFields($formData);
- } else {
- return false;
+ return $this->checkReliantFields($formData);
}
+
+ return false;
}
public function checkReliantFields($formData)
{
$noError = true;
- for ($i=1; $i<=10; $i++) {
-
+ for ($i = 1; $i <= 10; ++$i) {
$valid = true;
- $day = $formData['add_show_rebroadcast_date_absolute_'.$i];
- $time = $formData['add_show_rebroadcast_time_absolute_'.$i];
+ $day = $formData['add_show_rebroadcast_date_absolute_' . $i];
+ $time = $formData['add_show_rebroadcast_time_absolute_' . $i];
- if (trim($day) == "" && trim($time) == "") {
+ if (trim($day) == '' && trim($time) == '') {
continue;
}
- if (trim($day) == "") {
- $this->getElement('add_show_rebroadcast_date_absolute_'.$i)->setErrors(array(_("Day must be specified")));
+ if (trim($day) == '') {
+ $this->getElement('add_show_rebroadcast_date_absolute_' . $i)->setErrors([_('Day must be specified')]);
$valid = false;
}
- if (trim($time) == "") {
- $this->getElement('add_show_rebroadcast_time_absolute_'.$i)->setErrors(array(_("Time must be specified")));
+ if (trim($time) == '') {
+ $this->getElement('add_show_rebroadcast_time_absolute_' . $i)->setErrors([_('Time must be specified')]);
$valid = false;
}
if ($valid === false) {
$noError = false;
+
continue;
}
- $show_start_time = $formData['add_show_start_date']." ".$formData['add_show_start_time'];
+ $show_start_time = $formData['add_show_start_date'] . ' ' . $formData['add_show_start_time'];
$show_end = new DateTime($show_start_time);
$duration = $formData['add_show_duration'];
- $duration = explode(":", $duration);
+ $duration = explode(':', $duration);
- $show_end->add(new DateInterval("PT$duration[0]H"));
- $show_end->add(new DateInterval("PT$duration[1]M"));
- $show_end->add(new DateInterval("PT1H"));//min time to wait until a rebroadcast
+ $show_end->add(new DateInterval("PT{$duration[0]}H"));
+ $show_end->add(new DateInterval("PT{$duration[1]}M"));
+ $show_end->add(new DateInterval('PT1H')); //min time to wait until a rebroadcast
- $rebroad_start = $day." ".$formData['add_show_rebroadcast_time_absolute_'.$i];
+ $rebroad_start = $day . ' ' . $formData['add_show_rebroadcast_time_absolute_' . $i];
$rebroad_start = new DateTime($rebroad_start);
if ($rebroad_start < $show_end) {
- $this->getElement('add_show_rebroadcast_time_absolute_'.$i)->setErrors(array(_("Must wait at least 1 hour to rebroadcast")));
+ $this->getElement('add_show_rebroadcast_time_absolute_' . $i)->setErrors([_('Must wait at least 1 hour to rebroadcast')]);
$valid = false;
$noError = false;
}
diff --git a/legacy/application/forms/AddShowAutoPlaylist.php b/legacy/application/forms/AddShowAutoPlaylist.php
index c987480b2..0d463f910 100644
--- a/legacy/application/forms/AddShowAutoPlaylist.php
+++ b/legacy/application/forms/AddShowAutoPlaylist.php
@@ -4,9 +4,9 @@ class Application_Form_AddShowAutoPlaylist extends Zend_Form_SubForm
{
public function init()
{
- $this->setDecorators(array(
- array('ViewScript', array('viewScript' => 'form/add-show-autoplaylist.phtml'))
- ));
+ $this->setDecorators([
+ ['ViewScript', ['viewScript' => 'form/add-show-autoplaylist.phtml']],
+ ]);
$notEmptyValidator = Application_Form_Helper_ValidationTypes::overrideNotEmptyValidator();
// retrieves the length limit for each char field
@@ -14,26 +14,26 @@ class Application_Form_AddShowAutoPlaylist extends Zend_Form_SubForm
$maxLens = Application_Model_Show::getMaxLengths();
// Add autoplaylist checkbox element
- $this->addElement('checkbox', 'add_show_has_autoplaylist', array(
- 'label' => _('Add Autoloading Playlist ?'),
- 'required' => false,
- 'class' => 'input_text',
- 'decorators' => array('ViewHelper')
- ));
-
- $autoPlaylistSelect = new Zend_Form_Element_Select("add_show_autoplaylist_id");
- $autoPlaylistSelect->setLabel(_("Select Playlist"));
+ $this->addElement('checkbox', 'add_show_has_autoplaylist', [
+ 'label' => _('Add Autoloading Playlist ?'),
+ 'required' => false,
+ 'class' => 'input_text',
+ 'decorators' => ['ViewHelper'],
+ ]);
+
+ $autoPlaylistSelect = new Zend_Form_Element_Select('add_show_autoplaylist_id');
+ $autoPlaylistSelect->setLabel(_('Select Playlist'));
$autoPlaylistSelect->setMultiOptions(Application_Model_Library::getPlaylistNames(true));
$autoPlaylistSelect->setValue(null);
- $autoPlaylistSelect->setDecorators(array('ViewHelper'));
+ $autoPlaylistSelect->setDecorators(['ViewHelper']);
$this->addElement($autoPlaylistSelect);
// Add autoplaylist checkbox element
- $this->addElement('checkbox', 'add_show_autoplaylist_repeat', array(
- 'label' => _('Repeat Playlist Until Show is Full ?'),
- 'required' => false,
- 'class' => 'input_text',
- 'decorators' => array('ViewHelper')
- ));
+ $this->addElement('checkbox', 'add_show_autoplaylist_repeat', [
+ 'label' => _('Repeat Playlist Until Show is Full ?'),
+ 'required' => false,
+ 'class' => 'input_text',
+ 'decorators' => ['ViewHelper'],
+ ]);
}
public function disable()
@@ -41,7 +41,7 @@ class Application_Form_AddShowAutoPlaylist extends Zend_Form_SubForm
$elements = $this->getElements();
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
- $element->setAttrib('disabled','disabled');
+ $element->setAttrib('disabled', 'disabled');
}
}
}
@@ -51,7 +51,7 @@ class Application_Form_AddShowAutoPlaylist extends Zend_Form_SubForm
$elements = $this->getElements();
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
- $element->setAttrib('readonly','readonly');
+ $element->setAttrib('readonly', 'readonly');
}
}
}
diff --git a/legacy/application/forms/AddShowLiveStream.php b/legacy/application/forms/AddShowLiveStream.php
index cd2b7be15..b81bbd5ff 100644
--- a/legacy/application/forms/AddShowLiveStream.php
+++ b/legacy/application/forms/AddShowLiveStream.php
@@ -4,41 +4,44 @@ require_once 'customvalidators/ConditionalNotEmpty.php';
class Application_Form_AddShowLiveStream extends Zend_Form_SubForm
{
-
public function init()
{
- $cb_airtime_auth = new Zend_Form_Element_Checkbox("cb_airtime_auth");
- $cb_airtime_auth->setLabel(sprintf(_("Use %s Authentication:"), PRODUCT_NAME))
- ->setChecked(true)
- ->setRequired(false);
+ $cb_airtime_auth = new Zend_Form_Element_Checkbox('cb_airtime_auth');
+ $cb_airtime_auth->setLabel(sprintf(_('Use %s Authentication:'), PRODUCT_NAME))
+ ->setChecked(true)
+ ->setRequired(false)
+ ;
$this->addElement($cb_airtime_auth);
- $cb_custom_auth = new Zend_Form_Element_Checkbox("cb_custom_auth");
- $cb_custom_auth ->setLabel(_("Use Custom Authentication:"))
- ->setRequired(false);
+ $cb_custom_auth = new Zend_Form_Element_Checkbox('cb_custom_auth');
+ $cb_custom_auth->setLabel(_('Use Custom Authentication:'))
+ ->setRequired(false)
+ ;
$this->addElement($cb_custom_auth);
//custom username
$custom_username = new Zend_Form_Element_Text('custom_username');
$custom_username->setAttrib('class', 'input_text')
- ->setAttrib('autocomplete', 'off')
- ->setAllowEmpty(true)
- ->setLabel(_('Custom Username'))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- new ConditionalNotEmpty(array("cb_custom_auth"=>"1"))));
+ ->setAttrib('autocomplete', 'off')
+ ->setAllowEmpty(true)
+ ->setLabel(_('Custom Username'))
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ new ConditionalNotEmpty(['cb_custom_auth' => '1']), ])
+ ;
$this->addElement($custom_username);
//custom password
$custom_password = new Zend_Form_Element_Password('custom_password');
$custom_password->setAttrib('class', 'input_text')
- ->setAttrib('autocomplete', 'off')
- ->setAttrib('renderPassword','true')
- ->setAllowEmpty(true)
- ->setLabel(_('Custom Password'))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- new ConditionalNotEmpty(array("cb_custom_auth"=>"1"))));
+ ->setAttrib('autocomplete', 'off')
+ ->setAttrib('renderPassword', 'true')
+ ->setAllowEmpty(true)
+ ->setLabel(_('Custom Password'))
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ new ConditionalNotEmpty(['cb_custom_auth' => '1']), ])
+ ;
$this->addElement($custom_password);
$showSourceParams = parse_url(Application_Model_Preference::GetLiveDJSourceConnectionURL());
@@ -47,25 +50,29 @@ class Application_Form_AddShowLiveStream extends Zend_Form_SubForm
$showSourceHost = new Zend_Form_Element_Text('show_source_host');
$showSourceHost->setAttrib('readonly', true)
->setLabel(_('Host:'))
- ->setValue(isset($showSourceParams["host"])?$showSourceParams["host"]:"");
+ ->setValue(isset($showSourceParams['host']) ? $showSourceParams['host'] : '')
+ ;
$this->addElement($showSourceHost);
$showSourcePort = new Zend_Form_Element_Text('show_source_port');
$showSourcePort->setAttrib('readonly', true)
->setLabel(_('Port:'))
- ->setValue(isset($showSourceParams["port"])?$showSourceParams["port"]:"");
+ ->setValue(isset($showSourceParams['port']) ? $showSourceParams['port'] : '')
+ ;
$this->addElement($showSourcePort);
$showSourceMount = new Zend_Form_Element_Text('show_source_mount');
$showSourceMount->setAttrib('readonly', true)
->setLabel(_('Mount:'))
- ->setValue(isset($showSourceParams["path"])?$showSourceParams["path"]:"");
+ ->setValue(isset($showSourceParams['path']) ? $showSourceParams['path'] : '')
+ ;
$this->addElement($showSourceMount);
$this->setDecorators(
- array(
- array('ViewScript', array('viewScript' => 'form/add-show-live-stream.phtml'))
- ));
+ [
+ ['ViewScript', ['viewScript' => 'form/add-show-live-stream.phtml']],
+ ]
+ );
}
public function isValid($data)
@@ -74,13 +81,13 @@ class Application_Form_AddShowLiveStream extends Zend_Form_SubForm
if ($data['cb_custom_auth'] == 1) {
if (trim($data['custom_username']) == '') {
- $element = $this->getElement("custom_username");
- $element->addError(_("Username field cannot be empty."));
+ $element = $this->getElement('custom_username');
+ $element->addError(_('Username field cannot be empty.'));
$isValid = false;
}
if (trim($data['custom_password']) == '') {
- $element = $this->getElement("custom_password");
- $element->addError(_("Password field cannot be empty."));
+ $element = $this->getElement('custom_password');
+ $element->addError(_('Password field cannot be empty.'));
$isValid = false;
}
}
@@ -93,7 +100,7 @@ class Application_Form_AddShowLiveStream extends Zend_Form_SubForm
$elements = $this->getElements();
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
- $element->setAttrib('disabled','disabled');
+ $element->setAttrib('disabled', 'disabled');
}
}
}
diff --git a/legacy/application/forms/AddShowRR.php b/legacy/application/forms/AddShowRR.php
index f1fc4fcfd..2ea7d5e17 100644
--- a/legacy/application/forms/AddShowRR.php
+++ b/legacy/application/forms/AddShowRR.php
@@ -2,20 +2,19 @@
class Application_Form_AddShowRR extends Zend_Form_SubForm
{
-
public function init()
{
// Add record element
- $this->addElement('checkbox', 'add_show_record', array(
- 'label' => _('Record from Line In?'),
- 'required' => false,
- ));
+ $this->addElement('checkbox', 'add_show_record', [
+ 'label' => _('Record from Line In?'),
+ 'required' => false,
+ ]);
// Add record element
- $this->addElement('checkbox', 'add_show_rebroadcast', array(
- 'label' => _('Rebroadcast?'),
- 'required' => false,
- ));
+ $this->addElement('checkbox', 'add_show_rebroadcast', [
+ 'label' => _('Rebroadcast?'),
+ 'required' => false,
+ ]);
}
public function disable()
@@ -23,9 +22,8 @@ class Application_Form_AddShowRR extends Zend_Form_SubForm
$elements = $this->getElements();
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
- $element->setAttrib('disabled','disabled');
+ $element->setAttrib('disabled', 'disabled');
}
}
}
-
}
diff --git a/legacy/application/forms/AddShowRebroadcastDates.php b/legacy/application/forms/AddShowRebroadcastDates.php
index 58d6af872..867345df7 100644
--- a/legacy/application/forms/AddShowRebroadcastDates.php
+++ b/legacy/application/forms/AddShowRebroadcastDates.php
@@ -2,35 +2,33 @@
class Application_Form_AddShowRebroadcastDates extends Zend_Form_SubForm
{
-
public function init()
{
- $this->setDecorators(array(
- array('ViewScript', array('viewScript' => 'form/add-show-rebroadcast.phtml'))
- ));
+ $this->setDecorators([
+ ['ViewScript', ['viewScript' => 'form/add-show-rebroadcast.phtml']],
+ ]);
- $relativeDates = array();
- $relativeDates[""] = "";
- for ($i=0; $i<=30; $i++) {
- $relativeDates["$i days"] = "+$i "._("days");
+ $relativeDates = [];
+ $relativeDates[''] = '';
+ for ($i = 0; $i <= 30; ++$i) {
+ $relativeDates["{$i} days"] = "+{$i} " . _('days');
}
- for ($i=1; $i<=10; $i++) {
-
- $select = new Zend_Form_Element_Select("add_show_rebroadcast_date_$i");
+ for ($i = 1; $i <= 10; ++$i) {
+ $select = new Zend_Form_Element_Select("add_show_rebroadcast_date_{$i}");
$select->setAttrib('class', 'input_select');
$select->setMultiOptions($relativeDates);
$select->setRequired(false);
- $select->setDecorators(array('ViewHelper'));
+ $select->setDecorators(['ViewHelper']);
$this->addElement($select);
- $text = new Zend_Form_Element_Text("add_show_rebroadcast_time_$i");
+ $text = new Zend_Form_Element_Text("add_show_rebroadcast_time_{$i}");
$text->setAttrib('class', 'input_text');
$text->addFilter('StringTrim');
- $text->addValidator('date', false, array('HH:mm'));
- $text->addValidator('regex', false, array('/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')));
+ $text->addValidator('date', false, ['HH:mm']);
+ $text->addValidator('regex', false, ['/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')]);
$text->setRequired(false);
- $text->setDecorators(array('ViewHelper'));
+ $text->setDecorators(['ViewHelper']);
$this->addElement($text);
}
}
@@ -40,67 +38,68 @@ class Application_Form_AddShowRebroadcastDates extends Zend_Form_SubForm
$elements = $this->getElements();
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
- $element->setAttrib('disabled','disabled');
+ $element->setAttrib('disabled', 'disabled');
}
}
}
- public function isValid($formData) {
+ public function isValid($formData)
+ {
if (parent::isValid($formData)) {
- return $this->checkReliantFields($formData);
- } else {
- return false;
+ return $this->checkReliantFields($formData);
}
+
+ return false;
}
public function checkReliantFields($formData)
{
$noError = true;
- for ($i=1; $i<=10; $i++) {
-
+ for ($i = 1; $i <= 10; ++$i) {
$valid = true;
- $days = $formData['add_show_rebroadcast_date_'.$i];
- $time = $formData['add_show_rebroadcast_time_'.$i];
+ $days = $formData['add_show_rebroadcast_date_' . $i];
+ $time = $formData['add_show_rebroadcast_time_' . $i];
- if (trim($days) == "" && trim($time) == "") {
+ if (trim($days) == '' && trim($time) == '') {
continue;
}
- if (trim($days) == "") {
- $this->getElement('add_show_rebroadcast_date_'.$i)->setErrors(array(_("Day must be specified")));
+ if (trim($days) == '') {
+ $this->getElement('add_show_rebroadcast_date_' . $i)->setErrors([_('Day must be specified')]);
$valid = false;
}
- if (trim($time) == "") {
- $this->getElement('add_show_rebroadcast_time_'.$i)->setErrors(array(_("Time must be specified")));
+ if (trim($time) == '') {
+ $this->getElement('add_show_rebroadcast_time_' . $i)->setErrors([_('Time must be specified')]);
$valid = false;
}
if ($valid === false) {
$noError = false;
+
continue;
}
- $days = explode(" ", $days);
+ $days = explode(' ', $days);
$day = $days[0];
- $show_start_time = $formData['add_show_start_date']." ".$formData['add_show_start_time'];
+ $show_start_time = $formData['add_show_start_date'] . ' ' . $formData['add_show_start_time'];
$show_end = new DateTime($show_start_time);
$duration = $formData['add_show_duration'];
- $duration = explode(":", $duration);
+ $duration = explode(':', $duration);
- $show_end->add(new DateInterval("PT$duration[0]H"));
- $show_end->add(new DateInterval("PT$duration[1]M"));
- $show_end->add(new DateInterval("PT1H"));//min time to wait until a rebroadcast
+ $show_end->add(new DateInterval("PT{$duration[0]}H"));
+ $show_end->add(new DateInterval("PT{$duration[1]}M"));
+ $show_end->add(new DateInterval('PT1H')); //min time to wait until a rebroadcast
- $rebroad_start = $formData['add_show_start_date']." ".$formData['add_show_rebroadcast_time_'.$i];
+ $rebroad_start = $formData['add_show_start_date'] . ' ' . $formData['add_show_rebroadcast_time_' . $i];
$rebroad_start = new DateTime($rebroad_start);
- $rebroad_start->add(new DateInterval("P".$day."D"));
+ $rebroad_start->add(new DateInterval('P' . $day . 'D'));
if ($rebroad_start < $show_end) {
- $this->getElement('add_show_rebroadcast_time_'.$i)->setErrors(array(_("Must wait at least 1 hour to rebroadcast")));
+ $this->getElement('add_show_rebroadcast_time_' . $i)->setErrors([_('Must wait at least 1 hour to rebroadcast')]);
$valid = false;
$noError = false;
}
diff --git a/legacy/application/forms/AddShowRepeats.php b/legacy/application/forms/AddShowRepeats.php
index a8179ccd8..e62056a59 100644
--- a/legacy/application/forms/AddShowRepeats.php
+++ b/legacy/application/forms/AddShowRepeats.php
@@ -2,74 +2,75 @@
class Application_Form_AddShowRepeats extends Zend_Form_SubForm
{
-
public function init()
{
-
- $linked = new Zend_Form_Element_Checkbox("add_show_linked");
- $linked->setLabel(_("Link:"));
+ $linked = new Zend_Form_Element_Checkbox('add_show_linked');
+ $linked->setLabel(_('Link:'));
$this->addElement($linked);
//Add type select
- $this->addElement('select', 'add_show_repeat_type', array(
+ $this->addElement('select', 'add_show_repeat_type', [
'required' => true,
'label' => _('Repeat Type:'),
'class' => ' input_select',
- 'multiOptions' => array(
- "0" => _("weekly"),
- "1" => _("every 2 weeks"),
- "4" => _("every 3 weeks"),
- "5" => _("every 4 weeks"),
- "2" => _("monthly")
- ),
- ));
+ 'multiOptions' => [
+ '0' => _('weekly'),
+ '1' => _('every 2 weeks'),
+ '4' => _('every 3 weeks'),
+ '5' => _('every 4 weeks'),
+ '2' => _('monthly'),
+ ],
+ ]);
// Add days checkboxes
$this->addElement(
'multiCheckbox',
'add_show_day_check',
- array(
+ [
'label' => _('Select Days:'),
'required' => false,
- 'multiOptions' => array(
- "0" => _("Sun"),
- "1" => _("Mon"),
- "2" => _("Tue"),
- "3" => _("Wed"),
- "4" => _("Thu"),
- "5" => _("Fri"),
- "6" => _("Sat"),
- ),
- ));
+ 'multiOptions' => [
+ '0' => _('Sun'),
+ '1' => _('Mon'),
+ '2' => _('Tue'),
+ '3' => _('Wed'),
+ '4' => _('Thu'),
+ '5' => _('Fri'),
+ '6' => _('Sat'),
+ ],
+ ]
+ );
- $repeatMonthlyType = new Zend_Form_Element_Radio("add_show_monthly_repeat_type");
- $repeatMonthlyType
- ->setLabel(_("Repeat By:"))
- ->setRequired(true)
- ->setMultiOptions(
- array(2 => _("day of the month"), 3 => _("day of the week")))
- ->setValue(2);
- $this->addElement($repeatMonthlyType);
+ $repeatMonthlyType = new Zend_Form_Element_Radio('add_show_monthly_repeat_type');
+ $repeatMonthlyType
+ ->setLabel(_('Repeat By:'))
+ ->setRequired(true)
+ ->setMultiOptions(
+ [2 => _('day of the month'), 3 => _('day of the week')]
+ )
+ ->setValue(2)
+ ;
+ $this->addElement($repeatMonthlyType);
// Add end date element
- $this->addElement('text', 'add_show_end_date', array(
- 'label' => _('Date End:'),
- 'class' => 'input_text',
- 'value' => date("Y-m-d"),
- 'required' => false,
- 'filters' => array('StringTrim'),
- 'validators' => array(
+ $this->addElement('text', 'add_show_end_date', [
+ 'label' => _('Date End:'),
+ 'class' => 'input_text',
+ 'value' => date('Y-m-d'),
+ 'required' => false,
+ 'filters' => ['StringTrim'],
+ 'validators' => [
'NotEmpty',
- array('date', false, array('YYYY-MM-DD'))
- )
- ));
+ ['date', false, ['YYYY-MM-DD']],
+ ],
+ ]);
// Add no end element
- $this->addElement('checkbox', 'add_show_no_end', array(
- 'label' => _('No End?'),
- 'required' => false,
+ $this->addElement('checkbox', 'add_show_no_end', [
+ 'label' => _('No End?'),
+ 'required' => false,
'checked' => true,
- ));
+ ]);
}
public function disable()
@@ -77,17 +78,18 @@ class Application_Form_AddShowRepeats extends Zend_Form_SubForm
$elements = $this->getElements();
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
- $element->setAttrib('disabled','disabled');
+ $element->setAttrib('disabled', 'disabled');
}
}
}
- public function isValid($formData) {
- if (parent::isValid($formData)) {
+ public function isValid($formData)
+ {
+ if (parent::isValid($formData)) {
return $this->checkReliantFields($formData);
- } else {
- return false;
}
+
+ return false;
}
public function checkReliantFields($formData)
@@ -96,24 +98,25 @@ class Application_Form_AddShowRepeats extends Zend_Form_SubForm
$start_timestamp = $formData['add_show_start_date'];
$end_timestamp = $formData['add_show_end_date'];
$showTimeZone = new DateTimeZone($formData['add_show_timezone']);
-
+
//We're assuming all data is valid at this point (timezone, etc.).
-
+
$startDate = new DateTime($start_timestamp, $showTimeZone);
$endDate = new DateTime($end_timestamp, $showTimeZone);
-
+
if ($endDate < $startDate) {
- $this->getElement('add_show_end_date')->setErrors(array(_('End date must be after start date')));
+ $this->getElement('add_show_end_date')->setErrors([_('End date must be after start date')]);
+
return false;
}
+
return true;
}
if (!isset($formData['add_show_day_check'])) {
- $this->getElement('add_show_day_check')->setErrors(array(_('Please select a repeat day')));
+ $this->getElement('add_show_day_check')->setErrors([_('Please select a repeat day')]);
}
return true;
}
-
}
diff --git a/legacy/application/forms/AddShowStyle.php b/legacy/application/forms/AddShowStyle.php
index 0448df055..74bd260c5 100644
--- a/legacy/application/forms/AddShowStyle.php
+++ b/legacy/application/forms/AddShowStyle.php
@@ -4,102 +4,103 @@ require_once 'customfilters/ImageSize.php';
class Application_Form_AddShowStyle extends Zend_Form_SubForm
{
-
public function init()
{
- // Add show background-color input
- $this->addElement('text', 'add_show_background_color', array(
- 'label' => _('Background Colour:'),
- 'class' => 'input_text',
- 'filters' => array('StringTrim')
- ));
+ // Add show background-color input
+ $this->addElement('text', 'add_show_background_color', [
+ 'label' => _('Background Colour:'),
+ 'class' => 'input_text',
+ 'filters' => ['StringTrim'],
+ ]);
$bg = $this->getElement('add_show_background_color');
- $bg->setDecorators(array(array('ViewScript', array(
+ $bg->setDecorators([['ViewScript', [
'viewScript' => 'form/add-show-style.phtml',
- 'class' => 'big'
- ))));
+ 'class' => 'big',
+ ]]]);
$stringLengthValidator = Application_Form_Helper_ValidationTypes::overrideStringLengthValidator(6, 6);
- $bg->setValidators(array(
- 'Hex', $stringLengthValidator
- ));
+ $bg->setValidators([
+ 'Hex', $stringLengthValidator,
+ ]);
- // Add show color input
- $this->addElement('text', 'add_show_color', array(
- 'label' => _('Text Colour:'),
- 'class' => 'input_text',
- 'filters' => array('StringTrim')
- ));
+ // Add show color input
+ $this->addElement('text', 'add_show_color', [
+ 'label' => _('Text Colour:'),
+ 'class' => 'input_text',
+ 'filters' => ['StringTrim'],
+ ]);
$c = $this->getElement('add_show_color');
- $c->setDecorators(array(array('ViewScript', array(
+ $c->setDecorators([['ViewScript', [
'viewScript' => 'form/add-show-style.phtml',
- 'class' => 'big'
- ))));
+ 'class' => 'big',
+ ]]]);
+
+ $c->setValidators([
+ 'Hex', $stringLengthValidator,
+ ]);
- $c->setValidators(array(
- 'Hex', $stringLengthValidator
- ));
-
// Show the current logo
- $this->addElement('image', 'add_show_logo_current', array(
- 'label' => _('Current Logo:'),
- ));
-
+ $this->addElement('image', 'add_show_logo_current', [
+ 'label' => _('Current Logo:'),
+ ]);
+
$logo = $this->getElement('add_show_logo_current');
- $logo->setDecorators(array(
- array('ViewScript', array(
- 'viewScript' => 'form/add-show-style.phtml',
- 'class' => 'big'
- ))
- ));
+ $logo->setDecorators([
+ ['ViewScript', [
+ 'viewScript' => 'form/add-show-style.phtml',
+ 'class' => 'big',
+ ]],
+ ]);
// Since we need to use a Zend_Form_Element_Image proto, disable it
- $logo->setAttrib('disabled','disabled');
-
+ $logo->setAttrib('disabled', 'disabled');
+
// Button to remove the current logo
- $this->addElement('button', 'add_show_logo_current_remove', array(
- 'label' => '' . _('Remove') . '',
- 'class' => 'ui-button ui-state-default ui-button-text-only',
- 'escape' => false
- ));
-
+ $this->addElement('button', 'add_show_logo_current_remove', [
+ 'label' => '' . _('Remove') . '',
+ 'class' => 'ui-button ui-state-default ui-button-text-only',
+ 'escape' => false,
+ ]);
+
// Add show image input
$upload = new Zend_Form_Element_File('add_show_logo');
-
+
$upload->setLabel(_('Show Logo:'))
- ->setRequired(false)
- ->setDecorators(array('File', array('ViewScript', array(
- 'viewScript' => 'form/add-show-style.phtml',
- 'class' => 'big',
- 'placement' => false
- ))))
- ->addValidator('Count', false, 1)
- ->addValidator('Extension', false, 'jpg,jpeg,png,gif')
- ->addFilter('ImageSize');
+ ->setRequired(false)
+ ->setDecorators(['File', ['ViewScript', [
+ 'viewScript' => 'form/add-show-style.phtml',
+ 'class' => 'big',
+ 'placement' => false,
+ ]]])
+ ->addValidator('Count', false, 1)
+ ->addValidator('Extension', false, 'jpg,jpeg,png,gif')
+ ->addFilter('ImageSize')
+ ;
$this->addElement($upload);
-
+
// Add image preview
- $this->addElement('image', 'add_show_logo_preview', array(
- 'label' => _('Logo Preview:'),
- ));
-
+ $this->addElement('image', 'add_show_logo_preview', [
+ 'label' => _('Logo Preview:'),
+ ]);
+
$preview = $this->getElement('add_show_logo_preview');
- $preview->setDecorators(array(array('ViewScript', array(
- 'viewScript' => 'form/add-show-style.phtml',
- 'class' => 'big'
- ))));
- $preview->setAttrib('disabled','disabled');
+ $preview->setDecorators([['ViewScript', [
+ 'viewScript' => 'form/add-show-style.phtml',
+ 'class' => 'big',
+ ]]]);
+ $preview->setAttrib('disabled', 'disabled');
$csrf_namespace = new Zend_Session_Namespace('csrf_namespace');
$csrf_element = new Zend_Form_Element_Hidden('csrf');
$csrf_element->setValue($csrf_namespace->authtoken)
->setRequired('true')
->removeDecorator('HtmlTag')
- ->removeDecorator('Label');
+ ->removeDecorator('Label')
+ ;
$this->addElement($csrf_element);
}
@@ -110,14 +111,14 @@ class Application_Form_AddShowStyle extends Zend_Form_SubForm
if ($element->getType() != 'Zend_Form_Element_Hidden'
// We should still be able to remove the show logo
&& $element->getName() != 'add_show_logo_current_remove') {
- $element->setAttrib('disabled','disabled');
+ $element->setAttrib('disabled', 'disabled');
}
}
}
- public function hideShowLogo() {
+ public function hideShowLogo()
+ {
$this->removeElement('add_show_logo');
$this->removeElement('add_show_logo_preview');
}
-
}
diff --git a/legacy/application/forms/AddShowWhat.php b/legacy/application/forms/AddShowWhat.php
index 22111bec0..eb668b997 100644
--- a/legacy/application/forms/AddShowWhat.php
+++ b/legacy/application/forms/AddShowWhat.php
@@ -11,78 +11,78 @@ class Application_Form_AddShowWhat extends Zend_Form_SubForm
// Hidden element to indicate whether the show is new or
// whether we are updating an existing show.
- $this->addElement('hidden', 'add_show_id', array(
- 'decorators' => array('ViewHelper')
- ));
+ $this->addElement('hidden', 'add_show_id', [
+ 'decorators' => ['ViewHelper'],
+ ]);
// Hidden element to indicate the instance id of the show
// being edited.
- $this->addElement('hidden', 'add_show_instance_id', array(
- 'decorators' => array('ViewHelper')
- ));
+ $this->addElement('hidden', 'add_show_instance_id', [
+ 'decorators' => ['ViewHelper'],
+ ]);
// Add name element
- $this->addElement('text', 'add_show_name', array(
- 'label' => _('Name:'),
- 'class' => 'input_text',
- 'required' => true,
- 'filters' => array('StringTrim'),
- 'value' => _('Untitled Show'),
- 'validators' => array($notEmptyValidator, array('StringLength', false, array(0, $maxLens['name'])))
- ));
+ $this->addElement('text', 'add_show_name', [
+ 'label' => _('Name:'),
+ 'class' => 'input_text',
+ 'required' => true,
+ 'filters' => ['StringTrim'],
+ 'value' => _('Untitled Show'),
+ 'validators' => [$notEmptyValidator, ['StringLength', false, [0, $maxLens['name']]]],
+ ]);
- // Add URL element
- $this->addElement('text', 'add_show_url', array(
- 'label' => _('URL:'),
- 'class' => 'input_text',
- 'required' => false,
- 'filters' => array('StringTrim'),
- 'validators' => array($notEmptyValidator, array('StringLength', false, array(0, $maxLens['url'])))
- ));
+ // Add URL element
+ $this->addElement('text', 'add_show_url', [
+ 'label' => _('URL:'),
+ 'class' => 'input_text',
+ 'required' => false,
+ 'filters' => ['StringTrim'],
+ 'validators' => [$notEmptyValidator, ['StringLength', false, [0, $maxLens['url']]]],
+ ]);
- // Add genre element
- $this->addElement('text', 'add_show_genre', array(
- 'label' => _('Genre:'),
- 'class' => 'input_text',
- 'required' => false,
- 'filters' => array('StringTrim'),
- 'validators' => array(array('StringLength', false, array(0, $maxLens['genre'])))
- ));
+ // Add genre element
+ $this->addElement('text', 'add_show_genre', [
+ 'label' => _('Genre:'),
+ 'class' => 'input_text',
+ 'required' => false,
+ 'filters' => ['StringTrim'],
+ 'validators' => [['StringLength', false, [0, $maxLens['genre']]]],
+ ]);
- // Add the description element
- $this->addElement('textarea', 'add_show_description', array(
- 'label' => _('Description:'),
- 'required' => false,
- 'class' => 'input_text_area',
- 'validators' => array(array('StringLength', false, array(0, $maxLens['description'])))
- ));
+ // Add the description element
+ $this->addElement('textarea', 'add_show_description', [
+ 'label' => _('Description:'),
+ 'required' => false,
+ 'class' => 'input_text_area',
+ 'validators' => [['StringLength', false, [0, $maxLens['description']]]],
+ ]);
$descText = $this->getElement('add_show_description');
- $descText->setDecorators(array(array('ViewScript', array(
+ $descText->setDecorators([['ViewScript', [
'viewScript' => 'form/add-show-block.phtml',
- 'class' => 'block-display'
- ))));
-
+ 'class' => 'block-display',
+ ]]]);
+
// Add the instance description
- $this->addElement('textarea', 'add_show_instance_description', array(
- 'label' => _('Instance Description:'),
- 'required' => false,
- 'class' => 'input_text_area',
- 'validators' => array(array('StringLength', false, array(0, $maxLens['description'])))
- ));
-
+ $this->addElement('textarea', 'add_show_instance_description', [
+ 'label' => _('Instance Description:'),
+ 'required' => false,
+ 'class' => 'input_text_area',
+ 'validators' => [['StringLength', false, [0, $maxLens['description']]]],
+ ]);
+
$instanceDesc = $this->getElement('add_show_instance_description');
- $instanceDesc->setDecorators(array(array('ViewScript', array(
- 'viewScript' => 'form/add-show-block.phtml',
- 'class' => 'block-display'
- ))));
- $instanceDesc->setAttrib('disabled','disabled');
+ $instanceDesc->setDecorators([['ViewScript', [
+ 'viewScript' => 'form/add-show-block.phtml',
+ 'class' => 'block-display',
+ ]]]);
+ $instanceDesc->setAttrib('disabled', 'disabled');
}
/**
- * Enable the instance description when editing a show instance
+ * Enable the instance description when editing a show instance.
*/
public function enableInstanceDesc()
{
@@ -97,7 +97,7 @@ class Application_Form_AddShowWhat extends Zend_Form_SubForm
$elements = $this->getElements();
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
- $element->setAttrib('disabled','disabled');
+ $element->setAttrib('disabled', 'disabled');
}
}
}
@@ -107,7 +107,7 @@ class Application_Form_AddShowWhat extends Zend_Form_SubForm
$elements = $this->getElements();
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
- $element->setAttrib('readonly','readonly');
+ $element->setAttrib('readonly', 'readonly');
}
}
}
diff --git a/legacy/application/forms/AddShowWhen.php b/legacy/application/forms/AddShowWhen.php
index f5e4dccf2..1a96b35fb 100644
--- a/legacy/application/forms/AddShowWhen.php
+++ b/legacy/application/forms/AddShowWhen.php
@@ -2,45 +2,45 @@
class Application_Form_AddShowWhen extends Zend_Form_SubForm
{
-
public function init()
{
- $this->setDecorators(array(
- array('ViewScript', array('viewScript' => 'form/add-show-when.phtml'))
- ));
+ $this->setDecorators([
+ ['ViewScript', ['viewScript' => 'form/add-show-when.phtml']],
+ ]);
$notEmptyValidator = Application_Form_Helper_ValidationTypes::overrideNotEmptyValidator();
- $dateValidator = Application_Form_Helper_ValidationTypes::overrrideDateValidator("YYYY-MM-DD");
+ $dateValidator = Application_Form_Helper_ValidationTypes::overrrideDateValidator('YYYY-MM-DD');
$regexValidator = Application_Form_Helper_ValidationTypes::overrideRegexValidator(
- "/^[0-2]?[0-9]:[0-5][0-9]$/",
- _("'%value%' does not fit the time format 'HH:mm'"));
-
+ '/^[0-2]?[0-9]:[0-5][0-9]$/',
+ _("'%value%' does not fit the time format 'HH:mm'")
+ );
// Add start date element
$startNow = new Zend_Form_Element_Radio('add_show_start_now');
$startNow->setRequired(false)
->setLabel(_('Start Time:'))
- ->addMultiOptions(array(
+ ->addMultiOptions([
'now' => _('Now'),
- 'future' => _('In the Future:')
- ))
+ 'future' => _('In the Future:'),
+ ])
->setValue('future')
- ->setDecorators(array('ViewHelper'));
+ ->setDecorators(['ViewHelper'])
+ ;
//$startDate->setAttrib('alt', 'date');
$this->addElement($startNow);
-
// Add start date element
$startDate = new Zend_Form_Element_Text('add_show_start_date');
$startDate->class = 'input_text';
$startDate->setRequired(true)
- ->setLabel(_('In the Future:'))
- ->setValue(date("Y-m-d"))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- $notEmptyValidator,
- $dateValidator))
- ->setDecorators(array('ViewHelper'));
+ ->setLabel(_('In the Future:'))
+ ->setValue(date('Y-m-d'))
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ $notEmptyValidator,
+ $dateValidator, ])
+ ->setDecorators(['ViewHelper'])
+ ;
$startDate->setAttrib('alt', 'date');
$this->addElement($startDate);
@@ -48,12 +48,12 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
$startTime = new Zend_Form_Element_Text('add_show_start_time');
$startTime->class = 'input_text';
$startTime->setRequired(true)
- ->setValue('00:00')
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- $notEmptyValidator,
- $regexValidator
- ))->setDecorators(array('ViewHelper'));
+ ->setValue('00:00')
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ $notEmptyValidator,
+ $regexValidator,
+ ])->setDecorators(['ViewHelper']);
$startTime->setAttrib('alt', 'time');
$this->addElement($startTime);
@@ -61,13 +61,14 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
$endDate = new Zend_Form_Element_Text('add_show_end_date_no_repeat');
$endDate->class = 'input_text';
$endDate->setRequired(true)
- ->setLabel(_('End Time:'))
- ->setValue(date("Y-m-d"))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- $notEmptyValidator,
- $dateValidator))
- ->setDecorators(array('ViewHelper'));
+ ->setLabel(_('End Time:'))
+ ->setValue(date('Y-m-d'))
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ $notEmptyValidator,
+ $dateValidator, ])
+ ->setDecorators(['ViewHelper'])
+ ;
$endDate->setAttrib('alt', 'date');
$this->addElement($endDate);
@@ -75,76 +76,87 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
$endTime = new Zend_Form_Element_Text('add_show_end_time');
$endTime->class = 'input_text';
$endTime->setRequired(true)
- ->setValue('01:00')
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- $notEmptyValidator,
- $regexValidator))
- ->setDecorators(array('ViewHelper'));
+ ->setValue('01:00')
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ $notEmptyValidator,
+ $regexValidator, ])
+ ->setDecorators(['ViewHelper'])
+ ;
$endTime->setAttrib('alt', 'time');
$this->addElement($endTime);
// Add duration element
- $this->addElement('text', 'add_show_duration', array(
- 'label' => _('Duration:'),
- 'class' => 'input_text',
- 'value' => '01h 00m',
- 'readonly' => true,
- 'decorators' => array('ViewHelper')
- ));
+ $this->addElement('text', 'add_show_duration', [
+ 'label' => _('Duration:'),
+ 'class' => 'input_text',
+ 'value' => '01h 00m',
+ 'readonly' => true,
+ 'decorators' => ['ViewHelper'],
+ ]);
$timezone = new Zend_Form_Element_Select('add_show_timezone');
$timezone->setRequired(true)
- ->setLabel(_("Timezone:"))
- ->setMultiOptions(Application_Common_Timezone::getTimezones())
- ->setValue(Application_Model_Preference::GetUserTimezone())
- ->setAttrib('class', 'input_select add_show_input_select')
- ->setDecorators(array('ViewHelper'));
+ ->setLabel(_('Timezone:'))
+ ->setMultiOptions(Application_Common_Timezone::getTimezones())
+ ->setValue(Application_Model_Preference::GetUserTimezone())
+ ->setAttrib('class', 'input_select add_show_input_select')
+ ->setDecorators(['ViewHelper'])
+ ;
$this->addElement($timezone);
// Add repeats element
- $this->addElement('checkbox', 'add_show_repeats', array(
- 'label' => _('Repeats?'),
- 'required' => false,
- 'decorators' => array('ViewHelper')
- ));
-
+ $this->addElement('checkbox', 'add_show_repeats', [
+ 'label' => _('Repeats?'),
+ 'required' => false,
+ 'decorators' => ['ViewHelper'],
+ ]);
}
- public function isWhenFormValid($formData, $validateStartDate, $originalStartDate,
- $update, $instanceId) {
+ public function isWhenFormValid(
+ $formData,
+ $validateStartDate,
+ $originalStartDate,
+ $update,
+ $instanceId
+ ) {
if (parent::isValid($formData)) {
- return self::checkReliantFields($formData, $validateStartDate,
- $originalStartDate, $update, $instanceId);
- } else {
- return false;
+ return self::checkReliantFields(
+ $formData,
+ $validateStartDate,
+ $originalStartDate,
+ $update,
+ $instanceId
+ );
}
+
+ return false;
}
- public function checkReliantFields($formData, $validateStartDate, $originalStartDate=null, $update=false, $instanceId=null)
+ public function checkReliantFields($formData, $validateStartDate, $originalStartDate = null, $update = false, $instanceId = null)
{
$valid = true;
- $start_time = $formData['add_show_start_date']." ".$formData['add_show_start_time'];
- $end_time = $formData['add_show_end_date_no_repeat']." ".$formData['add_show_end_time'];
+ $start_time = $formData['add_show_start_date'] . ' ' . $formData['add_show_start_time'];
+ $end_time = $formData['add_show_end_date_no_repeat'] . ' ' . $formData['add_show_end_time'];
//have to use the timezone the user has entered in the form to check past/present
- $showTimezone = new DateTimeZone($formData["add_show_timezone"]);
- $nowDateTime = new DateTime("now", $showTimezone);
+ $showTimezone = new DateTimeZone($formData['add_show_timezone']);
+ $nowDateTime = new DateTime('now', $showTimezone);
$showStartDateTime = new DateTime($start_time, $showTimezone);
$showEndDateTime = new DateTime($end_time, $showTimezone);
- if ($validateStartDate && ($formData['add_show_start_now'] != "now")) {
+ if ($validateStartDate && ($formData['add_show_start_now'] != 'now')) {
if ($showStartDateTime < $nowDateTime) {
- $this->getElement('add_show_start_time')->setErrors(array(_('Cannot create show in the past')));
+ $this->getElement('add_show_start_time')->setErrors([_('Cannot create show in the past')]);
$valid = false;
}
// if edit action, check if original show start time is in the past. CC-3864
if ($originalStartDate) {
if ($originalStartDate < $nowDateTime) {
- $this->getElement('add_show_start_time')->setValue($originalStartDate->format("H:i"));
- $this->getElement('add_show_start_date')->setValue($originalStartDate->format("Y-m-d"));
- $this->getElement('add_show_start_time')->setErrors(array(_('Cannot modify start date/time of the show that is already started')));
+ $this->getElement('add_show_start_time')->setValue($originalStartDate->format('H:i'));
+ $this->getElement('add_show_start_date')->setValue($originalStartDate->format('Y-m-d'));
+ $this->getElement('add_show_start_time')->setErrors([_('Cannot modify start date/time of the show that is already started')]);
$this->disableStartDateAndTime();
$valid = false;
}
@@ -153,7 +165,7 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
// if end time is in the past, return error
if ($showEndDateTime < $nowDateTime) {
- $this->getElement('add_show_end_time')->setErrors(array(_('End date/time cannot be in the past')));
+ $this->getElement('add_show_end_time')->setErrors([_('End date/time cannot be in the past')]);
$valid = false;
}
@@ -161,75 +173,71 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
$duration = $showStartDateTime->diff($showEndDateTime);
if ($showStartDateTime > $showEndDateTime) {
- $this->getElement('add_show_duration')->setErrors(array(_('Cannot have duration < 0m')));
- $valid = false;
+ $this->getElement('add_show_duration')->setErrors([_('Cannot have duration < 0m')]);
+ $valid = false;
+ } elseif ($showStartDateTime == $showEndDateTime) {
+ $this->getElement('add_show_duration')->setErrors([_('Cannot have duration 00h 00m')]);
+ $valid = false;
+ } elseif (intval($duration->format('%d')) > 0
+ && (intval($duration->format('%h')) > 0
+ || intval($duration->format('%i')) > 0
+ || intval($duration->format('%s')) > 0)) {
+ $this->getElement('add_show_duration')->setErrors([_('Cannot have duration greater than 24h')]);
+ $valid = false;
}
- else if ($showStartDateTime == $showEndDateTime) {
- $this->getElement('add_show_duration')->setErrors(array(_('Cannot have duration 00h 00m')));
- $valid = false;
- }
- else if (intval($duration->format('%d')) > 0 &&
- (intval($duration->format('%h')) > 0
- || intval($duration->format('%i')) > 0
- || intval($duration->format('%s')) > 0)) {
- $this->getElement('add_show_duration')->setErrors(array(_('Cannot have duration greater than 24h')));
- $valid = false;
- }
-
/* We need to know the show duration broken down into hours and minutes
* They are used for checking overlapping shows and for validating
* rebroadcast instances
*/
- $hours = $duration->format("%h");
- $minutes = $duration->format("%i");
+ $hours = $duration->format('%h');
+ $minutes = $duration->format('%i');
/* Check if show is overlapping
* We will only do this check if the show is valid
* upto this point
*/
if ($valid) {
- //we need to know the start day of the week in show's local timezome
- $startDow = $showStartDateTime->format("w");
+ //we need to know the start day of the week in show's local timezome
+ $startDow = $showStartDateTime->format('w');
$utc = new DateTimeZone('UTC');
$showStartDateTime->setTimezone($utc);
$showEndDateTime->setTimezone($utc);
- if ($formData["add_show_repeats"]) {
-
+ if ($formData['add_show_repeats']) {
//get repeating show end date
- if ($formData["add_show_no_end"]) {
+ if ($formData['add_show_no_end']) {
$date = Application_Model_Preference::GetShowsPopulatedUntil();
if (is_null($date)) {
- $populateUntilDateTime = new DateTime("now", $utc);
+ $populateUntilDateTime = new DateTime('now', $utc);
Application_Model_Preference::SetShowsPopulatedUntil($populateUntilDateTime);
} else {
$populateUntilDateTime = clone $date;
}
-
- } elseif (!$formData["add_show_no_end"]) {
- $popUntil = $formData["add_show_end_date"]." ".$formData["add_show_end_time"];
+ } elseif (!$formData['add_show_no_end']) {
+ $popUntil = $formData['add_show_end_date'] . ' ' . $formData['add_show_end_time'];
$populateUntilDateTime = new DateTime($popUntil, $showTimezone);
$populateUntilDateTime->setTimezone($utc);
}
//get repeat interval
- if ($formData["add_show_repeat_type"] == 0) {
+ if ($formData['add_show_repeat_type'] == 0) {
$interval = 'P7D';
- } elseif ($formData["add_show_repeat_type"] == 1) {
+ } elseif ($formData['add_show_repeat_type'] == 1) {
$interval = 'P14D';
- } elseif ($formData["add_show_repeat_type"] == 4) {
+ } elseif ($formData['add_show_repeat_type'] == 4) {
$interval = 'P21D';
- } elseif ($formData["add_show_repeat_type"] == 5) {
+ } elseif ($formData['add_show_repeat_type'] == 5) {
$interval = 'P28D';
- } elseif ($formData["add_show_repeat_type"] == 2 && $formData["add_show_monthly_repeat_type"] == 2) {
+ } elseif ($formData['add_show_repeat_type'] == 2 && $formData['add_show_monthly_repeat_type'] == 2) {
$interval = 'P1M';
- } elseif ($formData["add_show_repeat_type"] == 2 && $formData["add_show_monthly_repeat_type"] == 3) {
+ } elseif ($formData['add_show_repeat_type'] == 2 && $formData['add_show_monthly_repeat_type'] == 3) {
list($weekNumberOfMonth, $dayOfWeek) =
Application_Service_ShowService::getMonthlyWeeklyRepeatInterval(
- new DateTime($start_time, $showTimezone));
+ new DateTime($start_time, $showTimezone)
+ );
}
/* Check first show
@@ -237,30 +245,37 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
*/
if ($update) {
$overlapping = Application_Model_Schedule::checkOverlappingShows(
- $showStartDateTime, $showEndDateTime, $update, null, $formData["add_show_id"]);
+ $showStartDateTime,
+ $showEndDateTime,
+ $update,
+ null,
+ $formData['add_show_id']
+ );
} else {
$overlapping = Application_Model_Schedule::checkOverlappingShows(
- $showStartDateTime, $showEndDateTime);
+ $showStartDateTime,
+ $showEndDateTime
+ );
}
/* Check if repeats overlap with previously scheduled shows
* Do this for each show day
*/
if (!$overlapping) {
-
if (!isset($formData['add_show_day_check'])) {
return false;
}
- foreach ($formData["add_show_day_check"] as $day) {
+ foreach ($formData['add_show_day_check'] as $day) {
$repeatShowStart = clone $showStartDateTime;
$repeatShowEnd = clone $showEndDateTime;
- $daysAdd=0;
+ $daysAdd = 0;
if ($startDow !== $day) {
- if ($startDow > $day)
+ if ($startDow > $day) {
$daysAdd = 6 - $startDow + 1 + $day;
- else
+ } else {
$daysAdd = $day - $startDow;
+ }
/* In case we are crossing daylights saving time we need
* to convert show start and show end to local time before
@@ -268,8 +283,8 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
*/
$repeatShowStart->setTimezone($showTimezone);
$repeatShowEnd->setTimezone($showTimezone);
- $repeatShowStart->add(new DateInterval("P".$daysAdd."D"));
- $repeatShowEnd->add(new DateInterval("P".$daysAdd."D"));
+ $repeatShowStart->add(new DateInterval('P' . $daysAdd . 'D'));
+ $repeatShowEnd->add(new DateInterval('P' . $daysAdd . 'D'));
//set back to UTC
$repeatShowStart->setTimezone($utc);
$repeatShowEnd->setTimezone($utc);
@@ -282,49 +297,58 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
if ($formData['add_show_id'] == -1) {
//this is a new show
$overlapping = Application_Model_Schedule::checkOverlappingShows(
- $repeatShowStart, $repeatShowEnd);
+ $repeatShowStart,
+ $repeatShowEnd
+ );
} else {
$overlapping = Application_Model_Schedule::checkOverlappingShows(
- $repeatShowStart, $repeatShowEnd, $update, null, $formData["add_show_id"]);
+ $repeatShowStart,
+ $repeatShowEnd,
+ $update,
+ null,
+ $formData['add_show_id']
+ );
}
if ($overlapping) {
$valid = false;
- $this->getElement('add_show_duration')->setErrors(array(_('Cannot schedule overlapping shows')));
- break 1;
+ $this->getElement('add_show_duration')->setErrors([_('Cannot schedule overlapping shows')]);
+
+ break;
+ }
+ if ($formData['add_show_repeat_type'] == 2 && $formData['add_show_monthly_repeat_type'] == 3) {
+ $monthlyWeeklyStart = new DateTime(
+ $repeatShowStart->format('Y-m'),
+ new DateTimeZone('UTC')
+ );
+ $monthlyWeeklyStart->add(new DateInterval('P1M'));
+ $repeatShowStart = clone Application_Service_ShowService::getNextMonthlyWeeklyRepeatDate(
+ $monthlyWeeklyStart,
+ $formData['add_show_timezone'],
+ $formData['add_show_start_time'],
+ $weekNumberOfMonth,
+ $dayOfWeek
+ );
+ $repeatShowEnd = clone $repeatShowStart;
+ $repeatShowEnd->add(new DateInterval('PT' . $hours . 'H' . $minutes . 'M'));
} else {
- if ($formData["add_show_repeat_type"] == 2 && $formData["add_show_monthly_repeat_type"] == 3) {
- $monthlyWeeklyStart = new DateTime($repeatShowStart->format("Y-m"),
- new DateTimeZone("UTC"));
- $monthlyWeeklyStart->add(new DateInterval("P1M"));
- $repeatShowStart = clone Application_Service_ShowService::getNextMonthlyWeeklyRepeatDate(
- $monthlyWeeklyStart,
- $formData["add_show_timezone"],
- $formData['add_show_start_time'],
- $weekNumberOfMonth,
- $dayOfWeek);
- $repeatShowEnd = clone $repeatShowStart;
- $repeatShowEnd->add(new DateInterval("PT".$hours."H".$minutes."M"));
- } else {
- $repeatShowStart->setTimezone($showTimezone);
- $repeatShowEnd->setTimezone($showTimezone);
- $repeatShowStart->add(new DateInterval($interval));
- $repeatShowEnd->add(new DateInterval($interval));
- $repeatShowStart->setTimezone($utc);
- $repeatShowEnd->setTimezone($utc);
- }
+ $repeatShowStart->setTimezone($showTimezone);
+ $repeatShowEnd->setTimezone($showTimezone);
+ $repeatShowStart->add(new DateInterval($interval));
+ $repeatShowEnd->add(new DateInterval($interval));
+ $repeatShowStart->setTimezone($utc);
+ $repeatShowEnd->setTimezone($utc);
}
}
}
} else {
$valid = false;
- $this->getElement('add_show_duration')->setErrors(array(_('Cannot schedule overlapping shows')));
+ $this->getElement('add_show_duration')->setErrors([_('Cannot schedule overlapping shows')]);
}
-
} else {
- $overlapping = Application_Model_Schedule::checkOverlappingShows($showStartDateTime, $showEndDateTime, $update, $instanceId);
+ $overlapping = Application_Model_Schedule::checkOverlappingShows($showStartDateTime, $showEndDateTime, $update, $instanceId);
if ($overlapping) {
- $this->getElement('add_show_duration')->setErrors(array(_('Cannot schedule overlapping shows')));
+ $this->getElement('add_show_duration')->setErrors([_('Cannot schedule overlapping shows')]);
$valid = false;
}
}
@@ -333,34 +357,47 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
return $valid;
}
- public function checkRebroadcastDates($repeatShowStart, $formData, $hours, $minutes, $showEdit=false) {
+ public function checkRebroadcastDates($repeatShowStart, $formData, $hours, $minutes, $showEdit = false)
+ {
$overlapping = false;
- for ($i = 1; $i <= 10; $i++) {
- if (empty($formData["add_show_rebroadcast_date_".$i])) break;
+ for ($i = 1; $i <= 10; ++$i) {
+ if (empty($formData['add_show_rebroadcast_date_' . $i])) {
+ break;
+ }
$rebroadcastShowStart = clone $repeatShowStart;
/* formData is in local time so we need to set the
* show start back to local time
*/
$rebroadcastShowStart->setTimezone(new DateTimeZone(
- $formData["add_show_timezone"]));
- $rebroadcastWhenDays = explode(" ", $formData["add_show_rebroadcast_date_".$i]);
- $rebroadcastWhenTime = explode(":", $formData["add_show_rebroadcast_time_".$i]);
- $rebroadcastShowStart->add(new DateInterval("P".$rebroadcastWhenDays[0]."D"));
+ $formData['add_show_timezone']
+ ));
+ $rebroadcastWhenDays = explode(' ', $formData['add_show_rebroadcast_date_' . $i]);
+ $rebroadcastWhenTime = explode(':', $formData['add_show_rebroadcast_time_' . $i]);
+ $rebroadcastShowStart->add(new DateInterval('P' . $rebroadcastWhenDays[0] . 'D'));
$rebroadcastShowStart->setTime($rebroadcastWhenTime[0], $rebroadcastWhenTime[1]);
$rebroadcastShowStart->setTimezone(new DateTimeZone('UTC'));
$rebroadcastShowEnd = clone $rebroadcastShowStart;
- $rebroadcastShowEnd->add(new DateInterval("PT".$hours."H".$minutes."M"));
+ $rebroadcastShowEnd->add(new DateInterval('PT' . $hours . 'H' . $minutes . 'M'));
if ($showEdit) {
$overlapping = Application_Model_Schedule::checkOverlappingShows(
- $rebroadcastShowStart, $rebroadcastShowEnd, true, null, $formData['add_show_id']);
+ $rebroadcastShowStart,
+ $rebroadcastShowEnd,
+ true,
+ null,
+ $formData['add_show_id']
+ );
} else {
$overlapping = Application_Model_Schedule::checkOverlappingShows(
- $rebroadcastShowStart, $rebroadcastShowEnd);
+ $rebroadcastShowStart,
+ $rebroadcastShowEnd
+ );
}
- if ($overlapping) break;
+ if ($overlapping) {
+ break;
+ }
}
return $overlapping;
@@ -371,7 +408,7 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
$elements = $this->getElements();
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
- $element->setAttrib('disabled','disabled');
+ $element->setAttrib('disabled', 'disabled');
}
}
}
@@ -380,16 +417,16 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
{
$element = $this->getElement('add_show_repeats');
if ($element->getType() != 'Zend_Form_Element_Hidden') {
- $element->setAttrib('disabled','disabled');
+ $element->setAttrib('disabled', 'disabled');
}
}
public function disableStartDateAndTime()
{
- $elements = array($this->getElement('add_show_start_date'), $this->getElement('add_show_start_time'));
+ $elements = [$this->getElement('add_show_start_date'), $this->getElement('add_show_start_time')];
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
- $element->setAttrib('disabled','disabled');
+ $element->setAttrib('disabled', 'disabled');
}
}
}
diff --git a/legacy/application/forms/AddShowWho.php b/legacy/application/forms/AddShowWho.php
index aba16e110..b659cdc91 100644
--- a/legacy/application/forms/AddShowWho.php
+++ b/legacy/application/forms/AddShowWho.php
@@ -2,17 +2,16 @@
class Application_Form_AddShowWho extends Zend_Form_SubForm
{
-
public function init()
{
// Add hosts autocomplete
- $this->addElement('text', 'add_show_hosts_autocomplete', array(
- 'label' => _('Search Users:'),
- 'class' => 'input_text ui-autocomplete-input',
- 'required' => false
- ));
+ $this->addElement('text', 'add_show_hosts_autocomplete', [
+ 'label' => _('Search Users:'),
+ 'class' => 'input_text ui-autocomplete-input',
+ 'required' => false,
+ ]);
- $options = array();
+ $options = [];
$hosts = Application_Model_User::getHosts();
foreach ($hosts as $host) {
@@ -22,7 +21,8 @@ class Application_Form_AddShowWho extends Zend_Form_SubForm
//Add hosts selection
$hosts = new Zend_Form_Element_MultiCheckbox('add_show_hosts');
$hosts->setLabel(_('DJs:'))
- ->setMultiOptions($options);
+ ->setMultiOptions($options)
+ ;
$this->addElement($hosts);
}
@@ -32,7 +32,7 @@ class Application_Form_AddShowWho extends Zend_Form_SubForm
$elements = $this->getElements();
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
- $element->setAttrib('disabled','disabled');
+ $element->setAttrib('disabled', 'disabled');
}
}
}
diff --git a/legacy/application/forms/AddTracktype.php b/legacy/application/forms/AddTracktype.php
index 6cfca6222..949fa207e 100644
--- a/legacy/application/forms/AddTracktype.php
+++ b/legacy/application/forms/AddTracktype.php
@@ -2,7 +2,6 @@
class Application_Form_AddTracktype extends Zend_Form
{
-
public function init()
{
$notEmptyValidator = Application_Form_Helper_ValidationTypes::overrideNotEmptyValidator();
@@ -10,12 +9,12 @@ class Application_Form_AddTracktype extends Zend_Form
$this->setAttrib('id', 'tracktype_form');
$hidden = new Zend_Form_Element_Hidden('tracktype_id');
- $hidden->setDecorators(array('ViewHelper'));
+ $hidden->setDecorators(['ViewHelper']);
$this->addElement($hidden);
- $this->addElement('hash', 'csrf', array(
- 'salt' => 'unique'
- ));
+ $this->addElement('hash', 'csrf', [
+ 'salt' => 'unique',
+ ]);
$typeName = new Zend_Form_Element_Text('type_name');
$typeName->setLabel(_('Type Name:'));
@@ -34,10 +33,11 @@ class Application_Form_AddTracktype extends Zend_Form
$description = new Zend_Form_Element_Textarea('description');
$description->setLabel(_('Description:'))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- new Zend_Validate_StringLength(array('max' => 200))
- ));
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ new Zend_Validate_StringLength(['max' => 200]),
+ ])
+ ;
$description->setAttrib('class', 'input_text');
$description->addFilter('StringTrim');
$this->addElement($description);
@@ -46,10 +46,10 @@ class Application_Form_AddTracktype extends Zend_Form
$visibility->setLabel(_('Visibility:'));
$visibility->setAttrib('class', 'input_select');
$visibility->setAttrib('style', 'width: 40%');
- $visibility->setMultiOptions(array(
- "0" => _("Disabled"),
- "1" => _("Enabled")
- ));
+ $visibility->setMultiOptions([
+ '0' => _('Disabled'),
+ '1' => _('Enabled'),
+ ]);
//$visibility->getValue();
$visibility->setRequired(true);
$this->addElement($visibility);
@@ -67,7 +67,7 @@ class Application_Form_AddTracktype extends Zend_Form
$count = CcTracktypesQuery::create()->filterByDbCode($data['code'])->count();
if ($count != 0) {
- $this->getElement('code')->setErrors(array(_("Code is not unique.")));
+ $this->getElement('code')->setErrors([_('Code is not unique.')]);
return false;
}
@@ -75,5 +75,4 @@ class Application_Form_AddTracktype extends Zend_Form
return true;
}
-
}
diff --git a/legacy/application/forms/AddUser.php b/legacy/application/forms/AddUser.php
index 9212be27b..7351b426e 100644
--- a/legacy/application/forms/AddUser.php
+++ b/legacy/application/forms/AddUser.php
@@ -2,7 +2,6 @@
class Application_Form_AddUser extends Zend_Form
{
-
public function init()
{
/*
@@ -13,16 +12,16 @@ class Application_Form_AddUser extends Zend_Form
$notEmptyValidator = Application_Form_Helper_ValidationTypes::overrideNotEmptyValidator();
$emailValidator = Application_Form_Helper_ValidationTypes::overrideEmailAddressValidator();
$notDemoValidator = new Application_Validate_NotDemoValidate();
-
+
$this->setAttrib('id', 'user_form');
-
+
$hidden = new Zend_Form_Element_Hidden('user_id');
- $hidden->setDecorators(array('ViewHelper'));
+ $hidden->setDecorators(['ViewHelper']);
$this->addElement($hidden);
- $this->addElement('hash', 'csrf', array(
- 'salt' => 'unique'
- ));
+ $this->addElement('hash', 'csrf', [
+ 'salt' => 'unique',
+ ]);
$login = new Zend_Form_Element_Text('login');
$login->setLabel(_('Username:'));
@@ -94,12 +93,12 @@ class Application_Form_AddUser extends Zend_Form
$select->setLabel(_('User Type:'));
$select->setAttrib('class', 'input_select');
$select->setAttrib('style', 'width: 40%');
- $select->setMultiOptions(array(
- "G" => _("Guest"),
- "H" => _("DJ"),
- "P" => _("Program Manager"),
- "A" => _("Admin"),
- ));
+ $select->setMultiOptions([
+ 'G' => _('Guest'),
+ 'H' => _('DJ'),
+ 'P' => _('Program Manager'),
+ 'A' => _('Admin'),
+ ]);
$select->setRequired(false);
$this->addElement($select);
@@ -116,7 +115,7 @@ class Application_Form_AddUser extends Zend_Form
$count = CcSubjsQuery::create()->filterByDbLogin($data['login'])->count();
if ($count != 0) {
- $this->getElement('login')->setErrors(array(_("Login name is not unique.")));
+ $this->getElement('login')->setErrors([_('Login name is not unique.')]);
return false;
}
@@ -127,10 +126,13 @@ class Application_Form_AddUser extends Zend_Form
// We need to add the password identical validator here in case
// Zend version is less than 1.10.5
- public function isValid($data) {
+ public function isValid($data)
+ {
$passwordIdenticalValidator = Application_Form_Helper_ValidationTypes::overridePasswordIdenticalValidator(
- $data['password']);
+ $data['password']
+ );
$this->getElement('passwordVerify')->addValidator($passwordIdenticalValidator);
+
return parent::isValid($data);
}
}
diff --git a/legacy/application/forms/DangerousPreferences.php b/legacy/application/forms/DangerousPreferences.php
index 28d203405..16b6add21 100644
--- a/legacy/application/forms/DangerousPreferences.php
+++ b/legacy/application/forms/DangerousPreferences.php
@@ -1,21 +1,20 @@
setDecorators(array(
- array('ViewScript', array('viewScript' => 'form/preferences_danger.phtml'))
- ));
+class Application_Form_DangerousPreferences extends Zend_Form_SubForm
+{
+ public function init()
+ {
+ $this->setDecorators([
+ ['ViewScript', ['viewScript' => 'form/preferences_danger.phtml']],
+ ]);
$clearLibrary = new Zend_Form_Element_Button('clear_library');
$clearLibrary->setLabel(_('Delete All Tracks in Library'));
//$submit->removeDecorator('Label');
- $clearLibrary->setAttribs(array('class'=>'btn centered'));
+ $clearLibrary->setAttribs(['class' => 'btn centered']);
$clearLibrary->setAttrib('onclick', 'deleteAllFiles();');
$clearLibrary->removeDecorator('DtDdWrapper');
$this->addElement($clearLibrary);
}
-
}
diff --git a/legacy/application/forms/DateRange.php b/legacy/application/forms/DateRange.php
index 4d8dd3570..7ce28d2b6 100644
--- a/legacy/application/forms/DateRange.php
+++ b/legacy/application/forms/DateRange.php
@@ -2,24 +2,24 @@
class Application_Form_DateRange extends Zend_Form_SubForm
{
-
public function init()
{
- $this->setDecorators(array(
- array('ViewScript', array('viewScript' => 'form/daterange.phtml'))
- ));
+ $this->setDecorators([
+ ['ViewScript', ['viewScript' => 'form/daterange.phtml']],
+ ]);
// Add start date element
$startDate = new Zend_Form_Element_Text('his_date_start');
$startDate->class = 'input_text';
$startDate->setRequired(true)
- ->setLabel(_('Date Start:'))
- ->setValue(date("Y-m-d"))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- 'NotEmpty',
- array('date', false, array('YYYY-MM-DD'))))
- ->setDecorators(array('ViewHelper'));
+ ->setLabel(_('Date Start:'))
+ ->setValue(date('Y-m-d'))
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ 'NotEmpty',
+ ['date', false, ['YYYY-MM-DD']], ])
+ ->setDecorators(['ViewHelper'])
+ ;
$startDate->setAttrib('alt', 'date');
$this->addElement($startDate);
@@ -27,13 +27,14 @@ class Application_Form_DateRange extends Zend_Form_SubForm
$startTime = new Zend_Form_Element_Text('his_time_start');
$startTime->class = 'input_text';
$startTime->setRequired(true)
- ->setValue('00:00')
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- 'NotEmpty',
- array('date', false, array('HH:mm')),
- array('regex', false, array('/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')))))
- ->setDecorators(array('ViewHelper'));
+ ->setValue('00:00')
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ 'NotEmpty',
+ ['date', false, ['HH:mm']],
+ ['regex', false, ['/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')]], ])
+ ->setDecorators(['ViewHelper'])
+ ;
$startTime->setAttrib('alt', 'time');
$this->addElement($startTime);
@@ -41,13 +42,14 @@ class Application_Form_DateRange extends Zend_Form_SubForm
$endDate = new Zend_Form_Element_Text('his_date_end');
$endDate->class = 'input_text';
$endDate->setRequired(true)
- ->setLabel(_('Date End:'))
- ->setValue(date("Y-m-d"))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- 'NotEmpty',
- array('date', false, array('YYYY-MM-DD'))))
- ->setDecorators(array('ViewHelper'));
+ ->setLabel(_('Date End:'))
+ ->setValue(date('Y-m-d'))
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ 'NotEmpty',
+ ['date', false, ['YYYY-MM-DD']], ])
+ ->setDecorators(['ViewHelper'])
+ ;
$endDate->setAttrib('alt', 'date');
$this->addElement($endDate);
@@ -55,13 +57,14 @@ class Application_Form_DateRange extends Zend_Form_SubForm
$endTime = new Zend_Form_Element_Text('his_time_end');
$endTime->class = 'input_text';
$endTime->setRequired(true)
- ->setValue('01:00')
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- 'NotEmpty',
- array('date', false, array('HH:mm')),
- array('regex', false, array('/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')))))
- ->setDecorators(array('ViewHelper'));
+ ->setValue('01:00')
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ 'NotEmpty',
+ ['date', false, ['HH:mm']],
+ ['regex', false, ['/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')]], ])
+ ->setDecorators(['ViewHelper'])
+ ;
$endTime->setAttrib('alt', 'time');
$this->addElement($endTime);
}
diff --git a/legacy/application/forms/EditAudioMD.php b/legacy/application/forms/EditAudioMD.php
index 95be04500..7b286a089 100644
--- a/legacy/application/forms/EditAudioMD.php
+++ b/legacy/application/forms/EditAudioMD.php
@@ -2,46 +2,48 @@
class Application_Form_EditAudioMD extends Zend_Form
{
-
- public function init() {}
+ public function init()
+ {
+ }
public function startForm($p_id)
{
$baseUrl = Application_Common_OsPath::getBaseDir();
- // Set the method for the display form to POST
+ // Set the method for the display form to POST
$this->setMethod('post');
$file_id = new Zend_Form_Element_Hidden('file_id');
$file_id->setValue($p_id);
- $file_id->addDecorator('HtmlTag', array('tag' => 'div', 'style' => 'display:none'));
+ $file_id->addDecorator('HtmlTag', ['tag' => 'div', 'style' => 'display:none']);
$file_id->removeDecorator('Label');
$file_id->setAttrib('class', 'obj_id');
$this->addElement($file_id);
// Add artwork hidden field
$artwork = new Zend_Form_Element_Hidden('artwork');
- $artwork->class = 'input_text artwork_'. $p_id;
- $artwork->setFilters(array('StringTrim'))
- ->setValidators(array(
- new Zend_Validate_StringLength(array('max' => 2048))
- ));
- $file_id->addDecorator('HtmlTag', array('tag' => 'div', 'style' => 'display:none'));
+ $artwork->class = 'input_text artwork_' . $p_id;
+ $artwork->setFilters(['StringTrim'])
+ ->setValidators([
+ new Zend_Validate_StringLength(['max' => 2048]),
+ ])
+ ;
+ $file_id->addDecorator('HtmlTag', ['tag' => 'div', 'style' => 'display:none']);
$file_id->removeDecorator('Label');
$file_id->setAttrib('class', 'artwork');
$this->addElement($artwork);
// Set artwork hidden field
$set_artwork = new Zend_Form_Element_Hidden('set_artwork');
- $set_artwork->class = 'input_text set_artwork_'. $p_id;
- $file_id->addDecorator('HtmlTag', array('tag' => 'div', 'style' => 'display:none'));
+ $set_artwork->class = 'input_text set_artwork_' . $p_id;
+ $file_id->addDecorator('HtmlTag', ['tag' => 'div', 'style' => 'display:none']);
$file_id->removeDecorator('Label');
$file_id->setAttrib('class', 'set_artwork');
$this->addElement($set_artwork);
// Remove artwork hidden field
$remove_artwork = new Zend_Form_Element_Hidden('remove_artwork');
- $remove_artwork->class = 'input_text remove_artwork_'. $p_id;
- $file_id->addDecorator('HtmlTag', array('tag' => 'div', 'style' => 'display:none'));
+ $remove_artwork->class = 'input_text remove_artwork_' . $p_id;
+ $file_id->addDecorator('HtmlTag', ['tag' => 'div', 'style' => 'display:none']);
$file_id->removeDecorator('Label');
$file_id->setAttrib('class', 'remove_artwork');
$this->addElement($remove_artwork);
@@ -50,35 +52,37 @@ class Application_Form_EditAudioMD extends Zend_Form
$track_title = new Zend_Form_Element_Text('track_title');
$track_title->class = 'input_text';
$track_title->setLabel(_('Title:'))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- new Zend_Validate_StringLength(array('max' => 512))
- ));
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ new Zend_Validate_StringLength(['max' => 512]),
+ ])
+ ;
$this->addElement($track_title);
// Add artist field
$artist_name = new Zend_Form_Element_Text('artist_name');
$artist_name->class = 'input_text';
$artist_name->setLabel(_('Creator:'))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- new Zend_Validate_StringLength(array('max' => 512))
- ));
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ new Zend_Validate_StringLength(['max' => 512]),
+ ])
+ ;
$this->addElement($artist_name);
// Add album field
$album_title = new Zend_Form_Element_Text('album_title');
$album_title->class = 'input_text';
$album_title->setLabel(_('Album:'))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- new Zend_Validate_StringLength(array('max' => 512))
- ));
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ new Zend_Validate_StringLength(['max' => 512]),
+ ])
+ ;
$this->addElement($album_title);
-
// Add album field
- $user_options = array();
+ $user_options = [];
$users = Application_Model_User::getNonGuestUsers();
foreach ($users as $host) {
@@ -92,14 +96,14 @@ class Application_Form_EditAudioMD extends Zend_Form
$this->addelement($owner_id);
// Add track type dropdown
- $track_type_options = array();
+ $track_type_options = [];
$track_types = Application_Model_Tracktype::getTracktypes();
-
- array_multisort(array_map(function($element) {
+
+ array_multisort(array_map(function ($element) {
return $element['type_name'];
}, $track_types), SORT_ASC, $track_types);
-
- $track_type_options[""] = _('Select a Type');
+
+ $track_type_options[''] = _('Select a Type');
foreach ($track_types as $key => $tt) {
$track_type_options[$tt['code']] = $tt['type_name'];
}
@@ -114,189 +118,204 @@ class Application_Form_EditAudioMD extends Zend_Form
$description = new Zend_Form_Element_Textarea('description');
$description->class = 'input_text';
$description->setLabel(_('Description:'))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- new Zend_Validate_StringLength(array('max' => 512))
- ));
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ new Zend_Validate_StringLength(['max' => 512]),
+ ])
+ ;
$this->addElement($description);
// Add track number field
$track_number = new Zend_Form_Element('track_number');
$track_number->class = 'input_text';
$track_number->setLabel('Track Number:')
- ->setFilters(array('StringTrim'))
- ->setValidators(array(new Zend_Validate_Int()));
+ ->setFilters(['StringTrim'])
+ ->setValidators([new Zend_Validate_Int()])
+ ;
$this->addElement($track_number);
// Add genre field
$genre = new Zend_Form_Element('genre');
$genre->class = 'input_text';
$genre->setLabel(_('Genre:'))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- new Zend_Validate_StringLength(array('max' => 64))
- ));
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ new Zend_Validate_StringLength(['max' => 64]),
+ ])
+ ;
$this->addElement($genre);
// Add year field
$year = new Zend_Form_Element_Text('year');
$year->class = 'input_text';
$year->setLabel(_('Year:'))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- new Zend_Validate_StringLength(array('max' => 10)),
- Application_Form_Helper_ValidationTypes::overrrideDateValidator("YYYY-MM-DD"),
- Application_Form_Helper_ValidationTypes::overrrideDateValidator("YYYY-MM"),
- Application_Form_Helper_ValidationTypes::overrrideDateValidator("YYYY")
- ));
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ new Zend_Validate_StringLength(['max' => 10]),
+ Application_Form_Helper_ValidationTypes::overrrideDateValidator('YYYY-MM-DD'),
+ Application_Form_Helper_ValidationTypes::overrrideDateValidator('YYYY-MM'),
+ Application_Form_Helper_ValidationTypes::overrrideDateValidator('YYYY'),
+ ])
+ ;
$this->addElement($year);
// Add label field
$label = new Zend_Form_Element('label');
$label->class = 'input_text';
$label->setLabel(_('Label:'))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- new Zend_Validate_StringLength(array('max' => 512))
- ));
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ new Zend_Validate_StringLength(['max' => 512]),
+ ])
+ ;
$this->addElement($label);
// Add composer field
$composer = new Zend_Form_Element('composer');
$composer->class = 'input_text';
$composer->setLabel(_('Composer:'))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- new Zend_Validate_StringLength(array('max' => 512))
- ));
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ new Zend_Validate_StringLength(['max' => 512]),
+ ])
+ ;
$this->addElement($composer);
// Add conductor field
$conductor = new Zend_Form_Element('conductor');
$conductor->class = 'input_text';
$conductor->setLabel(_('Conductor:'))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- new Zend_Validate_StringLength(array('max' => 512))
- ));
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ new Zend_Validate_StringLength(['max' => 512]),
+ ])
+ ;
$this->addElement($conductor);
// Add mood field
$mood = new Zend_Form_Element('mood');
$mood->class = 'input_text';
$mood->setLabel(_('Mood:'))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- new Zend_Validate_StringLength(array('max' => 64))
- ));
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ new Zend_Validate_StringLength(['max' => 64]),
+ ])
+ ;
$this->addElement($mood);
// Add bmp field
$bpm = new Zend_Form_Element_Text('bpm');
$bpm->class = 'input_text';
$bpm->setLabel(_('BPM:'))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- new Zend_Validate_StringLength(array('min'=>0,'max' => 8)),
- new Zend_Validate_Digits()));
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ new Zend_Validate_StringLength(['min' => 0, 'max' => 8]),
+ new Zend_Validate_Digits(), ])
+ ;
$this->addElement($bpm);
// Add copyright field
$copyright = new Zend_Form_Element('copyright');
$copyright->class = 'input_text';
$copyright->setLabel(_('Copyright:'))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- new Zend_Validate_StringLength(array('max' => 512))
- ));
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ new Zend_Validate_StringLength(['max' => 512]),
+ ])
+ ;
$this->addElement($copyright);
// Add isrc number field
$isrc_number = new Zend_Form_Element('isrc_number');
$isrc_number->class = 'input_text';
$isrc_number->setLabel(_('ISRC Number:'))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- new Zend_Validate_StringLength(array('max' => 512))
- ));
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ new Zend_Validate_StringLength(['max' => 512]),
+ ])
+ ;
$this->addElement($isrc_number);
// Add website field
$info_url = new Zend_Form_Element('info_url');
$info_url->class = 'input_text';
$info_url->setLabel(_('Website:'))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- new Zend_Validate_StringLength(array('max' => 512))
- ));
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ new Zend_Validate_StringLength(['max' => 512]),
+ ])
+ ;
$this->addElement($info_url);
// Add language field
$language = new Zend_Form_Element('language');
$language->class = 'input_text';
$language->setLabel(_('Language:'))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- new Zend_Validate_StringLength(array('max' => 512))
- ));
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ new Zend_Validate_StringLength(['max' => 512]),
+ ])
+ ;
$this->addElement($language);
$validCuePattern = '/^(?:[0-9]{1,2}:)?(?:[0-9]{1,2}:)?[0-9]{1,6}(\.\d{1,6})?$/';
$cueIn = new Zend_Form_Element_Text('cuein');
$cueIn->class = 'input_text';
- $cueIn->setLabel("Cue In:");
+ $cueIn->setLabel('Cue In:');
$cueInValidator = Application_Form_Helper_ValidationTypes::overrideRegexValidator(
- $validCuePattern, _(sprintf("Specify cue in time in the format %s", "(hh:mm:)ss(.dddddd)"))
+ $validCuePattern,
+ _(sprintf('Specify cue in time in the format %s', '(hh:mm:)ss(.dddddd)'))
);
- $cueIn->setValidators(array($cueInValidator));
+ $cueIn->setValidators([$cueInValidator]);
$this->addElement($cueIn);
$cueOut = new Zend_Form_Element_Text('cueout');
$cueOut->class = 'input_text';
$cueOut->setLabel('Cue Out:');
$cueOutValidator = Application_Form_Helper_ValidationTypes::overrideRegexValidator(
- $validCuePattern, _(sprintf("Specify cue out time in the format %s", "(hh:mm:)ss(.dddddd)"))
+ $validCuePattern,
+ _(sprintf('Specify cue out time in the format %s', '(hh:mm:)ss(.dddddd)'))
);
- $cueOut->setValidators(array($cueOutValidator));
+ $cueOut->setValidators([$cueOutValidator]);
$this->addElement($cueOut);
// Add the cancel button
- $this->addElement('button', 'editmdcancel', array(
- 'ignore' => true,
- 'class' => 'btn md-cancel',
- 'label' => _('Cancel'),
- 'decorators' => array(
- 'ViewHelper'
- )
- ));
+ $this->addElement('button', 'editmdcancel', [
+ 'ignore' => true,
+ 'class' => 'btn md-cancel',
+ 'label' => _('Cancel'),
+ 'decorators' => [
+ 'ViewHelper',
+ ],
+ ]);
// Add the submit button
- $this->addElement('button', 'editmdsave', array(
- 'ignore' => true,
- 'class' => 'btn md-save',
- 'label' => _('Save'),
- 'decorators' => array(
- 'ViewHelper'
- )
- ));
+ $this->addElement('button', 'editmdsave', [
+ 'ignore' => true,
+ 'class' => 'btn md-save',
+ 'label' => _('Save'),
+ 'decorators' => [
+ 'ViewHelper',
+ ],
+ ]);
// Button to open the publish dialog
- $this->addElement('button', 'publishdialog', array(
- 'ignore' => true,
- 'class' => 'btn md-publish',
- 'label' => _('Publish...'),
- 'decorators' => array(
- 'ViewHelper'
- )
- ));
+ $this->addElement('button', 'publishdialog', [
+ 'ignore' => true,
+ 'class' => 'btn md-publish',
+ 'label' => _('Publish...'),
+ 'decorators' => [
+ 'ViewHelper',
+ ],
+ ]);
- $this->addDisplayGroup(array('publishdialog', 'editmdsave', 'editmdcancel'), 'submitButtons', array(
- 'decorators' => array(
+ $this->addDisplayGroup(['publishdialog', 'editmdsave', 'editmdcancel'], 'submitButtons', [
+ 'decorators' => [
'FormElements',
- 'DtDdWrapper'
- )
- ));
+ 'DtDdWrapper',
+ ],
+ ]);
}
public function makeReadOnly()
@@ -306,13 +325,14 @@ class Application_Form_EditAudioMD extends Zend_Form
}
}
- public function removeOwnerEdit() {
+ public function removeOwnerEdit()
+ {
$this->removeElement('owner_id');
}
+
public function removeActionButtons()
{
$this->removeElement('editmdsave');
$this->removeElement('editmdcancel');
}
-
}
diff --git a/legacy/application/forms/EditHistory.php b/legacy/application/forms/EditHistory.php
index ad7ae7a05..e98697d04 100644
--- a/legacy/application/forms/EditHistory.php
+++ b/legacy/application/forms/EditHistory.php
@@ -2,210 +2,205 @@
class Application_Form_EditHistory extends Zend_Form
{
- const VALIDATE_DATETIME_FORMAT = 'yyyy-MM-dd HH:mm:ss';
- //this is used by the javascript widget, unfortunately h/H is opposite from Zend.
- const TIMEPICKER_DATETIME_FORMAT = 'yyyy-MM-dd hh:mm:ss';
+ public const VALIDATE_DATETIME_FORMAT = 'yyyy-MM-dd HH:mm:ss';
+ //this is used by the javascript widget, unfortunately h/H is opposite from Zend.
+ public const TIMEPICKER_DATETIME_FORMAT = 'yyyy-MM-dd hh:mm:ss';
- const VALIDATE_DATE_FORMAT = 'yyyy-MM-dd';
- const VALIDATE_TIME_FORMAT = 'HH:mm:ss';
+ public const VALIDATE_DATE_FORMAT = 'yyyy-MM-dd';
+ public const VALIDATE_TIME_FORMAT = 'HH:mm:ss';
- const ITEM_TYPE = "type";
- const ITEM_CLASS = "class";
- const ITEM_OPTIONS = "options";
- const ITEM_ID_SUFFIX = "name";
+ public const ITEM_TYPE = 'type';
+ public const ITEM_CLASS = 'class';
+ public const ITEM_OPTIONS = 'options';
+ public const ITEM_ID_SUFFIX = 'name';
- const TEXT_INPUT_CLASS = "input_text";
+ public const TEXT_INPUT_CLASS = 'input_text';
- private $formElTypes = array(
- TEMPLATE_DATE => array(
- "class" => "Zend_Form_Element_Text",
- "attrs" => array(
- "class" => self::TEXT_INPUT_CLASS
- ),
- "validators" => array(
- array(
- "class" => "Zend_Validate_Date",
- "params" => array(
- "format" => self::VALIDATE_DATE_FORMAT
- )
- )
- ),
- "filters" => array(
- "StringTrim"
- )
- ),
- TEMPLATE_TIME => array(
- "class" => "Zend_Form_Element_Text",
- "attrs" => array(
- "class" => self::TEXT_INPUT_CLASS
- ),
- "validators" => array(
- array(
- "class" => "Zend_Validate_Date",
- "params" => array(
- "format" => self::VALIDATE_TIME_FORMAT
- )
- )
- ),
- "filters" => array(
- "StringTrim"
- )
- ),
- TEMPLATE_DATETIME => array(
- "class" => "Zend_Form_Element_Text",
- "attrs" => array(
- "class" => self::TEXT_INPUT_CLASS
- ),
- "validators" => array(
- array(
- "class" => "Zend_Validate_Date",
- "params" => array(
- "format" => self::VALIDATE_DATETIME_FORMAT
- )
- )
- ),
- "filters" => array(
- "StringTrim"
- )
- ),
- TEMPLATE_STRING => array(
- "class" => "Zend_Form_Element_Text",
- "attrs" => array(
- "class" => self::TEXT_INPUT_CLASS
- ),
- "filters" => array(
- "StringTrim"
- )
- ),
- TEMPLATE_BOOLEAN => array(
- "class" => "Zend_Form_Element_Checkbox",
- "validators" => array(
- array(
- "class" => "Zend_Validate_InArray",
- "options" => array(
- "haystack" => array(0,1)
- )
- )
- )
- ),
- TEMPLATE_INT => array(
- "class" => "Zend_Form_Element_Text",
- "validators" => array(
- array(
- "class" => "Zend_Validate_Int",
- )
- ),
- "attrs" => array(
- "class" => self::TEXT_INPUT_CLASS
- )
- ),
- TEMPLATE_FLOAT => array(
- "class" => "Zend_Form_Element_Text",
- "attrs" => array(
- "class" => self::TEXT_INPUT_CLASS
- ),
- "validators" => array(
- array(
- "class" => "Zend_Validate_Float",
- )
- )
- ),
- );
+ private $formElTypes = [
+ TEMPLATE_DATE => [
+ 'class' => 'Zend_Form_Element_Text',
+ 'attrs' => [
+ 'class' => self::TEXT_INPUT_CLASS,
+ ],
+ 'validators' => [
+ [
+ 'class' => 'Zend_Validate_Date',
+ 'params' => [
+ 'format' => self::VALIDATE_DATE_FORMAT,
+ ],
+ ],
+ ],
+ 'filters' => [
+ 'StringTrim',
+ ],
+ ],
+ TEMPLATE_TIME => [
+ 'class' => 'Zend_Form_Element_Text',
+ 'attrs' => [
+ 'class' => self::TEXT_INPUT_CLASS,
+ ],
+ 'validators' => [
+ [
+ 'class' => 'Zend_Validate_Date',
+ 'params' => [
+ 'format' => self::VALIDATE_TIME_FORMAT,
+ ],
+ ],
+ ],
+ 'filters' => [
+ 'StringTrim',
+ ],
+ ],
+ TEMPLATE_DATETIME => [
+ 'class' => 'Zend_Form_Element_Text',
+ 'attrs' => [
+ 'class' => self::TEXT_INPUT_CLASS,
+ ],
+ 'validators' => [
+ [
+ 'class' => 'Zend_Validate_Date',
+ 'params' => [
+ 'format' => self::VALIDATE_DATETIME_FORMAT,
+ ],
+ ],
+ ],
+ 'filters' => [
+ 'StringTrim',
+ ],
+ ],
+ TEMPLATE_STRING => [
+ 'class' => 'Zend_Form_Element_Text',
+ 'attrs' => [
+ 'class' => self::TEXT_INPUT_CLASS,
+ ],
+ 'filters' => [
+ 'StringTrim',
+ ],
+ ],
+ TEMPLATE_BOOLEAN => [
+ 'class' => 'Zend_Form_Element_Checkbox',
+ 'validators' => [
+ [
+ 'class' => 'Zend_Validate_InArray',
+ 'options' => [
+ 'haystack' => [0, 1],
+ ],
+ ],
+ ],
+ ],
+ TEMPLATE_INT => [
+ 'class' => 'Zend_Form_Element_Text',
+ 'validators' => [
+ [
+ 'class' => 'Zend_Validate_Int',
+ ],
+ ],
+ 'attrs' => [
+ 'class' => self::TEXT_INPUT_CLASS,
+ ],
+ ],
+ TEMPLATE_FLOAT => [
+ 'class' => 'Zend_Form_Element_Text',
+ 'attrs' => [
+ 'class' => self::TEXT_INPUT_CLASS,
+ ],
+ 'validators' => [
+ [
+ 'class' => 'Zend_Validate_Float',
+ ],
+ ],
+ ],
+ ];
- public function init() {
-
- $history_id = new Zend_Form_Element_Hidden($this::ID_PREFIX.'id');
- $history_id->setValidators(array(
- new Zend_Validate_Int()
- ));
- $history_id->setDecorators(array('ViewHelper'));
- $this->addElement($history_id);
-
- $dynamic_attrs = new Zend_Form_SubForm();
- $this->addSubForm($dynamic_attrs, $this::ID_PREFIX.'template');
-
- // Add the submit button
- $this->addElement('button', $this::ID_PREFIX.'save', array(
- 'ignore' => true,
- 'class' => 'btn '.$this::ID_PREFIX.'save',
- 'label' => _('Save'),
- 'decorators' => array(
- 'ViewHelper'
- )
- ));
-
- // Add the cancel button
- $this->addElement('button', $this::ID_PREFIX.'cancel', array(
- 'ignore' => true,
- 'class' => 'btn '.$this::ID_PREFIX.'cancel',
- 'label' => _('Cancel'),
- 'decorators' => array(
- 'ViewHelper'
- )
- ));
- }
+ public function init()
+ {
+ $history_id = new Zend_Form_Element_Hidden($this::ID_PREFIX . 'id');
+ $history_id->setValidators([
+ new Zend_Validate_Int(),
+ ]);
+ $history_id->setDecorators(['ViewHelper']);
+ $this->addElement($history_id);
- public function createFromTemplate($template, $required) {
+ $dynamic_attrs = new Zend_Form_SubForm();
+ $this->addSubForm($dynamic_attrs, $this::ID_PREFIX . 'template');
- $templateSubForm = $this->getSubForm($this::ID_PREFIX.'template');
+ // Add the submit button
+ $this->addElement('button', $this::ID_PREFIX . 'save', [
+ 'ignore' => true,
+ 'class' => 'btn ' . $this::ID_PREFIX . 'save',
+ 'label' => _('Save'),
+ 'decorators' => [
+ 'ViewHelper',
+ ],
+ ]);
- for ($i = 0, $len = count($template); $i < $len; $i++) {
+ // Add the cancel button
+ $this->addElement('button', $this::ID_PREFIX . 'cancel', [
+ 'ignore' => true,
+ 'class' => 'btn ' . $this::ID_PREFIX . 'cancel',
+ 'label' => _('Cancel'),
+ 'decorators' => [
+ 'ViewHelper',
+ ],
+ ]);
+ }
- $item = $template[$i];
- //don't dynamically add this as it should be included in the
- //init() function already if it should show up in the UI..
- if (in_array($item["name"], $required)) {
- continue;
- }
+ public function createFromTemplate($template, $required)
+ {
+ $templateSubForm = $this->getSubForm($this::ID_PREFIX . 'template');
- $formElType = $this->formElTypes[$item[self::ITEM_TYPE]];
+ for ($i = 0, $len = count($template); $i < $len; ++$i) {
+ $item = $template[$i];
+ //don't dynamically add this as it should be included in the
+ //init() function already if it should show up in the UI..
+ if (in_array($item['name'], $required)) {
+ continue;
+ }
- $label = $item[self::ITEM_ID_SUFFIX];
- $id = $this::ID_PREFIX.$label;
- $el = new $formElType[self::ITEM_CLASS]($id);
- $el->setLabel($item["label"]);
+ $formElType = $this->formElTypes[$item[self::ITEM_TYPE]];
- if (isset($formElType["attrs"])) {
+ $label = $item[self::ITEM_ID_SUFFIX];
+ $id = $this::ID_PREFIX . $label;
+ $el = new $formElType[self::ITEM_CLASS]($id);
+ $el->setLabel($item['label']);
- $attrs = $formElType["attrs"];
+ if (isset($formElType['attrs'])) {
+ $attrs = $formElType['attrs'];
- foreach ($attrs as $key => $value) {
- $el->setAttrib($key, $value);
- }
- }
+ foreach ($attrs as $key => $value) {
+ $el->setAttrib($key, $value);
+ }
+ }
- if (isset($formElType["filters"])) {
+ if (isset($formElType['filters'])) {
+ $filters = $formElType['filters'];
- $filters = $formElType["filters"];
+ foreach ($filters as $filter) {
+ $el->addFilter($filter);
+ }
+ }
- foreach ($filters as $filter) {
- $el->addFilter($filter);
- }
- }
+ if (isset($formElType['validators'])) {
+ $validators = $formElType['validators'];
- if (isset($formElType["validators"])) {
+ foreach ($validators as $index => $arr) {
+ $options = isset($arr[self::ITEM_OPTIONS]) ? $arr[self::ITEM_OPTIONS] : null;
+ $validator = new $arr[self::ITEM_CLASS]($options);
- $validators = $formElType["validators"];
+ //extra validator info
+ if (isset($arr['params'])) {
+ foreach ($arr['params'] as $key => $value) {
+ $method = 'set' . ucfirst($key);
+ $validator->{$method}($value);
+ }
+ }
- foreach ($validators as $index => $arr) {
- $options = isset($arr[self::ITEM_OPTIONS]) ? $arr[self::ITEM_OPTIONS] : null;
- $validator = new $arr[self::ITEM_CLASS]($options);
+ $el->addValidator($validator);
+ }
+ }
- //extra validator info
- if (isset($arr["params"])) {
-
- foreach ($arr["params"] as $key => $value) {
- $method = "set".ucfirst($key);
- $validator->$method($value);
- }
- }
-
- $el->addValidator($validator);
- }
- }
-
- $el->setDecorators(array('ViewHelper'));
- $templateSubForm->addElement($el);
- }
- }
-}
\ No newline at end of file
+ $el->setDecorators(['ViewHelper']);
+ $templateSubForm->addElement($el);
+ }
+ }
+}
diff --git a/legacy/application/forms/EditHistoryFile.php b/legacy/application/forms/EditHistoryFile.php
index b58db19a1..16207b2f3 100644
--- a/legacy/application/forms/EditHistoryFile.php
+++ b/legacy/application/forms/EditHistoryFile.php
@@ -2,21 +2,21 @@
class Application_Form_EditHistoryFile extends Application_Form_EditHistory
{
- const ID_PREFIX = "his_file_";
-
- public function init() {
-
- parent::init();
+ public const ID_PREFIX = 'his_file_';
- $this->setDecorators(
- array(
- array('ViewScript', array('viewScript' => 'form/edit-history-file.phtml'))
- )
- );
- }
-
- public function createFromTemplate($template, $required) {
-
- parent::createFromTemplate($template, $required);
- }
-}
\ No newline at end of file
+ public function init()
+ {
+ parent::init();
+
+ $this->setDecorators(
+ [
+ ['ViewScript', ['viewScript' => 'form/edit-history-file.phtml']],
+ ]
+ );
+ }
+
+ public function createFromTemplate($template, $required)
+ {
+ parent::createFromTemplate($template, $required);
+ }
+}
diff --git a/legacy/application/forms/EditHistoryItem.php b/legacy/application/forms/EditHistoryItem.php
index 2f6f38043..eb0e851f0 100644
--- a/legacy/application/forms/EditHistoryItem.php
+++ b/legacy/application/forms/EditHistoryItem.php
@@ -2,65 +2,65 @@
class Application_Form_EditHistoryItem extends Application_Form_EditHistory
{
- const ID_PREFIX = "his_item_";
+ public const ID_PREFIX = 'his_item_';
- public function init() {
+ public function init()
+ {
+ parent::init();
- parent::init();
+ $this->setDecorators([
+ 'PrepareElements',
+ ['ViewScript', ['viewScript' => 'form/edit-history-item.phtml']],
+ ]);
- $this->setDecorators(array(
- 'PrepareElements',
- array('ViewScript', array('viewScript' => 'form/edit-history-item.phtml'))
- ));
+ /*
+ $instance = new Zend_Form_Element_Select("instance_id");
+ $instance->setLabel(_("Choose Show Instance"));
+ $instance->setMultiOptions(array("0" => "-----------"));
+ $instance->setValue(0);
+ $instance->setDecorators(array('ViewHelper'));
+ $this->addElement($instance);
+ */
- /*
- $instance = new Zend_Form_Element_Select("instance_id");
- $instance->setLabel(_("Choose Show Instance"));
- $instance->setMultiOptions(array("0" => "-----------"));
- $instance->setValue(0);
- $instance->setDecorators(array('ViewHelper'));
- $this->addElement($instance);
- */
+ $starts = new Zend_Form_Element_Text(self::ID_PREFIX . 'starts');
+ $starts->setValidators([
+ new Zend_Validate_Date(self::VALIDATE_DATETIME_FORMAT),
+ ]);
+ $starts->setAttrib('class', self::TEXT_INPUT_CLASS . ' datepicker');
+ $starts->setAttrib('data-format', self::TIMEPICKER_DATETIME_FORMAT);
+ $starts->addFilter('StringTrim');
+ $starts->setLabel(_('Start Time'));
+ $starts->setDecorators(['ViewHelper']);
+ $starts->setRequired(true);
+ $this->addElement($starts);
- $starts = new Zend_Form_Element_Text(self::ID_PREFIX.'starts');
- $starts->setValidators(array(
- new Zend_Validate_Date(self::VALIDATE_DATETIME_FORMAT)
- ));
- $starts->setAttrib('class', self::TEXT_INPUT_CLASS." datepicker");
- $starts->setAttrib('data-format', self::TIMEPICKER_DATETIME_FORMAT);
- $starts->addFilter('StringTrim');
- $starts->setLabel(_('Start Time'));
- $starts->setDecorators(array('ViewHelper'));
- $starts->setRequired(true);
- $this->addElement($starts);
+ $ends = new Zend_Form_Element_Text(self::ID_PREFIX . 'ends');
+ $ends->setValidators([
+ new Zend_Validate_Date(self::VALIDATE_DATETIME_FORMAT),
+ ]);
+ $ends->setAttrib('class', self::TEXT_INPUT_CLASS . ' datepicker');
+ $ends->setAttrib('data-format', self::TIMEPICKER_DATETIME_FORMAT);
+ $ends->addFilter('StringTrim');
+ $ends->setLabel(_('End Time'));
+ $ends->setDecorators(['ViewHelper']);
+ //$ends->setRequired(true);
+ $this->addElement($ends);
+ }
- $ends = new Zend_Form_Element_Text(self::ID_PREFIX.'ends');
- $ends->setValidators(array(
- new Zend_Validate_Date(self::VALIDATE_DATETIME_FORMAT)
- ));
- $ends->setAttrib('class', self::TEXT_INPUT_CLASS." datepicker");
- $ends->setAttrib('data-format', self::TIMEPICKER_DATETIME_FORMAT);
- $ends->addFilter('StringTrim');
- $ends->setLabel(_('End Time'));
- $ends->setDecorators(array('ViewHelper'));
- //$ends->setRequired(true);
- $this->addElement($ends);
- }
+ public function createFromTemplate($template, $required)
+ {
+ parent::createFromTemplate($template, $required);
+ }
- public function createFromTemplate($template, $required) {
+ public function populateShowInstances($possibleInstances, $default)
+ {
+ $possibleInstances['0'] = _('No Show');
- parent::createFromTemplate($template, $required);
- }
-
- public function populateShowInstances($possibleInstances, $default) {
-
- $possibleInstances["0"] = _("No Show");
-
- $instance = new Zend_Form_Element_Select("his_instance_select");
- //$instance->setLabel(_("Choose Show Instance"));
- $instance->setMultiOptions($possibleInstances);
- $instance->setValue($default);
- $instance->setDecorators(array('ViewHelper'));
- $this->addElement($instance);
- }
-}
\ No newline at end of file
+ $instance = new Zend_Form_Element_Select('his_instance_select');
+ //$instance->setLabel(_("Choose Show Instance"));
+ $instance->setMultiOptions($possibleInstances);
+ $instance->setValue($default);
+ $instance->setDecorators(['ViewHelper']);
+ $this->addElement($instance);
+ }
+}
diff --git a/legacy/application/forms/EditUser.php b/legacy/application/forms/EditUser.php
index e262118ce..f364d26cc 100644
--- a/legacy/application/forms/EditUser.php
+++ b/legacy/application/forms/EditUser.php
@@ -2,7 +2,6 @@
class Application_Form_EditUser extends Zend_Form
{
-
public function init()
{
/*
@@ -17,39 +16,39 @@ class Application_Form_EditUser extends Zend_Form
$notEmptyValidator = Application_Form_Helper_ValidationTypes::overrideNotEmptyValidator();
$emailValidator = Application_Form_Helper_ValidationTypes::overrideEmailAddressValidator();
$notDemoValidator = new Application_Validate_NotDemoValidate();
-
- $this->setDecorators(array(
- array('ViewScript', array('viewScript' => 'form/edit-user.phtml', "currentUser" => $currentUser->getLogin()))));
+
+ $this->setDecorators([
+ ['ViewScript', ['viewScript' => 'form/edit-user.phtml', 'currentUser' => $currentUser->getLogin()]], ]);
$this->setAttrib('id', 'current-user-form');
$csrf_namespace = new Zend_Session_Namespace('csrf_namespace');
$csrf_element = new Zend_Form_Element_Hidden('csrf');
$csrf_element->setValue($csrf_namespace->authtoken)->setRequired('true')->removeDecorator('HtmlTag')->removeDecorator('Label');
$this->addElement($csrf_element);
-
+
$hidden = new Zend_Form_Element_Hidden('cu_user_id');
- $hidden->setDecorators(array('ViewHelper'));
- $hidden->setValue($userData["id"]);
+ $hidden->setDecorators(['ViewHelper']);
+ $hidden->setValue($userData['id']);
$this->addElement($hidden);
$login = new Zend_Form_Element_Text('cu_login');
$login->setLabel(_('Username:'));
- $login->setValue($userData["login"]);
+ $login->setValue($userData['login']);
$login->setAttrib('class', 'input_text');
$login->setAttrib('readonly', 'readonly');
$login->setRequired(true);
$login->addValidator($notEmptyValidator);
$login->addFilter('StringTrim');
- $login->setDecorators(array('viewHelper'));
+ $login->setDecorators(['viewHelper']);
$this->addElement($login);
-
+
$password = new Zend_Form_Element_Password('cu_password');
$password->setLabel(_('Password:'));
$password->setAttrib('class', 'input_text');
$password->setRequired(true);
$password->addFilter('StringTrim');
$password->addValidator($notEmptyValidator);
- $password->setDecorators(array('viewHelper'));
+ $password->setDecorators(['viewHelper']);
$this->addElement($password);
$passwordVerify = new Zend_Form_Element_Password('cu_passwordVerify');
@@ -59,91 +58,94 @@ class Application_Form_EditUser extends Zend_Form
$passwordVerify->addFilter('StringTrim');
$passwordVerify->addValidator($notEmptyValidator);
$passwordVerify->addValidator($notDemoValidator);
- $passwordVerify->setDecorators(array('viewHelper'));
+ $passwordVerify->setDecorators(['viewHelper']);
$this->addElement($passwordVerify);
$firstName = new Zend_Form_Element_Text('cu_first_name');
$firstName->setLabel(_('Firstname:'));
- $firstName->setValue($userData["first_name"]);
+ $firstName->setValue($userData['first_name']);
$firstName->setAttrib('class', 'input_text');
$firstName->addFilter('StringTrim');
- $firstName->setDecorators(array('viewHelper'));
+ $firstName->setDecorators(['viewHelper']);
$this->addElement($firstName);
$lastName = new Zend_Form_Element_Text('cu_last_name');
$lastName->setLabel(_('Lastname:'));
- $lastName->setValue($userData["last_name"]);
+ $lastName->setValue($userData['last_name']);
$lastName->setAttrib('class', 'input_text');
$lastName->addFilter('StringTrim');
- $lastName->setDecorators(array('viewHelper'));
+ $lastName->setDecorators(['viewHelper']);
$this->addElement($lastName);
$email = new Zend_Form_Element_Text('cu_email');
$email->setLabel(_('Email:'));
- $email->setValue($userData["email"]);
+ $email->setValue($userData['email']);
$email->setAttrib('class', 'input_text');
$email->addFilter('StringTrim');
$email->setRequired(true);
$email->addValidator($notEmptyValidator);
$email->addValidator($emailValidator);
- $email->setDecorators(array('viewHelper'));
+ $email->setDecorators(['viewHelper']);
$this->addElement($email);
$cellPhone = new Zend_Form_Element_Text('cu_cell_phone');
$cellPhone->setLabel(_('Mobile Phone:'));
- $cellPhone->setValue($userData["cell_phone"]);
+ $cellPhone->setValue($userData['cell_phone']);
$cellPhone->setAttrib('class', 'input_text');
$cellPhone->addFilter('StringTrim');
- $cellPhone->setDecorators(array('viewHelper'));
+ $cellPhone->setDecorators(['viewHelper']);
$this->addElement($cellPhone);
$skype = new Zend_Form_Element_Text('cu_skype');
$skype->setLabel(_('Skype:'));
- $skype->setValue($userData["skype_contact"]);
+ $skype->setValue($userData['skype_contact']);
$skype->setAttrib('class', 'input_text');
$skype->addFilter('StringTrim');
- $skype->setDecorators(array('viewHelper'));
+ $skype->setDecorators(['viewHelper']);
$this->addElement($skype);
$jabber = new Zend_Form_Element_Text('cu_jabber');
$jabber->setLabel(_('Jabber:'));
- $jabber->setValue($userData["jabber_contact"]);
+ $jabber->setValue($userData['jabber_contact']);
$jabber->setAttrib('class', 'input_text');
$jabber->addFilter('StringTrim');
$jabber->addValidator($emailValidator);
- $jabber->setDecorators(array('viewHelper'));
+ $jabber->setDecorators(['viewHelper']);
$this->addElement($jabber);
- $locale = new Zend_Form_Element_Select("cu_locale");
- $locale->setLabel(_("Language:"));
+ $locale = new Zend_Form_Element_Select('cu_locale');
+ $locale->setLabel(_('Language:'));
$locale->setMultiOptions(Application_Model_Locale::getLocales());
$locale->setValue(Application_Model_Preference::GetUserLocale());
- $locale->setDecorators(array('ViewHelper'));
+ $locale->setDecorators(['ViewHelper']);
$this->addElement($locale);
$stationTz = Application_Model_Preference::GetDefaultTimezone();
$userTz = Application_Model_Preference::GetUserTimezone();
- $timezone = new Zend_Form_Element_Select("cu_timezone");
- $timezone->setLabel(_("Interface Timezone:"));
+ $timezone = new Zend_Form_Element_Select('cu_timezone');
+ $timezone->setLabel(_('Interface Timezone:'));
$timezone->setMultiOptions(Application_Common_Timezone::getTimezones());
$timezone->setValue($userTz == $stationTz ? null : $userTz);
- $timezone->setDecorators(array('ViewHelper'));
+ $timezone->setDecorators(['ViewHelper']);
$this->addElement($timezone);
}
- public function validateLogin($p_login, $p_userId) {
+ public function validateLogin($p_login, $p_userId)
+ {
$count = CcSubjsQuery::create()
->filterByDbLogin($p_login)
->filterByDbId($p_userId, Criteria::NOT_EQUAL)
- ->count();
+ ->count()
+ ;
if ($count != 0) {
- $this->getElement('cu_login')->setErrors(array(_("Login name is not unique.")));
+ $this->getElement('cu_login')->setErrors([_('Login name is not unique.')]);
+
return false;
- } else {
- return true;
}
+
+ return true;
}
// We need to add the password identical validator here in case
@@ -152,9 +154,11 @@ class Application_Form_EditUser extends Zend_Form
{
if (isset($data['cu_password'])) {
$passwordIdenticalValidator = Application_Form_Helper_ValidationTypes::overridePasswordIdenticalValidator(
- $data['cu_password']);
+ $data['cu_password']
+ );
$this->getElement('cu_passwordVerify')->addValidator($passwordIdenticalValidator);
}
+
return parent::isValid($data);
}
}
diff --git a/legacy/application/forms/GeneralPreferences.php b/legacy/application/forms/GeneralPreferences.php
index a4740ab1e..acdb2a007 100644
--- a/legacy/application/forms/GeneralPreferences.php
+++ b/legacy/application/forms/GeneralPreferences.php
@@ -6,7 +6,6 @@ require_once 'customfilters/ImageSize.php';
class Application_Form_GeneralPreferences extends Zend_Form_SubForm
{
-
public function init()
{
$maxLens = Application_Model_Show::getMaxLengths();
@@ -14,40 +13,41 @@ class Application_Form_GeneralPreferences extends Zend_Form_SubForm
$notEmptyValidator = Application_Form_Helper_ValidationTypes::overrideNotEmptyValidator();
$rangeValidator = Application_Form_Helper_ValidationTypes::overrideBetweenValidator(0, 59.9);
- $this->setDecorators(array(
- array('ViewScript', array('viewScript' => 'form/preferences_general.phtml'))
- ));
+ $this->setDecorators([
+ ['ViewScript', ['viewScript' => 'form/preferences_general.phtml']],
+ ]);
$defaultFadeIn = Application_Model_Preference::GetDefaultFadeIn();
$defaultFadeOut = Application_Model_Preference::GetDefaultFadeOut();
//Station name
- $this->addElement('text', 'stationName', array(
+ $this->addElement('text', 'stationName', [
'class' => 'input_text',
'label' => _('Station Name'),
'required' => false,
- 'filters' => array('StringTrim'),
+ 'filters' => ['StringTrim'],
'value' => Application_Model_Preference::GetStationName(),
- ));
+ ]);
// Station description
- $stationDescription = new Zend_Form_Element_Textarea("stationDescription");
+ $stationDescription = new Zend_Form_Element_Textarea('stationDescription');
$stationDescription->setLabel(_('Station Description'));
$stationDescription->setValue(Application_Model_Preference::GetStationDescription());
$stationDescription->setRequired(false);
- $stationDescription->setValidators(array(array('StringLength', false, array(0, $maxLens['description']))));
+ $stationDescription->setValidators([['StringLength', false, [0, $maxLens['description']]]]);
$stationDescription->setAttrib('rows', 4);
$this->addElement($stationDescription);
// Station Logo
$stationLogoUpload = new Zend_Form_Element_File('stationLogo');
$stationLogoUpload->setLabel(_('Station Logo:'))
- ->setDescription(_("Note: Anything larger than 600x600 will be resized."))
+ ->setDescription(_('Note: Anything larger than 600x600 will be resized.'))
->setRequired(false)
->addValidator('Count', false, 1)
->addValidator('Extension', false, 'jpg,jpeg,png,gif')
->setMaxFileSize(1000000)
- ->addFilter('ImageSize');
+ ->addFilter('ImageSize')
+ ;
$stationLogoUpload->setAttrib('accept', 'image/*');
$this->addElement($stationLogoUpload);
@@ -59,94 +59,94 @@ class Application_Form_GeneralPreferences extends Zend_Form_SubForm
$this->addElement($stationLogoRemove);
//Default station crossfade duration
- $this->addElement('text', 'stationDefaultCrossfadeDuration', array(
+ $this->addElement('text', 'stationDefaultCrossfadeDuration', [
'class' => 'input_text',
'label' => _('Default Crossfade Duration (s):'),
'required' => true,
- 'filters' => array('StringTrim'),
- 'validators' => array(
- $rangeValidator,
- $notEmptyValidator,
- array('regex', false, array('/^[0-9]+(\.\d+)?$/', 'messages' => _('Please enter a time in seconds (eg. 0.5)')))
- ),
+ 'filters' => ['StringTrim'],
+ 'validators' => [
+ $rangeValidator,
+ $notEmptyValidator,
+ ['regex', false, ['/^[0-9]+(\.\d+)?$/', 'messages' => _('Please enter a time in seconds (eg. 0.5)')]],
+ ],
'value' => Application_Model_Preference::GetDefaultCrossfadeDuration(),
- ));
+ ]);
//Default station fade in
- $this->addElement('text', 'stationDefaultFadeIn', array(
+ $this->addElement('text', 'stationDefaultFadeIn', [
'class' => 'input_text',
'label' => _('Default Fade In (s):'),
'required' => true,
- 'filters' => array('StringTrim'),
- 'validators' => array(
+ 'filters' => ['StringTrim'],
+ 'validators' => [
$rangeValidator,
$notEmptyValidator,
- array('regex', false, array('/^[0-9]+(\.\d+)?$/', 'messages' => _('Please enter a time in seconds (eg. 0.5)')))
- ),
+ ['regex', false, ['/^[0-9]+(\.\d+)?$/', 'messages' => _('Please enter a time in seconds (eg. 0.5)')]],
+ ],
'value' => $defaultFadeIn,
- ));
+ ]);
//Default station fade out
- $this->addElement('text', 'stationDefaultFadeOut', array(
+ $this->addElement('text', 'stationDefaultFadeOut', [
'class' => 'input_text',
'label' => _('Default Fade Out (s):'),
'required' => true,
- 'filters' => array('StringTrim'),
- 'validators' => array(
+ 'filters' => ['StringTrim'],
+ 'validators' => [
$rangeValidator,
$notEmptyValidator,
- array('regex', false, array('/^[0-9]+(\.\d+)?$/', 'messages' => _('Please enter a time in seconds (eg. 0.5)')))
- ),
+ ['regex', false, ['/^[0-9]+(\.\d+)?$/', 'messages' => _('Please enter a time in seconds (eg. 0.5)')]],
+ ],
'value' => $defaultFadeOut,
- ));
+ ]);
- $tracktypeDefault = new Zend_Form_Element_Select("tracktypeDefault");
- $tracktypeDefault->setLabel(_("Track Type Upload Default"));
+ $tracktypeDefault = new Zend_Form_Element_Select('tracktypeDefault');
+ $tracktypeDefault->setLabel(_('Track Type Upload Default'));
$tracktypeDefault->setMultiOptions(Application_Model_Library::getTracktypes());
$tracktypeDefault->setValue(Application_Model_Preference::GetTrackTypeDefault());
$this->addElement($tracktypeDefault);
// add intro playlist select here
- $introPlaylistSelect = new Zend_Form_Element_Select("introPlaylistSelect");
- $introPlaylistSelect->setLabel(_("Intro Autoloading Playlist"));
+ $introPlaylistSelect = new Zend_Form_Element_Select('introPlaylistSelect');
+ $introPlaylistSelect->setLabel(_('Intro Autoloading Playlist'));
$introPlaylistSelect->setMultiOptions(Application_Model_Library::getPlaylistNames(true));
$introPlaylistSelect->setValue(Application_Model_Preference::GetIntroPlaylist());
$this->addElement($introPlaylistSelect);
- $outroPlaylistSelect = new Zend_Form_Element_Select("outroPlaylistSelect");
- $outroPlaylistSelect->setLabel(_("Outro Autoloading Playlist"));
+ $outroPlaylistSelect = new Zend_Form_Element_Select('outroPlaylistSelect');
+ $outroPlaylistSelect->setLabel(_('Outro Autoloading Playlist'));
$outroPlaylistSelect->setMultiOptions(Application_Model_Library::getPlaylistNames(true));
$outroPlaylistSelect->setValue(Application_Model_Preference::GetOutroPlaylist());
$this->addElement($outroPlaylistSelect);
$podcast_album_override = new Zend_Form_Element_Radio('podcastAlbumOverride');
$podcast_album_override->setLabel(_('Overwrite Podcast Episode Metatags'));
- $podcast_album_override->setMultiOptions(array(
- _("Disabled"),
- _("Enabled"),
- ));
+ $podcast_album_override->setMultiOptions([
+ _('Disabled'),
+ _('Enabled'),
+ ]);
$podcast_album_override->setValue(Application_Model_Preference::GetPodcastAlbumOverride());
$podcast_album_override->setDescription(_('Enabling this feature will cause podcast episode tracks to have their Artist, Title, and Album metatags set from podcast feed values. Note that enabling this feature is recommended in order to ensure reliable scheduling of episodes via smartblocks.'));
$podcast_album_override->setSeparator(' '); //No between radio buttons
- $podcast_album_override->addDecorator('HtmlTag', array('tag' => 'dd',
- 'id'=>"podcastAlbumOverride-element",
+ $podcast_album_override->addDecorator('HtmlTag', ['tag' => 'dd',
+ 'id' => 'podcastAlbumOverride-element',
'class' => 'radio-inline-list',
- ));
+ ]);
$this->addElement($podcast_album_override);
$podcast_auto_smartblock = new Zend_Form_Element_Radio('podcastAutoSmartblock');
$podcast_auto_smartblock->setLabel(_('Generate a smartblock and a playlist upon creation of a new podcast'));
- $podcast_auto_smartblock->setMultiOptions(array(
- _("Disabled"),
- _("Enabled"),
- ));
+ $podcast_auto_smartblock->setMultiOptions([
+ _('Disabled'),
+ _('Enabled'),
+ ]);
$podcast_auto_smartblock->setValue(Application_Model_Preference::GetPodcastAutoSmartblock());
$podcast_auto_smartblock->setDescription(_('If this option is enabled, a new smartblock and playlist matching the newest track of a podcast will be generated immediately upon creation of a new podcast. Note that the "Overwrite Podcast Episode Metatags" feature must also be enabled in order for smartblocks to reliably find episodes.'));
$podcast_auto_smartblock->setSeparator(' '); //No between radio buttons
- $podcast_auto_smartblock->addDecorator('HtmlTag', array('tag' => 'dd',
- 'id'=>"podcastAutoSmartblock-element",
+ $podcast_auto_smartblock->addDecorator('HtmlTag', ['tag' => 'dd',
+ 'id' => 'podcastAutoSmartblock-element',
'class' => 'radio-inline-list',
- ));
+ ]);
$this->addElement($podcast_auto_smartblock);
//TODO add and insert Podcast Smartblock and Playlist autogenerate options
@@ -154,19 +154,19 @@ class Application_Form_GeneralPreferences extends Zend_Form_SubForm
$third_party_api = new Zend_Form_Element_Radio('thirdPartyApi');
$third_party_api->setLabel(_('Public LibreTime API'));
$third_party_api->setDescription(_('Required for embeddable schedule widget.'));
- $third_party_api->setMultiOptions(array(
- _("Disabled"),
- _("Enabled"),
- ));
+ $third_party_api->setMultiOptions([
+ _('Disabled'),
+ _('Enabled'),
+ ]);
$third_party_api->setValue(Application_Model_Preference::GetAllow3rdPartyApi());
$third_party_api->setDescription(_('Enabling this feature will allow LibreTime to provide schedule data
to external widgets that can be embedded in your website.'));
$third_party_api->setSeparator(' '); //No between radio buttons
//$third_party_api->addDecorator(new Zend_Form_Decorator_Label(array('tag' => 'dd', 'class' => 'radio-inline-list')));
- $third_party_api->addDecorator('HtmlTag', array('tag' => 'dd',
- 'id'=>"thirdPartyApi-element",
- 'class' => 'radio-inline-list',
- ));
+ $third_party_api->addDecorator('HtmlTag', ['tag' => 'dd',
+ 'id' => 'thirdPartyApi-element',
+ 'class' => 'radio-inline-list',
+ ]);
$this->addElement($third_party_api);
$allowedCorsUrlsValue = Application_Model_Preference::GetAllowedCorsUrls();
@@ -176,69 +176,67 @@ class Application_Form_GeneralPreferences extends Zend_Form_SubForm
$allowedCorsUrls->setValue($allowedCorsUrlsValue);
$this->addElement($allowedCorsUrls);
- $locale = new Zend_Form_Element_Select("locale");
- $locale->setLabel(_("Default Language"));
+ $locale = new Zend_Form_Element_Select('locale');
+ $locale->setLabel(_('Default Language'));
$locale->setMultiOptions(Application_Model_Locale::getLocales());
$locale->setValue(Application_Model_Preference::GetDefaultLocale());
$this->addElement($locale);
- /* Form Element for setting the Timezone */
- $timezone = new Zend_Form_Element_Select("timezone");
- $timezone->setLabel(_("Station Timezone"));
+ // Form Element for setting the Timezone
+ $timezone = new Zend_Form_Element_Select('timezone');
+ $timezone->setLabel(_('Station Timezone'));
$timezone->setMultiOptions(Application_Common_Timezone::getTimezones());
$timezone->setValue(Application_Model_Preference::GetDefaultTimezone());
$this->addElement($timezone);
- /* Form Element for setting which day is the start of the week */
- $week_start_day = new Zend_Form_Element_Select("weekStartDay");
- $week_start_day->setLabel(_("Week Starts On"));
+ // Form Element for setting which day is the start of the week
+ $week_start_day = new Zend_Form_Element_Select('weekStartDay');
+ $week_start_day->setLabel(_('Week Starts On'));
$week_start_day->setMultiOptions($this->getWeekStartDays());
$week_start_day->setValue(Application_Model_Preference::GetWeekStartDay());
$this->addElement($week_start_day);
- $radioPageLoginButton = new Zend_Form_Element_Checkbox("radioPageLoginButton");
- $radioPageLoginButton->setDecorators(array(
+ $radioPageLoginButton = new Zend_Form_Element_Checkbox('radioPageLoginButton');
+ $radioPageLoginButton->setDecorators([
'ViewHelper',
'Errors',
- 'Label'
- ));
+ 'Label',
+ ]);
$displayRadioPageLoginButtonValue = Application_Model_Preference::getRadioPageDisplayLoginButton();
- if ($displayRadioPageLoginButtonValue == "") {
+ if ($displayRadioPageLoginButtonValue == '') {
$displayRadioPageLoginButtonValue = true;
}
- $radioPageLoginButton->addDecorator('Label', array("class" => "enable-tunein"));
- $radioPageLoginButton->setLabel(_("Display login button on your Radio Page?"));
+ $radioPageLoginButton->addDecorator('Label', ['class' => 'enable-tunein']);
+ $radioPageLoginButton->setLabel(_('Display login button on your Radio Page?'));
$radioPageLoginButton->setValue($displayRadioPageLoginButtonValue);
$this->addElement($radioPageLoginButton);
$feature_preview_mode = new Zend_Form_Element_Radio('featurePreviewMode');
$feature_preview_mode->setLabel(_('Feature Previews'));
- $feature_preview_mode->setMultiOptions(array(
- _("Disabled"),
- _("Enabled"),
- ));
+ $feature_preview_mode->setMultiOptions([
+ _('Disabled'),
+ _('Enabled'),
+ ]);
$feature_preview_mode->setValue(Application_Model_Preference::GetFeaturePreviewMode());
$feature_preview_mode->setDescription(_('Enable this to opt-in to test new features.'));
$feature_preview_mode->setSeparator(' '); //No between radio buttons
- $feature_preview_mode->addDecorator('HtmlTag', array('tag' => 'dd',
- 'id'=>"featurePreviewMode-element",
+ $feature_preview_mode->addDecorator('HtmlTag', ['tag' => 'dd',
+ 'id' => 'featurePreviewMode-element',
'class' => 'radio-inline-list',
- ));
+ ]);
$this->addElement($feature_preview_mode);
}
private function getWeekStartDays()
{
- $days = array(
+ return [
_('Sunday'),
_('Monday'),
_('Tuesday'),
_('Wednesday'),
_('Thursday'),
_('Friday'),
- _('Saturday')
- );
-
- return $days;
+ _('Saturday'),
+ ];
}
}
diff --git a/legacy/application/forms/LiveStreamingPreferences.php b/legacy/application/forms/LiveStreamingPreferences.php
index b3f2c08f5..bc4361b14 100644
--- a/legacy/application/forms/LiveStreamingPreferences.php
+++ b/legacy/application/forms/LiveStreamingPreferences.php
@@ -2,7 +2,6 @@
class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
{
-
public function init()
{
$CC_CONFIG = Config::getConfig();
@@ -10,29 +9,32 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
$defaultFade = Application_Model_Preference::GetDefaultTransitionFade();
- $this->setDecorators(array(
- array('ViewScript', array('viewScript' => 'form/preferences_livestream.phtml')),
- ));
+ $this->setDecorators([
+ ['ViewScript', ['viewScript' => 'form/preferences_livestream.phtml']],
+ ]);
// automatic trasition on source disconnection
- $auto_transition = new Zend_Form_Element_Checkbox("auto_transition");
- $auto_transition->setLabel(_("Auto Switch Off:"))
- ->setValue(Application_Model_Preference::GetAutoTransition());
+ $auto_transition = new Zend_Form_Element_Checkbox('auto_transition');
+ $auto_transition->setLabel(_('Auto Switch Off:'))
+ ->setValue(Application_Model_Preference::GetAutoTransition())
+ ;
$this->addElement($auto_transition);
// automatic switch on upon source connection
- $auto_switch = new Zend_Form_Element_Checkbox("auto_switch");
- $auto_switch->setLabel(_("Auto Switch On:"))
- ->setValue(Application_Model_Preference::GetAutoSwitch());
+ $auto_switch = new Zend_Form_Element_Checkbox('auto_switch');
+ $auto_switch->setLabel(_('Auto Switch On:'))
+ ->setValue(Application_Model_Preference::GetAutoSwitch())
+ ;
$this->addElement($auto_switch);
// Default transition fade
- $transition_fade = new Zend_Form_Element_Text("transition_fade");
- $transition_fade->setLabel(_("Switch Transition Fade (s):"))
- ->setFilters(array('StringTrim'))
- ->addValidator('regex', false, array('/^\d*(\.\d+)?$/',
- 'messages' => _('Please enter a time in seconds (eg. 0.5)')))
- ->setValue($defaultFade);
+ $transition_fade = new Zend_Form_Element_Text('transition_fade');
+ $transition_fade->setLabel(_('Switch Transition Fade (s):'))
+ ->setFilters(['StringTrim'])
+ ->addValidator('regex', false, ['/^\d*(\.\d+)?$/',
+ 'messages' => _('Please enter a time in seconds (eg. 0.5)'), ])
+ ->setValue($defaultFade)
+ ;
$this->addElement($transition_fade);
//Master username
@@ -40,8 +42,9 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
$master_username->setAttrib('autocomplete', 'off')
->setAllowEmpty(true)
->setLabel(_('Username:'))
- ->setFilters(array('StringTrim'))
- ->setValue(Application_Model_Preference::GetLiveStreamMasterUsername());
+ ->setFilters(['StringTrim'])
+ ->setValue(Application_Model_Preference::GetLiveStreamMasterUsername())
+ ;
$this->addElement($master_username);
//Master password
@@ -56,7 +59,8 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
->setAllowEmpty(true)
->setValue(Application_Model_Preference::GetLiveStreamMasterPassword())
->setLabel(_('Password:'))
- ->setFilters(array('StringTrim'));
+ ->setFilters(['StringTrim'])
+ ;
$this->addElement($master_password);
$masterSourceParams = parse_url(Application_Model_Preference::GetMasterDJSourceConnectionURL());
@@ -65,10 +69,10 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
$masterSourceHost = new Zend_Form_Element_Text('master_source_host');
$masterSourceHost->setLabel(_('Master Source Host:'))
->setAttrib('readonly', true)
- ->setValue(Application_Model_Preference::GetMasterDJSourceConnectionURL());
+ ->setValue(Application_Model_Preference::GetMasterDJSourceConnectionURL())
+ ;
$this->addElement($masterSourceHost);
-
//liquidsoap harbor.input port
$betweenValidator = Application_Form_Helper_ValidationTypes::overrideBetweenValidator(1024, 49151);
@@ -77,19 +81,19 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
$masterSourcePort = new Zend_Form_Element_Text('master_source_port');
$masterSourcePort->setLabel(_('Master Source Port:'))
->setValue($m_port)
- ->setValidators(array($betweenValidator))
- ->addValidator('regex', false, array('pattern'=>'/^[0-9]+$/', 'messages'=>array('regexNotMatch'=>_('Only numbers are allowed.'))));
-
- $this->addElement($masterSourcePort);
-
+ ->setValidators([$betweenValidator])
+ ->addValidator('regex', false, ['pattern' => '/^[0-9]+$/', 'messages' => ['regexNotMatch' => _('Only numbers are allowed.')]])
+ ;
+ $this->addElement($masterSourcePort);
$m_mount = Application_Model_StreamSetting::getMasterLiveStreamMountPoint();
$masterSourceMount = new Zend_Form_Element_Text('master_source_mount');
$masterSourceMount->setLabel(_('Master Source Mount:'))
->setValue($m_mount)
- ->setValidators(array(
- array('regex', false, array('/^[^ &<>]+$/', 'messages' => _('Invalid character entered')))));
+ ->setValidators([
+ ['regex', false, ['/^[^ &<>]+$/', 'messages' => _('Invalid character entered')]], ])
+ ;
$this->addElement($masterSourceMount);
$showSourceParams = parse_url(Application_Model_Preference::GetLiveDJSourceConnectionURL());
@@ -98,7 +102,8 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
$showSourceHost = new Zend_Form_Element_Text('show_source_host');
$showSourceHost->setLabel(_('Show Source Host:'))
->setAttrib('readonly', true)
- ->setValue(Application_Model_Preference::GetLiveDJSourceConnectionURL());
+ ->setValue(Application_Model_Preference::GetLiveDJSourceConnectionURL())
+ ;
$this->addElement($showSourceHost);
//liquidsoap harbor.input port
@@ -107,16 +112,18 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
$showSourcePort = new Zend_Form_Element_Text('show_source_port');
$showSourcePort->setLabel(_('Show Source Port:'))
->setValue($l_port)
- ->setValidators(array($betweenValidator))
- ->addValidator('regex', false, array('pattern' => '/^[0-9]+$/', 'messages' => array('regexNotMatch' => _('Only numbers are allowed.'))));
+ ->setValidators([$betweenValidator])
+ ->addValidator('regex', false, ['pattern' => '/^[0-9]+$/', 'messages' => ['regexNotMatch' => _('Only numbers are allowed.')]])
+ ;
$this->addElement($showSourcePort);
$l_mount = Application_Model_StreamSetting::getDjLiveStreamMountPoint();
$showSourceMount = new Zend_Form_Element_Text('show_source_mount');
$showSourceMount->setLabel(_('Show Source Mount:'))
->setValue($l_mount)
- ->setValidators(array(
- array('regex', false, array('/^[^ &<>]+$/', 'messages' => _('Invalid character entered')))));
+ ->setValidators([
+ ['regex', false, ['/^[^ &<>]+$/', 'messages' => _('Invalid character entered')]], ])
+ ;
$this->addElement($showSourceMount);
}
@@ -129,20 +136,20 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
$showSourceParams = parse_url(Application_Model_Preference::GetLiveDJSourceConnectionURL());
$this->setDecorators(
- array(
- array('ViewScript',
- array(
+ [
+ ['ViewScript',
+ [
'viewScript' => 'form/preferences_livestream.phtml',
- 'master_source_host' => isset($masterSourceHost) ? Application_Model_Preference::GetMasterDJSourceConnectionURL() : "",
- 'master_source_port' => isset($masterSourcePort) ? Application_Model_StreamSetting::getMasterLiveStreamPort() : "",
- 'master_source_mount' => isset($masterSourceMount) ? Application_Model_StreamSetting::getMasterLiveStreamMountPoint() : "",
- 'show_source_host' => isset($showSourceHost) ? Application_Model_Preference::GetLiveDJSourceConnectionURL() : "",
- 'show_source_port' => isset($showSourcePort) ? Application_Model_StreamSetting::getDjLiveStreamPort() : "",
- 'show_source_mount' => isset($showSourceMount) ? Application_Model_StreamSetting::getDjLiveStreamMountPoint() : "",
+ 'master_source_host' => isset($masterSourceHost) ? Application_Model_Preference::GetMasterDJSourceConnectionURL() : '',
+ 'master_source_port' => isset($masterSourcePort) ? Application_Model_StreamSetting::getMasterLiveStreamPort() : '',
+ 'master_source_mount' => isset($masterSourceMount) ? Application_Model_StreamSetting::getMasterLiveStreamMountPoint() : '',
+ 'show_source_host' => isset($showSourceHost) ? Application_Model_Preference::GetLiveDJSourceConnectionURL() : '',
+ 'show_source_port' => isset($showSourcePort) ? Application_Model_StreamSetting::getDjLiveStreamPort() : '',
+ 'show_source_mount' => isset($showSourceMount) ? Application_Model_StreamSetting::getDjLiveStreamMountPoint() : '',
'isDemo' => $isDemo,
- )
- )
- )
+ ],
+ ],
+ ]
);
}
}
diff --git a/legacy/application/forms/Login.php b/legacy/application/forms/Login.php
index 5e7cfef25..ceec710f4 100644
--- a/legacy/application/forms/Login.php
+++ b/legacy/application/forms/Login.php
@@ -2,7 +2,6 @@
class Application_Form_Login extends Zend_Form
{
-
public function init()
{
$CC_CONFIG = Config::getConfig();
@@ -19,73 +18,73 @@ class Application_Form_Login extends Zend_Form
foreach (CORSHelper::getAllowedOrigins($request) as $safeOrigin) {
if ($this->startsWith($safeOrigin, $refererUrl)) {
$originIsSafe = true;
+
break;
}
}
}
if (!$originIsSafe) {
- $this->addElement('hash', 'csrf', array(
- 'salt' => 'unique'
- ));
+ $this->addElement('hash', 'csrf', [
+ 'salt' => 'unique',
+ ]);
}
- $this->setDecorators(array(
- array('ViewScript', array('viewScript' => 'form/login.phtml'))
- ));
+ $this->setDecorators([
+ ['ViewScript', ['viewScript' => 'form/login.phtml']],
+ ]);
// Add username element
- $username = new Zend_Form_Element_Text("username");
+ $username = new Zend_Form_Element_Text('username');
$username->setLabel(_('Username:'))
- ->setAttribs(array(
+ ->setAttribs([
'autofocus' => 'true',
'class' => 'input_text',
- 'required' => 'true'))
- ->setValue((isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1)?'admin':'')
+ 'required' => 'true', ])
+ ->setValue((isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1) ? 'admin' : '')
->addFilter('StringTrim')
- ->setDecorators(array('ViewHelper'))
- ->setValidators(array('NotEmpty'));
+ ->setDecorators(['ViewHelper'])
+ ->setValidators(['NotEmpty'])
+ ;
$this->addElement($username);
// Add password element
- $this->addElement('password', 'password', array(
- 'label' => _('Password:'),
- 'class' => 'input_text',
- 'required' => true,
- 'value' => (isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1)?'admin':'',
- 'filters' => array('StringTrim'),
- 'validators' => array(
+ $this->addElement('password', 'password', [
+ 'label' => _('Password:'),
+ 'class' => 'input_text',
+ 'required' => true,
+ 'value' => (isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1) ? 'admin' : '',
+ 'filters' => ['StringTrim'],
+ 'validators' => [
'NotEmpty',
- ),
- 'decorators' => array(
- 'ViewHelper'
- )
- ));
-
- $locale = new Zend_Form_Element_Select("locale");
- $locale->setLabel(_("Language:"));
+ ],
+ 'decorators' => [
+ 'ViewHelper',
+ ],
+ ]);
+
+ $locale = new Zend_Form_Element_Select('locale');
+ $locale->setLabel(_('Language:'));
$locale->setMultiOptions(Application_Model_Locale::getLocales());
- $locale->setDecorators(array('ViewHelper'));
+ $locale->setDecorators(['ViewHelper']);
$this->addElement($locale);
- $this->setDefaults(array(
- "locale" => Application_Model_Locale::getUserLocale()
- ));
+ $this->setDefaults([
+ 'locale' => Application_Model_Locale::getUserLocale(),
+ ]);
// Add the submit button
- $this->addElement('submit', 'submit', array(
- 'ignore' => true,
- 'label' => _('Login'),
- 'class' => 'ui-button ui-widget ui-state-default ui-button-text-only center',
- 'decorators' => array(
- 'ViewHelper'
- )
- ));
-
+ $this->addElement('submit', 'submit', [
+ 'ignore' => true,
+ 'label' => _('Login'),
+ 'class' => 'ui-button ui-widget ui-state-default ui-button-text-only center',
+ 'decorators' => [
+ 'ViewHelper',
+ ],
+ ]);
}
-
/**
- * tests if a string starts with a given string
+ * tests if a string starts with a given string.
*
* This method was pinched as is from phing since it was the only line of code
* actually used from phing. I'm not 100% convinced why it was deemed necessary
@@ -102,10 +101,10 @@ class Application_Form_Login extends Zend_Form
*/
private function startsWith($check, $string)
{
- if ($check === "" || $check === $string) {
+ if ($check === '' || $check === $string) {
return true;
- } else {
- return (strpos($string, $check) === 0) ? true : false;
}
+
+ return (strpos($string, $check) === 0) ? true : false;
}
}
diff --git a/legacy/application/forms/PasswordChange.php b/legacy/application/forms/PasswordChange.php
index ff29da86a..6112ef2ad 100644
--- a/legacy/application/forms/PasswordChange.php
+++ b/legacy/application/forms/PasswordChange.php
@@ -1,51 +1,49 @@
setDecorators(array(
- array('ViewScript', array('viewScript' => 'form/password-change.phtml'))
- ));
-
+ $this->setDecorators([
+ ['ViewScript', ['viewScript' => 'form/password-change.phtml']],
+ ]);
+
$notEmptyValidator = Application_Form_Helper_ValidationTypes::overrideNotEmptyValidator();
$stringLengthValidator = Application_Form_Helper_ValidationTypes::overrideStringLengthValidator(6, 80);
- $this->addElement('password', 'password', array(
+ $this->addElement('password', 'password', [
'label' => _('Password'),
'required' => true,
- 'filters' => array('stringTrim'),
- 'validators' => array($notEmptyValidator,
- $stringLengthValidator),
- 'decorators' => array(
- 'ViewHelper'
- )
- ));
+ 'filters' => ['stringTrim'],
+ 'validators' => [$notEmptyValidator,
+ $stringLengthValidator, ],
+ 'decorators' => [
+ 'ViewHelper',
+ ],
+ ]);
- $this->addElement('password', 'password_confirm', array(
+ $this->addElement('password', 'password_confirm', [
'label' => _('Confirm new password'),
'required' => true,
- 'filters' => array('stringTrim'),
- 'validators' => array(
+ 'filters' => ['stringTrim'],
+ 'validators' => [
new Zend_Validate_Callback(function ($value, $context) {
return $value == $context['password'];
}),
- ),
- 'errorMessages' => array(_("Password confirmation does not match your password.")),
- 'decorators' => array(
- 'ViewHelper'
- )
- ));
+ ],
+ 'errorMessages' => [_('Password confirmation does not match your password.')],
+ 'decorators' => [
+ 'ViewHelper',
+ ],
+ ]);
- $this->addElement('submit', 'submit', array(
+ $this->addElement('submit', 'submit', [
'label' => _('Save'),
'ignore' => true,
'class' => 'ui-button ui-widget ui-state-default ui-button-text-only center',
- 'decorators' => array(
- 'ViewHelper'
- )
- ));
+ 'decorators' => [
+ 'ViewHelper',
+ ],
+ ]);
}
}
diff --git a/legacy/application/forms/PasswordRestore.php b/legacy/application/forms/PasswordRestore.php
index ec3621ca4..5cb5cd8ed 100644
--- a/legacy/application/forms/PasswordRestore.php
+++ b/legacy/application/forms/PasswordRestore.php
@@ -1,52 +1,51 @@
setDecorators(array(
- array('ViewScript', array('viewScript' => 'form/password-restore.phtml'))
- ));
+ $this->setDecorators([
+ ['ViewScript', ['viewScript' => 'form/password-restore.phtml']],
+ ]);
- $this->addElement('text', 'email', array(
+ $this->addElement('text', 'email', [
'label' => _('Email'),
'required' => true,
- 'filters' => array(
+ 'filters' => [
'stringTrim',
- ),
- 'decorators' => array(
- 'ViewHelper'
- )
- ));
+ ],
+ 'decorators' => [
+ 'ViewHelper',
+ ],
+ ]);
- $this->addElement('text', 'username', array(
+ $this->addElement('text', 'username', [
'label' => _('Username'),
'required' => false,
- 'filters' => array(
+ 'filters' => [
'stringTrim',
- ),
- 'decorators' => array(
- 'ViewHelper'
- )
- ));
+ ],
+ 'decorators' => [
+ 'ViewHelper',
+ ],
+ ]);
- $this->addElement('submit', 'submit', array(
+ $this->addElement('submit', 'submit', [
'label' => _('Reset password'),
'ignore' => true,
'class' => 'ui-button ui-widget ui-state-default ui-button-text-only center',
- 'decorators' => array(
- 'ViewHelper'
- )
- ));
+ 'decorators' => [
+ 'ViewHelper',
+ ],
+ ]);
- $cancel = new Zend_Form_Element_Button("cancel");
+ $cancel = new Zend_Form_Element_Button('cancel');
$cancel->class = 'ui-button ui-widget ui-state-default ui-button-text-only center';
- $cancel->setLabel(_("Back"))
- ->setIgnore(True)
- ->setAttrib('onclick', 'window.location = ' . Zend_Controller_Front::getInstance()->getBaseUrl('login'))
- ->setDecorators(array('ViewHelper'));
+ $cancel->setLabel(_('Back'))
+ ->setIgnore(true)
+ ->setAttrib('onclick', 'window.location = ' . Zend_Controller_Front::getInstance()->getBaseUrl('login'))
+ ->setDecorators(['ViewHelper'])
+ ;
$this->addElement($cancel);
}
}
diff --git a/legacy/application/forms/Player.php b/legacy/application/forms/Player.php
index 862f0fd25..6f287792c 100644
--- a/legacy/application/forms/Player.php
+++ b/legacy/application/forms/Player.php
@@ -1,48 +1,48 @@
setDecorators(array(
- array('ViewScript', array('viewScript' => 'form/player.phtml'))
- ));
+ $this->setDecorators([
+ ['ViewScript', ['viewScript' => 'form/player.phtml']],
+ ]);
$title = new Zend_Form_Element_Text('player_title');
$title->setValue(_('Now Playing'));
$title->setLabel(_('Title:'));
- $title->setDecorators(array(
+ $title->setDecorators([
'ViewHelper',
'Errors',
- 'Label'
- ));
- $title->addDecorator('Label', array('class' => 'player-title'));
+ 'Label',
+ ]);
+ $title->addDecorator('Label', ['class' => 'player-title']);
$this->addElement($title);
$streamMode = new Zend_Form_Element_Radio('player_stream_mode');
$streamMode->setLabel(_('Select Stream:'));
$streamMode->setMultiOptions(
- array(
- "auto" => _("Auto detect the most appropriate stream to use."),
- "manual" => _("Select a stream:")
- )
+ [
+ 'auto' => _('Auto detect the most appropriate stream to use.'),
+ 'manual' => _('Select a stream:'),
+ ]
);
- $streamMode->setValue("auto");
+ $streamMode->setValue('auto');
$this->addElement($streamMode);
$streamURL = new Zend_Form_Element_Radio('player_stream_url');
$opusStreamCount = 0;
- $urlOptions = Array();
- foreach(Application_Model_StreamSetting::getEnabledStreamData() as $stream => $data) {
- $urlOptions[$stream] = strtoupper($data["codec"])." - ".$data["bitrate"]."kbps";
- if ($data["mobile"]) {
- $urlOptions[$stream] .= _(" - Mobile friendly");
+ $urlOptions = [];
+ foreach (Application_Model_StreamSetting::getEnabledStreamData() as $stream => $data) {
+ $urlOptions[$stream] = strtoupper($data['codec']) . ' - ' . $data['bitrate'] . 'kbps';
+ if ($data['mobile']) {
+ $urlOptions[$stream] .= _(' - Mobile friendly');
}
- if ($data["codec"] == OPUS) {
- $opusStreamCount += 1;
- $urlOptions[$stream] .= _(" - The player does not support Opus streams.");
+ if ($data['codec'] == OPUS) {
+ ++$opusStreamCount;
+ $urlOptions[$stream] .= _(' - The player does not support Opus streams.');
}
}
$streamURL->setMultiOptions(
@@ -53,35 +53,35 @@ class Application_Form_Player extends Zend_Form_SubForm
foreach ($urlOptions as $o => $v) {
if (strpos(strtolower($v), OPUS) !== false) {
continue;
- } else {
- $streamURL->setValue($o);
- break;
}
+ $streamURL->setValue($o);
+
+ break;
}
- $streamURL->setAttrib('numberOfEnabledStreams', sizeof($urlOptions)-$opusStreamCount);
+ $streamURL->setAttrib('numberOfEnabledStreams', sizeof($urlOptions) - $opusStreamCount);
$streamURL->removeDecorator('label');
$this->addElement($streamURL);
$embedSrc = new Zend_Form_Element_Textarea('player_embed_src');
- $embedSrc->setAttrib("readonly", "readonly");
- $embedSrc->setAttrib("class", "embed-player-text-box");
+ $embedSrc->setAttrib('readonly', 'readonly');
+ $embedSrc->setAttrib('class', 'embed-player-text-box');
$embedSrc->setAttrib('cols', '40')
- ->setAttrib('rows', '4');
- $embedSrc->setLabel(_("Embeddable code:"));
+ ->setAttrib('rows', '4')
+ ;
+ $embedSrc->setLabel(_('Embeddable code:'));
$embedSrc->setDescription(_("Copy this code and paste it into your website's HTML to embed the player in your site."));
- $embedSrc->setValue('');
+ $embedSrc->setValue('');
$this->addElement($embedSrc);
$previewLabel = new Zend_Form_Element_Text('player_preview_label');
- $previewLabel->setLabel(_("Preview:"));
- $previewLabel->setDecorators(array(
+ $previewLabel->setLabel(_('Preview:'));
+ $previewLabel->setDecorators([
'ViewHelper',
'Errors',
- 'Label'
- ));
- $previewLabel->addDecorator('Label', array('class' => 'preview-label'));
+ 'Label',
+ ]);
+ $previewLabel->addDecorator('Label', ['class' => 'preview-label']);
$this->addElement($previewLabel);
-
}
}
diff --git a/legacy/application/forms/PodcastPreferences.php b/legacy/application/forms/PodcastPreferences.php
index 9c007439e..01e7a73b8 100644
--- a/legacy/application/forms/PodcastPreferences.php
+++ b/legacy/application/forms/PodcastPreferences.php
@@ -1,22 +1,22 @@
setLabel(_('Feed Privacy'));
- $stationPodcastPrivacy->setMultiOptions(array(
- _("Public"),
- _("Private"),
- ));
+ $stationPodcastPrivacy->setMultiOptions([
+ _('Public'),
+ _('Private'),
+ ]);
$stationPodcastPrivacy->setSeparator(' ');
- $stationPodcastPrivacy->addDecorator('HtmlTag', array('tag' => 'dd',
- 'id'=>"stationPodcastPrivacy-element",
+ $stationPodcastPrivacy->addDecorator('HtmlTag', ['tag' => 'dd',
+ 'id' => 'stationPodcastPrivacy-element',
'class' => 'radio-inline-list',
- ));
+ ]);
$stationPodcastPrivacy->setValue($isPrivate);
$this->addElement($stationPodcastPrivacy);
}
-
-}
\ No newline at end of file
+}
diff --git a/legacy/application/forms/Preferences.php b/legacy/application/forms/Preferences.php
index 1892d5dd2..eb59b5417 100644
--- a/legacy/application/forms/Preferences.php
+++ b/legacy/application/forms/Preferences.php
@@ -6,9 +6,9 @@ class Application_Form_Preferences extends Zend_Form
{
$baseUrl = Application_Common_OsPath::getBaseDir();
- $this->setDecorators(array(
- array('ViewScript', array('viewScript' => 'form/preferences.phtml'))
- ));
+ $this->setDecorators([
+ ['ViewScript', ['viewScript' => 'form/preferences.phtml']],
+ ]);
$general_pref = new Application_Form_GeneralPreferences();
@@ -36,7 +36,7 @@ class Application_Form_Preferences extends Zend_Form
$submit = new Zend_Form_Element_Submit('submit');
$submit->setLabel(_('Save'));
//$submit->removeDecorator('Label');
- $submit->setAttribs(array('class'=>'btn right-floated'));
+ $submit->setAttribs(['class' => 'btn right-floated']);
$submit->removeDecorator('DtDdWrapper');
$this->addElement($submit);
diff --git a/legacy/application/forms/ScheduleShow.php b/legacy/application/forms/ScheduleShow.php
index 5ec6f8174..2239d10d9 100644
--- a/legacy/application/forms/ScheduleShow.php
+++ b/legacy/application/forms/ScheduleShow.php
@@ -2,10 +2,8 @@
class Application_Form_ScheduleShow extends Zend_Form
{
-
public function init()
{
- /* Form Elements & Other Definitions Here ... */
+ // Form Elements & Other Definitions Here ...
}
-
}
diff --git a/legacy/application/forms/SetupLanguageTimezone.php b/legacy/application/forms/SetupLanguageTimezone.php
index 5e90308f3..82151ba95 100644
--- a/legacy/application/forms/SetupLanguageTimezone.php
+++ b/legacy/application/forms/SetupLanguageTimezone.php
@@ -2,12 +2,10 @@
class Application_Form_SetupLanguageTimezone extends Zend_Form_SubForm
{
-
public function init()
{
-
- $this->setDecorators(array(
- array('ViewScript', array('viewScript' => 'form/setup-lang-timezone.phtml'))));
+ $this->setDecorators([
+ ['ViewScript', ['viewScript' => 'form/setup-lang-timezone.phtml']], ]);
$csrf_namespace = new Zend_Session_Namespace('csrf_namespace');
$csrf_element = new Zend_Form_Element_Hidden('csrf');
@@ -15,14 +13,13 @@ class Application_Form_SetupLanguageTimezone extends Zend_Form_SubForm
$this->addElement($csrf_element);
$language = new Zend_Form_Element_Select('setup_language');
- $language->setLabel(_("Station Language"));
+ $language->setLabel(_('Station Language'));
$language->setMultiOptions(Application_Model_Locale::getLocales());
$this->addElement($language);
$timezone = new Zend_Form_Element_Select('setup_timezone');
- $timezone->setLabel(_("Station Timezone"));
+ $timezone->setLabel(_('Station Timezone'));
$timezone->setMultiOptions(Application_Common_Timezone::getTimezones());
$this->addElement($timezone);
}
}
-
diff --git a/legacy/application/forms/ShowBuilder.php b/legacy/application/forms/ShowBuilder.php
index 5e7c54ff5..0cd414e32 100644
--- a/legacy/application/forms/ShowBuilder.php
+++ b/legacy/application/forms/ShowBuilder.php
@@ -2,26 +2,26 @@
class Application_Form_ShowBuilder extends Zend_Form_SubForm
{
-
public function init()
{
$user = Application_Model_User::getCurrentUser();
- $this->setDecorators(array(
- array('ViewScript', array('viewScript' => 'form/showbuilder.phtml'))
- ));
+ $this->setDecorators([
+ ['ViewScript', ['viewScript' => 'form/showbuilder.phtml']],
+ ]);
// Add start date element
$startDate = new Zend_Form_Element_Text('sb_date_start');
$startDate->class = 'input_text';
$startDate->setRequired(true)
- ->setLabel(_('Date Start:'))
- ->setValue(date("Y-m-d"))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- 'NotEmpty',
- array('date', false, array('YYYY-MM-DD'))))
- ->setDecorators(array('ViewHelper'));
+ ->setLabel(_('Date Start:'))
+ ->setValue(date('Y-m-d'))
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ 'NotEmpty',
+ ['date', false, ['YYYY-MM-DD']], ])
+ ->setDecorators(['ViewHelper'])
+ ;
$startDate->setAttrib('alt', 'date');
$this->addElement($startDate);
@@ -29,13 +29,14 @@ class Application_Form_ShowBuilder extends Zend_Form_SubForm
$startTime = new Zend_Form_Element_Text('sb_time_start');
$startTime->class = 'input_text';
$startTime->setRequired(true)
- ->setValue('00:00')
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- 'NotEmpty',
- array('date', false, array('HH:mm')),
- array('regex', false, array('/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')))))
- ->setDecorators(array('ViewHelper'));
+ ->setValue('00:00')
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ 'NotEmpty',
+ ['date', false, ['HH:mm']],
+ ['regex', false, ['/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')]], ])
+ ->setDecorators(['ViewHelper'])
+ ;
$startTime->setAttrib('alt', 'time');
$this->addElement($startTime);
@@ -43,13 +44,14 @@ class Application_Form_ShowBuilder extends Zend_Form_SubForm
$endDate = new Zend_Form_Element_Text('sb_date_end');
$endDate->class = 'input_text';
$endDate->setRequired(true)
- ->setLabel(_('Date End:'))
- ->setValue(date("Y-m-d"))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- 'NotEmpty',
- array('date', false, array('YYYY-MM-DD'))))
- ->setDecorators(array('ViewHelper'));
+ ->setLabel(_('Date End:'))
+ ->setValue(date('Y-m-d'))
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ 'NotEmpty',
+ ['date', false, ['YYYY-MM-DD']], ])
+ ->setDecorators(['ViewHelper'])
+ ;
$endDate->setAttrib('alt', 'date');
$this->addElement($endDate);
@@ -57,28 +59,30 @@ class Application_Form_ShowBuilder extends Zend_Form_SubForm
$endTime = new Zend_Form_Element_Text('sb_time_end');
$endTime->class = 'input_text';
$endTime->setRequired(true)
- ->setValue('01:00')
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
- 'NotEmpty',
- array('date', false, array('HH:mm')),
- array('regex', false, array('/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')))))
- ->setDecorators(array('ViewHelper'));
+ ->setValue('01:00')
+ ->setFilters(['StringTrim'])
+ ->setValidators([
+ 'NotEmpty',
+ ['date', false, ['HH:mm']],
+ ['regex', false, ['/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')]], ])
+ ->setDecorators(['ViewHelper'])
+ ;
$endTime->setAttrib('alt', 'time');
$this->addElement($endTime);
// add a select to choose a show.
- $showSelect = new Zend_Form_Element_Select("sb_show_filter");
- $showSelect->setLabel(_("Filter by Show"));
+ $showSelect = new Zend_Form_Element_Select('sb_show_filter');
+ $showSelect->setLabel(_('Filter by Show'));
$showSelect->setMultiOptions($this->getShowNames());
$showSelect->setValue(null);
- $showSelect->setDecorators(array('ViewHelper'));
+ $showSelect->setDecorators(['ViewHelper']);
$this->addElement($showSelect);
if ($user->getType() === 'H') {
$myShows = new Zend_Form_Element_Checkbox('sb_my_shows');
$myShows->setLabel(_('All My Shows:'))
- ->setDecorators(array('ViewHelper'));
+ ->setDecorators(['ViewHelper'])
+ ;
$this->addElement($myShows);
}
}
@@ -86,22 +90,21 @@ class Application_Form_ShowBuilder extends Zend_Form_SubForm
private function getShowNames()
{
$user = Application_Model_User::getCurrentUser();
- $showNames = array("0" => _("Filter by Show"));
+ $showNames = ['0' => _('Filter by Show')];
if ($user->getType() === 'H') {
- $showNames["-1"] = _("My Shows");
+ $showNames['-1'] = _('My Shows');
}
$shows = CcShowQuery::create()
->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)
->orderByDbName()
- ->find();
+ ->find()
+ ;
foreach ($shows as $show) {
-
$showNames[$show->getDbId()] = $show->getDbName();
}
return $showNames;
}
-
}
diff --git a/legacy/application/forms/ShowListenerStat.php b/legacy/application/forms/ShowListenerStat.php
index 60b4eb875..af6f5baa8 100644
--- a/legacy/application/forms/ShowListenerStat.php
+++ b/legacy/application/forms/ShowListenerStat.php
@@ -2,24 +2,24 @@
class Application_Form_ShowListenerStat extends Zend_Form_SubForm
{
-
public function init()
{
- $this->setDecorators(array(
- array('ViewScript', array('viewScript' => 'form/daterange.phtml'))
- ));
+ $this->setDecorators([
+ ['ViewScript', ['viewScript' => 'form/daterange.phtml']],
+ ]);
// Add start date element
$startDate = new Zend_Form_Element_Text('his_date_start');
$startDate->class = 'input_text';
$startDate->setRequired(true)
->setLabel(_('Date Start:'))
- ->setValue(date("Y-m-d"))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
+ ->setValue(date('Y-m-d'))
+ ->setFilters(['StringTrim'])
+ ->setValidators([
'NotEmpty',
- array('date', false, array('YYYY-MM-DD'))))
- ->setDecorators(array('ViewHelper'));
+ ['date', false, ['YYYY-MM-DD']], ])
+ ->setDecorators(['ViewHelper'])
+ ;
$startDate->setAttrib('alt', 'date');
$this->addElement($startDate);
@@ -28,12 +28,13 @@ class Application_Form_ShowListenerStat extends Zend_Form_SubForm
$startTime->class = 'input_text';
$startTime->setRequired(true)
->setValue('00:00')
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
+ ->setFilters(['StringTrim'])
+ ->setValidators([
'NotEmpty',
- array('date', false, array('HH:mm')),
- array('regex', false, array('/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')))))
- ->setDecorators(array('ViewHelper'));
+ ['date', false, ['HH:mm']],
+ ['regex', false, ['/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')]], ])
+ ->setDecorators(['ViewHelper'])
+ ;
$startTime->setAttrib('alt', 'time');
$this->addElement($startTime);
@@ -42,12 +43,13 @@ class Application_Form_ShowListenerStat extends Zend_Form_SubForm
$endDate->class = 'input_text';
$endDate->setRequired(true)
->setLabel(_('Date End:'))
- ->setValue(date("Y-m-d"))
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
+ ->setValue(date('Y-m-d'))
+ ->setFilters(['StringTrim'])
+ ->setValidators([
'NotEmpty',
- array('date', false, array('YYYY-MM-DD'))))
- ->setDecorators(array('ViewHelper'));
+ ['date', false, ['YYYY-MM-DD']], ])
+ ->setDecorators(['ViewHelper'])
+ ;
$endDate->setAttrib('alt', 'date');
$this->addElement($endDate);
@@ -56,12 +58,13 @@ class Application_Form_ShowListenerStat extends Zend_Form_SubForm
$endTime->class = 'input_text';
$endTime->setRequired(true)
->setValue('01:00')
- ->setFilters(array('StringTrim'))
- ->setValidators(array(
+ ->setFilters(['StringTrim'])
+ ->setValidators([
'NotEmpty',
- array('date', false, array('HH:mm')),
- array('regex', false, array('/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')))))
- ->setDecorators(array('ViewHelper'));
+ ['date', false, ['HH:mm']],
+ ['regex', false, ['/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')]], ])
+ ->setDecorators(['ViewHelper'])
+ ;
$endTime->setAttrib('alt', 'time');
$this->addElement($endTime);
}
diff --git a/legacy/application/forms/SmartBlockCriteria.php b/legacy/application/forms/SmartBlockCriteria.php
index e3385bef2..64071476d 100644
--- a/legacy/application/forms/SmartBlockCriteria.php
+++ b/legacy/application/forms/SmartBlockCriteria.php
@@ -1,4 +1,5 @@
"",
- "album_title" => "s",
- "bit_rate" => "n",
- "bpm" => "n",
- "composer" => "s",
- "conductor" => "s",
- "copyright" => "s",
- "cuein" => "n",
- "cueout" => "n",
- "description" => "s",
- "artist_name" => "s",
- "encoded_by" => "s",
- "utime" => "d",
- "mtime" => "d",
- "lptime" => "d",
- "genre" => "s",
- "isrc_number" => "s",
- "label" => "s",
- "language" => "s",
- "length" => "n",
- "mime" => "s",
- "mood" => "s",
- "owner_id" => "s",
- "replay_gain" => "n",
- "sample_rate" => "n",
- "track_title" => "s",
- "track_number" => "n",
- "info_url" => "s",
- "year" => "n",
- "track_type" => "tt"
- );
+ private $criteriaTypes = [
+ 0 => '',
+ 'album_title' => 's',
+ 'bit_rate' => 'n',
+ 'bpm' => 'n',
+ 'composer' => 's',
+ 'conductor' => 's',
+ 'copyright' => 's',
+ 'cuein' => 'n',
+ 'cueout' => 'n',
+ 'description' => 's',
+ 'artist_name' => 's',
+ 'encoded_by' => 's',
+ 'utime' => 'd',
+ 'mtime' => 'd',
+ 'lptime' => 'd',
+ 'genre' => 's',
+ 'isrc_number' => 's',
+ 'label' => 's',
+ 'language' => 's',
+ 'length' => 'n',
+ 'mime' => 's',
+ 'mood' => 's',
+ 'owner_id' => 's',
+ 'replay_gain' => 'n',
+ 'sample_rate' => 'n',
+ 'track_title' => 's',
+ 'track_number' => 'n',
+ 'info_url' => 's',
+ 'year' => 'n',
+ 'track_type' => 'tt',
+ ];
private function getCriteriaOptions($option = null)
{
if (!isset($this->criteriaOptions)) {
- $this->criteriaOptions = array(
- 0 => _("Select criteria"),
- "album_title" => _("Album"),
- "bit_rate" => _("Bit Rate (Kbps)"),
- "bpm" => _("BPM"),
- "composer" => _("Composer"),
- "conductor" => _("Conductor"),
- "copyright" => _("Copyright"),
- "cuein" => _("Cue In"),
- "cueout" => _("Cue Out"),
- "description" => _("Description"),
- "artist_name" => _("Creator"),
- "encoded_by" => _("Encoded By"),
- "genre" => _("Genre"),
- "isrc_number" => _("ISRC"),
- "label" => _("Label"),
- "language" => _("Language"),
- "mtime" => _("Last Modified"),
- "lptime" => _("Last Played"),
- "length" => _("Length"),
- "track_type" => _("Track Type"),
- "mime" => _("Mime"),
- "mood" => _("Mood"),
- "owner_id" => _("Owner"),
- "replay_gain" => _("Replay Gain"),
- "sample_rate" => _("Sample Rate (kHz)"),
- "track_title" => _("Title"),
- "track_number" => _("Track Number"),
- "utime" => _("Uploaded"),
- "info_url" => _("Website"),
- "year" => _("Year")
- );
+ $this->criteriaOptions = [
+ 0 => _('Select criteria'),
+ 'album_title' => _('Album'),
+ 'bit_rate' => _('Bit Rate (Kbps)'),
+ 'bpm' => _('BPM'),
+ 'composer' => _('Composer'),
+ 'conductor' => _('Conductor'),
+ 'copyright' => _('Copyright'),
+ 'cuein' => _('Cue In'),
+ 'cueout' => _('Cue Out'),
+ 'description' => _('Description'),
+ 'artist_name' => _('Creator'),
+ 'encoded_by' => _('Encoded By'),
+ 'genre' => _('Genre'),
+ 'isrc_number' => _('ISRC'),
+ 'label' => _('Label'),
+ 'language' => _('Language'),
+ 'mtime' => _('Last Modified'),
+ 'lptime' => _('Last Played'),
+ 'length' => _('Length'),
+ 'track_type' => _('Track Type'),
+ 'mime' => _('Mime'),
+ 'mood' => _('Mood'),
+ 'owner_id' => _('Owner'),
+ 'replay_gain' => _('Replay Gain'),
+ 'sample_rate' => _('Sample Rate (kHz)'),
+ 'track_title' => _('Title'),
+ 'track_number' => _('Track Number'),
+ 'utime' => _('Uploaded'),
+ 'info_url' => _('Website'),
+ 'year' => _('Year'),
+ ];
}
- if (is_null($option)) return $this->criteriaOptions;
- else return $this->criteriaOptions[$option];
+ if (is_null($option)) {
+ return $this->criteriaOptions;
+ }
+
+ return $this->criteriaOptions[$option];
}
private function getStringCriteriaOptions()
{
if (!isset($this->stringCriteriaOptions)) {
- $this->stringCriteriaOptions = array(
- "0" => _("Select modifier"),
- "contains" => _("contains"),
- "does not contain" => _("does not contain"),
- "is" => _("is"),
- "is not" => _("is not"),
- "starts with" => _("starts with"),
- "ends with" => _("ends with")
- );
+ $this->stringCriteriaOptions = [
+ '0' => _('Select modifier'),
+ 'contains' => _('contains'),
+ 'does not contain' => _('does not contain'),
+ 'is' => _('is'),
+ 'is not' => _('is not'),
+ 'starts with' => _('starts with'),
+ 'ends with' => _('ends with'),
+ ];
}
+
return $this->stringCriteriaOptions;
}
private function getNumericCriteriaOptions()
{
if (!isset($this->numericCriteriaOptions)) {
- $this->numericCriteriaOptions = array(
- "0" => _("Select modifier"),
- "is" => _("is"),
- "is not" => _("is not"),
- "is greater than" => _("is greater than"),
- "is less than" => _("is less than"),
- "is in the range" => _("is in the range")
- );
+ $this->numericCriteriaOptions = [
+ '0' => _('Select modifier'),
+ 'is' => _('is'),
+ 'is not' => _('is not'),
+ 'is greater than' => _('is greater than'),
+ 'is less than' => _('is less than'),
+ 'is in the range' => _('is in the range'),
+ ];
}
+
return $this->numericCriteriaOptions;
}
-
private function getDateTimeCriteriaOptions()
{
if (!isset($this->dateTimeCriteriaOptions)) {
- $this->dateTimeCriteriaOptions = array(
- "0" => _("Select modifier"),
- "before" => _("before"),
- "after" => _("after"),
- "between" => _("between"),
- "is" => _("is"),
- "is not" => _("is not"),
- "is greater than" => _("is greater than"),
- "is less than" => _("is less than"),
- "is in the range" => _("is in the range")
- );
+ $this->dateTimeCriteriaOptions = [
+ '0' => _('Select modifier'),
+ 'before' => _('before'),
+ 'after' => _('after'),
+ 'between' => _('between'),
+ 'is' => _('is'),
+ 'is not' => _('is not'),
+ 'is greater than' => _('is greater than'),
+ 'is less than' => _('is less than'),
+ 'is in the range' => _('is in the range'),
+ ];
}
+
return $this->dateTimeCriteriaOptions;
}
-
private function getTimePeriodCriteriaOptions()
{
if (!isset($this->timePeriodCriteriaOptions)) {
- $this->timePeriodCriteriaOptions = array(
- "0" => _("Select unit of time"),
- "minute" => _("minute(s)"),
- "hour" => _("hour(s)"),
- "day" => _("day(s)"),
- "week" => _("week(s)"),
- "month" => _("month(s)"),
- "year" => _("year(s)")
- );
+ $this->timePeriodCriteriaOptions = [
+ '0' => _('Select unit of time'),
+ 'minute' => _('minute(s)'),
+ 'hour' => _('hour(s)'),
+ 'day' => _('day(s)'),
+ 'week' => _('week(s)'),
+ 'month' => _('month(s)'),
+ 'year' => _('year(s)'),
+ ];
}
+
return $this->timePeriodCriteriaOptions;
}
-
private function getLimitOptions()
{
if (!isset($this->limitOptions)) {
- $this->limitOptions = array(
- "hours" => _("hours"),
- "minutes" => _("minutes"),
- "items" => _("items"),
- "remaining" => _("time remaining in show")
- );
+ $this->limitOptions = [
+ 'hours' => _('hours'),
+ 'minutes' => _('minutes'),
+ 'items' => _('items'),
+ 'remaining' => _('time remaining in show'),
+ ];
}
+
return $this->limitOptions;
}
- private function getSortOptions()
+
+ private function getSortOptions()
{
if (!isset($this->sortOptions)) {
- $this->sortOptions = array(
- "random" => _("Randomly"),
- "newest" => _("Newest"),
- "oldest" => _("Oldest"),
- "mostrecentplay" => _("Most recently played"),
- "leastrecentplay" => _("Least recently played")
- );
+ $this->sortOptions = [
+ 'random' => _('Randomly'),
+ 'newest' => _('Newest'),
+ 'oldest' => _('Oldest'),
+ 'mostrecentplay' => _('Most recently played'),
+ 'leastrecentplay' => _('Least recently played'),
+ ];
}
+
return $this->sortOptions;
}
private function getIsNotOptions()
{
if (!isset($this->isOrNotCriteriaOptions)) {
- $this->isOrNotCriteriaOptions = array(
- "0" => _("Select modifier"),
- "is" => _("is"),
- "is not" => _("is not")
- );
+ $this->isOrNotCriteriaOptions = [
+ '0' => _('Select modifier'),
+ 'is' => _('is'),
+ 'is not' => _('is not'),
+ ];
}
+
return $this->isOrNotCriteriaOptions;
}
@@ -199,11 +208,12 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm
{
if (!isset($this->trackTypeOptions)) {
$tracktypes = Application_Model_Tracktype::getTracktypes();
- $names[] = _("Select Track Type");
- foreach($tracktypes as $arr => $a){
- $names[$a["code"]] = $tracktypes[$arr]["type_name"];
+ $names[] = _('Select Track Type');
+ foreach ($tracktypes as $arr => $a) {
+ $names[$a['code']] = $tracktypes[$arr]['type_name'];
}
}
+
return $names;
}
@@ -211,30 +221,26 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm
{
}
- /*
- * converts UTC timestamp citeria into user timezone strings.
- */
+ // converts UTC timestamp citeria into user timezone strings.
private function convertTimestamps(&$criteria)
{
- $columns = array("utime", "mtime", "lptime");
+ $columns = ['utime', 'mtime', 'lptime'];
- foreach ($columns as $column) {
-
- if (isset($criteria[$column])) {
-
- foreach ($criteria[$column] as &$constraint) {
- // convert to appropriate timezone timestamps only if the modifier is not a relative time
- if (!in_array($constraint['modifier'], array('before','after','between'))) {
+ foreach ($columns as $column) {
+ if (isset($criteria[$column])) {
+ foreach ($criteria[$column] as &$constraint) {
+ // convert to appropriate timezone timestamps only if the modifier is not a relative time
+ if (!in_array($constraint['modifier'], ['before', 'after', 'between'])) {
$constraint['value'] =
Application_Common_DateHelper::UTCStringToUserTimezoneString($constraint['value']);
- if (isset($constraint['extra'])) {
- $constraint['extra'] =
- Application_Common_DateHelper::UTCStringToUserTimezoneString($constraint['extra']);
- }
+ if (isset($constraint['extra'])) {
+ $constraint['extra'] =
+ Application_Common_DateHelper::UTCStringToUserTimezoneString($constraint['extra']);
+ }
}
- }
- }
- }
+ }
+ }
+ }
}
/*
@@ -248,12 +254,11 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm
*
*/
-
public function startForm($p_blockId, $p_isValid = false)
{
// load type
$out = CcBlockQuery::create()->findPk($p_blockId);
- if ($out->getDbType() == "dynamic") {
+ if ($out->getDbType() == 'dynamic') {
$blockType = 0;
} else {
$blockType = 1;
@@ -261,13 +266,13 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm
$spType = new Zend_Form_Element_Radio('sp_type');
$spType->setLabel(_('Type:'))
- ->setDecorators(array('viewHelper'))
- ->setMultiOptions(array(
- 'dynamic' => _('Dynamic'),
- 'static' => _('Static')
-
- ))
- ->setValue($blockType);
+ ->setDecorators(['viewHelper'])
+ ->setMultiOptions([
+ 'dynamic' => _('Dynamic'),
+ 'static' => _('Static'),
+ ])
+ ->setValue($blockType)
+ ;
$this->addElement($spType);
$bl = new Application_Model_Block($p_blockId);
@@ -275,13 +280,13 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm
Logging::info($storedCrit);
//need to convert criteria to be displayed in the user's timezone if there's some timestamp type.
- self::convertTimestamps($storedCrit["crit"]);
+ self::convertTimestamps($storedCrit['crit']);
/* $modRoadMap stores the number of same criteria
* Ex: 3 Album titles, and 2 Track titles
* We need to know this so we display the form elements properly
*/
- $modRowMap = array();
+ $modRowMap = [];
$openSmartBlockOption = false;
if (!empty($storedCrit)) {
@@ -289,9 +294,9 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm
}
// this returns a number indexed array for each criteria found in the database
- $criteriaKeys = array();
- if (isset($storedCrit["crit"])) {
- $criteriaKeys = array_keys($storedCrit["crit"]);
+ $criteriaKeys = [];
+ if (isset($storedCrit['crit'])) {
+ $criteriaKeys = array_keys($storedCrit['crit']);
}
//the way the everything is currently built it setups 25 smartblock criteria forms and then disables them
//but this creates 29 elements
@@ -299,278 +304,278 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm
// loop through once for each potential criteria option ie album, composer, track
// criteria from different groups are separated already by the getCriteriaGrouped call
- for ($i = 0; $i < $numElements; $i++) {
- $criteriaType = "";
+ for ($i = 0; $i < $numElements; ++$i) {
+ $criteriaType = '';
// if there is a criteria found then count the number of rows for this specific criteria ie > 1 track title
// need to refactor this to maintain separation based upon criteria grouping
if (isset($criteriaKeys[$i])) {
//Logging::info($criteriaKeys[$i]);
- Logging::info($storedCrit["crit"][$criteriaKeys[$i]]);
- $critCount = count($storedCrit["crit"][$criteriaKeys[$i]]);
+ Logging::info($storedCrit['crit'][$criteriaKeys[$i]]);
+ $critCount = count($storedCrit['crit'][$criteriaKeys[$i]]);
} else {
$critCount = 1;
}
- // the challenge is that we need to increment the element for a new group
- // within the same criteria but not the reference point i in the array
- // and for these secondary groups they will have a differe$storedCrit["crit"][$criteriaKeys[$i]]nt j reference point
- // store the number of items with the same key in the ModRowMap
- $modRowMap[$i] = $critCount;
+ // the challenge is that we need to increment the element for a new group
+ // within the same criteria but not the reference point i in the array
+ // and for these secondary groups they will have a differe$storedCrit["crit"][$criteriaKeys[$i]]nt j reference point
+ // store the number of items with the same key in the ModRowMap
+ $modRowMap[$i] = $critCount;
- /* Loop through all criteria with the same field
- * Ex: all criteria for 'Album'
- */
- for ($j = 0; $j < $critCount; $j++) {
- /****************** CRITERIA ***********/
- // hide the criteria drop down select on any rows after the first
- if ($j > 0) {
- $invisible = ' sp-invisible';
+ /* Loop through all criteria with the same field
+ * Ex: all criteria for 'Album'
+ */
+ for ($j = 0; $j < $critCount; ++$j) {
+ // CRITERIA
+ // hide the criteria drop down select on any rows after the first
+ if ($j > 0) {
+ $invisible = ' sp-invisible';
+ } else {
+ $invisible = '';
+ }
+
+ $criteria = new Zend_Form_Element_Select('sp_criteria_field_' . $i . '_' . $j);
+ $criteria->setAttrib('class', 'input_select sp_input_select' . $invisible)
+ ->setValue('Select criteria')
+ ->setDecorators(['viewHelper'])
+ ->setMultiOptions($this->getCriteriaOptions())
+ ;
+ // if this isn't the first criteria and there isn't an entry for it already disable it
+ if ($i != 0 && !isset($criteriaKeys[$i])) {
+ $criteria->setAttrib('disabled', 'disabled');
+ }
+ // add the numbering to the form ie the i loop for each specific criteria and
+ // the j loop starts at 0 and grows for each item matching the same criteria
+ // look up the criteria type using the criteriaTypes function from above based upon the criteria value
+ if (isset($criteriaKeys[$i])) {
+ $criteriaType = $this->criteriaTypes[$storedCrit['crit'][$criteriaKeys[$i]][$j]['criteria']];
+ $criteria->setValue($storedCrit['crit'][$criteriaKeys[$i]][$j]['criteria']);
+ }
+ $this->addElement($criteria);
+
+ // MODIFIER
+ // every element has an optional modifier dropdown select
+
+ $criteriaModifers = new Zend_Form_Element_Select('sp_criteria_modifier_' . $i . '_' . $j);
+ $criteriaModifers->setValue('Select modifier')
+ ->setAttrib('class', 'input_select sp_input_select')
+ ->setDecorators(['viewHelper'])
+ ;
+ if ($i != 0 && !isset($criteriaKeys[$i])) {
+ $criteriaModifers->setAttrib('disabled', 'disabled');
+ }
+ // determine the modifier based upon criteria type which is looked up based upon an array
+ if (isset($criteriaKeys[$i])) {
+ if ($criteriaType == 's') {
+ $criteriaModifers->setMultiOptions($this->getStringCriteriaOptions());
+ } elseif ($criteriaType == 'd') {
+ $criteriaModifers->setMultiOptions($this->getDateTimeCriteriaOptions());
+ } elseif ($criteriaType == 'tt') {
+ $criteriaModifers->setMultiOptions($this->getIsNotOptions());
} else {
- $invisible = '';
+ $criteriaModifers->setMultiOptions($this->getNumericCriteriaOptions());
}
+ $criteriaModifers->setValue($storedCrit['crit'][$criteriaKeys[$i]][$j]['modifier']);
+ } else {
+ $criteriaModifers->setMultiOptions(['0' => _('Select modifier')]);
+ }
+ $this->addElement($criteriaModifers);
- $criteria = new Zend_Form_Element_Select("sp_criteria_field_" . $i . "_" . $j);
- $criteria->setAttrib('class', 'input_select sp_input_select' . $invisible)
- ->setValue('Select criteria')
- ->setDecorators(array('viewHelper'))
- ->setMultiOptions($this->getCriteriaOptions());
- // if this isn't the first criteria and there isn't an entry for it already disable it
- if ($i != 0 && !isset($criteriaKeys[$i])) {
- $criteria->setAttrib('disabled', 'disabled');
- }
- // add the numbering to the form ie the i loop for each specific criteria and
- // the j loop starts at 0 and grows for each item matching the same criteria
- // look up the criteria type using the criteriaTypes function from above based upon the criteria value
- if (isset($criteriaKeys[$i])) {
- $criteriaType = $this->criteriaTypes[$storedCrit["crit"][$criteriaKeys[$i]][$j]["criteria"]];
- $criteria->setValue($storedCrit["crit"][$criteriaKeys[$i]][$j]["criteria"]);
- }
- $this->addElement($criteria);
+ // VALUE
+ // The challenge here is that datetime
+ if (isset($criteriaKeys[$i])) {
+ $modifierTest = (string) $storedCrit['crit'][$criteriaKeys[$i]][$j]['modifier'];
+ if (isset($criteriaType) && $criteriaType == 'tt'
+ && preg_match('/is|is not/', $modifierTest) == 1) {
+ $criteriaValue = new Zend_Form_Element_Select('sp_criteria_value_' . $i . '_' . $j);
+ $criteriaValue->setAttrib('class', 'input_select sp_input_select')->setDecorators(['viewHelper']);
-
- /****************** MODIFIER ***********/
- // every element has an optional modifier dropdown select
-
- $criteriaModifers = new Zend_Form_Element_Select("sp_criteria_modifier_" . $i . "_" . $j);
- $criteriaModifers->setValue('Select modifier')
- ->setAttrib('class', 'input_select sp_input_select')
- ->setDecorators(array('viewHelper'));
- if ($i != 0 && !isset($criteriaKeys[$i])) {
- $criteriaModifers->setAttrib('disabled', 'disabled');
- }
- // determine the modifier based upon criteria type which is looked up based upon an array
- if (isset($criteriaKeys[$i])) {
- if ($criteriaType == "s") {
- $criteriaModifers->setMultiOptions($this->getStringCriteriaOptions());
- } elseif ($criteriaType == "d") {
- $criteriaModifers->setMultiOptions($this->getDateTimeCriteriaOptions());
- } elseif ($criteriaType == "tt") {
- $criteriaModifers->setMultiOptions($this->getIsNotOptions());
- } else {
- $criteriaModifers->setMultiOptions($this->getNumericCriteriaOptions());
- }
- $criteriaModifers->setValue($storedCrit["crit"][$criteriaKeys[$i]][$j]["modifier"]);
- } else {
- $criteriaModifers->setMultiOptions(array('0' => _('Select modifier')));
- }
- $this->addElement($criteriaModifers);
-
- /****************** VALUE ***********/
- /* The challenge here is that datetime */
- if (isset($criteriaKeys[$i])) {
- $modifierTest = (string)$storedCrit["crit"][$criteriaKeys[$i]][$j]["modifier"];
- if (isset($criteriaType) && $criteriaType == "tt" &&
- preg_match('/is|is not/', $modifierTest) == 1) {
-
- $criteriaValue = new Zend_Form_Element_Select("sp_criteria_value_" . $i . "_" . $j);
- $criteriaValue->setAttrib('class', 'input_select sp_input_select')->setDecorators(array('viewHelper'));
-
- if (isset($criteriaKeys[$i]) ) { //do if $relativeTT above
- $criteriaValue->setAttrib('enabled', 'enabled');
- } else {
- $criteriaValue->setAttrib('disabled', 'disabled');
- }
- } else {
- $criteriaValue = new Zend_Form_Element_Text("sp_criteria_value_" . $i . "_" . $j);
- $criteriaValue->setAttrib('class', 'input_text sp_input_text')->setDecorators(array('viewHelper'));
- if ($i != 0 && !isset($criteriaKeys[$i])) {
- $criteriaValue->setAttrib('disabled', 'disabled');
- }
- }
- } else {
-
- $criteriaValue = new Zend_Form_Element_Text("sp_criteria_value_" . $i . "_" . $j);
- $criteriaValue->setAttrib('class', 'input_text sp_input_text')->setDecorators(array('viewHelper'));
- if ($i != 0 && !isset($criteriaKeys[$i])) {
- $criteriaValue->setAttrib('disabled', 'disabled');
- }
- }
- if (isset($criteriaKeys[$i])) {
- /*
- * Need to parse relative dates in a special way to populate select box down below
- */
- // this is used below to test whether the datetime select should be shown or hidden
- $relativeDateTime = false;
- $modifierTest = (string)$storedCrit["crit"][$criteriaKeys[$i]][$j]["modifier"];
- if (isset($criteriaType) && $criteriaType == "d" &&
- preg_match('/before|after|between/', $modifierTest) == 1) {
- // set relativeDatetime boolean to true so that the datetime select is displayed below
- $relativeDateTime = true;
- $criteriaValue->setValue(filter_var($storedCrit["crit"][$criteriaKeys[$i]][$j]["value"], FILTER_SANITIZE_NUMBER_INT));
- } elseif (isset($criteriaType) && $criteriaType == "tt" &&
- preg_match('/is|is not/', $modifierTest) == 1) {
- // set relativeDatetime boolean to true so that the datetime select is displayed below
- $relativeDateTime = false;
-
- $tracktypeSelectValue = preg_replace('/[0-9]+/', '', $storedCrit["crit"][$criteriaKeys[$i]][$j]["value"]);
- $tracktypeSelectValue = trim(preg_replace('/\W\w+\s*(\W*)$/', '$1', $tracktypeSelectValue));
- $criteriaValue->setMultiOptions($this->getTracktypeOptions());
-
- if ($storedCrit["crit"][$criteriaKeys[$i]][$j]["value"]){
- $criteriaValue->setValue($storedCrit["crit"][$criteriaKeys[$i]][$j]["value"]);
- } else {
- $criteriaValue->setMultiOptions(array('0' => _('Select track type')));
- $criteriaValue->setMultiOptions($this->getTracktypeOptions());
- $criteriaValue->setValue($tracktypeSelectValue);
- }
+ if (isset($criteriaKeys[$i])) { //do if $relativeTT above
$criteriaValue->setAttrib('enabled', 'enabled');
} else {
- $criteriaValue->setValue($storedCrit["crit"][$criteriaKeys[$i]][$j]["value"]);
+ $criteriaValue->setAttrib('disabled', 'disabled');
+ }
+ } else {
+ $criteriaValue = new Zend_Form_Element_Text('sp_criteria_value_' . $i . '_' . $j);
+ $criteriaValue->setAttrib('class', 'input_text sp_input_text')->setDecorators(['viewHelper']);
+ if ($i != 0 && !isset($criteriaKeys[$i])) {
+ $criteriaValue->setAttrib('disabled', 'disabled');
}
}
- $this->addElement($criteriaValue);
-
-
- /****************** DATETIME SELECT *************/
- $criteriaDatetimeSelect = new Zend_Form_Element_Select("sp_criteria_datetime_select_" . $i . "_" . $j);
- $criteriaDatetimeSelect->setAttrib('class', 'input_select sp_input_select')
- ->setDecorators(array('viewHelper'));
- if (isset($criteriaKeys[$i]) && $relativeDateTime) {
- $criteriaDatetimeSelect->setAttrib('enabled', 'enabled');
- } else {
- $criteriaDatetimeSelect->setAttrib('disabled', 'disabled');
+ } else {
+ $criteriaValue = new Zend_Form_Element_Text('sp_criteria_value_' . $i . '_' . $j);
+ $criteriaValue->setAttrib('class', 'input_text sp_input_text')->setDecorators(['viewHelper']);
+ if ($i != 0 && !isset($criteriaKeys[$i])) {
+ $criteriaValue->setAttrib('disabled', 'disabled');
}
- // check if the value is stored and it is a relative datetime field
- if (isset($criteriaKeys[$i]) && isset($storedCrit["crit"][$criteriaKeys[$i]][$j]["value"])
- && isset($criteriaType) && $criteriaType == "d" &&
- preg_match('/before|after|between/', $modifierTest) == 1) {
- // need to remove any leading numbers stored in the database
- $dateTimeSelectValue = preg_replace('/[0-9]+/', '', $storedCrit["crit"][$criteriaKeys[$i]][$j]["value"]);
- // need to strip white from front and ago from the end to match with the value of the time unit select dropdown
- $dateTimeSelectValue = trim(preg_replace('/\W\w+\s*(\W*)$/', '$1', $dateTimeSelectValue));
- $criteriaDatetimeSelect->setMultiOptions($this->getTimePeriodCriteriaOptions());
- $criteriaDatetimeSelect->setValue($dateTimeSelectValue);
- $criteriaDatetimeSelect->setAttrib('enabled', 'enabled');
- } else {
- $criteriaDatetimeSelect->setMultiOptions(array('0' => _('Select unit of time')));
- $criteriaDatetimeSelect->setMultiOptions($this->getTimePeriodCriteriaOptions());
+ }
+ if (isset($criteriaKeys[$i])) {
+ // Need to parse relative dates in a special way to populate select box down below
+ // this is used below to test whether the datetime select should be shown or hidden
+ $relativeDateTime = false;
+ $modifierTest = (string) $storedCrit['crit'][$criteriaKeys[$i]][$j]['modifier'];
+ if (isset($criteriaType) && $criteriaType == 'd'
+ && preg_match('/before|after|between/', $modifierTest) == 1) {
+ // set relativeDatetime boolean to true so that the datetime select is displayed below
+ $relativeDateTime = true;
+ $criteriaValue->setValue(filter_var($storedCrit['crit'][$criteriaKeys[$i]][$j]['value'], FILTER_SANITIZE_NUMBER_INT));
+ } elseif (isset($criteriaType) && $criteriaType == 'tt'
+ && preg_match('/is|is not/', $modifierTest) == 1) {
+ // set relativeDatetime boolean to true so that the datetime select is displayed below
+ $relativeDateTime = false;
- }
+ $tracktypeSelectValue = preg_replace('/[0-9]+/', '', $storedCrit['crit'][$criteriaKeys[$i]][$j]['value']);
+ $tracktypeSelectValue = trim(preg_replace('/\W\w+\s*(\W*)$/', '$1', $tracktypeSelectValue));
+ $criteriaValue->setMultiOptions($this->getTracktypeOptions());
- $this->addElement($criteriaDatetimeSelect);
-
- /****************** EXTRA ***********/
- $criteriaExtra = new Zend_Form_Element_Text("sp_criteria_extra_" . $i . "_" . $j);
- $criteriaExtra->setAttrib('class', 'input_text sp_extra_input_text')
- ->setDecorators(array('viewHelper'));
- if (isset($criteriaKeys[$i]) && isset($storedCrit["crit"][$criteriaKeys[$i]][$j]["extra"])) {
- // need to check if this is a relative date time value
- if (isset($criteriaType) && $criteriaType == "d" && $modifierTest == 'between') {
- // the criteria value will be a number followed by time unit and ago so set input to number part
- $criteriaExtra->setValue(filter_var($storedCrit["crit"][$criteriaKeys[$i]][$j]["extra"], FILTER_SANITIZE_NUMBER_INT));
+ if ($storedCrit['crit'][$criteriaKeys[$i]][$j]['value']) {
+ $criteriaValue->setValue($storedCrit['crit'][$criteriaKeys[$i]][$j]['value']);
} else {
- $criteriaExtra->setValue($storedCrit["crit"][$criteriaKeys[$i]][$j]["extra"]);
+ $criteriaValue->setMultiOptions(['0' => _('Select track type')]);
+ $criteriaValue->setMultiOptions($this->getTracktypeOptions());
+ $criteriaValue->setValue($tracktypeSelectValue);
}
- $criteriaValue->setAttrib('class', 'input_text sp_extra_input_text');
+ $criteriaValue->setAttrib('enabled', 'enabled');
} else {
- $criteriaExtra->setAttrib('disabled', 'disabled');
+ $criteriaValue->setValue($storedCrit['crit'][$criteriaKeys[$i]][$j]['value']);
}
- $this->addElement($criteriaExtra);
- /****************** DATETIME SELECT EXTRA **********/
+ }
+ $this->addElement($criteriaValue);
- $criteriaExtraDatetimeSelect = new Zend_Form_Element_Select("sp_criteria_extra_datetime_select_" . $i . "_" . $j);
- $criteriaExtraDatetimeSelect->setAttrib('class', 'input_select sp_input_select')
- ->setDecorators(array('viewHelper'));
+ // DATETIME SELECT
+ $criteriaDatetimeSelect = new Zend_Form_Element_Select('sp_criteria_datetime_select_' . $i . '_' . $j);
+ $criteriaDatetimeSelect->setAttrib('class', 'input_select sp_input_select')
+ ->setDecorators(['viewHelper'])
+ ;
+ if (isset($criteriaKeys[$i]) && $relativeDateTime) {
+ $criteriaDatetimeSelect->setAttrib('enabled', 'enabled');
+ } else {
+ $criteriaDatetimeSelect->setAttrib('disabled', 'disabled');
+ }
+ // check if the value is stored and it is a relative datetime field
+ if (isset($criteriaKeys[$i], $storedCrit['crit'][$criteriaKeys[$i]][$j]['value'], $criteriaType)
+ && $criteriaType == 'd'
+ && preg_match('/before|after|between/', $modifierTest) == 1) {
+ // need to remove any leading numbers stored in the database
+ $dateTimeSelectValue = preg_replace('/[0-9]+/', '', $storedCrit['crit'][$criteriaKeys[$i]][$j]['value']);
+ // need to strip white from front and ago from the end to match with the value of the time unit select dropdown
+ $dateTimeSelectValue = trim(preg_replace('/\W\w+\s*(\W*)$/', '$1', $dateTimeSelectValue));
+ $criteriaDatetimeSelect->setMultiOptions($this->getTimePeriodCriteriaOptions());
+ $criteriaDatetimeSelect->setValue($dateTimeSelectValue);
+ $criteriaDatetimeSelect->setAttrib('enabled', 'enabled');
+ } else {
+ $criteriaDatetimeSelect->setMultiOptions(['0' => _('Select unit of time')]);
+ $criteriaDatetimeSelect->setMultiOptions($this->getTimePeriodCriteriaOptions());
+ }
- if (isset($criteriaKeys[$i]) && isset($storedCrit["crit"][$criteriaKeys[$i]][$j]["extra"])
+ $this->addElement($criteriaDatetimeSelect);
+
+ // EXTRA
+ $criteriaExtra = new Zend_Form_Element_Text('sp_criteria_extra_' . $i . '_' . $j);
+ $criteriaExtra->setAttrib('class', 'input_text sp_extra_input_text')
+ ->setDecorators(['viewHelper'])
+ ;
+ if (isset($criteriaKeys[$i], $storedCrit['crit'][$criteriaKeys[$i]][$j]['extra'])) {
+ // need to check if this is a relative date time value
+ if (isset($criteriaType) && $criteriaType == 'd' && $modifierTest == 'between') {
+ // the criteria value will be a number followed by time unit and ago so set input to number part
+ $criteriaExtra->setValue(filter_var($storedCrit['crit'][$criteriaKeys[$i]][$j]['extra'], FILTER_SANITIZE_NUMBER_INT));
+ } else {
+ $criteriaExtra->setValue($storedCrit['crit'][$criteriaKeys[$i]][$j]['extra']);
+ }
+ $criteriaValue->setAttrib('class', 'input_text sp_extra_input_text');
+ } else {
+ $criteriaExtra->setAttrib('disabled', 'disabled');
+ }
+ $this->addElement($criteriaExtra);
+ // DATETIME SELECT EXTRA
+
+ $criteriaExtraDatetimeSelect = new Zend_Form_Element_Select('sp_criteria_extra_datetime_select_' . $i . '_' . $j);
+ $criteriaExtraDatetimeSelect->setAttrib('class', 'input_select sp_input_select')
+ ->setDecorators(['viewHelper'])
+ ;
+
+ if (isset($criteriaKeys[$i], $storedCrit['crit'][$criteriaKeys[$i]][$j]['extra'])
&& $modifierTest == 'between') {
- // need to remove the leading numbers stored in the database
- $extraDateTimeSelectValue = preg_replace('/[0-9]+/', '', $storedCrit["crit"][$criteriaKeys[$i]][$j]["extra"]);
- // need to strip white from front and ago from the end to match with the value of the time unit select dropdown
- $extraDateTimeSelectValue = trim(preg_replace('/\W\w+\s*(\W*)$/', '$1', $extraDateTimeSelectValue));
- $criteriaExtraDatetimeSelect->setMultiOptions($this->getTimePeriodCriteriaOptions());
- // Logging::info('THIS IS-'.$extraDateTimeSelectValue.'-IT');
- $criteriaExtraDatetimeSelect->setValue($extraDateTimeSelectValue);
- $criteriaExtraDatetimeSelect->setAttrib('enabled', 'enabled');
-
- } else {
- $criteriaExtraDatetimeSelect->setMultiOptions(array('0' => _('Select unit of time')));
- $criteriaExtraDatetimeSelect->setMultiOptions($this->getTimePeriodCriteriaOptions());
- $criteriaExtraDatetimeSelect->setAttrib('disabled', 'disabled');
- }
- $this->addElement($criteriaExtraDatetimeSelect);
- }//for
+ // need to remove the leading numbers stored in the database
+ $extraDateTimeSelectValue = preg_replace('/[0-9]+/', '', $storedCrit['crit'][$criteriaKeys[$i]][$j]['extra']);
+ // need to strip white from front and ago from the end to match with the value of the time unit select dropdown
+ $extraDateTimeSelectValue = trim(preg_replace('/\W\w+\s*(\W*)$/', '$1', $extraDateTimeSelectValue));
+ $criteriaExtraDatetimeSelect->setMultiOptions($this->getTimePeriodCriteriaOptions());
+ // Logging::info('THIS IS-'.$extraDateTimeSelectValue.'-IT');
+ $criteriaExtraDatetimeSelect->setValue($extraDateTimeSelectValue);
+ $criteriaExtraDatetimeSelect->setAttrib('enabled', 'enabled');
+ } else {
+ $criteriaExtraDatetimeSelect->setMultiOptions(['0' => _('Select unit of time')]);
+ $criteriaExtraDatetimeSelect->setMultiOptions($this->getTimePeriodCriteriaOptions());
+ $criteriaExtraDatetimeSelect->setAttrib('disabled', 'disabled');
+ }
+ $this->addElement($criteriaExtraDatetimeSelect);
+ }//for
}//for
$repeatTracks = new Zend_Form_Element_Checkbox('sp_repeat_tracks');
- $repeatTracks->setDecorators(array('viewHelper'))
- ->setLabel(_('Allow Repeated Tracks:'));
- if (isset($storedCrit["repeat_tracks"])) {
- $repeatTracks->setChecked($storedCrit["repeat_tracks"]["value"] == 1?true:false);
+ $repeatTracks->setDecorators(['viewHelper'])
+ ->setLabel(_('Allow Repeated Tracks:'))
+ ;
+ if (isset($storedCrit['repeat_tracks'])) {
+ $repeatTracks->setChecked($storedCrit['repeat_tracks']['value'] == 1 ? true : false);
}
$this->addElement($repeatTracks);
$overflowTracks = new Zend_Form_Element_Checkbox('sp_overflow_tracks');
- $overflowTracks->setDecorators(array('viewHelper'))
- ->setLabel(_('Allow last track to exceed time limit:'));
- if (isset($storedCrit["overflow_tracks"])) {
- $overflowTracks->setChecked($storedCrit["overflow_tracks"]["value"] == 1);
+ $overflowTracks->setDecorators(['viewHelper'])
+ ->setLabel(_('Allow last track to exceed time limit:'))
+ ;
+ if (isset($storedCrit['overflow_tracks'])) {
+ $overflowTracks->setChecked($storedCrit['overflow_tracks']['value'] == 1);
}
$this->addElement($overflowTracks);
$sort = new Zend_Form_Element_Select('sp_sort_options');
$sort->setAttrib('class', 'sp_input_select')
- ->setDecorators(array('viewHelper'))
- ->setLabel(_("Sort Tracks:"))
- ->setMultiOptions($this->getSortOptions());
- if (isset($storedCrit["sort"])) {
- $sort->setValue($storedCrit["sort"]["value"]);
+ ->setDecorators(['viewHelper'])
+ ->setLabel(_('Sort Tracks:'))
+ ->setMultiOptions($this->getSortOptions())
+ ;
+ if (isset($storedCrit['sort'])) {
+ $sort->setValue($storedCrit['sort']['value']);
}
$this->addElement($sort);
$limit = new Zend_Form_Element_Select('sp_limit_options');
$limit->setAttrib('class', 'sp_input_select')
- ->setDecorators(array('viewHelper'))
- ->setMultiOptions($this->getLimitOptions());
- if (isset($storedCrit["limit"])) {
- $limit->setValue($storedCrit["limit"]["modifier"]);
+ ->setDecorators(['viewHelper'])
+ ->setMultiOptions($this->getLimitOptions())
+ ;
+ if (isset($storedCrit['limit'])) {
+ $limit->setValue($storedCrit['limit']['modifier']);
}
$this->addElement($limit);
$limitValue = new Zend_Form_Element_Text('sp_limit_value');
$limitValue->setAttrib('class', 'sp_input_text_limit')
- ->setLabel(_('Limit to:'))
- ->setDecorators(array('viewHelper'));
+ ->setLabel(_('Limit to:'))
+ ->setDecorators(['viewHelper'])
+ ;
$this->addElement($limitValue);
- if (isset($storedCrit["limit"])) {
- $limitValue->setValue($storedCrit["limit"]["value"]);
+ if (isset($storedCrit['limit'])) {
+ $limitValue->setValue($storedCrit['limit']['value']);
} else {
// setting default to 1 hour
$limitValue->setValue(1);
}
-
$generate = new Zend_Form_Element_Button('generate_button');
$generate->setAttrib('class', 'sp-button btn');
$generate->setAttrib('title', _('Generate playlist content and save criteria'));
$generate->setIgnore(true);
if ($blockType == 0) {
$generate->setLabel(_('Preview'));
- }
- else {
+ } else {
$generate->setLabel(_('Generate'));
}
- $generate->setDecorators(array('viewHelper'));
+ $generate->setDecorators(['viewHelper']);
$this->addElement($generate);
$shuffle = new Zend_Form_Element_Button('shuffle_button');
@@ -578,19 +583,19 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm
$shuffle->setAttrib('title', _('Shuffle playlist content'));
$shuffle->setIgnore(true);
$shuffle->setLabel(_('Shuffle'));
- $shuffle->setDecorators(array('viewHelper'));
+ $shuffle->setDecorators(['viewHelper']);
$this->addElement($shuffle);
- $this->setDecorators(array(
- array('ViewScript', array('viewScript' => 'form/smart-block-criteria.phtml', "openOption"=> $openSmartBlockOption,
- 'criteriasLength' => $numElements, 'modRowMap' => $modRowMap))
- ));
+ $this->setDecorators([
+ ['ViewScript', ['viewScript' => 'form/smart-block-criteria.phtml', 'openOption' => $openSmartBlockOption,
+ 'criteriasLength' => $numElements, 'modRowMap' => $modRowMap, ]],
+ ]);
}
- /*
- * This is a simple function that determines if a modValue should enable a datetime
- */
- public function enableDateTimeUnit($modValue) {
- return (preg_match('/before|after|between/', $modValue) == 1);
+
+ // This is a simple function that determines if a modValue should enable a datetime
+ public function enableDateTimeUnit($modValue)
+ {
+ return preg_match('/before|after|between/', $modValue) == 1;
}
public function preValidation($params)
@@ -598,120 +603,120 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm
$data = Application_Model_Block::organizeSmartPlaylistCriteria($params['data']);
// add elements that needs to be added
// set multioption for modifier according to criteria_field
- $modRowMap = array();
+ $modRowMap = [];
if (!isset($data['criteria'])) {
return $data;
}
- foreach ($data['criteria'] as $critKey=>$d) {
+ foreach ($data['criteria'] as $critKey => $d) {
$count = 1;
- foreach ($d as $modKey=>$modInfo) {
+ foreach ($d as $modKey => $modInfo) {
if ($modKey == 0) {
- $eleCrit = $this->getElement("sp_criteria_field_".$critKey."_".$modKey);
+ $eleCrit = $this->getElement('sp_criteria_field_' . $critKey . '_' . $modKey);
$eleCrit->setValue($this->getCriteriaOptions($modInfo['sp_criteria_field']));
- $eleCrit->setAttrib("disabled", null);
+ $eleCrit->setAttrib('disabled', null);
- $eleMod = $this->getElement("sp_criteria_modifier_".$critKey."_".$modKey);
+ $eleMod = $this->getElement('sp_criteria_modifier_' . $critKey . '_' . $modKey);
$criteriaType = $this->criteriaTypes[$modInfo['sp_criteria_field']];
- if ($criteriaType == "s") {
+ if ($criteriaType == 's') {
$eleMod->setMultiOptions($this->getStringCriteriaOptions());
- } elseif ($criteriaType == "n") {
+ } elseif ($criteriaType == 'n') {
$eleMod->setMultiOptions($this->getNumericCriteriaOptions());
- } elseif ($criteriaType == "d") {
+ } elseif ($criteriaType == 'd') {
$eleMod->setMultiOptions($this->getDateTimeCriteriaOptions());
- } elseif ($criteriaType == "tt") {
+ } elseif ($criteriaType == 'tt') {
$eleMod->setMultiOptions($this->getIsNotOptions());
} else {
- $eleMod->setMultiOptions(array('0' => _('Select modifier')));
+ $eleMod->setMultiOptions(['0' => _('Select modifier')]);
}
$eleMod->setValue($modInfo['sp_criteria_modifier']);
- $eleMod->setAttrib("disabled", null);
+ $eleMod->setAttrib('disabled', null);
- $eleDatetime = $this->getElement("sp_criteria_datetime_select_".$critKey."_".$modKey);
+ $eleDatetime = $this->getElement('sp_criteria_datetime_select_' . $critKey . '_' . $modKey);
if ($this->enableDateTimeUnit($eleMod->getValue())) {
- $eleDatetime->setAttrib("enabled", "enabled");
+ $eleDatetime->setAttrib('enabled', 'enabled');
$eleDatetime->setValue($modInfo['sp_criteria_datetime_select']);
- $eleDatetime->setAttrib("disabled", null);
+ $eleDatetime->setAttrib('disabled', null);
+ } else {
+ $eleDatetime->setAttrib('disabled', 'disabled');
}
- else {
- $eleDatetime->setAttrib("disabled","disabled");
- }
- $eleValue = $this->getElement("sp_criteria_value_".$critKey."_".$modKey);
+ $eleValue = $this->getElement('sp_criteria_value_' . $critKey . '_' . $modKey);
$eleValue->setValue($modInfo['sp_criteria_value']);
- $eleValue->setAttrib("disabled", null);
+ $eleValue->setAttrib('disabled', null);
if (isset($modInfo['sp_criteria_extra'])) {
- $eleExtra = $this->getElement("sp_criteria_extra_".$critKey."_".$modKey);
+ $eleExtra = $this->getElement('sp_criteria_extra_' . $critKey . '_' . $modKey);
$eleExtra->setValue($modInfo['sp_criteria_extra']);
$eleValue->setAttrib('class', 'input_text sp_extra_input_text');
- $eleExtra->setAttrib("disabled", null);
+ $eleExtra->setAttrib('disabled', null);
}
- $eleExtraDatetime = $this->getElement("sp_criteria_extra_datetime_select_".$critKey."_".$modKey);
+ $eleExtraDatetime = $this->getElement('sp_criteria_extra_datetime_select_' . $critKey . '_' . $modKey);
if ($eleMod->getValue() == 'between') {
- $eleExtraDatetime->setAttrib("enabled", "enabled");
+ $eleExtraDatetime->setAttrib('enabled', 'enabled');
$eleExtraDatetime->setValue($modInfo['sp_criteria_extra_datetime_select']);
- $eleExtraDatetime->setAttrib("disabled", null);
+ $eleExtraDatetime->setAttrib('disabled', null);
+ } else {
+ $eleExtraDatetime->setAttrib('disabled', 'disabled');
}
- else {
- $eleExtraDatetime->setAttrib("disabled","disabled");
- }
-
} else {
- $criteria = new Zend_Form_Element_Select("sp_criteria_field_".$critKey."_".$modKey);
+ $criteria = new Zend_Form_Element_Select('sp_criteria_field_' . $critKey . '_' . $modKey);
$criteria->setAttrib('class', 'input_select sp_input_select sp-invisible')
- ->setValue('Select criteria')
- ->setDecorators(array('viewHelper'))
- ->setMultiOptions($this->getCriteriaOptions());
+ ->setValue('Select criteria')
+ ->setDecorators(['viewHelper'])
+ ->setMultiOptions($this->getCriteriaOptions())
+ ;
$criteriaType = $this->criteriaTypes[$modInfo['sp_criteria_field']];
$criteria->setValue($this->getCriteriaOptions($modInfo['sp_criteria_field']));
$this->addElement($criteria);
- /****************** MODIFIER ***********/
- $criteriaModifers = new Zend_Form_Element_Select("sp_criteria_modifier_".$critKey."_".$modKey);
+ // MODIFIER
+ $criteriaModifers = new Zend_Form_Element_Select('sp_criteria_modifier_' . $critKey . '_' . $modKey);
$criteriaModifers->setValue('Select modifier')
- ->setAttrib('class', 'input_select sp_input_select')
- ->setDecorators(array('viewHelper'));
+ ->setAttrib('class', 'input_select sp_input_select')
+ ->setDecorators(['viewHelper'])
+ ;
- if ($criteriaType == "s") {
+ if ($criteriaType == 's') {
$criteriaModifers->setMultiOptions($this->getStringCriteriaOptions());
- } elseif ($criteriaType == "n") {
+ } elseif ($criteriaType == 'n') {
$criteriaModifers->setMultiOptions($this->getNumericCriteriaOptions());
- }
- elseif ($criteriaType == "d") {
- $criteriaModifers->setMultiOptions($this->getDateTimeCriteriaOptions());
- } elseif ($criteriaType == "tt") {
+ } elseif ($criteriaType == 'd') {
+ $criteriaModifers->setMultiOptions($this->getDateTimeCriteriaOptions());
+ } elseif ($criteriaType == 'tt') {
$criteriaModifers->setMultiOptions($this->getIsNotOptions());
} else {
- $criteriaModifers->setMultiOptions(array('0' => _('Select modifier')));
+ $criteriaModifers->setMultiOptions(['0' => _('Select modifier')]);
}
$criteriaModifers->setValue($modInfo['sp_criteria_modifier']);
$this->addElement($criteriaModifers);
- /****************** VALUE ***********/
- $criteriaValue = new Zend_Form_Element_Text("sp_criteria_value_".$critKey."_".$modKey);
+ // VALUE
+ $criteriaValue = new Zend_Form_Element_Text('sp_criteria_value_' . $critKey . '_' . $modKey);
$criteriaValue->setAttrib('class', 'input_text sp_input_text')
- ->setDecorators(array('viewHelper'));
+ ->setDecorators(['viewHelper'])
+ ;
$criteriaValue->setValue($modInfo['sp_criteria_value']);
$this->addElement($criteriaValue);
- /****************** DATETIME UNIT SELECT ***********/
+ // DATETIME UNIT SELECT
- $criteriaDatetimeSelect = new Zend_Form_Element_Select("sp_criteria_datetime_select_".$critKey."_".$modKey);
- $criteriaDatetimeSelect->setAttrib('class','input_select sp_input_select')
- ->setDecorators(array('viewHelper'));
+ $criteriaDatetimeSelect = new Zend_Form_Element_Select('sp_criteria_datetime_select_' . $critKey . '_' . $modKey);
+ $criteriaDatetimeSelect->setAttrib('class', 'input_select sp_input_select')
+ ->setDecorators(['viewHelper'])
+ ;
if ($this->enableDateTimeUnit($criteriaValue->getValue())) {
$criteriaDatetimeSelect->setAttrib('enabled', 'enabled');
$criteriaDatetimeSelect->setAttrib('disabled', null);
$criteriaDatetimeSelect->setValue($modInfo['sp_criteria_datetime_select']);
$this->addElement($criteriaDatetimeSelect);
- }
- else {
+ } else {
$criteriaDatetimeSelect->setAttrib('disabled', 'disabled');
}
- /****************** EXTRA ***********/
- $criteriaExtra = new Zend_Form_Element_Text("sp_criteria_extra_".$critKey."_".$modKey);
+ // EXTRA
+ $criteriaExtra = new Zend_Form_Element_Text('sp_criteria_extra_' . $critKey . '_' . $modKey);
$criteriaExtra->setAttrib('class', 'input_text sp_extra_input_text')
- ->setDecorators(array('viewHelper'));
+ ->setDecorators(['viewHelper'])
+ ;
if (isset($modInfo['sp_criteria_extra'])) {
$criteriaExtra->setValue($modInfo['sp_criteria_extra']);
$criteriaValue->setAttrib('class', 'input_text sp_extra_input_text');
@@ -720,35 +725,35 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm
}
$this->addElement($criteriaExtra);
- /****************** EXTRA DATETIME UNIT SELECT ***********/
+ // EXTRA DATETIME UNIT SELECT
- $criteriaExtraDatetimeSelect = new Zend_Form_Element_Select("sp_criteria_extra_datetime_select_".$critKey."_".$modKey);
- $criteriaExtraDatetimeSelect->setAttrib('class','input_select sp_input_select')
- ->setDecorators(array('viewHelper'));
+ $criteriaExtraDatetimeSelect = new Zend_Form_Element_Select('sp_criteria_extra_datetime_select_' . $critKey . '_' . $modKey);
+ $criteriaExtraDatetimeSelect->setAttrib('class', 'input_select sp_input_select')
+ ->setDecorators(['viewHelper'])
+ ;
if ($criteriaValue->getValue() == 'between') {
$criteriaExtraDatetimeSelect->setAttrib('enabled', 'enabled');
$criteriaExtraDatetimeSelect->setAttrib('disabled', null);
$criteriaExtraDatetimeSelect->setValue($modInfo['sp_criteria_extra_datetime_select']);
$this->addElement($criteriaExtraDatetimeSelect);
- }
- else {
+ } else {
$criteriaExtraDatetimeSelect->setAttrib('disabled', 'disabled');
}
- $count++;
+ ++$count;
}
}
$modRowMap[$critKey] = $count;
}
- $decorator = $this->getDecorator("ViewScript");
- $existingModRow = $decorator->getOption("modRowMap");
- foreach ($modRowMap as $key=>$v) {
+ $decorator = $this->getDecorator('ViewScript');
+ $existingModRow = $decorator->getOption('modRowMap');
+ foreach ($modRowMap as $key => $v) {
$existingModRow[$key] = $v;
}
- $decorator->setOption("modRowMap", $existingModRow);
+ $decorator->setOption('modRowMap', $existingModRow);
// reconstruct the params['criteria'] so we can populate the form
- $formData = array();
+ $formData = [];
foreach ($params['data'] as $ele) {
$formData[$ele['name']] = $ele['value'];
}
@@ -763,38 +768,38 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm
{
$isValid = true;
$data = $this->preValidation($params);
- $criteria2PeerMap = array(
- 0 => "Select criteria",
- "album_title" => "DbAlbumTitle",
- "artist_name" => "DbArtistName",
- "bit_rate" => "DbBitRate",
- "bpm" => "DbBpm",
- "composer" => "DbComposer",
- "conductor" => "DbConductor",
- "copyright" => "DbCopyright",
- "cuein" => "DbCuein",
- "cueout" => "DbCueout",
- "description" => "DbDescription",
- "encoded_by" => "DbEncodedBy",
- "utime" => "DbUtime",
- "mtime" => "DbMtime",
- "lptime" => "DbLPtime",
- "genre" => "DbGenre",
- "info_url" => "DbInfoUrl",
- "isrc_number" => "DbIsrcNumber",
- "label" => "DbLabel",
- "language" => "DbLanguage",
- "length" => "DbLength",
- "mime" => "DbMime",
- "mood" => "DbMood",
- "owner_id" => "DbOwnerId",
- "replay_gain" => "DbReplayGain",
- "sample_rate" => "DbSampleRate",
- "track_title" => "DbTrackTitle",
- "track_number" => "DbTrackNumber",
- "year" => "DbYear",
- "track_type" => "DbTrackType"
- );
+ $criteria2PeerMap = [
+ 0 => 'Select criteria',
+ 'album_title' => 'DbAlbumTitle',
+ 'artist_name' => 'DbArtistName',
+ 'bit_rate' => 'DbBitRate',
+ 'bpm' => 'DbBpm',
+ 'composer' => 'DbComposer',
+ 'conductor' => 'DbConductor',
+ 'copyright' => 'DbCopyright',
+ 'cuein' => 'DbCuein',
+ 'cueout' => 'DbCueout',
+ 'description' => 'DbDescription',
+ 'encoded_by' => 'DbEncodedBy',
+ 'utime' => 'DbUtime',
+ 'mtime' => 'DbMtime',
+ 'lptime' => 'DbLPtime',
+ 'genre' => 'DbGenre',
+ 'info_url' => 'DbInfoUrl',
+ 'isrc_number' => 'DbIsrcNumber',
+ 'label' => 'DbLabel',
+ 'language' => 'DbLanguage',
+ 'length' => 'DbLength',
+ 'mime' => 'DbMime',
+ 'mood' => 'DbMood',
+ 'owner_id' => 'DbOwnerId',
+ 'replay_gain' => 'DbReplayGain',
+ 'sample_rate' => 'DbSampleRate',
+ 'track_title' => 'DbTrackTitle',
+ 'track_number' => 'DbTrackNumber',
+ 'year' => 'DbYear',
+ 'track_type' => 'DbTrackType',
+ ];
// things we need to check
// 1. limit value shouldn't be empty and has upperbound of 24 hrs
@@ -808,43 +813,43 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm
$multiplier = 60;
}
if ($data['etc']['sp_limit_options'] == 'hours' || $data['etc']['sp_limit_options'] == 'mins') {
- $element = $this->getElement("sp_limit_value");
- if ($data['etc']['sp_limit_value'] == "" || floatval($data['etc']['sp_limit_value']) <= 0) {
- $element->addError(_("Limit cannot be empty or smaller than 0"));
+ $element = $this->getElement('sp_limit_value');
+ if ($data['etc']['sp_limit_value'] == '' || floatval($data['etc']['sp_limit_value']) <= 0) {
+ $element->addError(_('Limit cannot be empty or smaller than 0'));
$isValid = false;
} else {
$mins = floatval($data['etc']['sp_limit_value']) * $multiplier;
if ($mins > 1440) {
- $element->addError(_("Limit cannot be more than 24 hrs"));
+ $element->addError(_('Limit cannot be more than 24 hrs'));
$isValid = false;
}
}
} else {
- $element = $this->getElement("sp_limit_value");
- if ($data['etc']['sp_limit_value'] == "" || floatval($data['etc']['sp_limit_value']) <= 0) {
- $element->addError(_("Limit cannot be empty or smaller than 0"));
+ $element = $this->getElement('sp_limit_value');
+ if ($data['etc']['sp_limit_value'] == '' || floatval($data['etc']['sp_limit_value']) <= 0) {
+ $element->addError(_('Limit cannot be empty or smaller than 0'));
$isValid = false;
} elseif (!ctype_digit($data['etc']['sp_limit_value'])) {
- $element->addError(_("The value should be an integer"));
+ $element->addError(_('The value should be an integer'));
$isValid = false;
} elseif (intval($data['etc']['sp_limit_value']) > 500) {
- $element->addError(_("500 is the max item limit value you can set"));
+ $element->addError(_('500 is the max item limit value you can set'));
$isValid = false;
}
}
if (isset($data['criteria'])) {
- foreach ($data['criteria'] as $rowKey=>$row) {
- foreach ($row as $key=>$d) {
- $element = $this->getElement("sp_criteria_field_".$rowKey."_".$key);
+ foreach ($data['criteria'] as $rowKey => $row) {
+ foreach ($row as $key => $d) {
+ $element = $this->getElement('sp_criteria_field_' . $rowKey . '_' . $key);
// check for not selected select box
- if ($d['sp_criteria_field'] == "0" || $d['sp_criteria_modifier'] == "0") {
- $element->addError(_("You must select Criteria and Modifier"));
+ if ($d['sp_criteria_field'] == '0' || $d['sp_criteria_modifier'] == '0') {
+ $element->addError(_('You must select Criteria and Modifier'));
$isValid = false;
} else {
$column = CcFilesPeer::getTableMap()->getColumnByPhpName($criteria2PeerMap[$d['sp_criteria_field']]);
// validation on type of column
- if (in_array($d['sp_criteria_field'], array('length', 'cuein', 'cueout'))) {
+ if (in_array($d['sp_criteria_field'], ['length', 'cuein', 'cueout'])) {
if (!preg_match("/^(\d{2}):(\d{2}):(\d{2})/", $d['sp_criteria_value'])) {
$element->addError(_("'Length' should be in '00:00:00' format"));
$isValid = false;
@@ -852,26 +857,25 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm
// this looks up the column type for the criteria the modified time, upload time etc.
} elseif ($column->getType() == PropelColumnTypes::TIMESTAMP) {
// need to check for relative modifiers first - bypassing currently
- if (in_array($d['sp_criteria_modifier'], array('before','after','between'))) {
- if (!preg_match("/^[1-9][0-9]*$|0/",$d['sp_criteria_value'])) {
- $element->addError(_("Only non-negative integer numbers are allowed (e.g 1 or 5) for the text value"));
+ if (in_array($d['sp_criteria_modifier'], ['before', 'after', 'between'])) {
+ if (!preg_match('/^[1-9][0-9]*$|0/', $d['sp_criteria_value'])) {
+ $element->addError(_('Only non-negative integer numbers are allowed (e.g 1 or 5) for the text value'));
$isValid = false;
- // TODO validate this on numeric input with whatever parsing also do for extra
+ // TODO validate this on numeric input with whatever parsing also do for extra
//if the modifier is before ago or between we skip validation until we confirm format
- }
- elseif (isSet($d['sp_criteria_datetime_select']) && $d['sp_criteria_datetime_select'] == "0") {
- $element->addError(_("You must select a time unit for a relative datetime."));
+ } elseif (isset($d['sp_criteria_datetime_select']) && $d['sp_criteria_datetime_select'] == '0') {
+ $element->addError(_('You must select a time unit for a relative datetime.'));
$isValid = false;
}
} else {
if (!preg_match("/(\d{4})-(\d{2})-(\d{2})/", $d['sp_criteria_value'])) {
- $element->addError(_("The value should be in timestamp format (e.g. 0000-00-00 or 0000-00-00 00:00:00)"));
+ $element->addError(_('The value should be in timestamp format (e.g. 0000-00-00 or 0000-00-00 00:00:00)'));
$isValid = false;
} else {
$result = Application_Common_DateHelper::checkDateTimeRangeForSQL($d['sp_criteria_value']);
- if (!$result["success"]) {
+ if (!$result['success']) {
// check for if it is in valid range( 1753-01-01 ~ 12/31/9999 )
- $element->addError($result["errMsg"]);
+ $element->addError($result['errMsg']);
$isValid = false;
}
}
@@ -879,51 +883,50 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm
if (isset($d['sp_criteria_extra'])) {
if ($d['sp_criteria_modifier'] == 'between') {
// validate that the input value only contains a number if using relative date times
- if (!preg_match("/^[1-9][0-9]*$|0/",$d['sp_criteria_extra'])) {
- $element->addError(_("Only non-negative integer numbers are allowed for a relative date time"));
+ if (!preg_match('/^[1-9][0-9]*$|0/', $d['sp_criteria_extra'])) {
+ $element->addError(_('Only non-negative integer numbers are allowed for a relative date time'));
$isValid = false;
}
// also need to check to make sure they chose a time unit from the dropdown
- elseif ($d['sp_criteria_extra_datetime_select'] == "0") {
- $element->addError(_("You must select a time unit for a relative datetime."));
+ elseif ($d['sp_criteria_extra_datetime_select'] == '0') {
+ $element->addError(_('You must select a time unit for a relative datetime.'));
$isValid = false;
}
- }
- else {
+ } else {
if (!preg_match("/(\d{4})-(\d{2})-(\d{2})/", $d['sp_criteria_extra'])) {
- $element->addError(_("The value should be in timestamp format (e.g. 0000-00-00 or 0000-00-00 00:00:00)"));
+ $element->addError(_('The value should be in timestamp format (e.g. 0000-00-00 or 0000-00-00 00:00:00)'));
$isValid = false;
} else {
$result = Application_Common_DateHelper::checkDateTimeRangeForSQL($d['sp_criteria_extra']);
- if (!$result["success"]) {
+ if (!$result['success']) {
// check for if it is in valid range( 1753-01-01 ~ 12/31/9999 )
- $element->addError($result["errMsg"]);
+ $element->addError($result['errMsg']);
$isValid = false;
}
}
}
}
- } elseif ($column->getType() == PropelColumnTypes::INTEGER &&
- $d['sp_criteria_field'] != 'owner_id') {
+ } elseif ($column->getType() == PropelColumnTypes::INTEGER
+ && $d['sp_criteria_field'] != 'owner_id') {
if (!is_numeric($d['sp_criteria_value'])) {
- $element->addError(_("The value has to be numeric"));
+ $element->addError(_('The value has to be numeric'));
$isValid = false;
}
// length check
- if ($d['sp_criteria_value'] >= pow(2,31)) {
- $element->addError(_("The value should be less then 2147483648"));
+ if ($d['sp_criteria_value'] >= pow(2, 31)) {
+ $element->addError(_('The value should be less then 2147483648'));
$isValid = false;
}
} elseif ($column->getType() == PropelColumnTypes::VARCHAR) {
if (strlen($d['sp_criteria_value']) > $column->getSize()) {
- $element->addError(sprintf(_("The value should be less than %s characters"), $column->getSize()));
+ $element->addError(sprintf(_('The value should be less than %s characters'), $column->getSize()));
$isValid = false;
}
}
}
- if ($d['sp_criteria_value'] == "") {
- $element->addError(_("Value cannot be empty"));
+ if ($d['sp_criteria_value'] == '') {
+ $element->addError(_('Value cannot be empty'));
$isValid = false;
}
}//end foreach
diff --git a/legacy/application/forms/StationPodcast.php b/legacy/application/forms/StationPodcast.php
index 1c1954ef2..c6a4e2255 100644
--- a/legacy/application/forms/StationPodcast.php
+++ b/legacy/application/forms/StationPodcast.php
@@ -1,8 +1,9 @@
addSubForm($podcastPreferences, 'preferences_podcast');
@@ -12,8 +13,8 @@ class Application_Form_StationPodcast extends Zend_Form {
$csrf_element->setValue($csrf_namespace->authtoken)
->setRequired('true')
->removeDecorator('HtmlTag')
- ->removeDecorator('Label');
+ ->removeDecorator('Label')
+ ;
$this->addElement($csrf_element);
}
-
-}
\ No newline at end of file
+}
diff --git a/legacy/application/forms/StreamSetting.php b/legacy/application/forms/StreamSetting.php
index fe4c2bcc6..59f7d984e 100644
--- a/legacy/application/forms/StreamSetting.php
+++ b/legacy/application/forms/StreamSetting.php
@@ -6,7 +6,6 @@ class Application_Form_StreamSetting extends Zend_Form
public function init()
{
-
}
public function setSetting($setting)
@@ -16,74 +15,80 @@ class Application_Form_StreamSetting extends Zend_Form
public function startFrom()
{
- $this->setDecorators(array(
- array('ViewScript', array('viewScript' => 'preference/stream-setting.phtml'))
- ));
+ $this->setDecorators([
+ ['ViewScript', ['viewScript' => 'preference/stream-setting.phtml']],
+ ]);
$setting = $this->setting;
$output_sound_device = new Zend_Form_Element_Checkbox('output_sound_device');
$output_sound_device->setLabel(_('Hardware Audio Output:'))
- ->setRequired(false)
- ->setValue(($setting['output_sound_device'] == "true")?1:0)
- ->setDecorators(array('ViewHelper'));
+ ->setRequired(false)
+ ->setValue(($setting['output_sound_device'] == 'true') ? 1 : 0)
+ ->setDecorators(['ViewHelper'])
+ ;
$this->addElement($output_sound_device);
$output_sound_device_type = new Zend_Form_Element_Select('output_sound_device_type');
$output_sound_device_type->setLabel(_('Output Type'))
- ->setMultiOptions(array(
- "ALSA"=>_("ALSA"),
- "AO"=>_("AO"),
- "OSS"=>_("OSS"),
- "Portaudio"=>_("Portaudio"),
- "Pulseaudio"=>_("Pulseaudio"),
- "Jack"=>_("Jack")))
- ->setValue(isset($setting['output_sound_device_type'])?$setting['output_sound_device_type']:0)
- ->setDecorators(array('ViewHelper'));
+ ->setMultiOptions([
+ 'ALSA' => _('ALSA'),
+ 'AO' => _('AO'),
+ 'OSS' => _('OSS'),
+ 'Portaudio' => _('Portaudio'),
+ 'Pulseaudio' => _('Pulseaudio'),
+ 'Jack' => _('Jack'), ])
+ ->setValue(isset($setting['output_sound_device_type']) ? $setting['output_sound_device_type'] : 0)
+ ->setDecorators(['ViewHelper'])
+ ;
$this->addElement($output_sound_device_type);
$icecast_vorbis_metadata = new Zend_Form_Element_Checkbox('icecast_vorbis_metadata');
$icecast_vorbis_metadata->setLabel(_('Icecast Vorbis Metadata'))
- ->setRequired(false)
- ->setValue(($setting['icecast_vorbis_metadata'] == "true")?1:0)
- ->setDecorators(array('ViewHelper'));
- if (Application_Model_Preference::GetEnableStreamConf() == "false") {
- $icecast_vorbis_metadata->setAttrib("readonly", true);
+ ->setRequired(false)
+ ->setValue(($setting['icecast_vorbis_metadata'] == 'true') ? 1 : 0)
+ ->setDecorators(['ViewHelper'])
+ ;
+ if (Application_Model_Preference::GetEnableStreamConf() == 'false') {
+ $icecast_vorbis_metadata->setAttrib('readonly', true);
}
$this->addElement($icecast_vorbis_metadata);
$stream_format = new Zend_Form_Element_Radio('streamFormat');
$stream_format->setLabel(_('Stream Label:'));
- $stream_format->setMultiOptions(array(_("Artist - Title"),
- _("Show - Artist - Title"),
- _("Station name - Show name")));
+ $stream_format->setMultiOptions([_('Artist - Title'),
+ _('Show - Artist - Title'),
+ _('Station name - Show name'), ]);
$stream_format->setValue(Application_Model_Preference::GetStreamLabelFormat());
- $stream_format->setDecorators(array('ViewHelper'));
+ $stream_format->setDecorators(['ViewHelper']);
$this->addElement($stream_format);
-
+
$offAirMeta = new Zend_Form_Element_Text('offAirMeta');
$offAirMeta->setLabel(_('Off Air Metadata'))
- ->setValue(Application_Model_StreamSetting::getOffAirMeta())
- ->setDecorators(array('ViewHelper'));
+ ->setValue(Application_Model_StreamSetting::getOffAirMeta())
+ ->setDecorators(['ViewHelper'])
+ ;
$this->addElement($offAirMeta);
-
- $enable_replay_gain = new Zend_Form_Element_Checkbox("enableReplayGain");
- $enable_replay_gain->setLabel(_("Enable Replay Gain"))
- ->setValue(Application_Model_Preference::GetEnableReplayGain())
- ->setDecorators(array('ViewHelper'));
+
+ $enable_replay_gain = new Zend_Form_Element_Checkbox('enableReplayGain');
+ $enable_replay_gain->setLabel(_('Enable Replay Gain'))
+ ->setValue(Application_Model_Preference::GetEnableReplayGain())
+ ->setDecorators(['ViewHelper'])
+ ;
$this->addElement($enable_replay_gain);
-
- $replay_gain = new Zend_Form_Element_Hidden("replayGainModifier");
- $replay_gain->setLabel(_("Replay Gain Modifier"))
- ->setValue(Application_Model_Preference::getReplayGainModifier())
- ->setAttribs(array('style' => "border: 0; color: #f6931f; font-weight: bold;"))
- ->setDecorators(array('ViewHelper'));
+
+ $replay_gain = new Zend_Form_Element_Hidden('replayGainModifier');
+ $replay_gain->setLabel(_('Replay Gain Modifier'))
+ ->setValue(Application_Model_Preference::getReplayGainModifier())
+ ->setAttribs(['style' => 'border: 0; color: #f6931f; font-weight: bold;'])
+ ->setDecorators(['ViewHelper'])
+ ;
$this->addElement($replay_gain);
$custom = Application_Model_Preference::getUsingCustomStreamSettings();
$customSettings = new Zend_Form_Element_Radio('customStreamSettings');
$customSettings->setLabel(_('Streaming Server:'));
- $customSettings->setMultiOptions(array(_("Default Streaming"), _("Custom / 3rd Party Streaming")));
+ $customSettings->setMultiOptions([_('Default Streaming'), _('Custom / 3rd Party Streaming')]);
$customSettings->setValue(!empty($custom) ? $custom : 0);
$this->addElement($customSettings);
}
@@ -91,17 +96,16 @@ class Application_Form_StreamSetting extends Zend_Form
public function isValid($data)
{
if (isset($data['output_sound_device'])) {
- $d = array();
- $d["output_sound_device"] = $data['output_sound_device'];
- $d["icecast_vorbis_metadata"] = $data['icecast_vorbis_metadata'];
+ $d = [];
+ $d['output_sound_device'] = $data['output_sound_device'];
+ $d['icecast_vorbis_metadata'] = $data['icecast_vorbis_metadata'];
if (isset($data['output_sound_device_type'])) {
- $d["output_sound_device_type"] = $data['output_sound_device_type'];
+ $d['output_sound_device_type'] = $data['output_sound_device_type'];
}
- $d["streamFormat"] = $data['streamFormat'];
+ $d['streamFormat'] = $data['streamFormat'];
$this->populate($d);
}
- $isValid = parent::isValid($data);
- return $isValid;
+ return parent::isValid($data);
}
}
diff --git a/legacy/application/forms/StreamSettingSubForm.php b/legacy/application/forms/StreamSettingSubForm.php
index 34859dd5a..8bf7fd910 100644
--- a/legacy/application/forms/StreamSettingSubForm.php
+++ b/legacy/application/forms/StreamSettingSubForm.php
@@ -1,4 +1,5 @@
prefix;
+ $prefix = 's' . $this->prefix;
$stream_number = $this->prefix;
$setting = $this->setting;
$stream_types = $this->stream_types;
@@ -46,180 +46,196 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm
$useDefaults = !Application_Model_Preference::getUsingCustomStreamSettings();
$this->setIsArray(true);
- $this->setElementsBelongTo($prefix."_data");
+ $this->setElementsBelongTo($prefix . '_data');
$enable = new Zend_Form_Element_Checkbox('enable');
$enable->setLabel(_('Enabled:'))
- ->setValue($setting[$prefix.'_enable'] == 'true' ? 1 : 0)
- ->setDecorators(array('ViewHelper'));
+ ->setValue($setting[$prefix . '_enable'] == 'true' ? 1 : 0)
+ ->setDecorators(['ViewHelper'])
+ ;
$this->addElement($enable);
static::$customizable[] = $enable->getName();
$mobile = new Zend_Form_Element_Checkbox('mobile');
$mobile->setLabel(_('Mobile:'));
- $mobile->setValue($setting[$prefix.'_mobile']);
- $mobile->setDecorators(array('ViewHelper'));
+ $mobile->setValue($setting[$prefix . '_mobile']);
+ $mobile->setDecorators(['ViewHelper']);
$this->addElement($mobile);
static::$customizable[] = $mobile->getName();
$type = new Zend_Form_Element_Select('type');
- $type->setLabel(_("Stream Type:"))
- ->setMultiOptions($stream_types)
- ->setValue(isset($setting[$prefix.'_type'])?$setting[$prefix.'_type']:0)
- ->setDecorators(array('ViewHelper'));
+ $type->setLabel(_('Stream Type:'))
+ ->setMultiOptions($stream_types)
+ ->setValue(isset($setting[$prefix . '_type']) ? $setting[$prefix . '_type'] : 0)
+ ->setDecorators(['ViewHelper'])
+ ;
$this->addElement($type);
static::$customizable[] = $type->getName();
$bitrate = new Zend_Form_Element_Select('bitrate');
- $bitrate->setLabel(_("Bit Rate:"))
- ->setMultiOptions($stream_bitrates)
- ->setValue(isset($setting[$prefix.'_bitrate'])?$setting[$prefix.'_bitrate']:0)
- ->setDecorators(array('ViewHelper'));
+ $bitrate->setLabel(_('Bit Rate:'))
+ ->setMultiOptions($stream_bitrates)
+ ->setValue(isset($setting[$prefix . '_bitrate']) ? $setting[$prefix . '_bitrate'] : 0)
+ ->setDecorators(['ViewHelper'])
+ ;
$this->addElement($bitrate);
static::$customizable[] = $bitrate->getName();
$output = new Zend_Form_Element_Select('output');
- $output->setLabel(_("Service Type:"))
- ->setMultiOptions(array("icecast"=>"Icecast", "shoutcast"=>"SHOUTcast"))
- ->setValue($useDefaults ? $streamDefaults['output'] :
- (isset($setting[$prefix.'_output'])?$setting[$prefix.'_output']:"icecast"))
- ->setDecorators(array('ViewHelper'));
+ $output->setLabel(_('Service Type:'))
+ ->setMultiOptions(['icecast' => 'Icecast', 'shoutcast' => 'SHOUTcast'])
+ ->setValue($useDefaults ? $streamDefaults['output'] :
+ (isset($setting[$prefix . '_output']) ? $setting[$prefix . '_output'] : 'icecast'))
+ ->setDecorators(['ViewHelper'])
+ ;
$this->addElement($output);
$channels = new Zend_Form_Element_Select('channels');
- $channels->setLabel(_("Channels:"))
- ->setMultiOptions(array("mono"=>_("1 - Mono"), "stereo"=>_("2 - Stereo")))
- ->setValue(isset($setting[$prefix.'_channels']) ? $setting[$prefix.'_channels'] : "stereo")
- ->setDecorators(array('ViewHelper'));
+ $channels->setLabel(_('Channels:'))
+ ->setMultiOptions(['mono' => _('1 - Mono'), 'stereo' => _('2 - Stereo')])
+ ->setValue(isset($setting[$prefix . '_channels']) ? $setting[$prefix . '_channels'] : 'stereo')
+ ->setDecorators(['ViewHelper'])
+ ;
$this->addElement($channels);
static::$customizable[] = $channels->getName();
$host = new Zend_Form_Element_Text('host');
- $host->setLabel(_("Server"))
- ->setValue($useDefaults ? $streamDefaults['host'] :
- (isset($setting[$prefix.'_host'])?$setting[$prefix.'_host']:""))
- ->setValidators(array(
- array('regex', false, array('/^[0-9a-zA-Z-_.]+$/', 'messages' => _('Invalid character entered')))))
- ->setDecorators(array('ViewHelper'));
+ $host->setLabel(_('Server'))
+ ->setValue($useDefaults ? $streamDefaults['host'] :
+ (isset($setting[$prefix . '_host']) ? $setting[$prefix . '_host'] : ''))
+ ->setValidators([
+ ['regex', false, ['/^[0-9a-zA-Z-_.]+$/', 'messages' => _('Invalid character entered')]], ])
+ ->setDecorators(['ViewHelper'])
+ ;
$host->setAttrib('alt', 'domain');
$this->addElement($host);
$port = new Zend_Form_Element_Text('port');
- $port->setLabel(_("Port"))
- ->setValue($useDefaults ? $streamDefaults['port'] :
- (isset($setting[$prefix.'_port'])?$setting[$prefix.'_port']:""))
- ->setValidators(array(new Zend_Validate_Between(array('min'=>0, 'max'=>99999))))
- ->addValidator('regex', false, array('pattern'=>'/^[0-9]+$/', 'messages'=>array('regexNotMatch'=>_('Only numbers are allowed.'))))
- ->setDecorators(array('ViewHelper'));
+ $port->setLabel(_('Port'))
+ ->setValue($useDefaults ? $streamDefaults['port'] :
+ (isset($setting[$prefix . '_port']) ? $setting[$prefix . '_port'] : ''))
+ ->setValidators([new Zend_Validate_Between(['min' => 0, 'max' => 99999])])
+ ->addValidator('regex', false, ['pattern' => '/^[0-9]+$/', 'messages' => ['regexNotMatch' => _('Only numbers are allowed.')]])
+ ->setDecorators(['ViewHelper'])
+ ;
$this->addElement($port);
$pass = new Zend_Form_Element_Text('pass');
- $pass->setLabel(_("Password"))
- ->setValue($useDefaults ? $streamDefaults['pass'] :
- (isset($setting[$prefix.'_pass'])?$setting[$prefix.'_pass']:""))
- ->setValidators(array(
- array('regex', false, array('/^[^ &<>]+$/', 'messages' => _('Invalid character entered')))))
- ->setDecorators(array('ViewHelper'));
+ $pass->setLabel(_('Password'))
+ ->setValue($useDefaults ? $streamDefaults['pass'] :
+ (isset($setting[$prefix . '_pass']) ? $setting[$prefix . '_pass'] : ''))
+ ->setValidators([
+ ['regex', false, ['/^[^ &<>]+$/', 'messages' => _('Invalid character entered')]], ])
+ ->setDecorators(['ViewHelper'])
+ ;
$pass->setAttrib('alt', 'regular_text');
$this->addElement($pass);
$genre = new Zend_Form_Element_Text('genre');
- $genre->setLabel(_("Genre"))
- ->setValue(isset($setting[$prefix.'_genre'])?$setting[$prefix.'_genre']:"")
- ->setDecorators(array('ViewHelper'));
+ $genre->setLabel(_('Genre'))
+ ->setValue(isset($setting[$prefix . '_genre']) ? $setting[$prefix . '_genre'] : '')
+ ->setDecorators(['ViewHelper'])
+ ;
$this->addElement($genre);
$url = new Zend_Form_Element_Text('url');
- $url->setLabel(_("URL"))
- ->setValue(isset($setting[$prefix.'_url'])?$setting[$prefix.'_url']:"")
- ->setValidators(array(
- array('regex', false, array('/^[0-9a-zA-Z\-_.:\/]+$/', 'messages' => _('Invalid character entered')))))
- ->setDecorators(array('ViewHelper'));
+ $url->setLabel(_('URL'))
+ ->setValue(isset($setting[$prefix . '_url']) ? $setting[$prefix . '_url'] : '')
+ ->setValidators([
+ ['regex', false, ['/^[0-9a-zA-Z\-_.:\/]+$/', 'messages' => _('Invalid character entered')]], ])
+ ->setDecorators(['ViewHelper'])
+ ;
$url->setAttrib('alt', 'url');
$this->addElement($url);
$name = new Zend_Form_Element_Text('name');
- $name->setLabel(_("Name"))
- ->setValue(isset($setting[$prefix.'_name'])?$setting[$prefix.'_name']:"")
- ->setDecorators(array('ViewHelper'));
+ $name->setLabel(_('Name'))
+ ->setValue(isset($setting[$prefix . '_name']) ? $setting[$prefix . '_name'] : '')
+ ->setDecorators(['ViewHelper'])
+ ;
$this->addElement($name);
$description = new Zend_Form_Element_Text('description');
- $description->setLabel(_("Description"))
- ->setValue(isset($setting[$prefix.'_description'])?$setting[$prefix.'_description']:"")
- ->setDecorators(array('ViewHelper'));
+ $description->setLabel(_('Description'))
+ ->setValue(isset($setting[$prefix . '_description']) ? $setting[$prefix . '_description'] : '')
+ ->setDecorators(['ViewHelper'])
+ ;
$this->addElement($description);
$mount = new Zend_Form_Element_Text('mount');
- $mount->setLabel(_("Mount Point"))
- ->setValue($useDefaults ? $streamDefaults['mount'] :
- (isset($setting[$prefix.'_mount'])?$setting[$prefix.'_mount']:""))
- ->setValidators(array(
- array('regex', false, array('/^[^ &<>]+$/', 'messages' => _('Invalid character entered')))))
- ->setDecorators(array('ViewHelper'));
+ $mount->setLabel(_('Mount Point'))
+ ->setValue($useDefaults ? $streamDefaults['mount'] :
+ (isset($setting[$prefix . '_mount']) ? $setting[$prefix . '_mount'] : ''))
+ ->setValidators([
+ ['regex', false, ['/^[^ &<>]+$/', 'messages' => _('Invalid character entered')]], ])
+ ->setDecorators(['ViewHelper'])
+ ;
$mount->setAttrib('alt', 'regular_text');
$this->addElement($mount);
$user = new Zend_Form_Element_Text('user');
- $user->setLabel(_("Username"))
- ->setValue($useDefaults ? $streamDefaults['user'] :
- (isset($setting[$prefix.'_user'])?$setting[$prefix.'_user']:""))
- ->setValidators(array(
- array('regex', false, array('/^[^ &<>]+$/', 'messages' => _('Invalid character entered')))))
- ->setDecorators(array('ViewHelper'));
+ $user->setLabel(_('Username'))
+ ->setValue($useDefaults ? $streamDefaults['user'] :
+ (isset($setting[$prefix . '_user']) ? $setting[$prefix . '_user'] : ''))
+ ->setValidators([
+ ['regex', false, ['/^[^ &<>]+$/', 'messages' => _('Invalid character entered')]], ])
+ ->setDecorators(['ViewHelper'])
+ ;
$user->setAttrib('alt', 'regular_text');
$this->addElement($user);
-
+
$adminUser = new Zend_Form_Element_Text('admin_user');
- $adminUser->setLabel(_("Admin User"))
- ->setValue(Application_Model_StreamSetting::getAdminUser($prefix))
- ->setValidators(array(
- array('regex', false, array('/^[^ &<>]+$/', 'messages' => _('Invalid character entered')))))
- ->setDecorators(array('ViewHelper'));
+ $adminUser->setLabel(_('Admin User'))
+ ->setValue(Application_Model_StreamSetting::getAdminUser($prefix))
+ ->setValidators([
+ ['regex', false, ['/^[^ &<>]+$/', 'messages' => _('Invalid character entered')]], ])
+ ->setDecorators(['ViewHelper'])
+ ;
$adminUser->setAttrib('alt', 'regular_text');
$this->addElement($adminUser);
-
+
$adminPass = new Zend_Form_Element_Password('admin_pass');
- $adminPass->setLabel(_("Admin Password"))
- ->setValue(Application_Model_StreamSetting::getAdminPass($prefix))
- ->setValidators(array(
- array('regex', false, array('/^[^ &<>]+$/', 'messages' => _('Invalid character entered')))))
- ->setDecorators(array('ViewHelper'));
+ $adminPass->setLabel(_('Admin Password'))
+ ->setValue(Application_Model_StreamSetting::getAdminPass($prefix))
+ ->setValidators([
+ ['regex', false, ['/^[^ &<>]+$/', 'messages' => _('Invalid character entered')]], ])
+ ->setDecorators(['ViewHelper'])
+ ;
$adminPass->setAttrib('alt', 'regular_text');
$this->addElement($adminPass);
- $liquidsoap_error_msg = ''._('Getting information from the server...').' ';
+ $liquidsoap_error_msg = '' . _('Getting information from the server...') . ' ';
- $this->setDecorators(array(
- array('ViewScript', array('viewScript' => 'form/stream-setting-form.phtml',
- "stream_number"=>$stream_number,
- "enabled"=>$enable->getValue(),
- "liquidsoap_error_msg"=>$liquidsoap_error_msg))
- ));
+ $this->setDecorators([
+ ['ViewScript', ['viewScript' => 'form/stream-setting-form.phtml',
+ 'stream_number' => $stream_number,
+ 'enabled' => $enable->getValue(),
+ 'liquidsoap_error_msg' => $liquidsoap_error_msg, ]],
+ ]);
}
- public function isValid ($data)
+ public function isValid($data)
{
- $f_data = $data['s'.$this->prefix."_data"];
+ $f_data = $data['s' . $this->prefix . '_data'];
$isValid = parent::isValid($f_data);
// XXX: A couple of ugly workarounds here, but I guess that's what you get when you
// combine an already-complex POST and GET into a single action...
if (Application_Model_Preference::getUsingCustomStreamSettings() && $f_data) {
- if ($f_data['enable'] == 1 && isset($f_data["host"])) {
+ if ($f_data['enable'] == 1 && isset($f_data['host'])) {
if ($f_data['host'] == '') {
- $element = $this->getElement("host");
- $element->addError(_("Server cannot be empty."));
+ $element = $this->getElement('host');
+ $element->addError(_('Server cannot be empty.'));
$isValid = false;
}
if ($f_data['port'] == '') {
- $element = $this->getElement("port");
- $element->addError(_("Port cannot be empty."));
+ $element = $this->getElement('port');
+ $element->addError(_('Port cannot be empty.'));
$isValid = false;
}
if ($f_data['output'] == 'icecast') {
if ($f_data['mount'] == '') {
- $element = $this->getElement("mount");
- $element->addError(_("Mount cannot be empty with Icecast server."));
+ $element = $this->getElement('mount');
+ $element->addError(_('Mount cannot be empty with Icecast server.'));
$isValid = false;
}
}
@@ -229,12 +245,13 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm
return $isValid;
}
- public function toggleState() {
+ public function toggleState()
+ {
$elements = $this->getElements();
foreach ($elements as $element) {
if (Application_Model_Preference::getUsingCustomStreamSettings()) {
$element->setAttrib('disabled', null);
- } else if (!(in_array($element->getName(), static::$customizable)
+ } elseif (!(in_array($element->getName(), static::$customizable)
|| $element->getType() == 'Zend_Form_Element_Hidden')) {
$element->setAttrib('disabled', 'disabled');
}
diff --git a/legacy/application/forms/TuneInPreferences.php b/legacy/application/forms/TuneInPreferences.php
index 3e7c2a660..fc91ccb6f 100644
--- a/legacy/application/forms/TuneInPreferences.php
+++ b/legacy/application/forms/TuneInPreferences.php
@@ -6,37 +6,37 @@ class Application_Form_TuneInPreferences extends Zend_Form_SubForm
{
public function init()
{
- $this->setDecorators(array(
- array('ViewScript', array('viewScript' => 'form/preferences_tunein.phtml'))
- ));
+ $this->setDecorators([
+ ['ViewScript', ['viewScript' => 'form/preferences_tunein.phtml']],
+ ]);
- $enableTunein = new Zend_Form_Element_Checkbox("enable_tunein");
- $enableTunein->setDecorators(array(
+ $enableTunein = new Zend_Form_Element_Checkbox('enable_tunein');
+ $enableTunein->setDecorators([
'ViewHelper',
'Errors',
- 'Label'
- ));
- $enableTunein->addDecorator('Label', array('class' => 'enable-tunein'));
- $enableTunein->setLabel(_("Push metadata to your station on TuneIn?"));
+ 'Label',
+ ]);
+ $enableTunein->addDecorator('Label', ['class' => 'enable-tunein']);
+ $enableTunein->setLabel(_('Push metadata to your station on TuneIn?'));
$enableTunein->setValue(Application_Model_Preference::getTuneinEnabled());
$this->addElement($enableTunein);
- $tuneinStationId = new Zend_Form_Element_Text("tunein_station_id");
- $tuneinStationId->setLabel(_("Station ID:"));
+ $tuneinStationId = new Zend_Form_Element_Text('tunein_station_id');
+ $tuneinStationId->setLabel(_('Station ID:'));
$tuneinStationId->setValue(Application_Model_Preference::getTuneinStationId());
- $tuneinStationId->setAttrib("class", "input_text");
+ $tuneinStationId->setAttrib('class', 'input_text');
$this->addElement($tuneinStationId);
- $tuneinPartnerKey = new Zend_Form_Element_Text("tunein_partner_key");
- $tuneinPartnerKey->setLabel(_("Partner Key:"));
+ $tuneinPartnerKey = new Zend_Form_Element_Text('tunein_partner_key');
+ $tuneinPartnerKey->setLabel(_('Partner Key:'));
$tuneinPartnerKey->setValue(Application_Model_Preference::getTuneinPartnerKey());
- $tuneinPartnerKey->setAttrib("class", "input_text");
+ $tuneinPartnerKey->setAttrib('class', 'input_text');
$this->addElement($tuneinPartnerKey);
- $tuneinPartnerId = new Zend_Form_Element_Text("tunein_partner_id");
- $tuneinPartnerId->setLabel(_("Partner Id:"));
+ $tuneinPartnerId = new Zend_Form_Element_Text('tunein_partner_id');
+ $tuneinPartnerId->setLabel(_('Partner Id:'));
$tuneinPartnerId->setValue(Application_Model_Preference::getTuneinPartnerId());
- $tuneinPartnerId->setAttrib("class", "input_text");
+ $tuneinPartnerId->setAttrib('class', 'input_text');
$this->addElement($tuneinPartnerId);
}
@@ -49,18 +49,18 @@ class Application_Form_TuneInPreferences extends Zend_Form_SubForm
// with the commercial flag set to true, which removes the metadata
// from the station on TuneIn. After that, and if the test request
// succeeds, we will make another request with the real metadata.
- if ($data["enable_tunein"]) {
- $credentialsQryStr = "?partnerId=".$data["tunein_partner_id"]."&partnerKey=".$data["tunein_partner_key"]."&id=".$data["tunein_station_id"];
- $commercialFlagQryStr = "&commercial=true";
+ if ($data['enable_tunein']) {
+ $credentialsQryStr = '?partnerId=' . $data['tunein_partner_id'] . '&partnerKey=' . $data['tunein_partner_key'] . '&id=' . $data['tunein_station_id'];
+ $commercialFlagQryStr = '&commercial=true';
$metadata = Application_Model_Schedule::getCurrentPlayingTrack();
if (is_null($metadata)) {
$qryStr = $credentialsQryStr . $commercialFlagQryStr;
} else {
- $metadata["artist"] = empty($metadata["artist"]) ? "n/a" : $metadata["artist"];
- $metadata["title"] = empty($metadata["title"]) ? "n/a" : $metadata["title"];
- $metadataQryStr = "&artist=" . $metadata["artist"] . "&title=" . $metadata["title"];
+ $metadata['artist'] = empty($metadata['artist']) ? 'n/a' : $metadata['artist'];
+ $metadata['title'] = empty($metadata['title']) ? 'n/a' : $metadata['title'];
+ $metadataQryStr = '&artist=' . $metadata['artist'] . '&title=' . $metadata['title'];
$qryStr = $credentialsQryStr . $metadataQryStr;
}
@@ -73,9 +73,9 @@ class Application_Form_TuneInPreferences extends Zend_Form_SubForm
$xmlData = curl_exec($ch);
if (curl_error($ch)) {
- Logging::error("Failed to reach TuneIn: ". curl_errno($ch)." - ". curl_error($ch) . " - " . curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
- if (curl_error($ch) == "The requested URL returned error: 403 Forbidden") {
- $this->getElement("enable_tunein")->setErrors(array(_("Invalid TuneIn Settings. Please ensure your TuneIn settings are correct and try again.")));
+ Logging::error('Failed to reach TuneIn: ' . curl_errno($ch) . ' - ' . curl_error($ch) . ' - ' . curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
+ if (curl_error($ch) == 'The requested URL returned error: 403 Forbidden') {
+ $this->getElement('enable_tunein')->setErrors([_('Invalid TuneIn Settings. Please ensure your TuneIn settings are correct and try again.')]);
$valid = false;
}
}
@@ -83,10 +83,10 @@ class Application_Form_TuneInPreferences extends Zend_Form_SubForm
if ($valid) {
$xmlObj = new SimpleXMLElement($xmlData);
- if (!$xmlObj || $xmlObj->head->status != "200") {
- $this->getElement("enable_tunein")->setErrors(array(_("Invalid TuneIn Settings. Please ensure your TuneIn settings are correct and try again.")));
+ if (!$xmlObj || $xmlObj->head->status != '200') {
+ $this->getElement('enable_tunein')->setErrors([_('Invalid TuneIn Settings. Please ensure your TuneIn settings are correct and try again.')]);
$valid = false;
- } else if ($xmlObj->head->status == "200") {
+ } elseif ($xmlObj->head->status == '200') {
Application_Model_Preference::setLastTuneinMetadataUpdate(time());
$valid = true;
}
@@ -98,10 +98,10 @@ class Application_Form_TuneInPreferences extends Zend_Form_SubForm
if (!$valid) {
// Set values to what the user entered since the form is invalid so they
// don't have to enter in the values again and can see what they entered.
- $this->getElement("enable_tunein")->setValue($data["enable_tunein"]);
- $this->getElement("tunein_partner_key")->setValue($data["tunein_partner_key"]);
- $this->getElement("tunein_partner_id")->setValue($data["tunein_partner_id"]);
- $this->getElement("tunein_station_id")->setValue($data["tunein_station_id"]);
+ $this->getElement('enable_tunein')->setValue($data['enable_tunein']);
+ $this->getElement('tunein_partner_key')->setValue($data['tunein_partner_key']);
+ $this->getElement('tunein_partner_id')->setValue($data['tunein_partner_id']);
+ $this->getElement('tunein_station_id')->setValue($data['tunein_station_id']);
}
return $valid;
diff --git a/legacy/application/forms/WatchedDirPreferences.php b/legacy/application/forms/WatchedDirPreferences.php
index 7c4fca1c8..b42da727d 100644
--- a/legacy/application/forms/WatchedDirPreferences.php
+++ b/legacy/application/forms/WatchedDirPreferences.php
@@ -2,34 +2,33 @@
class Application_Form_WatchedDirPreferences extends Zend_Form_SubForm
{
-
public function init()
{
- $this->setDecorators(array(
- array('ViewScript', array('viewScript' => 'form/preferences_watched_dirs.phtml'))
- ));
+ $this->setDecorators([
+ ['ViewScript', ['viewScript' => 'form/preferences_watched_dirs.phtml']],
+ ]);
- $this->addElement('text', 'storageFolder', array(
- 'class' => 'input_text',
- 'label' => _('Import Folder:'),
- 'required' => false,
- 'filters' => array('StringTrim'),
+ $this->addElement('text', 'storageFolder', [
+ 'class' => 'input_text',
+ 'label' => _('Import Folder:'),
+ 'required' => false,
+ 'filters' => ['StringTrim'],
'value' => '',
- 'decorators' => array(
- 'ViewHelper'
- )
- ));
+ 'decorators' => [
+ 'ViewHelper',
+ ],
+ ]);
- $this->addElement('text', 'watchedFolder', array(
- 'class' => 'input_text',
- 'label' => _('Watched Folders:'),
- 'required' => false,
- 'filters' => array('StringTrim'),
+ $this->addElement('text', 'watchedFolder', [
+ 'class' => 'input_text',
+ 'label' => _('Watched Folders:'),
+ 'required' => false,
+ 'filters' => ['StringTrim'],
'value' => '',
- 'decorators' => array(
- 'ViewHelper'
- )
- ));
+ 'decorators' => [
+ 'ViewHelper',
+ ],
+ ]);
}
public function verifyChosenFolder($p_form_element_id)
@@ -37,15 +36,12 @@ class Application_Form_WatchedDirPreferences extends Zend_Form_SubForm
$element = $this->getElement($p_form_element_id);
if (!is_dir($element->getValue())) {
- $element->setErrors(array(_('Not a valid Directory')));
+ $element->setErrors([_('Not a valid Directory')]);
return false;
- } else {
- $element->setValue("");
-
- return true;
}
+ $element->setValue('');
+ return true;
}
-
}
diff --git a/legacy/application/forms/customfilters/ImageSize.php b/legacy/application/forms/customfilters/ImageSize.php
index 299121d20..52a8a3f15 100644
--- a/legacy/application/forms/customfilters/ImageSize.php
+++ b/legacy/application/forms/customfilters/ImageSize.php
@@ -1,15 +1,14 @@
'1', 'PARENT_2'=>'0')
+ * E.g., if we have a field that should only be validated when two other
+ * fields PARENT_1 and PARENT_2 have values of '1' and '0' respectively, then
+ * $fieldValues should contain ('PARENT_1'=>'1', 'PARENT_2'=>'0')
*/
public function __construct($fieldValues)
{
$this->_fieldValues = $fieldValues;
- $this->_messageTemplates = array(
- self::KEY_IS_EMPTY => _("Value is required and can't be empty")
- );
+ $this->_messageTemplates = [
+ self::KEY_IS_EMPTY => _("Value is required and can't be empty"),
+ ];
}
/**
@@ -39,18 +39,19 @@ class ConditionalNotEmpty extends Zend_Validate_Abstract
* this function returns true if the expected values doesn't match the actual user input,
* or if $value is not empty. Returns false otherwise.
*
- * @param String $value - this field's value
- * @param array $context - names and values of the rest of the fields in this form
- * @return boolean - true if valid; false otherwise
+ * @param string $value - this field's value
+ * @param array $context - names and values of the rest of the fields in this form
+ *
+ * @return bool - true if valid; false otherwise
*/
public function isValid($value, $context = null)
{
- if ($value != "") {
+ if ($value != '') {
return true;
}
if (is_array($context)) {
- foreach ($this->_fieldValues as $fieldName=>$fieldValue) {
+ foreach ($this->_fieldValues as $fieldName => $fieldValue) {
if (!isset($context[$fieldName]) || $context[$fieldName] != $fieldValue) {
return true;
}
diff --git a/legacy/application/forms/helpers/CustomDecorators.php b/legacy/application/forms/helpers/CustomDecorators.php
index 43370e7d6..db425ce4a 100644
--- a/legacy/application/forms/helpers/CustomDecorators.php
+++ b/legacy/application/forms/helpers/CustomDecorators.php
@@ -8,9 +8,9 @@ class Airtime_Decorator_SuperAdmin_Only extends Zend_Form_Decorator_Abstract
$currentUser = Application_Model_User::getCurrentUser();
if ($currentUser->isSuperAdmin()) {
return $content;
- } else {
- return "";
}
+
+ return '';
}
}
@@ -22,8 +22,8 @@ class Airtime_Decorator_Admin_Only extends Zend_Form_Decorator_Abstract
$currentUser = Application_Model_User::getCurrentUser();
if ($currentUser->isSuperAdmin() || $currentUser->isAdmin()) {
return $content;
- } else {
- return "";
}
+
+ return '';
}
-}
\ No newline at end of file
+}
diff --git a/legacy/application/forms/helpers/ValidationTypes.php b/legacy/application/forms/helpers/ValidationTypes.php
index 79d53e7b2..e0ce08c23 100644
--- a/legacy/application/forms/helpers/ValidationTypes.php
+++ b/legacy/application/forms/helpers/ValidationTypes.php
@@ -1,6 +1,7 @@
setToken($p_matchAgainst);
$validator->setMessage(
- _("Passwords do not match"),
+ _('Passwords do not match'),
Zend_Validate_Identical::NOT_SAME
);
return $validator;
}
-
-}
\ No newline at end of file
+}
diff --git a/legacy/application/logging/AirtimeLog.php b/legacy/application/logging/AirtimeLog.php
index 6691f51e9..3c3094a49 100644
--- a/legacy/application/logging/AirtimeLog.php
+++ b/legacy/application/logging/AirtimeLog.php
@@ -2,41 +2,38 @@
class Airtime_Zend_Log extends Zend_Log
{
-
/**
- *
- * @var boolean
+ * @var bool
*/
protected $_registeredErrorHandler = false;
-
+
/**
- *
- * @var array|boolean
+ * @var array|bool
*/
- protected $_errorHandlerMap = false;
-
+ protected $_errorHandlerMap = false;
+
/**
- *
- * @var callback
+ * @var callable
*/
- protected $_origErrorHandler = null;
-
-
+ protected $_origErrorHandler;
+
public function __construct(Zend_Log_Writer_Abstract $writer = null)
{
parent::__construct($writer);
}
-
+
/**
- * Error Handler will convert error into log message, and then call the original error handler
+ * Error Handler will convert error into log message, and then call the original error handler.
*
- * @link http://www.php.net/manual/en/function.set-error-handler.php Custom error handler
- * @param int $errno
+ * @see http://www.php.net/manual/en/function.set-error-handler.php Custom error handler
+ *
+ * @param int $errno
* @param string $errstr
* @param string $errfile
- * @param int $errline
- * @param array $errcontext
- * @return boolean
+ * @param int $errline
+ * @param array $errcontext
+ *
+ * @return bool
*/
public function errorHandler($errno, $errstr, $errfile, $errline, $errcontext)
{
@@ -48,15 +45,16 @@ class Airtime_Zend_Log extends Zend_Log
} else {
$priority = Zend_Log::INFO;
}
- $this->log($errstr, $priority, array('errno'=>$errno, 'file'=>$errfile, 'line'=>$errline, 'context'=>$errcontext));
+ $this->log($errstr, $priority, ['errno' => $errno, 'file' => $errfile, 'line' => $errline, 'context' => $errcontext]);
}
if ($this->_origErrorHandler !== null) {
return call_user_func($this->_origErrorHandler, $errno, $errstr, $errfile, $errline, $errcontext);
}
+
return false;
}
-
+
/**
* Register Logging system as an error handler to log php errors
* Note: it still calls the original error handler if set_error_handler is able to return it.
@@ -68,7 +66,7 @@ class Airtime_Zend_Log extends Zend_Log
* E_DEPRECATED, E_STRICT, E_USER_DEPRECATED => DEBUG
* (unknown/other) => INFO
*
- * @link http://www.php.net/manual/en/function.set-error-handler.php Custom error handler
+ * @see http://www.php.net/manual/en/function.set-error-handler.php Custom error handler
*
* @return Zend_Log
*/
@@ -79,22 +77,22 @@ class Airtime_Zend_Log extends Zend_Log
return $this;
}
- $this->_origErrorHandler = set_error_handler(array($this, 'errorHandler'));
+ $this->_origErrorHandler = set_error_handler([$this, 'errorHandler']);
// Contruct a default map of phpErrors to Zend_Log priorities.
// Some of the errors are uncatchable, but are included for completeness
- $this->_errorHandlerMap = array(
- E_NOTICE => Zend_Log::NOTICE,
- E_USER_NOTICE => Zend_Log::NOTICE,
- E_WARNING => Zend_Log::WARN,
- E_CORE_WARNING => Zend_Log::WARN,
- E_USER_WARNING => Zend_Log::WARN,
- E_ERROR => Zend_Log::ERR,
- E_USER_ERROR => Zend_Log::ERR,
- E_CORE_ERROR => Zend_Log::ERR,
+ $this->_errorHandlerMap = [
+ E_NOTICE => Zend_Log::NOTICE,
+ E_USER_NOTICE => Zend_Log::NOTICE,
+ E_WARNING => Zend_Log::WARN,
+ E_CORE_WARNING => Zend_Log::WARN,
+ E_USER_WARNING => Zend_Log::WARN,
+ E_ERROR => Zend_Log::ERR,
+ E_USER_ERROR => Zend_Log::ERR,
+ E_CORE_ERROR => Zend_Log::ERR,
E_RECOVERABLE_ERROR => Zend_Log::ERR,
- E_STRICT => Zend_Log::DEBUG,
- );
+ E_STRICT => Zend_Log::DEBUG,
+ ];
// PHP 5.3.0+
if (defined('E_DEPRECATED')) {
$this->_errorHandlerMap['E_DEPRECATED'] = Zend_Log::DEBUG;
@@ -104,6 +102,7 @@ class Airtime_Zend_Log extends Zend_Log
}
$this->_registeredErrorHandler = true;
+
return $this;
}
}
diff --git a/legacy/application/logging/Logging.php b/legacy/application/logging/Logging.php
index 4f8d00a79..72ee60018 100644
--- a/legacy/application/logging/Logging.php
+++ b/legacy/application/logging/Logging.php
@@ -1,7 +1,7 @@
0) {
+
+ if (Zend_Version::compareVersion('1.11') > 0) {
//Running Zend version 1.10 or lower. Need to instantiate our
//own Zend Log class with backported code from 1.11.
- require_once __DIR__."/AirtimeLog.php";
+ require_once __DIR__ . '/AirtimeLog.php';
self::$_logger = new Airtime_Zend_Log($writer);
} else {
self::$_logger = new Zend_Log($writer);
}
self::$_logger->registerErrorHandler();
}
+
return self::$_logger;
}
@@ -27,27 +28,29 @@ class Logging {
{
self::$_path = $path;
}
-
+
public static function toString($p_msg)
{
if (is_array($p_msg) || is_object($p_msg)) {
return print_r($p_msg, true);
- } else if (is_bool($p_msg)) {
- return $p_msg ? "true" : "false";
- } else {
- return $p_msg;
}
+ if (is_bool($p_msg)) {
+ return $p_msg ? 'true' : 'false';
+ }
+
+ return $p_msg;
}
/** @param debugMode Prints the function name, file, and line number. This is slow as it uses debug_backtrace()
* so don't use it unless you need it.
+ * @param mixed $debugMode
*/
- private static function getLinePrefix($debugMode=false)
+ private static function getLinePrefix($debugMode = false)
{
- $linePrefix = "";
+ $linePrefix = '';
if (array_key_exists('SERVER_NAME', $_SERVER)) {
- $linePrefix .= $_SERVER['SERVER_NAME'] . " ";
+ $linePrefix .= $_SERVER['SERVER_NAME'] . ' ';
}
if ($debugMode) {
@@ -56,16 +59,16 @@ class Logging {
$caller = $bt[1];
$file = basename($caller['file']);
$line = $caller['line'];
- $function = "Unknown function";
+ $function = 'Unknown function';
if (array_key_exists(2, $bt)) {
$function = $bt[2]['function'];
}
- $linePrefix .= "[$file:$line - $function()] - ";
+ $linePrefix .= "[{$file}:{$line} - {$function}()] - ";
}
return $linePrefix;
}
-
+
public static function info($p_msg)
{
$logger = self::getLogger();
@@ -81,17 +84,17 @@ class Logging {
public static function error($p_msg)
{
$logger = self::getLogger();
- $logger->err(self::getLinePrefix(true) . self::toString($p_msg));
+ $logger->err(self::getLinePrefix(true) . self::toString($p_msg));
//Escape the % symbols in any of our errors because Sentry chokes (vsprint formatting error).
$msg = self::toString($p_msg);
- $msg = str_replace("%", "%%", $msg);
+ $msg = str_replace('%', '%%', $msg);
SentryLogger::getInstance()->captureError($msg);
}
-
+
public static function debug($p_msg)
{
- if (!(defined('APPLICATION_ENV') && APPLICATION_ENV == "development")) {
+ if (!(defined('APPLICATION_ENV') && APPLICATION_ENV == 'development')) {
return;
}
@@ -103,8 +106,8 @@ class Logging {
public static function debug_sparse(array $p_msg)
{
- Logging::debug("Sparse output:");
- Logging::debug( array_filter($p_msg) );
+ Logging::debug('Sparse output:');
+ Logging::debug(array_filter($p_msg));
}
public static function enablePropelLogging()
@@ -138,8 +141,7 @@ class Logging {
return;
}
- switch($err['type'])
- {
+ switch ($err['type']) {
case E_ERROR:
case E_WARNING:
case E_PARSE:
@@ -153,17 +155,16 @@ class Logging {
if (array_key_exists('message', $err)) {
$errorStr .= $err['message'];
}
- if (array_key_exists('file', $err))
- {
- $errorStr .= ' at ' .$err['file'];
+ if (array_key_exists('file', $err)) {
+ $errorStr .= ' at ' . $err['file'];
}
- if (array_key_exists('line', $err))
- {
+ if (array_key_exists('line', $err)) {
$errorStr .= ':' . $err['line'];
}
$errorStr .= "\n" . var_export($err, true);
Logging::error($errorStr);
+
break;
}
}
@@ -173,6 +174,4 @@ class Logging {
//Static callback:
register_shutdown_function('Logging::loggingShutdownCallback');
}
-
}
-
diff --git a/legacy/application/logging/SentryLogging.php b/legacy/application/logging/SentryLogging.php
index a4d33f67b..76bcb4f38 100644
--- a/legacy/application/logging/SentryLogging.php
+++ b/legacy/application/logging/SentryLogging.php
@@ -2,7 +2,7 @@
class SentryLogger
{
- private static $instance = null;
+ private static $instance;
private $sentryClient;
/** Singleton getter */
@@ -10,31 +10,34 @@ class SentryLogger
{
if (!is_null(self::$instance)) {
return self::$instance;
- } else {
- self::$instance = new SentryLogger();
- return self::$instance;
}
+ self::$instance = new SentryLogger();
+
+ return self::$instance;
}
private function __construct()
{
if (!file_exists(SENTRY_CONFIG_PATH)) {
$this->sentryClient = null;
+
return;
}
// Instantiate a new client with a compatible DSN
$sentry_config = parse_ini_file(SENTRY_CONFIG_PATH, false);
$dsn = $sentry_config['dsn'];
- $this->sentryClient = new Raven_Client($dsn,
- array(
+ $this->sentryClient = new Raven_Client(
+ $dsn,
+ [
//FIXME: This doesn't seem to be working...
- 'processorOptions' => array(
- 'Raven_SanitizeDataProcessor' => array(
+ 'processorOptions' => [
+ 'Raven_SanitizeDataProcessor' => [
'fields_re' => '/(authorization|password|passwd|user_token|secret|SESSION)/i',
- 'values_re' => '/^(?:\d[ -]*?){13,16}$/'
- )
- )
- ));
+ 'values_re' => '/^(?:\d[ -]*?){13,16}$/',
+ ],
+ ],
+ ]
+ );
$client = $this->sentryClient;
/* The Raven docs suggest not enabling these because they're "too noisy".
@@ -74,10 +77,10 @@ class SentryLogger
self::addUserData($client);
self::addTags($client);
- $event_id = $client->getIdent($client->captureException($exception, array(
+ $event_id = $client->getIdent($client->captureException($exception, [
'extra' => $this->getExtraData(),
'tags' => $this->getTags(),
- )));
+ ]));
$client->context->clear();
}
@@ -92,17 +95,18 @@ class SentryLogger
// Provide some additional data with an exception
self::addUserData($client);
self::addTags($client);
- $event_id = $client->getIdent($client->captureMessage($errorMessage, array(
- 'extra' => $this->getExtraData()
- )));
+ $event_id = $client->getIdent($client->captureMessage($errorMessage, [
+ 'extra' => $this->getExtraData(),
+ ]));
$client->context->clear();
}
private static function getTags()
{
- $tags = array();
+ $tags = [];
$config = Config::getConfig();
- $tags['Development Environment'] = $config["dev_env"];
+ $tags['Development Environment'] = $config['dev_env'];
+
return $tags;
}
@@ -113,19 +117,19 @@ class SentryLogger
private static function addUserData($client)
{
- $userData = array();
+ $userData = [];
$userData['client_id'] = Application_Model_Preference::GetClientId();
- $userData['station_url'] = array_key_exists('SERVER_NAME', $_SERVER) ? $_SERVER['SERVER_NAME'] : "";
+ $userData['station_url'] = array_key_exists('SERVER_NAME', $_SERVER) ? $_SERVER['SERVER_NAME'] : '';
$client->user_context($userData);
}
/** Extra data to log with Sentry */
private function getExtraData()
{
- $extraData = array();
+ $extraData = [];
$extraData['php_version'] = phpversion();
$extraData['client_id'] = Application_Model_Preference::GetClientId();
+
return $extraData;
}
-
}
diff --git a/legacy/application/models/Auth.php b/legacy/application/models/Auth.php
index 7fc9b1ea5..032c78256 100644
--- a/legacy/application/models/Auth.php
+++ b/legacy/application/models/Auth.php
@@ -2,33 +2,33 @@
class Application_Model_Auth
{
- const TOKEN_LIFETIME = 'P2D'; // DateInterval syntax
+ public const TOKEN_LIFETIME = 'P2D'; // DateInterval syntax
private function generateToken($action, $user_id)
{
- $salt = md5("pro");
- $token = self::generateRandomString();
+ $salt = md5('pro');
+ $token = self::generateRandomString();
- $info = new CcSubjsToken();
- $info->setDbUserId($user_id);
- $info->setDbAction($action);
- $info->setDbToken(sha1($token.$salt));
- $info->setDbCreated(gmdate(DEFAULT_TIMESTAMP_FORMAT));
- $info->save();
+ $info = new CcSubjsToken();
+ $info->setDbUserId($user_id);
+ $info->setDbAction($action);
+ $info->setDbToken(sha1($token . $salt));
+ $info->setDbCreated(gmdate(DEFAULT_TIMESTAMP_FORMAT));
+ $info->save();
- Logging::debug("generated token {$token}");
+ Logging::debug("generated token {$token}");
- return $token;
+ return $token;
}
public function sendPasswordRestoreLink($user, $view)
{
$token = $this->generateToken('password.restore', $user->getDbId());
- $e_link_protocol = empty($_SERVER['HTTPS']) ? "http" : "https";
+ $e_link_protocol = empty($_SERVER['HTTPS']) ? 'http' : 'https';
$e_link_base = $_SERVER['SERVER_NAME'];
$e_link_port = $_SERVER['SERVER_PORT'];
- $e_link_path = $view->url(array('user_id' => $user->getDbId(), 'token' => $token), 'password-change');
+ $e_link_path = $view->url(['user_id' => $user->getDbId(), 'token' => $token], 'password-change');
$message = sprintf(_("Hi %s, \n\nPlease click this link to reset your password: "), $user->getDbLogin());
$message .= "{$e_link_protocol}://{$e_link_base}:{$e_link_port}{$e_link_path}";
@@ -36,26 +36,29 @@ class Application_Model_Auth
$message .= sprintf(_("\n\nThank you,\nThe %s Team"), SAAS_PRODUCT_BRANDING_NAME);
$str = sprintf(_('%s Password Reset'), SAAS_PRODUCT_BRANDING_NAME);
+
return Application_Model_Email::send($str, $message, $user->getDbEmail());
}
public function invalidateTokens($user, $action)
{
- CcSubjsTokenQuery::create()
- ->filterByDbAction($action)
- ->filterByDbUserId($user->getDbId())
- ->delete();
+ CcSubjsTokenQuery::create()
+ ->filterByDbAction($action)
+ ->filterByDbUserId($user->getDbId())
+ ->delete()
+ ;
}
public function checkToken($user_id, $token, $action)
{
- $salt = md5("pro");
+ $salt = md5('pro');
$token_info = CcSubjsTokenQuery::create()
- ->filterByDbAction($action)
- ->filterByDbUserId($user_id)
- ->filterByDbToken(sha1($token.$salt))
- ->findOne();
+ ->filterByDbAction($action)
+ ->filterByDbUserId($user_id)
+ ->filterByDbToken(sha1($token . $salt))
+ ->findOne()
+ ;
if (empty($token_info)) {
return false;
@@ -63,13 +66,13 @@ class Application_Model_Auth
$now = new DateTime();
$token_life = new DateInterval(self::TOKEN_LIFETIME);
- $token_created = new DateTime($token_info->getDbCreated(), new DateTimeZone("UTC"));
+ $token_created = new DateTime($token_info->getDbCreated(), new DateTimeZone('UTC'));
return $now->sub($token_life)->getTimestamp() < $token_created->getTimestamp();
}
/**
- * Gets the adapter for authentication against a database table
+ * Gets the adapter for authentication against a database table.
*
* @return object
*/
@@ -79,65 +82,71 @@ class Application_Model_Auth
if ($CC_CONFIG['auth'] !== 'local') {
return self::getCustomAuthAdapter($CC_CONFIG['auth']);
}
-
- // Database config
- $db = Zend_Db::factory('PDO_' . $CC_CONFIG['dsn']['phptype'], array(
- 'host' => $CC_CONFIG['dsn']['hostspec'],
+
+ // Database config
+ $db = Zend_Db::factory('PDO_' . $CC_CONFIG['dsn']['phptype'], [
+ 'host' => $CC_CONFIG['dsn']['hostspec'],
'username' => $CC_CONFIG['dsn']['username'],
'password' => $CC_CONFIG['dsn']['password'],
- 'dbname' => $CC_CONFIG['dsn']['database']
- ));
+ 'dbname' => $CC_CONFIG['dsn']['database'],
+ ]);
Zend_Db_Table_Abstract::setDefaultAdapter($db);
$authAdapter = new Zend_Auth_Adapter_DbTable($db);
$authAdapter->setTableName('cc_subjs')
- ->setIdentityColumn('login')
- ->setCredentialColumn('pass')
- ->setCredentialTreatment('MD5(?)');
+ ->setIdentityColumn('login')
+ ->setCredentialColumn('pass')
+ ->setCredentialTreatment('MD5(?)')
+ ;
return $authAdapter;
}
/**
- * Gets an alternative Adapter that does not need to auth agains a databse table
+ * Gets an alternative Adapter that does not need to auth agains a databse table.
+ *
+ * @param mixed $adaptor
*
* @return object
*/
- public static function getCustomAuthAdapter($adaptor) {
+ public static function getCustomAuthAdapter($adaptor)
+ {
return new $adaptor();
}
/**
- * Get random string
+ * Get random string.
+ *
+ * @param int $length
+ * @param string $allowed_chars
*
- * @param int $length
- * @param string $allowed_chars
* @return string
*/
final public function generateRandomString($length = 12, $allowed_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
{
$string = '';
- for ($i = 0; $i < $length; $i++) {
+ for ($i = 0; $i < $length; ++$i) {
$string .= $allowed_chars[mt_rand(0, strlen($allowed_chars) - 1)];
}
return $string;
}
-
+
/** It is essential to do this before interacting with Zend_Auth otherwise sessions could be shared between
* different copies of Airtime on the same webserver. This essentially pins this session to:
* - The server hostname - including subdomain so we segment multiple Airtime installs on different subdomains
* - The remote IP of the browser - to help prevent session hijacking
- * - The client ID - same reason as server hostname
- * @param Zend_Auth $auth Get this with Zend_Auth::getInstance().
+ * - The client ID - same reason as server hostname.
+ *
+ * @param Zend_Auth $auth get this with Zend_Auth::getInstance()
*/
public static function pinSessionToClient($auth)
{
$CC_CONFIG = Config::getConfig();
- $serverName = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : "";
- $remoteAddr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : "";
- $sessionIdentifier = 'Airtime' . '-' . $serverName . '-' . $remoteAddr . '-' . Application_Model_Preference::GetClientId() . '-' . $CC_CONFIG["baseDir"];
+ $serverName = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '';
+ $remoteAddr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
+ $sessionIdentifier = 'Airtime' . '-' . $serverName . '-' . $remoteAddr . '-' . Application_Model_Preference::GetClientId() . '-' . $CC_CONFIG['baseDir'];
$auth->setStorage(new Zend_Auth_Storage_Session($sessionIdentifier));
}
}
diff --git a/legacy/application/models/Block.php b/legacy/application/models/Block.php
index 696b0f31c..d461e67ab 100644
--- a/legacy/application/models/Block.php
+++ b/legacy/application/models/Block.php
@@ -1,8 +1,6 @@
"",
- "pos" => "",
- "cliplength" => "",
- "cuein" => "00:00:00",
- "cueout" => "00:00:00",
- "fadein" => "0.0",
- "fadeout" => "0.0",
- "crossfadeDuration" => 0
- );
+ private $blockItem = [
+ 'id' => '',
+ 'pos' => '',
+ 'cliplength' => '',
+ 'cuein' => '00:00:00',
+ 'cueout' => '00:00:00',
+ 'fadein' => '0.0',
+ 'fadeout' => '0.0',
+ 'crossfadeDuration' => 0,
+ ];
//using propel's phpNames.
- private $categories = array(
- "dc:title" => "Name",
- "dc:creator" => "Creator",
- "dc:description" => "Description",
- "dcterms:extent" => "Length"
- );
+ private $categories = [
+ 'dc:title' => 'Name',
+ 'dc:creator' => 'Creator',
+ 'dc:description' => 'Description',
+ 'dcterms:extent' => 'Length',
+ ];
- private static $modifier2CriteriaMap = array(
- "contains" => Criteria::ILIKE,
- "does not contain" => Criteria::NOT_ILIKE,
- "is" => Criteria::EQUAL,
- "is not" => Criteria::NOT_EQUAL,
- "starts with" => Criteria::ILIKE,
- "ends with" => Criteria::ILIKE,
- "is greater than" => Criteria::GREATER_THAN,
- "is less than" => Criteria::LESS_THAN,
- "is in the range" => Criteria::CUSTOM,
- "before" => Criteria::CUSTOM,
- "after" => Criteria::CUSTOM,
- "between" => Criteria::CUSTOM);
+ private static $modifier2CriteriaMap = [
+ 'contains' => Criteria::ILIKE,
+ 'does not contain' => Criteria::NOT_ILIKE,
+ 'is' => Criteria::EQUAL,
+ 'is not' => Criteria::NOT_EQUAL,
+ 'starts with' => Criteria::ILIKE,
+ 'ends with' => Criteria::ILIKE,
+ 'is greater than' => Criteria::GREATER_THAN,
+ 'is less than' => Criteria::LESS_THAN,
+ 'is in the range' => Criteria::CUSTOM,
+ 'before' => Criteria::CUSTOM,
+ 'after' => Criteria::CUSTOM,
+ 'between' => Criteria::CUSTOM, ];
- private static $criteria2PeerMap = array(
- 0 => "Select criteria",
- "album_title" => "DbAlbumTitle",
- "artist_name" => "DbArtistName",
- "bit_rate" => "DbBitRate",
- "bpm" => "DbBpm",
- "composer" => "DbComposer",
- "conductor" => "DbConductor",
- "copyright" => "DbCopyright",
- "cuein" => "DbCuein",
- "cueout" => "DbCueout",
- "description" => "DbDescription",
- "encoded_by" => "DbEncodedBy",
- "utime" => "DbUtime",
- "mtime" => "DbMtime",
- "lptime" => "DbLPtime",
- "genre" => "DbGenre",
- "info_url" => "DbInfoUrl",
- "isrc_number" => "DbIsrcNumber",
- "label" => "DbLabel",
- "language" => "DbLanguage",
- "length" => "DbLength",
- "mime" => "DbMime",
- "mood" => "DbMood",
- "owner_id" => "DbOwnerId",
- "replay_gain" => "DbReplayGain",
- "sample_rate" => "DbSampleRate",
- "track_title" => "DbTrackTitle",
- "track_number" => "DbTrackNumber",
- "year" => "DbYear",
- "track_type" => "DbTrackType"
- );
+ private static $criteria2PeerMap = [
+ 0 => 'Select criteria',
+ 'album_title' => 'DbAlbumTitle',
+ 'artist_name' => 'DbArtistName',
+ 'bit_rate' => 'DbBitRate',
+ 'bpm' => 'DbBpm',
+ 'composer' => 'DbComposer',
+ 'conductor' => 'DbConductor',
+ 'copyright' => 'DbCopyright',
+ 'cuein' => 'DbCuein',
+ 'cueout' => 'DbCueout',
+ 'description' => 'DbDescription',
+ 'encoded_by' => 'DbEncodedBy',
+ 'utime' => 'DbUtime',
+ 'mtime' => 'DbMtime',
+ 'lptime' => 'DbLPtime',
+ 'genre' => 'DbGenre',
+ 'info_url' => 'DbInfoUrl',
+ 'isrc_number' => 'DbIsrcNumber',
+ 'label' => 'DbLabel',
+ 'language' => 'DbLanguage',
+ 'length' => 'DbLength',
+ 'mime' => 'DbMime',
+ 'mood' => 'DbMood',
+ 'owner_id' => 'DbOwnerId',
+ 'replay_gain' => 'DbReplayGain',
+ 'sample_rate' => 'DbSampleRate',
+ 'track_title' => 'DbTrackTitle',
+ 'track_number' => 'DbTrackNumber',
+ 'year' => 'DbYear',
+ 'track_type' => 'DbTrackType',
+ ];
- public function __construct($id=null, $con=null)
+ public function __construct($id = null, $con = null)
{
if (isset($id)) {
$this->block = CcBlockQuery::create()->findPk($id);
@@ -99,13 +97,13 @@ class Application_Model_Block implements Application_Model_LibraryEditable
}
} else {
$this->block = new CcBlock();
- $this->block->setDbUTime(new DateTime("now", new DateTimeZone("UTC")));
+ $this->block->setDbUTime(new DateTime('now', new DateTimeZone('UTC')));
$this->block->save();
}
- $this->blockItem["fadein"] = Application_Model_Preference::GetDefaultFadeIn();
- $this->blockItem["fadeout"] = Application_Model_Preference::GetDefaultFadeOut();
- $this->blockItem["crossfadeDuration"] = Application_Model_Preference::GetDefaultCrossfadeDuration();
+ $this->blockItem['fadein'] = Application_Model_Preference::GetDefaultFadeIn();
+ $this->blockItem['fadeout'] = Application_Model_Preference::GetDefaultFadeOut();
+ $this->blockItem['crossfadeDuration'] = Application_Model_Preference::GetDefaultCrossfadeDuration();
$this->con = isset($con) ? $con : Propel::getConnection(CcBlockPeer::DATABASE_NAME);
$this->id = $this->block->getDbId();
@@ -122,19 +120,19 @@ class Application_Model_Block implements Application_Model_LibraryEditable
}
/**
- * Rename stored virtual block
+ * Rename stored virtual block.
*
* @param string $p_newname
*/
public function setName($p_newname)
{
$this->block->setDbName($p_newname);
- $this->block->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
+ $this->block->setDbMtime(new DateTime('now', new DateTimeZone('UTC')));
$this->block->save($this->con);
}
/**
- * Get mnemonic block name
+ * Get mnemonic block name.
*
* @return string
*/
@@ -146,7 +144,7 @@ class Application_Model_Block implements Application_Model_LibraryEditable
public function setDescription($p_description)
{
$this->block->setDbDescription($p_description);
- $this->block->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
+ $this->block->setDbMtime(new DateTime('now', new DateTimeZone('UTC')));
$this->block->save($this->con);
}
@@ -168,7 +166,7 @@ class Application_Model_Block implements Application_Model_LibraryEditable
public function setCreator($p_id)
{
$this->block->setDbCreatorId($p_id);
- $this->block->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
+ $this->block->setDbMtime(new DateTime('now', new DateTimeZone('UTC')));
$this->block->save($this->con);
}
@@ -184,13 +182,15 @@ class Application_Model_Block implements Application_Model_LibraryEditable
/**
* Get the entire block as a two dimensional array, sorted in order of play.
- * @param boolean $filterFiles if this is true, it will only return files that has
- * file_exists flag set to true
+ *
+ * @param bool $filterFiles if this is true, it will only return files that has
+ * file_exists flag set to true
+ *
* @return array
*/
- public function getContents($filterFiles=false)
+ public function getContents($filterFiles = false)
{
- $sql = <<$this->id);
+ $params = [':block_id' => $this->id];
if ($filterFiles) {
$params[':file_exists'] = $filterFiles;
}
@@ -231,7 +231,6 @@ SQL;
$offset = 0;
foreach ($rows as &$row) {
-
$clipSec = Application_Common_DateHelper::playlistTimeToSeconds($row['length']);
$row['trackSec'] = $clipSec;
@@ -268,8 +267,8 @@ SQL;
$row['orig_length'] = $formatter->format();
// XSS exploit prevention
- $row["track_title"] = htmlspecialchars($row["track_title"]);
- $row["creator"] = htmlspecialchars($row["creator"]);
+ $row['track_title'] = htmlspecialchars($row['track_title']);
+ $row['creator'] = htmlspecialchars($row['creator']);
}
return $rows;
@@ -279,19 +278,23 @@ SQL;
* The database stores fades in 00:00:00 Time format with optional millisecond resolution .000000
* but this isn't practical since fades shouldn't be very long usually 1 second or less. This function
* will normalize the fade so that it looks like 00.000000 to the user.
- **/
+ *
+ * @param mixed $fade
+ */
public function normalizeFade($fade)
{
//First get rid of the first six characters 00:00: which will be added back later for db update
$fade = substr($fade, 6);
//Second add .000000 if the fade does't have milliseconds format already
- $dbFadeStrPos = strpos( $fade, '.' );
- if ( $dbFadeStrPos === False )
+ $dbFadeStrPos = strpos($fade, '.');
+ if ($dbFadeStrPos === false) {
$fade .= '.000000';
- else
- while( strlen( $fade ) < 9 )
- $fade .= '0';
+ } else {
+ while (strlen($fade) < 9) {
+ $fade .= '0';
+ }
+ }
//done, just need to set back the formated values
return $fade;
@@ -312,47 +315,45 @@ SQL;
public function getLength()
{
$this->block->reload();
- $prepend = "";
+ $prepend = '';
if ($this->isStatic()) {
$length = $this->block->getDbLength();
} else {
$length = $this->getDynamicBlockLength();
if (!$this->hasItemLimit()) {
- $prepend = "~";
+ $prepend = '~';
}
}
$formatter = new LengthFormatter($length);
- $length = $prepend.$formatter->format();
- return $length;
+ return $prepend . $formatter->format();
}
public function getDynamicBlockLength()
{
list($value, $modifier) = $this->getLimitValueAndModifier();
- if ($modifier == "items") {
- $length = $value." "._("items");
+ if ($modifier == 'items') {
+ $length = $value . ' ' . _('items');
} else {
- $hour = "00";
- $mins = "00";
- if ($modifier == "minutes") {
+ $hour = '00';
+ $mins = '00';
+ if ($modifier == 'minutes') {
$mins = $value;
- if ($value >59) {
- $hour = intval($value/60);
- $mins = $value%60;
-
+ if ($value > 59) {
+ $hour = intval($value / 60);
+ $mins = $value % 60;
}
- } elseif ($modifier == "hours") {
+ } elseif ($modifier == 'hours') {
$mins = $value * 60;
- if ($mins >59) {
- $hour = intval($mins/60);
- $hour = str_pad($hour, 2, "0", STR_PAD_LEFT);
- $mins = $mins%60;
+ if ($mins > 59) {
+ $hour = intval($mins / 60);
+ $hour = str_pad($hour, 2, '0', STR_PAD_LEFT);
+ $mins = $mins % 60;
}
}
- $hour = str_pad($hour, 2, "0", STR_PAD_LEFT);
- $mins = str_pad($mins, 2, "0", STR_PAD_LEFT);
- $length = $hour.":".$mins.":00";
+ $hour = str_pad($hour, 2, '0', STR_PAD_LEFT);
+ $mins = str_pad($mins, 2, '0', STR_PAD_LEFT);
+ $length = $hour . ':' . $mins . ':00';
}
return $length;
@@ -361,26 +362,27 @@ SQL;
public function getLimitValueAndModifier()
{
$result = CcBlockcriteriaQuery::create()->filterByDbBlockId($this->id)
- ->filterByDbCriteria('limit')->findOne();
+ ->filterByDbCriteria('limit')->findOne();
if ($result) {
$modifier = $result->getDbModifier();
$value = $result->getDbValue();
- return array($value, $modifier);
- }
+ return [$value, $modifier];
+ }
}
// this function returns sum of all track length under this block.
public function getStaticLength()
{
- $sql = <<$this->id), 'all', PDO::FETCH_NUM);
+ $result = Application_Common_Database::prepareAndExecute($sql, [':block_id' => $this->id], 'all', PDO::FETCH_NUM);
+
return $result[0][0];
}
@@ -388,14 +390,14 @@ SQL;
{
$row = new CcBlockcontents();
$row->setDbBlockId($this->id);
- $row->setDbFileId($info["id"]);
- $row->setDbPosition($info["pos"]);
- $row->setDbCliplength($info["cliplength"]);
- $row->setDbCuein($info["cuein"]);
- $row->setDbCueout($info["cueout"]);
- $row->setDbFadein(Application_Common_DateHelper::secondsToPlaylistTime($info["fadein"]));
- $row->setDbFadeout(Application_Common_DateHelper::secondsToPlaylistTime($info["fadeout"]));
- $row->setDbTrackOffset($info["crossfadeDuration"]);
+ $row->setDbFileId($info['id']);
+ $row->setDbPosition($info['pos']);
+ $row->setDbCliplength($info['cliplength']);
+ $row->setDbCuein($info['cuein']);
+ $row->setDbCueout($info['cueout']);
+ $row->setDbFadein(Application_Common_DateHelper::secondsToPlaylistTime($info['fadein']));
+ $row->setDbFadeout(Application_Common_DateHelper::secondsToPlaylistTime($info['fadeout']));
+ $row->setDbTrackOffset($info['crossfadeDuration']);
$row->save($this->con);
// above save result update on cc_block table on length column.
// but $this->block doesn't get updated automatically
@@ -404,33 +406,30 @@ SQL;
$this->block = CcBlockQuery::create()->findPK($this->id);
}
- /*
- *
- */
private function buildEntry($p_item, $pos)
{
$file = CcFilesQuery::create()->findPK($p_item, $this->con);
if (isset($file) && $file->visible()) {
- $entry = $this->blockItem;
- $entry["id"] = $file->getDbId();
- $entry["pos"] = $pos;
- $entry["cueout"] = $file->getDbCueout();
- $entry["cuein"] = $file->getDbCuein();
+ $entry = $this->blockItem;
+ $entry['id'] = $file->getDbId();
+ $entry['pos'] = $pos;
+ $entry['cueout'] = $file->getDbCueout();
+ $entry['cuein'] = $file->getDbCuein();
$cue_out = Application_Common_DateHelper::calculateLengthInSeconds($entry['cueout']);
$cue_in = Application_Common_DateHelper::calculateLengthInSeconds($entry['cuein']);
- $entry["cliplength"] = Application_Common_DateHelper::secondsToPlaylistTime($cue_out-$cue_in);
+ $entry['cliplength'] = Application_Common_DateHelper::secondsToPlaylistTime($cue_out - $cue_in);
return $entry;
- } else {
- throw new Exception("trying to add a file that does not exist.");
}
+
+ throw new Exception('trying to add a file that does not exist.');
}
public function isStatic()
{
- return $this->block->getDbType() == "static";
+ return $this->block->getDbType() == 'static';
}
/*
@@ -441,13 +440,12 @@ SQL;
* @param string (before|after) $addAfter
* whether to add the clips before or after the selected item.
*/
- public function addAudioClips($p_items, $p_afterItem=NULL, $addType = 'after')
+ public function addAudioClips($p_items, $p_afterItem = null, $addType = 'after')
{
$this->con->beginTransaction();
- $contentsToUpdate = array();
+ $contentsToUpdate = [];
try {
-
if (is_numeric($p_afterItem)) {
Logging::info("Finding block content item {$p_afterItem}");
@@ -457,15 +455,15 @@ SQL;
$pos = ($addType == 'after') ? $index + 1 : $index;
$contentsToUpdate = CcBlockcontentsQuery::create()
- ->filterByDbBlockId($this->id)
- ->filterByDbPosition($pos, Criteria::GREATER_EQUAL)
- ->orderByDbPosition()
- ->find($this->con);
+ ->filterByDbBlockId($this->id)
+ ->filterByDbPosition($pos, Criteria::GREATER_EQUAL)
+ ->orderByDbPosition()
+ ->find($this->con)
+ ;
- Logging::info("Adding to block");
+ Logging::info('Adding to block');
Logging::info("at position {$pos}");
} else {
-
//add to the end of the block
if ($addType == 'after') {
$pos = $this->getSize();
@@ -475,18 +473,20 @@ SQL;
$pos = 0;
$contentsToUpdate = CcBlockcontentsQuery::create()
- ->filterByDbBlockId($this->id)
- ->orderByDbPosition()
- ->find($this->con);
+ ->filterByDbBlockId($this->id)
+ ->orderByDbPosition()
+ ->find($this->con)
+ ;
}
$contentsToUpdate = CcBlockcontentsQuery::create()
- ->filterByDbBlockId($this->id)
- ->filterByDbPosition($pos, Criteria::GREATER_EQUAL)
- ->orderByDbPosition()
- ->find($this->con);
+ ->filterByDbBlockId($this->id)
+ ->filterByDbPosition($pos, Criteria::GREATER_EQUAL)
+ ->orderByDbPosition()
+ ->find($this->con)
+ ;
- Logging::info("Adding to block");
+ Logging::info('Adding to block');
Logging::info("at position {$pos}");
}
@@ -515,54 +515,55 @@ SQL;
}
//reset the positions of the remaining items.
- for ($i = 0; $i < count($contentsToUpdate); $i++) {
+ for ($i = 0; $i < count($contentsToUpdate); ++$i) {
$contentsToUpdate[$i]->setDbPosition($pos);
$contentsToUpdate[$i]->save($this->con);
$pos = $pos + 1;
}
- $this->block->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
+ $this->block->setDbMtime(new DateTime('now', new DateTimeZone('UTC')));
$this->block->save($this->con);
$this->con->commit();
$this->updateBlockLengthInAllPlaylist();
-
} catch (Exception $e) {
$this->con->rollback();
+
throw $e;
}
}
/**
- * Move audioClip to the new position in the block
+ * Move audioClip to the new position in the block.
*
* @param array $p_items
- * array of unique ids of the selected items
- * @param int $p_afterItem
- * unique id of the item to move the clip after
+ * array of unique ids of the selected items
+ * @param int $p_afterItem
+ * unique id of the item to move the clip after
*/
- public function moveAudioClips($p_items, $p_afterItem=NULL)
+ public function moveAudioClips($p_items, $p_afterItem = null)
{
$this->con->beginTransaction();
try {
-
$contentsToMove = CcBlockcontentsQuery::create()
- ->filterByDbId($p_items, Criteria::IN)
- ->orderByDbPosition()
- ->find($this->con);
+ ->filterByDbId($p_items, Criteria::IN)
+ ->orderByDbPosition()
+ ->find($this->con)
+ ;
$otherContent = CcBlockcontentsQuery::create()
- ->filterByDbId($p_items, Criteria::NOT_IN)
- ->filterByDbBlockId($this->id)
- ->orderByDbPosition()
- ->find($this->con);
+ ->filterByDbId($p_items, Criteria::NOT_IN)
+ ->filterByDbBlockId($this->id)
+ ->orderByDbPosition()
+ ->find($this->con)
+ ;
$pos = 0;
//moving items to beginning of the block.
if (is_null($p_afterItem)) {
- Logging::info("moving items to beginning of block");
+ Logging::info('moving items to beginning of block');
foreach ($contentsToMove as $item) {
Logging::info("item {$item->getDbId()} to pos {$pos}");
@@ -599,62 +600,64 @@ SQL;
$this->con->commit();
} catch (Exception $e) {
$this->con->rollback();
+
throw $e;
}
$this->block = CcBlockQuery::create()->findPK($this->id);
- $this->block->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
+ $this->block->setDbMtime(new DateTime('now', new DateTimeZone('UTC')));
$this->block->save($this->con);
}
/**
- * Remove audioClip from block
+ * Remove audioClip from block.
*
* @param array $p_items
- * array of unique item ids to remove from the block..
+ * array of unique item ids to remove from the block..
*/
public function delAudioClips($p_items)
{
-
$this->con->beginTransaction();
try {
-
// we need to get the file id of the item we are deleting
// before the item gets deleted from the block
$itemsToDelete = CcBlockcontentsQuery::create()
->filterByPrimaryKeys($p_items)
->filterByDbFileId(null, Criteria::NOT_EQUAL)
- ->find($this->con);
+ ->find($this->con)
+ ;
CcBlockcontentsQuery::create()
- ->findPKs($p_items)
- ->delete($this->con);
+ ->findPKs($p_items)
+ ->delete($this->con)
+ ;
// now that the items have been deleted we can update the
// is_playlist flag in cc_files
Application_Model_StoredFile::setIsPlaylist($itemsToDelete, 'block', false);
$contents = CcBlockcontentsQuery::create()
- ->filterByDbBlockId($this->id)
- ->orderByDbPosition()
- ->find($this->con);
+ ->filterByDbBlockId($this->id)
+ ->orderByDbPosition()
+ ->find($this->con)
+ ;
//reset the positions of the remaining items.
- for ($i = 0; $i < count($contents); $i++) {
+ for ($i = 0; $i < count($contents); ++$i) {
$contents[$i]->setDbPosition($i);
$contents[$i]->save($this->con);
}
- $this->block->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
+ $this->block->setDbMtime(new DateTime('now', new DateTimeZone('UTC')));
$this->block->save($this->con);
$this->con->commit();
$this->updateBlockLengthInAllPlaylist();
-
} catch (Exception $e) {
$this->con->rollback();
+
throw $e;
}
}
@@ -664,19 +667,18 @@ SQL;
//Logging::info("Getting fade info for pos {$pos}");
$row = CcBlockcontentsQuery::create()
- ->joinWith(CcFilesPeer::OM_CLASS)
- ->filterByDbBlockId($this->id)
- ->filterByDbPosition($pos)
- ->findOne();
-
-
+ ->joinWith(CcFilesPeer::OM_CLASS)
+ ->filterByDbBlockId($this->id)
+ ->filterByDbPosition($pos)
+ ->findOne()
+ ;
//Propel returns values in form 00.000000 format which is for only seconds.
//We only want to display 1 decimal
$fadeIn = substr($row->getDbFadein(), 0, 4);
$fadeOut = substr($row->getDbFadeout(), 0, 4);
- return array($fadeIn, $fadeOut);
+ return [$fadeIn, $fadeOut];
}
/*
@@ -688,46 +690,49 @@ SQL;
*/
public function createCrossfade($id1, $fadeOut, $id2, $fadeIn, $offset)
{
- $this->con->beginTransaction();
+ $this->con->beginTransaction();
- if (!isset($offset)) {
- $offset = Application_Model_Preference::GetDefaultCrossfadeDuration();
- }
+ if (!isset($offset)) {
+ $offset = Application_Model_Preference::GetDefaultCrossfadeDuration();
+ }
- try {
- if (isset($id1)) {
- $this->changeFadeInfo($id1, null, $fadeOut);
- }
- if (isset($id2)) {
- $this->changeFadeInfo($id2, $fadeIn, null, $offset);
- }
+ try {
+ if (isset($id1)) {
+ $this->changeFadeInfo($id1, null, $fadeOut);
+ }
+ if (isset($id2)) {
+ $this->changeFadeInfo($id2, $fadeIn, null, $offset);
+ }
- $this->con->commit();
+ $this->con->commit();
+ } catch (Exception $e) {
+ $this->con->rollback();
- } catch (Exception $e) {
- $this->con->rollback();
- throw $e;
- }
+ throw $e;
+ }
}
/**
- * Change fadeIn and fadeOut values for block Element
- *
- * @param int $pos
- * position of audioclip in block
- * @param string $fadeIn
- * new value in ss.ssssss or extent format
- * @param string $fadeOut
- * new value in ss.ssssss or extent format
- * @return boolean
- */
- public function changeFadeInfo($id, $fadeIn, $fadeOut, $offset=null)
+ * Change fadeIn and fadeOut values for block Element.
+ *
+ * @param int $pos
+ * position of audioclip in block
+ * @param string $fadeIn
+ * new value in ss.ssssss or extent format
+ * @param string $fadeOut
+ * new value in ss.ssssss or extent format
+ * @param mixed $id
+ * @param null|mixed $offset
+ *
+ * @return bool
+ */
+ public function changeFadeInfo($id, $fadeIn, $fadeOut, $offset = null)
{
//See issue CC-2065, pad the fadeIn and fadeOut so that it is TIME compatable with the DB schema
//For the top level PlayList either fadeIn or fadeOut will sometimes be Null so need a gaurd against
//setting it to nonNull for checks down below
- $fadeIn = $fadeIn?'00:00:'.$fadeIn:$fadeIn;
- $fadeOut = $fadeOut?'00:00:'.$fadeOut:$fadeOut;
+ $fadeIn = $fadeIn ? '00:00:' . $fadeIn : $fadeIn;
+ $fadeOut = $fadeOut ? '00:00:' . $fadeOut : $fadeOut;
$this->con->beginTransaction();
@@ -735,18 +740,17 @@ SQL;
$row = CcBlockcontentsQuery::create()->findPK($id);
if (is_null($row)) {
- throw new Exception("Block item does not exist.");
+ throw new Exception('Block item does not exist.');
}
$clipLength = $row->getDbCliplength();
if (!is_null($fadeIn)) {
-
- $sql = "SELECT :fade_in::INTERVAL > :clip_length::INTERVAL";
- $params = array(
+ $sql = 'SELECT :fade_in::INTERVAL > :clip_length::INTERVAL';
+ $params = [
':fade_in' => $fadeIn,
- ':clip_length' => $clipLength
- );
+ ':clip_length' => $clipLength,
+ ];
$result = Application_Common_Database::prepareAndExecute($sql, $params, 'column');
if ($result) {
@@ -756,19 +760,17 @@ SQL;
$row->setDbFadein($fadeIn);
if (!is_null($offset)) {
- $row->setDbTrackOffset($offset);
- Logging::info("Setting offset {$offset} on item {$id}");
- $row->save($this->con);
+ $row->setDbTrackOffset($offset);
+ Logging::info("Setting offset {$offset} on item {$id}");
+ $row->save($this->con);
}
-
}
if (!is_null($fadeOut)) {
-
- $sql = "SELECT :fade_out::INTERVAL > :clip_length::INTERVAL";
- $params = array(
+ $sql = 'SELECT :fade_out::INTERVAL > :clip_length::INTERVAL';
+ $params = [
':fade_out' => $fadeOut,
- ':clip_length' => $clipLength
- );
+ ':clip_length' => $clipLength,
+ ];
$result = Application_Common_Database::prepareAndExecute($sql, $params, 'column');
if ($result) {
@@ -779,16 +781,17 @@ SQL;
}
$row->save($this->con);
- $this->block->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
+ $this->block->setDbMtime(new DateTime('now', new DateTimeZone('UTC')));
$this->block->save($this->con);
$this->con->commit();
} catch (Exception $e) {
$this->con->rollback();
+
throw $e;
}
- return array("fadeIn" => $fadeIn, "fadeOut" => $fadeOut);
+ return ['fadeIn' => $fadeIn, 'fadeOut' => $fadeOut];
}
public function setfades($fadein, $fadeout)
@@ -796,9 +799,10 @@ SQL;
if (isset($fadein)) {
Logging::info("Setting block fade in {$fadein}");
$row = CcBlockcontentsQuery::create()
- ->filterByDbBlockId($this->id)
- ->filterByDbPosition(0)
- ->findOne($this->con);
+ ->filterByDbBlockId($this->id)
+ ->filterByDbPosition(0)
+ ->findOne($this->con)
+ ;
$this->changeFadeInfo($row->getDbId(), $fadein, null);
}
@@ -806,140 +810,144 @@ SQL;
if (isset($fadeout)) {
Logging::info("Setting block fade out {$fadeout}");
$row = CcBlockcontentsQuery::create()
- ->filterByDbBlockId($this->id)
- ->filterByDbPosition($this->getSize()-1)
- ->findOne($this->con);
+ ->filterByDbBlockId($this->id)
+ ->filterByDbPosition($this->getSize() - 1)
+ ->findOne($this->con)
+ ;
$this->changeFadeInfo($row->getDbId(), null, $fadeout);
}
}
/**
- * Change cueIn/cueOut values for block element
- *
- * @param int $pos
- * position of audioclip in block
- * @param string $cueIn
- * new value in ss.ssssss or extent format
- * @param string $cueOut
- * new value in ss.ssssss or extent format
- * @return boolean or pear error object
- */
+ * Change cueIn/cueOut values for block element.
+ *
+ * @param int $pos
+ * position of audioclip in block
+ * @param string $cueIn
+ * new value in ss.ssssss or extent format
+ * @param string $cueOut
+ * new value in ss.ssssss or extent format
+ * @param mixed $id
+ *
+ * @return bool or pear error object
+ */
public function changeClipLength($id, $cueIn, $cueOut)
{
$this->con->beginTransaction();
- $errArray= array();
+ $errArray = [];
try {
if (is_null($cueIn) && is_null($cueOut)) {
- $errArray["error"] = _("Cue in and cue out are null.");
+ $errArray['error'] = _('Cue in and cue out are null.');
return $errArray;
}
$row = CcBlockcontentsQuery::create()
- ->joinWith(CcFilesPeer::OM_CLASS)
- ->filterByPrimaryKey($id)
- ->findOne($this->con);
+ ->joinWith(CcFilesPeer::OM_CLASS)
+ ->filterByPrimaryKey($id)
+ ->findOne($this->con)
+ ;
if (is_null($row)) {
- throw new Exception("Block item does not exist.");
+ throw new Exception('Block item does not exist.');
}
- $oldCueIn = $row->getDBCuein();
+ $oldCueIn = $row->getDBCuein();
$oldCueOut = $row->getDbCueout();
- $fadeIn = $row->getDbFadein();
- $fadeOut = $row->getDbFadeout();
+ $fadeIn = $row->getDbFadein();
+ $fadeOut = $row->getDbFadeout();
$file = $row->getCcFiles($this->con);
$origLength = $file->getDbLength();
if (!is_null($cueIn) && !is_null($cueOut)) {
-
- if ($cueOut === "") {
+ if ($cueOut === '') {
$cueOut = $origLength;
}
- $sql = "SELECT :cue_out::INTERVAL > :orig_length::INTERVAL";
- $params = array(
+ $sql = 'SELECT :cue_out::INTERVAL > :orig_length::INTERVAL';
+ $params = [
':cue_out' => $cueOut,
- ':orig_length' => $origLength
- );
+ ':orig_length' => $origLength,
+ ];
$result = Application_Common_Database::prepareAndExecute($sql, $params, 'column');
if ($result) {
- $errArray["error"] = _("Can't set cue out to be greater than file length.");
+ $errArray['error'] = _("Can't set cue out to be greater than file length.");
+
return $errArray;
}
- $sql = "SELECT :cue_in::INTERVAL > :cue_out::INTERVAL";
- $params = array(
+ $sql = 'SELECT :cue_in::INTERVAL > :cue_out::INTERVAL';
+ $params = [
':cue_in' => $cueIn,
- ':cue_out' => $cueOut
- );
+ ':cue_out' => $cueOut,
+ ];
$result = Application_Common_Database::prepareAndExecute($sql, $params, 'column');
if ($result) {
- $errArray["error"] = _("Can't set cue in to be larger than cue out.");
+ $errArray['error'] = _("Can't set cue in to be larger than cue out.");
+
return $errArray;
}
- $sql = "SELECT :cue_out::INTERVAL - :cue_in::INTERVAL";
+ $sql = 'SELECT :cue_out::INTERVAL - :cue_in::INTERVAL';
$result = Application_Common_Database::prepareAndExecute($sql, $params, 'column');
$cliplength = $result;
$row->setDbCuein($cueIn);
$row->setDbCueout($cueOut);
$row->setDBCliplength($cliplength);
-
} elseif (!is_null($cueIn)) {
-
- $sql = "SELECT :cue_in::INTERVAL > :old_cue_out::INTERVAL";
- $params = array(
+ $sql = 'SELECT :cue_in::INTERVAL > :old_cue_out::INTERVAL';
+ $params = [
':cue_in' => $cueIn,
- ':old_cue_out' => $oldCueOut
- );
+ ':old_cue_out' => $oldCueOut,
+ ];
$result = Application_Common_Database::prepareAndExecute($sql, $params, 'column');
if ($result) {
- $errArray["error"] = _("Can't set cue in to be larger than cue out.");
+ $errArray['error'] = _("Can't set cue in to be larger than cue out.");
+
return $errArray;
}
- $sql = "SELECT :old_cue_out::INTERVAL - :cue_in::INTERVAL";
+ $sql = 'SELECT :old_cue_out::INTERVAL - :cue_in::INTERVAL';
$result = Application_Common_Database::prepareAndExecute($sql, $params, 'column');
$cliplength = $result;
$row->setDbCuein($cueIn);
$row->setDBCliplength($cliplength);
-
} elseif (!is_null($cueOut)) {
-
- if ($cueOut === "") {
+ if ($cueOut === '') {
$cueOut = $origLength;
}
- $sql = "SELECT :cue_out::INTERVAL > :orig_length::INTERVAL";
- $params = array(
+ $sql = 'SELECT :cue_out::INTERVAL > :orig_length::INTERVAL';
+ $params = [
':cue_out' => $cueOut,
- ':orig_length' => $origLength
- );
+ ':orig_length' => $origLength,
+ ];
$result = Application_Common_Database::prepareAndExecute($sql, $params, 'column');
if ($result) {
- $errArray["error"] = _("Can't set cue out to be greater than file length.");
+ $errArray['error'] = _("Can't set cue out to be greater than file length.");
+
return $errArray;
}
- $sql = "SELECT :cue_out::INTERVAL < :old_cue_in::INTERVAL";
- $params = array(
+ $sql = 'SELECT :cue_out::INTERVAL < :old_cue_in::INTERVAL';
+ $params = [
':cue_out' => $cueOut,
- ':old_cue_in' => $oldCueIn
- );
+ ':old_cue_in' => $oldCueIn,
+ ];
$result = Application_Common_Database::prepareAndExecute($sql, $params, 'column');
if ($result) {
- $errArray["error"] = _("Can't set cue out to be smaller than cue in.");
+ $errArray['error'] = _("Can't set cue out to be smaller than cue in.");
+
return $errArray;
}
- $sql = "SELECT :cue_out::INTERVAL - :old_cue_in::INTERVAL";
+ $sql = 'SELECT :cue_out::INTERVAL - :old_cue_in::INTERVAL';
$result = Application_Common_Database::prepareAndExecute($sql, $params, 'column');
$cliplength = $result;
@@ -949,22 +957,22 @@ SQL;
$cliplength = $row->getDbCliplength();
- $sql = "SELECT :fade_in::INTERVAL > :clip_length::INTERVAL";
- $params = array(
+ $sql = 'SELECT :fade_in::INTERVAL > :clip_length::INTERVAL';
+ $params = [
':fade_in' => $fadeIn,
- ':clip_length' => $cliplength
- );
+ ':clip_length' => $cliplength,
+ ];
$result = Application_Common_Database::prepareAndExecute($sql, $params, 'column');
if ($result) {
$fadeIn = $cliplength;
$row->setDbFadein($fadeIn);
}
- $sql = "SELECT :fade_out::INTERVAL > :clip_length::INTERVAL";
- $params = array(
+ $sql = 'SELECT :fade_out::INTERVAL > :clip_length::INTERVAL';
+ $params = [
':fade_out' => $fadeOut,
- ':clip_length' => $cliplength
- );
+ ':clip_length' => $cliplength,
+ ];
$result = Application_Common_Database::prepareAndExecute($sql, $params, 'column');
if ($result) {
$fadeOut = $cliplength;
@@ -972,27 +980,28 @@ SQL;
}
$row->save($this->con);
- $this->block->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
+ $this->block->setDbMtime(new DateTime('now', new DateTimeZone('UTC')));
$this->block->save($this->con);
$this->con->commit();
} catch (Exception $e) {
$this->con->rollback();
+
throw $e;
}
- return array("cliplength"=> $cliplength, "cueIn"=> $cueIn, "cueOut"=> $cueOut, "length"=> $this->getUnformatedLength(),
- "fadeIn"=> $fadeIn, "fadeOut"=> $fadeOut);
+ return ['cliplength' => $cliplength, 'cueIn' => $cueIn, 'cueOut' => $cueOut, 'length' => $this->getUnformatedLength(),
+ 'fadeIn' => $fadeIn, 'fadeOut' => $fadeOut, ];
}
public function getAllPLMetaData()
{
$categories = $this->categories;
- $md = array();
+ $md = [];
foreach ($categories as $key => $val) {
$method = 'get' . $val;
- $md[$key] = $this->$method();
+ $md[$key] = $this->{$method}();
}
return $md;
@@ -1003,7 +1012,7 @@ SQL;
$cat = $this->categories[$category];
$method = 'get' . $cat;
- return $this->$method();
+ return $this->{$method}();
}
public function setMetadata($category, $value)
@@ -1011,44 +1020,49 @@ SQL;
$cat = $this->categories[$category];
$method = 'set' . $cat;
- $this->$method($value);
+ $this->{$method}($value);
}
public static function getBlockCount()
{
- $sql = 'SELECT count(*) as cnt FROM cc_playlist';
+ $sql = 'SELECT count(*) as cnt FROM cc_playlist';
- $res = Application_Common_Database::prepareAndExecute($sql, array(),
- Application_Common_Database::COLUMN);
-
- return $res;
- }
-
- /**
- * Delete the file from all blocks.
- * @param string $p_fileId
- */
- public static function DeleteFileFromAllBlocks($p_fileId)
- {
- CcBlockcontentsQuery::create()->filterByDbFileId($p_fileId)->delete();
+ return Application_Common_Database::prepareAndExecute(
+ $sql,
+ [],
+ Application_Common_Database::COLUMN
+ );
}
/**
- * Delete blocks that match the ids..
- * @param array $p_ids
- */
+ * Delete the file from all blocks.
+ *
+ * @param string $p_fileId
+ */
+ public static function DeleteFileFromAllBlocks($p_fileId)
+ {
+ CcBlockcontentsQuery::create()->filterByDbFileId($p_fileId)->delete();
+ }
+
+ /**
+ * Delete blocks that match the ids..
+ *
+ * @param array $p_ids
+ * @param mixed $p_userId
+ */
public static function deleteBlocks($p_ids, $p_userId)
{
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id);
- $isAdminOrPM = $user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
+ $isAdminOrPM = $user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER]);
// get only the files from the blocks
// we are about to delete
$itemsToDelete = CcBlockcontentsQuery::create()
->filterByDbBlockId($p_ids)
->filterByDbFileId(null, Criteria::NOT_EQUAL)
- ->find();
+ ->find()
+ ;
$updateIsPlaylistFlag = false;
@@ -1059,7 +1073,7 @@ SQL;
CcBlockQuery::create()->findPKs($p_ids)->delete();
$updateIsPlaylistFlag = true;
} else {
- throw new BlockNoPermissionException;
+ throw new BlockNoPermissionException();
}
} else {
CcBlockQuery::create()->findPKs($p_ids)->delete();
@@ -1081,21 +1095,19 @@ SQL;
{
$ownedByUser = CcBlockQuery::create()->filterByDbCreatorId($p_userId)->find()->getData();
$selectedPls = $p_ids;
- $ownedPls = array();
+ $ownedPls = [];
foreach ($ownedByUser as $pl) {
if (in_array($pl->getDbId(), $selectedPls)) {
$ownedPls[] = $pl->getDbId();
}
}
- $leftOvers = array_diff($selectedPls, $ownedPls);
-
- return $leftOvers;
+ return array_diff($selectedPls, $ownedPls);
}
/**
- * Delete all files from block
- */
+ * Delete all files from block.
+ */
public function deleteAllFilesFromBlock()
{
// get only the files from the playlist
@@ -1103,7 +1115,8 @@ SQL;
$itemsToDelete = CcBlockcontentsQuery::create()
->filterByDbBlockId($this->id)
->filterByDbFileId(null, Criteria::NOT_EQUAL)
- ->find();
+ ->find()
+ ;
CcBlockcontentsQuery::create()->findByDbBlockId($this->id)->delete();
@@ -1115,7 +1128,7 @@ SQL;
);
//$this->block->reload();
- $this->block->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
+ $this->block->setDbMtime(new DateTime('now', new DateTimeZone('UTC')));
$this->block->save($this->con);
$this->con->commit();
}
@@ -1124,19 +1137,20 @@ SQL;
public function shuffleSmartBlock()
{
// if it here that means it's static pl
- $this->saveType("static");
+ $this->saveType('static');
$contents = CcBlockcontentsQuery::create()
- ->filterByDbBlockId($this->id)
- ->orderByDbPosition()
- ->find();
- $shuffledPos = range(0, count($contents)-1);
+ ->filterByDbBlockId($this->id)
+ ->orderByDbPosition()
+ ->find()
+ ;
+ $shuffledPos = range(0, count($contents) - 1);
shuffle($shuffledPos);
foreach ($contents as $item) {
$item->setDbPosition(array_shift($shuffledPos));
$item->save();
}
- return array("result"=>0);
+ return ['result' => 0];
}
public function saveType($p_blockType)
@@ -1152,16 +1166,16 @@ SQL;
$this->updateBlockLengthInAllPlaylist();
}
-
/**
- * Saves smart block criteria
+ * Saves smart block criteria.
+ *
* @param array $p_criteria
*/
public function saveSmartBlockCriteria($p_criteria)
{
$data = $this->organizeSmartPlaylistCriteria($p_criteria);
// saving dynamic/static flag
- $blockType = $data['etc']['sp_type'] == 0 ? 'dynamic':'static';
+ $blockType = $data['etc']['sp_type'] == 0 ? 'dynamic' : 'static';
$this->saveType($blockType);
$this->storeCriteriaIntoDb($data);
@@ -1176,7 +1190,7 @@ SQL;
} else {
$length = $this->getStaticLength();
if (!$length) {
- $length = "00:00:00";
+ $length = '00:00:00';
}
$this->setLength($length);
}
@@ -1187,7 +1201,8 @@ SQL;
public function hasItemLimit()
{
list($value, $modifier) = $this->getLimitValueAndModifier();
- return ($modifier == 'items');
+
+ return $modifier == 'items';
}
public function storeCriteriaIntoDb($p_criteriaData)
@@ -1198,48 +1213,50 @@ SQL;
//insert modifier rows
if (isset($p_criteriaData['criteria'])) {
$critKeys = array_keys($p_criteriaData['criteria']);
- for ($i = 0; $i < count($critKeys); $i++) {
+ for ($i = 0; $i < count($critKeys); ++$i) {
// in order to maintain separation of different criteria to preserve AND statements for criteria
// that might contradict itself we group them based upon their original position on the form
$criteriaGroup = $i;
foreach ($p_criteriaData['criteria'][$critKeys[$i]] as $d) {
- $field = $d['sp_criteria_field'];
- $value = $d['sp_criteria_value'];
- $modifier = $d['sp_criteria_modifier'];
- if (isset($d['sp_criteria_extra'])) { $extra = $d['sp_criteria_extra']; }
- if (isset($d['sp_criteria_datetime_select'])) { $datetimeunit = $d['sp_criteria_datetime_select']; }
- if (isset($d['sp_criteria_extra_datetime_select'])) {$extradatetimeunit = $d['sp_criteria_extra_datetime_select'];}
+ $field = $d['sp_criteria_field'];
+ $value = $d['sp_criteria_value'];
+ $modifier = $d['sp_criteria_modifier'];
+ if (isset($d['sp_criteria_extra'])) {
+ $extra = $d['sp_criteria_extra'];
+ }
+ if (isset($d['sp_criteria_datetime_select'])) {
+ $datetimeunit = $d['sp_criteria_datetime_select'];
+ }
+ if (isset($d['sp_criteria_extra_datetime_select'])) {
+ $extradatetimeunit = $d['sp_criteria_extra_datetime_select'];
+ }
- if ($field == 'utime' || $field == 'mtime' || $field == 'lptime') {
- // if the date isn't relative we want to convert the value to a specific UTC date
- if (!(in_array($modifier,array('before','after','between')))) {
- $value = Application_Common_DateHelper::UserTimezoneStringToUTCString($value);
- }
- else {
+ if ($field == 'utime' || $field == 'mtime' || $field == 'lptime') {
+ // if the date isn't relative we want to convert the value to a specific UTC date
+ if (!(in_array($modifier, ['before', 'after', 'between']))) {
+ $value = Application_Common_DateHelper::UserTimezoneStringToUTCString($value);
+ } else {
$value = $value . ' ' . $datetimeunit . ' ago';
- // Logging::info($value);
-
+ // Logging::info($value);
}
- }
+ }
$qry = new CcBlockcriteria();
$qry->setDbCriteria($field)
- ->setDbModifier($d['sp_criteria_modifier'])
- ->setDbValue($value)
- ->setDbBlockId($this->id);
+ ->setDbModifier($d['sp_criteria_modifier'])
+ ->setDbValue($value)
+ ->setDbBlockId($this->id)
+ ;
if (isset($d['sp_criteria_extra'])) {
-
- if ($field == 'utime' || $field == 'mtime' || $field == 'lptime') {
+ if ($field == 'utime' || $field == 'mtime' || $field == 'lptime') {
// if the date isn't relative we want to convert the value to a specific UTC date
- if (!(in_array($modifier,array('before','after','between')))) {
+ if (!(in_array($modifier, ['before', 'after', 'between']))) {
$extra = Application_Common_DateHelper::UserTimezoneStringToUTCString($extra);
+ } else {
+ $extra = $extra . ' ' . $extradatetimeunit . ' ago';
}
- else {
- $extra = $extra . ' ' . $extradatetimeunit. ' ago';
- }
-
- }
+ }
$qry->setDbExtra($extra);
}
@@ -1255,53 +1272,55 @@ SQL;
// insert sort info
$qry = new CcBlockcriteria();
- $qry->setDbCriteria("sort")
- ->setDbModifier("N/A")
- ->setDbValue($p_criteriaData['etc']['sp_sort_options'])
- ->setDbBlockId($this->id)
- ->save();
-
-
+ $qry->setDbCriteria('sort')
+ ->setDbModifier('N/A')
+ ->setDbValue($p_criteriaData['etc']['sp_sort_options'])
+ ->setDbBlockId($this->id)
+ ->save()
+ ;
// insert limit info
$qry = new CcBlockcriteria();
- $qry->setDbCriteria("limit")
- ->setDbModifier($p_criteriaData['etc']['sp_limit_options'])
- ->setDbValue($p_criteriaData['etc']['sp_limit_value'])
- ->setDbBlockId($this->id)
- ->save();
-
+ $qry->setDbCriteria('limit')
+ ->setDbModifier($p_criteriaData['etc']['sp_limit_options'])
+ ->setDbValue($p_criteriaData['etc']['sp_limit_value'])
+ ->setDbBlockId($this->id)
+ ->save()
+ ;
// insert repeat track option
$qry = new CcBlockcriteria();
- $qry->setDbCriteria("repeat_tracks")
- ->setDbModifier("N/A")
- ->setDbValue($p_criteriaData['etc']['sp_repeat_tracks'])
- ->setDbBlockId($this->id)
- ->save();
+ $qry->setDbCriteria('repeat_tracks')
+ ->setDbModifier('N/A')
+ ->setDbValue($p_criteriaData['etc']['sp_repeat_tracks'])
+ ->setDbBlockId($this->id)
+ ->save()
+ ;
// insert overflow track option
$qry = new CcBlockcriteria();
- $qry->setDbCriteria("overflow_tracks")
- ->setDbModifier("N/A")
+ $qry->setDbCriteria('overflow_tracks')
+ ->setDbModifier('N/A')
->setDbValue($p_criteriaData['etc']['sp_overflow_tracks'])
->setDbBlockId($this->id)
- ->save();
-
+ ->save()
+ ;
}
/**
* generate list of tracks. This function saves criteria and generate
* tracks.
+ *
* @param array $p_criteria
+ * @param mixed $returnList
*/
- public function generateSmartBlock($p_criteria, $returnList=false)
+ public function generateSmartBlock($p_criteria, $returnList = false)
{
$this->saveSmartBlockCriteria($p_criteria);
$insertList = $this->getListOfFilesUnderLimit();
$this->deleteAllFilesFromBlock();
// construct id array
- $ids = array();
+ $ids = [];
foreach ($insertList as $ele) {
$ids[] = $ele['id'];
}
@@ -1309,7 +1328,7 @@ SQL;
// update length in playlist contents.
$this->updateBlockLengthInAllPlaylist();
- return array("result"=>0);
+ return ['result' => 0];
}
public function updateBlockLengthInAllPlaylist()
@@ -1319,7 +1338,7 @@ SQL;
$iterator = $blocks->getIterator();
while ($iterator->valid()) {
$length = $this->getUnformatedLength();
- if (!preg_match("/^[0-9]{2}:[0-9]{2}:[0-9]{2}/", $length)) {
+ if (!preg_match('/^[0-9]{2}:[0-9]{2}:[0-9]{2}/', $length)) {
$iterator->current()->setDbClipLength(null);
} else {
$iterator->current()->setDbClipLength($length);
@@ -1329,20 +1348,16 @@ SQL;
}
}
- /*
- *
- */
-
public function getListOfFilesUnderLimit($show = null)
{
- $info = $this->getListofFilesMeetCriteria($show);
- $files = $info['files'];
- $limit = $info['limit'];
- $repeat = $info['repeat_tracks'];
- $overflow = $info['overflow_tracks'];
+ $info = $this->getListofFilesMeetCriteria($show);
+ $files = $info['files'];
+ $limit = $info['limit'];
+ $repeat = $info['repeat_tracks'];
+ $overflow = $info['overflow_tracks'];
- $insertList = array();
- $totalTime = 0;
+ $insertList = [];
+ $totalTime = 0;
$totalItems = 0;
// this moves the pointer to the first element in the collection
@@ -1352,34 +1367,33 @@ SQL;
$isBlockFull = false;
while ($iterator->valid()) {
-
$id = $iterator->current()->getDbId();
$fileLength = $iterator->current()->getCueLength();
$length = Application_Common_DateHelper::calculateLengthInSeconds($fileLength);
// if the block is setup to allow the overflow of tracks this will add the next track even if it becomes
// longer than the time limit
if ($overflow == 1) {
- $insertList[] = array('id' => $id, 'length' => $length);
+ $insertList[] = ['id' => $id, 'length' => $length];
$totalTime += $length;
- $totalItems++;
- }
+ ++$totalItems;
+ }
// otherwise we need to check to determine if the track will make the playlist exceed the totalTime before
// adding it this could loop through a lot of tracks so I used the totalItems limit to prevent
// the algorithm from parsing too many items.
else {
- $projectedTime = $totalTime + $length;
+ $projectedTime = $totalTime + $length;
if ($projectedTime > $limit['time']) {
- $totalItems++;
- }
- else {
- $insertList[] = array('id' => $id, 'length' => $length);
+ ++$totalItems;
+ } else {
+ $insertList[] = ['id' => $id, 'length' => $length];
$totalTime += $length;
- $totalItems++;
+ ++$totalItems;
}
}
if ((!is_null($limit['items']) && $limit['items'] == count($insertList)) || $totalItems > 500 || $totalTime > $limit['time']) {
$isBlockFull = true;
+
break;
}
@@ -1391,8 +1405,8 @@ SQL;
// if block is not full and repeat_track is check, fill up more
// additionally still don't overflow the limit
while (!$isBlockFull && $repeat == 1 && $sizeOfInsert > 0) {
- Logging::debug("adding repeated tracks.");
- Logging::debug("total time = " . $totalTime);
+ Logging::debug('adding repeated tracks.');
+ Logging::debug('total time = ' . $totalTime);
$randomEleKey = array_rand(array_slice($insertList, 0, $sizeOfInsert));
// this will also allow the overflow of tracks so that time limited smart blocks will schedule until they
@@ -1400,17 +1414,15 @@ SQL;
if ($overflow == 1) {
$insertList[] = $insertList[$randomEleKey];
$totalTime += $insertList[$randomEleKey]['length'];
- $totalItems++;
- }
- else {
+ ++$totalItems;
+ } else {
$projectedTime = $totalTime + $insertList[$randomEleKey]['length'];
if ($projectedTime > $limit['time']) {
- $totalItems++;
- }
- else {
+ ++$totalItems;
+ } else {
$insertList[] = $insertList[$randomEleKey];
$totalTime += $insertList[$randomEleKey]['length'];
- $totalItems++;
+ ++$totalItems;
}
}
@@ -1425,67 +1437,64 @@ SQL;
/**
* Parses each row in the database for the criteria associated with this block and renders human readable labels.
* Returns it as an array with each criteria_name and modifier_name added based upon options array lookup.
- *
*/
-
-
public function getCriteria()
{
- $criteriaOptions = array(
- 0 => _("Select criteria"),
- "album_title" => _("Album"),
- "bit_rate" => _("Bit Rate (Kbps)"),
- "bpm" => _("BPM"),
- "composer" => _("Composer"),
- "conductor" => _("Conductor"),
- "copyright" => _("Copyright"),
- "cuein" => _("Cue In"),
- "cueout" => _("Cue Out"),
- "description" => _("Description"),
- "artist_name" => _("Creator"),
- "encoded_by" => _("Encoded By"),
- "genre" => _("Genre"),
- "isrc_number" => _("ISRC"),
- "label" => _("Label"),
- "language" => _("Language"),
- "utime" => _("Upload Time"),
- "mtime" => _("Last Modified"),
- "lptime" => _("Last Played"),
- "length" => _("Length"),
- "track_type" => _("Track Type"),
- "mime" => _("Mime"),
- "mood" => _("Mood"),
- "owner_id" => _("Owner"),
- "replay_gain" => _("Replay Gain"),
- "sample_rate" => _("Sample Rate (kHz)"),
- "track_title" => _("Title"),
- "track_number" => _("Track Number"),
- "utime" => _("Uploaded"),
- "info_url" => _("Website"),
- "year" => _("Year")
- );
+ $criteriaOptions = [
+ 0 => _('Select criteria'),
+ 'album_title' => _('Album'),
+ 'bit_rate' => _('Bit Rate (Kbps)'),
+ 'bpm' => _('BPM'),
+ 'composer' => _('Composer'),
+ 'conductor' => _('Conductor'),
+ 'copyright' => _('Copyright'),
+ 'cuein' => _('Cue In'),
+ 'cueout' => _('Cue Out'),
+ 'description' => _('Description'),
+ 'artist_name' => _('Creator'),
+ 'encoded_by' => _('Encoded By'),
+ 'genre' => _('Genre'),
+ 'isrc_number' => _('ISRC'),
+ 'label' => _('Label'),
+ 'language' => _('Language'),
+ 'utime' => _('Upload Time'),
+ 'mtime' => _('Last Modified'),
+ 'lptime' => _('Last Played'),
+ 'length' => _('Length'),
+ 'track_type' => _('Track Type'),
+ 'mime' => _('Mime'),
+ 'mood' => _('Mood'),
+ 'owner_id' => _('Owner'),
+ 'replay_gain' => _('Replay Gain'),
+ 'sample_rate' => _('Sample Rate (kHz)'),
+ 'track_title' => _('Title'),
+ 'track_number' => _('Track Number'),
+ 'utime' => _('Uploaded'),
+ 'info_url' => _('Website'),
+ 'year' => _('Year'),
+ ];
- $modifierOptions = array(
- "0" => _("Select modifier"),
- "contains" => _("contains"),
- "does not contain" => _("does not contain"),
- "is" => _("is"),
- "is not" => _("is not"),
- "starts with" => _("starts with"),
- "ends with" => _("ends with"),
- "before" => _("before"),
- "after" => _("after"),
- "between" => _("between"),
- "is" => _("is"),
- "is not" => _("is not"),
- "is greater than" => _("is greater than"),
- "is less than" => _("is less than"),
- "is in the range" => _("is in the range")
- );
+ $modifierOptions = [
+ '0' => _('Select modifier'),
+ 'contains' => _('contains'),
+ 'does not contain' => _('does not contain'),
+ 'is' => _('is'),
+ 'is not' => _('is not'),
+ 'starts with' => _('starts with'),
+ 'ends with' => _('ends with'),
+ 'before' => _('before'),
+ 'after' => _('after'),
+ 'between' => _('between'),
+ 'is' => _('is'),
+ 'is not' => _('is not'),
+ 'is greater than' => _('is greater than'),
+ 'is less than' => _('is less than'),
+ 'is in the range' => _('is in the range'),
+ ];
// Load criteria from db
$out = CcBlockcriteriaQuery::create()->orderByDbCriteria()->findByDbBlockId($this->id);
- $storedCrit = array();
+ $storedCrit = [];
foreach ($out as $crit) {
$criteria = $crit->getDbCriteria();
@@ -1494,98 +1503,94 @@ SQL;
$extra = $crit->getDbExtra();
$criteriagroup = $crit->getDbCriteriaGroup();
- if ($criteria == "limit") {
- $storedCrit["limit"] = array(
- "value"=>$value,
- "modifier"=>$modifier,
- "display_modifier"=>_($modifier));
- } else if($criteria == "repeat_tracks") {
- $storedCrit["repeat_tracks"] = array("value"=>$value);
- } else if($criteria == "overflow_tracks") {
- $storedCrit["overflow_tracks"] = array("value"=>$value);
- } else if($criteria == "sort") {
- $storedCrit["sort"] = array("value"=>$value);
+ if ($criteria == 'limit') {
+ $storedCrit['limit'] = [
+ 'value' => $value,
+ 'modifier' => $modifier,
+ 'display_modifier' => _($modifier), ];
+ } elseif ($criteria == 'repeat_tracks') {
+ $storedCrit['repeat_tracks'] = ['value' => $value];
+ } elseif ($criteria == 'overflow_tracks') {
+ $storedCrit['overflow_tracks'] = ['value' => $value];
+ } elseif ($criteria == 'sort') {
+ $storedCrit['sort'] = ['value' => $value];
} else {
- $storedCrit["crit"][$criteria][] = array(
- "criteria"=>$criteria,
- "value"=>$value,
- "modifier"=>$modifier,
- "extra"=>$extra,
- "criteria_group"=>$criteriagroup,
- "display_name"=>$criteriaOptions[$criteria],
- "display_modifier"=>$modifierOptions[$modifier]);
+ $storedCrit['crit'][$criteria][] = [
+ 'criteria' => $criteria,
+ 'value' => $value,
+ 'modifier' => $modifier,
+ 'extra' => $extra,
+ 'criteria_group' => $criteriagroup,
+ 'display_name' => $criteriaOptions[$criteria],
+ 'display_modifier' => $modifierOptions[$modifier], ];
}
}
return $storedCrit;
-
}
/**
* Parses each row in the database for the criteria associated with this block and renders human readable labels.
* Returns it as an array with each criteria_name and modifier_name added based upon options array lookup.
- * Maintains original separation of similar criteria that were separated by and statements
- *
+ * Maintains original separation of similar criteria that were separated by and statements.
*/
-
-
public function getCriteriaGrouped()
{
- $criteriaOptions = array(
- 0 => _("Select criteria"),
- "album_title" => _("Album"),
- "bit_rate" => _("Bit Rate (Kbps)"),
- "bpm" => _("BPM"),
- "composer" => _("Composer"),
- "conductor" => _("Conductor"),
- "copyright" => _("Copyright"),
- "cuein" => _("Cue In"),
- "cueout" => _("Cue Out"),
- "description" => _("Description"),
- "artist_name" => _("Creator"),
- "encoded_by" => _("Encoded By"),
- "genre" => _("Genre"),
- "isrc_number" => _("ISRC"),
- "label" => _("Label"),
- "language" => _("Language"),
- "utime" => _("Upload Time"),
- "mtime" => _("Last Modified"),
- "lptime" => _("Last Played"),
- "length" => _("Length"),
- "track_type" => _("Track Type"),
- "mime" => _("Mime"),
- "mood" => _("Mood"),
- "owner_id" => _("Owner"),
- "replay_gain" => _("Replay Gain"),
- "sample_rate" => _("Sample Rate (kHz)"),
- "track_title" => _("Title"),
- "track_number" => _("Track Number"),
- "utime" => _("Uploaded"),
- "info_url" => _("Website"),
- "year" => _("Year")
- );
+ $criteriaOptions = [
+ 0 => _('Select criteria'),
+ 'album_title' => _('Album'),
+ 'bit_rate' => _('Bit Rate (Kbps)'),
+ 'bpm' => _('BPM'),
+ 'composer' => _('Composer'),
+ 'conductor' => _('Conductor'),
+ 'copyright' => _('Copyright'),
+ 'cuein' => _('Cue In'),
+ 'cueout' => _('Cue Out'),
+ 'description' => _('Description'),
+ 'artist_name' => _('Creator'),
+ 'encoded_by' => _('Encoded By'),
+ 'genre' => _('Genre'),
+ 'isrc_number' => _('ISRC'),
+ 'label' => _('Label'),
+ 'language' => _('Language'),
+ 'utime' => _('Upload Time'),
+ 'mtime' => _('Last Modified'),
+ 'lptime' => _('Last Played'),
+ 'length' => _('Length'),
+ 'track_type' => _('Track Type'),
+ 'mime' => _('Mime'),
+ 'mood' => _('Mood'),
+ 'owner_id' => _('Owner'),
+ 'replay_gain' => _('Replay Gain'),
+ 'sample_rate' => _('Sample Rate (kHz)'),
+ 'track_title' => _('Title'),
+ 'track_number' => _('Track Number'),
+ 'utime' => _('Uploaded'),
+ 'info_url' => _('Website'),
+ 'year' => _('Year'),
+ ];
- $modifierOptions = array(
- "0" => _("Select modifier"),
- "contains" => _("contains"),
- "does not contain" => _("does not contain"),
- "is" => _("is"),
- "is not" => _("is not"),
- "starts with" => _("starts with"),
- "ends with" => _("ends with"),
- "before" => _("before"),
- "after" => _("after"),
- "between" => _("between"),
- "is" => _("is"),
- "is not" => _("is not"),
- "is greater than" => _("is greater than"),
- "is less than" => _("is less than"),
- "is in the range" => _("is in the range")
- );
+ $modifierOptions = [
+ '0' => _('Select modifier'),
+ 'contains' => _('contains'),
+ 'does not contain' => _('does not contain'),
+ 'is' => _('is'),
+ 'is not' => _('is not'),
+ 'starts with' => _('starts with'),
+ 'ends with' => _('ends with'),
+ 'before' => _('before'),
+ 'after' => _('after'),
+ 'between' => _('between'),
+ 'is' => _('is'),
+ 'is not' => _('is not'),
+ 'is greater than' => _('is greater than'),
+ 'is less than' => _('is less than'),
+ 'is in the range' => _('is in the range'),
+ ];
// Load criteria from db
$out = CcBlockcriteriaQuery::create()->orderByDbCriteria()->findByDbBlockId($this->id);
- $storedCrit = array();
+ $storedCrit = [];
foreach ($out as $crit) {
$criteria = $crit->getDbCriteria();
@@ -1594,48 +1599,47 @@ SQL;
$extra = $crit->getDbExtra();
$criteriagroup = $crit->getDbCriteriaGroup();
- if ($criteria == "limit") {
- $storedCrit["limit"] = array(
- "value"=>$value,
- "modifier"=>$modifier,
- "display_modifier"=>_($modifier));
- } else if($criteria == "repeat_tracks") {
- $storedCrit["repeat_tracks"] = array("value"=>$value);
- } else if($criteria == "overflow_tracks") {
- $storedCrit["overflow_tracks"] = array("value"=>$value);
- } else if($criteria == "sort") {
- $storedCrit["sort"] = array("value"=>$value);
+ if ($criteria == 'limit') {
+ $storedCrit['limit'] = [
+ 'value' => $value,
+ 'modifier' => $modifier,
+ 'display_modifier' => _($modifier), ];
+ } elseif ($criteria == 'repeat_tracks') {
+ $storedCrit['repeat_tracks'] = ['value' => $value];
+ } elseif ($criteria == 'overflow_tracks') {
+ $storedCrit['overflow_tracks'] = ['value' => $value];
+ } elseif ($criteria == 'sort') {
+ $storedCrit['sort'] = ['value' => $value];
} else {
- $storedCrit["crit"][$criteria . $criteriagroup][] = array(
- "criteria"=>$criteria,
- "value"=>$value,
- "modifier"=>$modifier,
- "extra"=>$extra,
- "display_name"=>$criteriaOptions[$criteria],
- "display_modifier"=>$modifierOptions[$modifier]);
+ $storedCrit['crit'][$criteria . $criteriagroup][] = [
+ 'criteria' => $criteria,
+ 'value' => $value,
+ 'modifier' => $modifier,
+ 'extra' => $extra,
+ 'display_name' => $criteriaOptions[$criteria],
+ 'display_modifier' => $modifierOptions[$modifier], ];
}
}
+
return $storedCrit;
-
}
-
// this function return list of propel object
public function getListofFilesMeetCriteria($showLimit = null)
{
$storedCrit = $this->getCriteria();
$qry = CcFilesQuery::create();
- $qry->useFkOwnerQuery("subj", "left join");
+ $qry->useFkOwnerQuery('subj', 'left join');
//Logging::info($storedCrit);
- if (isset($storedCrit["crit"])) {
- foreach ($storedCrit["crit"] as $crit) {
+ if (isset($storedCrit['crit'])) {
+ foreach ($storedCrit['crit'] as $crit) {
$i = 0;
$prevgroup = null;
$group = null;
// now we need to sort based upon extra which contains the and grouping from the form
- usort($crit, function($a, $b) {
+ usort($crit, function ($a, $b) {
return $a['criteria_group'] - $b['criteria_group'];
});
// we need to run the following loop separately for each criteria group inside of each array
@@ -1648,28 +1652,27 @@ SQL;
//data should already be in UTC, do we have to do anything special here anymore?
if ($column->getType() == PropelColumnTypes::TIMESTAMP) {
-
$spCriteriaValue = $criteria['value'];
if (isset($criteria['extra'])) {
$spCriteriaExtra = $criteria['extra'];
}
- } elseif ($spCriteria == "bit_rate" || $spCriteria == 'sample_rate') {
+ } elseif ($spCriteria == 'bit_rate' || $spCriteria == 'sample_rate') {
// multiply 1000 because we store only number value
// e.g 192kps is stored as 192000
$spCriteriaValue = $criteria['value'] * 1000;
if (isset($criteria['extra'])) {
$spCriteriaExtra = $criteria['extra'] * 1000;
}
- /*
- * If user is searching for an exact match of length we need to
- * search as if it starts with the specified length because the
- * user only sees the rounded version (i.e. 4:02.7 is 4:02.761625
- * in the database)
- */
- } elseif (in_array($spCriteria, array('length', 'cuein', 'cueout')) && $spCriteriaModifier == "is") {
- $spCriteriaModifier = "starts with";
- $spCriteria = $spCriteria.'::text';
+ /*
+ * If user is searching for an exact match of length we need to
+ * search as if it starts with the specified length because the
+ * user only sees the rounded version (i.e. 4:02.7 is 4:02.761625
+ * in the database)
+ */
+ } elseif (in_array($spCriteria, ['length', 'cuein', 'cueout']) && $spCriteriaModifier == 'is') {
+ $spCriteriaModifier = 'starts with';
+ $spCriteria = $spCriteria . '::text';
$spCriteriaValue = $criteria['value'];
} else {
/* Propel does not escape special characters properly when using LIKE/ILIKE
@@ -1686,28 +1689,26 @@ SQL;
$spCriteriaExtra = $criteria['extra'];
}
- if ($spCriteriaModifier == "starts with") {
- $spCriteriaValue = "$spCriteriaValue%";
- } elseif ($spCriteriaModifier == "ends with") {
- $spCriteriaValue = "%$spCriteriaValue";
- } elseif ($spCriteriaModifier == "contains" || $spCriteriaModifier == "does not contain") {
- $spCriteriaValue = "%$spCriteriaValue%";
- } elseif ($spCriteriaModifier == "is in the range") {
- $spCriteriaValue = "$spCriteria >= '$spCriteriaValue' AND $spCriteria <= '$spCriteriaExtra'";
- }
- elseif ($spCriteriaModifier == "before") {
+ if ($spCriteriaModifier == 'starts with') {
+ $spCriteriaValue = "{$spCriteriaValue}%";
+ } elseif ($spCriteriaModifier == 'ends with') {
+ $spCriteriaValue = "%{$spCriteriaValue}";
+ } elseif ($spCriteriaModifier == 'contains' || $spCriteriaModifier == 'does not contain') {
+ $spCriteriaValue = "%{$spCriteriaValue}%";
+ } elseif ($spCriteriaModifier == 'is in the range') {
+ $spCriteriaValue = "{$spCriteria} >= '{$spCriteriaValue}' AND {$spCriteria} <= '{$spCriteriaExtra}'";
+ } elseif ($spCriteriaModifier == 'before') {
// need to pull in the current time and subtract the value or figure out how to make it relative
$relativedate = new DateTime($spCriteriaValue);
$dt = $relativedate->format(DateTime::ISO8601);
- $spCriteriaValue = "$spCriteria <= '$dt'";
- // Logging::info($spCriteriaValue);
- }
- elseif ($spCriteriaModifier == "after") {
+ $spCriteriaValue = "{$spCriteria} <= '{$dt}'";
+ // Logging::info($spCriteriaValue);
+ } elseif ($spCriteriaModifier == 'after') {
$relativedate = new DateTime($spCriteriaValue);
$dt = $relativedate->format(DateTime::ISO8601);
- $spCriteriaValue = "$spCriteria >= '$dt'";
- // Logging::info($spCriteriaValue);
- } elseif ($spCriteriaModifier == "between") {
+ $spCriteriaValue = "{$spCriteria} >= '{$dt}'";
+ // Logging::info($spCriteriaValue);
+ } elseif ($spCriteriaModifier == 'between') {
$fromrelativedate = new DateTime($spCriteriaValue);
$fdt = $fromrelativedate->format(DateTime::ISO8601);
// Logging::info($fdt);
@@ -1715,19 +1716,19 @@ SQL;
$torelativedate = new DateTime($spCriteriaExtra);
$tdt = $torelativedate->format(DateTime::ISO8601);
// Logging::info($tdt);
- $spCriteriaValue = "$spCriteria >= '$fdt' AND $spCriteria <= '$tdt'";
+ $spCriteriaValue = "{$spCriteria} >= '{$fdt}' AND {$spCriteria} <= '{$tdt}'";
}
- // logging::info('before');
- // logging::info($spCriteriaModifier);
+ // logging::info('before');
+ // logging::info($spCriteriaModifier);
$spCriteriaModifier = self::$modifier2CriteriaMap[$spCriteriaModifier];
- // logging::info('after');
- // logging::info($spCriteriaModifier);
+ // logging::info('after');
+ // logging::info($spCriteriaModifier);
try {
- if ($spCriteria == "owner_id") {
- $spCriteria = "subj.login";
+ if ($spCriteria == 'owner_id') {
+ $spCriteria = 'subj.login';
}
if ($i > 0 && $prevgroup == $group) {
$qry->addOr($spCriteria, $spCriteriaValue, $spCriteriaModifier);
@@ -1736,22 +1737,22 @@ SQL;
}
// only add this NOT LIKE null if you aren't also matching on another criteria
if ($i == 0) {
- if ($spCriteriaModifier == Criteria::NOT_ILIKE || $spCriteriaModifier == Criteria::NOT_EQUAL) {
- $qry->addOr($spCriteria, null, Criteria::ISNULL);
- }
+ if ($spCriteriaModifier == Criteria::NOT_ILIKE || $spCriteriaModifier == Criteria::NOT_EQUAL) {
+ $qry->addOr($spCriteria, null, Criteria::ISNULL);
+ }
}
} catch (Exception $e) {
Logging::info($e);
}
$prevgroup = $group;
- $i++;
+ ++$i;
}
}
}
// check if file exists
- $qry->add("file_exists", "true", Criteria::EQUAL);
- $qry->add("hidden", "false", Criteria::EQUAL);
+ $qry->add('file_exists', 'true', Criteria::EQUAL);
+ $qry->add('hidden', 'false', Criteria::EQUAL);
$sortTracks = 'random';
if (isset($storedCrit['sort'])) {
@@ -1759,41 +1760,37 @@ SQL;
}
if ($sortTracks == 'newest') {
$qry->addDescendingOrderByColumn('utime');
- }
- else if ($sortTracks == 'oldest') {
+ } elseif ($sortTracks == 'oldest') {
$qry->addAscendingOrderByColumn('utime');
}
// these sort additions are needed to override the default postgres NULL sort behavior
- else if ($sortTracks == 'mostrecentplay') {
+ elseif ($sortTracks == 'mostrecentplay') {
$qry->addDescendingOrderByColumn('(lptime IS NULL), lptime');
- }
- else if ($sortTracks == 'leastrecentplay') {
+ } elseif ($sortTracks == 'leastrecentplay') {
$qry->addAscendingOrderByColumn('(lptime IS NOT NULL), lptime');
- }
- else if ($sortTracks == 'random') {
+ } elseif ($sortTracks == 'random') {
$qry->addAscendingOrderByColumn('random()');
} else {
- Logging::warning("Unimplemented sortTracks type in ".__FILE__);
+ Logging::warning('Unimplemented sortTracks type in ' . __FILE__);
}
// construct limit restriction
- $limits = array();
+ $limits = [];
if (isset($storedCrit['limit'])) {
- if ($storedCrit['limit']['modifier'] == "items") {
+ if ($storedCrit['limit']['modifier'] == 'items') {
$limits['time'] = 1440 * 60;
$limits['items'] = $storedCrit['limit']['value'];
- } elseif (($storedCrit['limit']['modifier'] == "remaining") ){
+ } elseif (($storedCrit['limit']['modifier'] == 'remaining')) {
// show will be null unless being called inside a show instance
if (!(is_null($showLimit))) {
$limits['time'] = $showLimit;
$limits['items'] = null;
- }
- else {
+ } else {
$limits['time'] = 60 * 60;
$limits['items'] = null;
}
} else {
- $limits['time'] = $storedCrit['limit']['modifier'] == "hours" ?
+ $limits['time'] = $storedCrit['limit']['modifier'] == 'hours' ?
intval(floatval($storedCrit['limit']['value']) * 60 * 60) :
intval($storedCrit['limit']['value'] * 60);
$limits['items'] = null;
@@ -1811,21 +1808,20 @@ SQL;
$overflowTracks = $storedCrit['overflow_tracks']['value'];
}
-
try {
$out = $qry->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)->find();
- return array("files"=>$out, "limit"=>$limits, "repeat_tracks"=> $repeatTracks, "overflow_tracks"=> $overflowTracks, "count"=>$out->count());
+
+ return ['files' => $out, 'limit' => $limits, 'repeat_tracks' => $repeatTracks, 'overflow_tracks' => $overflowTracks, 'count' => $out->count()];
} catch (Exception $e) {
Logging::info($e);
}
-
}
+
public static function organizeSmartPlaylistCriteria($p_criteria)
{
- $fieldNames = array('sp_criteria_field', 'sp_criteria_modifier', 'sp_criteria_value', 'sp_criteria_extra', 'sp_criteria_datetime_select', 'sp_criteria_extra_datetime_select');
- $output = array();
+ $fieldNames = ['sp_criteria_field', 'sp_criteria_modifier', 'sp_criteria_value', 'sp_criteria_extra', 'sp_criteria_datetime_select', 'sp_criteria_extra_datetime_select'];
+ $output = [];
foreach ($p_criteria as $ele) {
-
$index = strrpos($ele['name'], '_');
/* Strip field name of modifier index
@@ -1844,7 +1840,7 @@ SQL;
$lastChar = substr($ele['name'], -1);
// If lastChar is an integer we should strip it off
- if (!preg_match("/^[a-zA-Z]$/", $lastChar)) {
+ if (!preg_match('/^[a-zA-Z]$/', $lastChar)) {
/* Strip field name of criteria index
* Ex: sp_criteria_field_0 -> sp_criteria_field
* We do this to check if the field name is a criteria
@@ -1860,27 +1856,38 @@ SQL;
$output['etc'][$ele['name']] = $ele['value'];
}
}
+
return $output;
}
+
public static function getAllBlockFiles()
{
- $sql = <<$row[0]["artist_name"]." - ".$row[0]["track_title"],
- "starts"=>$row[0]["starts"],
- "ends"=>$row[0]["ends"]);
+ }
- }
- } else {
- if (count($row) == 0) {
- if ($showInstance->isRecorded()) {
- //last item is a show instance
- return array("name"=>$showInstance->getName(),
- "starts"=>$showInstance->getShowInstanceStart(),
- "ends"=>$showInstance->getShowInstanceEnd());
- } else {
- return null;
- }
- } else {
- //return the one that started later.
- if ($row[0]["starts"] >= $showInstance->getShowInstanceStart()) {
- return array("name"=>$row[0]["artist_name"]." - ".$row[0]["track_title"],
- "starts"=>$row[0]["starts"],
- "ends"=>$row[0]["ends"]);
- } else {
- return array("name"=>$showInstance->getName(),
- "starts"=>$showInstance->getShowInstanceStart(),
- "ends"=>$showInstance->getShowInstanceEnd());
- }
- }
+ return ['name' => $row[0]['artist_name'] . ' - ' . $row[0]['track_title'],
+ 'starts' => $row[0]['starts'],
+ 'ends' => $row[0]['ends'], ];
}
+ if (count($row) == 0) {
+ if ($showInstance->isRecorded()) {
+ //last item is a show instance
+ return ['name' => $showInstance->getName(),
+ 'starts' => $showInstance->getShowInstanceStart(),
+ 'ends' => $showInstance->getShowInstanceEnd(), ];
+ }
+
+ return null;
+ }
+ //return the one that started later.
+ if ($row[0]['starts'] >= $showInstance->getShowInstanceStart()) {
+ return ['name' => $row[0]['artist_name'] . ' - ' . $row[0]['track_title'],
+ 'starts' => $row[0]['starts'],
+ 'ends' => $row[0]['ends'], ];
+ }
+
+ return ['name' => $showInstance->getName(),
+ 'starts' => $showInstance->getShowInstanceStart(),
+ 'ends' => $showInstance->getShowInstanceEnd(), ];
}
public static function GetCurrentItem($p_timeNow)
@@ -54,7 +50,7 @@ class Application_Model_Dashboard
//after the last item in the schedule table, then return the show's
//name. Else return the last item from the schedule.
- $row = array();
+ $row = [];
$showInstance = Application_Model_ShowInstance::GetCurrentShowInstance($p_timeNow);
if (!is_null($showInstance)) {
$instanceId = $showInstance->getShowInstanceId();
@@ -63,38 +59,36 @@ class Application_Model_Dashboard
if (is_null($showInstance)) {
if (count($row) == 0) {
return null;
- } else {
- /* Should never reach here, but lets return the track information
- * just in case we allow tracks to be scheduled without a show
- * in the future.
- */
+ }
+ /* Should never reach here, but lets return the track information
+ * just in case we allow tracks to be scheduled without a show
+ * in the future.
+ */
- return array("name"=>$row[0]["artist_name"]." - ".$row[0]["track_title"],
- "artwork_data"=>$row[0]["artwork_data"],
- "starts"=>$row[0]["starts"],
- "ends"=>$row[0]["ends"]);
- }
- } else {
- if (count($row) == 0) {
- //last item is a show instance
- if ($showInstance->isRecorded()) {
- return array("name"=>$showInstance->getName(),
- "starts"=>$showInstance->getShowInstanceStart(),
- "ends"=>$showInstance->getShowInstanceEnd(),
- "media_item_played"=>false,
- "record"=>true);
- } else {
- return null;
- }
- } else {
- return array("name"=>$row[0]["artist_name"]." - ".$row[0]["track_title"],
- "artwork_data"=>$row[0]["artwork_data"],
- "starts"=>$row[0]["starts"],
- "ends"=>$row[0]["ends"],
- "media_item_played"=>$row[0]["media_item_played"],
- "record"=>0);
- }
+ return ['name' => $row[0]['artist_name'] . ' - ' . $row[0]['track_title'],
+ 'artwork_data' => $row[0]['artwork_data'],
+ 'starts' => $row[0]['starts'],
+ 'ends' => $row[0]['ends'], ];
}
+ if (count($row) == 0) {
+ //last item is a show instance
+ if ($showInstance->isRecorded()) {
+ return ['name' => $showInstance->getName(),
+ 'starts' => $showInstance->getShowInstanceStart(),
+ 'ends' => $showInstance->getShowInstanceEnd(),
+ 'media_item_played' => false,
+ 'record' => true, ];
+ }
+
+ return null;
+ }
+
+ return ['name' => $row[0]['artist_name'] . ' - ' . $row[0]['track_title'],
+ 'artwork_data' => $row[0]['artwork_data'],
+ 'starts' => $row[0]['starts'],
+ 'ends' => $row[0]['ends'],
+ 'media_item_played' => $row[0]['media_item_played'],
+ 'record' => 0, ];
}
public static function GetNextItem($p_timeNow)
@@ -110,37 +104,34 @@ class Application_Model_Dashboard
if (is_null($showInstance)) {
if (count($row) == 0) {
return null;
- } else {
- return array("name"=>$row[0]["artist_name"]." - ".$row[0]["track_title"],
- "artwork_data"=>$row[0]["artwork_data"],
- "starts"=>$row[0]["starts"],
- "ends"=>$row[0]["ends"]);
}
- } else {
- if (count($row) == 0) {
- if ($showInstance->isRecorded()) {
- //last item is a show instance
- return array("name"=>$showInstance->getName(),
- "starts"=>$showInstance->getShowInstanceStart(),
- "ends"=>$showInstance->getShowInstanceEnd());
- } else {
- return null;
- }
- } else {
- //return the one that starts sooner.
- if ($row[0]["starts"] <= $showInstance->getShowInstanceStart()) {
- return array("name"=>$row[0]["artist_name"]." - ".$row[0]["track_title"],
- "artwork_data"=>$row[0]["artwork_data"],
- "starts"=>$row[0]["starts"],
- "ends"=>$row[0]["ends"]);
- } else {
- return array("name"=>$showInstance->getName(),
- "starts"=>$showInstance->getShowInstanceStart(),
- "ends"=>$showInstance->getShowInstanceEnd());
- }
- }
+ return ['name' => $row[0]['artist_name'] . ' - ' . $row[0]['track_title'],
+ 'artwork_data' => $row[0]['artwork_data'],
+ 'starts' => $row[0]['starts'],
+ 'ends' => $row[0]['ends'], ];
}
- }
+ if (count($row) == 0) {
+ if ($showInstance->isRecorded()) {
+ //last item is a show instance
+ return ['name' => $showInstance->getName(),
+ 'starts' => $showInstance->getShowInstanceStart(),
+ 'ends' => $showInstance->getShowInstanceEnd(), ];
+ }
+ return null;
+ }
+ //return the one that starts sooner.
+
+ if ($row[0]['starts'] <= $showInstance->getShowInstanceStart()) {
+ return ['name' => $row[0]['artist_name'] . ' - ' . $row[0]['track_title'],
+ 'artwork_data' => $row[0]['artwork_data'],
+ 'starts' => $row[0]['starts'],
+ 'ends' => $row[0]['ends'], ];
+ }
+
+ return ['name' => $showInstance->getName(),
+ 'starts' => $showInstance->getShowInstanceStart(),
+ 'ends' => $showInstance->getShowInstanceEnd(), ];
+ }
}
diff --git a/legacy/application/models/Datatables.php b/legacy/application/models/Datatables.php
index b966269ae..b08610915 100644
--- a/legacy/application/models/Datatables.php
+++ b/legacy/application/models/Datatables.php
@@ -4,29 +4,27 @@ class Application_Model_Datatables
{
private static function buildWhereClauseForAdvancedSearch($dbname2searchTerm)
{
- $where = array();
- $where['clause'] = array();
- $where['params'] = array();
- foreach ($dbname2searchTerm as $dbname=>$term) {
+ $where = [];
+ $where['clause'] = [];
+ $where['params'] = [];
+ foreach ($dbname2searchTerm as $dbname => $term) {
$isRange = false;
if (strstr($term, '~')) {
$info = explode('~', $term);
if ($dbname == 'utime' || $dbname == 'mtime' || $dbname == 'lptime') {
-
try {
- $input1 = ($info[0] != "") ? Application_Common_DateHelper::UserTimezoneStringToUTCString($info[0]) : null;
- $input2 = ($info[1] != "") ? Application_Common_DateHelper::UserTimezoneStringToUTCString($info[1]) : null;
+ $input1 = ($info[0] != '') ? Application_Common_DateHelper::UserTimezoneStringToUTCString($info[0]) : null;
+ $input2 = ($info[1] != '') ? Application_Common_DateHelper::UserTimezoneStringToUTCString($info[1]) : null;
} catch (Exception $e) {
$input1 = null;
$input2 = null;
}
-
- } else if($dbname == 'bit_rate' || $dbname == 'sample_rate') {
- $input1 = isset($info[0])?doubleval($info[0]) * 1000:null;
- $input2 = isset($info[1])?doubleval($info[1]) * 1000:null;
+ } elseif ($dbname == 'bit_rate' || $dbname == 'sample_rate') {
+ $input1 = isset($info[0]) ? doubleval($info[0]) * 1000 : null;
+ $input2 = isset($info[1]) ? doubleval($info[1]) * 1000 : null;
} else {
- $input1 = isset($info[0])?$info[0]:null;
- $input2 = isset($info[1])?$info[1]:null;
+ $input1 = isset($info[0]) ? $info[0] : null;
+ $input2 = isset($info[1]) ? $info[1] : null;
}
$isRange = true;
} else {
@@ -34,156 +32,153 @@ class Application_Model_Datatables
}
if ($isRange) {
- $sub = array();
+ $sub = [];
if ($input1 != null) {
- $sub[] = $dbname." >= :" . $dbname . "1";
+ $sub[] = $dbname . ' >= :' . $dbname . '1';
}
if ($input2 != null) {
- $sub[] = $dbname." <= :" . $dbname . "2";
+ $sub[] = $dbname . ' <= :' . $dbname . '2';
}
if (!empty($sub)) {
- $where['clause'][$dbname] = "(".implode(' AND ', $sub).")";
+ $where['clause'][$dbname] = '(' . implode(' AND ', $sub) . ')';
if ($input1 != null) {
- $where['params'][$dbname."1"] = $input1;
+ $where['params'][$dbname . '1'] = $input1;
}
if ($input2 != null) {
- $where['params'][$dbname."2"] = $input2;
+ $where['params'][$dbname . '2'] = $input2;
}
}
} else {
- if (trim($input1) !== "") {
- $where['clause'][$dbname] = $dbname." ILIKE :" . $dbname."1";
- $where['params'][$dbname."1"] = "%".$input1."%";
+ if (trim($input1) !== '') {
+ $where['clause'][$dbname] = $dbname . ' ILIKE :' . $dbname . '1';
+ $where['params'][$dbname . '1'] = '%' . $input1 . '%';
}
}
}
return $where;
}
- /*
- * query used to return data for a paginated/searchable datatable.
- */
- public static function findEntries($con, $displayColumns, $fromTable,
- $data, $dataProp = "aaData")
- {
- $where = array();
+ // query used to return data for a paginated/searchable datatable.
+ public static function findEntries(
+ $con,
+ $displayColumns,
+ $fromTable,
+ $data,
+ $dataProp = 'aaData'
+ ) {
+ $where = [];
/* Holds the parameters for binding after the statement has been
prepared */
- $params = array();
+ $params = [];
if (isset($data['advSearch']) && $data['advSearch'] === 'true') {
-
$librarySetting = Application_Model_Preference::getCurrentLibraryTableColumnMap();
//$displayColumns[] = 'owner';
// map that maps original column position to db name
- $current2dbname = array();
+ $current2dbname = [];
// array of search terms
- $orig2searchTerm = array();
+ $orig2searchTerm = [];
foreach ($data as $key => $d) {
- if (strstr($key, "mDataProp_")) {
- list($dump, $index) = explode("_", $key);
+ if (strstr($key, 'mDataProp_')) {
+ list($dump, $index) = explode('_', $key);
$current2dbname[$index] = $d;
- } elseif (strstr($key, "sSearch_")) {
- list($dump, $index) = explode("_", $key);
+ } elseif (strstr($key, 'sSearch_')) {
+ list($dump, $index) = explode('_', $key);
$orig2searchTerm[$index] = $d;
}
}
// map that maps dbname to searchTerm
- $dbname2searchTerm = array();
+ $dbname2searchTerm = [];
foreach ($current2dbname as $currentPos => $dbname) {
$new_index = $librarySetting($currentPos);
// TODO : Fix this retarded hack later. Just a band aid for
// now at least we print some warnings so that we don't
// forget about this -- cc-4462
- if ( array_key_exists($new_index, $orig2searchTerm) ) {
+ if (array_key_exists($new_index, $orig2searchTerm)) {
$dbname2searchTerm[$dbname] = $orig2searchTerm[$new_index];
} else {
- Logging::warn("Trying to reorder to unknown index
- printing as much debugging as possible...");
- $debug = array(
- '$new_index' => $new_index,
- '$currentPos' => $currentPos,
- '$orig2searchTerm' => $orig2searchTerm);
+ Logging::warn('Trying to reorder to unknown index
+ printing as much debugging as possible...');
+ $debug = [
+ '$new_index' => $new_index,
+ '$currentPos' => $currentPos,
+ '$orig2searchTerm' => $orig2searchTerm, ];
Logging::warn($debug);
}
}
$advancedWhere = self::buildWhereClauseForAdvancedSearch($dbname2searchTerm);
if (!empty($advancedWhere['clause'])) {
- $where[] = join(" AND ", $advancedWhere['clause']);
+ $where[] = join(' AND ', $advancedWhere['clause']);
$params = $advancedWhere['params'];
}
}
- if ($data["sSearch"] !== "") {
- $searchTerms = explode(" ", $data["sSearch"]);
+ if ($data['sSearch'] !== '') {
+ $searchTerms = explode(' ', $data['sSearch']);
}
- $selectorCount = "SELECT COUNT(*) ";
- $selectorRows = "SELECT ".join(",", $displayColumns)." ";
+ $selectorCount = 'SELECT COUNT(*) ';
+ $selectorRows = 'SELECT ' . join(',', $displayColumns) . ' ';
- $sql = $selectorCount." FROM ".$fromTable;
+ $sql = $selectorCount . ' FROM ' . $fromTable;
$sqlTotalRows = $sql;
if (isset($searchTerms)) {
- $searchCols = array();
- for ($i = 0; $i < $data["iColumns"]; $i++) {
- if ($data["bSearchable_".$i] == "true") {
+ $searchCols = [];
+ for ($i = 0; $i < $data['iColumns']; ++$i) {
+ if ($data['bSearchable_' . $i] == 'true') {
$searchCols[] = $data["mDataProp_{$i}"];
}
}
- $outerCond = array();
- $simpleWhere = array();
+ $outerCond = [];
+ $simpleWhere = [];
foreach ($searchTerms as $term) {
-
foreach ($searchCols as $col) {
- $simpleWhere['clause']["simple_".$col] = "{$col}::text ILIKE :simple_".$col;
- $simpleWhere['params']["simple_".$col] = "%".$term."%";
+ $simpleWhere['clause']['simple_' . $col] = "{$col}::text ILIKE :simple_" . $col;
+ $simpleWhere['params']['simple_' . $col] = '%' . $term . '%';
}
- $outerCond[] = "(".implode(" OR ", $simpleWhere['clause']).")";
+ $outerCond[] = '(' . implode(' OR ', $simpleWhere['clause']) . ')';
}
- $where[] = "(" .implode(" AND ", $outerCond). ")";
+ $where[] = '(' . implode(' AND ', $outerCond) . ')';
$params = array_merge($params, $simpleWhere['params']);
}
// End Where clause
// Order By clause
- $orderby = array();
- for ($i = 0; $i < $data["iSortingCols"]; $i++) {
- $num = $data["iSortCol_".$i];
- $orderby[] = $data["mDataProp_{$num}"]." ".$data["sSortDir_".$i];
+ $orderby = [];
+ for ($i = 0; $i < $data['iSortingCols']; ++$i) {
+ $num = $data['iSortCol_' . $i];
+ $orderby[] = $data["mDataProp_{$num}"] . ' ' . $data['sSortDir_' . $i];
}
- $orderby[] = "id";
- $orderby = join("," , $orderby);
+ $orderby[] = 'id';
+ $orderby = join(',', $orderby);
// End Order By clause
- $displayLength = intval($data["iDisplayLength"]);
+ $displayLength = intval($data['iDisplayLength']);
$needToBind = false;
if (count($where) > 0) {
$needToBind = true;
- $where = join(" OR ", $where);
- $sql = $selectorCount." FROM ".$fromTable." WHERE ".$where;
+ $where = join(' OR ', $where);
+ $sql = $selectorCount . ' FROM ' . $fromTable . ' WHERE ' . $where;
$sqlTotalDisplayRows = $sql;
- $sql = $selectorRows." FROM ".$fromTable." WHERE ".$where." ORDER BY ".$orderby;
-
- }
- else {
- $sql = $selectorRows." FROM ".$fromTable." ORDER BY ".$orderby;
+ $sql = $selectorRows . ' FROM ' . $fromTable . ' WHERE ' . $where . ' ORDER BY ' . $orderby;
+ } else {
+ $sql = $selectorRows . ' FROM ' . $fromTable . ' ORDER BY ' . $orderby;
}
//limit the results returned.
if ($displayLength !== -1) {
- $sql .= " OFFSET ".$data["iDisplayStart"]." LIMIT ".$displayLength;
+ $sql .= ' OFFSET ' . $data['iDisplayStart'] . ' LIMIT ' . $displayLength;
}
try {
-
//Logging::info($sqlTotalRows);
$r = $con->query($sqlTotalRows);
@@ -193,8 +188,7 @@ class Application_Model_Datatables
//Logging::info("sql is set");
//Logging::info($sqlTotalDisplayRows);
$totalDisplayRows = Application_Common_Database::prepareAndExecute($sqlTotalDisplayRows, $params, 'column');
- }
- else {
+ } else {
//Logging::info("sql is not set.");
$totalDisplayRows = $totalRows;
}
@@ -202,22 +196,20 @@ class Application_Model_Datatables
//TODO
if ($needToBind) {
$results = Application_Common_Database::prepareAndExecute($sql, $params);
- }
- else {
+ } else {
$stmt = $con->query($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$results = $stmt->fetchAll();
}
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
Logging::info($e->getMessage());
}
- return array(
- "sEcho" => intval($data["sEcho"]),
- "iTotalDisplayRecords" => intval($totalDisplayRows),
- "iTotalRecords" => intval($totalRows),
- $dataProp => $results
- );
+ return [
+ 'sEcho' => intval($data['sEcho']),
+ 'iTotalDisplayRecords' => intval($totalDisplayRows),
+ 'iTotalRecords' => intval($totalRows),
+ $dataProp => $results,
+ ];
}
}
diff --git a/legacy/application/models/Email.php b/legacy/application/models/Email.php
index 65cccd771..a019e6094 100644
--- a/legacy/application/models/Email.php
+++ b/legacy/application/models/Email.php
@@ -2,20 +2,19 @@
class Application_Model_Email
{
-
/**
- * Send email
+ * Send email.
*
- * @param string $subject
- * @param string $message
- * @param mixed $to
- * @return boolean
+ * @param string $subject
+ * @param string $message
+ * @param mixed $to
+ *
+ * @return bool
*/
- public static function send($subject, $message, $to) {
-
+ public static function send($subject, $message, $to)
+ {
$headers = sprintf('From: %s <%s>', SAAS_PRODUCT_BRANDING_NAME, LIBRETIME_EMAIL_FROM);
+
return mail($to, $subject, $message, $headers);
-
}
-
}
diff --git a/legacy/application/models/FreeIpa.php b/legacy/application/models/FreeIpa.php
index 01937cb48..9efa82b8f 100644
--- a/legacy/application/models/FreeIpa.php
+++ b/legacy/application/models/FreeIpa.php
@@ -1,9 +1,11 @@
getFirst();
- $groupMap = array(
- UTYPE_GUEST => $config['ldap_groupmap_guest'],
- UTYPE_HOST => $config['ldap_groupmap_host'],
+ $groupMap = [
+ UTYPE_GUEST => $config['ldap_groupmap_guest'],
+ UTYPE_HOST => $config['ldap_groupmap_host'],
UTYPE_PROGRAM_MANAGER => $config['ldap_groupmap_program_manager'],
- UTYPE_ADMIN => $config['ldap_groupmap_admin'],
- UTYPE_SUPERADMIN => $config['ldap_groupmap_superadmin'],
- );
+ UTYPE_ADMIN => $config['ldap_groupmap_admin'],
+ UTYPE_SUPERADMIN => $config['ldap_groupmap_superadmin'],
+ ];
$type = UTYPE_GUEST;
foreach ($groupMap as $groupType => $group) {
if (in_array($group, $ldapUser['memberof'])) {
@@ -39,36 +41,37 @@ class LibreTime_Model_FreeIpa {
$mail = $ldapUser['mail'][0];
// return full user info for auth adapter
- return array(
- 'type' => $type,
+ return [
+ 'type' => $type,
'first_name' => $firstName,
- 'last_name' => $lastName,
- 'email' => $mail,
- 'cell_phone' => '', # empty since I did not find it in ldap
- 'skype' => '', # empty until we decide on a field
- 'jabber' => '' # empty until we decide on a field
- );
+ 'last_name' => $lastName,
+ 'email' => $mail,
+ 'cell_phone' => '', // empty since I did not find it in ldap
+ 'skype' => '', // empty until we decide on a field
+ 'jabber' => '', // empty until we decide on a field
+ ];
}
/**
- * Bind to ldap so we can fetch additional user info
+ * Bind to ldap so we can fetch additional user info.
*
* @return Zend_Ldap
*/
private static function _getLdapConnection()
{
$config = Config::getConfig();
-
- $options = array(
- 'host' => $config['ldap_hostname'],
- 'username' => $config['ldap_binddn'],
- 'password' => $config['ldap_password'],
- 'bindRequiresDn' => true,
+
+ $options = [
+ 'host' => $config['ldap_hostname'],
+ 'username' => $config['ldap_binddn'],
+ 'password' => $config['ldap_password'],
+ 'bindRequiresDn' => true,
'accountDomainName' => $config['ldap_account_domain'],
- 'baseDn' => $config['ldap_basedn']
- );
+ 'baseDn' => $config['ldap_basedn'],
+ ];
$conn = new Zend_Ldap($options);
$conn->connect();
+
return $conn;
}
}
diff --git a/legacy/application/models/Library.php b/legacy/application/models/Library.php
index 6f4c36a30..56adb9679 100644
--- a/legacy/application/models/Library.php
+++ b/legacy/application/models/Library.php
@@ -2,19 +2,18 @@
class Application_Model_Library
{
-
public static function getObjInfo($p_type)
{
- $info = array();
+ $info = [];
- if (strcmp($p_type, 'playlist')==0) {
+ if (strcmp($p_type, 'playlist') == 0) {
$info['className'] = 'Application_Model_Playlist';
- } elseif (strcmp($p_type, 'block')==0) {
+ } elseif (strcmp($p_type, 'block') == 0) {
$info['className'] = 'Application_Model_Block';
- } elseif (strcmp($p_type, 'webstream')==0) {
+ } elseif (strcmp($p_type, 'webstream') == 0) {
$info['className'] = 'Application_Model_Webstream';
} else {
- throw new Exception("Unknown object type: '$p_type'");
+ throw new Exception("Unknown object type: '{$p_type}'");
}
return $info;
@@ -25,8 +24,7 @@ class Application_Model_Library
$obj_sess = new Zend_Session_Namespace(UI_PLAYLISTCONTROLLER_OBJ_SESSNAME);
if (is_null($p_id) || is_null($p_type)) {
- unset($obj_sess->id);
- unset($obj_sess->type);
+ unset($obj_sess->id, $obj_sess->type);
} else {
$obj_sess->id = intval($p_id);
$obj_sess->type = $p_type;
@@ -35,20 +33,19 @@ class Application_Model_Library
public static function getPlaylistNames($alphasort = false)
{
-
- $playlistNames = array(NULL => _("None"));
+ $playlistNames = [null => _('None')];
//if we want to return the playlists sorted alphabetically by name
if ($alphasort) {
$playlists = CcPlaylistQuery::create()
->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)
->orderByname()
- ->find();
-
- }
- else {
+ ->find()
+ ;
+ } else {
$playlists = CcPlaylistQuery::create()
->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)
- ->find();
+ ->find()
+ ;
}
foreach ($playlists as $playlist) {
$playlistNames[$playlist->getDbId()] = $playlist->getDbName();
@@ -59,13 +56,13 @@ class Application_Model_Library
public static function getTracktypes()
{
- $track_type_options = array(NULL => _("None"));
+ $track_type_options = [null => _('None')];
$track_types = Application_Model_Tracktype::getTracktypes();
-
- array_multisort(array_map(function($element) {
+
+ array_multisort(array_map(function ($element) {
return $element['type_name'];
}, $track_types), SORT_ASC, $track_types);
-
+
foreach ($track_types as $key => $tt) {
$track_type_options[$tt['code']] = $tt['type_name'];
}
diff --git a/legacy/application/models/LibraryEditable.php b/legacy/application/models/LibraryEditable.php
index 9fb952a71..8d00c73a8 100644
--- a/legacy/application/models/LibraryEditable.php
+++ b/legacy/application/models/LibraryEditable.php
@@ -2,9 +2,11 @@
interface Application_Model_LibraryEditable
{
-
public function setMetadata($key, $val);
+
public function setName($name);
+
public function getLength();
+
public function getId();
}
diff --git a/legacy/application/models/ListenerStat.php b/legacy/application/models/ListenerStat.php
index 9580cadb0..f6fdbe54d 100644
--- a/legacy/application/models/ListenerStat.php
+++ b/legacy/application/models/ListenerStat.php
@@ -1,12 +1,14 @@
=:p1 AND ts.timestamp <=:p2)
group by mount_name
SQL;
- $data = Application_Common_Database::prepareAndExecute($sql,
- array('p1'=>$p_start, 'p2'=>$p_end));
- $out = array();
+ $data = Application_Common_Database::prepareAndExecute(
+ $sql,
+ ['p1' => $p_start, 'p2' => $p_end]
+ );
+ $out = [];
foreach ($data as $d) {
- $jump = intval($d['count']/1000);
+ $jump = intval($d['count'] / 1000);
$jump = max(1, $jump);
- $remainder = $jump == 1?0:1;
+ $remainder = $jump == 1 ? 0 : 1;
- $sql = <<=:p1 AND ts.timestamp <= :p2) AND mount_name=:p3) as temp
WHERE (temp.rownum%:p4) = :p5;
SQL;
- $result = Application_Common_Database::prepareAndExecute($sql,
- array('p1'=>$p_start, 'p2'=>$p_end, 'p3'=>$d['mount_name'], 'p4'=>$jump, 'p5'=>$remainder));
+ $result = Application_Common_Database::prepareAndExecute(
+ $sql,
+ ['p1' => $p_start, 'p2' => $p_end, 'p3' => $d['mount_name'], 'p4' => $jump, 'p5' => $remainder]
+ );
- $utcTimezone = new DateTimeZone("UTC");
+ $utcTimezone = new DateTimeZone('UTC');
$displayTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
-
+
foreach ($result as $r) {
$t = new DateTime($r['timestamp'], $utcTimezone);
$t->setTimezone($displayTimezone);
// tricking javascript so it thinks the server timezone is in UTC
$dt = new DateTime($t->format(DEFAULT_TIMESTAMP_FORMAT), $utcTimezone);
- $r['timestamp'] = $dt->format("U");
+ $r['timestamp'] = $dt->format('U');
$out[$r['mount_name']][] = $r;
}
}
return $out;
$enabledStreamIds = Application_Model_StreamSetting::getEnabledStreamIds();
- $enabledOut = array();
+ $enabledOut = [];
foreach ($enabledStreamIds as $sId) {
+ $sql = 'SELECT value FROM cc_stream_setting'
+ . ' WHERE keyname = :key';
- $sql = "SELECT value FROM cc_stream_setting"
- ." WHERE keyname = :key";
+ $result = Application_Common_Database::prepareAndExecute($sql, ['key' => $sId . '_mount'], 'single');
- $result = Application_Common_Database::prepareAndExecute($sql, array('key' => $sId."_mount"), "single");
+ $enabledMountPoint = $result['value'];
- $enabledMountPoint = $result["value"];
-
- if (isset($out[$enabledMountPoint])) {
- $enabledOut[$enabledMountPoint] = $out[$enabledMountPoint];
- }
- else {
- //TODO fix this hack (here for CC-5254)
- //all shoutcast streams are automatically put under "shoutcast" mount point.
- if (isset($out["shoutcast"])) {
- $enabledOut["shoutcast"] = $out["shoutcast"];
- }
- }
+ if (isset($out[$enabledMountPoint])) {
+ $enabledOut[$enabledMountPoint] = $out[$enabledMountPoint];
+ } else {
+ //TODO fix this hack (here for CC-5254)
+ //all shoutcast streams are automatically put under "shoutcast" mount point.
+ if (isset($out['shoutcast'])) {
+ $enabledOut['shoutcast'] = $out['shoutcast'];
+ }
+ }
}
return $enabledOut;
}
-// this will currently log the average number of listeners to a specific show during a certain range
- public static function getShowDataPointsWithinRange($p_start, $p_end, $show_id) {
+
+ // this will currently log the average number of listeners to a specific show during a certain range
+ public static function getShowDataPointsWithinRange($p_start, $p_end, $show_id)
+ {
$showData = [];
$ccShow = CcShowQuery::create()->findPk($show_id);
$showName = $ccShow->getDbName();
-
// this query selects all show instances that aired in this date range that match the show_id
- $sql = <<=:p2 AND ends <=:p3
SQL;
- $data = Application_Common_Database::prepareAndExecute($sql,
- array('p1'=>$show_id,'p2'=>$p_start, 'p3'=>$p_end));
+ $data = Application_Common_Database::prepareAndExecute(
+ $sql,
+ ['p1' => $show_id, 'p2' => $p_start, 'p3' => $p_end]
+ );
foreach ($data as $d) {
- $sql = <<=:p1 AND ts.timestamp <=:p2)
GROUP BY timestamp
SQL;
- $data = Application_Common_Database::prepareAndExecute($sql,
- array('p1'=>$d['starts'], 'p2'=>$d['ends']));
- $utcTimezone = new DateTimeZone("UTC");
+ $data = Application_Common_Database::prepareAndExecute(
+ $sql,
+ ['p1' => $d['starts'], 'p2' => $d['ends']]
+ );
+ $utcTimezone = new DateTimeZone('UTC');
$displayTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
if (sizeof($data) > 0) {
$t = new DateTime($data[0]['timestamp'], $utcTimezone);
@@ -111,27 +120,31 @@ SQL;
// tricking javascript so it thinks the server timezone is in UTC
$average_listeners = array_sum(array_column($data, 'listeners')) / sizeof($data);
$max_num_listeners = max(array_column($data, 'listeners'));
- $entry = array("show" => $showName, "time" => $t->format( 'Y-m-d H:i:s')
- , "average_number_of_listeners" => $average_listeners,
- "maximum_number_of_listeners" => $max_num_listeners);
+ $entry = ['show' => $showName, 'time' => $t->format('Y-m-d H:i:s'), 'average_number_of_listeners' => $average_listeners,
+ 'maximum_number_of_listeners' => $max_num_listeners, ];
array_push($showData, $entry);
}
- }
- return($showData);
+ }
+
+ return $showData;
}
- public static function getAllShowDataPointsWithinRange($p_start, $p_end) {
+
+ public static function getAllShowDataPointsWithinRange($p_start, $p_end)
+ {
// this query selects the id of all show instances that aired in this date range
$all_show_data = [];
- $sql = <<=:p1 AND ends <=:p2
GROUP BY show_id
SQL;
- $data = Application_Common_Database::prepareAndExecute($sql,
- array('p1'=>$p_start, 'p2'=>$p_end));
+ $data = Application_Common_Database::prepareAndExecute(
+ $sql,
+ ['p1' => $p_start, 'p2' => $p_end]
+ );
- foreach($data as $show_id) {
- $all_show_data = array_merge(self::getShowDataPointsWithinRange($p_start,$p_end,$show_id['show_id']), $all_show_data);
+ foreach ($data as $show_id) {
+ $all_show_data = array_merge(self::getShowDataPointsWithinRange($p_start, $p_end, $show_id['show_id']), $all_show_data);
}
/* option to sort by number of listeners currently commented out
usort($all_show_data, function($a, $b) {
@@ -141,32 +154,33 @@ SQL;
return $all_show_data;
}
- public static function insertDataPoints($p_dataPoints) {
+ public static function insertDataPoints($p_dataPoints)
+ {
+ $timestamp_sql = 'INSERT INTO cc_timestamp (timestamp) VALUES
+ (:ts::TIMESTAMP) RETURNING id;';
+ $mount_name_check_sql = 'SELECT id from cc_mount_name WHERE
+ mount_name = :mn;';
- $timestamp_sql = "INSERT INTO cc_timestamp (timestamp) VALUES
- (:ts::TIMESTAMP) RETURNING id;";
+ $mount_name_insert_sql = 'INSERT INTO cc_mount_name (mount_name) VALUES
+ (:mn) RETURNING id;';
- $mount_name_check_sql = "SELECT id from cc_mount_name WHERE
- mount_name = :mn;";
-
- $mount_name_insert_sql = "INSERT INTO cc_mount_name (mount_name) VALUES
- (:mn) RETURNING id;";
-
- $stats_sql = "INSERT INTO cc_listener_count (timestamp_id,
+ $stats_sql = 'INSERT INTO cc_listener_count (timestamp_id,
listener_count, mount_name_id) VALUES (:timestamp_id,
- :listener_count, :mount_name_id)";
+ :listener_count, :mount_name_id)';
foreach ($p_dataPoints as $dp) {
$timestamp_id = Application_Common_Database::prepareAndExecute(
$timestamp_sql,
- array('ts'=> $dp['timestamp']),
- "column");
+ ['ts' => $dp['timestamp']],
+ 'column'
+ );
$mount_name_id = Application_Common_Database::prepareAndExecute(
$mount_name_check_sql,
- array('mn' => $dp['mount_name']),
- "column");
+ ['mn' => $dp['mount_name']],
+ 'column'
+ );
if (strlen($mount_name_id) == 0) {
//there is a race condition here where theoretically the row
@@ -174,20 +188,18 @@ SQL;
//unlikely and won't break anything even if it happens.
$mount_name_id = Application_Common_Database::prepareAndExecute(
$mount_name_insert_sql,
- array('mn' => $dp['mount_name']),
- "column");
+ ['mn' => $dp['mount_name']],
+ 'column'
+ );
}
- Application_Common_Database::prepareAndExecute($stats_sql,
- array('timestamp_id' => $timestamp_id,
- 'listener_count' => $dp["num_listeners"],
- 'mount_name_id' => $mount_name_id,
- )
+ Application_Common_Database::prepareAndExecute(
+ $stats_sql,
+ ['timestamp_id' => $timestamp_id,
+ 'listener_count' => $dp['num_listeners'],
+ 'mount_name_id' => $mount_name_id,
+ ]
);
}
-
}
-
-
-
}
diff --git a/legacy/application/models/LiveLog.php b/legacy/application/models/LiveLog.php
index f4f26678e..2eca8f3b0 100644
--- a/legacy/application/models/LiveLog.php
+++ b/legacy/application/models/LiveLog.php
@@ -2,17 +2,18 @@
class Application_Model_LiveLog
{
-
- public static function GetLiveShowDuration($p_keepData=false)
+ public static function GetLiveShowDuration($p_keepData = false)
{
try {
-
- $sql = "SELECT * FROM CC_LIVE_LOG"
- ." WHERE state = :state"
- ." and (start_time >= (now() - INTERVAL '1 day'))"
- ." ORDER BY id";
- $rows = Application_Common_Database::prepareAndExecute($sql, array(':state'=>'L'),
- Application_Common_Database::ALL);
+ $sql = 'SELECT * FROM CC_LIVE_LOG'
+ . ' WHERE state = :state'
+ . " and (start_time >= (now() - INTERVAL '1 day'))"
+ . ' ORDER BY id';
+ $rows = Application_Common_Database::prepareAndExecute(
+ $sql,
+ [':state' => 'L'],
+ Application_Common_Database::ALL
+ );
/* Check if last log has end time.
* If not, set end time to current time
@@ -22,20 +23,26 @@ class Application_Model_LiveLog
array_push($rows, $last_row);
$skip = false;
} else {
- $sql = "SELECT * FROM CC_LIVE_LOG"
- ." WHERE state = :state"
- ." ORDER BY id";
- $rows = Application_Common_Database::prepareAndExecute($sql, array(':state'=>'L'),
- Application_Common_Database::ALL);
+ $sql = 'SELECT * FROM CC_LIVE_LOG'
+ . ' WHERE state = :state'
+ . ' ORDER BY id';
+ $rows = Application_Common_Database::prepareAndExecute(
+ $sql,
+ [':state' => 'L'],
+ Application_Common_Database::ALL
+ );
if ($rows != null) {
$last_row = self::UpdateLastLogEndTime(array_pop($rows));
array_push($rows, $last_row);
foreach ($rows as $row) {
- $sql_delete = "DELETE FROM CC_LIVE_LOG"
- ." WHERE id = :id";
- Application_Common_Database::prepareAndExecute($sql_delete, array(':id'=>$row['id']),
- Application_Common_Database::EXECUTE);
+ $sql_delete = 'DELETE FROM CC_LIVE_LOG'
+ . ' WHERE id = :id';
+ Application_Common_Database::prepareAndExecute(
+ $sql_delete,
+ [':id' => $row['id']],
+ Application_Common_Database::EXECUTE
+ );
}
}
$skip = true;
@@ -50,29 +57,29 @@ class Application_Model_LiveLog
$end = new DateTime($row['end_time']);
$start = new DateTime($row['start_time']);
$duration = $start->diff($end);
- $duration = $duration->format("%H:%i:%s");
- $intervals = explode(":", $duration);
- for ($i = 0; $i < sizeof($intervals); $i++) {
+ $duration = $duration->format('%H:%i:%s');
+ $intervals = explode(':', $duration);
+ for ($i = 0; $i < sizeof($intervals); ++$i) {
if (!isset($intervals[$i])) {
$intervals[$i] = 0;
}
}
// Trim milliseconds (DateInterval does not support)
- $sec = explode(".", $intervals[2]);
+ $sec = explode('.', $intervals[2]);
if (isset($sec[0])) {
$intervals[2] = $sec[0];
}
$seconds += $intervals[2];
if ($seconds / 60 >= 1) {
- $minutes += 1;
+ ++$minutes;
$seconds -= 60;
}
$minutes += $intervals[1];
if ($minutes / 60 >= 1) {
- $hours += 1;
+ ++$hours;
$minutes -= 60;
}
@@ -80,40 +87,46 @@ class Application_Model_LiveLog
if (!$p_keepData) {
// Delete data we just used to start a new log history
- $sql_delete = "DELETE FROM CC_LIVE_LOG"
- ." WHERE id = :id";
- Application_Common_Database::prepareAndExecute($sql_delete, array(':id'=>$row['id']),
- Application_Common_Database::EXECUTE);
+ $sql_delete = 'DELETE FROM CC_LIVE_LOG'
+ . ' WHERE id = :id';
+ Application_Common_Database::prepareAndExecute(
+ $sql_delete,
+ [':id' => $row['id']],
+ Application_Common_Database::EXECUTE
+ );
}
}
//Trim milliseconds
- $seconds = explode(".", $seconds);
+ $seconds = explode('.', $seconds);
if (isset($seconds[0])) {
- $minutes = (double) (($hours*60)+$minutes . "." . $seconds[0]);
+ $minutes = (float) (($hours * 60) + $minutes . '.' . $seconds[0]);
} else {
- $minutes = (double) (($hours*60)+$minutes);
+ $minutes = (float) (($hours * 60) + $minutes);
}
}
return $minutes;
} catch (Exception $e) {
header('HTTP/1.0 503 Service Unavailable');
- Logging::info("GetLiveShowDuration - Could not connect to database.");
+ Logging::info('GetLiveShowDuration - Could not connect to database.');
+
exit;
}
}
- public static function GetScheduledDuration($p_keepData=false)
+ public static function GetScheduledDuration($p_keepData = false)
{
try {
+ $sql_get_logs = 'SELECT * FROM CC_LIVE_LOG'
+ . ' WHERE state = :state'
+ . " and (start_time >= (now() - INTERVAL '1 day'))"
+ . ' ORDER BY id';
- $sql_get_logs = "SELECT * FROM CC_LIVE_LOG"
- ." WHERE state = :state"
- ." and (start_time >= (now() - INTERVAL '1 day'))"
- ." ORDER BY id";
-
- $rows = Application_Common_Database::prepareAndExecute($sql_get_logs, array(':state'=>'S'),
- Application_Common_Database::ALL);
+ $rows = Application_Common_Database::prepareAndExecute(
+ $sql_get_logs,
+ [':state' => 'S'],
+ Application_Common_Database::ALL
+ );
/* Check if last log has end time.
* If not, set end time to current time
@@ -123,20 +136,26 @@ class Application_Model_LiveLog
array_push($rows, $last_row);
$skip = false;
} else {
- $sql = "SELECT * FROM CC_LIVE_LOG"
- ." WHERE state = :state"
- ." ORDER BY id";
- $rows = Application_Common_Database::prepareAndExecute($sql, array(':state'=>'S'),
- Application_Common_Database::ALL);
+ $sql = 'SELECT * FROM CC_LIVE_LOG'
+ . ' WHERE state = :state'
+ . ' ORDER BY id';
+ $rows = Application_Common_Database::prepareAndExecute(
+ $sql,
+ [':state' => 'S'],
+ Application_Common_Database::ALL
+ );
if ($rows != null) {
$last_row = self::UpdateLastLogEndTime(array_pop($rows));
array_push($rows, $last_row);
foreach ($rows as $row) {
- $sql_delete = "DELETE FROM CC_LIVE_LOG"
- ." WHERE id = :id";
- Application_Common_Database::prepareAndExecute($sql_delete, array(':id'=>$row['id']),
- Application_Common_Database::EXECUTE);
+ $sql_delete = 'DELETE FROM CC_LIVE_LOG'
+ . ' WHERE id = :id';
+ Application_Common_Database::prepareAndExecute(
+ $sql_delete,
+ [':id' => $row['id']],
+ Application_Common_Database::EXECUTE
+ );
}
}
$skip = true;
@@ -151,17 +170,20 @@ class Application_Model_LiveLog
* during a scheduled state
*/
foreach ($rows as $row) {
- $sql_get_tracks = "SELECT * FROM cc_schedule"
- ." WHERE starts >= :starts1"
- ." AND starts < :starts2"
- ." AND file_id IS NOT NULL"
- ." AND media_item_played IS TRUE";
- $params = array(
- ':starts1'=>$row['start_time'],
- ':starts2'=>$row['end_time']
+ $sql_get_tracks = 'SELECT * FROM cc_schedule'
+ . ' WHERE starts >= :starts1'
+ . ' AND starts < :starts2'
+ . ' AND file_id IS NOT NULL'
+ . ' AND media_item_played IS TRUE';
+ $params = [
+ ':starts1' => $row['start_time'],
+ ':starts2' => $row['end_time'],
+ ];
+ $tracks = Application_Common_Database::prepareAndExecute(
+ $sql_get_tracks,
+ $params,
+ Application_Common_Database::ALL
);
- $tracks = Application_Common_Database::prepareAndExecute($sql_get_tracks, $params,
- Application_Common_Database::ALL);
foreach ($tracks as $track) {
if ($track['ends'] > $row['end_time']) {
@@ -176,68 +198,68 @@ class Application_Model_LiveLog
*/
$clip_length = $track['clip_length'];
//Convert clip_length into seconds
- $clip_length_intervals = explode(":", $clip_length);
- for ($i = 0; $i < sizeof($clip_length_intervals); $i++) {
+ $clip_length_intervals = explode(':', $clip_length);
+ for ($i = 0; $i < sizeof($clip_length_intervals); ++$i) {
if (!isset($clip_length_intervals[$i])) {
$clip_length_intervals[$i] = 0;
}
}
- $clip_length_seconds = $clip_length_intervals[0]*3600 + $clip_length_intervals[1]*60 + $clip_length_intervals[2];
+ $clip_length_seconds = $clip_length_intervals[0] * 3600 + $clip_length_intervals[1] * 60 + $clip_length_intervals[2];
- $extra_time = $extra_time->format("%H:%i:%s");
+ $extra_time = $extra_time->format('%H:%i:%s');
//Convert extra_time into seconds;
- $extra_time_intervals = explode(":", $extra_time);
- for ($i = 0; $i < sizeof($extra_time_intervals); $i++) {
+ $extra_time_intervals = explode(':', $extra_time);
+ for ($i = 0; $i < sizeof($extra_time_intervals); ++$i) {
if (!isset($extra_time_intervals[$i])) {
$extra_time_intervals[$i] = 0;
}
}
- $extra_time_seconds = $extra_time_intervals[0]*3600 + $extra_time_intervals[1]*60 + $extra_time_intervals[2];
+ $extra_time_seconds = $extra_time_intervals[0] * 3600 + $extra_time_intervals[1] * 60 + $extra_time_intervals[2];
$clip_length_seconds -= $extra_time_seconds;
//Convert new clip_length into "H-i-s" format
- $clip_length_arr = array();
+ $clip_length_arr = [];
if ($clip_length_seconds / 3600 >= 1) {
- array_push($clip_length_arr, str_pad(floor($clip_length_seconds / 3600), 2, "0", STR_PAD_LEFT));
+ array_push($clip_length_arr, str_pad(floor($clip_length_seconds / 3600), 2, '0', STR_PAD_LEFT));
$clip_length_seconds -= floor($clip_length_seconds / 3600);
} else {
- array_push($clip_length_arr, "00");
+ array_push($clip_length_arr, '00');
}
if ($clip_length_seconds / 60 >= 1) {
- array_push($clip_length_arr, str_pad(floor($clip_length_seconds / 60), 2, "0", STR_PAD_LEFT));
+ array_push($clip_length_arr, str_pad(floor($clip_length_seconds / 60), 2, '0', STR_PAD_LEFT));
$clip_length_seconds -= floor($clip_length_seconds / 60);
} else {
- array_push($clip_length_arr, "00");
+ array_push($clip_length_arr, '00');
}
- array_push($clip_length_arr, str_pad($clip_length_seconds, 2, "0", STR_PAD_LEFT));
- $clip_length = implode(":", $clip_length_arr);
+ array_push($clip_length_arr, str_pad($clip_length_seconds, 2, '0', STR_PAD_LEFT));
+ $clip_length = implode(':', $clip_length_arr);
} else {
$clip_length = $track['clip_length'];
}
- $intervals = explode(":", $clip_length);
- for ($i = 0; $i < sizeof($intervals); $i++) {
+ $intervals = explode(':', $clip_length);
+ for ($i = 0; $i < sizeof($intervals); ++$i) {
if (!isset($intervals[$i])) {
$intervals[$i] = 0;
}
}
// Trim milliseconds (DateInteral does not support)
- $sec = explode(".", $intervals[2]);
+ $sec = explode('.', $intervals[2]);
if (isset($sec[0])) {
$intervals[2] = $sec[0];
}
$seconds += $intervals[2];
if ($seconds / 60 >= 1) {
- $minutes += 1;
+ ++$minutes;
$seconds -= 60;
}
$minutes += $intervals[1];
if ($minutes / 60 >= 1) {
- $hours += 1;
+ ++$hours;
$minutes -= 60;
}
@@ -246,26 +268,29 @@ class Application_Model_LiveLog
if (!$p_keepData) {
//Delete row because we do not need data anymore
- $sql_delete = "DELETE FROM CC_LIVE_LOG"
- ." WHERE id = :id";
- Application_Common_Database::prepareAndExecute($sql_delete, array(':id'=>$row['id']),
- Application_Common_Database::EXECUTE);
+ $sql_delete = 'DELETE FROM CC_LIVE_LOG'
+ . ' WHERE id = :id';
+ Application_Common_Database::prepareAndExecute(
+ $sql_delete,
+ [':id' => $row['id']],
+ Application_Common_Database::EXECUTE
+ );
}
}
-
- $seconds = explode(".", $seconds);
+ $seconds = explode('.', $seconds);
if (isset($seconds[0])) {
- $minutes = (double) (($hours*60)+$minutes . "." . $seconds[0]);
+ $minutes = (float) (($hours * 60) + $minutes . '.' . $seconds[0]);
} else {
- $minutes = (double) (($hours*60)+$minutes);
+ $minutes = (float) (($hours * 60) + $minutes);
}
}
return $minutes;
} catch (Exception $e) {
header('HTTP/1.0 503 Service Unavailable');
- Logging::info("GetScheduledDuration - Could not connect to database.");
+ Logging::info('GetScheduledDuration - Could not connect to database.');
+
exit;
}
}
@@ -273,7 +298,7 @@ class Application_Model_LiveLog
public static function UpdateLastLogEndTime($log)
{
if ($log['end_time'] == null) {
- $current_time = new DateTime("now", new DateTimeZone('UTC'));
+ $current_time = new DateTime('now', new DateTimeZone('UTC'));
$log['end_time'] = $current_time;
$log['end_time'] = $log['end_time']->format(DEFAULT_TIMESTAMP_FORMAT);
self::SetEndTime($log['state'], $current_time, true);
@@ -286,7 +311,6 @@ class Application_Model_LiveLog
public static function SetNewLogTime($state, $dateTime)
{
try {
-
$scheduled = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play');
if ($state == 'L' && $scheduled == 'on') {
self::SetEndTime('S', $dateTime);
@@ -295,76 +319,87 @@ class Application_Model_LiveLog
/* Only insert new state if last log
* has ended
*/
- $sql_select = "SELECT max(id) from CC_LIVE_LOG"
- ." WHERE (state= :state1 and end_time is NULL) or (state= :state2 and end_time is NULL)";
- $params = array(
- ":state1"=> 'L',
- ":state2"=> 'S'
+ $sql_select = 'SELECT max(id) from CC_LIVE_LOG'
+ . ' WHERE (state= :state1 and end_time is NULL) or (state= :state2 and end_time is NULL)';
+ $params = [
+ ':state1' => 'L',
+ ':state2' => 'S',
+ ];
+ $id = Application_Common_Database::prepareAndExecute(
+ $sql_select,
+ $params,
+ Application_Common_Database::COLUMN
);
- $id = Application_Common_Database::prepareAndExecute($sql_select, $params,
- Application_Common_Database::COLUMN);
if ($id == null) {
- $sql_insert = "INSERT INTO CC_LIVE_LOG (state, start_time)"
- ." VALUES (:state, :start)";
- $params = array(
- ':state'=>$state,
- ':start'=>$dateTime->format(DEFAULT_TIMESTAMP_FORMAT)
+ $sql_insert = 'INSERT INTO CC_LIVE_LOG (state, start_time)'
+ . ' VALUES (:state, :start)';
+ $params = [
+ ':state' => $state,
+ ':start' => $dateTime->format(DEFAULT_TIMESTAMP_FORMAT),
+ ];
+ Application_Common_Database::prepareAndExecute(
+ $sql_insert,
+ $params,
+ Application_Common_Database::EXECUTE
);
- Application_Common_Database::prepareAndExecute($sql_insert, $params,
- Application_Common_Database::EXECUTE);
- if ($state == "S") {
+ if ($state == 'S') {
// if scheduled play source is getting broadcasted
Application_Model_Schedule::UpdateBrodcastedStatus($dateTime, 1);
}
}
-
} catch (Exception $e) {
header('HTTP/1.0 503 Service Unavailable');
- Logging::info("SetNewLogTime - Could not connect to database.");
+ Logging::info('SetNewLogTime - Could not connect to database.');
+
exit;
}
}
- public static function SetEndTime($state, $dateTime, $override=false)
+ public static function SetEndTime($state, $dateTime, $override = false)
{
try {
$dj_live = Application_Model_Preference::GetSourceSwitchStatus('live_dj');
$master_live = Application_Model_Preference::GetSourceSwitchStatus('master_dj');
- if (($dj_live=='off' && $master_live=='off') || $state == 'S' || $override) {
- $sql = "SELECT id, state from cc_live_log"
- ." where id in (select max(id) from cc_live_log)";
- $row = Application_Common_Database::prepareAndExecute($sql, array(),
- Application_Common_Database::SINGLE);
+ if (($dj_live == 'off' && $master_live == 'off') || $state == 'S' || $override) {
+ $sql = 'SELECT id, state from cc_live_log'
+ . ' where id in (select max(id) from cc_live_log)';
+ $row = Application_Common_Database::prepareAndExecute(
+ $sql,
+ [],
+ Application_Common_Database::SINGLE
+ );
/* Only set end time if state recevied ($state)
* is the last row in cc_live_log
*/
if ($row['state'] == $state) {
- $update_sql = "UPDATE CC_LIVE_LOG"
- ." SET end_time = :end"
- ." WHERE id = :id";
- $params = array(
- ':end'=>$dateTime->format(DEFAULT_TIMESTAMP_FORMAT),
- ':id'=>$row['id']
+ $update_sql = 'UPDATE CC_LIVE_LOG'
+ . ' SET end_time = :end'
+ . ' WHERE id = :id';
+ $params = [
+ ':end' => $dateTime->format(DEFAULT_TIMESTAMP_FORMAT),
+ ':id' => $row['id'],
+ ];
+ Application_Common_Database::prepareAndExecute(
+ $update_sql,
+ $params,
+ Application_Common_Database::EXECUTE
);
- Application_Common_Database::prepareAndExecute($update_sql, $params,
- Application_Common_Database::EXECUTE);
}
//If live broadcasting is off, turn scheduled play on
$scheduled = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play');
- if ($state == 'L' && $scheduled=='on' && !$override) {
+ if ($state == 'L' && $scheduled == 'on' && !$override) {
self::SetNewLogTime('S', $dateTime);
}
}
-
} catch (Exception $e) {
header('HTTP/1.0 503 Service Unavailable');
- Logging::info("SetEndTime - Could not connect to database.");
+ Logging::info('SetEndTime - Could not connect to database.');
+
exit;
}
}
-
}
diff --git a/legacy/application/models/Locale.php b/legacy/application/models/Locale.php
index 7d6567ba8..00290d662 100644
--- a/legacy/application/models/Locale.php
+++ b/legacy/application/models/Locale.php
@@ -2,34 +2,34 @@
final class Application_Model_Locale
{
- private static $domains = array(
- 'airtime',
+ private static $domains = [
+ 'airtime',
'pro',
- );
-
- public static $locales = array(
- "en_CA" => "English (Canada)",
- "en_GB" => "English (Britain)",
- "en_US" => "English (USA)",
- "cs_CZ" => "Český",
- "de_DE" => "Deutsch",
- "de_AT" => "Deutsch (Österreich)",
- "el_GR" => "Ελληνικά",
- "es_ES" => "Español",
- "fr_FR" => "Français",
- "hr_HR" => "Hrvatski",
- "hu_HU" => "Magyar",
- "it_IT" => "Italiano",
- "ja_JP" => "日本語",
- "ko_KR" => "한국어",
- "pl_PL" => "Polski",
- "pt_BR" => "Português (Brasil)",
- "ru_RU" => "Русский",
- "sr_RS" => "Српски (Ћирилица)",
- "sr_RS@latin" => "Srpski (Latinica)",
- "zh_CN" => "简体中文"
- );
-
+ ];
+
+ public static $locales = [
+ 'en_CA' => 'English (Canada)',
+ 'en_GB' => 'English (Britain)',
+ 'en_US' => 'English (USA)',
+ 'cs_CZ' => 'Český',
+ 'de_DE' => 'Deutsch',
+ 'de_AT' => 'Deutsch (Österreich)',
+ 'el_GR' => 'Ελληνικά',
+ 'es_ES' => 'Español',
+ 'fr_FR' => 'Français',
+ 'hr_HR' => 'Hrvatski',
+ 'hu_HU' => 'Magyar',
+ 'it_IT' => 'Italiano',
+ 'ja_JP' => '日本語',
+ 'ko_KR' => '한국어',
+ 'pl_PL' => 'Polski',
+ 'pt_BR' => 'Português (Brasil)',
+ 'ru_RU' => 'Русский',
+ 'sr_RS' => 'Српски (Ћирилица)',
+ 'sr_RS@latin' => 'Srpski (Latinica)',
+ 'zh_CN' => '简体中文',
+ ];
+
public static function getLocales()
{
return self::$locales;
@@ -39,45 +39,43 @@ final class Application_Model_Locale
{
$codeset = 'UTF-8';
if (is_null($locale)) {
- $lang = Application_Model_Preference::GetLocale().'.'.$codeset;
+ $lang = Application_Model_Preference::GetLocale() . '.' . $codeset;
} else {
- $lang = $locale.'.'.$codeset;
+ $lang = $locale . '.' . $codeset;
}
//putenv("LC_ALL=$lang");
//putenv("LANG=$lang");
- //Setting the LANGUAGE env var supposedly lets gettext search inside our locale dir even if the system
+ //Setting the LANGUAGE env var supposedly lets gettext search inside our locale dir even if the system
//doesn't have the particular locale that we want installed. This doesn't actually seem to work though. -- Albert
- putenv("LANGUAGE=$locale");
- if (setlocale(LC_MESSAGES, $lang) === false)
- {
- Logging::warn("Your system does not have the " . $lang . " locale installed. Run: sudo locale-gen " . $lang);
+ putenv("LANGUAGE={$locale}");
+ if (setlocale(LC_MESSAGES, $lang) === false) {
+ Logging::warn('Your system does not have the ' . $lang . ' locale installed. Run: sudo locale-gen ' . $lang);
}
-
+
// We need to run bindtextdomain and bind_textdomain_codeset for each domain we're using.
foreach (self::$domains as $domain) {
bindtextdomain($domain, '../locale');
bind_textdomain_codeset($domain, $codeset);
}
-
+
textdomain('airtime');
}
-
+
/**
- * We need this function for the case where a user has logged out, but
+ * We need this function for the case where a user has logged out, but
* has an airtime_locale cookie containing their locale setting.
- *
- * If the user does not have an airtime_locale cookie set, we default
+ *
+ * If the user does not have an airtime_locale cookie set, we default
* to the station locale.
- *
- * When the user logs in, the value set in the login form will be passed
- * into the airtime_locale cookie. This cookie is also updated when
+ *
+ * When the user logs in, the value set in the login form will be passed
+ * into the airtime_locale cookie. This cookie is also updated when
* a user updates their user settings.
*/
- public static function getUserLocale() {
+ public static function getUserLocale()
+ {
$request = Zend_Controller_Front::getInstance()->getRequest();
- $locale = $request->getCookie('airtime_locale', Application_Model_Preference::GetLocale());
- return $locale;
+
+ return $request->getCookie('airtime_locale', Application_Model_Preference::GetLocale());
}
-
}
-
diff --git a/legacy/application/models/LoginAttempts.php b/legacy/application/models/LoginAttempts.php
index 3997bc1ab..559692caf 100644
--- a/legacy/application/models/LoginAttempts.php
+++ b/legacy/application/models/LoginAttempts.php
@@ -1,4 +1,5 @@
$ip), Application_Common_Database::ALL);
+ $sql = 'select count(*) from cc_login_attempts WHERE ip= :ip';
+ $res = Application_Common_Database::prepareAndExecute($sql, [':ip' => $ip], Application_Common_Database::ALL);
if ($res) {
- $sql = "UPDATE cc_login_attempts SET attempts=attempts+1 WHERE ip= :ip";
- Application_Common_Database::prepareAndExecute($sql, array(':ip'=>$ip), Application_Common_Database::EXECUTE);
+ $sql = 'UPDATE cc_login_attempts SET attempts=attempts+1 WHERE ip= :ip';
+ Application_Common_Database::prepareAndExecute($sql, [':ip' => $ip], Application_Common_Database::EXECUTE);
} else {
$sql = "INSERT INTO cc_login_attempts (ip, attempts) values (':ip', '1')";
- Application_Common_Database::prepareAndExecute($sql, array(':ip'=>$ip), Application_Common_Database::EXECUTE);
+ Application_Common_Database::prepareAndExecute($sql, [':ip' => $ip], Application_Common_Database::EXECUTE);
}
}
public static function getAttempts($ip)
{
- $sql = "select attempts from cc_login_attempts WHERE ip= :ip";
- $res = Application_Common_Database::prepareAndExecute($sql, array(':ip'=>$ip), Application_Common_Database::ALL);
+ $sql = 'select attempts from cc_login_attempts WHERE ip= :ip';
+ $res = Application_Common_Database::prepareAndExecute($sql, [':ip' => $ip], Application_Common_Database::ALL);
return $res ? $res : 0;
}
public static function resetAttempts($ip)
{
- $sql = "select count(*) from cc_login_attempts WHERE ip= :ip";
- $res = Application_Common_Database::prepareAndExecute($sql, array(':ip'=>$ip), Application_Common_Database::COLUMN);
+ $sql = 'select count(*) from cc_login_attempts WHERE ip= :ip';
+ $res = Application_Common_Database::prepareAndExecute($sql, [':ip' => $ip], Application_Common_Database::COLUMN);
if ($res > 0) {
- $sql = "DELETE FROM cc_login_attempts WHERE ip= :ip";
- Application_Common_Database::prepareAndExecute($sql, array(':ip'=>$ip), Application_Common_Database::EXECUTE);
+ $sql = 'DELETE FROM cc_login_attempts WHERE ip= :ip';
+ Application_Common_Database::prepareAndExecute($sql, [':ip' => $ip], Application_Common_Database::EXECUTE);
}
}
}
diff --git a/legacy/application/models/MusicDir.php b/legacy/application/models/MusicDir.php
index 80f6cbe25..ca273d3d8 100644
--- a/legacy/application/models/MusicDir.php
+++ b/legacy/application/models/MusicDir.php
@@ -1,6 +1,8 @@
getId();
- $sql = << $music_dir_id ), 'all' );
+ $show_instances = Application_Common_Database::prepareAndExecute(
+ $sql,
+ [':musicDirId' => $music_dir_id],
+ 'all'
+ );
// get all the files on this dir
- $sql = << $music_dir_id ), 'all');
+ $affected = Application_Common_Database::prepareAndExecute(
+ $sql,
+ [':musicDirId' => $music_dir_id],
+ 'all'
+ );
// set RemovedFlag to true
if ($userAddedWatchedDir) {
@@ -111,7 +120,7 @@ SQL;
//$res = $this->_dir->delete();
foreach ($show_instances as $show_instance_row) {
- $temp_show = new Application_Model_ShowInstance($show_instance_row["instance_id"]);
+ $temp_show = new Application_Model_ShowInstance($show_instance_row['instance_id']);
$temp_show->updateScheduledTime();
}
Application_Model_RabbitMq::PushSchedule();
@@ -120,14 +129,15 @@ SQL;
/**
* Checks if p_dir1 is the ancestor of p_dir2. Returns
* true if it is the ancestor, false otherwise. Note that
- * /home/user is considered the ancestor of /home/user
+ * /home/user is considered the ancestor of /home/user.
*
* @param string $p_dir1
- * The potential ancestor directory.
+ * The potential ancestor directory
* @param string $p_dir2
- * The potential descendent directory.
- * @return boolean
- * Returns true if it is the ancestor, false otherwise.
+ * The potential descendent directory
+ *
+ * @return bool
+ * Returns true if it is the ancestor, false otherwise
*/
private static function isAncestorDir($p_dir1, $p_dir2)
{
@@ -144,8 +154,7 @@ SQL;
* or vice-versa. Throws a NestedDirectoryException if invalid.
*
* @param string $p_path
- * The path we want to validate
- * @return void
+ * The path we want to validate
*/
public static function isPathValid($p_path)
{
@@ -157,15 +166,15 @@ SQL;
$diff = strlen($dir) - strlen($p_path);
if ($diff == 0) {
if ($dir == $p_path) {
- throw new NestedDirectoryException(sprintf(_("%s is already watched."), $p_path));
+ throw new NestedDirectoryException(sprintf(_('%s is already watched.'), $p_path));
}
} elseif ($diff > 0) {
if (self::isAncestorDir($p_path, $dir)) {
- throw new NestedDirectoryException(sprintf(_("%s contains nested watched directory: %s"), $p_path, $dir));
+ throw new NestedDirectoryException(sprintf(_('%s contains nested watched directory: %s'), $p_path, $dir));
}
- } else { /* diff < 0*/
+ } else { // diff < 0
if (self::isAncestorDir($dir, $p_path)) {
- throw new NestedDirectoryException(sprintf(_("%s is nested within existing watched directory: %s"), $p_path, $dir));
+ throw new NestedDirectoryException(sprintf(_('%s is nested within existing watched directory: %s'), $p_path, $dir));
}
}
}
@@ -173,7 +182,7 @@ SQL;
/** There are 2 cases where this function can be called.
* 1. When watched dir was added
- * 2. When some dir was watched, but it was unmounted somehow, but gets mounted again
+ * 2. When some dir was watched, but it was unmounted somehow, but gets mounted again.
*
* In case of 1, $userAddedWatchedDir should be true
* In case of 2, $userAddedWatchedDir should be false
@@ -182,14 +191,17 @@ SQL;
* otherwise, it will set "Exists" flag to true
*
* @param $nestedWatch - if true, bypass path check, and Watched to false
- **/
- public static function addDir($p_path, $p_type, $userAddedWatchedDir=true, $nestedWatch=false)
+ * @param mixed $p_path
+ * @param mixed $p_type
+ * @param mixed $userAddedWatchedDir
+ */
+ public static function addDir($p_path, $p_type, $userAddedWatchedDir = true, $nestedWatch = false)
{
if (!is_dir($p_path)) {
- return array("code"=>2, "error"=>sprintf(_("%s is not a valid directory."), $p_path));
+ return ['code' => 2, 'error' => sprintf(_('%s is not a valid directory.'), $p_path)];
}
- $real_path = Application_Common_OsPath::normpath($p_path)."/";
- if ($real_path != "/") {
+ $real_path = Application_Common_OsPath::normpath($p_path) . '/';
+ if ($real_path != '/') {
$p_path = $real_path;
}
@@ -203,7 +215,7 @@ SQL;
}
$dir->setType($p_type);
- $p_path = Application_Common_OsPath::normpath($p_path)."/";
+ $p_path = Application_Common_OsPath::normpath($p_path) . '/';
try {
/* isPathValid() checks if path is a substring or a superstring of an
@@ -221,57 +233,64 @@ SQL;
}
$dir->setDirectory($p_path);
- return array("code"=>0);
+ return ['code' => 0];
} catch (NestedDirectoryException $nde) {
$msg = $nde->getMessage();
- return array("code"=>1, "error"=>"$msg");
+ return ['code' => 1, 'error' => "{$msg}"];
} catch (Exception $e) {
- return array("code"=>1,
- "error" => sprintf(
- _("%s is already set as the current storage dir or in the".
- " watched folders list"),
+ return ['code' => 1,
+ 'error' => sprintf(
+ _('%s is already set as the current storage dir or in the' .
+ ' watched folders list'),
$p_path
- )
- );
+ ),
+ ];
}
-
}
/** There are 2 cases where this function can be called.
* 1. When watched dir was added
- * 2. When some dir was watched, but it was unmounted somehow, but gets mounted again
+ * 2. When some dir was watched, but it was unmounted somehow, but gets mounted again.
*
* In case of 1, $userAddedWatchedDir should be true
* In case of 2, $userAddedWatchedDir should be false
*
* When $userAddedWatchedDir is true, it will set "Watched" flag to true
* otherwise, it will set "Exists" flag to true
- **/
- public static function addWatchedDir($p_path, $userAddedWatchedDir=true, $nestedWatch=false)
+ *
+ * @param mixed $p_path
+ * @param mixed $userAddedWatchedDir
+ * @param mixed $nestedWatch
+ */
+ public static function addWatchedDir($p_path, $userAddedWatchedDir = true, $nestedWatch = false)
{
- $res = self::addDir($p_path, "watched", $userAddedWatchedDir, $nestedWatch);
+ $res = self::addDir($p_path, 'watched', $userAddedWatchedDir, $nestedWatch);
- if ($res['code'] != 0) { return $res; }
+ if ($res['code'] != 0) {
+ return $res;
+ }
//convert "linked" files (Airtime <= 1.8.2) to watched files.
$propel_link_dir = CcMusicDirsQuery::create()
- ->filterByType('link')
- ->findOne();
+ ->filterByType('link')
+ ->findOne()
+ ;
//see if any linked files exist.
if (isset($propel_link_dir)) {
-
//newly added watched directory object
$propel_new_watch = CcMusicDirsQuery::create()
- ->filterByDirectory(Application_Common_OsPath::normpath($p_path)."/")
- ->findOne();
+ ->filterByDirectory(Application_Common_OsPath::normpath($p_path) . '/')
+ ->findOne()
+ ;
//any files of the deprecated "link" type.
$link_files = CcFilesQuery::create()
- ->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)
- ->filterByDbDirectory($propel_link_dir->getId())
- ->find();
+ ->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)
+ ->filterByDbDirectory($propel_link_dir->getId())
+ ->find()
+ ;
$newly_watched_dir = $propel_new_watch->getDirectory();
@@ -280,7 +299,6 @@ SQL;
//convert "link" file into a watched file.
if ((strlen($newly_watched_dir) < strlen($link_filepath)) && (substr($link_filepath, 0, strlen($newly_watched_dir)) === $newly_watched_dir)) {
-
//get the filepath path not including the watched directory.
$sub_link_filepath = substr($link_filepath, strlen($newly_watched_dir));
@@ -291,9 +309,9 @@ SQL;
}
}
- $data = array();
- $data["directory"] = $p_path;
- Application_Model_RabbitMq::SendMessageToMediaMonitor("new_watch", $data);
+ $data = [];
+ $data['directory'] = $p_path;
+ Application_Model_RabbitMq::SendMessageToMediaMonitor('new_watch', $data);
return $res;
}
@@ -304,44 +322,43 @@ SQL;
if (!$dir) {
return null;
}
- $mus_dir = new Application_Model_MusicDir($dir);
- return $mus_dir;
+ return new Application_Model_MusicDir($dir);
}
public static function getDirByPath($p_path)
{
$dir = CcMusicDirsQuery::create()
- ->filterByDirectory($p_path)
- ->findOne();
- if ($dir == NULL) {
+ ->filterByDirectory($p_path)
+ ->findOne()
+ ;
+ if ($dir == null) {
return null;
- } else {
- $mus_dir = new Application_Model_MusicDir($dir);
-
- return $mus_dir;
}
+
+ return new Application_Model_MusicDir($dir);
}
/**
- * Search and returns watched dirs
+ * Search and returns watched dirs.
*
* @param $exists search condition with exists flag
* @param $watched search condition with watched flag
*/
- public static function getWatchedDirs($exists=true, $watched=true)
+ public static function getWatchedDirs($exists = true, $watched = true)
{
- $result = array();
+ $result = [];
$dirs = CcMusicDirsQuery::create()
- ->filterByType("watched");
+ ->filterByType('watched')
+ ;
if ($exists !== null) {
$dirs = $dirs->filterByExists($exists);
}
if ($watched !== null) {
$dirs = $dirs->filterByWatched($watched);
}
- $dirs = $dirs->find();
+ $dirs = $dirs->find();
foreach ($dirs as $dir) {
$result[] = new Application_Model_MusicDir($dir);
@@ -353,56 +370,55 @@ SQL;
public static function getStorDir()
{
$dir = CcMusicDirsQuery::create()
- ->filterByType("stor")
- ->findOne();
+ ->filterByType('stor')
+ ->findOne()
+ ;
- $mus_dir = new Application_Model_MusicDir($dir);
-
- return $mus_dir;
+ return new Application_Model_MusicDir($dir);
}
public static function setStorDir($p_dir)
{
// we want to be consistent when storing dir path.
// path should always ends with trailing '/'
- $p_dir = Application_Common_OsPath::normpath($p_dir)."/";
+ $p_dir = Application_Common_OsPath::normpath($p_dir) . '/';
if (!is_dir($p_dir)) {
- return array("code"=>2, "error"=>sprintf(_("%s is not a valid directory."), $p_dir));
- } elseif (Application_Model_Preference::GetImportTimestamp()+10 > time()) {
- return array("code"=>3, "error"=>"Airtime is currently importing files. Please wait until this is complete before changing the storage directory.");
+ return ['code' => 2, 'error' => sprintf(_('%s is not a valid directory.'), $p_dir)];
+ }
+ if (Application_Model_Preference::GetImportTimestamp() + 10 > time()) {
+ return ['code' => 3, 'error' => 'Airtime is currently importing files. Please wait until this is complete before changing the storage directory.'];
}
$dir = self::getStorDir();
// if $p_dir doesn't exist in DB
$exist = $dir->getDirByPath($p_dir);
- if ($exist == NULL) {
+ if ($exist == null) {
$dir->setDirectory($p_dir);
$dirId = $dir->getId();
- $data = array();
- $data["directory"] = $p_dir;
- $data["dir_id"] = $dirId;
- Application_Model_RabbitMq::SendMessageToMediaMonitor("change_stor", $data);
+ $data = [];
+ $data['directory'] = $p_dir;
+ $data['dir_id'] = $dirId;
+ Application_Model_RabbitMq::SendMessageToMediaMonitor('change_stor', $data);
- return array("code"=>0);
- } else {
- return array("code"=>1,
- "error"=>sprintf(_("%s is already set as the current storage dir or in the watched folders list."), $p_dir));
+ return ['code' => 0];
}
+
+ return ['code' => 1,
+ 'error' => sprintf(_('%s is already set as the current storage dir or in the watched folders list.'), $p_dir), ];
}
public static function getWatchedDirFromFilepath($p_filepath)
{
$dirs = CcMusicDirsQuery::create()
- ->filterByType(array("watched", "stor"))
- ->filterByExists(true)
- ->filterByWatched(true)
- ->find();
+ ->filterByType(['watched', 'stor'])
+ ->filterByExists(true)
+ ->filterByWatched(true)
+ ->find()
+ ;
foreach ($dirs as $dir) {
$directory = $dir->getDirectory();
if (substr($p_filepath, 0, strlen($directory)) === $directory) {
- $mus_dir = new Application_Model_MusicDir($dir);
-
- return $mus_dir;
+ return new Application_Model_MusicDir($dir);
}
}
@@ -411,32 +427,34 @@ SQL;
/** There are 2 cases where this function can be called.
* 1. When watched dir was removed
- * 2. When some dir was watched, but it was unmounted
+ * 2. When some dir was watched, but it was unmounted.
*
* In case of 1, $userAddedWatchedDir should be true
* In case of 2, $userAddedWatchedDir should be false
*
* When $userAddedWatchedDir is true, it will set "Watched" flag to false
* otherwise, it will set "Exists" flag to true
- **/
- public static function removeWatchedDir($p_dir, $userAddedWatchedDir=true)
+ *
+ * @param mixed $p_dir
+ * @param mixed $userAddedWatchedDir
+ */
+ public static function removeWatchedDir($p_dir, $userAddedWatchedDir = true)
{
//make sure that $p_dir has a trailing "/"
- $real_path = Application_Common_OsPath::normpath($p_dir)."/";
- if ($real_path != "/") {
+ $real_path = Application_Common_OsPath::normpath($p_dir) . '/';
+ if ($real_path != '/') {
$p_dir = $real_path;
}
$dir = Application_Model_MusicDir::getDirByPath($p_dir);
if (is_null($dir)) {
- return array("code"=>1, "error"=>sprintf(_("%s doesn't exist in the watched list."), $p_dir));
- } else {
- $dir->remove($userAddedWatchedDir);
- $data = array();
- $data["directory"] = $p_dir;
- Application_Model_RabbitMq::SendMessageToMediaMonitor("remove_watch", $data);
-
- return array("code"=>0);
+ return ['code' => 1, 'error' => sprintf(_("%s doesn't exist in the watched list."), $p_dir)];
}
+ $dir->remove($userAddedWatchedDir);
+ $data = [];
+ $data['directory'] = $p_dir;
+ Application_Model_RabbitMq::SendMessageToMediaMonitor('remove_watch', $data);
+
+ return ['code' => 0];
}
public static function splitFilePath($p_filepath)
@@ -450,19 +468,18 @@ SQL;
$length_dir = strlen($mus_dir->getDirectory());
$fp = substr($p_filepath, $length_dir);
- return array($mus_dir->getDirectory(), trim($fp));
+ return [$mus_dir->getDirectory(), trim($fp)];
}
-
- public function unhideFiles()
+ public function unhideFiles()
{
$files = $this->_dir->getCcFiless();
$hid = 0;
foreach ($files as $file) {
- $hid++;
+ ++$hid;
$file->setDbHidden(false);
$file->save();
}
- Logging::info("unhide '$hid' files");
+ Logging::info("unhide '{$hid}' files");
}
}
diff --git a/legacy/application/models/Playlist.php b/legacy/application/models/Playlist.php
index 4c626d53d..883356a83 100644
--- a/legacy/application/models/Playlist.php
+++ b/legacy/application/models/Playlist.php
@@ -1,17 +1,15 @@
"",
- "pos" => "",
- "cliplength" => "",
- "cuein" => "00:00:00",
- "cueout" => "00:00:00",
- "fadein" => "0.0",
- "fadeout" => "0.0",
- "crossfadeDuration" => 0
- );
+ private $plItem = [
+ 'id' => '',
+ 'pos' => '',
+ 'cliplength' => '',
+ 'cuein' => '00:00:00',
+ 'cueout' => '00:00:00',
+ 'fadein' => '0.0',
+ 'fadeout' => '0.0',
+ 'crossfadeDuration' => 0,
+ ];
//using propel's phpNames.
- private $categories = array(
- "dc:title" => "Name",
- "dc:creator" => "Creator",
- "dc:description" => "Description",
- "dcterms:extent" => "Length"
- );
+ private $categories = [
+ 'dc:title' => 'Name',
+ 'dc:creator' => 'Creator',
+ 'dc:description' => 'Description',
+ 'dcterms:extent' => 'Length',
+ ];
- public function __construct($id=null, $con=null)
+ public function __construct($id = null, $con = null)
{
if (isset($id)) {
$this->pl = CcPlaylistQuery::create()->findPK($id);
@@ -59,13 +57,13 @@ class Application_Model_Playlist implements Application_Model_LibraryEditable
}
} else {
$this->pl = new CcPlaylist();
- $this->pl->setDbUTime(new DateTime("now", new DateTimeZone("UTC")));
+ $this->pl->setDbUTime(new DateTime('now', new DateTimeZone('UTC')));
$this->pl->save();
}
- $this->plItem["fadein"] = Application_Model_Preference::GetDefaultFadeIn();
- $this->plItem["fadeout"] = Application_Model_Preference::GetDefaultFadeOut();
- $this->plItem["crossfadeDuration"] = Application_Model_Preference::GetDefaultCrossfadeDuration();
+ $this->plItem['fadein'] = Application_Model_Preference::GetDefaultFadeIn();
+ $this->plItem['fadeout'] = Application_Model_Preference::GetDefaultFadeOut();
+ $this->plItem['crossfadeDuration'] = Application_Model_Preference::GetDefaultCrossfadeDuration();
$this->con = isset($con) ? $con : Propel::getConnection(CcPlaylistPeer::DATABASE_NAME);
$this->id = $this->pl->getDbId();
@@ -81,20 +79,20 @@ class Application_Model_Playlist implements Application_Model_LibraryEditable
return $this->id;
}
- /**
- * Rename stored virtual playlist
+ /**
+ * Rename stored virtual playlist.
*
* @param string $p_newname
*/
public function setName($p_newname)
{
$this->pl->setDbName($p_newname);
- $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
+ $this->pl->setDbMtime(new DateTime('now', new DateTimeZone('UTC')));
$this->pl->save($this->con);
}
- /**
- * Get mnemonic playlist name
+ /**
+ * Get mnemonic playlist name.
*
* @return string
*/
@@ -106,7 +104,7 @@ class Application_Model_Playlist implements Application_Model_LibraryEditable
public function setDescription($p_description)
{
$this->pl->setDbDescription($p_description);
- $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
+ $this->pl->setDbMtime(new DateTime('now', new DateTimeZone('UTC')));
$this->pl->save($this->con);
}
@@ -128,7 +126,7 @@ class Application_Model_Playlist implements Application_Model_LibraryEditable
public function setCreator($p_id)
{
$this->pl->setDbCreatorId($p_id);
- $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
+ $this->pl->setDbMtime(new DateTime('now', new DateTimeZone('UTC')));
$this->pl->save($this->con);
}
@@ -146,13 +144,15 @@ class Application_Model_Playlist implements Application_Model_LibraryEditable
/**
* Get the entire playlist as a two dimentional array, sorted in order of play.
- * @param boolean $filterFiles if this is true, it will only return files that has
- * file_exists flag set to true
+ *
+ * @param bool $filterFiles if this is true, it will only return files that has
+ * file_exists flag set to true
+ *
* @return array
*/
- public function getContents($filterFiles=false)
+ public function getContents($filterFiles = false)
{
- $sql = <<$this->id, ':playlist_id2'=>$this->id, ':playlist_id3'=>$this->id);
+ $params = [
+ ':playlist_id1' => $this->id, ':playlist_id2' => $this->id, ':playlist_id3' => $this->id, ];
if ($filterFiles) {
$params[':file_exists'] = $filterFiles;
}
@@ -239,15 +239,14 @@ SQL;
$offset = 0;
foreach ($rows as &$row) {
-
- //Logging::info($row);
-
+ //Logging::info($row);
+
$clipSec = Application_Common_DateHelper::playlistTimeToSeconds($row['length']);
$row['trackSec'] = $clipSec;
-
+
$row['cueInSec'] = Application_Common_DateHelper::playlistTimeToSeconds($row['cuein']);
$row['cueOutSec'] = Application_Common_DateHelper::playlistTimeToSeconds($row['cueout']);
-
+
$trackoffset = $row['trackoffset'];
$offset += $clipSec;
$offset -= $trackoffset;
@@ -269,7 +268,7 @@ SQL;
$fades = $this->getFadeInfo($row['position']);
$row['fadein'] = $fades[0];
$row['fadeout'] = $fades[1];
-
+
// format the cues in format 00:00:00(.0)
// we need to add the '.0' for cues and not fades
// because propel takes care of this for us
@@ -282,30 +281,32 @@ SQL;
$row['orig_length'] = $formatter->format();
// XSS exploit prevention
- $row["track_title"] = htmlspecialchars($row["track_title"]);
- $row["creator"] = htmlspecialchars($row["creator"]);
+ $row['track_title'] = htmlspecialchars($row['track_title']);
+ $row['creator'] = htmlspecialchars($row['creator']);
}
return $rows;
}
/**
- * The database stores fades in 00:00:00 Time format with optional millisecond resolution .000000
- * but this isn't practical since fades shouldn't be very long usuall 1 second or less. This function
- * will normalize the fade so that it looks like 00.000000 to the user.
- **/
+ * The database stores fades in 00:00:00 Time format with optional millisecond resolution .000000
+ * but this isn't practical since fades shouldn't be very long usuall 1 second or less. This function
+ * will normalize the fade so that it looks like 00.000000 to the user.
+ *
+ * @param mixed $fade
+ */
public function normalizeFade($fade)
{
//First get rid of the first six characters 00:00: which will be added back later for db update
$fade = substr($fade, 6);
//Second add .000000 if the fade does't have milliseconds format already
- $dbFadeStrPos = strpos( $fade, '.' );
+ $dbFadeStrPos = strpos($fade, '.');
if ($dbFadeStrPos === false) {
- $fade .= '.000000';
+ $fade .= '.000000';
} else {
while (strlen($fade) < 9) {
- $fade .= '0';
+ $fade .= '0';
}
}
@@ -319,9 +320,9 @@ SQL;
$ids = $this->getIdsOfDynamicBlocks();
if (count($ids) > 0) {
return true;
- } else {
- return false;
}
+
+ return false;
}
public function getIdsOfDynamicBlocks()
@@ -329,10 +330,8 @@ SQL;
$sql = "SELECT bl.id FROM cc_playlistcontents as pc
JOIN cc_block as bl ON pc.type=2 AND pc.block_id=bl.id AND bl.type='dynamic'
WHERE playlist_id=:playlist_id AND pc.type=2";
-
- $result = Application_Common_Database::prepareAndExecute($sql, array(':playlist_id'=>$this->id));
- return $result;
+ return Application_Common_Database::prepareAndExecute($sql, [':playlist_id' => $this->id]);
}
//aggregate column on playlistcontents cliplength column.
@@ -344,36 +343,36 @@ SQL;
foreach ($ids as $id) {
$bl = new Application_Model_Block($id['id']);
if ($bl->hasItemLimit()) {
- return "N/A";
+ return 'N/A';
}
}
$formatter = new LengthFormatter($length);
- return "~".$formatter->format();
- } else {
- return $this->pl->getDbLength();
+ return '~' . $formatter->format();
}
+
+ return $this->pl->getDbLength();
}
private function insertPlaylistElement($info)
{
$row = new CcPlaylistcontents();
$row->setDbPlaylistId($this->id);
- $row->setDbPosition($info["pos"]);
- $row->setDbCliplength($info["cliplength"]);
- $row->setDbCuein($info["cuein"]);
- $row->setDbCueout($info["cueout"]);
- $row->setDbFadein(Application_Common_DateHelper::secondsToPlaylistTime($info["fadein"]));
- $row->setDbFadeout(Application_Common_DateHelper::secondsToPlaylistTime($info["fadeout"]));
- if ($info["ftype"] == "audioclip") {
- $row->setDbFileId($info["id"]);
- $row->setDbTrackOffset($info["crossfadeDuration"]);
+ $row->setDbPosition($info['pos']);
+ $row->setDbCliplength($info['cliplength']);
+ $row->setDbCuein($info['cuein']);
+ $row->setDbCueout($info['cueout']);
+ $row->setDbFadein(Application_Common_DateHelper::secondsToPlaylistTime($info['fadein']));
+ $row->setDbFadeout(Application_Common_DateHelper::secondsToPlaylistTime($info['fadeout']));
+ if ($info['ftype'] == 'audioclip') {
+ $row->setDbFileId($info['id']);
+ $row->setDbTrackOffset($info['crossfadeDuration']);
$type = 0;
- } elseif ($info["ftype"] == "stream") {
- $row->setDbStreamId($info["id"]);
+ } elseif ($info['ftype'] == 'stream') {
+ $row->setDbStreamId($info['id']);
$type = 1;
- } elseif ($info["ftype"] == "block") {
- $row->setDbBlockId($info["id"]);
+ } elseif ($info['ftype'] == 'block') {
+ $row->setDbBlockId($info['id']);
$type = 2;
}
$row->setDbType($type);
@@ -385,68 +384,61 @@ SQL;
$this->pl = CcPlaylistQuery::create()->findPK($this->id);
}
- /*
- *
- */
private function buildEntry($p_item, $pos)
{
$objType = $p_item[1];
$objId = $p_item[0];
if ($objType == 'audioclip') {
$obj = CcFilesQuery::create()->findPK($objId, $this->con);
- } elseif ($objType == "stream") {
+ } elseif ($objType == 'stream') {
$obj = CcWebstreamQuery::create()->findPK($objId, $this->con);
- } elseif ($objType == "block") {
+ } elseif ($objType == 'block') {
$obj = CcBlockQuery::create()->findPK($objId, $this->con);
} else {
- throw new Exception("Unknown file type");
+ throw new Exception('Unknown file type');
}
if (isset($obj)) {
if (($obj instanceof CcFiles && $obj->visible())
- || $obj instanceof CcWebstream ||
- $obj instanceof CcBlock) {
-
+ || $obj instanceof CcWebstream
+ || $obj instanceof CcBlock) {
$entry = $this->plItem;
- $entry["id"] = $obj->getDbId();
- $entry["pos"] = $pos;
- $entry["cliplength"] = $obj->getDbLength();
-
- if ($obj instanceof CcFiles && $obj) {
-
- $entry["cuein"] = isset($p_item['cuein']) ?
- $p_item['cuein'] : $obj->getDbCuein();
-
- $entry["cueout"] = isset($p_item['cueout']) ?
- $p_item['cueout'] : $obj->getDbCueout();
+ $entry['id'] = $obj->getDbId();
+ $entry['pos'] = $pos;
+ $entry['cliplength'] = $obj->getDbLength();
- $cue_in = isset($p_item['cueInSec']) ?
- $p_item['cueInSec'] : Application_Common_DateHelper::calculateLengthInSeconds($entry['cuein']);
-
- $cue_out = isset($p_item['cueOutSec']) ?
- $p_item['cueOutSec'] : Application_Common_DateHelper::calculateLengthInSeconds($entry['cueout']);
-
- $entry["cliplength"] = isset($p_item['length']) ?
- $p_item['length'] : Application_Common_DateHelper::secondsToPlaylistTime($cue_out-$cue_in);
- }
- elseif ($obj instanceof CcWebstream && $obj) {
- $entry["cuein"] = "00:00:00";
- $entry["cueout"] = $entry["cliplength"];
+ if ($obj instanceof CcFiles && $obj) {
+ $entry['cuein'] = isset($p_item['cuein']) ?
+ $p_item['cuein'] : $obj->getDbCuein();
+
+ $entry['cueout'] = isset($p_item['cueout']) ?
+ $p_item['cueout'] : $obj->getDbCueout();
+
+ $cue_in = isset($p_item['cueInSec']) ?
+ $p_item['cueInSec'] : Application_Common_DateHelper::calculateLengthInSeconds($entry['cuein']);
+
+ $cue_out = isset($p_item['cueOutSec']) ?
+ $p_item['cueOutSec'] : Application_Common_DateHelper::calculateLengthInSeconds($entry['cueout']);
+
+ $entry['cliplength'] = isset($p_item['length']) ?
+ $p_item['length'] : Application_Common_DateHelper::secondsToPlaylistTime($cue_out - $cue_in);
+ } elseif ($obj instanceof CcWebstream && $obj) {
+ $entry['cuein'] = '00:00:00';
+ $entry['cueout'] = $entry['cliplength'];
}
- $entry["ftype"] = $objType;
-
- $entry["fadein"] = isset($p_item['fadein']) ?
- $p_item['fadein'] : $entry["fadein"];
-
- $entry["fadeout"] = isset($p_item['fadeout']) ?
- $p_item['fadeout'] : $entry["fadeout"];
+ $entry['ftype'] = $objType;
+
+ $entry['fadein'] = isset($p_item['fadein']) ?
+ $p_item['fadein'] : $entry['fadein'];
+
+ $entry['fadeout'] = isset($p_item['fadeout']) ?
+ $p_item['fadeout'] : $entry['fadeout'];
}
return $entry;
- }
- else {
- throw new Exception("trying to add a object that does not exist.");
}
+
+ throw new Exception('trying to add a object that does not exist.');
}
/*
@@ -457,15 +449,13 @@ SQL;
* @param string (before|after) $addAfter
* whether to add the clips before or after the selected item.
*/
- public function addAudioClips($p_items, $p_afterItem=null, $addType = 'after')
+ public function addAudioClips($p_items, $p_afterItem = null, $addType = 'after')
{
$this->con->beginTransaction();
- $contentsToUpdate = array();
+ $contentsToUpdate = [];
try {
-
if (is_numeric($p_afterItem)) {
-
$afterItem = CcPlaylistcontentsQuery::create()->findPK($p_afterItem);
$index = $afterItem->getDbPosition();
@@ -475,10 +465,9 @@ SQL;
->filterByDbPlaylistId($this->id)
->filterByDbPosition($pos, Criteria::GREATER_EQUAL)
->orderByDbPosition()
- ->find($this->con);
-
+ ->find($this->con)
+ ;
} else {
-
//add to the end of the playlist
if ($addType == 'after') {
$pos = $this->getSize();
@@ -490,75 +479,78 @@ SQL;
$contentsToUpdate = CcPlaylistcontentsQuery::create()
->filterByDbPlaylistId($this->id)
->orderByDbPosition()
- ->find($this->con);
+ ->find($this->con)
+ ;
}
$contentsToUpdate = CcPlaylistcontentsQuery::create()
->filterByDbPlaylistId($this->id)
->filterByDbPosition($pos, Criteria::GREATER_EQUAL)
->orderByDbPosition()
- ->find($this->con);
-
+ ->find($this->con)
+ ;
}
foreach ($p_items as $ac) {
$res = $this->insertPlaylistElement($this->buildEntry($ac, $pos));
// update is_playlist flag in cc_files to indicate the
// file belongs to a playlist or block (in this case a playlist)
- if ($ac[1] == "audioclip") {
+ if ($ac[1] == 'audioclip') {
$db_file = CcFilesQuery::create()->findPk($ac[0], $this->con);
$db_file->setDbIsPlaylist(true)->save($this->con);
}
-
+
$pos = $pos + 1;
}
//reset the positions of the remaining items.
- for ($i = 0; $i < count($contentsToUpdate); $i++) {
+ for ($i = 0; $i < count($contentsToUpdate); ++$i) {
$contentsToUpdate[$i]->setDbPosition($pos);
$contentsToUpdate[$i]->save($this->con);
$pos = $pos + 1;
}
- $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
+ $this->pl->setDbMtime(new DateTime('now', new DateTimeZone('UTC')));
$this->pl->save($this->con);
$this->con->commit();
} catch (Exception $e) {
$this->con->rollback();
+
throw $e;
}
}
/**
- * Move audioClip to the new position in the playlist
+ * Move audioClip to the new position in the playlist.
*
* @param array $p_items
- * array of unique ids of the selected items
- * @param int $p_afterItem
- * unique id of the item to move the clip after
+ * array of unique ids of the selected items
+ * @param int $p_afterItem
+ * unique id of the item to move the clip after
*/
- public function moveAudioClips($p_items, $p_afterItem=NULL)
+ public function moveAudioClips($p_items, $p_afterItem = null)
{
$this->con->beginTransaction();
try {
-
$contentsToMove = CcPlaylistcontentsQuery::create()
- ->filterByDbId($p_items, Criteria::IN)
- ->orderByDbPosition()
- ->find($this->con);
+ ->filterByDbId($p_items, Criteria::IN)
+ ->orderByDbPosition()
+ ->find($this->con)
+ ;
$otherContent = CcPlaylistcontentsQuery::create()
- ->filterByDbId($p_items, Criteria::NOT_IN)
- ->filterByDbPlaylistId($this->id)
- ->orderByDbPosition()
- ->find($this->con);
+ ->filterByDbId($p_items, Criteria::NOT_IN)
+ ->filterByDbPlaylistId($this->id)
+ ->orderByDbPosition()
+ ->find($this->con)
+ ;
$pos = 0;
//moving items to beginning of the playlist.
if (is_null($p_afterItem)) {
- Logging::info("moving items to beginning of playlist");
+ Logging::info('moving items to beginning of playlist');
foreach ($contentsToMove as $item) {
Logging::info("item {$item->getDbId()} to pos {$pos}");
@@ -595,59 +587,62 @@ SQL;
$this->con->commit();
} catch (Exception $e) {
$this->con->rollback();
+
throw $e;
}
$this->pl = CcPlaylistQuery::create()->findPK($this->id);
- $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
+ $this->pl->setDbMtime(new DateTime('now', new DateTimeZone('UTC')));
$this->pl->save($this->con);
}
/**
- * Remove audioClip from playlist
+ * Remove audioClip from playlist.
*
* @param array $p_items
- * array of unique item ids to remove from the playlist..
+ * array of unique item ids to remove from the playlist..
*/
public function delAudioClips($p_items)
{
-
$this->con->beginTransaction();
try {
-
// we need to get the file id of the item we are deleting
// before the item gets deleted from the playlist
$itemsToDelete = CcPlaylistcontentsQuery::create()
->filterByPrimaryKeys($p_items)
->filterByDbFileId(null, Criteria::NOT_EQUAL)
- ->find($this->con);
+ ->find($this->con)
+ ;
CcPlaylistcontentsQuery::create()
->findPKs($p_items)
- ->delete($this->con);
+ ->delete($this->con)
+ ;
// now that the items have been deleted we can update the
// is_playlist flag in cc_files
Application_Model_StoredFile::setIsPlaylist($itemsToDelete, 'playlist', false);
-
+
$contents = CcPlaylistcontentsQuery::create()
->filterByDbPlaylistId($this->id)
->orderByDbPosition()
- ->find($this->con);
+ ->find($this->con)
+ ;
//reset the positions of the remaining items.
- for ($i = 0; $i < count($contents); $i++) {
+ for ($i = 0; $i < count($contents); ++$i) {
$contents[$i]->setDbPosition($i);
$contents[$i]->save($this->con);
}
- $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
+ $this->pl->setDbMtime(new DateTime('now', new DateTimeZone('UTC')));
$this->pl->save($this->con);
$this->con->commit();
} catch (Exception $e) {
$this->con->rollback();
+
throw $e;
}
}
@@ -658,112 +653,114 @@ SQL;
->joinWith(CcFilesPeer::OM_CLASS)
->filterByDbPlaylistId($this->id)
->filterByDbPosition($pos)
- ->findOne();
+ ->findOne()
+ ;
if (!$row) {
- return NULL;
+ return null;
}
//Propel returns values in form 00.000000 format which is for only seconds.
//We only want to display 1 decimal
$fadeIn = substr($row->getDbFadein(), 0, 4);
$fadeOut = substr($row->getDbFadeout(), 0, 4);
- return array($fadeIn, $fadeOut);
+ return [$fadeIn, $fadeOut];
}
-
+
/*
* create a crossfade from item in cc_playlist_contents with $id1 to item $id2.
- *
+ *
* $fadeOut length of fade out in seconds if $id1
* $fadeIn length of fade in in seconds of $id2
* $offset time in seconds from end of $id1 that $id2 will begin to play.
*/
public function createCrossfade($id1, $fadeOut, $id2, $fadeIn, $offset)
{
- $this->con->beginTransaction();
-
- if (!isset($offset)) {
- $offset = Application_Model_Preference::GetDefaultCrossfadeDuration();
- }
-
- try {
- if (isset($id1)) {
- $this->changeFadeInfo($id1, null, $fadeOut);
- }
- if (isset($id2)) {
- $this->changeFadeInfo($id2, $fadeIn, null, $offset);
- }
-
- $this->con->commit();
-
- } catch (Exception $e) {
+ $this->con->beginTransaction();
+
+ if (!isset($offset)) {
+ $offset = Application_Model_Preference::GetDefaultCrossfadeDuration();
+ }
+
+ try {
+ if (isset($id1)) {
+ $this->changeFadeInfo($id1, null, $fadeOut);
+ }
+ if (isset($id2)) {
+ $this->changeFadeInfo($id2, $fadeIn, null, $offset);
+ }
+
+ $this->con->commit();
+ } catch (Exception $e) {
$this->con->rollback();
+
throw $e;
- }
+ }
}
/**
- * Change fadeIn and fadeOut values for playlist Element
+ * Change fadeIn and fadeOut values for playlist Element.
*
- * @param int $id
- * id of audioclip in playlist contents table.
- * @param string $fadeIn
- * new value in ss.ssssss or extent format
- * @param string $fadeOut
- * new value in ss.ssssss or extent format
- * @return boolean
+ * @param int $id
+ * id of audioclip in playlist contents table
+ * @param string $fadeIn
+ * new value in ss.ssssss or extent format
+ * @param string $fadeOut
+ * new value in ss.ssssss or extent format
+ * @param null|mixed $offset
+ *
+ * @return bool
*/
- public function changeFadeInfo($id, $fadeIn, $fadeOut, $offset=null)
+ public function changeFadeInfo($id, $fadeIn, $fadeOut, $offset = null)
{
//See issue CC-2065, pad the fadeIn and fadeOut so that it is TIME compatable with the DB schema
//For the top level PlayList either fadeIn or fadeOut will sometimes be Null so need a gaurd against
- //setting it to nonNull for checks down below
- $fadeIn = $fadeIn?'00:00:'.$fadeIn:$fadeIn;
- $fadeOut = $fadeOut?'00:00:'.$fadeOut:$fadeOut;
-
+ //setting it to nonNull for checks down below
+ $fadeIn = $fadeIn ? '00:00:' . $fadeIn : $fadeIn;
+ $fadeOut = $fadeOut ? '00:00:' . $fadeOut : $fadeOut;
+
$this->con->beginTransaction();
try {
$row = CcPlaylistcontentsQuery::create()->findPK($id);
if (is_null($row)) {
- throw new Exception("Playlist item does not exist.");
+ throw new Exception('Playlist item does not exist.');
}
$clipLength = $row->getDbCliplength();
if (!is_null($fadeIn)) {
-
$sql = "SELECT :fadein::INTERVAL > INTERVAL '{$clipLength}'";
- if (Application_Common_Database::prepareAndExecute($sql, array(':fadein'=>$fadeIn), 'column')) {
+ if (Application_Common_Database::prepareAndExecute($sql, [':fadein' => $fadeIn], 'column')) {
//"Fade In can't be larger than overall playlength.";
$fadeIn = $clipLength;
}
$row->setDbFadein($fadeIn);
-
+
if (!is_null($offset)) {
- $row->setDbTrackOffset($offset);
- $row->save($this->con);
+ $row->setDbTrackOffset($offset);
+ $row->save($this->con);
}
}
if (!is_null($fadeOut)) {
-
$sql = "SELECT :fadeout::INTERVAL > INTERVAL '{$clipLength}'";
- if (Application_Common_Database::prepareAndExecute($sql, array(':fadeout'=>$fadeOut), 'column')) {
+ if (Application_Common_Database::prepareAndExecute($sql, [':fadeout' => $fadeOut], 'column')) {
//Fade Out can't be larger than overall playlength.";
$fadeOut = $clipLength;
}
$row->setDbFadeout($fadeOut);
}
- $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
+ $this->pl->setDbMtime(new DateTime('now', new DateTimeZone('UTC')));
$this->pl->save($this->con);
-
+
$this->con->commit();
} catch (Exception $e) {
$this->con->rollback();
+
throw $e;
}
- return array("fadeIn" => $fadeIn, "fadeOut" => $fadeOut);
+ return ['fadeIn' => $fadeIn, 'fadeOut' => $fadeOut];
}
public function setfades($fadein, $fadeout)
@@ -773,7 +770,8 @@ SQL;
$row = CcPlaylistcontentsQuery::create()
->filterByDbPlaylistId($this->id)
->filterByDbPosition(0)
- ->findOne($this->con);
+ ->findOne($this->con)
+ ;
$this->changeFadeInfo($row->getDbId(), $fadein, null);
}
@@ -781,34 +779,37 @@ SQL;
Logging::info("Setting playlist fade out {$fadeout}");
$row = CcPlaylistcontentsQuery::create()
->filterByDbPlaylistId($this->id)
- ->filterByDbPosition($this->getSize()-1)
- ->findOne($this->con);
+ ->filterByDbPosition($this->getSize() - 1)
+ ->findOne($this->con)
+ ;
$this->changeFadeInfo($row->getDbId(), null, $fadeout);
}
}
/**
- * Change cueIn/cueOut values for playlist element
+ * Change cueIn/cueOut values for playlist element.
*
- * @param int $pos
- * position of audioclip in playlist
+ * @param int $pos
+ * position of audioclip in playlist
* @param string $cueIn
- * new value in ss.ssssss or extent format
+ * new value in ss.ssssss or extent format
* @param string $cueOut
- * new value in ss.ssssss or extent format
- * @return boolean or pear error object
+ * new value in ss.ssssss or extent format
+ * @param mixed $id
+ *
+ * @return bool or pear error object
*/
public function changeClipLength($id, $cueIn, $cueOut)
{
$this->con->beginTransaction();
- $errArray= array();
+ $errArray = [];
try {
if (is_null($cueIn) && is_null($cueOut)) {
- $errArray["error"] = _("Cue in and cue out are null.");
- $errArray["type"] = self::CUE_ALL_ERROR;
+ $errArray['error'] = _('Cue in and cue out are null.');
+ $errArray['type'] = self::CUE_ALL_ERROR;
return $errArray;
}
@@ -816,10 +817,11 @@ SQL;
$row = CcPlaylistcontentsQuery::create()
->joinWith(CcFilesPeer::OM_CLASS)
->filterByPrimaryKey($id)
- ->findOne($this->con);
+ ->findOne($this->con)
+ ;
if (is_null($row)) {
- throw new Exception("Playlist item does not exist.");
+ throw new Exception('Playlist item does not exist.');
}
$oldCueIn = $row->getDBCuein();
@@ -831,73 +833,69 @@ SQL;
$origLength = $file->getDbLength();
if (!is_null($cueIn) && !is_null($cueOut)) {
-
- if ($cueOut === "") {
+ if ($cueOut === '') {
$cueOut = $origLength;
}
- $sql = "SELECT :cueIn::INTERVAL > :cueOut::INTERVAL";
- if (Application_Common_Database::prepareAndExecute($sql, array(':cueIn'=>$cueIn, ':cueOut'=>$cueOut), 'column')) {
- $errArray["error"] = _("Can't set cue in to be larger than cue out.");
- $errArray["type"] = self::CUE_IN_ERROR;
+ $sql = 'SELECT :cueIn::INTERVAL > :cueOut::INTERVAL';
+ if (Application_Common_Database::prepareAndExecute($sql, [':cueIn' => $cueIn, ':cueOut' => $cueOut], 'column')) {
+ $errArray['error'] = _("Can't set cue in to be larger than cue out.");
+ $errArray['type'] = self::CUE_IN_ERROR;
return $errArray;
}
- $sql = "SELECT :cueOut::INTERVAL > :origLength::INTERVAL";
- if (Application_Common_Database::prepareAndExecute($sql, array(':cueOut'=>$cueOut, ':origLength'=>$origLength), 'column')) {
- $errArray["error"] = _("Can't set cue out to be greater than file length.");
- $errArray["type"] = self::CUE_OUT_ERROR;
+ $sql = 'SELECT :cueOut::INTERVAL > :origLength::INTERVAL';
+ if (Application_Common_Database::prepareAndExecute($sql, [':cueOut' => $cueOut, ':origLength' => $origLength], 'column')) {
+ $errArray['error'] = _("Can't set cue out to be greater than file length.");
+ $errArray['type'] = self::CUE_OUT_ERROR;
return $errArray;
}
- $sql = "SELECT :cueOut::INTERVAL - :cueIn::INTERVAL";
- $cliplength = Application_Common_Database::prepareAndExecute($sql, array(':cueOut'=>$cueOut, ':cueIn'=>$cueIn), 'column');
+ $sql = 'SELECT :cueOut::INTERVAL - :cueIn::INTERVAL';
+ $cliplength = Application_Common_Database::prepareAndExecute($sql, [':cueOut' => $cueOut, ':cueIn' => $cueIn], 'column');
$row->setDbCuein($cueIn);
$row->setDbCueout($cueOut);
$row->setDBCliplength($cliplength);
-
} elseif (!is_null($cueIn)) {
-
- $sql = "SELECT :cueIn::INTERVAL > :oldCueOut::INTERVAL";
- if (Application_Common_Database::prepareAndExecute($sql, array(':cueIn'=>$cueIn, ':oldCueOut'=>$oldCueOut), 'column')) {
- $errArray["error"] = _("Can't set cue in to be larger than cue out.");
- $errArray["type"] = self::CUE_IN_ERROR;
+ $sql = 'SELECT :cueIn::INTERVAL > :oldCueOut::INTERVAL';
+ if (Application_Common_Database::prepareAndExecute($sql, [':cueIn' => $cueIn, ':oldCueOut' => $oldCueOut], 'column')) {
+ $errArray['error'] = _("Can't set cue in to be larger than cue out.");
+ $errArray['type'] = self::CUE_IN_ERROR;
return $errArray;
}
- $sql = "SELECT :oldCueOut::INTERVAL - :cueIn::INTERVAL";
- $cliplength = Application_Common_Database::prepareAndExecute($sql, array(':cueIn'=>$cueIn, ':oldCueOut'=>$oldCueOut), 'column');
+ $sql = 'SELECT :oldCueOut::INTERVAL - :cueIn::INTERVAL';
+ $cliplength = Application_Common_Database::prepareAndExecute($sql, [':cueIn' => $cueIn, ':oldCueOut' => $oldCueOut], 'column');
$row->setDbCuein($cueIn);
$row->setDBCliplength($cliplength);
} elseif (!is_null($cueOut)) {
-
- if ($cueOut === "") {
+ if ($cueOut === '') {
$cueOut = $origLength;
}
- $sql = "SELECT :cueOut::INTERVAL < :oldCueIn::INTERVAL";
- if (Application_Common_Database::prepareAndExecute($sql, array(':cueOut'=>$cueOut, ':oldCueIn'=>$oldCueIn), 'column')) {
- $errArray["error"] = _("Can't set cue out to be smaller than cue in.");
- $errArray["type"] = self::CUE_OUT_ERROR;
+ $sql = 'SELECT :cueOut::INTERVAL < :oldCueIn::INTERVAL';
+ if (Application_Common_Database::prepareAndExecute($sql, [':cueOut' => $cueOut, ':oldCueIn' => $oldCueIn], 'column')) {
+ $errArray['error'] = _("Can't set cue out to be smaller than cue in.");
+ $errArray['type'] = self::CUE_OUT_ERROR;
return $errArray;
}
- $sql = "SELECT :cueOut::INTERVAL > :origLength::INTERVAL";
- if (Application_Common_Database::prepareAndExecute($sql, array(':cueOut'=>$cueOut, ':origLength'=>$origLength), 'column')) {
- $errArray["error"] = _("Can't set cue out to be greater than file length.");
- $errArray["type"] = self::CUE_OUT_ERROR;
+ $sql = 'SELECT :cueOut::INTERVAL > :origLength::INTERVAL';
+ if (Application_Common_Database::prepareAndExecute($sql, [':cueOut' => $cueOut, ':origLength' => $origLength], 'column')) {
+ $errArray['error'] = _("Can't set cue out to be greater than file length.");
+ $errArray['type'] = self::CUE_OUT_ERROR;
return $errArray;
}
- $sql = "SELECT :cueOut::INTERVAL - :oldCueIn::INTERVAL";
- $cliplength = Application_Common_Database::prepareAndExecute($sql, array(':cueOut'=>$cueOut, ':oldCueIn'=>$oldCueIn), 'column');
+ $sql = 'SELECT :cueOut::INTERVAL - :oldCueIn::INTERVAL';
+ $cliplength = Application_Common_Database::prepareAndExecute($sql, [':cueOut' => $cueOut, ':oldCueIn' => $oldCueIn], 'column');
$row->setDbCueout($cueOut);
$row->setDBCliplength($cliplength);
@@ -905,40 +903,41 @@ SQL;
$cliplength = $row->getDbCliplength();
- $sql = "SELECT :fadeIn::INTERVAL > :cliplength::INTERVAL";
- if (Application_Common_Database::prepareAndExecute($sql, array(':fadeIn'=>$fadeIn, ':cliplength'=>$cliplength), 'column')) {
+ $sql = 'SELECT :fadeIn::INTERVAL > :cliplength::INTERVAL';
+ if (Application_Common_Database::prepareAndExecute($sql, [':fadeIn' => $fadeIn, ':cliplength' => $cliplength], 'column')) {
$fadeIn = $cliplength;
$row->setDbFadein($fadeIn);
}
- $sql = "SELECT :fadeOut::INTERVAL > :cliplength::INTERVAL";
- if (Application_Common_Database::prepareAndExecute($sql, array(':fadeOut'=>$fadeOut, ':cliplength'=>$cliplength), 'column')) {
+ $sql = 'SELECT :fadeOut::INTERVAL > :cliplength::INTERVAL';
+ if (Application_Common_Database::prepareAndExecute($sql, [':fadeOut' => $fadeOut, ':cliplength' => $cliplength], 'column')) {
$fadeOut = $cliplength;
$row->setDbFadein($fadeOut);
}
$row->save($this->con);
- $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
+ $this->pl->setDbMtime(new DateTime('now', new DateTimeZone('UTC')));
$this->pl->save($this->con);
$this->con->commit();
} catch (Exception $e) {
$this->con->rollback();
+
throw $e;
}
- return array("cliplength"=> $cliplength, "cueIn"=> $cueIn, "cueOut"=> $cueOut, "length"=> $this->getLength(),
- "fadeIn"=> $fadeIn, "fadeOut"=> $fadeOut);
+ return ['cliplength' => $cliplength, 'cueIn' => $cueIn, 'cueOut' => $cueOut, 'length' => $this->getLength(),
+ 'fadeIn' => $fadeIn, 'fadeOut' => $fadeOut, ];
}
public function getAllPLMetaData()
{
$categories = $this->categories;
- $md = array();
+ $md = [];
foreach ($categories as $key => $val) {
$method = 'get' . $val;
- $md[$key] = $this->$method();
+ $md[$key] = $this->{$method}();
}
return $md;
@@ -949,7 +948,7 @@ SQL;
$cat = $this->categories[$category];
$method = 'get' . $cat;
- return $this->$method();
+ return $this->{$method}();
}
public function setMetadata($category, $value)
@@ -957,19 +956,23 @@ SQL;
$cat = $this->categories[$category];
$method = 'set' . $cat;
- $this->$method($value);
+ $this->{$method}($value);
}
public static function getPlaylistCount()
{
$sql = 'SELECT count(*) as cnt FROM cc_playlist';
- return Application_Common_Database::prepareAndExecute($sql, array(),
- Application_Common_Database::COLUMN);
+ return Application_Common_Database::prepareAndExecute(
+ $sql,
+ [],
+ Application_Common_Database::COLUMN
+ );
}
/**
* Delete the file from all playlists.
+ *
* @param string $p_fileId
*/
public static function DeleteFileFromAllPlaylists($p_fileId)
@@ -979,20 +982,23 @@ SQL;
/**
* Delete playlists that match the ids..
+ *
* @param array $p_ids
+ * @param mixed $p_userId
*/
public static function deletePlaylists($p_ids, $p_userId)
{
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id);
- $isAdminOrPM = $user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
+ $isAdminOrPM = $user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER]);
// get only the files from the playlists
// we are about to delete
$itemsToDelete = CcPlaylistcontentsQuery::create()
->filterByDbPlaylistId($p_ids)
->filterByDbFileId(null, Criteria::NOT_EQUAL)
- ->find();
+ ->find()
+ ;
$updateIsPlaylistFlag = false;
@@ -1001,15 +1007,14 @@ SQL;
if (count($leftOver) == 0) {
CcPlaylistQuery::create()->findPKs($p_ids)->delete();
$updateIsPlaylistFlag = true;
-
} else {
- throw new PlaylistNoPermissionException;
+ throw new PlaylistNoPermissionException();
}
} else {
CcPlaylistQuery::create()->findPKs($p_ids)->delete();
$updateIsPlaylistFlag = true;
}
-
+
if ($updateIsPlaylistFlag) {
// update is_playlist flag in cc_files
Application_Model_StoredFile::setIsPlaylist(
@@ -1025,20 +1030,19 @@ SQL;
{
$ownedByUser = CcPlaylistQuery::create()->filterByDbCreatorId($p_userId)->find()->getData();
$selectedPls = $p_ids;
- $ownedPls = array();
+ $ownedPls = [];
foreach ($ownedByUser as $pl) {
if (in_array($pl->getDbId(), $selectedPls)) {
$ownedPls[] = $pl->getDbId();
}
}
- $leftOvers = array_diff($selectedPls, $ownedPls);
-
- return $leftOvers;
+ return array_diff($selectedPls, $ownedPls);
}
/**
- * Delete all files from playlist
+ * Delete all files from playlist.
+ *
* @param int $p_playlistId
*/
public function deleteAllFilesFromPlaylist()
@@ -1048,7 +1052,8 @@ SQL;
$itemsToDelete = CcPlaylistcontentsQuery::create()
->filterByDbPlaylistId($this->id)
->filterByDbFileId(null, Criteria::NOT_EQUAL)
- ->find();
+ ->find()
+ ;
CcPlaylistcontentsQuery::create()->findByDbPlaylistId($this->id)->delete();
@@ -1059,79 +1064,84 @@ SQL;
false
);
- $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
+ $this->pl->setDbMtime(new DateTime('now', new DateTimeZone('UTC')));
$this->pl->save($this->con);
$this->con->commit();
}
-
+
public function shuffle()
{
- $sql = <<$this->id));
+ $out = Application_Common_Database::prepareAndExecute($sql, ['p1' => $this->id]);
$maxPosition = $out[0]['max'];
-
+
$map = range(0, $maxPosition);
shuffle($map);
-
+
$currentPos = implode(',', array_keys($map));
- $sql = "UPDATE cc_playlistcontents SET position = CASE position ";
+ $sql = 'UPDATE cc_playlistcontents SET position = CASE position ';
foreach ($map as $current => $after) {
- $sql .= sprintf("WHEN %d THEN %d ", $current, $after);
+ $sql .= sprintf('WHEN %d THEN %d ', $current, $after);
}
- $sql .= "END WHERE position IN ($currentPos) and playlist_id=:p1";
-
- Application_Common_Database::prepareAndExecute($sql, array("p1"=>$this->id));
- return array('result' => 0);
+ $sql .= "END WHERE position IN ({$currentPos}) and playlist_id=:p1";
+
+ Application_Common_Database::prepareAndExecute($sql, ['p1' => $this->id]);
+
+ return ['result' => 0];
}
public static function getAllPlaylistFiles()
{
- $sql = <<pl->getCcPlaylistcontentss("type = 0"); //type=0 is only files, not other types of media
-
+ $playlistContents = $this->pl->getCcPlaylistcontentss('type = 0'); //type=0 is only files, not other types of media
+
//Slightly faster than the other Propel version below (this one does an INNER JOIN):
$missingFiles = CcFilesQuery::create()
- ->join("CcFiles.CcPlaylistcontents")
- ->where("CcPlaylistcontents.DbPlaylistId = ?", $this->pl->getDbId())
- ->where("CcFiles.DbFileExists = ?", 'false')
- ->find();
-
+ ->join('CcFiles.CcPlaylistcontents')
+ ->where('CcPlaylistcontents.DbPlaylistId = ?', $this->pl->getDbId())
+ ->where('CcFiles.DbFileExists = ?', 'false')
+ ->find()
+ ;
+
//Nicer Propel version but slightly slower because it generates a LEFT JOIN:
/*
$missingFiles = CcPlaylistcontentsQuery::create()
@@ -1141,18 +1151,21 @@ SQL;
->endUse()
->find();
*/
-
- if (!$missingFiles->isEmpty())
- {
+
+ if (!$missingFiles->isEmpty()) {
return true;
}
-
- return false;
+
+ return false;
}
-
-
} // class Playlist
-class PlaylistNotFoundException extends Exception {}
-class PlaylistNoPermissionException extends Exception {}
-class PlaylistOutDatedException extends Exception {}
+class PlaylistNotFoundException extends Exception
+{
+}
+class PlaylistNoPermissionException extends Exception
+{
+}
+class PlaylistOutDatedException extends Exception
+{
+}
diff --git a/legacy/application/models/Preference.php b/legacy/application/models/Preference.php
index 0d164e7c8..4efef23ae 100644
--- a/legacy/application/models/Preference.php
+++ b/legacy/application/models/Preference.php
@@ -2,12 +2,11 @@
class Application_Model_Preference
{
-
private static function getUserId()
{
//pass in true so the check is made with the autoloader
//we need this check because saas calls this function from outside Zend
- if (!class_exists("Zend_Session", true) || !Zend_Session::isStarted() || !class_exists("Zend_Auth", true) || !Zend_Auth::getInstance()->hasIdentity()) {
+ if (!class_exists('Zend_Session', true) || !Zend_Session::isStarted() || !class_exists('Zend_Auth', true) || !Zend_Auth::getInstance()->hasIdentity()) {
$userId = null;
} else {
$auth = Zend_Auth::getInstance();
@@ -18,8 +17,9 @@ class Application_Model_Preference
}
/**
- *
- * @param boolean $isUserValue is true when we are setting a value for the current user
+ * @param bool $isUserValue is true when we are setting a value for the current user
+ * @param mixed $key
+ * @param mixed $value
*/
private static function setValue($key, $value, $isUserValue = false)
{
@@ -38,58 +38,59 @@ class Application_Model_Preference
}
//Check if key already exists
- $sql = "SELECT valstr FROM cc_pref"
- ." WHERE keystr = :key";
+ $sql = 'SELECT valstr FROM cc_pref'
+ . ' WHERE keystr = :key';
- $paramMap = array();
+ $paramMap = [];
$paramMap[':key'] = $key;
//For user specific preference, check if id matches as well
if ($isUserValue) {
- $sql .= " AND subjid = :id";
+ $sql .= ' AND subjid = :id';
$paramMap[':id'] = $userId;
}
- $sql .= " FOR UPDATE";
+ $sql .= ' FOR UPDATE';
- $result = Application_Common_Database::prepareAndExecute($sql,
- $paramMap,
- Application_Common_Database::ROW_COUNT,
- PDO::FETCH_ASSOC,
- $con);
+ $result = Application_Common_Database::prepareAndExecute(
+ $sql,
+ $paramMap,
+ Application_Common_Database::ROW_COUNT,
+ PDO::FETCH_ASSOC,
+ $con
+ );
- $paramMap = array();
+ $paramMap = [];
if ($result > 1) {
//this case should not happen.
- throw new Exception("Invalid number of results returned. Should be ".
- "0 or 1, but is '$result' instead");
- } else if ($result == 1) {
-
+ throw new Exception('Invalid number of results returned. Should be ' .
+ "0 or 1, but is '{$result}' instead");
+ }
+ if ($result == 1) {
// result found
if (!$isUserValue) {
// system pref
- $sql = "UPDATE cc_pref"
- ." SET subjid = NULL, valstr = :value"
- ." WHERE keystr = :key";
+ $sql = 'UPDATE cc_pref'
+ . ' SET subjid = NULL, valstr = :value'
+ . ' WHERE keystr = :key';
} else {
// user pref
- $sql = "UPDATE cc_pref"
- . " SET valstr = :value"
- . " WHERE keystr = :key AND subjid = :id";
+ $sql = 'UPDATE cc_pref'
+ . ' SET valstr = :value'
+ . ' WHERE keystr = :key AND subjid = :id';
$paramMap[':id'] = $userId;
}
} else {
-
// result not found
if (!$isUserValue) {
// system pref
- $sql = "INSERT INTO cc_pref (keystr, valstr)"
- ." VALUES (:key, :value)";
+ $sql = 'INSERT INTO cc_pref (keystr, valstr)'
+ . ' VALUES (:key, :value)';
} else {
// user pref
- $sql = "INSERT INTO cc_pref (subjid, keystr, valstr)"
- ." VALUES (:id, :key, :value)";
+ $sql = 'INSERT INTO cc_pref (subjid, keystr, valstr)'
+ . ' VALUES (:id, :key, :value)';
$paramMap[':id'] = $userId;
}
@@ -97,28 +98,31 @@ class Application_Model_Preference
$paramMap[':key'] = $key;
$paramMap[':value'] = $value;
- Application_Common_Database::prepareAndExecute($sql,
- $paramMap,
- Application_Common_Database::EXECUTE,
- PDO::FETCH_ASSOC,
- $con);
-
+ Application_Common_Database::prepareAndExecute(
+ $sql,
+ $paramMap,
+ Application_Common_Database::EXECUTE,
+ PDO::FETCH_ASSOC,
+ $con
+ );
} catch (Exception $e) {
header('HTTP/1.0 503 Service Unavailable');
- Logging::info("Database error: ".$e->getMessage());
+ Logging::info('Database error: ' . $e->getMessage());
+
exit;
}
}
/**
- * Given a PDO connection, lock the cc_pref table for the current transaction
+ * Given a PDO connection, lock the cc_pref table for the current transaction.
*
* Creates a table level lock, which defaults to ACCESS EXCLUSIVE mode;
* see http://www.postgresql.org/docs/9.1/static/explicit-locking.html
*
* @param PDO $con
*/
- private static function _lock($con) {
+ private static function _lock($con)
+ {
// If we're not in a transaction, a lock is pointless
if (!$con->inTransaction()) {
return;
@@ -127,21 +131,21 @@ class Application_Model_Preference
// in case we're handling simultaneous requests.
// Locks only last until the end of the transaction, so we shouldn't have to
// worry about this causing any noticeable difference in request processing speed
- $sql = "LOCK TABLE cc_pref";
+ $sql = 'LOCK TABLE cc_pref';
$st = $con->prepare($sql);
$st->execute();
}
/**
- * @param string $key the preference key string
- * @param bool|false $isUserValue select the preference for the current user
- * @param bool|false $forceDefault only look for default (no user ID) values
+ * @param string $key the preference key string
+ * @param bool|false $isUserValue select the preference for the current user
+ * @param bool|false $forceDefault only look for default (no user ID) values
+ *
* @return mixed the preference value
*/
private static function getValue($key, $isUserValue = false, $forceDefault = false)
{
try {
-
$userId = null;
if ($isUserValue) {
//This is nested in here because so we can still use getValue() when the session hasn't started yet.
@@ -152,55 +156,55 @@ class Application_Model_Preference
}
//Check if key already exists
- $sql = "SELECT COUNT(*) FROM cc_pref"
- ." WHERE keystr = :key";
+ $sql = 'SELECT COUNT(*) FROM cc_pref'
+ . ' WHERE keystr = :key';
- $paramMap = array();
+ $paramMap = [];
$paramMap[':key'] = $key;
//For user specific preference, check if id matches as well
if ($isUserValue) {
- $sql .= " AND subjid = :id";
+ $sql .= ' AND subjid = :id';
$paramMap[':id'] = $userId;
- } else if ($forceDefault) {
- $sql .= " AND subjid IS NULL";
+ } elseif ($forceDefault) {
+ $sql .= ' AND subjid IS NULL';
}
$result = Application_Common_Database::prepareAndExecute($sql, $paramMap, Application_Common_Database::COLUMN);
//return an empty string if the result doesn't exist.
if ($result == 0) {
- $res = "";
+ $res = '';
} else {
- $sql = "SELECT valstr FROM cc_pref"
- ." WHERE keystr = :key";
+ $sql = 'SELECT valstr FROM cc_pref'
+ . ' WHERE keystr = :key';
- $paramMap = array();
+ $paramMap = [];
$paramMap[':key'] = $key;
//For user specific preference, check if id matches as well
if ($isUserValue) {
- $sql .= " AND subjid = :id";
+ $sql .= ' AND subjid = :id';
$paramMap[':id'] = $userId;
}
$result = Application_Common_Database::prepareAndExecute($sql, $paramMap, Application_Common_Database::COLUMN);
- $res = ($result !== false) ? $result : "";
+ $res = ($result !== false) ? $result : '';
}
return $res;
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
header('HTTP/1.0 503 Service Unavailable');
- Logging::info("Could not connect to database: ".$e);
+ Logging::info('Could not connect to database: ' . $e);
+
exit;
}
}
public static function GetHeadTitle()
{
- $title = self::getValue("station_name");
+ $title = self::getValue('station_name');
if (empty($title)) {
$title = PRODUCT_NAME;
}
@@ -208,20 +212,20 @@ class Application_Model_Preference
return $title;
}
- public static function SetHeadTitle($title, $view=null)
+ public static function SetHeadTitle($title, $view = null)
{
- self::setValue("station_name", $title);
+ self::setValue('station_name', $title);
// in case this is called from airtime-saas script
if ($view !== null) {
//set session variable to new station name so that html title is updated.
//should probably do this in a view helper to keep this controller as minimal as possible.
- $view->headTitle()->exchangeArray(array()); //clear headTitle ArrayObject
+ $view->headTitle()->exchangeArray([]); //clear headTitle ArrayObject
$view->headTitle(self::GetHeadTitle());
}
- $eventType = "update_station_name";
- $md = array("station_name"=>$title);
+ $eventType = 'update_station_name';
+ $md = ['station_name' => $title];
Application_Model_RabbitMq::SendMessageToPypo($eventType, $md);
}
@@ -231,12 +235,12 @@ class Application_Model_Preference
* should be populated until.
*
* @param DateTime $dateTime
- * A row from cc_show_days table
+ * A row from cc_show_days table
*/
public static function SetShowsPopulatedUntil($dateTime)
{
- $dateTime->setTimezone(new DateTimeZone("UTC"));
- self::setValue("shows_populated_until", $dateTime->format(DEFAULT_TIMESTAMP_FORMAT));
+ $dateTime->setTimezone(new DateTimeZone('UTC'));
+ self::setValue('shows_populated_until', $dateTime->format(DEFAULT_TIMESTAMP_FORMAT));
}
/**
@@ -250,27 +254,27 @@ class Application_Model_Preference
*/
public static function GetShowsPopulatedUntil()
{
- $date = self::getValue("shows_populated_until");
+ $date = self::getValue('shows_populated_until');
- if ($date == "") {
+ if ($date == '') {
return null;
- } else {
- return new DateTime($date, new DateTimeZone("UTC"));
}
+
+ return new DateTime($date, new DateTimeZone('UTC'));
}
public static function SetDefaultCrossfadeDuration($duration)
{
- self::setValue("default_crossfade_duration", $duration);
+ self::setValue('default_crossfade_duration', $duration);
}
public static function GetDefaultCrossfadeDuration()
{
- $duration = self::getValue("default_crossfade_duration");
+ $duration = self::getValue('default_crossfade_duration');
- if ($duration === "") {
+ if ($duration === '') {
// the default value of the fade is 00.5
- return "0";
+ return '0';
}
return $duration;
@@ -278,16 +282,16 @@ class Application_Model_Preference
public static function SetDefaultFadeIn($fade)
{
- self::setValue("default_fade_in", $fade);
+ self::setValue('default_fade_in', $fade);
}
public static function GetDefaultFadeIn()
{
- $fade = self::getValue("default_fade_in");
+ $fade = self::getValue('default_fade_in');
- if ($fade === "") {
+ if ($fade === '') {
// the default value of the fade is 00.5
- return "0.5";
+ return '0.5';
}
return $fade;
@@ -295,16 +299,16 @@ class Application_Model_Preference
public static function SetDefaultFadeOut($fade)
{
- self::setValue("default_fade_out", $fade);
+ self::setValue('default_fade_out', $fade);
}
public static function GetDefaultFadeOut()
{
- $fade = self::getValue("default_fade_out");
+ $fade = self::getValue('default_fade_out');
- if ($fade === "") {
+ if ($fade === '') {
// the default value of the fade is 0.5
- return "0.5";
+ return '0.5';
}
return $fade;
@@ -312,237 +316,241 @@ class Application_Model_Preference
public static function SetDefaultFade($fade)
{
- self::setValue("default_fade", $fade);
+ self::setValue('default_fade', $fade);
}
public static function SetDefaultTransitionFade($fade)
{
- self::setValue("default_transition_fade", $fade);
+ self::setValue('default_transition_fade', $fade);
- $eventType = "update_transition_fade";
- $md = array("transition_fade"=>$fade);
+ $eventType = 'update_transition_fade';
+ $md = ['transition_fade' => $fade];
Application_Model_RabbitMq::SendMessageToPypo($eventType, $md);
}
public static function GetDefaultTransitionFade()
{
- $transition_fade = self::getValue("default_transition_fade");
- return ($transition_fade == "") ? "0.000" : $transition_fade;
+ $transition_fade = self::getValue('default_transition_fade');
+
+ return ($transition_fade == '') ? '0.000' : $transition_fade;
}
public static function SetStreamLabelFormat($type)
{
- self::setValue("stream_label_format", $type);
+ self::setValue('stream_label_format', $type);
- $eventType = "update_stream_format";
- $md = array("stream_format"=>$type);
+ $eventType = 'update_stream_format';
+ $md = ['stream_format' => $type];
Application_Model_RabbitMq::SendMessageToPypo($eventType, $md);
}
public static function GetStreamLabelFormat()
{
- return self::getValue("stream_label_format");
+ return self::getValue('stream_label_format');
}
public static function GetStationName()
{
- return self::getValue("station_name");
+ return self::getValue('station_name');
}
public static function SetStationName($station_name)
{
- self::setValue("station_name", $station_name);
+ self::setValue('station_name', $station_name);
}
public static function SetAllow3rdPartyApi($bool)
{
- self::setValue("third_party_api", $bool);
+ self::setValue('third_party_api', $bool);
}
public static function GetAllow3rdPartyApi()
{
- $val = self::getValue("third_party_api");
- return (strlen($val) == 0 ) ? "1" : $val;
+ $val = self::getValue('third_party_api');
+
+ return (strlen($val) == 0) ? '1' : $val;
}
public static function SetPodcastAlbumOverride($bool)
{
- self::setValue("podcast_album_override", $bool);
+ self::setValue('podcast_album_override', $bool);
}
public static function GetPodcastAlbumOverride()
{
- $val = self::getValue("podcast_album_override");
+ $val = self::getValue('podcast_album_override');
+
return $val === '1' ? true : false;
}
public static function SetPodcastAutoSmartblock($bool)
{
- self::setValue("podcast_auto_smartblock", $bool);
+ self::setValue('podcast_auto_smartblock', $bool);
}
public static function GetPodcastAutoSmartblock()
{
- $val = self::getValue("podcast_auto_smartblock");
+ $val = self::getValue('podcast_auto_smartblock');
+
return $val === '1' ? true : false;
}
public static function SetTrackTypeDefault($tracktype)
{
- self::setValue("tracktype_default", $tracktype);
+ self::setValue('tracktype_default', $tracktype);
}
public static function GetTrackTypeDefault()
{
- return self::getValue("tracktype_default");
+ return self::getValue('tracktype_default');
}
public static function GetIntroPlaylist()
{
- return self::getValue("intro_playlist");
+ return self::getValue('intro_playlist');
}
public static function GetOutroPlaylist()
{
- return self::getValue("outro_playlist");
+ return self::getValue('outro_playlist');
}
-
public static function SetIntroPlaylist($playlist)
{
- self::setValue("intro_playlist", $playlist);
+ self::setValue('intro_playlist', $playlist);
}
public static function SetOutroPlaylist($playlist)
{
- self::setValue("outro_playlist", $playlist);
+ self::setValue('outro_playlist', $playlist);
}
public static function SetPhone($phone)
{
- self::setValue("phone", $phone);
+ self::setValue('phone', $phone);
}
public static function GetPhone()
{
- return self::getValue("phone");
+ return self::getValue('phone');
}
public static function SetEmail($email)
{
- self::setValue("email", $email);
+ self::setValue('email', $email);
}
public static function GetEmail()
{
- return self::getValue("email");
+ return self::getValue('email');
}
public static function SetStationWebSite($site)
{
- self::setValue("station_website", $site);
+ self::setValue('station_website', $site);
}
public static function GetStationWebSite()
{
- return self::getValue("station_website");
+ return self::getValue('station_website');
}
public static function SetSupportFeedback($feedback)
{
- self::setValue("support_feedback", $feedback);
+ self::setValue('support_feedback', $feedback);
}
public static function GetSupportFeedback()
{
- return self::getValue("support_feedback");
+ return self::getValue('support_feedback');
}
public static function SetPublicise($publicise)
{
- self::setValue("publicise", $publicise);
+ self::setValue('publicise', $publicise);
}
public static function GetPublicise()
{
- return self::getValue("publicise");
+ return self::getValue('publicise');
}
public static function SetRegistered($registered)
{
- self::setValue("registered", $registered);
+ self::setValue('registered', $registered);
}
public static function GetRegistered()
{
- return self::getValue("registered");
+ return self::getValue('registered');
}
public static function SetStationCountry($country)
{
- self::setValue("country", $country);
+ self::setValue('country', $country);
}
public static function GetStationCountry()
{
- return self::getValue("country");
+ return self::getValue('country');
}
public static function SetStationCity($city)
{
- self::setValue("city", $city);
+ self::setValue('city', $city);
}
public static function GetStationCity()
{
- return self::getValue("city");
+ return self::getValue('city');
}
public static function SetStationDescription($description)
{
- self::setValue("description", $description);
+ self::setValue('description', $description);
}
public static function GetStationDescription()
{
- $description = self::getValue("description");
+ $description = self::getValue('description');
if (!empty($description)) {
return $description;
- } else {
- return sprintf(_("Powered by %s"), SAAS_PRODUCT_BRANDING_NAME);
}
+
+ return sprintf(_('Powered by %s'), SAAS_PRODUCT_BRANDING_NAME);
}
// Sets station default timezone (from preferences)
public static function SetDefaultTimezone($timezone)
{
- self::setValue("timezone", $timezone);
+ self::setValue('timezone', $timezone);
}
// Returns station default timezone (from preferences)
public static function GetDefaultTimezone()
{
- $stationTimezone = self::getValue("timezone");
- if (is_null($stationTimezone) || $stationTimezone == "") {
- $stationTimezone = "UTC";
+ $stationTimezone = self::getValue('timezone');
+ if (is_null($stationTimezone) || $stationTimezone == '') {
+ $stationTimezone = 'UTC';
}
+
return $stationTimezone;
}
public static function SetUserTimezone($timezone = null)
{
- self::setValue("user_timezone", $timezone, true);
+ self::setValue('user_timezone', $timezone, true);
}
public static function GetUserTimezone()
{
- $timezone = self::getValue("user_timezone", true);
+ $timezone = self::getValue('user_timezone', true);
if (!$timezone) {
return self::GetDefaultTimezone();
- } else {
- return $timezone;
}
+
+ return $timezone;
}
// Always attempts to returns the current user's personal timezone setting
@@ -552,40 +560,41 @@ class Application_Model_Preference
if (!is_null($userId)) {
return self::GetUserTimezone();
- } else {
- return self::GetDefaultTimezone();
}
+
+ return self::GetDefaultTimezone();
}
// This is the language setting on preferences page
public static function SetDefaultLocale($locale)
{
- self::setValue("locale", $locale);
+ self::setValue('locale', $locale);
}
public static function GetDefaultLocale()
{
- return self::getValue("locale");
+ return self::getValue('locale');
}
public static function GetUserLocale()
{
- $locale = self::getValue("user_locale", true);
+ $locale = self::getValue('user_locale', true);
// empty() checks for null and empty strings - more robust than !val
if (empty($locale)) {
return self::GetDefaultLocale();
- } else {
- return $locale;
}
+
+ return $locale;
}
public static function SetUserLocale($locale = null)
{
// When a new user is created they will get the default locale
// setting which the admin sets on preferences page
- if (is_null($locale))
+ if (is_null($locale)) {
$locale = self::GetDefaultLocale();
- self::setValue("user_locale", $locale, true);
+ }
+ self::setValue('user_locale', $locale, true);
}
public static function GetLocale()
@@ -594,75 +603,74 @@ class Application_Model_Preference
if (!is_null($userId)) {
return self::GetUserLocale();
- } else {
- return self::GetDefaultLocale();
}
+
+ return self::GetDefaultLocale();
}
public static function SetStationLogo($imagePath)
{
if (empty($imagePath)) {
- Logging::info("Removed station logo");
+ Logging::info('Removed station logo');
}
$image = @file_get_contents($imagePath);
$image = base64_encode($image);
- self::setValue("logoImage", $image);
+ self::setValue('logoImage', $image);
}
public static function GetStationLogo()
{
- $logoImage = self::getValue("logoImage");
+ $logoImage = self::getValue('logoImage');
if (!empty($logoImage)) {
return $logoImage;
- } else {
- // We return the Airtime logo if no logo is set in the database.
- // airtime_logo.png is stored under the public directory
- $image = @file_get_contents(Application_Common_HTTPHelper::getStationUrl() . DEFAULT_LOGO_FILE);
- $image = base64_encode($image);
- return $image;
}
+ // We return the Airtime logo if no logo is set in the database.
+ // airtime_logo.png is stored under the public directory
+ $image = @file_get_contents(Application_Common_HTTPHelper::getStationUrl() . DEFAULT_LOGO_FILE);
+
+ return base64_encode($image);
}
public static function SetUniqueId($id)
{
- self::setValue("uniqueId", $id);
+ self::setValue('uniqueId', $id);
}
public static function GetUniqueId()
{
- return self::getValue("uniqueId");
+ return self::getValue('uniqueId');
}
public static function GetCountryList()
{
- $sql = "SELECT * FROM cc_country";
+ $sql = 'SELECT * FROM cc_country';
- $res = Application_Common_Database::prepareAndExecute($sql, array());
+ $res = Application_Common_Database::prepareAndExecute($sql, []);
- $out = array();
- $out[""] = _("Select Country");
+ $out = [];
+ $out[''] = _('Select Country');
foreach ($res as $r) {
- $out[$r["isocode"]] = $r["name"];
+ $out[$r['isocode']] = $r['name'];
}
return $out;
}
- public static function GetSystemInfo($returnArray=false, $p_testing=false)
+ public static function GetSystemInfo($returnArray = false, $p_testing = false)
{
exec('/usr/bin/airtime-check-system --no-color', $output);
$output = preg_replace('/\s+/', ' ', $output);
- $systemInfoArray = array();
+ $systemInfoArray = [];
foreach ($output as $key => &$out) {
$info = explode('=', $out);
if (isset($info[1])) {
$key = str_replace(' ', '_', trim($info[0]));
$key = strtoupper($key);
- if ($key == 'WEB_SERVER' || $key == 'CPU' || $key == 'OS' || $key == 'TOTAL_RAM' ||
- $key == 'FREE_RAM' || $key == 'AIRTIME_VERSION' || $key == 'KERNAL_VERSION' ||
- $key == 'MACHINE_ARCHITECTURE' || $key == 'TOTAL_MEMORY_MBYTES' || $key == 'TOTAL_SWAP_MBYTES' ||
- $key == 'PLAYOUT_ENGINE_CPU_PERC') {
+ if ($key == 'WEB_SERVER' || $key == 'CPU' || $key == 'OS' || $key == 'TOTAL_RAM'
+ || $key == 'FREE_RAM' || $key == 'AIRTIME_VERSION' || $key == 'KERNAL_VERSION'
+ || $key == 'MACHINE_ARCHITECTURE' || $key == 'TOTAL_MEMORY_MBYTES' || $key == 'TOTAL_SWAP_MBYTES'
+ || $key == 'PLAYOUT_ENGINE_CPU_PERC') {
if ($key == 'AIRTIME_VERSION') {
// remove hash tag on the version string
$version = explode('+', $info[1]);
@@ -674,7 +682,7 @@ class Application_Model_Preference
}
}
- $outputArray = array();
+ $outputArray = [];
$outputArray['LIVE_DURATION'] = Application_Model_LiveLog::GetLiveShowDuration($p_testing);
$outputArray['SCHEDULED_DURATION'] = Application_Model_LiveLog::GetScheduledDuration($p_testing);
@@ -688,13 +696,13 @@ class Application_Model_Preference
$outputArray['STATION_DESCRIPTION'] = self::GetStationDescription();
// get web server info
- if (isset($systemInfoArray["AIRTIME_VERSION_URL"])) {
- $url = $systemInfoArray["AIRTIME_VERSION_URL"];
- $index = strpos($url,'/api/');
- $url = substr($url, 0, $index);
+ if (isset($systemInfoArray['AIRTIME_VERSION_URL'])) {
+ $url = $systemInfoArray['AIRTIME_VERSION_URL'];
+ $index = strpos($url, '/api/');
+ $url = substr($url, 0, $index);
- $headerInfo = get_headers(trim($url),1);
- $outputArray['WEB_SERVER'] = $headerInfo['Server'][0];
+ $headerInfo = get_headers(trim($url), 1);
+ $outputArray['WEB_SERVER'] = $headerInfo['Server'][0];
}
$outputArray['NUM_OF_USERS'] = Application_Model_User::getUserCount();
@@ -711,15 +719,15 @@ class Application_Model_Preference
$outputString = "\n";
foreach ($outputArray as $key => $out) {
- if ($key == "STREAM_INFO") {
- $outputString .= $key." :\n";
+ if ($key == 'STREAM_INFO') {
+ $outputString .= $key . " :\n";
foreach ($out as $s_info) {
foreach ($s_info as $k => $v) {
- $outputString .= "\t".strtoupper($k)." : ".$v."\n";
+ $outputString .= "\t" . strtoupper($k) . ' : ' . $v . "\n";
}
}
} else {
- $outputString .= $key.' : '.$out."\n";
+ $outputString .= $key . ' : ' . $out . "\n";
}
}
if ($returnArray) {
@@ -727,9 +735,9 @@ class Application_Model_Preference
$outputArray['LOGOIMG'] = self::GetStationLogo();
return $outputArray;
- } else {
- return $outputString;
}
+
+ return $outputString;
}
public static function GetInstallMethod()
@@ -738,74 +746,73 @@ class Application_Model_Preference
$debian_install = file_exists('/var/lib/dpkg/info/airtime.config');
if ($debian_install) {
if ($easy_install) {
- return "easy_install";
- } else {
- return "debian_install";
+ return 'easy_install';
}
- } else {
- return "manual_install";
+
+ return 'debian_install';
}
+
+ return 'manual_install';
}
public static function SetRemindMeDate($p_never = false)
{
if ($p_never) {
- self::setValue("remindme", -1);
+ self::setValue('remindme', -1);
} else {
- $weekAfter = mktime(0, 0, 0, gmdate("m"), gmdate("d")+7, gmdate("Y"));
- self::setValue("remindme", $weekAfter);
+ $weekAfter = mktime(0, 0, 0, gmdate('m'), gmdate('d') + 7, gmdate('Y'));
+ self::setValue('remindme', $weekAfter);
}
}
public static function GetRemindMeDate()
{
- return self::getValue("remindme");
+ return self::getValue('remindme');
}
public static function SetImportTimestamp()
{
$now = time();
- if (self::GetImportTimestamp()+5 < $now) {
- self::setValue("import_timestamp", $now);
+ if (self::GetImportTimestamp() + 5 < $now) {
+ self::setValue('import_timestamp', $now);
}
}
public static function GetImportTimestamp()
{
- return (int) self::getValue("import_timestamp");
+ return (int) self::getValue('import_timestamp');
}
public static function GetStreamType()
{
- $st = self::getValue("stream_type");
+ $st = self::getValue('stream_type');
return explode(',', $st);
}
public static function GetStreamBitrate()
{
- $sb = self::getValue("stream_bitrate");
+ $sb = self::getValue('stream_bitrate');
return explode(',', $sb);
}
public static function SetPrivacyPolicyCheck($flag)
{
- self::setValue("privacy_policy", $flag);
+ self::setValue('privacy_policy', $flag);
}
public static function GetPrivacyPolicyCheck()
{
- return self::getValue("privacy_policy");
+ return self::getValue('privacy_policy');
}
public static function SetNumOfStreams($num)
{
- self::setValue("num_of_streams", intval($num));
+ self::setValue('num_of_streams', intval($num));
//Enable or disable each stream according to whatever was just changed.
- for ($streamIdx = 1; $streamIdx <= MAX_NUM_STREAMS; $streamIdx++)
- {
+ for ($streamIdx = 1; $streamIdx <= MAX_NUM_STREAMS; ++$streamIdx) {
$prefix = 's' . $streamIdx . '_';
$enable = 'false';
if ($streamIdx <= intval($num)) {
@@ -813,37 +820,37 @@ class Application_Model_Preference
}
//Enable or disable the stream in the Stream Settings DB table.
- Application_Model_StreamSetting::setIndividualStreamSetting(array($prefix.'enable' => $enable));
+ Application_Model_StreamSetting::setIndividualStreamSetting([$prefix . 'enable' => $enable]);
}
}
public static function GetNumOfStreams()
{
- return self::getValue("num_of_streams");
+ return self::getValue('num_of_streams');
}
public static function SetMaxBitrate($bitrate)
{
- self::setValue("max_bitrate", intval($bitrate));
+ self::setValue('max_bitrate', intval($bitrate));
}
public static function GetMaxBitrate()
{
- return self::getValue("max_bitrate");
+ return self::getValue('max_bitrate');
}
public static function SetEnableStreamConf($bool)
{
- self::setValue("enable_stream_conf", $bool);
+ self::setValue('enable_stream_conf', $bool);
}
public static function GetEnableStreamConf()
{
- if (self::getValue("enable_stream_conf") == Null) {
- return "true";
+ if (self::getValue('enable_stream_conf') == null) {
+ return 'true';
}
- return self::getValue("enable_stream_conf");
+ return self::getValue('enable_stream_conf');
}
public static function GetSchemaVersion()
@@ -854,21 +861,23 @@ class Application_Model_Preference
//New versions use schema_version
$pref = CcPrefQuery::create()
->filterByKeystr('schema_version')
- ->findOne();
+ ->findOne()
+ ;
if (empty($pref)) {
//Pre-2.5.2 releases all used this ambiguous "system_version" key to represent both the code and schema versions...
$pref = CcPrefQuery::create()
->filterByKeystr('system_version')
- ->findOne();
+ ->findOne()
+ ;
}
- $schemaVersion = $pref->getValStr();
- return $schemaVersion;
+
+ return $pref->getValStr();
}
public static function SetSchemaVersion($version)
{
- self::setValue("schema_version", $version);
+ self::setValue('schema_version', $version);
}
public static function GetLatestVersion()
@@ -882,22 +891,23 @@ class Application_Model_Preference
}
$rss = new SimplePie();
- $rss->set_feed_url(array(LIBRETIME_UPDATE_FEED));
+ $rss->set_feed_url([LIBRETIME_UPDATE_FEED]);
$rss->enable_cache(false);
$rss->init();
$rss->handle_content_type();
// get all available versions ut to default github api limit
- $versions = array();
+ $versions = [];
foreach ($rss->get_items() as $item) {
$versions[] = $item->get_title();
}
$latest = $versions;
self::setValue('latest_version_nextcheck', strtotime('+1 week'));
if (empty($latest)) {
- return array($config['airtime_version']);
+ return [$config['airtime_version']];
}
self::setValue('latest_version', json_encode($latest));
+
return $latest;
}
@@ -905,74 +915,76 @@ class Application_Model_Preference
{
$pattern = "/^[0-9]+\.[0-9]+\.[0-9]+/";
if (preg_match($pattern, $version)) {
- self::setValue("latest_version", $version);
+ self::setValue('latest_version', $version);
}
}
public static function GetLatestLink()
{
- $link = self::getValue("latest_link");
+ $link = self::getValue('latest_link');
if ($link == null || strlen($link) == 0) {
return LIBRETIME_WHATS_NEW_URL;
- } else {
- return $link;
}
+
+ return $link;
}
public static function SetLatestLink($link)
{
- $pattern = "#^(http|https|ftp)://" .
+ $pattern = '#^(http|https|ftp)://' .
"([a-zA-Z0-9]+\.)*[a-zA-Z0-9]+" .
"(/[a-zA-Z0-9\-\.\_\~\:\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=]+)*/?$#";
if (preg_match($pattern, $link)) {
- self::setValue("latest_link", $link);
+ self::setValue('latest_link', $link);
}
}
public static function SetWeekStartDay($day)
{
- self::setValue("week_start_day", $day);
+ self::setValue('week_start_day', $day);
}
public static function GetWeekStartDay()
{
- $val = self::getValue("week_start_day");
- return (strlen($val) == 0) ? "0" : $val;
+ $val = self::getValue('week_start_day');
+
+ return (strlen($val) == 0) ? '0' : $val;
}
/**
- * Stores the last timestamp of user updating stream setting
- */
+ * Stores the last timestamp of user updating stream setting.
+ */
public static function SetStreamUpdateTimestamp()
{
$now = time();
- self::setValue("stream_update_timestamp", $now);
+ self::setValue('stream_update_timestamp', $now);
}
/**
- * Gets the last timestamp of user updating stream setting
+ * Gets the last timestamp of user updating stream setting.
*/
public static function GetStreamUpdateTimestemp()
{
- $update_time = self::getValue("stream_update_timestamp");
+ $update_time = self::getValue('stream_update_timestamp');
+
return ($update_time == null) ? 0 : $update_time;
}
public static function GetClientId()
{
- return self::getValue("client_id");
+ return self::getValue('client_id');
}
public static function SetClientId($id)
{
if (is_numeric($id)) {
- self::setValue("client_id", $id);
+ self::setValue('client_id', $id);
} else {
- Logging::warn("Attempting to set client_id to invalid value: $id");
+ Logging::warn("Attempting to set client_id to invalid value: {$id}");
}
}
- /* User specific preferences start */
+ // User specific preferences start
/**
* Sets the time scale preference (agendaDay/agendaWeek/month) in Calendar.
@@ -981,18 +993,18 @@ class Application_Model_Preference
*/
public static function SetCalendarTimeScale($timeScale)
{
- self::setValue("calendar_time_scale", $timeScale, true /* user specific */);
+ self::setValue('calendar_time_scale', $timeScale, true /* user specific */);
}
/**
* Retrieves the time scale preference for the current user.
- * Defaults to month if no entry exists
+ * Defaults to month if no entry exists.
*/
public static function GetCalendarTimeScale()
{
- $val = self::getValue("calendar_time_scale", true /* user specific */);
+ $val = self::getValue('calendar_time_scale', true /* user specific */);
if (strlen($val) == 0) {
- $val = "month";
+ $val = 'month';
}
return $val;
@@ -1005,18 +1017,18 @@ class Application_Model_Preference
*/
public static function SetLibraryNumEntries($numEntries)
{
- self::setValue("library_num_entries", $numEntries, true /* user specific */);
+ self::setValue('library_num_entries', $numEntries, true /* user specific */);
}
/**
* Retrieves the number of entries to show preference in library under Playlist Builder.
- * Defaults to 10 if no entry exists
+ * Defaults to 10 if no entry exists.
*/
public static function GetLibraryNumEntries()
{
- $val = self::getValue("library_num_entries", true /* user specific */);
+ $val = self::getValue('library_num_entries', true /* user specific */);
if (strlen($val) == 0) {
- $val = "10";
+ $val = '10';
}
return $val;
@@ -1029,48 +1041,50 @@ class Application_Model_Preference
*/
public static function SetCalendarTimeInterval($timeInterval)
{
- self::setValue("calendar_time_interval", $timeInterval, true /* user specific */);
+ self::setValue('calendar_time_interval', $timeInterval, true /* user specific */);
}
/**
* Retrieves the time interval preference for the current user.
- * Defaults to 30 min if no entry exists
+ * Defaults to 30 min if no entry exists.
*/
public static function GetCalendarTimeInterval()
{
- $val = self::getValue("calendar_time_interval", true /* user specific */);
- return (strlen($val) == 0) ? "30" : $val;
+ $val = self::getValue('calendar_time_interval', true /* user specific */);
+
+ return (strlen($val) == 0) ? '30' : $val;
}
public static function SetDiskQuota($value)
{
- self::setValue("disk_quota", $value, false);
+ self::setValue('disk_quota', $value, false);
}
public static function GetDiskQuota()
{
- $val = self::getValue("disk_quota");
- return empty($val) ? 2147483648 : $val; # If there is no value for disk quota, return 2GB
+ $val = self::getValue('disk_quota');
+
+ return empty($val) ? 2147483648 : $val; // If there is no value for disk quota, return 2GB
}
public static function SetLiveStreamMasterUsername($value)
{
- self::setValue("live_stream_master_username", $value, false);
+ self::setValue('live_stream_master_username', $value, false);
}
public static function GetLiveStreamMasterUsername()
{
- return self::getValue("live_stream_master_username");
+ return self::getValue('live_stream_master_username');
}
public static function SetLiveStreamMasterPassword($value)
{
- self::setValue("live_stream_master_password", $value, false);
+ self::setValue('live_stream_master_password', $value, false);
}
public static function GetLiveStreamMasterPassword()
{
- return self::getValue("live_stream_master_password");
+ return self::getValue('live_stream_master_password');
}
public static function SetSourceStatus($sourcename, $status)
@@ -1081,12 +1095,13 @@ class Application_Model_Preference
public static function GetSourceStatus($sourcename)
{
$value = self::getValue($sourcename);
- return !($value == null || $value == "false");
+
+ return !($value == null || $value == 'false');
}
public static function SetSourceSwitchStatus($sourcename, $status)
{
- self::setValue($sourcename."_switch", $status, false);
+ self::setValue($sourcename . '_switch', $status, false);
}
public static function GetSourceSwitchStatus($sourcename)
@@ -1094,90 +1109,91 @@ class Application_Model_Preference
// Scheduled play switch should always be "on".
// Even though we've hidden this element in the dashboard we should
// always make sure it's on or else a station's stream could go offline.
- if ($sourcename == "scheduled_play") {
- return "on";
+ if ($sourcename == 'scheduled_play') {
+ return 'on';
}
- $value = self::getValue($sourcename."_switch");
- return ($value == null || $value == "off") ? 'off' : 'on';
+ $value = self::getValue($sourcename . '_switch');
+
+ return ($value == null || $value == 'off') ? 'off' : 'on';
}
public static function SetMasterDJSourceConnectionURL($value)
{
- self::setValue("master_dj_source_connection_url", $value, false);
+ self::setValue('master_dj_source_connection_url', $value, false);
}
public static function GetMasterDJSourceConnectionURL()
{
- $master_connection_url = self::getValue("master_dj_source_connection_url");
- if ($master_connection_url == "") {
- $master_connection_url = "http://".$_SERVER['SERVER_NAME'].":". Application_Model_StreamSetting::getMasterLiveStreamPort() . Application_Model_StreamSetting::getMasterLiveStreamMountPoint();
- }
+ $master_connection_url = self::getValue('master_dj_source_connection_url');
+ if ($master_connection_url == '') {
+ $master_connection_url = 'http://' . $_SERVER['SERVER_NAME'] . ':' . Application_Model_StreamSetting::getMasterLiveStreamPort() . Application_Model_StreamSetting::getMasterLiveStreamMountPoint();
+ }
return $master_connection_url;
-
}
public static function SetLiveDJSourceConnectionURL($value)
{
- self::setValue("live_dj_source_connection_url", $value, false);
+ self::setValue('live_dj_source_connection_url', $value, false);
}
public static function GetLiveDJSourceConnectionURL()
{
- $livedj_connection_url = self::getValue("live_dj_source_connection_url");
- if ($livedj_connection_url == "") {
- $livedj_connection_url = "http://".$_SERVER['SERVER_NAME'].":". Application_Model_StreamSetting::getDjLiveStreamPort() . Application_Model_StreamSetting::getDjLiveStreamMountPoint();
+ $livedj_connection_url = self::getValue('live_dj_source_connection_url');
+ if ($livedj_connection_url == '') {
+ $livedj_connection_url = 'http://' . $_SERVER['SERVER_NAME'] . ':' . Application_Model_StreamSetting::getDjLiveStreamPort() . Application_Model_StreamSetting::getDjLiveStreamMountPoint();
}
+
return $livedj_connection_url;
}
- /* Source Connection URL override status starts */
+ // Source Connection URL override status starts
public static function GetLiveDjConnectionUrlOverride()
{
- return self::getValue("live_dj_connection_url_override");
+ return self::getValue('live_dj_connection_url_override');
}
public static function SetLiveDjConnectionUrlOverride($value)
{
- self::setValue("live_dj_connection_url_override", $value, false);
+ self::setValue('live_dj_connection_url_override', $value, false);
}
public static function GetMasterDjConnectionUrlOverride()
{
- return self::getValue("master_dj_connection_url_override");
+ return self::getValue('master_dj_connection_url_override');
}
public static function SetMasterDjConnectionUrlOverride($value)
{
- self::setValue("master_dj_connection_url_override", $value, false);
+ self::setValue('master_dj_connection_url_override', $value, false);
}
- /* Source Connection URL override status ends */
+ // Source Connection URL override status ends
public static function SetAutoTransition($value)
{
- self::setValue("auto_transition", $value, false);
+ self::setValue('auto_transition', $value, false);
}
public static function GetAutoTransition()
{
- return self::getValue("auto_transition");
+ return self::getValue('auto_transition');
}
public static function SetAutoSwitch($value)
{
- self::setValue("auto_switch", $value, false);
+ self::setValue('auto_switch', $value, false);
}
public static function GetAutoSwitch()
{
- return self::getValue("auto_switch");
+ return self::getValue('auto_switch');
}
- /* User specific preferences end */
+ // User specific preferences end
public static function ShouldShowPopUp()
{
- $today = mktime(0, 0, 0, gmdate("m"), gmdate("d"), gmdate("Y"));
+ $today = mktime(0, 0, 0, gmdate('m'), gmdate('d'), gmdate('Y'));
$remindDate = Application_Model_Preference::GetRemindMeDate();
$retVal = false;
@@ -1188,8 +1204,6 @@ class Application_Model_Preference
return $retVal;
}
-
-
public static function getOrderingMap($pref_param)
{
$v = self::getValue($pref_param, true);
@@ -1202,7 +1216,6 @@ class Application_Model_Preference
$ds = unserialize($v);
-
if (is_null($ds) || !is_array($ds)) {
return $id;
}
@@ -1214,119 +1227,130 @@ class Application_Model_Preference
return function ($x) use ($ds) {
if (array_key_exists($x, $ds['ColReorder'])) {
return $ds['ColReorder'][$x];
- } else {
- /*For now we just have this hack for debugging. We should not
- rely on this behaviour in case of failure*/
- Logging::warn("Index $x does not exist preferences");
- Logging::warn("Defaulting to identity and printing preferences");
- Logging::warn($ds);
- return $x;
}
+ /*For now we just have this hack for debugging. We should not
+ rely on this behaviour in case of failure*/
+ Logging::warn("Index {$x} does not exist preferences");
+ Logging::warn('Defaulting to identity and printing preferences');
+ Logging::warn($ds);
+
+ return $x;
};
}
public static function getCurrentLibraryTableColumnMap()
{
- return self::getOrderingMap("library_datatable");
+ return self::getOrderingMap('library_datatable');
}
public static function setCurrentLibraryTableSetting($settings)
{
$data = serialize($settings);
- self::setValue("library_datatable", $data, true);
+ self::setValue('library_datatable', $data, true);
}
public static function getCurrentLibraryTableSetting()
{
- $data = self::getValue("library_datatable", true);
- return ($data != "") ? unserialize($data) : null;
- }
+ $data = self::getValue('library_datatable', true);
+ return ($data != '') ? unserialize($data) : null;
+ }
public static function setTimelineDatatableSetting($settings)
{
$data = serialize($settings);
- self::setValue("timeline_datatable", $data, true);
+ self::setValue('timeline_datatable', $data, true);
}
public static function getTimelineDatatableSetting()
{
- $data = self::getValue("timeline_datatable", true);
- return ($data != "") ? unserialize($data) : null;
- }
+ $data = self::getValue('timeline_datatable', true);
+ return ($data != '') ? unserialize($data) : null;
+ }
public static function setNowPlayingScreenSettings($settings)
{
$data = serialize($settings);
- self::setValue("nowplaying_screen", $data, true);
+ self::setValue('nowplaying_screen', $data, true);
}
public static function getNowPlayingScreenSettings()
{
- $data = self::getValue("nowplaying_screen", true);
- return ($data != "") ? unserialize($data) : null;
+ $data = self::getValue('nowplaying_screen', true);
+
+ return ($data != '') ? unserialize($data) : null;
}
public static function setLibraryScreenSettings($settings)
{
$data = serialize($settings);
- self::setValue("library_screen", $data, true);
+ self::setValue('library_screen', $data, true);
}
public static function getLibraryScreenSettings()
{
- $data = self::getValue("library_screen", true);
- return ($data != "") ? unserialize($data) : null;
+ $data = self::getValue('library_screen', true);
+
+ return ($data != '') ? unserialize($data) : null;
}
- public static function SetEnableReplayGain($value) {
- self::setValue("enable_replay_gain", $value, false);
+ public static function SetEnableReplayGain($value)
+ {
+ self::setValue('enable_replay_gain', $value, false);
}
- public static function GetEnableReplayGain() {
- return self::getValue("enable_replay_gain", false);
+ public static function GetEnableReplayGain()
+ {
+ return self::getValue('enable_replay_gain', false);
}
- public static function getReplayGainModifier() {
- $rg_modifier = self::getValue("replay_gain_modifier");
+ public static function getReplayGainModifier()
+ {
+ $rg_modifier = self::getValue('replay_gain_modifier');
- if ($rg_modifier === "")
- return "0";
+ if ($rg_modifier === '') {
+ return '0';
+ }
return $rg_modifier;
}
public static function setReplayGainModifier($rg_modifier)
{
- self::setValue("replay_gain_modifier", $rg_modifier, true);
+ self::setValue('replay_gain_modifier', $rg_modifier, true);
}
- public static function SetHistoryItemTemplate($value) {
- self::setValue("history_item_template", $value);
+ public static function SetHistoryItemTemplate($value)
+ {
+ self::setValue('history_item_template', $value);
}
- public static function GetHistoryItemTemplate() {
- return self::getValue("history_item_template");
+ public static function GetHistoryItemTemplate()
+ {
+ return self::getValue('history_item_template');
}
- public static function SetHistoryFileTemplate($value) {
- self::setValue("history_file_template", $value);
+ public static function SetHistoryFileTemplate($value)
+ {
+ self::setValue('history_file_template', $value);
}
- public static function GetHistoryFileTemplate() {
- return self::getValue("history_file_template");
+ public static function GetHistoryFileTemplate()
+ {
+ return self::getValue('history_file_template');
}
public static function getDiskUsage()
{
- $val = self::getValue("disk_usage");
+ $val = self::getValue('disk_usage');
+
return (strlen($val) == 0) ? 0 : $val;
}
public static function setDiskUsage($value)
{
- self::setValue("disk_usage", $value);
+ self::setValue('disk_usage', $value);
}
public static function updateDiskUsage($filesize)
@@ -1341,220 +1365,242 @@ class Application_Model_Preference
public static function setTuneinEnabled($value)
{
- self::setValue("tunein_enabled", $value);
+ self::setValue('tunein_enabled', $value);
}
public static function getTuneinEnabled()
{
- return self::getValue("tunein_enabled");
+ return self::getValue('tunein_enabled');
}
public static function setTuneinPartnerKey($value)
{
- self::setValue("tunein_partner_key", $value);
+ self::setValue('tunein_partner_key', $value);
}
public static function getTuneinPartnerKey()
{
- return self::getValue("tunein_partner_key");
+ return self::getValue('tunein_partner_key');
}
public static function setTuneinPartnerId($value)
{
- self::setValue("tunein_partner_id", $value);
+ self::setValue('tunein_partner_id', $value);
}
public static function getTuneinPartnerId()
{
- return self::getValue("tunein_partner_id");
+ return self::getValue('tunein_partner_id');
}
public static function setTuneinStationId($value)
{
- self::setValue("tunein_station_id", $value);
+ self::setValue('tunein_station_id', $value);
}
public static function getTuneinStationId()
{
- return self::getValue("tunein_station_id");
+ return self::getValue('tunein_station_id');
}
public static function geLastTuneinMetadataUpdate()
{
- return self::getValue("last_tunein_metadata_update");
+ return self::getValue('last_tunein_metadata_update');
}
public static function setLastTuneinMetadataUpdate($value)
{
- self::setValue("last_tunein_metadata_update", $value);
+ self::setValue('last_tunein_metadata_update', $value);
}
// TaskManager Lock Timestamp
- public static function getTaskManagerLock() {
- return self::getValue("task_manager_lock");
+ public static function getTaskManagerLock()
+ {
+ return self::getValue('task_manager_lock');
}
- public static function setTaskManagerLock($value) {
- self::setValue("task_manager_lock", $value);
+ public static function setTaskManagerLock($value)
+ {
+ self::setValue('task_manager_lock', $value);
}
// SAAS-876 - Toggle indicating whether user is using custom stream settings
- public static function getUsingCustomStreamSettings() {
- $val = self::getValue("using_custom_stream_settings");
+ public static function getUsingCustomStreamSettings()
+ {
+ $val = self::getValue('using_custom_stream_settings');
+
return empty($val) ? false : $val;
}
- public static function setUsingCustomStreamSettings($value) {
- self::setValue("using_custom_stream_settings", $value);
+ public static function setUsingCustomStreamSettings($value)
+ {
+ self::setValue('using_custom_stream_settings', $value);
}
// SAAS-876 - Store the default Icecast password to restore when switching
// back to Airtime Pro streaming settings
- public static function getDefaultIcecastPassword() {
- $val = self::getValue("default_icecast_password");
+ public static function getDefaultIcecastPassword()
+ {
+ $val = self::getValue('default_icecast_password');
+
return empty($val) ? DEFAULT_ICECAST_PASS : $val;
}
- public static function setDefaultIcecastPassword($value) {
- self::setValue("default_icecast_password", $value);
+ public static function setDefaultIcecastPassword($value)
+ {
+ self::setValue('default_icecast_password', $value);
}
public static function getRadioPageDisplayLoginButton()
{
- return self::getValue("radio_page_display_login_button");
+ return self::getValue('radio_page_display_login_button');
}
public static function setRadioPageDisplayLoginButton($value)
{
- self::setValue("radio_page_display_login_button", $value);
+ self::setValue('radio_page_display_login_button', $value);
}
public static function getLangTimezoneSetupComplete()
{
- return self::getValue("lang_tz_setup_complete");
+ return self::getValue('lang_tz_setup_complete');
}
public static function setLangTimezoneSetupComplete($value)
{
- self::setValue("lang_tz_setup_complete", $value);
+ self::setValue('lang_tz_setup_complete', $value);
}
public static function getWhatsNewDialogViewed()
{
- $val = self::getValue("whats_new_dialog_viewed", true);
+ $val = self::getValue('whats_new_dialog_viewed', true);
if (empty($val)) {
// Check the default (no user ID) value if the user value is empty
// This is so that new stations won't see the popup
- $val = self::getValue("whats_new_dialog_viewed", false, true);
+ $val = self::getValue('whats_new_dialog_viewed', false, true);
}
+
return empty($val) ? false : $val;
}
public static function setWhatsNewDialogViewed($value)
{
- self::setValue("whats_new_dialog_viewed", $value, true);
+ self::setValue('whats_new_dialog_viewed', $value, true);
}
- public static function getAutoPlaylistPollLock() {
- return self::getValue("autoplaylist_poll_lock");
+ public static function getAutoPlaylistPollLock()
+ {
+ return self::getValue('autoplaylist_poll_lock');
}
public static function setAutoPlaylistPollLock($value)
{
- self::setValue("autoplaylist_poll_lock", $value);
+ self::setValue('autoplaylist_poll_lock', $value);
}
- public static function getPodcastPollLock() {
- return self::getValue("podcast_poll_lock");
+ public static function getPodcastPollLock()
+ {
+ return self::getValue('podcast_poll_lock');
}
public static function setPodcastPollLock($value)
{
- self::setValue("podcast_poll_lock", $value);
+ self::setValue('podcast_poll_lock', $value);
}
public static function getStationPodcastId()
{
// Create the Station podcast if it doesn't exist.
- $stationPodcastId = self::getValue("station_podcast_id");
+ $stationPodcastId = self::getValue('station_podcast_id');
if (empty($stationPodcastId)) {
$stationPodcastId = Application_Service_PodcastService::createStationPodcast();
}
+
return $stationPodcastId;
}
public static function setStationPodcastId($value)
{
- self::setValue("station_podcast_id", $value);
+ self::setValue('station_podcast_id', $value);
}
// SAAS-1081 - Implement a universal download key for downloading episodes from the station podcast
// Store and increment the download counter, resetting every month
- public static function getStationPodcastDownloadKey() {
- return self::getValue("station_podcast_download_key");
+ public static function getStationPodcastDownloadKey()
+ {
+ return self::getValue('station_podcast_download_key');
}
- public static function setStationPodcastDownloadKey($value = null) {
+ public static function setStationPodcastDownloadKey($value = null)
+ {
$value = empty($value) ? (new Application_Model_Auth())->generateRandomString() : $value;
- self::setValue("station_podcast_download_key", $value);
+ self::setValue('station_podcast_download_key', $value);
}
- public static function getStationPodcastDownloadResetTimer() {
- return self::getValue("station_podcast_download_reset_timer");
+ public static function getStationPodcastDownloadResetTimer()
+ {
+ return self::getValue('station_podcast_download_reset_timer');
}
- public static function setStationPodcastDownloadResetTimer($value) {
- self::setValue("station_podcast_download_reset_timer", $value);
+ public static function setStationPodcastDownloadResetTimer($value)
+ {
+ self::setValue('station_podcast_download_reset_timer', $value);
}
- public static function getStationPodcastDownloadCounter() {
- return self::getValue("station_podcast_download_counter");
+ public static function getStationPodcastDownloadCounter()
+ {
+ return self::getValue('station_podcast_download_counter');
}
- public static function resetStationPodcastDownloadCounter() {
- self::setValue("station_podcast_download_counter", 0);
+ public static function resetStationPodcastDownloadCounter()
+ {
+ self::setValue('station_podcast_download_counter', 0);
}
- public static function incrementStationPodcastDownloadCounter() {
+ public static function incrementStationPodcastDownloadCounter()
+ {
$c = self::getStationPodcastDownloadCounter();
- self::setValue("station_podcast_download_counter", empty($c) ? 1 : ++$c);
+ self::setValue('station_podcast_download_counter', empty($c) ? 1 : ++$c);
}
// For fail cases, we may need to decrement the download counter
- public static function decrementStationPodcastDownloadCounter() {
+ public static function decrementStationPodcastDownloadCounter()
+ {
$c = self::getStationPodcastDownloadCounter();
- self::setValue("station_podcast_download_counter", empty($c) ? 0 : --$c);
+ self::setValue('station_podcast_download_counter', empty($c) ? 0 : --$c);
}
/**
* @return int either 0 (public) or 1 (private)
*/
- public static function getStationPodcastPrivacy() {
- return self::getValue("station_podcast_privacy");
+ public static function getStationPodcastPrivacy()
+ {
+ return self::getValue('station_podcast_privacy');
}
- public static function setStationPodcastPrivacy($value) {
- self::setValue("station_podcast_privacy", $value);
+ public static function setStationPodcastPrivacy($value)
+ {
+ self::setValue('station_podcast_privacy', $value);
}
/**
- * Getter for CORS URLs
+ * Getter for CORS URLs.
*
* @return string
*/
- public static function GetAllowedCorsUrls() {
+ public static function GetAllowedCorsUrls()
+ {
return self::getValue('allowed_cors_urls');
}
/**
- * Setter for CORS URLs
+ * Setter for CORS URLs.
*
* @param string $value
- * @return void
*/
public static function SetAllowedCorsUrls($value)
{
@@ -1574,7 +1620,8 @@ class Application_Model_Preference
*
* @return bool
*/
- public static function GetFeaturePreviewMode() {
+ public static function GetFeaturePreviewMode()
+ {
return self::getValue('feature_preview_mode') === '1';
}
@@ -1582,9 +1629,9 @@ class Application_Model_Preference
* Setter for feature preview mode.
*
* @param bool $value
- * @return void
*/
- public static function SetFeaturePreviewMode($value) {
+ public static function SetFeaturePreviewMode($value)
+ {
return self::setValue('feature_preview_mode', $value);
}
}
diff --git a/legacy/application/models/RabbitMq.php b/legacy/application/models/RabbitMq.php
index 8e2a2336e..caf0f50df 100644
--- a/legacy/application/models/RabbitMq.php
+++ b/legacy/application/models/RabbitMq.php
@@ -12,29 +12,36 @@ class Application_Model_RabbitMq
self::$doPush = true;
}
- private static function sendMessage($exchange, $exchangeType, $autoDeleteExchange, $data, $queue="")
+ private static function sendMessage($exchange, $exchangeType, $autoDeleteExchange, $data, $queue = '')
{
$CC_CONFIG = Config::getConfig();
- $conn = new \PhpAmqpLib\Connection\AMQPConnection($CC_CONFIG["rabbitmq"]["host"],
- $CC_CONFIG["rabbitmq"]["port"],
- $CC_CONFIG["rabbitmq"]["user"],
- $CC_CONFIG["rabbitmq"]["password"],
- $CC_CONFIG["rabbitmq"]["vhost"]);
+ $conn = new \PhpAmqpLib\Connection\AMQPConnection(
+ $CC_CONFIG['rabbitmq']['host'],
+ $CC_CONFIG['rabbitmq']['port'],
+ $CC_CONFIG['rabbitmq']['user'],
+ $CC_CONFIG['rabbitmq']['password'],
+ $CC_CONFIG['rabbitmq']['vhost']
+ );
if (!isset($conn)) {
- throw new Exception("Cannot connect to RabbitMQ server");
+ throw new Exception('Cannot connect to RabbitMQ server');
}
$channel = $conn->channel();
- $channel->access_request($CC_CONFIG["rabbitmq"]["vhost"], false, false,
- true, true);
+ $channel->access_request(
+ $CC_CONFIG['rabbitmq']['vhost'],
+ false,
+ false,
+ true,
+ true
+ );
//I'm pretty sure we DON'T want to autodelete ANY exchanges but I'm keeping the code
//the way it is just so I don't accidentally break anything when I add the Analyzer code in. -- Albert, March 13, 2014
$channel->exchange_declare($exchange, $exchangeType, false, true, $autoDeleteExchange);
- $msg = new \PhpAmqpLib\Message\AMQPMessage($data, array('content_type' => 'text/plain'));
+ $msg = new \PhpAmqpLib\Message\AMQPMessage($data, ['content_type' => 'text/plain']);
$channel->basic_publish($msg, $exchange);
$channel->close();
@@ -43,7 +50,7 @@ class Application_Model_RabbitMq
public static function SendMessageToPypo($event_type, $md)
{
- $md["event_type"] = $event_type;
+ $md['event_type'] = $event_type;
$exchange = 'airtime-pypo';
$data = json_encode($md, JSON_FORCE_OBJECT);
@@ -52,7 +59,7 @@ class Application_Model_RabbitMq
public static function SendMessageToMediaMonitor($event_type, $md)
{
- $md["event_type"] = $event_type;
+ $md['event_type'] = $event_type;
$exchange = 'airtime-analyzer';
$data = json_encode($md);
@@ -63,32 +70,43 @@ class Application_Model_RabbitMq
{
$exchange = 'airtime-pypo';
- $now = new DateTime("@".time()); //in UTC timezone
- $end_timestamp = new DateTime("@".(time() + 3600*2)); //in UTC timezone
+ $now = new DateTime('@' . time()); //in UTC timezone
+ $end_timestamp = new DateTime('@' . (time() + 3600 * 2)); //in UTC timezone
- $temp = array();
+ $temp = [];
$temp['event_type'] = $event_type;
$temp['server_timezone'] = Application_Model_Preference::GetTimezone();
- if ($event_type == "update_recorder_schedule") {
- $temp['shows'] = Application_Model_Show::getShows($now,
- $end_timestamp, $onlyRecord=true);
+ if ($event_type == 'update_recorder_schedule') {
+ $temp['shows'] = Application_Model_Show::getShows(
+ $now,
+ $end_timestamp,
+ $onlyRecord = true
+ );
}
$data = json_encode($temp);
self::sendMessage($exchange, 'direct', true, $data);
}
- public static function SendMessageToAnalyzer($tmpFilePath, $importedStorageDirectory, $originalFilename,
- $callbackUrl, $apiKey, $storageBackend, $filePrefix)
- {
+ public static function SendMessageToAnalyzer(
+ $tmpFilePath,
+ $importedStorageDirectory,
+ $originalFilename,
+ $callbackUrl,
+ $apiKey,
+ $storageBackend,
+ $filePrefix
+ ) {
$config = Config::getConfig();
- $conn = new \PhpAmqpLib\Connection\AMQPConnection($config["rabbitmq"]["host"],
- $config["rabbitmq"]["port"],
- $config["rabbitmq"]["user"],
- $config["rabbitmq"]["password"],
- $config["rabbitmq"]["vhost"]);
-
+ $conn = new \PhpAmqpLib\Connection\AMQPConnection(
+ $config['rabbitmq']['host'],
+ $config['rabbitmq']['port'],
+ $config['rabbitmq']['user'],
+ $config['rabbitmq']['password'],
+ $config['rabbitmq']['vhost']
+ );
+
$exchange = 'airtime-uploads';
$exchangeType = 'topic';
$queue = 'airtime-uploads';
@@ -101,32 +119,36 @@ class Application_Model_RabbitMq
$data['api_key'] = $apiKey;
// We add a prefix to the resource name so files are not all placed
- // under the root folder. We do this in case we need to restore a
+ // under the root folder. We do this in case we need to restore a
// customer's file/s; File restoration is done via the S3 Browser
// client. The client will hang if there are too many files under the
// same folder.
$data['file_prefix'] = $filePrefix;
-
+
$jsonData = json_encode($data);
//self::sendMessage($exchange, 'topic', false, $jsonData, 'airtime-uploads');
-
+
if (!isset($conn)) {
- throw new Exception("Cannot connect to RabbitMQ server");
+ throw new Exception('Cannot connect to RabbitMQ server');
}
-
+
$channel = $conn->channel();
- $channel->access_request($config["rabbitmq"]["vhost"], false, false,
- true, true);
-
+ $channel->access_request(
+ $config['rabbitmq']['vhost'],
+ false,
+ false,
+ true,
+ true
+ );
+
//I'm pretty sure we DON'T want to autodelete ANY exchanges but I'm keeping the code
//the way it is just so I don't accidentally break anything when I add the Analyzer code in. -- Albert, March 13, 2014
$channel->exchange_declare($exchange, $exchangeType, false, true, $autoDeleteExchange);
-
- $msg = new \PhpAmqpLib\Message\AMQPMessage($jsonData, array('content_type' => 'text/plain'));
+
+ $msg = new \PhpAmqpLib\Message\AMQPMessage($jsonData, ['content_type' => 'text/plain']);
$channel->basic_publish($msg, $exchange);
$channel->close();
$conn->close();
-
}
}
diff --git a/legacy/application/models/Schedule.php b/legacy/application/models/Schedule.php
index 34dcd4688..7b673c1c0 100644
--- a/legacy/application/models/Schedule.php
+++ b/legacy/application/models/Schedule.php
@@ -2,11 +2,10 @@
class Application_Model_Schedule
{
-
- const MASTER_SOURCE_NAME = "Master";
- const SHOW_SOURCE_NAME = "Live";
- const SCHEDULED_SOURCE_NAME = "Scheduled";
- const LIVE_STREAM = "Live Stream";
+ public const MASTER_SOURCE_NAME = 'Master';
+ public const SHOW_SOURCE_NAME = 'Live';
+ public const SCHEDULED_SOURCE_NAME = 'Scheduled';
+ public const LIVE_STREAM = 'Live Stream';
/**
* Return TRUE if file is going to be played in the future.
@@ -15,29 +14,30 @@ class Application_Model_Schedule
*/
public static function IsFileScheduledInTheFuture($p_fileId)
{
- $sql = << NOW() AT TIME ZONE 'UTC'
SQL;
- $count = Application_Common_Database::prepareAndExecute( $sql, array(
- ':file_id'=>$p_fileId), 'column');
- return (is_numeric($count) && ($count != '0'));
+ $count = Application_Common_Database::prepareAndExecute($sql, [
+ ':file_id' => $p_fileId, ], 'column');
+
+ return is_numeric($count) && ($count != '0');
}
- public static function getAllFutureScheduledFiles($instanceId=null)
+ public static function getAllFutureScheduledFiles($instanceId = null)
{
- $sql = << now() AT TIME ZONE 'UTC'
AND file_id is not null
SQL;
- $files = Application_Common_Database::prepareAndExecute( $sql, array());
+ $files = Application_Common_Database::prepareAndExecute($sql, []);
- $real_files = array();
+ $real_files = [];
foreach ($files as $f) {
$real_files[] = $f['file_id'];
}
@@ -47,15 +47,15 @@ SQL;
public static function getAllFutureScheduledWebstreams()
{
- $sql = << now() AT TIME ZONE 'UTC'
AND stream_id is not null
SQL;
- $streams = Application_Common_Database::prepareAndExecute( $sql, array());
+ $streams = Application_Common_Database::prepareAndExecute($sql, []);
- $real_streams = array();
+ $real_streams = [];
foreach ($streams as $s) {
$real_streams[] = $s['stream_id'];
}
@@ -74,20 +74,23 @@ SQL;
public static function getCurrentPlayingTrack()
{
$currentScheduleInfo = self::GetPlayOrderRange();
- if (empty($currentScheduleInfo["tracks"]["current"])) {
+ if (empty($currentScheduleInfo['tracks']['current'])) {
return null;
}
- $currentTrackArray = explode(" - ", $currentScheduleInfo["tracks"]["current"]["name"]);
- $currentTrackMetadata = array(
- "artist" => empty($currentTrackArray[0]) ? null : urlencode($currentTrackArray[0]),
- "title" => empty($currentTrackArray[1]) ? null : urlencode($currentTrackArray[1])
- );
- return $currentTrackMetadata;
+ $currentTrackArray = explode(' - ', $currentScheduleInfo['tracks']['current']['name']);
+
+ return [
+ 'artist' => empty($currentTrackArray[0]) ? null : urlencode($currentTrackArray[0]),
+ 'title' => empty($currentTrackArray[1]) ? null : urlencode($currentTrackArray[1]),
+ ];
}
-
+
/**
* Returns data related to the scheduled items.
+ *
+ * @param null|mixed $utcTimeEnd
+ * @param mixed $showsToRetrieve
*/
public static function GetPlayOrderRange($utcTimeEnd = null, $showsToRetrieve = 5)
{
@@ -96,73 +99,70 @@ SQL;
// 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"));
+ $end->add(new DateInterval('P2D')); // Add 2 days
+ $end->setTimezone(new DateTimeZone('UTC'));
$utcTimeEnd = $end->format(DEFAULT_TIMESTAMP_FORMAT);
}
- $utcNow = new DateTime("now", new DateTimeZone("UTC"));
+ $utcNow = new DateTime('now', new DateTimeZone('UTC'));
$shows = Application_Model_Show::getPrevCurrentNext($utcNow, $utcTimeEnd, $showsToRetrieve);
$currentShowID = null;
- if (is_array($shows['currentShow']) && count($shows['currentShow'])>0) {
- $currentShowID = $shows['currentShow']['instance_id'];
+ if (is_array($shows['currentShow']) && count($shows['currentShow']) > 0) {
+ $currentShowID = $shows['currentShow']['instance_id'];
}
$source = self::_getSource();
$results = Application_Model_Schedule::getPreviousCurrentNextMedia($utcNow, $currentShowID, self::_getSource());
- $range = array(
- "station" => array (
- "env" => APPLICATION_ENV,
- "schedulerTime" => $utcNow->format(DEFAULT_TIMESTAMP_FORMAT),
- "source_enabled" => $source
- ),
+ return [
+ 'station' => [
+ 'env' => APPLICATION_ENV,
+ 'schedulerTime' => $utcNow->format(DEFAULT_TIMESTAMP_FORMAT),
+ 'source_enabled' => $source,
+ ],
//Previous, current, next songs!
- "tracks" => array(
- "previous" => $results['previous'],
- "current" => $results['current'],
- "next" => $results['next']
- ),
+ 'tracks' => [
+ '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;
+ 'shows' => [
+ 'previous' => $shows['previousShow'],
+ 'current' => $shows['currentShow'],
+ 'next' => $shows['nextShow'],
+ ],
+ ];
}
/**
- * Old version of the function for backwards compatibility
+ * 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"));
-
+
+ $utcNow = new DateTime('now', new DateTimeZone('UTC'));
+
$shows = Application_Model_Show::getPrevCurrentNextOld($utcNow);
- $currentShowID = count($shows['currentShow'])>0?$shows['currentShow'][0]['instance_id']:null;
+ $currentShowID = count($shows['currentShow']) > 0 ? $shows['currentShow'][0]['instance_id'] : null;
$source = self::_getSource();
$results = Application_Model_Schedule::getPreviousCurrentNextMedia($utcNow, $currentShowID, $source);
- $range = array(
- "env" => APPLICATION_ENV,
- "schedulerTime" => $utcNow->format(DEFAULT_TIMESTAMP_FORMAT),
- //Previous, current, next songs!
- "previous"=>$results['previous'] !=null?$results['previous']:(count($shows['previousShow'])>0?$shows['previousShow'][0]:null),
- "current"=>$results['current'] !=null?$results['current']:((count($shows['currentShow'])>0 && $shows['currentShow'][0]['record'] == 1)?$shows['currentShow'][0]:null),
- "next"=> $results['next'] !=null?$results['next']:(count($shows['nextShow'])>0?$shows['nextShow'][0]:null),
- //Current and next shows
- "currentShow"=>$shows['currentShow'],
- "nextShow"=>$shows['nextShow'],
- "source_enabled" => $source
- );
-
- return $range;
+ return [
+ 'env' => APPLICATION_ENV,
+ 'schedulerTime' => $utcNow->format(DEFAULT_TIMESTAMP_FORMAT),
+ //Previous, current, next songs!
+ 'previous' => $results['previous'] != null ? $results['previous'] : (count($shows['previousShow']) > 0 ? $shows['previousShow'][0] : null),
+ 'current' => $results['current'] != null ? $results['current'] : ((count($shows['currentShow']) > 0 && $shows['currentShow'][0]['record'] == 1) ? $shows['currentShow'][0] : null),
+ 'next' => $results['next'] != null ? $results['next'] : (count($shows['nextShow']) > 0 ? $shows['nextShow'][0] : null),
+ //Current and next shows
+ 'currentShow' => $shows['currentShow'],
+ 'nextShow' => $shows['nextShow'],
+ 'source_enabled' => $source,
+ ];
}
/**
@@ -173,29 +173,30 @@ SQL;
* @param $utcNow DateTime current time in UTC
* @param $currentShowInstanceId int id of the show instance currently playing
* @param $source string the current prioritized source
+ *
* @return array with data about the previous, current, and next media items playing.
- * Returns an empty arrays if there is no media item currently playing
+ * Returns an empty arrays if there is no media item currently playing
*/
public static function getPreviousCurrentNextMedia($utcNow, $currentShowInstanceId, $source)
{
- $timeZone = new DateTimeZone("UTC"); //This function works entirely in UTC.
- assert(get_class($utcNow) === "DateTime");
+ $timeZone = new DateTimeZone('UTC'); //This function works entirely in UTC.
+ assert(get_class($utcNow) === 'DateTime');
assert($utcNow->getTimeZone() == $timeZone);
$results['previous'] = null;
- $results['current'] = null;
- $results['next'] = null;
+ $results['current'] = null;
+ $results['next'] = null;
- $sql = "select s.id, s.starts, s.ends, s.file_id, s.stream_id, s.media_item_played,
+ $sql = 'select s.id, s.starts, s.ends, s.file_id, s.stream_id, s.media_item_played,
s.instance_id, si.ends as show_ends from cc_schedule s left join cc_show_instances si
on s.instance_id = si.id where s.playout_status > 0 and s.starts <= :p1
- and s.ends >= :p2 and s.instance_id = :p3 order by starts desc limit 1";
+ and s.ends >= :p2 and s.instance_id = :p3 order by starts desc limit 1';
- $params = array(
- ":p1" => $utcNow->format(DEFAULT_TIMESTAMP_FORMAT),
- ":p2" => $utcNow->format(DEFAULT_TIMESTAMP_FORMAT),
- ":p3" => $currentShowInstanceId
- );
+ $params = [
+ ':p1' => $utcNow->format(DEFAULT_TIMESTAMP_FORMAT),
+ ':p2' => $utcNow->format(DEFAULT_TIMESTAMP_FORMAT),
+ ':p3' => $currentShowInstanceId,
+ ];
$rows = Application_Common_Database::prepareAndExecute($sql, $params);
@@ -203,155 +204,164 @@ SQL;
// track information to the current show values
if ($source != self::SCHEDULED_SOURCE_NAME) {
$show = Application_Model_Show::getCurrentShow();
- $results["current"] = isset($show[0]) ? array(
- "starts" => $show[0]["starts"],
- "ends" => $show[0]["ends"],
- "type" => _("livestream"),
- "name" => $show[0]["name"] . " - " . _(self::LIVE_STREAM),
- "media_item_played" => false,
- "record" => "0"
- ) : null;
- } else if (count($rows) >= 1) {
+ $results['current'] = isset($show[0]) ? [
+ 'starts' => $show[0]['starts'],
+ 'ends' => $show[0]['ends'],
+ 'type' => _('livestream'),
+ 'name' => $show[0]['name'] . ' - ' . _(self::LIVE_STREAM),
+ 'media_item_played' => false,
+ 'record' => '0',
+ ] : null;
+ } elseif (count($rows) >= 1) {
$currentMedia = $rows[0];
- if ($currentMedia["ends"] > $currentMedia["show_ends"]) {
- $currentMedia["ends"] = $currentMedia["show_ends"];
+ if ($currentMedia['ends'] > $currentMedia['show_ends']) {
+ $currentMedia['ends'] = $currentMedia['show_ends'];
}
$currentMetadata = null;
- $currentMediaName = "";
- $currentMediaFileId = $currentMedia["file_id"];
- $currentMediaStreamId = $currentMedia["stream_id"];
+ $currentMediaName = '';
+ $currentMediaFileId = $currentMedia['file_id'];
+ $currentMediaStreamId = $currentMedia['stream_id'];
if (isset($currentMediaFileId)) {
- $currentMediaType = "track";
+ $currentMediaType = 'track';
$currentFile = CcFilesQuery::create()
->filterByDbId($currentMediaFileId)
- ->findOne();
- $currentMediaName = $currentFile->getDbArtistName() . " - " . $currentFile->getDbTrackTitle();
+ ->findOne()
+ ;
+ $currentMediaName = $currentFile->getDbArtistName() . ' - ' . $currentFile->getDbTrackTitle();
$currentMetadata = CcFiles::sanitizeResponse($currentFile);
- } else if (isset($currentMediaStreamId)) {
- $currentMediaType = "webstream";
+ } elseif (isset($currentMediaStreamId)) {
+ $currentMediaType = 'webstream';
$currentWebstream = CcWebstreamQuery::create()
->filterByDbId($currentMediaStreamId)
- ->findOne();
+ ->findOne()
+ ;
$currentWebstreamMetadata = CcWebstreamMetadataQuery::create()
- ->filterByDbInstanceId($currentMedia["id"])
+ ->filterByDbInstanceId($currentMedia['id'])
->orderByDbStartTime(Criteria::DESC)
- ->findOne();
+ ->findOne()
+ ;
$currentMediaName = $currentWebstream->getDbName();
if (isset($currentWebstreamMetadata)) {
- $currentMediaName .= " - " . $currentWebstreamMetadata->getDbLiquidsoapData();
+ $currentMediaName .= ' - ' . $currentWebstreamMetadata->getDbLiquidsoapData();
}
} else {
$currentMediaType = null;
}
- $results["current"] = array(
- "starts" => $currentMedia["starts"],
- "ends" => $currentMedia["ends"],
- "type" => $currentMediaType,
- "name" => $currentMediaName,
- "media_item_played" => $currentMedia["media_item_played"],
- "metadata" => $currentMetadata,
- "record" => "0"
- );
+ $results['current'] = [
+ 'starts' => $currentMedia['starts'],
+ 'ends' => $currentMedia['ends'],
+ 'type' => $currentMediaType,
+ 'name' => $currentMediaName,
+ 'media_item_played' => $currentMedia['media_item_played'],
+ 'metadata' => $currentMetadata,
+ 'record' => '0',
+ ];
}
$previousMedia = CcScheduleQuery::create()
->filterByDbEnds($utcNow, Criteria::LESS_THAN)
->filterByDbPlayoutStatus(0, Criteria::GREATER_THAN)
->orderByDbStarts(Criteria::DESC)
- ->findOne();
+ ->findOne()
+ ;
if (isset($previousMedia)) {
$previousMetadata = null;
- $previousMediaName = "";
+ $previousMediaName = '';
$previousMediaFileId = $previousMedia->getDbFileId();
$previousMediaStreamId = $previousMedia->getDbStreamId();
if (isset($previousMediaFileId)) {
- $previousMediaType = "track";
+ $previousMediaType = 'track';
$previousFile = CcFilesQuery::create()
->filterByDbId($previousMediaFileId)
- ->findOne();
+ ->findOne()
+ ;
if (isset($previousFile)) {
- $previousMediaName = $previousFile->getDbArtistName() . " - " . $previousFile->getDbTrackTitle();
+ $previousMediaName = $previousFile->getDbArtistName() . ' - ' . $previousFile->getDbTrackTitle();
$previousMetadata = CcFiles::sanitizeResponse($previousFile);
}
- } else if (isset($previousMediaStreamId)) {
+ } elseif (isset($previousMediaStreamId)) {
$previousMediaName = null;
- $previousMediaType = "webstream";
+ $previousMediaType = 'webstream';
$previousWebstream = CcWebstreamQuery::create()
->filterByDbId($previousMediaStreamId)
- ->findOne();
+ ->findOne()
+ ;
$previousMediaName = $previousWebstream->getDbName();
} else {
$previousMediaType = null;
}
- $results["previous"] = array(
- "starts" => $previousMedia->getDbStarts(),
- "ends" => $previousMedia->getDbEnds(),
- "type" => $previousMediaType,
- "name" => $previousMediaName,
- "metadata" => $previousMetadata,
- );
+ $results['previous'] = [
+ 'starts' => $previousMedia->getDbStarts(),
+ 'ends' => $previousMedia->getDbEnds(),
+ 'type' => $previousMediaType,
+ 'name' => $previousMediaName,
+ 'metadata' => $previousMetadata,
+ ];
}
$nextMedia = CcScheduleQuery::create()
->filterByDbStarts($utcNow, Criteria::GREATER_THAN)
->filterByDbPlayoutStatus(0, Criteria::GREATER_THAN)
->orderByDbStarts(Criteria::ASC)
- ->findOne();
+ ->findOne()
+ ;
if (isset($nextMedia)) {
$nextMetadata = null;
- $nextMediaName = "";
+ $nextMediaName = '';
$nextMediaFileId = $nextMedia->getDbFileId();
$nextMediaStreamId = $nextMedia->getDbStreamId();
if (isset($nextMediaFileId)) {
- $nextMediaType = "track";
+ $nextMediaType = 'track';
$nextFile = CcFilesQuery::create()
->filterByDbId($nextMediaFileId)
- ->findOne();
+ ->findOne()
+ ;
$nextMetadata = CcFiles::sanitizeResponse($nextFile);
- $nextMediaName = $nextFile->getDbArtistName() . " - " . $nextFile->getDbTrackTitle();
- } else if (isset($nextMediaStreamId)) {
- $nextMediaType = "webstream";
+ $nextMediaName = $nextFile->getDbArtistName() . ' - ' . $nextFile->getDbTrackTitle();
+ } elseif (isset($nextMediaStreamId)) {
+ $nextMediaType = 'webstream';
$nextWebstream = CcWebstreamQuery::create()
->filterByDbId($nextMediaStreamId)
- ->findOne();
+ ->findOne()
+ ;
$nextMediaName = $nextWebstream->getDbName();
} else {
$nextMediaType = null;
}
- $results["next"] = array(
- "starts" => $nextMedia->getDbStarts(),
- "ends" => $nextMedia->getDbEnds(),
- "type" => $nextMediaType,
- "name" => $nextMediaName,
- "metadata" => $nextMetadata
- );
+ $results['next'] = [
+ 'starts' => $nextMedia->getDbStarts(),
+ 'ends' => $nextMedia->getDbEnds(),
+ 'type' => $nextMediaType,
+ 'name' => $nextMediaName,
+ 'metadata' => $nextMetadata,
+ ];
}
return $results;
-
}
/**
- * Get the current prioritized source
+ * Get the current prioritized source.
*
* Priority order is Master->Live/Show->Scheduled.
*
* @return string the source name
*/
- private static function _getSource() {
- $live_dj = Application_Model_Preference::GetSourceStatus("live_dj");
- $master_dj = Application_Model_Preference::GetSourceStatus("master_dj");
- $source = ($master_dj ? self::MASTER_SOURCE_NAME
- : ($live_dj ? self::SHOW_SOURCE_NAME : self::SCHEDULED_SOURCE_NAME));
- return $source;
+ private static function _getSource()
+ {
+ $live_dj = Application_Model_Preference::GetSourceStatus('live_dj');
+ $master_dj = Application_Model_Preference::GetSourceStatus('master_dj');
+
+ return $master_dj ? self::MASTER_SOURCE_NAME
+ : ($live_dj ? self::SHOW_SOURCE_NAME : self::SCHEDULED_SOURCE_NAME);
}
public static function GetLastScheduleItem($p_timeNow)
{
- $sql = <<$p_timeNow));
- return $row;
+ return Application_Common_Database::prepareAndExecute($sql, [':timeNow' => $p_timeNow]);
}
public static function GetCurrentScheduleItem($p_timeNow, $p_instanceId)
@@ -380,40 +389,36 @@ SQL;
* this reason, we need to get the track that starts later, as
* this is the *real* track that is currently playing. So this
* is why we are ordering by track start time. */
- $sql = "SELECT *"
- ." FROM cc_schedule st"
- ." LEFT JOIN cc_files ft"
- ." ON st.file_id = ft.id"
- ." WHERE st.starts <= TIMESTAMP :timeNow1"
- ." AND st.instance_id = :instanceId"
- ." AND st.ends > TIMESTAMP :timeNow2"
- ." ORDER BY st.starts DESC"
- ." LIMIT 1";
+ $sql = 'SELECT *'
+ . ' FROM cc_schedule st'
+ . ' LEFT JOIN cc_files ft'
+ . ' ON st.file_id = ft.id'
+ . ' WHERE st.starts <= TIMESTAMP :timeNow1'
+ . ' AND st.instance_id = :instanceId'
+ . ' AND st.ends > TIMESTAMP :timeNow2'
+ . ' ORDER BY st.starts DESC'
+ . ' LIMIT 1';
- $row = Application_Common_Database::prepareAndExecute($sql, array(':timeNow1'=>$p_timeNow, ':instanceId'=>$p_instanceId, ':timeNow2'=>$p_timeNow,));
-
- return $row;
+ return Application_Common_Database::prepareAndExecute($sql, [':timeNow1' => $p_timeNow, ':instanceId' => $p_instanceId, ':timeNow2' => $p_timeNow]);
}
public static function GetNextScheduleItem($p_timeNow)
{
- $sql = "SELECT"
- ." ft.artist_name, ft.track_title,"
- ." st.starts as starts, st.ends as ends"
- ." 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 :timeNow"
- ." AND st.starts >= sit.starts" //this and the next line are necessary since we can overbook shows.
- ." AND st.starts < sit.ends"
- ." ORDER BY st.starts"
- ." LIMIT 1";
+ $sql = 'SELECT'
+ . ' ft.artist_name, ft.track_title,'
+ . ' st.starts as starts, st.ends as ends'
+ . ' 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 :timeNow'
+ . ' AND st.starts >= sit.starts' //this and the next line are necessary since we can overbook shows.
+ . ' AND st.starts < sit.ends'
+ . ' ORDER BY st.starts'
+ . ' LIMIT 1';
- $row = Application_Common_Database::prepareAndExecute($sql, array(':timeNow'=>$p_timeNow));
-
- return $row;
+ return Application_Common_Database::prepareAndExecute($sql, [':timeNow' => $p_timeNow]);
}
/*
@@ -432,10 +437,10 @@ SQL;
//We need to search 48 hours before and after the show times so that that we
//capture all of the show's contents.
- $p_track_start= $p_start->sub(new DateInterval("PT48H"))->format(DEFAULT_TIMESTAMP_FORMAT);
- $p_track_end = $p_end->add(new DateInterval("PT48H"))->format(DEFAULT_TIMESTAMP_FORMAT);
+ $p_track_start = $p_start->sub(new DateInterval('PT48H'))->format(DEFAULT_TIMESTAMP_FORMAT);
+ $p_track_end = $p_end->add(new DateInterval('PT48H'))->format(DEFAULT_TIMESTAMP_FORMAT);
- $templateSql = <<= :fj_ts_1
@@ -469,23 +474,27 @@ SQL;
AND sched.ends >= :fj_ts_6))
)
SQL;
- $paramMap = array(
- ":fj_ts_1" => $p_track_start,
- ":fj_ts_2" => $p_track_end,
- ":fj_ts_3" => $p_track_start,
- ":fj_ts_4" => $p_track_end,
- ":fj_ts_5" => $p_track_start,
- ":fj_ts_6" => $p_track_end,
+ $paramMap = [
+ ':fj_ts_1' => $p_track_start,
+ ':fj_ts_2' => $p_track_end,
+ ':fj_ts_3' => $p_track_start,
+ ':fj_ts_4' => $p_track_end,
+ ':fj_ts_5' => $p_track_start,
+ ':fj_ts_6' => $p_track_end,
+ ];
+
+ $filesSql = str_replace(
+ '%%columns%%',
+ $filesColumns,
+ $templateSql
+ );
+ $filesSql = str_replace(
+ '%%join%%',
+ $filesJoin,
+ $filesSql
);
- $filesSql = str_replace("%%columns%%",
- $filesColumns,
- $templateSql);
- $filesSql= str_replace("%%join%%",
- $filesJoin,
- $filesSql);
-
- $streamColumns = <<= :sj_ts_1
@@ -505,41 +514,43 @@ SQL;
)
LEFT JOIN cc_subjs AS sub ON (ws.creator_id = sub.id)
SQL;
- $map = array(
- ":sj_ts_1" => $p_track_start,
- ":sj_ts_2" => $p_track_end,
- ":sj_ts_3" => $p_track_start,
- ":sj_ts_4" => $p_track_end,
- ":sj_ts_5" => $p_track_start,
- ":sj_ts_6" => $p_track_end,
- );
+ $map = [
+ ':sj_ts_1' => $p_track_start,
+ ':sj_ts_2' => $p_track_end,
+ ':sj_ts_3' => $p_track_start,
+ ':sj_ts_4' => $p_track_end,
+ ':sj_ts_5' => $p_track_start,
+ ':sj_ts_6' => $p_track_end,
+ ];
$paramMap = $paramMap + $map;
- $streamSql = str_replace("%%columns%%",
+ $streamSql = str_replace(
+ '%%columns%%',
$streamColumns,
- $templateSql);
- $streamSql = str_replace("%%join%%",
+ $templateSql
+ );
+ $streamSql = str_replace(
+ '%%join%%',
$streamJoin,
- $streamSql);
+ $streamSql
+ );
-
- $showPredicate = "";
+ $showPredicate = '';
if (count($p_shows) > 0) {
+ $params = [];
+ $map = [];
- $params = array();
- $map = array();
+ for ($i = 0, $len = count($p_shows); $i < $len; ++$i) {
+ $holder = ':show_' . $i;
- for ($i = 0, $len = count($p_shows); $i < $len; $i++) {
- $holder = ":show_".$i;
-
- $params[] = $holder;
- $map[$holder] = $p_shows[$i];
+ $params[] = $holder;
+ $map[$holder] = $p_shows[$i];
}
- $showPredicate = " AND show_id IN (".implode(",", $params).")";
+ $showPredicate = ' AND show_id IN (' . implode(',', $params) . ')';
$paramMap = $paramMap + $map;
- } else if (count($p_show_instances) > 0) {
- $showPredicate = " AND si.id IN (".implode(",", $p_show_instances).")";
+ } elseif (count($p_show_instances) > 0) {
+ $showPredicate = ' AND si.id IN (' . implode(',', $p_show_instances) . ')';
}
$sql = <<= :ts_1
AND si.starts < :ts_2)
OR (si.ends > :ts_3
@@ -573,113 +584,116 @@ ORDER BY si_starts,
sched_starts;
SQL;
- $map = array(
- ":ts_1" => $p_start_str,
- ":ts_2" => $p_end_str,
- ":ts_3" => $p_start_str,
- ":ts_4" => $p_end_str,
- ":ts_5" => $p_start_str,
- ":ts_6" => $p_end_str,
- );
+ $map = [
+ ':ts_1' => $p_start_str,
+ ':ts_2' => $p_end_str,
+ ':ts_3' => $p_start_str,
+ ':ts_4' => $p_end_str,
+ ':ts_5' => $p_start_str,
+ ':ts_6' => $p_end_str,
+ ];
$paramMap = $paramMap + $map;
- $rows = Application_Common_Database::prepareAndExecute(
- $sql,
- $paramMap,
- Application_Common_Database::ALL
+ return Application_Common_Database::prepareAndExecute(
+ $sql,
+ $paramMap,
+ Application_Common_Database::ALL
);
-
- return $rows;
}
public static function UpdateMediaPlayedStatus($p_id)
{
- $sql = "UPDATE cc_schedule"
- ." SET media_item_played=TRUE";
+ $sql = 'UPDATE cc_schedule'
+ . ' SET media_item_played=TRUE';
// we need to update 'broadcasted' column as well
// check the current switch status
- $live_dj = Application_Model_Preference::GetSourceSwitchStatus('live_dj') == 'on';
- $master_dj = Application_Model_Preference::GetSourceSwitchStatus('master_dj') == 'on';
+ $live_dj = Application_Model_Preference::GetSourceSwitchStatus('live_dj') == 'on';
+ $master_dj = Application_Model_Preference::GetSourceSwitchStatus('master_dj') == 'on';
$scheduled_play = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play') == 'on';
if (!$live_dj && !$master_dj && $scheduled_play) {
- $sql .= ", broadcasted=1";
+ $sql .= ', broadcasted=1';
}
- $sql .= " WHERE id=:pid";
- $map = array(":pid" => $p_id);
+ $sql .= ' WHERE id=:pid';
+ $map = [':pid' => $p_id];
- Application_Common_Database::prepareAndExecute($sql, $map,
- Application_Common_Database::EXECUTE);
+ Application_Common_Database::prepareAndExecute(
+ $sql,
+ $map,
+ Application_Common_Database::EXECUTE
+ );
}
public static function UpdateBrodcastedStatus($dateTime, $value)
{
$now = $dateTime->format(DEFAULT_TIMESTAMP_FORMAT);
- $sql = <<= :ends::TIMESTAMP
SQL;
- $retVal = Application_Common_Database::prepareAndExecute($sql, array(
+ return Application_Common_Database::prepareAndExecute($sql, [
':broadcastedValue' => $value,
':starts' => $now,
- ':ends' => $now), 'execute');
- return $retVal;
+ ':ends' => $now, ], 'execute');
}
public static function getSchduledPlaylistCount()
{
- $sql = "SELECT count(*) as cnt FROM cc_schedule";
+ $sql = 'SELECT count(*) as cnt FROM cc_schedule';
- $res = Application_Common_Database::prepareAndExecute($sql, array(),
- Application_Common_Database::COLUMN);
-
- return $res;
+ return Application_Common_Database::prepareAndExecute(
+ $sql,
+ [],
+ Application_Common_Database::COLUMN
+ );
}
/**
* Convert a time string in the format "YYYY-MM-DD HH:mm:SS"
* to "YYYY-MM-DD-HH-mm-SS".
*
- * @param string $p_time
+ * @param string $p_time
+ *
* @return string
*/
private static function AirtimeTimeToPypoTime($p_time)
{
$p_time = substr($p_time, 0, 19);
- $p_time = str_replace(" ", "-", $p_time);
- $p_time = str_replace(":", "-", $p_time);
+ $p_time = str_replace(' ', '-', $p_time);
- return $p_time;
+ return str_replace(':', '-', $p_time);
}
/**
* Convert a time string in the format "YYYY-MM-DD-HH-mm-SS" to
* "YYYY-MM-DD HH:mm:SS".
*
- * @param string $p_time
+ * @param string $p_time
+ *
* @return string
*/
private static function PypoTimeToAirtimeTime($p_time)
{
- $t = explode("-", $p_time);
+ $t = explode('-', $p_time);
- return $t[0]."-".$t[1]."-".$t[2]." ".$t[3].":".$t[4].":00";
+ return $t[0] . '-' . $t[1] . '-' . $t[2] . ' ' . $t[3] . ':' . $t[4] . ':00';
}
/**
- * Return true if the input string is in the format YYYY-MM-DD-HH-mm
+ * Return true if the input string is in the format YYYY-MM-DD-HH-mm.
*
- * @param string $p_time
- * @return boolean
+ * @param string $p_time
+ *
+ * @return bool
*/
public static function ValidPypoTimeFormat($p_time)
{
- $t = explode("-", $p_time);
+ $t = explode('-', $p_time);
if (count($t) != 5) {
return false;
}
@@ -696,25 +710,25 @@ SQL;
* Converts a time value as a string (with format HH:MM:SS.mmmmmm) to
* millisecs.
*
- * @param string $p_time
+ * @param string $p_time
+ *
* @return int
*/
public static function WallTimeToMillisecs($p_time)
{
- $t = explode(":", $p_time);
+ $t = explode(':', $p_time);
$millisecs = 0;
- if (strpos($t[2], ".")) {
- $secParts = explode(".", $t[2]);
+ if (strpos($t[2], '.')) {
+ $secParts = explode('.', $t[2]);
$millisecs = $secParts[1];
- $millisecs = str_pad(substr($millisecs, 0, 3),3, '0');
+ $millisecs = str_pad(substr($millisecs, 0, 3), 3, '0');
$millisecs = intval($millisecs);
$seconds = intval($secParts[0]);
} else {
$seconds = intval($t[2]);
}
- $ret = $millisecs + ($seconds * 1000) + ($t[1] * 60 * 1000) + ($t[0] * 60 * 60 * 1000);
- return $ret;
+ return $millisecs + ($seconds * 1000) + ($t[1] * 60 * 1000) + ($t[0] * 60 * 60 * 1000);
}
/**
@@ -724,18 +738,18 @@ SQL;
* do not have to be entirely within this range. It is enough that the end
* or beginning of the scheduled item is in the range.
*
- *
* @param string $p_startTime
- * In the format YYYY-MM-DD HH:MM:SS.nnnnnn
+ * In the format YYYY-MM-DD HH:MM:SS.nnnnnn
* @param string $p_endTime
- * In the format YYYY-MM-DD HH:MM:SS.nnnnnn
+ * In the format YYYY-MM-DD HH:MM:SS.nnnnnn
+ *
* @return array
- * Returns null if nothing found, else an array of associative
- * arrays representing each row.
+ * Returns null if nothing found, else an array of associative
+ * arrays representing each row
*/
public static function getItems($p_startTime, $p_endTime)
{
- $baseQuery = << :startTime1
AND st.starts < :endTime
AND st.playout_status > 0
@@ -767,19 +781,19 @@ WHERE st.ends > :startTime1
ORDER BY st.starts
SQL;
- $sql = $baseQuery." ".$predicates;
+ $sql = $baseQuery . ' ' . $predicates;
- $rows = Application_Common_Database::prepareAndExecute($sql, array(
+ $rows = Application_Common_Database::prepareAndExecute($sql, [
':startTime1' => $p_startTime,
- ':endTime' => $p_endTime,
- ':startTime2' => $p_startTime));
+ ':endTime' => $p_endTime,
+ ':startTime2' => $p_startTime, ]);
if (count($rows) < 3) {
- $dt = new DateTime("@".time());
- $dt->add(new DateInterval("PT24H"));
+ $dt = new DateTime('@' . time());
+ $dt->add(new DateInterval('PT24H'));
$range_end = $dt->format(DEFAULT_TIMESTAMP_FORMAT);
- $predicates = << :startTime1
AND st.starts < :rangeEnd
AND st.playout_status > 0
@@ -788,12 +802,14 @@ WHERE st.ends > :startTime1
ORDER BY st.starts LIMIT 3
SQL;
- $sql = $baseQuery." ".$predicates." ";
- $rows = Application_Common_Database::prepareAndExecute($sql,
- array(
+ $sql = $baseQuery . ' ' . $predicates . ' ';
+ $rows = Application_Common_Database::prepareAndExecute(
+ $sql,
+ [
':startTime1' => $p_startTime,
- ':rangeEnd' => $range_end,
- ':startTime2' => $p_startTime));
+ ':rangeEnd' => $range_end,
+ ':startTime2' => $p_startTime, ]
+ );
}
return $rows;
@@ -802,103 +818,106 @@ SQL;
/**
* This function will ensure that an existing index in the
* associative array is never overwritten, instead appending
- * _0, _1, _2, ... to the end of the key to make sure it is unique
+ * _0, _1, _2, ... to the end of the key to make sure it is unique.
+ *
+ * @param mixed $data
+ * @param mixed $time
+ * @param mixed $item
*/
private static function appendScheduleItem(&$data, $time, $item)
{
$key = $time;
$i = 0;
- while (array_key_exists($key, $data["media"])) {
+ while (array_key_exists($key, $data['media'])) {
$key = "{$time}_{$i}";
- $i++;
+ ++$i;
}
- $data["media"][$key] = $item;
+ $data['media'][$key] = $item;
}
private static function createInputHarborKickTimes(&$data, $range_start, $range_end)
{
- $utcTimeZone = new DateTimeZone("UTC");
+ $utcTimeZone = new DateTimeZone('UTC');
$kick_times = Application_Model_ShowInstance::GetEndTimeOfNextShowWithLiveDJ($range_start, $range_end);
foreach ($kick_times as $kick_time_info) {
$kick_time = $kick_time_info['ends'];
$temp = explode('.', Application_Model_Preference::GetDefaultTransitionFade());
// we round down transition time since PHP cannot handle millisecond. We need to
// handle this better in the future
- $transition_time = intval($temp[0]);
+ $transition_time = intval($temp[0]);
$switchOffDataTime = new DateTime($kick_time, $utcTimeZone);
- $switch_off_time = $switchOffDataTime->sub(new DateInterval('PT'.$transition_time.'S'));
- $switch_off_time = $switch_off_time->format(DEFAULT_TIMESTAMP_FORMAT);
+ $switch_off_time = $switchOffDataTime->sub(new DateInterval('PT' . $transition_time . 'S'));
+ $switch_off_time = $switch_off_time->format(DEFAULT_TIMESTAMP_FORMAT);
$kick_start = self::AirtimeTimeToPypoTime($kick_time);
- $data["media"][$kick_start]['start'] = $kick_start;
- $data["media"][$kick_start]['end'] = $kick_start;
- $data["media"][$kick_start]['event_type'] = "kick_out";
- $data["media"][$kick_start]['type'] = "event";
- $data["media"][$kick_start]['independent_event'] = true;
+ $data['media'][$kick_start]['start'] = $kick_start;
+ $data['media'][$kick_start]['end'] = $kick_start;
+ $data['media'][$kick_start]['event_type'] = 'kick_out';
+ $data['media'][$kick_start]['type'] = 'event';
+ $data['media'][$kick_start]['independent_event'] = true;
if ($kick_time !== $switch_off_time) {
$switch_start = self::AirtimeTimeToPypoTime($switch_off_time);
- $data["media"][$switch_start]['start'] = $switch_start;
- $data["media"][$switch_start]['end'] = $switch_start;
- $data["media"][$switch_start]['event_type'] = "switch_off";
- $data["media"][$switch_start]['type'] = "event";
- $data["media"][$switch_start]['independent_event'] = true;
+ $data['media'][$switch_start]['start'] = $switch_start;
+ $data['media'][$switch_start]['end'] = $switch_start;
+ $data['media'][$switch_start]['event_type'] = 'switch_off';
+ $data['media'][$switch_start]['type'] = 'event';
+ $data['media'][$switch_start]['independent_event'] = true;
}
}
}
/**
- *
* Appends schedule "events" to an array of schedule events that gets
* sent to PYPO. Each schedule event contains information PYPO and
* Liquidsoap need for playout.
- *
- * @param Array $data array to be filled with schedule info - $item(s)
- * @param Array $item schedule info about one track
- * @param Integer $media_id scheduled item's cc_files id
- * @param String $uri path to the scheduled item's physical location
- * @param Integer $filsize The file's file size in bytes
- *
+ *
+ * @param array $data array to be filled with schedule info - $item(s)
+ * @param array $item schedule info about one track
+ * @param int $media_id scheduled item's cc_files id
+ * @param string $uri path to the scheduled item's physical location
+ * @param int $filsize The file's file size in bytes
+ * @param mixed $filesize
*/
private static function createFileScheduleEvent(&$data, $item, $media_id, $uri, $filesize)
{
- $start = self::AirtimeTimeToPypoTime($item["start"]);
- $end = self::AirtimeTimeToPypoTime($item["end"]);
+ $start = self::AirtimeTimeToPypoTime($item['start']);
+ $end = self::AirtimeTimeToPypoTime($item['end']);
- list(,,,$start_hour,,) = explode("-", $start);
- list(,,,$end_hour,,) = explode("-", $end);
+ list(, , , $start_hour) = explode('-', $start);
+ list(, , , $end_hour) = explode('-', $end);
$same_hour = $start_hour == $end_hour;
$independent_event = !$same_hour;
- $replay_gain = is_null($item["replay_gain"]) ? "0": $item["replay_gain"];
+ $replay_gain = is_null($item['replay_gain']) ? '0' : $item['replay_gain'];
$replay_gain += Application_Model_Preference::getReplayGainModifier();
- if (!Application_Model_Preference::GetEnableReplayGain() ) {
+ if (!Application_Model_Preference::GetEnableReplayGain()) {
$replay_gain = 0;
}
$fileMetadata = CcFiles::sanitizeResponse(CcFilesQuery::create()->findPk($media_id));
-
- $schedule_item = array(
- 'id' => $media_id,
- 'type' => 'file',
- 'metadata' => $fileMetadata,
- 'row_id' => $item["id"],
- 'uri' => $uri,
- 'fade_in' => Application_Model_Schedule::WallTimeToMillisecs($item["fade_in"]),
- 'fade_out' => Application_Model_Schedule::WallTimeToMillisecs($item["fade_out"]),
- 'cue_in' => Application_Common_DateHelper::CalculateLengthInSeconds($item["cue_in"]),
- 'cue_out' => Application_Common_DateHelper::CalculateLengthInSeconds($item["cue_out"]),
- 'start' => $start,
- 'end' => $end,
- 'show_name' => $item["show_name"],
- 'replay_gain' => $replay_gain,
+
+ $schedule_item = [
+ 'id' => $media_id,
+ 'type' => 'file',
+ 'metadata' => $fileMetadata,
+ 'row_id' => $item['id'],
+ 'uri' => $uri,
+ 'fade_in' => Application_Model_Schedule::WallTimeToMillisecs($item['fade_in']),
+ 'fade_out' => Application_Model_Schedule::WallTimeToMillisecs($item['fade_out']),
+ 'cue_in' => Application_Common_DateHelper::CalculateLengthInSeconds($item['cue_in']),
+ 'cue_out' => Application_Common_DateHelper::CalculateLengthInSeconds($item['cue_out']),
+ 'start' => $start,
+ 'end' => $end,
+ 'show_name' => $item['show_name'],
+ 'replay_gain' => $replay_gain,
'independent_event' => $independent_event,
- 'filesize' => $filesize,
- );
+ 'filesize' => $filesize,
+ ];
if ($schedule_item['cue_in'] > $schedule_item['cue_out']) {
$schedule_item['cue_in'] = $schedule_item['cue_out'];
@@ -908,62 +927,62 @@ SQL;
private static function createStreamScheduleEvent(&$data, $item, $media_id, $uri)
{
- $start = self::AirtimeTimeToPypoTime($item["start"]);
- $end = self::AirtimeTimeToPypoTime($item["end"]);
+ $start = self::AirtimeTimeToPypoTime($item['start']);
+ $end = self::AirtimeTimeToPypoTime($item['end']);
//create an event to start stream buffering 5 seconds ahead of the streams actual time.
- $buffer_start = new DateTime($item["start"], new DateTimeZone('UTC'));
- $buffer_start->sub(new DateInterval("PT5S"));
+ $buffer_start = new DateTime($item['start'], new DateTimeZone('UTC'));
+ $buffer_start->sub(new DateInterval('PT5S'));
$stream_buffer_start = self::AirtimeTimeToPypoTime($buffer_start->format(DEFAULT_TIMESTAMP_FORMAT));
- $schedule_item = array(
- 'start' => $stream_buffer_start,
- 'end' => $stream_buffer_start,
- 'uri' => $uri,
- 'row_id' => $item["id"],
- 'type' => 'stream_buffer_start',
- 'independent_event' => true
- );
+ $schedule_item = [
+ 'start' => $stream_buffer_start,
+ 'end' => $stream_buffer_start,
+ 'uri' => $uri,
+ 'row_id' => $item['id'],
+ 'type' => 'stream_buffer_start',
+ 'independent_event' => true,
+ ];
self::appendScheduleItem($data, $start, $schedule_item);
- $schedule_item = array(
- 'id' => $media_id,
- 'type' => 'stream_output_start',
- 'row_id' => $item["id"],
- 'uri' => $uri,
- 'start' => $start,
- 'end' => $end,
- 'show_name' => $item["show_name"],
- 'independent_event' => true
- );
+ $schedule_item = [
+ 'id' => $media_id,
+ 'type' => 'stream_output_start',
+ 'row_id' => $item['id'],
+ 'uri' => $uri,
+ 'start' => $start,
+ 'end' => $end,
+ 'show_name' => $item['show_name'],
+ 'independent_event' => true,
+ ];
self::appendScheduleItem($data, $start, $schedule_item);
//since a stream never ends we have to insert an additional "kick stream" event. The "start"
//time of this event is the "end" time of the stream minus 1 second.
- $dt = new DateTime($item["end"], new DateTimeZone('UTC'));
- $dt->sub(new DateInterval("PT1S"));
+ $dt = new DateTime($item['end'], new DateTimeZone('UTC'));
+ $dt->sub(new DateInterval('PT1S'));
$stream_end = self::AirtimeTimeToPypoTime($dt->format(DEFAULT_TIMESTAMP_FORMAT));
- $schedule_item = array(
- 'start' => $stream_end,
- 'end' => $stream_end,
- 'uri' => $uri,
- 'type' => 'stream_buffer_end',
- 'row_id' => $item["id"],
- 'independent_event' => true
- );
+ $schedule_item = [
+ 'start' => $stream_end,
+ 'end' => $stream_end,
+ 'uri' => $uri,
+ 'type' => 'stream_buffer_end',
+ 'row_id' => $item['id'],
+ 'independent_event' => true,
+ ];
self::appendScheduleItem($data, $stream_end, $schedule_item);
- $schedule_item = array(
- 'start' => $stream_end,
- 'end' => $stream_end,
- 'uri' => $uri,
- 'type' => 'stream_output_end',
- 'independent_event' => true
- );
+ $schedule_item = [
+ 'start' => $stream_end,
+ 'end' => $stream_end,
+ 'uri' => $uri,
+ 'type' => 'stream_output_end',
+ 'independent_event' => true,
+ ];
self::appendScheduleItem($data, $stream_end, $schedule_item);
}
@@ -976,15 +995,15 @@ SQL;
/* if $p_fromDateTime and $p_toDateTime function parameters are null,
then set range * from "now" to "now + 24 hours". */
if (is_null($p_fromDateTime)) {
- $t1 = new DateTime("@".time(), $utcTimeZone);
+ $t1 = new DateTime('@' . time(), $utcTimeZone);
$range_start = $t1->format(DEFAULT_TIMESTAMP_FORMAT);
} else {
$range_start = Application_Model_Schedule::PypoTimeToAirtimeTime($p_fromDateTime);
}
if (is_null($p_fromDateTime)) {
- $t2 = new DateTime("@".time(), $utcTimeZone);
+ $t2 = new DateTime('@' . time(), $utcTimeZone);
- $cache_ahead_hours = $CC_CONFIG["cache_ahead_hours"];
+ $cache_ahead_hours = $CC_CONFIG['cache_ahead_hours'];
if (is_numeric($cache_ahead_hours)) {
//make sure we are not dealing with a float
@@ -993,26 +1012,25 @@ SQL;
$cache_ahead_hours = 1;
}
- $t2->add(new DateInterval("PT".$cache_ahead_hours."H"));
+ $t2->add(new DateInterval('PT' . $cache_ahead_hours . 'H'));
$range_end = $t2->format(DEFAULT_TIMESTAMP_FORMAT);
} else {
$range_end = Application_Model_Schedule::PypoTimeToAirtimeTime($p_toDateTime);
}
- return array($range_start, $range_end);
+ return [$range_start, $range_end];
}
-
private static function createScheduledEvents(&$data, $range_start, $range_end)
{
- $utcTimeZone = new DateTimeZone("UTC");
+ $utcTimeZone = new DateTimeZone('UTC');
$items = self::getItems($range_start, $range_end);
foreach ($items as $item) {
- $showEndDateTime = new DateTime($item["show_end"], $utcTimeZone);
+ $showEndDateTime = new DateTime($item['show_end'], $utcTimeZone);
- $trackStartDateTime = new DateTime($item["start"], $utcTimeZone);
- $trackEndDateTime = new DateTime($item["end"], $utcTimeZone);
+ $trackStartDateTime = new DateTime($item['start'], $utcTimeZone);
+ $trackEndDateTime = new DateTime($item['end'], $utcTimeZone);
if ($trackStartDateTime->getTimestamp() > $showEndDateTime->getTimestamp()) {
//do not send any tracks that start past their show's end time
@@ -1022,8 +1040,8 @@ SQL;
if ($trackEndDateTime->getTimestamp() > $showEndDateTime->getTimestamp()) {
$di = $trackStartDateTime->diff($showEndDateTime);
- $item["cue_out"] = $di->format("%H:%i:%s").".000";
- $item["end"] = $showEndDateTime->format(DEFAULT_TIMESTAMP_FORMAT);
+ $item['cue_out'] = $di->format('%H:%i:%s') . '.000';
+ $item['end'] = $showEndDateTime->format(DEFAULT_TIMESTAMP_FORMAT);
}
if (!is_null($item['file_id'])) {
@@ -1033,37 +1051,34 @@ SQL;
$file = $storedFile->getPropelOrm();
//Even local files are downloaded through the REST API in case we need to transform
//their filenames (eg. in the case of a bad file extension, because Liquidsoap won't play them)
- $uri = Application_Common_HTTPHelper::getStationUrl() . "rest/media/" . $media_id;
+ $uri = Application_Common_HTTPHelper::getStationUrl() . 'rest/media/' . $media_id;
//$uri = $file->getAbsoluteFilePath();
-
+
$filesize = $file->getFileSize();
self::createFileScheduleEvent($data, $item, $media_id, $uri, $filesize);
- }
-
- elseif (!is_null($item['stream_id'])) {
+ } elseif (!is_null($item['stream_id'])) {
//row is type "webstream"
$media_id = $item['stream_id'];
$uri = $item['url'];
self::createStreamScheduleEvent($data, $item, $media_id, $uri);
}
- else {
- //throw new Exception("Unknown schedule type: ".print_r($item, true));
+
+ //throw new Exception("Unknown schedule type: ".print_r($item, true));
//It's currently possible (and normal) to get cc_schedule rows without
//a file_id or stream_id. If you're using linked shows, placeholder rows can be put
//in the schedule when you cancel a track or delete stuff, so we should not throw an exception
//here and instead just ignore it.
- }
-
}
}
- /* Check if two events are less than or equal to 1 second apart
- */
- public static function areEventsLinked($event1, $event2) {
- $dt1 = DateTime::createFromFormat("Y-m-d-H-i-s", $event1['start']);
- $dt2 = DateTime::createFromFormat("Y-m-d-H-i-s", $event2['start']);
+ // Check if two events are less than or equal to 1 second apart
+ public static function areEventsLinked($event1, $event2)
+ {
+ $dt1 = DateTime::createFromFormat('Y-m-d-H-i-s', $event1['start']);
+ $dt2 = DateTime::createFromFormat('Y-m-d-H-i-s', $event2['start']);
$seconds = $dt2->getTimestamp() - $dt1->getTimestamp();
+
return $seconds <= 1;
}
@@ -1082,6 +1097,8 @@ SQL;
* There's a special case here is well. When the back-to-back streams are the same, we
* can collapse the instructions 1,2,(3,4,1,2),3,4 to 1,2,3,4. We basically cut out the
* middle part. This function handles this.
+ *
+ * @param mixed $data
*/
private static function foldData(&$data)
{
@@ -1092,15 +1109,12 @@ SQL;
$previous_previous_previous_key = null;
$previous_previous_previous_val = null;
foreach ($data as $k => $v) {
-
- if ($v["type"] == "stream_output_start"
+ if ($v['type'] == 'stream_output_start'
&& !is_null($previous_previous_val)
- && $previous_previous_val["type"] == "stream_output_end"
+ && $previous_previous_val['type'] == 'stream_output_end'
&& self::areEventsLinked($previous_previous_val, $v)) {
+ unset($data[$previous_previous_previous_key], $data[$previous_previous_key], $data[$previous_key]);
- unset($data[$previous_previous_previous_key]);
- unset($data[$previous_previous_key]);
- unset($data[$previous_key]);
if ($previous_previous_val['uri'] == $v['uri']) {
unset($data[$k]);
}
@@ -1121,14 +1135,14 @@ SQL;
//for days beyond the shows_populated_until value in cc_pref
$needScheduleUntil = $p_toDateTime;
if (is_null($needScheduleUntil)) {
- $needScheduleUntil = new DateTime("now", new DateTimeZone("UTC"));
- $needScheduleUntil->add(new DateInterval("P1D"));
+ $needScheduleUntil = new DateTime('now', new DateTimeZone('UTC'));
+ $needScheduleUntil->add(new DateInterval('P1D'));
}
Application_Model_Show::createAndFillShowInstancesPastPopulatedUntilDate($needScheduleUntil);
list($range_start, $range_end) = self::getRangeStartAndEnd($p_fromDateTime, $p_toDateTime);
- $data = array();
- $data["media"] = array();
+ $data = [];
+ $data['media'] = [];
//Harbor kick times *MUST* be ahead of schedule events, so that pypo
//executes them first.
@@ -1141,30 +1155,39 @@ SQL;
public static function deleteAll()
{
- $sql = "TRUNCATE TABLE cc_schedule";
- Application_Common_Database::prepareAndExecute($sql, array(),
- Application_Common_Database::EXECUTE);
+ $sql = 'TRUNCATE TABLE cc_schedule';
+ Application_Common_Database::prepareAndExecute(
+ $sql,
+ [],
+ Application_Common_Database::EXECUTE
+ );
}
public static function deleteWithFileId($fileId)
{
- $sql = "DELETE FROM cc_schedule WHERE file_id=:file_id";
- Application_Common_Database::prepareAndExecute($sql, array(':file_id'=>$fileId), 'execute');
+ $sql = 'DELETE FROM cc_schedule WHERE file_id=:file_id';
+ Application_Common_Database::prepareAndExecute($sql, [':file_id' => $fileId], 'execute');
}
- public static function checkOverlappingShows($show_start, $show_end,
- $update=false, $instanceId=null, $showId=null)
- {
+ public static function checkOverlappingShows(
+ $show_start,
+ $show_end,
+ $update = false,
+ $instanceId = null,
+ $showId = null
+ ) {
//if the show instance does not exist or was deleted, return false
if (!is_null($showId)) {
$ccShowInstance = CcShowInstancesQuery::create()
->filterByDbShowId($showId)
->filterByDbStarts($show_start->format(DEFAULT_TIMESTAMP_FORMAT))
- ->findOne();
+ ->findOne()
+ ;
} elseif (!is_null($instanceId)) {
$ccShowInstance = CcShowInstancesQuery::create()
->filterByDbId($instanceId)
- ->findOne();
+ ->findOne()
+ ;
}
if ($update && ($ccShowInstance && $ccShowInstance->getDbModifiedInstance() == true)) {
return false;
@@ -1172,19 +1195,18 @@ SQL;
$overlapping = false;
- $params = array(
- ':show_end1' => $show_end->format(DEFAULT_TIMESTAMP_FORMAT),
- ':show_end2' => $show_end->format(DEFAULT_TIMESTAMP_FORMAT),
- ':show_end3' => $show_end->format(DEFAULT_TIMESTAMP_FORMAT)
- );
-
+ $params = [
+ ':show_end1' => $show_end->format(DEFAULT_TIMESTAMP_FORMAT),
+ ':show_end2' => $show_end->format(DEFAULT_TIMESTAMP_FORMAT),
+ ':show_end3' => $show_end->format(DEFAULT_TIMESTAMP_FORMAT),
+ ];
/* If a show is being edited, exclude it from the query
* In both cases (new and edit) we only grab shows that
* are scheduled 2 days prior
*/
if ($update) {
- $sql = << $show_end->format(DEFAULT_TIMESTAMP_FORMAT),
':show_end2' => $show_end->format(DEFAULT_TIMESTAMP_FORMAT),
- ':show_end3' => $show_end->format(DEFAULT_TIMESTAMP_FORMAT)), 'all');
+ ':show_end3' => $show_end->format(DEFAULT_TIMESTAMP_FORMAT), ], 'all');
}
foreach ($rows as $row) {
- $start = new DateTime($row["starts"], new DateTimeZone('UTC'));
- $end = new DateTime($row["ends"], new DateTimeZone('UTC'));
+ $start = new DateTime($row['starts'], new DateTimeZone('UTC'));
+ $end = new DateTime($row['ends'], new DateTimeZone('UTC'));
- if ($show_start->getTimestamp() < $end->getTimestamp() &&
- $show_end->getTimestamp() > $start->getTimestamp()) {
+ if ($show_start->getTimestamp() < $end->getTimestamp()
+ && $show_end->getTimestamp() > $start->getTimestamp()) {
$overlapping = true;
+
break;
}
}
@@ -1241,13 +1264,14 @@ SQL;
return $overlapping;
}
- public static function GetType($p_scheduleId){
+ public static function GetType($p_scheduleId)
+ {
$scheduledItem = CcScheduleQuery::create()->findPK($p_scheduleId);
if ($scheduledItem->getDbFileId() == null) {
return 'webstream';
- } else {
- return 'file';
}
+
+ return 'file';
}
public static function GetFileId($p_scheduleId)
diff --git a/legacy/application/models/Scheduler.php b/legacy/application/models/Scheduler.php
index 5dcb733dc..759996271 100644
--- a/legacy/application/models/Scheduler.php
+++ b/legacy/application/models/Scheduler.php
@@ -3,16 +3,16 @@
final class Application_Model_Scheduler
{
private $con;
- private $fileInfo = array(
- "id" => "",
- "cliplength" => "",
- "cuein" => "00:00:00",
- "cueout" => "00:00:00",
- "fadein" => "00:00:00",
- "fadeout" => "00:00:00",
- "sched_id" => null,
- "type" => 0 //default type of '0' to represent files. type '1' represents a webstream
- );
+ private $fileInfo = [
+ 'id' => '',
+ 'cliplength' => '',
+ 'cuein' => '00:00:00',
+ 'cueout' => '00:00:00',
+ 'fadein' => '00:00:00',
+ 'fadeout' => '00:00:00',
+ 'sched_id' => null,
+ 'type' => 0, //default type of '0' to represent files. type '1' represents a webstream
+ ];
private $epochNow;
private $nowDT;
@@ -23,7 +23,7 @@ final class Application_Model_Scheduler
private $checkUserPermissions = true;
- public function __construct($checkUserPermissions=true)
+ public function __construct($checkUserPermissions = true)
{
$this->con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME);
@@ -31,13 +31,13 @@ final class Application_Model_Scheduler
//to epochNow and then send the new schedule to pypo. Sometimes the currently cancelled
//track can still be included in the new schedule because it may have a few ms left to play.
//subtracting 1 second from epochNow resolves this issue.
- $this->epochNow = microtime(true)-1;
- $this->nowDT = DateTime::createFromFormat("U.u", $this->epochNow, new DateTimeZone("UTC"));
+ $this->epochNow = microtime(true) - 1;
+ $this->nowDT = DateTime::createFromFormat('U.u', $this->epochNow, new DateTimeZone('UTC'));
if ($this->nowDT === false) {
// DateTime::createFromFormat does not support millisecond string formatting in PHP 5.3.2 (Ubuntu 10.04).
// In PHP 5.3.3 (Ubuntu 10.10), this has been fixed.
- $this->nowDT = DateTime::createFromFormat("U", time(), new DateTimeZone("UTC"));
+ $this->nowDT = DateTime::createFromFormat('U', time(), new DateTimeZone('UTC'));
}
$this->setCheckUserPermissions($checkUserPermissions);
@@ -56,25 +56,29 @@ final class Application_Model_Scheduler
private function validateItemMove($itemsToMove, $destination)
{
- $destinationInstanceId = $destination["instance"];
+ $destinationInstanceId = $destination['instance'];
$destinationCcShowInstance = CcShowInstancesQuery::create()
- ->findPk($destinationInstanceId);
+ ->findPk($destinationInstanceId)
+ ;
$isDestinationLinked = $destinationCcShowInstance->getCcShow()->isLinked();
foreach ($itemsToMove as $itemToMove) {
- $sourceInstanceId = $itemToMove["instance"];
+ $sourceInstanceId = $itemToMove['instance'];
$ccShowInstance = CcShowInstancesQuery::create()
- ->findPk($sourceInstanceId);
+ ->findPk($sourceInstanceId)
+ ;
//does the item being moved belong to a linked show
$isSourceLinked = $ccShowInstance->getCcShow()->isLinked();
if ($isDestinationLinked && !$isSourceLinked) {
- throw new Exception("Cannot move items into linked shows");
- } elseif (!$isDestinationLinked && $isSourceLinked) {
- throw new Exception("Cannot move items out of linked shows");
- } elseif ($isSourceLinked && $sourceInstanceId != $destinationInstanceId) {
- throw new Exception(_("Cannot move items out of linked shows"));
+ throw new Exception('Cannot move items into linked shows');
+ }
+ if (!$isDestinationLinked && $isSourceLinked) {
+ throw new Exception('Cannot move items out of linked shows');
+ }
+ if ($isSourceLinked && $sourceInstanceId != $destinationInstanceId) {
+ throw new Exception(_('Cannot move items out of linked shows'));
}
}
}
@@ -84,33 +88,33 @@ final class Application_Model_Scheduler
*
* @param array $items, an array containing pks of cc_schedule items.
*/
- private function validateRequest($items, $addRemoveAction=false, $cancelShow=false)
+ private function validateRequest($items, $addRemoveAction = false, $cancelShow = false)
{
//$items is where tracks get inserted (they are schedule locations)
- $nowEpoch = floatval($this->nowDT->format("U.u"));
+ $nowEpoch = floatval($this->nowDT->format('U.u'));
- $schedInfo = array();
- $instanceInfo = array();
+ $schedInfo = [];
+ $instanceInfo = [];
- for ($i = 0; $i < count($items); $i++) {
- $id = $items[$i]["id"];
+ for ($i = 0; $i < count($items); ++$i) {
+ $id = $items[$i]['id'];
//could be added to the beginning of a show, which sends id = 0;
if ($id > 0) {
//schedule_id of where we are inserting after?
- $schedInfo[$id] = $items[$i]["instance"];
+ $schedInfo[$id] = $items[$i]['instance'];
}
//format is instance_id => timestamp
- $instanceInfo[$items[$i]["instance"]] = $items[$i]["timestamp"];
+ $instanceInfo[$items[$i]['instance']] = $items[$i]['timestamp'];
}
if (count($instanceInfo) === 0) {
- throw new Exception("Invalid Request.");
+ throw new Exception('Invalid Request.');
}
- $schedIds = array();
+ $schedIds = [];
if (count($schedInfo) > 0) {
$schedIds = array_keys($schedInfo);
}
@@ -137,31 +141,30 @@ final class Application_Model_Scheduler
}
}
-
foreach ($showInstances as $instance) {
-
$id = $instance->getDbId();
$show = $instance->getCcShow($this->con);
if ($this->checkUserPermissions && $this->user->canSchedule($show->getDbId()) === false) {
- throw new Exception(sprintf(_("You are not allowed to schedule show %s."), $show->getDbName()));
+ throw new Exception(sprintf(_('You are not allowed to schedule show %s.'), $show->getDbName()));
}
if ($instance->getDbRecord()) {
- throw new Exception(_("You cannot add files to recording shows."));
+ throw new Exception(_('You cannot add files to recording shows.'));
}
- $showEndEpoch = floatval($instance->getDbEnds("U.u"));
+ $showEndEpoch = floatval($instance->getDbEnds('U.u'));
if ($showEndEpoch < $nowEpoch) {
- throw new OutDatedScheduleException(sprintf(_("The show %s is over and cannot be scheduled."), $show->getDbName()));
+ throw new OutDatedScheduleException(sprintf(_('The show %s is over and cannot be scheduled.'), $show->getDbName()));
}
$ts = intval($instanceInfo[$id]);
- $lastSchedTs = intval($instance->getDbLastScheduled("U")) ? : 0;
+ $lastSchedTs = intval($instance->getDbLastScheduled('U')) ?: 0;
if ($ts < $lastSchedTs) {
Logging::info("ts {$ts} last sched {$lastSchedTs}");
- throw new OutDatedScheduleException(sprintf(_("The show %s has been previously updated!"), $show->getDbName()));
+
+ throw new OutDatedScheduleException(sprintf(_('The show %s has been previously updated!'), $show->getDbName()));
}
/*
@@ -179,30 +182,28 @@ final class Application_Model_Scheduler
$ccShowInstances = $ccShow->getCcShowInstancess();
$timeNowUTC = gmdate(DEFAULT_TIMESTAMP_FORMAT);
foreach ($ccShowInstances as $ccShowInstance) {
-
- if ($ccShowInstance->getDbStarts() <= $timeNowUTC &&
- $ccShowInstance->getDbEnds() > $timeNowUTC) {
- throw new Exception(_("Content in linked shows cannot be changed while on air!"));
+ if ($ccShowInstance->getDbStarts() <= $timeNowUTC
+ && $ccShowInstance->getDbEnds() > $timeNowUTC) {
+ throw new Exception(_('Content in linked shows cannot be changed while on air!'));
}
}
}
}
}
}
-
+
private function validateMediaItems($mediaItems)
{
- foreach ($mediaItems as $mediaItem)
- {
- $id = $mediaItem["id"];
- if ($mediaItem["type"] === "playlist")
- {
+ foreach ($mediaItems as $mediaItem) {
+ $id = $mediaItem['id'];
+ if ($mediaItem['type'] === 'playlist') {
$playlist = new Application_Model_Playlist($id, $this->con);
if ($playlist->containsMissingFiles()) {
- throw new Exception(_("Cannot schedule a playlist that contains missing files."));
+ throw new Exception(_('Cannot schedule a playlist that contains missing files.'));
}
}
}
+
return true;
}
@@ -219,67 +220,66 @@ final class Application_Model_Scheduler
$showInstance = new Application_Model_ShowInstance($show);
$showLimit = $showInstance->getSecondsRemaining();
- $files = array();
- if ($type === "audioclip") {
+ $files = [];
+ if ($type === 'audioclip') {
$file = CcFilesQuery::create()->findPK($id, $this->con);
if (is_null($file) || !$file->visible()) {
- throw new Exception(_("A selected File does not exist!"));
- } else {
- $data = $this->fileInfo;
- $data["id"] = $id;
-
- $cuein = Application_Common_DateHelper::playlistTimeToSeconds($file->getDbCuein());
- $cueout = Application_Common_DateHelper::playlistTimeToSeconds($file->getDbCueout());
- $row_length = Application_Common_DateHelper::secondsToPlaylistTime($cueout - $cuein);
-
- $data["cliplength"] = $row_length;
-
- $data["cuein"] = $file->getDbCuein();
- $data["cueout"] = $file->getDbCueout();
-
- //fade is in format SS.uuuuuu
- $data["fadein"] = Application_Model_Preference::GetDefaultFadeIn();
- $data["fadeout"] = Application_Model_Preference::GetDefaultFadeOut();
-
- $files[] = $data;
+ throw new Exception(_('A selected File does not exist!'));
}
- } elseif ($type === "playlist") {
+ $data = $this->fileInfo;
+ $data['id'] = $id;
+
+ $cuein = Application_Common_DateHelper::playlistTimeToSeconds($file->getDbCuein());
+ $cueout = Application_Common_DateHelper::playlistTimeToSeconds($file->getDbCueout());
+ $row_length = Application_Common_DateHelper::secondsToPlaylistTime($cueout - $cuein);
+
+ $data['cliplength'] = $row_length;
+
+ $data['cuein'] = $file->getDbCuein();
+ $data['cueout'] = $file->getDbCueout();
+
+ //fade is in format SS.uuuuuu
+ $data['fadein'] = Application_Model_Preference::GetDefaultFadeIn();
+ $data['fadeout'] = Application_Model_Preference::GetDefaultFadeOut();
+
+ $files[] = $data;
+ } elseif ($type === 'playlist') {
$pl = new Application_Model_Playlist($id);
$contents = $pl->getContents();
// because the time remaining is not updated until after the schedule inserts we need to track it for
// the entire add vs. querying on the smartblock level
foreach ($contents as $plItem) {
if ($plItem['type'] == 0) {
- $data["id"] = $plItem['item_id'];
- $data["cliplength"] = $plItem['length'];
- $data["cuein"] = $plItem['cuein'];
- $data["cueout"] = $plItem['cueout'];
- $data["fadein"] = $plItem['fadein'];
- $data["fadeout"] = $plItem['fadeout'];
- $data["type"] = 0;
+ $data['id'] = $plItem['item_id'];
+ $data['cliplength'] = $plItem['length'];
+ $data['cuein'] = $plItem['cuein'];
+ $data['cueout'] = $plItem['cueout'];
+ $data['fadein'] = $plItem['fadein'];
+ $data['fadeout'] = $plItem['fadeout'];
+ $data['type'] = 0;
$files[] = $data;
} elseif ($plItem['type'] == 1) {
- $data["id"] = $plItem['item_id'];
- $data["cliplength"] = $plItem['length'];
- $data["cuein"] = $plItem['cuein'];
- $data["cueout"] = $plItem['cueout'];
- $data["fadein"] = "00.500000";//$plItem['fadein'];
- $data["fadeout"] = "00.500000";//$plItem['fadeout'];
- $data["type"] = 1;
+ $data['id'] = $plItem['item_id'];
+ $data['cliplength'] = $plItem['length'];
+ $data['cuein'] = $plItem['cuein'];
+ $data['cueout'] = $plItem['cueout'];
+ $data['fadein'] = '00.500000'; //$plItem['fadein'];
+ $data['fadeout'] = '00.500000'; //$plItem['fadeout'];
+ $data['type'] = 1;
$files[] = $data;
} elseif ($plItem['type'] == 2) {
// if it's a block
$bl = new Application_Model_Block($plItem['item_id']);
if ($bl->isStatic()) {
foreach ($bl->getContents() as $track) {
- $data["id"] = $track['item_id'];
- $data["cliplength"] = $track['length'];
- $data["cuein"] = $track['cuein'];
- $data["cueout"] = $track['cueout'];
- $data["fadein"] = $track['fadein'];
- $data["fadeout"] = $track['fadeout'];
- $data["type"] = 0;
+ $data['id'] = $track['item_id'];
+ $data['cliplength'] = $track['length'];
+ $data['cuein'] = $track['cuein'];
+ $data['cueout'] = $track['cueout'];
+ $data['fadein'] = $track['fadein'];
+ $data['fadeout'] = $track['fadeout'];
+ $data['type'] = 0;
$files[] = $data;
}
} else {
@@ -290,19 +290,19 @@ final class Application_Model_Scheduler
$fileId = $f['id'];
$file = CcFilesQuery::create()->findPk($fileId);
if (isset($file) && $file->visible()) {
- $data["id"] = $file->getDbId();
- $data["cuein"] = $file->getDbCuein();
- $data["cueout"] = $file->getDbCueout();
+ $data['id'] = $file->getDbId();
+ $data['cuein'] = $file->getDbCuein();
+ $data['cueout'] = $file->getDbCueout();
- $cuein = Application_Common_DateHelper::calculateLengthInSeconds($data["cuein"]);
- $cueout = Application_Common_DateHelper::calculateLengthInSeconds($data["cueout"]);
- $data["cliplength"] = Application_Common_DateHelper::secondsToPlaylistTime($cueout - $cuein);
+ $cuein = Application_Common_DateHelper::calculateLengthInSeconds($data['cuein']);
+ $cueout = Application_Common_DateHelper::calculateLengthInSeconds($data['cueout']);
+ $data['cliplength'] = Application_Common_DateHelper::secondsToPlaylistTime($cueout - $cuein);
//fade is in format SS.uuuuuu
- $data["fadein"] = $defaultFadeIn;
- $data["fadeout"] = $defaultFadeOut;
+ $data['fadein'] = $defaultFadeIn;
+ $data['fadeout'] = $defaultFadeOut;
- $data["type"] = 0;
+ $data['type'] = 0;
$files[] = $data;
}
}
@@ -312,36 +312,35 @@ final class Application_Model_Scheduler
// since the schedule isn't updated until after this insert we need to keep tally
$showLimit -= $this->timeLengthOfFiles($files);
}
- } elseif ($type == "stream") {
+ } elseif ($type == 'stream') {
//need to return
- $stream = CcWebstreamQuery::create()->findPK($id, $this->con);
+ $stream = CcWebstreamQuery::create()->findPK($id, $this->con);
if (is_null($stream) /* || !$file->visible() */) {
- throw new Exception(_("A selected File does not exist!"));
- } else {
- $data = $this->fileInfo;
- $data["id"] = $id;
- $data["cliplength"] = $stream->getDbLength();
- $data["cueout"] = $stream->getDbLength();
- $data["type"] = 1;
-
- //fade is in format SS.uuuuuu
- $data["fadein"] = Application_Model_Preference::GetDefaultFadeIn();
- $data["fadeout"] = Application_Model_Preference::GetDefaultFadeOut();
-
- $files[] = $data;
+ throw new Exception(_('A selected File does not exist!'));
}
- } elseif ($type == "block") {
+ $data = $this->fileInfo;
+ $data['id'] = $id;
+ $data['cliplength'] = $stream->getDbLength();
+ $data['cueout'] = $stream->getDbLength();
+ $data['type'] = 1;
+
+ //fade is in format SS.uuuuuu
+ $data['fadein'] = Application_Model_Preference::GetDefaultFadeIn();
+ $data['fadeout'] = Application_Model_Preference::GetDefaultFadeOut();
+
+ $files[] = $data;
+ } elseif ($type == 'block') {
$bl = new Application_Model_Block($id);
if ($bl->isStatic()) {
foreach ($bl->getContents() as $track) {
- $data["id"] = $track['item_id'];
- $data["cliplength"] = $track['length'];
- $data["cuein"] = $track['cuein'];
- $data["cueout"] = $track['cueout'];
- $data["fadein"] = $track['fadein'];
- $data["fadeout"] = $track['fadeout'];
- $data["type"] = 0;
+ $data['id'] = $track['item_id'];
+ $data['cliplength'] = $track['length'];
+ $data['cuein'] = $track['cuein'];
+ $data['cueout'] = $track['cueout'];
+ $data['fadein'] = $track['fadein'];
+ $data['fadeout'] = $track['fadeout'];
+ $data['type'] = 0;
$files[] = $data;
}
} else {
@@ -352,19 +351,19 @@ final class Application_Model_Scheduler
$fileId = $f['id'];
$file = CcFilesQuery::create()->findPk($fileId);
if (isset($file) && $file->visible()) {
- $data["id"] = $file->getDbId();
- $data["cuein"] = $file->getDbCuein();
- $data["cueout"] = $file->getDbCueout();
+ $data['id'] = $file->getDbId();
+ $data['cuein'] = $file->getDbCuein();
+ $data['cueout'] = $file->getDbCueout();
- $cuein = Application_Common_DateHelper::calculateLengthInSeconds($data["cuein"]);
- $cueout = Application_Common_DateHelper::calculateLengthInSeconds($data["cueout"]);
- $data["cliplength"] = Application_Common_DateHelper::secondsToPlaylistTime($cueout - $cuein);
+ $cuein = Application_Common_DateHelper::calculateLengthInSeconds($data['cuein']);
+ $cueout = Application_Common_DateHelper::calculateLengthInSeconds($data['cueout']);
+ $data['cliplength'] = Application_Common_DateHelper::secondsToPlaylistTime($cueout - $cuein);
//fade is in format SS.uuuuuu
- $data["fadein"] = $defaultFadeIn;
- $data["fadeout"] = $defaultFadeOut;
+ $data['fadein'] = $defaultFadeIn;
+ $data['fadeout'] = $defaultFadeOut;
- $data["type"] = 0;
+ $data['type'] = 0;
$files[] = $data;
}
}
@@ -383,35 +382,36 @@ final class Application_Model_Scheduler
*/
private function findTimeDifference($p_startDT, $p_seconds)
{
- $startEpoch = $p_startDT->format("U.u");
-
- //add two float numbers to 6 subsecond precision
- //DateTime::createFromFormat("U.u") will have a problem if there is no decimal in the resulting number.
- $newEpoch = bcsub($startEpoch , (string) $p_seconds, 6);
-
- $dt = DateTime::createFromFormat("U.u", $newEpoch, new DateTimeZone("UTC"));
-
- if ($dt === false) {
- //PHP 5.3.2 problem
- $dt = DateTime::createFromFormat("U", intval($newEpoch), new DateTimeZone("UTC"));
- }
-
- return $dt;
- }
-
- private function findTimeDifference2($p_startDT, $p_endDT) {
- $startEpoch = $p_startDT->format("U.u");
- $endEpoch = $p_endDT->format("U.u");
+ $startEpoch = $p_startDT->format('U.u');
//add two float numbers to 6 subsecond precision
//DateTime::createFromFormat("U.u") will have a problem if there is no decimal in the resulting number.
- $newEpoch = bcsub($endEpoch, (string)$startEpoch, 6);
+ $newEpoch = bcsub($startEpoch, (string) $p_seconds, 6);
- $dt = DateTime::createFromFormat("U.u", $newEpoch, new DateTimeZone("UTC"));
+ $dt = DateTime::createFromFormat('U.u', $newEpoch, new DateTimeZone('UTC'));
if ($dt === false) {
//PHP 5.3.2 problem
- $dt = DateTime::createFromFormat("U", intval($newEpoch), new DateTimeZone("UTC"));
+ $dt = DateTime::createFromFormat('U', intval($newEpoch), new DateTimeZone('UTC'));
+ }
+
+ return $dt;
+ }
+
+ private function findTimeDifference2($p_startDT, $p_endDT)
+ {
+ $startEpoch = $p_startDT->format('U.u');
+ $endEpoch = $p_endDT->format('U.u');
+
+ //add two float numbers to 6 subsecond precision
+ //DateTime::createFromFormat("U.u") will have a problem if there is no decimal in the resulting number.
+ $newEpoch = bcsub($endEpoch, (string) $startEpoch, 6);
+
+ $dt = DateTime::createFromFormat('U.u', $newEpoch, new DateTimeZone('UTC'));
+
+ if ($dt === false) {
+ //PHP 5.3.2 problem
+ $dt = DateTime::createFromFormat('U', intval($newEpoch), new DateTimeZone('UTC'));
}
return $dt;
@@ -426,18 +426,18 @@ final class Application_Model_Scheduler
*/
private function findEndTime($p_startDT, $p_duration)
{
- $startEpoch = $p_startDT->format("U.u");
+ $startEpoch = $p_startDT->format('U.u');
$durationSeconds = Application_Common_DateHelper::playlistTimeToSeconds($p_duration);
//add two float numbers to 6 subsecond precision
//DateTime::createFromFormat("U.u") will have a problem if there is no decimal in the resulting number.
- $endEpoch = bcadd($startEpoch , (string) $durationSeconds, 6);
+ $endEpoch = bcadd($startEpoch, (string) $durationSeconds, 6);
- $dt = DateTime::createFromFormat("U.u", $endEpoch, new DateTimeZone("UTC"));
+ $dt = DateTime::createFromFormat('U.u', $endEpoch, new DateTimeZone('UTC'));
if ($dt === false) {
//PHP 5.3.2 problem
- $dt = DateTime::createFromFormat("U", intval($endEpoch), new DateTimeZone("UTC"));
+ $dt = DateTime::createFromFormat('U', intval($endEpoch), new DateTimeZone('UTC'));
}
return $dt;
@@ -447,17 +447,17 @@ final class Application_Model_Scheduler
{
// TODO: there is at least one case where this function creates a filler block with
// an incorrect length; should keep an eye on it
- $sEpoch = $DT->format("U.u");
+ $sEpoch = $DT->format('U.u');
$nEpoch = $this->epochNow;
//check for if the show has started.
- if (bccomp( $nEpoch , $sEpoch , 6) === 1) {
+ if (bccomp($nEpoch, $sEpoch, 6) === 1) {
$this->applyCrossfades = false;
//need some kind of placeholder for cc_schedule.
//playout_status will be -1.
$nextDT = $this->nowDT;
- $length = bcsub($nEpoch , $sEpoch , 6);
+ $length = bcsub($nEpoch, $sEpoch, 6);
$cliplength = Application_Common_DateHelper::secondsToPlaylistTime($length);
//fillers are for only storing a chunk of time space that has already passed.
@@ -469,7 +469,8 @@ final class Application_Model_Scheduler
->setDbCueOut('00:00:00')
->setDbPlayoutStatus(-1)
->setDbInstanceId($instanceId)
- ->save($this->con);
+ ->save($this->con)
+ ;
} else {
$nextDT = $DT;
}
@@ -484,7 +485,7 @@ final class Application_Model_Scheduler
*/
private function calculateCrossfades($instanceId)
{
- Logging::info("adjusting start, end times of scheduled items to account for crossfades show instance #".$instanceId);
+ Logging::info('adjusting start, end times of scheduled items to account for crossfades show instance #' . $instanceId);
$instance = CcShowInstancesQuery::create()->findPk($instanceId);
if (is_null($instance)) {
@@ -494,20 +495,23 @@ final class Application_Model_Scheduler
$schedule = CcScheduleQuery::create()
->filterByDbInstanceId($instanceId)
->orderByDbStarts()
- ->find($this->con);
+ ->find($this->con)
+ ;
- $now = new DateTime("now", new DateTimeZone("UTC"));
+ $now = new DateTime('now', new DateTimeZone('UTC'));
$itemStartDT = $instance->getDbStarts(null);
foreach ($schedule as $item) {
$itemEndDT = $this->findEndTime($itemStartDT, $item->getDbClipLength());
// If the track has already ended, don't change it.
if ($itemEndDT < $now) {
$itemStartDT = $itemEndDT;
+
continue;
}
$item->setDbStarts($itemStartDT)
->setDbEnds($itemEndDT)
- ->save($this->con);
+ ->save($this->con)
+ ;
$itemStartDT = $this->findTimeDifference($itemEndDT, $this->crossfadeDuration);
}
}
@@ -519,9 +523,9 @@ final class Application_Model_Scheduler
* This function squeezes all items of a show together so that
* there are no gaps between them.
*/
- public function removeGaps($showInstance, $exclude=null)
+ public function removeGaps($showInstance, $exclude = null)
{
- Logging::info("removing gaps from show instance #".$showInstance);
+ Logging::info('removing gaps from show instance #' . $showInstance);
$instance = CcShowInstancesQuery::create()->findPk($showInstance, $this->con);
if (is_null($instance)) {
@@ -532,20 +536,23 @@ final class Application_Model_Scheduler
->filterByDbInstanceId($showInstance)
->filterByDbId($exclude, Criteria::NOT_IN)
->orderByDbStarts()
- ->find($this->con);
+ ->find($this->con)
+ ;
- $now = new DateTime("now", new DateTimeZone("UTC"));
+ $now = new DateTime('now', new DateTimeZone('UTC'));
$itemStartDT = $instance->getDbStarts(null);
foreach ($schedule as $item) {
$itemEndDT = $this->findEndTime($itemStartDT, $item->getDbClipLength());
// If the track has already ended, don't change it.
if ($itemEndDT < $now) {
$itemStartDT = $itemEndDT;
+
continue;
}
$item->setDbStarts($itemStartDT)
- ->setDbEnds($itemEndDT);
+ ->setDbEnds($itemEndDT)
+ ;
$itemStartDT = $itemEndDT;
}
@@ -554,10 +561,13 @@ final class Application_Model_Scheduler
}
/** Temporary hack to copy the track cue in, out, and length from the cc_files table to fix
- * incorrect track lengths (RKTN-260)
+ * incorrect track lengths (RKTN-260).
+ *
+ * @param mixed $showInstance
+ * @param null|mixed $exclude
*/
- public function removeGaps2($showInstance, $exclude = null) {
-
+ public function removeGaps2($showInstance, $exclude = null)
+ {
$instance = CcShowInstancesQuery::create()->findPK($showInstance, $this->con);
if (is_null($instance)) {
throw new OutDatedScheduleException(_("The schedule you're viewing is out of date!"));
@@ -569,10 +579,10 @@ final class Application_Model_Scheduler
->filterByDbInstanceId($showInstance)
->filterByDbId($exclude, Criteria::NOT_IN)
->orderByDbStarts()
- ->find($this->con);
+ ->find($this->con)
+ ;
foreach ($schedule as $item) {
-
//START OF TIME RECALC HACK
//TODO: Copy the cue in, cue out, and track length from the cc_files table
@@ -598,7 +608,8 @@ final class Application_Model_Scheduler
$itemEndDT = $this->findEndTime($itemStartDT, $item->getDbClipLength());
$item->setDbStarts($itemStartDT)
->setDbEnds($itemEndDT)
- ->save($this->con);
+ ->save($this->con)
+ ;
$itemStartDT = $this->findTimeDifference($itemEndDT, $this->crossfadeDuration);
}
@@ -608,29 +619,31 @@ final class Application_Model_Scheduler
}
/**
- *
* Enter description here ...
+ *
* @param $scheduleItems
* cc_schedule items, where the items get inserted after
* @param $filesToInsert
* array of schedule item info, what gets inserted into cc_schedule
* @param $adjustSched
+ * @param mixed $mediaItems
+ * @param mixed $moveAction
*/
- private function insertAfter($scheduleItems, $mediaItems, $filesToInsert=null, $adjustSched=true, $moveAction=false)
+ private function insertAfter($scheduleItems, $mediaItems, $filesToInsert = null, $adjustSched = true, $moveAction = false)
{
try {
// temporary fix for CC-5665
set_time_limit(180);
- $affectedShowInstances = array();
+ $affectedShowInstances = [];
//dont want to recalculate times for moved items
//only moved items have a sched_id
- $excludeIds = array();
+ $excludeIds = [];
$startProfile = microtime(true);
- $temp = array();
+ $temp = [];
$instance = null;
/* Items in shows are ordered by position number. We need to know
@@ -645,7 +658,7 @@ final class Application_Model_Scheduler
//reset
$this->applyCrossfades = true;
- $id = intval($schedule["id"]);
+ $id = intval($schedule['id']);
/* Find out if the show where the cursor position (where an item will
* be inserted) is located is linked or not. If the show is linked,
@@ -654,18 +667,24 @@ final class Application_Model_Scheduler
* of inserted items
*/
if ($id != 0) {
- $schedule_sql = "SELECT * FROM cc_schedule WHERE id = ".$id;
+ $schedule_sql = 'SELECT * FROM cc_schedule WHERE id = ' . $id;
$ccSchedule = Application_Common_Database::prepareAndExecute(
- $schedule_sql, array(), Application_Common_Database::SINGLE);
+ $schedule_sql,
+ [],
+ Application_Common_Database::SINGLE
+ );
- $show_sql = "SELECT * FROM cc_show WHERE id IN (".
- "SELECT show_id FROM cc_show_instances WHERE id = ".$ccSchedule["instance_id"].")";
+ $show_sql = 'SELECT * FROM cc_show WHERE id IN (' .
+ 'SELECT show_id FROM cc_show_instances WHERE id = ' . $ccSchedule['instance_id'] . ')';
$ccShow = Application_Common_Database::prepareAndExecute(
- $show_sql, array(), Application_Common_Database::SINGLE);
+ $show_sql,
+ [],
+ Application_Common_Database::SINGLE
+ );
- $linked = $ccShow["linked"];
+ $linked = $ccShow['linked'];
if ($linked) {
- $unique = $ccShow["id"] . $ccSchedule["position"];
+ $unique = $ccShow['id'] . $ccSchedule['position'];
if (!in_array($unique, $temp)) {
$temp[] = $unique;
} else {
@@ -673,14 +692,17 @@ final class Application_Model_Scheduler
}
}
} else {
- $show_sql = "SELECT * FROM cc_show WHERE id IN (".
- "SELECT show_id FROM cc_show_instances WHERE id = ".$schedule["instance"].")";
+ $show_sql = 'SELECT * FROM cc_show WHERE id IN (' .
+ 'SELECT show_id FROM cc_show_instances WHERE id = ' . $schedule['instance'] . ')';
$ccShow = Application_Common_Database::prepareAndExecute(
- $show_sql, array(), Application_Common_Database::SINGLE);
+ $show_sql,
+ [],
+ Application_Common_Database::SINGLE
+ );
- $linked = $ccShow["linked"];
+ $linked = $ccShow['linked'];
if ($linked) {
- $unique = $ccShow["id"] . "a";
+ $unique = $ccShow['id'] . 'a';
if (!in_array($unique, $temp)) {
$temp[] = $unique;
} else {
@@ -695,17 +717,19 @@ final class Application_Model_Scheduler
*/
if ($linked) {
$instances = CcShowInstancesQuery::create()
- ->filterByDbShowId($ccShow["id"])
+ ->filterByDbShowId($ccShow['id'])
->filterByDbStarts(gmdate(DEFAULT_TIMESTAMP_FORMAT), Criteria::GREATER_THAN)
- ->find();
+ ->find()
+ ;
} else {
$instances = CcShowInstancesQuery::create()
- ->filterByDbId($schedule["instance"])
- ->find();
+ ->filterByDbId($schedule['instance'])
+ ->find()
+ ;
}
- $excludePositions = array();
- foreach($instances as &$instance) {
+ $excludePositions = [];
+ foreach ($instances as &$instance) {
//reset
$this->applyCrossfades = true;
@@ -715,54 +739,64 @@ final class Application_Model_Scheduler
/* We use the selected cursor's position to find the same
* positions in every other linked instance
*/
- $pos = $ccSchedule["position"];
+ $pos = $ccSchedule['position'];
- $linkedItem_sql = "SELECT ends FROM cc_schedule ".
- "WHERE instance_id = {$instanceId} ".
- "AND position = {$pos} ".
- "AND playout_status != -1";
+ $linkedItem_sql = 'SELECT ends FROM cc_schedule ' .
+ "WHERE instance_id = {$instanceId} " .
+ "AND position = {$pos} " .
+ 'AND playout_status != -1';
$linkedItemEnds = Application_Common_Database::prepareAndExecute(
- $linkedItem_sql, array(), Application_Common_Database::COLUMN);
+ $linkedItem_sql,
+ [],
+ Application_Common_Database::COLUMN
+ );
if (!$linkedItemEnds) {
//With dynamic smart blocks there may be different number of items in
//each show. In case the position does not exist we need to select
//the end time of the last position
- $maxPos_sql = "SELECT max(position) from cc_schedule ".
+ $maxPos_sql = 'SELECT max(position) from cc_schedule ' .
"WHERE instance_id = {$instanceId}";
$pos = Application_Common_Database::prepareAndExecute(
- $maxPos_sql, array(), Application_Common_Database::COLUMN);
+ $maxPos_sql,
+ [],
+ Application_Common_Database::COLUMN
+ );
//show instance has no scheduled tracks
if (empty($pos)) {
$pos = 0;
- $nextStartDT = new DateTime($instance->getDbStarts(), new DateTimeZone("UTC"));
+ $nextStartDT = new DateTime($instance->getDbStarts(), new DateTimeZone('UTC'));
} else {
-
- $linkedItem_sql = "SELECT ends FROM cc_schedule ".
- "WHERE instance_id = {$instanceId} ".
- "AND position = {$pos} ".
- "AND playout_status != -1";
+ $linkedItem_sql = 'SELECT ends FROM cc_schedule ' .
+ "WHERE instance_id = {$instanceId} " .
+ "AND position = {$pos} " .
+ 'AND playout_status != -1';
$linkedItemEnds = Application_Common_Database::prepareAndExecute(
- $linkedItem_sql, array(), Application_Common_Database::COLUMN);
+ $linkedItem_sql,
+ [],
+ Application_Common_Database::COLUMN
+ );
$nextStartDT = $this->findNextStartTime(
- new DateTime($linkedItemEnds, new DateTimeZone("UTC")),
- $instanceId);
+ new DateTime($linkedItemEnds, new DateTimeZone('UTC')),
+ $instanceId
+ );
}
} else {
$nextStartDT = $this->findNextStartTime(
- new DateTime($linkedItemEnds, new DateTimeZone("UTC")),
- $instanceId);
+ new DateTime($linkedItemEnds, new DateTimeZone('UTC')),
+ $instanceId
+ );
- $pos++;
+ ++$pos;
}
//$pos++;
}
//selected empty row to add after
else {
- $showStartDT = new DateTime($instance->getDbStarts(), new DateTimeZone("UTC"));
+ $showStartDT = new DateTime($instance->getDbStarts(), new DateTimeZone('UTC'));
$nextStartDT = $this->findNextStartTime($showStartDT, $instanceId);
//first item in show so start position counter at 0
@@ -783,18 +817,19 @@ final class Application_Model_Scheduler
* following the item just inserted, per show instance
*/
if ($adjustSched === true) {
-
$pstart = microtime(true);
if ($this->applyCrossfades) {
$initalStartDT = clone $this->findTimeDifference(
- $nextStartDT, $this->crossfadeDuration);
+ $nextStartDT,
+ $this->crossfadeDuration
+ );
} else {
$initalStartDT = clone $nextStartDT;
}
$pend = microtime(true);
- Logging::debug("finding all following items.");
+ Logging::debug('finding all following items.');
Logging::debug(floatval($pend) - floatval($pstart));
}
@@ -802,19 +837,21 @@ final class Application_Model_Scheduler
// can be used to determine the remaining time
// in the case of a fill remaining time smart block
if (is_null($filesToInsert)) {
- $filesToInsert = array();
+ $filesToInsert = [];
foreach ($mediaItems as $media) {
- $filesToInsert = array_merge($filesToInsert,
- $this->retrieveMediaFiles($media["id"], $media["type"], $schedule["instance"]));
+ $filesToInsert = array_merge(
+ $filesToInsert,
+ $this->retrieveMediaFiles($media['id'], $media['type'], $schedule['instance'])
+ );
}
}
$doInsert = false;
$doUpdate = false;
- $values = array();
+ $values = [];
//array that stores the cc_file ids so we can update the is_scheduled flag
- $fileIds = array();
+ $fileIds = [];
foreach ($filesToInsert as &$file) {
//item existed previously and is being moved.
@@ -823,17 +860,20 @@ final class Application_Model_Scheduler
$adjustFromDT = clone $nextStartDT;
$doUpdate = true;
- $movedItem_sql = "SELECT * FROM cc_schedule ".
- "WHERE id = ".$file["sched_id"];
+ $movedItem_sql = 'SELECT * FROM cc_schedule ' .
+ 'WHERE id = ' . $file['sched_id'];
$sched = Application_Common_Database::prepareAndExecute(
- $movedItem_sql, array(), Application_Common_Database::SINGLE);
+ $movedItem_sql,
+ [],
+ Application_Common_Database::SINGLE
+ );
/* We need to keep a record of the original positon a track
* is being moved from so we can use it to retrieve the correct
* items in linked instances
*/
if (!isset($originalPosition)) {
- $originalPosition = $sched["position"];
+ $originalPosition = $sched['position'];
}
/* If we are moving an item in a linked show we need to get
@@ -841,12 +881,15 @@ final class Application_Model_Scheduler
* relative item is by its position
*/
if ($linked) {
- $movedItem_sql = "SELECT * FROM cc_schedule ".
- "WHERE position = {$originalPosition} ".
+ $movedItem_sql = 'SELECT * FROM cc_schedule ' .
+ "WHERE position = {$originalPosition} " .
"AND instance_id = {$instanceId}";
$sched = Application_Common_Database::prepareAndExecute(
- $movedItem_sql, array(), Application_Common_Database::SINGLE);
+ $movedItem_sql,
+ [],
+ Application_Common_Database::SINGLE
+ );
}
/* If we don't find a schedule item it means the linked
* shows have a different amount of items (dyanmic block)
@@ -855,20 +898,20 @@ final class Application_Model_Scheduler
if (!$sched) {
continue;
}
- $excludeIds[] = intval($sched["id"]);
+ $excludeIds[] = intval($sched['id']);
- $file["cliplength"] = $sched["clip_length"];
- $file["cuein"] = $sched["cue_in"];
- $file["cueout"] = $sched["cue_out"];
- $file["fadein"] = $sched["fade_in"];
- $file["fadeout"] = $sched["fade_out"];
+ $file['cliplength'] = $sched['clip_length'];
+ $file['cuein'] = $sched['cue_in'];
+ $file['cueout'] = $sched['cue_out'];
+ $file['fadein'] = $sched['fade_in'];
+ $file['fadeout'] = $sched['fade_out'];
} else {
$doInsert = true;
}
// default fades are in seconds
// we need to convert to '00:00:00' format
- // added a check to only run the conversion if they are in seconds format
+ // added a check to only run the conversion if they are in seconds format
// otherwise php > 7.1 throws errors
if (is_numeric($file['fadein'])) {
$file['fadein'] = Application_Common_DateHelper::secondsToPlaylistTime($file['fadein']);
@@ -877,22 +920,28 @@ final class Application_Model_Scheduler
$file['fadeout'] = Application_Common_DateHelper::secondsToPlaylistTime($file['fadeout']);
}
- switch ($file["type"]) {
+ switch ($file['type']) {
case 0:
- $fileId = $file["id"];
- $streamId = "null";
+ $fileId = $file['id'];
+ $streamId = 'null';
$fileIds[] = $fileId;
+
break;
+
case 1:
- $streamId = $file["id"];
- $fileId = "null";
+ $streamId = $file['id'];
+ $fileId = 'null';
+
break;
+
default: break;
}
if ($this->applyCrossfades) {
- $nextStartDT = $this->findTimeDifference($nextStartDT,
- $this->crossfadeDuration);
+ $nextStartDT = $this->findTimeDifference(
+ $nextStartDT,
+ $this->crossfadeDuration
+ );
$endTimeDT = $this->findEndTime($nextStartDT, $file['cliplength']);
$endTimeDT = $this->findTimeDifference($endTimeDT, $this->crossfadeDuration);
/* Set it to false because the rest of the crossfades
@@ -903,52 +952,53 @@ final class Application_Model_Scheduler
$endTimeDT = $this->findEndTime($nextStartDT, $file['cliplength']);
if ($doInsert) {
- $values[] = "(".
- "'{$nextStartDT->format(DEFAULT_MICROTIME_FORMAT)}', ".
- "'{$endTimeDT->format(DEFAULT_MICROTIME_FORMAT)}', ".
- "'{$file["cuein"]}', ".
- "'{$file["cueout"]}', ".
- "'{$file["fadein"]}', ".
- "'{$file["fadeout"]}', ".
- "'{$file["cliplength"]}', ".
- "{$pos}, ".
- "{$instanceId}, ".
- "{$fileId}, ".
+ $values[] = '(' .
+ "'{$nextStartDT->format(DEFAULT_MICROTIME_FORMAT)}', " .
+ "'{$endTimeDT->format(DEFAULT_MICROTIME_FORMAT)}', " .
+ "'{$file['cuein']}', " .
+ "'{$file['cueout']}', " .
+ "'{$file['fadein']}', " .
+ "'{$file['fadeout']}', " .
+ "'{$file['cliplength']}', " .
+ "{$pos}, " .
+ "{$instanceId}, " .
+ "{$fileId}, " .
"{$streamId})";
-
} elseif ($doUpdate) {
- $update_sql = "UPDATE cc_schedule SET ".
- "starts = '{$nextStartDT->format(DEFAULT_MICROTIME_FORMAT)}', ".
- "ends = '{$endTimeDT->format(DEFAULT_MICROTIME_FORMAT)}', ".
- "cue_in = '{$file["cuein"]}', ".
- "cue_out = '{$file["cueout"]}', ".
- "fade_in = '{$file["fadein"]}', ".
- "fade_out = '{$file["fadeout"]}', ".
- "clip_length = '{$file["cliplength"]}', ".
- "position = {$pos}, ".
- "instance_id = {$instanceId} ".
- "WHERE id = {$sched["id"]}";
+ $update_sql = 'UPDATE cc_schedule SET ' .
+ "starts = '{$nextStartDT->format(DEFAULT_MICROTIME_FORMAT)}', " .
+ "ends = '{$endTimeDT->format(DEFAULT_MICROTIME_FORMAT)}', " .
+ "cue_in = '{$file['cuein']}', " .
+ "cue_out = '{$file['cueout']}', " .
+ "fade_in = '{$file['fadein']}', " .
+ "fade_out = '{$file['fadeout']}', " .
+ "clip_length = '{$file['cliplength']}', " .
+ "position = {$pos}, " .
+ "instance_id = {$instanceId} " .
+ "WHERE id = {$sched['id']}";
Application_Common_Database::prepareAndExecute(
- $update_sql, array(), Application_Common_Database::EXECUTE);
+ $update_sql,
+ [],
+ Application_Common_Database::EXECUTE
+ );
}
$nextStartDT = $this->findTimeDifference($endTimeDT, $this->crossfadeDuration);
- $pos++;
-
+ ++$pos;
}//all files have been inserted/moved
if ($doInsert) {
- $insert_sql = "INSERT INTO cc_schedule ".
- "(starts, ends, cue_in, cue_out, fade_in, fade_out, ".
- "clip_length, position, instance_id, file_id, stream_id) VALUES ".
- implode($values, ",")." RETURNING id";
+ $insert_sql = 'INSERT INTO cc_schedule ' .
+ '(starts, ends, cue_in, cue_out, fade_in, fade_out, ' .
+ 'clip_length, position, instance_id, file_id, stream_id) VALUES ' .
+ implode($values, ',') . ' RETURNING id';
$stmt = $this->con->prepare($insert_sql);
if ($stmt->execute()) {
foreach ($stmt->fetchAll() as $row) {
- $excludeIds[] = $row["id"];
+ $excludeIds[] = $row['id'];
}
- };
+ }
}
$selectCriteria = new Criteria();
@@ -966,54 +1016,57 @@ final class Application_Model_Scheduler
}
if ($adjustSched === true) {
-
- $followingItems_sql = "SELECT * FROM cc_schedule ".
- "WHERE starts >= '{$initalStartDT->format(DEFAULT_MICROTIME_FORMAT)}' ".
+ $followingItems_sql = 'SELECT * FROM cc_schedule ' .
+ "WHERE starts >= '{$initalStartDT->format(DEFAULT_MICROTIME_FORMAT)}' " .
"AND instance_id = {$instanceId} ";
if (count($excludeIds) > 0) {
- $followingItems_sql .= "AND id NOT IN (". implode($excludeIds, ",").") ";
+ $followingItems_sql .= 'AND id NOT IN (' . implode($excludeIds, ',') . ') ';
}
- $followingItems_sql .= "ORDER BY starts";
+ $followingItems_sql .= 'ORDER BY starts';
$followingSchedItems = Application_Common_Database::prepareAndExecute(
- $followingItems_sql);
+ $followingItems_sql
+ );
$pstart = microtime(true);
//recalculate the start/end times after the inserted items.
foreach ($followingSchedItems as $item) {
- $endTimeDT = $this->findEndTime($nextStartDT, $item["clip_length"]);
+ $endTimeDT = $this->findEndTime($nextStartDT, $item['clip_length']);
$endTimeDT = $this->findTimeDifference($endTimeDT, $this->crossfadeDuration);
- $update_sql = "UPDATE cc_schedule SET ".
- "starts = '{$nextStartDT->format(DEFAULT_MICROTIME_FORMAT)}', ".
- "ends = '{$endTimeDT->format(DEFAULT_MICROTIME_FORMAT)}', ".
- "position = {$pos} ".
- "WHERE id = {$item["id"]}";
+ $update_sql = 'UPDATE cc_schedule SET ' .
+ "starts = '{$nextStartDT->format(DEFAULT_MICROTIME_FORMAT)}', " .
+ "ends = '{$endTimeDT->format(DEFAULT_MICROTIME_FORMAT)}', " .
+ "position = {$pos} " .
+ "WHERE id = {$item['id']}";
Application_Common_Database::prepareAndExecute(
- $update_sql, array(), Application_Common_Database::EXECUTE);
+ $update_sql,
+ [],
+ Application_Common_Database::EXECUTE
+ );
$nextStartDT = $this->findTimeDifference($endTimeDT, $this->crossfadeDuration);
- $pos++;
+ ++$pos;
}
$pend = microtime(true);
- Logging::debug("adjusting all following items.");
+ Logging::debug('adjusting all following items.');
Logging::debug(floatval($pend) - floatval($pstart));
}
if ($moveAction) {
$this->calculateCrossfades($instanceId);
}
}//for each instance
-
}//for each schedule location
$endProfile = microtime(true);
- Logging::debug("finished adding scheduled items.");
+ Logging::debug('finished adding scheduled items.');
Logging::debug(floatval($endProfile) - floatval($startProfile));
//update the status flag in cc_schedule.
$instances = CcShowInstancesQuery::create()
->filterByPrimaryKeys($affectedShowInstances)
- ->find($this->con);
+ ->find($this->con)
+ ;
$startProfile = microtime(true);
@@ -1022,7 +1075,7 @@ final class Application_Model_Scheduler
}
$endProfile = microtime(true);
- Logging::debug("updating show instances status.");
+ Logging::debug('updating show instances status.');
Logging::debug(floatval($endProfile) - floatval($startProfile));
$startProfile = microtime(true);
@@ -1030,20 +1083,21 @@ final class Application_Model_Scheduler
//update the last scheduled timestamp.
CcShowInstancesQuery::create()
->filterByPrimaryKeys($affectedShowInstances)
- ->update(array('DbLastScheduled' => new DateTime("now", new DateTimeZone("UTC"))), $this->con);
+ ->update(['DbLastScheduled' => new DateTime('now', new DateTimeZone('UTC'))], $this->con)
+ ;
$endProfile = microtime(true);
- Logging::debug("updating last scheduled timestamp.");
+ Logging::debug('updating last scheduled timestamp.');
Logging::debug(floatval($endProfile) - floatval($startProfile));
} catch (Exception $e) {
Logging::debug($e->getMessage());
+
throw $e;
}
}
private function updateMovedItem()
{
-
}
private function getInstances($instanceId)
@@ -1052,9 +1106,9 @@ final class Application_Model_Scheduler
$ccShow = $ccShowInstance->getCcShow();
if ($ccShow->isLinked()) {
return $ccShow->getFutureCcShowInstancess();
- } else {
- return array($ccShowInstance);
}
+
+ return [$ccShowInstance];
}
/*
@@ -1068,7 +1122,7 @@ final class Application_Model_Scheduler
try {
//Increase the transaction isolation level to prevent two concurrent requests from potentially resulting
//in tracks scheduled at the same time.
- $this->con->exec("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
+ $this->con->exec('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE');
$this->validateMediaItems($mediaItems); //Check for missing files, etc.
$this->validateRequest($scheduleItems, true);
@@ -1104,6 +1158,7 @@ final class Application_Model_Scheduler
Application_Model_RabbitMq::PushSchedule();
} catch (Exception $e) {
$this->con->rollback();
+
throw $e;
}
}
@@ -1122,7 +1177,7 @@ final class Application_Model_Scheduler
try {
//Increase the transaction isolation level to prevent two concurrent requests from potentially resulting
//in tracks scheduled at the same time.
- $this->con->exec("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
+ $this->con->exec('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE');
$this->validateItemMove($selectedItems, $afterItems[0]);
$this->validateRequest($selectedItems);
@@ -1132,26 +1187,25 @@ final class Application_Model_Scheduler
//Logging::debug("validating move request took:");
//Logging::debug(floatval($endProfile) - floatval($startProfile));
- $afterInstance = CcShowInstancesQuery::create()->findPK($afterItems[0]["instance"], $this->con);
+ $afterInstance = CcShowInstancesQuery::create()->findPK($afterItems[0]['instance'], $this->con);
//map show instances to cc_schedule primary keys.
- $modifiedMap = array();
- $movedData = array();
+ $modifiedMap = [];
+ $movedData = [];
//prepare each of the selected items.
- for ($i = 0; $i < count($selectedItems); $i++) {
-
- $selected = CcScheduleQuery::create()->findPk($selectedItems[$i]["id"], $this->con);
+ for ($i = 0; $i < count($selectedItems); ++$i) {
+ $selected = CcScheduleQuery::create()->findPk($selectedItems[$i]['id'], $this->con);
$selectedInstance = $selected->getCcShowInstances($this->con);
$data = $this->fileInfo;
- $data["id"] = $selected->getDbFileId();
- $data["cliplength"] = $selected->getDbClipLength();
- $data["cuein"] = $selected->getDbCueIn();
- $data["cueout"] = $selected->getDbCueOut();
- $data["fadein"] = $selected->getDbFadeIn();
- $data["fadeout"] = $selected->getDbFadeOut();
- $data["sched_id"] = $selected->getDbId();
+ $data['id'] = $selected->getDbFileId();
+ $data['cliplength'] = $selected->getDbClipLength();
+ $data['cuein'] = $selected->getDbCueIn();
+ $data['cueout'] = $selected->getDbCueOut();
+ $data['fadein'] = $selected->getDbFadeIn();
+ $data['fadeout'] = $selected->getDbFadeOut();
+ $data['sched_id'] = $selected->getDbId();
$movedData[] = $data;
@@ -1161,7 +1215,7 @@ final class Application_Model_Scheduler
if (isset($modifiedMap[$showInstanceId])) {
array_push($modifiedMap[$showInstanceId], $schedId);
} else {
- $modifiedMap[$showInstanceId] = array($schedId);
+ $modifiedMap[$showInstanceId] = [$schedId];
}
}
@@ -1187,7 +1241,6 @@ final class Application_Model_Scheduler
$modified = array_keys($modifiedMap);
//need to adjust shows we have moved items from.
foreach ($modified as $instanceId) {
-
$instance = CcShowInstancesQuery::create()->findPK($instanceId, $this->con);
$instance->updateScheduleStatus($this->con);
}
@@ -1198,22 +1251,22 @@ final class Application_Model_Scheduler
Application_Model_RabbitMq::PushSchedule();
} catch (Exception $e) {
$this->con->rollback();
+
throw $e;
}
}
- public function removeItems($scheduledItems, $adjustSched = true, $cancelShow=false)
+ public function removeItems($scheduledItems, $adjustSched = true, $cancelShow = false)
{
- $showInstances = array();
+ $showInstances = [];
$this->con->beginTransaction();
try {
-
$this->validateRequest($scheduledItems, true, true);
- $scheduledIds = array();
+ $scheduledIds = [];
foreach ($scheduledItems as $item) {
- $scheduledIds[] = $item["id"];
+ $scheduledIds[] = $item['id'];
}
$removedItems = CcScheduleQuery::create()->findPks($scheduledIds);
@@ -1221,7 +1274,7 @@ final class Application_Model_Scheduler
// This array is used to keep track of every show instance that was
// effected by the track deletion. It will be used later on to
// remove gaps in the schedule and adjust crossfade times.
- $effectedInstanceIds = array();
+ $effectedInstanceIds = [];
foreach ($removedItems as $removedItem) {
$instance = $removedItem->getCcShowInstances($this->con);
@@ -1233,33 +1286,32 @@ final class Application_Model_Scheduler
//returns all linked instances if linked
$ccShowInstances = $this->getInstances($instance->getDbId());
- $instanceIds = array();
+ $instanceIds = [];
foreach ($ccShowInstances as $ccShowInstance) {
$instanceIds[] = $ccShowInstance->getDbId();
}
$effectedInstanceIds = array_merge($effectedInstanceIds, $instanceIds);
-
+
// Delete the same track, represented by $removedItem, in
// each linked show instance.
$itemsToDelete = CcScheduleQuery::create()
->filterByDbPosition($removedItem->getDbPosition())
->filterByDbInstanceId($instanceIds, Criteria::IN)
->filterByDbId($removedItem->getDbId(), Criteria::NOT_EQUAL)
- ->delete($this->con);
+ ->delete($this->con)
+ ;
}
-
//check to truncate the currently playing item instead of deleting it.
if ($removedItem->isCurrentItem($this->epochNow)) {
-
$nEpoch = $this->epochNow;
$sEpoch = $removedItem->getDbStarts('U.u');
- $length = bcsub($nEpoch , $sEpoch , 6);
+ $length = bcsub($nEpoch, $sEpoch, 6);
$cliplength = Application_Common_DateHelper::secondsToPlaylistTime($length);
$cueinSec = Application_Common_DateHelper::playlistTimeToSeconds($removedItem->getDbCueIn());
- $cueOutSec = bcadd($cueinSec , $length, 6);
+ $cueOutSec = bcadd($cueinSec, $length, 6);
$cueout = Application_Common_DateHelper::secondsToPlaylistTime($cueOutSec);
//Set DbEnds - 1 second because otherwise there can be a timing issue
@@ -1268,7 +1320,8 @@ final class Application_Model_Scheduler
$removedItem->setDbCueOut($cueout)
->setDbClipLength($cliplength)
->setDbEnds($this->nowDT)
- ->save($this->con);
+ ->save($this->con)
+ ;
} else {
$removedItem->delete($this->con);
}
@@ -1285,7 +1338,8 @@ final class Application_Model_Scheduler
//update the status flag in cc_schedule.
$instances = CcShowInstancesQuery::create()
->filterByPrimaryKeys($effectedInstanceIds)
- ->find($this->con);
+ ->find($this->con)
+ ;
foreach ($instances as $instance) {
$instance->updateScheduleStatus($this->con);
@@ -1295,29 +1349,30 @@ final class Application_Model_Scheduler
//update the last scheduled timestamp.
CcShowInstancesQuery::create()
->filterByPrimaryKeys($showInstances)
- ->update(array('DbLastScheduled' => new DateTime("now", new DateTimeZone("UTC"))), $this->con);
+ ->update(['DbLastScheduled' => new DateTime('now', new DateTimeZone('UTC'))], $this->con)
+ ;
$this->con->commit();
Application_Model_RabbitMq::PushSchedule();
} catch (Exception $e) {
$this->con->rollback();
+
throw $e;
}
}
- /*
- * This is used to determine the duration of a files array
- *
- *
- */
- public function timeLengthOfFiles($files) {
- $timeLength = 0;
- foreach ($files as $file) {
- $timeLength += Application_Common_DateHelper::playlistTimeToSeconds($file['cliplength']);
- $timeLength += $file['fadein'];
- $timeLength += $file['fadeout'];
- }
- return $timeLength;
+
+ // This is used to determine the duration of a files array
+ public function timeLengthOfFiles($files)
+ {
+ $timeLength = 0;
+ foreach ($files as $file) {
+ $timeLength += Application_Common_DateHelper::playlistTimeToSeconds($file['cliplength']);
+ $timeLength += $file['fadein'];
+ $timeLength += $file['fadeout'];
+ }
+
+ return $timeLength;
}
/*
@@ -1330,24 +1385,23 @@ final class Application_Model_Scheduler
$this->con->beginTransaction();
try {
-
$instance = CcShowInstancesQuery::create()->findPK($p_id);
if (!$instance->getDbRecord()) {
-
$items = CcScheduleQuery::create()
->filterByDbInstanceId($p_id)
->filterByDbEnds($this->nowDT, Criteria::GREATER_THAN)
- ->find($this->con);
+ ->find($this->con)
+ ;
if (count($items) > 0) {
- $remove = array();
+ $remove = [];
$ts = $this->nowDT->format('U');
- for ($i = 0; $i < count($items); $i++) {
- $remove[$i]["instance"] = $p_id;
- $remove[$i]["timestamp"] = $ts;
- $remove[$i]["id"] = $items[$i]->getDbId();
+ for ($i = 0; $i < count($items); ++$i) {
+ $remove[$i]['instance'] = $p_id;
+ $remove[$i]['timestamp'] = $ts;
+ $remove[$i]['id'] = $items[$i]->getDbId();
}
$this->removeItems($remove, false, true);
@@ -1363,13 +1417,16 @@ final class Application_Model_Scheduler
$this->con->commit();
if ($instance->getDbRecord()) {
- Application_Model_RabbitMq::SendMessageToShowRecorder("cancel_recording");
+ Application_Model_RabbitMq::SendMessageToShowRecorder('cancel_recording');
}
} catch (Exception $e) {
$this->con->rollback();
+
throw $e;
}
}
}
-class OutDatedScheduleException extends Exception {}
+class OutDatedScheduleException extends Exception
+{
+}
diff --git a/legacy/application/models/ServiceRegister.php b/legacy/application/models/ServiceRegister.php
index 543bfb24b..e79e82489 100644
--- a/legacy/application/models/ServiceRegister.php
+++ b/legacy/application/models/ServiceRegister.php
@@ -1,16 +1,17 @@
setDbIp($p_ipAddress);
$component->save();
}
-
}
diff --git a/legacy/application/models/Show.php b/legacy/application/models/Show.php
index de981eb9f..9961b0595 100644
--- a/legacy/application/models/Show.php
+++ b/legacy/application/models/Show.php
@@ -4,7 +4,7 @@ class Application_Model_Show
{
private $_showId;
- public function __construct($showId=NULL)
+ public function __construct($showId = null)
{
$this->_showId = $showId;
}
@@ -67,6 +67,7 @@ class Application_Model_Show
public function getColor()
{
$show = CcShowQuery::create()->findPK($this->_showId);
+
return $show->getDbColor();
}
@@ -113,9 +114,9 @@ class Application_Model_Show
$color = $show->getDbBackgroundColor();
if (empty($color)) {
return DEFAULT_SHOW_COLOR;
- } else {
- return $color;
}
+
+ return $color;
}
public function setBackgroundColor($backgroundColor)
@@ -132,14 +133,15 @@ class Application_Model_Show
public function getHasAutoPlaylist()
{
$show = CcShowQuery::create()->findPK($this->_showId);
- $hasAutoPlaylist = $show->getDbHasAutoPlaylist();
- return $hasAutoPlaylist;
+
+ return $show->getDbHasAutoPlaylist();
}
- public function getAutoPlaylistRepeat() {
+ public function getAutoPlaylistRepeat()
+ {
$show = CcShowQuery::create()->findPK($this->_showId);
- $AutoPlaylistRepeat = $show->getDbAutoPlaylistRepeat();
- return $AutoPlaylistRepeat;
+
+ return $show->getDbAutoPlaylistRepeat();
}
public function setAutoPlaylistRepeat($value)
@@ -147,7 +149,7 @@ class Application_Model_Show
$show = CcShowQuery::create()->findPK($this->_showId);
$show->setDbAutoPlaylistRepeat($value);
}
-
+
public function setHasAutoPlaylist($value)
{
$show = CcShowQuery::create()->findPK($this->_showId);
@@ -157,8 +159,8 @@ class Application_Model_Show
public function getAutoPlaylistId()
{
$show = CcShowQuery::create()->findPK($this->_showId);
- $autoPlaylistId = $show->getDbAutoPlaylistId();
- return $autoPlaylistId;
+
+ return $show->getDbAutoPlaylistId();
}
public function setAutoPlaylistId($playlistid)
@@ -169,7 +171,7 @@ class Application_Model_Show
public function getHosts()
{
- $sql = << $this->getId() ), 'all');
+ $hosts = Application_Common_Database::prepareAndExecute(
+ $sql,
+ [':show_id' => $this->getId()],
+ 'all'
+ );
- $res = array();
+ $res = [];
foreach ($hosts as $host) {
- $res[] = $host['first_name']." ".$host['last_name'];
+ $res[] = $host['first_name'] . ' ' . $host['last_name'];
}
+
return $res;
}
public function getHostsIds()
{
- $sql = << $this->getId() ), 'all');
-
- return $hosts;
+ return Application_Common_Database::prepareAndExecute(
+ $sql,
+ [':show_id' => $this->getId()],
+ 'all'
+ );
}
/**
@@ -219,25 +226,24 @@ SQL;
$con = Propel::getConnection();
if ($deltaDay > 0) {
- return _("Shows can have a max length of 24 hours.");
+ return _('Shows can have a max length of 24 hours.');
}
- $utcTimezone = new DateTimeZone("UTC");
- $nowDateTime = new DateTime("now", $utcTimezone);
+ $utcTimezone = new DateTimeZone('UTC');
+ $nowDateTime = new DateTime('now', $utcTimezone);
//keep track of cc_show_day entries we need to update
- $showDayIds = array();
+ $showDayIds = [];
/*
* If the resized show is an edited instance of a repeating show we
* need to treat it as a separate show and not resize the other instances
- *
+ *
* Also, if the resized show has edited instances, we need to exclude
* those from the resize
*/
$ccShow = CcShowQuery::create()->findPk($this->_showId);
if ($ccShow->isRepeating()) {
-
//convert instance to local timezone
$ccShowInstance = CcShowInstancesQuery::create()->findPk($instanceId);
$startsDT = $ccShowInstance->getDbStarts(null);
@@ -249,10 +255,11 @@ SQL;
* show and we can assume we aren't resizing a modified instance
*/
$ccShowDay = CcShowDaysQuery::create()
- ->filterByDbFirstShow($startsDT->format("Y-m-d"))
- ->filterByDbStartTime($startsDT->format("H:i:s"))
+ ->filterByDbFirstShow($startsDT->format('Y-m-d'))
+ ->filterByDbStartTime($startsDT->format('H:i:s'))
->filterByDbShowId($this->_showId)
- ->findOne();
+ ->findOne()
+ ;
/* Check if this cc_show_day rule is non-repeating. If it is, then
* we know this instance was edited out of the repeating sequence
@@ -270,14 +277,16 @@ SQL;
->filterByDbShowId($this->_showId)
->filterByDbModifiedInstance(false)
->filterByDbId($excludeIds, criteria::NOT_IN)
- ->find();
+ ->find()
+ ;
} elseif ($ccShowDay->getDbRepeatType() == -1) {
array_push($showDayIds, $ccShowDay->getDbId());
//treat edited instance as separate show for resize
$showInstances = CcShowInstancesQuery::create()
->filterByDbId($instanceId)
- ->find();
+ ->find()
+ ;
}
} else {
$ccShowDays = $ccShow->getCcShowDayss();
@@ -287,7 +296,8 @@ SQL;
$showInstances = CcShowInstancesQuery::create()
->filterByDbShowId($this->_showId)
- ->find($con);
+ ->find($con)
+ ;
}
/* Check two things:
@@ -296,15 +306,15 @@ SQL;
with other scheduled shows */
//keep track of instance ids for update show instances start/end times
- $instanceIds = array();
+ $instanceIds = [];
$displayTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
-
+
//check if new show time overlaps with any other shows
foreach ($showInstances as $si) {
array_push($instanceIds, $si->getDbId());
$startsDateTime = $si->getDbStarts(null);
- $endsDateTime = $si->getDbEnds(null);
+ $endsDateTime = $si->getDbEnds(null);
/* The user is moving the show on the calendar from the perspective
of local time. * incase a show is moved across a time change
@@ -314,10 +324,10 @@ SQL;
$endsDateTime->setTimezone($displayTimezone);
//$newStartsDateTime = Application_Model_ShowInstance::addDeltas($startsDateTime, $deltaDay, $deltaMin);
- $newEndsDateTime = Application_Model_ShowInstance::addDeltas($endsDateTime, $deltaDay, $deltaMin);
+ $newEndsDateTime = Application_Model_ShowInstance::addDeltas($endsDateTime, $deltaDay, $deltaMin);
if ($newEndsDateTime->getTimestamp() < $nowDateTime->getTimestamp()) {
- return _("End date/time cannot be in the past");
+ return _('End date/time cannot be in the past');
}
//convert our new starts/ends to UTC.
@@ -325,45 +335,55 @@ SQL;
$newEndsDateTime->setTimezone($utcTimezone);
$overlapping = Application_Model_Schedule::checkOverlappingShows(
- $startsDateTime, $newEndsDateTime, true, $si->getDbId());
+ $startsDateTime,
+ $newEndsDateTime,
+ true,
+ $si->getDbId()
+ );
if ($overlapping) {
- return _("Cannot schedule overlapping shows.\nNote: Resizing a repeating show ".
- "affects all of its repeats.");
+ return _("Cannot schedule overlapping shows.\nNote: Resizing a repeating show " .
+ 'affects all of its repeats.');
}
}
- $hours = $deltaMin/60;
+ $hours = $deltaMin / 60;
$hours = ($hours > 0) ? floor($hours) : ceil($hours);
- $mins = abs($deltaMin % 60);
+ $mins = abs($deltaMin % 60);
- $sql_gen = "UPDATE cc_show_instances ".
- "SET ends = (ends + :deltaDay1::INTERVAL + :interval1::INTERVAL) ".
- "WHERE (id IN (".implode($instanceIds, ",").") ".
- "AND ends > :current_timestamp1) ".
+ $sql_gen = 'UPDATE cc_show_instances ' .
+ 'SET ends = (ends + :deltaDay1::INTERVAL + :interval1::INTERVAL) ' .
+ 'WHERE (id IN (' . implode($instanceIds, ',') . ') ' .
+ 'AND ends > :current_timestamp1) ' .
"AND ((ends + :deltaDay2::INTERVAL + :interval2::INTERVAL - starts) <= interval '24:00')";
- Application_Common_Database::prepareAndExecute($sql_gen,
- array(
- ':deltaDay1' => "$deltaDay days",
- ':interval1' => "$hours:$mins",
- ':current_timestamp1' => $nowDateTime->format(DEFAULT_TIMESTAMP_FORMAT),
- ':deltaDay2' => "$deltaDay days",
- ':interval2' => "$hours:$mins"
- ), "execute");
+ Application_Common_Database::prepareAndExecute(
+ $sql_gen,
+ [
+ ':deltaDay1' => "{$deltaDay} days",
+ ':interval1' => "{$hours}:{$mins}",
+ ':current_timestamp1' => $nowDateTime->format(DEFAULT_TIMESTAMP_FORMAT),
+ ':deltaDay2' => "{$deltaDay} days",
+ ':interval2' => "{$hours}:{$mins}",
+ ],
+ 'execute'
+ );
- $sql_gen = "UPDATE cc_show_days ".
- "SET duration = (CAST(duration AS interval) + :deltaDay3::INTERVAL + :interval3::INTERVAL) ".
- "WHERE id IN (".implode($showDayIds, ",").") ".
+ $sql_gen = 'UPDATE cc_show_days ' .
+ 'SET duration = (CAST(duration AS interval) + :deltaDay3::INTERVAL + :interval3::INTERVAL) ' .
+ 'WHERE id IN (' . implode($showDayIds, ',') . ') ' .
"AND ((CAST(duration AS interval) + :deltaDay4::INTERVAL + :interval4::INTERVAL) <= interval '24:00')";
- Application_Common_Database::prepareAndExecute($sql_gen,
- array(
- ':deltaDay3' => "$deltaDay days",
- ':interval3' => "$hours:$mins",
- ':deltaDay4' => "$deltaDay days",
- ':interval4' => "$hours:$mins"
- ), "execute");
+ Application_Common_Database::prepareAndExecute(
+ $sql_gen,
+ [
+ ':deltaDay3' => "{$deltaDay} days",
+ ':interval3' => "{$hours}:{$mins}",
+ ':deltaDay4' => "{$deltaDay} days",
+ ':interval4' => "{$hours}:{$mins}",
+ ],
+ 'execute'
+ );
$con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME);
$con->beginTransaction();
@@ -380,7 +400,8 @@ SQL;
$instances = CcShowInstancesQuery::create()
->filterByDbEnds($nowDateTime->format(DEFAULT_TIMESTAMP_FORMAT), Criteria::GREATER_THAN)
->filterByDbId($instanceIds, Criteria::IN)
- ->find($con);
+ ->find($con)
+ ;
foreach ($instances as $instance) {
$instance->updateScheduleStatus($con);
@@ -398,25 +419,26 @@ SQL;
public function cancelShow($day_timestamp)
{
- $timeinfo = explode(" ", $day_timestamp);
+ $timeinfo = explode(' ', $day_timestamp);
CcShowDaysQuery::create()
->filterByDbShowId($this->_showId)
- ->update(array('DbLastShow' => $timeinfo[0]));
+ ->update(['DbLastShow' => $timeinfo[0]])
+ ;
- $sql = <<= :dayTimestamp::TIMESTAMP
AND show_id = :showId
SQL;
-
- $rows = Application_Common_Database::prepareAndExecute( $sql, array(
+
+ $rows = Application_Common_Database::prepareAndExecute($sql, [
':dayTimestamp' => $day_timestamp,
- ':showId' => $this->getId()), 'all');
+ ':showId' => $this->getId(), ], 'all');
foreach ($rows as $row) {
try {
- $showInstance = new Application_Model_ShowInstance($row["id"]);
+ $showInstance = new Application_Model_ShowInstance($row['id']);
$showInstance->delete($rabbitmqPush = false);
} catch (Exception $e) {
Logging::info($e->getMessage());
@@ -430,8 +452,8 @@ SQL;
* Check whether the current show originated
* from a recording.
*
- * @return boolean
- * true if originated from recording, otherwise false.
+ * @return bool
+ * true if originated from recording, otherwise false
*/
public function isRecorded()
{
@@ -439,7 +461,8 @@ SQL;
->filterByDbShowId($this->getId())
->filterByDbRecord(1)
->filterByDbModifiedInstance(false)
- ->findOne();
+ ->findOne()
+ ;
return !is_null($showInstancesRow);
}
@@ -448,16 +471,17 @@ SQL;
* Check whether the current show has rebroadcasts of a recorded
* show. Should be used in conjunction with isRecorded().
*
- * @return boolean
- * true if show has rebroadcasts, otherwise false.
+ * @return bool
+ * true if show has rebroadcasts, otherwise false
*/
public function isRebroadcast()
{
- $showInstancesRow = CcShowInstancesQuery::create()
- ->filterByDbShowId($this->_showId)
- ->filterByDbRebroadcast(1)
- ->filterByDbModifiedInstance(false)
- ->findOne();
+ $showInstancesRow = CcShowInstancesQuery::create()
+ ->filterByDbShowId($this->_showId)
+ ->filterByDbRebroadcast(1)
+ ->filterByDbModifiedInstance(false)
+ ->findOne()
+ ;
return !is_null($showInstancesRow);
}
@@ -465,87 +489,96 @@ SQL;
/**
* Get start time and relative start date for a recorded
* shows rebroadcasts. For example start date format would be
- * "x days" and time would HH:MM:SS
+ * "x days" and time would HH:MM:SS.
*
* @return array
- * array of associate arrays containing "day_offset" and "start_time"
+ * array of associate arrays containing "day_offset" and "start_time"
*/
public function getRebroadcastsRelative()
{
- $sql = << $this->getId() ), 'all' );
+
+ return Application_Common_Database::prepareAndExecute(
+ $sql,
+ [':showId' => $this->getId()],
+ 'all'
+ );
}
/**
* Check whether the current show is set to repeat
* repeating shows.
*
- * @return boolean
- * true if repeating shows, otherwise false.
+ * @return bool
+ * true if repeating shows, otherwise false
*/
public function isRepeating()
{
$showDaysRow = CcShowDaysQuery::create()
->filterByDbShowId($this->_showId)
- ->findOne();
+ ->findOne()
+ ;
if (!is_null($showDaysRow)) {
- return ($showDaysRow->getDbRepeatType() != -1);
- } else {
- return false;
+ return $showDaysRow->getDbRepeatType() != -1;
}
+
+ return false;
}
/**
- * Get the repeat type of the show. Show can have repeat type of
+ * Get the repeat type of the show. Show can have repeat type of
* "weekly", "every 2 weeks", "monthly", "monthly on the same weekday",
- * "every 3 weeks" and "every 4 weeks". These values are represented
+ * "every 3 weeks" and "every 4 weeks". These values are represented
* by 0, 1, 2, 3, 4 and 5, respectively.
*
* @return int
- * Return the integer corresponding to the repeat type.
+ * Return the integer corresponding to the repeat type
*/
public function getRepeatType()
{
$showDaysRow = CcShowDaysQuery::create()
->filterByDbShowId($this->_showId)
- ->findOne();
+ ->findOne()
+ ;
- if (!is_null($showDaysRow))
+ if (!is_null($showDaysRow)) {
return $showDaysRow->getDbRepeatType();
- else
- return -1;
+ }
+
+ return -1;
}
/**
- * Get the end date for a repeating show in the format yyyy-mm-dd
+ * Get the end date for a repeating show in the format yyyy-mm-dd.
*
* @return string
- * Return the end date for the repeating show or the empty
- * string if there is no end.
+ * Return the end date for the repeating show or the empty
+ * string if there is no end
*/
public function getRepeatingEndDate()
{
- $sql = << $this->getId() ), 'column' );
+ $query = Application_Common_Database::prepareAndExecute(
+ $sql,
+ ['showId' => $this->getId()],
+ 'column'
+ );
- /* TODO: Why return empty string instead of false? very confusing --RG
- */
- return ($query !== false) ? $query : "";
+ // TODO: Why return empty string instead of false? very confusing --RG
+ return ($query !== false) ? $query : '';
}
/**
@@ -560,15 +593,18 @@ SQL;
*/
public function deleteAllInstances()
{
- $sql = << :timestamp::TIMESTAMP
AND show_id = :showId
SQL;
- Application_Common_Database::prepareAndExecute( $sql,
- array( ':timestamp' => gmdate(DEFAULT_TIMESTAMP_FORMAT),
- ':showId' => $this->getId()), 'execute');
+ Application_Common_Database::prepareAndExecute(
+ $sql,
+ [':timestamp' => gmdate(DEFAULT_TIMESTAMP_FORMAT),
+ ':showId' => $this->getId(), ],
+ 'execute'
+ );
}
/**
@@ -577,24 +613,27 @@ SQL;
*/
public function deleteAllRebroadcasts()
{
- $sql = << :timestamp::TIMESTAMP
AND show_id :showId
AND rebroadcast 1
SQL;
- Application_Common_Database::prepareAndExecute( $sql,
- array( ':showId' => $this->getId(),
- ':timestamp' => gmdate(DEFAULT_TIMESTAMP_FORMAT)), 'execute');
+ Application_Common_Database::prepareAndExecute(
+ $sql,
+ [':showId' => $this->getId(),
+ ':timestamp' => gmdate(DEFAULT_TIMESTAMP_FORMAT), ],
+ 'execute'
+ );
}
/**
* Get the start date of the current show in UTC timezone.
*
* @return string
- * The start date in the format YYYY-MM-DD or empty string in case
- * start date could not be found
+ * The start date in the format YYYY-MM-DD or empty string in case
+ * start date could not be found
*/
public function getStartDateAndTime()
{
@@ -602,36 +641,37 @@ SQL;
$showId = $this->getId();
$stmt = $con->prepare(
- "SELECT first_show, start_time, timezone FROM cc_show_days"
- ." WHERE show_id = :showId"
- ." ORDER BY first_show"
- ." LIMIT 1");
+ 'SELECT first_show, start_time, timezone FROM cc_show_days'
+ . ' WHERE show_id = :showId'
+ . ' ORDER BY first_show'
+ . ' LIMIT 1'
+ );
$stmt->bindParam(':showId', $showId);
$stmt->execute();
if (!$stmt) {
- return "";
+ return '';
}
$rows = $stmt->fetchAll();
$row = $rows[0];
- $dt = new DateTime($row["first_show"]." ".$row["start_time"], new DateTimeZone($row["timezone"]));
- $dt->setTimezone(new DateTimeZone("UTC"));
+ $dt = new DateTime($row['first_show'] . ' ' . $row['start_time'], new DateTimeZone($row['timezone']));
+ $dt->setTimezone(new DateTimeZone('UTC'));
- return $dt->format("Y-m-d H:i");
+ return $dt->format('Y-m-d H:i');
}
/**
* Get the start date of the current show in UTC timezone.
*
* @return string
- * The start date in the format YYYY-MM-DD
+ * The start date in the format YYYY-MM-DD
*/
public function getStartDate()
{
- list($date,) = explode(" ", $this->getStartDateAndTime());
+ list($date) = explode(' ', $this->getStartDateAndTime());
return $date;
}
@@ -640,33 +680,32 @@ SQL;
* Get the start time of the current show in UTC timezone.
*
* @return string
- * The start time in the format HH:MM
+ * The start time in the format HH:MM
*/
-
public function getStartTime()
{
- list(,$time) = explode(" ", $this->getStartDateAndTime());
+ list(, $time) = explode(' ', $this->getStartDateAndTime());
return $time;
}
/**
* Get the end date of the current show.
- * Note that this is not the end date of repeated show
+ * Note that this is not the end date of repeated show.
*
* @return string
- * The end date in the format YYYY-MM-DD
+ * The end date in the format YYYY-MM-DD
*/
public function getEndDate()
{
- $startDate = $this->getStartDate();
- $startTime = $this->getStartTime();
- $duration = $this->getDuration();
+ $startDate = $this->getStartDate();
+ $startTime = $this->getStartTime();
+ $duration = $this->getDuration();
- $startDateTime = new DateTime($startDate.' '.$startTime);
- $duration = explode(":", $duration);
+ $startDateTime = new DateTime($startDate . ' ' . $startTime);
+ $duration = explode(':', $duration);
- $endDate = $startDateTime->add(new DateInterval('PT'.$duration[0].'H'.$duration[1].'M'));
+ $endDate = $startDateTime->add(new DateInterval('PT' . $duration[0] . 'H' . $duration[1] . 'M'));
return $endDate->format('Y-m-d');
}
@@ -675,7 +714,7 @@ SQL;
* Get the end time of the current show.
*
* @return string
- * The start time in the format HH:MM:SS
+ * The start time in the format HH:MM:SS
*/
public function getEndTime()
{
@@ -683,10 +722,10 @@ SQL;
$startTime = $this->getStartTime();
$duration = $this->getDuration();
- $startDateTime = new DateTime($startDate.' '.$startTime);
- $duration = explode(":", $duration);
+ $startDateTime = new DateTime($startDate . ' ' . $startTime);
+ $duration = explode(':', $duration);
- $endDate = $startDateTime->add(new DateInterval('PT'.$duration[0].'H'.$duration[1].'M'));
+ $endDate = $startDateTime->add(new DateInterval('PT' . $duration[0] . 'H' . $duration[1] . 'M'));
return $endDate->format('H:i:s');
}
@@ -695,38 +734,42 @@ SQL;
* Indicate whether the starting point of the show is in the
* past.
*
- * @return boolean
- * true if the StartDate is in the past, false otherwise
+ * @return bool
+ * true if the StartDate is in the past, false otherwise
*/
public function isStartDateTimeInPast()
{
- return (gmdate(DEFAULT_TIMESTAMP_FORMAT) > ($this->getStartDate()." ".$this->getStartTime()));
+ return gmdate(DEFAULT_TIMESTAMP_FORMAT) > ($this->getStartDate() . ' ' . $this->getStartTime());
}
/**
* Get the ID's of future instance of the current show.
*
* @return array
- * A simple array containing all ID's of show instance
- * scheduled in the future.
+ * A simple array containing all ID's of show instance
+ * scheduled in the future
*/
public function getAllFutureInstanceIds()
{
- $sql = << :timestamp::TIMESTAMP
AND modified_instance != TRUE
SQL;
- $rows = Application_Common_Database::prepareAndExecute($sql,
- array( ':showId' => $this->getId(),
- ':timestamp' => gmdate(DEFAULT_TIMESTAMP_FORMAT)), "all");
+ $rows = Application_Common_Database::prepareAndExecute(
+ $sql,
+ [':showId' => $this->getId(),
+ ':timestamp' => gmdate(DEFAULT_TIMESTAMP_FORMAT), ],
+ 'all'
+ );
- $res = array();
+ $res = [];
foreach ($rows as $r) {
$res[] = $r['id'];
}
+
return $res;
}
@@ -743,48 +786,48 @@ SQL;
$con = Propel::getConnection();
$timestamp = gmdate(DEFAULT_TIMESTAMP_FORMAT);
- $stmt = $con->prepare("UPDATE cc_show_days "
- ."SET duration = :add_show_duration "
- ."WHERE show_id = :add_show_id" );
- $stmt->execute( array(
+ $stmt = $con->prepare('UPDATE cc_show_days '
+ . 'SET duration = :add_show_duration '
+ . 'WHERE show_id = :add_show_id');
+ $stmt->execute([
':add_show_duration' => $p_data['add_show_duration'],
- ':add_show_id' => $p_data['add_show_id']
- ));
+ ':add_show_id' => $p_data['add_show_id'],
+ ]);
-
- $sql = << :timestamp::TIMESTAMP
SQL;
-
- Application_Common_Database::prepareAndExecute( $sql, array(
+
+ Application_Common_Database::prepareAndExecute($sql, [
':add_show_duration' => $p_data['add_show_duration'],
':show_id' => $p_data['add_show_id'],
- ':timestamp' => $timestamp), "execute");
+ ':timestamp' => $timestamp, ], 'execute');
}
- public function getDuration($format=false)
+ public function getDuration($format = false)
{
$showDay = CcShowDaysQuery::create()->filterByDbShowId($this->getId())->findOne();
if (!$format) {
return $showDay->getDbDuration();
- } else {
- $info = explode(':',$showDay->getDbDuration());
-
- return str_pad(intval($info[0]),2,'0',STR_PAD_LEFT).'h '.str_pad(intval($info[1]),2,'0',STR_PAD_LEFT).'m';
}
+ $info = explode(':', $showDay->getDbDuration());
+
+ return str_pad(intval($info[0]), 2, '0', STR_PAD_LEFT) . 'h ' . str_pad(intval($info[1]), 2, '0', STR_PAD_LEFT) . 'm';
}
public function getShowDays()
{
$showDays = CcShowDaysQuery::create()->filterByDbShowId(
- $this->getId())->find();
- $res = array();
+ $this->getId()
+ )->find();
+ $res = [];
foreach ($showDays as $showDay) {
$res[] = $showDay->getDbDay();
}
+
return $res;
}
@@ -793,7 +836,7 @@ SQL;
* @return Boolean: true if show has an instance, otherwise false. */
public function hasInstance()
{
- return (!is_null($this->getInstance()));
+ return !is_null($this->getInstance());
}
/* Only used for shows that aren't repeating.
@@ -802,30 +845,29 @@ SQL;
* row in the cc_show_instances table. */
public function getInstance()
{
- $showInstance = CcShowInstancesQuery::create()
+ return CcShowInstancesQuery::create()
->filterByDbShowId($this->getId())
- ->findOne();
-
- return $showInstance;
+ ->findOne()
+ ;
}
/**
- * returns info about live stream override info
+ * returns info about live stream override info.
*/
public function getLiveStreamInfo()
{
- $info = array();
+ $info = [];
if ($this->getId() == null) {
return $info;
- } else {
- $ccShow = CcShowQuery::create()->findPK($this->_showId);
- $info['custom_username'] = $ccShow->getDbLiveStreamUser();
- $info['cb_airtime_auth'] = $ccShow->getDbLiveStreamUsingAirtimeAuth();
- $info['cb_custom_auth'] = $ccShow->getDbLiveStreamUsingCustomAuth();
- $info['custom_username'] = $ccShow->getDbLiveStreamUser();
- $info['custom_password'] = $ccShow->getDbLiveStreamPass();
- return $info;
}
+ $ccShow = CcShowQuery::create()->findPK($this->_showId);
+ $info['custom_username'] = $ccShow->getDbLiveStreamUser();
+ $info['cb_airtime_auth'] = $ccShow->getDbLiveStreamUsingAirtimeAuth();
+ $info['cb_custom_auth'] = $ccShow->getDbLiveStreamUsingCustomAuth();
+ $info['custom_username'] = $ccShow->getDbLiveStreamUser();
+ $info['custom_password'] = $ccShow->getDbLiveStreamPass();
+
+ return $info;
}
/* Only used for shows that are repeating. Note that this will return
@@ -840,7 +882,7 @@ SQL;
* otherwise false. */
public function hasInstanceOnDate($p_dateTime)
{
- return (!is_null($this->getInstanceOnDate($p_dateTime)));
+ return !is_null($this->getInstanceOnDate($p_dateTime));
}
/* Only used for shows that are repeating. Note that this will return
@@ -854,43 +896,50 @@ SQL;
public function getInstanceOnDate($p_dateTime)
{
$timestamp = $p_dateTime->format(DEFAULT_TIMESTAMP_FORMAT);
- $sql = << $this->getId(),
- ':timestamp' => $timestamp ), 'column');
+ $row = Application_Common_Database::prepareAndExecute(
+ $sql,
+ [':showId' => $this->getId(),
+ ':timestamp' => $timestamp, ],
+ 'column'
+ );
+
return CcShowInstancesQuery::create()
- ->findPk($row);
+ ->findPk($row)
+ ;
} catch (Exception $e) {
return null;
}
-
}
-
+
/**
- *
* Creates show instances that are scheduled after the shows_populated_until
* value in cc_pref. If the show instances are linked their show content will
* get filled.
- *
+ *
* This can occur when a user is viewing the next day/week/month in the
* calendar or when pypo is requesting the schedule after the shows_populated_until
* date and time.
+ *
+ * @param mixed $needScheduleUntil
*/
public static function createAndFillShowInstancesPastPopulatedUntilDate($needScheduleUntil)
{
$con = Propel::getConnection(CcPrefPeer::DATABASE_NAME);
+
try {
$con->beginTransaction();
//It is extremely important that we increase the transaction isolation level, so that if two
//requests cause the show schedule to be generated at the same time, one will be rolled back.
- $con->exec("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
+ $con->exec('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE');
//UTC DateTime object
$showsPopUntil = Application_Model_Preference::GetShowsPopulatedUntil();
@@ -904,30 +953,30 @@ SQL;
} catch (Exception $e) {
$con->rollBack();
//throw $e;
- Logging::warn("Did not create show instances due to transaction error. This is usually safe
- and caused by two concurrent transactions. " . $e->getMessage());
+ Logging::warn('Did not create show instances due to transaction error. This is usually safe
+ and caused by two concurrent transactions. ' . $e->getMessage());
}
-
}
/**
* Get all the show instances in the given time range (inclusive).
*
- * @param DateTime $start_timestamp
- * In UTC time.
- * @param DateTime $end_timestamp
- * In UTC time.
- * @param unknown_type $excludeInstance
- * @param boolean $onlyRecord
- * @param int $showId
- * limits the results to instances of a given showId only
+ * @param dateTime $start_timestamp
+ * In UTC time
+ * @param dateTime $end_timestamp
+ * In UTC time
+ * @param unknown_type $excludeInstance
+ * @param bool $onlyRecord
+ * @param int $showId
+ * limits the results to instances of a given showId only
+ *
* @return array
*/
- public static function getShows($start_timestamp, $end_timestamp, $onlyRecord=FALSE, $showId=null)
+ public static function getShows($start_timestamp, $end_timestamp, $onlyRecord = false, $showId = null)
{
self::createAndFillShowInstancesPastPopulatedUntilDate($end_timestamp);
- $sql = <<format(DEFAULT_TIMESTAMP_FORMAT);
$end_string = $end_timestamp->format(DEFAULT_TIMESTAMP_FORMAT);
- $params = array();
+ $params = [];
if ($showId) {
- $sql .= " AND (si1.show_id = :show_id)";
- $params[':show_id'] = $showId;
+ $sql .= ' AND (si1.show_id = :show_id)';
+ $params[':show_id'] = $showId;
}
if ($onlyRecord) {
- $sql .= " AND (si1.starts >= :start::TIMESTAMP AND si1.starts < :end::TIMESTAMP)";
- $sql .= " AND (si1.record = 1)";
+ $sql .= ' AND (si1.starts >= :start::TIMESTAMP AND si1.starts < :end::TIMESTAMP)';
+ $sql .= ' AND (si1.record = 1)';
$params[':start'] = $start_string;
$params[':end'] = $end_string;
- return Application_Common_Database::prepareAndExecute( $sql, $params, 'all');
- } else {
- $sql .= " ". <<= :start1::TIMESTAMP AND si1.starts < :end1::TIMESTAMP)
OR (si1.ends > :start2::TIMESTAMP AND si1.ends <= :end2::TIMESTAMP)
OR (si1.starts <= :start3::TIMESTAMP AND si1.ends >= :end3::TIMESTAMP))
ORDER BY si1.starts
SQL;
- $params = array_merge($params, array(
- 'start1' => $start_string,
- 'start2' => $start_string,
- 'start3' => $start_string,
- 'end1' => $end_string,
- 'end2' => $end_string,
- 'end3' => $end_string
- )
- );
- return Application_Common_Database::prepareAndExecute( $sql, $params, 'all');
- }
+ $params = array_merge(
+ $params,
+ [
+ 'start1' => $start_string,
+ 'start2' => $start_string,
+ 'start3' => $start_string,
+ 'end1' => $end_string,
+ 'end2' => $end_string,
+ 'end3' => $end_string,
+ ]
+ );
+
+ return Application_Common_Database::prepareAndExecute($sql, $params, 'all');
}
private static function setNextPop($next_date, $show_id, $day)
{
- $nextInfo = explode(" ", $next_date);
+ $nextInfo = explode(' ', $next_date);
$repeatInfo = CcShowDaysQuery::create()
->filterByDbShowId($show_id)
->filterByDbDay($day)
- ->findOne();
+ ->findOne()
+ ;
$repeatInfo->setDbNextPopDate($nextInfo[0])
- ->save();
+ ->save()
+ ;
}
/**
- *
* @param DateTime $start
- * -in UTC time
+ * -in UTC time
* @param DateTime $end
- * -in UTC time
- * @param boolean $editable
+ * -in UTC time
+ * @param bool $editable
+ * @param mixed $p_start
+ * @param mixed $p_end
+ * @param mixed $p_editable
*/
- public static function &getFullCalendarEvents($p_start, $p_end, $p_editable=false)
+ public static function &getFullCalendarEvents($p_start, $p_end, $p_editable = false)
{
- $events = array();
+ $events = [];
$interval = $p_start->diff($p_end);
- $days = $interval->format('%a');
- $shows = Application_Model_Show::getShows($p_start, $p_end);
+ $days = $interval->format('%a');
+ $shows = Application_Model_Show::getShows($p_start, $p_end);
$content_count = Application_Model_ShowInstance::getContentCount(
- $p_start, $p_end);
+ $p_start,
+ $p_end
+ );
$isFull = Application_Model_ShowInstance::getIsFull($p_start, $p_end);
$hasAutoPlaylist = Application_Model_ShowInstance::getShowHasAutoplaylist($p_start, $p_end);
$displayTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
- $utcTimezone = new DateTimeZone("UTC");
- $now = new DateTime("now", $utcTimezone);
+ $utcTimezone = new DateTimeZone('UTC');
+ $now = new DateTime('now', $utcTimezone);
foreach ($shows as &$show) {
- $options = array();
+ $options = [];
- $options["percent"] = Application_Model_Show::getPercentScheduled($show["starts"], $show["ends"], $show["time_filled"]);
+ $options['percent'] = Application_Model_Show::getPercentScheduled($show['starts'], $show['ends'], $show['time_filled']);
- if (isset($show["parent_starts"])) {
- $parentStartsDT = new DateTime($show["parent_starts"], $utcTimezone);
+ if (isset($show['parent_starts'])) {
+ $parentStartsDT = new DateTime($show['parent_starts'], $utcTimezone);
}
- $startsDT = DateTime::createFromFormat("Y-m-d G:i:s",
- $show["starts"], $utcTimezone);
- $endsDT = DateTime::createFromFormat("Y-m-d G:i:s",
- $show["ends"], $utcTimezone);
+ $startsDT = DateTime::createFromFormat(
+ 'Y-m-d G:i:s',
+ $show['starts'],
+ $utcTimezone
+ );
+ $endsDT = DateTime::createFromFormat(
+ 'Y-m-d G:i:s',
+ $show['ends'],
+ $utcTimezone
+ );
- if( $p_editable ) {
- if ($show["record"] && $now > $startsDT) {
- $options["editable"] = false;
- } elseif ($show["rebroadcast"] &&
- $now > $parentStartsDT) {
- $options["editable"] = false;
+ if ($p_editable) {
+ if ($show['record'] && $now > $startsDT) {
+ $options['editable'] = false;
+ } elseif ($show['rebroadcast']
+ && $now > $parentStartsDT) {
+ $options['editable'] = false;
} elseif ($now < $endsDT) {
- $options["editable"] = true;
+ $options['editable'] = true;
}
}
$startsDT->setTimezone($displayTimezone);
$endsDT->setTimezone($displayTimezone);
- $options["show_empty"] = (array_key_exists($show['instance_id'],
- $content_count)) ? 0 : 1;
+ $options['show_empty'] = (array_key_exists(
+ $show['instance_id'],
+ $content_count
+ )) ? 0 : 1;
if (array_key_exists($show['instance_id'], $isFull)) {
- $options["show_partial_filled"] = !$isFull[$show['instance_id']];
+ $options['show_partial_filled'] = !$isFull[$show['instance_id']];
} else {
- $options["show_partial_filled"] = true;
+ $options['show_partial_filled'] = true;
}
if (array_key_exists($show['instance_id'], $hasAutoPlaylist)) {
- $options["show_has_auto_playlist"] = true;
+ $options['show_has_auto_playlist'] = true;
} else {
- $options["show_has_auto_playlist"] = false;
+ $options['show_has_auto_playlist'] = false;
}
- $event = array();
+ $event = [];
+
+ $event['id'] = intval($show['instance_id']);
+ $event['title'] = $show['name'];
+ $event['start'] = $startsDT->format(DEFAULT_TIMESTAMP_FORMAT);
+ $event['end'] = $endsDT->format(DEFAULT_TIMESTAMP_FORMAT);
+ $event['allDay'] = false;
+ $event['showId'] = intval($show['show_id']);
+ $event['linked'] = intval($show['linked']);
+ $event['record'] = intval($show['record']);
+ $event['rebroadcast'] = intval($show['rebroadcast']);
- $event["id"] = intval($show["instance_id"]);
- $event["title"] = $show["name"];
- $event["start"] = $startsDT->format(DEFAULT_TIMESTAMP_FORMAT);
- $event["end"] = $endsDT->format(DEFAULT_TIMESTAMP_FORMAT);
- $event["allDay"] = false;
- $event["showId"] = intval($show["show_id"]);
- $event["linked"] = intval($show["linked"]);
- $event["record"] = intval($show["record"]);
- $event["rebroadcast"] = intval($show["rebroadcast"]);
-
//for putting the now playing icon on the show.
if ($now > $startsDT && $now < $endsDT) {
- $event["nowPlaying"] = true;
- }
- else {
- $event["nowPlaying"] = false;
- }
-
- if (!empty($show["background_color"])) {
- $event["color"] = "#" . $show["background_color"];
+ $event['nowPlaying'] = true;
} else {
- $event["color"] = "#" . self::getDefaultBackgroundColor($startsDT);//DEFAULT_SHOW_COLOR;
+ $event['nowPlaying'] = false;
}
+ if (!empty($show['background_color'])) {
+ $event['color'] = '#' . $show['background_color'];
+ } else {
+ $event['color'] = '#' . self::getDefaultBackgroundColor($startsDT); //DEFAULT_SHOW_COLOR;
+ }
//event colouring
- if ($show["color"] != "") {
- $event["textColor"] = "#".$show["color"];
+ if ($show['color'] != '') {
+ $event['textColor'] = '#' . $show['color'];
} else {
- $bg = $event["color"];
+ $bg = $event['color'];
//Calculate the text colour (black or white) based on the brightness of the background.
$r = intval(substr($bg, 1, 2), 16);
$g = intval(substr($bg, 3, 2), 16);
$b = intval(substr($bg, 5, 2), 16);
- $brightness = 0.299*floatval($r) + 0.587*floatval($g) + 0.114*floatval($b);
+ $brightness = 0.299 * floatval($r) + 0.587 * floatval($g) + 0.114 * floatval($b);
if ($brightness > 130) {
- $event["textColor"] = "#000000";
+ $event['textColor'] = '#000000';
} else {
- $event["textColor"] = "#fcfcfc";
+ $event['textColor'] = '#fcfcfc';
}
}
-
foreach ($options as $key => $value) {
$event[$key] = $value;
}
$events[] = $event;
}
+
return $events;
}
/** Get a palettized colour for the show. */
- private static function getDefaultBackgroundColor($date) {
-
+ private static function getDefaultBackgroundColor($date)
+ {
$basePalette = ['A22BE8', '2FFF8D', 'FF743C', '2ED4FF', 'E8D82B'];
// 'B23F11', 'FF7E4A', 'FF6C31'
@@ -1134,7 +1197,7 @@ SQL;
['4264d5', '566fbd', '6576ab', '7b8193']];
*/
$palette = [];
- for ($baseColorIdx = 0; $baseColorIdx < count($basePalette); $baseColorIdx++) {
+ for ($baseColorIdx = 0; $baseColorIdx < count($basePalette); ++$baseColorIdx) {
$dayPalette = [];
for ($shade = 0.0; $shade < 0.8; $shade += 0.1) {
$origColour = $basePalette[$baseColorIdx];
@@ -1144,7 +1207,7 @@ SQL;
$r = floatval($r) * (1.0 - $shade);
$g = floatval($g) * (1.0 - $shade);
$b = floatval($b) * (1.0 - $shade);
- $color = sprintf("%02x%02x%02x", $r, $g, $b);
+ $color = sprintf('%02x%02x%02x', $r, $g, $b);
array_push($dayPalette, $color);
}
array_push($palette, $dayPalette);
@@ -1153,30 +1216,34 @@ SQL;
//$hashValue = (md5($date->format('d'))[0] % $cols) + ((intval($date->format('h'))/24) % $rows);
$row = intval($date->format('w')) % sizeof($palette);
$foo = $date->format('H');
- $col = intval(intval($date->format('H'))/24.0 * sizeof($palette[0]));
+ $col = intval(intval($date->format('H')) / 24.0 * sizeof($palette[0]));
//$color = $palette[$hashValue % sizeof($palette)];
- $color = $palette[$row][$col];
- return $color;
+ return $palette[$row][$col];
}
/**
* Calculates the percentage of a show scheduled given the start and end times in date/time format
* and the time_filled as the total time the schow is scheduled for in time format.
- *
+ *
* TODO when using propel properly this should be a method on the propel show instance model.
- **/
+ *
+ * @param mixed $p_starts
+ * @param mixed $p_ends
+ * @param mixed $p_time_filled
+ */
private static function getPercentScheduled($p_starts, $p_ends, $p_time_filled)
{
- $utcTimezone = new DatetimeZone("UTC");
+ $utcTimezone = new DatetimeZone('UTC');
$startDt = new DateTime($p_starts, $utcTimezone);
$endDt = new DateTime($p_ends, $utcTimezone);
- $durationSeconds = intval($endDt->format("U")) - intval($startDt->format("U"));
+ $durationSeconds = intval($endDt->format('U')) - intval($startDt->format('U'));
$time_filled = Application_Common_DateHelper::playlistTimeToSeconds($p_time_filled);
if ($durationSeconds != 0) { //Prevent division by zero if the show duration somehow becomes zero.
- $percent = ceil(( $time_filled / $durationSeconds) * 100);
+ $percent = ceil(($time_filled / $durationSeconds) * 100);
} else {
$percent = 0;
}
+
return $percent;
}
@@ -1184,17 +1251,18 @@ SQL;
* Given time $timeNow, returns the show being played right now.
* Times are all in UTC time.
*
- * @param String $timeNow - current time (in UTC)
- * @return array - show being played right now
+ * @param string $timeNow - current time (in UTC)
+ *
+ * @return array - show being played right now
*/
- public static function getCurrentShow($timeNow=null)
+ public static function getCurrentShow($timeNow = null)
{
$con = Propel::getConnection();
if ($timeNow == null) {
$timeNow = gmdate(DEFAULT_TIMESTAMP_FORMAT);
}
//TODO, returning starts + ends twice (once with an alias). Unify this after the 2.0 release. --Martin
- $sql = <<fetchAll();
} else {
$msg = implode(',', $stmt->errorInfo());
- throw new Exception("Error: $msg");
+
+ throw new Exception("Error: {$msg}");
}
return $rows;
@@ -1233,24 +1302,27 @@ SQL;
/**
* 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.
+ *
+ * @param $utcNow A DateTime object containing the current time in UTC
+ * @param mixed $utcEndStr
+ * @param mixed $showsToRetrieve
+ *
+ * @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");
+ $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
+ // 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 = <<prepare($sql);
-
+
$utcNowStr = $utcNow->format(DEFAULT_TIMESTAMP_FORMAT);
$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");
+
+ throw new Exception("Error: {$msg}");
}
$numberOfRows = count($rows);
- $results['previousShow'] = array();
- $results['currentShow'] = null;
- $results['nextShow'] = array();
+ $results['previousShow'] = [];
+ $results['currentShow'] = null;
+ $results['nextShow'] = [];
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);
-
+ $showEndTime = new DateTime($rows[$i]['ends'], $timeZone);
+
// Find the show that is within the current time.
- if (($showStartTime <= $utcNow) && ($showEndTime > $utcNow)) {
+ if (($showStartTime <= $utcNow) && ($showEndTime > $utcNow)) {
$results['currentShow'] = $rows[$i];
- } else if ($showEndTime < $utcNow ) {
+ } elseif ($showEndTime < $utcNow) {
array_push($results['previousShow'], $rows[$i]);
- } else if ($showStartTime > $utcNow) {
+ } elseif ($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.
*
- * @param $utcNow A DateTime object containing the current time in UTC.
+ * @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.
+ * current show id, and next show id
+ *
* @deprecated
*/
public static function getPrevCurrentNextOld($utcNow)
{
- $timeZone = new DateTimeZone("UTC"); //This function works entirely in UTC.
- assert(get_class($utcNow) === "DateTime");
+ $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();
//TODO, returning starts + ends twice (once with an alias). Unify this after the 2.0 release. --Martin
- $sql = <<prepare($sql);
-
+
$utcNowStr = $utcNow->format(DEFAULT_TIMESTAMP_FORMAT);
$stmt->bindValue(':timeNow1', $utcNowStr);
$stmt->bindValue(':timeNow2', $utcNowStr);
-
+
if ($stmt->execute()) {
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
$msg = implode(',', $stmt->errorInfo());
- throw new Exception("Error: $msg");
+
+ throw new Exception("Error: {$msg}");
}
-
+
$numberOfRows = count($rows);
-
- $results['previousShow'] = array();
- $results['currentShow'] = array();
- $results['nextShow'] = array();
-
+
+ $results['previousShow'] = [];
+ $results['currentShow'] = [];
+ $results['nextShow'] = [];
+
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);
-
+ $showEndTime = new DateTime($rows[$i]['ends'], $timeZone);
+
//Find the show that is within the current time.
- if (($showStartTime <= $utcNow) && ($showEndTime > $utcNow))
- {
- if ($i-1 >= 0) {
- $results['previousShow'][0] = array(
- "id" => $rows[$i-1]['id'],
- "instance_id" => $rows[$i-1]['instance_id'],
- "name" => $rows[$i-1]['name'],
- "description" => $rows[$i-1]['description'],
- "url" => $rows[$i-1]['url'],
- "start_timestamp" => $rows[$i-1]['start_timestamp'],
- "end_timestamp" => $rows[$i-1]['end_timestamp'],
- "starts" => $rows[$i-1]['starts'],
- "ends" => $rows[$i-1]['ends'],
- "record" => $rows[$i-1]['record'],
- "image_path" => $rows[$i-1]['image_path'],
- "type" => "show");
+ if (($showStartTime <= $utcNow) && ($showEndTime > $utcNow)) {
+ if ($i - 1 >= 0) {
+ $results['previousShow'][0] = [
+ 'id' => $rows[$i - 1]['id'],
+ 'instance_id' => $rows[$i - 1]['instance_id'],
+ 'name' => $rows[$i - 1]['name'],
+ 'description' => $rows[$i - 1]['description'],
+ 'url' => $rows[$i - 1]['url'],
+ 'start_timestamp' => $rows[$i - 1]['start_timestamp'],
+ 'end_timestamp' => $rows[$i - 1]['end_timestamp'],
+ 'starts' => $rows[$i - 1]['starts'],
+ 'ends' => $rows[$i - 1]['ends'],
+ 'record' => $rows[$i - 1]['record'],
+ 'image_path' => $rows[$i - 1]['image_path'],
+ 'type' => 'show', ];
}
-
- $results['currentShow'][0] = $rows[$i];
-
- if (isset($rows[$i+1])) {
- $results['nextShow'][0] = array(
- "id" => $rows[$i+1]['id'],
- "instance_id" => $rows[$i+1]['instance_id'],
- "name" => $rows[$i+1]['name'],
- "description" => $rows[$i+1]['description'],
- "url" => $rows[$i+1]['url'],
- "start_timestamp" => $rows[$i+1]['start_timestamp'],
- "end_timestamp" => $rows[$i+1]['end_timestamp'],
- "starts" => $rows[$i+1]['starts'],
- "ends" => $rows[$i+1]['ends'],
- "record" => $rows[$i+1]['record'],
- "image_path" => $rows[$i+1]['image_path'],
- "type" => "show");
+
+ $results['currentShow'][0] = $rows[$i];
+
+ if (isset($rows[$i + 1])) {
+ $results['nextShow'][0] = [
+ 'id' => $rows[$i + 1]['id'],
+ 'instance_id' => $rows[$i + 1]['instance_id'],
+ 'name' => $rows[$i + 1]['name'],
+ 'description' => $rows[$i + 1]['description'],
+ 'url' => $rows[$i + 1]['url'],
+ 'start_timestamp' => $rows[$i + 1]['start_timestamp'],
+ 'end_timestamp' => $rows[$i + 1]['end_timestamp'],
+ 'starts' => $rows[$i + 1]['starts'],
+ 'ends' => $rows[$i + 1]['ends'],
+ 'record' => $rows[$i + 1]['record'],
+ 'image_path' => $rows[$i + 1]['image_path'],
+ 'type' => 'show', ];
}
+
break;
}
//Previous is any row that ends after time now capture it in case we need it later.
- if ($showEndTime < $utcNow ) {
+ if ($showEndTime < $utcNow) {
$previousShowIndex = $i;
}
//if we hit this we know we've gone to far and can stop looping.
if ($showStartTime > $utcNow) {
- $results['nextShow'][0] = array(
- "id" => $rows[$i]['id'],
- "instance_id" => $rows[$i]['instance_id'],
- "name" => $rows[$i]['name'],
- "description" => $rows[$i]['description'],
- "url" => $rows[$i]['url'],
- "start_timestamp" => $rows[$i]['start_timestamp'],
- "end_timestamp" => $rows[$i]['end_timestamp'],
- "starts" => $rows[$i]['starts'],
- "ends" => $rows[$i]['ends'],
- "record" => $rows[$i]['record'],
- "image_path" => $rows[$i]['image_path'],
- "type" => "show");
+ $results['nextShow'][0] = [
+ 'id' => $rows[$i]['id'],
+ 'instance_id' => $rows[$i]['instance_id'],
+ 'name' => $rows[$i]['name'],
+ 'description' => $rows[$i]['description'],
+ 'url' => $rows[$i]['url'],
+ 'start_timestamp' => $rows[$i]['start_timestamp'],
+ 'end_timestamp' => $rows[$i]['end_timestamp'],
+ 'starts' => $rows[$i]['starts'],
+ 'ends' => $rows[$i]['ends'],
+ 'record' => $rows[$i]['record'],
+ 'image_path' => $rows[$i]['image_path'],
+ 'type' => 'show', ];
+
break;
}
}
//If we didn't find a a current show because the time didn't fit we may still have
//found a previous show so use it.
if (count($results['previousShow']) == 0 && isset($previousShowIndex)) {
- $results['previousShow'][0] = array(
- "id" => $rows[$previousShowIndex]['id'],
- "instance_id" => $rows[$previousShowIndex]['instance_id'],
- "name" => $rows[$previousShowIndex]['name'],
- "description" => $rows[$previousShowIndex]['description'],
- "start_timestamp" => $rows[$previousShowIndex]['start_timestamp'],
- "end_timestamp" => $rows[$previousShowIndex]['end_timestamp'],
- "starts" => $rows[$previousShowIndex]['starts'],
- "ends" => $rows[$previousShowIndex]['ends'],
- "record" => $rows[$previousShowIndex]['record'],
- "type" => "show");
+ $results['previousShow'][0] = [
+ 'id' => $rows[$previousShowIndex]['id'],
+ 'instance_id' => $rows[$previousShowIndex]['instance_id'],
+ 'name' => $rows[$previousShowIndex]['name'],
+ 'description' => $rows[$previousShowIndex]['description'],
+ 'start_timestamp' => $rows[$previousShowIndex]['start_timestamp'],
+ 'end_timestamp' => $rows[$previousShowIndex]['end_timestamp'],
+ 'starts' => $rows[$previousShowIndex]['starts'],
+ 'ends' => $rows[$previousShowIndex]['ends'],
+ 'record' => $rows[$previousShowIndex]['record'],
+ 'type' => 'show', ];
}
-
+
return $results;
}
@@ -1469,21 +1546,22 @@ SQL;
* If $limit not given, all shows within the intervals are returned
* Times are all in UTC time.
*
- * @param String $timeStart - interval start time (in UTC)
- * @param int $limit - number of shows to return
- * @param String $timeEnd - interval end time (in UTC)
- * @return array - the next $limit number of shows within the time interval
+ * @param string $timeStart - interval start time (in UTC)
+ * @param int $limit - number of shows to return
+ * @param string $timeEnd - interval end time (in UTC)
+ *
+ * @return array - the next $limit number of shows within the time interval
*/
- public static function getNextShows($timeStart, $limit = "ALL", $timeEnd = "")
+ public static function getNextShows($timeStart, $limit = 'ALL', $timeEnd = '')
{
// defaults to retrieving shows from next 2 days if no end time has
// been specified
- if ($timeEnd == "") {
- $timeEnd = "'$timeStart' + INTERVAL '2 days'";
+ if ($timeEnd == '') {
+ $timeEnd = "'{$timeStart}' + INTERVAL '2 days'";
}
//TODO, returning starts + ends twice (once with an alias). Unify this after the 2.0 release. --Martin
- $sql = << $timeStart,
- ':timeEnd' => $timeEnd,
- ':lim' => $limit);
+ if ($limit != 'ALL') {
+ $sql .= PHP_EOL . 'LIMIT :lim';
+ $params = [
+ ':timeStart' => $timeStart,
+ ':timeEnd' => $timeEnd,
+ ':lim' => $limit, ];
} else {
- $params = array(
- ':timeStart' => $timeStart,
- ':timeEnd' => $timeEnd);
+ $params = [
+ ':timeStart' => $timeStart,
+ ':timeEnd' => $timeEnd, ];
}
- return Application_Common_Database::prepareAndExecute( $sql, $params, 'all');
+ return Application_Common_Database::prepareAndExecute($sql, $params, 'all');
}
public static function getMaxLengths()
{
- $sql = << 0
SQL;
- $result = Application_Common_Database::prepareAndExecute($sql);
- $assocArray = array();
+ $result = Application_Common_Database::prepareAndExecute($sql);
+ $assocArray = [];
foreach ($result as $row) {
$assocArray[$row['column_name']] = $row['character_maximum_length'];
}
+
return $assocArray;
}
- public static function getStartEndCurrentMonthView() {
-
- $utcTimeZone = new DateTimeZone("UTC");
+ public static function getStartEndCurrentMonthView()
+ {
+ $utcTimeZone = new DateTimeZone('UTC');
//We have to get the start of the day in the user's timezone, and then convert that to UTC.
- $start = new DateTime("first day of this month", new DateTimeZone(Application_Model_Preference::GetUserTimezone()));
+ $start = new DateTime('first day of this month', new DateTimeZone(Application_Model_Preference::GetUserTimezone()));
$start->setTimezone($utcTimeZone); //Covert it to UTC.
- $monthInterval = new DateInterval("P1M");
- $end = clone($start);
+ $monthInterval = new DateInterval('P1M');
+ $end = clone $start;
$end->add($monthInterval);
- return array($start, $end);
+ return [$start, $end];
}
/** Returns the start and end date that FullCalendar will display for today's month.
@@ -1558,53 +1637,53 @@ SQL;
* FullCalendar displays 6 weeks, starting on a Sunday, for a total of 42 days. This function returns 42 days worth
* of data (a few days before, and a few days after.)
*/
- public static function getStartEndCurrentMonthPlusView() {
-
- $utcTimeZone = new DateTimeZone("UTC");
+ public static function getStartEndCurrentMonthPlusView()
+ {
+ $utcTimeZone = new DateTimeZone('UTC');
//We have to get the start of the day in the user's timezone, and then convert that to UTC.
- $start = new DateTime("first day of this month", new DateTimeZone(Application_Model_Preference::GetUserTimezone()));
+ $start = new DateTime('first day of this month', new DateTimeZone(Application_Model_Preference::GetUserTimezone()));
$dayOfWeekNumeric = $start->format('w');
$start->sub(new DateInterval("P{$dayOfWeekNumeric}D")); //Subtract the index of the day of the week the month starts on. (adds this many days from the previous month)
$start->setTimezone($utcTimeZone); //Covert it to UTC.
- $fullCalendarMonthInterval = new DateInterval("P42D"); //42 days
- $end = clone($start);
+ $fullCalendarMonthInterval = new DateInterval('P42D'); //42 days
+ $end = clone $start;
$end->add($fullCalendarMonthInterval);
- return array($start, $end);
+ return [$start, $end];
}
-
- public static function getStartEndCurrentWeekView() {
-
+ public static function getStartEndCurrentWeekView()
+ {
$weekStartDayNum = Application_Model_Preference::GetWeekStartDay();
- $utcTimeZone = new DateTimeZone("UTC");
+ $utcTimeZone = new DateTimeZone('UTC');
//We have to get the start of the week in the user's timezone, and then convert that to UTC.
- $start = new DateTime("Sunday last week", new DateTimeZone(Application_Model_Preference::GetUserTimezone()));
+ $start = new DateTime('Sunday last week', new DateTimeZone(Application_Model_Preference::GetUserTimezone()));
$start->add(new DateInterval("P{$weekStartDayNum}D")); //Shift the start date to the station's "Week Starts on Day"
$start->setTimezone($utcTimeZone); //Covert it to UTC.
- $weekInterval = new DateInterval("P1W");
- $end = clone($start);
+ $weekInterval = new DateInterval('P1W');
+ $end = clone $start;
$end->add($weekInterval);
- return array($start, $end);
+
+ return [$start, $end];
}
- public static function getStartEndCurrentDayView() {
- $utcTimeZone = new DateTimeZone("UTC");
+ public static function getStartEndCurrentDayView()
+ {
+ $utcTimeZone = new DateTimeZone('UTC');
//We have to get the start of the day in the user's timezone, and then convert that to UTC.
- $start = new DateTime("today", new DateTimeZone(Application_Model_Preference::GetUserTimezone()));
+ $start = new DateTime('today', new DateTimeZone(Application_Model_Preference::GetUserTimezone()));
$start->setTimezone($utcTimeZone); //Covert it to UTC.
- $dayInterval = new DateInterval("P1D");
- $end = clone($start);
+ $dayInterval = new DateInterval('P1D');
+ $end = clone $start;
$end->add($dayInterval);
- return array($start, $end);
+ return [$start, $end];
}
-
}
diff --git a/legacy/application/models/ShowBuilder.php b/legacy/application/models/ShowBuilder.php
index ca5b4a051..9fbee366b 100644
--- a/legacy/application/models/ShowBuilder.php
+++ b/legacy/application/models/ShowBuilder.php
@@ -18,32 +18,32 @@ class Application_Model_ShowBuilder
private $currentShow;
private $currentShowId;
- private $showInstances = array();
+ private $showInstances = [];
- private $defaultRowArray = array(
- "header" => false,
- "footer" => false,
- "empty" => false,
- "allowed" => false,
- "linked_allowed" => true,
- "id" => 0,
- "instance" => "",
- "starts" => "",
- "ends" => "",
- "runtime" => "",
- "title" => "",
- "creator" => "",
- "album" => "",
- "timestamp" => null,
- "cuein" => "",
- "cueout" => "",
- "fadein" => "",
- "fadeout" => "",
- "image" => false,
- "mime" => null,
- "color" => "", //in hex without the '#' sign.
- "backgroundColor" => "", //in hex without the '#' sign.
- );
+ private $defaultRowArray = [
+ 'header' => false,
+ 'footer' => false,
+ 'empty' => false,
+ 'allowed' => false,
+ 'linked_allowed' => true,
+ 'id' => 0,
+ 'instance' => '',
+ 'starts' => '',
+ 'ends' => '',
+ 'runtime' => '',
+ 'title' => '',
+ 'creator' => '',
+ 'album' => '',
+ 'timestamp' => null,
+ 'cuein' => '',
+ 'cueout' => '',
+ 'fadein' => '',
+ 'fadeout' => '',
+ 'image' => false,
+ 'mime' => null,
+ 'color' => '', //in hex without the '#' sign.
+ 'backgroundColor' => '', //in hex without the '#' sign.
+ ];
/*
* @param DateTime $p_startsDT
@@ -62,12 +62,13 @@ class Application_Model_ShowBuilder
private function getUsersShows()
{
- $shows = array();
+ $shows = [];
$host_shows = CcShowHostsQuery::create()
->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)
->filterByDbHost($this->user->getId())
- ->find();
+ ->find()
+ ;
foreach ($host_shows as $host_show) {
$shows[] = $host_show->getDbShow();
@@ -80,60 +81,60 @@ class Application_Model_ShowBuilder
private function isAllowed($p_item, &$row)
{
//cannot schedule in a recorded show.
- if (intval($p_item["si_record"]) === 1) {
+ if (intval($p_item['si_record']) === 1) {
return;
}
if ($this->currentShow) {
- $this->currentShowId = $p_item["show_id"];
+ $this->currentShowId = $p_item['show_id'];
}
/* If any linked show instance is currently playing
* we have to disable editing, or else the times
* will not make sense for shows scheduled in the future
*/
- if ($p_item["linked"] && $p_item["show_id"] == $this->currentShowId) {
- $row["linked_allowed"] = false;
+ if ($p_item['linked'] && $p_item['show_id'] == $this->currentShowId) {
+ $row['linked_allowed'] = false;
}
- if ($this->user->canSchedule($p_item["show_id"]) == true) {
- $row["allowed"] = true;
+ if ($this->user->canSchedule($p_item['show_id']) == true) {
+ $row['allowed'] = true;
}
}
private function getItemColor($p_item, &$row)
{
- $defaultColor = "ffffff";
+ $defaultColor = 'ffffff';
$defaultBackground = DEFAULT_SHOW_COLOR;
- $color = $p_item["show_color"];
+ $color = $p_item['show_color'];
if ($color === '') {
$color = $defaultColor;
}
- $backgroundColor = $p_item["show_background_color"];
+ $backgroundColor = $p_item['show_background_color'];
if ($backgroundColor === '') {
$backgroundColor = $defaultBackground;
}
- $row["color"] = $color;
- $row["backgroundColor"] = $backgroundColor;
+ $row['color'] = $color;
+ $row['backgroundColor'] = $backgroundColor;
}
//information about whether a track is inside|boundary|outside a show.
private function getItemStatus($p_item, &$row)
{
- $row["status"] = intval($p_item["playout_status"]);
+ $row['status'] = intval($p_item['playout_status']);
}
private function getRowTimestamp($p_item, &$row)
{
- if (is_null($p_item["si_last_scheduled"])) {
+ if (is_null($p_item['si_last_scheduled'])) {
$ts = 0;
} else {
- $dt = new DateTime($p_item["si_last_scheduled"], new DateTimeZone("UTC"));
- $ts = intval($dt->format("U"));
+ $dt = new DateTime($p_item['si_last_scheduled'], new DateTimeZone('UTC'));
+ $ts = intval($dt->format('U'));
}
- $row["timestamp"] = $ts;
+ $row['timestamp'] = $ts;
}
/*
@@ -145,39 +146,39 @@ class Application_Model_ShowBuilder
*/
private function getScheduledStatus($p_epochItemStart, $p_epochItemEnd, &$row)
{
- if ($row["footer"] === true && $this->epoch_now > $p_epochItemStart &&
- $this->epoch_now > $p_epochItemEnd) {
- $row["scheduled"] = 0;
- } elseif ($row["footer"] === true && $this->epoch_now < $p_epochItemEnd) {
- $row["scheduled"] = 2;
- } elseif ($row["header"] === true && $this->epoch_now >= $p_epochItemStart) {
- $row["scheduled"] = 0;
- } elseif ($row["header"] === true && $this->epoch_now < $p_epochItemEnd) {
- $row["scheduled"] = 2;
+ if ($row['footer'] === true && $this->epoch_now > $p_epochItemStart
+ && $this->epoch_now > $p_epochItemEnd) {
+ $row['scheduled'] = 0;
+ } elseif ($row['footer'] === true && $this->epoch_now < $p_epochItemEnd) {
+ $row['scheduled'] = 2;
+ } elseif ($row['header'] === true && $this->epoch_now >= $p_epochItemStart) {
+ $row['scheduled'] = 0;
+ } elseif ($row['header'] === true && $this->epoch_now < $p_epochItemEnd) {
+ $row['scheduled'] = 2;
}
//item is in the past.
- else if ($this->epoch_now > $p_epochItemEnd) {
- $row["scheduled"] = 0;
+ elseif ($this->epoch_now > $p_epochItemEnd) {
+ $row['scheduled'] = 0;
}
//item is the currently scheduled item.
- else if ($this->epoch_now >= $p_epochItemStart && $this->epoch_now < $p_epochItemEnd) {
- $row["scheduled"] = 1;
+ elseif ($this->epoch_now >= $p_epochItemStart && $this->epoch_now < $p_epochItemEnd) {
+ $row['scheduled'] = 1;
//how many seconds the view should wait to redraw itself.
- $row["refresh"] = $p_epochItemEnd - $this->epoch_now;
+ $row['refresh'] = $p_epochItemEnd - $this->epoch_now;
}
//item is in the future.
- else if ($this->epoch_now < $p_epochItemStart) {
- $row["scheduled"] = 2;
+ elseif ($this->epoch_now < $p_epochItemStart) {
+ $row['scheduled'] = 2;
} else {
- Logging::warn("No-op? is this what should happen...printing
- debug just in case");
- $d = array(
+ Logging::warn('No-op? is this what should happen...printing
+ debug just in case');
+ $d = [
'$p_epochItemStart' => $p_epochItemStart,
- '$p_epochItemEnd' => $p_epochItemEnd,
- '$row' => $row);
+ '$p_epochItemEnd' => $p_epochItemEnd,
+ '$row' => $row, ];
Logging::warn($d);
}
}
@@ -189,30 +190,30 @@ class Application_Model_ShowBuilder
$this->getRowTimestamp($p_item, $row);
$this->getItemColor($p_item, $row);
- $showStartDT = new DateTime($p_item["si_starts"], new DateTimeZone("UTC"));
+ $showStartDT = new DateTime($p_item['si_starts'], new DateTimeZone('UTC'));
$showStartDT->setTimezone(new DateTimeZone($this->timezone));
- $startsEpoch = floatval($showStartDT->format("U.u"));
- $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC"));
+ $startsEpoch = floatval($showStartDT->format('U.u'));
+ $showEndDT = new DateTime($p_item['si_ends'], new DateTimeZone('UTC'));
$showEndDT->setTimezone(new DateTimeZone($this->timezone));
- $endsEpoch = floatval($showEndDT->format("U.u"));
+ $endsEpoch = floatval($showEndDT->format('U.u'));
//is a rebroadcast show
- if (intval($p_item["si_rebroadcast"]) === 1) {
- $row["rebroadcast"] = true;
+ if (intval($p_item['si_rebroadcast']) === 1) {
+ $row['rebroadcast'] = true;
- $parentInstance = CcShowInstancesQuery::create()->findPk($p_item["parent_show"]);
- $name = $parentInstance->getCcShow()->getDbName();
- $dt = $parentInstance->getDbStarts(null);
+ $parentInstance = CcShowInstancesQuery::create()->findPk($p_item['parent_show']);
+ $name = $parentInstance->getCcShow()->getDbName();
+ $dt = $parentInstance->getDbStarts(null);
$dt->setTimezone(new DateTimeZone($this->timezone));
- $time = $dt->format("Y-m-d H:i");
+ $time = $dt->format('Y-m-d H:i');
- $row["rebroadcast_title"] = sprintf(_("Rebroadcast of %s from %s"), $name, $time);
- } elseif (intval($p_item["si_record"]) === 1) {
- $row["record"] = true;
+ $row['rebroadcast_title'] = sprintf(_('Rebroadcast of %s from %s'), $name, $time);
+ } elseif (intval($p_item['si_record']) === 1) {
+ $row['record'] = true;
}
if ($startsEpoch < $this->epoch_now && $endsEpoch > $this->epoch_now) {
- $row["currentShow"] = true;
+ $row['currentShow'] = true;
$this->currentShow = true;
} else {
$this->currentShow = false;
@@ -220,18 +221,18 @@ class Application_Model_ShowBuilder
$this->isAllowed($p_item, $row);
- $row["header"] = true;
- $row["starts"] = $showStartDT->format("Y-m-d H:i");
- $row["startDate"] = $showStartDT->format("Y-m-d");
- $row["startTime"] = $showStartDT->format("H:i");
- $row["refresh"] = floatval($showStartDT->format("U.u")) - $this->epoch_now;
- $row["ends"] = $showEndDT->format("Y-m-d H:i");
- $row["endDate"] = $showEndDT->format("Y-m-d");
- $row["endTime"] = $showEndDT->format("H:i");
- $row["duration"] = floatval($showEndDT->format("U.u")) - floatval($showStartDT->format("U.u"));
- $row["title"] = htmlspecialchars($p_item["show_name"]);
- $row["instance"] = intval($p_item["si_id"]);
- $row["image"] = '';
+ $row['header'] = true;
+ $row['starts'] = $showStartDT->format('Y-m-d H:i');
+ $row['startDate'] = $showStartDT->format('Y-m-d');
+ $row['startTime'] = $showStartDT->format('H:i');
+ $row['refresh'] = floatval($showStartDT->format('U.u')) - $this->epoch_now;
+ $row['ends'] = $showEndDT->format('Y-m-d H:i');
+ $row['endDate'] = $showEndDT->format('Y-m-d');
+ $row['endTime'] = $showEndDT->format('H:i');
+ $row['duration'] = floatval($showEndDT->format('U.u')) - floatval($showStartDT->format('U.u'));
+ $row['title'] = htmlspecialchars($p_item['show_name']);
+ $row['instance'] = intval($p_item['si_id']);
+ $row['image'] = '';
$this->getScheduledStatus($startsEpoch, $endsEpoch, $row);
@@ -244,77 +245,80 @@ class Application_Model_ShowBuilder
{
$row = $this->defaultRowArray;
- if (isset($p_item["sched_starts"])) {
-
- $schedStartDT = new DateTime($p_item["sched_starts"],
- new DateTimeZone("UTC"));
+ if (isset($p_item['sched_starts'])) {
+ $schedStartDT = new DateTime(
+ $p_item['sched_starts'],
+ new DateTimeZone('UTC')
+ );
$schedStartDT->setTimezone(new DateTimeZone($this->timezone));
- $schedEndDT = new DateTime($p_item["sched_ends"],
- new DateTimeZone("UTC"));
+ $schedEndDT = new DateTime(
+ $p_item['sched_ends'],
+ new DateTimeZone('UTC')
+ );
$schedEndDT->setTimezone(new DateTimeZone($this->timezone));
- $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC"));
+ $showEndDT = new DateTime($p_item['si_ends'], new DateTimeZone('UTC'));
$this->getItemStatus($p_item, $row);
- $startsEpoch = floatval($schedStartDT->format("U.u"));
- $endsEpoch = floatval($schedEndDT->format("U.u"));
- $showEndEpoch = floatval($showEndDT->format("U.u"));
+ $startsEpoch = floatval($schedStartDT->format('U.u'));
+ $endsEpoch = floatval($schedEndDT->format('U.u'));
+ $showEndEpoch = floatval($showEndDT->format('U.u'));
//don't want an overbooked item to stay marked as current.
$this->getScheduledStatus($startsEpoch, min($endsEpoch, $showEndEpoch), $row);
- $row["id"] = intval($p_item["sched_id"]);
- $row["image"] = $p_item["file_exists"];
- $row["instance"] = intval($p_item["si_id"]);
- $row["starts"] = $schedStartDT->format("H:i:s");
- $row["ends"] = $schedEndDT->format("H:i:s");
-
+ $row['id'] = intval($p_item['sched_id']);
+ $row['image'] = $p_item['file_exists'];
+ $row['instance'] = intval($p_item['si_id']);
+ $row['starts'] = $schedStartDT->format('H:i:s');
+ $row['ends'] = $schedEndDT->format('H:i:s');
+
$cue_out = Application_Common_DateHelper::playlistTimeToSeconds($p_item['cue_out']);
$cue_in = Application_Common_DateHelper::playlistTimeToSeconds($p_item['cue_in']);
-
- $run_time = $cue_out-$cue_in;
-
+
+ $run_time = $cue_out - $cue_in;
+
$formatter = new LengthFormatter(Application_Common_DateHelper::secondsToPlaylistTime($run_time));
$row['runtime'] = $formatter->format();
- $row["title"] = htmlspecialchars($p_item["file_track_title"]);
- $row["creator"] = htmlspecialchars($p_item["file_artist_name"]);
- $row["album"] = htmlspecialchars($p_item["file_album_title"]);
+ $row['title'] = htmlspecialchars($p_item['file_track_title']);
+ $row['creator'] = htmlspecialchars($p_item['file_artist_name']);
+ $row['album'] = htmlspecialchars($p_item['file_album_title']);
- $row["cuein"] = $p_item["cue_in"];
- $row["cueout"] = $p_item["cue_out"];
- $row["fadein"] = round(substr($p_item["fade_in"], 6), 6);
- $row["fadeout"] = round(substr($p_item["fade_out"], 6), 6);
- $row["mime"] = $p_item["file_mime"];
+ $row['cuein'] = $p_item['cue_in'];
+ $row['cueout'] = $p_item['cue_out'];
+ $row['fadein'] = round(substr($p_item['fade_in'], 6), 6);
+ $row['fadeout'] = round(substr($p_item['fade_out'], 6), 6);
+ $row['mime'] = $p_item['file_mime'];
- $row["pos"] = $this->pos++;
+ $row['pos'] = $this->pos++;
$this->contentDT = $schedEndDT;
}
//show is empty or is a special kind of show (recording etc)
- else if (intval($p_item["si_record"]) === 1) {
- $row["record"] = true;
- $row["instance"] = intval($p_item["si_id"]);
+ elseif (intval($p_item['si_record']) === 1) {
+ $row['record'] = true;
+ $row['instance'] = intval($p_item['si_id']);
- $showStartDT = new DateTime($p_item["si_starts"], new DateTimeZone("UTC"));
- $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC"));
+ $showStartDT = new DateTime($p_item['si_starts'], new DateTimeZone('UTC'));
+ $showEndDT = new DateTime($p_item['si_ends'], new DateTimeZone('UTC'));
- $startsEpoch = floatval($showStartDT->format("U.u"));
- $endsEpoch = floatval($showEndDT->format("U.u"));
+ $startsEpoch = floatval($showStartDT->format('U.u'));
+ $endsEpoch = floatval($showEndDT->format('U.u'));
$this->getScheduledStatus($startsEpoch, $endsEpoch, $row);
} else {
- $row["empty"] = true;
- $row["id"] = 0 ;
- $row["instance"] = intval($p_item["si_id"]);
+ $row['empty'] = true;
+ $row['id'] = 0;
+ $row['instance'] = intval($p_item['si_id']);
}
- if (intval($p_item["si_rebroadcast"]) === 1) {
- $row["rebroadcast"] = true;
+ if (intval($p_item['si_rebroadcast']) === 1) {
+ $row['rebroadcast'] = true;
}
if ($this->currentShow === true) {
- $row["currentShow"] = true;
+ $row['currentShow'] = true;
}
$this->getItemColor($p_item, $row);
@@ -326,38 +330,38 @@ class Application_Model_ShowBuilder
private function makeFooterRow($p_item)
{
- $row = $this->defaultRowArray;
- $row["footer"] = true;
- $row["instance"] = intval($p_item["si_id"]);
+ $row = $this->defaultRowArray;
+ $row['footer'] = true;
+ $row['instance'] = intval($p_item['si_id']);
$this->getRowTimestamp($p_item, $row);
- $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC"));
- $contentDT = $this->contentDT;
+ $showEndDT = new DateTime($p_item['si_ends'], new DateTimeZone('UTC'));
+ $contentDT = $this->contentDT;
- $runtime = bcsub($contentDT->format("U.u"), $showEndDT->format("U.u"), 6);
- $row["runtime"] = $runtime;
+ $runtime = bcsub($contentDT->format('U.u'), $showEndDT->format('U.u'), 6);
+ $row['runtime'] = $runtime;
- $timeFilled = new TimeFilledFormatter($runtime);
- $row["fRuntime"] = $timeFilled->format();
+ $timeFilled = new TimeFilledFormatter($runtime);
+ $row['fRuntime'] = $timeFilled->format();
- $showStartDT = new DateTime($p_item["si_starts"], new DateTimeZone("UTC"));
+ $showStartDT = new DateTime($p_item['si_starts'], new DateTimeZone('UTC'));
$showStartDT->setTimezone(new DateTimeZone($this->timezone));
- $startsEpoch = floatval($showStartDT->format("U.u"));
- $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC"));
+ $startsEpoch = floatval($showStartDT->format('U.u'));
+ $showEndDT = new DateTime($p_item['si_ends'], new DateTimeZone('UTC'));
$showEndDT->setTimezone(new DateTimeZone($this->timezone));
- $endsEpoch = floatval($showEndDT->format("U.u"));
+ $endsEpoch = floatval($showEndDT->format('U.u'));
- $row["refresh"] = floatval($showEndDT->format("U.u")) - $this->epoch_now;
+ $row['refresh'] = floatval($showEndDT->format('U.u')) - $this->epoch_now;
if ($this->currentShow === true) {
- $row["currentShow"] = true;
+ $row['currentShow'] = true;
}
$this->getScheduledStatus($startsEpoch, $endsEpoch, $row);
$this->isAllowed($p_item, $row);
- if (intval($p_item["si_record"]) === 1) {
- $row["record"] = true;
+ if (intval($p_item['si_record']) === 1) {
+ $row['record'] = true;
}
return $row;
@@ -375,34 +379,36 @@ class Application_Model_ShowBuilder
$outdated = false;
$shows = Application_Model_Show::getShows($this->startDT, $this->endDT);
- $include = array();
- if ($this->opts["showFilter"] !== 0) {
- $include[] = $this->opts["showFilter"];
- } elseif ($this->opts["myShows"] === 1) {
-
+ $include = [];
+ if ($this->opts['showFilter'] !== 0) {
+ $include[] = $this->opts['showFilter'];
+ } elseif ($this->opts['myShows'] === 1) {
$include = $this->getUsersShows();
}
-
- $currentInstances = array();
+ $currentInstances = [];
foreach ($shows as $show) {
+ if (empty($include) || in_array($show['show_id'], $include)) {
+ $currentInstances[] = $show['instance_id'];
- if (empty($include) || in_array($show["show_id"], $include)) {
- $currentInstances[] = $show["instance_id"];
-
- if (isset($show["last_scheduled"])) {
- $dt = new DateTime($show["last_scheduled"],
- new DateTimeZone("UTC"));
+ if (isset($show['last_scheduled'])) {
+ $dt = new DateTime(
+ $show['last_scheduled'],
+ new DateTimeZone('UTC')
+ );
} else {
- $dt = new DateTime($show["created"],
- new DateTimeZone("UTC"));
+ $dt = new DateTime(
+ $show['created'],
+ new DateTimeZone('UTC')
+ );
}
//check if any of the shows have a more recent timestamp.
- $showTimeStamp = intval($dt->format("U"));
+ $showTimeStamp = intval($dt->format('U'));
if ($timestamp < $showTimeStamp) {
$outdated = true;
+
break;
}
}
@@ -412,7 +418,7 @@ class Application_Model_ShowBuilder
//empty schedule etc)
if ($outdated === false && count($instances)
!== count($currentInstances)) {
- Logging::debug("show instances have changed.");
+ Logging::debug('show instances have changed.');
$outdated = true;
}
@@ -422,46 +428,48 @@ class Application_Model_ShowBuilder
public function getItems()
{
$current_id = -1;
- $display_items = array();
-
- $shows = array();
- $showInstance = array();
- if ($this->opts["myShows"] === 1) {
+ $display_items = [];
+ $shows = [];
+ $showInstance = [];
+ if ($this->opts['myShows'] === 1) {
$shows = $this->getUsersShows();
- } elseif ($this->opts["showFilter"] !== 0) {
- $shows[] = $this->opts["showFilter"];
- } elseif ($this->opts["showInstanceFilter"] !== 0) {
- $showInstance[] = $this->opts["showInstanceFilter"];
+ } elseif ($this->opts['showFilter'] !== 0) {
+ $shows[] = $this->opts['showFilter'];
+ } elseif ($this->opts['showInstanceFilter'] !== 0) {
+ $showInstance[] = $this->opts['showInstanceFilter'];
}
$scheduled_items = Application_Model_Schedule::GetScheduleDetailItems(
- $this->startDT, $this->endDT, $shows, $showInstance);
-
- for ($i = 0, $rows = count($scheduled_items); $i < $rows; $i++) {
+ $this->startDT,
+ $this->endDT,
+ $shows,
+ $showInstance
+ );
+ for ($i = 0, $rows = count($scheduled_items); $i < $rows; ++$i) {
$item = $scheduled_items[$i];
//don't send back data for filler rows.
- if (isset($item["playout_status"]) &&
- $item["playout_status"] < 0) {
+ if (isset($item['playout_status'])
+ && $item['playout_status'] < 0) {
continue;
}
//make a header row.
- if ($current_id !== $item["si_id"]) {
-
+ if ($current_id !== $item['si_id']) {
//make a footer row.
if ($current_id !== -1) {
// pass in the previous row as it's the last row for
// the previous show.
$display_items[] = $this->makeFooterRow(
- $scheduled_items[$i-1]);
+ $scheduled_items[$i - 1]
+ );
}
$display_items[] = $this->makeHeaderRow($item);
- $current_id = $item["si_id"];
+ $current_id = $item['si_id'];
$this->pos = 1;
}
@@ -473,8 +481,8 @@ class Application_Model_ShowBuilder
$display_items[] = $row;
}
- if ($current_id !== -1 &&
- !in_array($current_id, $this->showInstances)) {
+ if ($current_id !== -1
+ && !in_array($current_id, $this->showInstances)) {
$this->showInstances[] = $current_id;
}
}
@@ -482,11 +490,11 @@ class Application_Model_ShowBuilder
//make the last footer if there were any scheduled items.
if (count($scheduled_items) > 0) {
$display_items[] = $this->makeFooterRow($scheduled_items[
- count($scheduled_items)-1]);
+ count($scheduled_items) - 1]);
}
-
- return array(
- "schedule" => $display_items,
- "showInstances" => $this->showInstances);
+
+ return [
+ 'schedule' => $display_items,
+ 'showInstances' => $this->showInstances, ];
}
}
diff --git a/legacy/application/models/ShowInstance.php b/legacy/application/models/ShowInstance.php
index 1cb7e8057..8da14b6db 100644
--- a/legacy/application/models/ShowInstance.php
+++ b/legacy/application/models/ShowInstance.php
@@ -36,15 +36,15 @@ class Application_Model_ShowInstance
{
$timestamp = gmdate(DEFAULT_TIMESTAMP_FORMAT);
$instance_id = $this->getShowInstanceId();
- $sql = << :timestamp::TIMESTAMP
AND instance_id = :instanceId
AND rebroadcast = 1;
SQL;
- Application_Common_Database::prepareAndExecute( $sql, array(
+ Application_Common_Database::prepareAndExecute($sql, [
':instanceId' => $instance_id,
- ':timestamp' => $timestamp), 'execute');
+ ':timestamp' => $timestamp, ], 'execute');
}
/* This function is weird. It should return a boolean, but instead returns
@@ -67,12 +67,12 @@ SQL;
return $show->getDbName();
}
-
+
public function getImagePath()
{
- $show = CcShowQuery::create()->findPK($this->getShowId());
-
- return $show->getDbImagePath();
+ $show = CcShowQuery::create()->findPK($this->getShowId());
+
+ return $show->getDbImagePath();
}
public function getGenre()
@@ -82,43 +82,47 @@ SQL;
return $show->getDbGenre();
}
-
public function hasAutoPlaylist()
{
$show = CcShowQuery::create()->findPK($this->getShowId());
- return $show->getDbHasAutoPlaylist();
+ return $show->getDbHasAutoPlaylist();
}
-
+
public function getAutoPlaylistId()
{
$show = CcShowQuery::create()->findPK($this->getShowId());
+
return $show->getDbAutoPlaylistId();
-
}
public function getAutoPlaylistRepeat()
{
$show = CcShowQuery::create()->findPK($this->getShowId());
- return $show->getDbAutoPlaylistRepeat();
+ return $show->getDbAutoPlaylistRepeat();
}
-
/**
- * Return the start time of the Show (UTC time)
+ * Return the start time of the Show (UTC time).
+ *
+ * @param mixed $format
+ *
* @return string in format DEFAULT_TIMESTAMP_FORMAT (PHP time notation)
*/
- public function getShowInstanceStart($format=DEFAULT_TIMESTAMP_FORMAT)
+ public function getShowInstanceStart($format = DEFAULT_TIMESTAMP_FORMAT)
{
return $this->_showInstance->getDbStarts($format);
}
/**
- * Return the end time of the Show (UTC time)
+ * Return the end time of the Show (UTC time).
+ *
+ * @param mixed $format
+ *
* @return string in format DEFAULT_TIMESTAMP_FORMAT (PHP time notation)
*/
- public function getShowInstanceEnd($format=DEFAULT_TIMESTAMP_FORMAT)
+ public function getShowInstanceEnd($format = DEFAULT_TIMESTAMP_FORMAT)
{
return $this->_showInstance->getDbEnds($format);
}
@@ -126,7 +130,7 @@ SQL;
public function getStartDate()
{
$showStart = $this->getShowInstanceStart();
- $showStartExplode = explode(" ", $showStart);
+ $showStartExplode = explode(' ', $showStart);
return $showStartExplode[0];
}
@@ -134,17 +138,17 @@ SQL;
public function getStartTime()
{
$showStart = $this->getShowInstanceStart();
- $showStartExplode = explode(" ", $showStart);
+ $showStartExplode = explode(' ', $showStart);
return $showStartExplode[1];
}
public function getRecordedFile()
{
- $file_id = $this->_showInstance->getDbRecordedFile();
+ $file_id = $this->_showInstance->getDbRecordedFile();
if (isset($file_id)) {
- $file = Application_Model_StoredFile::RecallById($file_id);
+ $file = Application_Model_StoredFile::RecallById($file_id);
if (isset($file)) {
$filePaths = $file->getFilePaths();
@@ -160,21 +164,24 @@ SQL;
public function setShowStart($start)
{
$this->_showInstance->setDbStarts($start)
- ->save();
+ ->save()
+ ;
Application_Model_RabbitMq::PushSchedule();
}
public function setShowEnd($end)
{
$this->_showInstance->setDbEnds($end)
- ->save();
+ ->save()
+ ;
Application_Model_RabbitMq::PushSchedule();
}
public function setAutoPlaylistBuilt($bool)
{
$this->_showInstance->setDbAutoPlaylistBuilt($bool)
- ->save();
+ ->save()
+ ;
}
public function updateScheduledTime()
@@ -229,18 +236,20 @@ SQL;
/**
* Add a playlist as the last item of the current show.
*
- * @param int $plId
- * Playlist ID.
+ * @param int $plId
+ * Playlist ID
+ * @param mixed $pl_id
+ * @param mixed $checkUserPerm
*/
public function addPlaylistToShow($pl_id, $checkUserPerm = true)
{
- $ts = intval($this->_showInstance->getDbLastScheduled("U")) ? : 0;
+ $ts = intval($this->_showInstance->getDbLastScheduled('U')) ?: 0;
$id = $this->_showInstance->getDbId();
$lastid = $this->getLastAudioItemId();
$scheduler = new Application_Model_Scheduler($checkUserPerm);
$scheduler->scheduleAfter(
- array(array("id" => $lastid, "instance" => $id, "timestamp" => $ts)),
- array(array("id" => $pl_id, "type" => "playlist"))
+ [['id' => $lastid, 'instance' => $id, 'timestamp' => $ts]],
+ [['id' => $pl_id, 'type' => 'playlist']]
);
// doing this to update the database schedule so that subsequent adds will work.
$con = Propel::getConnection(CcShowInstancesPeer::DATABASE_NAME);
@@ -250,39 +259,41 @@ SQL;
/**
* Add a playlist as the first item of the current show.
*
- * @param int $plId
- * Playlist ID.
+ * @param int $plId
+ * Playlist ID
+ * @param mixed $pl_id
+ * @param mixed $checkUserPerm
*/
public function addPlaylistToShowStart($pl_id, $checkUserPerm = true)
{
- $ts = intval($this->_showInstance->getDbLastScheduled("U")) ? : 0;
+ $ts = intval($this->_showInstance->getDbLastScheduled('U')) ?: 0;
$id = $this->_showInstance->getDbId();
$scheduler = new Application_Model_Scheduler($checkUserPerm);
$scheduler->scheduleAfter(
- array(array("id" => 0, "instance" => $id, "timestamp" => $ts)),
- array(array("id" => $pl_id, "type" => "playlist"))
+ [['id' => 0, 'instance' => $id, 'timestamp' => $ts]],
+ [['id' => $pl_id, 'type' => 'playlist']]
);
// doing this to update the database schedule so that subsequent adds will work.
$con = Propel::getConnection(CcShowInstancesPeer::DATABASE_NAME);
$this->_showInstance->updateScheduleStatus($con);
}
-
/**
* Add a media file as the last item in the show.
*
- * @param int $file_id
+ * @param int $file_id
+ * @param mixed $checkUserPerm
*/
public function addFileToShow($file_id, $checkUserPerm = true)
{
- $ts = intval($this->_showInstance->getDbLastScheduled("U")) ? : 0;
+ $ts = intval($this->_showInstance->getDbLastScheduled('U')) ?: 0;
$id = $this->_showInstance->getDbId();
$scheduler = new Application_Model_Scheduler();
$scheduler->setCheckUserPermissions($checkUserPerm);
$scheduler->scheduleAfter(
- array(array("id" => 0, "instance" => $id, "timestamp" => $ts)),
- array(array("id" => $file_id, "type" => "audioclip"))
+ [['id' => 0, 'instance' => $id, 'timestamp' => $ts]],
+ [['id' => $file_id, 'type' => 'audioclip']]
);
}
@@ -290,7 +301,7 @@ SQL;
* Add the given playlists to the show.
*
* @param array $plIds
- * An array of playlist IDs.
+ * An array of playlist IDs
*/
public function scheduleShow($plIds)
{
@@ -303,20 +314,21 @@ SQL;
{
CcScheduleQuery::create()
->filterByDbInstanceId($this->_instanceId)
- ->delete();
+ ->delete()
+ ;
Application_Model_RabbitMq::PushSchedule();
$this->updateScheduledTime();
}
private function checkToDeleteShow($showId)
-
{
//UTC DateTime object
$showsPopUntil = Application_Model_Preference::GetShowsPopulatedUntil();
$showDays = CcShowDaysQuery::create()
->filterByDbShowId($showId)
- ->findOne();
+ ->findOne()
+ ;
$showEnd = $showDays->getDbLastShow();
@@ -339,30 +351,32 @@ SQL;
->filterByDbShowId($showId)
->filterByDbModifiedInstance(false)
->filterByDbRebroadcast(0)
- ->find();
+ ->find()
+ ;
if (is_null($showInstances)) {
return true;
}
//only 1 show instance left of the show, make it non repeating.
- else if (count($showInstances) === 1) {
+ if (count($showInstances) === 1) {
$showInstance = $showInstances[0];
$showDaysOld = CcShowDaysQuery::create()
->filterByDbShowId($showId)
- ->find();
+ ->find()
+ ;
$tz = $showDaysOld[0]->getDbTimezone();
- $startDate = new DateTime($showInstance->getDbStarts(), new DateTimeZone("UTC"));
+ $startDate = new DateTime($showInstance->getDbStarts(), new DateTimeZone('UTC'));
$startDate->setTimeZone(new DateTimeZone($tz));
$endDate = self::addDeltas($startDate, 1, 0);
//make a new rule for a non repeating show.
$showDayNew = new CcShowDays();
- $showDayNew->setDbFirstShow($startDate->format("Y-m-d"));
- $showDayNew->setDbLastShow($endDate->format("Y-m-d"));
- $showDayNew->setDbStartTime($startDate->format("H:i:s"));
+ $showDayNew->setDbFirstShow($startDate->format('Y-m-d'));
+ $showDayNew->setDbLastShow($endDate->format('Y-m-d'));
+ $showDayNew->setDbStartTime($startDate->format('H:i:s'));
$showDayNew->setDbTimezone($tz);
$showDayNew->setDbDay($startDate->format('w'));
$showDayNew->setDbDuration($showDaysOld[0]->getDbDuration());
@@ -378,7 +392,8 @@ SQL;
$showInstances = CcShowInstancesQuery::create()
->filterByDbShowId($showId)
->filterByDbModifiedInstance(true)
- ->delete();
+ ->delete()
+ ;
}
return false;
@@ -397,11 +412,11 @@ SQL;
if ($current_timestamp <= $this->getShowInstanceEnd()) {
if ($show->isRepeating()) {
-
CcShowInstancesQuery::create()
->findPK($this->_instanceId)
->setDbModifiedInstance(true)
- ->save();
+ ->save()
+ ;
if ($this->isRebroadcast()) {
return;
@@ -411,19 +426,21 @@ SQL;
if ($recording) {
CcShowInstancesQuery::create()
->filterByDbOriginalShow($this->_instanceId)
- ->delete();
+ ->delete()
+ ;
}
- /* Automatically delete all files scheduled in cc_schedules table. */
+ // Automatically delete all files scheduled in cc_schedules table.
CcScheduleQuery::create()
->filterByDbInstanceId($this->_instanceId)
- ->delete();
-
+ ->delete()
+ ;
if ($this->checkToDeleteShow($showId)) {
CcShowQuery::create()
->filterByDbId($showId)
- ->delete();
+ ->delete()
+ ;
}
} else {
if ($this->isRebroadcast()) {
@@ -442,16 +459,18 @@ SQL;
public function setRecordedFile($file_id)
{
$showInstance = CcShowInstancesQuery::create()
- ->findPK($this->_instanceId);
+ ->findPK($this->_instanceId)
+ ;
$showInstance->setDbRecordedFile($file_id)
- ->save();
+ ->save()
+ ;
$rebroadcasts = CcShowInstancesQuery::create()
->filterByDbOriginalShow($this->_instanceId)
- ->find();
+ ->find()
+ ;
foreach ($rebroadcasts as $rebroadcast) {
-
try {
$rebroad = new Application_Model_ShowInstance($rebroadcast->getDbId());
$rebroad->addFileToShow($file_id, false);
@@ -465,23 +484,22 @@ SQL;
{
$time = $this->_showInstance->getDbTimeFilled();
- if ($time != "00:00:00" && !empty($time)) {
- $time_arr = explode(".", $time);
+ if ($time != '00:00:00' && !empty($time)) {
+ $time_arr = explode('.', $time);
if (count($time_arr) > 1) {
- $time_arr[1] = "." . $time_arr[1];
+ $time_arr[1] = '.' . $time_arr[1];
$milliseconds = number_format(round($time_arr[1], 2), 2);
$time = $time_arr[0] . substr($milliseconds, 1);
} else {
- $time = $time_arr[0] . ".00";
+ $time = $time_arr[0] . '.00';
}
} else {
- $time = "00:00:00.00";
+ $time = '00:00:00.00';
}
return $time;
}
-
public function getTimeScheduledSecs()
{
$time_filled = $this->getTimeScheduled();
@@ -500,19 +518,20 @@ SQL;
// should return the amount of seconds remaining to be scheduled in a show instance
public function getSecondsRemaining()
{
- return ($this->getDurationSecs() - $this->getTimeScheduledSecs());
+ return $this->getDurationSecs() - $this->getTimeScheduledSecs();
}
public function getPercentScheduled()
{
$durationSeconds = $this->getDurationSecs();
$timeSeconds = $this->getTimeScheduledSecs();
-
+
if ($durationSeconds != 0) { //Prevent division by zero if the show duration is somehow zero.
$percent = ceil(($timeSeconds / $durationSeconds) * 100);
} else {
$percent = 0;
}
+
return $percent;
}
@@ -522,23 +541,23 @@ SQL;
$end = $this->getShowInstanceEnd(null);
$interval = $start->diff($end);
- $days = $interval->format("%d");
- $hours = sprintf("%02d" ,$interval->format("%h"));
+ $days = $interval->format('%d');
+ $hours = sprintf('%02d', $interval->format('%h'));
if ($days > 0) {
$totalHours = $days * 24 + $hours;
//$interval object does not have milliseconds so hard code to .00
- $returnStr = $totalHours . ":" . $interval->format("%I:%S") . ".00";
+ $returnStr = $totalHours . ':' . $interval->format('%I:%S') . '.00';
} else {
- $returnStr = $hours . ":" . $interval->format("%I:%S") . ".00";
+ $returnStr = $hours . ':' . $interval->format('%I:%S') . '.00';
}
return $returnStr;
}
- public static function getContentCount($p_start, $p_end)
+ public static function getContentCount($p_start, $p_end)
{
- $sql = << :p_start::TIMESTAMP
GROUP BY instance_id
SQL;
- $counts = Application_Common_Database::prepareAndExecute($sql, array(
- ':p_start' => $p_start->format("Y-m-d G:i:s"),
- ':p_end' => $p_end->format("Y-m-d G:i:s"))
- , 'all');
+ $counts = Application_Common_Database::prepareAndExecute($sql, [
+ ':p_start' => $p_start->format('Y-m-d G:i:s'),
+ ':p_end' => $p_end->format('Y-m-d G:i:s'), ], 'all');
- $real_counts = array();
+ $real_counts = [];
foreach ($counts as $c) {
$real_counts[$c['instance_id']] = $c['instance_count'];
}
- return $real_counts;
+ return $real_counts;
}
public static function getIsFull($p_start, $p_end)
{
- $sql = << :p_start::TIMESTAMP
AND starts < :p_end::TIMESTAMP
SQL;
- $res = Application_Common_Database::prepareAndExecute($sql, array(
- ':p_start' => $p_start->format("Y-m-d G:i:s"),
- ':p_end' => $p_end->format("Y-m-d G:i:s"))
- , 'all');
+ $res = Application_Common_Database::prepareAndExecute($sql, [
+ ':p_start' => $p_start->format('Y-m-d G:i:s'),
+ ':p_end' => $p_end->format('Y-m-d G:i:s'), ], 'all');
- $isFilled = array();
+ $isFilled = [];
foreach ($res as $r) {
$isFilled[$r['id']] = $r['filled'];
}
@@ -586,6 +603,7 @@ SQL;
{
$con = Propel::getConnection(CcShowInstancesPeer::DATABASE_NAME);
$con->beginTransaction();
+
try {
// query the show instances to find whether a show instance has an autoplaylist
$showInstances = CcShowInstancesQuery::create()
@@ -593,15 +611,15 @@ SQL;
->filterByDbStarts($p_start->format(DEFAULT_TIMESTAMP_FORMAT), Criteria::GREATER_THAN)
->leftJoinCcShow()
->where('CcShow.has_autoplaylist = ?', 'true')
- ->find($con);
- $hasAutoplaylist = array();
+ ->find($con)
+ ;
+ $hasAutoplaylist = [];
foreach ($showInstances->toArray() as $ap) {
$hasAutoplaylist[$ap['DbId']] = true;
}
- return $hasAutoplaylist;
- }
- catch (Exception $e) {
+ return $hasAutoplaylist;
+ } catch (Exception $e) {
$con->rollback();
Logging::info("Couldn't query show instances for calendar to find which had autoplaylists");
Logging::info($e->getMessage());
@@ -610,7 +628,7 @@ SQL;
public function showEmpty()
{
- $sql = << $this->_instanceId ), 'all' );
- # TODO : A bit retarded. fix this later
+ // TODO : use prepareAndExecute properly
+ $res = Application_Common_Database::prepareAndExecute(
+ $sql,
+ [':instance_id' => $this->_instanceId],
+ 'all'
+ );
+ // TODO : A bit retarded. fix this later
foreach ($res as $r) {
return false;
}
- return true;
+ return true;
}
public function getShowListContent($timezone = null)
{
$con = Propel::getConnection();
- $sql = <<prepare($sql);
- $stmt->execute(array(
+ $stmt->execute([
':instance_id1' => $this->_instanceId,
- ':instance_id2' => $this->_instanceId
- ));
+ ':instance_id2' => $this->_instanceId,
+ ]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
-
+
if (isset($timezone)) {
$displayTimezone = new DateTimeZone($timezone);
- } else {
+ } else {
$userTimezone = Application_Model_Preference::GetUserTimezone();
$displayTimezone = new DateTimeZone($userTimezone);
}
- $utcTimezone = new DateTimeZone("UTC");
+ $utcTimezone = new DateTimeZone('UTC');
foreach ($results as &$row) {
-
- $dt = new DateTime($row["starts"], $utcTimezone);
+ $dt = new DateTime($row['starts'], $utcTimezone);
$dt->setTimezone($displayTimezone);
- $row["starts"] = $dt->format(DEFAULT_TIMESTAMP_FORMAT);
+ $row['starts'] = $dt->format(DEFAULT_TIMESTAMP_FORMAT);
if (isset($row['length'])) {
- $formatter = new LengthFormatter($row["length"]);
- $row["length"] = $formatter->format();
+ $formatter = new LengthFormatter($row['length']);
+ $row['length'] = $formatter->format();
}
}
-
return $results;
}
@@ -710,46 +729,51 @@ SQL;
{
$con = Propel::getConnection();
- $sql = "SELECT id FROM cc_schedule "
- ."WHERE instance_id = :instanceId "
- ."ORDER BY ends DESC "
- ."LIMIT 1";
+ $sql = 'SELECT id FROM cc_schedule '
+ . 'WHERE instance_id = :instanceId '
+ . 'ORDER BY ends DESC '
+ . 'LIMIT 1';
- $query = Application_Common_Database::prepareAndExecute( $sql,
- array(':instanceId' => $this->_instanceId), 'column');
+ $query = Application_Common_Database::prepareAndExecute(
+ $sql,
+ [':instanceId' => $this->_instanceId],
+ 'column'
+ );
return ($query !== false) ? $query : null;
}
-
public function getLastAudioItemEnd()
{
$con = Propel::getConnection();
- $sql = "SELECT ends FROM cc_schedule "
- ."WHERE instance_id = :instanceId "
- ."ORDER BY ends DESC "
- ."LIMIT 1";
+ $sql = 'SELECT ends FROM cc_schedule '
+ . 'WHERE instance_id = :instanceId '
+ . 'ORDER BY ends DESC '
+ . 'LIMIT 1';
- $query = Application_Common_Database::prepareAndExecute( $sql,
- array(':instanceId' => $this->_instanceId), 'column');
+ $query = Application_Common_Database::prepareAndExecute(
+ $sql,
+ [':instanceId' => $this->_instanceId],
+ 'column'
+ );
return ($query !== false) ? $query : null;
}
public static function GetLastShowInstance($p_timeNow)
{
- $sql = << $p_timeNow ), 'column' );
+ $id = Application_Common_Database($sql, [
+ ':timeNow' => $p_timeNow, ], 'column');
- return ($id ? new Application_Model_ShowInstance($id) : null );
+ return $id ? new Application_Model_ShowInstance($id) : null;
}
public static function GetCurrentShowInstance($p_timeNow)
@@ -760,7 +784,7 @@ SQL;
* is actually playing, and so this is the one we want.
*/
- $sql = << $p_timeNow,
- ':timeNow2' => $p_timeNow ), 'column');
+ ':timeNow2' => $p_timeNow, ], 'column');
- return ( $id ? new Application_Model_ShowInstance($id) : null );
+ return $id ? new Application_Model_ShowInstance($id) : null;
}
public static function GetNextShowInstance($p_timeNow)
{
- $sql = << :timeNow::TIMESTAMP
@@ -786,27 +810,35 @@ AND si.modified_instance = 'f'
ORDER BY si.starts
LIMIT 1
SQL;
- $id = Application_Common_Database::prepareAndExecute( $sql,
- array( 'timeNow' => $p_timeNow ), 'column' );
- return ( $id ? new Application_Model_ShowInstance($id) : null );
+ $id = Application_Common_Database::prepareAndExecute(
+ $sql,
+ ['timeNow' => $p_timeNow],
+ 'column'
+ );
+
+ return $id ? new Application_Model_ShowInstance($id) : null;
}
// returns number of show instances that ends later than $day
public static function GetShowInstanceCount($day)
{
- $sql = << $day ), 'column' );
+
+ return Application_Common_Database::prepareAndExecute(
+ $sql,
+ [':day' => $day],
+ 'column'
+ );
}
// this returns end timestamp of all shows that are in the range and has live DJ set up
public static function GetEndTimeOfNextShowWithLiveDJ($p_startTime, $p_endTime)
{
- $sql = << :startTime::TIMESTAMP
OR live_stream_using_custom_auth)
ORDER BY si.ends
SQL;
- return Application_Common_Database::prepareAndExecute( $sql, array(
+
+ return Application_Common_Database::prepareAndExecute($sql, [
':startTime' => $p_startTime,
- ':endTime' => $p_endTime), 'all');
+ ':endTime' => $p_endTime, ], 'all');
}
public function isRepeating()
diff --git a/legacy/application/models/StoredFile.php b/legacy/application/models/StoredFile.php
index 1f0b55570..1a6958e62 100644
--- a/legacy/application/models/StoredFile.php
+++ b/legacy/application/models/StoredFile.php
@@ -1,18 +1,18 @@
propel
+ * array of db metadata -> propel.
*/
- private $_dbMD = array (
- "track_title" => "DbTrackTitle",
- "artist_name" => "DbArtistName",
- "album_title" => "DbAlbumTitle",
- "genre" => "DbGenre",
- "mood" => "DbMood",
- "track_number" => "DbTrackNumber",
- "bpm" => "DbBpm",
- "label" => "DbLabel",
- "composer" => "DbComposer",
- "encoded_by" => "DbEncodedBy",
- "conductor" => "DbConductor",
- "year" => "DbYear",
- "info_url" => "DbInfoUrl",
- "isrc_number" => "DbIsrcNumber",
- "copyright" => "DbCopyright",
- "length" => "DbLength",
- "bit_rate" => "DbBitRate",
- "sample_rate" => "DbSampleRate",
- "mime" => "DbMime",
+ private $_dbMD = [
+ 'track_title' => 'DbTrackTitle',
+ 'artist_name' => 'DbArtistName',
+ 'album_title' => 'DbAlbumTitle',
+ 'genre' => 'DbGenre',
+ 'mood' => 'DbMood',
+ 'track_number' => 'DbTrackNumber',
+ 'bpm' => 'DbBpm',
+ 'label' => 'DbLabel',
+ 'composer' => 'DbComposer',
+ 'encoded_by' => 'DbEncodedBy',
+ 'conductor' => 'DbConductor',
+ 'year' => 'DbYear',
+ 'info_url' => 'DbInfoUrl',
+ 'isrc_number' => 'DbIsrcNumber',
+ 'copyright' => 'DbCopyright',
+ 'length' => 'DbLength',
+ 'bit_rate' => 'DbBitRate',
+ 'sample_rate' => 'DbSampleRate',
+ 'mime' => 'DbMime',
//"md5" => "DbMd5",
- "ftype" => "DbFtype",
- "language" => "DbLanguage",
- "replay_gain" => "DbReplayGain",
- "directory" => "DbDirectory",
- "owner_id" => "DbOwnerId",
- "cuein" => "DbCueIn",
- "cueout" => "DbCueOut",
- "description" => "DbDescription",
- "artwork" => "DbArtwork",
- "track_type" => "DbTrackType"
- );
+ 'ftype' => 'DbFtype',
+ 'language' => 'DbLanguage',
+ 'replay_gain' => 'DbReplayGain',
+ 'directory' => 'DbDirectory',
+ 'owner_id' => 'DbOwnerId',
+ 'cuein' => 'DbCueIn',
+ 'cueout' => 'DbCueOut',
+ 'description' => 'DbDescription',
+ 'artwork' => 'DbArtwork',
+ 'track_type' => 'DbTrackType',
+ ];
- function __construct($file, $con) {
+ public function __construct($file, $con)
+ {
$this->_file = $file;
$this->_con = $con;
}
@@ -99,25 +100,25 @@ class Application_Model_StoredFile
$this->_file->save();
}
- public static function createWithFile($f, $con) {
- $storedFile = new Application_Model_StoredFile($f, $con);
- return $storedFile;
+ public static function createWithFile($f, $con)
+ {
+ return new Application_Model_StoredFile($f, $con);
}
/**
* Set multiple metadata values using defined metadata constants.
*
* @param array $p_md
- * example: $p_md['MDATA_KEY_URL'] = 'http://www.fake.com'
+ * example: $p_md['MDATA_KEY_URL'] = 'http://www.fake.com'
*/
- public function setMetadata($p_md=null)
+ public function setMetadata($p_md = null)
{
if (is_null($p_md)) {
$this->setDbColMetadata();
} else {
- $dbMd = array();
+ $dbMd = [];
- if (isset($p_md["MDATA_KEY_YEAR"])) {
+ if (isset($p_md['MDATA_KEY_YEAR'])) {
// We need to make sure to clean this value before
// inserting into database. If value is outside of range
// [-2^31, 2^31-1] then postgresl will throw error when
@@ -128,7 +129,7 @@ class Application_Model_StoredFile
// If the value is 2012-01-01, then substring to first 4
// digits is an OK result. CC-3771
- $year = $p_md["MDATA_KEY_YEAR"];
+ $year = $p_md['MDATA_KEY_YEAR'];
if (strlen($year) > 4) {
$year = substr($year, 0, 4);
@@ -136,16 +137,16 @@ class Application_Model_StoredFile
if (!is_numeric($year)) {
$year = 0;
}
- $p_md["MDATA_KEY_YEAR"] = $year;
+ $p_md['MDATA_KEY_YEAR'] = $year;
}
- # Translate metadata attributes from media monitor (MDATA_KEY_*)
- # to their counterparts in constants.php (usually the column names)
+ // Translate metadata attributes from media monitor (MDATA_KEY_*)
+ // to their counterparts in constants.php (usually the column names)
$track_length = $p_md['MDATA_KEY_DURATION'];
$track_length_in_sec = Application_Common_DateHelper::calculateLengthInSeconds($track_length);
foreach ($p_md as $mdConst => $mdValue) {
if (defined($mdConst)) {
- if ($mdConst == "MDATA_KEY_CUE_OUT") {
+ if ($mdConst == 'MDATA_KEY_CUE_OUT') {
if ($mdValue == '0.0') {
$mdValue = $track_length_in_sec;
} else {
@@ -153,7 +154,6 @@ class Application_Model_StoredFile
}
}
$dbMd[constant($mdConst)] = $mdValue;
-
}
}
$this->setDbColMetadata($dbMd);
@@ -164,14 +164,14 @@ class Application_Model_StoredFile
* Set multiple metadata values using database columns as indexes.
*
* @param array $p_md
- * example: $p_md['url'] = 'http://www.fake.com'
+ * example: $p_md['url'] = 'http://www.fake.com'
*/
- public function setDbColMetadata($p_md=null)
+ public function setDbColMetadata($p_md = null)
{
if (is_null($p_md)) {
foreach ($this->_dbMD as $dbColumn => $propelColumn) {
- $method = "set$propelColumn";
- $this->_file->$method(null);
+ $method = "set{$propelColumn}";
+ $this->_file->{$method}(null);
}
} else {
// in order to edit the owner of a file we see if owner_id exists in the track form metadata otherwise
@@ -184,15 +184,18 @@ class Application_Model_StoredFile
// first admin user we find
if (!array_key_exists('owner_id', $p_md)) {
//$admins = Application_Model_User::getUsers(array('A'));
- $admins = array_merge(Application_Model_User::getUsersOfType('A')->getData(),
- Application_Model_User::getUsersOfType('S')->getData());
+ $admins = array_merge(
+ Application_Model_User::getUsersOfType('A')->getData(),
+ Application_Model_User::getUsersOfType('S')->getData()
+ );
if (count($admins) > 0) { // found admin => pick first one
$owner = $admins[0];
}
} // get the user by id and set it like that
else {
$user = CcSubjsQuery::create()
- ->findPk($p_md['owner_id']);
+ ->findPk($p_md['owner_id'])
+ ;
if ($user) {
$owner = $user;
}
@@ -208,40 +211,44 @@ class Application_Model_StoredFile
foreach ($p_md as $dbColumn => $mdValue) {
// don't blank out name, defaults to original filename on first
// insertion to database.
- if ($dbColumn == "track_title" && (is_null($mdValue) || $mdValue == "")) {
+ if ($dbColumn == 'track_title' && (is_null($mdValue) || $mdValue == '')) {
continue;
}
// Bpm gets POSTed as a string type. With Propel 1.6 this value
// was casted to an integer type before saving it to the db. But
// Propel 1.7 does not do this
- if ($dbColumn == "bpm") {
+ if ($dbColumn == 'bpm') {
$mdValue = (int) $mdValue;
}
- # TODO : refactor string evals
+ // TODO : refactor string evals
if (isset($this->_dbMD[$dbColumn])) {
$propelColumn = $this->_dbMD[$dbColumn];
- $method = "set$propelColumn";
+ $method = "set{$propelColumn}";
/* We need to set track_number to null if it is an empty string
* because propel defaults empty strings to zeros */
- if ($dbColumn == "track_number" && empty($mdValue)) $mdValue = null;
- $this->_file->$method($mdValue);
+ if ($dbColumn == 'track_number' && empty($mdValue)) {
+ $mdValue = null;
+ }
+ $this->_file->{$method}($mdValue);
}
}
}
- $this->_file->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
+ $this->_file->setDbMtime(new DateTime('now', new DateTimeZone('UTC')));
$this->_file->save($this->_con);
}
/**
- * Set metadata element value
+ * Set metadata element value.
*
* @param string $category
- * Metadata element by metadata constant
+ * Metadata element by metadata constant
* @param string $value
- * value to store, if NULL then delete record
+ * value to store, if NULL then delete record
+ * @param mixed $p_category
+ * @param mixed $p_value
*/
public function setMetadataValue($p_category, $p_value)
{
@@ -251,24 +258,26 @@ class Application_Model_StoredFile
}
/**
- * Set metadata element value
+ * Set metadata element value.
*
* @param string $category
- * Metadata element by db column
+ * Metadata element by db column
* @param string $value
- * value to store, if NULL then delete record
+ * value to store, if NULL then delete record
+ * @param mixed $p_category
+ * @param mixed $p_value
*/
public function setDbColMetadataValue($p_category, $p_value)
{
//don't blank out name, defaults to original filename on first insertion to database.
- if ($p_category == "track_title" && (is_null($p_value) || $p_value == "")) {
+ if ($p_category == 'track_title' && (is_null($p_value) || $p_value == '')) {
return;
}
if (isset($this->_dbMD[$p_category])) {
// TODO : fix this crust -- RG
$propelColumn = $this->_dbMD[$p_category];
- $method = "set$propelColumn";
- $this->_file->$method($p_value);
+ $method = "set{$propelColumn}";
+ $this->_file->{$method}($p_value);
$this->_file->save();
}
}
@@ -280,10 +289,10 @@ class Application_Model_StoredFile
*/
public function getDbColMetadata()
{
- $md = array();
+ $md = [];
foreach ($this->_dbMD as $dbColumn => $propelColumn) {
- $method = "get$propelColumn";
- $md[$dbColumn] = $this->_file->$method();
+ $method = "get{$propelColumn}";
+ $md[$dbColumn] = $this->_file->{$method}();
}
return $md;
@@ -297,7 +306,7 @@ class Application_Model_StoredFile
public function getMetadata()
{
$c = get_defined_constants(true);
- $md = array();
+ $md = [];
/* Create a copy of dbMD here and create a "filepath" key inside of
* it. The reason we do this here, instead of creating this key inside
@@ -307,14 +316,14 @@ class Application_Model_StoredFile
* into base and relative path)
* */
$dbmd_copy = $this->_dbMD;
- $dbmd_copy["filepath"] = "DbFilepath";
+ $dbmd_copy['filepath'] = 'DbFilepath';
foreach ($c['user'] as $constant => $value) {
if (preg_match('/^MDATA_KEY/', $constant)) {
if (isset($dbmd_copy[$value])) {
- $propelColumn = $dbmd_copy[$value];
- $method = "get$propelColumn";
- $md[$constant] = $this->_file->$method();
+ $propelColumn = $dbmd_copy[$value];
+ $method = "get{$propelColumn}";
+ $md[$constant] = $this->_file->{$method}();
}
}
}
@@ -324,13 +333,14 @@ class Application_Model_StoredFile
/**
* Returns an array of playlist objects that this file is a part of.
+ *
* @return array
*/
public function getPlaylists()
{
$con = Propel::getConnection();
- $sql = <<fetchAll();
} else {
$msg = implode(',', $stmt->errorInfo());
- throw new Exception("Error: $msg");
+
+ throw new Exception("Error: {$msg}");
}
if (is_array($ids) && count($ids) > 0) {
- return array_map( function ($id) {
+ return array_map(function ($id) {
return Application_Model_Playlist::RecallById($id);
}, $ids);
} else {
- return array();
+ return [];
}
}
/**
* Check if the file (on disk) corresponding to this class exists or not.
- * @return boolean true if the file exists, false otherwise.
+ *
+ * @return bool true if the file exists, false otherwise
*/
public function existsOnDisk()
{
$exists = false;
+
try {
$filePaths = $this->getFilePaths();
$filePath = $filePaths[0];
@@ -369,14 +382,16 @@ SQL;
} catch (Exception $e) {
return false;
}
+
return $exists;
}
/**
- * Deletes the physical file from the local file system or from the cloud
+ * Deletes the physical file from the local file system or from the cloud.
*
+ * @param mixed $quiet
*/
- public function delete($quiet=false)
+ public function delete($quiet = false)
{
// Check if the file is scheduled to be played in the future
if (Application_Model_Schedule::IsFileScheduledInTheFuture($this->_file->getCcFileId())) {
@@ -385,17 +400,17 @@ SQL;
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id);
- $isAdminOrPM = $user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
+ $isAdminOrPM = $user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER]);
if (!$isAdminOrPM && $this->getFileOwnerId() != $user->getId()) {
throw new FileNoPermissionException();
}
$file_id = $this->_file->getDbId();
Logging::info($file_id);
- Logging::info("User ".$user->getLogin()." is deleting file: ".$this->_file->getDbTrackTitle()." - file id: ".$file_id);
+ Logging::info('User ' . $user->getLogin() . ' is deleting file: ' . $this->_file->getDbTrackTitle() . ' - file id: ' . $file_id);
$filesize = $this->_file->getFileSize();
if ($filesize < 0) {
- throw new Exception("Cannot delete file with filesize ".$filesize);
+ throw new Exception('Cannot delete file with filesize ' . $filesize);
}
//Delete the physical file from either the local stor directory
@@ -403,9 +418,7 @@ SQL;
if ($this->_file->getDbImportStatus() == CcFiles::IMPORT_STATUS_SUCCESS) {
try {
$this->_file->deletePhysicalFile();
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
if ($quiet) {
Logging::info($e);
} else {
@@ -450,12 +463,12 @@ SQL;
/**
* This function is for when media monitor detects deletion of file
- * and trying to update airtime side
- *
- * @param boolean $p_deleteFile
+ * and trying to update airtime side.
*
+ * @param bool $p_deleteFile
+ * @param mixed $deleteFromPlaylist
*/
- public function deleteByMediaMonitor($deleteFromPlaylist=false)
+ public function deleteByMediaMonitor($deleteFromPlaylist = false)
{
if ($deleteFromPlaylist) {
Application_Model_Playlist::DeleteFileFromAllPlaylists($this->getId());
@@ -466,7 +479,7 @@ SQL;
}
/**
- * Get the absolute filepath
+ * Get the absolute filepath.
*
* @return array of strings
*/
@@ -478,7 +491,9 @@ SQL;
}
/**
- * Set real filename of raw media data
+ * Set real filename of raw media data.
+ *
+ * @param mixed $p_filepath
*
* @return string
*/
@@ -497,38 +512,40 @@ SQL;
}
/**
- * Get the URL to access this file
+ * Get the URL to access this file.
*/
public function getFileUrl()
{
- $CC_CONFIG = Config::getConfig();
+ $CC_CONFIG = Config::getConfig();
- $protocol = empty($_SERVER['HTTPS']) ? "http" : "https";
+ $protocol = empty($_SERVER['HTTPS']) ? 'http' : 'https';
- $serverName = $_SERVER['SERVER_NAME'];
- $serverPort = $_SERVER['SERVER_PORT'];
- $subDir = $CC_CONFIG['baseDir'];
+ $serverName = $_SERVER['SERVER_NAME'];
+ $serverPort = $_SERVER['SERVER_PORT'];
+ $subDir = $CC_CONFIG['baseDir'];
if ($protocol === 'https' && $serverPort == 80) {
$serverPort = 443;
}
- if ($subDir[0] === "/") {
- $subDir = substr($subDir, 1, strlen($subDir) - 1);
- }
+ if ($subDir[0] === '/') {
+ $subDir = substr($subDir, 1, strlen($subDir) - 1);
+ }
- $baseUrl = "{$protocol}://{$serverName}:{$serverPort}/{$subDir}";
+ $baseUrl = "{$protocol}://{$serverName}:{$serverPort}/{$subDir}";
return $this->getRelativeFileUrl($baseUrl);
}
/**
* Sometimes we want a relative URL and not a full URL. See bug
- * http://dev.sourcefabric.org/browse/CC-2403
+ * http://dev.sourcefabric.org/browse/CC-2403.
+ *
+ * @param mixed $baseUrl
*/
public function getRelativeFileUrl($baseUrl)
{
- return $baseUrl."api/get-media/file/".$this->getId();
+ return $baseUrl . 'api/get-media/file/' . $this->getId();
}
public function getResourceId()
@@ -543,20 +560,21 @@ SQL;
// It's OK for the file size to be zero. Pypo will make a request to Airtime and update
// the file size and md5 hash if they are not set.
if ($filesize < 0) {
- throw new Exception ("Could not determine filesize for file id: ".$this->_file->getDbId().". Filesize: ".$filesize);
+ throw new Exception('Could not determine filesize for file id: ' . $this->_file->getDbId() . '. Filesize: ' . $filesize);
}
+
return $filesize;
}
public static function Insert($md, $con)
{
// save some work by checking if filepath is given right away
- if ( !isset($md['MDATA_KEY_FILEPATH']) ) {
+ if (!isset($md['MDATA_KEY_FILEPATH'])) {
return null;
}
$file = new CcFiles();
- $now = new DateTime("now", new DateTimeZone("UTC"));
+ $now = new DateTime('now', new DateTimeZone('UTC'));
$file->setDbUtime($now);
$file->setDbMtime($now);
@@ -567,7 +585,7 @@ SQL;
// path. Also note that mediamonitor normalizes the paths anyway
// before passing them to php so it's not necessary to do this at all
- $filepath = str_replace("//", "/", $md['MDATA_KEY_FILEPATH']);
+ $filepath = str_replace('//', '/', $md['MDATA_KEY_FILEPATH']);
$res = $storedFile->setFilePath($filepath);
if ($res === -1) {
return null;
@@ -582,11 +600,14 @@ SQL;
/**
* @param int $p_id
* @param Propel Connection
+ * @param null|mixed $con
+ *
+ * @throws Exception
*
* @return Application_Model_StoredFile
- * @throws Exception
*/
- public static function RecallById($p_id=null, $con=null) {
+ public static function RecallById($p_id = null, $con = null)
+ {
//TODO
if (is_null($con)) {
$con = Propel::getConnection(CcFilesPeer::DATABASE_NAME);
@@ -595,9 +616,9 @@ SQL;
if (isset($p_id)) {
$p_id = intval($p_id);
- $storedFile = CcFilesQuery::create()->findPK($p_id, $con);
+ $storedFile = CcFilesQuery::create()->findPK($p_id, $con);
if (is_null($storedFile)) {
- throw new Exception("Could not recall file with id: ".$p_id);
+ throw new Exception('Could not recall file with id: ' . $p_id);
}
//Attempt to get the cloud file object and return it. If no cloud
@@ -607,12 +628,12 @@ SQL;
if (is_null($cloudFile)) {
return self::createWithFile($storedFile, $con);
- } else {
- return self::createWithFile($cloudFile, $con);
}
- } else {
- throw new Exception("No arguments passed to RecallById");
+
+ return self::createWithFile($cloudFile, $con);
}
+
+ throw new Exception('No arguments passed to RecallById');
}
public function getName()
@@ -623,8 +644,10 @@ SQL;
/**
* Fetch the Application_Model_StoredFile by looking up its filepath.
*
- * @param string $p_filepath path of file stored in Airtime.
- * @return Application_Model_StoredFile|NULL
+ * @param string $p_filepath path of file stored in Airtime
+ * @param mixed $con
+ *
+ * @return null|Application_Model_StoredFile
*/
public static function RecallByFilepath($p_filepath, $con)
{
@@ -636,9 +659,11 @@ SQL;
$music_dir = Application_Model_MusicDir::getDirByPath($path_info[0]);
$file = CcFilesQuery::create()
- ->filterByDbDirectory($music_dir->getId())
- ->filterByDbFilepath($path_info[1])
- ->findOne($con);
+ ->filterByDbDirectory($music_dir->getId())
+ ->filterByDbFilepath($path_info[1])
+ ->findOne($con)
+ ;
+
return is_null($file) ? null : self::createWithFile($file, $con);
}
@@ -652,28 +677,28 @@ SQL;
$music_dir = Application_Model_MusicDir::getDirByPath($path_info[0]);
$files = CcFilesQuery::create()
- ->filterByDbDirectory($music_dir->getId())
- ->filterByDbFilepath("$path_info[1]%")
- ->find($con);
- $res = array();
+ ->filterByDbDirectory($music_dir->getId())
+ ->filterByDbFilepath("{$path_info[1]}%")
+ ->find($con)
+ ;
+ $res = [];
foreach ($files as $file) {
- $storedFile = new Application_Model_StoredFile($file, $con);
- $res[] = $storedFile;
+ $storedFile = new Application_Model_StoredFile($file, $con);
+ $res[] = $storedFile;
}
return $res;
}
-
public static function getLibraryColumns()
{
- return array("id", "track_title", "artist_name", "album_title",
- "genre", "length", "year", "utime", "mtime", "ftype",
- "track_number", "mood", "bpm", "composer", "info_url",
- "bit_rate", "sample_rate", "isrc_number", "encoded_by", "label",
- "copyright", "mime", "language", "filepath", "owner_id",
- "conductor", "replay_gain", "lptime", "is_playlist", "is_scheduled",
- "cuein", "cueout", "description", "artwork", "track_type" );
+ return ['id', 'track_title', 'artist_name', 'album_title',
+ 'genre', 'length', 'year', 'utime', 'mtime', 'ftype',
+ 'track_number', 'mood', 'bpm', 'composer', 'info_url',
+ 'bit_rate', 'sample_rate', 'isrc_number', 'encoded_by', 'label',
+ 'copyright', 'mime', 'language', 'filepath', 'owner_id',
+ 'conductor', 'replay_gain', 'lptime', 'is_playlist', 'is_scheduled',
+ 'cuein', 'cueout', 'description', 'artwork', 'track_type', ];
}
public static function searchLibraryFiles($datatables)
@@ -684,119 +709,106 @@ SQL;
$displayColumns = self::getLibraryColumns();
- $plSelect = array();
- $blSelect = array();
- $fileSelect = array();
- $streamSelect = array();
+ $plSelect = [];
+ $blSelect = [];
+ $fileSelect = [];
+ $streamSelect = [];
foreach ($displayColumns as $key) {
-
- if ($key === "id") {
- $plSelect[] = "PL.id AS ".$key;
- $blSelect[] = "BL.id AS ".$key;
- $fileSelect[] = "FILES.id AS $key";
- $streamSelect[] = "ws.id AS ".$key;
- }
- elseif ($key === "track_title") {
- $plSelect[] = "name AS ".$key;
- $blSelect[] = "name AS ".$key;
- $fileSelect[] = $key;
- $streamSelect[] = "name AS ".$key;
- }
- elseif ($key === "ftype") {
- $plSelect[] = "'playlist'::varchar AS ".$key;
- $blSelect[] = "'block'::varchar AS ".$key;
- $fileSelect[] = $key;
- $streamSelect[] = "'stream'::varchar AS ".$key;
- }
- elseif ($key === "artist_name") {
- $plSelect[] = "login AS ".$key;
- $blSelect[] = "login AS ".$key;
- $fileSelect[] = $key;
- $streamSelect[] = "login AS ".$key;
- }
- elseif ($key === "owner_id") {
- $plSelect[] = "login AS ".$key;
- $blSelect[] = "login AS ".$key;
- $fileSelect[] = "sub.login AS $key";
- $streamSelect[] = "login AS ".$key;
- }
- elseif ($key === "replay_gain") {
- $plSelect[] = "NULL::NUMERIC AS ".$key;
- $blSelect[] = "NULL::NUMERIC AS ".$key;
- $fileSelect[] = $key;
- $streamSelect[] = "NULL::NUMERIC AS ".$key;
- }
- elseif ($key === "lptime") {
- $plSelect[] = "NULL::TIMESTAMP AS ".$key;
- $blSelect[] = "NULL::TIMESTAMP AS ".$key;
- $fileSelect[] = $key;
+ if ($key === 'id') {
+ $plSelect[] = 'PL.id AS ' . $key;
+ $blSelect[] = 'BL.id AS ' . $key;
+ $fileSelect[] = "FILES.id AS {$key}";
+ $streamSelect[] = 'ws.id AS ' . $key;
+ } elseif ($key === 'track_title') {
+ $plSelect[] = 'name AS ' . $key;
+ $blSelect[] = 'name AS ' . $key;
+ $fileSelect[] = $key;
+ $streamSelect[] = 'name AS ' . $key;
+ } elseif ($key === 'ftype') {
+ $plSelect[] = "'playlist'::varchar AS " . $key;
+ $blSelect[] = "'block'::varchar AS " . $key;
+ $fileSelect[] = $key;
+ $streamSelect[] = "'stream'::varchar AS " . $key;
+ } elseif ($key === 'artist_name') {
+ $plSelect[] = 'login AS ' . $key;
+ $blSelect[] = 'login AS ' . $key;
+ $fileSelect[] = $key;
+ $streamSelect[] = 'login AS ' . $key;
+ } elseif ($key === 'owner_id') {
+ $plSelect[] = 'login AS ' . $key;
+ $blSelect[] = 'login AS ' . $key;
+ $fileSelect[] = "sub.login AS {$key}";
+ $streamSelect[] = 'login AS ' . $key;
+ } elseif ($key === 'replay_gain') {
+ $plSelect[] = 'NULL::NUMERIC AS ' . $key;
+ $blSelect[] = 'NULL::NUMERIC AS ' . $key;
+ $fileSelect[] = $key;
+ $streamSelect[] = 'NULL::NUMERIC AS ' . $key;
+ } elseif ($key === 'lptime') {
+ $plSelect[] = 'NULL::TIMESTAMP AS ' . $key;
+ $blSelect[] = 'NULL::TIMESTAMP AS ' . $key;
+ $fileSelect[] = $key;
$streamSelect[] = $key;
- }
- elseif ($key === "is_scheduled" || $key === "is_playlist") {
- $plSelect[] = "NULL::boolean AS ".$key;
- $blSelect[] = "NULL::boolean AS ".$key;
- $fileSelect[] = $key;
- $streamSelect[] = "NULL::boolean AS ".$key;
- }
- elseif ($key === "cuein" || $key === "cueout") {
- $plSelect[] = "NULL::INTERVAL AS ".$key;
- $blSelect[] = "NULL::INTERVAL AS ".$key;
- $fileSelect[] = $key;
- $streamSelect[] = "NULL::INTERVAL AS ".$key;
+ } elseif ($key === 'is_scheduled' || $key === 'is_playlist') {
+ $plSelect[] = 'NULL::boolean AS ' . $key;
+ $blSelect[] = 'NULL::boolean AS ' . $key;
+ $fileSelect[] = $key;
+ $streamSelect[] = 'NULL::boolean AS ' . $key;
+ } elseif ($key === 'cuein' || $key === 'cueout') {
+ $plSelect[] = 'NULL::INTERVAL AS ' . $key;
+ $blSelect[] = 'NULL::INTERVAL AS ' . $key;
+ $fileSelect[] = $key;
+ $streamSelect[] = 'NULL::INTERVAL AS ' . $key;
}
//file length is displayed based on cueout - cuein.
- else if ($key === "length") {
- $plSelect[] = $key;
- $blSelect[] = $key;
- $fileSelect[] = "(cueout - cuein)::INTERVAL AS length";
- $streamSelect[] = $key;
+ elseif ($key === 'length') {
+ $plSelect[] = $key;
+ $blSelect[] = $key;
+ $fileSelect[] = '(cueout - cuein)::INTERVAL AS length';
+ $streamSelect[] = $key;
}
//same columns in each table.
- else if (in_array($key, array("utime", "mtime"))) {
- $plSelect[] = $key;
- $blSelect[] = $key;
- $fileSelect[] = $key;
+ elseif (in_array($key, ['utime', 'mtime'])) {
+ $plSelect[] = $key;
+ $blSelect[] = $key;
+ $fileSelect[] = $key;
$streamSelect[] = $key;
- }
- elseif ($key === "year") {
- $plSelect[] = "EXTRACT(YEAR FROM utime)::varchar AS ".$key;
- $blSelect[] = "EXTRACT(YEAR FROM utime)::varchar AS ".$key;
- $fileSelect[] = "year AS ".$key;
- $streamSelect[] = "EXTRACT(YEAR FROM utime)::varchar AS ".$key;
+ } elseif ($key === 'year') {
+ $plSelect[] = 'EXTRACT(YEAR FROM utime)::varchar AS ' . $key;
+ $blSelect[] = 'EXTRACT(YEAR FROM utime)::varchar AS ' . $key;
+ $fileSelect[] = 'year AS ' . $key;
+ $streamSelect[] = 'EXTRACT(YEAR FROM utime)::varchar AS ' . $key;
}
//need to cast certain data as ints for the union to search on.
- else if (in_array($key, array("track_number", "bit_rate", "sample_rate", "bpm"))) {
- $plSelect[] = "NULL::int AS ".$key;
- $blSelect[] = "NULL::int AS ".$key;
- $fileSelect[] = $key;
- $streamSelect[] = "NULL::int AS ".$key;
- }
- elseif ($key === "filepath") {
- $plSelect[] = "NULL::VARCHAR AS ".$key;
- $blSelect[] = "NULL::VARCHAR AS ".$key;
- $fileSelect[] = $key;
- $streamSelect[] = "url AS ".$key;
- }
- else if ($key == "mime") {
- $plSelect[] = "NULL::VARCHAR AS ".$key;
- $blSelect[] = "NULL::VARCHAR AS ".$key;
- $fileSelect[] = $key;
+ elseif (in_array($key, ['track_number', 'bit_rate', 'sample_rate', 'bpm'])) {
+ $plSelect[] = 'NULL::int AS ' . $key;
+ $blSelect[] = 'NULL::int AS ' . $key;
+ $fileSelect[] = $key;
+ $streamSelect[] = 'NULL::int AS ' . $key;
+ } elseif ($key === 'filepath') {
+ $plSelect[] = 'NULL::VARCHAR AS ' . $key;
+ $blSelect[] = 'NULL::VARCHAR AS ' . $key;
+ $fileSelect[] = $key;
+ $streamSelect[] = 'url AS ' . $key;
+ } elseif ($key == 'mime') {
+ $plSelect[] = 'NULL::VARCHAR AS ' . $key;
+ $blSelect[] = 'NULL::VARCHAR AS ' . $key;
+ $fileSelect[] = $key;
$streamSelect[] = $key;
- }
- else {
- $plSelect[] = "NULL::text AS ".$key;
- $blSelect[] = "NULL::text AS ".$key;
- $fileSelect[] = $key;
- $streamSelect[] = "NULL::text AS ".$key;
+ } else {
+ $plSelect[] = 'NULL::text AS ' . $key;
+ $blSelect[] = 'NULL::text AS ' . $key;
+ $fileSelect[] = $key;
+ $streamSelect[] = 'NULL::text AS ' . $key;
}
}
- $plSelect = "SELECT ". join(",", $plSelect);
- $blSelect = "SELECT ". join(",", $blSelect);
- $fileSelect = "SELECT ". join(",", $fileSelect);
- $streamSelect = "SELECT ". join(",", $streamSelect);
+ $plSelect = 'SELECT ' . join(',', $plSelect);
+ $blSelect = 'SELECT ' . join(',', $blSelect);
+ $fileSelect = 'SELECT ' . join(',', $fileSelect);
+ $streamSelect = 'SELECT ' . join(',', $streamSelect);
- $type = intval($datatables["type"]);
+ $type = intval($datatables['type']);
$plTable = "({$plSelect} FROM cc_playlist AS PL LEFT JOIN cc_subjs AS sub ON (sub.id = PL.creator_id))";
$blTable = "({$blSelect} FROM cc_block AS BL LEFT JOIN cc_subjs AS sub ON (sub.id = BL.creator_id))";
@@ -808,17 +820,25 @@ SQL;
//choose which table we need to select data from.
switch ($type) {
case MediaType::FILE:
- $fromTable = $fileTable." AS File"; //need an alias for the table if it's standalone.
+ $fromTable = $fileTable . ' AS File'; //need an alias for the table if it's standalone.
+
break;
+
case MediaType::PLAYLIST:
- $fromTable = $plTable." AS Playlist"; //need an alias for the table if it's standalone.
+ $fromTable = $plTable . ' AS Playlist'; //need an alias for the table if it's standalone.
+
break;
+
case MediaType::BLOCK:
- $fromTable = $blTable." AS Block"; //need an alias for the table if it's standalone.
+ $fromTable = $blTable . ' AS Block'; //need an alias for the table if it's standalone.
+
break;
+
case MediaType::WEBSTREAM:
- $fromTable = $streamTable." AS StreamTable"; //need an alias for the table if it's standalone.
+ $fromTable = $streamTable . ' AS StreamTable'; //need an alias for the table if it's standalone.
+
break;
+
default:
$fromTable = $unionTable;
}
@@ -829,7 +849,7 @@ SQL;
$results = Application_Model_Datatables::findEntries($con, $displayColumns, $fromTable, $datatables);
$displayTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
- $utcTimezone = new DateTimeZone("UTC");
+ $utcTimezone = new DateTimeZone('UTC');
$storDir = Application_Model_MusicDir::getStorDir();
$fp = $storDir->getDirectory();
@@ -842,23 +862,22 @@ SQL;
if ($r['ftype'] == 'playlist') {
$pl = new Application_Model_Playlist($r['id']);
$r['length'] = $pl->getLength();
- } elseif ($r['ftype'] == "block") {
+ } elseif ($r['ftype'] == 'block') {
$bl = new Application_Model_Block($r['id']);
$r['bl_type'] = $bl->isStatic() ? 'static' : 'dynamic';
- $r['length'] = $bl->getLength();
+ $r['length'] = $bl->getLength();
}
}
- if ($row['ftype'] === "audioclip") {
+ if ($row['ftype'] === 'audioclip') {
+ $cuein_formatter = new LengthFormatter($row['cuein']);
+ $row['cuein'] = $cuein_formatter->format();
- $cuein_formatter = new LengthFormatter($row["cuein"]);
- $row["cuein"] = $cuein_formatter->format();
+ $cueout_formatter = new LengthFormatter($row['cueout']);
+ $row['cueout'] = $cueout_formatter->format();
- $cueout_formatter = new LengthFormatter($row["cueout"]);
- $row["cueout"] = $cueout_formatter->format();
-
- $cuein = Application_Common_DateHelper::playlistTimeToSeconds($row["cuein"]);
- $cueout = Application_Common_DateHelper::playlistTimeToSeconds($row["cueout"]);
+ $cuein = Application_Common_DateHelper::playlistTimeToSeconds($row['cuein']);
+ $cueout = Application_Common_DateHelper::playlistTimeToSeconds($row['cueout']);
$row_length = Application_Common_DateHelper::secondsToPlaylistTime($cueout - $cuein);
$formatter = new SamplerateFormatter($row['sample_rate']);
@@ -871,11 +890,8 @@ SQL;
$row['artwork_data'] = $get_artwork;
// for audio preview
- $row['audioFile'] = $row['id'].".".pathinfo($row['filepath'], PATHINFO_EXTENSION);
-
- }
- else {
-
+ $row['audioFile'] = $row['id'] . '.' . pathinfo($row['filepath'], PATHINFO_EXTENSION);
+ } else {
$row['audioFile'] = $row['id'];
$row_length = $row['length'];
}
@@ -893,16 +909,16 @@ SQL;
//need to convert last played to localtime if it exists.
if (isset($row['lptime'])) {
- $row['lptime'] = new DateTime($row['lptime'], $utcTimezone);
- $row['lptime']->setTimeZone($displayTimezone);
- $row['lptime'] = $row['lptime']->format(DEFAULT_TIMESTAMP_FORMAT);
+ $row['lptime'] = new DateTime($row['lptime'], $utcTimezone);
+ $row['lptime']->setTimeZone($displayTimezone);
+ $row['lptime'] = $row['lptime']->format(DEFAULT_TIMESTAMP_FORMAT);
}
// we need to initalize the checkbox and image row because we do not retrieve
// any data from the db for these and datatables will complain
- $row['checkbox'] = "";
- $row['image'] = "";
- $row['options'] = "";
+ $row['checkbox'] = '';
+ $row['image'] = '';
+ $row['options'] = '';
$type = substr($row['ftype'], 0, 2);
$row['tr_id'] = "{$type}_{$row['id']}";
@@ -928,40 +944,45 @@ SQL;
*
* @param string $tempFilePath
* @param string $originalFilename
- * @param bool $copyFile Copy the file instead of moving it.
+ * @param bool $copyFile copy the file instead of moving it
+ *
* @throws Exception
+ *
* @return Ambigous
*/
- public static function moveFileToStor($tempFilePath, $originalFilename, $copyFile=false)
+ public static function moveFileToStor($tempFilePath, $originalFilename, $copyFile = false)
{
$audio_file = $tempFilePath;
$storDir = Application_Model_MusicDir::getStorDir();
- $stor = $storDir->getDirectory();
+ $stor = $storDir->getDirectory();
// check if "organize" dir exists and if not create one
- if (!file_exists($stor."/organize")) {
- if (!mkdir($stor."/organize", 0777)) {
- throw new Exception("Failed to create organize directory.");
+ if (!file_exists($stor . '/organize')) {
+ if (!mkdir($stor . '/organize', 0777)) {
+ throw new Exception('Failed to create organize directory.');
}
}
if (chmod($audio_file, 0644) === false) {
- Logging::info("Warning: couldn't change permissions of $audio_file to 0644");
+ Logging::info("Warning: couldn't change permissions of {$audio_file} to 0644");
}
// Did all the checks for real, now trying to copy
- $audio_stor = Application_Common_OsPath::join($stor, "organize",
- $originalFilename);
+ $audio_stor = Application_Common_OsPath::join(
+ $stor,
+ 'organize',
+ $originalFilename
+ );
//if the uploaded file is not UTF-8 encoded, let's encode it. Assuming source
//encoding is ISO-8859-1
- $audio_stor = mb_detect_encoding($audio_stor, "UTF-8") == "UTF-8" ? $audio_stor : utf8_encode($audio_stor);
+ $audio_stor = mb_detect_encoding($audio_stor, 'UTF-8') == 'UTF-8' ? $audio_stor : utf8_encode($audio_stor);
if ($copyFile) {
- Logging::info("Copying file $audio_file to $audio_stor");
+ Logging::info("Copying file {$audio_file} to {$audio_stor}");
if (@copy($audio_file, $audio_stor) === false) {
- throw new Exception("Failed to copy $audio_file to $audio_stor");
+ throw new Exception("Failed to copy {$audio_file} to {$audio_stor}");
}
} else {
- Logging::info("Moving file $audio_file to $audio_stor");
+ Logging::info("Moving file {$audio_file} to {$audio_stor}");
//Ensure we have permissions to overwrite the file in stor, in case it already exists.
if (file_exists($audio_stor)) {
@@ -977,53 +998,60 @@ SQL;
//is enough disk space .
unlink($audio_file); //remove the file after failed rename
- throw new Exception("The file was not uploaded, this error can occur if the computer "
- . "hard drive does not have enough disk space or the stor "
- . "directory does not have correct write permissions.");
+ throw new Exception('The file was not uploaded, this error can occur if the computer '
+ . 'hard drive does not have enough disk space or the stor '
+ . 'directory does not have correct write permissions.');
}
}
+
return $audio_stor;
}
- /*
- * Pass the file through Liquidsoap and test if it is readable. Return True if readable, and False otherwise.
- */
+ // Pass the file through Liquidsoap and test if it is readable. Return True if readable, and False otherwise.
public static function liquidsoapFilePlayabilityTest($audio_file)
{
- $LIQUIDSOAP_ERRORS = array('TagLib: MPEG::Properties::read() -- Could not find a valid last MPEG frame in the stream.');
+ $LIQUIDSOAP_ERRORS = ['TagLib: MPEG::Properties::read() -- Could not find a valid last MPEG frame in the stream.'];
// Ask Liquidsoap if file is playable
- /* CC-5990/5991 - Changed to point directly to liquidsoap, removed PATH export */
- $command = sprintf('liquidsoap -v -c "output.dummy(audio_to_stereo(single(%s)))" 2>&1',
- escapeshellarg($audio_file));
+ // CC-5990/5991 - Changed to point directly to liquidsoap, removed PATH export
+ $command = sprintf(
+ 'liquidsoap -v -c "output.dummy(audio_to_stereo(single(%s)))" 2>&1',
+ escapeshellarg($audio_file)
+ );
exec($command, $output, $rv);
$isError = count($output) > 0 && in_array($output[0], $LIQUIDSOAP_ERRORS);
- Logging::info("Is error?! : " . $isError);
- Logging::info("ls playability response: " . $rv);
- return ($rv == 0 && !$isError);
+ Logging::info('Is error?! : ' . $isError);
+ Logging::info('ls playability response: ' . $rv);
+
+ return $rv == 0 && !$isError;
}
public static function getFileCount()
{
- $sql = "SELECT count(*) as cnt FROM cc_files WHERE file_exists";
- return Application_Common_Database::prepareAndExecute($sql, array(),
- Application_Common_Database::COLUMN);
+ $sql = 'SELECT count(*) as cnt FROM cc_files WHERE file_exists';
+
+ return Application_Common_Database::prepareAndExecute(
+ $sql,
+ [],
+ Application_Common_Database::COLUMN
+ );
}
/**
- *
* Enter description here ...
+ *
* @param $dir_id - if this is not provided, it returns all files with full
- * path constructed.
+ * path constructed
+ * @param mixed $all
*/
- public static function listAllFiles($dir_id=null, $all=true)
+ public static function listAllFiles($dir_id = null, $all = true)
{
$con = Propel::getConnection();
- $sql = <<fetchAll();
} else {
$msg = implode(',', $stmt->errorInfo());
- throw new Exception("Error: $msg");
+
+ throw new Exception("Error: {$msg}");
}
- $results = array();
+ $results = [];
foreach ($rows as $row) {
- $results[] = $row["fp"];
+ $results[] = $row['fp'];
}
return $results;
}
//TODO: MERGE THIS FUNCTION AND "listAllFiles" -MK
- public static function listAllFiles2($dir_id=null, $limit="ALL")
+ public static function listAllFiles2($dir_id = null, $limit = 'ALL')
{
$con = Propel::getConnection();
- $sql = <<fetchAll(PDO::FETCH_ASSOC);
} else {
$msg = implode(',', $stmt->errorInfo());
- throw new Exception("Error: $msg");
+
+ throw new Exception("Error: {$msg}");
}
return $rows;
}
- public static function getAllFilesWithoutSilan() {
+ public static function getAllFilesWithoutSilan()
+ {
$con = Propel::getConnection();
- $sql = <<fetchAll(PDO::FETCH_ASSOC);
} else {
$msg = implode(',', $stmt->errorInfo());
- throw new Exception("Error: $msg");
+
+ throw new Exception("Error: {$msg}");
}
return $rows;
@@ -1110,12 +1142,15 @@ SQL;
public function setFileExistsFlag($flag)
{
$this->_file->setDbFileExists($flag)
- ->save();
+ ->save()
+ ;
}
+
public function setFileHiddenFlag($flag)
{
$this->_file->setDbHidden($flag)
- ->save();
+ ->save()
+ ;
}
// This method seems to be unsued everywhere so I've commented it out
@@ -1123,7 +1158,7 @@ SQL;
// removed soon
//public function getFileExistsFlag()
//{
- //return $this->_file->getDbFileExists();
+ //return $this->_file->getDbFileExists();
//}
public function getFileOwnerId()
@@ -1131,8 +1166,8 @@ SQL;
return $this->_file->getDbOwnerId();
}
-
- public static function setIsPlaylist($p_playlistItems, $p_type, $p_status) {
+ public static function setIsPlaylist($p_playlistItems, $p_type, $p_status)
+ {
foreach ($p_playlistItems as $item) {
$file = self::RecallById($item->getDbFileId());
$fileId = $file->_file->getDbId();
@@ -1150,13 +1185,15 @@ SQL;
}
}
- public static function setIsScheduled($fileId, $status) {
-
+ public static function setIsScheduled($fileId, $status)
+ {
$file = self::RecallById($fileId);
$updateIsScheduled = false;
- if (!is_null($fileId) && !in_array($fileId,
- Application_Model_Schedule::getAllFutureScheduledFiles())) {
+ if (!is_null($fileId) && !in_array(
+ $fileId,
+ Application_Model_Schedule::getAllFutureScheduledFiles()
+ )) {
$file->_file->setDbIsScheduled($status)->save();
$updateIsScheduled = true;
}
@@ -1165,7 +1202,6 @@ SQL;
}
/**
- *
* 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.
@@ -1197,6 +1233,12 @@ SQL;
}
}
-class DeleteScheduledFileException extends Exception {}
-class FileDoesNotExistException extends Exception {}
-class FileNoPermissionException extends Exception {}
+class DeleteScheduledFileException extends Exception
+{
+}
+class FileDoesNotExistException extends Exception
+{
+}
+class FileNoPermissionException extends Exception
+{
+}
diff --git a/legacy/application/models/StreamSetting.php b/legacy/application/models/StreamSetting.php
index 4454560f0..f11ff7817 100644
--- a/legacy/application/models/StreamSetting.php
+++ b/legacy/application/models/StreamSetting.php
@@ -1,6 +1,6 @@
prepare($sql);
$stmt->bindParam(':key', $key);
-
+
if ($stmt->execute()) {
$result = $stmt->fetchColumn(0);
} else {
$msg = implode(',', $stmt->errorInfo());
- throw new Exception("Error: $msg");
+
+ throw new Exception("Error: {$msg}");
}
if ($result == 1) {
- $sql = "UPDATE cc_stream_setting"
- ." SET value = :value, type = :type"
- ." WHERE keyname = :key";
+ $sql = 'UPDATE cc_stream_setting'
+ . ' SET value = :value, type = :type'
+ . ' WHERE keyname = :key';
} else {
- $sql = "INSERT INTO cc_stream_setting (keyname, value, type)"
- ." VALUES (:key, :value, :type)";
+ $sql = 'INSERT INTO cc_stream_setting (keyname, value, type)'
+ . ' VALUES (:key, :value, :type)';
}
$stmt = $con->prepare($sql);
$stmt->bindParam(':key', $key);
$stmt->bindParam(':value', $value);
$stmt->bindParam(':type', $type);
-
+
if ($stmt->execute()) {
//do nothing
} else {
$msg = implode(',', $stmt->errorInfo());
- throw new Exception("Error: $msg");
+
+ throw new Exception("Error: {$msg}");
}
}
- public static function getValue($key, $default="")
+ public static function getValue($key, $default = '')
{
$con = Propel::getConnection();
-
+
//Check if key already exists
- $sql = "SELECT value FROM cc_stream_setting"
- ." WHERE keyname = :key";
+ $sql = 'SELECT value FROM cc_stream_setting'
+ . ' WHERE keyname = :key';
$stmt = $con->prepare($sql);
$stmt->bindParam(':key', $key);
-
+
if ($stmt->execute()) {
$result = $stmt->fetchColumn(0);
} else {
$msg = implode(',', $stmt->errorInfo());
- throw new Exception("Error: $msg");
+
+ throw new Exception("Error: {$msg}");
}
return $result ? $result : $default;
@@ -67,26 +70,27 @@ class Application_Model_StreamSetting
public static function getEnabledStreamData()
{
- $streams = Array();
+ $streams = [];
$streamIds = self::getEnabledStreamIds();
foreach ($streamIds as $id) {
$streamData = self::getStreamData($id);
- $prefix = $id."_";
- $host = $streamData[$prefix."host"];
- $port = $streamData[$prefix."port"];
- $mount = $streamData[$prefix."mount"];
- if ($streamData[$prefix."output"] == "shoutcast") {
- $url = "http://$host:$port/;"; //The semi-colon is important to make Shoutcast stream URLs play instead turn into a page.
+ $prefix = $id . '_';
+ $host = $streamData[$prefix . 'host'];
+ $port = $streamData[$prefix . 'port'];
+ $mount = $streamData[$prefix . 'mount'];
+ if ($streamData[$prefix . 'output'] == 'shoutcast') {
+ $url = "http://{$host}:{$port}/;"; //The semi-colon is important to make Shoutcast stream URLs play instead turn into a page.
} else { //Icecast
- $url = "http://$host:$port/$mount";
+ $url = "http://{$host}:{$port}/{$mount}";
}
- $streams[$id] = Array(
- "url" => $url,
- "codec" => $streamData[$prefix."type"],
- "bitrate" => $streamData[$prefix."bitrate"],
- "mobile" => $streamData[$prefix."mobile"]
- );
+ $streams[$id] = [
+ 'url' => $url,
+ 'codec' => $streamData[$prefix . 'type'],
+ 'bitrate' => $streamData[$prefix . 'bitrate'],
+ 'mobile' => $streamData[$prefix . 'mobile'],
+ ];
}
+
return $streams;
}
@@ -95,17 +99,17 @@ class Application_Model_StreamSetting
public static function getEnabledStreamIds()
{
$con = Propel::getConnection();
- $sql = "SELECT * "
- ."FROM cc_stream_setting "
- ."WHERE keyname LIKE '%_enable' "
- ."AND value='true'";
+ $sql = 'SELECT * '
+ . 'FROM cc_stream_setting '
+ . "WHERE keyname LIKE '%_enable' "
+ . "AND value='true'";
- $ids = array();
-
- $rows = Application_Common_Database::prepareAndExecute($sql, array(), 'all');
+ $ids = [];
+
+ $rows = Application_Common_Database::prepareAndExecute($sql, [], 'all');
foreach ($rows as $row) {
- $ids[] = substr($row["keyname"], 0, strpos($row["keyname"], "_"));
+ $ids[] = substr($row['keyname'], 0, strpos($row['keyname'], '_'));
}
return $ids;
@@ -116,33 +120,32 @@ class Application_Model_StreamSetting
public static function getStreamData($p_streamId)
{
$rows = CcStreamSettingQuery::create()
- ->filterByDbKeyName("${p_streamId}_%")
- ->find();
+ ->filterByDbKeyName("{$p_streamId}_%")
+ ->find()
+ ;
//This is way too much code because someone made only stupid decisions about how
//the layout of this table worked. The git history doesn't lie.
- $data = array();
+ $data = [];
foreach ($rows as $row) {
$key = $row->getDbKeyName();
$value = $row->getDbValue();
$type = $row->getDbType();
//Fix stupid defaults so we end up with proper typing in our JSON
- if ($row->getDbType() == "boolean") {
+ if ($row->getDbType() == 'boolean') {
if (empty($value)) {
//In Python, there is no way to tell the difference between ints and booleans,
//which we need to differentiate between for when we're generating the Liquidsoap
//config file. Returning booleans as a string is a workaround that lets us do that.
- $value = "false";
+ $value = 'false';
}
$data[$key] = $value;
- }
- elseif ($row->getDbType() == "integer") {
+ } elseif ($row->getDbType() == 'integer') {
if (empty($value)) {
$value = 0;
}
$data[$key] = intval($value);
- }
- else {
+ } else {
$data[$key] = $value;
}
}
@@ -152,12 +155,12 @@ class Application_Model_StreamSetting
self::ensureKeyExists($keyPrefix . 'admin_pass', $data);
self::ensureKeyExists($keyPrefix . 'admin_user', $data);
self::ensureKeyExists($keyPrefix . 'bitrate', $data, 128);
- self::ensureKeyExists($keyPrefix . 'channels', $data, "stereo");
+ self::ensureKeyExists($keyPrefix . 'channels', $data, 'stereo');
self::ensureKeyExists($keyPrefix . 'description', $data);
- self::ensureKeyExists($keyPrefix . 'enable', $data, "false");
+ self::ensureKeyExists($keyPrefix . 'enable', $data, 'false');
self::ensureKeyExists($keyPrefix . 'genre', $data);
self::ensureKeyExists($keyPrefix . 'host', $data);
- self::ensureKeyExists($keyPrefix . 'liquidsoap_error', $data, "waiting");
+ self::ensureKeyExists($keyPrefix . 'liquidsoap_error', $data, 'waiting');
self::ensureKeyExists($keyPrefix . 'mount', $data);
self::ensureKeyExists($keyPrefix . 'name', $data);
self::ensureKeyExists($keyPrefix . 'output', $data);
@@ -176,43 +179,43 @@ class Application_Model_StreamSetting
public static function getStreamDataNormalized($p_streamId)
{
$settings = self::getStreamData($p_streamId);
- foreach ($settings as $key => $value)
- {
+ foreach ($settings as $key => $value) {
unset($settings[$key]);
- $newKey = substr($key, strlen($p_streamId)+1); //$p_streamId is assumed to be the key prefix.
+ $newKey = substr($key, strlen($p_streamId) + 1); //$p_streamId is assumed to be the key prefix.
$settings[$newKey] = $value;
}
+
return $settings;
}
- private static function ensureKeyExists($key, &$array, $default='')
+ private static function ensureKeyExists($key, &$array, $default = '')
{
if (!array_key_exists($key, $array)) {
$array[$key] = $default;
}
+
return $array;
}
public static function getStreamSetting()
{
- $settings = array();
+ $settings = [];
$numStreams = MAX_NUM_STREAMS;
- for ($streamIdx = 1; $streamIdx <= $numStreams; $streamIdx++)
- {
- $settings = array_merge($settings, self::getStreamData("s" . $streamIdx));
+ for ($streamIdx = 1; $streamIdx <= $numStreams; ++$streamIdx) {
+ $settings = array_merge($settings, self::getStreamData('s' . $streamIdx));
}
- $settings["master_live_stream_port"] = self::getMasterLiveStreamPort();
- $settings["master_live_stream_mp"] = self::getMasterLiveStreamMountPoint();
- $settings["dj_live_stream_port"] = self::getDjLiveStreamPort();
- $settings["dj_live_stream_mp"] = self::getDjLiveStreamMountPoint();
- $settings["off_air_meta"] = self::getOffAirMeta();
- $settings["icecast_vorbis_metadata"] = self::getIcecastVorbisMetadata();
- $settings["output_sound_device"] = self::getOutputSoundDevice();
- $settings["output_sound_device_type"] = self::getOutputSoundDeviceType();
+ $settings['master_live_stream_port'] = self::getMasterLiveStreamPort();
+ $settings['master_live_stream_mp'] = self::getMasterLiveStreamMountPoint();
+ $settings['dj_live_stream_port'] = self::getDjLiveStreamPort();
+ $settings['dj_live_stream_mp'] = self::getDjLiveStreamMountPoint();
+ $settings['off_air_meta'] = self::getOffAirMeta();
+ $settings['icecast_vorbis_metadata'] = self::getIcecastVorbisMetadata();
+ $settings['output_sound_device'] = self::getOutputSoundDevice();
+ $settings['output_sound_device_type'] = self::getOutputSoundDeviceType();
+
return $settings;
}
-
private static function saveStreamSetting($key, $value)
{
$stream_setting = CcStreamSettingQuery::create()->filterByDbKeyName($key)->findOne();
@@ -220,7 +223,7 @@ class Application_Model_StreamSetting
//throw new Exception("Keyname $key does not exist!");
$stream_setting = new CcStreamSetting();
$stream_setting->setDbKeyName($key);
- $stream_setting->setDbType("");
+ $stream_setting->setDbType('');
}
$stream_setting->setDbValue($value);
@@ -237,11 +240,11 @@ class Application_Model_StreamSetting
public static function setStreamSetting($data)
{
foreach ($data as $key => $d) {
- if ($key == "output_sound_device" || $key == "icecast_vorbis_metadata") {
- $v = ($d == 1) ? "true" : "false";
+ if ($key == 'output_sound_device' || $key == 'icecast_vorbis_metadata') {
+ $v = ($d == 1) ? 'true' : 'false';
self::saveStreamSetting($key, $v);
- } elseif ($key == "output_sound_device_type") {
+ } elseif ($key == 'output_sound_device_type') {
self::saveStreamSetting($key, $d);
} elseif (is_array($d)) {
$temp = explode('_', $key);
@@ -251,7 +254,7 @@ class Application_Model_StreamSetting
$d = array_merge($d, static::getDefaults($prefix));
}
foreach ($d as $k => $v) {
- $keyname = $prefix . "_" . $k;
+ $keyname = $prefix . '_' . $k;
if ($k == 'enable') {
$v = $d['enable'] == 1 ? 'true' : 'false';
}
@@ -270,23 +273,25 @@ class Application_Model_StreamSetting
}
/**
- * SAAS-876 - Get the default stream settings values for Airtime Pro streaming
+ * SAAS-876 - Get the default stream settings values for Airtime Pro streaming.
*
* @param int $prefix
*
* @return array array of default stream setting values
*/
- public static function getDefaults($prefix) {
+ public static function getDefaults($prefix)
+ {
$config = Config::getConfig();
- return array(
- 'host' => $config['baseUrl'],
- 'port' => DEFAULT_ICECAST_PORT,
+
+ return [
+ 'host' => $config['baseUrl'],
+ 'port' => DEFAULT_ICECAST_PORT,
'output' => 'icecast',
- 'user' => $config['stationId'],
- 'pass' => Application_Model_Preference::getDefaultIcecastPassword(),
+ 'user' => $config['stationId'],
+ 'pass' => Application_Model_Preference::getDefaultIcecastPassword(),
// Manually setting default mountpoint
- 'mount' => 'airtime_128',
- );
+ 'mount' => 'airtime_128',
+ ];
}
/*
@@ -300,58 +305,62 @@ class Application_Model_StreamSetting
public static function setIndividualStreamSetting($data)
{
foreach ($data as $keyname => $v) {
- $sql = "UPDATE cc_stream_setting SET value=:v WHERE keyname=:keyname";
- $map = array(":v" => $v, ":keyname"=>$keyname);
+ $sql = 'UPDATE cc_stream_setting SET value=:v WHERE keyname=:keyname';
+ $map = [':v' => $v, ':keyname' => $keyname];
- $res = Application_Common_Database::prepareAndExecute($sql, $map,
- Application_Common_Database::EXECUTE);
+ $res = Application_Common_Database::prepareAndExecute(
+ $sql,
+ $map,
+ Application_Common_Database::EXECUTE
+ );
}
}
-
/*
* Stores liquidsoap status if $boot_time > save time.
* save time is the time that user clicked save on stream setting page
*/
- public static function setLiquidsoapError($stream_id, $msg, $boot_time=null)
+ public static function setLiquidsoapError($stream_id, $msg, $boot_time = null)
{
$con = Propel::getConnection();
$update_time = Application_Model_Preference::GetStreamUpdateTimestemp();
-
+
if ($boot_time == null || $boot_time > $update_time) {
- $keyname = "s".$stream_id."_liquidsoap_error";
- $sql = "SELECT COUNT(*) FROM cc_stream_setting"
- ." WHERE keyname = :keyname";
+ $keyname = 's' . $stream_id . '_liquidsoap_error';
+ $sql = 'SELECT COUNT(*) FROM cc_stream_setting'
+ . ' WHERE keyname = :keyname';
$stmt = $con->prepare($sql);
$stmt->bindParam(':keyname', $keyname);
if ($stmt->execute()) {
- $result= $stmt->fetchColumn(0);
+ $result = $stmt->fetchColumn(0);
} else {
$msg = implode(',', $stmt->errorInfo());
- throw new Exception("Error: $msg");
+
+ throw new Exception("Error: {$msg}");
}
if ($result == 1) {
- $sql = "UPDATE cc_stream_setting"
- ." SET value = :msg"
- ." WHERE keyname = :keyname";
+ $sql = 'UPDATE cc_stream_setting'
+ . ' SET value = :msg'
+ . ' WHERE keyname = :keyname';
} else {
- $sql = "INSERT INTO cc_stream_setting (keyname, value, type)"
- ." VALUES (:keyname, :msg, 'string')";
+ $sql = 'INSERT INTO cc_stream_setting (keyname, value, type)'
+ . " VALUES (:keyname, :msg, 'string')";
}
$stmt = $con->prepare($sql);
$stmt->bindParam(':keyname', $keyname);
$stmt->bindParam(':msg', $msg);
-
+
if ($stmt->execute()) {
//do nothing
} else {
$msg = implode(',', $stmt->errorInfo());
- throw new Exception("Error: $msg");
+
+ throw new Exception("Error: {$msg}");
}
}
}
@@ -360,18 +369,19 @@ class Application_Model_StreamSetting
{
$con = Propel::getConnection();
- $keyname = "s".$stream_id."_liquidsoap_error";
- $sql = "SELECT value FROM cc_stream_setting"
- ." WHERE keyname = :keyname";
+ $keyname = 's' . $stream_id . '_liquidsoap_error';
+ $sql = 'SELECT value FROM cc_stream_setting'
+ . ' WHERE keyname = :keyname';
$stmt = $con->prepare($sql);
$stmt->bindParam(':keyname', $keyname);
if ($stmt->execute()) {
- $result= $stmt->fetchColumn(0);
+ $result = $stmt->fetchColumn(0);
} else {
$msg = implode(',', $stmt->errorInfo());
- throw new Exception("Error: $msg");
+
+ throw new Exception("Error: {$msg}");
}
return ($result !== false) ? $result : null;
@@ -381,21 +391,22 @@ class Application_Model_StreamSetting
{
$con = Propel::getConnection();
- $keyname = "s" . $stream_id . "_enable";
- $sql = "SELECT value FROM cc_stream_setting"
- ." WHERE keyname = :keyname";
+ $keyname = 's' . $stream_id . '_enable';
+ $sql = 'SELECT value FROM cc_stream_setting'
+ . ' WHERE keyname = :keyname';
$stmt = $con->prepare($sql);
$stmt->bindParam(':keyname', $keyname);
if ($stmt->execute()) {
- $result= $stmt->fetchColumn(0);
+ $result = $stmt->fetchColumn(0);
} else {
$msg = implode(',', $stmt->errorInfo());
- throw new Exception("Error: $msg");
+
+ throw new Exception("Error: {$msg}");
}
- return ($result != 'false');
+ return $result != 'false';
}
/*
@@ -406,15 +417,15 @@ class Application_Model_StreamSetting
{
$con = Propel::getConnection();
- $out = array();
+ $out = [];
$enabled_stream = self::getEnabledStreamIds();
foreach ($enabled_stream as $stream) {
- $keys = array("{$stream}_output", "{$stream}_type", "{$stream}_bitrate", "{$stream}_host");
+ $keys = ["{$stream}_output", "{$stream}_type", "{$stream}_bitrate", "{$stream}_host"];
$key_csv = implode(',', $keys);
- $sql = "SELECT keyname, value FROM cc_stream_setting"
- ." WHERE keyname IN (:key_csv)";
+ $sql = 'SELECT keyname, value FROM cc_stream_setting'
+ . ' WHERE keyname IN (:key_csv)';
$stmt = $con->prepare($sql);
$stmt->bindParam(':key_csv', $key_csv);
@@ -423,12 +434,13 @@ class Application_Model_StreamSetting
$rows = $stmt->fetchAll();
} else {
$msg = implode(',', $stmt->errorInfo());
- throw new Exception("Error: $msg");
+
+ throw new Exception("Error: {$msg}");
}
- $info = array();
+ $info = [];
foreach ($rows as $r) {
- $temp = explode("_", $r['keyname']);
+ $temp = explode('_', $r['keyname']);
$info[$temp[1]] = $r['value'];
$out[$stream] = $info;
}
@@ -439,98 +451,109 @@ class Application_Model_StreamSetting
public static function setMasterLiveStreamPort($value)
{
- self::setValue("master_live_stream_port", $value, "integer");
+ self::setValue('master_live_stream_port', $value, 'integer');
}
public static function getMasterLiveStreamPort()
{
- return self::getValue("master_live_stream_port", 8001);
+ return self::getValue('master_live_stream_port', 8001);
}
public static function setMasterLiveStreamMountPoint($value)
{
- self::setValue("master_live_stream_mp", $value, "string");
+ self::setValue('master_live_stream_mp', $value, 'string');
}
public static function getMasterLiveStreamMountPoint()
{
- return self::getValue("master_live_stream_mp", "/master");
+ return self::getValue('master_live_stream_mp', '/master');
}
public static function setDjLiveStreamPort($value)
{
- self::setValue("dj_live_stream_port", $value, "integer");
+ self::setValue('dj_live_stream_port', $value, 'integer');
}
public static function getDjLiveStreamPort()
{
- return self::getValue("dj_live_stream_port", 8002);
+ return self::getValue('dj_live_stream_port', 8002);
}
public static function setDjLiveStreamMountPoint($value)
{
- self::setValue("dj_live_stream_mp", $value, "string");
+ self::setValue('dj_live_stream_mp', $value, 'string');
}
public static function getDjLiveStreamMountPoint()
{
- return self::getValue("dj_live_stream_mp", "/show");
+ return self::getValue('dj_live_stream_mp', '/show');
}
-
- public static function getAdminUser($stream){
- return self::getValue($stream."_admin_user");
- }
-
- public static function setAdminUser($stream, $v){
- self::setValue($stream."_admin_user", $v, "string");
- }
-
- public static function getAdminPass($stream){
- return self::getValue($stream."_admin_pass");
- }
-
- public static function setAdminPass($stream, $v){
- self::setValue($stream."_admin_pass", $v, "string");
- }
-
- public static function getOffAirMeta(){
- return self::getValue("off_air_meta");
- }
-
- public static function setOffAirMeta($offAirMeta){
- self::setValue("off_air_meta", $offAirMeta, "string");
- }
-
- public static function GetAllListenerStatErrors(){
- $sql = "SELECT * FROM cc_stream_setting WHERE keyname like :p1";
- $mounts = Application_Common_Database::prepareAndExecute($sql, array(':p1'=>'%_mount'));
-
- $mps = array();
-
- foreach($mounts as $mount) {
- $mps[] = "'" .$mount["value"] . "_listener_stat_error'";
- }
-
- $in = implode(",", $mps);
-
- $sql = "SELECT * FROM cc_stream_setting WHERE keyname IN ( $in )";
- return Application_Common_Database::prepareAndExecute($sql, array());
+ public static function getAdminUser($stream)
+ {
+ return self::getValue($stream . '_admin_user');
}
-
- public static function SetListenerStatError($key, $v) {
+
+ public static function setAdminUser($stream, $v)
+ {
+ self::setValue($stream . '_admin_user', $v, 'string');
+ }
+
+ public static function getAdminPass($stream)
+ {
+ return self::getValue($stream . '_admin_pass');
+ }
+
+ public static function setAdminPass($stream, $v)
+ {
+ self::setValue($stream . '_admin_pass', $v, 'string');
+ }
+
+ public static function getOffAirMeta()
+ {
+ return self::getValue('off_air_meta');
+ }
+
+ public static function setOffAirMeta($offAirMeta)
+ {
+ self::setValue('off_air_meta', $offAirMeta, 'string');
+ }
+
+ public static function GetAllListenerStatErrors()
+ {
+ $sql = 'SELECT * FROM cc_stream_setting WHERE keyname like :p1';
+ $mounts = Application_Common_Database::prepareAndExecute($sql, [':p1' => '%_mount']);
+
+ $mps = [];
+
+ foreach ($mounts as $mount) {
+ $mps[] = "'" . $mount['value'] . "_listener_stat_error'";
+ }
+
+ $in = implode(',', $mps);
+
+ $sql = "SELECT * FROM cc_stream_setting WHERE keyname IN ( {$in} )";
+
+ return Application_Common_Database::prepareAndExecute($sql, []);
+ }
+
+ public static function SetListenerStatError($key, $v)
+ {
self::setValue($key, $v, 'string');
}
- public static function getIcecastVorbisMetadata() {
- return self::getValue("icecast_vorbis_metadata", "");
+ public static function getIcecastVorbisMetadata()
+ {
+ return self::getValue('icecast_vorbis_metadata', '');
}
- public static function getOutputSoundDevice() {
- return self::getValue("output_sound_device", "false");
+ public static function getOutputSoundDevice()
+ {
+ return self::getValue('output_sound_device', 'false');
}
- public static function getOutputSoundDeviceType() {
- return self::getValue("output_sound_device_type", "");
+ public static function getOutputSoundDeviceType()
+ {
+ return self::getValue('output_sound_device_type', '');
}
}
diff --git a/legacy/application/models/Subjects.php b/legacy/application/models/Subjects.php
index ab03bfb87..e6adc1859 100644
--- a/legacy/application/models/Subjects.php
+++ b/legacy/application/models/Subjects.php
@@ -1,54 +1,60 @@
$login);
+ $map = [':login' => $login];
- $res = Application_Common_Database::prepareAndExecute($sql, $map,
- Application_Common_Database::EXECUTE);
+ $res = Application_Common_Database::prepareAndExecute(
+ $sql,
+ $map,
+ Application_Common_Database::EXECUTE
+ );
- return (intval($res) > 0);
+ return intval($res) > 0;
}
public static function resetLoginAttempts($login)
{
$sql = "UPDATE cc_subjs SET login_attempts = '0'"
- ." WHERE login=:login";
- $map = array(":login" => $login);
+ . ' WHERE login=:login';
+ $map = [':login' => $login];
- $res = Application_Common_Database::prepareAndExecute($sql, $map,
- Application_Common_Database::EXECUTE);
+ $res = Application_Common_Database::prepareAndExecute(
+ $sql,
+ $map,
+ Application_Common_Database::EXECUTE
+ );
return true;
}
public static function getLoginAttempts($login)
{
- $sql = "SELECT login_attempts FROM cc_subjs WHERE login=:login";
- $map = array(":login" => $login);
-
- $res = Application_Common_Database::prepareAndExecute($sql, $map,
- Application_Common_Database::COLUMN);
+ $sql = 'SELECT login_attempts FROM cc_subjs WHERE login=:login';
+ $map = [':login' => $login];
+
+ $res = Application_Common_Database::prepareAndExecute(
+ $sql,
+ $map,
+ Application_Common_Database::COLUMN
+ );
return ($res !== false) ? $res : 0;
}
-
} // class Subjects
diff --git a/legacy/application/models/Systemstatus.php b/legacy/application/models/Systemstatus.php
index e417a2745..d7ffbbd95 100644
--- a/legacy/application/models/Systemstatus.php
+++ b/legacy/application/models/Systemstatus.php
@@ -2,14 +2,13 @@
class Application_Model_Systemstatus
{
-
public static function GetMonitStatus($p_ip)
{
$CC_CONFIG = Config::getConfig();
// $monit_user = $CC_CONFIG['monit_user'];
// $monit_password = $CC_CONFIG['monit_password'];
- $url = "http://$p_ip:2812/_status?format=xml";
+ $url = "http://{$p_ip}:2812/_status?format=xml";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
@@ -23,8 +22,8 @@ class Application_Model_Systemstatus
curl_close($ch);
$docRoot = null;
- if ($result !== FALSE && $info["http_code"] === 200) {
- if ($result != "") {
+ if ($result !== false && $info['http_code'] === 200) {
+ if ($result != '') {
$xmlDoc = new DOMDocument();
$xmlDoc->loadXML($result);
$docRoot = $xmlDoc->documentElement;
@@ -36,84 +35,83 @@ class Application_Model_Systemstatus
public static function ExtractServiceInformation($p_docRoot, $p_serviceName)
{
- $starting = array(
- "name"=>"",
- "process_id"=>"STARTING...",
- "uptime_seconds"=>"-1",
- "status"=>0,
- "memory_perc"=>"0%",
- "memory_kb"=>"0",
- "cpu_perc"=>"0%");
+ $starting = [
+ 'name' => '',
+ 'process_id' => 'STARTING...',
+ 'uptime_seconds' => '-1',
+ 'status' => 0,
+ 'memory_perc' => '0%',
+ 'memory_kb' => '0',
+ 'cpu_perc' => '0%', ];
- $notMonitored = array(
- "name"=>$p_serviceName,
- "process_id"=>"NOT MONITORED",
- "uptime_seconds"=>"1",
- "status"=>1,
- "memory_perc"=>"0%",
- "memory_kb"=>"0",
- "cpu_perc"=>"0%"
- );
+ $notMonitored = [
+ 'name' => $p_serviceName,
+ 'process_id' => 'NOT MONITORED',
+ 'uptime_seconds' => '1',
+ 'status' => 1,
+ 'memory_perc' => '0%',
+ 'memory_kb' => '0',
+ 'cpu_perc' => '0%',
+ ];
- $notRunning = array(
- "name"=>$p_serviceName,
- "process_id"=>"FAILED",
- "uptime_seconds"=>"-1",
- "status"=>0,
- "memory_perc"=>"0%",
- "memory_kb"=>"0",
- "cpu_perc"=>"0%"
- );
+ $notRunning = [
+ 'name' => $p_serviceName,
+ 'process_id' => 'FAILED',
+ 'uptime_seconds' => '-1',
+ 'status' => 0,
+ 'memory_perc' => '0%',
+ 'memory_kb' => '0',
+ 'cpu_perc' => '0%',
+ ];
$data = $notRunning;
if (!is_null($p_docRoot)) {
- foreach ($p_docRoot->getElementsByTagName("service") AS $item) {
- if ($item->getElementsByTagName("name")->item(0)->nodeValue == $p_serviceName) {
-
- $monitor = $item->getElementsByTagName("monitor");
+ foreach ($p_docRoot->getElementsByTagName('service') as $item) {
+ if ($item->getElementsByTagName('name')->item(0)->nodeValue == $p_serviceName) {
+ $monitor = $item->getElementsByTagName('monitor');
if ($monitor->length > 0) {
$status = $monitor->item(0)->nodeValue;
- if ($status == "2") {
+ if ($status == '2') {
$data = $starting;
} elseif ($status == 1) {
//is monitored, but is it running?
- $pid = $item->getElementsByTagName("pid");
+ $pid = $item->getElementsByTagName('pid');
if ($pid->length == 0) {
$data = $notRunning;
- } else {
- //running!
}
+ //running!
} elseif ($status == 0) {
$data = $notMonitored;
}
}
- $process_id = $item->getElementsByTagName("name");
+ $process_id = $item->getElementsByTagName('name');
if ($process_id->length > 0) {
- $data["name"] = $process_id->item(0)->nodeValue;
+ $data['name'] = $process_id->item(0)->nodeValue;
}
- $process_id = $item->getElementsByTagName("pid");
+ $process_id = $item->getElementsByTagName('pid');
if ($process_id->length > 0) {
- $data["process_id"] = $process_id->item(0)->nodeValue;
- $data["status"] = 0;
+ $data['process_id'] = $process_id->item(0)->nodeValue;
+ $data['status'] = 0;
}
- $uptime = $item->getElementsByTagName("uptime");
+ $uptime = $item->getElementsByTagName('uptime');
if ($uptime->length > 0) {
- $data["uptime_seconds"] = $uptime->item(0)->nodeValue;
+ $data['uptime_seconds'] = $uptime->item(0)->nodeValue;
}
- $memory = $item->getElementsByTagName("memory");
+ $memory = $item->getElementsByTagName('memory');
if ($memory->length > 0) {
- $data["memory_perc"] = $memory->item(0)->getElementsByTagName("percenttotal")->item(0)->nodeValue."%";
- $data["memory_kb"] = $memory->item(0)->getElementsByTagName("kilobytetotal")->item(0)->nodeValue;
+ $data['memory_perc'] = $memory->item(0)->getElementsByTagName('percenttotal')->item(0)->nodeValue . '%';
+ $data['memory_kb'] = $memory->item(0)->getElementsByTagName('kilobytetotal')->item(0)->nodeValue;
}
- $cpu = $item->getElementsByTagName("cpu");
+ $cpu = $item->getElementsByTagName('cpu');
if ($cpu->length > 0) {
- $data["cpu_perc"] = $cpu->item(0)->getElementsByTagName("percent")->item(0)->nodeValue."%";
+ $data['cpu_perc'] = $cpu->item(0)->getElementsByTagName('percent')->item(0)->nodeValue . '%';
}
+
break;
}
}
@@ -124,15 +122,15 @@ class Application_Model_Systemstatus
public static function GetPlatformInfo()
{
- $keys = array("release", "machine", "memory", "swap");
- $data = array();
+ $keys = ['release', 'machine', 'memory', 'swap'];
+ $data = [];
foreach ($keys as $key) {
- $data[$key] = "UNKNOWN";
+ $data[$key] = 'UNKNOWN';
}
- $docRoot = self::GetMonitStatus("localhost");
+ $docRoot = self::GetMonitStatus('localhost');
if (!is_null($docRoot)) {
- foreach ($docRoot->getElementsByTagName("platform") AS $item) {
+ foreach ($docRoot->getElementsByTagName('platform') as $item) {
foreach ($keys as $key) {
$keyElement = $item->getElementsByTagName($key);
if ($keyElement->length > 0) {
@@ -147,73 +145,66 @@ class Application_Model_Systemstatus
public static function GetPypoStatus()
{
- $component = CcServiceRegisterQuery::create()->findOneByDbName("pypo");
+ $component = CcServiceRegisterQuery::create()->findOneByDbName('pypo');
if (is_null($component)) {
return null;
- } else {
- $ip = $component->getDbIp();
-
- $docRoot = self::GetMonitStatus($ip);
- $data = self::ExtractServiceInformation($docRoot, "airtime-playout");
-
- return $data;
}
+ $ip = $component->getDbIp();
+
+ $docRoot = self::GetMonitStatus($ip);
+
+ return self::ExtractServiceInformation($docRoot, 'airtime-playout');
}
public static function GetLiquidsoapStatus()
{
- $component = CcServiceRegisterQuery::create()->findOneByDbName("pypo");
+ $component = CcServiceRegisterQuery::create()->findOneByDbName('pypo');
if (is_null($component)) {
return null;
- } else {
- $ip = $component->getDbIp();
-
- $docRoot = self::GetMonitStatus($ip);
- $data = self::ExtractServiceInformation($docRoot, "airtime-liquidsoap");
-
- return $data;
}
+ $ip = $component->getDbIp();
+
+ $docRoot = self::GetMonitStatus($ip);
+
+ return self::ExtractServiceInformation($docRoot, 'airtime-liquidsoap');
}
public static function GetMediaMonitorStatus()
{
- $component = CcServiceRegisterQuery::create()->findOneByDbName("media-monitor");
+ $component = CcServiceRegisterQuery::create()->findOneByDbName('media-monitor');
if (is_null($component)) {
return null;
- } else {
- $ip = $component->getDbIp();
-
- $docRoot = self::GetMonitStatus($ip);
- $data = self::ExtractServiceInformation($docRoot, "airtime-analyzer");
-
- return $data;
}
+ $ip = $component->getDbIp();
+
+ $docRoot = self::GetMonitStatus($ip);
+
+ return self::ExtractServiceInformation($docRoot, 'airtime-analyzer');
}
public static function GetIcecastStatus()
{
- $docRoot = self::GetMonitStatus("localhost");
- $data = self::ExtractServiceInformation($docRoot, "icecast2");
+ $docRoot = self::GetMonitStatus('localhost');
- return $data;
+ return self::ExtractServiceInformation($docRoot, 'icecast2');
}
public static function GetRabbitMqStatus()
{
- if (isset($_SERVER["RABBITMQ_HOST"])) {
- $rabbitmq_host = $_SERVER["RABBITMQ_HOST"];
+ if (isset($_SERVER['RABBITMQ_HOST'])) {
+ $rabbitmq_host = $_SERVER['RABBITMQ_HOST'];
} else {
- $rabbitmq_host = "localhost";
+ $rabbitmq_host = 'localhost';
}
$docRoot = self::GetMonitStatus($rabbitmq_host);
- $data = self::ExtractServiceInformation($docRoot, "rabbitmq-server");
+ $data = self::ExtractServiceInformation($docRoot, 'rabbitmq-server');
return $data;
}
public static function GetDiskInfo()
{
- $partitions = array();
+ $partitions = [];
/* First lets get all the watched directories. Then we can group them
* into the same partitions by comparing the partition sizes. */
$musicDirs = Application_Model_MusicDir::getWatchedDirs();
@@ -221,13 +212,14 @@ class Application_Model_Systemstatus
foreach ($musicDirs as $md) {
$totalSpace = disk_total_space($md->getDirectory());
if (!isset($partitions[$totalSpace])) {
- $partitions[$totalSpace] = new StdClass;
+ $partitions[$totalSpace] = new StdClass();
$partitions[$totalSpace]->totalSpace = $totalSpace;
$partitions[$totalSpace]->totalFreeSpace = disk_free_space($md->getDirectory());
$partitions[$totalSpace]->usedSpace = $totalSpace - $partitions[$totalSpace]->totalFreeSpace;
}
$partitions[$totalSpace]->dirs[] = $md->getDirectory();
}
+
return array_values($partitions);
}
diff --git a/legacy/application/models/Tracktype.php b/legacy/application/models/Tracktype.php
index 632b50254..650b94e0c 100644
--- a/legacy/application/models/Tracktype.php
+++ b/legacy/application/models/Tracktype.php
@@ -88,68 +88,68 @@ class Application_Model_Tracktype
private function createTracktype()
{
- $tracktype = new CcTracktypes();
-
- return $tracktype;
+ return new CcTracktypes();
}
- public static function getTracktypes($search=null)
+ public static function getTracktypes($search = null)
{
- return Application_Model_Tracktype::getTracktypesData(array(true), $search);
+ return Application_Model_Tracktype::getTracktypesData([true], $search);
}
- public static function getTracktypesData(array $visible, $search=null)
+ public static function getTracktypesData(array $visible, $search = null)
{
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
- $sql_gen = "SELECT id, code, type_name, description FROM cc_track_types ";
+ $sql_gen = 'SELECT id, code, type_name, description FROM cc_track_types ';
- $visibility = array();
- $params = array();
- for ($i=0; $i &$record){
+ foreach ($res['aaData'] as $key => &$record) {
if ($record['code'] == $tracktypename) {
- $record['delete'] = "self";
+ $record['delete'] = 'self';
} else {
- $record['delete'] = "";
+ $record['delete'] = '';
}
$record = array_map('htmlspecialchars', $record);
}
@@ -161,13 +161,13 @@ class Application_Model_Tracktype
public static function getTracktypeData($id)
{
- $sql = << $id), 'single');
- }
+ return Application_Common_Database::prepareAndExecute($sql, [
+ ':id' => $id, ], 'single');
+ }
}
diff --git a/legacy/application/models/User.php b/legacy/application/models/User.php
index 6f39d01d6..6318ca2dc 100644
--- a/legacy/application/models/User.php
+++ b/legacy/application/models/User.php
@@ -30,6 +30,7 @@ class Application_Model_User
public function isHostOfShow($showId)
{
$userId = $this->_userInstance->getDbId();
+
return CcShowHostsQuery::create()
->filterByDbShow($showId)
->filterByDbHost($userId)->count() > 0;
@@ -49,32 +50,34 @@ class Application_Model_User
{
return $this->isUserType(UTYPE_ADMIN);
}
-
+
public function isSuperAdmin()
{
return $this->isUserType(UTYPE_SUPERADMIN);
}
-
+
public function canSchedule($p_showId)
{
$type = $this->getType();
$result = false;
- if ($this->isAdmin() ||
- $this->isSuperAdmin() ||
- $this->isPM() ||
- self::isHostOfShow($p_showId)) {
+ if ($this->isAdmin()
+ || $this->isSuperAdmin()
+ || $this->isPM()
+ || self::isHostOfShow($p_showId)) {
$result = true;
}
+
return $result;
}
public function isSourcefabricAdmin()
{
$username = $this->getLogin();
- if ($username == "sourcefabric_admin") {
+ if ($username == 'sourcefabric_admin') {
return true;
}
+
return false;
}
@@ -83,9 +86,10 @@ class Application_Model_User
public function isUserType($type)
{
if (!is_array($type)) {
- $type = array($type);
+ $type = [$type];
}
$real_type = $this->_userInstance->getDbType();
+
return in_array($real_type, $type);
}
@@ -204,7 +208,6 @@ class Application_Model_User
$user = $this->_userInstance;
return $user->getDbJabberContact();
-
}
public function save()
@@ -218,6 +221,7 @@ class Application_Model_User
$this->_userInstance->delete();
}
}
+
public function getOwnedFiles()
{
$user = $this->_userInstance;
@@ -243,9 +247,7 @@ class Application_Model_User
private function createUser()
{
- $user = new CcSubjs();
-
- return $user;
+ return new CcSubjs();
}
public static function getUsersOfType($type)
@@ -254,92 +256,95 @@ class Application_Model_User
}
/**
- * Get the first admin user from the database
+ * Get the first admin user from the database.
*
* This function gets used in UserController in the delete action. The controller
* uses it to figure out who to reassign the deleted users files to.
*
* @param $ignoreUser String optional userid of a user that shall be ignored when
- * when looking for the "first" admin.
+ * when looking for the "first" admin
*
- * @return CcSubj|null
+ * @return null|CcSubj
*/
- public static function getFirstAdmin($ignoreUser = null) {
+ public static function getFirstAdmin($ignoreUser = null)
+ {
$superAdmins = Application_Model_User::getUsersOfType('S');
if (count($superAdmins) > 0) { // found superadmin => pick first one
return $superAdmins[0];
- } else {
- // get all admin users
- $query = CcSubjsQuery::create()->filterByDbType('A');
- // ignore current user if one was specified
- if ($ignoreUser !== null) {
- $query->filterByDbId($ignoreUser, Criteria::NOT_EQUAL);
- }
- $admins = $query->find();
- if (count($admins) > 0) { // found admin => pick first one
- return $admins[0];
- }
- Logging::warn("Warning. no admins found in database");
- return null;
}
+ // get all admin users
+ $query = CcSubjsQuery::create()->filterByDbType('A');
+ // ignore current user if one was specified
+ if ($ignoreUser !== null) {
+ $query->filterByDbId($ignoreUser, Criteria::NOT_EQUAL);
+ }
+ $admins = $query->find();
+ if (count($admins) > 0) { // found admin => pick first one
+ return $admins[0];
+ }
+ Logging::warn('Warning. no admins found in database');
+
+ return null;
}
- public static function getUsers(array $type, $search=null)
+ public static function getUsers(array $type, $search = null)
{
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
- $sql_gen = "SELECT login AS value, login AS label, id as index FROM cc_subjs ";
+ $sql_gen = 'SELECT login AS value, login AS label, id as index FROM cc_subjs ';
- $types = array();
- $params = array();
- for ($i=0; $ihasIdentity()) {
@@ -349,39 +354,40 @@ class Application_Model_User
$res = Application_Model_Datatables::findEntries($con, $displayColumns, $fromTable, $datatables);
// mark record which is for the current user
- foreach($res['aaData'] as $key => &$record){
+ foreach ($res['aaData'] as $key => &$record) {
if ($record['login'] == $username) {
- $record['delete'] = "self";
+ $record['delete'] = 'self';
} else {
- $record['delete'] = "";
+ $record['delete'] = '';
}
-
- if($record['login'] == 'sourcefabric_admin'){
+
+ if ($record['login'] == 'sourcefabric_admin') {
//arrays in PHP are basically associative arrays that can be iterated in order.
//Deleting an earlier element does not change the keys of elements that come after it. --MK
unset($res['aaData'][$key]);
- $res['iTotalDisplayRecords']--;
- $res['iTotalRecords']--;
+ --$res['iTotalDisplayRecords'];
+ --$res['iTotalRecords'];
}
$record = array_map('htmlspecialchars', $record);
}
$res['aaData'] = array_values($res['aaData']);
-
+
return $res;
}
public static function getUserData($id)
{
- $sql = << $id), 'single');
+
+ return Application_Common_Database::prepareAndExecute($sql, [
+ ':id' => $id, ], 'single');
}
public static function getCurrentUser()
@@ -390,6 +396,7 @@ SQL;
if (is_null($userinfo)) {
return null;
}
+
try {
return new self($userinfo->id);
} catch (Exception $e) {
diff --git a/legacy/application/models/Webstream.php b/legacy/application/models/Webstream.php
index 87eee7797..2e534073e 100644
--- a/legacy/application/models/Webstream.php
+++ b/legacy/application/models/Webstream.php
@@ -45,15 +45,15 @@ class Application_Model_Webstream implements Application_Model_LibraryEditable
public function getDefaultLength()
{
$dateString = $this->webstream->getDbLength();
- $arr = explode(":", $dateString);
+ $arr = explode(':', $dateString);
if (count($arr) == 3) {
list($hours, $min, $sec) = $arr;
$di = new DateInterval("PT{$hours}H{$min}M{$sec}S");
- return $di->format("%Hh %Im");
+ return $di->format('%Hh %Im');
}
- return "";
+ return '';
}
public function getLength()
@@ -77,28 +77,28 @@ class Application_Model_Webstream implements Application_Model_LibraryEditable
$username = $subjs->getDbLogin();
- return array(
- "name" => $this->webstream->getDbName(),
- "length" => $this->webstream->getDbLength(),
- "description" => $this->webstream->getDbDescription(),
- "login" => $username,
- "url" => $this->webstream->getDbUrl(),
- );
+ return [
+ 'name' => $this->webstream->getDbName(),
+ 'length' => $this->webstream->getDbLength(),
+ 'description' => $this->webstream->getDbDescription(),
+ 'login' => $username,
+ 'url' => $this->webstream->getDbUrl(),
+ ];
}
public static function deleteStreams($p_ids, $p_userId)
{
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id);
- $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
-
+ $isAdminOrPM = $user->isUserType([UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER]);
+
if (!$isAdminOrPM) {
//Make sure the user has ownership of ALL the selected webstreams before
$leftOver = self::streamsNotOwnedByUser($p_ids, $p_userId);
if (count($leftOver) == 0) {
CcWebstreamQuery::create()->findPKs($p_ids)->delete();
} else {
- throw new WebstreamNoPermissionException;
+ throw new WebstreamNoPermissionException();
}
} else {
CcWebstreamQuery::create()->findPKs($p_ids)->delete();
@@ -109,26 +109,24 @@ class Application_Model_Webstream implements Application_Model_LibraryEditable
private static function streamsNotOwnedByUser($p_ids, $p_userId)
{
$ownedByUser = CcWebstreamQuery::create()->filterByDbCreatorId($p_userId)->find()->getData();
- $ownedStreams = array();
+ $ownedStreams = [];
foreach ($ownedByUser as $pl) {
if (in_array($pl->getDbId(), $p_ids)) {
$ownedStreams[] = $pl->getDbId();
}
}
- $leftOvers = array_diff($p_ids, $ownedStreams);
-
- return $leftOvers;
+ return array_diff($p_ids, $ownedStreams);
}
public static function analyzeFormData($parameters)
{
- $valid = array("length" => array(true, ''),
- "url" => array(true, ''),
- "name" => array(true, ''));
+ $valid = ['length' => [true, ''],
+ 'url' => [true, ''],
+ 'name' => [true, ''], ];
$di = null;
- $length = $parameters["length"];
+ $length = $parameters['length'];
$result = preg_match("/^(?:([0-9]{1,2})h)?\s*(?:([0-9]{1,2})m)?$/", $length, $matches);
$invalid_date_interval = false;
@@ -143,7 +141,6 @@ class Application_Model_Webstream implements Application_Model_LibraryEditable
}
if (!$invalid_date_interval) {
-
//Due to the way our Regular Expression is set up, we could have $minutes or $hours
//not set. Do simple test here
if (!is_numeric($hours)) {
@@ -154,8 +151,8 @@ class Application_Model_Webstream implements Application_Model_LibraryEditable
}
//minutes cannot be over 59. Need to convert anything > 59 minutes into hours.
- $hours += intval($minutes/60);
- $minutes = $minutes%60;
+ $hours += intval($minutes / 60);
+ $minutes = $minutes % 60;
$di = new DateInterval("PT{$hours}H{$minutes}M");
@@ -165,13 +162,12 @@ class Application_Model_Webstream implements Application_Model_LibraryEditable
$valid['length'][0] = false;
$valid['length'][1] = _('Length needs to be greater than 0 minutes');
}
-
} else {
$valid['length'][0] = false;
$valid['length'][1] = _('Length should be of form "00h 00m"');
}
- $url = $parameters["url"];
+ $url = $parameters['url'];
//simple validator that checks to make sure that the url starts with
//http(s),
//and that the domain is at least 1 letter long
@@ -186,16 +182,15 @@ class Application_Model_Webstream implements Application_Model_LibraryEditable
$valid['url'][0] = false;
$valid['url'][1] = _('URL should be 512 characters or less');
} else {
-
try {
list($mime, $content_length_found) = self::discoverStreamMime($url);
if (is_null($mime)) {
- throw new Exception(_("No MIME type found for webstream."));
+ throw new Exception(_('No MIME type found for webstream.'));
}
$mediaUrl = self::getMediaUrl($url, $mime, $content_length_found);
if (preg_match("/(x-mpegurl)|(xspf\+xml)|(pls\+xml)|(x-scpls)/", $mime)) {
- list($mime, $content_length_found) = self::discoverStreamMime($mediaUrl);
+ list($mime, $content_length_found) = self::discoverStreamMime($mediaUrl);
}
} catch (Exception $e) {
$valid['url'][0] = false;
@@ -203,15 +198,15 @@ class Application_Model_Webstream implements Application_Model_LibraryEditable
}
}
- $name = $parameters["name"];
+ $name = $parameters['name'];
if (strlen($name) == 0) {
$valid['name'][0] = false;
$valid['name'][1] = _('Webstream name cannot be empty');
}
- $id = $parameters["id"];
+ $id = $parameters['id'];
- return array($valid, $mime, $mediaUrl, $di);
+ return [$valid, $mime, $mediaUrl, $di];
}
public static function isValid($analysis)
@@ -221,6 +216,7 @@ class Application_Model_Webstream implements Application_Model_LibraryEditable
return false;
}
}
+
return true;
}
@@ -228,14 +224,14 @@ class Application_Model_Webstream implements Application_Model_LibraryEditable
//This function should not be defined in the interface.
public function setMetadata($key, $val)
{
- throw new Exception("Not implemented.");
+ throw new Exception('Not implemented.');
}
public function setName($name)
{
$this->webstream->setDbName($name);
}
-
+
public function setLastPlayed($timestamp)
{
$this->webstream->setDbLPtime($timestamp);
@@ -255,7 +251,7 @@ class Application_Model_Webstream implements Application_Model_LibraryEditable
// close cURL resource, and free up system resources
curl_close($ch);
-
+
return $content;
}
@@ -263,7 +259,7 @@ class Application_Model_Webstream implements Application_Model_LibraryEditable
{
$content = self::getUrlData($url);
- $dom = new DOMDocument;
+ $dom = new DOMDocument();
//TODO: What if invalid xml?
$dom->loadXML($content);
$tracks = $dom->getElementsByTagName('track');
@@ -275,28 +271,28 @@ class Application_Model_Webstream implements Application_Model_LibraryEditable
}
}
- throw new Exception(_("Could not parse XSPF playlist"));
+ throw new Exception(_('Could not parse XSPF playlist'));
}
-
+
private static function getPlsUrl($url)
{
$content = self::getUrlData($url);
- $matches = array();
+ $matches = [];
$numStreams = 0; //Number of streams explicitly listed in the PLS.
-
- if (preg_match("/NumberOfEntries=([0-9]*)/", $content, $matches) !== FALSE) {
+
+ if (preg_match('/NumberOfEntries=([0-9]*)/', $content, $matches) !== false) {
$numStreams = $matches[1];
}
//Find all the stream URLs in the playlist
- if (preg_match_all("/File[0-9]*=(.*)/", $content, $matches) !== FALSE) {
+ if (preg_match_all('/File[0-9]*=(.*)/', $content, $matches) !== false) {
//This array contains all the streams! If we need fallback stream URLs in the future,
//they're already in this array...
return $matches[1][0];
- } else {
- throw new Exception(_("Could not parse PLS playlist"));
}
+
+ throw new Exception(_('Could not parse PLS playlist'));
}
private static function getM3uUrl($url)
@@ -308,39 +304,37 @@ class Application_Model_Webstream implements Application_Model_LibraryEditable
if (strpos($content, "\r\n") !== false) {
$delim = "\r\n";
}
- $lines = explode("$delim", $content);
- #$lines = preg_split('/$\R?^/m', $content);
+ $lines = explode("{$delim}", $content);
+ //$lines = preg_split('/$\R?^/m', $content);
if (count($lines) > 0) {
return $lines[0];
}
- throw new Exception(_("Could not parse M3U playlist"));
+ throw new Exception(_('Could not parse M3U playlist'));
}
private static function getMediaUrl($url, $mime, $content_length_found)
{
-
- if (preg_match("/x-mpegurl/", $mime)) {
+ if (preg_match('/x-mpegurl/', $mime)) {
$media_url = self::getM3uUrl($url);
} elseif (preg_match("/xspf\+xml/", $mime)) {
$media_url = self::getXspfUrl($url);
- } elseif (preg_match("/pls\+xml/", $mime) || preg_match("/x-scpls/", $mime)) {
+ } elseif (preg_match("/pls\+xml/", $mime) || preg_match('/x-scpls/', $mime)) {
$media_url = self::getPlsUrl($url);
} elseif (preg_match("/(mpeg|ogg|audio\/aacp|audio\/aac)/", $mime)) {
if ($content_length_found) {
- throw new Exception(_("Invalid webstream - This appears to be a file download."));
+ throw new Exception(_('Invalid webstream - This appears to be a file download.'));
}
$media_url = $url;
} else {
- throw new Exception(sprintf(_("Unrecognized stream type: %s"), $mime));
+ throw new Exception(sprintf(_('Unrecognized stream type: %s'), $mime));
}
return $media_url;
-
}
- /* PHP get_headers has an annoying property where if the passed in URL is
+ /* PHP get_headers has an annoying property where if the passed in URL is
* a redirect, then it goes to the new URL, and returns headers from both
* requests. We only want the headers from the final request. Here's an
* example:
@@ -362,18 +356,20 @@ class Application_Model_Webstream implements Application_Model_LibraryEditable
* 14 => "icy-br: 68",
* 15 => "Server: MediaGateway 3.2.1-04",
* */
- private static function cleanHeaders($headers) {
+ private static function cleanHeaders($headers)
+ {
//find the position of HTTP/1 200 OK
//
$position = 0;
foreach ($headers as $i => $v) {
- if (preg_match("/^HTTP.*200 OK$/i", $v)) {
+ if (preg_match('/^HTTP.*200 OK$/i', $v)) {
$position = $i;
+
break;
}
}
- return array_slice($headers, $position);
+ return array_slice($headers, $position);
}
private static function discoverStreamMime($url)
@@ -383,25 +379,25 @@ class Application_Model_Webstream implements Application_Model_LibraryEditable
$mime = null;
$content_length_found = false;
-
+
if ($headers !== false) {
$headers = self::cleanHeaders($headers);
foreach ($headers as $h) {
- if (preg_match("/^content-type:/i", $h)) {
- list(, $value) = explode(":", $h, 2);
+ if (preg_match('/^content-type:/i', $h)) {
+ list(, $value) = explode(':', $h, 2);
$mime = trim($value);
}
- if (preg_match("/^content-length:/i", $h)) {
+ if (preg_match('/^content-length:/i', $h)) {
$content_length_found = true;
}
}
}
} catch (Exception $e) {
- Logging::info("Invalid stream URL");
+ Logging::info('Invalid stream URL');
Logging::info($e->getMessage());
}
- return array($mime, $content_length_found);
+ return [$mime, $content_length_found];
}
public static function save($parameters, $mime, $mediaUrl, $di)
@@ -415,15 +411,15 @@ class Application_Model_Webstream implements Application_Model_LibraryEditable
$webstream = new CcWebstream();
}
- $webstream->setDbName($parameters["name"]);
- $webstream->setDbDescription($parameters["description"]);
+ $webstream->setDbName($parameters['name']);
+ $webstream->setDbDescription($parameters['description']);
$webstream->setDbUrl($mediaUrl);
- $dblength = $di->format("%H:%I");
+ $dblength = $di->format('%H:%I');
$webstream->setDbLength($dblength);
$webstream->setDbCreatorId($userInfo->id);
- $webstream->setDbUtime(new DateTime("now", new DateTimeZone('UTC')));
- $webstream->setDbMtime(new DateTime("now", new DateTimeZone('UTC')));
+ $webstream->setDbUtime(new DateTime('now', new DateTimeZone('UTC')));
+ $webstream->setDbMtime(new DateTime('now', new DateTimeZone('UTC')));
$ws = new Application_Model_Webstream($webstream);
@@ -432,24 +428,25 @@ class Application_Model_Webstream implements Application_Model_LibraryEditable
return $webstream->getDbId();
}
-
- /*
- * method is not used, webstreams aren't currently kept track of for isScheduled.
- */
- public static function setIsScheduled($p_webstreamId, $p_status) {
-
- $webstream = CcWebstreamQuery::create()->findPK($p_webstreamId);
- $updateIsScheduled = false;
-
- if (isset($webstream) && !in_array($p_webstreamId,
- Application_Model_Schedule::getAllFutureScheduledWebstreams())) {
- //$webstream->setDbIsScheduled($p_status)->save();
- $updateIsScheduled = true;
- }
-
- return $updateIsScheduled;
+
+ // method is not used, webstreams aren't currently kept track of for isScheduled.
+ public static function setIsScheduled($p_webstreamId, $p_status)
+ {
+ $webstream = CcWebstreamQuery::create()->findPK($p_webstreamId);
+ $updateIsScheduled = false;
+
+ if (isset($webstream) && !in_array(
+ $p_webstreamId,
+ Application_Model_Schedule::getAllFutureScheduledWebstreams()
+ )) {
+ //$webstream->setDbIsScheduled($p_status)->save();
+ $updateIsScheduled = true;
+ }
+
+ return $updateIsScheduled;
}
}
-class WebstreamNoPermissionException extends Exception {}
-
+class WebstreamNoPermissionException extends Exception
+{
+}
diff --git a/legacy/application/models/airtime/CcAccess.php b/legacy/application/models/airtime/CcAccess.php
index 2b3d4443d..fc965374a 100644
--- a/legacy/application/models/airtime/CcAccess.php
+++ b/legacy/application/models/airtime/CcAccess.php
@@ -1,18 +1,12 @@
utime, new DateTimeZone("UTC"));
+ $dt = new DateTime($this->utime, new DateTimeZone('UTC'));
} catch (Exception $x) {
- throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->utime, true), $x);
+ throw new PropelException('Internally stored date/time/timestamp value could not be converted to DateTime: ' . var_export($this->utime, true), $x);
}
if ($format === null) {
// Because propel.useDateTimeClass is TRUE, we return a DateTime object.
return $dt;
- } elseif (strpos($format, '%') !== false) {
- return strftime($format, $dt->format('U'));
- } else {
- return $dt->format($format);
}
+ if (strpos($format, '%') !== false) {
+ return strftime($format, $dt->format('U'));
+ }
+
+ return $dt->format($format);
}
/**
* Get the [optionally formatted] temporal [mtime] column value.
*
+ * @param string $format The date/time format string (either date()-style or strftime()-style).
+ * If format is NULL, then the raw DateTime object will be returned.
*
- * @param string $format The date/time format string (either date()-style or strftime()-style).
- * If format is NULL, then the raw DateTime object will be returned.
- * @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL
- * @throws PropelException - if unable to parse/validate the date/time value.
+ * @throws propelException - if unable to parse/validate the date/time value
+ *
+ * @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL
*/
public function getDbMtime($format = 'Y-m-d H:i:s')
{
@@ -61,19 +59,20 @@ class CcBlock extends BaseCcBlock {
}
try {
- $dt = new DateTime($this->mtime, new DateTimeZone("UTC"));
+ $dt = new DateTime($this->mtime, new DateTimeZone('UTC'));
} catch (Exception $x) {
- throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->mtime, true), $x);
+ throw new PropelException('Internally stored date/time/timestamp value could not be converted to DateTime: ' . var_export($this->mtime, true), $x);
}
if ($format === null) {
// Because propel.useDateTimeClass is TRUE, we return a DateTime object.
return $dt;
- } elseif (strpos($format, '%') !== false) {
- return strftime($format, $dt->format('U'));
- } else {
- return $dt->format($format);
}
+ if (strpos($format, '%') !== false) {
+ return strftime($format, $dt->format('U'));
+ }
+
+ return $dt->format($format);
}
/**
@@ -86,7 +85,7 @@ class CcBlock extends BaseCcBlock {
*/
public function computeDbLength(PropelPDO $con)
{
- $sql = <<fetchColumn();
if (is_null($length)) {
- $length = "00:00:00";
+ $length = '00:00:00';
}
return $length;
diff --git a/legacy/application/models/airtime/CcBlockPeer.php b/legacy/application/models/airtime/CcBlockPeer.php
index 491ea67ee..e6751879a 100644
--- a/legacy/application/models/airtime/CcBlockPeer.php
+++ b/legacy/application/models/airtime/CcBlockPeer.php
@@ -1,18 +1,12 @@
fadein = $dt->format('H:i:s.u');
} else {
- $this->fadein = $dt->format('H:i:s').".".$microsecond;
+ $this->fadein = $dt->format('H:i:s') . '.' . $microsecond;
}
$this->modifiedColumns[] = CcBlockcontentsPeer::FADEIN;
-
+
return $this;
} // setDbFadein()
-
+
/**
- *
- * @param String in format SS.uuuuuu, Datetime, or DateTime accepted string.
+ * @param string in format SS.uuuuuu, Datetime, or DateTime accepted string.
+ * @param mixed $v
*
* @return CcBlockcontents The current object (for fluent API support)
*/
@@ -84,15 +83,13 @@ class CcBlockcontents extends BaseCcBlockcontents {
$microsecond = 0;
if ($v instanceof DateTime) {
$dt = $v;
- }
- else if (preg_match('/^[0-9]{1,2}(\.\d{1,6})?$/', $v)) {
+ } elseif (preg_match('/^[0-9]{1,2}(\.\d{1,6})?$/', $v)) {
// in php 5.3.2 createFromFormat() with "u" is not supported(bug)
// Hence we need to do parsing.
$info = explode('.', $v);
$microsecond = $info[1];
- $dt = DateTime::createFromFormat("s", $info[0]);
- }
- else {
+ $dt = DateTime::createFromFormat('s', $info[0]);
+ } else {
try {
$dt = new DateTime($v);
} catch (Exception $x) {
@@ -103,11 +100,10 @@ class CcBlockcontents extends BaseCcBlockcontents {
if ($microsecond == 0) {
$this->fadeout = $dt->format('H:i:s.u');
} else {
- $this->fadeout = $dt->format('H:i:s').".".$microsecond;
+ $this->fadeout = $dt->format('H:i:s') . '.' . $microsecond;
}
$this->modifiedColumns[] = CcBlockcontentsPeer::FADEOUT;
-
+
return $this;
} // setDbFadeout()
-
} // CcBlockcontents
diff --git a/legacy/application/models/airtime/CcBlockcontentsPeer.php b/legacy/application/models/airtime/CcBlockcontentsPeer.php
index 024cb0523..f8cdc8cc8 100644
--- a/legacy/application/models/airtime/CcBlockcontentsPeer.php
+++ b/legacy/application/models/airtime/CcBlockcontentsPeer.php
@@ -1,18 +1,12 @@
findPk($fileId);
if ($file) {
return CcFiles::sanitizeResponse($file);
- } else {
- throw new LibreTimeFileNotFoundException();
}
+
+ throw new LibreTimeFileNotFoundException();
}
/** Used to create a CcFiles object from an array containing metadata and a file uploaded by POST.
* This is used by our Media REST API!
- * @param $fileArray An array containing metadata for a CcFiles object.
+ *
+ * @param $fileArray An array containing metadata for a CcFiles object
+ *
+ * @throws Exception
*
* @return object the sanitized response
- * @throws Exception
*/
public static function createFromUpload($fileArray)
{
@@ -100,6 +96,7 @@ class CcFiles extends BaseCcFiles {
if (file_exists($tempFilePath)) {
unlink($tempFilePath);
}
+
throw $e;
}
}
@@ -107,38 +104,43 @@ class CcFiles extends BaseCcFiles {
/** Import a music file to the library from a local file on disk (something pre-existing).
* This function allows you to copy a file rather than move it, which is useful for importing
* static music files (like sample tracks).
- * @param string $filePath The full path to the audio file to import.
- * @param bool $copyFile True if you want to just copy the false, false if you want to move it (default false)
+ *
+ * @param string $filePath the full path to the audio file to import
+ * @param bool $copyFile True if you want to just copy the false, false if you want to move it (default false)
+ * @param mixed $fileArray
+ *
* @throws Exception
*/
- public static function createFromLocalFile($fileArray, $filePath, $copyFile=false)
+ public static function createFromLocalFile($fileArray, $filePath, $copyFile = false)
{
$info = pathinfo($filePath);
- $fileName = basename($filePath).'.'.$info['extension'];
+ $fileName = basename($filePath) . '.' . $info['extension'];
self::createAndImport($fileArray, $filePath, $fileName, $copyFile);
}
/** Create a new CcFiles object/row and import a file for it.
* You shouldn't call this directly. Either use createFromUpload() or createFromLocalFile().
- * @param array $fileArray Any metadata to pre-fill for the audio file
- * @param string $filePath The full path to the audio file to import
+ *
+ * @param array $fileArray Any metadata to pre-fill for the audio file
+ * @param string $filePath The full path to the audio file to import
* @param string $originalFilename
- * @param bool $copyFile
- * @return mixed
+ * @param bool $copyFile
+ *
* @throws Exception
* @throws PropelException
+ *
+ * @return mixed
*/
- private static function createAndImport($fileArray, $filePath, $originalFilename, $copyFile=false)
+ private static function createAndImport($fileArray, $filePath, $originalFilename, $copyFile = false)
{
$file = new CcFiles();
- try
- {
+ try {
//Only accept files with a file extension that we support.
// Let the analyzer do the heavy lifting in terms of mime verification and playability
$fileExtension = pathinfo($originalFilename, PATHINFO_EXTENSION);
if (!in_array(strtolower($fileExtension), array_values(FileDataHelper::getAudioMimeTypeArray()))) {
- throw new Exception("Bad file extension.");
+ throw new Exception('Bad file extension.');
}
$fileArray = self::removeBlacklistedFields($fileArray);
@@ -146,14 +148,14 @@ class CcFiles extends BaseCcFiles {
self::validateFileArray($fileArray);
$storDir = Application_Model_MusicDir::getStorDir();
- $importedStorageDir = $storDir->getDirectory() . "imported/" . self::getOwnerId() . "/";
- $importedDbPath = "imported/" . self::getOwnerId() . "/";
+ $importedStorageDir = $storDir->getDirectory() . 'imported/' . self::getOwnerId() . '/';
+ $importedDbPath = 'imported/' . self::getOwnerId() . '/';
$artwork = FileDataHelper::saveArtworkData($filePath, $originalFilename, $importedStorageDir, $importedDbPath);
$trackType = FileDataHelper::saveTrackType();
$file->fromArray($fileArray);
$file->setDbOwnerId(self::getOwnerId());
- $now = new DateTime("now", new DateTimeZone("UTC"));
+ $now = new DateTime('now', new DateTimeZone('UTC'));
$file->setDbTrackTitle($originalFilename);
$file->setDbArtwork($artwork);
$file->setDbTrackType($trackType);
@@ -161,28 +163,35 @@ class CcFiles extends BaseCcFiles {
$file->setDbHidden(true);
$file->save();
- $callbackUrl = Application_Common_HTTPHelper::getStationUrl() . "/rest/media/" . $file->getPrimaryKey();
+ $callbackUrl = Application_Common_HTTPHelper::getStationUrl() . '/rest/media/' . $file->getPrimaryKey();
- Application_Service_MediaService::importFileToLibrary($callbackUrl, $filePath,
- $originalFilename, self::getOwnerId(), $copyFile);
+ Application_Service_MediaService::importFileToLibrary(
+ $callbackUrl,
+ $filePath,
+ $originalFilename,
+ self::getOwnerId(),
+ $copyFile
+ );
return CcFiles::sanitizeResponse($file);
-
} catch (Exception $e) {
$file->setDbImportStatus(self::IMPORT_STATUS_FAILED);
$file->setDbHidden(true);
$file->save();
+
throw $e;
}
}
/** Update a file with metadata specified in an array.
- * @param $fileId string The ID of the file to update in the DB.
+ * @param $fileId string The ID of the file to update in the DB
* @param $fileArray array An associative array containing metadata. Replaces those fields if they exist.
- * @return array A sanitized version of the file metadata array.
+ *
* @throws Exception
* @throws LibreTimeFileNotFoundException
* @throws PropelException
+ *
+ * @return array a sanitized version of the file metadata array
*/
public static function updateFromArray($fileId, $fileArray)
{
@@ -192,29 +201,26 @@ class CcFiles extends BaseCcFiles {
$fileArray = self::stripTimeStampFromYearTag($fileArray);
try {
-
self::validateFileArray($fileArray);
- if ($file && isset($fileArray["resource_id"])) {
-
+ if ($file && isset($fileArray['resource_id'])) {
$file->fromArray($fileArray, BasePeer::TYPE_FIELDNAME);
//store the original filename
- $file->setDbFilepath($fileArray["filename"]);
+ $file->setDbFilepath($fileArray['filename']);
- $fileSizeBytes = $fileArray["filesize"];
+ $fileSizeBytes = $fileArray['filesize'];
if (!isset($fileSizeBytes) || $fileSizeBytes === false) {
- throw new LibreTimeFileNotFoundException("Invalid filesize for $fileId");
+ throw new LibreTimeFileNotFoundException("Invalid filesize for {$fileId}");
}
$cloudFile = new CloudFile();
- $cloudFile->setStorageBackend($fileArray["storage_backend"]);
- $cloudFile->setResourceId($fileArray["resource_id"]);
+ $cloudFile->setStorageBackend($fileArray['storage_backend']);
+ $cloudFile->setResourceId($fileArray['resource_id']);
$cloudFile->setCcFiles($file);
$cloudFile->save();
Application_Model_Preference::updateDiskUsage($fileSizeBytes);
- } else if ($file) {
-
+ } elseif ($file) {
// Since we check for this value when deleting files, set it first
$file->setDbDirectory(self::MUSIC_DIRS_STOR_PK);
@@ -223,18 +229,18 @@ class CcFiles extends BaseCcFiles {
//Our RESTful API takes "full_path" as a field, which we then split and translate to match
//our internal schema. Internally, file path is stored relative to a directory, with the directory
//as a foreign key to cc_music_dirs.
- if (isset($fileArray["full_path"])) {
- $fileSizeBytes = filesize($fileArray["full_path"]);
+ if (isset($fileArray['full_path'])) {
+ $fileSizeBytes = filesize($fileArray['full_path']);
if (!isset($fileSizeBytes) || $fileSizeBytes === false) {
- throw new LibreTimeFileNotFoundException("Invalid filesize for $fileId");
+ throw new LibreTimeFileNotFoundException("Invalid filesize for {$fileId}");
}
Application_Model_Preference::updateDiskUsage($fileSizeBytes);
- $fullPath = $fileArray["full_path"];
+ $fullPath = $fileArray['full_path'];
$storDir = Application_Model_MusicDir::getStorDir()->getDirectory();
$pos = strpos($fullPath, $storDir);
- if ($pos !== FALSE) {
+ if ($pos !== false) {
assert($pos == 0); //Path must start with the stor directory path
$filePathRelativeToStor = substr($fullPath, strlen($storDir));
@@ -245,15 +251,14 @@ class CcFiles extends BaseCcFiles {
throw new LibreTimeFileNotFoundException();
}
- $now = new DateTime("now", new DateTimeZone("UTC"));
+ $now = new DateTime('now', new DateTimeZone('UTC'));
$file->setDbMtime($now);
$file->save();
- }
- catch (LibreTimeFileNotFoundException $e)
- {
+ } catch (LibreTimeFileNotFoundException $e) {
$file->setDbImportStatus(self::IMPORT_STATUS_FAILED);
$file->setDbHidden(true);
$file->save();
+
throw $e;
}
@@ -262,6 +267,7 @@ class CcFiles extends BaseCcFiles {
/** Delete a file from the database and disk (or cloud).
* @param $id The file ID
+ *
* @throws DeleteScheduledFileException
* @throws Exception
* @throws FileNoPermissionException
@@ -278,10 +284,8 @@ class CcFiles extends BaseCcFiles {
} else {
throw new LibreTimeFileNotFoundException();
}
-
}
-
private static function validateFileArray(&$fileArray)
{
// Sanitize any wildly incorrect metadata before it goes to be validated
@@ -298,7 +302,7 @@ class CcFiles extends BaseCcFiles {
* genre is more than 64 chars, for example, we don't want to reject
* tracks for that reason
*/
- foreach($fileArray as $tag => &$value) {
+ foreach ($fileArray as $tag => &$value) {
if ($fileForm->getElement($tag)) {
$stringLengthValidator = $fileForm->getElement($tag)->getValidator('StringLength');
//$stringLengthValidator will be false if the StringLength validator doesn't exist on the current element
@@ -315,56 +319,55 @@ class CcFiles extends BaseCcFiles {
$errors = $fileForm->getErrors();
$messages = $fileForm->getMessages();
Logging::error($messages);
- throw new Exception("Data validation failed: $errors - $messages");
+
+ throw new Exception("Data validation failed: {$errors} - {$messages}");
}
return true;
}
-
public function getCueLength()
- {
- $cuein = $this->getDbCuein();
- $cueout = $this->getDbCueout();
+ {
+ $cuein = $this->getDbCuein();
+ $cueout = $this->getDbCueout();
- $cueinSec = Application_Common_DateHelper::calculateLengthInSeconds($cuein);
- $cueoutSec = Application_Common_DateHelper::calculateLengthInSeconds($cueout);
- $lengthSec = bcsub($cueoutSec, $cueinSec, 6);
+ $cueinSec = Application_Common_DateHelper::calculateLengthInSeconds($cuein);
+ $cueoutSec = Application_Common_DateHelper::calculateLengthInSeconds($cueout);
+ $lengthSec = bcsub($cueoutSec, $cueinSec, 6);
- $length = Application_Common_DateHelper::secondsToPlaylistTime($lengthSec);
-
- return $length;
- }
+ return Application_Common_DateHelper::secondsToPlaylistTime($lengthSec);
+ }
public function setDbTrackNumber($v)
{
- $max = pow(2, 31)-1;
+ $max = pow(2, 31) - 1;
$v = ($v > $max) ? $max : $v;
return parent::setDbTrackNumber($v);
}
// returns true if the file exists and is not hidden
- public function visible() {
+ public function visible()
+ {
return $this->getDbFileExists() && !$this->getDbHidden();
}
public function reassignTo($user)
{
- $this->setDbOwnerId( $user->getDbId() );
+ $this->setDbOwnerId($user->getDbId());
$this->save();
}
/**
- *
- * Strips out the private fields we do not want to send back in API responses
+ * Strips out the private fields we do not want to send back in API responses.
*
* @param CcFiles $file a CcFiles object
*
* @return array
*/
//TODO: rename this function?
- public static function sanitizeResponse($file) {
+ public static function sanitizeResponse($file)
+ {
$response = $file->toArray(BasePeer::TYPE_FIELDNAME);
foreach (self::$privateFields as $key) {
@@ -398,7 +401,7 @@ class CcFiles extends BaseCcFiles {
*/
public function getURLsForTrackPreviewOrDownload()
{
- return array($this->getAbsoluteFilePath());
+ return [$this->getAbsoluteFilePath()];
}
/**
@@ -408,10 +411,11 @@ class CcFiles extends BaseCcFiles {
{
$music_dir = Application_Model_MusicDir::getDirByPK($this->getDbDirectory());
if (!$music_dir) {
- throw new Exception("Invalid music_dir for file " . $this->getDbId() . " in database.");
+ throw new Exception('Invalid music_dir for file ' . $this->getDbId() . ' in database.');
}
$directory = $music_dir->getDirectory();
- $filepath = $this->getDbFilepath();
+ $filepath = $this->getDbFilepath();
+
return Application_Common_OsPath::join($directory, $filepath);
}
@@ -422,18 +426,18 @@ class CcFiles extends BaseCcFiles {
{
$music_dir = Application_Model_MusicDir::getDirByPK($this->getDbDirectory());
if (!$music_dir) {
- throw new Exception("Invalid music_dir for file " . $this->getDbId() . " in database.");
+ throw new Exception('Invalid music_dir for file ' . $this->getDbId() . ' in database.');
}
$directory = $music_dir->getDirectory();
- $filepath = $this->getDbArtwork();
+ $filepath = $this->getDbArtwork();
return Application_Common_OsPath::join($directory, $filepath);
}
/**
- *
* Strips out fields from incoming request data that should never be modified
- * from outside of Airtime
+ * from outside of Airtime.
+ *
* @param array $data
*/
private static function removeBlacklistedFields($data)
@@ -445,29 +449,31 @@ class CcFiles extends BaseCcFiles {
return $data;
}
-
private static function getOwnerId()
{
try {
if (Zend_Auth::getInstance()->hasIdentity()) {
$service_user = new Application_Service_UserService();
+
return $service_user->getCurrentUser()->getDbId();
- } else {
- $defaultOwner = CcSubjsQuery::create()
- ->filterByDbType('A')
- ->orderByDbId()
- ->findOne();
- if (!$defaultOwner) {
- // what to do if there is no admin user?
- // should we handle this case?
- return null;
- }
- return $defaultOwner->getDbId();
}
- } catch(Exception $e) {
+ $defaultOwner = CcSubjsQuery::create()
+ ->filterByDbType('A')
+ ->orderByDbId()
+ ->findOne()
+ ;
+ if (!$defaultOwner) {
+ // what to do if there is no admin user?
+ // should we handle this case?
+ return null;
+ }
+
+ return $defaultOwner->getDbId();
+ } catch (Exception $e) {
Logging::info($e->getMessage());
}
}
+
/*
* It's possible that the year tag will be a timestamp but Airtime doesn't support this.
* The year field in cc_files can only be 16 chars max.
@@ -476,11 +482,12 @@ class CcFiles extends BaseCcFiles {
*/
private static function stripTimeStampFromYearTag($metadata)
{
- if (isset($metadata["year"])) {
- if (preg_match("/^(\d{4})-(\d{2})-(\d{2})(?:\s+(\d{2}):(\d{2}):(\d{2}))?$/", $metadata["year"])) {
- $metadata["year"] = substr($metadata["year"], 0, 4);
+ if (isset($metadata['year'])) {
+ if (preg_match("/^(\d{4})-(\d{2})-(\d{2})(?:\s+(\d{2}):(\d{2}):(\d{2}))?$/", $metadata['year'])) {
+ $metadata['year'] = substr($metadata['year'], 0, 4);
}
}
+
return $metadata;
}
@@ -488,28 +495,29 @@ class CcFiles extends BaseCcFiles {
{
//Remove invalid UTF-8 characters
//reject overly long 2 byte sequences, as well as characters above U+10000 and replace with ?
- $string = preg_replace('/[\x00-\x08\x10\x0B\x0C\x0E-\x19\x7F]'.
- '|[\x00-\x7F][\x80-\xBF]+'.
- '|([\xC0\xC1]|[\xF0-\xFF])[\x80-\xBF]*'.
- '|[\xC2-\xDF]((?![\x80-\xBF])|[\x80-\xBF]{2,})'.
+ $string = preg_replace(
+ '/[\x00-\x08\x10\x0B\x0C\x0E-\x19\x7F]' .
+ '|[\x00-\x7F][\x80-\xBF]+' .
+ '|([\xC0\xC1]|[\xF0-\xFF])[\x80-\xBF]*' .
+ '|[\xC2-\xDF]((?![\x80-\xBF])|[\x80-\xBF]{2,})' .
'|[\xE0-\xEF](([\x80-\xBF](?![\x80-\xBF]))|(?![\x80-\xBF]{2})|[\x80-\xBF]{3,})/S',
- '?', $string );
+ '?',
+ $string
+ );
//reject overly long 3 byte sequences and UTF-16 surrogates and replace with ?
- $string = preg_replace('/\xE0[\x80-\x9F][\x80-\xBF]'.
- '|\xED[\xA0-\xBF][\x80-\xBF]/S','?', $string );
+ $string = preg_replace('/\xE0[\x80-\x9F][\x80-\xBF]' .
+ '|\xED[\xA0-\xBF][\x80-\xBF]/S', '?', $string);
//Do a final encoding conversion to
- $string = mb_convert_encoding($string, 'UTF-8', 'UTF-8');
- return $string;
+ return mb_convert_encoding($string, 'UTF-8', 'UTF-8');
}
private function removeEmptySubFolders($path)
{
- exec("find $path -empty -type d -delete");
+ exec("find {$path} -empty -type d -delete");
}
-
/**
* Checks if the file is a regular file that can be previewed and downloaded.
*/
@@ -519,7 +527,6 @@ class CcFiles extends BaseCcFiles {
}
/**
- *
* Deletes the file from the stor directory on disk.
*/
public function deletePhysicalFile()
@@ -529,17 +536,16 @@ class CcFiles extends BaseCcFiles {
if (file_exists($filepath)) {
unlink($filepath);
// also delete related images (dataURI and jpeg files)
- foreach (glob("$artworkpath*", GLOB_NOSORT) as $filename) {
+ foreach (glob("{$artworkpath}*", GLOB_NOSORT) as $filename) {
unlink($filename);
}
unlink($artworkpath);
} else {
- throw new Exception("Could not locate file ".$filepath);
+ throw new Exception('Could not locate file ' . $filepath);
}
}
/**
- *
* This function refers to the file's Amazon S3 resource id.
* Returns null because cc_files are stored on local disk.
*/
@@ -552,5 +558,4 @@ class CcFiles extends BaseCcFiles {
{
return $this->id;
}
-
} // CcFiles
diff --git a/legacy/application/models/airtime/CcFilesPeer.php b/legacy/application/models/airtime/CcFilesPeer.php
index 0e2fbbe86..f1dad684d 100644
--- a/legacy/application/models/airtime/CcFilesPeer.php
+++ b/legacy/application/models/airtime/CcFilesPeer.php
@@ -1,18 +1,12 @@
utime, new DateTimeZone("UTC"));
+ $dt = new DateTime($this->utime, new DateTimeZone('UTC'));
} catch (Exception $x) {
- throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->utime, true), $x);
+ throw new PropelException('Internally stored date/time/timestamp value could not be converted to DateTime: ' . var_export($this->utime, true), $x);
}
if ($format === null) {
// Because propel.useDateTimeClass is TRUE, we return a DateTime object.
return $dt;
- } elseif (strpos($format, '%') !== false) {
- return strftime($format, $dt->format('U'));
- } else {
- return $dt->format($format);
}
+ if (strpos($format, '%') !== false) {
+ return strftime($format, $dt->format('U'));
+ }
+
+ return $dt->format($format);
}
/**
* Get the [optionally formatted] temporal [mtime] column value.
*
+ * @param string $format The date/time format string (either date()-style or strftime()-style).
+ * If format is NULL, then the raw DateTime object will be returned.
*
- * @param string $format The date/time format string (either date()-style or strftime()-style).
- * If format is NULL, then the raw DateTime object will be returned.
- * @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL
- * @throws PropelException - if unable to parse/validate the date/time value.
+ * @throws propelException - if unable to parse/validate the date/time value
+ *
+ * @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL
*/
public function getDbMtime($format = 'Y-m-d H:i:s')
{
@@ -62,19 +59,20 @@ class CcPlaylist extends BaseCcPlaylist {
}
try {
- $dt = new DateTime($this->mtime, new DateTimeZone("UTC"));
+ $dt = new DateTime($this->mtime, new DateTimeZone('UTC'));
} catch (Exception $x) {
- throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->mtime, true), $x);
+ throw new PropelException('Internally stored date/time/timestamp value could not be converted to DateTime: ' . var_export($this->mtime, true), $x);
}
if ($format === null) {
// Because propel.useDateTimeClass is TRUE, we return a DateTime object.
return $dt;
- } elseif (strpos($format, '%') !== false) {
- return strftime($format, $dt->format('U'));
- } else {
- return $dt->format($format);
}
+ if (strpos($format, '%') !== false) {
+ return strftime($format, $dt->format('U'));
+ }
+
+ return $dt->format($format);
}
/**
@@ -87,7 +85,7 @@ class CcPlaylist extends BaseCcPlaylist {
*/
public function computeDbLength(PropelPDO $con)
{
- $sql = <<execute();
$length = $stmt->fetchColumn();
if (is_null($length)) {
- $length = "00:00:00";
+ $length = '00:00:00';
}
return $length;
}
-
} // CcPlaylist
diff --git a/legacy/application/models/airtime/CcPlaylistPeer.php b/legacy/application/models/airtime/CcPlaylistPeer.php
index 4f7c82791..20b66ad98 100644
--- a/legacy/application/models/airtime/CcPlaylistPeer.php
+++ b/legacy/application/models/airtime/CcPlaylistPeer.php
@@ -1,18 +1,12 @@
fadein = $dt->format('H:i:s.u');
} else {
- $this->fadein = $dt->format('H:i:s').".".$microsecond;
+ $this->fadein = $dt->format('H:i:s') . '.' . $microsecond;
}
$this->modifiedColumns[] = CcPlaylistcontentsPeer::FADEIN;
$this->save();
@@ -76,25 +76,23 @@ class CcPlaylistcontents extends BaseCcPlaylistcontents {
} // setDbFadein()
/**
- *
- * @param String in format SS.uuuuuu, Datetime, or DateTime accepted string.
- *
- * @return CcPlaylistcontents The current object (for fluent API support)
- */
+ * @param string in format SS.uuuuuu, Datetime, or DateTime accepted string.
+ * @param mixed $v
+ *
+ * @return CcPlaylistcontents The current object (for fluent API support)
+ */
public function setDbFadeout($v)
{
$microsecond = 0;
if ($v instanceof DateTime) {
$dt = $v;
- }
- else if (preg_match('/^[0-9]{1,2}(\.\d{1,6})?$/', $v)) {
+ } elseif (preg_match('/^[0-9]{1,2}(\.\d{1,6})?$/', $v)) {
// in php 5.3.2 createFromFormat() with "u" is not supported(bug)
// Hence we need to do parsing.
$info = explode('.', $v);
$microsecond = $info[1];
- $dt = DateTime::createFromFormat("s", $info[0]);
- }
- else {
+ $dt = DateTime::createFromFormat('s', $info[0]);
+ } else {
try {
$dt = new DateTime($v);
} catch (Exception $x) {
@@ -105,14 +103,13 @@ class CcPlaylistcontents extends BaseCcPlaylistcontents {
if ($microsecond == 0) {
$this->fadeout = $dt->format('H:i:s.u');
} else {
- $this->fadeout = $dt->format('H:i:s').".".$microsecond;
+ $this->fadeout = $dt->format('H:i:s') . '.' . $microsecond;
}
$this->modifiedColumns[] = CcPlaylistcontentsPeer::FADEOUT;
$this->save();
//FIXME(XXX): Propel silently drops the milliseconds from our fadeout time. :(
-
+
return $this;
} // setDbFadeout()
-
} // CcPlaylistcontents
diff --git a/legacy/application/models/airtime/CcPlaylistcontentsPeer.php b/legacy/application/models/airtime/CcPlaylistcontentsPeer.php
index 00210575b..67bd620ca 100644
--- a/legacy/application/models/airtime/CcPlaylistcontentsPeer.php
+++ b/legacy/application/models/airtime/CcPlaylistcontentsPeer.php
@@ -1,18 +1,12 @@
starts, new DateTimeZone("UTC"));
+ $dt = new DateTime($this->starts, new DateTimeZone('UTC'));
} catch (Exception $x) {
- throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->starts, true), $x);
+ throw new PropelException('Internally stored date/time/timestamp value could not be converted to DateTime: ' . var_export($this->starts, true), $x);
}
if ($format === null) {
// Because propel.useDateTimeClass is TRUE, we return a DateTime object.
return $dt;
- } elseif (strpos($format, '%') !== false) {
- return strftime($format, $dt->format('U'));
- } else {
- return $dt->format($format);
}
+ if (strpos($format, '%') !== false) {
+ return strftime($format, $dt->format('U'));
+ }
+
+ return $dt->format($format);
}
/**
* Get the [optionally formatted] temporal [ends] column value.
*
+ * @param string $format The date/time format string (either date()-style or strftime()-style).
+ * If format is NULL, then the raw DateTime object will be returned.
*
- * @param string $format The date/time format string (either date()-style or strftime()-style).
- * If format is NULL, then the raw DateTime object will be returned.
- * @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL
- * @throws PropelException - if unable to parse/validate the date/time value.
+ * @throws propelException - if unable to parse/validate the date/time value
+ *
+ * @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL
*/
public function getDbEnds($format = 'Y-m-d H:i:s.u')
{
@@ -62,28 +59,32 @@ class CcSchedule extends BaseCcSchedule {
}
try {
- $dt = new DateTime($this->ends, new DateTimeZone("UTC"));
+ $dt = new DateTime($this->ends, new DateTimeZone('UTC'));
} catch (Exception $x) {
- throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->ends, true), $x);
+ throw new PropelException('Internally stored date/time/timestamp value could not be converted to DateTime: ' . var_export($this->ends, true), $x);
}
if ($format === null) {
// Because propel.useDateTimeClass is TRUE, we return a DateTime object.
return $dt;
- } elseif (strpos($format, '%') !== false) {
- return strftime($format, $dt->format('U'));
- } else {
- return $dt->format($format);
}
+ if (strpos($format, '%') !== false) {
+ return strftime($format, $dt->format('U'));
+ }
+
+ return $dt->format($format);
}
- /**
+ /**
* Get the [optionally formatted] temporal [fadein] column value.
*
- * @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL
- * @throws PropelException - if unable to parse/validate the date/time value.
+ * @param mixed $format
+ *
+ * @throws propelException - if unable to parse/validate the date/time value
+ *
+ * @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL
*/
- public function getDbFadeIn($format = "s.u")
+ public function getDbFadeIn($format = 's.u')
{
return parent::getDbFadein($format);
}
@@ -91,17 +92,20 @@ class CcSchedule extends BaseCcSchedule {
/**
* Get the [optionally formatted] temporal [fadein] column value.
*
- * @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL
- * @throws PropelException - if unable to parse/validate the date/time value.
+ * @param mixed $format
+ *
+ * @throws propelException - if unable to parse/validate the date/time value
+ *
+ * @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL
*/
- public function getDbFadeOut($format = "s.u")
+ public function getDbFadeOut($format = 's.u')
{
return parent::getDbFadeout($format);
}
/**
- *
- * @param String in format SS.uuuuuu, Datetime, or DateTime accepted string.
+ * @param string in format SS.uuuuuu, Datetime, or DateTime accepted string.
+ * @param mixed $v
*
* @return CcPlaylistcontents The current object (for fluent API support)
*/
@@ -110,15 +114,13 @@ class CcSchedule extends BaseCcSchedule {
$microsecond = 0;
if ($v instanceof DateTime) {
$dt = $v;
- }
- else if (preg_match('/^[0-9]{1,2}(\.\d{1,6})?$/', $v)) {
+ } elseif (preg_match('/^[0-9]{1,2}(\.\d{1,6})?$/', $v)) {
// in php 5.3.2 createFromFormat() with "u" is not supported(bug)
// Hence we need to do parsing.
$info = explode('.', $v);
$microsecond = $info[1];
- $dt = DateTime::createFromFormat("s", $info[0]);
- }
- else {
+ $dt = DateTime::createFromFormat('s', $info[0]);
+ } else {
try {
$dt = new DateTime($v);
} catch (Exception $x) {
@@ -129,7 +131,7 @@ class CcSchedule extends BaseCcSchedule {
if ($microsecond == 0) {
$this->fade_in = $dt->format('H:i:s.u');
} else {
- $this->fade_in = $dt->format('H:i:s').".".$microsecond;
+ $this->fade_in = $dt->format('H:i:s') . '.' . $microsecond;
}
$this->modifiedColumns[] = CcSchedulePeer::FADE_IN;
@@ -137,25 +139,23 @@ class CcSchedule extends BaseCcSchedule {
} // setDbFadein()
/**
- *
- * @param String in format SS.uuuuuu, Datetime, or DateTime accepted string.
- *
- * @return CcPlaylistcontents The current object (for fluent API support)
- */
+ * @param string in format SS.uuuuuu, Datetime, or DateTime accepted string.
+ * @param mixed $v
+ *
+ * @return CcPlaylistcontents The current object (for fluent API support)
+ */
public function setDbFadeOut($v)
{
$microsecond = 0;
if ($v instanceof DateTime) {
$dt = $v;
- }
- else if (preg_match('/^[0-9]{1,2}(\.\d{1,6})?$/', $v)) {
+ } elseif (preg_match('/^[0-9]{1,2}(\.\d{1,6})?$/', $v)) {
// in php 5.3.2 createFromFormat() with "u" is not supported(bug)
// Hence we need to do parsing.
$info = explode('.', $v);
$microsecond = $info[1];
- $dt = DateTime::createFromFormat("s", $info[0]);
- }
- else {
+ $dt = DateTime::createFromFormat('s', $info[0]);
+ } else {
try {
$dt = new DateTime($v);
} catch (Exception $x) {
@@ -166,7 +166,7 @@ class CcSchedule extends BaseCcSchedule {
if ($microsecond == 0) {
$this->fade_out = $dt->format('H:i:s.u');
} else {
- $this->fade_out = $dt->format('H:i:s').".".$microsecond;
+ $this->fade_out = $dt->format('H:i:s') . '.' . $microsecond;
}
$this->modifiedColumns[] = CcSchedulePeer::FADE_OUT;
@@ -176,15 +176,16 @@ class CcSchedule extends BaseCcSchedule {
/**
* Sets the value of [starts] column to a normalized version of the date/time value specified.
*
- * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will
- * be treated as NULL for temporal objects.
- * @return CcSchedule The current object (for fluent API support)
+ * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will
+ * be treated as NULL for temporal objects.
+ *
+ * @return CcSchedule The current object (for fluent API support)
*/
public function setDbStarts($v)
{
$utcTimeZone = new DateTimeZone('UTC');
-
- if ($v instanceof DateTime) {
+
+ if ($v instanceof DateTime) {
$dt = $v;
$dt->setTimezone($utcTimeZone);
} else {
@@ -192,8 +193,7 @@ class CcSchedule extends BaseCcSchedule {
// validate it.
try {
if (is_numeric($v)) { // if it's a unix timestamp
- $dt = new DateTime('@'.$v, $utcTimeZone);
-
+ $dt = new DateTime('@' . $v, $utcTimeZone);
} else {
$dt = new DateTime($v, $utcTimeZone);
}
@@ -211,14 +211,15 @@ class CcSchedule extends BaseCcSchedule {
/**
* Sets the value of [ends] column to a normalized version of the date/time value specified.
*
- * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will
- * be treated as NULL for temporal objects.
- * @return CcSchedule The current object (for fluent API support)
+ * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will
+ * be treated as NULL for temporal objects.
+ *
+ * @return CcSchedule The current object (for fluent API support)
*/
public function setDbEnds($v)
{
- $utcTimeZone = new DateTimeZone('UTC');
-
+ $utcTimeZone = new DateTimeZone('UTC');
+
if ($v instanceof DateTime) {
$dt = $v;
$dt->setTimezone($utcTimeZone);
@@ -227,8 +228,7 @@ class CcSchedule extends BaseCcSchedule {
// validate it.
try {
if (is_numeric($v)) { // if it's a unix timestamp
- $dt = new DateTime('@'.$v, $utcTimeZone);
-
+ $dt = new DateTime('@' . $v, $utcTimeZone);
} else {
$dt = new DateTime($v, $utcTimeZone);
}
@@ -242,21 +242,20 @@ class CcSchedule extends BaseCcSchedule {
return $this;
} // setDbEnds()
-
- public function isCurrentItem($epochNow = null) {
-
+
+ public function isCurrentItem($epochNow = null)
+ {
if (is_null($epochNow)) {
$epochNow = microtime(true);
}
-
+
$epochStart = floatval($this->getDbStarts('U.u'));
$epochEnd = floatval($this->getDbEnds('U.u'));
-
+
if ($epochStart < $epochNow && $epochEnd > $epochNow) {
return true;
}
-
+
return false;
}
-
} // CcSchedule
diff --git a/legacy/application/models/airtime/CcSchedulePeer.php b/legacy/application/models/airtime/CcSchedulePeer.php
index 869599c7c..9c8cc373d 100644
--- a/legacy/application/models/airtime/CcSchedulePeer.php
+++ b/legacy/application/models/airtime/CcSchedulePeer.php
@@ -1,18 +1,12 @@
filterByDbShowId($this->id)
->filterByDbRepeatType(-1, Criteria::NOT_EQUAL)
- ->find();
+ ->find()
+ ;
}
/**
@@ -40,17 +36,19 @@ class CcShow extends BaseCcShow {
* If this CcShow is new, it will return
* an empty collection or the current collection; the criteria is ignored on a new object.
*
- * @param Criteria $criteria optional Criteria object to narrow the query
- * @param PropelPDO $con optional connection object
- * @return PropelCollection|array CcShowDays[] List of CcShowDays objects
- * @throws PropelException
+ * @param Criteria $criteria optional Criteria object to narrow the query
+ * @param PropelPDO $con optional connection object
+ *
+ * @throws PropelException
+ *
+ * @return array|PropelCollection CcShowDays[] List of CcShowDays objects
*/
public function getFirstCcShowDay($criteria = null, PropelPDO $con = null)
{
/*CcShowPeer::clearInstancePool();
CcShowPeer::clearRelatedInstancePool();*/
- if(null === $this->collCcShowDayss || null !== $criteria) {
+ if (null === $this->collCcShowDayss || null !== $criteria) {
if ($this->isNew() && null === $this->collCcShowDayss) {
// return empty collection
$this->initCcShowDayss();
@@ -59,22 +57,23 @@ class CcShow extends BaseCcShow {
->filterByCcShow($this)
->orderByDbFirstShow()
->limit(1)
- ->find($con);
+ ->find($con)
+ ;
if (null !== $criteria) {
return $collCcShowDayss;
}
$this->collCcShowDayss = $collCcShowDayss;
}
}
+
return $this->collCcShowDayss[0];
}
/**
- *
* A repeating show may have a rule in cc_show_days with a repeat type
* of -1 (not repeating). This happens when a single instances was edited
* from the repeating sequence.
- *
+ *
* When the repeating show gets edited in this case, we want to exclude all
* the edited instances from the update. We do this by not returning any of
* the cc_show_day rules with a -1 repeat type.
@@ -85,16 +84,16 @@ class CcShow extends BaseCcShow {
->filterByDbShowId($this->id)
->filterByDbRepeatType(-1, Criteria::NOT_EQUAL)
->orderByDbFirstShow()
- ->findOne();
+ ->findOne()
+ ;
}
/**
- *
* In order to determine if a show is repeating we need to check each
* cc_show_day entry and check if there are any non -1 repeat types.
* Because editing a single instances creates a new cc_show_day rule
* with a -1 (non repeating) repeat type we need to check all cc_show_day
- * entries
+ * entries.
*/
public function isRepeating()
{
@@ -102,7 +101,8 @@ class CcShow extends BaseCcShow {
$ccShowDays = CcShowDaysQuery::create()
->filterByDbShowId($this->id)
->filterByDbRepeatType(0, Criteria::GREATER_EQUAL)
- ->find();
+ ->find()
+ ;
if (!$ccShowDays->isEmpty()) {
return true;
@@ -113,7 +113,7 @@ class CcShow extends BaseCcShow {
/**
* Returns all cc_show_instances that have been edited out of
- * a repeating sequence
+ * a repeating sequence.
*/
public function getEditedRepeatingInstanceIds()
{
@@ -121,27 +121,29 @@ class CcShow extends BaseCcShow {
$ccShowDays = CcShowDaysQuery::create()
->filterByDbShowId($this->id)
->filterByDbRepeatType(-1)
- ->find();
+ ->find()
+ ;
- $startsUTC = array();
+ $startsUTC = [];
- $utc = new DateTimeZone("UTC");
+ $utc = new DateTimeZone('UTC');
foreach ($ccShowDays as $day) {
//convert to UTC
$starts = new DateTime(
- $day->getDbFirstShow()." ".$day->getDbStartTime(),
+ $day->getDbFirstShow() . ' ' . $day->getDbStartTime(),
new DateTimeZone($day->getDbTimezone())
);
$starts->setTimezone($utc);
- array_push($startsUTC, $starts->format("Y-m-d H:i:s"));
+ array_push($startsUTC, $starts->format('Y-m-d H:i:s'));
}
$excludeInstances = CcShowInstancesQuery::create()
->filterByDbShowId($this->id)
->filterByDbStarts($startsUTC, criteria::IN)
- ->find();
+ ->find()
+ ;
- $excludeIds = array();
+ $excludeIds = [];
foreach ($excludeInstances as $instance) {
array_push($excludeIds, $instance->getDbId());
}
@@ -158,29 +160,33 @@ class CcShow extends BaseCcShow {
* If this CcShow is new, it will return
* an empty collection or the current collection; the criteria is ignored on a new object.
*
- * @param Criteria $criteria optional Criteria object to narrow the query
- * @param PropelPDO $con optional connection object
- * @return PropelCollection|array CcShowInstances[] List of CcShowInstances objects
- * @throws PropelException
+ * @param Criteria $criteria optional Criteria object to narrow the query
+ * @param PropelPDO $con optional connection object
+ *
+ * @throws PropelException
+ *
+ * @return array|PropelCollection CcShowInstances[] List of CcShowInstances objects
*/
public function getFutureCcShowInstancess($criteria = null, PropelPDO $con = null)
{
- if(null === $this->collCcShowInstancess || null !== $criteria) {
+ if (null === $this->collCcShowInstancess || null !== $criteria) {
if ($this->isNew() && null === $this->collCcShowInstancess) {
// return empty collection
$this->initCcShowInstancess();
} else {
$collCcShowInstancess = CcShowInstancesQuery::create(null, $criteria)
->filterByCcShow($this)
- ->filterByDbStarts(gmdate("Y-m-d H:i:s"), Criteria::GREATER_THAN)
+ ->filterByDbStarts(gmdate('Y-m-d H:i:s'), Criteria::GREATER_THAN)
->filterByDbModifiedInstance(false)
- ->find($con);
+ ->find($con)
+ ;
if (null !== $criteria) {
return $collCcShowInstancess;
}
$this->collCcShowInstancess = $collCcShowInstancess;
}
}
+
return $this->collCcShowInstancess;
}
@@ -189,18 +195,20 @@ class CcShow extends BaseCcShow {
$ccShowDay = CcShowDaysQuery::create()
->filterByDbShowId($this->getDbId())
->filterByDbRecord(1)
- ->findOne();
+ ->findOne()
+ ;
- return (!is_null($ccShowDay));
+ return !is_null($ccShowDay);
}
public function isRebroadcast()
{
$ccShowRebroadcast = CcShowRebroadcastQuery::create()
->filterByDbShowId($this->getDbId())
- ->findOne();
+ ->findOne()
+ ;
- return (!is_null($ccShowRebroadcast));
+ return !is_null($ccShowRebroadcast);
}
public function getRebroadcastsRelative()
@@ -208,7 +216,8 @@ class CcShow extends BaseCcShow {
return CcShowRebroadcastQuery::create()
->filterByDbShowId($this->getDbId())
->orderByDbDayOffset()
- ->find();
+ ->find()
+ ;
}
public function getRebroadcastsAbsolute()
@@ -218,7 +227,8 @@ class CcShow extends BaseCcShow {
->filterByDbRebroadcast(1)
->filterByDbModifiedInstance(false)
->orderByDbStarts()
- ->find();
+ ->find()
+ ;
}
public function isLinked()
@@ -240,18 +250,21 @@ class CcShow extends BaseCcShow {
* If this CcShow is new, it will return
* an empty collection or the current collection; the criteria is ignored on a new object.
*
- * @param Criteria $criteria optional Criteria object to narrow the query
- * @param PropelPDO $con optional connection object
- * @return PropelCollection|array CcShowInstances[] List of CcShowInstances objects
- * @throws PropelException
+ * @param Criteria $criteria optional Criteria object to narrow the query
+ * @param PropelPDO $con optional connection object
+ *
+ * @throws PropelException
+ *
+ * @return array|PropelCollection CcShowInstances[] List of CcShowInstances objects
*/
public function getCcShowInstancess($criteria = null, PropelPDO $con = null)
{
return CcShowInstancesQuery::create(null, $criteria)
- ->filterByCcShow($this)
- ->filterByDbModifiedInstance(false)
- ->orderByDbId()
- ->find($con);
+ ->filterByCcShow($this)
+ ->filterByDbModifiedInstance(false)
+ ->orderByDbId()
+ ->find($con)
+ ;
/*if(null === $this->collCcShowInstancess || null !== $criteria) {
if ($this->isNew() && null === $this->collCcShowInstancess) {
@@ -273,26 +286,30 @@ class CcShow extends BaseCcShow {
return $this->collCcShowInstancess;*/
}
- public function getInstanceIds() {
- $instanceIds = array();
+ public function getInstanceIds()
+ {
+ $instanceIds = [];
foreach ($this->getCcShowInstancess() as $ccShowInstance) {
$instanceIds[] = $ccShowInstance->getDbId();
}
+
return $instanceIds;
}
-
+
/*
* Returns cc_show_instance ids where the start time is greater than
* the current time
- *
- * If a Criteria object is passed in Propel will always fetch the
+ *
+ * If a Criteria object is passed in Propel will always fetch the
* results from the database and not return a cached collection
*/
- public function getFutureInstanceIds($criteria = null) {
- $instanceIds = array();
+ public function getFutureInstanceIds($criteria = null)
+ {
+ $instanceIds = [];
foreach ($this->getFutureCcShowInstancess($criteria) as $ccShowInstance) {
$instanceIds[] = $ccShowInstance->getDbId();
}
+
return $instanceIds;
}
@@ -302,28 +319,28 @@ class CcShow extends BaseCcShow {
return CcShowInstancesQuery::create()
->filterByCcShow($this)
->filterByDbId($instanceId, Criteria::NOT_EQUAL)
- ->find();
+ ->find()
+ ;
}
public function getShowInfo()
{
- $info = array();
+ $info = [];
if ($this->getDbId() == null) {
return $info;
- } else {
- $info['name'] = $this->getDbName();
- $info['id'] = $this->getDbId();
- $info['url'] = $this->getDbUrl();
- $info['genre'] = $this->getDbGenre();
- $info['description'] = $this->getDbDescription();
- $info['color'] = $this->getDbColor();
- $info['background_color'] = $this->getDbBackgroundColor();
- $info['linked'] = $this->getDbLinked();
- $info['has_autoplaylist'] = $this->getDbHasAutoPlaylist();
- $info['autoplaylist_id'] = $this->getDbAutoPlaylistId();
- $info['autoplaylist_repeat'] = $this->getDbAutoPlaylistRepeat();
- return $info;
}
+ $info['name'] = $this->getDbName();
+ $info['id'] = $this->getDbId();
+ $info['url'] = $this->getDbUrl();
+ $info['genre'] = $this->getDbGenre();
+ $info['description'] = $this->getDbDescription();
+ $info['color'] = $this->getDbColor();
+ $info['background_color'] = $this->getDbBackgroundColor();
+ $info['linked'] = $this->getDbLinked();
+ $info['has_autoplaylist'] = $this->getDbHasAutoPlaylist();
+ $info['autoplaylist_id'] = $this->getDbAutoPlaylistId();
+ $info['autoplaylist_repeat'] = $this->getDbAutoPlaylistRepeat();
+ return $info;
}
} // CcShow
diff --git a/legacy/application/models/airtime/CcShowDays.php b/legacy/application/models/airtime/CcShowDays.php
index 2f187bf44..ea4efe61f 100644
--- a/legacy/application/models/airtime/CcShowDays.php
+++ b/legacy/application/models/airtime/CcShowDays.php
@@ -1,20 +1,14 @@
getDbRepeatType() != -1;
@@ -26,7 +20,7 @@ class CcShowDays extends BaseCcShowDays {
"{$this->getDbFirstShow()} {$this->getDbStartTime()}",
new DateTimeZone($this->getDbTimezone())
);
- $dt->setTimezone(new DateTimeZone("UTC"));
+ $dt->setTimezone(new DateTimeZone('UTC'));
return $dt;
}
@@ -34,38 +28,37 @@ class CcShowDays extends BaseCcShowDays {
// Returns the start of a show in the timezone it was created in
public function getLocalStartDateAndTime()
{
- $dt = new DateTime(
+ return new DateTime(
"{$this->getDbFirstShow()} {$this->getDbStartTime()}",
new DateTimeZone($this->getDbTimezone())
);
//set timezone to that of the show
//$dt->setTimezone(new DateTimeZone($this->getDbTimezone()));
- return $dt;
}
/**
- *
- * Returns the end of a show in the timezone it was created in
+ * Returns the end of a show in the timezone it was created in.
+ *
* @param DateTime $startDateTime first show in show's local time
*/
public function getLocalEndDateAndTime()
{
$startDateTime = $this->getLocalStartDateAndTime();
- $duration = explode(":", $this->getDbDuration());
+ $duration = explode(':', $this->getDbDuration());
- return $startDateTime->add(new DateInterval('PT'.$duration[0].'H'.$duration[1].'M'));
+ return $startDateTime->add(new DateInterval('PT' . $duration[0] . 'H' . $duration[1] . 'M'));
}
public function isShowStartInPast()
{
- return $this->getUTCStartDateAndTime()->format("Y-m-d H:i:s") < gmdate("Y-m-d H:i:s");
+ return $this->getUTCStartDateAndTime()->format('Y-m-d H:i:s') < gmdate('Y-m-d H:i:s');
}
public function formatDuration()
{
- $info = explode(':',$this->getDbDuration());
+ $info = explode(':', $this->getDbDuration());
- return str_pad(intval($info[0]),2,'0',STR_PAD_LEFT).'h '.str_pad(intval($info[1]),2,'0',STR_PAD_LEFT).'m';
+ return str_pad(intval($info[0]), 2, '0', STR_PAD_LEFT) . 'h ' . str_pad(intval($info[1]), 2, '0', STR_PAD_LEFT) . 'm';
}
} // CcShowDays
diff --git a/legacy/application/models/airtime/CcShowDaysPeer.php b/legacy/application/models/airtime/CcShowDaysPeer.php
index d6f5d8f7b..e21de8772 100644
--- a/legacy/application/models/airtime/CcShowDaysPeer.php
+++ b/legacy/application/models/airtime/CcShowDaysPeer.php
@@ -1,18 +1,12 @@
starts, new DateTimeZone("UTC"));
+ $dt = new DateTime($this->starts, new DateTimeZone('UTC'));
} catch (Exception $x) {
- throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->starts, true), $x);
+ throw new PropelException('Internally stored date/time/timestamp value could not be converted to DateTime: ' . var_export($this->starts, true), $x);
}
if ($format === null) {
// Because propel.useDateTimeClass is TRUE, we return a DateTime object.
return $dt;
- } elseif (strpos($format, '%') !== false) {
- return strftime($format, $dt->format('U'));
- } else {
- return $dt->format($format);
}
+ if (strpos($format, '%') !== false) {
+ return strftime($format, $dt->format('U'));
+ }
+
+ return $dt->format($format);
}
/**
* Get the [optionally formatted] temporal [ends] column value.
*
+ * @param string $format The date/time format string (either date()-style or strftime()-style).
+ * If format is NULL, then the raw DateTime object will be returned.
*
- * @param string $format The date/time format string (either date()-style or strftime()-style).
- * If format is NULL, then the raw DateTime object will be returned.
- * @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL
- * @throws PropelException - if unable to parse/validate the date/time value.
+ * @throws propelException - if unable to parse/validate the date/time value
+ *
+ * @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL
*/
public function getDbEnds($format = 'Y-m-d H:i:s')
{
@@ -62,29 +59,31 @@ class CcShowInstances extends BaseCcShowInstances {
}
try {
- $dt = new DateTime($this->ends, new DateTimeZone("UTC"));
+ $dt = new DateTime($this->ends, new DateTimeZone('UTC'));
} catch (Exception $x) {
- throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->ends, true), $x);
+ throw new PropelException('Internally stored date/time/timestamp value could not be converted to DateTime: ' . var_export($this->ends, true), $x);
}
if ($format === null) {
// Because propel.useDateTimeClass is TRUE, we return a DateTime object.
return $dt;
- } elseif (strpos($format, '%') !== false) {
- return strftime($format, $dt->format('U'));
- } else {
- return $dt->format($format);
}
+ if (strpos($format, '%') !== false) {
+ return strftime($format, $dt->format('U'));
+ }
+
+ return $dt->format($format);
}
/**
* Get the [optionally formatted] temporal [last_scheduled] column value.
*
+ * @param string $format The date/time format string (either date()-style or strftime()-style).
+ * If format is NULL, then the raw DateTime object will be returned.
*
- * @param string $format The date/time format string (either date()-style or strftime()-style).
- * If format is NULL, then the raw DateTime object will be returned.
- * @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL
- * @throws PropelException - if unable to parse/validate the date/time value.
+ * @throws propelException - if unable to parse/validate the date/time value
+ *
+ * @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL
*/
public function getDbLastScheduled($format = 'Y-m-d H:i:s')
{
@@ -93,24 +92,25 @@ class CcShowInstances extends BaseCcShowInstances {
}
try {
- $dt = new DateTime($this->last_scheduled, new DateTimeZone("UTC"));
+ $dt = new DateTime($this->last_scheduled, new DateTimeZone('UTC'));
} catch (Exception $x) {
- throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->last_scheduled, true), $x);
+ throw new PropelException('Internally stored date/time/timestamp value could not be converted to DateTime: ' . var_export($this->last_scheduled, true), $x);
}
if ($format === null) {
// Because propel.useDateTimeClass is TRUE, we return a DateTime object.
return $dt;
- } elseif (strpos($format, '%') !== false) {
- return strftime($format, $dt->format('U'));
- } else {
- return $dt->format($format);
}
+ if (strpos($format, '%') !== false) {
+ return strftime($format, $dt->format('U'));
+ }
+
+ return $dt->format($format);
}
//post save hook to update the cc_schedule status column for the tracks in the show.
- public function updateScheduleStatus(PropelPDO $con) {
-
+ public function updateScheduleStatus(PropelPDO $con)
+ {
$this->updateDbTimeFilled($con);
//scheduled track is in the show
@@ -118,7 +118,8 @@ class CcShowInstances extends BaseCcShowInstances {
->filterByDbInstanceId($this->id)
->filterByDbPlayoutStatus(0, Criteria::GREATER_EQUAL)
->filterByDbEnds($this->ends, Criteria::LESS_EQUAL)
- ->update(array('DbPlayoutStatus' => 1), $con);
+ ->update(['DbPlayoutStatus' => 1], $con)
+ ;
//scheduled track is a boundary track
CcScheduleQuery::create()
@@ -126,24 +127,25 @@ class CcShowInstances extends BaseCcShowInstances {
->filterByDbPlayoutStatus(0, Criteria::GREATER_EQUAL)
->filterByDbStarts($this->ends, Criteria::LESS_THAN)
->filterByDbEnds($this->ends, Criteria::GREATER_THAN)
- ->update(array('DbPlayoutStatus' => 2), $con);
+ ->update(['DbPlayoutStatus' => 2], $con)
+ ;
//scheduled track is overbooked.
CcScheduleQuery::create()
->filterByDbInstanceId($this->id)
->filterByDbPlayoutStatus(0, Criteria::GREATER_EQUAL)
->filterByDbStarts($this->ends, Criteria::GREATER_THAN)
- ->update(array('DbPlayoutStatus' => 0), $con);
-
- $this->setDbLastScheduled(gmdate("Y-m-d H:i:s"));
+ ->update(['DbPlayoutStatus' => 0], $con)
+ ;
+
+ $this->setDbLastScheduled(gmdate('Y-m-d H:i:s'));
$this->save($con);
}
/**
- *
* This function resets the cc_schedule table's position numbers so that
- * tracks for each cc_show_instances start at position 1
- *
+ * tracks for each cc_show_instances start at position 1.
+ *
* The position numbers can become out of sync when the user deletes items
* from linekd shows filled with dyanmic smart blocks, where each instance
* has a different amount of scheduled items
@@ -153,17 +155,18 @@ class CcShowInstances extends BaseCcShowInstances {
$schedule = CcScheduleQuery::create()
->filterByDbInstanceId($this->id)
->orderByDbStarts()
- ->find();
+ ->find()
+ ;
$pos = 0;
foreach ($schedule as $item) {
$item->setDbPosition($pos)->save();
- $pos++;
+ ++$pos;
}
}
-
+
/**
- * Computes the value of the aggregate column time_filled
+ * Computes the value of the aggregate column time_filled.
*
* @param PropelPDO $con A connection object
*
@@ -174,27 +177,30 @@ class CcShowInstances extends BaseCcShowInstances {
$stmt = $con->prepare('SELECT SUM(clip_length) FROM "cc_schedule" WHERE cc_schedule.INSTANCE_ID = :p1');
$stmt->bindValue(':p1', $this->getDbId());
$stmt->execute();
+
return $stmt->fetchColumn();
}
-
+
/**
- * Updates the aggregate column time_filled
+ * Updates the aggregate column time_filled.
*
* @param PropelPDO $con A connection object
*/
public function updateDbTimeFilled(PropelPDO $con)
{
$timefilled = $this->computeDbTimeFilled($con);
- if(is_null($timefilled)){
- $timefilled = "00:00:00";
+ if (is_null($timefilled)) {
+ $timefilled = '00:00:00';
}
$this->setDbTimeFilled($timefilled);
$this->save($con);
}
-
- public function preInsert(PropelPDO $con = null) {
- $now = new DateTime("now", new DateTimeZone("UTC"));
+
+ public function preInsert(PropelPDO $con = null)
+ {
+ $now = new DateTime('now', new DateTimeZone('UTC'));
$this->setDbCreated($now);
+
return true;
}
@@ -211,7 +217,7 @@ class CcShowInstances extends BaseCcShowInstances {
public function getLocalStartDateTime()
{
$startDT = $this->getDbStarts(null);
+
return $startDT->setTimezone(new DateTimeZone(Application_Model_Preference::GetTimezone()));
}
-
} // CcShowInstances
diff --git a/legacy/application/models/airtime/CcShowInstancesPeer.php b/legacy/application/models/airtime/CcShowInstancesPeer.php
index 0b131d575..380de9eee 100644
--- a/legacy/application/models/airtime/CcShowInstancesPeer.php
+++ b/legacy/application/models/airtime/CcShowInstancesPeer.php
@@ -1,18 +1,12 @@
type === UTYPE_SUPERADMIN || $this->type === UTYPE_ADMIN || $this->type === UTYPE_PROGRAM_MANAGER;
@@ -34,11 +30,12 @@ class CcSubjs extends BaseCcSubjs {
public function isHostOfShowInstance($instanceId)
{
$showInstance = CcShowInstancesQuery::create()
- ->findPk($instanceId);
+ ->findPk($instanceId)
+ ;
return CcShowHostsQuery::create()
- ->filterByDbShow($showInstance->getDbShowId())
- ->filterByDbHost($this->getDbId())
- ->count() > 0;
+ ->filterByDbShow($showInstance->getDbShowId())
+ ->filterByDbHost($this->getDbId())
+ ->count() > 0;
}
} // CcSubjs
diff --git a/legacy/application/models/airtime/CcSubjsPeer.php b/legacy/application/models/airtime/CcSubjsPeer.php
index c3a3108e5..62d7f0de0 100644
--- a/legacy/application/models/airtime/CcSubjsPeer.php
+++ b/legacy/application/models/airtime/CcSubjsPeer.php
@@ -1,18 +1,12 @@
proxyStorageBackend == null) {
$this->proxyStorageBackend = new ProxyStorageBackend($this->getStorageBackend());
}
+
return $this->proxyStorageBackend->getDownloadURLs($this->getResourceId(), $this->getFilename());
}
-
+
/**
- *
* Returns a url to the file's object on Amazon S3.
*/
public function getAbsoluteFilePath()
@@ -42,9 +40,10 @@ class CloudFile extends BaseCloudFile
if ($this->proxyStorageBackend == null) {
$this->proxyStorageBackend = new ProxyStorageBackend($this->getStorageBackend());
}
+
return $this->proxyStorageBackend->getAbsoluteFilePath($this->getResourceId());
}
-
+
public function getFilename()
{
$filename = $this->getDbFilepath();
@@ -56,7 +55,7 @@ class CloudFile extends BaseCloudFile
return $info['filename'] . $extension;
}
-
+
/**
* Checks if the file is a regular file that can be previewed and downloaded.
*/
@@ -68,10 +67,9 @@ class CloudFile extends BaseCloudFile
// does not get imported into the Airtime library.
return true;
}
-
+
/**
- *
- * Deletes the file from cloud storage
+ * Deletes the file from cloud storage.
*/
public function deletePhysicalFile()
{
@@ -80,12 +78,11 @@ class CloudFile extends BaseCloudFile
}
$this->proxyStorageBackend->deletePhysicalFile($this->getResourceId());
}
-
+
/**
- *
* Deletes the cc_file and cloud_file entries from the database.
*/
- public function delete(PropelPDO $con = NULL)
+ public function delete(PropelPDO $con = null)
{
CcFilesQuery::create()->findPk($this->getCcFileId())->delete();
parent::delete();
diff --git a/legacy/application/models/airtime/CloudFilePeer.php b/legacy/application/models/airtime/CloudFilePeer.php
index 873219860..6cb845957 100644
--- a/legacy/application/models/airtime/CloudFilePeer.php
+++ b/legacy/application/models/airtime/CloudFilePeer.php
@@ -1,17 +1,11 @@
fromArray($arr, $keyType);
$importedPodcast->save();
- } else {
- //TODO: station podcast
}
+ //TODO: station podcast
}
-
}
diff --git a/legacy/application/models/airtime/PodcastEpisodes.php b/legacy/application/models/airtime/PodcastEpisodes.php
index f1ea44b59..f80c43554 100644
--- a/legacy/application/models/airtime/PodcastEpisodes.php
+++ b/legacy/application/models/airtime/PodcastEpisodes.php
@@ -1,21 +1,14 @@
getDbPodcastId();
// We may have more station podcasts later, so use this instead of checking the id stored in Preference
$podcast = StationPodcastQuery::create()->findOneByDbPodcastId($podcastId);
@@ -35,9 +29,10 @@ class PodcastEpisodes extends BasePodcastEpisodes
$file = CcFilesQuery::create()->findPk($fileId);
$ext = FileDataHelper::getAudioMimeTypeArray()[$file->getDbMime()];
$key = Application_Model_Preference::getStationPodcastDownloadKey();
- return Application_Common_HTTPHelper::getStationUrl()."rest/media/$fileId/download/$key.$ext";
+
+ return Application_Common_HTTPHelper::getStationUrl() . "rest/media/{$fileId}/download/{$key}.{$ext}";
}
+
return parent::getDbDownloadUrl();
}
-
}
diff --git a/legacy/application/models/airtime/PodcastEpisodesPeer.php b/legacy/application/models/airtime/PodcastEpisodesPeer.php
index 082d056cd..9d7eda9d7 100644
--- a/legacy/application/models/airtime/PodcastEpisodesPeer.php
+++ b/legacy/application/models/airtime/PodcastEpisodesPeer.php
@@ -1,17 +1,11 @@
filterByDbPodcastId($this->getDbPodcastId())
- ->find();
+ ->find()
+ ;
foreach ($episodes as $e) {
- if ($e->getDbFileId() == $fileId) return true;
+ if ($e->getDbFileId() == $fileId) {
+ return true;
+ }
}
+
return false;
}
-
}
diff --git a/legacy/application/models/airtime/StationPodcastPeer.php b/legacy/application/models/airtime/StationPodcastPeer.php
index 3b27e1b0e..824420d11 100644
--- a/legacy/application/models/airtime/StationPodcastPeer.php
+++ b/legacy/application/models/airtime/StationPodcastPeer.php
@@ -1,17 +1,11 @@
_bitrate = $bitrate;
@@ -20,9 +18,9 @@ class BitrateFormatter
$kbps = bcdiv($this->_bitrate, 1000, 0);
if ($kbps == 0) {
- return "";
- } else {
- return "$kbps Kbps";
+ return '';
}
+
+ return "{$kbps} Kbps";
}
}
diff --git a/legacy/application/models/formatters/LengthFormatter.php b/legacy/application/models/formatters/LengthFormatter.php
index 140d69b1c..eb065ee48 100644
--- a/legacy/application/models/formatters/LengthFormatter.php
+++ b/legacy/application/models/formatters/LengthFormatter.php
@@ -7,9 +7,7 @@ class LengthFormatter
*/
private $_length;
- /*
- * @param string $length formatted H:i:s.u (can be > 24 hours)
- */
+ // @param string $length formatted H:i:s.u (can be > 24 hours)
public function __construct($length)
{
$this->_length = $length;
@@ -17,26 +15,25 @@ class LengthFormatter
public function format()
{
- if (!preg_match("/^[0-9]{2}:[0-9]{2}:[0-9]{2}/", $this->_length)) {
+ if (!preg_match('/^[0-9]{2}:[0-9]{2}:[0-9]{2}/', $this->_length)) {
return $this->_length;
}
- $pieces = explode(":", $this->_length);
+ $pieces = explode(':', $this->_length);
$seconds = round($pieces[2], 1);
$seconds = number_format($seconds, 1);
- list($seconds, $milliStr) = explode(".", $seconds);
+ list($seconds, $milliStr) = explode('.', $seconds);
if (intval($pieces[0]) !== 0) {
- $hours = ltrim($pieces[0], "0");
+ $hours = ltrim($pieces[0], '0');
}
$minutes = $pieces[1];
//length is less than 1 hour
if (!isset($hours)) {
-
if (intval($minutes) !== 0) {
- $minutes = ltrim($minutes, "0");
+ $minutes = ltrim($minutes, '0');
}
//length is less than 1 minute
else {
@@ -44,15 +41,14 @@ class LengthFormatter
}
}
- if (isset($hours) && isset($minutes) && isset($seconds)) {
- $time = sprintf("%d:%02d:%02d.%s", $hours, $minutes, $seconds, $milliStr);
- } elseif (isset($minutes) && isset($seconds)) {
- $time = sprintf("%d:%02d.%s", $minutes, $seconds, $milliStr);
+ if (isset($hours, $minutes, $seconds)) {
+ $time = sprintf('%d:%02d:%02d.%s', $hours, $minutes, $seconds, $milliStr);
+ } elseif (isset($minutes, $seconds)) {
+ $time = sprintf('%d:%02d.%s', $minutes, $seconds, $milliStr);
} else {
- $time = sprintf("%d.%s", $seconds, $milliStr);
+ $time = sprintf('%d.%s', $seconds, $milliStr);
}
return $time;
}
-
}
diff --git a/legacy/application/models/formatters/SamplerateFormatter.php b/legacy/application/models/formatters/SamplerateFormatter.php
index f3c436f30..2c309108b 100644
--- a/legacy/application/models/formatters/SamplerateFormatter.php
+++ b/legacy/application/models/formatters/SamplerateFormatter.php
@@ -7,9 +7,7 @@ class SamplerateFormatter
*/
private $_samplerate;
- /*
- * @param string $samplerate Hz
- */
+ // @param string $samplerate Hz
public function __construct($samplerate)
{
$this->_samplerate = $samplerate;
diff --git a/legacy/application/models/formatters/TimeFilledFormatter.php b/legacy/application/models/formatters/TimeFilledFormatter.php
index df3476612..9785be13f 100644
--- a/legacy/application/models/formatters/TimeFilledFormatter.php
+++ b/legacy/application/models/formatters/TimeFilledFormatter.php
@@ -7,9 +7,7 @@ class TimeFilledFormatter
*/
private $_seconds;
- /*
- * @param string $seconds
- */
+ // @param string $seconds
public function __construct($seconds)
{
$this->_seconds = $seconds;
@@ -17,23 +15,23 @@ class TimeFilledFormatter
public function format()
{
- $formatted = "";
- $sign = ($this->_seconds < 0) ? "-" : "+";
+ $formatted = '';
+ $sign = ($this->_seconds < 0) ? '-' : '+';
$perfect = true;
$time = Application_Common_DateHelper::secondsToPlaylistTime(abs($this->_seconds));
- $info = explode(":", $time);
+ $info = explode(':', $time);
$formatted .= $sign;
if (intval($info[0]) > 0) {
- $info[0] = ltrim($info[0], "0");
+ $info[0] = ltrim($info[0], '0');
$formatted .= " {$info[0]}h";
$perfect = false;
}
if (intval($info[1]) > 0) {
- $info[1] = ltrim($info[1], "0");
+ $info[1] = ltrim($info[1], '0');
$formatted .= " {$info[1]}m";
$perfect = false;
}
@@ -46,7 +44,7 @@ class TimeFilledFormatter
//0 over/under lap of content.
if ($perfect === true) {
- $formatted = "+ 0s";
+ $formatted = '+ 0s';
}
return $formatted;
diff --git a/legacy/application/models/tests/AllTests.php b/legacy/application/models/tests/AllTests.php
index 7bfc03c9e..148e0fa74 100644
--- a/legacy/application/models/tests/AllTests.php
+++ b/legacy/application/models/tests/AllTests.php
@@ -1,17 +1,16 @@
addTestSuite("PlaylistTests");
-$suite->addTestSuite("SchedulerTests");
+$suite = new PHPUnit_TestSuite('StoredFileTest');
+$suite->addTestSuite('PlaylistTests');
+$suite->addTestSuite('SchedulerTests');
//$suite->addTestSuite("SchedulerExportTests");
$result = PHPUnit::run($suite);
echo $result->toString();
-
-
diff --git a/legacy/application/models/tests/SchedulerExportTests.php b/legacy/application/models/tests/SchedulerExportTests.php
index d5acc4bae..5b680eac0 100644
--- a/legacy/application/models/tests/SchedulerExportTests.php
+++ b/legacy/application/models/tests/SchedulerExportTests.php
@@ -1,40 +1,46 @@
exec($sql);
+ // Clear the files table
+ $sql = 'DELETE FROM ' . $CC_CONFIG['filesTable'];
+ $con->exec($sql);
- // Add a file
- $values = array("filepath" => dirname(__FILE__)."/test10001.mp3");
- $this->storedFile = Application_Model_StoredFile::Insert($values, false);
+ // Add a file
+ $values = ['filepath' => dirname(__FILE__) . '/test10001.mp3'];
+ $this->storedFile = Application_Model_StoredFile::Insert($values, false);
- // Add a file
- $values = array("filepath" => dirname(__FILE__)."/test10002.mp3");
- $this->storedFile2 = Application_Model_StoredFile::Insert($values, false);
+ // Add a file
+ $values = ['filepath' => dirname(__FILE__) . '/test10002.mp3'];
+ $this->storedFile2 = Application_Model_StoredFile::Insert($values, false);
- // Clear the schedule table
- $sql = "DELETE FROM ".$CC_CONFIG["scheduleTable"];
- $con->exec($sql);
+ // Clear the schedule table
+ $sql = 'DELETE FROM ' . $CC_CONFIG['scheduleTable'];
+ $con->exec($sql);
- // Create a playlist
- $playlist = new Application_Model_Playlist();
- $playlist->create("Scheduler Unit Test");
- $result = $playlist->addAudioClip($this->storedFile->getId());
- $result = $playlist->addAudioClip($this->storedFile2->getId());
- $result = $playlist->addAudioClip($this->storedFile2->getId());
+ // Create a playlist
+ $playlist = new Application_Model_Playlist();
+ $playlist->create('Scheduler Unit Test');
+ $result = $playlist->addAudioClip($this->storedFile->getId());
+ $result = $playlist->addAudioClip($this->storedFile2->getId());
+ $result = $playlist->addAudioClip($this->storedFile2->getId());
- // Schedule it
- $i = new Application_Model_ScheduleGroup();
- $this->groupIdCreated = $i->add('2010-11-11 01:30:23', null, $playlist->getId());
- }
+ // Schedule it
+ $i = new Application_Model_ScheduleGroup();
+ $this->groupIdCreated = $i->add('2010-11-11 01:30:23', null, $playlist->getId());
+ }
- public function testExport() {
- echo Application_Model_Schedule::ExportRangeAsJson("2010-01-01 00:00:00", "2011-01-01 00:00:00");
- }
+ public function testExport()
+ {
+ echo Application_Model_Schedule::ExportRangeAsJson('2010-01-01 00:00:00', '2011-01-01 00:00:00');
+ }
}
-
diff --git a/legacy/application/models/tests/SchedulerTests.php b/legacy/application/models/tests/SchedulerTests.php
index dfafcb046..8359d3fce 100644
--- a/legacy/application/models/tests/SchedulerTests.php
+++ b/legacy/application/models/tests/SchedulerTests.php
@@ -1,60 +1,68 @@
dirname(__FILE__)."/test10001.mp3");
+ $values = ['filepath' => dirname(__FILE__) . '/test10001.mp3'];
$this->storedFile = Application_Model_StoredFile::Insert($values, false);
// Add a file
- $values = array("filepath" => dirname(__FILE__)."/test10002.mp3");
+ $values = ['filepath' => dirname(__FILE__) . '/test10002.mp3'];
$this->storedFile2 = Application_Model_StoredFile::Insert($values, false);
// Clear the schedule table
//$sql = "DELETE FROM ".$CC_CONFIG["scheduleTable"];
}
- function testDateToId() {
- $dateStr = "2006-04-02 10:20:08.123456";
+ public function testDateToId()
+ {
+ $dateStr = '2006-04-02 10:20:08.123456';
$id = Application_Model_ScheduleGroup::dateToId($dateStr);
- $expected = "20060402102008123";
+ $expected = '20060402102008123';
if ($id != $expected) {
- $this->fail("Did not convert date to ID correctly #1: $id != $expected");
+ $this->fail("Did not convert date to ID correctly #1: {$id} != {$expected}");
}
- $dateStr = "2006-04-02 10:20:08";
+ $dateStr = '2006-04-02 10:20:08';
$id = Application_Model_ScheduleGroup::dateToId($dateStr);
- $expected = "20060402102008000";
+ $expected = '20060402102008000';
if ($id != $expected) {
- $this->fail("Did not convert date to ID correctly #2: $id != $expected");
+ $this->fail("Did not convert date to ID correctly #2: {$id} != {$expected}");
}
}
- function testAddAndRemoveAudioFile() {
+ public function testAddAndRemoveAudioFile()
+ {
$i = new Application_Model_ScheduleGroup();
$this->groupIdCreated = $i->add('2010-10-10 01:30:23', $this->storedFile->getId());
$i = new Application_Model_ScheduleGroup($this->groupIdCreated);
$result = $i->remove();
if ($result != 1) {
- $this->fail("Did not remove item.");
+ $this->fail('Did not remove item.');
}
}
- function testAddAndRemovePlaylist() {
+ public function testAddAndRemovePlaylist()
+ {
// Create a playlist
$playlist = new Application_Model_Playlist();
- $playlist->create("Scheduler Unit Test ".uniqid());
+ $playlist->create('Scheduler Unit Test ' . uniqid());
$result = $playlist->addAudioClip($this->storedFile->getId());
$result = $playlist->addAudioClip($this->storedFile2->getId());
$result = $playlist->addAudioClip($this->storedFile2->getId());
@@ -63,54 +71,57 @@ class SchedulerTests extends PHPUnit_TestCase {
$this->groupIdCreated = $i->add('2010-11-11 01:30:23', null, $playlist->getId());
$group = new Application_Model_ScheduleGroup($this->groupIdCreated);
if ($group->count() != 3) {
- $this->fail("Wrong number of items added.");
+ $this->fail('Wrong number of items added.');
}
$items = $group->getItems();
- if (!is_array($items) || ($items[1]["starts"] != "2010-11-11 01:30:34.231")) {
- $this->fail("Wrong start time for 2nd item.");
+ if (!is_array($items) || ($items[1]['starts'] != '2010-11-11 01:30:34.231')) {
+ $this->fail('Wrong start time for 2nd item.');
}
$result = $group->remove();
if ($result != 1) {
- $this->fail("Did not remove item.");
+ $this->fail('Did not remove item.');
}
Application_Model_Playlist::Delete($playlist->getId());
}
- function testIsScheduleEmptyInRange() {
+ public function testIsScheduleEmptyInRange()
+ {
$i = new Application_Model_ScheduleGroup();
$this->groupIdCreated = $i->add('2011-10-10 01:30:23', $this->storedFile->getId());
if (Application_Model_Schedule::isScheduleEmptyInRange('2011-10-10 01:30:23', '00:00:12.555')) {
- $this->fail("Reporting empty schedule when it isnt.");
+ $this->fail('Reporting empty schedule when it isnt.');
+
return;
}
// echo "groupid: ".$this->groupIdCreated."\n";
$success = $i->remove();
if ($success === false) {
- $this->fail("Failed to delete schedule group.");
+ $this->fail('Failed to delete schedule group.');
+
return;
}
if (!Application_Model_Schedule::isScheduleEmptyInRange('2011-10-10 01:30:23', '00:00:12.555')) {
- $this->fail("Reporting booked schedule when it isnt.");
+ $this->fail('Reporting booked schedule when it isnt.');
+
return;
}
}
-/*
- function testGetItems() {
- $i1 = new Application_Model_ScheduleGroup();
- $groupId1 = $i1->add('2008-01-01 12:00:00.000', $this->storedFile->getId());
- $i2 = new Application_Model_ScheduleGroup();
- $i2->addAfter($groupId1, $this->storedFile->getId());
- $items = Application_Model_Schedule::getItems("2008-01-01", "2008-01-02");
- if (count($items) != 2) {
- $this->fail("Wrong number of items returned.");
- return;
+ /*
+ function testGetItems() {
+ $i1 = new Application_Model_ScheduleGroup();
+ $groupId1 = $i1->add('2008-01-01 12:00:00.000', $this->storedFile->getId());
+ $i2 = new Application_Model_ScheduleGroup();
+ $i2->addAfter($groupId1, $this->storedFile->getId());
+ $items = Application_Model_Schedule::getItems("2008-01-01", "2008-01-02");
+ if (count($items) != 2) {
+ $this->fail("Wrong number of items returned.");
+ return;
+ }
+ $i1->remove();
+ $i2->remove();
}
- $i1->remove();
- $i2->remove();
- }
-*/
+ */
}
-
diff --git a/legacy/application/models/tests/StoredFileTests.php b/legacy/application/models/tests/StoredFileTests.php
index d6ef61e85..65b7e2f02 100644
--- a/legacy/application/models/tests/StoredFileTests.php
+++ b/legacy/application/models/tests/StoredFileTests.php
@@ -1,48 +1,57 @@
fail("Metadata has unexpected values:\n".$str);
+ if (($metadata['dc:description'] != 'Tmu sem tam videla ...')
+ || ($metadata['audio']['dataformat'] != 'mp3')
+ || ($metadata['dc:type'] != 'Speech')) {
+ $str = ' [dc:description] = ' . $metadata['dc:description'] . "\n"
+ . ' [audio][dataformat] = ' . $metadata['audio']['dataformat'] . "\n"
+ . ' [dc:type] = ' . $metadata['dc:type'] . "\n";
+ $this->fail("Metadata has unexpected values:\n" . $str);
}
//var_dump($metadata);
//$this->assertTrue(FALSE);
}
- function testDeleteAndPutFile() {
- $STORAGE_SERVER_PATH = dirname(__FILE__)."/../../";
- $filePath = dirname(__FILE__)."/ex1.mp3";
+ public function testDeleteAndPutFile()
+ {
+ $STORAGE_SERVER_PATH = dirname(__FILE__) . '/../../';
+ $filePath = dirname(__FILE__) . '/ex1.mp3';
// Delete any old data from previous tests
$md5 = md5_file($filePath);
$duplicate = Application_Model_StoredFile::RecallByMd5($md5);
if ($duplicate) {
- $duplicate->delete();
+ $duplicate->delete();
}
// Test inserting a file by linking
- $values = array("filepath" => $filePath,
- "dc:description" => "Unit test ".time());
+ $values = ['filepath' => $filePath,
+ 'dc:description' => 'Unit test ' . time(), ];
$storedFile = Application_Model_StoredFile::Insert($values, false);
//var_dump($storedFile);
$id = $storedFile->getId();
if (!is_numeric($id)) {
- $this->fail("StoredFile not created correctly. id = ".$id);
+ $this->fail('StoredFile not created correctly. id = ' . $id);
+
return;
}
@@ -51,19 +60,19 @@ class StoredFileTest extends PHPUnit_TestCase {
$f->__setGunid($storedFile->getGunid());
$f->loadMetadata();
if (!is_array($md = $f->getMetadata())) {
- $this->fail("Unable to load metadata.");
- return;
+ $this->fail('Unable to load metadata.');
+
+ return;
}
//var_dump($md);
// Check if the length field has been set.
$f2 = Application_Model_StoredFile::RecallByGunid($storedFile->getGunid());
$m2 = $f2->getMetadata();
- if (!isset($m2["length"]) || $m2["length"] == "00:00:00.000000") {
- $this->fail("Length not reporting correctly in metadata.");
- return;
+ if (!isset($m2['length']) || $m2['length'] == '00:00:00.000000') {
+ $this->fail('Length not reporting correctly in metadata.');
+
+ return;
}
-
}
-
}
diff --git a/legacy/application/models/tests/index.php b/legacy/application/models/tests/index.php
index 4674d9c4c..89ea3b78c 100644
--- a/legacy/application/models/tests/index.php
+++ b/legacy/application/models/tests/index.php
@@ -1,3 +1,5 @@
exec($sql);
-$sql = "DELETE FROM cc_show_days";
+$sql = 'DELETE FROM cc_show_days';
$con->exec($sql);
-$sql = "DELETE FROM cc_show_instances";
+$sql = 'DELETE FROM cc_show_instances';
$con->exec($sql);
/*
@@ -44,66 +55,60 @@ echo "Created playlist ".$playlist->getName()." with ID ".$playlist->getId()."\n
*/
// Create the shows
-
-function createTestShow($showNumber, $showTime, $duration = "1:00")
+function createTestShow($showNumber, $showTime, $duration = '1:00')
{
- $data = array();
- $strTime = $showTime->format("Y-m-d H:i");
- echo "Adding show: $strTime\n";
- $data['add_show_name'] = 'automated show '.$showNumber;
- $data['add_show_start_date'] = $showTime->format("Y-m-d");
- $data['add_show_start_time'] = $showTime->format("H:i");
+ $data = [];
+ $strTime = $showTime->format('Y-m-d H:i');
+ echo "Adding show: {$strTime}\n";
+ $data['add_show_name'] = 'automated show ' . $showNumber;
+ $data['add_show_start_date'] = $showTime->format('Y-m-d');
+ $data['add_show_start_time'] = $showTime->format('H:i');
$data['add_show_duration'] = $duration;
$data['add_show_no_end'] = 0;
$data['add_show_repeats'] = 0;
$data['add_show_description'] = 'automated show';
$data['add_show_url'] = 'http://www.OfirGal.com';
- $data['add_show_color'] = "";
- $data['add_show_genre'] = "Ofir";
- $data['add_show_background_color'] = "";
+ $data['add_show_color'] = '';
+ $data['add_show_genre'] = 'Ofir';
+ $data['add_show_background_color'] = '';
$data['add_show_record'] = 0;
- $data['add_show_hosts'] ="";
+ $data['add_show_hosts'] = '';
$showId = Application_Model_Show::create($data);
//echo "show created, ID: $showId\n";
// populating the show with a playlist
$instances = Application_Model_Show::getShows($showTime, $showTime);
$instance = array_pop($instances);
- $show = new Application_Model_ShowInstance($instance["instance_id"]);
+ $show = new Application_Model_ShowInstance($instance['instance_id']);
//echo "Adding playlist to show instance ".$show->getShowInstanceId()."\n";
- $show->scheduleShow(array(1));
+ $show->scheduleShow([1]);
//echo "done\n";
//$show->scheduleShow(array($playlist->getId()));
}
$showTime = new DateTime();
-$resolution = "hour";
+$resolution = 'hour';
$showNumber = 1;
$numberOfDays = 180;
$numberOfHours = 0;
$endDate = new DateTime();
-$endDate->add(new DateInterval("P".$numberOfDays."DT".$numberOfHours."H"));
-echo "End date: ".$endDate->format("Y-m-d H:i")."\n";
+$endDate->add(new DateInterval('P' . $numberOfDays . 'DT' . $numberOfHours . 'H'));
+echo 'End date: ' . $endDate->format('Y-m-d H:i') . "\n";
while ($showTime < $endDate) {
- echo $showTime->format("Y-m-d H:i")." < " .$endDate->format("Y-m-d H:i")."\n";
- if ($resolution == "minute") {
- createTestShow($showNumber, $showTime, "0:01");
- $showTime->add(new DateInterval("PT1M"));
- } elseif ($resolution == "hour") {
+ echo $showTime->format('Y-m-d H:i') . ' < ' . $endDate->format('Y-m-d H:i') . "\n";
+ if ($resolution == 'minute') {
+ createTestShow($showNumber, $showTime, '0:01');
+ $showTime->add(new DateInterval('PT1M'));
+ } elseif ($resolution == 'hour') {
createTestShow($showNumber, $showTime);
- $showTime->add(new DateInterval("PT1H"));
+ $showTime->add(new DateInterval('PT1H'));
}
$showNumber = $showNumber + 1;
}
if (Application_Model_RabbitMq::$doPush) {
- $md = array('schedule' => Application_Model_Schedule::getSchedule());
- Application_Model_RabbitMq::SendMessageToPypo("update_schedule", $md);
+ $md = ['schedule' => Application_Model_Schedule::getSchedule()];
+ Application_Model_RabbitMq::SendMessageToPypo('update_schedule', $md);
}
-
-
-
-
-
diff --git a/legacy/application/modules/rest/Bootstrap.php b/legacy/application/modules/rest/Bootstrap.php
index 3ac5a1891..67a7dcc07 100644
--- a/legacy/application/modules/rest/Bootstrap.php
+++ b/legacy/application/modules/rest/Bootstrap.php
@@ -7,128 +7,129 @@ class Rest_Bootstrap extends Zend_Application_Module_Bootstrap
$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
- $restRoute = new Zend_Rest_Route($front, array(), array(
- 'rest'=> array('media', 'show-image', 'podcast', 'podcast-episodes')));
+ $restRoute = new Zend_Rest_Route($front, [], [
+ 'rest' => ['media', 'show-image', 'podcast', 'podcast-episodes'], ]);
$router->addRoute('rest', $restRoute);
$podcastBulkRoute = new Zend_Controller_Router_Route(
'rest/podcast/bulk',
- array(
+ [
'controller' => 'podcast',
'action' => 'bulk',
- 'module' => 'rest'
- )
+ 'module' => 'rest',
+ ]
);
$router->addRoute('podcast-bulk', $podcastBulkRoute);
-
$smartblockPodcastRoute = new Zend_Controller_Router_Route(
'rest/podcast/smartblock',
- array(
+ [
'controller' => 'podcast',
'action' => 'smartblock',
- 'module' => 'rest'
- )
+ 'module' => 'rest',
+ ]
);
$router->addRoute('podcast-smartblock', $smartblockPodcastRoute);
$stationPodcastRoute = new Zend_Controller_Router_Route(
'rest/podcast/station',
- array(
+ [
'controller' => 'podcast',
'action' => 'station',
- 'module' => 'rest'
- )
+ 'module' => 'rest',
+ ]
);
$router->addRoute('station-podcast', $stationPodcastRoute);
- $route = new Rest_RouteController($front,
+ $route = new Rest_RouteController(
+ $front,
'rest/podcast/:id/episodes',
- array(
+ [
'controller' => 'podcast-episodes',
- 'module' => 'rest'
- ),
- array(
- 'id' => '\d+'
- )
+ 'module' => 'rest',
+ ],
+ [
+ 'id' => '\d+',
+ ]
);
$router->addRoute('podcast-episodes-index', $route);
- $route = new Rest_RouteController($front,
+ $route = new Rest_RouteController(
+ $front,
'rest/podcast/:id/episodes/:episode_id',
- array(
+ [
'controller' => 'podcast-episodes',
- 'module' => 'rest'
- ),
- array(
+ 'module' => 'rest',
+ ],
+ [
'id' => '\d+',
- 'episode_id' => '\d+'
- )
+ 'episode_id' => '\d+',
+ ]
);
$router->addRoute('podcast-episodes', $route);
- /** MediaController Routes **/
+ /** MediaController Routes */
$downloadRoute = new Zend_Controller_Router_Route(
'rest/media/:id/download',
- array(
+ [
'controller' => 'media',
'action' => 'download',
- 'module' => 'rest'
- ),
- array(
- 'id' => '\d+'
- )
+ 'module' => 'rest',
+ ],
+ [
+ 'id' => '\d+',
+ ]
);
$router->addRoute('download', $downloadRoute);
$podcastEpisodeDownloadRoute = new Zend_Controller_Router_Route_Regex(
'rest/media/(?\d+)/download/(?.+)\.(?\w+)',
- array(
+ [
'controller' => 'media',
'action' => 'download',
- 'module' => 'rest'
- ),
- array(
- 1 => "id",
- 2 => "download_key",
- 3 => "file_ext"
- )
+ 'module' => 'rest',
+ ],
+ [
+ 1 => 'id',
+ 2 => 'download_key',
+ 3 => 'file_ext',
+ ]
);
$router->addRoute('podcast-episode-download', $podcastEpisodeDownloadRoute);
$clearLibraryRoute = new Zend_Controller_Router_Route(
'rest/media/clear',
- array(
+ [
'controller' => 'media',
'action' => 'clear',
- 'module' => 'rest'
- )
+ 'module' => 'rest',
+ ]
);
$router->addRoute('clear', $clearLibraryRoute);
$publishRoute = new Zend_Controller_Router_Route(
'rest/media/:id/publish',
- array(
+ [
'controller' => 'media',
'action' => 'publish',
- 'module' => 'rest'
- ),
- array(
- 'id' => '\d+'
- )
+ 'module' => 'rest',
+ ],
+ [
+ 'id' => '\d+',
+ ]
);
$router->addRoute('publish', $publishRoute);
$publishSourcesRoute = new Zend_Controller_Router_Route(
'rest/media/:id/publish-sources',
- array(
+ [
'controller' => 'media',
'action' => 'publish-sources',
- 'module' => 'rest'
- ),
- array(
- 'id' => '\d+'
- )
+ 'module' => 'rest',
+ ],
+ [
+ 'id' => '\d+',
+ ]
);
$router->addRoute('publish-sources', $publishSourcesRoute);
}
diff --git a/legacy/application/modules/rest/controllers/MediaController.php b/legacy/application/modules/rest/controllers/MediaController.php
index 674e869ea..b4dea2304 100644
--- a/legacy/application/modules/rest/controllers/MediaController.php
+++ b/legacy/application/modules/rest/controllers/MediaController.php
@@ -11,15 +11,13 @@ class Rest_MediaController extends Zend_Rest_Controller
}
/**
- * headAction is needed as it is defined as an abstract function in the base controller
- *
- * @return void
+ * headAction is needed as it is defined as an abstract function in the base controller.
*/
public function headAction()
{
- Logging::info("HEAD action received");
+ Logging::info('HEAD action received');
}
-
+
public function indexAction()
{
$totalFileCount = CcFilesQuery::create()->count();
@@ -39,29 +37,29 @@ class Rest_MediaController extends Zend_Rest_Controller
->filterByDbImportStatus(0)
->setLimit($limit)
->setOffset($offset)
- ->orderBy($sortColumn, $sortDir);
- //->orderByDbId();
-
+ ->orderBy($sortColumn, $sortDir)
+ ;
+ //->orderByDbId();
$queryCount = $query->count();
$queryResult = $query->find();
- $files_array = array();
- foreach ($queryResult as $file)
- {
+ $files_array = [];
+ foreach ($queryResult as $file) {
array_push($files_array, CcFiles::sanitizeResponse($file));
}
$this->getResponse()
->setHttpResponseCode(200)
->setHeader('X-TOTAL-COUNT', $totalFileCount)
- ->appendBody(json_encode($files_array));
-
- /** TODO: Use this simpler code instead after we upgrade to Propel 1.7 (Airtime 2.6.x branch):
- $this->getResponse()
- ->setHttpResponseCode(200)
- ->appendBody(json_encode(CcFilesQuery::create()->find()->toArray(BasePeer::TYPE_FIELDNAME)));
- */
+ ->appendBody(json_encode($files_array))
+ ;
+
+ /* TODO: Use this simpler code instead after we upgrade to Propel 1.7 (Airtime 2.6.x branch):
+ * $this->getResponse()
+ * ->setHttpResponseCode(200)
+ * ->appendBody(json_encode(CcFilesQuery::create()->find()->toArray(BasePeer::TYPE_FIELDNAME)));
+ */
}
public function downloadAction()
@@ -73,28 +71,30 @@ class Rest_MediaController extends Zend_Rest_Controller
// In case the download fails
$counterIncremented = false;
+
try {
$this->getResponse()
- ->setHttpResponseCode(200);
+ ->setHttpResponseCode(200)
+ ;
$inline = false;
// SAAS-1081 - download counter for station podcast downloads
- if ($key = $this->getRequest()->getParam("download_key", false)) {
+ if ($key = $this->getRequest()->getParam('download_key', false)) {
Application_Model_Preference::incrementStationPodcastDownloadCounter();
$counterIncremented = true;
}
Application_Service_MediaService::streamFileDownload($id, $inline);
- }
- catch (LibreTimeFileNotFoundException $e) {
+ } catch (LibreTimeFileNotFoundException $e) {
$this->fileNotFoundResponse();
Logging::error($e->getMessage());
- }
- catch (Exception $e) {
- if ($counterIncremented) Application_Model_Preference::decrementStationPodcastDownloadCounter();
+ } catch (Exception $e) {
+ if ($counterIncremented) {
+ Application_Model_Preference::decrementStationPodcastDownloadCounter();
+ }
$this->unknownErrorResponse();
Logging::error($e->getMessage());
}
}
-
+
public function getAction()
{
$id = $this->getId();
@@ -105,18 +105,17 @@ class Rest_MediaController extends Zend_Rest_Controller
try {
$this->getResponse()
->setHttpResponseCode(200)
- ->appendBody(json_encode(CcFiles::getSanitizedFileById($id)));
- }
- catch (LibreTimeFileNotFoundException $e) {
+ ->appendBody(json_encode(CcFiles::getSanitizedFileById($id)))
+ ;
+ } catch (LibreTimeFileNotFoundException $e) {
$this->fileNotFoundResponse();
Logging::error($e->getMessage());
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->unknownErrorResponse();
Logging::error($e->getMessage());
}
}
-
+
public function postAction()
{
//If we do get an ID on a POST, then that doesn't make any sense
@@ -124,7 +123,8 @@ class Rest_MediaController extends Zend_Rest_Controller
if ($id = $this->_getParam('id', false)) {
$resp = $this->getResponse();
$resp->setHttpResponseCode(400);
- $resp->appendBody("ERROR: ID should not be specified when using POST. POST is only used for file creation, and an ID will be chosen by Airtime");
+ $resp->appendBody('ERROR: ID should not be specified when using POST. POST is only used for file creation, and an ID will be chosen by Airtime');
+
return;
}
@@ -135,7 +135,7 @@ class Rest_MediaController extends Zend_Rest_Controller
// this error should not really get hit, letting the user know if it does is nice for debugging
// see: https://github.com/LibreTime/libretime/issues/3#issuecomment-281143417
if (!$upload->isValid('file')) {
- throw new Exception("invalid file uploaded");
+ throw new Exception('invalid file uploaded');
}
$fileInfo = $upload->getFileInfo('file');
// this should have more info on any actual faults detected by php
@@ -145,18 +145,17 @@ class Rest_MediaController extends Zend_Rest_Controller
$sanitizedFile = CcFiles::createFromUpload($fileInfo);
$this->getResponse()
->setHttpResponseCode(201)
- ->appendBody(json_encode($sanitizedFile));
- }
- catch (InvalidMetadataException $e) {
+ ->appendBody(json_encode($sanitizedFile))
+ ;
+ } catch (InvalidMetadataException $e) {
$this->invalidDataResponse();
Logging::error($e->getMessage());
- }
- catch (OverDiskQuotaException $e) {
+ } catch (OverDiskQuotaException $e) {
$this->getResponse()
->setHttpResponseCode(400)
- ->appendBody("ERROR: Disk Quota reached.");
- }
- catch (Exception $e) {
+ ->appendBody('ERROR: Disk Quota reached.')
+ ;
+ } catch (Exception $e) {
$this->serviceUnavailableResponse();
Logging::error($e->getMessage() . "\n" . $e->getTraceAsString());
}
@@ -175,17 +174,15 @@ class Rest_MediaController extends Zend_Rest_Controller
$this->getResponse()
->setHttpResponseCode(201)
- ->appendBody(json_encode($sanitizedFile));
- }
- catch (InvalidMetadataException $e) {
+ ->appendBody(json_encode($sanitizedFile))
+ ;
+ } catch (InvalidMetadataException $e) {
$this->invalidDataResponse();
Logging::error($e->getMessage());
- }
- catch (LibreTimeFileNotFoundException $e) {
+ } catch (LibreTimeFileNotFoundException $e) {
$this->fileNotFoundResponse();
Logging::error($e->getMessage());
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->unknownErrorResponse();
Logging::error($e->getMessage());
}
@@ -197,45 +194,49 @@ class Rest_MediaController extends Zend_Rest_Controller
if (!$id) {
return;
}
+
try {
CcFiles::deleteById($id);
$this->getResponse()
- ->setHttpResponseCode(204);
- }
- catch (LibreTimeFileNotFoundException $e) {
+ ->setHttpResponseCode(204)
+ ;
+ } catch (LibreTimeFileNotFoundException $e) {
$this->fileNotFoundResponse();
Logging::error($e->getMessage());
- }
- catch (Exception $e) {
- $this->unknownErrorResponse();
- Logging::error($e->getMessage());
- }
- }
-
- /**
- * Publish endpoint for individual media items
- */
- public function publishAction() {
- $id = $this->getId();
- try {
- // Is there a better way to do this?
- $data = json_decode($this->getRequest()->getRawBody(), true)["sources"];
- Application_Service_PublishService::publish($id, $data);
- $this->getResponse()
- ->setHttpResponseCode(200);
} catch (Exception $e) {
$this->unknownErrorResponse();
Logging::error($e->getMessage());
}
}
- public function publishSourcesAction() {
+ /**
+ * Publish endpoint for individual media items.
+ */
+ public function publishAction()
+ {
+ $id = $this->getId();
+
+ try {
+ // Is there a better way to do this?
+ $data = json_decode($this->getRequest()->getRawBody(), true)['sources'];
+ Application_Service_PublishService::publish($id, $data);
+ $this->getResponse()
+ ->setHttpResponseCode(200)
+ ;
+ } catch (Exception $e) {
+ $this->unknownErrorResponse();
+ Logging::error($e->getMessage());
+ }
+ }
+
+ public function publishSourcesAction()
+ {
$id = $this->_getParam('id', false);
$sources = Application_Service_PublishService::getSourceLists($id);
$this->getResponse()
->setHttpResponseCode(200)
- ->appendBody(json_encode($sources));
-
+ ->appendBody(json_encode($sources))
+ ;
}
private function getId()
@@ -243,9 +244,11 @@ class Rest_MediaController extends Zend_Rest_Controller
if (!$id = $this->_getParam('id', false)) {
$resp = $this->getResponse();
$resp->setHttpResponseCode(400);
- $resp->appendBody("ERROR: No file ID specified.");
+ $resp->appendBody('ERROR: No file ID specified.');
+
return false;
- }
+ }
+
return $id;
}
@@ -253,28 +256,27 @@ class Rest_MediaController extends Zend_Rest_Controller
{
$resp = $this->getResponse();
$resp->setHttpResponseCode(404);
- $resp->appendBody("ERROR: Media not found.");
+ $resp->appendBody('ERROR: Media not found.');
}
-
+
private function importFailedResponse()
{
$resp = $this->getResponse();
$resp->setHttpResponseCode(200);
- $resp->appendBody("ERROR: Import Failed.");
+ $resp->appendBody('ERROR: Import Failed.');
}
private function unknownErrorResponse()
{
$resp = $this->getResponse();
$resp->setHttpResponseCode(400);
- $resp->appendBody("An unknown error occurred.");
+ $resp->appendBody('An unknown error occurred.');
}
private function serviceUnavailableResponse()
{
$resp = $this->getResponse();
$resp->setHttpResponseCode(400);
- $resp->appendBody("An error occurred while processing your upload. Please try again in a few minutes.");
+ $resp->appendBody('An error occurred while processing your upload. Please try again in a few minutes.');
}
}
-
diff --git a/legacy/application/modules/rest/controllers/PodcastController.php b/legacy/application/modules/rest/controllers/PodcastController.php
index 3797a51f1..a7cd314bd 100644
--- a/legacy/application/modules/rest/controllers/PodcastController.php
+++ b/legacy/application/modules/rest/controllers/PodcastController.php
@@ -2,7 +2,6 @@
class Rest_PodcastController extends Zend_Rest_Controller
{
-
public function init()
{
$this->view->layout()->disableLayout();
@@ -13,13 +12,11 @@ class Rest_PodcastController extends Zend_Rest_Controller
}
/**
- * headAction is needed as it is defined as an abstract function in the base controller
- *
- * @return void
+ * headAction is needed as it is defined as an abstract function in the base controller.
*/
public function headAction()
{
- Logging::info("HEAD action received");
+ Logging::info('HEAD action received');
}
public function indexAction()
@@ -38,20 +35,24 @@ class Rest_PodcastController extends Zend_Rest_Controller
// Don't return the Station podcast - we fetch it separately
->filterByDbId($stationPodcastId, Criteria::NOT_EQUAL)
->leftJoinImportedPodcast()
- ->withColumn('auto_ingest_timestamp');
+ ->withColumn('auto_ingest_timestamp')
+ ;
$total = $result->count();
- if ($limit > 0) { $result->setLimit($limit); }
+ if ($limit > 0) {
+ $result->setLimit($limit);
+ }
$result->setOffset($offset)
- ->orderBy($sortColumn, $sortDir);
+ ->orderBy($sortColumn, $sortDir)
+ ;
$result = $result->find();
$podcastArray = $result->toArray(null, false, BasePeer::TYPE_FIELDNAME);
-
$this->getResponse()
->setHttpResponseCode(200)
->setHeader('X-TOTAL-COUNT', $total)
- ->appendBody(json_encode($podcastArray));
+ ->appendBody(json_encode($podcastArray))
+ ;
}
public function getAction()
@@ -64,12 +65,12 @@ class Rest_PodcastController extends Zend_Rest_Controller
try {
$this->getResponse()
->setHttpResponseCode(200)
- ->appendBody(json_encode(Application_Service_PodcastService::getPodcastById($id)));
+ ->appendBody(json_encode(Application_Service_PodcastService::getPodcastById($id)))
+ ;
} catch (PodcastNotFoundException $e) {
$this->podcastNotFoundResponse();
Logging::error($e->getMessage());
} catch (Exception $e) {
-
}
}
@@ -80,28 +81,28 @@ class Rest_PodcastController extends Zend_Rest_Controller
if ($id = $this->_getParam('id', false)) {
$resp = $this->getResponse();
$resp->setHttpResponseCode(400);
- $resp->appendBody("ERROR: ID should not be specified when using POST. POST is only used for podcast creation, and an ID will be chosen by Airtime");
+ $resp->appendBody('ERROR: ID should not be specified when using POST. POST is only used for podcast creation, and an ID will be chosen by Airtime');
+
return;
}
try {
$requestData = $this->getRequest()->getPost();
- $podcast = Application_Service_PodcastService::createFromFeedUrl($requestData["url"]);
+ $podcast = Application_Service_PodcastService::createFromFeedUrl($requestData['url']);
$path = 'podcast/podcast.phtml';
$this->view->podcast = $podcast;
- $this->_helper->json->sendJson(array(
- "podcast"=>json_encode($podcast),
- "html"=>$this->view->render($path),
- ));
- }
- catch (InvalidPodcastException $e) {
+ $this->_helper->json->sendJson([
+ 'podcast' => json_encode($podcast),
+ 'html' => $this->view->render($path),
+ ]);
+ } catch (InvalidPodcastException $e) {
$this->getResponse()
->setHttpResponseCode(400)
- ->appendBody("Invalid podcast!");
- }
- catch (Exception $e) {
+ ->appendBody('Invalid podcast!')
+ ;
+ } catch (Exception $e) {
Logging::error($e->getMessage());
$this->unknownErrorResponse();
}
@@ -120,13 +121,12 @@ class Rest_PodcastController extends Zend_Rest_Controller
$this->getResponse()
->setHttpResponseCode(201)
- ->appendBody(json_encode($podcast));
- }
- catch (PodcastNotFoundException $e) {
+ ->appendBody(json_encode($podcast))
+ ;
+ } catch (PodcastNotFoundException $e) {
$this->podcastNotFoundResponse();
Logging::error($e->getMessage());
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->unknownErrorResponse();
Logging::error($e->getMessage());
}
@@ -142,26 +142,28 @@ class Rest_PodcastController extends Zend_Rest_Controller
try {
Application_Service_PodcastService::deletePodcastById($id);
$this->getResponse()
- ->setHttpResponseCode(204);
- }
- catch (PodcastNotFoundException $e) {
+ ->setHttpResponseCode(204)
+ ;
+ } catch (PodcastNotFoundException $e) {
$this->podcastNotFoundResponse();
Logging::error($e->getMessage());
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->unknownErrorResponse();
Logging::error($e->getMessage());
}
}
/**
- * Endpoint for performing bulk actions (deleting multiple podcasts, opening multiple editors)
+ * Endpoint for performing bulk actions (deleting multiple podcasts, opening multiple editors).
*/
- public function bulkAction() {
+ public function bulkAction()
+ {
if ($this->_request->getMethod() != HttpRequestType::POST) {
$this->getResponse()
->setHttpResponseCode(405)
- ->appendBody("ERROR: Method not accepted");
+ ->appendBody('ERROR: Method not accepted')
+ ;
+
return;
}
@@ -170,33 +172,34 @@ class Rest_PodcastController extends Zend_Rest_Controller
$responseBody = [];
// XXX: Should this be a map of HttpRequestType => function call instead? Would be a bit cleaner
- switch($method) {
+ switch ($method) {
case HttpRequestType::DELETE:
- foreach($ids as $id) {
+ foreach ($ids as $id) {
Application_Service_PodcastService::deletePodcastById($id);
}
+
break;
+
case HttpRequestType::GET:
$path = 'podcast/podcast.phtml';
- foreach($ids as $id) {
- $responseBody[] = array(
- "podcast" => json_encode(Application_Service_PodcastService::getPodcastById($id)),
- "html" => $this->view->render($path)
- );
+ foreach ($ids as $id) {
+ $responseBody[] = [
+ 'podcast' => json_encode(Application_Service_PodcastService::getPodcastById($id)),
+ 'html' => $this->view->render($path),
+ ];
}
+
break;
}
$this->_helper->json->sendJson($responseBody);
}
-
/**
- * Endpoint for triggering the generation of a smartblock and playlist to match the podcast name
+ * Endpoint for triggering the generation of a smartblock and playlist to match the podcast name.
*/
-
- public function smartblockAction() {
-
+ public function smartblockAction()
+ {
$title = $this->_getParam('title', []);
$id = $this->_getParam('id', []);
if (!$id) {
@@ -208,22 +211,21 @@ class Rest_PodcastController extends Zend_Rest_Controller
Application_Service_PodcastService::createPodcastSmartblockAndPlaylist($podcast, $title);
}
-
-
/**
* @throws PodcastNotFoundException
*
* @deprecated
*/
- public function stationAction() {
+ public function stationAction()
+ {
$stationPodcastId = Application_Model_Preference::getStationPodcastId();
$podcast = Application_Service_PodcastService::getPodcastById($stationPodcastId);
$path = 'podcast/station.phtml';
$this->view->podcast = $podcast;
- $this->_helper->json->sendJson(array(
- "podcast" => json_encode($podcast),
- "html" => $this->view->render($path)
- ));
+ $this->_helper->json->sendJson([
+ 'podcast' => json_encode($podcast),
+ 'html' => $this->view->render($path),
+ ]);
}
private function getId()
@@ -231,9 +233,11 @@ class Rest_PodcastController extends Zend_Rest_Controller
if (!$id = $this->_getParam('id', false)) {
$resp = $this->getResponse();
$resp->setHttpResponseCode(400);
- $resp->appendBody("ERROR: No podcast ID specified.");
+ $resp->appendBody('ERROR: No podcast ID specified.');
+
return false;
}
+
return $id;
}
@@ -241,14 +245,13 @@ class Rest_PodcastController extends Zend_Rest_Controller
{
$resp = $this->getResponse();
$resp->setHttpResponseCode(500);
- $resp->appendBody("An unknown error occurred.");
+ $resp->appendBody('An unknown error occurred.');
}
private function podcastNotFoundResponse()
{
$resp = $this->getResponse();
$resp->setHttpResponseCode(404);
- $resp->appendBody("ERROR: Podcast not found.");
+ $resp->appendBody('ERROR: Podcast not found.');
}
-
}
diff --git a/legacy/application/modules/rest/controllers/PodcastEpisodesController.php b/legacy/application/modules/rest/controllers/PodcastEpisodesController.php
index 1bf85fafc..af4a33d57 100644
--- a/legacy/application/modules/rest/controllers/PodcastEpisodesController.php
+++ b/legacy/application/modules/rest/controllers/PodcastEpisodesController.php
@@ -2,7 +2,6 @@
class Rest_PodcastEpisodesController extends Zend_Rest_Controller
{
-
/**
* @var Application_Service_PodcastEpisodeService
*/
@@ -18,13 +17,11 @@ class Rest_PodcastEpisodesController extends Zend_Rest_Controller
}
/**
- * headAction is needed as it is defined as an abstract function in the base controller
- *
- * @return void
+ * headAction is needed as it is defined as an abstract function in the base controller.
*/
public function headAction()
{
- Logging::info("HEAD action received");
+ Logging::info('HEAD action received');
}
public function indexAction()
@@ -34,10 +31,12 @@ class Rest_PodcastEpisodesController extends Zend_Rest_Controller
if (!$id) {
return;
}
+
try {
$totalPodcastEpisodesCount = PodcastEpisodesQuery::create()
->filterByDbPodcastId($id)
- ->count();
+ ->count()
+ ;
// Check if offset and limit were sent with request.
// Default limit to zero and offset to $totalFileCount
@@ -51,8 +50,8 @@ class Rest_PodcastEpisodesController extends Zend_Rest_Controller
$this->getResponse()
->setHttpResponseCode(201)
->setHeader('X-TOTAL-COUNT', $totalPodcastEpisodesCount)
- ->appendBody(json_encode($this->_service->getPodcastEpisodes($id, $offset, $limit, $sortColumn, $sortDir)));
-
+ ->appendBody(json_encode($this->_service->getPodcastEpisodes($id, $offset, $limit, $sortColumn, $sortDir)))
+ ;
} catch (PodcastNotFoundException $e) {
$this->podcastNotFoundResponse();
Logging::error($e->getMessage());
@@ -78,8 +77,8 @@ class Rest_PodcastEpisodesController extends Zend_Rest_Controller
try {
$this->getResponse()
->setHttpResponseCode(201)
- ->appendBody(json_encode($this->_service->getPodcastEpisodeById($episodeId)));
-
+ ->appendBody(json_encode($this->_service->getPodcastEpisodeById($episodeId)))
+ ;
} catch (PodcastNotFoundException $e) {
$this->podcastNotFoundResponse();
Logging::error($e->getMessage());
@@ -99,8 +98,9 @@ class Rest_PodcastEpisodesController extends Zend_Rest_Controller
if ($episodeId = $this->_getParam('episode_id', false)) {
$resp = $this->getResponse();
$resp->setHttpResponseCode(400);
- $resp->appendBody("ERROR: Episode ID should not be specified when using POST. POST is only used for "
- . "importing podcast episodes, and an episode ID will be chosen by Airtime");
+ $resp->appendBody('ERROR: Episode ID should not be specified when using POST. POST is only used for '
+ . 'importing podcast episodes, and an episode ID will be chosen by Airtime');
+
return;
}
@@ -112,16 +112,15 @@ class Rest_PodcastEpisodesController extends Zend_Rest_Controller
try {
$requestData = json_decode($this->getRequest()->getRawBody(), true);
- $episode = $this->_service->importEpisode($id, $requestData["episode"]);
+ $episode = $this->_service->importEpisode($id, $requestData['episode']);
$this->getResponse()
->setHttpResponseCode(201)
- ->appendBody(json_encode($episode));
-
+ ->appendBody(json_encode($episode))
+ ;
} catch (Exception $e) {
$this->unknownErrorResponse();
Logging::error($e->getMessage());
}
-
}
public function deleteAction()
@@ -139,7 +138,8 @@ class Rest_PodcastEpisodesController extends Zend_Rest_Controller
try {
$this->_service->deletePodcastEpisodeById($episodeId);
$this->getResponse()
- ->setHttpResponseCode(204);
+ ->setHttpResponseCode(204)
+ ;
} catch (PodcastEpisodeNotFoundException $e) {
$this->podcastEpisodeNotFoundResponse();
Logging::error($e->getMessage());
@@ -151,7 +151,6 @@ class Rest_PodcastEpisodesController extends Zend_Rest_Controller
public function putAction()
{
-
}
private function getId()
@@ -159,9 +158,11 @@ class Rest_PodcastEpisodesController extends Zend_Rest_Controller
if (!$id = $this->_getParam('id', false)) {
$resp = $this->getResponse();
$resp->setHttpResponseCode(400);
- $resp->appendBody("ERROR: No podcast ID specified.");
+ $resp->appendBody('ERROR: No podcast ID specified.');
+
return false;
}
+
return $id;
}
@@ -170,9 +171,11 @@ class Rest_PodcastEpisodesController extends Zend_Rest_Controller
if (!$episodeId = $this->_getParam('episode_id', false)) {
$resp = $this->getResponse();
$resp->setHttpResponseCode(400);
- $resp->appendBody("ERROR: No podcast episode ID specified.");
+ $resp->appendBody('ERROR: No podcast episode ID specified.');
+
return false;
}
+
return $episodeId;
}
@@ -180,21 +183,20 @@ class Rest_PodcastEpisodesController extends Zend_Rest_Controller
{
$resp = $this->getResponse();
$resp->setHttpResponseCode(400);
- $resp->appendBody("An unknown error occurred.");
+ $resp->appendBody('An unknown error occurred.');
}
private function podcastNotFoundResponse()
{
$resp = $this->getResponse();
$resp->setHttpResponseCode(404);
- $resp->appendBody("ERROR: Podcast not found.");
+ $resp->appendBody('ERROR: Podcast not found.');
}
private function podcastEpisodeNotFoundResponse()
{
$resp = $this->getResponse();
$resp->setHttpResponseCode(404);
- $resp->appendBody("ERROR: Podcast episode not found.");
+ $resp->appendBody('ERROR: Podcast episode not found.');
}
-
}
diff --git a/legacy/application/modules/rest/controllers/RouteController.php b/legacy/application/modules/rest/controllers/RouteController.php
index ba3bddff9..0340af0c2 100644
--- a/legacy/application/modules/rest/controllers/RouteController.php
+++ b/legacy/application/modules/rest/controllers/RouteController.php
@@ -1,64 +1,60 @@
_front = $front;
+ $this->_front = $front;
$this->_dispatcher = $front->getDispatcher();
parent::__construct($route, $defaults, $reqs, $translator, $locale);
}
-
-
/**
* Matches a user submitted path with parts defined by a map. Assigns and
* returns an array of variables on a successful match.
*
- * @param string $path Path used to match against this routing map
+ * @param string $path Path used to match against this routing map
+ * @param mixed $partial
+ *
* @return array|false An array of assigned values or a false on a mismatch
*/
public function match($path, $partial = false)
{
-
-
$return = parent::match($path, $partial);
// add the RESTful action mapping
if ($return) {
$request = $this->_front->getRequest();
- $path = $request->getPathInfo();
+ $path = $request->getPathInfo();
$params = $request->getParams();
- $path = trim($path, self::URI_DELIMITER);
+ $path = trim($path, self::URI_DELIMITER);
if ($path != '') {
$path = explode(self::URI_DELIMITER, $path);
@@ -72,7 +68,7 @@ class Rest_RouteController extends Zend_Controller_Router_Route
if ($requestMethod != 'get') {
if ($request->getParam('_method')) {
$return[$this->_actionKey] = strtolower($request->getParam('_method'));
- } elseif ( $request->getHeader('X-HTTP-Method-Override') ) {
+ } elseif ($request->getHeader('X-HTTP-Method-Override')) {
$return[$this->_actionKey] = strtolower($request->getHeader('X-HTTP-Method-Override'));
} else {
$return[$this->_actionKey] = $requestMethod;
@@ -80,15 +76,17 @@ class Rest_RouteController extends Zend_Controller_Router_Route
// Map PUT and POST to actual create/update actions
// based on parameter count (posting to resource or collection)
- switch( $return[$this->_actionKey] ){
+ switch ($return[$this->_actionKey]) {
case 'post':
$return[$this->_actionKey] = 'post';
+
break;
+
case 'put':
$return[$this->_actionKey] = 'put';
+
break;
}
-
} else {
// if the last argument in the path is a numeric value, consider this request a GET of an item
$lastParam = array_pop($path);
@@ -98,11 +96,8 @@ class Rest_RouteController extends Zend_Controller_Router_Route
$return[$this->_actionKey] = 'index';
}
}
-
}
return $return;
-
}
-
-}
\ No newline at end of file
+}
diff --git a/legacy/application/modules/rest/controllers/ShowImageController.php b/legacy/application/modules/rest/controllers/ShowImageController.php
index 0e524924f..e7b057ae3 100644
--- a/legacy/application/modules/rest/controllers/ShowImageController.php
+++ b/legacy/application/modules/rest/controllers/ShowImageController.php
@@ -7,14 +7,16 @@
* 18/09/2014 : v1.1 Changed auth references to static calls
* 06/02/2015 : v1.2 Changed endpoints to be more RESTful, changed classname to
* better reflect functionality
- * 09/02/2015 : v1.2.1 Added more comments
+ * 09/02/2015 : v1.2.1 Added more comments.
+ *
* @author sourcefabric
+ *
* @version 1.2.1
*/
-
-class Rest_ShowImageController extends Zend_Rest_Controller {
-
- public function init() {
+class Rest_ShowImageController extends Zend_Rest_Controller
+{
+ public function init()
+ {
// Remove layout dependencies
$this->view->layout()->disableLayout();
// Remove reliance on .phtml files to render requests
@@ -22,53 +24,59 @@ class Rest_ShowImageController extends Zend_Rest_Controller {
}
/**
- * headAction is needed as it is defined as an abstract function in the base controller
- *
- * @return void
+ * headAction is needed as it is defined as an abstract function in the base controller.
*/
public function headAction()
{
- Logging::info("HEAD action received");
+ Logging::info('HEAD action received');
}
- public function indexAction() {
- Logging::info("INDEX action received");
+ public function indexAction()
+ {
+ Logging::info('INDEX action received');
}
- public function getAction() {
- Logging::info("GET action received");
+ public function getAction()
+ {
+ Logging::info('GET action received');
}
- public function putAction() {
- Logging::info("PUT action received");
+ public function putAction()
+ {
+ Logging::info('PUT action received');
}
/**
- * RESTful POST endpoint; used when uploading show images
+ * RESTful POST endpoint; used when uploading show images.
*/
- public function postAction() {
-
+ public function postAction()
+ {
$showId = $this->getShowId();
if (!$showId) {
$this->getResponse()
->setHttpResponseCode(400)
- ->appendBody("No show ID provided");
+ ->appendBody('No show ID provided')
+ ;
+
return;
}
try {
- $path = $this->processUploadedImage($showId, $_FILES["file"]["tmp_name"]);
+ $path = $this->processUploadedImage($showId, $_FILES['file']['tmp_name']);
} catch (Exception $e) {
$this->getResponse()
->setHttpResponseCode(500)
- ->appendBody("Error processing image: " . $e->getMessage());
+ ->appendBody('Error processing image: ' . $e->getMessage())
+ ;
+
return;
}
$show = CcShowQuery::create()->findPk($showId);
$con = Propel::getConnection();
+
try {
$con->beginTransaction();
@@ -80,24 +88,28 @@ class Rest_ShowImageController extends Zend_Rest_Controller {
$con->rollBack();
$this->getResponse()
->setHttpResponseCode(500)
- ->appendBody("Couldn't add show image: " . $e->getMessage());
+ ->appendBody("Couldn't add show image: " . $e->getMessage())
+ ;
}
$this->getResponse()
- ->setHttpResponseCode(201);
+ ->setHttpResponseCode(201)
+ ;
}
/**
- * RESTful DELETE endpoint; used when deleting show images
+ * RESTful DELETE endpoint; used when deleting show images.
*/
- public function deleteAction() {
-
+ public function deleteAction()
+ {
$showId = $this->getShowId();
if (!$showId) {
$this->getResponse()
->setHttpResponseCode(400)
- ->appendBody("No show ID provided");
+ ->appendBody('No show ID provided')
+ ;
+
return;
}
@@ -106,12 +118,14 @@ class Rest_ShowImageController extends Zend_Rest_Controller {
} catch (Exception $e) {
$this->getResponse()
->setHttpResponseCode(500)
- ->appendBody("Error processing image: " . $e->getMessage());
+ ->appendBody('Error processing image: ' . $e->getMessage())
+ ;
}
$show = CcShowQuery::create()->findPk($showId);
$con = Propel::getConnection();
+
try {
$con->beginTransaction();
@@ -123,114 +137,125 @@ class Rest_ShowImageController extends Zend_Rest_Controller {
$con->rollBack();
$this->getResponse()
->setHttpResponseCode(500)
- ->appendBody("Couldn't remove show image: " . $e->getMessage());
+ ->appendBody("Couldn't remove show image: " . $e->getMessage())
+ ;
}
$this->getResponse()
- ->setHttpResponseCode(201);
+ ->setHttpResponseCode(201)
+ ;
}
/**
* Verify and process an uploaded image file, copying it into
* .../stor/imported/:owner-id/show-images/:show-id/ to differentiate between
- * individual users and shows
+ * individual users and shows.
*
* @param int $showId the ID of the show we're adding the image to
* @param string $tempFilePath temporary filepath assigned to the upload generally of the form /tmp/:tmp_name
*
* @throws Exception
- * - when a file with an unsupported file extension is uploaded or an
- * error occurs in copyFileToStor
+ * - when a file with an unsupported file extension is uploaded or an
+ * error occurs in copyFileToStor
+ *
* @return string the path to the new location for the file
*/
- private function processUploadedImage($showId, $tempFilePath) {
+ private function processUploadedImage($showId, $tempFilePath)
+ {
$ownerId = RestAuth::getOwnerId();
//Only accept files with a file extension that we support.
$fileExtension = $this->getFileExtension($tempFilePath);
- if (!in_array(strtolower($fileExtension), explode(",", "jpg,png,gif,jpeg"))) {
+ if (!in_array(strtolower($fileExtension), explode(',', 'jpg,png,gif,jpeg'))) {
@unlink($tempFilePath);
- throw new Exception("Bad file extension.");
+
+ throw new Exception('Bad file extension.');
}
$storDir = Application_Model_MusicDir::getStorDir();
- $importedStorageDirectory = $storDir->getDirectory() . "imported/" . $ownerId . "/show-images/" . $showId;
+ $importedStorageDirectory = $storDir->getDirectory() . 'imported/' . $ownerId . '/show-images/' . $showId;
try {
$importedStorageDirectory = $this->copyFileToStor($tempFilePath, $importedStorageDirectory, $fileExtension);
} catch (Exception $e) {
@unlink($tempFilePath);
- throw new Exception("Failed to copy file: " . $e->getMessage());
+
+ throw new Exception('Failed to copy file: ' . $e->getMessage());
}
return $importedStorageDirectory;
}
/**
- * Check the MIME type of an uploaded file to determine what extension it should have
+ * Check the MIME type of an uploaded file to determine what extension it should have.
*
* @param $tempFilePath the file path to the uploaded file in /tmp
*
* @return string the file extension for the new file based on its MIME type
*/
- private function getFileExtension($tempFilePath) {
+ private function getFileExtension($tempFilePath)
+ {
// Don't trust the extension - get the MIME-type instead
$fileInfo = finfo_open();
$mime = finfo_file($fileInfo, $tempFilePath, FILEINFO_MIME_TYPE);
+
return $this->getExtensionFromMime($mime);
}
/**
- * Use a hardcoded list of accepted MIME types to return a file extension
+ * Use a hardcoded list of accepted MIME types to return a file extension.
*
* @param $mime the MIME type of the file
*
* @return string the file extension based on the given MIME type
*/
- private function getExtensionFromMime($mime) {
- $extensions = array(
+ private function getExtensionFromMime($mime)
+ {
+ $extensions = [
'image/jpeg' => 'jpg',
'image/png' => 'png',
- 'image/gif' => 'gif'
- );
+ 'image/gif' => 'gif',
+ ];
return $extensions[$mime];
}
/**
- * Copy a given file in /tmp to the user's stor directory
+ * Copy a given file in /tmp to the user's stor directory.
*
* @param string $tempFilePath the path to the file in /tmp
* @param string $importedStorageDirectory the path to the new location for the file
* @param string $fileExtension the file's extension based on its MIME type
*
- * @return string the new full path to the file in stor
* @throws Exception if either the storage directory does not exist and cannot be
* created, the storage directory does not have write permissions
* enabled, or the user's hard drive does not have enough space to
* store the file
+ *
+ * @return string the new full path to the file in stor
*/
- private function copyFileToStor($tempFilePath, $importedStorageDirectory, $fileExtension) {
+ private function copyFileToStor($tempFilePath, $importedStorageDirectory, $fileExtension)
+ {
$image_file = $tempFilePath;
// check if show image dir exists and if not, create one
if (!file_exists($importedStorageDirectory)) {
if (!mkdir($importedStorageDirectory, 0777, true)) {
- throw new Exception("Failed to create storage directory.");
+ throw new Exception('Failed to create storage directory.');
}
}
if (chmod($image_file, 0644) === false) {
- Logging::info("Warning: couldn't change permissions of $image_file to 0644");
+ Logging::info("Warning: couldn't change permissions of {$image_file} to 0644");
}
- $newFileName = substr($tempFilePath, strrpos($tempFilePath, "/")) . "." . $fileExtension;
+ $newFileName = substr($tempFilePath, strrpos($tempFilePath, '/')) . '.' . $fileExtension;
// Did all the checks for real, now trying to copy
$image_stor = Application_Common_OsPath::join($importedStorageDirectory, $newFileName);
- Logging::info("Adding image: " . $image_stor);
- Logging::info("copyFileToStor: moving file $image_file to $image_stor");
+ Logging::info('Adding image: ' . $image_stor);
+ Logging::info("copyFileToStor: moving file {$image_file} to {$image_stor}");
if (@rename($image_file, $image_stor) === false) {
//something went wrong likely there wasn't enough space in .
@@ -239,9 +264,9 @@ class Rest_ShowImageController extends Zend_Rest_Controller {
//is enough disk space .
unlink($image_file); //remove the file after failed rename
- throw new Exception("The file was not uploaded, this error can occur if the computer "
- . "hard drive does not have enough disk space or the stor "
- . "directory does not have correct write permissions.");
+ throw new Exception('The file was not uploaded, this error can occur if the computer '
+ . 'hard drive does not have enough disk space or the stor '
+ . 'directory does not have correct write permissions.');
}
return $image_stor;
@@ -249,51 +274,58 @@ class Rest_ShowImageController extends Zend_Rest_Controller {
// Should this be an endpoint instead?
/**
- * Delete any images belonging to the show with the given ID
+ * Delete any images belonging to the show with the given ID.
*
* @param int $showId the ID of the show we're deleting images from
*
* @return bool true if the images were successfully deleted, otherwise false
*/
- public static function deleteShowImagesFromStor($showId) {
+ public static function deleteShowImagesFromStor($showId)
+ {
$ownerId = RestAuth::getOwnerId();
$storDir = Application_Model_MusicDir::getStorDir();
- $importedStorageDirectory = $storDir->getDirectory() . "imported/" . $ownerId . "/show-images/" . $showId;
+ $importedStorageDirectory = $storDir->getDirectory() . 'imported/' . $ownerId . '/show-images/' . $showId;
- Logging::info("Deleting images from " . $importedStorageDirectory);
+ Logging::info('Deleting images from ' . $importedStorageDirectory);
// to be safe in case image uploading functionality is extended later
if (!file_exists($importedStorageDirectory)) {
- Logging::info("No uploaded images for show with id " . $showId);
+ Logging::info('No uploaded images for show with id ' . $showId);
+
return true;
- } else {
- return self::delTree($importedStorageDirectory);
}
+
+ return self::delTree($importedStorageDirectory);
}
// from a note @ http://php.net/manual/en/function.rmdir.php
- private static function delTree($dir) {
- $files = array_diff(scandir($dir), array('.', '..'));
+ private static function delTree($dir)
+ {
+ $files = array_diff(scandir($dir), ['.', '..']);
foreach ($files as $file) {
- (is_dir("$dir/$file")) ? self::delTree("$dir/$file") : unlink("$dir/$file");
+ (is_dir("{$dir}/{$file}")) ? self::delTree("{$dir}/{$file}") : unlink("{$dir}/{$file}");
}
+
return rmdir($dir);
}
/**
* Fetch the id parameter from the request.
- * @return boolean|int false if the show id wasn't
- * provided, otherwise returns the id
+ *
+ * @return bool|int false if the show id wasn't
+ * provided, otherwise returns the id
*/
- private function getShowId() {
+ private function getShowId()
+ {
if (!($id = $this->_getParam('id', false))) {
$resp = $this->getResponse();
$resp->setHttpResponseCode(400);
- $resp->appendBody("ERROR: No show ID specified.");
+ $resp->appendBody('ERROR: No show ID specified.');
+
return false;
}
+
return $id;
}
-
-}
\ No newline at end of file
+}
diff --git a/legacy/application/modules/rest/helpers/RestAuth.php b/legacy/application/modules/rest/helpers/RestAuth.php
index d7390ab8b..705bf9b54 100644
--- a/legacy/application/modules/rest/helpers/RestAuth.php
+++ b/legacy/application/modules/rest/helpers/RestAuth.php
@@ -1,8 +1,9 @@
getResponse()
->setHttpResponseCode(401)
- ->appendBody(json_encode(array("message" => "ERROR: Incorrect API key.")));
+ ->appendBody(json_encode(['message' => 'ERROR: Incorrect API key.']))
+ ;
return false;
}
- public static function getOwnerId() {
+ public static function getOwnerId()
+ {
try {
if (self::verifySession()) {
$service_user = new Application_Service_UserService();
+
return $service_user->getCurrentUser()->getDbId();
- } else {
- $defaultOwner = CcSubjsQuery::create()
- ->filterByDbType(array('A', 'S'), Criteria::IN)
- ->orderByDbId()
- ->findOne();
- if (!$defaultOwner) {
- // what to do if there is no admin user?
- // should we handle this case?
- return null;
- }
- return $defaultOwner->getDbId();
}
+ $defaultOwner = CcSubjsQuery::create()
+ ->filterByDbType(['A', 'S'], Criteria::IN)
+ ->orderByDbId()
+ ->findOne()
+ ;
+ if (!$defaultOwner) {
+ // what to do if there is no admin user?
+ // should we handle this case?
+ return null;
+ }
+
+ return $defaultOwner->getDbId();
} catch (Exception $e) {
Logging::info($e->getMessage());
}
}
- private static function verifySession() {
+ private static function verifySession()
+ {
$auth = Zend_Auth::getInstance();
+
return $auth->hasIdentity();
}
- private static function verifyAPIKey($action) {
+ private static function verifyAPIKey($action)
+ {
//The API key is passed in via HTTP "basic authentication":
// http://en.wikipedia.org/wiki/Basic_access_authentication
$CC_CONFIG = Config::getConfig();
//Decode the API key that was passed to us in the HTTP request.
- $authHeader = $action->getRequest()->getHeader("Authorization");
- $encodedRequestApiKey = substr($authHeader, strlen("Basic "));
- $encodedStoredApiKey = base64_encode($CC_CONFIG["apiKey"][0] . ":");
+ $authHeader = $action->getRequest()->getHeader('Authorization');
+ $encodedRequestApiKey = substr($authHeader, strlen('Basic '));
+ $encodedStoredApiKey = base64_encode($CC_CONFIG['apiKey'][0] . ':');
- return ($encodedRequestApiKey === $encodedStoredApiKey);
+ return $encodedRequestApiKey === $encodedStoredApiKey;
}
-
-}
\ No newline at end of file
+}
diff --git a/legacy/application/services/CalendarService.php b/legacy/application/services/CalendarService.php
index e85814afb..5fcf1e6e2 100644
--- a/legacy/application/services/CalendarService.php
+++ b/legacy/application/services/CalendarService.php
@@ -11,7 +11,7 @@ class Application_Service_CalendarService
if (!is_null($instanceId)) {
$this->ccShowInstance = CcShowInstancesQuery::create()->findPk($instanceId);
if (is_null($this->ccShowInstance)) {
- throw new Exception("Instance does not exist");
+ throw new Exception('Instance does not exist');
}
$this->ccShow = $this->ccShowInstance->getCcShow();
}
@@ -21,12 +21,11 @@ class Application_Service_CalendarService
}
/**
- *
* Enter description here ...
*/
public function makeContextMenu()
{
- $menu = array();
+ $menu = [];
$now = time();
$baseUrl = Application_Common_OsPath::getBaseDir();
$isAdminOrPM = $this->currentUser->isAdminOrPM();
@@ -43,87 +42,83 @@ class Application_Service_CalendarService
//show has ended
if ($now > $end) {
if ($this->ccShowInstance->isRecorded()) {
-
$ccFile = $this->ccShowInstance->getCcFiles();
if (!isset($ccFile)) {
- $menu["error when recording"] = array (
- "name" => _("Record file doesn't exist"),
- "icon" => "error");
- }else {
- $menu["view_recorded"] = array(
- "name" => _("View Recorded File Metadata"),
- "icon" => "overview",
- "url" => $baseUrl."library/edit-file-md/id/".$ccFile->getDbId());
+ $menu['error when recording'] = [
+ 'name' => _("Record file doesn't exist"),
+ 'icon' => 'error', ];
+ } else {
+ $menu['view_recorded'] = [
+ 'name' => _('View Recorded File Metadata'),
+ 'icon' => 'overview',
+ 'url' => $baseUrl . 'library/edit-file-md/id/' . $ccFile->getDbId(), ];
}
} else {
- $menu["content"] = array(
+ $menu['content'] = [
// "name"=> _("Show Content"),
- "name"=> _("View"),
- "icon" => "overview",
- "url" => $baseUrl."schedule/show-content-dialog");
+ 'name' => _('View'),
+ 'icon' => 'overview',
+ 'url' => $baseUrl . 'schedule/show-content-dialog', ];
}
} else {
// Show content can be modified from the calendar if:
// the user is admin or hosting the show,
// the show is not recorded
$currentShow = Application_Model_Show::getCurrentShow();
- $currentShowId = count($currentShow) == 1 ? $currentShow[0]["id"] : null;
+ $currentShowId = count($currentShow) == 1 ? $currentShow[0]['id'] : null;
$showIsLinked = $this->ccShow->isLinked();
//user can add/remove content if the show has not ended
if ($now < $end && ($isAdminOrPM || $isHostOfShow) && !$this->ccShowInstance->isRecorded()) {
//if the show is not linked OR if the show is linked AND not the current playing show
//the user can add/remove content
- if (!$showIsLinked || ($showIsLinked && $currentShowId != $this->ccShow->getDbId())) {
-
- $menu["schedule"] = array(
+ if (!$showIsLinked || ($showIsLinked && $currentShowId != $this->ccShow->getDbId())) {
+ $menu['schedule'] = [
// "name"=> _("Add / Remove Content"),
- "name" => _("Schedule Tracks"),
- "icon" => "add-remove-content",
- "url" => $baseUrl."showbuilder/builder-dialog/");
+ 'name' => _('Schedule Tracks'),
+ 'icon' => 'add-remove-content',
+ 'url' => $baseUrl . 'showbuilder/builder-dialog/', ];
}
}
//"Show Content" should be a menu item at all times except when
//the show is recorded
if (!$this->ccShowInstance->isRecorded()) {
-
- $menu["content"] = array(
+ $menu['content'] = [
// "name"=> _("Show Content"),
- "name"=> _("View"),
- "icon" => "overview",
- "url" => $baseUrl."schedule/show-content-dialog");
+ 'name' => _('View'),
+ 'icon' => 'overview',
+ 'url' => $baseUrl . 'schedule/show-content-dialog', ];
}
//user can remove all content if the show has not started
- if ($now < $start && ($isAdminOrPM || $isHostOfShow) && !$this->ccShowInstance->isRecorded() ) {
+ if ($now < $start && ($isAdminOrPM || $isHostOfShow) && !$this->ccShowInstance->isRecorded()) {
//if the show is not linked OR if the show is linked AND not the current playing show
//the user can remove all content
- if (!$showIsLinked || ($showIsLinked && $currentShowId != $this->ccShow->getDbId())) {
-
- $menu["clear"] = array(
- // "name"=> _("Remove All Content"),
- "name"=> _("Clear Show"),
- "icon" => "remove-all-content",
- "url" => $baseUrl."schedule/clear-show");
+ if (!$showIsLinked || ($showIsLinked && $currentShowId != $this->ccShow->getDbId())) {
+ $menu['clear'] = [
+ // "name"=> _("Remove All Content"),
+ 'name' => _('Clear Show'),
+ 'icon' => 'remove-all-content',
+ 'url' => $baseUrl . 'schedule/clear-show', ];
}
}
//show is currently playing and user is admin
if ($start <= $now && $now < $end && $isAdminOrPM) {
// Menu separator
- $menu["sep1"] = "-----------";
+ $menu['sep1'] = '-----------';
if ($this->ccShowInstance->isRecorded()) {
- $menu["cancel_recorded"] = array(
+ $menu['cancel_recorded'] = [
// "name"=> _("Cancel Current Show"),
- "name"=> _("Cancel Show"),
- "icon" => "delete");
+ 'name' => _('Cancel Show'),
+ 'icon' => 'delete', ];
} else {
- $menu["cancel"] = array(
+ $menu['cancel'] = [
// "name"=> _("Cancel Current Show"),
- "name"=> _("Cancel Show"),
- "icon" => "delete");
+ 'name' => _('Cancel Show'),
+ 'icon' => 'delete', ];
}
}
@@ -137,91 +132,92 @@ class Application_Service_CalendarService
if (!$this->ccShowInstance->isRebroadcast() && $isAdminOrPM) {
// Menu separator
- $menu["sep2"] = "-----------";
+ $menu['sep2'] = '-----------';
if ($isRepeating) {
if ($populateInstance) {
- $menu["edit"] = array(
+ $menu['edit'] = [
// "name" => _("Edit This Instance"),
- "name" => _("Edit Instance"),
- "icon" => "edit",
- "url" => $baseUrl . "Schedule/populate-repeating-show-instance-form"
- );
+ 'name' => _('Edit Instance'),
+ 'icon' => 'edit',
+ 'url' => $baseUrl . 'Schedule/populate-repeating-show-instance-form',
+ ];
} else {
- $menu["edit"] = array(
- "name" => _("Edit"),
- "icon" => "edit",
- "items" => array()
- );
+ $menu['edit'] = [
+ 'name' => _('Edit'),
+ 'icon' => 'edit',
+ 'items' => [],
+ ];
- $menu["edit"]["items"]["all"] = array(
- "name" => _("Edit Show"),
- "icon" => "edit",
- "url" => $baseUrl . "Schedule/populate-show-form"
- );
+ $menu['edit']['items']['all'] = [
+ 'name' => _('Edit Show'),
+ 'icon' => 'edit',
+ 'url' => $baseUrl . 'Schedule/populate-show-form',
+ ];
- $menu["edit"]["items"]["instance"] = array(
+ $menu['edit']['items']['instance'] = [
// "name" => _("Edit This Instance"),
- "name" => _("Edit Instance"),
- "icon" => "edit",
- "url" => $baseUrl . "Schedule/populate-repeating-show-instance-form"
- );
+ 'name' => _('Edit Instance'),
+ 'icon' => 'edit',
+ 'url' => $baseUrl . 'Schedule/populate-repeating-show-instance-form',
+ ];
}
} else {
- $menu["edit"] = array(
- "name"=> _("Edit Show"),
- "icon" => "edit",
- "_type"=>"all",
- "url" => $baseUrl."Schedule/populate-show-form");
+ $menu['edit'] = [
+ 'name' => _('Edit Show'),
+ 'icon' => 'edit',
+ '_type' => 'all',
+ 'url' => $baseUrl . 'Schedule/populate-show-form', ];
}
}
//show hasn't started yet and user is admin
if ($now < $start && $isAdminOrPM) {
// Menu separator
- $menu["sep3"] = "-----------";
+ $menu['sep3'] = '-----------';
//show is repeating so give user the option to delete all
//repeating instances or just the one
if ($isRepeating) {
- $menu["del"] = array(
- "name"=> _("Delete"),
- "icon" => "delete",
- "items" => array());
+ $menu['del'] = [
+ 'name' => _('Delete'),
+ 'icon' => 'delete',
+ 'items' => [], ];
- $menu["del"]["items"]["single"] = array(
+ $menu['del']['items']['single'] = [
// "name"=> _("Delete This Instance"),
- "name"=> _("Delete Instance"),
- "icon" => "delete",
- "url" => $baseUrl."schedule/delete-show-instance");
+ 'name' => _('Delete Instance'),
+ 'icon' => 'delete',
+ 'url' => $baseUrl . 'schedule/delete-show-instance', ];
- $menu["del"]["items"]["following"] = array(
+ $menu['del']['items']['following'] = [
// "name"=> _("Delete This Instance and All Following"),
- "name"=> _("Delete Instance and All Following"),
- "icon" => "delete",
- "url" => $baseUrl."schedule/delete-show");
+ 'name' => _('Delete Instance and All Following'),
+ 'icon' => 'delete',
+ 'url' => $baseUrl . 'schedule/delete-show', ];
} elseif ($populateInstance) {
- $menu["del"] = array(
- "name"=> _("Delete"),
- "icon" => "delete",
- "url" => $baseUrl."schedule/delete-show-instance");
+ $menu['del'] = [
+ 'name' => _('Delete'),
+ 'icon' => 'delete',
+ 'url' => $baseUrl . 'schedule/delete-show-instance', ];
} else {
- $menu["del"] = array(
- "name"=> _("Delete"),
- "icon" => "delete",
- "url" => $baseUrl."schedule/delete-show");
+ $menu['del'] = [
+ 'name' => _('Delete'),
+ 'icon' => 'delete',
+ 'url' => $baseUrl . 'schedule/delete-show', ];
}
}
}
+
return $menu;
}
/**
- *
* Enter description here ...
+ *
* @param DateTime $dateTime object to add deltas to
- * @param int $deltaDay delta days show moved
- * @param int $deltaMin delta minutes show moved
+ * @param int $deltaDay delta days show moved
+ * @param int $deltaMin delta minutes show moved
*/
public static function addDeltas($dateTime, $deltaDay, $deltaMin)
{
@@ -251,7 +247,7 @@ class Application_Service_CalendarService
private function validateShowMove($deltaDay, $deltaMin)
{
if (!$this->currentUser->isAdminOrPM()) {
- throw new Exception(_("Permission denied"));
+ throw new Exception(_('Permission denied'));
}
if ($this->ccShow->isRepeating()) {
@@ -275,7 +271,7 @@ class Application_Service_CalendarService
$endsDateTime->setTimezone(new DateTimeZone($showTimezone));
$duration = $startsDateTime->diff($endsDateTime);
-
+
$newStartsDateTime = self::addDeltas($startsDateTime, $deltaDay, $deltaMin);
/* WARNING: Do not separately add a time delta to the start and end times because
that does not preserve the duration across a DST time change.
@@ -283,9 +279,9 @@ class Application_Service_CalendarService
BUT, 6am - 3 hours = 3am also!
So when a DST change occurs, adding the deltas like this
separately does not conserve the duration of a show.
- Since that's what we want (otherwise we'll get a zero length show),
+ Since that's what we want (otherwise we'll get a zero length show),
we calculate the show duration FIRST, then we just add that on
- to the start time to calculate the end time.
+ to the start time to calculate the end time.
This is a safer approach.
The key lesson here is that in general: duration != end - start
... so be careful!
@@ -293,10 +289,10 @@ class Application_Service_CalendarService
//$newEndsDateTime = self::addDeltas($endsDateTime, $deltaDay, $deltaMin); <--- Wrong, don't do it.
$newEndsDateTime = clone $newStartsDateTime;
$newEndsDateTime = $newEndsDateTime->add($duration);
-
+
//convert our new starts/ends to UTC.
- $newStartsDateTime->setTimezone(new DateTimeZone("UTC"));
- $newEndsDateTime->setTimezone(new DateTimeZone("UTC"));
+ $newStartsDateTime->setTimezone(new DateTimeZone('UTC'));
+ $newEndsDateTime->setTimezone(new DateTimeZone('UTC'));
if ($today_timestamp > $newStartsDateTime->getTimestamp()) {
throw new Exception(_("Can't move show into past"));
@@ -304,9 +300,13 @@ class Application_Service_CalendarService
//check if show is overlapping
$overlapping = Application_Model_Schedule::checkOverlappingShows(
- $newStartsDateTime, $newEndsDateTime, true, $this->ccShowInstance->getDbId());
+ $newStartsDateTime,
+ $newEndsDateTime,
+ true,
+ $this->ccShowInstance->getDbId()
+ );
if ($overlapping) {
- throw new Exception(_("Cannot schedule overlapping shows"));
+ throw new Exception(_('Cannot schedule overlapping shows'));
}
if ($this->ccShow->isRecorded()) {
@@ -316,7 +316,8 @@ class Application_Service_CalendarService
$rebroadcasts = CcShowInstancesQuery::create()
->filterByDbOriginalShow($this->ccShow->getDbId())
->filterByDbStarts($minRebroadcastStart->format(DEFAULT_TIMESTAMP_FORMAT), Criteria::LESS_THAN)
- ->find();
+ ->find()
+ ;
if (count($rebroadcasts) > 0) {
throw new Exception(_("Can't move a recorded show less than 1 hour before its rebroadcasts."));
@@ -326,20 +327,23 @@ class Application_Service_CalendarService
if ($this->ccShow->isRebroadcast()) {
$recordedShow = CcShowInstancesQuery::create()
->filterByCcShow($this->ccShowInstance->getDbOriginalShow())
- ->findOne();
+ ->findOne()
+ ;
if (is_null($recordedShow)) {
$this->ccShowInstance->delete();
- throw new Exception(_("Show was deleted because recorded show does not exist!"));
+
+ throw new Exception(_('Show was deleted because recorded show does not exist!'));
}
- $recordEndDateTime = new DateTime($recordedShow->getDbEnds(), new DateTimeZone("UTC"));
+ $recordEndDateTime = new DateTime($recordedShow->getDbEnds(), new DateTimeZone('UTC'));
$newRecordEndDateTime = self::addDeltas($recordEndDateTime, 0, 60);
if ($newStartsDateTime->getTimestamp() < $newRecordEndDateTime->getTimestamp()) {
- throw new Exception(_("Must wait 1 hour to rebroadcast."));
+ throw new Exception(_('Must wait 1 hour to rebroadcast.'));
}
}
- return array($newStartsDateTime, $newEndsDateTime);
+
+ return [$newStartsDateTime, $newEndsDateTime];
}
public function moveShow($deltaDay, $deltaMin)
@@ -350,14 +354,17 @@ class Application_Service_CalendarService
//new starts,ends are in UTC
list($newStartsDateTime, $newEndsDateTime) = $this->validateShowMove(
- $deltaDay, $deltaMin);
-
+ $deltaDay,
+ $deltaMin
+ );
+
$oldStartDateTime = $this->ccShowInstance->getDbStarts(null);
$this->ccShowInstance
->setDbStarts($newStartsDateTime)
->setDbEnds($newEndsDateTime)
- ->save($con);
+ ->save($con)
+ ;
if (!$this->ccShowInstance->getCcShow()->isRebroadcast()) {
//we can get the first show day because we know the show is
@@ -365,20 +372,24 @@ class Application_Service_CalendarService
$ccShowDay = $this->ccShow->getFirstCcShowDay();
$showTimezone = new DateTimeZone($ccShowDay->getDbTimezone());
$ccShowDay
- ->setDbFirstShow($newStartsDateTime->setTimezone($showTimezone)->format("Y-m-d"))
- ->setDbStartTime($newStartsDateTime->format("H:i"))
- ->save($con);
+ ->setDbFirstShow($newStartsDateTime->setTimezone($showTimezone)->format('Y-m-d'))
+ ->setDbStartTime($newStartsDateTime->format('H:i'))
+ ->save($con)
+ ;
}
-
+
$diff = $newStartsDateTime->getTimestamp() - $oldStartDateTime->getTimestamp();
-
+
Application_Service_SchedulerService::updateScheduleStartTime(
- array($this->ccShowInstance->getDbId()), $diff);
+ [$this->ccShowInstance->getDbId()],
+ $diff
+ );
$con->commit();
Application_Model_RabbitMq::PushSchedule();
} catch (Exception $e) {
$con->rollback();
+
return $e->getMessage();
}
}
@@ -396,5 +407,4 @@ class Application_Service_CalendarService
return $e->getMessage();
}
}
-
}
diff --git a/legacy/application/services/CeleryServiceFactory.php b/legacy/application/services/CeleryServiceFactory.php
index 08952c756..7f5ab4be3 100644
--- a/legacy/application/services/CeleryServiceFactory.php
+++ b/legacy/application/services/CeleryServiceFactory.php
@@ -1,21 +1,22 @@
con = isset($con) ? $con : Propel::getConnection(CcPlayoutHistoryPeer::DATABASE_NAME);
- $this->timezone = Application_Model_Preference::GetTimezone();
- }
+ public function __construct()
+ {
+ $this->con = isset($con) ? $con : Propel::getConnection(CcPlayoutHistoryPeer::DATABASE_NAME);
+ $this->timezone = Application_Model_Preference::GetTimezone();
+ }
- public function getSupportedTemplateTypes()
- {
- return array(self::TEMPLATE_TYPE_ITEM, self::TEMPLATE_TYPE_FILE);
- }
+ public function getSupportedTemplateTypes()
+ {
+ return [self::TEMPLATE_TYPE_ITEM, self::TEMPLATE_TYPE_FILE];
+ }
- //opts is from datatables.
- public function getPlayedItemData($startDT, $endDT, $opts, $instanceId=null)
- {
- $mainSqlQuery = "";
- $paramMap = array();
- $sqlTypes = $this->getSqlTypes();
+ //opts is from datatables.
+ public function getPlayedItemData($startDT, $endDT, $opts, $instanceId = null)
+ {
+ $mainSqlQuery = '';
+ $paramMap = [];
+ $sqlTypes = $this->getSqlTypes();
- $start = $startDT->format(DEFAULT_TIMESTAMP_FORMAT);
- $end = $endDT->format(DEFAULT_TIMESTAMP_FORMAT);
+ $start = $startDT->format(DEFAULT_TIMESTAMP_FORMAT);
+ $end = $endDT->format(DEFAULT_TIMESTAMP_FORMAT);
- $template = $this->getConfiguredItemTemplate();
- $fields = $template["fields"];
- $required = $this->mandatoryItemFields();
+ $template = $this->getConfiguredItemTemplate();
+ $fields = $template['fields'];
+ $required = $this->mandatoryItemFields();
- $fields_filemd = array();
- $filemd_keys = array();
- $fields_general = array();
- $general_keys = array();
+ $fields_filemd = [];
+ $filemd_keys = [];
+ $fields_general = [];
+ $general_keys = [];
- foreach ($fields as $index=>$field) {
+ foreach ($fields as $index => $field) {
+ if (in_array($field['name'], $required)) {
+ continue;
+ }
- if (in_array($field["name"], $required)) {
- continue;
- }
+ if ($field['isFileMd']) {
+ $fields_filemd[] = $field;
+ $filemd_keys[] = $field['name'];
+ } else {
+ $fields_general[] = $field;
+ $general_keys[] = $field['name'];
+ }
+ }
- if ($field["isFileMd"]) {
- $fields_filemd[] = $field;
- $filemd_keys[] = $field["name"];
- }
- else {
- $fields_general[] = $field;
- $general_keys[] = $field["name"];
- }
- }
+ //-----------------------------------------------------------------------
+ //Using the instance_id to filter the data.
- //-----------------------------------------------------------------------
- //Using the instance_id to filter the data.
+ $historyRange = '(' .
+ 'SELECT history.starts, history.ends, history.id AS history_id, history.instance_id' .
+ ' FROM cc_playout_history as history';
-
- $historyRange = "(".
- "SELECT history.starts, history.ends, history.id AS history_id, history.instance_id".
- " FROM cc_playout_history as history";
-
- if (isset($instanceId)) {
- $historyRange.= " WHERE history.instance_id = :instance";
- $paramMap["instance"] = $instanceId;
- }
- else {
- $historyRange.= " WHERE history.starts >= :starts and history.starts < :ends";
- $paramMap["starts"] = $start;
- $paramMap["ends"] = $end;
- }
-
- $historyRange.= ") AS history_range";
-
- $manualMeta = "(".
- "SELECT %KEY%.value AS %KEY%, %KEY%.history_id".
- " FROM (".
- " SELECT * from cc_playout_history_metadata AS phm WHERE phm.key = :meta_%KEY%".
- " ) AS %KEY%".
- " ) AS %KEY%_filter";
-
- $mainSelect = array(
- "history_range.starts",
- "history_range.ends",
- "history_range.history_id",
- "history_range.instance_id"
- );
- $mdFilters = array();
-
- $numFileMdFields = count($fields_filemd);
-
- if ($numFileMdFields > 0) {
-
- //these 3 selects are only needed if $fields_filemd has some fields.
- $fileSelect = array("history_file.history_id");
- $nonNullFileSelect = array("file.id as file_id");
- $nullFileSelect = array("null_file.history_id");
-
- $fileMdFilters = array();
-
- //populate the different dynamic selects with file info.
- for ($i = 0; $i < $numFileMdFields; $i++) {
-
- $field = $fields_filemd[$i];
- $key = $field["name"];
- $type = $sqlTypes[$field["type"]];
-
- $fileSelect[] = "file_md.{$key}::{$type}";
- $nonNullFileSelect[] = "file.{$key}::{$type}";
- $nullFileSelect[] = "{$key}_filter.{$key}::{$type}";
- $mainSelect[] = "file_info.{$key}::{$type}";
-
- $fileMdFilters[] = str_replace("%KEY%", $key, $manualMeta);
- $paramMap["meta_{$key}"] = $key;
- }
-
- //the files associated with scheduled playback in Airtime.
- $historyFile = "(".
- "SELECT history.id AS history_id, history.file_id".
- " FROM cc_playout_history AS history".
- " WHERE history.file_id IS NOT NULL".
- ") AS history_file";
-
- $fileMd = "(".
- "SELECT %NON_NULL_FILE_SELECT%".
- " FROM cc_files AS file".
- ") AS file_md";
-
- $fileMd = str_replace("%NON_NULL_FILE_SELECT%", join(", ", $nonNullFileSelect), $fileMd);
-
- //null files are from manually added data (filling in webstream info etc)
- $nullFile = "(".
- "SELECT history.id AS history_id".
- " FROM cc_playout_history AS history".
- " WHERE history.file_id IS NULL".
- ") AS null_file";
-
-
- //----------------------------------
- //building the file inner query
-
- $fileSqlQuery =
- "SELECT ".join(", ", $fileSelect).
- " FROM {$historyFile}".
- " LEFT JOIN {$fileMd} USING (file_id)".
- " UNION".
- " SELECT ".join(", ", $nullFileSelect).
- " FROM {$nullFile}";
-
- foreach ($fileMdFilters as $filter) {
-
- $fileSqlQuery.=
- " LEFT JOIN {$filter} USING(history_id)";
- }
-
- }
-
- for ($i = 0, $len = count($fields_general); $i < $len; $i++) {
-
- $field = $fields_general[$i];
- $key = $field["name"];
- $type = $sqlTypes[$field["type"]];
-
- $mdFilters[] = str_replace("%KEY%", $key, $manualMeta);
- $paramMap["meta_{$key}"] = $key;
- $mainSelect[] = "{$key}_filter.{$key}::{$type}";
- }
-
- $mainSqlQuery.=
- "SELECT ".join(", ", $mainSelect).
- " FROM {$historyRange}";
-
- if (isset($fileSqlQuery)) {
-
- $mainSqlQuery.=
- " LEFT JOIN ( {$fileSqlQuery} ) as file_info USING(history_id)";
- }
-
- foreach ($mdFilters as $filter) {
-
- $mainSqlQuery.=
- " LEFT JOIN {$filter} USING(history_id)";
- }
-
- //----------------------------------------------------------------------
- //need to count the total rows to tell Datatables.
- $stmt = $this->con->prepare($mainSqlQuery);
- foreach ($paramMap as $param => $v) {
- $stmt->bindValue($param, $v);
- }
-
- if ($stmt->execute()) {
- $totalRows = $stmt->rowCount();
- }
- else {
- $msg = implode(',', $stmt->errorInfo());
- throw new Exception("Error: $msg");
- }
-
- //------------------------------------------------------------------------
- //Using Datatables parameters to sort the data.
-
- if (empty($opts["iSortingCols"])) {
- $orderBys = array();
+ if (isset($instanceId)) {
+ $historyRange .= ' WHERE history.instance_id = :instance';
+ $paramMap['instance'] = $instanceId;
} else {
- $numOrderColumns = $opts["iSortingCols"];
- $orderBys = array();
+ $historyRange .= ' WHERE history.starts >= :starts and history.starts < :ends';
+ $paramMap['starts'] = $start;
+ $paramMap['ends'] = $end;
+ }
- for ($i = 0; $i < $numOrderColumns; $i++) {
+ $historyRange .= ') AS history_range';
- $colNum = $opts["iSortCol_".$i];
- $key = $opts["mDataProp_".$colNum];
- $sortDir = $opts["sSortDir_".$i];
+ $manualMeta = '(' .
+ 'SELECT %KEY%.value AS %KEY%, %KEY%.history_id' .
+ ' FROM (' .
+ ' SELECT * from cc_playout_history_metadata AS phm WHERE phm.key = :meta_%KEY%' .
+ ' ) AS %KEY%' .
+ ' ) AS %KEY%_filter';
+
+ $mainSelect = [
+ 'history_range.starts',
+ 'history_range.ends',
+ 'history_range.history_id',
+ 'history_range.instance_id',
+ ];
+ $mdFilters = [];
+
+ $numFileMdFields = count($fields_filemd);
+
+ if ($numFileMdFields > 0) {
+ //these 3 selects are only needed if $fields_filemd has some fields.
+ $fileSelect = ['history_file.history_id'];
+ $nonNullFileSelect = ['file.id as file_id'];
+ $nullFileSelect = ['null_file.history_id'];
+
+ $fileMdFilters = [];
+
+ //populate the different dynamic selects with file info.
+ for ($i = 0; $i < $numFileMdFields; ++$i) {
+ $field = $fields_filemd[$i];
+ $key = $field['name'];
+ $type = $sqlTypes[$field['type']];
+
+ $fileSelect[] = "file_md.{$key}::{$type}";
+ $nonNullFileSelect[] = "file.{$key}::{$type}";
+ $nullFileSelect[] = "{$key}_filter.{$key}::{$type}";
+ $mainSelect[] = "file_info.{$key}::{$type}";
+
+ $fileMdFilters[] = str_replace('%KEY%', $key, $manualMeta);
+ $paramMap["meta_{$key}"] = $key;
+ }
+
+ //the files associated with scheduled playback in Airtime.
+ $historyFile = '(' .
+ 'SELECT history.id AS history_id, history.file_id' .
+ ' FROM cc_playout_history AS history' .
+ ' WHERE history.file_id IS NOT NULL' .
+ ') AS history_file';
+
+ $fileMd = '(' .
+ 'SELECT %NON_NULL_FILE_SELECT%' .
+ ' FROM cc_files AS file' .
+ ') AS file_md';
+
+ $fileMd = str_replace('%NON_NULL_FILE_SELECT%', join(', ', $nonNullFileSelect), $fileMd);
+
+ //null files are from manually added data (filling in webstream info etc)
+ $nullFile = '(' .
+ 'SELECT history.id AS history_id' .
+ ' FROM cc_playout_history AS history' .
+ ' WHERE history.file_id IS NULL' .
+ ') AS null_file';
+
+ //----------------------------------
+ //building the file inner query
+
+ $fileSqlQuery =
+ 'SELECT ' . join(', ', $fileSelect) .
+ " FROM {$historyFile}" .
+ " LEFT JOIN {$fileMd} USING (file_id)" .
+ ' UNION' .
+ ' SELECT ' . join(', ', $nullFileSelect) .
+ " FROM {$nullFile}";
+
+ foreach ($fileMdFilters as $filter) {
+ $fileSqlQuery .=
+ " LEFT JOIN {$filter} USING(history_id)";
+ }
+ }
+
+ for ($i = 0, $len = count($fields_general); $i < $len; ++$i) {
+ $field = $fields_general[$i];
+ $key = $field['name'];
+ $type = $sqlTypes[$field['type']];
+
+ $mdFilters[] = str_replace('%KEY%', $key, $manualMeta);
+ $paramMap["meta_{$key}"] = $key;
+ $mainSelect[] = "{$key}_filter.{$key}::{$type}";
+ }
+
+ $mainSqlQuery .=
+ 'SELECT ' . join(', ', $mainSelect) .
+ " FROM {$historyRange}";
+
+ if (isset($fileSqlQuery)) {
+ $mainSqlQuery .=
+ " LEFT JOIN ( {$fileSqlQuery} ) as file_info USING(history_id)";
+ }
+
+ foreach ($mdFilters as $filter) {
+ $mainSqlQuery .=
+ " LEFT JOIN {$filter} USING(history_id)";
+ }
+
+ //----------------------------------------------------------------------
+ //need to count the total rows to tell Datatables.
+ $stmt = $this->con->prepare($mainSqlQuery);
+ foreach ($paramMap as $param => $v) {
+ $stmt->bindValue($param, $v);
+ }
+
+ if ($stmt->execute()) {
+ $totalRows = $stmt->rowCount();
+ } else {
+ $msg = implode(',', $stmt->errorInfo());
+
+ throw new Exception("Error: {$msg}");
+ }
+
+ //------------------------------------------------------------------------
+ //Using Datatables parameters to sort the data.
+
+ if (empty($opts['iSortingCols'])) {
+ $orderBys = [];
+ } else {
+ $numOrderColumns = $opts['iSortingCols'];
+ $orderBys = [];
+
+ for ($i = 0; $i < $numOrderColumns; ++$i) {
+ $colNum = $opts['iSortCol_' . $i];
+ $key = $opts['mDataProp_' . $colNum];
+ $sortDir = $opts['sSortDir_' . $i];
if (in_array($key, $required)) {
-
$orderBys[] = "history_range.{$key} {$sortDir}";
- }
- else if (in_array($key, $filemd_keys)) {
-
+ } elseif (in_array($key, $filemd_keys)) {
$orderBys[] = "file_info.{$key} {$sortDir}";
- }
- else if (in_array($key, $general_keys)) {
-
+ } elseif (in_array($key, $general_keys)) {
$orderBys[] = "{$key}_filter.{$key} {$sortDir}";
}
- else {
- //throw new Exception("Error: $key is not part of the template.");
- }
+
+ //throw new Exception("Error: $key is not part of the template.");
}
- }
+ }
- if (count($orderBys) > 0) {
+ if (count($orderBys) > 0) {
+ $orders = join(', ', $orderBys);
- $orders = join(", ", $orderBys);
+ $mainSqlQuery .=
+ " ORDER BY {$orders}";
+ }
- $mainSqlQuery.=
- " ORDER BY {$orders}";
- }
+ //---------------------------------------------------------------
+ //using Datatables parameters to add limits/offsets
- //---------------------------------------------------------------
- //using Datatables parameters to add limits/offsets
+ $displayLength = empty($opts['iDisplayLength']) ? -1 : intval($opts['iDisplayLength']);
+ //limit the results returned.
+ if ($displayLength !== -1) {
+ $mainSqlQuery .=
+ ' OFFSET :offset LIMIT :limit';
- $displayLength = empty($opts["iDisplayLength"]) ? -1 : intval($opts["iDisplayLength"]);
- //limit the results returned.
- if ($displayLength !== -1) {
- $mainSqlQuery.=
- " OFFSET :offset LIMIT :limit";
+ $paramMap['offset'] = intval($opts['iDisplayStart']);
+ $paramMap['limit'] = $displayLength;
+ }
- $paramMap["offset"] = intval($opts["iDisplayStart"]);
- $paramMap["limit"] = $displayLength;
- }
+ $stmt = $this->con->prepare($mainSqlQuery);
+ foreach ($paramMap as $param => $v) {
+ $stmt->bindValue($param, $v);
+ }
- $stmt = $this->con->prepare($mainSqlQuery);
- foreach ($paramMap as $param => $v) {
- $stmt->bindValue($param, $v);
- }
+ $rows = [];
+ if ($stmt->execute()) {
+ $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ } else {
+ $msg = implode(',', $stmt->errorInfo());
- $rows = array();
- if ($stmt->execute()) {
- $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
- }
- else {
- $msg = implode(',', $stmt->errorInfo());
- throw new Exception("Error: $msg");
- }
+ throw new Exception("Error: {$msg}");
+ }
- //-----------------------------------------------------------------------
- //processing results.
+ //-----------------------------------------------------------------------
+ //processing results.
- $timezoneUTC = new DateTimeZone("UTC");
- $timezoneLocal = new DateTimeZone($this->timezone);
+ $timezoneUTC = new DateTimeZone('UTC');
+ $timezoneLocal = new DateTimeZone($this->timezone);
- $boolCast = array();
- foreach ($fields as $index=>$field) {
+ $boolCast = [];
+ foreach ($fields as $index => $field) {
+ if ($field['type'] == TEMPLATE_BOOLEAN) {
+ $boolCast[] = $field;
+ }
+ }
- if ($field["type"] == TEMPLATE_BOOLEAN) {
- $boolCast[] = $field;
- }
- }
+ foreach ($rows as $index => &$result) {
+ foreach ($boolCast as $field) {
+ $result[$field['label']] = (bool) $result[$field['name']];
+ }
- foreach ($rows as $index => &$result) {
+ //need to display the results in the station's timezone.
+ $dateTime = new DateTime($result['starts'], $timezoneUTC);
+ $dateTime->setTimezone($timezoneLocal);
+ $result['starts'] = $dateTime->format(DEFAULT_TIMESTAMP_FORMAT);
- foreach ($boolCast as $field) {
- $result[$field['label']] = (bool) $result[$field['name']];
- }
+ //if ends is null we don't want it to default to "now"
+ if (isset($result['ends'])) {
+ $dateTime = new DateTime($result['ends'], $timezoneUTC);
+ $dateTime->setTimezone($timezoneLocal);
+ $result['ends'] = $dateTime->format(DEFAULT_TIMESTAMP_FORMAT);
+ }
- //need to display the results in the station's timezone.
- $dateTime = new DateTime($result["starts"], $timezoneUTC);
- $dateTime->setTimezone($timezoneLocal);
- $result["starts"] = $dateTime->format(DEFAULT_TIMESTAMP_FORMAT);
+ if (isset($result[MDATA_KEY_DURATION])) {
+ $formatter = new LengthFormatter($result[MDATA_KEY_DURATION]);
+ $result[MDATA_KEY_DURATION] = $formatter->format();
+ }
- //if ends is null we don't want it to default to "now"
- if (isset($result["ends"])) {
- $dateTime = new DateTime($result["ends"], $timezoneUTC);
- $dateTime->setTimezone($timezoneLocal);
- $result["ends"] = $dateTime->format(DEFAULT_TIMESTAMP_FORMAT);
- }
+ //need to add a checkbox..
+ $result['checkbox'] = '';
- if (isset($result[MDATA_KEY_DURATION])) {
- $formatter = new LengthFormatter($result[MDATA_KEY_DURATION]);
- $result[MDATA_KEY_DURATION] = $formatter->format();
- }
+ //$unicodeChar = '\u2612';
+ //$result["new"] = json_decode('"'.$unicodeChar.'"');
+ //$result["new"] = "U+2612";
+ }
- //need to add a checkbox..
- $result["checkbox"] = "";
+ return [
+ 'sEcho' => empty($opts['sEcho']) ? null : intval($opts['sEcho']),
+ //"iTotalDisplayRecords" => intval($totalDisplayRows),
+ 'iTotalDisplayRecords' => intval($totalRows),
+ 'iTotalRecords' => intval($totalRows),
+ 'history' => $rows,
+ ];
+ }
- //$unicodeChar = '\u2612';
- //$result["new"] = json_decode('"'.$unicodeChar.'"');
- //$result["new"] = "U+2612";
- }
+ public function getFileSummaryData($startDT, $endDT, $opts)
+ {
+ $select = [
+ 'summary.played',
+ 'summary.file_id',
+ 'summary.' . MDATA_KEY_TITLE,
+ 'summary.' . MDATA_KEY_CREATOR,
+ ];
- return array(
- "sEcho" => empty($opts["sEcho"]) ? null : intval($opts["sEcho"]),
- //"iTotalDisplayRecords" => intval($totalDisplayRows),
- "iTotalDisplayRecords" => intval($totalRows),
- "iTotalRecords" => intval($totalRows),
- "history" => $rows
- );
- }
+ $mainSqlQuery = '';
+ $paramMap = [];
+ $start = $startDT->format(DEFAULT_TIMESTAMP_FORMAT);
+ $end = $endDT->format(DEFAULT_TIMESTAMP_FORMAT);
- public function getFileSummaryData($startDT, $endDT, $opts)
- {
- $select = array (
- "summary.played",
- "summary.file_id",
- "summary.".MDATA_KEY_TITLE,
- "summary.".MDATA_KEY_CREATOR
- );
+ $paramMap['starts'] = $start;
+ $paramMap['ends'] = $end;
- $mainSqlQuery = "";
- $paramMap = array();
- $start = $startDT->format(DEFAULT_TIMESTAMP_FORMAT);
- $end = $endDT->format(DEFAULT_TIMESTAMP_FORMAT);
+ $template = $this->getConfiguredFileTemplate();
+ $fields = $template['fields'];
+ $required = $this->mandatoryFileFields();
- $paramMap["starts"] = $start;
- $paramMap["ends"] = $end;
+ foreach ($fields as $index => $field) {
+ $key = $field['name'];
- $template = $this->getConfiguredFileTemplate();
- $fields = $template["fields"];
- $required = $this->mandatoryFileFields();
+ if (in_array($field['name'], $required)) {
+ continue;
+ }
- foreach ($fields as $index=>$field) {
+ $select[] = "summary.{$key}";
+ }
- $key = $field["name"];
-
- if (in_array($field["name"], $required)) {
- continue;
- }
-
- $select[] = "summary.{$key}";
- }
-
- $fileSummaryTable = "((
+ $fileSummaryTable = '((
SELECT COUNT(history.file_id) as played, history.file_id as file_id
FROM cc_playout_history AS history
WHERE history.starts >= :starts AND history.starts < :ends
AND history.file_id IS NOT NULL
GROUP BY history.file_id
) AS playout
- LEFT JOIN cc_files AS file ON (file.id = playout.file_id)) AS summary";
+ LEFT JOIN cc_files AS file ON (file.id = playout.file_id)) AS summary';
- $mainSqlQuery.=
- "SELECT ".join(", ", $select).
- " FROM {$fileSummaryTable}";
+ $mainSqlQuery .=
+ 'SELECT ' . join(', ', $select) .
+ " FROM {$fileSummaryTable}";
- //-------------------------------------------------------------------------
- //need to count the total rows to tell Datatables.
- $stmt = $this->con->prepare($mainSqlQuery);
- foreach ($paramMap as $param => $v) {
- $stmt->bindValue($param, $v);
- }
+ //-------------------------------------------------------------------------
+ //need to count the total rows to tell Datatables.
+ $stmt = $this->con->prepare($mainSqlQuery);
+ foreach ($paramMap as $param => $v) {
+ $stmt->bindValue($param, $v);
+ }
- if ($stmt->execute()) {
- $totalRows = $stmt->rowCount();
- }
- else {
- $msg = implode(',', $stmt->errorInfo());
- throw new Exception("Error: $msg");
- }
+ if ($stmt->execute()) {
+ $totalRows = $stmt->rowCount();
+ } else {
+ $msg = implode(',', $stmt->errorInfo());
- //------------------------------------------------------------------------
- //Using Datatables parameters to sort the data.
+ throw new Exception("Error: {$msg}");
+ }
- $numOrderColumns = $opts["iSortingCols"];
- $orderBys = array();
+ //------------------------------------------------------------------------
+ //Using Datatables parameters to sort the data.
- for ($i = 0; $i < $numOrderColumns; $i++) {
+ $numOrderColumns = $opts['iSortingCols'];
+ $orderBys = [];
- $colNum = $opts["iSortCol_".$i];
- $key = $opts["mDataProp_".$colNum];
- $sortDir = $opts["sSortDir_".$i];
+ for ($i = 0; $i < $numOrderColumns; ++$i) {
+ $colNum = $opts['iSortCol_' . $i];
+ $key = $opts['mDataProp_' . $colNum];
+ $sortDir = $opts['sSortDir_' . $i];
- $orderBys[] = "summary.{$key} {$sortDir}";
- }
+ $orderBys[] = "summary.{$key} {$sortDir}";
+ }
- if ($numOrderColumns > 0) {
+ if ($numOrderColumns > 0) {
+ $orders = join(', ', $orderBys);
- $orders = join(", ", $orderBys);
+ $mainSqlQuery .=
+ " ORDER BY {$orders}";
+ }
- $mainSqlQuery.=
- " ORDER BY {$orders}";
- }
+ //------------------------------------------------------------
+ //using datatables params to add limits/offsets
+ $displayLength = intval($opts['iDisplayLength']);
+ if ($displayLength !== -1) {
+ $mainSqlQuery .=
+ ' OFFSET :offset LIMIT :limit';
- //------------------------------------------------------------
- //using datatables params to add limits/offsets
- $displayLength = intval($opts["iDisplayLength"]);
- if ($displayLength !== -1) {
- $mainSqlQuery.=
- " OFFSET :offset LIMIT :limit";
+ $paramMap['offset'] = $opts['iDisplayStart'];
+ $paramMap['limit'] = $displayLength;
+ }
- $paramMap["offset"] = $opts["iDisplayStart"];
- $paramMap["limit"] = $displayLength;
- }
+ $stmt = $this->con->prepare($mainSqlQuery);
+ foreach ($paramMap as $param => $v) {
+ $stmt->bindValue($param, $v);
+ }
- $stmt = $this->con->prepare($mainSqlQuery);
- foreach ($paramMap as $param => $v) {
- $stmt->bindValue($param, $v);
- }
+ $rows = [];
+ if ($stmt->execute()) {
+ $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ } else {
+ $msg = implode(',', $stmt->errorInfo());
- $rows = array();
- if ($stmt->execute()) {
- $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
- }
- else {
- $msg = implode(',', $stmt->errorInfo());
- throw new Exception("Error: $msg");
- }
+ throw new Exception("Error: {$msg}");
+ }
- //-----------------------------------------------------------------
- //processing the results
- foreach ($rows as &$row) {
- if (isset($row[MDATA_KEY_DURATION])) {
- $formatter = new LengthFormatter($row[MDATA_KEY_DURATION]);
- $row[MDATA_KEY_DURATION] = $formatter->format();
- }
- }
+ //-----------------------------------------------------------------
+ //processing the results
+ foreach ($rows as &$row) {
+ if (isset($row[MDATA_KEY_DURATION])) {
+ $formatter = new LengthFormatter($row[MDATA_KEY_DURATION]);
+ $row[MDATA_KEY_DURATION] = $formatter->format();
+ }
+ }
- return array(
- "sEcho" => intval($opts["sEcho"]),
- //"iTotalDisplayRecords" => intval($totalDisplayRows),
- "iTotalDisplayRecords" => intval($totalRows),
- "iTotalRecords" => intval($totalRows),
- "history" => $rows
- );
- }
+ return [
+ 'sEcho' => intval($opts['sEcho']),
+ //"iTotalDisplayRecords" => intval($totalDisplayRows),
+ 'iTotalDisplayRecords' => intval($totalRows),
+ 'iTotalRecords' => intval($totalRows),
+ 'history' => $rows,
+ ];
+ }
- public function getShowList($startDT, $endDT, $userId = null)
- {
+ public function getShowList($startDT, $endDT, $userId = null)
+ {
if (empty($userId)) {
- $user = Application_Model_User::getCurrentUser();
+ $user = Application_Model_User::getCurrentUser();
} else {
$user = new Application_Model_User($userId);
}
- $shows = Application_Model_Show::getShows($startDT, $endDT);
+ $shows = Application_Model_Show::getShows($startDT, $endDT);
- Logging::info($startDT->format(DEFAULT_TIMESTAMP_FORMAT));
- Logging::info($endDT->format(DEFAULT_TIMESTAMP_FORMAT));
+ Logging::info($startDT->format(DEFAULT_TIMESTAMP_FORMAT));
+ Logging::info($endDT->format(DEFAULT_TIMESTAMP_FORMAT));
- Logging::info($shows);
+ Logging::info($shows);
- //need to filter the list to only their shows
- if ((!empty($user)) && ($user->isHost())) {
+ //need to filter the list to only their shows
+ if ((!empty($user)) && ($user->isHost())) {
+ $showIds = [];
- $showIds = array();
+ foreach ($shows as $show) {
+ $showIds[] = $show['show_id'];
+ }
- foreach ($shows as $show) {
- $showIds[] = $show["show_id"];
- }
+ $showIds = array_unique($showIds);
+ Logging::info($showIds);
- $showIds = array_unique($showIds);
- Logging::info($showIds);
+ $hostRecords = CcShowHostsQuery::create()
+ ->filterByDbHost($user->getId())
+ ->filterByDbShow($showIds)
+ ->find($this->con)
+ ;
- $hostRecords = CcShowHostsQuery::create()
- ->filterByDbHost($user->getId())
- ->filterByDbShow($showIds)
- ->find($this->con);
+ $filteredShowIds = [];
- $filteredShowIds = array();
+ foreach ($hostRecords as $record) {
+ $filteredShowIds[] = $record->getDbShow();
+ }
- foreach($hostRecords as $record) {
- $filteredShowIds[] = $record->getDbShow();
- }
+ Logging::info($filteredShowIds);
- Logging::info($filteredShowIds);
+ $filteredShows = [];
- $filteredShows = array();
+ foreach ($shows as $show) {
+ if (in_array($show['show_id'], $filteredShowIds)) {
+ $filteredShows[] = $show;
+ }
+ }
+ } else {
+ $filteredShows = $shows;
+ }
- foreach($shows as $show) {
- if (in_array($show["show_id"], $filteredShowIds)) {
- $filteredShows[] = $show;
- }
- }
- }
- else {
- $filteredShows = $shows;
- }
+ $timezoneUTC = new DateTimeZone('UTC');
+ $timezoneLocal = new DateTimeZone($this->timezone);
- $timezoneUTC = new DateTimeZone("UTC");
- $timezoneLocal = new DateTimeZone($this->timezone);
+ foreach ($filteredShows as &$result) {
+ //need to display the results in the station's timezone.
+ $dateTime = new DateTime($result['starts'], $timezoneUTC);
+ $dateTime->setTimezone($timezoneLocal);
+ $result['starts'] = $dateTime->format(DEFAULT_TIMESTAMP_FORMAT);
- foreach ($filteredShows as &$result) {
+ $dateTime = new DateTime($result['ends'], $timezoneUTC);
+ $dateTime->setTimezone($timezoneLocal);
+ $result['ends'] = $dateTime->format(DEFAULT_TIMESTAMP_FORMAT);
+ }
+
+ return $filteredShows;
+ }
+
+ public function insertWebstreamMetadata($schedId, $startDT, $data)
+ {
+ $this->con->beginTransaction();
+
+ try {
+ $item = CcScheduleQuery::create()->findPK($schedId, $this->con);
+
+ //TODO figure out how to combine these all into 1 query.
+ $showInstance = $item->getCcShowInstances($this->con);
+ $show = $showInstance->getCcShow($this->con);
+
+ $webstream = $item->getCcWebstream($this->con);
+
+ $metadata = [];
+ $metadata['showname'] = $show->getDbName();
+ $metadata[MDATA_KEY_TITLE] = $data->title;
+ $metadata[MDATA_KEY_CREATOR] = $webstream->getDbName();
+
+ $history = new CcPlayoutHistory();
+ $history->setDbStarts($startDT);
+ $history->setDbEnds(null);
+ $history->setDbInstanceId($item->getDbInstanceId());
+
+ foreach ($metadata as $key => $val) {
+ $meta = new CcPlayoutHistoryMetaData();
+ $meta->setDbKey($key);
+ $meta->setDbValue($val);
+
+ $history->addCcPlayoutHistoryMetaData($meta);
+ }
+
+ $history->save($this->con);
+
+ $this->con->commit();
+ } catch (Exception $e) {
+ $this->con->rollback();
+
+ throw $e;
+ }
+ }
+
+ public function insertPlayedItem($schedId)
+ {
+ $this->con->beginTransaction();
+
+ try {
+ $item = CcScheduleQuery::create()->findPK($schedId, $this->con);
+ if (is_null($item)) {
+ throw new Exception('Invalid schedule id: ' . $schedId);
+ }
+
+ //TODO figure out how to combine these all into 1 query.
+ $showInstance = $item->getCcShowInstances($this->con);
+ $show = $showInstance->getCcShow($this->con);
+
+ $fileId = $item->getDbFileId();
+
+ //don't add webstreams
+ if (isset($fileId)) {
+ $metadata = [];
+ $metadata['showname'] = $show->getDbName();
+
+ $instanceEnd = $showInstance->getDbEnds(null);
+ $itemEnd = $item->getDbEnds(null);
+ $recordStart = $item->getDbStarts(null);
+ $recordEnd = ($instanceEnd < $itemEnd) ? $instanceEnd : $itemEnd;
+
+ //first check if this is a duplicate
+ // (caused by restarting liquidsoap)
+
+ $prevRecord = CcPlayoutHistoryQuery::create()
+ ->filterByDbStarts($recordStart)
+ ->filterByDbEnds($recordEnd)
+ ->filterByDbFileId($fileId)
+ ->findOne($this->con)
+ ;
+
+ if (empty($prevRecord)) {
+ $history = new CcPlayoutHistory();
+ $history->setDbFileId($fileId);
+ $history->setDbStarts($recordStart);
+ $history->setDbEnds($recordEnd);
+ $history->setDbInstanceId($item->getDbInstanceId());
+
+ foreach ($metadata as $key => $val) {
+ $meta = new CcPlayoutHistoryMetaData();
+ $meta->setDbKey($key);
+ $meta->setDbValue($val);
+
+ $history->addCcPlayoutHistoryMetaData($meta);
+ }
+
+ $history->save($this->con);
+ $this->con->commit();
+ }
+ }
+ } catch (Exception $e) {
+ $this->con->rollback();
+
+ throw $e;
+ }
+ }
+
+ // id is an id in cc_playout_history
+ public function makeHistoryItemForm($id, $populate = false)
+ {
+ try {
+ $form = new Application_Form_EditHistoryItem();
+ $template = $this->getConfiguredItemTemplate();
+ $required = $this->mandatoryItemFields();
+ $form->createFromTemplate($template['fields'], $required);
+
+ if ($populate) {
+ $formValues = [];
+
+ $historyRecord = CcPlayoutHistoryQuery::create()->findPk($id, $this->con);
+ $file = $historyRecord->getCcFiles($this->con);
+ $instance = $historyRecord->getCcShowInstances($this->con);
+
+ if (isset($instance)) {
+ $show = $instance->getCcShow($this->con);
+ $selOpts = [];
+ $instance_id = $instance->getDbId();
+ $selOpts[$instance_id] = $show->getDbName();
+ $form->populateShowInstances($selOpts, $instance_id);
+ }
+
+ if (isset($file)) {
+ $f = Application_Model_StoredFile::createWithFile($file, $this->con);
+ $filemd = $f->getDbColMetadata();
+ }
+ $metadata = [];
+ $mds = $historyRecord->getCcPlayoutHistoryMetaDatas();
+ foreach ($mds as $md) {
+ $metadata[$md->getDbKey()] = $md->getDbValue();
+ }
+
+ $prefix = Application_Form_EditHistoryItem::ID_PREFIX;
+ $formValues["{$prefix}id"] = $id;
+
+ foreach ($template['fields'] as $index => $field) {
+ $key = $field['name'];
+ $value = '';
+
+ if (in_array($key, $required)) {
+ $method = 'getDb' . ucfirst($key);
+ $value = $historyRecord->{$method}();
+ } elseif (isset($filemd) && $field['isFileMd']) {
+ $value = $filemd[$key];
+ } elseif (isset($metadata[$key])) {
+ $value = $metadata[$key];
+ }
+
+ //need to convert to the station's local time first.
+ if ($field['type'] == TEMPLATE_DATETIME && !is_null($value)) {
+ $timezoneUTC = new DateTimeZone('UTC');
+ $timezoneLocal = new DateTimeZone($this->timezone);
+
+ $dateTime = new DateTime($value, $timezoneUTC);
+ $dateTime->setTimezone($timezoneLocal);
+ $value = $dateTime->format(DEFAULT_TIMESTAMP_FORMAT);
+ }
+
+ $formValues["{$prefix}{$key}"] = $value;
+ }
+
+ $form->populate($formValues);
+ }
+
+ return $form;
+ } catch (Exception $e) {
+ Logging::info($e);
+
+ throw $e;
+ }
+ }
+
+ // id is an id in cc_files
+ public function makeHistoryFileForm($id)
+ {
+ try {
+ $form = new Application_Form_EditHistoryFile();
+ $template = $this->getConfiguredFileTemplate();
+ $required = $this->mandatoryFileFields();
+ $form->createFromTemplate($template['fields'], $required);
+
+ $file = Application_Model_StoredFile::RecallById($id, $this->con);
+ $md = $file->getDbColMetadata();
+
+ $prefix = Application_Form_EditHistoryFile::ID_PREFIX;
+ $formValues = [];
+ $formValues["{$prefix}id"] = $id;
+
+ foreach ($template['fields'] as $index => $field) {
+ $key = $field['name'];
+
+ if (in_array($key, $required)) {
+ continue;
+ }
+
+ $value = $md[$key];
+ $formValues["{$prefix}{$key}"] = $value;
+ }
+
+ $form->populate($formValues);
+
+ return $form;
+ } catch (Exception $e) {
+ Logging::info($e);
+
+ throw $e;
+ }
+ }
+
+ public function populateTemplateFile($values, $id)
+ {
+ $this->con->beginTransaction();
+
+ try {
+ $file = Application_Model_StoredFile::RecallById($id, $this->con);
+
+ $prefix = Application_Form_EditHistoryFile::ID_PREFIX;
+ $prefix_len = strlen($prefix);
+ $templateValues = $values[$prefix . 'template'];
+
+ $md = [];
+
+ foreach ($templateValues as $index => $value) {
+ $key = substr($index, $prefix_len);
+ $md[$key] = $value;
+ }
+
+ $file->setDbColMetadata($md);
+ $this->con->commit();
+ } catch (Exception $e) {
+ $this->con->rollback();
+
+ throw $e;
+ }
+ }
+
+ public function populateTemplateItem($values, $id = null, $instance_id = null)
+ {
+ $this->con->beginTransaction();
+
+ try {
+ $template = $this->getConfiguredItemTemplate();
+ $prefix = Application_Form_EditHistoryItem::ID_PREFIX;
+
+ if (isset($id)) {
+ $historyRecord = CcPlayoutHistoryQuery::create()->findPk($id, $this->con);
+ } else {
+ $historyRecord = new CcPlayoutHistory();
+ }
- //need to display the results in the station's timezone.
- $dateTime = new DateTime($result["starts"], $timezoneUTC);
- $dateTime->setTimezone($timezoneLocal);
- $result["starts"] = $dateTime->format(DEFAULT_TIMESTAMP_FORMAT);
+ if (isset($instance_id)) {
+ $historyRecord->setDbInstanceId($instance_id);
+ }
- $dateTime = new DateTime($result["ends"], $timezoneUTC);
- $dateTime->setTimezone($timezoneLocal);
- $result["ends"] = $dateTime->format(DEFAULT_TIMESTAMP_FORMAT);
+ $timezoneUTC = new DateTimeZone('UTC');
+ $timezoneLocal = new DateTimeZone($this->timezone);
- }
+ $dateTime = new DateTime($values[$prefix . 'starts'], $timezoneLocal);
+ $dateTime->setTimezone($timezoneUTC);
+ $historyRecord->setDbStarts($dateTime->format(DEFAULT_TIMESTAMP_FORMAT));
- return $filteredShows;
- }
+ $dateTime = new DateTime($values[$prefix . 'ends'], $timezoneLocal);
+ $dateTime->setTimezone($timezoneUTC);
+ $historyRecord->setDbEnds($dateTime->format(DEFAULT_TIMESTAMP_FORMAT));
+
+ $templateValues = $values[$prefix . 'template'];
- public function insertWebstreamMetadata($schedId, $startDT, $data) {
+ $file = $historyRecord->getCcFiles();
+
+ $md = [];
+ $metadata = [];
+ $fields = $template['fields'];
+ $required = $this->mandatoryItemFields();
+ $phpCasts = $this->getPhpCasts();
- $this->con->beginTransaction();
+ for ($i = 0, $len = count($fields); $i < $len; ++$i) {
+ $field = $fields[$i];
+ $key = $field['name'];
- try {
+ //required is delt with before this loop.
+ if (in_array($key, $required)) {
+ continue;
+ }
- $item = CcScheduleQuery::create()->findPK($schedId, $this->con);
+ $isFileMd = $field['isFileMd'];
+ $entry = $phpCasts[$field['type']]($templateValues[$prefix . $key]);
- //TODO figure out how to combine these all into 1 query.
- $showInstance = $item->getCcShowInstances($this->con);
- $show = $showInstance->getCcShow($this->con);
-
- $webstream = $item->getCcWebstream($this->con);
-
- $metadata = array();
- $metadata["showname"] = $show->getDbName();
- $metadata[MDATA_KEY_TITLE] = $data->title;
- $metadata[MDATA_KEY_CREATOR] = $webstream->getDbName();
-
- $history = new CcPlayoutHistory();
- $history->setDbStarts($startDT);
- $history->setDbEnds(null);
- $history->setDbInstanceId($item->getDbInstanceId());
-
- foreach ($metadata as $key => $val) {
- $meta = new CcPlayoutHistoryMetaData();
- $meta->setDbKey($key);
- $meta->setDbValue($val);
-
- $history->addCcPlayoutHistoryMetaData($meta);
- }
-
- $history->save($this->con);
-
- $this->con->commit();
- }
- catch (Exception $e) {
- $this->con->rollback();
- throw $e;
- }
- }
-
- public function insertPlayedItem($schedId) {
-
- $this->con->beginTransaction();
-
- try {
-
- $item = CcScheduleQuery::create()->findPK($schedId, $this->con);
- if (is_null($item)) {
- throw new Exception("Invalid schedule id: ".$schedId);
- }
-
- //TODO figure out how to combine these all into 1 query.
- $showInstance = $item->getCcShowInstances($this->con);
- $show = $showInstance->getCcShow($this->con);
-
- $fileId = $item->getDbFileId();
-
- //don't add webstreams
- if (isset($fileId)) {
-
- $metadata = array();
- $metadata["showname"] = $show->getDbName();
-
- $instanceEnd = $showInstance->getDbEnds(null);
- $itemEnd = $item->getDbEnds(null);
- $recordStart = $item->getDbStarts(null);
- $recordEnd = ($instanceEnd < $itemEnd) ? $instanceEnd : $itemEnd;
-
- //first check if this is a duplicate
- // (caused by restarting liquidsoap)
-
- $prevRecord = CcPlayoutHistoryQuery::create()
- ->filterByDbStarts($recordStart)
- ->filterByDbEnds($recordEnd)
- ->filterByDbFileId($fileId)
- ->findOne($this->con);
-
- if (empty($prevRecord)) {
-
- $history = new CcPlayoutHistory();
- $history->setDbFileId($fileId);
- $history->setDbStarts($recordStart);
- $history->setDbEnds($recordEnd);
- $history->setDbInstanceId($item->getDbInstanceId());
-
- foreach ($metadata as $key => $val) {
- $meta = new CcPlayoutHistoryMetaData();
- $meta->setDbKey($key);
- $meta->setDbValue($val);
-
- $history->addCcPlayoutHistoryMetaData($meta);
- }
-
- $history->save($this->con);
- $this->con->commit();
- }
- }
- }
- catch (Exception $e) {
- $this->con->rollback();
- throw $e;
- }
- }
-
- /* id is an id in cc_playout_history */
- public function makeHistoryItemForm($id, $populate=false) {
-
- try {
- $form = new Application_Form_EditHistoryItem();
- $template = $this->getConfiguredItemTemplate();
- $required = $this->mandatoryItemFields();
- $form->createFromTemplate($template["fields"], $required);
-
- if ($populate) {
- $formValues = array();
-
- $historyRecord = CcPlayoutHistoryQuery::create()->findPk($id, $this->con);
- $file = $historyRecord->getCcFiles($this->con);
- $instance = $historyRecord->getCcShowInstances($this->con);
-
- if (isset($instance)) {
- $show = $instance->getCcShow($this->con);
- $selOpts = array();
- $instance_id = $instance->getDbId();
- $selOpts[$instance_id] = $show->getDbName();
- $form->populateShowInstances($selOpts, $instance_id);
- }
-
- if (isset($file)) {
- $f = Application_Model_StoredFile::createWithFile($file, $this->con);
- $filemd = $f->getDbColMetadata();
- }
- $metadata = array();
- $mds = $historyRecord->getCcPlayoutHistoryMetaDatas();
- foreach ($mds as $md) {
- $metadata[$md->getDbKey()] = $md->getDbValue();
- }
-
- $prefix = Application_Form_EditHistoryItem::ID_PREFIX;
- $formValues["{$prefix}id"] = $id;
-
- foreach($template["fields"] as $index => $field) {
-
- $key = $field["name"];
- $value = "";
-
- if (in_array($key, $required)) {
-
- $method = "getDb".ucfirst($key);
- $value = $historyRecord->$method();
- }
- else if (isset($filemd) && $field["isFileMd"]) {
-
- $value = $filemd[$key];
- }
- else if (isset($metadata[$key])) {
- $value = $metadata[$key];
- }
-
- //need to convert to the station's local time first.
- if ($field["type"] == TEMPLATE_DATETIME && !is_null($value)) {
- $timezoneUTC = new DateTimeZone("UTC");
- $timezoneLocal = new DateTimeZone($this->timezone);
-
- $dateTime = new DateTime($value, $timezoneUTC);
- $dateTime->setTimezone($timezoneLocal);
- $value = $dateTime->format(DEFAULT_TIMESTAMP_FORMAT);
- }
-
- $formValues["$prefix{$key}"] = $value;
- }
-
- $form->populate($formValues);
- }
-
- return $form;
- }
- catch (Exception $e) {
- Logging::info($e);
- throw $e;
- }
- }
-
- /* id is an id in cc_files */
- public function makeHistoryFileForm($id) {
-
- try {
- $form = new Application_Form_EditHistoryFile();
- $template = $this->getConfiguredFileTemplate();
- $required = $this->mandatoryFileFields();
- $form->createFromTemplate($template["fields"], $required);
-
- $file = Application_Model_StoredFile::RecallById($id, $this->con);
- $md = $file->getDbColMetadata();
-
- $prefix = Application_Form_EditHistoryFile::ID_PREFIX;
- $formValues = array();
- $formValues["{$prefix}id"] = $id;
-
- foreach($template["fields"] as $index => $field) {
-
- $key = $field["name"];
-
- if (in_array($key, $required)) {
- continue;
- }
-
- $value = $md[$key];
- $formValues["$prefix{$key}"] = $value;
- }
-
- $form->populate($formValues);
-
- return $form;
- }
- catch (Exception $e) {
- Logging::info($e);
- throw $e;
- }
- }
-
- public function populateTemplateFile($values, $id) {
-
- $this->con->beginTransaction();
-
- try {
-
- $file = Application_Model_StoredFile::RecallById($id, $this->con);
-
- $prefix = Application_Form_EditHistoryFile::ID_PREFIX;
- $prefix_len = strlen($prefix);
- $templateValues = $values[$prefix."template"];
-
- $md = array();
-
- foreach ($templateValues as $index => $value) {
-
- $key = substr($index, $prefix_len);
- $md[$key] = $value;
- }
-
- $file->setDbColMetadata($md);
- $this->con->commit();
- }
- catch (Exception $e) {
- $this->con->rollback();
- throw $e;
- }
- }
-
- public function populateTemplateItem($values, $id=null, $instance_id=null) {
-
- $this->con->beginTransaction();
-
- try {
- $template = $this->getConfiguredItemTemplate();
- $prefix = Application_Form_EditHistoryItem::ID_PREFIX;
-
- if (isset($id)) {
- $historyRecord = CcPlayoutHistoryQuery::create()->findPk($id, $this->con);
- }
- else {
- $historyRecord = new CcPlayoutHistory();
- }
-
- if (isset($instance_id)) {
- $historyRecord->setDbInstanceId($instance_id);
- }
-
- $timezoneUTC = new DateTimeZone("UTC");
- $timezoneLocal = new DateTimeZone($this->timezone);
-
- $dateTime = new DateTime($values[$prefix."starts"], $timezoneLocal);
- $dateTime->setTimezone($timezoneUTC);
- $historyRecord->setDbStarts($dateTime->format(DEFAULT_TIMESTAMP_FORMAT));
-
- $dateTime = new DateTime($values[$prefix."ends"], $timezoneLocal);
- $dateTime->setTimezone($timezoneUTC);
- $historyRecord->setDbEnds($dateTime->format(DEFAULT_TIMESTAMP_FORMAT));
-
- $templateValues = $values[$prefix."template"];
-
- $file = $historyRecord->getCcFiles();
-
- $md = array();
- $metadata = array();
- $fields = $template["fields"];
- $required = $this->mandatoryItemFields();
- $phpCasts = $this->getPhpCasts();
-
- for ($i = 0, $len = count($fields); $i < $len; $i++) {
-
- $field = $fields[$i];
- $key = $field["name"];
-
- //required is delt with before this loop.
- if (in_array($key, $required)) {
- continue;
- }
-
- $isFileMd = $field["isFileMd"];
- $entry = $phpCasts[$field["type"]]($templateValues[$prefix.$key]);
-
- if ($isFileMd && isset($file)) {
- Logging::info("adding metadata associated to a file for {$key} = {$entry}");
- $md[$key] = $entry;
- }
- else {
- Logging::info("adding metadata for {$key} = {$entry}");
+ if ($isFileMd && isset($file)) {
+ Logging::info("adding metadata associated to a file for {$key} = {$entry}");
+ $md[$key] = $entry;
+ } else {
+ Logging::info("adding metadata for {$key} = {$entry}");
$metadata[$key] = $entry;
- }
- }
+ }
+ }
- if (count($md) > 0) {
- $f = Application_Model_StoredFile::createWithFile($file, $this->con);
- $f->setDbColMetadata($md);
- }
+ if (count($md) > 0) {
+ $f = Application_Model_StoredFile::createWithFile($file, $this->con);
+ $f->setDbColMetadata($md);
+ }
- //Use this array to update existing values.
- $mds = $historyRecord->getCcPlayoutHistoryMetaDatas();
- foreach ($mds as $md) {
- $prevmd[$md->getDbKey()] = $md;
- }
- foreach ($metadata as $key => $val) {
+ //Use this array to update existing values.
+ $mds = $historyRecord->getCcPlayoutHistoryMetaDatas();
+ foreach ($mds as $md) {
+ $prevmd[$md->getDbKey()] = $md;
+ }
+ foreach ($metadata as $key => $val) {
+ if (isset($prevmd[$key])) {
+ $meta = $prevmd[$key];
+ $meta->setDbValue($val);
+ } else {
+ $meta = new CcPlayoutHistoryMetaData();
+ $meta->setDbKey($key);
+ $meta->setDbValue($val);
- if (isset($prevmd[$key])) {
- $meta = $prevmd[$key];
- $meta->setDbValue($val);
- }
- else {
- $meta = new CcPlayoutHistoryMetaData();
- $meta->setDbKey($key);
- $meta->setDbValue($val);
+ $historyRecord->addCcPlayoutHistoryMetaData($meta);
+ }
+ }
- $historyRecord->addCcPlayoutHistoryMetaData($meta);
- }
- }
+ $historyRecord->save($this->con);
+ $this->con->commit();
+ } catch (Exception $e) {
+ $this->con->rollback();
- $historyRecord->save($this->con);
- $this->con->commit();
- }
- catch (Exception $e) {
- $this->con->rollback();
- throw $e;
- }
- }
+ throw $e;
+ }
+ }
- //start,end timestamp strings in local timezone.
- public function populateShowInstances($start, $end) {
- $timezoneLocal = new DateTimeZone($this->timezone);
+ //start,end timestamp strings in local timezone.
+ public function populateShowInstances($start, $end)
+ {
+ $timezoneLocal = new DateTimeZone($this->timezone);
- $startDT = new DateTime($start, $timezoneLocal);
- $endDT = new DateTime($end, $timezoneLocal);
+ $startDT = new DateTime($start, $timezoneLocal);
+ $endDT = new DateTime($end, $timezoneLocal);
- $shows = $this->getShowList($startDT, $endDT);
+ $shows = $this->getShowList($startDT, $endDT);
- $select = array();
+ $select = [];
- foreach ($shows as &$show) {
- $select[$show["instance_id"]] = $show["name"];
- }
+ foreach ($shows as &$show) {
+ $select[$show['instance_id']] = $show['name'];
+ }
- return $select;
- }
+ return $select;
+ }
- private function validateHistoryItem($instanceId, $form) {
+ private function validateHistoryItem($instanceId, $form)
+ {
+ /*
+ $userService = new Application_Service_UserService();
+ $currentUser = $userService->getCurrentUser();
- /*
- $userService = new Application_Service_UserService();
- $currentUser = $userService->getCurrentUser();
+ if (!$currentUser->isAdminOrPM()) {
+ if (empty($instance_id) ) {
- if (!$currentUser->isAdminOrPM()) {
- if (empty($instance_id) ) {
+ }
+ }
+ */
- }
- }
- */
+ $valid = true;
- $valid = true;
+ $recordStartsEl = $form->getElement('his_item_starts');
+ $recordStarts = $recordStartsEl->getValue();
+ $recordEndsEl = $form->getElement('his_item_starts');
+ $recordEnds = $recordEndsEl->getValue();
- $recordStartsEl = $form->getElement("his_item_starts");
- $recordStarts = $recordStartsEl->getValue();
- $recordEndsEl = $form->getElement("his_item_starts");
- $recordEnds = $recordEndsEl->getValue();
+ $timezoneLocal = new DateTimeZone($this->timezone);
- $timezoneLocal = new DateTimeZone($this->timezone);
+ $startDT = new DateTime($recordStarts, $timezoneLocal);
+ $endDT = new DateTime($recordEnds, $timezoneLocal);
- $startDT = new DateTime($recordStarts, $timezoneLocal);
- $endDT = new DateTime($recordEnds, $timezoneLocal);
+ if ($recordStarts > $recordEnds) {
+ $valid = false;
+ $recordEndsEl->addErrorMessage('End time must be after start time');
+ }
- if ($recordStarts > $recordEnds) {
- $valid = false;
- $recordEndsEl->addErrorMessage("End time must be after start time");
- }
+ if (isset($instanceId)) {
+ $instance = CcShowInstancesQuery::create()->findPk($instanceId, $this->con);
+ $inStartsDT = $instance->getDbStarts(null);
+ $inEndsDT = $instance->getDbEnds(null);
- if (isset($instanceId)) {
+ if ($startDT < $inStartsDT) {
+ $valid = false;
+ $form->addErrorMessage('History item begins before show.');
+ } elseif ($startDT > $inEndsDT) {
+ $valid = false;
+ $form->addErrorMessage('History item begins after show.');
+ }
+ }
- $instance = CcShowInstancesQuery::create()->findPk($instanceId, $this->con);
- $inStartsDT = $instance->getDbStarts(null);
- $inEndsDT = $instance->getDbEnds(null);
+ return $valid;
+ }
- if ($startDT < $inStartsDT) {
- $valid = false;
- $form->addErrorMessage("History item begins before show.");
- }
- else if ($startDT > $inEndsDT) {
- $valid = false;
- $form->addErrorMessage("History item begins after show.");
- }
- }
+ public function createPlayedItem($data)
+ {
+ try {
+ $form = $this->makeHistoryItemForm(null);
+ $history_id = $form->getElement('his_item_id');
+ $instanceId = isset($data['instance_id']) ? $data['instance_id'] : null;
+ $json = [];
- return $valid;
- }
+ if ($form->isValid($data) && $this->validateHistoryItem($instanceId, $form)) {
+ $history_id->setIgnore(true);
+ $values = $form->getValues();
- public function createPlayedItem($data) {
+ $this->populateTemplateItem($values, null, $instanceId);
+ } else {
+ $json['form'] = $form;
+ }
- try {
- $form = $this->makeHistoryItemForm(null);
- $history_id = $form->getElement("his_item_id");
- $instanceId = isset($data["instance_id"]) ? $data["instance_id"] : null;
- $json = array();
+ return $json;
+ } catch (Exception $e) {
+ throw $e;
+ }
+ }
- if ($form->isValid($data) && $this->validateHistoryItem($instanceId, $form)) {
+ // id is an id in cc_playout_history
+ public function editPlayedItem($data)
+ {
+ try {
+ $id = $data['his_item_id'];
+ $instanceId = isset($data['instance_id']) ? $data['instance_id'] : null;
+ $form = $this->makeHistoryItemForm($id);
+ $history_id = $form->getElement('his_item_id');
+ $history_id->setRequired(true);
- $history_id->setIgnore(true);
- $values = $form->getValues();
+ $json = [];
- $this->populateTemplateItem($values, null, $instanceId);
- }
- else {
- $json["form"] = $form;
- }
+ if ($form->isValid($data) && $this->validateHistoryItem($instanceId, $form)) {
+ $history_id->setIgnore(true);
+ $values = $form->getValues();
+ $this->populateTemplateItem($values, $id, $instanceId);
+ } else {
+ $json['form'] = SecurityHelper::htmlescape_recursive($form);
+ }
- return $json;
- }
- catch (Exception $e) {
- throw $e;
- }
- }
+ return $json;
+ } catch (Exception $e) {
+ throw $e;
+ }
+ }
- /* id is an id in cc_playout_history */
- public function editPlayedItem($data) {
+ // id is an id in cc_files
+ public function editPlayedFile($data)
+ {
+ try {
+ $id = $data['his_file_id'];
+ $form = $form = $this->makeHistoryFileForm($id);
+ $history_id = $form->getElement('his_file_id');
+ $history_id->setRequired(true);
- try {
- $id = $data["his_item_id"];
- $instanceId = isset($data["instance_id"]) ? $data["instance_id"] : null;
- $form = $this->makeHistoryItemForm($id);
- $history_id = $form->getElement("his_item_id");
- $history_id->setRequired(true);
+ $json = [];
- $json = array();
+ if ($form->isValid($data)) {
+ $history_id->setIgnore(true);
+ $values = $form->getValues();
- if ($form->isValid($data) && $this->validateHistoryItem($instanceId, $form)) {
+ $this->populateTemplateFile($values, $id);
+ } else {
+ $json['error'] = $form->getErrorMessages();
+ $json['error'] = SecurityHelper::htmlescape_recursive($json['error']);
+ }
- $history_id->setIgnore(true);
- $values = $form->getValues();
- $this->populateTemplateItem($values, $id, $instanceId);
- }
- else {
- $json["form"] = SecurityHelper::htmlescape_recursive($form);
- }
+ return $json;
+ $this->con->commit();
+ } catch (Exception $e) {
+ $this->con->rollback();
+ Logging::info($e);
- return $json;
- }
- catch (Exception $e) {
- throw $e;
- }
- }
-
- /* id is an id in cc_files */
- public function editPlayedFile($data) {
-
- try {
- $id = $data["his_file_id"];
- $form = $form = $this->makeHistoryFileForm($id);
- $history_id = $form->getElement("his_file_id");
- $history_id->setRequired(true);
-
- $json = array();
-
- if ($form->isValid($data)) {
- $history_id->setIgnore(true);
- $values = $form->getValues();
-
- $this->populateTemplateFile($values, $id);
- }
- else {
- $json["error"] = $form->getErrorMessages();
- $json["error"] = SecurityHelper::htmlescape_recursive($json["error"]);
- }
-
- return $json;
-
- $this->con->commit();
- }
- catch (Exception $e) {
- $this->con->rollback();
- Logging::info($e);
- throw $e;
- }
+ throw $e;
+ }
return $json;
- }
-
- /* id is an id in cc_playout_history */
- public function deletePlayedItem($id) {
-
- $this->con->beginTransaction();
-
- try {
-
- $record = CcPlayoutHistoryQuery::create()->findPk($id, $this->con);
- $record->delete($this->con);
-
- $this->con->commit();
- }
- catch (Exception $e) {
- $this->con->rollback();
- Logging::info($e);
- throw $e;
- }
- }
-
- /* id is an id in cc_playout_history */
- public function deletePlayedItems($ids) {
-
- $this->con->beginTransaction();
+ }
+
+ // id is an id in cc_playout_history
+ public function deletePlayedItem($id)
+ {
+ $this->con->beginTransaction();
+
+ try {
+ $record = CcPlayoutHistoryQuery::create()->findPk($id, $this->con);
+ $record->delete($this->con);
+
+ $this->con->commit();
+ } catch (Exception $e) {
+ $this->con->rollback();
+ Logging::info($e);
+
+ throw $e;
+ }
+ }
+
+ // id is an id in cc_playout_history
+ public function deletePlayedItems($ids)
+ {
+ $this->con->beginTransaction();
+
+ try {
+ $records = CcPlayoutHistoryQuery::create()->findPks($ids, $this->con);
+ $records->delete($this->con);
+
+ $this->con->commit();
+ } catch (Exception $e) {
+ $this->con->rollback();
+ Logging::info($e);
+
+ throw $e;
+ }
+ }
+
+ //---------------- Following code is for History Templates --------------------------//
+
+ public function getFieldTypes()
+ {
+ return [
+ //TEMPLATE_DATE,
+ //TEMPLATE_TIME,
+ //TEMPLATE_DATETIME,
+ TEMPLATE_STRING,
+ TEMPLATE_BOOLEAN,
+ TEMPLATE_INT,
+ TEMPLATE_FLOAT,
+ ];
+ }
+
+ private function getPhpCasts()
+ {
+ return [
+ TEMPLATE_DATE => 'strval',
+ TEMPLATE_TIME => 'strval',
+ TEMPLATE_DATETIME => 'strval',
+ TEMPLATE_STRING => 'strval',
+ TEMPLATE_BOOLEAN => 'intval', //boolval only exists in php 5.5+
+ TEMPLATE_INT => 'intval',
+ TEMPLATE_FLOAT => 'floatval',
+ ];
+ }
+
+ private function getSqlTypes()
+ {
+ return [
+ TEMPLATE_DATE => 'date',
+ TEMPLATE_TIME => 'time',
+ TEMPLATE_DATETIME => 'datetime',
+ TEMPLATE_STRING => 'text',
+ TEMPLATE_BOOLEAN => 'boolean',
+ TEMPLATE_INT => 'integer',
+ TEMPLATE_FLOAT => 'float',
+ ];
+ }
+
+ public function getFileMetadataTypes()
+ {
+ return [
+ ['name' => MDATA_KEY_TITLE, 'label' => _('Title'), 'type' => TEMPLATE_STRING],
+ ['name' => MDATA_KEY_CREATOR, 'label' => _('Creator'), 'type' => TEMPLATE_STRING],
+ ['name' => MDATA_KEY_SOURCE, 'label' => _('Album'), 'type' => TEMPLATE_STRING],
+ ['name' => MDATA_KEY_DURATION, 'label' => _('Length'), 'type' => TEMPLATE_STRING],
+ ['name' => MDATA_KEY_GENRE, 'label' => _('Genre'), 'type' => TEMPLATE_STRING],
+ ['name' => MDATA_KEY_MOOD, 'label' => _('Mood'), 'type' => TEMPLATE_STRING],
+ ['name' => MDATA_KEY_LABEL, 'label' => _('Label'), 'type' => TEMPLATE_STRING],
+ ['name' => MDATA_KEY_COMPOSER, 'label' => _('Composer'), 'type' => TEMPLATE_STRING],
+ ['name' => MDATA_KEY_ISRC, 'label' => _('ISRC'), 'type' => TEMPLATE_STRING],
+ ['name' => MDATA_KEY_COPYRIGHT, 'label' => _('Copyright'), 'type' => TEMPLATE_STRING],
+ ['name' => MDATA_KEY_YEAR, 'label' => _('Year'), 'type' => TEMPLATE_INT],
+ ['name' => MDATA_KEY_TRACKNUMBER, 'label' => _('Track'), 'type' => TEMPLATE_INT],
+ ['name' => MDATA_KEY_CONDUCTOR, 'label' => _('Conductor'), 'type' => TEMPLATE_STRING],
+ ['name' => MDATA_KEY_LANGUAGE, 'label' => _('Language'), 'type' => TEMPLATE_STRING],
+ ['name' => MDATA_KEY_TRACK_TYPE, 'label' => _('Track Type'), 'type' => TEMPLATE_STRING],
+ ];
+ }
+
+ public function mandatoryItemFields()
+ {
+ return ['starts', 'ends'];
+ }
+
+ public function mandatoryFileFields()
+ {
+ return ['played'];
+ }
+
+ private function defaultItemTemplate()
+ {
+ $template = [];
+ $fields = [];
+
+ $fields[] = ['name' => 'starts', 'label' => _('Start Time'), 'type' => TEMPLATE_DATETIME, 'isFileMd' => false];
+ $fields[] = ['name' => 'ends', 'label' => _('End Time'), 'type' => TEMPLATE_DATETIME, 'isFileMd' => false];
+ $fields[] = ['name' => MDATA_KEY_TITLE, 'label' => _('Title'), 'type' => TEMPLATE_STRING, 'isFileMd' => true]; //these fields can be populated from an associated file.
+ $fields[] = ['name' => MDATA_KEY_CREATOR, 'label' => _('Creator'), 'type' => TEMPLATE_STRING, 'isFileMd' => true];
+
+ $template['name'] = 'Log Sheet ' . date(DEFAULT_TIMESTAMP_FORMAT) . ' Template';
+ $template['fields'] = $fields;
+
+ return $template;
+ }
+
+ // Default File Summary Template. Taken from The Czech radio requirements (customer requested this in the past).
+ private function defaultFileTemplate()
+ {
+ $template = [];
+ $fields = [];
+
+ $fields[] = ['name' => MDATA_KEY_TITLE, 'label' => _('Title'), 'type' => TEMPLATE_STRING, 'isFileMd' => true];
+ $fields[] = ['name' => MDATA_KEY_CREATOR, 'label' => _('Creator'), 'type' => TEMPLATE_STRING, 'isFileMd' => true];
+ $fields[] = ['name' => 'played', 'label' => _('Played'), 'type' => TEMPLATE_INT, 'isFileMd' => false];
+ $fields[] = ['name' => MDATA_KEY_DURATION, 'label' => _('Length'), 'type' => TEMPLATE_STRING, 'isFileMd' => true];
+ $fields[] = ['name' => MDATA_KEY_COMPOSER, 'label' => _('Composer'), 'type' => TEMPLATE_STRING, 'isFileMd' => true];
+ $fields[] = ['name' => MDATA_KEY_COPYRIGHT, 'label' => _('Copyright'), 'type' => TEMPLATE_STRING, 'isFileMd' => true];
+
+ $template['name'] = 'File Summary ' . date(DEFAULT_TIMESTAMP_FORMAT) . ' Template';
+ $template['fields'] = $fields;
+
+ return $template;
+ }
+
+ public function loadTemplate($id)
+ {
+ try {
+ if (!is_numeric($id)) {
+ throw new Exception("Error: {$id} is not numeric.");
+ }
+
+ $template = CcPlayoutHistoryTemplateQuery::create()->findPk($id, $this->con);
+
+ if (empty($template)) {
+ throw new Exception("Error: Template {$id} does not exist.");
+ }
+
+ $c = new Criteria();
+ $c->addAscendingOrderByColumn(CcPlayoutHistoryTemplateFieldPeer::POSITION);
+ $config = $template->getCcPlayoutHistoryTemplateFields($c, $this->con);
+ $fields = [];
+
+ foreach ($config as $item) {
+ $fields[] = [
+ 'name' => $item->getDbName(),
+ 'label' => $item->getDbLabel(),
+ 'type' => $item->getDbType(),
+ 'isFileMd' => $item->getDbIsFileMD(),
+ 'id' => $item->getDbId(),
+ ];
+ }
+
+ $data = [];
+ $data['id'] = $template->getDbId();
+ $data['name'] = $template->getDbName();
+ $data['fields'] = $fields;
+ $data['type'] = $template->getDbType();
+
+ return $data;
+ } catch (Exception $e) {
+ throw $e;
+ }
+ }
+
+ public function getItemTemplate($id)
+ {
+ if (is_numeric($id)) {
+ Logging::info("template id is: {$id}");
+ $template = $this->loadTemplate($id);
+ } else {
+ Logging::info('Using default template');
+ $template = $this->defaultItemTemplate();
+ }
+
+ return $template;
+ }
+
+ public function getTemplates($type)
+ {
+ $list = [];
+
+ try {
+ $query = CcPlayoutHistoryTemplateQuery::create()
+ ->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)
+ ;
+
+ if (isset($type)) {
+ $templates = $query->findByDbType($type);
+ } else {
+ $templates = $query->find();
+ }
+
+ foreach ($templates as $template) {
+ $list[$template->getDbId()] = $template->getDbName();
+ }
+
+ return $list;
+ } catch (Exception $e) {
+ throw $e;
+ }
+ }
+
+ public function getListItemTemplates()
+ {
+ return $this->getTemplates(self::TEMPLATE_TYPE_ITEM);
+ }
+
+ public function getFileTemplates()
+ {
+ return $this->getTemplates(self::TEMPLATE_TYPE_FILE);
+ }
+
+ private function datatablesColumns($fields)
+ {
+ $columns = [];
+
+ foreach ($fields as $field) {
+ $label = $field['label'];
+ $key = $field['name'];
+
+ $columns[] = [
+ 'sTitle' => $label,
+ 'mDataProp' => $key,
+ 'sClass' => "his_{$key}",
+ 'sDataType' => $field['type'],
+ ];
+ }
+
+ return $columns;
+ }
+
+ public function getDatatablesLogSheetColumns()
+ {
+ //need to prepend a checkbox column.
+ $checkbox = [
+ 'sTitle' => '',
+ 'mDataProp' => 'checkbox',
+ 'sClass' => 'his_checkbox',
+ 'bSortable' => false,
+ ];
+
+ try {
+ $template = $this->getConfiguredItemTemplate();
+ $fields = $template['fields'];
+
+ $columns = $this->datatablesColumns($fields);
+ array_unshift($columns, $checkbox);
+
+ return $columns;
+ } catch (Exception $e) {
+ throw $e;
+ }
+ }
+
+ public function getDatatablesFileSummaryColumns()
+ {
+ try {
+ $template = $this->getConfiguredFileTemplate();
+
+ return $this->datatablesColumns($template['fields']);
+ } catch (Exception $e) {
+ throw $e;
+ }
+ }
+
+ public function getConfiguredItemTemplate()
+ {
+ try {
+ $id = Application_Model_Preference::GetHistoryItemTemplate();
+
+ if (is_numeric($id)) {
+ $template = $this->loadTemplate($id);
+ } else {
+ $template = $this->defaultItemTemplate();
+ }
+
+ return $template;
+ } catch (Exception $e) {
+ throw $e;
+ }
+ }
+
+ public function setConfiguredItemTemplate($id)
+ {
+ try {
+ Application_Model_Preference::SetHistoryItemTemplate($id);
+ } catch (Exception $e) {
+ throw $e;
+ }
+ }
+
+ public function getConfiguredFileTemplate()
+ {
+ try {
+ $id = Application_Model_Preference::GetHistoryFileTemplate();
+
+ if (is_numeric($id)) {
+ $template = $this->loadTemplate($id);
+ } else {
+ $template = $this->defaultFileTemplate();
+ }
+
+ return $template;
+ } catch (Exception $e) {
+ throw $e;
+ }
+ }
+
+ public function setConfiguredFileTemplate($id)
+ {
+ try {
+ Application_Model_Preference::SetHistoryFileTemplate($id);
+ } catch (Exception $e) {
+ throw $e;
+ }
+ }
+
+ public function setConfiguredTemplate($id)
+ {
+ try {
+ $template = $this->loadTemplate($id);
+ $type = $template['type'];
+
+ $setTemplate = 'setConfigured' . ucfirst($type) . 'Template';
+
+ $this->{$setTemplate}($id);
+ } catch (Exception $e) {
+ throw $e;
+ }
+ }
+
+ public function getConfiguredTemplateIds()
+ {
+ try {
+ $id = Application_Model_Preference::GetHistoryItemTemplate();
+ $id2 = Application_Model_Preference::GetHistoryFileTemplate();
+
+ $configured = [];
+
+ if (is_numeric($id)) {
+ $configured[] = $id;
+ }
+
+ if (is_numeric($id2)) {
+ $configured[] = $id2;
+ }
+
+ return $configured;
+ } catch (Exception $e) {
+ throw $e;
+ }
+ }
+
+ public function createTemplate($config)
+ {
+ $this->con->beginTransaction();
+
+ try {
+ $type = $config['type'];
+
+ $method = 'default' . ucfirst($type) . 'Template';
+ $default = $this->{$method}();
+
+ $name = isset($config['name']) ? $config['name'] : $default['name'];
+ $fields = isset($config['fields']) ? $config['fields'] : $default['fields'];
+
+ $doSetDefault = isset($config['setDefault']) ? $config['setDefault'] : false;
+
+ $template = new CcPlayoutHistoryTemplate();
+ $template->setDbName($name);
+ $template->setDbType($type);
+
+ foreach ($fields as $index => $field) {
+ $isMd = ($field['isFileMd'] == 'true') ? true : false;
+
+ $templateField = new CcPlayoutHistoryTemplateField();
+ $templateField->setDbName($field['name']);
+ $templateField->setDbLabel($field['label']);
+ $templateField->setDbType($field['type']);
+ $templateField->setDbIsFileMD($isMd);
+ $templateField->setDbPosition($index);
+
+ $template->addCcPlayoutHistoryTemplateField($templateField);
+ }
+
+ $template->save($this->con);
+
+ if ($doSetDefault) {
+ $this->setConfiguredItemTemplate($template->getDbid());
+ }
+
+ $this->con->commit();
+
+ return $template->getDbid();
+ } catch (Exception $e) {
+ $this->con->rollback();
+
+ throw $e;
+ }
+ }
- try {
+ public function updateItemTemplate($id, $name, $fields, $doSetDefault = false)
+ {
+ $this->con->beginTransaction();
- $records = CcPlayoutHistoryQuery::create()->findPks($ids, $this->con);
- $records->delete($this->con);
+ try {
+ $template = CcPlayoutHistoryTemplateQuery::create()->findPk($id, $this->con);
+ $template->setDbName($name);
- $this->con->commit();
- }
- catch (Exception $e) {
- $this->con->rollback();
- Logging::info($e);
- throw $e;
- }
- }
+ if (count($fields) === 0) {
+ $t = $this->defaultItemTemplate();
+ $fields = $t['fields'];
+ }
+ $template->getCcPlayoutHistoryTemplateFields()->delete($this->con);
- //---------------- Following code is for History Templates --------------------------//
+ foreach ($fields as $index => $field) {
+ $isMd = ($field['isFileMd'] == 'true') ? true : false;
- public function getFieldTypes() {
+ $templateField = new CcPlayoutHistoryTemplateField();
+ $templateField->setDbName($field['name']);
+ $templateField->setDbType($field['type']);
+ $templateField->setDbLabel($field['label']);
+ $templateField->setDbIsFileMD($isMd);
+ $templateField->setDbPosition($index);
- $fields = array(
- //TEMPLATE_DATE,
- //TEMPLATE_TIME,
- //TEMPLATE_DATETIME,
- TEMPLATE_STRING,
- TEMPLATE_BOOLEAN,
- TEMPLATE_INT,
- TEMPLATE_FLOAT,
- );
+ $template->addCcPlayoutHistoryTemplateField($templateField);
+ }
- return $fields;
- }
+ $template->save($this->con);
- private function getPhpCasts() {
+ if ($doSetDefault) {
+ $this->setConfiguredItemTemplate($template->getDbid());
+ }
- $fields = array(
- TEMPLATE_DATE => "strval",
- TEMPLATE_TIME => "strval",
- TEMPLATE_DATETIME => "strval",
- TEMPLATE_STRING => "strval",
- TEMPLATE_BOOLEAN => "intval", //boolval only exists in php 5.5+
- TEMPLATE_INT => "intval",
- TEMPLATE_FLOAT => "floatval",
- );
+ $this->con->commit();
+ } catch (Exception $e) {
+ $this->con->rollback();
- return $fields;
- }
+ throw $e;
+ }
+ }
- private function getSqlTypes() {
+ public function deleteTemplate($id)
+ {
+ $this->con->beginTransaction();
- $fields = array(
- TEMPLATE_DATE => "date",
- TEMPLATE_TIME => "time",
- TEMPLATE_DATETIME => "datetime",
- TEMPLATE_STRING => "text",
- TEMPLATE_BOOLEAN => "boolean",
- TEMPLATE_INT => "integer",
- TEMPLATE_FLOAT => "float",
- );
+ try {
+ $template = CcPlayoutHistoryTemplateQuery::create()->findPk($id, $this->con);
+ $template->delete($this->con);
- return $fields;
- }
+ $this->con->commit();
+ } catch (Exception $e) {
+ $this->con->rollback();
- public function getFileMetadataTypes() {
-
- $fileMD = array(
- array("name"=> MDATA_KEY_TITLE, "label"=> _("Title"), "type"=> TEMPLATE_STRING),
- array("name"=> MDATA_KEY_CREATOR, "label"=> _("Creator"), "type"=> TEMPLATE_STRING),
- array("name"=> MDATA_KEY_SOURCE, "label"=> _("Album"), "type"=> TEMPLATE_STRING),
- array("name"=> MDATA_KEY_DURATION, "label"=> _("Length"), "type"=> TEMPLATE_STRING),
- array("name"=> MDATA_KEY_GENRE, "label"=> _("Genre"), "type"=> TEMPLATE_STRING),
- array("name"=> MDATA_KEY_MOOD, "label"=> _("Mood"), "type"=> TEMPLATE_STRING),
- array("name"=> MDATA_KEY_LABEL, "label"=> _("Label"), "type"=> TEMPLATE_STRING),
- array("name"=> MDATA_KEY_COMPOSER, "label"=> _("Composer"), "type"=> TEMPLATE_STRING),
- array("name"=> MDATA_KEY_ISRC, "label"=> _("ISRC"), "type"=> TEMPLATE_STRING),
- array("name"=> MDATA_KEY_COPYRIGHT, "label"=> _("Copyright"), "type"=> TEMPLATE_STRING),
- array("name"=> MDATA_KEY_YEAR, "label"=> _("Year"), "type"=> TEMPLATE_INT),
- array("name"=> MDATA_KEY_TRACKNUMBER, "label"=> _("Track"), "type"=> TEMPLATE_INT),
- array("name"=> MDATA_KEY_CONDUCTOR, "label"=> _("Conductor"), "type"=> TEMPLATE_STRING),
- array("name"=> MDATA_KEY_LANGUAGE, "label"=> _("Language"), "type"=> TEMPLATE_STRING),
- array("name"=> MDATA_KEY_TRACK_TYPE, "label"=> _("Track Type"), "type"=> TEMPLATE_STRING),
- );
-
- return $fileMD;
- }
-
- public function mandatoryItemFields() {
-
- $fields = array("starts", "ends");
-
- return $fields;
- }
-
- public function mandatoryFileFields() {
-
- $fields = array("played");
-
- return $fields;
- }
-
- private function defaultItemTemplate() {
-
- $template = array();
- $fields = array();
-
- $fields[] = array("name" => "starts", "label"=> _("Start Time"),"type" => TEMPLATE_DATETIME, "isFileMd" => false);
- $fields[] = array("name" => "ends", "label"=> _("End Time"), "type" => TEMPLATE_DATETIME, "isFileMd" => false);
- $fields[] = array("name" => MDATA_KEY_TITLE, "label"=> _("Title"), "type" => TEMPLATE_STRING, "isFileMd" => true); //these fields can be populated from an associated file.
- $fields[] = array("name" => MDATA_KEY_CREATOR, "label"=> _("Creator"), "type" => TEMPLATE_STRING, "isFileMd" => true);
-
- $template["name"] = "Log Sheet ".date(DEFAULT_TIMESTAMP_FORMAT)." Template";
- $template["fields"] = $fields;
-
- return $template;
- }
-
- /*
- * Default File Summary Template. Taken from The Czech radio requirements (customer requested this in the past).
- */
- private function defaultFileTemplate() {
-
- $template = array();
- $fields = array();
-
- $fields[] = array("name" => MDATA_KEY_TITLE, "label"=> _("Title"), "type" => TEMPLATE_STRING, "isFileMd" => true);
- $fields[] = array("name" => MDATA_KEY_CREATOR, "label"=> _("Creator"), "type" => TEMPLATE_STRING, "isFileMd" => true);
- $fields[] = array("name" => "played", "label"=> _("Played"), "type" => TEMPLATE_INT, "isFileMd" => false);
- $fields[] = array("name" => MDATA_KEY_DURATION, "label"=> _("Length"), "type" => TEMPLATE_STRING, "isFileMd" => true);
- $fields[] = array("name" => MDATA_KEY_COMPOSER, "label"=> _("Composer"), "type" => TEMPLATE_STRING, "isFileMd" => true);
- $fields[] = array("name" => MDATA_KEY_COPYRIGHT, "label"=> _("Copyright"), "type" => TEMPLATE_STRING, "isFileMd" => true);
-
- $template["name"] = "File Summary ".date(DEFAULT_TIMESTAMP_FORMAT)." Template";
- $template["fields"] = $fields;
-
- return $template;
- }
-
- public function loadTemplate($id) {
-
- try {
-
- if (!is_numeric($id)) {
- throw new Exception("Error: $id is not numeric.");
- }
-
- $template = CcPlayoutHistoryTemplateQuery::create()->findPk($id, $this->con);
-
- if (empty($template)) {
- throw new Exception("Error: Template $id does not exist.");
- }
-
- $c = new Criteria();
- $c->addAscendingOrderByColumn(CcPlayoutHistoryTemplateFieldPeer::POSITION);
- $config = $template->getCcPlayoutHistoryTemplateFields($c, $this->con);
- $fields = array();
-
- foreach ($config as $item) {
-
- $fields[] = array(
- "name" => $item->getDbName(),
- "label" => $item->getDbLabel(),
- "type" => $item->getDbType(),
- "isFileMd" => $item->getDbIsFileMD(),
- "id" => $item->getDbId()
- );
- }
-
- $data = array();
- $data["id"] = $template->getDbId();
- $data["name"] = $template->getDbName();
- $data["fields"] = $fields;
- $data["type"] = $template->getDbType();
-
- return $data;
- }
- catch (Exception $e) {
- throw $e;
- }
- }
-
- public function getItemTemplate($id) {
-
- if (is_numeric($id)) {
- Logging::info("template id is: $id");
- $template = $this->loadTemplate($id);
- }
- else {
- Logging::info("Using default template");
- $template = $this->defaultItemTemplate();
- }
-
- return $template;
- }
-
- public function getTemplates($type) {
-
- $list = array();
-
- try {
-
- $query = CcPlayoutHistoryTemplateQuery::create()
- ->setFormatter(ModelCriteria::FORMAT_ON_DEMAND);
-
- if (isset($type)) {
- $templates = $query->findByDbType($type);
- }
- else {
- $templates = $query->find();
- }
-
- foreach ($templates as $template) {
- $list[$template->getDbId()] = $template->getDbName();
- }
-
- return $list;
- }
- catch (Exception $e) {
- throw $e;
- }
- }
-
- public function getListItemTemplates() {
- return $this->getTemplates(self::TEMPLATE_TYPE_ITEM);
- }
-
- public function getFileTemplates() {
- return $this->getTemplates(self::TEMPLATE_TYPE_FILE);
- }
-
- private function datatablesColumns($fields) {
-
- $columns = array();
-
- foreach ($fields as $field) {
-
- $label = $field["label"];
- $key = $field["name"];
-
- $columns[] = array(
- "sTitle"=> $label,
- "mDataProp"=> $key,
- "sClass"=> "his_{$key}",
- "sDataType"=> $field["type"]
- );
- }
-
- return $columns;
- }
-
- public function getDatatablesLogSheetColumns() {
-
- //need to prepend a checkbox column.
- $checkbox = array(
- "sTitle"=> "",
- "mDataProp"=> "checkbox",
- "sClass"=> "his_checkbox",
- "bSortable"=> false
- );
-
- try {
- $template = $this->getConfiguredItemTemplate();
- $fields = $template["fields"];
-
- $columns = $this->datatablesColumns($fields);
- array_unshift($columns, $checkbox);
-
- return $columns;
- }
- catch (Exception $e) {
- throw $e;
- }
- }
-
- public function getDatatablesFileSummaryColumns() {
-
- try {
- $template = $this->getConfiguredFileTemplate();
- return $this->datatablesColumns($template["fields"]);
- }
- catch (Exception $e) {
- throw $e;
- }
- }
-
- public function getConfiguredItemTemplate() {
-
- try {
- $id = Application_Model_Preference::GetHistoryItemTemplate();
-
- if (is_numeric($id)) {
- $template = $this->loadTemplate($id);
- }
- else {
- $template = $this->defaultItemTemplate();
- }
- return $template;
- }
- catch (Exception $e) {
- throw $e;
- }
- }
-
- public function setConfiguredItemTemplate($id) {
- try {
- Application_Model_Preference::SetHistoryItemTemplate($id);
- }
- catch (Exception $e) {
- throw $e;
- }
- }
-
- public function getConfiguredFileTemplate() {
-
- try {
- $id = Application_Model_Preference::GetHistoryFileTemplate();
-
- if (is_numeric($id)) {
- $template = $this->loadTemplate($id);
- }
- else {
- $template = $this->defaultFileTemplate();
- }
- return $template;
- }
- catch (Exception $e) {
- throw $e;
- }
- }
-
- public function setConfiguredFileTemplate($id) {
- try {
- Application_Model_Preference::SetHistoryFileTemplate($id);
- }
- catch (Exception $e) {
- throw $e;
- }
- }
-
- public function setConfiguredTemplate($id) {
- try {
-
- $template = $this->loadTemplate($id);
- $type = $template["type"];
-
- $setTemplate = "setConfigured".ucfirst($type)."Template";
-
- $this->$setTemplate($id);
- }
- catch (Exception $e) {
- throw $e;
- }
- }
-
- public function getConfiguredTemplateIds() {
-
- try {
- $id = Application_Model_Preference::GetHistoryItemTemplate();
- $id2 = Application_Model_Preference::GetHistoryFileTemplate();
-
- $configured = array();
-
- if (is_numeric($id)) {
- $configured[] = $id;
- }
-
- if (is_numeric($id2)) {
- $configured[] = $id2;
- }
-
- return $configured;
- }
- catch (Exception $e) {
- throw $e;
- }
- }
-
- public function createTemplate($config) {
-
- $this->con->beginTransaction();
-
- try {
-
- $type = $config["type"];
-
- $method = "default".ucfirst($type)."Template";
- $default = $this->$method();
-
- $name = isset($config["name"]) ? $config["name"] : $default["name"];
- $fields = isset($config["fields"]) ? $config["fields"] : $default["fields"];
-
- $doSetDefault = isset($config['setDefault']) ? $config['setDefault'] : false;
-
- $template = new CcPlayoutHistoryTemplate();
- $template->setDbName($name);
- $template->setDbType($type);
-
- foreach ($fields as $index=>$field) {
-
- $isMd = ($field["isFileMd"] == 'true') ? true : false;
-
- $templateField = new CcPlayoutHistoryTemplateField();
- $templateField->setDbName($field["name"]);
- $templateField->setDbLabel($field["label"]);
- $templateField->setDbType($field["type"]);
- $templateField->setDbIsFileMD($isMd);
- $templateField->setDbPosition($index);
-
- $template->addCcPlayoutHistoryTemplateField($templateField);
- }
-
- $template->save($this->con);
-
- if ($doSetDefault) {
- $this->setConfiguredItemTemplate($template->getDbid());
- }
-
- $this->con->commit();
-
- return $template->getDbid();
- }
- catch (Exception $e) {
- $this->con->rollback();
- throw $e;
- }
- }
-
- public function updateItemTemplate($id, $name, $fields, $doSetDefault=false) {
-
- $this->con->beginTransaction();
-
- try {
-
- $template = CcPlayoutHistoryTemplateQuery::create()->findPk($id, $this->con);
- $template->setDbName($name);
-
- if (count($fields) === 0) {
- $t = $this->defaultItemTemplate();
- $fields = $t["fields"];
- }
-
- $template->getCcPlayoutHistoryTemplateFields()->delete($this->con);
-
- foreach ($fields as $index=>$field) {
-
- $isMd = ($field["isFileMd"] == 'true') ? true : false;
-
- $templateField = new CcPlayoutHistoryTemplateField();
- $templateField->setDbName($field["name"]);
- $templateField->setDbType($field["type"]);
- $templateField->setDbLabel($field["label"]);
- $templateField->setDbIsFileMD($isMd);
- $templateField->setDbPosition($index);
-
- $template->addCcPlayoutHistoryTemplateField($templateField);
- }
-
- $template->save($this->con);
-
- if ($doSetDefault) {
- $this->setConfiguredItemTemplate($template->getDbid());
- }
-
- $this->con->commit();
- }
- catch (Exception $e) {
- $this->con->rollback();
- throw $e;
- }
- }
-
- public function deleteTemplate($id) {
-
- $this->con->beginTransaction();
-
- try {
-
- $template = CcPlayoutHistoryTemplateQuery::create()->findPk($id, $this->con);
- $template->delete($this->con);
-
- $this->con->commit();
- }
- catch (Exception $e) {
- $this->con->rollback();
- throw $e;
- }
- }
+ throw $e;
+ }
+ }
}
diff --git a/legacy/application/services/MediaService.php b/legacy/application/services/MediaService.php
index dc6a99a01..de5041a5d 100644
--- a/legacy/application/services/MediaService.php
+++ b/legacy/application/services/MediaService.php
@@ -2,8 +2,7 @@
class Application_Service_MediaService
{
-
- const PENDING_FILE_TIMEOUT_SECONDS = 3600;
+ public const PENDING_FILE_TIMEOUT_SECONDS = 3600;
/**
* @var array store an internal array of the pending files so we don't have
@@ -12,24 +11,27 @@ class Application_Service_MediaService
private static $_pendingFiles;
/** Move (or copy) a file to the stor/organize directory and send it off to the
- analyzer to be processed.
+ * analyzer to be processed.
+ *
* @param $callbackUrl
* @param $filePath string Path to the local file to import to the library
- * @param $originalFilename string The original filename, if you want it to be preserved after import.
- * @param $ownerId string The ID of the user that will own the file inside Airtime.
+ * @param $originalFilename string The original filename, if you want it to be preserved after import
+ * @param $ownerId string The ID of the user that will own the file inside Airtime
* @param $copyFile bool True if you want to copy the file to the "organize" directory, false if you want to move it (default)
- * @return Ambigous
+ *
* @throws Exception
+ *
+ * @return Ambigous
*/
public static function importFileToLibrary($callbackUrl, $filePath, $originalFilename, $ownerId, $copyFile)
{
$CC_CONFIG = Config::getConfig();
- $apiKey = $CC_CONFIG["apiKey"][0];
+ $apiKey = $CC_CONFIG['apiKey'][0];
- $importedStorageDirectory = "";
- if ($CC_CONFIG["current_backend"] == "file") {
+ $importedStorageDirectory = '';
+ if ($CC_CONFIG['current_backend'] == 'file') {
$storDir = Application_Model_MusicDir::getStorDir();
- $importedStorageDirectory = $storDir->getDirectory() . "/imported/" . $ownerId;
+ $importedStorageDirectory = $storDir->getDirectory() . '/imported/' . $ownerId;
}
//Copy the temporary file over to the "organize" folder so that it's off our webserver
@@ -38,24 +40,28 @@ class Application_Service_MediaService
//Dispatch a message to libretime-analyzer through RabbitMQ,
//notifying it that there's a new upload to process!
- $storageBackend = new ProxyStorageBackend($CC_CONFIG["current_backend"]);
- Application_Model_RabbitMq::SendMessageToAnalyzer($newTempFilePath,
- $importedStorageDirectory, basename($originalFilename),
- $callbackUrl, $apiKey,
- $CC_CONFIG["current_backend"],
- $storageBackend->getFilePrefix());
+ $storageBackend = new ProxyStorageBackend($CC_CONFIG['current_backend']);
+ Application_Model_RabbitMq::SendMessageToAnalyzer(
+ $newTempFilePath,
+ $importedStorageDirectory,
+ basename($originalFilename),
+ $callbackUrl,
+ $apiKey,
+ $CC_CONFIG['current_backend'],
+ $storageBackend->getFilePrefix()
+ );
return $newTempFilePath;
}
-
/**
* @param $fileId
* @param bool $inline Set the Content-Disposition header to inline to prevent a download dialog from popping up (or attachment if false)
+ *
* @throws Exception
* @throws LibreTimeFileNotFoundException
*/
- public static function streamFileDownload($fileId, $inline=false)
+ public static function streamFileDownload($fileId, $inline = false)
{
$media = Application_Model_StoredFile::RecallById($fileId);
if ($media == null) {
@@ -64,7 +70,7 @@ class Application_Service_MediaService
// Make sure we don't have some wrong result because of caching
clearstatcache();
- $filePath = "";
+ $filePath = '';
if ($media->getPropelOrm()->isValidPhysicalFile()) {
$filename = $media->getPropelOrm()->getFilename();
@@ -96,10 +102,12 @@ class Application_Service_MediaService
do {
//Read from $filePath and stream it to the browser.
$filePath = array_shift($filePaths);
+
try {
- $size= $media->getFileSize();
+ $size = $media->getFileSize();
$mimeType = $media->getPropelOrm()->getDbMime();
Application_Common_FileIO::smartReadFile($filePath, $size, $mimeType);
+
break; //Break out of the loop if we successfully read the file!
} catch (LibreTimeFileNotFoundException $e) {
//If we have no alternate filepaths left, then let the exception bubble up.
@@ -111,43 +119,44 @@ class Application_Service_MediaService
} while (sizeof($filePaths) > 0);
exit;
-
- } else {
- throw new LibreTimeFileNotFoundException($filePath);
}
+
+ throw new LibreTimeFileNotFoundException($filePath);
}
/**
* Check if there are any files that have been stuck
- * in Pending status for over an hour
+ * in Pending status for over an hour.
*
* @return bool true if there are any files stuck pending,
* otherwise false
*/
- public static function areFilesStuckInPending() {
+ public static function areFilesStuckInPending()
+ {
$oneHourAgo = gmdate(DEFAULT_TIMESTAMP_FORMAT, (microtime(true) - self::PENDING_FILE_TIMEOUT_SECONDS));
self::$_pendingFiles = CcFilesQuery::create()
->filterByDbImportStatus(CcFiles::IMPORT_STATUS_PENDING)
->filterByDbUtime($oneHourAgo, Criteria::LESS_EQUAL)
- ->find();
+ ->find()
+ ;
$pendingEpisodes = Application_Service_PodcastEpisodeService::getStuckPendingImports();
+
return !self::$_pendingFiles->isEmpty() || !empty($pendingEpisodes);
}
/**
- * Clean up stuck imports by changing their import status to Failed
+ * Clean up stuck imports by changing their import status to Failed.
*/
- public static function clearStuckPendingImports() {
+ public static function clearStuckPendingImports()
+ {
$pendingEpisodes = Application_Service_PodcastEpisodeService::getStuckPendingImports();
foreach (self::$_pendingFiles as $file) {
- /** @var $file CcFiles */
+ // @var $file CcFiles
$file->setDbImportStatus(CcFiles::IMPORT_STATUS_FAILED)->save();
}
foreach ($pendingEpisodes as $episode) {
- /** @var $episode PodcastEpisodes */
+ // @var $episode PodcastEpisodes
$episode->delete();
}
}
-
}
-
diff --git a/legacy/application/services/PodcastEpisodeService.php b/legacy/application/services/PodcastEpisodeService.php
index 0d98ae3ab..73263a509 100644
--- a/legacy/application/services/PodcastEpisodeService.php
+++ b/legacy/application/services/PodcastEpisodeService.php
@@ -1,18 +1,21 @@
'podcast-download'
+ self::DOWNLOAD => 'podcast-download',
];
- private static $privateFields = array(
- "id"
- );
+ private static $privateFields = [
+ 'id',
+ ];
/**
- * Utility function to import and download a single episode
+ * Utility function to import and download a single episode.
*
- * @param int $podcastId ID of the podcast the episode should belong to
- * @param array $episode array of episode data to store
+ * @param int $podcastId ID of the podcast the episode should belong to
+ * @param array $episode array of episode data to store
*
* @return PodcastEpisodes the stored PodcastEpisodes object
*/
- public function importEpisode($podcastId, $episode) {
+ public function importEpisode($podcastId, $episode)
+ {
$e = $this->addPlaceholder($podcastId, $episode);
$p = $e->getPodcast();
- $this->_download($e->getDbId(), $e->getDbDownloadUrl(), $p->getDbTitle(), $this->_getAlbumOverride($p), $episode["title"]);
+ $this->_download($e->getDbId(), $e->getDbDownloadUrl(), $p->getDbTitle(), $this->_getAlbumOverride($p), $episode['title']);
+
return $e;
}
/**
* Given an array of episodes, store them in the database as placeholder objects until
- * they can be processed by Celery
+ * they can be processed by Celery.
*
- * @param int $podcastId Podcast object identifier
- * @param array $episodes array of podcast episodes
+ * @param int $podcastId Podcast object identifier
+ * @param array $episodes array of podcast episodes
*
* @return array the stored PodcastEpisodes objects
*/
- public function addPodcastEpisodePlaceholders($podcastId, $episodes) {
- $storedEpisodes = array();
+ public function addPodcastEpisodePlaceholders($podcastId, $episodes)
+ {
+ $storedEpisodes = [];
foreach ($episodes as $episode) {
try {
$e = $this->addPlaceholder($podcastId, $episode);
- } catch(DuplicatePodcastEpisodeException $ex) {
+ } catch (DuplicatePodcastEpisodeException $ex) {
Logging::warn($ex->getMessage());
+
continue;
}
array_push($storedEpisodes, $e);
}
+
return $storedEpisodes;
}
/**
* Given an episode, store it in the database as a placeholder object until
- * it can be processed by Celery
+ * it can be processed by Celery.
*
- * @param int $podcastId Podcast object identifier
- * @param array $episode array of podcast episode data
- *
- * @return PodcastEpisodes the stored PodcastEpisodes object
+ * @param int $podcastId Podcast object identifier
+ * @param array $episode array of podcast episode data
*
* @throws DuplicatePodcastEpisodeException
+ *
+ * @return PodcastEpisodes the stored PodcastEpisodes object
*/
- public function addPlaceholder($podcastId, $episode) {
- $existingEpisode = PodcastEpisodesQuery::create()->findOneByDbEpisodeGuid($episode["guid"]);
+ public function addPlaceholder($podcastId, $episode)
+ {
+ $existingEpisode = PodcastEpisodesQuery::create()->findOneByDbEpisodeGuid($episode['guid']);
if (!empty($existingEpisode)) {
throw new DuplicatePodcastEpisodeException(sprintf("Episode already exists for podcast: %s, guid: %s\n", $episode['podcast_id'], $episode['guid']));
}
// We need to check whether the array is parsed directly from the SimplePie
// feed object, or whether it's passed in as json
- $enclosure = $episode["enclosure"];
- $url = $enclosure instanceof SimplePie_Enclosure ? $enclosure->get_link() : $enclosure["link"];
- return $this->_buildEpisode($podcastId, $url, $episode["guid"], $episode["pub_date"], $episode["title"], $episode["description"]);
+ $enclosure = $episode['enclosure'];
+ $url = $enclosure instanceof SimplePie_Enclosure ? $enclosure->get_link() : $enclosure['link'];
+
+ return $this->_buildEpisode($podcastId, $url, $episode['guid'], $episode['pub_date'], $episode['title'], $episode['description']);
}
/**
- * Given episode parameters, construct and store a basic PodcastEpisodes object
+ * Given episode parameters, construct and store a basic PodcastEpisodes object.
*
- * @param int $podcastId the podcast the episode belongs to
- * @param string $url the download URL for the episode
- * @param string $guid the unique id for the episode. Often the same as the download URL
- * @param string $publicationDate the publication date of the episode
- * @param string $title the title of the episode
- * @param string $description the description of the epsiode
- *
- * @return PodcastEpisodes the newly created PodcastEpisodes object
+ * @param int $podcastId the podcast the episode belongs to
+ * @param string $url the download URL for the episode
+ * @param string $guid the unique id for the episode. Often the same as the download URL
+ * @param string $publicationDate the publication date of the episode
+ * @param string $title the title of the episode
+ * @param string $description the description of the epsiode
*
* @throws Exception
* @throws PropelException
+ *
+ * @return PodcastEpisodes the newly created PodcastEpisodes object
*/
- private function _buildEpisode($podcastId, $url, $guid, $publicationDate, $title = NULL, $description = NULL) {
+ private function _buildEpisode($podcastId, $url, $guid, $publicationDate, $title = null, $description = null)
+ {
$e = new PodcastEpisodes();
$e->setDbPodcastId($podcastId);
$e->setDbDownloadUrl($url);
@@ -120,60 +131,66 @@ class Application_Service_PodcastEpisodeService extends Application_Service_Thir
$e->setDbEpisodeTitle($title);
$e->setDbEpisodeDescription($description);
$e->save();
+
return $e;
}
/**
- * Given an array of episodes, extract the IDs and download URLs and send them to Celery
+ * Given an array of episodes, extract the IDs and download URLs and send them to Celery.
*
* @param array $episodes array of podcast episodes
*/
- public function downloadEpisodes($episodes) {
+ public function downloadEpisodes($episodes)
+ {
/** @var PodcastEpisodes $episode */
- foreach($episodes as $episode) {
+ foreach ($episodes as $episode) {
$podcast = $episode->getPodcast();
$this->_download($episode->getDbId(), $episode->getDbDownloadUrl(), $podcast->getDbTitle(), $this->_getAlbumOverride($podcast), $episode->getDbEpisodeTitle());
}
}
/**
- * check if there is a podcast specific album override
+ * check if there is a podcast specific album override.
*
* @param object $podcast podcast object
*
- * @return boolean
+ * @return bool
*/
- private function _getAlbumOverride($podcast) {
+ private function _getAlbumOverride($podcast)
+ {
$override = Application_Model_Preference::GetPodcastAlbumOverride();
$podcast_override = $podcast->toArray();
$podcast_override = $podcast_override['DbAlbumOverride'];
if ($podcast_override) {
$override = $podcast_override;
}
+
return $override;
}
/**
* Given an episode ID and a download URL, send a Celery task
- * to download an RSS feed track
+ * to download an RSS feed track.
*
- * @param int $id episode unique ID
- * @param string $url download url for the episode
- * @param string $title title of podcast to be downloaded - added as album to track metadata
- * @param boolean $album_override should we override the album name when downloading
+ * @param int $id episode unique ID
+ * @param string $url download url for the episode
+ * @param string $title title of podcast to be downloaded - added as album to track metadata
+ * @param bool $album_override should we override the album name when downloading
+ * @param null|mixed $track_title
*/
- private function _download($id, $url, $title, $album_override, $track_title = null) {
+ private function _download($id, $url, $title, $album_override, $track_title = null)
+ {
$CC_CONFIG = Config::getConfig();
$stationUrl = Application_Common_HTTPHelper::getStationUrl();
$stationUrl .= substr($stationUrl, -1) == '/' ? '' : '/';
- $data = array(
- 'id' => $id,
- 'url' => $url,
- 'callback_url' => $stationUrl . 'rest/media',
- 'api_key' => $CC_CONFIG["apiKey"][0],
- 'podcast_name' => $title,
+ $data = [
+ 'id' => $id,
+ 'url' => $url,
+ 'callback_url' => $stationUrl . 'rest/media',
+ 'api_key' => $CC_CONFIG['apiKey'][0],
+ 'podcast_name' => $title,
'album_override' => $album_override,
- 'track_title' => $track_title);
+ 'track_title' => $track_title, ];
$task = $this->_executeTask(static::$_CELERY_TASKS[self::DOWNLOAD], $data);
// Get the created ThirdPartyTaskReference and set the episode ID so
// we can remove the placeholder if the import ends up stuck in a pending state
@@ -182,19 +199,20 @@ class Application_Service_PodcastEpisodeService extends Application_Service_Thir
}
/**
- * Update a ThirdPartyTrackReferences object for a completed upload
+ * Update a ThirdPartyTrackReferences object for a completed upload.
*
* @param $task CeleryTasks the completed CeleryTasks object
* @param $episodeId int PodcastEpisodes identifier
* @param $episode stdClass simple object containing Podcast episode information
* @param $status string Celery task status
*
- * @return ThirdPartyTrackReferences the updated ThirdPartyTrackReferences object
- *
* @throws Exception
* @throws PropelException
+ *
+ * @return ThirdPartyTrackReferences the updated ThirdPartyTrackReferences object
*/
- public function updateTrackReference($task, $episodeId, $episode, $status) {
+ public function updateTrackReference($task, $episodeId, $episode, $status)
+ {
$ref = parent::updateTrackReference($task, $episodeId, $episode, $status);
$ref->setDbForeignId($episode->episodeid)->save();
$dbEpisode = PodcastEpisodesQuery::create()->findOneByDbId($episode->episodeid);
@@ -202,7 +220,8 @@ class Application_Service_PodcastEpisodeService extends Application_Service_Thir
try {
// If the placeholder for the episode is somehow removed, return with a warning
if (!$dbEpisode) {
- Logging::warn("Celery task $task episode $episode->episodeid unsuccessful: episode placeholder removed");
+ Logging::warn("Celery task {$task} episode {$episode->episodeid} unsuccessful: episode placeholder removed");
+
return $ref;
}
@@ -210,12 +229,12 @@ class Application_Service_PodcastEpisodeService extends Application_Service_Thir
if ($status == CELERY_SUCCESS_STATUS && $episode->status == 1) {
$dbEpisode->setDbFileId($episode->fileid)->save();
} else {
- Logging::warn("Celery task $task episode $episode->episodeid unsuccessful with message $episode->error");
+ Logging::warn("Celery task {$task} episode {$episode->episodeid} unsuccessful with message {$episode->error}");
$dbEpisode->delete();
}
} catch (Exception $e) {
$dbEpisode->delete();
- Logging::warn("Catastrophic failure updating from task $task, recovering by deleting episode row.\n
+ Logging::warn("Catastrophic failure updating from task {$task}, recovering by deleting episode row.\n
This can occur if the episode's corresponding CcFile is deleted before being processed.");
}
@@ -223,13 +242,14 @@ class Application_Service_PodcastEpisodeService extends Application_Service_Thir
}
/**
- * Publish the file with the given file ID to the station podcast
+ * Publish the file with the given file ID to the station podcast.
*
* @param int $fileId ID of the file to be published
*/
- public function publish($fileId) {
+ public function publish($fileId)
+ {
$id = Application_Model_Preference::getStationPodcastId();
- $url = $guid = Application_Common_HTTPHelper::getStationUrl()."rest/media/$fileId/download";
+ $url = $guid = Application_Common_HTTPHelper::getStationUrl() . "rest/media/{$fileId}/download";
if (!PodcastEpisodesQuery::create()
->filterByDbPodcastId($id)
->findOneByDbFileId($fileId)) { // Don't allow duplicate episodes
@@ -239,20 +259,22 @@ class Application_Service_PodcastEpisodeService extends Application_Service_Thir
}
/**
- * Unpublish the file with the given file ID from the station podcast
+ * Unpublish the file with the given file ID from the station podcast.
*
* @param int $fileId ID of the file to be unpublished
*/
- public function unpublish($fileId) {
+ public function unpublish($fileId)
+ {
$id = Application_Model_Preference::getStationPodcastId();
PodcastEpisodesQuery::create()
->filterByDbPodcastId($id)
->findOneByDbFileId($fileId)
- ->delete();
+ ->delete()
+ ;
}
/**
- * Fetch the publication status for the file with the given ID
+ * Fetch the publication status for the file with the given ID.
*
* @param int $fileId the ID of the file to check
*
@@ -261,45 +283,55 @@ class Application_Service_PodcastEpisodeService extends Application_Service_Thir
* -1 if the file is in a pending state,
* 2 if the source is unreachable (disconnected)
*/
- public function getPublishStatus($fileId) {
+ public function getPublishStatus($fileId)
+ {
$stationPodcast = StationPodcastQuery::create()
- ->findOneByDbPodcastId(Application_Model_Preference::getStationPodcastId());
+ ->findOneByDbPodcastId(Application_Model_Preference::getStationPodcastId())
+ ;
+
return (int) $stationPodcast->hasEpisodeForFile($fileId);
}
/**
* Find any episode placeholders that have been stuck pending (empty file ID) for over
- * PENDING_EPISODE_TIMEOUT_SECONDS
+ * PENDING_EPISODE_TIMEOUT_SECONDS.
*
* @see Application_Service_PodcastEpisodeService::PENDING_EPISODE_TIMEOUT_SECONDS
*
* @return array the episode imports stuck in pending
*/
- public static function getStuckPendingImports() {
+ public static function getStuckPendingImports()
+ {
$timeout = gmdate(DEFAULT_TIMESTAMP_FORMAT, (microtime(true) - self::PENDING_EPISODE_TIMEOUT_SECONDS));
$episodes = PodcastEpisodesQuery::create()
->filterByDbFileId()
- ->find();
- $stuckImports = array();
+ ->find()
+ ;
+ $stuckImports = [];
foreach ($episodes as $episode) {
$ref = ThirdPartyTrackReferencesQuery::create()
- ->findOneByDbForeignId(strval($episode->getDbId()));
+ ->findOneByDbForeignId(strval($episode->getDbId()))
+ ;
if (!empty($ref)) {
$task = CeleryTasksQuery::create()
->filterByDbDispatchTime($timeout, Criteria::LESS_EQUAL)
- ->findOneByDbTrackReference($ref->getDbId());
+ ->findOneByDbTrackReference($ref->getDbId())
+ ;
if (!empty($task)) {
array_push($stuckImports, $episode);
}
}
}
+
return $stuckImports;
}
/**
* @param $episodeId
- * @return array
+ *
* @throws PodcastEpisodeNotFoundException
+ *
+ * @return array
*/
public static function getPodcastEpisodeById($episodeId)
{
@@ -315,29 +347,33 @@ class Application_Service_PodcastEpisodeService extends Application_Service_Thir
* Returns an array of Podcast episodes, with the option to paginate the results.
*
* @param $podcastId
- * @param int $offset
- * @param int $limit
+ * @param int $offset
+ * @param int $limit
* @param string $sortColumn
- * @param string $sortDir "ASC" || "DESC"
- * @return array
+ * @param string $sortDir "ASC" || "DESC"
+ *
* @throws PodcastNotFoundException
+ *
+ * @return array
*/
- public function getPodcastEpisodes($podcastId,
- $offset=0,
- $limit=10,
- $sortColumn=PodcastEpisodesPeer::PUBLICATION_DATE,
- $sortDir="ASC")
- {
+ public function getPodcastEpisodes(
+ $podcastId,
+ $offset = 0,
+ $limit = 10,
+ $sortColumn = PodcastEpisodesPeer::PUBLICATION_DATE,
+ $sortDir = 'ASC'
+ ) {
$podcast = PodcastQuery::create()->findPk($podcastId);
if (!$podcast) {
throw new PodcastNotFoundException();
}
- $sortDir = ($sortDir === "DESC") ? $sortDir = Criteria::DESC : Criteria::ASC;
+ $sortDir = ($sortDir === 'DESC') ? $sortDir = Criteria::DESC : Criteria::ASC;
$isStationPodcast = $podcastId == Application_Model_Preference::getStationPodcastId();
$episodes = PodcastEpisodesQuery::create()
- ->filterByDbPodcastId($podcastId);
+ ->filterByDbPodcastId($podcastId)
+ ;
if ($isStationPodcast && $limit != 0) {
$episodes = $episodes->setLimit($limit);
}
@@ -346,7 +382,8 @@ class Application_Service_PodcastEpisodeService extends Application_Service_Thir
$episodes = $episodes->joinWith('PodcastEpisodes.CcFiles', Criteria::LEFT_JOIN)
->setOffset($offset)
->orderBy($sortColumn, $sortDir)
- ->find();
+ ->find()
+ ;
return $isStationPodcast ? $this->_getStationPodcastEpisodeArray($episodes)
: $this->_getImportedPodcastEpisodeArray($podcast, $episodes);
@@ -354,59 +391,63 @@ class Application_Service_PodcastEpisodeService extends Application_Service_Thir
/**
* Given an array of PodcastEpisodes objects from the Station Podcast,
- * convert the episode data into array form
+ * convert the episode data into array form.
*
* @param array $episodes array of PodcastEpisodes to convert
+ *
* @return array
*/
- private function _getStationPodcastEpisodeArray($episodes) {
- $episodesArray = array();
+ private function _getStationPodcastEpisodeArray($episodes)
+ {
+ $episodesArray = [];
foreach ($episodes as $episode) {
/** @var PodcastEpisodes $episode */
$episodeArr = $episode->toArray(BasePeer::TYPE_FIELDNAME, true, [], true);
array_push($episodesArray, $episodeArr);
}
+
return $episodesArray;
}
/**
* Given an ImportedPodcast object and an array of stored PodcastEpisodes objects,
- * fetch all episodes from the podcast RSS feed, and serialize them in a readable form
+ * fetch all episodes from the podcast RSS feed, and serialize them in a readable form.
*
* TODO: there's definitely a better approach than this... we should be trying to create
* PodcastEpisdoes objects instead of our own arrays
*
- * @param ImportedPodcast $podcast Podcast object to fetch the episodes for
- * @param array $episodes array of PodcastEpisodes objects to
- *
- * @return array array of episode data
+ * @param ImportedPodcast $podcast Podcast object to fetch the episodes for
+ * @param array $episodes array of PodcastEpisodes objects to
*
* @throws CcFiles/LibreTimeFileNotFoundException
+ *
+ * @return array array of episode data
*/
- public function _getImportedPodcastEpisodeArray($podcast, $episodes) {
+ public function _getImportedPodcastEpisodeArray($podcast, $episodes)
+ {
$rss = Application_Service_PodcastService::getPodcastFeed($podcast->getDbUrl());
- $episodeIds = array();
- $episodeFiles = array();
+ $episodeIds = [];
+ $episodeFiles = [];
foreach ($episodes as $e) {
- /** @var PodcastEpisodes $e */
+ // @var PodcastEpisodes $e
array_push($episodeIds, $e->getDbEpisodeGuid());
$episodeFiles[$e->getDbEpisodeGuid()] = $e->getDbFileId();
}
- $episodesArray = array();
+ $episodesArray = [];
foreach ($rss->get_items() as $item) {
/** @var SimplePie_Item $item */
// If the enclosure is empty or has not URL, this isn't a podcast episode (there's no audio data)
// technically podcasts shouldn't have multiple enclosures but often CMS add non-audio files
$enclosure = $item->get_enclosure();
- $url = $enclosure instanceof SimplePie_Enclosure ? $enclosure->get_link() : $enclosure["link"];
+ $url = $enclosure instanceof SimplePie_Enclosure ? $enclosure->get_link() : $enclosure['link'];
if (empty($url)) {
continue;
}
// next we check and see if the enclosure is not an audio file - this can happen from improperly
// formatted podcasts and we instead will search through the enclosures and see if there is an audio item
// then we pass that on, otherwise we just pass the first item since it is probably an audio file
- elseif (!(substr($enclosure->get_type(), 0, 5) === 'audio')) {
+ if (!(substr($enclosure->get_type(), 0, 5) === 'audio')) {
// this is a rather hackish way of accessing the enclosures but get_enclosures() didnt detect multiple
// enclosures at certain points so we search through them and then manually create an enclosure object
// if we find an audio file in an enclosure and send it off
@@ -417,11 +458,12 @@ class Application_Service_PodcastEpisodeService extends Application_Service_Thir
if (is_array($testenclosures)) {
$numenclosures = sizeof($testenclosures);
// now we loop through and look for a audio file and then stop the loop at the first one we find
- for ($i = 0; $i < $numenclosures + 1; $i++) {
+ for ($i = 0; $i < $numenclosures + 1; ++$i) {
$enclosure_attribs = array_values($testenclosures[$i]['attribs'])[0];
if (stripos($enclosure_attribs['type'], 'audio') !== false) {
$url = $enclosure_attribs['url'];
$enclosure = new SimplePie_Enclosure($enclosure_attribs['url'], $enclosure_attribs['type'], $length = $enclosure_attribs['length']);
+
break;
}
// if we didn't find an audio file we need to continue because there were no audio item enclosures
@@ -430,8 +472,7 @@ class Application_Service_PodcastEpisodeService extends Application_Service_Thir
continue;
}
}
- }
- else {
+ } else {
continue;
}
} else {
@@ -441,38 +482,40 @@ class Application_Service_PodcastEpisodeService extends Application_Service_Thir
$itemId = $item->get_id();
$ingested = in_array($itemId, $episodeIds) ? (empty($episodeFiles[$itemId]) ? -1 : 1) : 0;
$file = $ingested > 0 && !empty($episodeFiles[$itemId]) ?
- CcFiles::getSanitizedFileById($episodeFiles[$itemId]) : array();
+ CcFiles::getSanitizedFileById($episodeFiles[$itemId]) : [];
// If the analyzer hasn't finished with the file, leave it as pending
- if (!empty($file) && $file["import_status"] == CcFiles::IMPORT_STATUS_PENDING) {
+ if (!empty($file) && $file['import_status'] == CcFiles::IMPORT_STATUS_PENDING) {
$ingested = -1;
}
- array_push($episodesArray, array(
- "podcast_id" => $podcast->getDbId(),
- "guid" => $itemId,
- "ingested" => $ingested,
- "title" => $item->get_title(),
+ array_push($episodesArray, [
+ 'podcast_id' => $podcast->getDbId(),
+ 'guid' => $itemId,
+ 'ingested' => $ingested,
+ 'title' => $item->get_title(),
// From the RSS spec best practices:
// 'An item's author element provides the e-mail address of the person who wrote the item'
- "author" => $this->_buildAuthorString($item),
- "description" => htmlspecialchars($item->get_description()),
- "pub_date" => $item->get_gmdate(),
- "link" => $url,
- "enclosure" => $enclosure,
- "file" => $file
- ));
+ 'author' => $this->_buildAuthorString($item),
+ 'description' => htmlspecialchars($item->get_description()),
+ 'pub_date' => $item->get_gmdate(),
+ 'link' => $url,
+ 'enclosure' => $enclosure,
+ 'file' => $file,
+ ]);
}
+
return $episodesArray;
}
/**
- * Construct a string representation of the author fields of a SimplePie_Item object
+ * Construct a string representation of the author fields of a SimplePie_Item object.
*
* @param SimplePie_Item $item the SimplePie_Item to extract the author data from
*
* @return string the string representation of the author data
*/
- private function _buildAuthorString(SimplePie_Item $item) {
+ private function _buildAuthorString(SimplePie_Item $item)
+ {
$authorString = $author = $item->get_author();
if (!empty($author)) {
$authorString = $author->get_email();
@@ -499,5 +542,4 @@ class Application_Service_PodcastEpisodeService extends Application_Service_Thir
unset($data[$key]);
}
}
-
}
diff --git a/legacy/application/services/PodcastFactory.php b/legacy/application/services/PodcastFactory.php
index 486ce5f56..e7b7a1141 100644
--- a/legacy/application/services/PodcastFactory.php
+++ b/legacy/application/services/PodcastFactory.php
@@ -12,4 +12,4 @@ class PodcastFactory
return Application_Service_PodcastService::createFromFeedUrl($feedUrl);
}
-}
\ No newline at end of file
+}
diff --git a/legacy/application/services/PodcastService.php b/legacy/application/services/PodcastService.php
index 78aca0748..e6d057180 100644
--- a/legacy/application/services/PodcastService.php
+++ b/legacy/application/services/PodcastService.php
@@ -1,24 +1,25 @@
set_feed_url($feedUrl);
$feed->enable_cache(false);
$feed->init();
+
return $feed;
} catch (Exception $e) {
return false;
@@ -38,13 +40,14 @@ class Application_Service_PodcastService
}
/** Creates a Podcast object from the given podcast URL.
- * This is used by our Podcast REST API
+ * This is used by our Podcast REST API.
*
* @param string $feedUrl Podcast RSS Feed Url
*
- * @return array Podcast Array with a full list of episodes
* @throws Exception
* @throws InvalidPodcastException
+ *
+ * @return array Podcast Array with a full list of episodes
*/
public static function createFromFeedUrl($feedUrl)
{
@@ -60,55 +63,55 @@ class Application_Service_PodcastService
// Ensure we are only creating Podcast with the given URL, and excluding
// any extra data fields that may have been POSTED
- $podcastArray = array();
- $podcastArray["url"] = $feedUrl;
+ $podcastArray = [];
+ $podcastArray['url'] = $feedUrl;
- $podcastArray["title"] = htmlspecialchars($rss->get_title());
- $podcastArray["description"] = htmlspecialchars($rss->get_description());
- $podcastArray["link"] = htmlspecialchars($rss->get_link());
- $podcastArray["language"] = htmlspecialchars($rss->get_language());
- $podcastArray["copyright"] = htmlspecialchars($rss->get_copyright());
+ $podcastArray['title'] = htmlspecialchars($rss->get_title());
+ $podcastArray['description'] = htmlspecialchars($rss->get_description());
+ $podcastArray['link'] = htmlspecialchars($rss->get_link());
+ $podcastArray['language'] = htmlspecialchars($rss->get_language());
+ $podcastArray['copyright'] = htmlspecialchars($rss->get_copyright());
$author = $rss->get_author();
- $name = empty($author) ? "" : $author->get_name();
- $podcastArray["creator"] = htmlspecialchars($name);
+ $name = empty($author) ? '' : $author->get_name();
+ $podcastArray['creator'] = htmlspecialchars($name);
- $categories = array();
+ $categories = [];
if (is_array($rss->get_categories())) {
foreach ($rss->get_categories() as $category) {
- array_push($categories, $category->get_scheme() . ":" . $category->get_term());
+ array_push($categories, $category->get_scheme() . ':' . $category->get_term());
}
}
- $podcastArray["category"] = htmlspecialchars(implode($categories));
+ $podcastArray['category'] = htmlspecialchars(implode($categories));
//TODO: put in constants
- $itunesChannel = "http://www.itunes.com/dtds/podcast-1.0.dtd";
+ $itunesChannel = 'http://www.itunes.com/dtds/podcast-1.0.dtd';
$itunesSubtitle = $rss->get_channel_tags($itunesChannel, 'subtitle');
- $podcastArray["itunes_subtitle"] = isset($itunesSubtitle[0]["data"]) ? $itunesSubtitle[0]["data"] : "";
+ $podcastArray['itunes_subtitle'] = isset($itunesSubtitle[0]['data']) ? $itunesSubtitle[0]['data'] : '';
$itunesCategory = $rss->get_channel_tags($itunesChannel, 'category');
- $categoryArray = array();
+ $categoryArray = [];
if (is_array($itunesCategory)) {
foreach ($itunesCategory as $c => $data) {
- foreach ($data["attribs"] as $attrib) {
- array_push($categoryArray, $attrib["text"]);
+ foreach ($data['attribs'] as $attrib) {
+ array_push($categoryArray, $attrib['text']);
}
}
}
- $podcastArray["itunes_category"] = implode(",", $categoryArray);
+ $podcastArray['itunes_category'] = implode(',', $categoryArray);
$itunesAuthor = $rss->get_channel_tags($itunesChannel, 'author');
- $podcastArray["itunes_author"] = isset($itunesAuthor[0]["data"]) ? $itunesAuthor[0]["data"] : "";
+ $podcastArray['itunes_author'] = isset($itunesAuthor[0]['data']) ? $itunesAuthor[0]['data'] : '';
$itunesSummary = $rss->get_channel_tags($itunesChannel, 'summary');
- $podcastArray["itunes_summary"] = isset($itunesSummary[0]["data"]) ? $itunesSummary[0]["data"] : "";
+ $podcastArray['itunes_summary'] = isset($itunesSummary[0]['data']) ? $itunesSummary[0]['data'] : '';
$itunesKeywords = $rss->get_channel_tags($itunesChannel, 'keywords');
- $podcastArray["itunes_keywords"] = isset($itunesKeywords[0]["data"]) ? $itunesKeywords[0]["data"] : "";
+ $podcastArray['itunes_keywords'] = isset($itunesKeywords[0]['data']) ? $itunesKeywords[0]['data'] : '';
$itunesExplicit = $rss->get_channel_tags($itunesChannel, 'explicit');
- $podcastArray["itunes_explicit"] = isset($itunesExplicit[0]["data"]) ? $itunesExplicit[0]["data"] : "";
+ $podcastArray['itunes_explicit'] = isset($itunesExplicit[0]['data']) ? $itunesExplicit[0]['data'] : '';
self::validatePodcastMetadata($podcastArray);
@@ -130,10 +133,10 @@ class Application_Service_PodcastService
self::createPodcastSmartblockAndPlaylist($podcast);
}
-
return $podcast->toArray(BasePeer::TYPE_FIELDNAME);
- } catch(Exception $e) {
+ } catch (Exception $e) {
$podcast->delete();
+
throw $e;
}
}
@@ -141,9 +144,8 @@ class Application_Service_PodcastService
/**
* @param $podcast
* @param $title passed in directly from web UI input
- * This will automatically create a smartblock and playlist for this podcast.
+ * This will automatically create a smartblock and playlist for this podcast
*/
-
public static function createPodcastSmartblockAndPlaylist($podcast, $title = null)
{
if (is_array($podcast)) {
@@ -158,7 +160,7 @@ class Application_Service_PodcastService
$newBl = new Application_Model_Block();
$newBl->setCreator(Application_Model_User::getCurrentUser()->getId());
$newBl->setName($title);
- $newBl->setDescription(_("Auto-generated smartblock for podcast"));
+ $newBl->setDescription(_('Auto-generated smartblock for podcast'));
$newBl->saveType('dynamic');
// limit the smartblock to 1 item
$row = new CcBlockcriteria();
@@ -194,11 +196,10 @@ class Application_Service_PodcastService
$row->save();
}
-
public static function createStationPodcast()
{
$podcast = new Podcast();
- $podcast->setDbUrl(Application_Common_HTTPHelper::getStationUrl() . "feeds/station-rss");
+ $podcast->setDbUrl(Application_Common_HTTPHelper::getStationUrl() . 'feeds/station-rss');
$title = Application_Model_Preference::GetStationName();
$title = empty($title) ? "My Station's Podcast" : $title;
@@ -219,6 +220,7 @@ class Application_Service_PodcastService
// Set the download key when we create the station podcast
// The value is randomly generated in the setter
Application_Model_Preference::setStationPodcastDownloadKey();
+
return $podcast->getDbId();
}
@@ -228,26 +230,28 @@ class Application_Service_PodcastService
try {
if (Zend_Auth::getInstance()->hasIdentity()) {
$service_user = new Application_Service_UserService();
+
return $service_user->getCurrentUser()->getDbId();
- } else {
- $defaultOwner = CcSubjsQuery::create()
- ->filterByDbType('A')
- ->orderByDbId()
- ->findOne();
- if (!$defaultOwner) {
- // what to do if there is no admin user?
- // should we handle this case?
- return null;
- }
- return $defaultOwner->getDbId();
}
- } catch(Exception $e) {
+ $defaultOwner = CcSubjsQuery::create()
+ ->filterByDbType('A')
+ ->orderByDbId()
+ ->findOne()
+ ;
+ if (!$defaultOwner) {
+ // what to do if there is no admin user?
+ // should we handle this case?
+ return null;
+ }
+
+ return $defaultOwner->getDbId();
+ } catch (Exception $e) {
Logging::info($e->getMessage());
}
}
/**
- * Trims the podcast metadata to fit the table's column max size
+ * Trims the podcast metadata to fit the table's column max size.
*
* @param $podcastArray
*/
@@ -271,12 +275,13 @@ class Application_Service_PodcastService
/**
* Fetches a Podcast's rss feed and returns all its episodes with
- * the Podcast object
+ * the Podcast object.
*
* @param $podcastId
*
* @throws PodcastNotFoundException
* @throws InvalidPodcastException
+ *
* @return array - Podcast Array with a full list of episodes
*/
public static function getPodcastById($podcastId)
@@ -287,14 +292,16 @@ class Application_Service_PodcastService
}
$podcast = $podcast->toArray(BasePeer::TYPE_FIELDNAME);
- $podcast["itunes_explicit"] = ($podcast["itunes_explicit"] == "yes") ? true : false;
+ $podcast['itunes_explicit'] = ($podcast['itunes_explicit'] == 'yes') ? true : false;
+
return $podcast;
}
/**
- * Deletes a Podcast and its podcast episodes
+ * Deletes a Podcast and its podcast episodes.
*
* @param $podcastId
+ *
* @throws Exception
* @throws PodcastNotFoundException
*/
@@ -314,35 +321,39 @@ class Application_Service_PodcastService
}
/**
- * Build a response with podcast data and embedded HTML to load on the frontend
+ * Build a response with podcast data and embedded HTML to load on the frontend.
*
- * @param int $podcastId ID of the podcast to build a response for
- * @param Zend_View_Interface $view Zend view object to render the response HTML
- *
- * @return array the response array containing the podcast data and editor HTML
+ * @param int $podcastId ID of the podcast to build a response for
+ * @param Zend_View_Interface $view Zend view object to render the response HTML
*
* @throws PodcastNotFoundException
+ *
+ * @return array the response array containing the podcast data and editor HTML
*/
- public static function buildPodcastEditorResponse($podcastId, $view) {
+ public static function buildPodcastEditorResponse($podcastId, $view)
+ {
// Check the StationPodcast table rather than checking
// the station podcast ID key in preferences for extensibility
$podcast = StationPodcastQuery::create()->findOneByDbPodcastId($podcastId);
$path = $podcast ? 'podcast/station.phtml' : 'podcast/podcast.phtml';
$podcast = Application_Service_PodcastService::getPodcastById($podcastId);
- return array(
- "podcast" => json_encode($podcast),
- "html" => $view->render($path),
- );
+
+ return [
+ 'podcast' => json_encode($podcast),
+ 'html' => $view->render($path),
+ ];
}
/**
- * Updates a Podcast object with the given metadata
+ * Updates a Podcast object with the given metadata.
*
* @param $podcastId
* @param $data
- * @return array
+ *
* @throws Exception
* @throws PodcastNotFoundException
+ *
+ * @return array
*/
public static function updatePodcastFromArray($podcastId, $data)
{
@@ -351,31 +362,32 @@ class Application_Service_PodcastService
throw new PodcastNotFoundException();
}
- self::removePrivateFields($data["podcast"]);
- self::validatePodcastMetadata($data["podcast"]);
- if (array_key_exists("auto_ingest", $data["podcast"])) {
+ self::removePrivateFields($data['podcast']);
+ self::validatePodcastMetadata($data['podcast']);
+ if (array_key_exists('auto_ingest', $data['podcast'])) {
self::_updateAutoIngestTimestamp($podcast, $data);
}
- $data["podcast"]["itunes_explicit"] = $data["podcast"]["itunes_explicit"] ? "yes" : "clean";
- $podcast->fromArray($data["podcast"], BasePeer::TYPE_FIELDNAME);
+ $data['podcast']['itunes_explicit'] = $data['podcast']['itunes_explicit'] ? 'yes' : 'clean';
+ $podcast->fromArray($data['podcast'], BasePeer::TYPE_FIELDNAME);
$podcast->save();
return $podcast->toArray(BasePeer::TYPE_FIELDNAME);
}
/**
- * Update the automatic ingestion timestamp for the given Podcast
+ * Update the automatic ingestion timestamp for the given Podcast.
*
- * @param Podcast $podcast Podcast object to update
- * @param array $data Podcast update data array
+ * @param Podcast $podcast Podcast object to update
+ * @param array $data Podcast update data array
*/
- private static function _updateAutoIngestTimestamp($podcast, $data) {
+ private static function _updateAutoIngestTimestamp($podcast, $data)
+ {
// Get podcast data with lazy loaded columns since we can't directly call getDbAutoIngest()
$currData = $podcast->toArray(BasePeer::TYPE_FIELDNAME, true);
// Add an auto-ingest timestamp when turning auto-ingest on
- if ($data["podcast"]["auto_ingest"] == 1 && $currData["auto_ingest"] != 1) {
- $data["podcast"]["auto_ingest_timestamp"] = gmdate('r');
+ if ($data['podcast']['auto_ingest'] == 1 && $currData['auto_ingest'] != 1) {
+ $data['podcast']['auto_ingest_timestamp'] = gmdate('r');
}
}
@@ -386,19 +398,21 @@ class Application_Service_PodcastService
}
}
- private static function addEscapedChild($node, $name, $value = null, $namespace = null) {
+ private static function addEscapedChild($node, $name, $value = null, $namespace = null)
+ {
if (empty($value)) {
return null;
}
$child = $node->addChild($name, null, $namespace);
$child[0] = $value;
+
return $child;
}
public static function createStationRssFeed()
{
$stationPodcastId = Application_Model_Preference::getStationPodcastId();
-
+
try {
$podcast = PodcastQuery::create()->findPk($stationPodcastId);
if (!$podcast) {
@@ -407,107 +421,105 @@ class Application_Service_PodcastService
$xml = new SimpleXMLElement('');
- $channel = $xml->addChild("channel");
- self::addEscapedChild($channel, "title", $podcast->getDbTitle());
- self::addEscapedChild($channel, "link", $podcast->getDbLink());
- self::addEscapedChild($channel, "description", $podcast->getDbDescription());
- self::addEscapedChild($channel, "language", $podcast->getDbLanguage());
- self::addEscapedChild($channel, "copyright", $podcast->getDbCopyright());
+ $channel = $xml->addChild('channel');
+ self::addEscapedChild($channel, 'title', $podcast->getDbTitle());
+ self::addEscapedChild($channel, 'link', $podcast->getDbLink());
+ self::addEscapedChild($channel, 'description', $podcast->getDbDescription());
+ self::addEscapedChild($channel, 'language', $podcast->getDbLanguage());
+ self::addEscapedChild($channel, 'copyright', $podcast->getDbCopyright());
- $xml->addAttribute('xmlns:xmlns:atom', "http://www.w3.org/2005/Atom");
+ $xml->addAttribute('xmlns:xmlns:atom', 'http://www.w3.org/2005/Atom');
- $atomLink = $channel->addChild("xmlns:atom:link");
- $atomLink->addAttribute("href", Application_Common_HTTPHelper::getStationUrl() . "feeds/station-rss");
- $atomLink->addAttribute("rel", "self");
- $atomLink->addAttribute("type", "application/rss+xml");
+ $atomLink = $channel->addChild('xmlns:atom:link');
+ $atomLink->addAttribute('href', Application_Common_HTTPHelper::getStationUrl() . 'feeds/station-rss');
+ $atomLink->addAttribute('rel', 'self');
+ $atomLink->addAttribute('type', 'application/rss+xml');
- $imageUrl = Application_Common_HTTPHelper::getStationUrl()."api/station-logo";
- $image = $channel->addChild("image");
- $image->addChild("title", htmlspecialchars($podcast->getDbTitle()));
- self::addEscapedChild($image, "url", $imageUrl);
- self::addEscapedChild($image, "link", Application_Common_HTTPHelper::getStationUrl());
+ $imageUrl = Application_Common_HTTPHelper::getStationUrl() . 'api/station-logo';
+ $image = $channel->addChild('image');
+ $image->addChild('title', htmlspecialchars($podcast->getDbTitle()));
+ self::addEscapedChild($image, 'url', $imageUrl);
+ self::addEscapedChild($image, 'link', Application_Common_HTTPHelper::getStationUrl());
$xml->addAttribute('xmlns:xmlns:itunes', ITUNES_XML_NAMESPACE_URL);
- self::addEscapedChild($channel, "xmlns:itunes:author", $podcast->getDbItunesAuthor());
- self::addEscapedChild($channel, "xmlns:itunes:keywords", $podcast->getDbItunesKeywords());
- self::addEscapedChild($channel, "xmlns:itunes:summary", $podcast->getDbItunesSummary());
- self::addEscapedChild($channel, "xmlns:itunes:subtitle", $podcast->getDbItunesSubtitle());
- self::addEscapedChild($channel, "xmlns:itunes:explicit", $podcast->getDbItunesExplicit());
- $owner = $channel->addChild("xmlns:itunes:owner");
- self::addEscapedChild($owner, "xmlns:itunes:name", Application_Model_Preference::GetStationName());
- self::addEscapedChild($owner, "xmlns:itunes:email", Application_Model_Preference::GetEmail());
+ self::addEscapedChild($channel, 'xmlns:itunes:author', $podcast->getDbItunesAuthor());
+ self::addEscapedChild($channel, 'xmlns:itunes:keywords', $podcast->getDbItunesKeywords());
+ self::addEscapedChild($channel, 'xmlns:itunes:summary', $podcast->getDbItunesSummary());
+ self::addEscapedChild($channel, 'xmlns:itunes:subtitle', $podcast->getDbItunesSubtitle());
+ self::addEscapedChild($channel, 'xmlns:itunes:explicit', $podcast->getDbItunesExplicit());
+ $owner = $channel->addChild('xmlns:itunes:owner');
+ self::addEscapedChild($owner, 'xmlns:itunes:name', Application_Model_Preference::GetStationName());
+ self::addEscapedChild($owner, 'xmlns:itunes:email', Application_Model_Preference::GetEmail());
- $itunesImage = $channel->addChild("xmlns:itunes:image");
- $itunesImage->addAttribute("href", $imageUrl);
+ $itunesImage = $channel->addChild('xmlns:itunes:image');
+ $itunesImage->addAttribute('href', $imageUrl);
// Need to split categories into separate tags
- $itunesCategories = explode(",", $podcast->getDbItunesCategory());
+ $itunesCategories = explode(',', $podcast->getDbItunesCategory());
foreach ($itunesCategories as $c) {
if (!empty($c)) {
- $category = $channel->addChild("xmlns:itunes:category");
- $category->addAttribute("text", $c);
+ $category = $channel->addChild('xmlns:itunes:category');
+ $category->addAttribute('text', $c);
}
}
$episodes = PodcastEpisodesQuery::create()->filterByDbPodcastId($stationPodcastId)->find();
foreach ($episodes as $episode) {
- $item = $channel->addChild("item");
+ $item = $channel->addChild('item');
$publishedFile = CcFilesQuery::create()->findPk($episode->getDbFileId());
//title
- self::addEscapedChild($item, "title", $publishedFile->getDbTrackTitle());
+ self::addEscapedChild($item, 'title', $publishedFile->getDbTrackTitle());
//link - do we need this?
//pubDate
- self::addEscapedChild($item, "pubDate", gmdate(DATE_RFC2822, strtotime($episode->getDbPublicationDate())));
+ self::addEscapedChild($item, 'pubDate', gmdate(DATE_RFC2822, strtotime($episode->getDbPublicationDate())));
//category
- foreach($itunesCategories as $c) {
+ foreach ($itunesCategories as $c) {
if (!empty($c)) {
- self::addEscapedChild($item, "category", $c);
+ self::addEscapedChild($item, 'category', $c);
}
}
//guid
- $guid = self::addEscapedChild($item, "guid", $episode->getDbEpisodeGuid());
- $guid->addAttribute("isPermaLink", "false");
+ $guid = self::addEscapedChild($item, 'guid', $episode->getDbEpisodeGuid());
+ $guid->addAttribute('isPermaLink', 'false');
//description
- self::addEscapedChild($item, "description", $publishedFile->getDbDescription());
+ self::addEscapedChild($item, 'description', $publishedFile->getDbDescription());
//encolsure - url, length, type attribs
- $enclosure = $item->addChild("enclosure");
- $enclosure->addAttribute("url", $episode->getDbDownloadUrl());
- $enclosure->addAttribute("length", $publishedFile->getDbFilesize());
- $enclosure->addAttribute("type", $publishedFile->getDbMime());
+ $enclosure = $item->addChild('enclosure');
+ $enclosure->addAttribute('url', $episode->getDbDownloadUrl());
+ $enclosure->addAttribute('length', $publishedFile->getDbFilesize());
+ $enclosure->addAttribute('type', $publishedFile->getDbMime());
//itunes:subtitle
// From http://www.apple.com/ca/itunes/podcasts/specs.html#subtitle :
// 'The contents of the tag are displayed in the Description column in iTunes.'
// self::addEscapedChild($item, "xmlns:itunes:subtitle", $publishedFile->getDbTrackTitle());
- self::addEscapedChild($item, "xmlns:itunes:subtitle", $publishedFile->getDbDescription());
+ self::addEscapedChild($item, 'xmlns:itunes:subtitle', $publishedFile->getDbDescription());
//itunes:summary
- self::addEscapedChild($item, "xmlns:itunes:summary", $publishedFile->getDbDescription());
+ self::addEscapedChild($item, 'xmlns:itunes:summary', $publishedFile->getDbDescription());
//itunes:author
- self::addEscapedChild($item, "xmlns:itunes:author", $publishedFile->getDbArtistName());
+ self::addEscapedChild($item, 'xmlns:itunes:author', $publishedFile->getDbArtistName());
//itunes:explicit - skip this?
//itunes:duration
- self::addEscapedChild($item, "xmlns:itunes:duration", explode('.', $publishedFile->getDbLength())[0]);
+ self::addEscapedChild($item, 'xmlns:itunes:duration', explode('.', $publishedFile->getDbLength())[0]);
}
//Format it nicely with newlines...
$dom = new DOMDocument();
$dom->loadXML($xml->asXML());
$dom->formatOutput = true;
- $formattedXML = $dom->saveXML();
-
- return $formattedXML;
+ return $dom->saveXML();
} catch (FeedException $e) {
return false;
}
diff --git a/legacy/application/services/PublishService.php b/legacy/application/services/PublishService.php
index df4a71483..509bd41f5 100644
--- a/legacy/application/services/PublishService.php
+++ b/legacy/application/services/PublishService.php
@@ -1,25 +1,26 @@
"My Podcast"
- );
+ private static $SOURCES = [
+ 'station_podcast' => 'My Podcast',
+ ];
/**
* Publish or remove the file with the given file ID from the services
- * specified in the request data (ie. the station podcast)
+ * specified in the request data (ie. the station podcast).
*
- * @param int $fileId ID of the file to be published
+ * @param int $fileId ID of the file to be published
* @param array $data request data containing what services to publish to
*/
- public static function publish($fileId, $data) {
+ public static function publish($fileId, $data)
+ {
foreach ($data as $k => $v) {
$service = PublishServiceFactory::getService($k);
- $service->$v($fileId);
+ $service->{$v}($fileId);
}
}
@@ -35,26 +36,27 @@ class Application_Service_PublishService {
*
* @return array array containing published and toPublish arrays. Has the form
* [
- * "toPublish" => [
- * "source" => "label",
- * ...
- * ]
- * "published" => [
- * "source" => "label",
- * ...
- * ]
+ * "toPublish" => [
+ * "source" => "label",
+ * ...
+ * ]
+ * "published" => [
+ * "source" => "label",
+ * ...
+ * ]
* ]
*/
- public static function getSourceLists($fileId) {
- $sources = array();
+ public static function getSourceLists($fileId)
+ {
+ $sources = [];
foreach (self::$SOURCES as $source => $label) {
$service = PublishServiceFactory::getService($source);
$status = $service->getPublishStatus($fileId);
- array_push($sources, array(
- "source" => $source,
- "label" => _($label),
- "status" => $status
- ));
+ array_push($sources, [
+ 'source' => $source,
+ 'label' => _($label),
+ 'status' => $status,
+ ]);
}
return $sources;
@@ -69,7 +71,8 @@ class Application_Service_PublishService {
* @return bool true if the file has been published to any source,
* otherwise false
*/
- public static function isPublished($fileId) {
+ public static function isPublished($fileId)
+ {
foreach (self::$SOURCES as $source => $label) {
$service = PublishServiceFactory::getService($source);
// 1: published or -1: pending
@@ -77,7 +80,7 @@ class Application_Service_PublishService {
return true;
}
}
+
return false;
}
-
}
diff --git a/legacy/application/services/PublishServiceFactory.php b/legacy/application/services/PublishServiceFactory.php
index 2ebb9277a..3cda04a82 100644
--- a/legacy/application/services/PublishServiceFactory.php
+++ b/legacy/application/services/PublishServiceFactory.php
@@ -1,21 +1,22 @@
"",
- "cliplength" => "",
- "cuein" => "00:00:00",
- "cueout" => "00:00:00",
- "fadein" => "00:00:00",
- "fadeout" => "00:00:00",
- "sched_id" => null,
- "type" => 0 //default type of '0' to represent files. type '1' represents a webstream
- );
+ private $fileInfo = [
+ 'id' => '',
+ 'cliplength' => '',
+ 'cuein' => '00:00:00',
+ 'cueout' => '00:00:00',
+ 'fadein' => '00:00:00',
+ 'fadeout' => '00:00:00',
+ 'sched_id' => null,
+ 'type' => 0, //default type of '0' to represent files. type '1' represents a webstream
+ ];
private $epochNow;
private $nowDT;
@@ -26,13 +27,13 @@ class Application_Service_SchedulerService
//to epochNow and then send the new schedule to pypo. Sometimes the currently cancelled
//track can still be included in the new schedule because it may have a few ms left to play.
//subtracting 1 second from epochNow resolves this issue.
- $this->epochNow = microtime(true)-1;
- $this->nowDT = DateTime::createFromFormat("U.u", $this->epochNow, new DateTimeZone("UTC"));
+ $this->epochNow = microtime(true) - 1;
+ $this->nowDT = DateTime::createFromFormat('U.u', $this->epochNow, new DateTimeZone('UTC'));
if ($this->nowDT === false) {
// DateTime::createFromFormat does not support millisecond string formatting in PHP 5.3.2 (Ubuntu 10.04).
// In PHP 5.3.3 (Ubuntu 10.10), this has been fixed.
- $this->nowDT = DateTime::createFromFormat("U", time(), new DateTimeZone("UTC"));
+ $this->nowDT = DateTime::createFromFormat('U', time(), new DateTimeZone('UTC'));
}
$user_service = new Application_Service_UserService();
@@ -40,9 +41,8 @@ class Application_Service_SchedulerService
}
/**
- *
- * Applies the show start difference to any scheduled items
- *
+ * Applies the show start difference to any scheduled items.
+ *
* @param $instanceIds
* @param $diff (integer, difference between unix epoch in seconds)
*/
@@ -50,13 +50,14 @@ class Application_Service_SchedulerService
{
$con = Propel::getConnection();
if (count($instanceIds) > 0) {
- $showIdList = implode(",", $instanceIds);
+ $showIdList = implode(',', $instanceIds);
$ccSchedules = CcScheduleQuery::create()
->filterByDbInstanceId($instanceIds, Criteria::IN)
- ->find($con);
+ ->find($con)
+ ;
- $interval = new DateInterval("PT".abs($diff)."S");
+ $interval = new DateInterval('PT' . abs($diff) . 'S');
if ($diff < 0) {
$interval->invert = 1;
}
@@ -68,23 +69,24 @@ class Application_Service_SchedulerService
$ccSchedule
->setDbStarts($newStart)
->setDbEnds($newEnd)
- ->save($con);
+ ->save($con)
+ ;
}
}
}
/**
- *
- * Removes any time gaps in shows
- *
+ * Removes any time gaps in shows.
+ *
* @param array $schedIds schedule ids to exclude
+ * @param mixed $showId
*/
- public function removeGaps($showId, $schedIds=null)
+ public function removeGaps($showId, $schedIds = null)
{
$ccShowInstances = CcShowInstancesQuery::create()->filterByDbShowId($showId)->find();
foreach ($ccShowInstances as $instance) {
- Logging::info("Removing gaps from show instance #".$instance->getDbId());
+ Logging::info('Removing gaps from show instance #' . $instance->getDbId());
//DateTime object
$itemStart = $instance->getDbStarts(null);
@@ -92,14 +94,16 @@ class Application_Service_SchedulerService
->filterByDbInstanceId($instance->getDbId())
->filterByDbId($schedIds, Criteria::NOT_IN)
->orderByDbStarts()
- ->find();
+ ->find()
+ ;
foreach ($ccScheduleItems as $ccSchedule) {
//DateTime object
$itemEnd = $this->findEndTime($itemStart, $ccSchedule->getDbClipLength());
$ccSchedule->setDbStarts($itemStart)
- ->setDbEnds($itemEnd);
+ ->setDbEnds($itemEnd)
+ ;
$itemStart = $itemEnd;
}
@@ -108,25 +112,25 @@ class Application_Service_SchedulerService
}
/**
- *
* Enter description here ...
+ *
* @param DateTime $instanceStart
- * @param string $clipLength
+ * @param string $clipLength
*/
private static function findEndTime($instanceStart, $clipLength)
{
- $startEpoch = $instanceStart->format("U.u");
+ $startEpoch = $instanceStart->format('U.u');
$durationSeconds = Application_Common_DateHelper::playlistTimeToSeconds($clipLength);
//add two float numbers to 6 subsecond precision
//DateTime::createFromFormat("U.u") will have a problem if there is no decimal in the resulting number.
- $endEpoch = bcadd($startEpoch , (string) $durationSeconds, 6);
+ $endEpoch = bcadd($startEpoch, (string) $durationSeconds, 6);
- $dt = DateTime::createFromFormat("U.u", $endEpoch, new DateTimeZone("UTC"));
+ $dt = DateTime::createFromFormat('U.u', $endEpoch, new DateTimeZone('UTC'));
if ($dt === false) {
//PHP 5.3.2 problem
- $dt = DateTime::createFromFormat("U", intval($endEpoch), new DateTimeZone("UTC"));
+ $dt = DateTime::createFromFormat('U', intval($endEpoch), new DateTimeZone('UTC'));
}
return $dt;
@@ -134,44 +138,43 @@ class Application_Service_SchedulerService
private static function findTimeDifference($p_startDT, $p_seconds)
{
- $startEpoch = $p_startDT->format("U.u");
-
- //add two float numbers to 6 subsecond precision
- //DateTime::createFromFormat("U.u") will have a problem if there is no decimal in the resulting number.
- $newEpoch = bcsub($startEpoch , (string) $p_seconds, 6);
-
- $dt = DateTime::createFromFormat("U.u", $newEpoch, new DateTimeZone("UTC"));
-
- if ($dt === false) {
- //PHP 5.3.2 problem
- $dt = DateTime::createFromFormat("U", intval($newEpoch), new DateTimeZone("UTC"));
- }
-
- return $dt;
+ $startEpoch = $p_startDT->format('U.u');
+
+ //add two float numbers to 6 subsecond precision
+ //DateTime::createFromFormat("U.u") will have a problem if there is no decimal in the resulting number.
+ $newEpoch = bcsub($startEpoch, (string) $p_seconds, 6);
+
+ $dt = DateTime::createFromFormat('U.u', $newEpoch, new DateTimeZone('UTC'));
+
+ if ($dt === false) {
+ //PHP 5.3.2 problem
+ $dt = DateTime::createFromFormat('U', intval($newEpoch), new DateTimeZone('UTC'));
+ }
+
+ return $dt;
}
/**
- *
- * Gets a copy of the linked show's schedule from cc_schedule table
- *
+ * Gets a copy of the linked show's schedule from cc_schedule table.
+ *
* If $instanceId is not null, we use that variable to grab the linked
* show's schedule from cc_schedule table. (This is likely to be the case
* if a user has edited a show and changed it from un-linked to linked, in
* which case we copy the show content from the show instance that was clicked
* on to edit the show in the calendar.) Otherwise the schedule is taken
* from the most recent show instance that existed before new show
- * instances were created. (This is likely to be the case when a user edits a
+ * instances were created. (This is likely to be the case when a user edits a
* show and a new repeat show day is added (i.e. mondays), or moves forward in the
* calendar triggering show creation)
- *
- * @param integer $showId
+ *
+ * @param int $showId
* @param array $instancsIdsToFill
- * @param integer $instanceId
+ * @param int $instanceId
*/
private static function getLinkedShowSchedule($showId, $instancsIdsToFill, $instanceId)
{
$con = Propel::getConnection();
-
+
if (is_null($instanceId)) {
$showsPopulatedUntil = Application_Model_Preference::GetShowsPopulatedUntil();
@@ -181,7 +184,8 @@ class Application_Service_SchedulerService
->filterByDbId($instancsIdsToFill, Criteria::NOT_IN)
->orderByDbStarts(Criteria::DESC)
->limit(1)
- ->findOne();
+ ->findOne()
+ ;
if (is_null($showInstanceWithMostRecentSchedule)) {
return null;
@@ -190,46 +194,50 @@ class Application_Service_SchedulerService
}
$linkedShowSchedule_sql = $con->prepare(
- "select * from cc_schedule where instance_id = :instance_id ".
- "order by starts");
+ 'select * from cc_schedule where instance_id = :instance_id ' .
+ 'order by starts'
+ );
$linkedShowSchedule_sql->bindParam(':instance_id', $instanceId);
$linkedShowSchedule_sql->execute();
return $linkedShowSchedule_sql->fetchAll();
}
-
+
/**
- *
* This function gets called after new linked show_instances are created, or after
* a show has been edited and went from being un-linked to linked.
* It fills the new show instances' schedules.
- *
+ *
* @param CcShow_type $ccShow
- * @param array $instanceIdsToFill ids of the new linked cc_show_instances that
- * need their schedules filled
+ * @param array $instanceIdsToFill ids of the new linked cc_show_instances that
+ * need their schedules filled
+ * @param null|mixed $instanceId
*/
- public static function fillLinkedInstances($ccShow, $instanceIdsToFill, $instanceId=null)
+ public static function fillLinkedInstances($ccShow, $instanceIdsToFill, $instanceId = null)
{
- //Get the "template" schedule for the linked show (contents of the linked show) that will be
+ //Get the "template" schedule for the linked show (contents of the linked show) that will be
//copied into to all the new show instances.
$linkedShowSchedule = self::getLinkedShowSchedule($ccShow->getDbId(), $instanceIdsToFill, $instanceId);
//get time_filled so we can update cc_show_instances
if (!empty($linkedShowSchedule)) {
- $timeFilled_sql = "SELECT time_filled FROM cc_show_instances ".
- "WHERE id = {$linkedShowSchedule[0]["instance_id"]}";
+ $timeFilled_sql = 'SELECT time_filled FROM cc_show_instances ' .
+ "WHERE id = {$linkedShowSchedule[0]['instance_id']}";
$timeFilled = Application_Common_Database::prepareAndExecute(
- $timeFilled_sql, array(), Application_Common_Database::COLUMN);
+ $timeFilled_sql,
+ [],
+ Application_Common_Database::COLUMN
+ );
} else {
//We probably shouldn't return here because the code below will
//set this on each empty show instance...
- $timeFilled = "00:00:00";
+ $timeFilled = '00:00:00';
}
-
- $values = array();
+
+ $values = [];
$con = Propel::getConnection();
-
+
//Here we begin to fill the new show instances (as specified by $instanceIdsToFill)
//with content from $linkedShowSchedule.
try {
@@ -242,50 +250,60 @@ class Application_Service_SchedulerService
self::clearShowInstanceContents($id);
// Now fill the show instance with the same content that $linkedShowSchedule has.
- $instanceStart_sql = "SELECT starts FROM cc_show_instances " .
- "WHERE id = {$id} " . "ORDER BY starts";
+ $instanceStart_sql = 'SELECT starts FROM cc_show_instances ' .
+ "WHERE id = {$id} " . 'ORDER BY starts';
//What's tricky here is that when we copy the content, we have to adjust
//the start and end times of each track so they're inside the new show instance's time slot.
$nextStartDT = new DateTime(
Application_Common_Database::prepareAndExecute(
- $instanceStart_sql, array(),
- Application_Common_Database::COLUMN),
- new DateTimeZone("UTC"));
+ $instanceStart_sql,
+ [],
+ Application_Common_Database::COLUMN
+ ),
+ new DateTimeZone('UTC')
+ );
$defaultCrossfadeDuration = Application_Model_Preference::GetDefaultCrossfadeDuration();
unset($values);
- $values = array();
+ $values = [];
foreach ($linkedShowSchedule as $item) {
- $endTimeDT = self::findEndTime($nextStartDT,
- $item["clip_length"]);
+ $endTimeDT = self::findEndTime(
+ $nextStartDT,
+ $item['clip_length']
+ );
- if (is_null($item["file_id"])) {
- $item["file_id"] = "null";
+ if (is_null($item['file_id'])) {
+ $item['file_id'] = 'null';
}
- if (is_null($item["stream_id"])) {
- $item["stream_id"] = "null";
+ if (is_null($item['stream_id'])) {
+ $item['stream_id'] = 'null';
}
- $values[] = "(" . "'{$nextStartDT->format(DEFAULT_TIMESTAMP_FORMAT)}', " .
+ $values[] = '(' . "'{$nextStartDT->format(DEFAULT_TIMESTAMP_FORMAT)}', " .
"'{$endTimeDT->format(DEFAULT_TIMESTAMP_FORMAT)}', " .
- "'{$item["clip_length"]}', " .
- "'{$item["fade_in"]}', " . "'{$item["fade_out"]}', " .
- "'{$item["cue_in"]}', " . "'{$item["cue_out"]}', " .
- "{$item["file_id"]}, " . "{$item["stream_id"]}, " .
- "{$id}, " . "{$item["position"]})";
+ "'{$item['clip_length']}', " .
+ "'{$item['fade_in']}', " . "'{$item['fade_out']}', " .
+ "'{$item['cue_in']}', " . "'{$item['cue_out']}', " .
+ "{$item['file_id']}, " . "{$item['stream_id']}, " .
+ "{$id}, " . "{$item['position']})";
- $nextStartDT = self::findTimeDifference($endTimeDT,
- $defaultCrossfadeDuration);
+ $nextStartDT = self::findTimeDifference(
+ $endTimeDT,
+ $defaultCrossfadeDuration
+ );
} //foreach show item
if (!empty($values)) {
- $insert_sql = "INSERT INTO cc_schedule (starts, ends, " .
- "clip_length, fade_in, fade_out, cue_in, cue_out, " .
- "file_id, stream_id, instance_id, position) VALUES " .
- implode($values, ",");
+ $insert_sql = 'INSERT INTO cc_schedule (starts, ends, ' .
+ 'clip_length, fade_in, fade_out, cue_in, cue_out, ' .
+ 'file_id, stream_id, instance_id, position) VALUES ' .
+ implode($values, ',');
Application_Common_Database::prepareAndExecute(
- $insert_sql, array(), Application_Common_Database::EXECUTE);
+ $insert_sql,
+ [],
+ Application_Common_Database::EXECUTE
+ );
}
//update cc_schedule status column
@@ -298,18 +316,19 @@ class Application_Service_SchedulerService
$now = gmdate(DEFAULT_TIMESTAMP_FORMAT);
$whereClause = new Criteria();
$whereClause->add(CcShowInstancesPeer::ID, $instanceIdsToFill, Criteria::IN);
-
+
$updateClause = new Criteria();
$updateClause->add(CcShowInstancesPeer::TIME_FILLED, $timeFilled);
$updateClause->add(CcShowInstancesPeer::LAST_SCHEDULED, $now);
-
+
BasePeer::doUpdate($whereClause, $updateClause, $con);
- $con->commit();
- Logging::info("finished fill");
+ $con->commit();
+ Logging::info('finished fill');
} catch (Exception $e) {
$con->rollback();
- Logging::info("Error filling linked shows: ".$e->getMessage());
+ Logging::info('Error filling linked shows: ' . $e->getMessage());
+
exit();
}
}
@@ -322,10 +341,10 @@ class Application_Service_SchedulerService
foreach ($ccShow->getCcShowInstancess() as $ccShowInstance) {
$ccSchedules = CcScheduleQuery::create()
->filterByDbInstanceId($ccShowInstance->getDbId())
- ->find();
+ ->find()
+ ;
if ($ccSchedules->isEmpty()) {
-
$nextStartDT = $ccShowInstance->getDbStarts(null);
foreach ($showStamp as $item) {
@@ -344,16 +363,20 @@ class Application_Service_SchedulerService
->setDbCueOut($item->getDbCueOut())
->setDbInstanceId($ccShowInstance->getDbId())
->setDbPosition($item->getDbPosition())
- ->save();
+ ->save()
+ ;
- $nextStartDT = self::findTimeDifference($endTimeDT,
- Application_Model_Preference::GetDefaultCrossfadeDuration());
+ $nextStartDT = self::findTimeDifference(
+ $endTimeDT,
+ Application_Model_Preference::GetDefaultCrossfadeDuration()
+ );
} //foreach show item
$ccShowInstance
->setDbTimeFilled($timeFilled)
->setDbLastScheduled(gmdate(DEFAULT_TIMESTAMP_FORMAT))
- ->save();
+ ->save()
+ ;
}
}
}
@@ -363,11 +386,11 @@ class Application_Service_SchedulerService
{
//Application_Common_Database::prepareAndExecute($delete_sql, array(), Application_Common_Database::EXECUTE);
$con = Propel::getConnection();
- $query = $con->prepare("DELETE FROM cc_schedule WHERE instance_id = :instance_id");
+ $query = $con->prepare('DELETE FROM cc_schedule WHERE instance_id = :instance_id');
$query->bindParam(':instance_id', $instanceId);
$query->execute();
}
-
+
/*
private static function replaceInstanceContentCheck($currentShowStamp, $showStamp, $instance_id)
{
@@ -398,7 +421,7 @@ class Application_Service_SchedulerService
//If we get here, the content in the show instance is the same
// as what we want to replace it with, so we can leave as is
-
+
return false;
}*/
@@ -407,8 +430,8 @@ class Application_Service_SchedulerService
try {
$ccShowInstance = CcShowInstancesQuery::create()->findPk($instanceId);
- $instances = array();
- $instanceIds = array();
+ $instances = [];
+ $instanceIds = [];
if ($ccShowInstance->getCcShow()->isLinked()) {
foreach ($ccShowInstance->getCcShow()->getFutureCcShowInstancess() as $instance) {
@@ -427,16 +450,18 @@ class Application_Service_SchedulerService
$ccSchedules = CcScheduleQuery::create()
->filterByDbInstanceId($instanceIds, Criteria::IN)
->setDistinct(CcSchedulePeer::FILE_ID)
- ->find();
- $fileIds = array();
+ ->find()
+ ;
+ $fileIds = [];
foreach ($ccSchedules as $ccSchedule) {
$fileIds[] = $ccSchedule->getDbFileId();
}
- /* Clear out the schedule */
+ // Clear out the schedule
CcScheduleQuery::create()
->filterByDbInstanceId($instanceIds, Criteria::IN)
- ->delete();
+ ->delete()
+ ;
/* Now that the schedule has been cleared we need to make
* sure we do not update the is_scheduled flag for tracks
@@ -464,27 +489,25 @@ class Application_Service_SchedulerService
return true;
} catch (Exception $e) {
Logging::info($e->getMessage());
+
return false;
}
}
-
- /*
- * TODO in the future this should probably support webstreams.
- */
- public function updateFutureIsScheduled($scheduleId, $status)
+
+ // TODO in the future this should probably support webstreams.
+ public function updateFutureIsScheduled($scheduleId, $status)
{
- $sched = CcScheduleQuery::create()->findPk($scheduleId);
- $redraw = false;
-
- if (isset($sched)) {
-
- $fileId = $sched->getDbFileId();
-
- if (isset($fileId)) {
- $redraw = Application_Model_StoredFile::setIsScheduled($fileId, $status);
- }
- }
-
- return $redraw;
+ $sched = CcScheduleQuery::create()->findPk($scheduleId);
+ $redraw = false;
+
+ if (isset($sched)) {
+ $fileId = $sched->getDbFileId();
+
+ if (isset($fileId)) {
+ $redraw = Application_Model_StoredFile::setIsScheduled($fileId, $status);
+ }
+ }
+
+ return $redraw;
}
}
diff --git a/legacy/application/services/ShowFormService.php b/legacy/application/services/ShowFormService.php
index 765058825..20d959a80 100644
--- a/legacy/application/services/ShowFormService.php
+++ b/legacy/application/services/ShowFormService.php
@@ -1,4 +1,5 @@
ccShow = CcShowQuery::create()->findPk($showId);
}
-
+
$this->instanceId = $instanceId;
}
/**
- *
* @return array of show forms
*/
public function createShowForms()
{
- $formWhat = new Application_Form_AddShowWhat();
+ $formWhat = new Application_Form_AddShowWhat();
$formAutoPlaylist = new Application_Form_AddShowAutoPlaylist();
- $formWho = new Application_Form_AddShowWho();
- $formWhen = new Application_Form_AddShowWhen();
+ $formWho = new Application_Form_AddShowWho();
+ $formWhen = new Application_Form_AddShowWhen();
$formRepeats = new Application_Form_AddShowRepeats();
- $formStyle = new Application_Form_AddShowStyle();
- $formLive = new Application_Form_AddShowLiveStream();
+ $formStyle = new Application_Form_AddShowStyle();
+ $formLive = new Application_Form_AddShowLiveStream();
$formRecord = new Application_Form_AddShowRR();
$formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates();
$formRebroadcast = new Application_Form_AddShowRebroadcastDates();
@@ -41,101 +41,105 @@ class Application_Service_ShowFormService
$formAbsoluteRebroadcast->removeDecorator('DtDdWrapper');
$formRebroadcast->removeDecorator('DtDdWrapper');
- $forms = array();
- $forms["what"] = $formWhat;
- $forms["autoplaylist"] = $formAutoPlaylist;
- $forms["who"] = $formWho;
- $forms["when"] = $formWhen;
- $forms["repeats"] = $formRepeats;
- $forms["style"] = $formStyle;
- $forms["live"] = $formLive;
- $forms["record"] = $formRecord;
- $forms["abs_rebroadcast"] = $formAbsoluteRebroadcast;
- $forms["rebroadcast"] = $formRebroadcast;
+ $forms = [];
+ $forms['what'] = $formWhat;
+ $forms['autoplaylist'] = $formAutoPlaylist;
+ $forms['who'] = $formWho;
+ $forms['when'] = $formWhen;
+ $forms['repeats'] = $formRepeats;
+ $forms['style'] = $formStyle;
+ $forms['live'] = $formLive;
+ $forms['record'] = $formRecord;
+ $forms['abs_rebroadcast'] = $formAbsoluteRebroadcast;
+ $forms['rebroadcast'] = $formRebroadcast;
return $forms;
}
/**
- *
* Popluates the what, autoplaylist, when, and repeat forms
- * with default values
+ * with default values.
+ *
+ * @param mixed $formWhat
+ * @param mixed $formWhen
+ * @param mixed $formRepeats
*/
public function populateNewShowForms($formWhat, $formWhen, $formRepeats)
{
$formWhat->populate(
- array('add_show_id' => '-1',
- 'add_show_instance_id' => '-1'));
+ ['add_show_id' => '-1',
+ 'add_show_instance_id' => '-1', ]
+ );
$formWhen->populate(
- array('add_show_start_date' => date("Y-m-d"),
- 'add_show_start_time' => '00:00',
- 'add_show_end_date_no_repeate' => date("Y-m-d"),
- 'add_show_end_time' => '01:00',
- 'add_show_duration' => '01h 00m'));
+ ['add_show_start_date' => date('Y-m-d'),
+ 'add_show_start_time' => '00:00',
+ 'add_show_end_date_no_repeate' => date('Y-m-d'),
+ 'add_show_end_time' => '01:00',
+ 'add_show_duration' => '01h 00m', ]
+ );
- $formRepeats->populate(array('add_show_end_date' => date("Y-m-d")));
+ $formRepeats->populate(['add_show_end_date' => date('Y-m-d')]);
}
public function delegateShowInstanceFormPopulation($forms)
{
- $this->populateFormWhat($forms["what"]);
- $this->populateInstanceFormWhen($forms["when"]);
- $this->populateFormWho($forms["who"]);
- $this->populateFormLive($forms["live"]);
- $this->populateFormStyle($forms["style"]);
+ $this->populateFormWhat($forms['what']);
+ $this->populateInstanceFormWhen($forms['when']);
+ $this->populateFormWho($forms['who']);
+ $this->populateFormLive($forms['live']);
+ $this->populateFormStyle($forms['style']);
/* Only the field on the 'when' form will get updated so we should
* make all other forms disabled or readonly
- *
+ *
* 'what' needs to be readonly because zendform will not validate
* if they are disabled
- *
+ *
* All other forms can be disabled because we do not update those values
* when the user edits a repeating instance
*/
- $forms["what"]->makeReadonly();
- $forms["what"]->enableInstanceDesc();
- $forms["autoplaylist"]->disable();
- $forms["repeats"]->disable();
- $forms["who"]->disable();
- $forms["style"]->disable();
+ $forms['what']->makeReadonly();
+ $forms['what']->enableInstanceDesc();
+ $forms['autoplaylist']->disable();
+ $forms['repeats']->disable();
+ $forms['who']->disable();
+ $forms['style']->disable();
// Hide the show logo fields when users are editing a single instance
- $forms["style"]->hideShowLogo();
- $forms["live"]->disable();
- $forms["record"]->disable();
- $forms["rebroadcast"]->disable();
- $forms["abs_rebroadcast"]->disable();
+ $forms['style']->hideShowLogo();
+ $forms['live']->disable();
+ $forms['record']->disable();
+ $forms['rebroadcast']->disable();
+ $forms['abs_rebroadcast']->disable();
}
/**
- *
* Delegates populating each show form with the appropriate
- * data of the current show being edited
- *
+ * data of the current show being edited.
+ *
* @param $forms
*/
public function delegateShowFormPopulation($forms)
{
- $this->populateFormWhat($forms["what"]);
+ $this->populateFormWhat($forms['what']);
//local show start DT
- $this->populateFormAutoPlaylist($forms["autoplaylist"]);
- $showStart = $this->populateFormWhen($forms["when"]);
- $this->populateFormRepeats($forms["repeats"], $showStart);
- $this->populateFormWho($forms["who"]);
- $this->populateFormStyle($forms["style"]);
- $this->populateFormLive($forms["live"]);
- $this->populateFormRecord($forms["record"]);
- $this->populateFormRebroadcastRelative($forms["rebroadcast"]);
- $this->populateFormRebroadcastAbsolute($forms["abs_rebroadcast"]);
+ $this->populateFormAutoPlaylist($forms['autoplaylist']);
+ $showStart = $this->populateFormWhen($forms['when']);
+ $this->populateFormRepeats($forms['repeats'], $showStart);
+ $this->populateFormWho($forms['who']);
+ $this->populateFormStyle($forms['style']);
+ $this->populateFormLive($forms['live']);
+ $this->populateFormRecord($forms['record']);
+ $this->populateFormRebroadcastRelative($forms['rebroadcast']);
+ $this->populateFormRebroadcastAbsolute($forms['abs_rebroadcast']);
}
private function populateFormWhat($form)
{
$ccShowInstance = CcShowInstancesQuery::create()->findPk($this->instanceId);
-
+
$form->populate(
- array(
+ [
'add_show_instance_id' => $this->instanceId,
'add_show_id' => $this->ccShow->getDbId(),
'add_show_name' => $this->ccShow->getDbName(),
@@ -143,24 +147,24 @@ class Application_Service_ShowFormService
'add_show_genre' => $this->ccShow->getDbGenre(),
'add_show_description' => $this->ccShow->getDbDescription(),
'add_show_instance_description' => $ccShowInstance->getDbDescription(),
- ));
+ ]
+ );
}
private function populateFormAutoPlaylist($form)
{
$ccShowInstance = CcShowInstancesQuery::create()->findPk($this->instanceId);
-
+
$form->populate(
- array(
- 'add_show_has_autoplaylist' => $this->ccShow->getDbHasAutoPlaylist() ? 1 : 0,
- 'add_show_autoplaylist_id' => $this->ccShow->getDbAutoPlaylistId(),
- 'add_show_autoplaylist_repeat' => $this->ccShow->getDbAutoPlaylistRepeat()
-
- ));
+ [
+ 'add_show_has_autoplaylist' => $this->ccShow->getDbHasAutoPlaylist() ? 1 : 0,
+ 'add_show_autoplaylist_id' => $this->ccShow->getDbAutoPlaylistId(),
+ 'add_show_autoplaylist_repeat' => $this->ccShow->getDbAutoPlaylistRepeat(),
+ ]
+ );
}
-
- private function populateFormWhen($form)
+ private function populateFormWhen($form)
{
if ($this->ccShow->isRepeating()) {
$ccShowDay = $this->ccShow->getFirstRepeatingCcShowDay();
@@ -180,8 +184,8 @@ class Application_Service_ShowFormService
} else {
$showStartAndEnd = $this->getNextFutureRepeatShowTime();
if (!is_null($showStartAndEnd)) {
- $showStart = $showStartAndEnd["starts"];
- $showEnd = $showStartAndEnd["ends"];
+ $showStart = $showStartAndEnd['starts'];
+ $showEnd = $showStartAndEnd['ends'];
}
if ($this->hasShowStarted($showStart)) {
$form->disableStartDateAndTime();
@@ -190,17 +194,18 @@ class Application_Service_ShowFormService
}
//Disable starting a show 'now' when editing an existing show.
- $form->getElement('add_show_start_now')->setAttrib('disable', array('now'));
+ $form->getElement('add_show_start_now')->setAttrib('disable', ['now']);
$form->populate(
- array(
- 'add_show_start_date' => $showStart->format("Y-m-d"),
- 'add_show_start_time' => $showStart->format("H:i"),
- 'add_show_end_date_no_repeat' => $showEnd->format("Y-m-d"),
- 'add_show_end_time' => $showEnd->format("H:i"),
+ [
+ 'add_show_start_date' => $showStart->format('Y-m-d'),
+ 'add_show_start_time' => $showStart->format('H:i'),
+ 'add_show_end_date_no_repeat' => $showEnd->format('Y-m-d'),
+ 'add_show_end_time' => $showEnd->format('H:i'),
'add_show_duration' => $ccShowDay->formatDuration(true),
'add_show_timezone' => $ccShowDay->getDbTimezone(),
- 'add_show_repeats' => $ccShowDay->isRepeating() ? 1 : 0));
+ 'add_show_repeats' => $ccShowDay->isRepeating() ? 1 : 0, ]
+ );
return $showStart;
}
@@ -210,22 +215,23 @@ class Application_Service_ShowFormService
$ccShowInstance = CcShowInstancesQuery::create()
->filterByDbShowId($this->ccShow->getDbId())
->filterByDbModifiedInstance(false)
- ->filterByDbStarts(gmdate("Y-m-d H:i:s"), Criteria::GREATER_THAN)
+ ->filterByDbStarts(gmdate('Y-m-d H:i:s'), Criteria::GREATER_THAN)
->orderByDbStarts()
- ->findOne();
+ ->findOne()
+ ;
if (!$ccShowInstance) {
return null;
}
- $starts = new DateTime($ccShowInstance->getDbStarts(), new DateTimeZone("UTC"));
- $ends = new DateTime($ccShowInstance->getDbEnds(), new DateTimeZone("UTC"));
+ $starts = new DateTime($ccShowInstance->getDbStarts(), new DateTimeZone('UTC'));
+ $ends = new DateTime($ccShowInstance->getDbEnds(), new DateTimeZone('UTC'));
$showTimezone = $this->ccShow->getFirstCcShowDay()->getDbTimezone();
$starts->setTimezone(new DateTimeZone($showTimezone));
$ends->setTimezone(new DateTimeZone($showTimezone));
- return array("starts" => $starts, "ends" => $ends);
+ return ['starts' => $starts, 'ends' => $ends];
}
private function populateInstanceFormWhen($form)
@@ -249,26 +255,30 @@ class Application_Service_ShowFormService
}
//Disable starting a show 'now' when editing an existing show.
- $form->getElement('add_show_start_now')->setAttrib('disable', array('now'));
+ $form->getElement('add_show_start_now')->setAttrib('disable', ['now']);
$form->populate(
- array(
+ [
'add_show_start_now' => 'future',
- 'add_show_start_date' => $showStart->format("Y-m-d"),
- 'add_show_start_time' => $showStart->format("H:i"),
- 'add_show_end_date_no_repeat' => $showEnd->format("Y-m-d"),
- 'add_show_end_time' => $showEnd->format("H:i"),
+ 'add_show_start_date' => $showStart->format('Y-m-d'),
+ 'add_show_start_time' => $showStart->format('H:i'),
+ 'add_show_end_date_no_repeat' => $showEnd->format('Y-m-d'),
+ 'add_show_end_time' => $showEnd->format('H:i'),
'add_show_duration' => $this->calculateDuration(
- $showStart->format(DEFAULT_TIMESTAMP_FORMAT), $showEnd->format(DEFAULT_TIMESTAMP_FORMAT), $timezone),
+ $showStart->format(DEFAULT_TIMESTAMP_FORMAT),
+ $showEnd->format(DEFAULT_TIMESTAMP_FORMAT),
+ $timezone
+ ),
'add_show_timezone' => $timezone,
- 'add_show_repeats' => 0));
+ 'add_show_repeats' => 0, ]
+ );
- $form->getElement('add_show_repeats')->setOptions(array("disabled" => true));
+ $form->getElement('add_show_repeats')->setOptions(['disabled' => true]);
}
/**
- *
* Enter description here ...
+ *
* @param $form
* @param DateTime $nextFutureShowStart user's local timezone
*/
@@ -280,10 +290,10 @@ class Application_Service_ShowFormService
$ccShowDays = $this->ccShow->getCcShowDayss();
}
- $days = array();
+ $days = [];
foreach ($ccShowDays as $ccShowDay) {
$showStart = $ccShowDay->getLocalStartDateAndTime();
- array_push($days, $showStart->format("w"));
+ array_push($days, $showStart->format('w'));
}
$service_show = new Application_Service_ShowService($this->ccShow->getDbId());
@@ -291,9 +301,9 @@ class Application_Service_ShowFormService
//end dates are stored non-inclusively so we need to
//subtract one day
if (!is_null($repeatEndDate)) {
- $repeatEndDate->sub(new DateInterval("P1D"));
+ $repeatEndDate->sub(new DateInterval('P1D'));
}
-
+
//default monthly repeat type
$monthlyRepeatType = 2;
$repeatType = $ccShowDays[0]->getDbRepeatType();
@@ -306,22 +316,23 @@ class Application_Service_ShowFormService
}
$form->populate(
- array(
+ [
'add_show_linked' => $this->ccShow->getDbLinked(),
'add_show_repeat_type' => $repeatType,
'add_show_day_check' => $days,
- 'add_show_end_date' => (!is_null($repeatEndDate)) ? $repeatEndDate->format("Y-m-d"):null,
+ 'add_show_end_date' => (!is_null($repeatEndDate)) ? $repeatEndDate->format('Y-m-d') : null,
'add_show_no_end' => (is_null($repeatEndDate)),
- 'add_show_monthly_repeat_type' => $monthlyRepeatType));
+ 'add_show_monthly_repeat_type' => $monthlyRepeatType, ]
+ );
if (!$this->ccShow->isLinkable() || $this->ccShow->isRecorded()) {
- $form->getElement('add_show_linked')->setOptions(array('disabled' => true));
+ $form->getElement('add_show_linked')->setOptions(['disabled' => true]);
}
/* Because live editing of a linked show is disabled, we will make
* the linking option readonly if the current show is being edited. We
* dont' want the user to suddenly not be able to edit the current show
- *
+ *
* Readonly does not work with checkboxes but we can't disable it
* because the value won't get posted. In add-show.js we stop the
* onclick event from firing by returning false
@@ -335,86 +346,93 @@ class Application_Service_ShowFormService
{
$ccShowHosts = $this->ccShow->getCcShowHostss();
- $hosts = array();
+ $hosts = [];
foreach ($ccShowHosts as $ccShowHost) {
array_push($hosts, $ccShowHost->getDbHost());
}
- $form->populate(array('add_show_hosts' => $hosts));
+ $form->populate(['add_show_hosts' => $hosts]);
}
private function populateFormStyle($form)
{
- $src = $this->ccShow->getDbImagePath() ?
+ $src = $this->ccShow->getDbImagePath() ?
$this->imagePathToDataUri($this->ccShow->getDbImagePath()) : '';
-
+
$form->populate(
- array(
+ [
'add_show_background_color' => $this->ccShow->getDbBackgroundColor(),
'add_show_color' => $this->ccShow->getDbColor(),
- 'add_show_logo_current' => $src));
+ 'add_show_logo_current' => $src, ]
+ );
}
-
+
/**
- * Convert a static image from disk to a base64 data URI
- *
+ * Convert a static image from disk to a base64 data URI.
+ *
* @param unknown $path
- * - the path to the image on the disk
+ * - the path to the image on the disk
+ *
* @return string
- * - the data URI representation of the image
+ * - the data URI representation of the image
*/
- private function imagePathToDataUri($path) {
+ private function imagePathToDataUri($path)
+ {
$imageData = null;
$bytesRead = 0;
+
try {
ob_start();
- header("Content-type: image/*");
+ header('Content-type: image/*');
$bytesRead = @readfile($path);
$imageData = base64_encode(ob_get_contents());
ob_end_clean();
- if ($bytesRead === FALSE) {
+ if ($bytesRead === false) {
$imageData = null;
}
} catch (Exception $e) {
- Logging::error("Failed to read image: " . $path);
+ Logging::error('Failed to read image: ' . $path);
$imageData = null;
}
// return the data URI - data:{mime};base64,{data}
- return ($imageData === null || $imageData === '') ?
- '' : 'data: '.mime_content_type($path).';base64,'.$imageData;
+ return ($imageData === null || $imageData === '') ?
+ '' : 'data: ' . mime_content_type($path) . ';base64,' . $imageData;
}
private function populateFormLive($form)
{
$form->populate(
- array(
- "cb_airtime_auth" => $this->ccShow->getDbLiveStreamUsingAirtimeAuth(),
- "cb_custom_auth" => $this->ccShow->getDbLiveStreamUsingCustomAuth(),
- "custom_username" => $this->ccShow->getDbLiveStreamUser(),
- "custom_password" => $this->ccShow->getDbLiveStreamPass()));
+ [
+ 'cb_airtime_auth' => $this->ccShow->getDbLiveStreamUsingAirtimeAuth(),
+ 'cb_custom_auth' => $this->ccShow->getDbLiveStreamUsingCustomAuth(),
+ 'custom_username' => $this->ccShow->getDbLiveStreamUser(),
+ 'custom_password' => $this->ccShow->getDbLiveStreamPass(), ]
+ );
}
private function populateFormRecord($form)
{
$form->populate(
- array(
+ [
'add_show_record' => $this->ccShow->isRecorded(),
- 'add_show_rebroadcast' => $this->ccShow->isRebroadcast()));
+ 'add_show_rebroadcast' => $this->ccShow->isRebroadcast(), ]
+ );
- $form->getElement('add_show_record')->setOptions(array('disabled' => true));
+ $form->getElement('add_show_record')->setOptions(['disabled' => true]);
}
private function populateFormRebroadcastRelative($form)
{
$relativeRebroadcasts = $this->ccShow->getRebroadcastsRelative();
- $formValues = array();
+ $formValues = [];
$i = 1;
foreach ($relativeRebroadcasts as $rr) {
- $formValues["add_show_rebroadcast_date_$i"] = $rr->getDbDayOffset();
- $formValues["add_show_rebroadcast_time_$i"] = Application_Common_DateHelper::removeSecondsFromTime(
- $rr->getDbStartTime());
- $i++;
+ $formValues["add_show_rebroadcast_date_{$i}"] = $rr->getDbDayOffset();
+ $formValues["add_show_rebroadcast_time_{$i}"] = Application_Common_DateHelper::removeSecondsFromTime(
+ $rr->getDbStartTime()
+ );
+ ++$i;
}
$form->populate($formValues);
@@ -425,47 +443,49 @@ class Application_Service_ShowFormService
$absolutRebroadcasts = $this->ccShow->getRebroadcastsAbsolute();
$timezone = $this->ccShow->getFirstCcShowDay()->getDbTimezone();
- $formValues = array();
+ $formValues = [];
$i = 1;
foreach ($absolutRebroadcasts as $ar) {
//convert dates to user's local time
- $start = new DateTime($ar->getDbStarts(), new DateTimeZone("UTC"));
+ $start = new DateTime($ar->getDbStarts(), new DateTimeZone('UTC'));
$start->setTimezone(new DateTimeZone($timezone));
- $formValues["add_show_rebroadcast_date_absolute_$i"] = $start->format("Y-m-d");
- $formValues["add_show_rebroadcast_time_absolute_$i"] = $start->format("H:i");
- $i++;
+ $formValues["add_show_rebroadcast_date_absolute_{$i}"] = $start->format('Y-m-d');
+ $formValues["add_show_rebroadcast_time_absolute_{$i}"] = $start->format('H:i');
+ ++$i;
}
$form->populate($formValues);
}
/**
- *
* Enter description here ...
- * @param DateTime $showStart user's local time
+ *
+ * @param DateTime $showStart user's local time
+ * @param mixed $p_showStart
*/
- private function hasShowStarted($p_showStart) {
+ private function hasShowStarted($p_showStart)
+ {
$showStart = clone $p_showStart;
- $showStart->setTimeZone(new DateTimeZone("UTC"));
+ $showStart->setTimeZone(new DateTimeZone('UTC'));
- if ($showStart->format("Y-m-d H:i:s") < gmdate("Y-m-d H:i:s")) {
+ if ($showStart->format('Y-m-d H:i:s') < gmdate('Y-m-d H:i:s')) {
return true;
- } else {
- return false;
}
+
+ return false;
}
/**
* Before we send the form data in for validation, there
- * are a few fields we may need to adjust first
- *
+ * are a few fields we may need to adjust first.
+ *
* @param $formData
*/
public function preEditShowValidationCheck($formData)
{
// If the start date or time were disabled, don't validate them
- $validateStartDate = $formData['start_date_disabled'] === "false";
- $validateStartTime = $formData['start_time_disabled'] === "false";
+ $validateStartDate = $formData['start_date_disabled'] === 'false';
+ $validateStartTime = $formData['start_time_disabled'] === 'false';
//CcShowDays object of the show currently being edited
$currentShowDay = $this->ccShow->getFirstCcShowDay();
@@ -481,13 +501,12 @@ class Application_Service_ShowFormService
$originalShowStartDateTime = $dt;
}
- return array($formData, $validateStartDate, $validateStartTime, $originalShowStartDateTime);
+ return [$formData, $validateStartDate, $validateStartTime, $originalShowStartDateTime];
}
/**
- *
* Returns a DateTime object, in the user's local time,
- * of the current or next show instance start time
+ * of the current or next show instance start time.
*
* Returns null if there is no next future repeating show instance
*/
@@ -496,15 +515,16 @@ class Application_Service_ShowFormService
$ccShowInstance = CcShowInstancesQuery::create()
->filterByDbShowId($this->ccShow->getDbId())
->filterByDbModifiedInstance(false)
- ->filterByDbStarts(gmdate("Y-m-d H:i:s"), Criteria::GREATER_EQUAL)
+ ->filterByDbStarts(gmdate('Y-m-d H:i:s'), Criteria::GREATER_EQUAL)
->orderByDbStarts()
- ->findOne();
+ ->findOne()
+ ;
if (!$ccShowInstance) {
return null;
}
-
- $starts = new DateTime($ccShowInstance->getDbStarts(), new DateTimeZone("UTC"));
+
+ $starts = new DateTime($ccShowInstance->getDbStarts(), new DateTimeZone('UTC'));
$showTimezone = $this->ccShow->getFirstCcShowDay()->getDbTimezone();
$starts->setTimezone(new DateTimeZone($showTimezone));
@@ -512,53 +532,69 @@ class Application_Service_ShowFormService
return $starts;
}
-
/**
- *
- * Validates show forms
- *
- * @return boolean
+ * Validates show forms.
+ *
+ * @param mixed $forms
+ * @param mixed $formData
+ * @param mixed $validateStartDate
+ * @param null|mixed $originalStartDate
+ * @param mixed $editShow
+ * @param null|mixed $instanceId
+ *
+ * @return bool
*/
- public function validateShowForms($forms, $formData, $validateStartDate = true,
- $originalStartDate=null, $editShow=false, $instanceId=null)
- {
- $what = $forms["what"]->isValid($formData);
- $autoplaylist = $forms["autoplaylist"]->isValid($formData);
- $live = $forms["live"]->isValid($formData);
- $record = $forms["record"]->isValid($formData);
- $who = $forms["who"]->isValid($formData);
-
+ public function validateShowForms(
+ $forms,
+ $formData,
+ $validateStartDate = true,
+ $originalStartDate = null,
+ $editShow = false,
+ $instanceId = null
+ ) {
+ $what = $forms['what']->isValid($formData);
+ $autoplaylist = $forms['autoplaylist']->isValid($formData);
+ $live = $forms['live']->isValid($formData);
+ $record = $forms['record']->isValid($formData);
+ $who = $forms['who']->isValid($formData);
+
/*
* hack to prevent validating the file upload field since it
* isn't passed into $data
*/
- $upload = $forms["style"]->getElement("add_show_logo");
- $forms["style"]->removeElement("add_show_logo");
-
- $style = $forms["style"]->isValid($formData);
-
+ $upload = $forms['style']->getElement('add_show_logo');
+ $forms['style']->removeElement('add_show_logo');
+
+ $style = $forms['style']->isValid($formData);
+
// re-add the upload element
- $forms["style"]->addElement($upload);
-
- $when = $forms["when"]->isWhenFormValid($formData, $validateStartDate,
- $originalStartDate, $editShow, $instanceId);
+ $forms['style']->addElement($upload);
+
+ $when = $forms['when']->isWhenFormValid(
+ $formData,
+ $validateStartDate,
+ $originalStartDate,
+ $editShow,
+ $instanceId
+ );
$repeats = true;
- if ($formData["add_show_repeats"]) {
- $repeats = $forms["repeats"]->isValid($formData);
+ if ($formData['add_show_repeats']) {
+ $repeats = $forms['repeats']->isValid($formData);
/*
* Make the absolute rebroadcast form valid since
* it does not get used if the show is repeating
*/
- $forms["abs_rebroadcast"]->reset();
+ $forms['abs_rebroadcast']->reset();
$absRebroadcast = true;
$rebroadcast = true;
- if (isset($formData["add_show_rebroadcast"]) && $formData["add_show_rebroadcast"]) {
- $formData["add_show_duration"] = Application_Service_ShowService::formatShowDuration(
- $formData["add_show_duration"]);
- $rebroadcast = $forms["rebroadcast"]->isValid($formData);
+ if (isset($formData['add_show_rebroadcast']) && $formData['add_show_rebroadcast']) {
+ $formData['add_show_duration'] = Application_Service_ShowService::formatShowDuration(
+ $formData['add_show_duration']
+ );
+ $rebroadcast = $forms['rebroadcast']->isValid($formData);
}
} else {
/*
@@ -566,25 +602,25 @@ class Application_Service_ShowFormService
* not get used if the show is not repeating.
* Instead, we use the absolute rebroadcast form
*/
- $forms["rebroadcast"]->reset();
+ $forms['rebroadcast']->reset();
$rebroadcast = true;
$absRebroadcast = true;
- if (isset($formData["add_show_rebroadcast"]) && $formData["add_show_rebroadcast"]) {
- $formData["add_show_duration"] = Application_Service_ShowService::formatShowDuration(
- $formData["add_show_duration"]);
- $absRebroadcast = $forms["abs_rebroadcast"]->isValid($formData);
+ if (isset($formData['add_show_rebroadcast']) && $formData['add_show_rebroadcast']) {
+ $formData['add_show_duration'] = Application_Service_ShowService::formatShowDuration(
+ $formData['add_show_duration']
+ );
+ $absRebroadcast = $forms['abs_rebroadcast']->isValid($formData);
}
}
- return ($what && $autoplaylist && $live && $record && $who && $style && $when &&
- $repeats && $absRebroadcast && $rebroadcast);
+ return $what && $autoplaylist && $live && $record && $who && $style && $when
+ && $repeats && $absRebroadcast && $rebroadcast;
}
-
+
public function calculateDuration($start, $end, $timezone)
{
try {
-
$tz = new DateTimeZone($timezone);
$startDateTime = new DateTime($start, $tz);
$endDateTime = new DateTime($end, $tz);
@@ -598,33 +634,37 @@ class Application_Service_ShowFormService
$hour += $day * 24;
$hour = min($hour, 99);
$sign = $duration->format('%r');
+
return sprintf('%s%02dh %02dm', $sign, $hour, $min);
- } else {
- return $duration->format('%r%Hh %Im');
}
+
+ return $duration->format('%r%Hh %Im');
} catch (Exception $e) {
Logging::info($e->getMessage());
- return "Invalid Date";
+
+ return 'Invalid Date';
}
}
/**
* When the timezone is changed in add-show form this function
- * applies the new timezone to the start and end time
+ * applies the new timezone to the start and end time.
*
* @param $date String
* @param $time String
* @param $timezone String
+ * @param mixed $newTimezone
+ * @param mixed $oldTimezone
*/
public static function localizeDateTime($date, $time, $newTimezone, $oldTimezone)
{
- $dt = new DateTime($date." ".$time, new DateTimeZone($oldTimezone));
+ $dt = new DateTime($date . ' ' . $time, new DateTimeZone($oldTimezone));
$dt->setTimeZone(new DateTimeZone($newTimezone));
- return array(
- "date" => $dt->format("Y-m-d"),
- "time" => $dt->format("H:i")
- );
+ return [
+ 'date' => $dt->format('Y-m-d'),
+ 'time' => $dt->format('H:i'),
+ ];
}
}
diff --git a/legacy/application/services/ShowService.php b/legacy/application/services/ShowService.php
index 61cfddc76..3d718a612 100644
--- a/legacy/application/services/ShowService.php
+++ b/legacy/application/services/ShowService.php
@@ -1,12 +1,13 @@
ccShow = CcShowQuery::create()->findPk($showId);
}
- if (isset($showData["add_show_repeats"]) && $showData["add_show_repeats"]) {
- $this->repeatType = $showData["add_show_repeat_type"];
- if ($showData["add_show_repeat_type"] == 2) {
- $this->repeatType = $showData["add_show_monthly_repeat_type"];
+ if (isset($showData['add_show_repeats']) && $showData['add_show_repeats']) {
+ $this->repeatType = $showData['add_show_repeat_type'];
+ if ($showData['add_show_repeat_type'] == 2) {
+ $this->repeatType = $showData['add_show_monthly_repeat_type'];
}
} else {
$this->repeatType = -1;
@@ -45,70 +46,82 @@ class Application_Service_ShowService
$this->isRecorded = (isset($showData['add_show_record']) && $showData['add_show_record']) ? 1 : 0;
$this->isRebroadcast = (isset($showData['add_show_rebroadcast']) && $showData['add_show_rebroadcast']) ? 1 : 0;
$this->isUpdate = $isUpdate;
- $this->instanceIdsForScheduleUpdates = array();
- $this->newInstanceIdsCreated = array();
+ $this->instanceIdsForScheduleUpdates = [];
+ $this->newInstanceIdsCreated = [];
}
- public function editRepeatingShowInstance($showData) {
+ public function editRepeatingShowInstance($showData)
+ {
$service_user = new Application_Service_UserService();
$currentUser = $service_user->getCurrentUser();
- $showData["add_show_duration"] = $this->formatShowDuration(
- $showData["add_show_duration"]);
+ $showData['add_show_duration'] = $this->formatShowDuration(
+ $showData['add_show_duration']
+ );
$con = Propel::getConnection();
$con->beginTransaction();
+
try {
if (!$currentUser->isAdminOrPM()) {
- throw new Exception("Permission denied");
+ throw new Exception('Permission denied');
}
- $showId = $showData["add_show_id"];
+ $showId = $showData['add_show_id'];
- /****** UPDATE SCHEDULE START TIME ******/
+ // UPDATE SCHEDULE START TIME
//get the ccShow object to which this instance belongs
//so we can get the original start date and time
$this->ccShow = CcShowQuery::create()
- ->findPk($showId);
+ ->findPk($showId)
+ ;
//DateTime in shows's local time
- $newStartDateTime = new DateTime($showData["add_show_start_date"]." ".
- $showData["add_show_start_time"],
- new DateTimeZone($showData["add_show_timezone"]));
+ $newStartDateTime = new DateTime(
+ $showData['add_show_start_date'] . ' ' .
+ $showData['add_show_start_time'],
+ new DateTimeZone($showData['add_show_timezone'])
+ );
$ccShowInstanceOrig = CcShowInstancesQuery::create()
- ->findPk($showData["add_show_instance_id"]);
+ ->findPk($showData['add_show_instance_id'])
+ ;
//convert original start time into the show's local timezone
$origLocalStartDateTime = $ccShowInstanceOrig->getLocalStartDateTime();
- $diff = $this->calculateShowStartDiff($newStartDateTime,
- $origLocalStartDateTime);
+ $diff = $this->calculateShowStartDiff(
+ $newStartDateTime,
+ $origLocalStartDateTime
+ );
if ($diff != 0) {
Application_Service_SchedulerService::updateScheduleStartTime(
- array($showData["add_show_instance_id"]), $diff);
+ [$showData['add_show_instance_id']],
+ $diff
+ );
}
- /****** UPDATE SCHEDULE START TIME ENDS******/
+ // UPDATE SCHEDULE START TIME ENDS
/*
* In the case where an instance is being edited for a second
* (or third, fourth, etc.) time we need to delete the old
* cc_show_day record
- *
+ *
* Since we don't store the cc_show_day ids we need to use the
* original start time from cc_show_instances, convert it to the show's
* local timezone, and find the record in cc_show_days
- *
+ *
* *** There is a flaw here: We have to assume the show timezone has
* *** not changed (make timezone readonly??)
*/
$origCcShowDay = CcShowDaysQuery::create()
->filterByDbShowId($showId)
->filterByDbRepeatType(-1)
- ->filterByDbFirstShow($origLocalStartDateTime->format("Y-m-d"))
- ->filterByDbStartTime($origLocalStartDateTime->format("H:i:s"))
- ->delete();
+ ->filterByDbFirstShow($origLocalStartDateTime->format('Y-m-d'))
+ ->filterByDbStartTime($origLocalStartDateTime->format('H:i:s'))
+ ->delete()
+ ;
/*
* Set the new cc_show_day record
@@ -124,17 +137,20 @@ class Application_Service_ShowService
$showDay = CcShowDaysQuery::create()
->filterByDbShowId($showId)
->filterByDbRepeatType(-1)
- ->filterByDbFirstShow($showData["add_show_start_date"])
- ->filterByDbStartTime($showData["add_show_start_time"].":00")
- ->findOne();
+ ->filterByDbFirstShow($showData['add_show_start_date'])
+ ->filterByDbStartTime($showData['add_show_start_time'] . ':00')
+ ->findOne()
+ ;
- $ccShowInstance = $this->createNonRepeatingInstance($showDay,
- $this->getPopulateShowUntilDateTIme());
+ $ccShowInstance = $this->createNonRepeatingInstance(
+ $showDay,
+ $this->getPopulateShowUntilDateTIme()
+ );
//update cc_schedule with the new instance id
$con = Propel::getConnection(CcShowInstancesPeer::DATABASE_NAME);
$selectCriteria = new Criteria();
- $selectCriteria->add(CcSchedulePeer::INSTANCE_ID, $showData["add_show_instance_id"]);
+ $selectCriteria->add(CcSchedulePeer::INSTANCE_ID, $showData['add_show_instance_id']);
$updateCriteria = new Criteria();
$updateCriteria->add(CcSchedulePeer::INSTANCE_ID, $ccShowInstance->getDbId());
BasePeer::doUpdate($selectCriteria, $updateCriteria, $con);
@@ -143,28 +159,29 @@ class Application_Service_ShowService
$ccShowInstance->updateScheduleStatus($con);
$ccShowInstance
->setDbDescription($showData['add_show_instance_description'])
- ->save();
+ ->save()
+ ;
//delete the edited instance from the repeating sequence
$ccShowInstanceOrig
->setDbModifiedInstance(true)
->setDbDescription($showData['add_show_instance_description'])
- ->save();
+ ->save()
+ ;
$con->commit();
Application_Model_RabbitMq::PushSchedule();
} catch (Exception $e) {
$con->rollback();
- Logging::info("EXCEPTION: Show update failed.");
+ Logging::info('EXCEPTION: Show update failed.');
Logging::info($e->getMessage());
}
}
/**
- *
* If a user is editing a show we need to store the original timezone and
* start time in case the show's timezone is changed and we are crossing
- * over DST
+ * over DST.
*/
private function storeOrigLocalShowInfo()
{
@@ -178,42 +195,43 @@ class Application_Service_ShowService
$this->oldShowTimezone = $this->origCcShowDay->getDbTimezone();
- $origStartTime = explode(":", $this->origCcShowDay->getDbStartTime());
+ $origStartTime = explode(':', $this->origCcShowDay->getDbStartTime());
$this->localShowStartHour = $origStartTime[0];
$this->localShowStartMin = $origStartTime[1];
}
-
+
public function addUpdateShow($showData)
{
$service_user = new Application_Service_UserService();
$currentUser = $service_user->getCurrentUser();
- $showData["add_show_duration"] = $this->formatShowDuration(
- $showData["add_show_duration"]);
+ $showData['add_show_duration'] = $this->formatShowDuration(
+ $showData['add_show_duration']
+ );
$con = Propel::getConnection();
$con->beginTransaction();
+
try {
if (!$currentUser->isAdminOrPM()) {
- throw new Exception("Permission denied");
+ throw new Exception('Permission denied');
}
//update ccShow
$this->setCcShow($showData);
- $daysAdded = array();
+ $daysAdded = [];
if ($this->isUpdate) {
-
$showId = $this->ccShow->getDbId();
-
+
// Only delete the previous logo if a new one is being uploaded
- if (array_key_exists("add_show_logo_name", $showData) && $showData["add_show_logo_name"] !== "") {
+ if (array_key_exists('add_show_logo_name', $showData) && $showData['add_show_logo_name'] !== '') {
if (!Rest_ShowImageController::deleteShowImagesFromStor($showId)) {
- throw new Exception("Error deleting show images");
+ throw new Exception('Error deleting show images');
}
}
-
+
if (!$this->ccShow->getCcShowDayss()->isEmpty()) {
$this->storeOrigLocalShowInfo();
}
@@ -240,44 +258,41 @@ class Application_Service_ShowService
//update ccShowHosts
$this->setCcShowHosts($showData);
-
+
//create new ccShowInstances
$this->delegateInstanceCreation($daysAdded);
if ($this->isUpdate) {
-
/* If the show is repeating and the start date changes we need
* to ignore that difference when re-calculating schedule start times.
* Otherwise it might calculate a difference of a week, for example.
*/
- if ($this->ccShow->isRepeating() &&
- $this->origCcShowDay->getLocalStartDateAndTime()->format("Y-m-d") != $showData["add_show_start_date"]) {
- $showData["add_show_start_date"] = $this->origCcShowDay->getLocalStartDateAndTime()->format("Y-m-d");
+ if ($this->ccShow->isRepeating()
+ && $this->origCcShowDay->getLocalStartDateAndTime()->format('Y-m-d') != $showData['add_show_start_date']) {
+ $showData['add_show_start_date'] = $this->origCcShowDay->getLocalStartDateAndTime()->format('Y-m-d');
}
$this->adjustSchedule($showData);
-
}
$con->commit();
Application_Model_RabbitMq::PushSchedule();
} catch (Exception $e) {
$con->rollback();
- $this->isUpdate ? $action = "update" : $action = "creation";
- Logging::info("EXCEPTION: Show ".$action." failed.");
+ $this->isUpdate ? $action = 'update' : $action = 'creation';
+ Logging::info('EXCEPTION: Show ' . $action . ' failed.');
Logging::info($e->getMessage());
}
-
+
// Added to pass along to the RESTful ShowImageController
return $this->ccShow->getDbId();
}
/**
- *
* Returns an array of instance ids that already exist
- * We need this if a show is being updated so we can separate the
+ * We need this if a show is being updated so we can separate the
* instances that already exist and any new instances that
- * get created (by adding a new repeat show day)
+ * get created (by adding a new repeat show day).
*/
private function storeInstanceIds()
{
@@ -287,10 +302,10 @@ class Application_Service_ShowService
}
}
- /**
- *
+ /**
* Adjusts the items in cc_schedule to reflect the
- * new (if one) start and end time of the show getting updated
+ * new (if one) start and end time of the show getting updated.
+ *
* @param $showData
*/
private function adjustSchedule($showData)
@@ -306,11 +321,14 @@ class Application_Service_ShowService
}
/**
- *
* Receives a cc_show id and determines whether to create a
- * single show instance or repeating show instances
+ * single show instance or repeating show instances.
+ *
+ * @param null|mixed $daysAdded
+ * @param null|mixed $end
+ * @param mixed $fillInstances
*/
- public function delegateInstanceCreation($daysAdded=null, $end=null, $fillInstances=false)
+ public function delegateInstanceCreation($daysAdded = null, $end = null, $fillInstances = false)
{
$populateUntil = $this->getPopulateShowUntilDateTIme();
@@ -321,14 +339,15 @@ class Application_Service_ShowService
$ccShowDays = $this->ccShow->getRepeatingCcShowDays();
} else {
//$ccShowDays = $this->ccShow->getCcShowDayss();
-
+
/* Cannot use the above statement to get the cc_show_days
* object because it's getting the old object before the
* show was edited. clearInstancePool() didn't work.
*/
$ccShowDays = CcShowDaysQuery::create()
->filterByDbShowId($this->ccShow->getDbId())
- ->find();
+ ->find()
+ ;
}
}
@@ -340,10 +359,9 @@ class Application_Service_ShowService
* linked shows in the schedule we need to keep track of each cc_show
* so we know which shows need to be filled with content
*/
- $ccShows = array();
+ $ccShows = [];
foreach ($ccShowDays as $day) {
-
$this->ccShow = $day->getCcShow();
$this->isRecorded = $this->ccShow->isRecorded();
$this->isRebroadcast = $this->ccShow->isRebroadcast();
@@ -352,38 +370,71 @@ class Application_Service_ShowService
if (!isset($ccShows[$show_id])) {
$ccShows[$show_id] = $day->getccShow();
}
-
+
//keep track of the new show instances getting created
//so we can fill their schedule after
if (!isset($this->newInstanceIdsCreated[$show_id])) {
- $this->newInstanceIdsCreated[$show_id] = array();
+ $this->newInstanceIdsCreated[$show_id] = [];
}
switch ($day->getDbRepeatType()) {
case NO_REPEAT:
$this->createNonRepeatingInstance($day, $populateUntil);
+
break;
+
case REPEAT_WEEKLY:
- $this->createWeeklyRepeatInstances($day, $populateUntil, REPEAT_WEEKLY,
- new DateInterval("P7D"), $daysAdded);
+ $this->createWeeklyRepeatInstances(
+ $day,
+ $populateUntil,
+ REPEAT_WEEKLY,
+ new DateInterval('P7D'),
+ $daysAdded
+ );
+
break;
+
case REPEAT_BI_WEEKLY:
- $this->createWeeklyRepeatInstances($day, $populateUntil, REPEAT_BI_WEEKLY,
- new DateInterval("P14D"), $daysAdded);
+ $this->createWeeklyRepeatInstances(
+ $day,
+ $populateUntil,
+ REPEAT_BI_WEEKLY,
+ new DateInterval('P14D'),
+ $daysAdded
+ );
+
break;
+
case REPEAT_TRI_WEEKLY:
- $this->createWeeklyRepeatInstances($day, $populateUntil, REPEAT_TRI_WEEKLY,
- new DateInterval("P21D"), $daysAdded);
+ $this->createWeeklyRepeatInstances(
+ $day,
+ $populateUntil,
+ REPEAT_TRI_WEEKLY,
+ new DateInterval('P21D'),
+ $daysAdded
+ );
+
break;
+
case REPEAT_QUAD_WEEKLY:
- $this->createWeeklyRepeatInstances($day, $populateUntil, REPEAT_QUAD_WEEKLY,
- new DateInterval("P28D"), $daysAdded);
+ $this->createWeeklyRepeatInstances(
+ $day,
+ $populateUntil,
+ REPEAT_QUAD_WEEKLY,
+ new DateInterval('P28D'),
+ $daysAdded
+ );
+
break;
+
case REPEAT_MONTHLY_MONTHLY:
$this->createMonthlyRepeatInstances($day, $populateUntil);
+
break;
+
case REPEAT_MONTHLY_WEEKLY:
$this->createMonthlyRepeatInstances($day, $populateUntil);
+
break;
}
}
@@ -391,7 +442,9 @@ class Application_Service_ShowService
foreach ($ccShows as $ccShow) {
if (($this->isUpdate || $fillInstances) && $ccShow->isLinked()) {
Application_Service_SchedulerService::fillLinkedInstances(
- $ccShow, $this->newInstanceIdsCreated[$ccShow->getDbId()]);
+ $ccShow,
+ $this->newInstanceIdsCreated[$ccShow->getDbId()]
+ );
}
}
@@ -409,7 +462,7 @@ class Application_Service_ShowService
if (!is_null($start)) {
$startTimeString = $start->format(DEFAULT_TIMESTAMP_FORMAT);
} else {
- $today_timestamp = new DateTime("now", new DateTimeZone("UTC"));
+ $today_timestamp = new DateTime('now', new DateTimeZone('UTC'));
$startTimeString = $today_timestamp->format(DEFAULT_TIMESTAMP_FORMAT);
}
@@ -434,18 +487,17 @@ class Application_Service_ShowService
$hValue = trim(substr($duration, 0, $hPos));
}
if ($mPos !== false) {
- $hPos = $hPos === false ? 0 : $hPos+1;
- $mValue = trim(substr($duration, $hPos, -1 ));
+ $hPos = $hPos === false ? 0 : $hPos + 1;
+ $mValue = trim(substr($duration, $hPos, -1));
}
- return $hValue.":".$mValue;
+ return $hValue . ':' . $mValue;
}
/**
- *
* Deletes all the cc_show_days entries for a specific show
* that is currently being edited. They will get recreated with
- * the new show day specs
+ * the new show day specs.
*/
private function deleteCcShowDays()
{
@@ -454,26 +506,27 @@ class Application_Service_ShowService
private function deleteRebroadcastInstances()
{
- $sql = << :timestamp::TIMESTAMP
AND show_id = :showId
AND rebroadcast = 1;
SQL;
- Application_Common_Database::prepareAndExecute( $sql, array(
+ Application_Common_Database::prepareAndExecute($sql, [
':showId' => $this->ccShow->getDbId(),
- ':timestamp' => gmdate(DEFAULT_TIMESTAMP_FORMAT)), 'execute');
+ ':timestamp' => gmdate(DEFAULT_TIMESTAMP_FORMAT), ], 'execute');
}
private function deleteAllShowDays($showId)
{
CcShowDaysQuery::create()
->filterByDbShowId($showId)
- ->delete();
+ ->delete()
+ ;
}
/**
- * TODO: This function is messy. Needs refactoring
+ * TODO: This function is messy. Needs refactoring.
*
* When editing a show we may need to perform some actions to reflect the new specs:
* - Delete some show instances
@@ -488,7 +541,7 @@ SQL;
{
$showId = $this->ccShow->getDbId();
- $daysAdded = array();
+ $daysAdded = [];
//CcShowDay object
if ($this->ccShow->isRepeating()) {
@@ -510,7 +563,7 @@ SQL;
if ($showData['add_show_repeats'] != $currentShowDay->isRepeating()) {
$this->deleteAllRepeatInstances($currentShowDay, $showId);
- if (!$showData["add_show_repeats"]) {
+ if (!$showData['add_show_repeats']) {
$this->deleteAllShowDays($showId);
}
@@ -523,17 +576,15 @@ SQL;
}
if ($showData['add_show_repeats']) {
-
$localShowStart = $currentShowDay->getLocalStartDateAndTime();
//if the start date changes, these are the repeat types
//that require show instance deletion
- $deleteRepeatTypes = array(REPEAT_BI_WEEKLY, REPEAT_TRI_WEEKLY, REPEAT_QUAD_WEEKLY, REPEAT_MONTHLY_MONTHLY,
- REPEAT_MONTHLY_WEEKLY);
-
- if (in_array($this->repeatType, $deleteRepeatTypes) &&
- $showData["add_show_start_date"] != $localShowStart->format("Y-m-d")) {
+ $deleteRepeatTypes = [REPEAT_BI_WEEKLY, REPEAT_TRI_WEEKLY, REPEAT_QUAD_WEEKLY, REPEAT_MONTHLY_MONTHLY,
+ REPEAT_MONTHLY_WEEKLY, ];
+ if (in_array($this->repeatType, $deleteRepeatTypes)
+ && $showData['add_show_start_date'] != $localShowStart->format('Y-m-d')) {
//Start date has changed when repeat type is bi-weekly or monthly.
//This screws up the repeating positions of show instances, so
//we need to delete them (CC-2351)
@@ -552,7 +603,7 @@ SQL;
//repeat type is the same, check if the days of the week are the same
$repeatingDaysChanged = false;
- $showDays = array();
+ $showDays = [];
foreach ($ccShowDays as $day) {
$showDays[] = $day->getDbDay();
}
@@ -569,7 +620,7 @@ SQL;
if ($repeatingDaysChanged) {
$daysRemoved = array_diff($showDays, $showData['add_show_day_check']);
- $newDays = array_diff($showData["add_show_day_check"], $showDays);
+ $newDays = array_diff($showData['add_show_day_check'], $showDays);
foreach ($newDays as $newDay) {
array_push($daysAdded, $newDay);
}
@@ -580,32 +631,32 @@ SQL;
/*if ($this->ccShow->isLinked()) {
$this->preserveLinkedShowContent();
}*/
- $this->deleteRemovedShowDayInstances($daysRemoved,
- $ccShowDays, $showId);
+ $this->deleteRemovedShowDayInstances(
+ $daysRemoved,
+ $ccShowDays,
+ $showId
+ );
}
}
- if ($showData['add_show_start_date'] != $localShowStart->format("Y-m-d")
- || $showData['add_show_start_time'] != $localShowStart->format("H:i")) {
-
+ if ($showData['add_show_start_date'] != $localShowStart->format('Y-m-d')
+ || $showData['add_show_start_time'] != $localShowStart->format('H:i')) {
//start date has been pushed forward so we need to delete
//any instances of this show scheduled before the new start date
- if ($showData['add_show_start_date'] > $localShowStart->format("Y-m-d")) {
+ if ($showData['add_show_start_date'] > $localShowStart->format('Y-m-d')) {
$this->deleteInstancesBeforeDate($showData['add_show_start_date'], $showId);
}
-
-
}
}
//get the endate from the past for this show.
//check if this is null if "no end"
$currentShowEndDateTime = $this->getRepeatingEndDate();
-
+
if ($endDateTime && $currentShowEndDateTime != $endDateTime) {
$endDate = clone $endDateTime;
- $endDate->setTimezone(new DateTimeZone("UTC"));
-
+ $endDate->setTimezone(new DateTimeZone('UTC'));
+
//show's "No End" option was toggled
//or the end date comes earlier
if (is_null($currentShowEndDateTime) || ($endDateTime < $currentShowEndDateTime)) {
@@ -614,7 +665,7 @@ SQL;
//OR
//end date was pushed back so we have to delete any
//instances of this show scheduled after the new end date
- $this->deleteInstancesFromDate($endDate->format("Y-m-d"), $showId);
+ $this->deleteInstancesFromDate($endDate->format('Y-m-d'), $showId);
}
}
}
@@ -641,12 +692,10 @@ SQL;
}
}*/
- /*
- * returns a DateTime of the current show end date set to the timezone of the show.
- */
+ // returns a DateTime of the current show end date set to the timezone of the show.
public function getRepeatingEndDate()
{
- $sql = << $this->ccShow->getDbId() ), 'single');
-
+ $query = Application_Common_Database::prepareAndExecute(
+ $sql,
+ ['showId' => $this->ccShow->getDbId()],
+ 'single'
+ );
+
$date = null;
-
- if ($query !== false && isset($query["last_show"])) {
+
+ if ($query !== false && isset($query['last_show'])) {
$date = new DateTime(
- $query["last_show"],
- new DateTimeZone($query["timezone"])
+ $query['last_show'],
+ new DateTimeZone($query['timezone'])
);
}
-
+
return $date;
}
private function deleteInstancesFromDate($endDate, $showId)
{
- $sql = <<= :endDate::DATE
AND starts > :timestamp::TIMESTAMP
AND show_id = :showId
SQL;
- Application_Common_Database::prepareAndExecute($sql, array(
+ Application_Common_Database::prepareAndExecute($sql, [
':endDate' => $endDate, ':timestamp' => gmdate(DEFAULT_TIMESTAMP_FORMAT),
- ':showId' => $showId), 'execute');
+ ':showId' => $showId, ], 'execute');
}
private function deleteInstancesBeforeDate($newStartDate, $showId)
{
- $sql = << $newStartDate, ":timestamp" => gmdate(DEFAULT_TIMESTAMP_FORMAT),
- ":showId" => $showId), "execute");
+ Application_Common_Database::prepareAndExecute($sql, [
+ ':newStartDate' => $newStartDate, ':timestamp' => gmdate(DEFAULT_TIMESTAMP_FORMAT),
+ ':showId' => $showId, ], 'execute');
}
/**
- *
* Enter description here ...
+ *
* @param $daysRemoved array of days (days of the week) removed
* (days of the week are represented numerically
* 0=>sunday, 1=>monday, 2=>tuesday, etc.)
@@ -708,14 +760,14 @@ SQL;
*/
private function deleteRemovedShowDayInstances($daysRemoved, $showDays, $showId)
{
- $daysRemovedUTC = array();
+ $daysRemovedUTC = [];
//convert the start day of the week to UTC
foreach ($showDays as $showDay) {
if (in_array($showDay->getDbDay(), $daysRemoved)) {
- $showDay->reload();
- $startDay = $showDay->getUTCStartDateAndTime();
- $daysRemovedUTC[] = $startDay->format('w');
+ $showDay->reload();
+ $startDay = $showDay->getUTCStartDateAndTime();
+ $daysRemovedUTC[] = $startDay->format('w');
}
}
@@ -724,63 +776,68 @@ SQL;
CcShowDaysQuery::create()
->filterByDbShowId($showId)
->filterByDbDay($day)
- ->delete();
+ ->delete()
+ ;
}
- $uncheckedDays = pg_escape_string(implode(",", $daysRemovedUTC));
+ $uncheckedDays = pg_escape_string(implode(',', $daysRemovedUTC));
$sql = << :timestamp::TIMESTAMP
AND show_id = :showId
SQL;
- Application_Common_Database::prepareAndExecute( $sql, array(
- ":timestamp" => gmdate(DEFAULT_TIMESTAMP_FORMAT), ":showId" => $showId),
- "execute");
-
+ Application_Common_Database::prepareAndExecute(
+ $sql,
+ [
+ ':timestamp' => gmdate(DEFAULT_TIMESTAMP_FORMAT), ':showId' => $showId, ],
+ 'execute'
+ );
}
- public function deleteShow($instanceId, $singleInstance=false)
+ public function deleteShow($instanceId, $singleInstance = false)
{
$service_user = new Application_Service_UserService();
$currentUser = $service_user->getCurrentUser();
$con = Propel::getConnection();
$con->beginTransaction();
+
try {
-
if (!$currentUser->isAdminOrPM()) {
- throw new Exception("Permission denied");
+ throw new Exception('Permission denied');
}
$ccShowInstance = CcShowInstancesQuery::create()
- ->findPk($instanceId);
+ ->findPk($instanceId)
+ ;
if (!$ccShowInstance) {
- throw new Exception("Could not find show instance");
+ throw new Exception('Could not find show instance');
}
// Delete show images
$showId = $ccShowInstance->getDbShowId();
if (!$singleInstance && !Rest_ShowImageController::deleteShowImagesFromStor($showId)) {
- throw new Exception("Error deleting show images");
+ throw new Exception('Error deleting show images');
}
-
+
if ($singleInstance) {
- $ccShowInstances = array($ccShowInstance);
+ $ccShowInstances = [$ccShowInstance];
} else {
$ccShowInstances = CcShowInstancesQuery::create()
->filterByDbShowId($showId)
->filterByDbStarts($ccShowInstance->getDbStarts(), Criteria::GREATER_EQUAL)
- ->find();
+ ->find()
+ ;
}
if (gmdate(DEFAULT_TIMESTAMP_FORMAT) <= $ccShowInstance->getDbEnds()) {
$this->deleteShowInstances($ccShowInstances, $showId);
} else {
- throw new Exception("Cannot delete a show instance in the past");
+ throw new Exception('Cannot delete a show instance in the past');
}
Application_Model_StoredFile::updatePastFilesIsScheduled();
@@ -792,12 +849,13 @@ SQL;
return $showId;
} catch (Exception $e) {
$con->rollback();
- Logging::info("Delete show instance failed");
+ Logging::info('Delete show instance failed');
Logging::info($e->getMessage());
+
return false;
}
}
-
+
public function deleteShowInstances($ccShowInstances, $showId)
{
foreach ($ccShowInstances as $ccShowInstance) {
@@ -805,25 +863,29 @@ SQL;
$ccShowInstance
->setDbModifiedInstance(true)
- ->save();
+ ->save()
+ ;
//delete the rebroadcasts of the removed recorded show
if ($ccShowInstance->isRecorded()) {
CcShowInstancesQuery::create()
->filterByDbOriginalShow($instanceId)
- ->delete();
+ ->delete()
+ ;
}
//delete all files scheduled in cc_schedules table
CcScheduleQuery::create()
->filterByDbInstanceId($instanceId)
- ->delete();
+ ->delete()
+ ;
}
if ($this->checkToDeleteCcShow($showId)) {
CcShowQuery::create()
->filterByDbId($showId)
- ->delete();
+ ->delete()
+ ;
/* There is only one cc_show_instance if the user selects 'Delete This Instance'
* There is more than one cc_show_instance if the user selects 'Delete This
* Instance and All Following'. We only need to set the last_show value
@@ -841,12 +903,13 @@ SQL;
->filterByDbModifiedInstance(false)
->filterByDbRebroadcast(0)
->orderByDbStarts()
- ->find();
+ ->find()
+ ;
/* We need to update the last_show in cc_show_days so the instances
* don't get recreated as the user moves forward in the calendar
*/
- $lastShowDays = array();
+ $lastShowDays = [];
//get the show's timezone
$ccShow = CcShowQuery::create()->findPk($showId);
@@ -864,7 +927,7 @@ SQL;
foreach ($ccShowInstances as $instance) {
$instanceStartDT = $instance->getDbStarts(null);
$instanceStartDT->setTimezone(new DateTimeZone($showTimezone));
- $lastShowDays[$instanceStartDT->format("w")] = $instanceStartDT;
+ $lastShowDays[$instanceStartDT->format('w')] = $instanceStartDT;
}
foreach ($lastShowDays as $dayOfWeek => $lastShowStartDT) {
@@ -872,17 +935,23 @@ SQL;
->filterByDbShowId($showId)
->filterByDbDay($dayOfWeek)
->filterByDbRepeatType(-1, Criteria::NOT_EQUAL)
- ->findOne();
+ ->findOne()
+ ;
if (isset($ccShowDay)) {
$lastShowStartDT->setTimeZone(new DateTimeZone(
- $ccShowDay->getDbTimezone()));
+ $ccShowDay->getDbTimezone()
+ ));
$lastShowEndDT = Application_Service_CalendarService::addDeltas(
- $lastShowStartDT, 1, 0);
+ $lastShowStartDT,
+ 1,
+ 0
+ );
$ccShowDay
- ->setDbLastShow($lastShowEndDT->format("Y-m-d"))
- ->save();
+ ->setDbLastShow($lastShowEndDT->format('Y-m-d'))
+ ->save()
+ ;
}
}
@@ -893,7 +962,8 @@ SQL;
->filterByDbShowId($showId)
->filterByDbRepeatType(0, Criteria::GREATER_EQUAL)
->filterByDbLastShow(null)
- ->find();
+ ->find()
+ ;
foreach ($showDays as $showDay) {
$showDay->setDbLastShow($showDay->getDbFirstShow())->save();
}
@@ -907,7 +977,8 @@ SQL;
->filterByDbModifiedInstance(false)
->filterByDbRebroadcast(0)
->orderByDbStarts()
- ->find();
+ ->find()
+ ;
if ($ccShowInstances->isEmpty()) {
return true;
@@ -918,40 +989,46 @@ SQL;
private function deleteAllInstances($showId)
{
- $sql = << :timestamp::TIMESTAMP
AND show_id = :showId
SQL;
- Application_Common_Database::prepareAndExecute( $sql,
- array( ':timestamp' => gmdate(DEFAULT_TIMESTAMP_FORMAT),
- ':showId' => $showId), 'execute');
+ Application_Common_Database::prepareAndExecute(
+ $sql,
+ [':timestamp' => gmdate(DEFAULT_TIMESTAMP_FORMAT),
+ ':showId' => $showId, ],
+ 'execute'
+ );
}
private function deleteAllRepeatInstances($currentShowDay, $showId)
{
$firstShow = $currentShowDay->getUTCStartDateAndTime();
- $sql = << :timestamp::TIMESTAMP
AND show_id = :showId
AND starts != :firstShow
SQL;
- Application_Common_Database::prepareAndExecute( $sql,
- array( ':timestamp' => gmdate(DEFAULT_TIMESTAMP_FORMAT),
- ':showId' => $showId,
- ':firstShow' => $firstShow->format(DEFAULT_TIMESTAMP_FORMAT)), 'execute');
+ Application_Common_Database::prepareAndExecute(
+ $sql,
+ [':timestamp' => gmdate(DEFAULT_TIMESTAMP_FORMAT),
+ ':showId' => $showId,
+ ':firstShow' => $firstShow->format(DEFAULT_TIMESTAMP_FORMAT), ],
+ 'execute'
+ );
}
/**
- *
* Determines what the show end date should be based on
- * the form data
+ * the form data.
*
* @param $showData add/edit show form data
+ *
* @return DateTime object in user's local timezone
*/
private function calculateEndDate($showData)
@@ -959,22 +1036,22 @@ SQL;
//if no end return null
if ($showData['add_show_no_end']) {
$endDate = null;
- }
+ }
//if the show is repeating & ends, then return the end date
elseif ($showData['add_show_repeats']) {
$endDate = new DateTime(
- $showData['add_show_end_date'],
- new DateTimeZone($showData["add_show_timezone"])
+ $showData['add_show_end_date'],
+ new DateTimeZone($showData['add_show_timezone'])
);
- $endDate->add(new DateInterval("P1D"));
+ $endDate->add(new DateInterval('P1D'));
}
- //the show doesn't repeat, so add one day to the start date.
+ //the show doesn't repeat, so add one day to the start date.
else {
$endDate = new DateTime(
$showData['add_show_start_date'],
- new DateTimeZone($showData["add_show_timezone"])
+ new DateTimeZone($showData['add_show_timezone'])
);
- $endDate->add(new DateInterval("P1D"));
+ $endDate->add(new DateInterval('P1D'));
}
return $endDate;
@@ -984,22 +1061,26 @@ SQL;
{
$showId = $this->ccShow->getDbId();
//DateTime in show's local time
- $newStartDateTime = new DateTime($showData["add_show_start_date"]." ".
- $showData["add_show_start_time"],
- new DateTimeZone($showData["add_show_timezone"]));
+ $newStartDateTime = new DateTime(
+ $showData['add_show_start_date'] . ' ' .
+ $showData['add_show_start_time'],
+ new DateTimeZone($showData['add_show_timezone'])
+ );
- $diff = $this->calculateShowStartDiff($newStartDateTime,
- $this->origCcShowDay->getLocalStartDateAndTime());
+ $diff = $this->calculateShowStartDiff(
+ $newStartDateTime,
+ $this->origCcShowDay->getLocalStartDateAndTime()
+ );
Application_Service_SchedulerService::updateScheduleStartTime(
$this->instanceIdsForScheduleUpdates,
- $diff);
+ $diff
+ );
}
/**
- *
* Returns the difference in seconds between a show's new and
- * old start time
+ * old start time.
*
* @param $newStartDateTime DateTime object
* @param $oldStartDateTime DateTime object
@@ -1010,14 +1091,14 @@ SQL;
}
/**
- *
- * Updates the start and end time for cc_show_instances
+ * Updates the start and end time for cc_show_instances.
*
* @param $showData edit show form data
+ * @param mixed $diff
*/
private function updateInstanceStartEndTime($diff)
{
- $sql = << :timestamp::TIMESTAMP
SQL;
- Application_Common_Database::prepareAndExecute($sql,
- array(':diff1' => $diff, ':diff2' => $diff,
- ':showId' => $this->ccShow->getDbId(), ':timestamp' => gmdate(DEFAULT_TIMESTAMP_FORMAT)),
- 'execute');
+ Application_Common_Database::prepareAndExecute(
+ $sql,
+ [':diff1' => $diff, ':diff2' => $diff,
+ ':showId' => $this->ccShow->getDbId(), ':timestamp' => gmdate(DEFAULT_TIMESTAMP_FORMAT), ],
+ 'execute'
+ );
}
/**
- *
* Enter description here ...
+ *
* @param ccShowDays $showDay
- * @param DateTime $showStartDate user's local time
+ * @param DateTime $showStartDate user's local time
* @param $instanceId
*/
private function createRebroadcastInstances($showDay, $showStartDate, $instanceId)
@@ -1043,17 +1126,23 @@ SQL;
$currentUtcTimestamp = gmdate(DEFAULT_TIMESTAMP_FORMAT);
$showId = $this->ccShow->getDbId();
- $sql = "SELECT * FROM cc_show_rebroadcast WHERE show_id=:show_id";
- $rebroadcasts = Application_Common_Database::prepareAndExecute($sql,
- array( ':show_id' => $showId ), 'all');
+ $sql = 'SELECT * FROM cc_show_rebroadcast WHERE show_id=:show_id';
+ $rebroadcasts = Application_Common_Database::prepareAndExecute(
+ $sql,
+ [':show_id' => $showId],
+ 'all'
+ );
foreach ($rebroadcasts as $rebroadcast) {
- $days = explode(" ", $rebroadcast["day_offset"]);
- $time = explode(":", $rebroadcast["start_time"]);
- $offset = array("days"=>$days[0], "hours"=>$time[0], "mins"=>$time[1]);
+ $days = explode(' ', $rebroadcast['day_offset']);
+ $time = explode(':', $rebroadcast['start_time']);
+ $offset = ['days' => $days[0], 'hours' => $time[0], 'mins' => $time[1]];
list($utcStartDateTime, $utcEndDateTime) = $this->createUTCStartEndDateTime(
- $showStartDate, $showDay->getDbDuration(), $offset);
+ $showStartDate,
+ $showDay->getDbDuration(),
+ $offset
+ );
if ($utcStartDateTime->format(DEFAULT_TIMESTAMP_FORMAT) > $currentUtcTimestamp) {
$ccShowInstance = new CcShowInstances();
@@ -1069,8 +1158,8 @@ SQL;
}
/**
+ * Sets a single cc_show_instance table row.
*
- * Sets a single cc_show_instance table row
* @param $showDay
* @param $populateUntil
*/
@@ -1080,20 +1169,22 @@ SQL;
$start = $showDay->getLocalStartDateAndTime();
list($utcStartDateTime, $utcEndDateTime) = $this->createUTCStartEndDateTime(
- $start, $showDay->getDbDuration());
+ $start,
+ $showDay->getDbDuration()
+ );
if ($utcStartDateTime->getTimestamp() < $populateUntil->getTimestamp()) {
$ccShowInstance = new CcShowInstances();
if ($this->isUpdate) {
//use original cc_show_day object to get the current cc_show_instance
$origStartDateTime = new DateTime(
- $this->origCcShowDay->getDbFirstShow()." ".$this->origCcShowDay->getDbStartTime(),
+ $this->origCcShowDay->getDbFirstShow() . ' ' . $this->origCcShowDay->getDbStartTime(),
new DateTimeZone($this->origCcShowDay->getDbTimezone())
);
- $origStartDateTime->setTimezone(new DateTimeZone("UTC"));
+ $origStartDateTime->setTimezone(new DateTimeZone('UTC'));
$ccShowInstance = $this->getInstance($origStartDateTime);
if (!$ccShowInstance) {
- throw new Exception("Could not find show instance with start time: ".$origStartDateTime->format(DEFAULT_TIMESTAMP_FORMAT));
+ throw new Exception('Could not find show instance with start time: ' . $origStartDateTime->format(DEFAULT_TIMESTAMP_FORMAT));
}
}
@@ -1107,45 +1198,55 @@ SQL;
$this->createRebroadcastInstances($showDay, $start, $ccShowInstance->getDbId());
}
}
+
return $ccShowInstance;
}
/**
+ * Sets multiple cc_show_instances table rows.
*
- * Sets multiple cc_show_instances table rows
* @param unknown_type $showDay
* @param unknown_type $populateUntil
* @param unknown_type $repeatInterval
* @param unknown_type $isRebroadcast
+ * @param mixed $repeatType
+ * @param null|mixed $daysAdded
*/
- private function createWeeklyRepeatInstances($showDay, $populateUntil,
- $repeatType, $repeatInterval, $daysAdded=null)
- {
-
- $show_id = $showDay->getDbShowId();
- $first_show = $showDay->getDbFirstShow(); //non-UTC
- $last_show = $showDay->getDbLastShow(); //non-UTC
- $duration = $showDay->getDbDuration();
- $day = $showDay->getDbDay();
- $record = $showDay->getDbRecord();
- $timezone = $showDay->getDbTimezone();
+ private function createWeeklyRepeatInstances(
+ $showDay,
+ $populateUntil,
+ $repeatType,
+ $repeatInterval,
+ $daysAdded = null
+ ) {
+ $show_id = $showDay->getDbShowId();
+ $first_show = $showDay->getDbFirstShow(); //non-UTC
+ $last_show = $showDay->getDbLastShow(); //non-UTC
+ $duration = $showDay->getDbDuration();
+ $day = $showDay->getDbDay();
+ $record = $showDay->getDbRecord();
+ $timezone = $showDay->getDbTimezone();
//DateTime local
$start = $this->getNextRepeatingPopulateStartDateTime($showDay);
- if (is_null($repeatInterval)&& $repeatType == REPEAT_MONTHLY_WEEKLY) {
+ if (is_null($repeatInterval) && $repeatType == REPEAT_MONTHLY_WEEKLY) {
$repeatInterval = self::getMonthlyWeeklyRepeatInterval($start, $timezone);
}
//DatePeriod in user's local time
- $datePeriod = $this->getDatePeriod($start, $timezone, $last_show,
- $repeatInterval, $populateUntil);
+ $datePeriod = $this->getDatePeriod(
+ $start,
+ $timezone,
+ $last_show,
+ $repeatInterval,
+ $populateUntil
+ );
if ($last_show) {
$utcLastShowDateTime = new DateTime($last_show, new DateTimeZone($timezone));
- $utcLastShowDateTime->setTimezone(new DateTimeZone("UTC"));
- }
- else {
+ $utcLastShowDateTime->setTimezone(new DateTimeZone('UTC'));
+ } else {
$utcLastShowDateTime = null;
}
@@ -1153,15 +1254,16 @@ SQL;
foreach ($datePeriod as $date) {
list($utcStartDateTime, $utcEndDateTime) = $this->createUTCStartEndDateTime(
- $date, $duration);
+ $date,
+ $duration
+ );
/*
* Make sure start date is less than populate until date AND
* last show date is null OR start date is less than last show date
*/
- if ($utcStartDateTime <= $populateUntil &&
- ( is_null($utcLastShowDateTime) || $utcStartDateTime < $utcLastShowDateTime) ) {
-
- $lastCreatedShow = clone $utcStartDateTime;
+ if ($utcStartDateTime <= $populateUntil
+ && (is_null($utcLastShowDateTime) || $utcStartDateTime < $utcLastShowDateTime)) {
+ $lastCreatedShow = clone $utcStartDateTime;
/* There may not always be an instance when editing a show
* This will be the case when we are adding a new show day to
* a repeating show
@@ -1174,7 +1276,7 @@ SQL;
$newInstance = true;
$ccShowInstance = new CcShowInstances();
}
- } else {
+ } else {
$newInstance = true;
$ccShowInstance = new CcShowInstances();
}
@@ -1189,7 +1291,7 @@ SQL;
$ccShowInstance->setDbRecord($record);
$ccShowInstance->save();
}
-
+
if ($newInstance) {
array_push($this->newInstanceIdsCreated[$show_id], $ccShowInstance->getDbId());
}
@@ -1208,24 +1310,24 @@ SQL;
* created and we shouldn't update the next populate date.
*/
if (isset($lastCreatedShow)) {
- /* Set UTC to local time before setting the next repeat date. If we don't
- * the next repeat date might be scheduled for the following day
- * THIS MUST BE IN THE TIMEZONE THE SHOW WAS CREATED IN */
+ /* Set UTC to local time before setting the next repeat date. If we don't
+ * the next repeat date might be scheduled for the following day
+ * THIS MUST BE IN THE TIMEZONE THE SHOW WAS CREATED IN */
$lastCreatedShow->setTimezone(new DateTimeZone($timezone));
$nextDate = $lastCreatedShow->add($repeatInterval);
- $this->setNextRepeatingShowDate($nextDate->format("Y-m-d"), $day, $show_id);
+ $this->setNextRepeatingShowDate($nextDate->format('Y-m-d'), $day, $show_id);
}
}
private function createMonthlyRepeatInstances($showDay, $populateUntil)
{
- $show_id = $showDay->getDbShowId();
- $first_show = $showDay->getDbFirstShow(); //non-UTC
- $last_show = $showDay->getDbLastShow(); //non-UTC
- $duration = $showDay->getDbDuration();
- $day = $showDay->getDbDay();
- $record = $showDay->getDbRecord();
- $timezone = $showDay->getDbTimezone();
+ $show_id = $showDay->getDbShowId();
+ $first_show = $showDay->getDbFirstShow(); //non-UTC
+ $last_show = $showDay->getDbLastShow(); //non-UTC
+ $duration = $showDay->getDbDuration();
+ $day = $showDay->getDbDay();
+ $record = $showDay->getDbRecord();
+ $timezone = $showDay->getDbTimezone();
//DateTime local
$start = $this->getNextRepeatingPopulateStartDateTime($showDay);
@@ -1238,30 +1340,31 @@ SQL;
// We will only need this if the repeat type is MONTHLY_WEEKLY
list($weekNumberOfMonth, $dayOfWeek) =
self::getMonthlyWeeklyRepeatInterval(
- new DateTime($first_show, new DateTimeZone($timezone)));
+ new DateTime($first_show, new DateTimeZone($timezone))
+ );
$this->repeatType = $showDay->getDbRepeatType();
if ($last_show) {
$utcLastShowDateTime = new DateTime($last_show, new DateTimeZone($timezone));
- $utcLastShowDateTime->setTimezone(new DateTimeZone("UTC"));
- }
- else {
+ $utcLastShowDateTime->setTimezone(new DateTimeZone('UTC'));
+ } else {
$utcLastShowDateTime = null;
}
while ($start->getTimestamp() < $end->getTimestamp()) {
list($utcStartDateTime, $utcEndDateTime) = $this->createUTCStartEndDateTime(
- $start, $duration);
+ $start,
+ $duration
+ );
/*
* Make sure start date is less than populate until date AND
* last show date is null OR start date is less than last show date
*/
- if ($utcStartDateTime->getTimestamp() <= $populateUntil->getTimestamp() &&
- ( is_null($utcLastShowDateTime) ||
- $utcStartDateTime->getTimestamp() < $utcLastShowDateTime->getTimestamp()) ) {
-
- $lastCreatedShow = clone $utcStartDateTime;
+ if ($utcStartDateTime->getTimestamp() <= $populateUntil->getTimestamp()
+ && (is_null($utcLastShowDateTime)
+ || $utcStartDateTime->getTimestamp() < $utcLastShowDateTime->getTimestamp())) {
+ $lastCreatedShow = clone $utcStartDateTime;
/* There may not always be an instance when editing a show
* This will be the case when we are adding a new show day to
* a repeating show
@@ -1284,7 +1387,7 @@ SQL;
$ccShowInstance->setDbRecord($record);
$ccShowInstance->save();
}
-
+
if ($newInstance) {
array_push($this->newInstanceIdsCreated[$show_id], $ccShowInstance->getDbId());
}
@@ -1294,102 +1397,118 @@ SQL;
}
}
if ($this->repeatType == REPEAT_MONTHLY_WEEKLY) {
- $monthlyWeeklyStart = new DateTime($utcStartDateTime->format("Y-m"),
- new DateTimeZone("UTC"));
- $monthlyWeeklyStart->add(new DateInterval("P1M"));
+ $monthlyWeeklyStart = new DateTime(
+ $utcStartDateTime->format('Y-m'),
+ new DateTimeZone('UTC')
+ );
+ $monthlyWeeklyStart->add(new DateInterval('P1M'));
$start = self::getNextMonthlyWeeklyRepeatDate(
$monthlyWeeklyStart,
$timezone,
$showDay->getDbStartTime(),
$weekNumberOfMonth,
- $dayOfWeek);
+ $dayOfWeek
+ );
} else {
$start = $this->getNextMonthlyMonthlyRepeatDate(
- $start, $timezone, $showDay->getDbStartTime());
+ $start,
+ $timezone,
+ $showDay->getDbStartTime()
+ );
}
}
- $this->setNextRepeatingShowDate($start->format("Y-m-d"), $day, $show_id);
+ $this->setNextRepeatingShowDate($start->format('Y-m-d'), $day, $show_id);
}
/**
- *
* i.e. last thursday of each month
- * i.e. second monday of each month
+ * i.e. second monday of each month.
*
* @param string $showStart
- * @param string $timezone user's local timezone
+ * @param string $timezone user's local timezone
*/
public static function getMonthlyWeeklyRepeatInterval($showStart)
{
$start = clone $showStart;
- $dayOfMonth = $start->format("j");
- $dayOfWeek = $start->format("l");
- $yearAndMonth = $start->format("Y-m");
- $firstDayOfWeek = strtotime($dayOfWeek." ".$yearAndMonth);
+ $dayOfMonth = $start->format('j');
+ $dayOfWeek = $start->format('l');
+ $yearAndMonth = $start->format('Y-m');
+ $firstDayOfWeek = strtotime($dayOfWeek . ' ' . $yearAndMonth);
// if $dayOfWeek is Friday, what number of the month does
// the first Friday fall on
- $numberOfFirstDayOfWeek = date("j", $firstDayOfWeek);
+ $numberOfFirstDayOfWeek = date('j', $firstDayOfWeek);
$weekCount = 0;
while ($dayOfMonth >= $numberOfFirstDayOfWeek) {
- $weekCount++;
+ ++$weekCount;
$dayOfMonth -= 7;
}
switch ($weekCount) {
case 1:
- $weekNumberOfMonth = "first";
+ $weekNumberOfMonth = 'first';
+
break;
+
case 2:
- $weekNumberOfMonth = "second";
+ $weekNumberOfMonth = 'second';
+
break;
+
case 3:
- $weekNumberOfMonth = "third";
+ $weekNumberOfMonth = 'third';
+
break;
+
case 4:
- $weekNumberOfMonth = "fourth";
+ $weekNumberOfMonth = 'fourth';
+
break;
+
case 5:
- $weekNumberOfMonth = "fifth";
+ $weekNumberOfMonth = 'fifth';
+
break;
}
/* return DateInterval::createFromDateString(
$weekNumberOfMonth." ".$dayOfWeek." of next month"); */
- return array($weekNumberOfMonth, $dayOfWeek);
+ return [$weekNumberOfMonth, $dayOfWeek];
}
/**
- *
* Enter description here ...
+ *
* @param $start user's local time
+ * @param mixed $timezone
+ * @param mixed $startTime
*/
private function getNextMonthlyMonthlyRepeatDate($start, $timezone, $startTime)
{
- $dt = new DateTime($start->format("Y-m"), new DateTimeZone($timezone));
+ $dt = new DateTime($start->format('Y-m'), new DateTimeZone($timezone));
do {
- $dt->add(new DateInterval("P1M"));
- } while (!checkdate($dt->format("m"), $start->format("d"), $dt->format("Y")));
+ $dt->add(new DateInterval('P1M'));
+ } while (!checkdate($dt->format('m'), $start->format('d'), $dt->format('Y')));
- $dt->setDate($dt->format("Y"), $dt->format("m"), $start->format("d"));
+ $dt->setDate($dt->format('Y'), $dt->format('m'), $start->format('d'));
- $startTime = explode(":", $startTime);
- $hours = isset($startTime[0]) ? $startTime[0] : "00";
- $minutes = isset($startTime[1]) ? $startTime[1] : "00";
- $seconds = isset($startTime[2]) ? $startTime[2] : "00";
+ $startTime = explode(':', $startTime);
+ $hours = isset($startTime[0]) ? $startTime[0] : '00';
+ $minutes = isset($startTime[1]) ? $startTime[1] : '00';
+ $seconds = isset($startTime[2]) ? $startTime[2] : '00';
$dt->setTime($hours, $minutes, $seconds);
+
return $dt;
}
/**
- *
* Returns a DateTime object of when the next repeating show that repeats
- * monthly, by day of the week (i.e. every fourth Tuesday) should be created
- *
+ * monthly, by day of the week (i.e. every fourth Tuesday) should be created.
+ *
* @param DateTime $start
- * $start only has the year and month of the next show
- * @param string $timezone
+ * $start only has the year and month of the next show
+ * @param string $timezone
* @param string (i.e. '14:30' $startTime
* @param string (i.e. 'first', 'second') $weekNumberOfMonth
* @param string (i.e. 'Monday') $dayOfWeek
@@ -1399,14 +1518,14 @@ SQL;
$timezone,
$startTime,
$weekNumberOfMonth,
- $dayOfWeek)
- {
- $dt = new DateTime($start->format("Y-m"), new DateTimeZone($timezone));
+ $dayOfWeek
+ ) {
+ $dt = new DateTime($start->format('Y-m'), new DateTimeZone($timezone));
$tempDT = clone $dt;
$fifthWeekExists = false;
do {
- $nextDT = date_create($weekNumberOfMonth." ".$dayOfWeek.
- " of ".$tempDT->format("F")." ".$tempDT->format("Y"));
+ $nextDT = date_create($weekNumberOfMonth . ' ' . $dayOfWeek .
+ ' of ' . $tempDT->format('F') . ' ' . $tempDT->format('Y'));
$nextDT->setTimezone(new DateTimeZone($timezone));
/* We have to check if the next date is in the same month in case
@@ -1414,19 +1533,20 @@ SQL;
* If it's not in the same month we know that a fifth week of
* the next month does not exist. So let's skip it.
*/
- if ($tempDT->format("F") == $nextDT->format("F")) {
+ if ($tempDT->format('F') == $nextDT->format('F')) {
$fifthWeekExists = true;
}
- $tempDT->add(new DateInterval("P1M"));
+ $tempDT->add(new DateInterval('P1M'));
} while (!$fifthWeekExists);
$dt = $nextDT;
- $startTime = explode(":", $startTime);
- $hours = isset($startTime[0]) ? $startTime[0] : "00";
- $minutes = isset($startTime[1]) ? $startTime[1] : "00";
- $seconds = isset($startTime[2]) ? $startTime[2] : "00";
+ $startTime = explode(':', $startTime);
+ $hours = isset($startTime[0]) ? $startTime[0] : '00';
+ $minutes = isset($startTime[1]) ? $startTime[1] : '00';
+ $seconds = isset($startTime[2]) ? $startTime[2] : '00';
$dt->setTime($hours, $minutes, $seconds);
+
return $dt;
}
@@ -1436,16 +1556,21 @@ SQL;
$startTime = $showDay->getDbStartTime();
if (isset($nextPopDate)) {
- return new DateTime($nextPopDate." ".$startTime, new DateTimeZone($showDay->getDbTimezone()));
- } else {
- return new DateTime($showDay->getDbFirstShow()." ".$startTime, new DateTimeZone($showDay->getDbTimezone()));
+ return new DateTime($nextPopDate . ' ' . $startTime, new DateTimeZone($showDay->getDbTimezone()));
}
+
+ return new DateTime($showDay->getDbFirstShow() . ' ' . $startTime, new DateTimeZone($showDay->getDbTimezone()));
}
/**
- *
* Create a DatePeriod object in the user's local time
- * It will get converted to UTC before the show instance gets created
+ * It will get converted to UTC before the show instance gets created.
+ *
+ * @param mixed $start
+ * @param mixed $timezone
+ * @param mixed $lastShow
+ * @param mixed $repeatInterval
+ * @param mixed $populateUntil
*/
private function getDatePeriod($start, $timezone, $lastShow, $repeatInterval, $populateUntil)
{
@@ -1464,21 +1589,22 @@ SQL;
}
/**
- *
* Attempts to retrieve the cc_show_instance belonging to a cc_show
* that starts at $starts. We have to pass in the start
- * time in case the show is repeating
+ * time in case the show is repeating.
*
* Returns the instance if one was found (one that is not a recording
* and modified instance is false (has not been deleted))
+ *
+ * @param mixed $starts
*/
private function getInstance($starts)
{
- $temp = clone($starts);
+ $temp = clone $starts;
$temp->setTimezone(new DateTimeZone($this->oldShowTimezone));
$temp->setTime($this->localShowStartHour, $this->localShowStartMin);
-
- $temp->setTimezone(new DateTimeZone("UTC"));
+
+ $temp->setTimezone(new DateTimeZone('UTC'));
$ccShowInstance = CcShowInstancesQuery::create()
->filterByDbStarts($temp->format(DEFAULT_TIMESTAMP_FORMAT), Criteria::EQUAL)
@@ -1486,13 +1612,14 @@ SQL;
//->filterByDbModifiedInstance(false, Criteria::EQUAL)
->filterByDbRebroadcast(0, Criteria::EQUAL)
->limit(1)
- ->find();
+ ->find()
+ ;
if ($ccShowInstance->isEmpty()) {
return false;
- } else {
- return $ccShowInstance[0];
}
+
+ return $ccShowInstance[0];
}
private function hasCcShowDay($repeatType, $day)
@@ -1507,18 +1634,19 @@ SQL;
->filterByDbDay($day)
->filterByDbRepeatType($repeatType)
->limit(1)
- ->find();
+ ->find()
+ ;
if ($ccShowDay->isEmpty()) {
return false;
- } else {
- return $ccShowDay[0];
}
+
+ return $ccShowDay[0];
}
/**
+ * Sets the fields for a cc_show table row.
*
- * Sets the fields for a cc_show table row
* @param $ccShow
* @param $showData
*/
@@ -1527,7 +1655,7 @@ SQL;
if (!$this->isUpdate) {
$ccShow = new CcShow();
} else {
- $ccShow = CcShowQuery::create()->findPk($showData["add_show_id"]);
+ $ccShow = CcShowQuery::create()->findPk($showData['add_show_id']);
}
$ccShow->setDbName($showData['add_show_name']);
@@ -1546,24 +1674,24 @@ SQL;
if ($showData['add_show_autoplaylist_id'] != '') {
$ccShow->setDbAutoPlaylistId($showData['add_show_autoplaylist_id']);
}
-
+
//Here a user has edited a show and linked it.
//We need to grab the existing show instances ids and fill their content
//with the content from the show instance that was clicked on to edit the show.
//We do this because linked show instances need to have the same content in each.
- if ($this->isUpdate && (!$ccShow->getDbLinked() && $showData["add_show_linked"])) {
+ if ($this->isUpdate && (!$ccShow->getDbLinked() && $showData['add_show_linked'])) {
$existingShowInstanceIds = $ccShow->getFutureInstanceIds(new Criteria());
- Application_Service_SchedulerService::fillLinkedInstances($ccShow, $existingShowInstanceIds, $showData["add_show_instance_id"]);
+ Application_Service_SchedulerService::fillLinkedInstances($ccShow, $existingShowInstanceIds, $showData['add_show_instance_id']);
}
- $ccShow->setDbLinked($showData["add_show_linked"]);
+ $ccShow->setDbLinked($showData['add_show_linked']);
$ccShow->save();
$this->ccShow = $ccShow;
}
/**
+ * Sets the fields for a cc_show_days table row.
*
- * Sets the fields for a cc_show_days table row
* @param $showData
* @param $showId
* @param $userId
@@ -1576,33 +1704,32 @@ SQL;
$showId = $this->ccShow->getDbId();
$startDateTime = new DateTime(
- $showData['add_show_start_date']." ".$showData['add_show_start_time'],
- new DateTimeZone($showData['add_show_timezone'])
+ $showData['add_show_start_date'] . ' ' . $showData['add_show_start_time'],
+ new DateTimeZone($showData['add_show_timezone'])
);
$endDateTime = $this->calculateEndDate($showData);
if (!is_null($endDateTime)) {
- $endDate = $endDateTime->format("Y-m-d");
- }
- else {
+ $endDate = $endDateTime->format('Y-m-d');
+ } else {
$endDate = null;
}
//Our calculated start DOW must be used for non repeating since a day has not been selected.
//For all repeating shows, only the selected days of the week will be repeated on.
- $startDow = $startDateTime->format("w");
+ $startDow = $startDateTime->format('w');
if (!$showData['add_show_repeats']) {
- $showData['add_show_day_check'] = array($startDow);
+ $showData['add_show_day_check'] = [$startDow];
}
// Don't set day for monthly repeat type, it's invalid
if ($showData['add_show_repeats'] && $showData['add_show_repeat_type'] == 2) {
-
if ($this->isUpdate) {
$showDay = CcShowDaysQuery::create()
->filterByDbShowId($showId)
->filterByDbRepeatType($this->origCcShowDay->getDbRepeatType())
- ->findOne();
+ ->findOne()
+ ;
if (!$showDay) {
//repeat type changed so we have to create a new show_day rule
$showDay = new CcShowDays();
@@ -1611,9 +1738,9 @@ SQL;
$showDay = new CcShowDays();
}
- $showDay->setDbFirstShow($startDateTime->format("Y-m-d"));
+ $showDay->setDbFirstShow($startDateTime->format('Y-m-d'));
$showDay->setDbLastShow($endDate);
- $showDay->setDbStartTime($startDateTime->format("H:i:s"));
+ $showDay->setDbStartTime($startDateTime->format('H:i:s'));
$showDay->setDbTimezone($showData['add_show_timezone']);
$showDay->setDbDuration($showData['add_show_duration']);
$showDay->setDbRepeatType($this->repeatType);
@@ -1621,37 +1748,38 @@ SQL;
$showDay->setDbRecord($this->isRecorded);
//in case we are editing a show we need to set this to the first show
//so when editing, the date period iterator will start from the beginning
- $showDay->setDbNextPopDate($startDateTime->format("Y-m-d"));
+ $showDay->setDbNextPopDate($startDateTime->format('Y-m-d'));
$showDay->save();
} else {
foreach ($showData['add_show_day_check'] as $day) {
- $daysAdd=0;
+ $daysAdd = 0;
$startDateTimeClone = clone $startDateTime;
if ($startDow !== $day) {
- if ($startDow > $day)
+ if ($startDow > $day) {
$daysAdd = 6 - $startDow + 1 + $day;
- else
+ } else {
$daysAdd = $day - $startDow;
+ }
- $startDateTimeClone->add(new DateInterval("P".$daysAdd."D"));
+ $startDateTimeClone->add(new DateInterval('P' . $daysAdd . 'D'));
}
if (is_null($endDate) || $startDateTimeClone->getTimestamp() <= $endDateTime->getTimestamp()) {
-
if ($this->isUpdate) {
- if ($this->origCcShowDay->getDbRepeatType() == 2 ||
- $this->origCcShowDay->getDbRepeatType() == 3) {
+ if ($this->origCcShowDay->getDbRepeatType() == 2
+ || $this->origCcShowDay->getDbRepeatType() == 3) {
$day = null;
- } else if (!$this->origShowRepeatStatus) {
+ } elseif (!$this->origShowRepeatStatus) {
//keep current show day to use for updating cc_show_day rule
$keepDay = $day;
$day = $this->origCcShowDay->getDbDay();
}
$showDay = CcShowDaysQuery::create()
- ->filterByDbShowId($showId)
- ->filterByDbRepeatType($this->origCcShowDay->getDbRepeatType())
- ->filterByDbDay($day)
- ->findOne();
+ ->filterByDbShowId($showId)
+ ->filterByDbRepeatType($this->origCcShowDay->getDbRepeatType())
+ ->filterByDbDay($day)
+ ->findOne()
+ ;
if (!$showDay) {
//if no show day object was found it is because a new
//repeating day of the week was added OR the repeat
@@ -1666,9 +1794,9 @@ SQL;
$showDay = new CcShowDays();
}
- $showDay->setDbFirstShow($startDateTimeClone->format("Y-m-d"));
+ $showDay->setDbFirstShow($startDateTimeClone->format('Y-m-d'));
$showDay->setDbLastShow($endDate);
- $showDay->setDbStartTime($startDateTimeClone->format("H:i"));
+ $showDay->setDbStartTime($startDateTimeClone->format('H:i'));
$showDay->setDbTimezone($showData['add_show_timezone']);
$showDay->setDbDuration($showData['add_show_duration']);
$showDay->setDbDay($day);
@@ -1677,7 +1805,7 @@ SQL;
$showDay->setDbRecord($this->isRecorded);
//in case we are editing a show we need to set this to the first show
//so when editing, the date period iterator will start from the beginning
- $showDay->setDbNextPopDate($startDateTimeClone->format("Y-m-d"));
+ $showDay->setDbNextPopDate($startDateTimeClone->format('Y-m-d'));
$showDay->save();
}
}
@@ -1685,10 +1813,9 @@ SQL;
}
/**
- *
* Deletes all the cc_show_rebroadcast entries for a specific show
* that is currently being edited. They will get recreated with
- * the new show specs
+ * the new show specs.
*/
private function deleteCcShowRebroadcasts()
{
@@ -1696,8 +1823,8 @@ SQL;
}
/**
+ * Sets the fields for a cc_show_rebroadcast table row.
*
- * Sets the fields for a cc_show_rebroadcast table row
* @param $showData
* @param $showId
* @param $repeatType
@@ -1708,25 +1835,25 @@ SQL;
$showId = $this->ccShow->getDbId();
if (($this->isRecorded && $showData['add_show_rebroadcast']) && ($this->repeatType != -1)) {
- for ($i = 1; $i <= MAX_REBROADCAST_DATES; $i++) {
- if ($showData['add_show_rebroadcast_date_'.$i]) {
+ for ($i = 1; $i <= MAX_REBROADCAST_DATES; ++$i) {
+ if ($showData['add_show_rebroadcast_date_' . $i]) {
$showRebroad = new CcShowRebroadcast();
- $showRebroad->setDbDayOffset($showData['add_show_rebroadcast_date_'.$i]);
- $showRebroad->setDbStartTime($showData['add_show_rebroadcast_time_'.$i]);
+ $showRebroad->setDbDayOffset($showData['add_show_rebroadcast_date_' . $i]);
+ $showRebroad->setDbStartTime($showData['add_show_rebroadcast_time_' . $i]);
$showRebroad->setDbShowId($showId);
$showRebroad->save();
}
}
} elseif ($this->isRecorded && $showData['add_show_rebroadcast'] && ($this->repeatType == -1)) {
- for ($i = 1; $i <= MAX_REBROADCAST_DATES; $i++) {
- if ($showData['add_show_rebroadcast_date_absolute_'.$i]) {
- $rebroadcastDate = new DateTime($showData["add_show_rebroadcast_date_absolute_$i"]);
+ for ($i = 1; $i <= MAX_REBROADCAST_DATES; ++$i) {
+ if ($showData['add_show_rebroadcast_date_absolute_' . $i]) {
+ $rebroadcastDate = new DateTime($showData["add_show_rebroadcast_date_absolute_{$i}"]);
$startDate = new DateTime($showData['add_show_start_date']);
$offsetDays = $startDate->diff($rebroadcastDate);
$showRebroad = new CcShowRebroadcast();
- $showRebroad->setDbDayOffset($offsetDays->format("%a days"));
- $showRebroad->setDbStartTime($showData['add_show_rebroadcast_time_absolute_'.$i]);
+ $showRebroad->setDbDayOffset($offsetDays->format('%a days'));
+ $showRebroad->setDbStartTime($showData['add_show_rebroadcast_time_absolute_' . $i]);
$showRebroad->setDbShowId($showId);
$showRebroad->save();
}
@@ -1735,10 +1862,9 @@ SQL;
}
/**
- *
* Deletes all the cc_show_hosts entries for a specific show
* that is currently being edited. They will get recreated with
- * the new show specs
+ * the new show specs.
*/
private function deleteCcShowHosts()
{
@@ -1746,8 +1872,8 @@ SQL;
}
/**
+ * Sets the fields for a cc_show_hosts table row.
*
- * Sets the fields for a cc_show_hosts table row
* @param $showData
* @param $showId
*/
@@ -1762,9 +1888,8 @@ SQL;
}
}
}
-
+
/**
- *
* Gets the date and time shows (particularly repeating shows)
* can be populated until.
*
@@ -1775,23 +1900,24 @@ SQL;
$populateUntil = Application_Model_Preference::GetShowsPopulatedUntil();
if (is_null($populateUntil)) {
- $populateUntil = new DateTime("now", new DateTimeZone('UTC'));
+ $populateUntil = new DateTime('now', new DateTimeZone('UTC'));
Application_Model_Preference::SetShowsPopulatedUntil($populateUntil);
}
+
return $populateUntil;
}
/**
- *
* Enter description here ...
+ *
* @param DateTime $showStart user's local time
- * @param string $duration time interval (h)h:(m)m(:ss)
- * @param string $timezone "Europe/Prague"
- * @param array $offset (days, hours, mins) used for rebroadcast shows
+ * @param string $duration time interval (h)h:(m)m(:ss)
+ * @param string $timezone "Europe/Prague"
+ * @param array $offset (days, hours, mins) used for rebroadcast shows
*
* @return array of 2 DateTime objects, start/end time of the show in UTC
*/
- private function createUTCStartEndDateTime($showStart, $duration, $offset=null)
+ private function createUTCStartEndDateTime($showStart, $duration, $offset = null)
{
$startDateTime = clone $showStart;
$timezone = $startDateTime->getTimezone();
@@ -1799,24 +1925,23 @@ SQL;
if (isset($offset)) {
//$offset["hours"] and $offset["mins"] represents the start time
//of a rebroadcast show
- $startDateTime = new DateTime($startDateTime->format("Y-m-d")." ".
- $offset["hours"].":".$offset["mins"], $timezone);
- $startDateTime->add(new DateInterval("P{$offset["days"]}D"));
+ $startDateTime = new DateTime($startDateTime->format('Y-m-d') . ' ' .
+ $offset['hours'] . ':' . $offset['mins'], $timezone);
+ $startDateTime->add(new DateInterval("P{$offset['days']}D"));
}
$endDateTime = clone $startDateTime;
- $duration = explode(":", $duration);
+ $duration = explode(':', $duration);
list($hours, $mins) = array_slice($duration, 0, 2);
$endDateTime->add(new DateInterval("PT{$hours}H{$mins}M"));
$startDateTime->setTimezone(new DateTimeZone('UTC'));
$endDateTime->setTimezone(new DateTimeZone('UTC'));
- return array($startDateTime, $endDateTime);
+ return [$startDateTime, $endDateTime];
}
/**
- *
* Show instances for repeating shows only get created up
* until what is visible on the calendar. We need to set the
* date for when the next repeating show instance should be created
@@ -1828,15 +1953,17 @@ SQL;
*/
private function setNextRepeatingShowDate($nextDate, $day, $showId)
{
- $nextInfo = explode(" ", $nextDate);
+ $nextInfo = explode(' ', $nextDate);
$repeatInfo = CcShowDaysQuery::create()
->filterByDbShowId($showId)
->filterByDbDay($day)
->filterByDbRepeatType(-1, Criteria::NOT_EQUAL)
- ->findOne();
+ ->findOne()
+ ;
$repeatInfo->setDbNextPopDate($nextInfo[0])
- ->save();
+ ->save()
+ ;
}
}
diff --git a/legacy/application/services/ThirdPartyCeleryService.php b/legacy/application/services/ThirdPartyCeleryService.php
index 25c6a9487..06b9bd547 100644
--- a/legacy/application/services/ThirdPartyCeleryService.php
+++ b/legacy/application/services/ThirdPartyCeleryService.php
@@ -1,7 +1,7 @@
_createTaskReference($fileId, $brokerTaskId, $taskName);
} catch (Exception $e) {
- Logging::error("Invalid request: " . $e->getMessage());
+ Logging::error('Invalid request: ' . $e->getMessage());
+
throw $e;
}
}
@@ -44,21 +49,23 @@ abstract class Application_Service_ThirdPartyCeleryService extends Application_S
* receive completed task messages
* @param $taskName string broker task name
*
- * @return CeleryTasks the created task
- *
* @throws Exception
* @throws PropelException
+ *
+ * @return CeleryTasks the created task
*/
- protected function _createTaskReference($fileId, $brokerTaskId, $taskName) {
+ protected function _createTaskReference($fileId, $brokerTaskId, $taskName)
+ {
$trackReferenceId = $this->createTrackReference($fileId);
$task = new CeleryTasks();
$task->setDbTaskId($brokerTaskId);
$task->setDbName($taskName);
- $utc = new DateTimeZone("UTC");
- $task->setDbDispatchTime(new DateTime("now", $utc));
+ $utc = new DateTimeZone('UTC');
+ $task->setDbDispatchTime(new DateTime('now', $utc));
$task->setDbStatus(CELERY_PENDING_STATUS);
$task->setDbTrackReference($trackReferenceId);
$task->save();
+
return $task;
}
@@ -72,13 +79,14 @@ abstract class Application_Service_ThirdPartyCeleryService extends Application_S
* @throws Exception
* @throws PropelException
*/
- public function updateTask($task, $status) {
+ public function updateTask($task, $status)
+ {
$task->setDbStatus($status);
$task->save();
}
/**
- * Update a ThirdPartyTrackReferences object for a completed upload
+ * Update a ThirdPartyTrackReferences object for a completed upload.
*
* Manipulation and use of the track object is left up to child implementations
*
@@ -87,23 +95,25 @@ abstract class Application_Service_ThirdPartyCeleryService extends Application_S
* @param $result mixed Celery task result message
* @param $status string Celery task status
*
- * @return ThirdPartyTrackReferences the updated ThirdPartyTrackReferences object
- *
* @throws Exception
* @throws PropelException
+ *
+ * @return ThirdPartyTrackReferences the updated ThirdPartyTrackReferences object
*/
- public function updateTrackReference($task, $trackId, $result, $status) {
+ public function updateTrackReference($task, $trackId, $result, $status)
+ {
static::updateTask($task, $status);
$ref = ThirdPartyTrackReferencesQuery::create()
- ->findOneByDbId($trackId);
+ ->findOneByDbId($trackId)
+ ;
if (is_null($ref)) {
$ref = new ThirdPartyTrackReferences();
}
$ref->setDbService(static::$_SERVICE_NAME);
- $utc = new DateTimeZone("UTC");
- $ref->setDbUploadTime(new DateTime("now", $utc));
+ $utc = new DateTimeZone('UTC');
+ $ref->setDbUploadTime(new DateTime('now', $utc));
$ref->save();
+
return $ref;
}
-
-}
\ No newline at end of file
+}
diff --git a/legacy/application/services/ThirdPartyService.php b/legacy/application/services/ThirdPartyService.php
index 1fca386f5..74139aa7b 100644
--- a/legacy/application/services/ThirdPartyService.php
+++ b/legacy/application/services/ThirdPartyService.php
@@ -1,15 +1,17 @@
filterByDbService(static::$_SERVICE_NAME)
- ->findOneByDbFileId($fileId);
+ ->findOneByDbFileId($fileId)
+ ;
if (is_null($ref)) {
$ref = new ThirdPartyTrackReferences();
}
$ref->setDbService(static::$_SERVICE_NAME);
$ref->setDbFileId($fileId);
$ref->save();
+
return $ref->getDbId();
}
/**
* Remove a ThirdPartyTrackReferences row from the database.
* This is necessary if the track was removed from the service
- * or the foreign id in our database is incorrect
+ * or the foreign id in our database is incorrect.
*
* @param $fileId int cc_files identifier
*
* @throws Exception
* @throws PropelException
*/
- public function removeTrackReference($fileId) {
+ public function removeTrackReference($fileId)
+ {
$ref = ThirdPartyTrackReferencesQuery::create()
->filterByDbService(static::$_SERVICE_NAME)
- ->findOneByDbFileId($fileId);
+ ->findOneByDbFileId($fileId)
+ ;
$ref->delete();
}
/**
* Given a CcFiles identifier for a file that's been uploaded to a third-party service,
- * return the third-party identifier for the remote file
+ * return the third-party identifier for the remote file.
*
* @param int $fileId the cc_files identifier
*
* @return string the service foreign identifier
*/
- public function getServiceId($fileId) {
+ public function getServiceId($fileId)
+ {
$ref = ThirdPartyTrackReferencesQuery::create()
->filterByDbService(static::$_SERVICE_NAME)
- ->findOneByDbFileId($fileId); // There shouldn't be duplicates!
+ ->findOneByDbFileId($fileId) // There shouldn't be duplicates!
+ ;
+
return empty($ref) ? '' : $ref->getDbForeignId();
}
/**
- * Check if a reference exists for a given CcFiles identifier
+ * Check if a reference exists for a given CcFiles identifier.
*
* @param int $fileId the cc_files identifier
*
@@ -83,18 +93,22 @@ abstract class Application_Service_ThirdPartyService {
* 0 if the file has yet to be published,
* or -1 if the file is in a pending state
*/
- public function referenceExists($fileId) {
+ public function referenceExists($fileId)
+ {
$ref = ThirdPartyTrackReferencesQuery::create()
->filterByDbService(static::$_SERVICE_NAME)
- ->findOneByDbFileId($fileId);
+ ->findOneByDbFileId($fileId)
+ ;
if (!empty($ref)) {
$task = CeleryTasksQuery::create()
->orderByDbDispatchTime(Criteria::DESC)
- ->findOneByDbTrackReference($ref->getDbId());
+ ->findOneByDbTrackReference($ref->getDbId())
+ ;
+
return $task->getDbStatus() == CELERY_PENDING_STATUS ? -1
: ($task->getDbStatus() == CELERY_FAILED_STATUS ? 0 : 1);
}
+
return 0;
}
-
-}
\ No newline at end of file
+}
diff --git a/legacy/application/services/UserService.php b/legacy/application/services/UserService.php
index 40e077a39..f39042431 100644
--- a/legacy/application/services/UserService.php
+++ b/legacy/application/services/UserService.php
@@ -13,8 +13,7 @@ class Application_Service_UserService
}
/**
- *
- * Returns a CcSubjs object
+ * Returns a CcSubjs object.
*/
public function getCurrentUser()
{
@@ -24,5 +23,4 @@ class Application_Service_UserService
return $this->currentUser;
}
-
-}
\ No newline at end of file
+}
diff --git a/legacy/application/upgrade/Upgrades.php b/legacy/application/upgrade/Upgrades.php
index 547a2226c..3c066b212 100644
--- a/legacy/application/upgrade/Upgrades.php
+++ b/legacy/application/upgrade/Upgrades.php
@@ -1,57 +1,60 @@
checkIfUpgradeSupported() && $upgrader->upgrade();
}
/**
- * Run the given downgrade
+ * Run the given downgrade.
*
* @param $downgrader AirtimeUpgrader the upgrader class to be executed
* @param $supportedVersions array array of supported versions
*
* @return bool true if the downgrade was successful, otherwise false
*/
- private static function _runDowngrade(AirtimeUpgrader $downgrader) {
+ private static function _runDowngrade(AirtimeUpgrader $downgrader)
+ {
return $downgrader->checkIfDowngradeSupported() && $downgrader->downgrade();
}
-
}
abstract class AirtimeUpgrader
{
protected $_dir;
- protected $username, $password, $host, $database;
+ protected $username;
+ protected $password;
+ protected $host;
+ protected $database;
/**
* @param $dir string directory housing upgrade files
*/
- public function __construct($dir) {
+ public function __construct($dir)
+ {
$this->_dir = $dir;
}
@@ -136,8 +144,9 @@ abstract class AirtimeUpgrader
}
/**
- * This function checks to see if this class can perform an upgrade of your version of Airtime
- * @return boolean True if we can upgrade your version of Airtime.
+ * This function checks to see if this class can perform an upgrade of your version of Airtime.
+ *
+ * @return bool true if we can upgrade your version of Airtime
*/
public function checkIfUpgradeSupported()
{
@@ -145,9 +154,9 @@ abstract class AirtimeUpgrader
}
/**
- * This function checks to see if this class can perform a downgrade of your version of Airtime
+ * This function checks to see if this class can perform a downgrade of your version of Airtime.
*
- * @return boolean True if we can downgrade your version of Airtime.
+ * @return bool true if we can downgrade your version of Airtime
*/
public function checkIfDowngradeSupported()
{
@@ -156,8 +165,7 @@ abstract class AirtimeUpgrader
protected function toggleMaintenanceScreen($toggle)
{
- if ($toggle)
- {
+ if ($toggle) {
//Disable Airtime UI
//create a temporary maintenance notification file
//when this file is on the server, zend framework redirects all
@@ -167,21 +175,21 @@ abstract class AirtimeUpgrader
$file = fopen($this->maintenanceFile, 'w');
fclose($file);
*/
- } else {
- //delete maintenance.txt to give users access back to Airtime
+ }
+ //delete maintenance.txt to give users access back to Airtime
/* DISABLED because this does not work correctly
if ($this->maintenanceFile) {
unlink($this->maintenanceFile);
}*/
- }
}
/**
* Implement this for each new version of Airtime
* This function abstracts out the core upgrade functionality,
- * allowing child classes to overwrite _runUpgrade to reduce duplication
+ * allowing child classes to overwrite _runUpgrade to reduce duplication.
*/
- public function upgrade() {
+ public function upgrade()
+ {
try {
// $this->toggleMaintenanceScreen(true);
@@ -191,9 +199,10 @@ abstract class AirtimeUpgrader
Application_Model_Preference::SetSchemaVersion($this->getNewVersion());
// $this->toggleMaintenanceScreen(false);
- } catch(Exception $e) {
+ } catch (Exception $e) {
// $this->toggleMaintenanceScreen(false);
- Logging::error('Error in upgrade: '. $e->getMessage());
+ Logging::error('Error in upgrade: ' . $e->getMessage());
+
return false;
}
@@ -203,10 +212,10 @@ abstract class AirtimeUpgrader
/**
* Implement this for each new version of Airtime
* This function abstracts out the core downgrade functionality,
- * allowing child classes to overwrite _runDowngrade to reduce duplication
+ * allowing child classes to overwrite _runDowngrade to reduce duplication.
*/
- public function downgrade() {
-
+ public function downgrade()
+ {
try {
$this->_getDbValues();
$this->_runDowngrade();
@@ -221,42 +230,43 @@ abstract class AirtimeUpgrader
// Set the schema version to the highest supported version so we don't skip versions when downgrading
Application_Model_Preference::SetSchemaVersion($highestSupportedVersion);
-
- } catch(Exception $e) {
+ } catch (Exception $e) {
return false;
}
return true;
}
- protected function _getDbValues() {
+ protected function _getDbValues()
+ {
$config = Config::getConfig();
$this->username = $config['dsn']['username'];
$this->password = $config['dsn']['password'];
- $this->host = $config['dsn']['hostspec'];
+ $this->host = $config['dsn']['hostspec'];
$this->database = $config['dsn']['database'];
}
- protected function _runUpgrade() {
- passthru("export PGPASSWORD=".$this->password." && /usr/bin/psql -h ".$this->host." -U ".$this->username." -q -f ".$this->_dir."/upgrade_sql/airtime_"
- .$this->getNewVersion()."/upgrade.sql ".$this->database." 2>&1 | grep -v -E \"will create implicit sequence|will create implicit index\"");
+ protected function _runUpgrade()
+ {
+ passthru('export PGPASSWORD=' . $this->password . ' && /usr/bin/psql -h ' . $this->host . ' -U ' . $this->username . ' -q -f ' . $this->_dir . '/upgrade_sql/airtime_'
+ . $this->getNewVersion() . '/upgrade.sql ' . $this->database . ' 2>&1 | grep -v -E "will create implicit sequence|will create implicit index"');
}
- protected function _runDowngrade() {
- passthru("export PGPASSWORD=".$this->password." && /usr/bin/psql -h ".$this->host." -U ".$this->username." -q -f ".$this->_dir."/downgrade_sql/airtime_"
- .$this->getNewVersion()."/downgrade.sql ".$this->database." 2>&1 | grep -v -E \"will create implicit sequence|will create implicit index\"");
+ protected function _runDowngrade()
+ {
+ passthru('export PGPASSWORD=' . $this->password . ' && /usr/bin/psql -h ' . $this->host . ' -U ' . $this->username . ' -q -f ' . $this->_dir . '/downgrade_sql/airtime_'
+ . $this->getNewVersion() . '/downgrade.sql ' . $this->database . ' 2>&1 | grep -v -E "will create implicit sequence|will create implicit index"');
}
-
}
class AirtimeUpgrader253 extends AirtimeUpgrader
{
protected function getSupportedSchemaVersions()
{
- return array('2.5.1', '2.5.2');
-
+ return ['2.5.1', '2.5.2'];
}
+
public function getNewVersion()
{
return '2.5.3';
@@ -265,8 +275,8 @@ class AirtimeUpgrader253 extends AirtimeUpgrader
protected function _runUpgrade()
{
//Update disk_usage value in cc_pref
- $storDir = isset($_SERVER['AIRTIME_BASE']) ? $_SERVER['AIRTIME_BASE']."srv/airtime/stor" : "/srv/airtime/stor";
- $diskUsage = shell_exec("du -sb $storDir | awk '{print $1}'");
+ $storDir = isset($_SERVER['AIRTIME_BASE']) ? $_SERVER['AIRTIME_BASE'] . 'srv/airtime/stor' : '/srv/airtime/stor';
+ $diskUsage = shell_exec("du -sb {$storDir} | awk '{print $1}'");
Application_Model_Preference::setDiskUsage($diskUsage);
@@ -278,8 +288,9 @@ class AirtimeUpgrader254 extends AirtimeUpgrader
{
protected function getSupportedSchemaVersions()
{
- return array('2.5.3');
+ return ['2.5.3'];
}
+
public function getNewVersion()
{
return '2.5.4';
@@ -290,23 +301,24 @@ class AirtimeUpgrader254 extends AirtimeUpgrader
//First, ensure there are no superadmins already.
$numberOfSuperAdmins = CcSubjsQuery::create()
->filterByDbType(UTYPE_SUPERADMIN)
- ->filterByDbLogin("sourcefabric_admin", Criteria::NOT_EQUAL) //Ignore sourcefabric_admin users
- ->count();
+ ->filterByDbLogin('sourcefabric_admin', Criteria::NOT_EQUAL) //Ignore sourcefabric_admin users
+ ->count()
+ ;
//Only create a super admin if there isn't one already.
- if ($numberOfSuperAdmins == 0)
- {
+ if ($numberOfSuperAdmins == 0) {
//Find the "admin" user and promote them to superadmin.
$adminUser = CcSubjsQuery::create()
->filterByDbLogin('admin')
- ->findOne();
- if (!$adminUser)
- {
+ ->findOne()
+ ;
+ if (!$adminUser) {
// Otherwise get the user with the lowest ID that is of type administrator:
$adminUser = CcSubjsQuery::create()
->filterByDbType(UTYPE_ADMIN)
->orderByDbId(Criteria::ASC)
- ->findOne();
+ ->findOne()
+ ;
if (!$adminUser) {
throw new Exception("Failed to find any users of type 'admin' ('A').");
@@ -316,76 +328,89 @@ class AirtimeUpgrader254 extends AirtimeUpgrader
$adminUser = new Application_Model_User($adminUser->getDbId());
$adminUser->setType(UTYPE_SUPERADMIN);
$adminUser->save();
- Logging::info($_SERVER['HTTP_HOST'] . ': ' . $this->getNewVersion() . " Upgrade: Promoted user " . $adminUser->getLogin() . " to be a Super Admin.");
+ Logging::info($_SERVER['HTTP_HOST'] . ': ' . $this->getNewVersion() . ' Upgrade: Promoted user ' . $adminUser->getLogin() . ' to be a Super Admin.');
//Also try to promote the sourcefabric_admin user
$sofabAdminUser = CcSubjsQuery::create()
->filterByDbLogin('sourcefabric_admin')
- ->findOne();
+ ->findOne()
+ ;
if ($sofabAdminUser) {
$sofabAdminUser = new Application_Model_User($sofabAdminUser->getDbId());
$sofabAdminUser->setType(UTYPE_SUPERADMIN);
$sofabAdminUser->save();
- Logging::info($_SERVER['HTTP_HOST'] . ': ' . $this->getNewVersion() . " Upgrade: Promoted user " . $sofabAdminUser->getLogin() . " to be a Super Admin.");
+ Logging::info($_SERVER['HTTP_HOST'] . ': ' . $this->getNewVersion() . ' Upgrade: Promoted user ' . $sofabAdminUser->getLogin() . ' to be a Super Admin.');
}
}
}
}
-class AirtimeUpgrader255 extends AirtimeUpgrader {
- protected function getSupportedSchemaVersions() {
- return array (
- '2.5.4'
- );
+class AirtimeUpgrader255 extends AirtimeUpgrader
+{
+ protected function getSupportedSchemaVersions()
+ {
+ return [
+ '2.5.4',
+ ];
}
- public function getNewVersion() {
+ public function getNewVersion()
+ {
return '2.5.5';
}
}
-class AirtimeUpgrader259 extends AirtimeUpgrader {
- protected function getSupportedSchemaVersions() {
- return array (
- '2.5.5'
- );
+class AirtimeUpgrader259 extends AirtimeUpgrader
+{
+ protected function getSupportedSchemaVersions()
+ {
+ return [
+ '2.5.5',
+ ];
}
- public function getNewVersion() {
+ public function getNewVersion()
+ {
return '2.5.9';
}
}
class AirtimeUpgrader2510 extends AirtimeUpgrader
{
- protected function getSupportedSchemaVersions() {
- return array (
- '2.5.9'
- );
+ protected function getSupportedSchemaVersions()
+ {
+ return [
+ '2.5.9',
+ ];
}
- public function getNewVersion() {
+ public function getNewVersion()
+ {
return '2.5.10';
}
}
class AirtimeUpgrader2511 extends AirtimeUpgrader
{
- protected function getSupportedSchemaVersions() {
- return array (
- '2.5.10'
- );
+ protected function getSupportedSchemaVersions()
+ {
+ return [
+ '2.5.10',
+ ];
}
- public function getNewVersion() {
+ public function getNewVersion()
+ {
return '2.5.11';
}
- protected function _runUpgrade() {
+ protected function _runUpgrade()
+ {
$queryResult = CcFilesQuery::create()
- ->select(array('disk_usage'))
+ ->select(['disk_usage'])
->withColumn('SUM(CcFiles.filesize)', 'disk_usage')
- ->find();
+ ->find()
+ ;
$disk_usage = $queryResult[0];
Application_Model_Preference::setDiskUsage($disk_usage);
}
@@ -393,20 +418,22 @@ class AirtimeUpgrader2511 extends AirtimeUpgrader
class AirtimeUpgrader2512 extends AirtimeUpgrader
{
- protected function getSupportedSchemaVersions() {
- return array (
+ protected function getSupportedSchemaVersions()
+ {
+ return [
'2.5.10',
- '2.5.11'
- );
+ '2.5.11',
+ ];
}
- public function getNewVersion() {
+ public function getNewVersion()
+ {
return '2.5.12';
}
}
/**
- * Class AirtimeUpgrader2513 - Celery and SoundCloud upgrade
+ * Class AirtimeUpgrader2513 - Celery and SoundCloud upgrade.
*
* Adds third_party_track_references and celery_tasks tables for third party service
* authentication and task architecture.
@@ -428,41 +455,44 @@ class AirtimeUpgrader2512 extends AirtimeUpgrader
* name -> string external Celery task name
* dispatch_time -> timestamp internal message dispatch time
* status -> string external Celery task status
- *
*/
class AirtimeUpgrader2513 extends AirtimeUpgrader
{
- protected function getSupportedSchemaVersions() {
- return array (
- '2.5.12'
- );
+ protected function getSupportedSchemaVersions()
+ {
+ return [
+ '2.5.12',
+ ];
}
- public function getNewVersion() {
+ public function getNewVersion()
+ {
return '2.5.13';
}
}
/**
- * Class AirtimeUpgrader2514
+ * Class AirtimeUpgrader2514.
*
* SAAS-923 - Add a partial constraint to cc_pref so that keystrings must be unique
*/
class AirtimeUpgrader2514 extends AirtimeUpgrader
{
- protected function getSupportedSchemaVersions() {
- return array (
- '2.5.13'
- );
+ protected function getSupportedSchemaVersions()
+ {
+ return [
+ '2.5.13',
+ ];
}
- public function getNewVersion() {
+ public function getNewVersion()
+ {
return '2.5.14';
}
}
/**
- * Class AirtimeUpgrader2515
+ * Class AirtimeUpgrader2515.
*
* SAAS-1071 - Remove not null constraint from file_id fk in third_party_track_references
* so that we can create track references for downloads (which won't have a file
@@ -470,184 +500,205 @@ class AirtimeUpgrader2514 extends AirtimeUpgrader
*/
class AirtimeUpgrader2515 extends AirtimeUpgrader
{
- protected function getSupportedSchemaVersions() {
- return array (
- '2.5.14'
- );
+ protected function getSupportedSchemaVersions()
+ {
+ return [
+ '2.5.14',
+ ];
}
- public function getNewVersion() {
+ public function getNewVersion()
+ {
return '2.5.15';
}
}
class AirtimeUpgrader2516 extends AirtimeUpgrader
{
- protected function getSupportedSchemaVersions() {
- return array(
- '2.5.15'
- );
+ protected function getSupportedSchemaVersions()
+ {
+ return [
+ '2.5.15',
+ ];
}
- public function getNewVersion() {
+ public function getNewVersion()
+ {
return '2.5.16';
}
}
class AirtimeUpgrader300alpha extends AirtimeUpgrader
{
- protected function getSupportedSchemaVersions() {
- return array(
- '2.5.16'
- );
+ protected function getSupportedSchemaVersions()
+ {
+ return [
+ '2.5.16',
+ ];
}
- public function getNewVersion() {
+ public function getNewVersion()
+ {
return '3.0.0-alpha';
}
}
class AirtimeUpgrader300alpha1 extends AirtimeUpgrader
{
- protected function getSupportedSchemaVersions() {
- return array(
- '3.0.0-alpha'
- );
+ protected function getSupportedSchemaVersions()
+ {
+ return [
+ '3.0.0-alpha',
+ ];
}
- public function getNewVersion() {
+ public function getNewVersion()
+ {
return '3.0.0-alpha.1';
}
}
class AirtimeUpgrader300alpha6 extends AirtimeUpgrader
{
- protected function getSupportedSchemaVersions() {
- return array(
- '3.0.0-alpha.1'
- );
+ protected function getSupportedSchemaVersions()
+ {
+ return [
+ '3.0.0-alpha.1',
+ ];
}
- public function getNewVersion() {
+ public function getNewVersion()
+ {
return '3.0.0-alpha.6';
}
}
/**
- * Class AirtimeUpgrader300alpha7
+ * Class AirtimeUpgrader300alpha7.
*
* GH-#636 - https://github.com/LibreTime/libretime/pull/636 - Change dynamic smartblock to be default smartblock type
*/
-
-
class AirtimeUpgrader300alpha7 extends AirtimeUpgrader
{
- protected function getSupportedSchemaVersions() {
- return array(
- '3.0.0-alpha.6'
- );
- }
- public function getNewVersion() {
- return '3.0.0-alpha.7';
+ protected function getSupportedSchemaVersions()
+ {
+ return [
+ '3.0.0-alpha.6',
+ ];
}
+ public function getNewVersion()
+ {
+ return '3.0.0-alpha.7';
+ }
}
/**
- * Class AirtimeUpgrader300alpha7-1
+ * Class AirtimeUpgrader300alpha7-1.
*
* GH-#659 - https://github.com/LibreTime/libretime/pull/659/ - Add description and title to podcast episodes database table
*/
-
-
class AirtimeUpgrader300alpha7_1 extends AirtimeUpgrader
{
- protected function getSupportedSchemaVersions() {
- return array(
- '3.0.0-alpha.7'
- );
- }
- public function getNewVersion() {
- return '3.0.0-alpha.7.1';
+ protected function getSupportedSchemaVersions()
+ {
+ return [
+ '3.0.0-alpha.7',
+ ];
}
+ public function getNewVersion()
+ {
+ return '3.0.0-alpha.7.1';
+ }
}
/**
- * Class AirtimeUpgrader300alpha7-2
+ * Class AirtimeUpgrader300alpha7-2.
*
* GH-#704 - https://github.com/LibreTime/libretime/pull/704/ - Add criteria group to smartblock table to enable database to store separately
*/
-
-
-
class AirtimeUpgrader300alpha7_2 extends AirtimeUpgrader
{
- protected function getSupportedSchemaVersions() {
- return array(
- '3.0.0-alpha.7.1'
- );
+ protected function getSupportedSchemaVersions()
+ {
+ return [
+ '3.0.0-alpha.7.1',
+ ];
}
- public function getNewVersion() {
+
+ public function getNewVersion()
+ {
return '3.0.0-alpha.7.2';
}
}
class AirtimeUpgrader300alpha7_3 extends AirtimeUpgrader
{
- protected function getSupportedSchemaVersions() {
- return array(
- '3.0.0-alpha.7.2'
- );
+ protected function getSupportedSchemaVersions()
+ {
+ return [
+ '3.0.0-alpha.7.2',
+ ];
}
- public function getNewVersion() {
+
+ public function getNewVersion()
+ {
return '3.0.0-alpha.7.3';
}
}
class AirtimeUpgrader300alpha9_1 extends AirtimeUpgrader
{
- protected function getSupportedSchemaVersions() {
- return array(
- '3.0.0-alpha.7.3'
- );
+ protected function getSupportedSchemaVersions()
+ {
+ return [
+ '3.0.0-alpha.7.3',
+ ];
}
- public function getNewVersion() {
+ public function getNewVersion()
+ {
return '3.0.0-alpha.9.1';
}
}
class AirtimeUpgrader300alpha9_2 extends AirtimeUpgrader
{
- protected function getSupportedSchemaVersions() {
- return array(
- '3.0.0-alpha.9.1'
- );
+ protected function getSupportedSchemaVersions()
+ {
+ return [
+ '3.0.0-alpha.9.1',
+ ];
}
- public function getNewVersion() {
+ public function getNewVersion()
+ {
return '3.0.0-alpha.9.2';
}
}
class AirtimeUpgrader200alpha9_3 extends AirtimeUpgrader
{
- protected function getSupportedSchemaVersions() {
- return array(
- '3.0.0-alpha.9.2'
- );
+ protected function getSupportedSchemaVersions()
+ {
+ return [
+ '3.0.0-alpha.9.2',
+ ];
}
- public function getNewVersion() {
+ public function getNewVersion()
+ {
return '3.0.0-alpha.9.3';
}
}
class AirtimeUpgrader200alpha9_4 extends AirtimeUpgrader
{
- protected function getSupportedSchemaVersions() {
- return array(
- '3.0.0-alpha.9.3'
- );
+ protected function getSupportedSchemaVersions()
+ {
+ return [
+ '3.0.0-alpha.9.3',
+ ];
}
- public function getNewVersion() {
+ public function getNewVersion()
+ {
return '3.0.0-alpha.9.4';
}
-}
\ No newline at end of file
+}
diff --git a/legacy/application/validate/NotDemoValidate.php b/legacy/application/validate/NotDemoValidate.php
index 2ebdfcc14..957790840 100644
--- a/legacy/application/validate/NotDemoValidate.php
+++ b/legacy/application/validate/NotDemoValidate.php
@@ -2,23 +2,23 @@
class Application_Validate_NotDemoValidate extends Zend_Validate_Abstract
{
- const NOTDEMO = 'notdemo';
+ public const NOTDEMO = 'notdemo';
- protected $_messageTemplates = array(
- self::NOTDEMO => "Cannot be changed in demo mode"
- );
+ protected $_messageTemplates = [
+ self::NOTDEMO => 'Cannot be changed in demo mode',
+ ];
public function isValid($value)
{
- $this->_setValue($value);
-
+ $this->_setValue($value);
+
$CC_CONFIG = Config::getConfig();
if (isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1) {
- $this->_error(self::NOTDEMO);
- return false;
- } else {
- return true;
+ $this->_error(self::NOTDEMO);
+
+ return false;
}
+
+ return true;
}
}
-
diff --git a/legacy/application/validate/UserNameValidate.php b/legacy/application/validate/UserNameValidate.php
index 1338b6c72..e3f06113f 100644
--- a/legacy/application/validate/UserNameValidate.php
+++ b/legacy/application/validate/UserNameValidate.php
@@ -2,11 +2,11 @@
class Application_Validate_UserNameValidate extends Zend_Validate_Abstract
{
- const LOGIN = 'login';
+ public const LOGIN = 'login';
- protected $_messageTemplates = array(
- self::LOGIN => "'%value%' is already taken"
- );
+ protected $_messageTemplates = [
+ self::LOGIN => "'%value%' is already taken",
+ ];
public function isValid($value)
{
@@ -16,10 +16,10 @@ class Application_Validate_UserNameValidate extends Zend_Validate_Abstract
if ($count != 0) {
$this->_error(self::LOGIN);
+
return false;
}
return true;
}
}
-
diff --git a/legacy/application/views/helpers/LoggedInAs.php b/legacy/application/views/helpers/LoggedInAs.php
index 77f0b663e..496187a94 100644
--- a/legacy/application/views/helpers/LoggedInAs.php
+++ b/legacy/application/views/helpers/LoggedInAs.php
@@ -2,15 +2,15 @@
class Airtime_View_Helper_LoggedInAs extends Zend_View_Helper_Abstract
{
- public function loggedInAs ()
+ public function loggedInAs()
{
- $username = "";
+ $username = '';
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
$username = $auth->getIdentity()->login;
}
+
return $username;
}
}
-
diff --git a/legacy/application/views/helpers/SourceConnectionStatus.php b/legacy/application/views/helpers/SourceConnectionStatus.php
index 1d86b0f57..2b9d71d29 100644
--- a/legacy/application/views/helpers/SourceConnectionStatus.php
+++ b/legacy/application/views/helpers/SourceConnectionStatus.php
@@ -1,8 +1,9 @@
Application_Model_Preference::GetSourceStatus("live_dj"), "master_dj"=>Application_Model_Preference::GetSourceStatus("master_dj"));
- return $status;
+class Airtime_View_Helper_SourceConnectionStatus extends Zend_View_Helper_Abstract
+{
+ public function SourceConnectionStatus()
+ {
+ return ['live_dj' => Application_Model_Preference::GetSourceStatus('live_dj'), 'master_dj' => Application_Model_Preference::GetSourceStatus('master_dj')];
}
-}
\ No newline at end of file
+}
diff --git a/legacy/application/views/helpers/SourceSwitchStatus.php b/legacy/application/views/helpers/SourceSwitchStatus.php
index 86ca01707..c801fbdcf 100644
--- a/legacy/application/views/helpers/SourceSwitchStatus.php
+++ b/legacy/application/views/helpers/SourceSwitchStatus.php
@@ -1,10 +1,11 @@
Application_Model_Preference::GetSourceSwitchStatus("live_dj"),
- "master_dj"=>Application_Model_Preference::GetSourceSwitchStatus("master_dj"),
- "scheduled_play"=>Application_Model_Preference::GetSourceSwitchStatus("scheduled_play"));
- return $status;
+class Airtime_View_Helper_SourceSwitchStatus extends Zend_View_Helper_Abstract
+{
+ public function SourceSwitchStatus()
+ {
+ return ['live_dj' => Application_Model_Preference::GetSourceSwitchStatus('live_dj'),
+ 'master_dj' => Application_Model_Preference::GetSourceSwitchStatus('master_dj'),
+ 'scheduled_play' => Application_Model_Preference::GetSourceSwitchStatus('scheduled_play'), ];
}
-}
\ No newline at end of file
+}
diff --git a/legacy/application/views/helpers/VersionNotify.php b/legacy/application/views/helpers/VersionNotify.php
index dd6f6424b..48cbcd6e5 100644
--- a/legacy/application/views/helpers/VersionNotify.php
+++ b/legacy/application/views/helpers/VersionNotify.php
@@ -1,6 +1,5 @@
versionParser = new VersionParser();
}
/**
- * Prepare data for update notifier widget
+ * Prepare data for update notifier widget.
*
* Grabs the version from the VERSION file created by build.sh and compares
* it against the versions available from github using the semver code from
* the composer project.
*/
- public function versionNotify() {
-
+ public function versionNotify()
+ {
$config = Config::getConfig();
// retrieve and validate current and latest versions,
@@ -59,13 +59,13 @@ class Airtime_View_Helper_VersionNotify extends Zend_View_Helper_Abstract {
$hasStable = !empty($stableVersions) && !$isGitRelease;
// no warning if no major release available, orange warning if you are on unreleased code
$class = $hasStable ? 'update2' : 'uptodate';
- } else if ($hasPatch || $hasMultiMajor) {
+ } elseif ($hasPatch || $hasMultiMajor) {
// current patch or more than 1 major behind
$class = 'outdated';
- } else if ($hasMinor) {
+ } elseif ($hasMinor) {
// green warning for feature update
$class = 'update';
- } else if ($hasMajor) {
+ } elseif ($hasMajor) {
// orange warning for 1 major beind
$class = 'update2';
} else {
@@ -74,7 +74,7 @@ class Airtime_View_Helper_VersionNotify extends Zend_View_Helper_Abstract {
$latest = SemVer::rsort($latest);
$highestVersion = $latest[0];
- $data = (object) array(
+ $data = (object) [
'link' => $link,
'latest' => $highestVersion,
'current' => $current,
@@ -83,27 +83,27 @@ class Airtime_View_Helper_VersionNotify extends Zend_View_Helper_Abstract {
'hasMajor' => $hasMajor,
'isPreRelease' => $isPreRelease,
'hasMultiMajor' => $hasMultiMajor,
- );
+ ];
- $result = sprintf('', json_encode($data))
+ return sprintf('', json_encode($data))
. "";
- return $result;
}
- private function normalizeVersion($version, $isGit) {
+ private function normalizeVersion($version, $isGit)
+ {
try {
$this->versionParser->normalize($version);
- } catch(UnexpectedValueException $e) {
+ } catch (UnexpectedValueException $e) {
// recover by assuming an unknown version
- $version= '0.0.0';
+ $version = '0.0.0';
}
- $parts = array();
+ $parts = [];
if (!$isGit) {
$parts = preg_split("/(\.|-)/", $version);
}
if (count($parts) < 3) {
- $parts = array(0, 0, 0);
+ $parts = [0, 0, 0];
}
return $parts;
diff --git a/legacy/application/views/scripts/partialviews/dashboard-sub-nav.php b/legacy/application/views/scripts/partialviews/dashboard-sub-nav.php
index f4bfec11b..aeed7282b 100644
--- a/legacy/application/views/scripts/partialviews/dashboard-sub-nav.php
+++ b/legacy/application/views/scripts/partialviews/dashboard-sub-nav.php
@@ -1,20 +1,20 @@
- |