diff --git a/airtime_mvc/application/controllers/ApiController.php b/airtime_mvc/application/controllers/ApiController.php
index 036174e62..2a8a3ad75 100644
--- a/airtime_mvc/application/controllers/ApiController.php
+++ b/airtime_mvc/application/controllers/ApiController.php
@@ -5,6 +5,7 @@ class ApiController extends Zend_Controller_Action
public function init()
{
+ $this->checkAuth();
/* Initialize action controller here */
$context = $this->_helper->getHelper('contextSwitch');
$context->addActionContext('version', 'json')
@@ -35,19 +36,19 @@ class ApiController extends Zend_Controller_Action
->addActionContext('reload-metadata-group', 'json')
->initContext();
}
-
+
public function checkAuth()
{
global $CC_CONFIG;
-
+
$api_key = $this->_getParam('api_key');
-
+
if (!in_array($api_key, $CC_CONFIG["apiKey"]) &&
is_null(Zend_Auth::getInstance()->getStorage()->read())) {
header('HTTP/1.0 401 Unauthorized');
print 'You are not allowed to access this resource.';
exit;
- }
+ }
}
public function indexAction()
@@ -67,8 +68,6 @@ class ApiController extends Zend_Controller_Action
*/
public function versionAction()
{
- $this->checkAuth();
-
// disable the view and the layout
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
@@ -81,13 +80,15 @@ class ApiController extends Zend_Controller_Action
* Sets up and send init values used in the Calendar.
* This is only being used by schedule.js at the moment.
*/
- public function calendarInitAction(){
+ public function calendarInitAction()
+ {
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
- if(is_null(Zend_Auth::getInstance()->getStorage()->read())) {
+ if (is_null(Zend_Auth::getInstance()->getStorage()->read())) {
header('HTTP/1.0 401 Unauthorized');
print 'You are not allowed to access this resource.';
+
return;
}
@@ -108,8 +109,6 @@ class ApiController extends Zend_Controller_Action
*/
public function getMediaAction()
{
- $this->checkAuth();
-
// disable the view and the layout
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
@@ -117,14 +116,12 @@ class ApiController extends Zend_Controller_Action
$fileID = $this->_getParam("file");
$file_id = substr($fileID, 0, strpos($fileID, "."));
- if (ctype_alnum($file_id) && strlen($file_id) == 32)
- {
+ if (ctype_alnum($file_id) && strlen($file_id) == 32) {
$media = Application_Model_StoredFile::RecallByGunid($file_id);
- if ( $media != null )
- {
-
+ if ($media != null) {
+
$filepath = $media->getFilePath();
- if(is_file($filepath)){
+ if (is_file($filepath)) {
$full_path = $media->getPropelOrm()->getDbFilepath();
$file_base_name = strrchr($full_path, '/');
@@ -141,7 +138,7 @@ class ApiController extends Zend_Controller_Action
// http://www.php.net/manual/en/book.fileinfo.php
$ext = pathinfo($fileID, PATHINFO_EXTENSION);
//Download user left clicks a track and selects Download.
- if ("true" == $this->_getParam('download')){
+ if ("true" == $this->_getParam('download')) {
//path_info breaks up a file path into seperate pieces of informaiton.
//We just want the basename which is the file name with the path
//information stripped away. We are using Content-Disposition to specify
@@ -151,21 +148,22 @@ class ApiController extends Zend_Controller_Action
// I'm removing pathinfo() since it strips away UTF-8 characters.
// Using manualy parsing
header('Content-Disposition: attachment; filename="'.$file_base_name.'"');
- }else{
+ } else {
//user clicks play button for track and downloads it.
header('Content-Disposition: inline; filename="'.$file_base_name.'"');
}
- if (strtolower($ext) === 'mp3'){
+ if (strtolower($ext) === 'mp3') {
$this->smartReadFile($filepath, 'audio/mpeg');
} else {
$this->smartReadFile($filepath, 'audio/'.$ext);
}
exit;
- }else{
+ } else {
header ("HTTP/1.1 404 Not Found");
}
}
}
+
return;
}
@@ -181,41 +179,33 @@ class ApiController extends Zend_Controller_Action
* @link https://groups.google.com/d/msg/jplayer/nSM2UmnSKKA/Hu76jDZS4xcJ
* @link http://php.net/manual/en/function.readfile.php#86244
*/
- function smartReadFile($location, $mimeType = 'audio/mp3')
+ public function smartReadFile($location, $mimeType = 'audio/mp3')
{
- $this->checkAuth();
-
$size= filesize($location);
$time= date('r', filemtime($location));
$fm = @fopen($location, 'rb');
- if (!$fm)
- {
+ if (!$fm) {
header ("HTTP/1.1 505 Internal server error");
+
return;
}
$begin= 0;
$end= $size - 1;
- if (isset($_SERVER['HTTP_RANGE']))
- {
- if (preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches))
- {
+ if (isset($_SERVER['HTTP_RANGE'])) {
+ if (preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches)) {
$begin = intval($matches[1]);
- if (!empty($matches[2]))
- {
+ if (!empty($matches[2])) {
$end = intval($matches[2]);
}
}
}
- if (isset($_SERVER['HTTP_RANGE']))
- {
+ if (isset($_SERVER['HTTP_RANGE'])) {
header('HTTP/1.1 206 Partial Content');
- }
- else
- {
+ } else {
header('HTTP/1.1 200 OK');
}
header("Content-Type: $mimeType");
@@ -223,8 +213,7 @@ class ApiController extends Zend_Controller_Action
header('Pragma: no-cache');
header('Accept-Ranges: bytes');
header('Content-Length:' . (($end - $begin) + 1));
- if (isset($_SERVER['HTTP_RANGE']))
- {
+ if (isset($_SERVER['HTTP_RANGE'])) {
header("Content-Range: bytes $begin-$end/$size");
}
header("Content-Transfer-Encoding: binary");
@@ -238,8 +227,7 @@ class ApiController extends Zend_Controller_Action
$cur = $begin;
fseek($fm, $begin, 0);
- while(!feof($fm) && $cur <= $end && (connection_status() == 0))
- {
+ while (!feof($fm) && $cur <= $end && (connection_status() == 0)) {
echo fread($fm, min(1024 * 16, ($end - $cur) + 1));
$cur += 1024 * 16;
}
@@ -262,7 +250,7 @@ class ApiController extends Zend_Controller_Action
*/
public function liveInfoAction()
{
- if (Application_Model_Preference::GetAllow3rdPartyApi()){
+ if (Application_Model_Preference::GetAllow3rdPartyApi()) {
// disable the view and the layout
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
@@ -273,7 +261,7 @@ class ApiController extends Zend_Controller_Action
$request = $this->getRequest();
$type = $request->getParam('type');
- if($type == "endofday") {
+ if ($type == "endofday") {
// make getNextShows use end of day
$utcTimeEnd = Application_Common_DateHelper::GetDayEndTimestampInUtc();
$result = array("env"=>APPLICATION_ENV,
@@ -281,10 +269,10 @@ class ApiController extends Zend_Controller_Action
"nextShow"=>Application_Model_Show::getNextShows($utcTimeNow, 5, $utcTimeEnd));
Application_Model_Show::convertToLocalTimeZone($result["nextShow"], array("starts", "ends", "start_timestamp", "end_timestamp"));
- }else{
+ } else {
$limit = $request->getParam('limit');
- if($limit == "" || !is_numeric($limit)) {
+ if ($limit == "" || !is_numeric($limit)) {
$limit = "5";
}
@@ -309,7 +297,7 @@ class ApiController extends Zend_Controller_Action
public function weekInfoAction()
{
- if (Application_Model_Preference::GetAllow3rdPartyApi()){
+ if (Application_Model_Preference::GetAllow3rdPartyApi()) {
// disable the view and the layout
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
@@ -321,7 +309,7 @@ class ApiController extends Zend_Controller_Action
$dow = array("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday");
$result = array();
- for ($i=0; $i<7; $i++){
+ for ($i=0; $i<7; $i++) {
$utcDayEnd = Application_Common_DateHelper::GetDayEndTimestamp($utcDayStart);
$shows = Application_Model_Show::getNextShows($utcDayStart, "0", $utcDayEnd);
$utcDayStart = $utcDayEnd;
@@ -342,8 +330,6 @@ class ApiController extends Zend_Controller_Action
public function scheduleAction()
{
- $this->checkAuth();
-
// disable the view and the layout
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
@@ -354,8 +340,6 @@ class ApiController extends Zend_Controller_Action
public function notifyMediaItemStartPlayAction()
{
- $this->checkAuth();
-
// disable the view and the layout
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
@@ -368,8 +352,6 @@ class ApiController extends Zend_Controller_Action
public function recordedShowsAction()
{
- $this->checkAuth();
-
$today_timestamp = date("Y-m-d H:i:s");
$now = new DateTime($today_timestamp);
$end_timestamp = $now->add(new DateInterval("PT2H"));
@@ -386,15 +368,13 @@ class ApiController extends Zend_Controller_Action
$rows = Application_Model_Show::GetCurrentShow($today_timestamp);
Application_Model_Show::convertToLocalTimeZone($rows, array("starts", "ends", "start_timestamp", "end_timestamp"));
- if (count($rows) > 0){
+ if (count($rows) > 0) {
$this->view->is_recording = ($rows[0]['record'] == 1);
}
}
public function uploadFileAction()
{
- $this->checkAuth();
-
$upload_dir = ini_get("upload_tmp_dir");
$tempFilePath = Application_Model_StoredFile::uploadFile($upload_dir);
$tempFileName = basename($tempFilePath);
@@ -402,15 +382,13 @@ class ApiController extends Zend_Controller_Action
$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
$result = Application_Model_StoredFile::copyFileToStor($upload_dir, $fileName, $tempFileName);
- if (!is_null($result)){
+ if (!is_null($result)) {
die('{"jsonrpc" : "2.0", "error" : {"code": '.$result[code].', "message" : "'.$result[message].'"}}');
}
}
public function uploadRecordedAction()
{
- $this->checkAuth();
-
//this file id is the recording for this show instance.
$show_instance_id = $this->_getParam('showinstanceid');
$file_id = $this->_getParam('fileid');
@@ -432,7 +410,7 @@ class ApiController extends Zend_Controller_Action
$show_genre = $show_inst->getGenre();
$show_start_time = Application_Common_DateHelper::ConvertToLocalDateTimeString($show_inst->getShowInstanceStart());
- } 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).
@@ -456,8 +434,7 @@ class ApiController extends Zend_Controller_Action
$new_name[] = $filename_parts[count($filename_parts)-1];
$tmpTitle = implode("-", $new_name);
- }
- else {
+ } else {
$tmpTitle = $file->getName();
}
@@ -465,16 +442,14 @@ class ApiController extends Zend_Controller_Action
$file->setMetadataValue('MDATA_KEY_CREATOR', "Airtime Show Recorder");
$file->setMetadataValue('MDATA_KEY_TRACKNUMBER', $show_instance_id);
- if (!$showCanceled && Application_Model_Preference::GetAutoUploadRecordedShowToSoundcloud())
- {
- $id = $file->getId();
+ if (!$showCanceled && Application_Model_Preference::GetAutoUploadRecordedShowToSoundcloud()) {
+ $id = $file->getId();
$res = exec("/usr/lib/airtime/utils/soundcloud-uploader $id > /dev/null &");
}
}
- public function mediaMonitorSetupAction() {
- $this->checkAuth();
-
+ public function mediaMonitorSetupAction()
+ {
// disable the view and the layout
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
@@ -483,7 +458,7 @@ class ApiController extends Zend_Controller_Action
$watchedDirs = Application_Model_MusicDir::getWatchedDirs();
$watchedDirsPath = array();
- foreach($watchedDirs as $wd){
+ foreach ($watchedDirs as $wd) {
$watchedDirsPath[] = $wd->getDirectory();
}
$this->view->watched_dirs = $watchedDirsPath;
@@ -491,9 +466,6 @@ class ApiController extends Zend_Controller_Action
public function dispatchMetaDataAction($md, $mode)
{
- // NOTE : if you are using this method. Make sure you've checked authorization
- // in its caller because this method does not do checkAuth
- // update import timestamp
Application_Model_Preference::SetImportTimestamp();
if ($mode == "create") {
$filepath = $md['MDATA_KEY_FILEPATH'];
@@ -568,9 +540,8 @@ class ApiController extends Zend_Controller_Action
return $file->getId();
}
- public function reloadMetadataGroupAction() {
- # reload-metadata-group
- $this->checkAuth();
+ public function reloadMetadataGroupAction()
+ {
$request = $this->getRequest();
//extract all file metadata params from the request.
//The value is a json encoded hash that has all the information related to this action
@@ -589,9 +560,8 @@ class ApiController extends Zend_Controller_Action
die(json_encode( array('successes' => 19, 'fails' => 123) ));
}
- public function reloadMetadataAction() {
- $this->checkAuth();
-
+ public function reloadMetadataAction()
+ {
$request = $this->getRequest();
$mode = $request->getParam('mode');
@@ -616,21 +586,20 @@ class ApiController extends Zend_Controller_Action
$file = Application_Model_StoredFile::RecallByFilepath($filepath);
if (is_null($file)) {
$file = Application_Model_StoredFile::Insert($md);
- }
- else {
+ } else {
// path already exist
- if($file->getFileExistsFlag()){
+ if ($file->getFileExistsFlag()) {
// file marked as exists
$this->view->error = "File already exists in Airtime.";
+
return;
- }else{
+ } else {
// file marked as not exists
$file->setFileExistsFlag(true);
$file->setMetadata($md);
}
}
- }
- else if ($mode == "modify") {
+ } else if ($mode == "modify") {
$filepath = $md['MDATA_KEY_FILEPATH'];
//$filepath = str_replace("\\", "", $filepath);
$file = Application_Model_StoredFile::RecallByFilepath($filepath);
@@ -638,65 +607,61 @@ class ApiController extends Zend_Controller_Action
//File is not in database anymore.
if (is_null($file)) {
$this->view->error = "File does not exist in Airtime.";
+
return;
- }
- //Updating a metadata change.
- else {
+ } else {
+ //Updating a metadata change.
$file->setMetadata($md);
}
- }
- else if ($mode == "moved") {
+ } else if ($mode == "moved") {
$md5 = $md['MDATA_KEY_MD5'];
$file = Application_Model_StoredFile::RecallByMd5($md5);
if (is_null($file)) {
$this->view->error = "File doesn't exist in Airtime.";
+
return;
- }
- else {
+ } else {
$filepath = $md['MDATA_KEY_FILEPATH'];
//$filepath = str_replace("\\", "", $filepath);
$file->setFilePath($filepath);
}
- }
- else if ($mode == "delete") {
+ } else if ($mode == "delete") {
$filepath = $md['MDATA_KEY_FILEPATH'];
//$filepath = str_replace("\\", "", $filepath);
$file = Application_Model_StoredFile::RecallByFilepath($filepath);
if (is_null($file)) {
$this->view->error = "File doesn't exist in Airtime.";
+
return;
- }
- else {
+ } else {
$file->deleteByMediaMonitor();
}
- }
- else if ($mode == "delete_dir") {
+ } else if ($mode == "delete_dir") {
$filepath = $md['MDATA_KEY_FILEPATH'];
//$filepath = str_replace("\\", "", $filepath);
$files = Application_Model_StoredFile::RecallByPartialFilepath($filepath);
- foreach($files as $file){
+ foreach ($files as $file) {
$file->deleteByMediaMonitor();
}
+
return;
}
$this->view->id = $file->getId();
}
- public function listAllFilesAction() {
- $this->checkAuth();
-
+ public function listAllFilesAction()
+ {
$request = $this->getRequest();
$dir_id = $request->getParam('dir_id');
$this->view->files = Application_Model_StoredFile::listAllFiles($dir_id);
}
- public function listAllWatchedDirsAction() {
- $this->checkAuth();
-
+ public function listAllWatchedDirsAction()
+ {
$request = $this->getRequest();
$result = array();
@@ -706,52 +671,47 @@ class ApiController extends Zend_Controller_Action
$result[$storDir->getId()] = $storDir->getDirectory();
- foreach ($arrWatchedDirs as $watchedDir){
+ foreach ($arrWatchedDirs as $watchedDir) {
$result[$watchedDir->getId()] = $watchedDir->getDirectory();
}
$this->view->dirs = $result;
}
- public function addWatchedDirAction() {
- $this->checkAuth();
-
+ public function addWatchedDirAction()
+ {
$request = $this->getRequest();
$path = base64_decode($request->getParam('path'));
$this->view->msg = Application_Model_MusicDir::addWatchedDir($path);
}
- public function removeWatchedDirAction() {
- $this->checkAuth();
-
+ public function removeWatchedDirAction()
+ {
$request = $this->getRequest();
$path = base64_decode($request->getParam('path'));
$this->view->msg = Application_Model_MusicDir::removeWatchedDir($path);
}
- public function setStorageDirAction() {
- $this->checkAuth();
-
+ public function setStorageDirAction()
+ {
$request = $this->getRequest();
$path = base64_decode($request->getParam('path'));
$this->view->msg = Application_Model_MusicDir::setStorDir($path);
}
- public function getStreamSettingAction() {
- $this->checkAuth();
-
+ public function getStreamSettingAction()
+ {
$request = $this->getRequest();
$info = Application_Model_StreamSetting::getStreamSetting();
$this->view->msg = $info;
}
- public function statusAction() {
- $this->checkAuth();
-
+ public function statusAction()
+ {
$request = $this->getRequest();
$getDiskInfo = $request->getParam('diskinfo') == "true";
@@ -766,14 +726,15 @@ class ApiController extends Zend_Controller_Action
)
);
- if ($getDiskInfo){
+ if ($getDiskInfo) {
$status["partitions"] = Application_Model_Systemstatus::GetDiskInfo();
}
$this->view->status = $status;
}
- public function registerComponentAction(){
+ public function registerComponentAction()
+ {
$request = $this->getRequest();
$component = $request->getParam('component');
@@ -783,7 +744,8 @@ class ApiController extends Zend_Controller_Action
Application_Model_ServiceRegister::Register($component, $remoteAddr);
}
- public function updateLiquidsoapStatusAction(){
+ public function updateLiquidsoapStatusAction()
+ {
$request = $this->getRequest();
$msg = $request->getParam('msg');
@@ -793,7 +755,8 @@ class ApiController extends Zend_Controller_Action
Application_Model_StreamSetting::setLiquidsoapError($stream_id, $msg, $boot_time);
}
- public function updateSourceStatusAction(){
+ public function updateSourceStatusAction()
+ {
$request = $this->getRequest();
$msg = $request->getParam('msg');
@@ -802,13 +765,13 @@ 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()){
+ 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()){
+ } 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");
@@ -819,14 +782,13 @@ class ApiController extends Zend_Controller_Action
}
// handles addition/deletion of mount point which watched dirs reside
- public function updateFileSystemMountAction(){
- $this->checkAuth();
-
+ public function updateFileSystemMountAction()
+ {
$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'])?array():explode(',', $params['added_dir']);
+ $removed_list = empty($params['removed_dir'])?array():explode(',', $params['removed_dir']);
// get all watched dirs
$watched_dirs = Application_Model_MusicDir::getWatchedDirs(null, null);
@@ -839,10 +801,10 @@ class ApiController extends Zend_Controller_Action
// if mount path itself was watched
if ($dirPath == $ad) {
Application_Model_MusicDir::addWatchedDir($dirPath, false);
- } else if(substr($dirPath, 0, strlen($ad)) === $ad && $dir->getExistsFlag() == false) {
+ } else if (substr($dirPath, 0, strlen($ad)) === $ad && $dir->getExistsFlag() == false) {
// if dir contains any dir in removed_list( if watched dir resides on new mounted path )
Application_Model_MusicDir::addWatchedDir($dirPath, false);
- } else if (substr($ad, 0, strlen($dirPath)) === $dirPath) {
+ } elseif (substr($ad, 0, strlen($dirPath)) === $dirPath) {
// is new mount point within the watched dir?
// pyinotify doesn't notify anyhing in this case, so we add this mount point as
// watched dir
@@ -851,32 +813,31 @@ class ApiController extends Zend_Controller_Action
}
}
}
-
- foreach( $removed_list as $rd) {
+
+ foreach ($removed_list as $rd) {
$rd .= '/';
foreach ($watched_dirs as $dir) {
$dirPath = $dir->getDirectory();
// if dir contains any dir in removed_list( if watched dir resides on new mounted path )
if (substr($dirPath, 0, strlen($rd)) === $rd && $dir->getExistsFlag() == true) {
Application_Model_MusicDir::removeWatchedDir($dirPath, false);
- } else if (substr($rd, 0, strlen($dirPath)) === $dirPath) {
+ } elseif (substr($rd, 0, strlen($dirPath)) === $dirPath) {
// is new mount point within the watched dir?
// pyinotify doesn't notify anyhing in this case, so we walk through all files within
// this watched dir in DB and mark them deleted.
// In case of h) of use cases, due to pyinotify behaviour of noticing mounted dir, we need to
// compare agaisnt all files in cc_files table
-
+
$watchDir = Application_Model_MusicDir::getDirByPath($rd);
// get all the files that is under $dirPath
$files = Application_Model_StoredFile::listAllFiles($dir->getId(), true);
foreach ($files as $f) {
// if the file is from this mount
- if (substr( $f->getFilePath(),0,strlen($rd) ) === $rd) {
+ if (substr($f->getFilePath(), 0, strlen($rd)) === $rd) {
$f->delete();
}
}
-
- if($watchDir) {
+ if ($watchDir) {
Application_Model_MusicDir::removeWatchedDir($rd, false);
}
}
@@ -887,8 +848,6 @@ class ApiController extends Zend_Controller_Action
// handles case where watched dir is missing
public function handleWatchedDirMissingAction()
{
- $this->checkAuth();
-
$request = $this->getRequest();
$dir = base64_decode($request->getParam('dir'));
@@ -900,8 +859,6 @@ class ApiController extends Zend_Controller_Action
* out a message to pypo that a potential change has been made. */
public function rabbitmqDoPushAction()
{
- $this->checkAuth();
-
$request = $this->getRequest();
Logging::log("Notifying RabbitMQ to send message to pypo");
@@ -924,8 +881,6 @@ class ApiController extends Zend_Controller_Action
/* This is used but Liquidsoap to check authentication of live streams*/
public function checkLiveStreamAuthAction()
{
- $this->checkAuth();
-
$request = $this->getRequest();
$username = $request->getParam('username');
@@ -934,7 +889,7 @@ class ApiController extends Zend_Controller_Action
if ($djtype == 'master') {
//check against master
- if ($username == Application_Model_Preference::GetLiveSteamMasterUsername()
+ if ($username == Application_Model_Preference::GetLiveSteamMasterUsername()
&& $password == Application_Model_Preference::GetLiveSteamMasterPassword()) {
$this->view->msg = true;
} else {
@@ -960,8 +915,9 @@ class ApiController extends Zend_Controller_Action
if ($CcShow->getDbLiveStreamUsingAirtimeAuth()) {
foreach ($hosts_ids as $host) {
$h = new Application_Model_User($host['subjs_id']);
- if($username == $h->getLogin() && md5($password) == $h->getPassword()) {
+ if ($username == $h->getLogin() && md5($password) == $h->getPassword()) {
$this->view->msg = true;
+
return;
}
}
@@ -982,21 +938,42 @@ class ApiController extends Zend_Controller_Action
}
}
}
-
+
/* This action is for use by our dev scripts, that make
* a change to the database and we want rabbitmq to send
* out a message to pypo that a potential change has been made. */
public function getFilesWithoutReplayGainAction()
{
- $this->checkAuth();
-
// disable the view and the layout
$this->view->layout()->disableLayout();
+ $this->_helper->viewRenderer->setNoRender(true);
+
$dir_id = $this->_getParam('dir_id');
-
+
//connect to db and get get sql
- $this->view->rows = Application_Model_StoredFile::listAllFiles2($dir_id, 0);
+ $rows = Application_Model_StoredFile::listAllFiles2($dir_id, 100);
+ echo json_encode($rows);
+ }
+
+ public function updateReplayGainValueAction()
+ {
+ $this->checkAuth();
+
+ // disable layout
+ $this->view->layout()->disableLayout();
+ $this->_helper->viewRenderer->setNoRender(true);
+
+ $request = $this->getRequest();
+ $data = json_decode($request->getParam('data'));
+
+ foreach ($data as $pair) {
+ list($id, $gain) = $pair;
+
+ $file = Application_Model_StoredFile::Recall($p_id = $id)->getPropelOrm();
+ Logging::log("Setting $gain for file id $id");
+ $file->setDbReplayGain($gain);
+ $file->save();
+ }
}
}
-
diff --git a/airtime_mvc/application/controllers/AudiopreviewController.php b/airtime_mvc/application/controllers/AudiopreviewController.php
index 40b233f47..037eeca30 100644
--- a/airtime_mvc/application/controllers/AudiopreviewController.php
+++ b/airtime_mvc/application/controllers/AudiopreviewController.php
@@ -36,7 +36,7 @@ class AudiopreviewController extends Zend_Controller_Action
$this->_helper->layout->setLayout('audioPlayer');
$logo = Application_Model_Preference::GetStationLogo();
- if($logo){
+ if ($logo) {
$this->view->logo = "data:image/png;base64,$logo";
} else {
$this->view->logo = "$baseUrl/css/images/airtime_logo_jp.png";
@@ -70,7 +70,7 @@ class AudiopreviewController extends Zend_Controller_Action
$this->_helper->layout->setLayout('audioPlayer');
$logo = Application_Model_Preference::GetStationLogo();
- if($logo){
+ if ($logo) {
$this->view->logo = "data:image/png;base64,$logo";
} else {
$this->view->logo = "$baseUrl/css/images/airtime_logo_jp.png";
@@ -84,21 +84,22 @@ class AudiopreviewController extends Zend_Controller_Action
/**
*Function will load and return the contents of the requested playlist.
*/
- public function getPlaylistAction(){
+ public function getPlaylistAction()
+ {
// disable the view and the layout
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$playlistID = $this->_getParam('playlistID');
- if (!isset($playlistID)){
+ if (!isset($playlistID)) {
return;
}
$pl = new Application_Model_Playlist($playlistID);
$result = Array();
- foreach ( $pl->getContents(true) as $track ){
+ foreach ( $pl->getContents(true) as $track ) {
$elementMap = array( 'element_title' => isset($track['CcFiles']['track_title'])?$track['CcFiles']['track_title']:"",
'element_artist' => isset($track['CcFiles']['artist_name'])?$track['CcFiles']['artist_name']:"",
@@ -106,9 +107,9 @@ class AudiopreviewController extends Zend_Controller_Action
'element_position' => isset($track['position'])?$track['position']:"",
);
$fileExtension = pathinfo($track['CcFiles']['filepath'], PATHINFO_EXTENSION);
- if (strtolower($fileExtension) === 'mp3'){
+ if (strtolower($fileExtension) === 'mp3') {
$elementMap['element_mp3'] = $track['CcFiles']['gunid'].'.'.$fileExtension;
- } else if(strtolower($fileExtension) === 'ogg') {
+ } elseif (strtolower($fileExtension) === 'ogg') {
$elementMap['element_oga'] = $track['CcFiles']['gunid'].'.'.$fileExtension;
} else {
//the media was neither mp3 or ogg
@@ -141,7 +142,7 @@ class AudiopreviewController extends Zend_Controller_Action
$this->_helper->layout->setLayout('audioPlayer');
$logo = Application_Model_Preference::GetStationLogo();
- if ($logo){
+ if ($logo) {
$this->view->logo = "data:image/png;base64,$logo";
} else {
$this->view->logo = "$baseUrl/css/images/airtime_logo_jp.png";
@@ -164,14 +165,14 @@ class AudiopreviewController extends Zend_Controller_Action
$showID = $this->_getParam('showID');
- if (!isset($showID)){
+ if (!isset($showID)) {
return;
}
$showInstance = new Application_Model_ShowInstance($showID);
$result = array();
$position = 0;
- foreach ($showInstance->getShowListContent() as $track){
+ foreach ($showInstance->getShowListContent() as $track) {
$elementMap = array(
'element_title' => isset($track['track_title']) ? $track['track_title'] : "",
@@ -181,9 +182,9 @@ class AudiopreviewController extends Zend_Controller_Action
);
$fileExtension = pathinfo($track['filepath'], PATHINFO_EXTENSION);
- if (strtolower($fileExtension) === 'mp3'){
+ if (strtolower($fileExtension) === 'mp3') {
$elementMap['element_mp3'] = $track['gunid'].'.'.$fileExtension;
- } else if(strtolower($fileExtension) === 'ogg') {
+ } elseif (strtolower($fileExtension) === 'ogg') {
$elementMap['element_oga'] = $track['gunid'].'.'.$fileExtension;
} else {
//the media was neither mp3 or ogg
diff --git a/airtime_mvc/application/controllers/DashboardController.php b/airtime_mvc/application/controllers/DashboardController.php
index fa3299b79..719899fb1 100644
--- a/airtime_mvc/application/controllers/DashboardController.php
+++ b/airtime_mvc/application/controllers/DashboardController.php
@@ -16,7 +16,8 @@ class DashboardController extends Zend_Controller_Action
// action body
}
- public function disconnectSourceAction(){
+ public function disconnectSourceAction()
+ {
$request = $this->getRequest();
$sourcename = $request->getParam('sourcename');
@@ -29,19 +30,20 @@ class DashboardController extends Zend_Controller_Action
$source_connected = Application_Model_Preference::GetSourceStatus($sourcename);
- if($user->canSchedule($show_id) && $source_connected){
+ if ($user->canSchedule($show_id) && $source_connected) {
$data = array("sourcename"=>$sourcename);
Application_Model_RabbitMq::SendMessageToPypo("disconnect_source", $data);
- }else{
- if($source_connected){
+ } else {
+ if ($source_connected) {
$this->view->error = "You don't have permission to disconnect source.";
- }else{
+ } else {
$this->view->error = "There is no source connected to this input.";
}
}
}
- public function switchSourceAction(){
+ public function switchSourceAction()
+ {
$request = $this->getRequest();
$sourcename = $this->_getParam('sourcename');
$current_status = $this->_getParam('status');
@@ -53,24 +55,24 @@ class DashboardController extends Zend_Controller_Action
$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";
- if(strtolower($current_status) == "on"){
+ 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"){
+ 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')));
- }else{
+ } else {
Application_Model_Preference::SetSourceSwitchStatus($sourcename, "on");
$this->view->status = "ON";
@@ -78,22 +80,21 @@ class DashboardController extends Zend_Controller_Action
Application_Model_LiveLog::SetNewLogTime($sourcename == 'scheduled_play'?'S':'L',
new DateTime("now", new DateTimeZone('UTC')));
}
- }
- else{
- if($source_connected){
+ } else {
+ if ($source_connected) {
$this->view->error = "You don't have permission to switch source.";
- }else{
- if($sourcename == 'scheduled_play'){
+ } else {
+ if ($sourcename == 'scheduled_play') {
$this->view->error = "You don't have permission to disconnect source.";
- }else{
+ } else {
$this->view->error = "There is no source connected to this input.";
}
}
}
}
- public function switchOffSource(){
-
+ public function switchOffSource()
+ {
}
public function streamPlayerAction()
@@ -107,7 +108,7 @@ class DashboardController extends Zend_Controller_Action
$this->_helper->layout->setLayout('bare');
$logo = Application_Model_Preference::GetStationLogo();
- if($logo){
+ if ($logo) {
$this->view->logo = "data:image/png;base64,$logo";
} else {
$this->view->logo = "$baseUrl/css/images/airtime_logo_jp.png";
@@ -125,4 +126,3 @@ class DashboardController extends Zend_Controller_Action
}
}
-
diff --git a/airtime_mvc/application/controllers/ErrorController.php b/airtime_mvc/application/controllers/ErrorController.php
index 5dfed60a5..2c1aa0b87 100644
--- a/airtime_mvc/application/controllers/ErrorController.php
+++ b/airtime_mvc/application/controllers/ErrorController.php
@@ -43,6 +43,7 @@ class ErrorController extends Zend_Controller_Action
return false;
}
$log = $bootstrap->getResource('Log');
+
return $log;
}
@@ -51,8 +52,4 @@ class ErrorController extends Zend_Controller_Action
// action body
}
-
}
-
-
-
diff --git a/airtime_mvc/application/controllers/IndexController.php b/airtime_mvc/application/controllers/IndexController.php
index 4899ac104..8dcdb3a64 100644
--- a/airtime_mvc/application/controllers/IndexController.php
+++ b/airtime_mvc/application/controllers/IndexController.php
@@ -19,10 +19,3 @@ class IndexController extends Zend_Controller_Action
}
}
-
-
-
-
-
-
-
diff --git a/airtime_mvc/application/controllers/LibraryController.php b/airtime_mvc/application/controllers/LibraryController.php
index 8605c6c96..918efdca5 100644
--- a/airtime_mvc/application/controllers/LibraryController.php
+++ b/airtime_mvc/application/controllers/LibraryController.php
@@ -40,7 +40,7 @@ class LibraryController extends Zend_Controller_Action
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id);
- //Open a jPlayer window and play the audio clip.
+ //Open a jPlayer window and play the audio clip.
$menu["play"] = array("name"=> "Preview", "icon" => "play");
$isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
@@ -52,7 +52,7 @@ class LibraryController extends Zend_Controller_Action
if (isset($this->pl_sess->id) && $screen == "playlist") {
// if the user is not admin or pm, check the creator and see if this person owns the playlist
$playlist = new Application_Model_Playlist($this->pl_sess->id);
- if($isAdminOrPM || $playlist->getCreatorId() == $user->getId()){
+ if ($isAdminOrPM || $playlist->getCreatorId() == $user->getId()) {
$menu["pl_add"] = array("name"=> "Add to Playlist", "icon" => "add-playlist", "icon" => "copy");
}
}
@@ -63,44 +63,41 @@ class LibraryController extends Zend_Controller_Action
$url = $file->getRelativeFileUrl($baseUrl).'/download/true';
$menu["download"] = array("name" => "Download", "icon" => "download", "url" => $url);
- }
- else if ($type === "playlist") {
+ } elseif ($type === "playlist") {
$playlist = new Application_Model_Playlist($id);
if ($this->pl_sess->id !== $id && $screen == "playlist") {
- if($isAdminOrPM || $playlist->getCreatorId() == $user->getId()){
+ if ($isAdminOrPM || $playlist->getCreatorId() == $user->getId()) {
$menu["edit"] = array("name"=> "Edit", "icon" => "edit");
}
}
- if($isAdminOrPM || $playlist->getCreatorId() == $user->getId()){
+ if ($isAdminOrPM || $playlist->getCreatorId() == $user->getId()) {
$menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => "/library/delete");
}
}
-
//SOUNDCLOUD MENU OPTIONS
- if ($type === "audioclip" && Application_Model_Preference::GetUploadToSoundcloudOption()) {
-
- //create a menu separator
- $menu["sep1"] = "-----------";
-
- //create a sub menu for Soundcloud actions.
- $menu["soundcloud"] = array("name" => "Soundcloud", "icon" => "soundcloud", "items" => array());
-
+ if ($type === "audioclip" && Application_Model_Preference::GetUploadToSoundcloudOption()) {
+
+ //create a menu separator
+ $menu["sep1"] = "-----------";
+
+ //create a sub menu for Soundcloud actions.
+ $menu["soundcloud"] = array("name" => "Soundcloud", "icon" => "soundcloud", "items" => array());
+
$scid = $file->getSoundCloudId();
- if ($scid > 0){
- $url = $file->getSoundCloudLinkToFile();
- $menu["soundcloud"]["items"]["view"] = array("name" => "View on Soundcloud", "icon" => "soundcloud", "url" => $url);
- }
-
- if (!is_null($scid)){
- $text = "Re-upload to SoundCloud";
- }
- else {
- $text = "Upload to SoundCloud";
- }
-
- $menu["soundcloud"]["items"]["upload"] = array("name" => $text, "icon" => "soundcloud", "url" => "/library/upload-file-soundcloud/id/{$id}");
+ if ($scid > 0) {
+ $url = $file->getSoundCloudLinkToFile();
+ $menu["soundcloud"]["items"]["view"] = array("name" => "View on Soundcloud", "icon" => "soundcloud", "url" => $url);
+ }
+
+ if (!is_null($scid)) {
+ $text = "Re-upload to SoundCloud";
+ } else {
+ $text = "Upload to SoundCloud";
+ }
+
+ $menu["soundcloud"]["items"]["upload"] = array("name" => $text, "icon" => "soundcloud", "url" => "/library/upload-file-soundcloud/id/{$id}");
}
$this->view->items = $menu;
@@ -123,8 +120,7 @@ class LibraryController extends Zend_Controller_Action
if ($media["type"] === "audioclip") {
$files[] = intval($media["id"]);
- }
- else if ($media["type"] === "playlist") {
+ } elseif ($media["type"] === "playlist") {
$playlists[] = intval($media["id"]);
}
}
@@ -132,10 +128,10 @@ class LibraryController extends Zend_Controller_Action
$hasPermission = true;
if (count($playlists)) {
// make sure use has permission to delete all playslists in the list
- if(!$isAdminOrPM){
- foreach($playlists as $pid){
+ if (!$isAdminOrPM) {
+ foreach ($playlists as $pid) {
$pl = new Application_Model_Playlist($pid);
- if($pl->getCreatorId() != $user->getId()){
+ if ($pl->getCreatorId() != $user->getId()) {
$hasPermission = false;
}
}
@@ -145,10 +141,11 @@ class LibraryController extends Zend_Controller_Action
if (!$isAdminOrPM && count($files)) {
$hasPermission = false;
}
- if(!$hasPermission){
+ if (!$hasPermission) {
$this->view->message = "You don't have a permission to delete all playlists/files that are selected.";
+
return;
- }else{
+ } else {
Application_Model_Playlist::DeletePlaylists($playlists);
}
@@ -180,25 +177,23 @@ class LibraryController extends Zend_Controller_Action
//TODO move this to the datatables row callback.
foreach ($r["aaData"] as &$data) {
- if ($data['ftype'] == 'audioclip'){
+ if ($data['ftype'] == 'audioclip') {
$file = Application_Model_StoredFile::Recall($data['id']);
$scid = $file->getSoundCloudId();
- if ($scid == "-2"){
+ if ($scid == "-2") {
$data['track_title'] .= '';
- }
- else if ($scid == "-3"){
+ } elseif ($scid == "-3") {
$data['track_title'] .= '';
- }
- else if (!is_null($scid)){
+ } elseif (!is_null($scid)) {
$data['track_title'] .= '';
}
}
}
-
- $this->view->sEcho = $r["sEcho"];
- $this->view->iTotalDisplayRecords = $r["iTotalDisplayRecords"];
- $this->view->iTotalRecords = $r["iTotalRecords"];
+
+ $this->view->sEcho = $r["sEcho"];
+ $this->view->iTotalDisplayRecords = $r["iTotalDisplayRecords"];
+ $this->view->iTotalRecords = $r["iTotalRecords"];
$this->view->files = $r["aaData"];
}
@@ -206,7 +201,7 @@ class LibraryController extends Zend_Controller_Action
{
$user = Application_Model_User::getCurrentUser();
$isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
- if(!$isAdminOrPM){
+ if (!$isAdminOrPM) {
return;
}
@@ -266,8 +261,7 @@ class LibraryController extends Zend_Controller_Action
$this->view->md = $md;
- }
- else if ($type == "playlist") {
+ } elseif ($type == "playlist") {
$file = new Application_Model_Playlist($id);
$this->view->type = $type;
@@ -279,20 +273,21 @@ class LibraryController extends Zend_Controller_Action
$this->view->md = $md;
$this->view->contents = $file->getContents();
}
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
Logging::log($e->getMessage());
}
}
- public function uploadFileSoundcloudAction(){
+ public function uploadFileSoundcloudAction()
+ {
$id = $this->_getParam('id');
$res = exec("/usr/lib/airtime/utils/soundcloud-uploader $id > /dev/null &");
// we should die with ui info
die();
}
- public function getUploadToSoundcloudStatusAction(){
+ public function getUploadToSoundcloudStatusAction()
+ {
$id = $this->_getParam('id');
$type = $this->_getParam('type');
@@ -302,8 +297,7 @@ class LibraryController extends Zend_Controller_Action
$file = $show_instance->getRecordedFile();
$this->view->error_code = $file->getSoundCloudErrorCode();
$this->view->error_msg = $file->getSoundCloudErrorMsg();
- }
- else if ($type == "file") {
+ } elseif ($type == "file") {
$file = Application_Model_StoredFile::Recall($id);
$this->view->sc_id = $file->getSoundCloudId();
$this->view->error_code = $file->getSoundCloudErrorCode();
diff --git a/airtime_mvc/application/controllers/LoginController.php b/airtime_mvc/application/controllers/LoginController.php
index 9cedd6eab..ca0076e52 100644
--- a/airtime_mvc/application/controllers/LoginController.php
+++ b/airtime_mvc/application/controllers/LoginController.php
@@ -12,8 +12,7 @@ class LoginController extends Zend_Controller_Action
{
global $CC_CONFIG;
- if (Zend_Auth::getInstance()->hasIdentity())
- {
+ if (Zend_Auth::getInstance()->hasIdentity()) {
$this->_redirect('Showbuilder');
}
@@ -30,21 +29,19 @@ class LoginController extends Zend_Controller_Action
$message = "Please enter your user name and password";
- if($request->isPost())
- {
+ if ($request->isPost()) {
// if the post contains recaptcha field, which means form had recaptcha field.
// Hence add the element for validation.
- if(array_key_exists('recaptcha_response_field', $request->getPost())){
+ if (array_key_exists('recaptcha_response_field', $request->getPost())) {
$form->addRecaptcha();
}
- if($form->isValid($request->getPost()))
- {
+ if ($form->isValid($request->getPost())) {
//get the username and password from the form
$username = $form->getValue('username');
$password = $form->getValue('password');
- if(Application_Model_Subjects::getLoginAttempts($username) >= 3 && $form->getElement('captcha') == NULL){
+ if (Application_Model_Subjects::getLoginAttempts($username) >= 3 && $form->getElement('captcha') == NULL) {
$form->addRecaptcha();
- }else{
+ } else {
$authAdapter = Application_Model_Auth::getAuthAdapter();
//pass to the adapter the submitted username and password
@@ -53,8 +50,7 @@ class LoginController extends Zend_Controller_Action
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);
- if($result->isValid())
- {
+ if ($result->isValid()) {
//all info about this user from the login table omit only the password
$userInfo = $authAdapter->getResultRowObject(null, 'password');
@@ -69,9 +65,7 @@ class LoginController extends Zend_Controller_Action
$tempSess->referrer = 'login';
$this->_redirect('Showbuilder');
- }
- else
- {
+ } else {
$message = "Wrong username or password provided. Please try again.";
Application_Model_Subjects::increaseLoginAttempts($username);
Application_Model_LoginAttempts::increaseAttempts($_SERVER['REMOTE_ADDR']);
@@ -87,7 +81,7 @@ class LoginController extends Zend_Controller_Action
$this->view->form = $form;
$this->view->airtimeVersion = Application_Model_Preference::GetAirtimeVersion();
$this->view->airtimeCopyright = AIRTIME_COPYRIGHT_DATE;
- if(isset($CC_CONFIG['demo'])){
+ if (isset($CC_CONFIG['demo'])) {
$this->view->demo = $CC_CONFIG['demo'];
}
}
@@ -98,7 +92,7 @@ class LoginController extends Zend_Controller_Action
$this->_redirect('showbuilder/index');
}
- public function passwordRestoreAction()
+ public function passwordRestoreAction()
{
global $CC_CONFIG;
@@ -108,92 +102,87 @@ class LoginController extends Zend_Controller_Action
if (!Application_Model_Preference::GetEnableSystemEmail()) {
$this->_redirect('login');
- }
- else {
- //uses separate layout without a navigation.
- $this->_helper->layout->setLayout('login');
-
- $form = new Application_Form_PasswordRestore();
-
- $request = $this->getRequest();
- if ($request->isPost() && $form->isValid($request->getPost())) {
- $user = CcSubjsQuery::create()
- ->filterByDbEmail($form->email->getValue())
- ->findOne();
-
- if (!empty($user)) {
- $auth = new Application_Model_Auth();
-
+ } else {
+ //uses separate layout without a navigation.
+ $this->_helper->layout->setLayout('login');
+
+ $form = new Application_Form_PasswordRestore();
+
+ $request = $this->getRequest();
+ if ($request->isPost() && $form->isValid($request->getPost())) {
+ $user = CcSubjsQuery::create()
+ ->filterByDbEmail($form->email->getValue())
+ ->findOne();
+
+ if (!empty($user)) {
+ $auth = new Application_Model_Auth();
+
$success = $auth->sendPasswordRestoreLink($user, $this->view);
- if ($success) {
+ 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."));
- }
- }
- else {
- $form->email->addError($this->view->translate("Given email not found."));
- }
+ }
+ } else {
+ $form->email->addError($this->view->translate("Given email not found."));
+ }
}
-
+
$this->view->form = $form;
- }
- }
-
- public function passwordRestoreAfterAction()
- {
- //uses separate layout without a navigation.
- $this->_helper->layout->setLayout('login');
- }
-
- public function passwordChangeAction()
- {
- //uses separate layout without a navigation.
- $this->_helper->layout->setLayout('login');
-
- $request = $this->getRequest();
- $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);
-
- //check validity of token
- if (!$auth->checkToken($user_id, $token, 'password.restore')) {
- 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();
-
- $auth->invalidateTokens($user, 'password.restore');
-
- $zend_auth = Zend_Auth::getInstance();
- $zend_auth->clearIdentity();
-
- $authAdapter = Application_Model_Auth::getAuthAdapter();
- $authAdapter->setIdentity($user->getDbLogin())
- ->setCredential($form->password->getValue());
-
- $result = $zend_auth->authenticate($authAdapter);
-
- //all info about this user from the login table omit only the password
- $userInfo = $authAdapter->getResultRowObject(null, 'password');
-
- //the default storage is a session with namespace Zend_Auth
- $authStorage = $zend_auth->getStorage();
- $authStorage->write($userInfo);
-
- $this->_helper->redirector('index', 'showbuilder');
- }
-
- $this->view->form = $form;
+ }
+ }
+
+ public function passwordRestoreAfterAction()
+ {
+ //uses separate layout without a navigation.
+ $this->_helper->layout->setLayout('login');
+ }
+
+ public function passwordChangeAction()
+ {
+ //uses separate layout without a navigation.
+ $this->_helper->layout->setLayout('login');
+
+ $request = $this->getRequest();
+ $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);
+
+ //check validity of token
+ if (!$auth->checkToken($user_id, $token, 'password.restore')) {
+ 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();
+
+ $auth->invalidateTokens($user, 'password.restore');
+
+ $zend_auth = Zend_Auth::getInstance();
+ $zend_auth->clearIdentity();
+
+ $authAdapter = Application_Model_Auth::getAuthAdapter();
+ $authAdapter->setIdentity($user->getDbLogin())
+ ->setCredential($form->password->getValue());
+
+ $result = $zend_auth->authenticate($authAdapter);
+
+ //all info about this user from the login table omit only the password
+ $userInfo = $authAdapter->getResultRowObject(null, 'password');
+
+ //the default storage is a session with namespace Zend_Auth
+ $authStorage = $zend_auth->getStorage();
+ $authStorage->write($userInfo);
+
+ $this->_helper->redirector('index', 'showbuilder');
+ }
+
+ $this->view->form = $form;
}
}
-
-
-
diff --git a/airtime_mvc/application/controllers/PlaylistController.php b/airtime_mvc/application/controllers/PlaylistController.php
index 892da79ce..c29b4e947 100644
--- a/airtime_mvc/application/controllers/PlaylistController.php
+++ b/airtime_mvc/application/controllers/PlaylistController.php
@@ -40,6 +40,7 @@ class PlaylistController extends Zend_Controller_Action
throw new PlaylistOutDatedException("You are viewing an older version of {$pl->getName()}");
}
}
+
return $pl;
}
@@ -47,8 +48,7 @@ class PlaylistController extends Zend_Controller_Action
{
if (is_null($pl_id)) {
unset($this->pl_sess->id);
- }
- else {
+ } else {
$this->pl_sess->id = intval($pl_id);
}
}
@@ -77,8 +77,7 @@ class PlaylistController extends Zend_Controller_Action
$this->view->id = $pl->getId();
$this->view->html = $this->view->render('playlist/playlist.phtml');
unset($this->view->pl);
- }
- else {
+ } else {
$this->view->html = $this->view->render('playlist/playlist.phtml');
}
}
@@ -114,23 +113,23 @@ class PlaylistController extends Zend_Controller_Action
$baseUrl = $request->getBaseUrl();
$this->view->headScript()->appendFile($baseUrl.'/js/blockui/jquery.blockUI.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/datatables/plugin/dataTables.ColVis.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.ColReorder.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.FixedColumns.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/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/datatables/plugin/dataTables.ColVis.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.ColReorder.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.FixedColumns.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/library/library.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($this->view->baseUrl('/js/airtime/library/events/library_playlistbuilder.js'),'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/ColReorder.css?'.$CC_CONFIG['airtime_version']);
+ $this->view->headScript()->appendFile($this->view->baseUrl('/js/airtime/library/events/library_playlistbuilder.js'),'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/ColReorder.css?'.$CC_CONFIG['airtime_version']);
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/library/spl.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headLink()->appendStylesheet($baseUrl.'/css/playlist_builder.css?'.$CC_CONFIG['airtime_version']);
@@ -143,11 +142,9 @@ class PlaylistController extends Zend_Controller_Action
$formatter = new LengthFormatter($pl->getLength());
$this->view->length = $formatter->format();
}
- }
- catch (PlaylistNotFoundException $e) {
+ } catch (PlaylistNotFoundException $e) {
$this->playlistNotFound();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->playlistUnknownError($e);
}
}
@@ -177,11 +174,9 @@ class PlaylistController extends Zend_Controller_Action
try {
$pl = new Application_Model_Playlist($id);
$this->createFullResponse($pl);
- }
- catch (PlaylistNotFoundException $e) {
+ } catch (PlaylistNotFoundException $e) {
$this->playlistNotFound();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->playlistUnknownError($e);
}
}
@@ -198,19 +193,16 @@ class PlaylistController extends Zend_Controller_Action
if (in_array($this->pl_sess->id, $ids)) {
Logging::log("Deleting currently active playlist");
$this->changePlaylist(null);
- }
- else {
+ } else {
Logging::log("Not deleting currently active playlist");
$pl = new Application_Model_Playlist($this->pl_sess->id);
}
Application_Model_Playlist::DeletePlaylists($ids);
$this->createFullResponse($pl);
- }
- catch (PlaylistNotFoundException $e) {
+ } catch (PlaylistNotFoundException $e) {
$this->playlistNotFound();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->playlistUnknownError($e);
}
}
@@ -226,14 +218,11 @@ class PlaylistController extends Zend_Controller_Action
$pl = $this->getPlaylist();
$pl->addAudioClips($ids, $afterItem, $addType);
$this->createUpdateResponse($pl);
- }
- catch (PlaylistOutDatedException $e) {
+ } catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($pl, $e);
- }
- catch (PlaylistNotFoundException $e) {
+ } catch (PlaylistNotFoundException $e) {
$this->playlistNotFound();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->playlistUnknownError($e);
}
}
@@ -249,14 +238,11 @@ class PlaylistController extends Zend_Controller_Action
$pl = $this->getPlaylist();
$pl->moveAudioClips($ids, $afterItem);
$this->createUpdateResponse($pl);
- }
- catch (PlaylistOutDatedException $e) {
+ } catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($pl, $e);
- }
- catch (PlaylistNotFoundException $e) {
+ } catch (PlaylistNotFoundException $e) {
$this->playlistNotFound();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->playlistUnknownError($e);
}
}
@@ -271,14 +257,11 @@ class PlaylistController extends Zend_Controller_Action
$pl = $this->getPlaylist();
$pl->delAudioClips($ids);
$this->createUpdateResponse($pl);
- }
- catch (PlaylistOutDatedException $e) {
+ } catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($pl, $e);
- }
- catch (PlaylistNotFoundException $e) {
+ } catch (PlaylistNotFoundException $e) {
$this->playlistNotFound();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->playlistUnknownError($e);
}
}
@@ -296,18 +279,14 @@ class PlaylistController extends Zend_Controller_Action
if (!isset($response["error"])) {
$this->view->response = $response;
$this->createUpdateResponse($pl);
- }
- else {
+ } else {
$this->view->cue_error = $response["error"];
}
- }
- catch (PlaylistOutDatedException $e) {
+ } catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($pl, $e);
- }
- catch (PlaylistNotFoundException $e) {
+ } catch (PlaylistNotFoundException $e) {
$this->playlistNotFound();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->playlistUnknownError($e);
}
}
@@ -325,18 +304,14 @@ class PlaylistController extends Zend_Controller_Action
if (!isset($response["error"])) {
$this->createUpdateResponse($pl);
$this->view->response = $response;
- }
- else {
+ } else {
$this->view->fade_error = $response["error"];
}
- }
- catch (PlaylistOutDatedException $e) {
+ } catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($pl, $e);
- }
- catch (PlaylistNotFoundException $e) {
+ } catch (PlaylistNotFoundException $e) {
$this->playlistNotFound();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->playlistUnknownError($e);
}
}
@@ -350,14 +325,11 @@ class PlaylistController extends Zend_Controller_Action
$fades = $pl->getFadeInfo($pl->getSize()-1);
$this->view->fadeOut = $fades[1];
- }
- catch (PlaylistOutDatedException $e) {
+ } catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($pl, $e);
- }
- catch (PlaylistNotFoundException $e) {
+ } catch (PlaylistNotFoundException $e) {
$this->playlistNotFound();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->playlistUnknownError($e);
}
}
@@ -376,14 +348,11 @@ class PlaylistController extends Zend_Controller_Action
$pl = $this->getPlaylist();
$pl->setPlaylistfades($fadeIn, $fadeOut);
$this->view->modified = $pl->getLastModified("U");
- }
- catch (PlaylistOutDatedException $e) {
+ } catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($pl, $e);
- }
- catch (PlaylistNotFoundException $e) {
+ } catch (PlaylistNotFoundException $e) {
$this->playlistNotFound();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->playlistUnknownError($e);
}
}
@@ -397,14 +366,11 @@ class PlaylistController extends Zend_Controller_Action
$pl->setName($name);
$this->view->playlistName = $name;
$this->view->modified = $pl->getLastModified("U");
- }
- catch (PlaylistOutDatedException $e) {
+ } catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($pl, $e);
- }
- catch (PlaylistNotFoundException $e) {
+ } catch (PlaylistNotFoundException $e) {
$this->playlistNotFound();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->playlistUnknownError($e);
}
}
@@ -418,16 +384,12 @@ class PlaylistController extends Zend_Controller_Action
$pl->setDescription($description);
$this->view->description = $pl->getDescription();
$this->view->modified = $pl->getLastModified("U");
- }
- catch (PlaylistOutDatedException $e) {
+ } catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($pl, $e);
- }
- catch (PlaylistNotFoundException $e) {
+ } catch (PlaylistNotFoundException $e) {
$this->playlistNotFound();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->playlistUnknownError($e);
}
}
}
-
diff --git a/airtime_mvc/application/controllers/PlayouthistoryController.php b/airtime_mvc/application/controllers/PlayouthistoryController.php
index ec190acd0..ecd0fd4c8 100644
--- a/airtime_mvc/application/controllers/PlayouthistoryController.php
+++ b/airtime_mvc/application/controllers/PlayouthistoryController.php
@@ -1,19 +1,19 @@
_helper->getHelper('AjaxContext');
+ public function init()
+ {
+ $ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext
- ->addActionContext('playout-history-feed', 'json')
- ->initContext();
+ ->addActionContext('playout-history-feed', 'json')
+ ->initContext();
}
-
- public function indexAction()
+
+ public function indexAction()
{
global $CC_CONFIG;
-
+
$request = $this->getRequest();
$baseUrl = $request->getBaseUrl();
@@ -35,50 +35,50 @@ class PlayoutHistoryController extends Zend_Controller_Action
'his_time_end' => $end->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->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/datatables/plugin/TableTools/js/ZeroClipboard.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/TableTools/js/TableTools.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
-
- $offset = date("Z") * -1;
- $this->view->headScript()->appendScript("var serverTimezoneOffset = {$offset}; //in seconds");
- $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/datatables/plugin/TableTools/js/ZeroClipboard.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/TableTools/js/TableTools.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+
+ $offset = date("Z") * -1;
+ $this->view->headScript()->appendScript("var serverTimezoneOffset = {$offset}; //in seconds");
+ $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/playouthistory/historytable.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.'/js/datatables/plugin/TableTools/css/TableTools.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']);
}
-
- public function playoutHistoryFeedAction()
+
+ public function playoutHistoryFeedAction()
{
- $request = $this->getRequest();
+ $request = $this->getRequest();
$current_time = time();
-
- $params = $request->getParams();
-
- $starts_epoch = $request->getParam("start", $current_time - (60*60*24));
+
+ $params = $request->getParams();
+
+ $starts_epoch = $request->getParam("start", $current_time - (60*60*24));
$ends_epoch = $request->getParam("end", $current_time);
-
- $startsDT = DateTime::createFromFormat("U", $starts_epoch, new DateTimeZone("UTC"));
- $endsDT = DateTime::createFromFormat("U", $ends_epoch, new DateTimeZone("UTC"));
-
- Logging::log("history starts {$startsDT->format("Y-m-d H:i:s")}");
+
+ $startsDT = DateTime::createFromFormat("U", $starts_epoch, new DateTimeZone("UTC"));
+ $endsDT = DateTime::createFromFormat("U", $ends_epoch, new DateTimeZone("UTC"));
+
+ Logging::log("history starts {$startsDT->format("Y-m-d H:i:s")}");
Logging::log("history ends {$endsDT->format("Y-m-d H:i:s")}");
-
+
$history = new Application_Model_PlayoutHistory($startsDT, $endsDT, $params);
-
+
$r = $history->getItems();
-
+
$this->view->sEcho = $r["sEcho"];
$this->view->iTotalDisplayRecords = $r["iTotalDisplayRecords"];
$this->view->iTotalRecords = $r["iTotalRecords"];
- $this->view->history = $r["history"];
+ $this->view->history = $r["history"];
}
-}
\ No newline at end of file
+}
diff --git a/airtime_mvc/application/controllers/PluploadController.php b/airtime_mvc/application/controllers/PluploadController.php
index 8d8bc117c..32a9b4850 100644
--- a/airtime_mvc/application/controllers/PluploadController.php
+++ b/airtime_mvc/application/controllers/PluploadController.php
@@ -34,7 +34,8 @@ class PluploadController extends Zend_Controller_Action
die('{"jsonrpc" : "2.0", "tempfilepath" : "'.$tempFileName.'" }');
}
- public function copyfileAction(){
+ public function copyfileAction()
+ {
$upload_dir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
$filename = $this->_getParam('name');
$tempname = $this->_getParam('tempname');
@@ -45,6 +46,3 @@ class PluploadController extends Zend_Controller_Action
die('{"jsonrpc" : "2.0"}');
}
}
-
-
-
diff --git a/airtime_mvc/application/controllers/PreferenceController.php b/airtime_mvc/application/controllers/PreferenceController.php
index 8332dc36c..29946086d 100644
--- a/airtime_mvc/application/controllers/PreferenceController.php
+++ b/airtime_mvc/application/controllers/PreferenceController.php
@@ -84,18 +84,18 @@ class PreferenceController extends Zend_Controller_Action
if ($request->isPost()) {
$values = $request->getPost();
if ($form->isValid($values)) {
- if (!$isSass && $values["Publicise"] != 1){
+ if (!$isSass && $values["Publicise"] != 1) {
Application_Model_Preference::SetSupportFeedback($values["SupportFeedback"]);
Application_Model_Preference::SetPublicise($values["Publicise"]);
- if(isset($values["Privacy"])){
+ if (isset($values["Privacy"])) {
Application_Model_Preference::SetPrivacyPolicyCheck($values["Privacy"]);
}
- }else{
+ } else {
Application_Model_Preference::SetHeadTitle($values["stationName"], $this->view);
Application_Model_Preference::SetPhone($values["Phone"]);
Application_Model_Preference::SetEmail($values["Email"]);
Application_Model_Preference::SetStationWebSite($values["StationWebSite"]);
- if(!$isSass){
+ if (!$isSass) {
Application_Model_Preference::SetSupportFeedback($values["SupportFeedback"]);
Application_Model_Preference::SetPublicise($values["Publicise"]);
}
@@ -107,7 +107,7 @@ class PreferenceController extends Zend_Controller_Action
Application_Model_Preference::SetStationCity($values["City"]);
Application_Model_Preference::SetStationDescription($values["Description"]);
Application_Model_Preference::SetStationLogo($imagePath);
- if(!$isSass && isset($values["Privacy"])){
+ if (!$isSass && isset($values["Privacy"])) {
Application_Model_Preference::SetPrivacyPolicyCheck($values["Privacy"]);
}
}
@@ -115,11 +115,11 @@ class PreferenceController extends Zend_Controller_Action
}
}
$logo = Application_Model_Preference::GetStationLogo();
- if($logo){
+ if ($logo) {
$this->view->logoImg = $logo;
}
$privacyChecked = false;
- if(Application_Model_Preference::GetPrivacyPolicyCheck() == 1){
+ if (Application_Model_Preference::GetPrivacyPolicyCheck() == 1) {
$privacyChecked = true;
}
$this->view->privacyChecked = $privacyChecked;
@@ -132,7 +132,7 @@ class PreferenceController extends Zend_Controller_Action
{
global $CC_CONFIG;
- if(Application_Model_Preference::GetPlanLevel() == 'disabled'){
+ if (Application_Model_Preference::GetPlanLevel() == 'disabled') {
$request = $this->getRequest();
$baseUrl = $request->getBaseUrl();
@@ -159,17 +159,17 @@ class PreferenceController extends Zend_Controller_Action
// get current settings
$temp = Application_Model_StreamSetting::getStreamSetting();
$setting = array();
- foreach ($temp as $t){
+ foreach ($temp as $t) {
$setting[$t['keyname']] = $t['value'];
}
// get predefined type and bitrate from pref table
$temp_types = Application_Model_Preference::GetStreamType();
$stream_types = array();
- foreach ($temp_types as $type){
- if(trim($type) == "ogg"){
+ foreach ($temp_types as $type) {
+ if (trim($type) == "ogg") {
$temp = "OGG/VORBIS";
- }else{
+ } else {
$temp = strtoupper(trim($type));
}
$stream_types[trim($type)] = $temp;
@@ -178,8 +178,8 @@ class PreferenceController extends Zend_Controller_Action
$temp_bitrate = Application_Model_Preference::GetStreamBitrate();
$max_bitrate = intval(Application_Model_Preference::GetMaxBitrate());
$stream_bitrates = array();
- foreach ($temp_bitrate as $type){
- if(intval($type) <= $max_bitrate){
+ foreach ($temp_bitrate as $type) {
+ if (intval($type) <= $max_bitrate) {
$stream_bitrates[trim($type)] = strtoupper(trim($type))." Kbit/s";
}
}
@@ -193,7 +193,7 @@ class PreferenceController extends Zend_Controller_Action
$live_stream_subform = new Application_Form_LiveStreamingPreferences();
$form->addSubForm($live_stream_subform, "live_stream_subform");
- 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);
@@ -208,7 +208,7 @@ class PreferenceController extends Zend_Controller_Action
$error = false;
$values = $post_data;
- if($form->isValid($post_data)){
+ if ($form->isValid($post_data)) {
if (!$isSaas) {
$values['output_sound_device'] = $form->getValue('output_sound_device');
$values['output_sound_device_type'] = $form->getValue('output_sound_device_type');
@@ -232,8 +232,7 @@ class PreferenceController extends Zend_Controller_Action
$master_connection_url = "http://".$_SERVER['SERVER_NAME'].":".$values["master_harbor_input_port"]."/".$values["master_harbor_input_mount_point"];
if (empty($values["master_harbor_input_port"]) || empty($values["master_harbor_input_mount_point"])) {
Application_Model_Preference::SetMasterDJSourceConnectionURL('N/A');
- }
- else {
+ } else {
Application_Model_Preference::SetMasterDJSourceConnectionURL($master_connection_url);
}
} else {
@@ -244,12 +243,10 @@ class PreferenceController extends Zend_Controller_Action
$live_connection_url = "http://".$_SERVER['SERVER_NAME'].":".$values["dj_harbor_input_port"]."/".$values["dj_harbor_input_mount_point"];
if (empty($values["dj_harbor_input_port"]) || empty($values["dj_harbor_input_mount_point"])) {
Application_Model_Preference::SetLiveDJSourceConnectionURL('N/A');
- }
- else {
+ } else {
Application_Model_Preference::SetLiveDJSourceConnectionURL($live_connection_url);
}
- }
- else {
+ } else {
Application_Model_Preference::SetLiveDJSourceConnectionURL($values["live_dj_connection_url"]);
}
@@ -266,7 +263,7 @@ class PreferenceController extends Zend_Controller_Action
$data = array();
$info = Application_Model_StreamSetting::getStreamSetting();
$data['setting'] = $info;
- for($i=1;$i<=$num_of_stream;$i++){
+ for ($i=1;$i<=$num_of_stream;$i++) {
Application_Model_StreamSetting::setLiquidsoapError($i, "waiting");
}
@@ -290,19 +287,16 @@ class PreferenceController extends Zend_Controller_Action
$result = array();
- if(is_null($path))
- {
+ if (is_null($path)) {
$element = array();
$element["name"] = "path should be specified";
$element["isFolder"] = false;
$element["isError"] = true;
$result[$path] = $element;
- }
- else
- {
+ } else {
$path = $path.'/';
$handle = opendir($path);
- if ($handle !== false){
+ if ($handle !== false) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
//only show directories that aren't private.
@@ -329,7 +323,7 @@ class PreferenceController extends Zend_Controller_Action
$watched_dirs_form = new Application_Form_WatchedDirPreferences();
$res = Application_Model_MusicDir::setStorDir($chosen);
- if($res['code'] != 0){
+ if ($res['code'] != 0) {
$watched_dirs_form->populate(array('storageFolder' => $chosen));
$watched_dirs_form->getElement($element)->setErrors(array($res['error']));
}
@@ -344,7 +338,7 @@ class PreferenceController extends Zend_Controller_Action
$watched_dirs_form = new Application_Form_WatchedDirPreferences();
$res = Application_Model_MusicDir::addWatchedDir($chosen);
- if($res['code'] != 0){
+ if ($res['code'] != 0) {
$watched_dirs_form->populate(array('watchedFolder' => $chosen));
$watched_dirs_form->getElement($element)->setErrors(array($res['error']));
}
@@ -373,22 +367,24 @@ class PreferenceController extends Zend_Controller_Action
$this->view->subform = $watched_dirs_form->render();
}
- public function isImportInProgressAction(){
+ public function isImportInProgressAction()
+ {
$now = time();
$res = false;
- if(Application_Model_Preference::GetImportTimestamp()+10 > $now){
+ if (Application_Model_Preference::GetImportTimestamp()+10 > $now) {
$res = true;
}
die(json_encode($res));
}
- public function getLiquidsoapStatusAction(){
+ public function getLiquidsoapStatusAction()
+ {
$out = array();
$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;
- if(!Application_Model_StreamSetting::getStreamEnabled($i)){
+ if (!Application_Model_StreamSetting::getStreamEnabled($i)) {
$status = "N/A";
}
$out[] = array("id"=>$i, "status"=>$status);
@@ -396,16 +392,17 @@ class PreferenceController extends Zend_Controller_Action
die(json_encode($out));
}
- public function setSourceConnectionUrlAction(){
+ public function setSourceConnectionUrlAction()
+ {
$request = $this->getRequest();
$type = $request->getParam("type", null);
$url = urldecode($request->getParam("url", null));
$override = $request->getParam("override", false);
- if($type == 'masterdj'){
+ if ($type == 'masterdj') {
Application_Model_Preference::SetMasterDJSourceConnectionURL($url);
Application_Model_Preference::SetMasterDjConnectionUrlOverride($override);
- }elseif($type == 'livedj'){
+ } elseif ($type == 'livedj') {
Application_Model_Preference::SetLiveDJSourceConnectionURL($url);
Application_Model_Preference::SetLiveDjConnectionUrlOverride($override);
}
@@ -413,6 +410,3 @@ class PreferenceController extends Zend_Controller_Action
die();
}
}
-
-
-
diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php
index 82a42c042..50615d354 100644
--- a/airtime_mvc/application/controllers/ScheduleController.php
+++ b/airtime_mvc/application/controllers/ScheduleController.php
@@ -92,7 +92,7 @@ class ScheduleController extends Zend_Controller_Action
$user = Application_Model_User::getCurrentUser();
- if($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))){
+ if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
$this->view->preloadShowForm = true;
}
@@ -110,15 +110,15 @@ class ScheduleController extends Zend_Controller_Action
$user = new Application_Model_User($userInfo->id);
if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
$editable = true;
- }
- else {
+ } else {
$editable = false;
}
$this->view->events = Application_Model_Show::getFullCalendarEvents($start, $end, $editable);
}
- public function getCurrentShowAction() {
+ public function getCurrentShowAction()
+ {
$currentShow = Application_Model_Show::GetCurrentShow();
if (!empty($currentShow)) {
$this->view->si_id = $currentShow[0]["instance_id"];
@@ -140,8 +140,9 @@ class ScheduleController extends Zend_Controller_Action
if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
try {
$showInstance = new Application_Model_ShowInstance($showInstanceId);
- } catch (Exception $e){
+ } catch (Exception $e) {
$this->view->show_error = true;
+
return false;
}
$error = $showInstance->moveShow($deltaDay, $deltaMin);
@@ -162,10 +163,11 @@ class ScheduleController extends Zend_Controller_Action
$user = new Application_Model_User($userInfo->id);
if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
- try{
+ try {
$show = new Application_Model_Show($showId);
- }catch(Exception $e){
+ } catch (Exception $e) {
$this->view->show_error = true;
+
return false;
}
$error = $show->resizeShow($deltaDay, $deltaMin);
@@ -187,9 +189,9 @@ class ScheduleController extends Zend_Controller_Action
try {
$showInstance = new Application_Model_ShowInstance($showInstanceId);
- }
- catch(Exception $e){
+ } catch (Exception $e) {
$this->view->show_error = true;
+
return false;
}
@@ -203,10 +205,11 @@ class ScheduleController extends Zend_Controller_Action
{
global $CC_CONFIG;
$show_instance = $this->_getParam('id');
- try{
+ try {
$show_inst = new Application_Model_ShowInstance($show_instance);
- }catch(Exception $e){
+ } catch (Exception $e) {
$this->view->show_error = true;
+
return false;
}
@@ -225,10 +228,11 @@ class ScheduleController extends Zend_Controller_Action
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id);
- try{
+ try {
$instance = new Application_Model_ShowInstance($id);
- }catch(Exception $e){
+ } catch (Exception $e) {
$this->view->show_error = true;
+
return false;
}
@@ -243,7 +247,7 @@ class ScheduleController extends Zend_Controller_Action
$file = $instance->getRecordedFile();
$fileId = $file->getId();
- $menu["view_recorded"] = array("name" => "View Recorded File Metadata", "icon" => "overview",
+ $menu["view_recorded"] = array("name" => "View Recorded File Metadata", "icon" => "overview",
"url" => "/library/edit-file-md/id/".$fileId);
}
@@ -269,13 +273,13 @@ class ScheduleController extends Zend_Controller_Action
&& $instance->isRecorded()
&& Application_Model_Preference::GetUploadToSoundcloudOption()) {
- $file = $instance->getRecordedFile();
+ $file = $instance->getRecordedFile();
$fileId = $file->getId();
$scid = $instance->getSoundCloudFileId();
- if ($scid > 0){
- $url = $file->getSoundCloudLinkToFile();
- $menu["soundcloud_view"] = array("name" => "View on Soundcloud", "icon" => "soundcloud", "url" => $url);
+ if ($scid > 0) {
+ $url = $file->getSoundCloudLinkToFile();
+ $menu["soundcloud_view"] = array("name" => "View on Soundcloud", "icon" => "soundcloud", "url" => $url);
}
$text = is_null($scid) ? 'Upload to SoundCloud' : 'Re-upload to SoundCloud';
@@ -287,8 +291,7 @@ class ScheduleController extends Zend_Controller_Action
if ($instance->isRecorded()) {
$menu["cancel_recorded"] = array("name"=> "Cancel Current Show", "icon" => "delete");
- }
- else {
+ } else {
if (!$instance->isRebroadcast()) {
$menu["edit"] = array("name"=> "Edit Show", "icon" => "edit", "_type"=>"all", "url" => "/Schedule/populate-show-form");
@@ -312,8 +315,7 @@ class ScheduleController extends Zend_Controller_Action
$menu["del"]["items"]["single"] = array("name"=> "Delete This Instance", "icon" => "delete", "url" => "/schedule/delete-show");
$menu["del"]["items"]["following"] = array("name"=> "Delete This Instance and All Following", "icon" => "delete", "url" => "/schedule/cancel-show");
- }
- else if ($isAdminOrPM){
+ } elseif ($isAdminOrPM) {
$menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => "/schedule/delete-show");
}
@@ -327,10 +329,11 @@ class ScheduleController extends Zend_Controller_Action
$showInstanceId = $this->_getParam('id');
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id);
- try{
+ try {
$show = new Application_Model_ShowInstance($showInstanceId);
- }catch(Exception $e){
+ } catch (Exception $e) {
$this->view->show_error = true;
+
return false;
}
@@ -344,15 +347,15 @@ class ScheduleController extends Zend_Controller_Action
$show = Application_Model_Show::GetCurrentShow();
/* Convert all UTC times to localtime before sending back to user. */
- if (isset($range["previous"])){
+ if (isset($range["previous"])) {
$range["previous"]["starts"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["previous"]["starts"]);
$range["previous"]["ends"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["previous"]["ends"]);
}
- if (isset($range["current"])){
+ if (isset($range["current"])) {
$range["current"]["starts"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["current"]["starts"]);
$range["current"]["ends"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["current"]["ends"]);
}
- if (isset($range["next"])){
+ if (isset($range["next"])) {
$range["next"]["starts"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["next"]["starts"]);
$range["next"]["ends"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["next"]["ends"]);
}
@@ -391,14 +394,15 @@ class ScheduleController extends Zend_Controller_Action
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id);
- try{
+ try {
$show = new Application_Model_ShowInstance($showInstanceId);
- }catch(Exception $e){
+ } catch (Exception $e) {
$this->view->show_error = true;
+
return false;
}
- if($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER, UTYPE_HOST),$show->getShowId())) {
+ if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER, UTYPE_HOST),$show->getShowId())) {
$show->removeGroupFromShow($group_id);
}
@@ -412,19 +416,21 @@ class ScheduleController extends Zend_Controller_Action
public function showContentDialogAction()
{
$showInstanceId = $this->_getParam('id');
- try{
+ try {
$show = new Application_Model_ShowInstance($showInstanceId);
- }catch(Exception $e){
+ } catch (Exception $e) {
$this->view->show_error = true;
+
return false;
}
$originalShowId = $show->isRebroadcast();
- if (!is_null($originalShowId)){
- try{
+ if (!is_null($originalShowId)) {
+ try {
$originalShow = new Application_Model_ShowInstance($originalShowId);
- }catch(Exception $e){
+ } catch (Exception $e) {
$this->view->show_error = true;
+
return false;
}
$originalShowName = $originalShow->getName();
@@ -506,12 +512,10 @@ class ScheduleController extends Zend_Controller_Action
$formRepeats->disable();
$formStyle->disable();
-
//$formRecord->disable();
//$formAbsoluteRebroadcast->disable();
//$formRebroadcast->disable();
-
$this->view->action = "edit-show-instance";
$this->view->newForm = $this->view->render('schedule/add-show-form.phtml');
}*/
@@ -529,21 +533,22 @@ class ScheduleController extends Zend_Controller_Action
$type = $this->_getParam('type');
$this->view->action = "edit-show";
- try{
+ try {
$showInstance = new Application_Model_ShowInstance($showInstanceId);
- }catch(Exception $e){
+ } catch (Exception $e) {
$this->view->show_error = true;
+
return false;
}
$isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
$isDJ = $user->isHost($showInstance->getShowId());
- if(!($isAdminOrPM || $isDJ)) {
+ if (!($isAdminOrPM || $isDJ)) {
return;
}
- if($isDJ){
+ if ($isDJ) {
$this->view->action = "dj-edit-show";
}
@@ -590,12 +595,12 @@ class ScheduleController extends Zend_Controller_Action
'add_show_duration' => $show->getDuration(true),
'add_show_repeats' => $show->isRepeating() ? 1 : 0));
- if ($show->isStartDateTimeInPast()){
+ if ($show->isStartDateTimeInPast()) {
// for a non-repeating show, we should never allow user to change the start time.
// for the repeating show, we should allow because the form works as repeating template form
- if(!$showInstance->getShow()->isRepeating()){
+ if (!$showInstance->getShow()->isRepeating()) {
$formWhen->disableStartDateAndTime();
- }else{
+ } else {
$formWhen->getElement('add_show_start_date')->setOptions(array('disabled' => true));
}
}
@@ -603,7 +608,7 @@ class ScheduleController extends Zend_Controller_Action
//need to get the days of the week in the php timezone (for the front end).
$days = array();
$showDays = CcShowDaysQuery::create()->filterByDbShowId($showInstance->getShowId())->find();
- foreach($showDays as $showDay){
+ foreach ($showDays as $showDay) {
$showStartDay = new DateTime($showDay->getDbFirstShow(), new DateTimeZone($showDay->getDbTimezone()));
$showStartDay->setTimezone(new DateTimeZone(date_default_timezone_get()));
array_push($days, $showStartDay->format('w'));
@@ -620,7 +625,7 @@ class ScheduleController extends Zend_Controller_Action
$hosts = array();
$showHosts = CcShowHostsQuery::create()->filterByDbShow($showInstance->getShowId())->find();
- foreach($showHosts as $showHost){
+ foreach ($showHosts as $showHost) {
array_push($hosts, $showHost->getDbHost());
}
$formWho->populate(array('add_show_hosts' => $hosts));
@@ -629,7 +634,7 @@ class ScheduleController extends Zend_Controller_Action
$formLive->populate($show->getLiveStreamInfo());
- if(!$isSaas){
+ if (!$isSaas) {
$formRecord = new Application_Form_AddShowRR();
$formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates();
$formRebroadcast = new Application_Form_AddShowRebroadcastDates();
@@ -652,7 +657,7 @@ class ScheduleController extends Zend_Controller_Action
$rebroadcastsRelative = $show->getRebroadcastsRelative();
$rebroadcastFormValues = array();
$i = 1;
- foreach ($rebroadcastsRelative as $rebroadcast){
+ foreach ($rebroadcastsRelative as $rebroadcast) {
$rebroadcastFormValues["add_show_rebroadcast_date_$i"] = $rebroadcast['day_offset'];
$rebroadcastFormValues["add_show_rebroadcast_time_$i"] = Application_Common_DateHelper::removeSecondsFromTime($rebroadcast['start_time']);
$i++;
@@ -662,20 +667,20 @@ class ScheduleController extends Zend_Controller_Action
$rebroadcastsAbsolute = $show->getRebroadcastsAbsolute();
$rebroadcastAbsoluteFormValues = array();
$i = 1;
- foreach ($rebroadcastsAbsolute as $rebroadcast){
+ foreach ($rebroadcastsAbsolute as $rebroadcast) {
$rebroadcastAbsoluteFormValues["add_show_rebroadcast_date_absolute_$i"] = $rebroadcast['start_date'];
$rebroadcastAbsoluteFormValues["add_show_rebroadcast_time_absolute_$i"] = $rebroadcast['start_time'];
$i++;
}
$formAbsoluteRebroadcast->populate($rebroadcastAbsoluteFormValues);
- if(!$isAdminOrPM){
+ if (!$isAdminOrPM) {
$formRecord->disable();
$formAbsoluteRebroadcast->disable();
$formRebroadcast->disable();
}
}
- if(!$isAdminOrPM){
+ if (!$isAdminOrPM) {
$formWhat->disable();
$formWho->disable();
$formWhen->disable();
@@ -687,22 +692,23 @@ class ScheduleController extends Zend_Controller_Action
$this->view->entries = 5;
}
- public function getFormAction() {
-
+ public function getFormAction()
+ {
$user = Application_Model_User::getCurrentUser();
- if($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))){
+ if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
Application_Model_Schedule::createNewFormSections($this->view);
$this->view->form = $this->view->render('schedule/add-show-form.phtml');
}
}
- public function djEditShowAction(){
+ public function djEditShowAction()
+ {
$js = $this->_getParam('data');
$data = array();
//need to convert from serialized jQuery array.
- foreach($js as $j){
+ foreach ($js as $j) {
$data[$j["name"]] = $j["value"];
}
@@ -721,12 +727,12 @@ class ScheduleController extends Zend_Controller_Action
$data = array();
//need to convert from serialized jQuery array.
- foreach($js as $j){
+ foreach ($js as $j) {
$data[$j["name"]] = $j["value"];
}
$success = Application_Model_Schedule::updateShowInstance($data, $this);
- if ($success){
+ if ($success) {
$this->view->addNewShow = true;
$this->view->newForm = $this->view->render('schedule/add-show-form.phtml');
} else {
@@ -735,21 +741,21 @@ class ScheduleController extends Zend_Controller_Action
}
}*/
- public function editShowAction(){
-
+ public function editShowAction()
+ {
//1) Get add_show_start_date since it might not have been sent
$js = $this->_getParam('data');
$data = array();
//need to convert from serialized jQuery array.
- foreach($js as $j){
+ foreach ($js as $j) {
$data[$j["name"]] = $j["value"];
}
$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;
}
@@ -757,14 +763,14 @@ class ScheduleController extends Zend_Controller_Action
$validateStartDate = true;
$validateStartTime = true;
- if (!array_key_exists('add_show_start_date', $data)){
+ if (!array_key_exists('add_show_start_date', $data)) {
//Changing the start date was disabled, since the
//array key does not exist. We need to repopulate this entry from the db.
//The start date will be returned in UTC time, so lets convert it to local time.
$dt = Application_Common_DateHelper::ConvertToLocalDateTime($show->getStartDateAndTime());
$data['add_show_start_date'] = $dt->format("Y-m-d");
- if (!array_key_exists('add_show_start_time', $data)){
+ if (!array_key_exists('add_show_start_time', $data)) {
$data['add_show_start_time'] = $dt->format("H:i");
$validateStartTime = false;
}
@@ -775,14 +781,14 @@ class ScheduleController extends Zend_Controller_Action
$origianlShowStartDateTime = Application_Common_DateHelper::ConvertToLocalDateTime($show->getStartDateAndTime());
$success = Application_Model_Schedule::addUpdateShow($data, $this, $validateStartDate, $origianlShowStartDateTime, true, $data['add_show_instance_id']);
- if ($success){
+ if ($success) {
$this->view->addNewShow = true;
$this->view->newForm = $this->view->render('schedule/add-show-form.phtml');
} else {
- if (!$validateStartDate){
+ if (!$validateStartDate) {
$this->view->when->getElement('add_show_start_date')->setOptions(array('disabled' => true));
}
- if(!$validateStartTime){
+ if (!$validateStartTime) {
$this->view->when->getElement('add_show_start_time')->setOptions(array('disabled' => true));
}
$this->view->rr->getElement('add_show_record')->setOptions(array('disabled' => true));
@@ -792,26 +798,27 @@ class ScheduleController extends Zend_Controller_Action
}
}
- public function addShowAction(){
+ public function addShowAction()
+ {
$js = $this->_getParam('data');
$data = array();
//need to convert from serialized jQuery array.
- foreach($js as $j){
+ foreach ($js as $j) {
$data[$j["name"]] = $j["value"];
}
$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;
}
$validateStartDate = true;
$success = Application_Model_Schedule::addUpdateShow($data, $this, $validateStartDate);
- if ($success){
+ if ($success) {
$this->view->addNewShow = true;
$this->view->newForm = $this->view->render('schedule/add-show-form.phtml');
} else {
@@ -829,8 +836,9 @@ class ScheduleController extends Zend_Controller_Action
try {
$showInstance = new Application_Model_ShowInstance($showInstanceId);
- } catch(Exception $e) {
+ } catch (Exception $e) {
$this->view->show_error = true;
+
return false;
}
$show = new Application_Model_Show($showInstance->getShowId());
@@ -847,23 +855,23 @@ class ScheduleController extends Zend_Controller_Action
if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
$id = $this->_getParam('id');
- try {
- $scheduler = new Application_Model_Scheduler();
+ try {
+ $scheduler = new Application_Model_Scheduler();
$scheduler->cancelShow($id);
// send kick out source stream signal to pypo
$data = array("sourcename"=>"live_dj");
- Application_Model_RabbitMq::SendMessageToPypo("disconnect_source", $data);
- }
- catch (Exception $e) {
- $this->view->error = $e->getMessage();
- Logging::log($e->getMessage());
- Logging::log("{$e->getFile()}");
- Logging::log("{$e->getLine()}");
+ Application_Model_RabbitMq::SendMessageToPypo("disconnect_source", $data);
+ } catch (Exception $e) {
+ $this->view->error = $e->getMessage();
+ Logging::log($e->getMessage());
+ Logging::log("{$e->getFile()}");
+ Logging::log("{$e->getLine()}");
}
}
}
- public function contentContextMenuAction(){
+ public function contentContextMenuAction()
+ {
global $CC_CONFIG;
$id = $this->_getParam('id');
@@ -891,7 +899,8 @@ class ScheduleController extends Zend_Controller_Action
* Sets the user specific preference for which time scale to use in Calendar.
* This is only being used by schedule.js at the moment.
*/
- public function setTimeScaleAction() {
+ public function setTimeScaleAction()
+ {
Application_Model_Preference::SetCalendarTimeScale($this->_getParam('timeScale'));
}
@@ -899,17 +908,19 @@ class ScheduleController extends Zend_Controller_Action
* Sets the user specific preference for which time interval to use in Calendar.
* This is only being used by schedule.js at the moment.
*/
- public function setTimeIntervalAction() {
+ public function setTimeIntervalAction()
+ {
Application_Model_Preference::SetCalendarTimeInterval($this->_getParam('timeInterval'));
}
- public function calculateDurationAction() {
+ public function calculateDurationAction()
+ {
global $CC_CONFIG;
$startParam = $this->_getParam('startTime');
$endParam = $this->_getParam('endTime');
- try{
+ try {
$startDateTime = new DateTime($startParam);
$endDateTime = new DateTime($endParam);
@@ -919,17 +930,17 @@ class ScheduleController extends Zend_Controller_Action
$duration = $UTCEndDateTime->diff($UTCStartDateTime);
$day = intval($duration->format('%d'));
- if($day > 0){
+ if ($day > 0) {
$hour = intval($duration->format('%h'));
$min = intval($duration->format('%i'));
$hour += $day * 24;
$hour = min($hour, 99);
$sign = $duration->format('%r');
$result = sprintf('%s%02dh %02dm', $sign, $hour, $min);
- }else{
+ } else {
$result = $duration->format('%r%Hh %Im');
}
- }catch (Exception $e){
+ } catch (Exception $e) {
$result = "Invalid Date";
}
@@ -937,4 +948,3 @@ class ScheduleController extends Zend_Controller_Action
exit();
}
}
-
diff --git a/airtime_mvc/application/controllers/ShowbuilderController.php b/airtime_mvc/application/controllers/ShowbuilderController.php
index 32c7c53fb..f5dcd6cca 100644
--- a/airtime_mvc/application/controllers/ShowbuilderController.php
+++ b/airtime_mvc/application/controllers/ShowbuilderController.php
@@ -16,130 +16,125 @@ class ShowbuilderController extends Zend_Controller_Action
->initContext();
}
- public function indexAction() {
+ public function indexAction()
+ {
+ global $CC_CONFIG;
- global $CC_CONFIG;
-
- $request = $this->getRequest();
+ $request = $this->getRequest();
$baseUrl = $request->getBaseUrl();
$user = Application_Model_User::getCurrentUser();
$userType = $user->getType();
$this->view->headScript()->appendScript("localStorage.setItem( 'user-type', '$userType' );");
- $data = Application_Model_Preference::getValue("library_datatable", true);
- if ($data != "") {
- $libraryTable = json_encode(unserialize($data));
- $this->view->headScript()->appendScript("localStorage.setItem( 'datatables-library', JSON.stringify($libraryTable) );");
- }
- else {
+ $data = Application_Model_Preference::getValue("library_datatable", true);
+ if ($data != "") {
+ $libraryTable = json_encode(unserialize($data));
+ $this->view->headScript()->appendScript("localStorage.setItem( 'datatables-library', JSON.stringify($libraryTable) );");
+ } else {
$this->view->headScript()->appendScript("localStorage.setItem( 'datatables-library', '' );");
}
- $data = Application_Model_Preference::getValue("timeline_datatable", true);
- if ($data != "") {
+ $data = Application_Model_Preference::getValue("timeline_datatable", true);
+ if ($data != "") {
$timelineTable = json_encode(unserialize($data));
- $this->view->headScript()->appendScript("localStorage.setItem( 'datatables-timeline', JSON.stringify($timelineTable) );");
- }
- else {
- $this->view->headScript()->appendScript("localStorage.setItem( 'datatables-timeline', '' );");
+ $this->view->headScript()->appendScript("localStorage.setItem( 'datatables-timeline', JSON.stringify($timelineTable) );");
+ } else {
+ $this->view->headScript()->appendScript("localStorage.setItem( 'datatables-timeline', '' );");
}
- $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/datatables/plugin/dataTables.ColVis.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.ColReorder.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- $this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.FixedColumns.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/datatables/plugin/dataTables.ColVis.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.ColReorder.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ $this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.FixedColumns.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/airtime/library/library.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/ColReorder.css?'.$CC_CONFIG['airtime_version']);
+ $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/airtime/library/library.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/ColReorder.css?'.$CC_CONFIG['airtime_version']);
$this->view->headScript()->appendFile($this->view->baseUrl('/js/airtime/library/events/library_showbuilder.js?'.$CC_CONFIG['airtime_version']),'text/javascript');
- $refer_sses = new Zend_Session_Namespace('referrer');
-
- if ($request->isPost()) {
- $form = new Application_Form_RegisterAirtime();
-
- $values = $request->getPost();
- if ($values["Publicise"] != 1 && $form->isValid($values)) {
+ $refer_sses = new Zend_Session_Namespace('referrer');
+
+ if ($request->isPost()) {
+ $form = new Application_Form_RegisterAirtime();
+
+ $values = $request->getPost();
+ if ($values["Publicise"] != 1 && $form->isValid($values)) {
Application_Model_Preference::SetSupportFeedback($values["SupportFeedback"]);
-
- if (isset($values["Privacy"])) {
- Application_Model_Preference::SetPrivacyPolicyCheck($values["Privacy"]);
- }
- // unset session
- Zend_Session::namespaceUnset('referrer');
- }
- else if ($values["Publicise"] == '1' && $form->isValid($values)) {
- Application_Model_Preference::SetHeadTitle($values["stnName"], $this->view);
- Application_Model_Preference::SetPhone($values["Phone"]);
- Application_Model_Preference::SetEmail($values["Email"]);
- Application_Model_Preference::SetStationWebSite($values["StationWebSite"]);
- Application_Model_Preference::SetPublicise($values["Publicise"]);
-
- $form->Logo->receive();
- $imagePath = $form->Logo->getFileName();
-
- Application_Model_Preference::SetStationCountry($values["Country"]);
- Application_Model_Preference::SetStationCity($values["City"]);
- Application_Model_Preference::SetStationDescription($values["Description"]);
- Application_Model_Preference::SetStationLogo($imagePath);
+
+ if (isset($values["Privacy"])) {
+ Application_Model_Preference::SetPrivacyPolicyCheck($values["Privacy"]);
+ }
+ // unset session
+ Zend_Session::namespaceUnset('referrer');
+ } elseif ($values["Publicise"] == '1' && $form->isValid($values)) {
+ Application_Model_Preference::SetHeadTitle($values["stnName"], $this->view);
+ Application_Model_Preference::SetPhone($values["Phone"]);
+ Application_Model_Preference::SetEmail($values["Email"]);
+ Application_Model_Preference::SetStationWebSite($values["StationWebSite"]);
+ Application_Model_Preference::SetPublicise($values["Publicise"]);
+
+ $form->Logo->receive();
+ $imagePath = $form->Logo->getFileName();
+
+ Application_Model_Preference::SetStationCountry($values["Country"]);
+ Application_Model_Preference::SetStationCity($values["City"]);
+ Application_Model_Preference::SetStationDescription($values["Description"]);
+ Application_Model_Preference::SetStationLogo($imagePath);
Application_Model_Preference::SetSupportFeedback($values["SupportFeedback"]);
-
- if (isset($values["Privacy"])){
- Application_Model_Preference::SetPrivacyPolicyCheck($values["Privacy"]);
- }
- // unset session
- Zend_Session::namespaceUnset('referrer');
+
+ if (isset($values["Privacy"])) {
+ Application_Model_Preference::SetPrivacyPolicyCheck($values["Privacy"]);
+ }
+ // unset session
+ Zend_Session::namespaceUnset('referrer');
+ } else {
+ $logo = Application_Model_Preference::GetStationLogo();
+ if ($logo) {
+ $this->view->logoImg = $logo;
+ }
+ $this->view->dialog = $form;
+ $this->view->headScript()->appendFile($baseUrl.'/js/airtime/nowplaying/register.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
}
- else {
- $logo = Application_Model_Preference::GetStationLogo();
- if ($logo) {
- $this->view->logoImg = $logo;
- }
- $this->view->dialog = $form;
- $this->view->headScript()->appendFile($baseUrl.'/js/airtime/nowplaying/register.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- }
}
-
- //popup if previous page was login
- if ($refer_sses->referrer == 'login' && Application_Model_Preference::ShouldShowPopUp()
- && !Application_Model_Preference::GetSupportFeedback() && $user->isAdmin()){
-
- $form = new Application_Form_RegisterAirtime();
-
- $logo = Application_Model_Preference::GetStationLogo();
- if ($logo) {
- $this->view->logoImg = $logo;
- }
- $this->view->dialog = $form;
- $this->view->headScript()->appendFile($baseUrl.'/js/airtime/nowplaying/register.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
- }
+
+ //popup if previous page was login
+ if ($refer_sses->referrer == 'login' && Application_Model_Preference::ShouldShowPopUp()
+ && !Application_Model_Preference::GetSupportFeedback() && $user->isAdmin()){
+
+ $form = new Application_Form_RegisterAirtime();
+
+ $logo = Application_Model_Preference::GetStationLogo();
+ if ($logo) {
+ $this->view->logoImg = $logo;
+ }
+ $this->view->dialog = $form;
+ $this->view->headScript()->appendFile($baseUrl.'/js/airtime/nowplaying/register.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
+ }
//determine whether to remove/hide/display the library.
- $showLib = false;
+ $showLib = false;
if (!$user->isGuest()) {
$disableLib = false;
- $data = Application_Model_Preference::getValue("nowplaying_screen", true);
- if ($data != "") {
+ $data = Application_Model_Preference::getValue("nowplaying_screen", true);
+ if ($data != "") {
$settings = unserialize($data);
if ($settings["library"] == "true") {
$showLib = true;
- }
+ }
}
- }
- else {
+ } else {
$disableLib = true;
}
$this->view->disableLib = $disableLib;
@@ -175,36 +170,36 @@ class ShowbuilderController extends Zend_Controller_Action
$this->view->headLink()->appendStylesheet($baseUrl.'/css/showbuilder.css?'.$CC_CONFIG['airtime_version']);
}
- public function contextMenuAction()
- {
- $id = $this->_getParam('id');
- $now = floatval(microtime(true));
-
- $request = $this->getRequest();
- $baseUrl = $request->getBaseUrl();
- $menu = array();
-
- $user = Application_Model_User::getCurrentUser();
-
- $item = CcScheduleQuery::create()->findPK($id);
- $instance = $item->getCcShowInstances();
-
- $menu["preview"] = array("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())) {
-
- //remove/truncate the item from the schedule
- $menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => "/showbuilder/schedule-remove");
- }
-
- $this->view->items = $menu;
+ public function contextMenuAction()
+ {
+ $id = $this->_getParam('id');
+ $now = floatval(microtime(true));
+
+ $request = $this->getRequest();
+ $baseUrl = $request->getBaseUrl();
+ $menu = array();
+
+ $user = Application_Model_User::getCurrentUser();
+
+ $item = CcScheduleQuery::create()->findPK($id);
+ $instance = $item->getCcShowInstances();
+
+ $menu["preview"] = array("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())) {
+
+ //remove/truncate the item from the schedule
+ $menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => "/showbuilder/schedule-remove");
+ }
+
+ $this->view->items = $menu;
}
- public function builderDialogAction() {
-
+ public function builderDialogAction()
+ {
$request = $this->getRequest();
$id = $request->getParam("id");
@@ -212,6 +207,7 @@ class ShowbuilderController extends Zend_Controller_Action
if (is_null($instance)) {
$this->view->error = "show does not exist";
+
return;
}
@@ -231,8 +227,8 @@ class ShowbuilderController extends Zend_Controller_Action
$this->view->dialog = $this->view->render('showbuilder/builderDialog.phtml');
}
- public function checkBuilderFeedAction() {
-
+ public function checkBuilderFeedAction()
+ {
$request = $this->getRequest();
$current_time = time();
@@ -254,14 +250,13 @@ class ShowbuilderController extends Zend_Controller_Action
// -1 default will always call the schedule to be sent back if no timestamp is defined.
if ($showBuilder->hasBeenUpdatedSince($timestamp, $instances)) {
$this->view->update = true;
- }
- else {
+ } else {
$this->view->update = false;
}
}
- public function builderFeedAction() {
-
+ public function builderFeedAction()
+ {
$start = microtime(true);
$request = $this->getRequest();
@@ -285,14 +280,14 @@ class ShowbuilderController extends Zend_Controller_Action
$this->view->instances = $data["showInstances"];
$this->view->timestamp = $current_time;
- $end = microtime(true);
-
- Logging::debug("getting builder feed info took:");
+ $end = microtime(true);
+
+ Logging::debug("getting builder feed info took:");
Logging::debug(floatval($end) - floatval($start));
}
- public function scheduleAddAction() {
-
+ public function scheduleAddAction()
+ {
$request = $this->getRequest();
$mediaItems = $request->getParam("mediaIds", array());
$scheduledItems = $request->getParam("schedIds", array());
@@ -300,14 +295,12 @@ class ShowbuilderController extends Zend_Controller_Action
try {
$scheduler = new Application_Model_Scheduler();
$scheduler->scheduleAfter($scheduledItems, $mediaItems);
- }
- catch (OutDatedScheduleException $e) {
+ } catch (OutDatedScheduleException $e) {
$this->view->error = $e->getMessage();
Logging::log($e->getMessage());
Logging::log("{$e->getFile()}");
Logging::log("{$e->getLine()}");
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->view->error = $e->getMessage();
Logging::log($e->getMessage());
Logging::log("{$e->getFile()}");
@@ -323,14 +316,12 @@ class ShowbuilderController extends Zend_Controller_Action
try {
$scheduler = new Application_Model_Scheduler();
$scheduler->removeItems($items);
- }
- catch (OutDatedScheduleException $e) {
+ } catch (OutDatedScheduleException $e) {
$this->view->error = $e->getMessage();
Logging::log($e->getMessage());
Logging::log("{$e->getFile()}");
Logging::log("{$e->getLine()}");
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->view->error = $e->getMessage();
Logging::log($e->getMessage());
Logging::log("{$e->getFile()}");
@@ -338,8 +329,8 @@ class ShowbuilderController extends Zend_Controller_Action
}
}
- public function scheduleMoveAction() {
-
+ public function scheduleMoveAction()
+ {
$request = $this->getRequest();
$selectedItems = $request->getParam("selectedItem");
$afterItem = $request->getParam("afterItem");
@@ -347,14 +338,12 @@ class ShowbuilderController extends Zend_Controller_Action
try {
$scheduler = new Application_Model_Scheduler();
$scheduler->moveItem($selectedItems, $afterItem);
- }
- catch (OutDatedScheduleException $e) {
+ } catch (OutDatedScheduleException $e) {
$this->view->error = $e->getMessage();
Logging::log($e->getMessage());
Logging::log("{$e->getFile()}");
Logging::log("{$e->getLine()}");
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->view->error = $e->getMessage();
Logging::log($e->getMessage());
Logging::log("{$e->getFile()}");
@@ -362,8 +351,8 @@ class ShowbuilderController extends Zend_Controller_Action
}
}
- public function scheduleReorderAction() {
-
+ public function scheduleReorderAction()
+ {
$request = $this->getRequest();
$showInstance = $request->getParam("instanceId");
diff --git a/airtime_mvc/application/controllers/UserController.php b/airtime_mvc/application/controllers/UserController.php
index 8c0a8af85..0c86e29eb 100644
--- a/airtime_mvc/application/controllers/UserController.php
+++ b/airtime_mvc/application/controllers/UserController.php
@@ -38,10 +38,9 @@ class UserController extends Zend_Controller_Action
if ($form->isValid($request->getPost())) {
$formdata = $form->getValues();
- if(isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1 && $formdata['login'] == 'admin' && $formdata['user_id'] != 0){
+ if (isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1 && $formdata['login'] == 'admin' && $formdata['user_id'] != 0) {
$this->view->successMessage = "
Specific action is not allowed in demo version!
";
- }
- else if ($form->validateLogin($formdata)){
+ } elseif ($form->validateLogin($formdata)) {
$user = new Application_Model_User($formdata['user_id']);
$user->setFirstName($formdata['first_name']);
$user->setLastName($formdata['last_name']);
@@ -57,7 +56,7 @@ class UserController extends Zend_Controller_Action
$form->reset();
- if (strlen($formdata['user_id']) == 0){
+ if (strlen($formdata['user_id']) == 0) {
$this->view->successMessage = "User added successfully!
";
} else {
$this->view->successMessage = "User updated successfully!
";
@@ -98,23 +97,11 @@ class UserController extends Zend_Controller_Action
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$userId = $userInfo->id;
- if ($delId != $userId){
+ if ($delId != $userId) {
$user = new Application_Model_User($delId);
$this->view->entries = $user->delete();
}
}
-
}
-
-
-
-
-
-
-
-
-
-
-
diff --git a/airtime_mvc/application/controllers/UsersettingsController.php b/airtime_mvc/application/controllers/UsersettingsController.php
index f60f18af4..b999b8ed1 100644
--- a/airtime_mvc/application/controllers/UsersettingsController.php
+++ b/airtime_mvc/application/controllers/UsersettingsController.php
@@ -11,31 +11,31 @@ class UsersettingsController extends Zend_Controller_Action
->addActionContext('get-library-datatable', 'json')
->addActionContext('set-library-datatable', 'json')
->addActionContext('get-timeline-datatable', 'json')
- ->addActionContext('set-timeline-datatable', 'json')
+ ->addActionContext('set-timeline-datatable', 'json')
->addActionContext('remindme', 'json')
->addActionContext('donotshowregistrationpopup', 'json')
->initContext();
}
- public function setNowPlayingScreenSettingsAction() {
+ public function setNowPlayingScreenSettingsAction()
+ {
+ $request = $this->getRequest();
+ $settings = $request->getParam("settings");
- $request = $this->getRequest();
- $settings = $request->getParam("settings");
-
- $data = serialize($settings);
+ $data = serialize($settings);
Application_Model_Preference::setValue("nowplaying_screen", $data, true);
}
- public function getNowPlayingScreenSettingsAction() {
-
- $data = Application_Model_Preference::getValue("nowplaying_screen", true);
- if ($data != "") {
- $this->view->settings = unserialize($data);
- }
+ public function getNowPlayingScreenSettingsAction()
+ {
+ $data = Application_Model_Preference::getValue("nowplaying_screen", true);
+ if ($data != "") {
+ $this->view->settings = unserialize($data);
+ }
}
- public function setLibraryDatatableAction() {
-
+ public function setLibraryDatatableAction()
+ {
$request = $this->getRequest();
$settings = $request->getParam("settings");
@@ -43,16 +43,16 @@ class UsersettingsController extends Zend_Controller_Action
Application_Model_Preference::setValue("library_datatable", $data, true);
}
- public function getLibraryDatatableAction() {
-
+ public function getLibraryDatatableAction()
+ {
$data = Application_Model_Preference::getValue("library_datatable", true);
if ($data != "") {
$this->view->settings = unserialize($data);
}
}
- public function setTimelineDatatableAction() {
-
+ public function setTimelineDatatableAction()
+ {
$start = microtime(true);
$request = $this->getRequest();
@@ -67,8 +67,8 @@ class UsersettingsController extends Zend_Controller_Action
Logging::debug(floatval($end) - floatval($start));
}
- public function getTimelineDatatableAction() {
-
+ public function getTimelineDatatableAction()
+ {
$start = microtime(true);
$data = Application_Model_Preference::getValue("timeline_datatable", true);
@@ -76,22 +76,22 @@ class UsersettingsController extends Zend_Controller_Action
$this->view->settings = unserialize($data);
}
- $end = microtime(true);
-
- Logging::debug("getting timeline datatables info took:");
+ $end = microtime(true);
+
+ Logging::debug("getting timeline datatables info took:");
Logging::debug(floatval($end) - floatval($start));
}
- public function remindmeAction()
- {
- // unset session
- Zend_Session::namespaceUnset('referrer');
- Application_Model_Preference::SetRemindMeDate();
- }
-
- public function donotshowregistrationpopupAction()
- {
- // unset session
- Zend_Session::namespaceUnset('referrer');
+ public function remindmeAction()
+ {
+ // unset session
+ Zend_Session::namespaceUnset('referrer');
+ Application_Model_Preference::SetRemindMeDate();
}
-}
\ No newline at end of file
+
+ public function donotshowregistrationpopupAction()
+ {
+ // unset session
+ Zend_Session::namespaceUnset('referrer');
+ }
+}
diff --git a/airtime_mvc/application/controllers/plugins/Acl_plugin.php b/airtime_mvc/application/controllers/plugins/Acl_plugin.php
index c8f116748..b28de407a 100644
--- a/airtime_mvc/application/controllers/plugins/Acl_plugin.php
+++ b/airtime_mvc/application/controllers/plugins/Acl_plugin.php
@@ -40,7 +40,7 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
/**
* Sets the ACL object
*
- * @param mixed $aclData
+ * @param mixed $aclData
* @return void
**/
public function setAcl(Zend_Acl $aclData)
@@ -77,9 +77,9 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
/**
* Sets the error page
*
- * @param string $action
- * @param string $controller
- * @param string $module
+ * @param string $action
+ * @param string $controller
+ * @param string $module
* @return void
**/
public function setErrorPage($action, $controller = 'error', $module = null)
@@ -109,20 +109,19 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$controller = strtolower($request->getControllerName());
-
- if (in_array($controller, array("api", "auth"))){
-
- $this->setRoleName("G");
- }
- else if (!Zend_Auth::getInstance()->hasIdentity()){
-
+
+ if (in_array($controller, array("api", "auth"))) {
+
+ $this->setRoleName("G");
+ } elseif (!Zend_Auth::getInstance()->hasIdentity()) {
+
if ($controller !== 'login') {
if ($request->isXmlHttpRequest()) {
$url = 'http://'.$request->getHttpHost().'/login';
$json = Zend_Json::encode(array('auth' => false, 'url' => $url));
-
+
// Prepare response
$this->getResponse()
->setHttpResponseCode(401)
@@ -131,14 +130,12 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
//redirectAndExit() cleans up, sends the headers and stops the script
Zend_Controller_Action_HelperBroker::getStaticHelper('redirector')->redirectAndExit();
- }
- else {
+ } else {
$r = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$r->gotoSimpleAndExit('index', 'login', $request->getModuleName());
}
}
- }
- else {
+ } else {
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$this->setRoleName($userInfo->type);
diff --git a/airtime_mvc/application/controllers/plugins/RabbitMqPlugin.php b/airtime_mvc/application/controllers/plugins/RabbitMqPlugin.php
index 07f58c742..ad3042e53 100644
--- a/airtime_mvc/application/controllers/plugins/RabbitMqPlugin.php
+++ b/airtime_mvc/application/controllers/plugins/RabbitMqPlugin.php
@@ -7,7 +7,7 @@ class RabbitMqPlugin extends Zend_Controller_Plugin_Abstract
if (Application_Model_RabbitMq::$doPush) {
$md = array('schedule' => Application_Model_Schedule::GetScheduledPlaylists());
Application_Model_RabbitMq::SendMessageToPypo("update_schedule", $md);
- if (!isset($_SERVER['AIRTIME_SRV'])){
+ if (!isset($_SERVER['AIRTIME_SRV'])) {
Application_Model_RabbitMq::SendMessageToShowRecorder("update_recorder_schedule");
}
}
diff --git a/airtime_mvc/application/models/Auth.php b/airtime_mvc/application/models/Auth.php
index 12a3bfe33..8ddc8f363 100644
--- a/airtime_mvc/application/models/Auth.php
+++ b/airtime_mvc/application/models/Auth.php
@@ -1,7 +1,7 @@
$row[0]["artist_name"]." - ".$row[0]["track_title"],
@@ -22,8 +23,8 @@ class Application_Model_Dashboard
}
} else {
- if (count($row) == 0){
- if ($showInstance->isRecorded()){
+ if (count($row) == 0) {
+ if ($showInstance->isRecorded()) {
//last item is a show instance
return array("name"=>$showInstance->getName(),
"starts"=>$showInstance->getShowInstanceStart(),
@@ -33,7 +34,7 @@ class Application_Model_Dashboard
}
} else {
//return the one that started later.
- if ($row[0]["starts"] >= $showInstance->getShowInstanceStart()){
+ 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"]);
@@ -46,7 +47,8 @@ class Application_Model_Dashboard
}
}
- public static function GetCurrentItem($p_timeNow){
+ public static function GetCurrentItem($p_timeNow)
+ {
//get previous show and previous item in the schedule table.
//Compare the two and if the last show was recorded and started
//after the last item in the schedule table, then return the show's
@@ -54,26 +56,27 @@ class Application_Model_Dashboard
$row = array();
$showInstance = Application_Model_ShowInstance::GetCurrentShowInstance($p_timeNow);
- if (!is_null($showInstance)){
+ if (!is_null($showInstance)) {
$instanceId = $showInstance->getShowInstanceId();
$row = Application_Model_Schedule::GetCurrentScheduleItem($p_timeNow, $instanceId);
}
- if (is_null($showInstance)){
- if (count($row) == 0){
+ 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.
*/
+
return array("name"=>$row[0]["artist_name"]." - ".$row[0]["track_title"],
"starts"=>$row[0]["starts"],
"ends"=>$row[0]["ends"]);
}
} else {
- if (count($row) == 0){
+ if (count($row) == 0) {
//last item is a show instance
- if ($showInstance->isRecorded()){
+ if ($showInstance->isRecorded()) {
return array("name"=>$showInstance->getName(),
"starts"=>$showInstance->getShowInstanceStart(),
"ends"=>$showInstance->getShowInstanceEnd(),
@@ -92,7 +95,8 @@ class Application_Model_Dashboard
}
}
- public static function GetNextItem($p_timeNow){
+ public static function GetNextItem($p_timeNow)
+ {
//get previous show and previous item in the schedule table.
//Compare the two and if the last show was recorded and started
//after the last item in the schedule table, then return the show's
@@ -101,8 +105,8 @@ class Application_Model_Dashboard
$showInstance = Application_Model_ShowInstance::GetNextShowInstance($p_timeNow);
$row = Application_Model_Schedule::GetNextScheduleItem($p_timeNow);
- if (is_null($showInstance)){
- if (count($row) == 0){
+ if (is_null($showInstance)) {
+ if (count($row) == 0) {
return null;
} else {
return array("name"=>$row[0]["artist_name"]." - ".$row[0]["track_title"],
@@ -110,8 +114,8 @@ class Application_Model_Dashboard
"ends"=>$row[0]["ends"]);
}
} else {
- if (count($row) == 0){
- if ($showInstance->isRecorded()){
+ if (count($row) == 0) {
+ if ($showInstance->isRecorded()) {
//last item is a show instance
return array("name"=>$showInstance->getName(),
"starts"=>$showInstance->getShowInstanceStart(),
@@ -122,7 +126,7 @@ class Application_Model_Dashboard
} else {
//return the one that starts sooner.
- if ($row[0]["starts"] <= $showInstance->getShowInstanceStart()){
+ 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"]);
diff --git a/airtime_mvc/application/models/Datatables.php b/airtime_mvc/application/models/Datatables.php
index 227b8b645..3e588a112 100644
--- a/airtime_mvc/application/models/Datatables.php
+++ b/airtime_mvc/application/models/Datatables.php
@@ -1,7 +1,7 @@
query($sqlTotalDisplayRows);
$totalDisplayRows = $r->fetchColumn(0);
- }
- else {
+ } else {
$totalDisplayRows = $totalRows;
}
$r = $con->query($sql);
$r->setFetchMode(PDO::FETCH_ASSOC);
$results = $r->fetchAll();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
Logging::debug($e->getMessage());
}
diff --git a/airtime_mvc/application/models/Email.php b/airtime_mvc/application/models/Email.php
index 64c4a4356..a809045c9 100644
--- a/airtime_mvc/application/models/Email.php
+++ b/airtime_mvc/application/models/Email.php
@@ -1,13 +1,13 @@
= 1) {
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 {
+ } else {
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));
$clip_length_seconds -= floor($clip_length_seconds / 60);
- }
- else {
+ } else {
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);
- }
- else {
+ } else {
$clip_length = $track['clip_length'];
}
@@ -248,12 +245,12 @@ class Application_Model_LiveLog
$seconds = explode(".", $seconds);
if (isset($seconds[0])) {
- $minutes = (double)(($hours*60)+$minutes . "." . $seconds[0]);
- }
- else {
- $minutes = (double)(($hours*60)+$minutes);
+ $minutes = (double) (($hours*60)+$minutes . "." . $seconds[0]);
+ } else {
+ $minutes = (double) (($hours*60)+$minutes);
}
}
+
return $minutes;
} catch (Exception $e) {
header('HTTP/1.0 503 Service Unavailable');
@@ -262,7 +259,8 @@ class Application_Model_LiveLog
}
}
- public static function UpdateLastLogEndTime($log) {
+ public static function UpdateLastLogEndTime($log)
+ {
if ($log['end_time'] == null) {
$current_time = new DateTime("now", new DateTimeZone('UTC'));
$log['end_time'] = $current_time;
@@ -270,10 +268,12 @@ class Application_Model_LiveLog
self::SetEndTime($log['state'], $current_time, true);
self::SetNewLogTime($log['state'], $current_time);
}
+
return $log;
}
- public static function SetNewLogTime($state, $dateTime){
+ public static function SetNewLogTime($state, $dateTime)
+ {
try {
$con = Propel::getConnection();
@@ -293,7 +293,7 @@ class Application_Model_LiveLog
$sql_insert = "INSERT INTO CC_LIVE_LOG (state, start_time)"
." VALUES ('$state', '{$dateTime->format("Y-m-d H:i:s")}')";
$con->exec($sql_insert);
- if($state == "S"){
+ if ($state == "S") {
// if scheduled play source is getting broadcasted
Application_Model_Schedule::UpdateBrodcastedStatus($dateTime, 1);
}
@@ -306,7 +306,8 @@ class Application_Model_LiveLog
}
}
- public static function SetEndTime($state, $dateTime, $override=false){
+ public static function SetEndTime($state, $dateTime, $override=false)
+ {
try {
$con = Propel::getConnection();
diff --git a/airtime_mvc/application/models/LoginAttempts.php b/airtime_mvc/application/models/LoginAttempts.php
index 6ebeafff6..63cdce6b5 100644
--- a/airtime_mvc/application/models/LoginAttempts.php
+++ b/airtime_mvc/application/models/LoginAttempts.php
@@ -1,10 +1,12 @@
query($sql)->fetchColumn(0);
@@ -17,14 +19,17 @@ class Application_Model_LoginAttempts {
}
}
- public static function getAttempts($ip){
+ public static function getAttempts($ip)
+ {
$con = Propel::getConnection();
$sql = "select attempts from cc_login_attempts WHERE ip='$ip'";
$res = $con->query($sql)->fetchColumn(0);
+
return $res ? $res : 0;
}
- public static function resetAttempts($ip){
+ public static function resetAttempts($ip)
+ {
$con = Propel::getConnection();
$sql = "select count(*) from cc_login_attempts WHERE ip='$ip'";
$res = $con->query($sql)->fetchColumn(0);
@@ -33,4 +38,4 @@ class Application_Model_LoginAttempts {
$con->exec($sql);
}
}
-}
\ No newline at end of file
+}
diff --git a/airtime_mvc/application/models/MusicDir.php b/airtime_mvc/application/models/MusicDir.php
index f4fd92802..f8e950821 100644
--- a/airtime_mvc/application/models/MusicDir.php
+++ b/airtime_mvc/application/models/MusicDir.php
@@ -2,8 +2,8 @@
class NestedDirectoryException extends Exception { }
-class Application_Model_MusicDir {
-
+class Application_Model_MusicDir
+{
/**
* @holds propel database object
*/
@@ -40,21 +40,25 @@ class Application_Model_MusicDir {
$this->_dir->save();
}
- public function setExistsFlag($flag){
+ public function setExistsFlag($flag)
+ {
$this->_dir->setExists($flag);
$this->_dir->save();
}
- public function setWatchedFlag($flag){
+ public function setWatchedFlag($flag)
+ {
$this->_dir->setWatched($flag);
$this->_dir->save();
}
- public function getWatchedFlag(){
+ public function getWatchedFlag()
+ {
return $this->_dir->getWatched();
}
- public function getExistsFlag(){
+ public function getExistsFlag()
+ {
return $this->_dir->getExists();
}
@@ -113,8 +117,9 @@ class Application_Model_MusicDir {
* @return boolean
* Returns true if it is the ancestor, false otherwise.
*/
- private static function isAncestorDir($p_dir1, $p_dir2){
- if (strlen($p_dir1) > strlen($p_dir2)){
+ private static function isAncestorDir($p_dir1, $p_dir2)
+ {
+ if (strlen($p_dir1) > strlen($p_dir2)) {
return false;
}
@@ -130,23 +135,24 @@ class Application_Model_MusicDir {
* The path we want to validate
* @return void
*/
- public static function isPathValid($p_path){
+ public static function isPathValid($p_path)
+ {
$dirs = self::getWatchedDirs();
$dirs[] = self::getStorDir();
- foreach ($dirs as $dirObj){
+ foreach ($dirs as $dirObj) {
$dir = $dirObj->getDirectory();
$diff = strlen($dir) - strlen($p_path);
- if ($diff == 0){
- if ($dir == $p_path){
+ if ($diff == 0) {
+ if ($dir == $p_path) {
throw new NestedDirectoryException("'$p_path' is already watched.");
}
- } else if ($diff > 0){
- if (self::isAncestorDir($p_path, $dir)){
+ } elseif ($diff > 0) {
+ if (self::isAncestorDir($p_path, $dir)) {
throw new NestedDirectoryException("'$p_path' contains nested watched directory: '$dir'");
}
} else { /* diff < 0*/
- if (self::isAncestorDir($dir, $p_path)){
+ if (self::isAncestorDir($dir, $p_path)) {
throw new NestedDirectoryException("'$p_path' is nested within existing watched directory: '$dir'");
}
}
@@ -167,37 +173,36 @@ class Application_Model_MusicDir {
**/
public static function addDir($p_path, $p_type, $userAddedWatchedDir=true, $nestedWatch=false)
{
- if(!is_dir($p_path)){
+ if (!is_dir($p_path)) {
return array("code"=>2, "error"=>"'$p_path' is not a valid directory.");
}
$real_path = Application_Common_OsPath::normpath($p_path)."/";
- if($real_path != "/"){
+ if ($real_path != "/") {
$p_path = $real_path;
}
$exist_dir = self::getDirByPath($p_path);
- if( $exist_dir == NULL ){
+ if ($exist_dir == NULL) {
$temp_dir = new CcMusicDirs();
$dir = new Application_Model_MusicDir($temp_dir);
- }else{
+ } else {
$dir = $exist_dir;
}
$dir->setType($p_type);
$p_path = Application_Common_OsPath::normpath($p_path)."/";
-
try {
/* isPathValid() checks if path is a substring or a superstring of an
* existing dir and if not, throws NestedDirectoryException */
- if(!$nestedWatch){
+ if (!$nestedWatch) {
self::isPathValid($p_path);
}
- if($userAddedWatchedDir){
+ if ($userAddedWatchedDir) {
$dir->setWatchedFlag(true);
- }else{
- if($nestedWatch){
+ } else {
+ if ($nestedWatch) {
$dir->setWatchedFlag(false);
}
$dir->setExistsFlag(true);
@@ -205,10 +210,11 @@ class Application_Model_MusicDir {
$dir->setDirectory($p_path);
return array("code"=>0);
- } catch (NestedDirectoryException $nde){
+ } catch (NestedDirectoryException $nde) {
$msg = $nde->getMessage();
+
return array("code"=>1, "error"=>"$msg");
- } catch(Exception $e){
+ } catch (Exception $e) {
return array("code"=>1, "error"=>"'$p_path' is already set as the current storage dir or in the watched folders list");
}
@@ -228,7 +234,7 @@ class Application_Model_MusicDir {
{
$res = self::addDir($p_path, "watched", $userAddedWatchedDir, $nestedWatch);
- if ($res['code'] == 0){
+ if ($res['code'] == 0) {
//convert "linked" files (Airtime <= 1.8.2) to watched files.
$propel_link_dir = CcMusicDirsQuery::create()
@@ -271,6 +277,7 @@ class Application_Model_MusicDir {
$data["directory"] = $p_path;
Application_Model_RabbitMq::SendMessageToMediaMonitor("new_watch", $data);
}
+
return $res;
}
@@ -288,11 +295,11 @@ class Application_Model_MusicDir {
$dir = CcMusicDirsQuery::create()
->filterByDirectory($p_path)
->findOne();
- if($dir == NULL){
+ if ($dir == NULL) {
return null;
- }
- else{
+ } else {
$mus_dir = new Application_Model_MusicDir($dir);
+
return $mus_dir;
}
}
@@ -309,15 +316,15 @@ class Application_Model_MusicDir {
$dirs = CcMusicDirsQuery::create()
->filterByType("watched");
- if($exists !== null){
+ if ($exists !== null) {
$dirs = $dirs->filterByExists($exists);
}
- if($watched !== null){
+ if ($watched !== null) {
$dirs = $dirs->filterByWatched($watched);
}
$dirs = $dirs->find();
- foreach($dirs as $dir) {
+ foreach ($dirs as $dir) {
$result[] = new Application_Model_MusicDir($dir);
}
@@ -340,23 +347,24 @@ class Application_Model_MusicDir {
// we want to be consistent when storing dir path.
// path should always ends with trailing '/'
$p_dir = Application_Common_OsPath::normpath($p_dir)."/";
- if(!is_dir($p_dir)){
+ if (!is_dir($p_dir)) {
return array("code"=>2, "error"=>"'$p_dir' is not a valid directory.");
- }else if(Application_Model_Preference::GetImportTimestamp()+10 > time()){
+ } 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.");
}
$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);
+
return array("code"=>0);
- }else{
+ } else {
return array("code"=>1, "error"=>"'$p_dir' is already set as the current storage dir or in the watched folders list.");
}
}
@@ -369,10 +377,11 @@ class Application_Model_MusicDir {
->filterByWatched(true)
->find();
- foreach($dirs as $dir) {
+ 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;
}
}
@@ -390,11 +399,11 @@ class Application_Model_MusicDir {
* 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){
-
+ 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 != "/"){
+ if ($real_path != "/") {
$p_dir = $real_path;
}
$dir = Application_Model_MusicDir::getDirByPath($p_dir);
@@ -405,6 +414,7 @@ class Application_Model_MusicDir {
$data = array();
$data["directory"] = $p_dir;
Application_Model_RabbitMq::SendMessageToMediaMonitor("remove_watch", $data);
+
return array("code"=>0);
}
}
@@ -413,7 +423,7 @@ class Application_Model_MusicDir {
{
$mus_dir = self::getWatchedDirFromFilepath($p_filepath);
- if(is_null($mus_dir)) {
+ if (is_null($mus_dir)) {
return null;
}
diff --git a/airtime_mvc/application/models/Playlist.php b/airtime_mvc/application/models/Playlist.php
index 86985b1b3..cabd17563 100644
--- a/airtime_mvc/application/models/Playlist.php
+++ b/airtime_mvc/application/models/Playlist.php
@@ -8,8 +8,8 @@ require_once 'formatters/LengthFormatter.php';
* @copyright 2010 Sourcefabric O.P.S.
* @license http://www.gnu.org/licenses/gpl.txt
*/
-class Application_Model_Playlist {
-
+class Application_Model_Playlist
+{
/**
* propel connection object.
*/
@@ -55,8 +55,7 @@ class Application_Model_Playlist {
if (is_null($this->pl)) {
throw new PlaylistNotFoundException();
}
- }
- else {
+ } else {
$this->pl = new CcPlaylist();
$this->pl->setDbUTime("now", new DateTimeZone("UTC"));
$this->pl->save();
@@ -79,7 +78,8 @@ class Application_Model_Playlist {
*
* @return int
*/
- public function getId() {
+ public function getId()
+ {
return $this->id;
}
@@ -117,28 +117,30 @@ class Application_Model_Playlist {
return $this->pl->getDbDescription();
}
- public function getCreator() {
-
+ public function getCreator()
+ {
return $this->pl->getCcSubjs()->getDbLogin();
}
- public function getCreatorId() {
+ public function getCreatorId()
+ {
return $this->pl->getCcSubjs()->getDbId();
}
- public function setCreator($p_id) {
-
+ public function setCreator($p_id)
+ {
$this->pl->setDbCreatorId($p_id);
$this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
$this->pl->save($this->con);
}
- public function getLastModified($format = null) {
+ public function getLastModified($format = null)
+ {
return $this->pl->getDbMtime($format);
}
- public function getSize() {
-
+ public function getSize()
+ {
return $this->pl->countCcPlaylistcontentss();
}
@@ -148,15 +150,15 @@ class Application_Model_Playlist {
* file_exists flag set to true
* @return array
*/
- public function getContents($filterFiles=false) {
-
+ public function getContents($filterFiles=false)
+ {
Logging::log("Getting contents for playlist {$this->id}");
$files = array();
$query = CcPlaylistcontentsQuery::create()
->filterByDbPlaylistId($this->id);
- if($filterFiles){
+ if ($filterFiles) {
$query->useCcFilesQuery()
->filterByDbFileExists(true)
->endUse();
@@ -193,8 +195,8 @@ class Application_Model_Playlist {
* 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.
**/
- public function normalizeFade($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);
@@ -211,12 +213,11 @@ class Application_Model_Playlist {
}
//aggregate column on playlistcontents cliplength column.
- public function getLength() {
-
+ public function getLength()
+ {
return $this->pl->getDbLength();
}
-
private function insertPlaylistElement($info)
{
$row = new CcPlaylistcontents();
@@ -246,8 +247,7 @@ class Application_Model_Playlist {
$entry["cueout"] = $file->getDbLength();
return $entry;
- }
- else {
+ } else {
throw new Exception("trying to add a file that does not exist.");
}
}
@@ -275,7 +275,6 @@ class Application_Model_Playlist {
Logging::log("index is {$index}");
$pos = ($addType == 'after') ? $index + 1 : $index;
-
$contentsToUpdate = CcPlaylistcontentsQuery::create()
->filterByDbPlaylistId($this->id)
->filterByDbPosition($pos, Criteria::GREATER_EQUAL)
@@ -284,8 +283,7 @@ class Application_Model_Playlist {
Logging::log("Adding to playlist");
Logging::log("at position {$pos}");
- }
- else {
+ } else {
//add to the end of the playlist
if ($addType == 'after') {
@@ -311,7 +309,7 @@ class Application_Model_Playlist {
Logging::log("at position {$pos}");
}
- foreach($p_items as $ac) {
+ foreach ($p_items as $ac) {
Logging::log("Adding audio file {$ac}");
$res = $this->insertPlaylistElement($this->buildEntry($ac, $pos));
@@ -329,8 +327,7 @@ class Application_Model_Playlist {
$this->pl->save($this->con);
$this->con->commit();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->con->rollback();
throw $e;
}
@@ -378,8 +375,7 @@ class Application_Model_Playlist {
$item->save($this->con);
$pos = $pos + 1;
}
- }
- else {
+ } else {
Logging::log("moving items after {$p_afterItem}");
foreach ($otherContent as $item) {
@@ -400,13 +396,11 @@ class Application_Model_Playlist {
}
$this->con->commit();
- }
- catch (Exception $e) {
+ } 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->save($this->con);
@@ -444,16 +438,14 @@ class Application_Model_Playlist {
$this->pl->save($this->con);
$this->con->commit();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->con->rollback();
throw $e;
}
}
-
- public function getFadeInfo($pos) {
-
+ public function getFadeInfo($pos)
+ {
Logging::log("Getting fade info for pos {$pos}");
$row = CcPlaylistcontentsQuery::create()
@@ -465,6 +457,7 @@ class Application_Model_Playlist {
#Propel returns values in form 00.000000 format which is for only seconds.
$fadeIn = $row->getDbFadein();
$fadeOut = $row->getDbFadeout();
+
return array($fadeIn, $fadeOut);
}
@@ -510,7 +503,7 @@ class Application_Model_Playlist {
}
$row->setDbFadein($fadeIn);
}
- if (!is_null($fadeOut)){
+ if (!is_null($fadeOut)) {
$sql = "SELECT INTERVAL '{$fadeOut}' > INTERVAL '{$clipLength}'";
$r = $this->con->query($sql);
@@ -526,8 +519,7 @@ class Application_Model_Playlist {
$this->pl->save($this->con);
$this->con->commit();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->con->rollback();
throw $e;
}
@@ -535,8 +527,8 @@ class Application_Model_Playlist {
return array("fadeIn" => $fadeIn, "fadeOut" => $fadeOut);
}
- public function setPlaylistfades($fadein, $fadeout) {
-
+ public function setPlaylistfades($fadein, $fadeout)
+ {
if (isset($fadein)) {
Logging::log("Setting playlist fade in {$fadein}");
$row = CcPlaylistcontentsQuery::create()
@@ -578,6 +570,7 @@ class Application_Model_Playlist {
try {
if (is_null($cueIn) && is_null($cueOut)) {
$errArray["error"] = "Cue in and cue out are null.";
+
return $errArray;
}
@@ -598,9 +591,9 @@ class Application_Model_Playlist {
$file = $row->getCcFiles($this->con);
$origLength = $file->getDbLength();
- if (!is_null($cueIn) && !is_null($cueOut)){
+ if (!is_null($cueIn) && !is_null($cueOut)) {
- if ($cueOut === ""){
+ if ($cueOut === "") {
$cueOut = $origLength;
}
@@ -608,13 +601,15 @@ class Application_Model_Playlist {
$r = $this->con->query($sql);
if ($r->fetchColumn(0)) {
$errArray["error"] = "Can't set cue in to be larger than cue out.";
+
return $errArray;
}
$sql = "SELECT INTERVAL '{$cueOut}' > INTERVAL '{$origLength}'";
$r = $this->con->query($sql);
- if ($r->fetchColumn(0)){
+ if ($r->fetchColumn(0)) {
$errArray["error"] = "Can't set cue out to be greater than file length.";
+
return $errArray;
}
@@ -626,13 +621,13 @@ class Application_Model_Playlist {
$row->setDbCueout($cueOut);
$row->setDBCliplength($cliplength);
- }
- else if (!is_null($cueIn)) {
+ } elseif (!is_null($cueIn)) {
$sql = "SELECT INTERVAL '{$cueIn}' > INTERVAL '{$oldCueOut}'";
$r = $this->con->query($sql);
if ($r->fetchColumn(0)) {
$errArray["error"] = "Can't set cue in to be larger than cue out.";
+
return $errArray;
}
@@ -642,10 +637,9 @@ class Application_Model_Playlist {
$row->setDbCuein($cueIn);
$row->setDBCliplength($cliplength);
- }
- else if (!is_null($cueOut)) {
+ } elseif (!is_null($cueOut)) {
- if ($cueOut === ""){
+ if ($cueOut === "") {
$cueOut = $origLength;
}
@@ -653,13 +647,15 @@ class Application_Model_Playlist {
$r = $this->con->query($sql);
if ($r->fetchColumn(0)) {
$errArray["error"] = "Can't set cue out to be smaller than cue in.";
+
return $errArray;
}
$sql = "SELECT INTERVAL '{$cueOut}' > INTERVAL '{$origLength}'";
$r = $this->con->query($sql);
- if ($r->fetchColumn(0)){
+ if ($r->fetchColumn(0)) {
$errArray["error"] = "Can't set cue out to be greater than file length.";
+
return $errArray;
}
@@ -675,14 +671,14 @@ class Application_Model_Playlist {
$sql = "SELECT INTERVAL '{$fadeIn}' > INTERVAL '{$cliplength}'";
$r = $this->con->query($sql);
- if ($r->fetchColumn(0)){
+ if ($r->fetchColumn(0)) {
$fadeIn = $cliplength;
$row->setDbFadein($fadeIn);
}
$sql = "SELECT INTERVAL '{$fadeOut}' > INTERVAL '{$cliplength}'";
$r = $this->con->query($sql);
- if ($r->fetchColumn(0)){
+ if ($r->fetchColumn(0)) {
$fadeOut = $cliplength;
$row->setDbFadein($fadeOut);
}
@@ -692,8 +688,7 @@ class Application_Model_Playlist {
$this->pl->save($this->con);
$this->con->commit();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->con->rollback();
throw $e;
}
@@ -707,7 +702,7 @@ class Application_Model_Playlist {
$categories = $this->categories;
$md = array();
- foreach($categories as $key => $val) {
+ foreach ($categories as $key => $val) {
$method = 'get' . $val;
$md[$key] = $this->$method();
}
@@ -719,6 +714,7 @@ class Application_Model_Playlist {
{
$cat = $this->categories[$category];
$method = 'get' . $cat;
+
return $this->$method();
}
@@ -749,6 +745,7 @@ class Application_Model_Playlist {
if (isset($arr[1])) {
return intval($arr[0])*60 + floatval($arr[1]);
}
+
return floatval($arr[0]);
}
@@ -758,7 +755,7 @@ class Application_Model_Playlist {
*
* Convert float seconds value to playlist time format
*
- * @param float $seconds
+ * @param float $seconds
* @return string
* interval in playlist time format (HH:mm:ss.d)
*/
@@ -766,9 +763,9 @@ class Application_Model_Playlist {
{
$info = explode('.', $p_seconds);
$seconds = $info[0];
- if(!isset($info[1])){
+ if (!isset($info[1])) {
$milliStr = 0;
- }else{
+ } else {
$milliStr = $info[1];
}
$hours = floor($seconds / 3600);
@@ -786,6 +783,7 @@ class Application_Model_Playlist {
global $CC_CONFIG;
$con = Propel::getConnection();
$sql = 'SELECT count(*) as cnt FROM '.$CC_CONFIG["playListTable"];
+
return $con->query($sql)->fetchColumn(0);
}
diff --git a/airtime_mvc/application/models/PlayoutHistory.php b/airtime_mvc/application/models/PlayoutHistory.php
index 6dad4bee3..c4a61a78c 100644
--- a/airtime_mvc/application/models/PlayoutHistory.php
+++ b/airtime_mvc/application/models/PlayoutHistory.php
@@ -2,16 +2,16 @@
require_once 'formatters/LengthFormatter.php';
-class Application_Model_PlayoutHistory {
-
+class Application_Model_PlayoutHistory
+{
private $con;
- private $timezone;
-
- //in UTC timezone
- private $startDT;
- //in UTC timezone
+ private $timezone;
+
+ //in UTC timezone
+ private $startDT;
+ //in UTC timezone
private $endDT;
-
+
private $epoch_now;
private $opts;
@@ -24,12 +24,12 @@ class Application_Model_PlayoutHistory {
"copyright" => "file.copyright",
);
- public function __construct($p_startDT, $p_endDT, $p_opts) {
-
+ public function __construct($p_startDT, $p_endDT, $p_opts)
+ {
$this->con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME);
- $this->startDT = $p_startDT;
- $this->endDT = $p_endDT;
- $this->timezone = date_default_timezone_get();
+ $this->startDT = $p_startDT;
+ $this->endDT = $p_endDT;
+ $this->timezone = date_default_timezone_get();
$this->epoch_now = time();
$this->opts = $p_opts;
}
@@ -37,16 +37,16 @@ class Application_Model_PlayoutHistory {
/*
* map front end mDataProp labels to proper column names for searching etc.
*/
- private function translateColumns() {
+ private function translateColumns()
+ {
+ for ($i = 0; $i < $this->opts["iColumns"]; $i++) {
- for ($i = 0; $i < $this->opts["iColumns"]; $i++){
-
- $this->opts["mDataProp_{$i}"] = $this->mDataPropMap[$this->opts["mDataProp_{$i}"]];
+ $this->opts["mDataProp_{$i}"] = $this->mDataPropMap[$this->opts["mDataProp_{$i}"]];
}
}
- public function getItems() {
-
+ public function getItems()
+ {
$this->translateColumns();
$select = array(
@@ -61,20 +61,20 @@ class Application_Model_PlayoutHistory {
$start = $this->startDT->format("Y-m-d H:i:s");
$end = $this->endDT->format("Y-m-d H:i:s");
-
- $historyTable = "(
- select count(schedule.file_id) as played, schedule.file_id as file_id
- from cc_schedule as schedule
+
+ $historyTable = "(
+ select count(schedule.file_id) as played, schedule.file_id as file_id
+ from cc_schedule as schedule
where schedule.starts >= '{$start}' and schedule.starts < '{$end}'
- and schedule.playout_status > 0 and schedule.media_item_played != FALSE and schedule.broadcasted = 1
- group by schedule.file_id
- )
+ and schedule.playout_status > 0 and schedule.media_item_played != FALSE and schedule.broadcasted = 1
+ group by schedule.file_id
+ )
AS playout left join cc_files as file on (file.id = playout.file_id)";
$results = Application_Model_Datatables::findEntries($this->con, $select, $historyTable, $this->opts, "history");
foreach ($results["history"] as &$row) {
- $formatter = new LengthFormatter($row['length']);
+ $formatter = new LengthFormatter($row['length']);
$row['length'] = $formatter->format();
}
diff --git a/airtime_mvc/application/models/Preference.php b/airtime_mvc/application/models/Preference.php
index 582058d7c..df3b1fdde 100644
--- a/airtime_mvc/application/models/Preference.php
+++ b/airtime_mvc/application/models/Preference.php
@@ -3,15 +3,15 @@
class Application_Model_Preference
{
- public static function setValue($key, $value, $isUserValue = false){
+ public static function setValue($key, $value, $isUserValue = false)
+ {
try {
$con = Propel::getConnection();
//called from a daemon process
- if(!class_exists("Zend_Auth", false) || !Zend_Auth::getInstance()->hasIdentity()) {
+ if (!class_exists("Zend_Auth", false) || !Zend_Auth::getInstance()->hasIdentity()) {
$id = NULL;
- }
- else {
+ } else {
$auth = Zend_Auth::getInstance();
$id = $auth->getIdentity()->id;
}
@@ -24,21 +24,21 @@ class Application_Model_Preference
." WHERE keystr = '$key'";
//For user specific preference, check if id matches as well
- if($isUserValue) {
+ if ($isUserValue) {
$sql .= " AND subjid = '$id'";
}
$result = $con->query($sql)->fetchColumn(0);
- if($value == "") {
+ if ($value == "") {
$value = "NULL";
- }else {
+ } else {
$value = "'$value'";
}
- if($result == 1) {
+ if ($result == 1) {
// result found
- if(is_null($id) || !$isUserValue) {
+ if (is_null($id) || !$isUserValue) {
// system pref
$sql = "UPDATE cc_pref"
." SET subjid = NULL, valstr = $value"
@@ -51,7 +51,7 @@ class Application_Model_Preference
}
} else {
// result not found
- if(is_null($id) || !$isUserValue) {
+ if (is_null($id) || !$isUserValue) {
// system pref
$sql = "INSERT INTO cc_pref (keystr, valstr)"
." VALUES ('$key', $value)";
@@ -64,7 +64,7 @@ class Application_Model_Preference
$con->exec($sql);
- } catch (Exception $e){
+ } catch (Exception $e) {
header('HTTP/1.0 503 Service Unavailable');
Logging::log("Could not connect to database: ".$e->getMessage());
exit;
@@ -72,7 +72,8 @@ class Application_Model_Preference
}
- public static function getValue($key, $isUserValue = false){
+ public static function getValue($key, $isUserValue = false)
+ {
try {
$con = Propel::getConnection();
@@ -82,24 +83,26 @@ class Application_Model_Preference
//For user specific preference, check if id matches as well
if ($isUserValue) {
$auth = Zend_Auth::getInstance();
- if($auth->hasIdentity()) {
+ if ($auth->hasIdentity()) {
$id = $auth->getIdentity()->id;
$sql .= " AND subjid = '$id'";
}
}
$result = $con->query($sql)->fetchColumn(0);
if ($result == 0)
+
return "";
else {
$sql = "SELECT valstr FROM cc_pref"
." WHERE keystr = '$key'";
//For user specific preference, check if id matches as well
- if($isUserValue && $auth->hasIdentity()) {
+ if ($isUserValue && $auth->hasIdentity()) {
$sql .= " AND subjid = '$id'";
}
$result = $con->query($sql)->fetchColumn(0);
+
return ($result !== false) ? $result : "";
}
} catch (Exception $e) {
@@ -109,7 +112,8 @@ class Application_Model_Preference
}
}
- public static function GetHeadTitle(){
+ public static function GetHeadTitle()
+ {
$title = self::getValue("station_name");
$defaultNamespace->title = $title;
if (strlen($title) > 0)
@@ -118,11 +122,12 @@ class Application_Model_Preference
return $title."Airtime";
}
- public static function SetHeadTitle($title, $view=null){
+ public static function SetHeadTitle($title, $view=null)
+ {
self::setValue("station_name", $title);
// in case this is called from airtime-saas script
- if($view !== null){
+ 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
@@ -142,7 +147,8 @@ class Application_Model_Preference
* @param DateTime $dateTime
* A row from cc_show_days table
*/
- public static function SetShowsPopulatedUntil($dateTime) {
+ public static function SetShowsPopulatedUntil($dateTime)
+ {
self::setValue("shows_populated_until", $dateTime->format("Y-m-d H:i:s"));
}
@@ -155,21 +161,24 @@ class Application_Model_Preference
*
* @return DateTime (in UTC Timezone)
*/
- public static function GetShowsPopulatedUntil() {
+ public static function GetShowsPopulatedUntil()
+ {
$date = self::getValue("shows_populated_until");
- if ($date == ""){
+ if ($date == "") {
return null;
} else {
return new DateTime($date, new DateTimeZone("UTC"));
}
}
- public static function SetDefaultFade($fade) {
+ public static function SetDefaultFade($fade)
+ {
self::setValue("default_fade", $fade);
}
- public static function GetDefaultFade() {
+ public static function GetDefaultFade()
+ {
$fade = self::getValue("default_fade");
if ($fade === "") {
@@ -179,7 +188,7 @@ class Application_Model_Preference
// we need this function to work with 2.0 version on default_fade value in cc_pref
// it has 00:00:00.000000 format where in 2.1 we have 00.000000 format
- if(preg_match("/([0-9]{2}):([0-9]{2}):([0-9]{2}).([0-9]{6})/", $fade, $matches) == 1 && count($matches) == 5){
+ if (preg_match("/([0-9]{2}):([0-9]{2}):([0-9]{2}).([0-9]{6})/", $fade, $matches) == 1 && count($matches) == 5) {
$out = 0;
$out += intval($matches[1] * 3600);
$out += intval($matches[2] * 60);
@@ -191,10 +200,12 @@ class Application_Model_Preference
$fade = number_format($fade, 6);
//fades need 2 leading zeros for DateTime conversion
$fade = str_pad($fade, 9, "0", STR_PAD_LEFT);
+
return $fade;
}
- public static function SetDefaultTransitionFade($fade) {
+ public static function SetDefaultTransitionFade($fade)
+ {
self::setValue("default_transition_fade", $fade);
$eventType = "update_transition_fade";
@@ -202,15 +213,18 @@ class Application_Model_Preference
Application_Model_RabbitMq::SendMessageToPypo($eventType, $md);
}
- public static function GetDefaultTransitionFade() {
+ public static function GetDefaultTransitionFade()
+ {
$transition_fade = self::getValue("default_transition_fade");
- if($transition_fade == ""){
+ if ($transition_fade == "") {
$transition_fade = "00.000000";
}
+
return $transition_fade;
}
- public static function SetStreamLabelFormat($type){
+ public static function SetStreamLabelFormat($type)
+ {
self::setValue("stream_label_format", $type);
$eventType = "update_stream_format";
@@ -219,179 +233,220 @@ class Application_Model_Preference
Application_Model_RabbitMq::SendMessageToPypo($eventType, $md);
}
- public static function GetStreamLabelFormat(){
+ public static function GetStreamLabelFormat()
+ {
return self::getValue("stream_label_format");
}
- public static function GetStationName(){
+ public static function GetStationName()
+ {
return self::getValue("station_name");
}
- public static function SetAutoUploadRecordedShowToSoundcloud($upload) {
+ public static function SetAutoUploadRecordedShowToSoundcloud($upload)
+ {
self::setValue("soundcloud_auto_upload_recorded_show", $upload);
}
- public static function GetAutoUploadRecordedShowToSoundcloud() {
+ public static function GetAutoUploadRecordedShowToSoundcloud()
+ {
return self::getValue("soundcloud_auto_upload_recorded_show");
}
- public static function SetSoundCloudUser($user) {
+ public static function SetSoundCloudUser($user)
+ {
self::setValue("soundcloud_user", $user);
}
- public static function GetSoundCloudUser() {
+ public static function GetSoundCloudUser()
+ {
return self::getValue("soundcloud_user");
}
- public static function SetSoundCloudPassword($password) {
+ public static function SetSoundCloudPassword($password)
+ {
if (strlen($password) > 0)
self::setValue("soundcloud_password", $password);
}
- public static function GetSoundCloudPassword() {
+ public static function GetSoundCloudPassword()
+ {
return self::getValue("soundcloud_password");
}
- public static function SetSoundCloudTags($tags) {
+ public static function SetSoundCloudTags($tags)
+ {
self::setValue("soundcloud_tags", $tags);
}
- public static function GetSoundCloudTags() {
+ public static function GetSoundCloudTags()
+ {
return self::getValue("soundcloud_tags");
}
- public static function SetSoundCloudGenre($genre) {
+ public static function SetSoundCloudGenre($genre)
+ {
self::setValue("soundcloud_genre", $genre);
}
- public static function GetSoundCloudGenre() {
+ public static function GetSoundCloudGenre()
+ {
return self::getValue("soundcloud_genre");
}
- public static function SetSoundCloudTrackType($track_type) {
+ public static function SetSoundCloudTrackType($track_type)
+ {
self::setValue("soundcloud_tracktype", $track_type);
}
- public static function GetSoundCloudTrackType() {
+ public static function GetSoundCloudTrackType()
+ {
return self::getValue("soundcloud_tracktype");
}
- public static function SetSoundCloudLicense($license) {
+ public static function SetSoundCloudLicense($license)
+ {
self::setValue("soundcloud_license", $license);
}
- public static function GetSoundCloudLicense() {
+ public static function GetSoundCloudLicense()
+ {
return self::getValue("soundcloud_license");
}
- public static function SetAllow3rdPartyApi($bool) {
+ public static function SetAllow3rdPartyApi($bool)
+ {
self::setValue("third_party_api", $bool);
}
- public static function GetAllow3rdPartyApi() {
+ public static function GetAllow3rdPartyApi()
+ {
$val = self::getValue("third_party_api");
- if (strlen($val) == 0){
+ if (strlen($val) == 0) {
return "0";
} else {
return $val;
}
}
- public static function SetPhone($phone){
+ public static function SetPhone($phone)
+ {
self::setValue("phone", $phone);
}
- public static function GetPhone(){
+ public static function GetPhone()
+ {
return self::getValue("phone");
}
- public static function SetEmail($email){
+ public static function SetEmail($email)
+ {
self::setValue("email", $email);
}
- public static function GetEmail(){
+ public static function GetEmail()
+ {
return self::getValue("email");
}
- public static function SetStationWebSite($site){
+ public static function SetStationWebSite($site)
+ {
self::setValue("station_website", $site);
}
- public static function GetStationWebSite(){
+ public static function GetStationWebSite()
+ {
return self::getValue("station_website");
}
- public static function SetSupportFeedback($feedback){
+ public static function SetSupportFeedback($feedback)
+ {
self::setValue("support_feedback", $feedback);
}
- public static function GetSupportFeedback(){
+ public static function GetSupportFeedback()
+ {
return self::getValue("support_feedback");
}
- public static function SetPublicise($publicise){
+ public static function SetPublicise($publicise)
+ {
self::setValue("publicise", $publicise);
}
- public static function GetPublicise(){
+ public static function GetPublicise()
+ {
return self::getValue("publicise");
}
- public static function SetRegistered($registered){
+ public static function SetRegistered($registered)
+ {
self::setValue("registered", $registered);
}
- public static function GetRegistered(){
+ public static function GetRegistered()
+ {
return self::getValue("registered");
}
- public static function SetStationCountry($country){
+ public static function SetStationCountry($country)
+ {
self::setValue("country", $country);
}
- public static function GetStationCountry(){
+ public static function GetStationCountry()
+ {
return self::getValue("country");
}
- public static function SetStationCity($city){
+ public static function SetStationCity($city)
+ {
self::setValue("city", $city);
}
- public static function GetStationCity(){
+ public static function GetStationCity()
+ {
return self::getValue("city");
}
- public static function SetStationDescription($description){
+ public static function SetStationDescription($description)
+ {
self::setValue("description", $description);
}
- public static function GetStationDescription(){
+ public static function GetStationDescription()
+ {
return self::getValue("description");
}
- public static function SetTimezone($timezone){
+ public static function SetTimezone($timezone)
+ {
self::setValue("timezone", $timezone);
date_default_timezone_set($timezone);
$md = array("timezone" => $timezone);
}
- public static function GetTimezone(){
+ public static function GetTimezone()
+ {
return self::getValue("timezone");
}
- public static function SetStationLogo($imagePath){
- if(!empty($imagePath)){
+ public static function SetStationLogo($imagePath)
+ {
+ if (!empty($imagePath)) {
$image = @file_get_contents($imagePath);
$image = base64_encode($image);
self::setValue("logoImage", $image);
}
}
- public static function GetStationLogo(){
+ public static function GetStationLogo()
+ {
return self::getValue("logoImage");
}
- public static function GetUniqueId(){
+ public static function GetUniqueId()
+ {
return self::getValue("uniqueId");
}
@@ -402,9 +457,10 @@ class Application_Model_Preference
$res = $con->query($sql)->fetchAll();
$out = array();
$out[""] = "Select Country";
- foreach($res as $r){
+ foreach ($res as $r) {
$out[$r["isocode"]] = $r["name"];
}
+
return $out;
}
@@ -414,20 +470,20 @@ class Application_Model_Preference
$output = preg_replace('/\s+/', ' ', $output);
$systemInfoArray = array();
- foreach( $output as $key => &$out){
+ foreach ($output as $key => &$out) {
$info = explode('=', $out);
- if(isset($info[1])){
+ 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 == 'AIRTIME_VERSION'){
+ $key == 'PLAYOUT_ENGINE_CPU_PERC') {
+ if ($key == 'AIRTIME_VERSION') {
// remove hash tag on the version string
$version = explode('+', $info[1]);
$systemInfoArray[$key] = $version[0];
- }else{
+ } else {
$systemInfoArray[$key] = $info[1];
}
}
@@ -453,7 +509,7 @@ class Application_Model_Preference
$outputArray['STATION_DESCRIPTION'] = self::GetStationDescription();
// get web server info
- if(isset($systemInfoArray["AIRTIME_VERSION_URL"])){
+ if (isset($systemInfoArray["AIRTIME_VERSION_URL"])) {
$url = $systemInfoArray["AIRTIME_VERSION_URL"];
$index = strpos($url,'/api/');
$url = substr($url, 0, $index);
@@ -481,206 +537,242 @@ class Application_Model_Preference
$outputArray = array_merge($systemInfoArray, $outputArray);
$outputString = "\n";
- foreach($outputArray as $key => $out){
- if($key == 'TRIAL_END_DATE' && ($out != '' || $out != 'NULL')){
+ foreach ($outputArray as $key => $out) {
+ if ($key == 'TRIAL_END_DATE' && ($out != '' || $out != 'NULL')) {
continue;
}
- if($key == "STREAM_INFO"){
+ if ($key == "STREAM_INFO") {
$outputString .= $key." :\n";
- foreach($out as $s_info){
- foreach($s_info as $k => $v){
+ foreach ($out as $s_info) {
+ foreach ($s_info as $k => $v) {
$outputString .= "\t".strtoupper($k)." : ".$v."\n";
}
}
- }else if ($key == "SOUNDCLOUD_ENABLED") {
+ } elseif ($key == "SOUNDCLOUD_ENABLED") {
if ($out) {
$outputString .= $key." : TRUE\n";
- } else if (!$out) {
+ } elseif (!$out) {
$outputString .= $key." : FALSE\n";
}
- }else if ($key == "SAAS") {
+ } elseif ($key == "SAAS") {
if (strcmp($out, 'disabled')!=0) {
$outputString .= $key.' : '.$out."\n";
}
- }else{
+ } else {
$outputString .= $key.' : '.$out."\n";
}
}
- if($returnArray){
+ if ($returnArray) {
$outputArray['PROMOTE'] = self::GetPublicise();
$outputArray['LOGOIMG'] = self::GetStationLogo();
+
return $outputArray;
- }else{
+ } else {
return $outputString;
}
}
- public static function GetInstallMethod(){
+ public static function GetInstallMethod()
+ {
$easy_install = file_exists('/usr/bin/airtime-easy-setup');
$debian_install = file_exists('/var/lib/dpkg/info/airtime.config');
- if($debian_install){
- if($easy_install){
+ if ($debian_install) {
+ if ($easy_install) {
return "easy_install";
- }else{
+ } else {
return "debian_install";
}
- }else{
+ } else {
return "manual_install";
}
}
- public static function SetRemindMeDate(){
+ public static function SetRemindMeDate()
+ {
$weekAfter = mktime(0, 0, 0, gmdate("m"), gmdate("d")+7, gmdate("Y"));
self::setValue("remindme", $weekAfter);
}
- public static function GetRemindMeDate(){
+ public static function GetRemindMeDate()
+ {
return self::getValue("remindme");
}
- public static function SetImportTimestamp(){
+ public static function SetImportTimestamp()
+ {
$now = time();
- if(self::GetImportTimestamp()+5 < $now){
+ if (self::GetImportTimestamp()+5 < $now) {
self::setValue("import_timestamp", $now);
}
}
- public static function GetImportTimestamp(){
+ public static function GetImportTimestamp()
+ {
return self::getValue("import_timestamp");
}
- public static function GetStreamType(){
+ public static function GetStreamType()
+ {
$st = self::getValue("stream_type");
+
return explode(',', $st);
}
- public static function GetStreamBitrate(){
+ public static function GetStreamBitrate()
+ {
$sb = self::getValue("stream_bitrate");
+
return explode(',', $sb);
}
- public static function SetPrivacyPolicyCheck($flag){
+ public static function SetPrivacyPolicyCheck($flag)
+ {
self::setValue("privacy_policy", $flag);
}
- public static function GetPrivacyPolicyCheck(){
+ public static function GetPrivacyPolicyCheck()
+ {
return self::getValue("privacy_policy");
}
- public static function SetNumOfStreams($num){
+ public static function SetNumOfStreams($num)
+ {
self::setValue("num_of_streams", intval($num));
}
- public static function GetNumOfStreams(){
+ public static function GetNumOfStreams()
+ {
return self::getValue("num_of_streams");
}
- public static function SetMaxBitrate($bitrate){
+ public static function SetMaxBitrate($bitrate)
+ {
self::setValue("max_bitrate", intval($bitrate));
}
- public static function GetMaxBitrate(){
+ public static function GetMaxBitrate()
+ {
return self::getValue("max_bitrate");
}
- public static function SetPlanLevel($plan){
+ public static function SetPlanLevel($plan)
+ {
self::setValue("plan_level", $plan);
}
- public static function GetPlanLevel(){
+ public static function GetPlanLevel()
+ {
$plan = self::getValue("plan_level");
- if(trim($plan) == ''){
+ if (trim($plan) == '') {
$plan = 'disabled';
}
+
return $plan;
}
- public static function SetTrialEndingDate($date){
+ public static function SetTrialEndingDate($date)
+ {
self::setValue("trial_end_date", $date);
}
- public static function GetTrialEndingDate(){
+ public static function GetTrialEndingDate()
+ {
return self::getValue("trial_end_date");
}
- public static function SetEnableStreamConf($bool){
+ public static function SetEnableStreamConf($bool)
+ {
self::setValue("enable_stream_conf", $bool);
}
- public static function GetEnableStreamConf(){
- if(self::getValue("enable_stream_conf") == Null){
+ public static function GetEnableStreamConf()
+ {
+ if (self::getValue("enable_stream_conf") == Null) {
return "true";
}
+
return self::getValue("enable_stream_conf");
}
- public static function GetAirtimeVersion(){
- if (defined('APPLICATION_ENV') && APPLICATION_ENV == "development" && function_exists('exec')){
+ public static function GetAirtimeVersion()
+ {
+ if (defined('APPLICATION_ENV') && APPLICATION_ENV == "development" && function_exists('exec')) {
$version = exec("git rev-parse --short HEAD 2>/dev/null", $out, $return_code);
- if ($return_code == 0){
+ if ($return_code == 0) {
return self::getValue("system_version")."+".$version.":".time();
}
}
+
return self::getValue("system_version");
}
- public static function GetLatestVersion(){
+ public static function GetLatestVersion()
+ {
$latest = self::getValue("latest_version");
- if($latest == null || strlen($latest) == 0) {
+ if ($latest == null || strlen($latest) == 0) {
return self::GetAirtimeVersion();
} else {
return $latest;
}
}
- public static function SetLatestVersion($version){
+ public static function SetLatestVersion($version)
+ {
$pattern = "/^[0-9]+\.[0-9]+\.[0-9]+/";
- if(preg_match($pattern, $version)) {
+ if (preg_match($pattern, $version)) {
self::setValue("latest_version", $version);
}
}
- public static function GetLatestLink(){
+ public static function GetLatestLink()
+ {
$link = self::getValue("latest_link");
- if($link == null || strlen($link) == 0) {
+ if ($link == null || strlen($link) == 0) {
return 'http://airtime.sourcefabric.org';
} else {
return $link;
}
}
- public static function SetLatestLink($link){
+ public static function SetLatestLink($link)
+ {
$pattern = "#^(http|https|ftp)://" .
"([a-zA-Z0-9]+\.)*[a-zA-Z0-9]+" .
"(/[a-zA-Z0-9\-\.\_\~\:\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=]+)*/?$#";
- if(preg_match($pattern, $link)) {
+ if (preg_match($pattern, $link)) {
self::setValue("latest_link", $link);
}
}
- public static function SetUploadToSoundcloudOption($upload) {
+ public static function SetUploadToSoundcloudOption($upload)
+ {
self::setValue("soundcloud_upload_option", $upload);
}
- public static function GetUploadToSoundcloudOption() {
+ public static function GetUploadToSoundcloudOption()
+ {
return self::getValue("soundcloud_upload_option");
}
- public static function SetSoundCloudDownloadbleOption($upload) {
+ public static function SetSoundCloudDownloadbleOption($upload)
+ {
self::setValue("soundcloud_downloadable", $upload);
}
- public static function GetSoundCloudDownloadbleOption() {
+ public static function GetSoundCloudDownloadbleOption()
+ {
return self::getValue("soundcloud_downloadable");
}
- public static function SetWeekStartDay($day) {
+ public static function SetWeekStartDay($day)
+ {
self::setValue("week_start_day", $day);
}
- public static function GetWeekStartDay() {
+ public static function GetWeekStartDay()
+ {
$val = self::getValue("week_start_day");
- if (strlen($val) == 0){
+ if (strlen($val) == 0) {
return "0";
} else {
return $val;
@@ -690,7 +782,8 @@ class Application_Model_Preference
/**
* Stores the last timestamp of user updating stream setting
*/
- public static function SetStreamUpdateTimestamp() {
+ public static function SetStreamUpdateTimestamp()
+ {
$now = time();
self::setValue("stream_update_timestamp", $now);
}
@@ -698,19 +791,23 @@ class Application_Model_Preference
/**
* Gets the last timestamp of user updating stream setting
*/
- public static function GetStreamUpdateTimestemp() {
+ public static function GetStreamUpdateTimestemp()
+ {
$update_time = self::getValue("stream_update_timestamp");
- if($update_time == null){
+ if ($update_time == null) {
$update_time = 0;
}
+
return $update_time;
}
- public static function GetClientId() {
+ public static function GetClientId()
+ {
return self::getValue("client_id");
}
- public static function SetClientId($id) {
+ public static function SetClientId($id)
+ {
if (is_numeric($id)) {
self::setValue("client_id", $id);
}
@@ -723,7 +820,8 @@ class Application_Model_Preference
*
* @param $timeScale new time scale
*/
- public static function SetCalendarTimeScale($timeScale) {
+ public static function SetCalendarTimeScale($timeScale)
+ {
self::setValue("calendar_time_scale", $timeScale, true /* user specific */);
}
@@ -731,11 +829,13 @@ class Application_Model_Preference
* Retrieves the time scale preference for the current user.
* Defaults to month if no entry exists
*/
- public static function GetCalendarTimeScale() {
+ public static function GetCalendarTimeScale()
+ {
$val = self::getValue("calendar_time_scale", true /* user specific */);
- if(strlen($val) == 0) {
+ if (strlen($val) == 0) {
$val = "month";
}
+
return $val;
}
@@ -744,7 +844,8 @@ class Application_Model_Preference
*
* @param $numEntries new number of entries to show
*/
- public static function SetLibraryNumEntries($numEntries) {
+ public static function SetLibraryNumEntries($numEntries)
+ {
self::setValue("library_num_entries", $numEntries, true /* user specific */);
}
@@ -752,11 +853,13 @@ class Application_Model_Preference
* Retrieves the number of entries to show preference in library under Playlist Builder.
* Defaults to 10 if no entry exists
*/
- public static function GetLibraryNumEntries() {
+ public static function GetLibraryNumEntries()
+ {
$val = self::getValue("library_num_entries", true /* user specific */);
- if(strlen($val) == 0) {
+ if (strlen($val) == 0) {
$val = "10";
}
+
return $val;
}
@@ -765,7 +868,8 @@ class Application_Model_Preference
*
* @param $timeInterval new time interval
*/
- public static function SetCalendarTimeInterval($timeInterval) {
+ public static function SetCalendarTimeInterval($timeInterval)
+ {
self::setValue("calendar_time_interval", $timeInterval, true /* user specific */);
}
@@ -773,187 +877,226 @@ class Application_Model_Preference
* Retrieves the time interval preference for the current user.
* Defaults to 30 min if no entry exists
*/
- public static function GetCalendarTimeInterval() {
+ public static function GetCalendarTimeInterval()
+ {
$val = self::getValue("calendar_time_interval", true /* user specific */);
- if(strlen($val) == 0) {
+ if (strlen($val) == 0) {
$val = "30";
}
+
return $val;
}
- public static function SetDiskQuota($value){
+ public static function SetDiskQuota($value)
+ {
self::setValue("disk_quota", $value, false);
}
- public static function GetDiskQuota(){
+ public static function GetDiskQuota()
+ {
$val = self::getValue("disk_quota");
- if(strlen($val) == 0) {
+ if (strlen($val) == 0) {
$val = "0";
}
+
return $val;
}
- public static function SetLiveSteamMasterUsername($value){
+ public static function SetLiveSteamMasterUsername($value)
+ {
self::setValue("live_stream_master_username", $value, false);
}
- public static function GetLiveSteamMasterUsername(){
+ public static function GetLiveSteamMasterUsername()
+ {
return self::getValue("live_stream_master_username");
}
- public static function SetLiveSteamMasterPassword($value){
+ public static function SetLiveSteamMasterPassword($value)
+ {
self::setValue("live_stream_master_password", $value, false);
}
- public static function GetLiveSteamMasterPassword(){
+ public static function GetLiveSteamMasterPassword()
+ {
return self::getValue("live_stream_master_password");
}
- public static function SetSourceStatus($sourcename, $status){
+ public static function SetSourceStatus($sourcename, $status)
+ {
self::setValue($sourcename, $status, false);
}
- public static function GetSourceStatus($sourcename){
+ public static function GetSourceStatus($sourcename)
+ {
$value = self::getValue($sourcename);
- if($value == null || $value == "false"){
+ if ($value == null || $value == "false") {
return false;
- }else{
+ } else {
return true;
}
}
- public static function SetSourceSwitchStatus($sourcename, $status){
+ public static function SetSourceSwitchStatus($sourcename, $status)
+ {
self::setValue($sourcename."_switch", $status, false);
}
- public static function GetSourceSwitchStatus($sourcename){
+ public static function GetSourceSwitchStatus($sourcename)
+ {
$value = self::getValue($sourcename."_switch");
- if($value == null || $value == "off"){
+ if ($value == null || $value == "off") {
return "off";
- }else{
+ } else {
return "on";
}
}
- public static function SetMasterDJSourceConnectionURL($value){
+ public static function SetMasterDJSourceConnectionURL($value)
+ {
self::setValue("master_dj_source_connection_url", $value, false);
}
- public static function GetMasterDJSourceConnectionURL(){
+ public static function GetMasterDJSourceConnectionURL()
+ {
return self::getValue("master_dj_source_connection_url");
}
- public static function SetLiveDJSourceConnectionURL($value){
+ public static function SetLiveDJSourceConnectionURL($value)
+ {
self::setValue("live_dj_source_connection_url", $value, false);
}
- public static function GetLiveDJSourceConnectionURL(){
+ public static function GetLiveDJSourceConnectionURL()
+ {
return self::getValue("live_dj_source_connection_url");
}
/* Source Connection URL override status starts */
- public static function GetLiveDjConnectionUrlOverride(){
+ public static function GetLiveDjConnectionUrlOverride()
+ {
return self::getValue("live_dj_connection_url_override");
}
- public static function SetLiveDjConnectionUrlOverride($value){
+ public static function SetLiveDjConnectionUrlOverride($value)
+ {
self::setValue("live_dj_connection_url_override", $value, false);
}
- public static function GetMasterDjConnectionUrlOverride(){
+ public static function GetMasterDjConnectionUrlOverride()
+ {
return self::getValue("master_dj_connection_url_override");
}
- public static function SetMasterDjConnectionUrlOverride($value){
+ public static function SetMasterDjConnectionUrlOverride($value)
+ {
self::setValue("master_dj_connection_url_override", $value, false);
}
/* Source Connection URL override status ends */
- public static function SetAutoTransition($value){
+ public static function SetAutoTransition($value)
+ {
self::setValue("auto_transition", $value, false);
}
- public static function GetAutoTransition(){
+ public static function GetAutoTransition()
+ {
return self::getValue("auto_transition");
}
- public static function SetAutoSwitch($value){
+ public static function SetAutoSwitch($value)
+ {
self::setValue("auto_switch", $value, false);
}
- public static function GetAutoSwitch(){
+ public static function GetAutoSwitch()
+ {
return self::getValue("auto_switch");
}
- public static function SetEnableSystemEmail($upload) {
- self::setValue("enable_system_email", $upload);
- }
-
- public static function GetEnableSystemEmail() {
+ public static function SetEnableSystemEmail($upload)
+ {
+ self::setValue("enable_system_email", $upload);
+ }
+
+ public static function GetEnableSystemEmail()
+ {
$v = self::getValue("enable_system_email");
if ($v === "") {
return 0;
}
- return $v;
+ return $v;
}
- public static function SetSystemEmail($value) {
- self::setValue("system_email", $value, false);
- }
-
- public static function GetSystemEmail() {
- return self::getValue("system_email");
+ public static function SetSystemEmail($value)
+ {
+ self::setValue("system_email", $value, false);
}
- public static function SetMailServerConfigured($value) {
+ public static function GetSystemEmail()
+ {
+ return self::getValue("system_email");
+ }
+
+ public static function SetMailServerConfigured($value)
+ {
self::setValue("mail_server_configured", $value, false);
}
- public static function GetMailServerConfigured() {
+ public static function GetMailServerConfigured()
+ {
return self::getValue("mail_server_configured");
}
- public static function SetMailServer($value) {
+ public static function SetMailServer($value)
+ {
self::setValue("mail_server", $value, false);
}
- public static function GetMailServer() {
+ public static function GetMailServer()
+ {
return self::getValue("mail_server");
}
- public static function SetMailServerEmailAddress($value) {
+ public static function SetMailServerEmailAddress($value)
+ {
self::setValue("mail_server_email_address", $value, false);
}
- public static function GetMailServerEmailAddress() {
+ public static function GetMailServerEmailAddress()
+ {
return self::getValue("mail_server_email_address");
}
- public static function SetMailServerPassword($value) {
+ public static function SetMailServerPassword($value)
+ {
self::setValue("mail_server_password", $value, false);
}
- public static function GetMailServerPassword() {
+ public static function GetMailServerPassword()
+ {
return self::getValue("mail_server_password");
}
- public static function SetMailServerPort($value) {
+ public static function SetMailServerPort($value)
+ {
self::setValue("mail_server_port", $value, false);
}
- public static function GetMailServerPort() {
+ public static function GetMailServerPort()
+ {
return self::getValue("mail_server_port");
}
/* User specific preferences end */
- public static function ShouldShowPopUp(){
- $today = mktime(0, 0, 0, gmdate("m"), gmdate("d"), gmdate("Y"));
- $remindDate = Application_Model_Preference::GetRemindMeDate();
- if($remindDate == NULL || $today >= $remindDate){
- return true;
- }
+ public static function ShouldShowPopUp()
+ {
+ $today = mktime(0, 0, 0, gmdate("m"), gmdate("d"), gmdate("Y"));
+ $remindDate = Application_Model_Preference::GetRemindMeDate();
+ if ($remindDate == NULL || $today >= $remindDate) {
+ return true;
+ }
}
}
-
diff --git a/airtime_mvc/application/models/RabbitMq.php b/airtime_mvc/application/models/RabbitMq.php
index 973cc34a2..c91342373 100644
--- a/airtime_mvc/application/models/RabbitMq.php
+++ b/airtime_mvc/application/models/RabbitMq.php
@@ -3,12 +3,13 @@ require_once 'php-amqplib/amqp.inc';
class Application_Model_RabbitMq
{
- static public $doPush = FALSE;
+ public static $doPush = FALSE;
/**
* Sets a flag to push the schedule at the end of the request.
*/
- public static function PushSchedule() {
+ public static function PushSchedule()
+ {
Application_Model_RabbitMq::$doPush = TRUE;
}
@@ -82,7 +83,7 @@ class Application_Model_RabbitMq
$temp['event_type'] = $event_type;
$temp['server_timezone'] = Application_Model_Preference::GetTimezone();
- if($event_type == "update_recorder_schedule"){
+ if ($event_type == "update_recorder_schedule") {
$temp['shows'] = Application_Model_Show::getShows($now, $end_timestamp, $excludeInstance=NULL, $onlyRecord=TRUE);
}
$data = json_encode($temp);
@@ -93,4 +94,3 @@ class Application_Model_RabbitMq
$conn->close();
}
}
-
diff --git a/airtime_mvc/application/models/Schedule.php b/airtime_mvc/application/models/Schedule.php
index be0f52238..91676bd09 100644
--- a/airtime_mvc/application/models/Schedule.php
+++ b/airtime_mvc/application/models/Schedule.php
@@ -1,7 +1,7 @@
$rows[$i]["show_ends"]){
+ if ($rows[$i]['ends'] > $rows[$i]["show_ends"]) {
$rows[$i]['ends'] = $rows[$i]["show_ends"];
}
- if ((strtotime($rows[$i]['starts']) <= $timeNowAsMillis) && (strtotime($rows[$i]['ends']) >= $timeNowAsMillis)){
- if ( $i - 1 >= 0){
+ if ((strtotime($rows[$i]['starts']) <= $timeNowAsMillis) && (strtotime($rows[$i]['ends']) >= $timeNowAsMillis)) {
+ if ($i - 1 >= 0) {
$results['previous'] = array("name"=>$rows[$i-1]["artist_name"]." - ".$rows[$i-1]["track_title"],
"starts"=>$rows[$i-1]["starts"],
"ends"=>$rows[$i-1]["ends"],
@@ -135,7 +135,7 @@ class Application_Model_Schedule {
"media_item_played"=>$rows[$i]["media_item_played"],
"record"=>0,
"type"=>'track');
- if ( isset($rows[$i+1])){
+ if ( isset($rows[$i+1])) {
$results['next'] = array("name"=>$rows[$i+1]["artist_name"]." - ".$rows[$i+1]["track_title"],
"starts"=>$rows[$i+1]["starts"],
"ends"=>$rows[$i+1]["ends"],
@@ -161,10 +161,12 @@ class Application_Model_Schedule {
"starts"=>$rows[$previousIndex]["starts"],
"ends"=>$rows[$previousIndex]["ends"]);;
}
+
return $results;
}
- public static function GetLastScheduleItem($p_timeNow){
+ public static function GetLastScheduleItem($p_timeNow)
+ {
global $CC_CONFIG;
$con = Propel::getConnection();
$sql = "SELECT"
@@ -182,11 +184,13 @@ class Application_Model_Schedule {
." LIMIT 1";
$row = $con->query($sql)->fetchAll();
+
return $row;
}
- public static function GetCurrentScheduleItem($p_timeNow, $p_instanceId){
+ public static function GetCurrentScheduleItem($p_timeNow, $p_instanceId)
+ {
global $CC_CONFIG;
$con = Propel::getConnection();
/* Note that usually there will be one result returned. In some
@@ -207,10 +211,12 @@ class Application_Model_Schedule {
." LIMIT 1";
$row = $con->query($sql)->fetchAll();
+
return $row;
}
- public static function GetNextScheduleItem($p_timeNow){
+ public static function GetNextScheduleItem($p_timeNow)
+ {
global $CC_CONFIG;
$con = Propel::getConnection();
$sql = "SELECT"
@@ -228,6 +234,7 @@ class Application_Model_Schedule {
." LIMIT 1";
$row = $con->query($sql)->fetchAll();
+
return $row;
}
@@ -273,7 +280,6 @@ class Application_Model_Schedule {
OR (si.ends > '{$p_start}' AND si.ends <= '{$p_end}')
OR (si.starts <= '{$p_start}' AND si.ends >= '{$p_end}'))";
-
if (count($p_shows) > 0) {
$sql .= " AND show_id IN (".implode(",", $p_shows).")";
}
@@ -283,6 +289,7 @@ class Application_Model_Schedule {
Logging::debug($sql);
$rows = $con->query($sql)->fetchAll();
+
return $rows;
}
@@ -298,17 +305,19 @@ class Application_Model_Schedule {
$master_dj = Application_Model_Preference::GetSourceSwitchStatus('master_dj') == 'on'?true:false;
$scheduled_play = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play') == 'on'?true:false;
- if(!$live_dj && !$master_dj && $scheduled_play){
+ if (!$live_dj && !$master_dj && $scheduled_play) {
$sql .= ", broadcasted=1";
}
$sql .= " WHERE id=$p_id";
$retVal = $con->exec($sql);
+
return $retVal;
}
- public static function UpdateBrodcastedStatus($dateTime, $value){
+ public static function UpdateBrodcastedStatus($dateTime, $value)
+ {
global $CC_CONFIG;
$con = Propel::getConnection();
$now = $dateTime->format("Y-m-d H:i:s");
@@ -316,6 +325,7 @@ class Application_Model_Schedule {
." SET broadcasted=$value"
." WHERE starts <= '$now' AND ends >= '$now'";
$retVal = $con->exec($sql);
+
return $retVal;
}
@@ -324,15 +334,15 @@ class Application_Model_Schedule {
global $CC_CONFIG;
$con = Propel::getConnection();
$sql = "SELECT count(*) as cnt FROM ".$CC_CONFIG['scheduleTable'];
+
return $con->query($sql)->fetchColumn(0);
}
-
/**
* 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)
@@ -340,6 +350,7 @@ class Application_Model_Schedule {
$p_time = substr($p_time, 0, 19);
$p_time = str_replace(" ", "-", $p_time);
$p_time = str_replace(":", "-", $p_time);
+
return $p_time;
}
@@ -347,19 +358,20 @@ class Application_Model_Schedule {
* 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);
+
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
*
- * @param string $p_time
+ * @param string $p_time
* @return boolean
*/
public static function ValidPypoTimeFormat($p_time)
@@ -373,6 +385,7 @@ class Application_Model_Schedule {
return false;
}
}
+
return true;
}
@@ -380,7 +393,7 @@ class Application_Model_Schedule {
* 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)
@@ -397,16 +410,16 @@ class Application_Model_Schedule {
$seconds = intval($t[2]);
}
$ret = $millisecs + ($seconds * 1000) + ($t[1] * 60 * 1000) + ($t[0] * 60 * 60 * 1000);
+
return $ret;
}
-
/**
* Compute the difference between two times in the format "HH:MM:SS.mmmmmm".
* Note: currently only supports calculating millisec differences.
*
- * @param string $p_time1
- * @param string $p_time2
+ * @param string $p_time1
+ * @param string $p_time2
* @return double
*/
private static function TimeDiff($p_time1, $p_time2)
@@ -423,6 +436,7 @@ class Application_Model_Schedule {
$millisec2 = intval($millisec2);
$diff = abs($millisec1 - $millisec2)/1000;
}
+
return $diff;
}
@@ -442,7 +456,8 @@ class Application_Model_Schedule {
* Returns null if nothing found, else an array of associative
* arrays representing each row.
*/
- public static function GetItems($p_startTime, $p_endTime) {
+ public static function GetItems($p_startTime, $p_endTime)
+ {
global $CC_CONFIG;
$con = Propel::getConnection();
@@ -464,7 +479,6 @@ class Application_Model_Schedule {
." LEFT JOIN $CC_CONFIG[filesTable] AS f"
." ON st.file_id = f.id";
-
$predicates = " WHERE st.ends > '$p_startTime'"
." AND st.starts < '$p_endTime'"
." AND st.playout_status > 0"
@@ -475,7 +489,7 @@ class Application_Model_Schedule {
$rows = $con->query($sql)->fetchAll();
- if (count($rows) < 3){
+ if (count($rows) < 3) {
Logging::debug("Get Schedule: Less than 3 results returned. Doing another query since we need a minimum of 3 results.");
$dt = new DateTime("@".time());
@@ -496,8 +510,8 @@ class Application_Model_Schedule {
return $rows;
}
- public static function GetScheduledPlaylists($p_fromDateTime = null, $p_toDateTime = null){
-
+ public static function GetScheduledPlaylists($p_fromDateTime = null, $p_toDateTime = null)
+ {
global $CC_CONFIG;
/* if $p_fromDateTime and $p_toDateTime function parameters are null, then set range
@@ -513,7 +527,7 @@ class Application_Model_Schedule {
$cache_ahead_hours = $CC_CONFIG["cache_ahead_hours"];
- if (is_numeric($cache_ahead_hours)){
+ if (is_numeric($cache_ahead_hours)) {
//make sure we are not dealing with a float
$cache_ahead_hours = intval($cache_ahead_hours);
} else {
@@ -536,7 +550,7 @@ class Application_Model_Schedule {
$data["media"] = array();
$kick_times = Application_Model_ShowInstance::GetEndTimeOfNextShowWithLiveDJ($range_start, $range_end);
- foreach($kick_times as $kick_time_info){
+ 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
@@ -552,7 +566,7 @@ class Application_Model_Schedule {
$data["media"][$kick_start]['event_type'] = "kick_out";
$data["media"][$kick_start]['type'] = "event";
- if($kick_time !== $switch_off_time){
+ if ($kick_time !== $switch_off_time) {
$switch_start = Application_Model_Schedule::AirtimeTimeToPypoTime($switch_off_time);
$data["media"][$switch_start]['start'] = $switch_start;
$data["media"][$switch_start]['end'] = $switch_start;
@@ -561,7 +575,7 @@ class Application_Model_Schedule {
}
}
- foreach ($items as $item){
+ foreach ($items as $item) {
$showInstance = CcShowInstancesQuery::create()->findPK($item["instance_id"]);
$showId = $showInstance->getDbShowId();
@@ -572,13 +586,13 @@ class Application_Model_Schedule {
$trackStartDateTime = new DateTime($item["start"], $utcTimeZone);
$trackEndDateTime = new DateTime($item["end"], $utcTimeZone);
- if ($trackStartDateTime->getTimestamp() > $showEndDateTime->getTimestamp()){
+ if ($trackStartDateTime->getTimestamp() > $showEndDateTime->getTimestamp()) {
continue;
}
/* Note: cue_out and end are always the same. */
/* TODO: Not all tracks will have "show_end" */
- if ($trackEndDateTime->getTimestamp() > $showEndDateTime->getTimestamp()){
+ if ($trackEndDateTime->getTimestamp() > $showEndDateTime->getTimestamp()) {
$di = $trackStartDateTime->diff($showEndDateTime);
$item["cue_out"] = $di->format("%H:%i:%s").".000";
@@ -601,7 +615,7 @@ class Application_Model_Schedule {
'start' => $start,
'end' => Application_Model_Schedule::AirtimeTimeToPypoTime($item["end"]),
'show_name' => $showName,
- 'replay_gain' => $item["replay_gain"]
+ 'replay_gain' => is_null($item["replay_gain"]) ? "0": $item["replay_gain"]
);
}
@@ -615,14 +629,16 @@ class Application_Model_Schedule {
$con->exec("TRUNCATE TABLE ".$CC_CONFIG["scheduleTable"]);
}
- public static function deleteWithFileId($fileId){
+ public static function deleteWithFileId($fileId)
+ {
global $CC_CONFIG;
$con = Propel::getConnection();
$sql = "DELETE FROM ".$CC_CONFIG["scheduleTable"]." WHERE file_id=$fileId";
$res = $con->query($sql);
}
- public static function createNewFormSections($p_view){
+ public static function createNewFormSections($p_view)
+ {
$isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true;
$formWhat = new Application_Form_AddShowWhat();
@@ -656,7 +672,7 @@ class Application_Model_Schedule {
$formRepeats->populate(array('add_show_end_date' => date("Y-m-d")));
- if(!$isSaas){
+ if (!$isSaas) {
$formRecord = new Application_Form_AddShowRR();
$formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates();
$formRebroadcast = new Application_Form_AddShowRebroadcastDates();
@@ -677,7 +693,8 @@ class Application_Model_Schedule {
* There is still lots of clean-up to do. For example we shouldn't be passing $controller into
* this method to manipulate the view (this should be done inside the controller function). With
* 2.1 deadline looming, this is OK for now. -Martin */
- public static function updateShowInstance($data, $controller){
+ public static function updateShowInstance($data, $controller)
+ {
$isSaas = (Application_Model_Preference::GetPlanLevel() != 'disabled');
$formWhat = new Application_Form_AddShowWhat();
@@ -694,7 +711,7 @@ class Application_Model_Schedule {
$formStyle->removeDecorator('DtDdWrapper');
$formLive->removeDecorator('DtDdWrapper');
- if(!$isSaas){
+ if (!$isSaas) {
$formRecord = new Application_Form_AddShowRR();
$formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates();
$formRebroadcast = new Application_Form_AddShowRebroadcastDates();
@@ -705,7 +722,7 @@ class Application_Model_Schedule {
}
$when = $formWhen->isValid($data);
- if($when && $formWhen->checkReliantFields($data, true, null, true)) {
+ if ($when && $formWhen->checkReliantFields($data, true, null, true)) {
$start_dt = new DateTime($data['add_show_start_date']." ".$data['add_show_start_time'], new DateTimeZone(date_default_timezone_get()));
$start_dt->setTimezone(new DateTimeZone('UTC'));
@@ -734,7 +751,7 @@ class Application_Model_Schedule {
$controller->view->who = $formWho;
$controller->view->style = $formStyle;
$controller->view->live = $formLive;
- if(!$isSaas){
+ if (!$isSaas) {
$controller->view->rr = $formRecord;
$controller->view->absoluteRebroadcast = $formAbsoluteRebroadcast;
$controller->view->rebroadcast = $formRebroadcast;
@@ -743,6 +760,7 @@ class Application_Model_Schedule {
//$formAbsoluteRebroadcast->disable();
//$formRebroadcast->disable();
}
+
return false;
}
}
@@ -755,8 +773,8 @@ class Application_Model_Schedule {
* Another clean-up is to move all the form manipulation to the proper form class.....
* -Martin
*/
- public static function addUpdateShow($data, $controller, $validateStartDate, $originalStartDate=null, $update=false, $instanceId=null){
-
+ public static function addUpdateShow($data, $controller, $validateStartDate, $originalStartDate=null, $update=false, $instanceId=null)
+ {
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id);
$isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
@@ -781,7 +799,7 @@ class Application_Model_Schedule {
$what = $formWhat->isValid($data);
$when = $formWhen->isValid($data);
$live = $formLive->isValid($data);
- if($when) {
+ if ($when) {
$when = $formWhen->checkReliantFields($data, $validateStartDate, $originalStartDate, $update, $instanceId);
}
@@ -797,17 +815,17 @@ class Application_Model_Schedule {
$hValue = 0;
$mValue = 0;
- if($hPos !== false){
+ if ($hPos !== false) {
$hValue = trim(substr($data["add_show_duration"], 0, $hPos));
}
- if($mPos !== false){
+ if ($mPos !== false) {
$hPos = $hPos === FALSE ? 0 : $hPos+1;
$mValue = trim(substr($data["add_show_duration"], $hPos, -1 ));
}
$data["add_show_duration"] = $hValue.":".$mValue;
- if(!$isSaas){
+ if (!$isSaas) {
$formRecord = new Application_Form_AddShowRR();
$formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates();
$formRebroadcast = new Application_Form_AddShowRebroadcastDates();
@@ -820,19 +838,19 @@ class Application_Model_Schedule {
$record = $formRecord->isValid($data);
}
- if($data["add_show_repeats"]) {
+ if ($data["add_show_repeats"]) {
$repeats = $formRepeats->isValid($data);
- if($repeats) {
+ if ($repeats) {
$repeats = $formRepeats->checkReliantFields($data);
}
- if(!$isSaas){
+ if (!$isSaas) {
$formAbsoluteRebroadcast->reset();
//make it valid, results don't matter anyways.
$rebroadAb = 1;
if ($data["add_show_rebroadcast"]) {
$rebroad = $formRebroadcast->isValid($data);
- if($rebroad) {
+ if ($rebroad) {
$rebroad = $formRebroadcast->checkReliantFields($data);
}
} else {
@@ -841,14 +859,14 @@ class Application_Model_Schedule {
}
} else {
$repeats = 1;
- if(!$isSaas){
+ if (!$isSaas) {
$formRebroadcast->reset();
//make it valid, results don't matter anyways.
$rebroad = 1;
if ($data["add_show_rebroadcast"]) {
$rebroadAb = $formAbsoluteRebroadcast->isValid($data);
- if($rebroadAb) {
+ if ($rebroadAb) {
$rebroadAb = $formAbsoluteRebroadcast->checkReliantFields($data);
}
} else {
@@ -860,8 +878,8 @@ class Application_Model_Schedule {
$who = $formWho->isValid($data);
$style = $formStyle->isValid($data);
if ($what && $when && $repeats && $who && $style && $live) {
- if(!$isSaas){
- if($record && $rebroadAb && $rebroad){
+ if (!$isSaas) {
+ if ($record && $rebroadAb && $rebroad) {
if ($isAdminOrPM) {
Application_Model_Show::create($data);
}
@@ -906,7 +924,7 @@ class Application_Model_Schedule {
$controller->view->style = $formStyle;
$controller->view->live = $formLive;
- if(!$isSaas){
+ if (!$isSaas) {
$controller->view->rr = $formRecord;
$controller->view->absoluteRebroadcast = $formAbsoluteRebroadcast;
$controller->view->rebroadcast = $formRebroadcast;
@@ -917,7 +935,8 @@ class Application_Model_Schedule {
}
}
- public static function checkOverlappingShows($show_start, $show_end, $update=false, $instanceId=null) {
+ public static function checkOverlappingShows($show_start, $show_end, $update=false, $instanceId=null)
+ {
global $CC_CONFIG;
$overlapping = false;
@@ -934,7 +953,7 @@ class Application_Model_Schedule {
}
$rows = $con->query($sql);
- foreach($rows as $row) {
+ foreach ($rows as $row) {
$start = new DateTime($row["starts"], new DateTimeZone('UTC'));
$end = new DateTime($row["ends"], new DateTimeZone('UTC'));
@@ -944,6 +963,7 @@ class Application_Model_Schedule {
break;
}
}
+
return $overlapping;
}
}
diff --git a/airtime_mvc/application/models/Scheduler.php b/airtime_mvc/application/models/Scheduler.php
index 6e8e21278..692d2ad44 100644
--- a/airtime_mvc/application/models/Scheduler.php
+++ b/airtime_mvc/application/models/Scheduler.php
@@ -1,7 +1,7 @@
"",
@@ -19,14 +19,14 @@ class Application_Model_Scheduler {
private $checkUserPermissions = true;
- public function __construct() {
-
+ public function __construct()
+ {
$this->con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME);
$this->epochNow = microtime(true);
$this->nowDT = DateTime::createFromFormat("U.u", $this->epochNow, new DateTimeZone("UTC"));
- if ($this->nowDT === false){
+ 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"));
@@ -35,18 +35,18 @@ class Application_Model_Scheduler {
$this->user = Application_Model_User::getCurrentUser();
}
- public function setCheckUserPermissions($value) {
+ public function setCheckUserPermissions($value)
+ {
$this->checkUserPermissions = $value;
}
-
- /*
- * make sure any incoming requests for scheduling are ligit.
- *
- * @param array $items, an array containing pks of cc_schedule items.
- */
- private function validateRequest($items) {
-
+ /*
+ * make sure any incoming requests for scheduling are ligit.
+ *
+ * @param array $items, an array containing pks of cc_schedule items.
+ */
+ private function validateRequest($items)
+ {
$nowEpoch = floatval($this->nowDT->format("U.u"));
for ($i = 0; $i < count($items); $i++) {
@@ -57,7 +57,7 @@ class Application_Model_Scheduler {
$schedInfo[$id] = $items[$i]["instance"];
}
- $instanceInfo[$items[$i]["instance"]] = $items[$i]["timestamp"];
+ $instanceInfo[$items[$i]["instance"]] = $items[$i]["timestamp"];
}
if (count($instanceInfo) === 0) {
@@ -73,21 +73,21 @@ class Application_Model_Scheduler {
$showInstances = CcShowInstancesQuery::create()->findPKs($instanceIds, $this->con);
//an item has been deleted
- if (count($schedIds) !== count($schedItems)) {
- throw new OutDatedScheduleException("The schedule you're viewing is out of date! (sched mismatch)");
+ if (count($schedIds) !== count($schedItems)) {
+ throw new OutDatedScheduleException("The schedule you're viewing is out of date! (sched mismatch)");
}
- //a show has been deleted
- if (count($instanceIds) !== count($showInstances)) {
- throw new OutDatedScheduleException("The schedule you're viewing is out of date! (instance mismatch)");
+ //a show has been deleted
+ if (count($instanceIds) !== count($showInstances)) {
+ throw new OutDatedScheduleException("The schedule you're viewing is out of date! (instance mismatch)");
}
foreach ($schedItems as $schedItem) {
$id = $schedItem->getDbId();
$instance = $schedItem->getCcShowInstances($this->con);
- if (intval($schedInfo[$id]) !== $instance->getDbId()) {
- throw new OutDatedScheduleException("The schedule you're viewing is out of date!");
+ if (intval($schedInfo[$id]) !== $instance->getDbId()) {
+ throw new OutDatedScheduleException("The schedule you're viewing is out of date!");
}
}
@@ -96,23 +96,23 @@ class Application_Model_Scheduler {
$id = $instance->getDbId();
$show = $instance->getCcShow($this->con);
- if ($this->checkUserPermissions && $this->user->canSchedule($show->getDbId()) === false) {
- throw new Exception("You are not allowed to schedule show {$show->getDbName()}.");
+ if ($this->checkUserPermissions && $this->user->canSchedule($show->getDbId()) === false) {
+ throw new Exception("You are not allowed to schedule show {$show->getDbName()}.");
}
- $showEndEpoch = floatval($instance->getDbEnds("U.u"));
-
- if ($showEndEpoch < $nowEpoch) {
- throw new OutDatedScheduleException("The show {$show->getDbName()} is over and cannot be scheduled.");
+ $showEndEpoch = floatval($instance->getDbEnds("U.u"));
+
+ if ($showEndEpoch < $nowEpoch) {
+ throw new OutDatedScheduleException("The show {$show->getDbName()} is over and cannot be scheduled.");
}
$ts = intval($instanceInfo[$id]);
- $lastSchedTs = intval($instance->getDbLastScheduled("U")) ? : 0;
+ $lastSchedTs = intval($instance->getDbLastScheduled("U")) ? : 0;
if ($ts < $lastSchedTs) {
- Logging::log("ts {$ts} last sched {$lastSchedTs}");
- throw new OutDatedScheduleException("The show {$show->getDbName()} has been previously updated!");
+ Logging::log("ts {$ts} last sched {$lastSchedTs}");
+ throw new OutDatedScheduleException("The show {$show->getDbName()} has been previously updated!");
}
- }
+ }
}
/*
@@ -121,8 +121,8 @@ class Application_Model_Scheduler {
*
* @return $files
*/
- private function retrieveMediaFiles($id, $type) {
-
+ private function retrieveMediaFiles($id, $type)
+ {
$files = array();
if ($type === "audioclip") {
@@ -130,8 +130,7 @@ class Application_Model_Scheduler {
if (is_null($file) || !$file->getDbFileExists()) {
throw new Exception("A selected File does not exist!");
- }
- else {
+ } else {
$data = $this->fileInfo;
$data["id"] = $id;
$data["cliplength"] = $file->getDbLength();
@@ -146,8 +145,7 @@ class Application_Model_Scheduler {
$files[] = $data;
}
- }
- else if ($type === "playlist") {
+ } elseif ($type === "playlist") {
$contents = CcPlaylistcontentsQuery::create()
->orderByDbPosition()
@@ -186,8 +184,8 @@ class Application_Model_Scheduler {
*
* @return DateTime endDT in UTC
*/
- private function findEndTime($p_startDT, $p_duration) {
-
+ private function findEndTime($p_startDT, $p_duration)
+ {
$startEpoch = $p_startDT->format("U.u");
$durationSeconds = Application_Model_Playlist::playlistTimeToSeconds($p_duration);
@@ -205,70 +203,68 @@ class Application_Model_Scheduler {
return $dt;
}
- private function findNextStartTime($DT, $instance) {
-
- $sEpoch = $DT->format("U.u");
+ private function findNextStartTime($DT, $instance)
+ {
+ $sEpoch = $DT->format("U.u");
$nEpoch = $this->epochNow;
-
- //check for if the show has started.
- if (bccomp( $nEpoch , $sEpoch , 6) === 1) {
- //need some kind of placeholder for cc_schedule.
- //playout_status will be -1.
+
+ //check for if the show has started.
+ if (bccomp( $nEpoch , $sEpoch , 6) === 1) {
+ //need some kind of placeholder for cc_schedule.
+ //playout_status will be -1.
$nextDT = $this->nowDT;
- $length = bcsub($nEpoch , $sEpoch , 6);
- $cliplength = Application_Model_Playlist::secondsToPlaylistTime($length);
-
- //fillers are for only storing a chunk of time space that has already passed.
- $filler = new CcSchedule();
- $filler->setDbStarts($DT)
- ->setDbEnds($this->nowDT)
- ->setDbClipLength($cliplength)
- ->setDbPlayoutStatus(-1)
- ->setDbInstanceId($instance->getDbId())
- ->save($this->con);
- }
- else {
- $nextDT = $DT;
+ $length = bcsub($nEpoch , $sEpoch , 6);
+ $cliplength = Application_Model_Playlist::secondsToPlaylistTime($length);
+
+ //fillers are for only storing a chunk of time space that has already passed.
+ $filler = new CcSchedule();
+ $filler->setDbStarts($DT)
+ ->setDbEnds($this->nowDT)
+ ->setDbClipLength($cliplength)
+ ->setDbPlayoutStatus(-1)
+ ->setDbInstanceId($instance->getDbId())
+ ->save($this->con);
+ } else {
+ $nextDT = $DT;
}
return $nextDT;
}
- /*
- * @param int $showInstance
- * @param array $exclude
- * ids of sched items to remove from the calulation.
- */
- private function removeGaps($showInstance, $exclude=null) {
-
- Logging::log("removing gaps from show instance #".$showInstance);
-
- $instance = CcShowInstancesQuery::create()->findPK($showInstance, $this->con);
- if (is_null($instance)) {
- throw new OutDatedScheduleException("The schedule you're viewing is out of date!");
- }
-
- $itemStartDT = $instance->getDbStarts(null);
-
- $schedule = CcScheduleQuery::create()
- ->filterByDbInstanceId($showInstance)
- ->filterByDbId($exclude, Criteria::NOT_IN)
- ->orderByDbStarts()
- ->find($this->con);
-
-
- foreach ($schedule as $item) {
-
- $itemEndDT = $this->findEndTime($itemStartDT, $item->getDbClipLength());
-
- $item->setDbStarts($itemStartDT)
- ->setDbEnds($itemEndDT);
-
- $itemStartDT = $itemEndDT;
+ /*
+ * @param int $showInstance
+ * @param array $exclude
+ * ids of sched items to remove from the calulation.
+ */
+ private function removeGaps($showInstance, $exclude=null)
+ {
+ Logging::log("removing gaps from show instance #".$showInstance);
+
+ $instance = CcShowInstancesQuery::create()->findPK($showInstance, $this->con);
+ if (is_null($instance)) {
+ throw new OutDatedScheduleException("The schedule you're viewing is out of date!");
}
- $schedule->save($this->con);
+ $itemStartDT = $instance->getDbStarts(null);
+
+ $schedule = CcScheduleQuery::create()
+ ->filterByDbInstanceId($showInstance)
+ ->filterByDbId($exclude, Criteria::NOT_IN)
+ ->orderByDbStarts()
+ ->find($this->con);
+
+ foreach ($schedule as $item) {
+
+ $itemEndDT = $this->findEndTime($itemStartDT, $item->getDbClipLength());
+
+ $item->setDbStarts($itemStartDT)
+ ->setDbEnds($itemEndDT);
+
+ $itemStartDT = $itemEndDT;
+ }
+
+ $schedule->save($this->con);
}
/*
@@ -276,8 +272,8 @@ class Application_Model_Scheduler {
* @param array $fileIds
* @param array $playlistIds
*/
- private function insertAfter($scheduleItems, $schedFiles, $adjustSched = true) {
-
+ private function insertAfter($scheduleItems, $schedFiles, $adjustSched = true)
+ {
try {
$affectedShowInstances = array();
@@ -326,12 +322,12 @@ class Application_Model_Scheduler {
->orderByDbStarts()
->find($this->con);
- $pend = microtime(true);
- Logging::debug("finding all following items.");
+ $pend = microtime(true);
+ Logging::debug("finding all following items.");
Logging::debug(floatval($pend) - floatval($pstart));
}
- foreach($schedFiles as $file) {
+ foreach ($schedFiles as $file) {
$endTimeDT = $this->findEndTime($nextStartDT, $file['cliplength']);
@@ -339,8 +335,7 @@ class Application_Model_Scheduler {
//need to keep same id for resources if we want REST.
if (isset($file['sched_id'])) {
$sched = CcScheduleQuery::create()->findPK($file['sched_id'], $this->con);
- }
- else {
+ } else {
$sched = new CcSchedule();
}
Logging::log(print_r($file,true));
@@ -374,13 +369,13 @@ class Application_Model_Scheduler {
}
$pend = microtime(true);
- Logging::debug("adjusting all following items.");
+ Logging::debug("adjusting all following items.");
Logging::debug(floatval($pend) - floatval($pstart));
}
}
- $endProfile = microtime(true);
- Logging::debug("finished adding scheduled items.");
+ $endProfile = microtime(true);
+ Logging::debug("finished adding scheduled items.");
Logging::debug(floatval($endProfile) - floatval($startProfile));
//update the status flag in cc_schedule.
@@ -394,8 +389,8 @@ class Application_Model_Scheduler {
$instance->updateScheduleStatus($this->con);
}
- $endProfile = microtime(true);
- Logging::debug("updating show instances status.");
+ $endProfile = microtime(true);
+ Logging::debug("updating show instances status.");
Logging::debug(floatval($endProfile) - floatval($startProfile));
$startProfile = microtime(true);
@@ -405,11 +400,10 @@ class Application_Model_Scheduler {
->filterByPrimaryKeys($affectedShowInstances)
->update(array('DbLastScheduled' => new DateTime("now", new DateTimeZone("UTC"))), $this->con);
- $endProfile = microtime(true);
- Logging::debug("updating last scheduled timestamp.");
+ $endProfile = microtime(true);
+ Logging::debug("updating last scheduled timestamp.");
Logging::debug(floatval($endProfile) - floatval($startProfile));
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
Logging::debug($e->getMessage());
throw $e;
}
@@ -419,8 +413,8 @@ class Application_Model_Scheduler {
* @param array $scheduleItems
* @param array $mediaItems
*/
- public function scheduleAfter($scheduleItems, $mediaItems, $adjustSched = true) {
-
+ public function scheduleAfter($scheduleItems, $mediaItems, $adjustSched = true)
+ {
$this->con->beginTransaction();
$schedFiles = array();
@@ -437,8 +431,7 @@ class Application_Model_Scheduler {
$this->con->commit();
Application_Model_RabbitMq::PushSchedule();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->con->rollback();
throw $e;
}
@@ -448,8 +441,8 @@ class Application_Model_Scheduler {
* @param array $selectedItem
* @param array $afterItem
*/
- public function moveItem($selectedItems, $afterItems, $adjustSched = true) {
-
+ public function moveItem($selectedItems, $afterItems, $adjustSched = true)
+ {
$startProfile = microtime(true);
$this->con->beginTransaction();
@@ -460,11 +453,11 @@ class Application_Model_Scheduler {
$this->validateRequest($selectedItems);
$this->validateRequest($afterItems);
- $endProfile = microtime(true);
- Logging::debug("validating move request took:");
+ $endProfile = microtime(true);
+ 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();
@@ -473,16 +466,16 @@ class Application_Model_Scheduler {
//prepare each of the selected items.
for ($i = 0; $i < count($selectedItems); $i++) {
- $selected = CcScheduleQuery::create()->findPk($selectedItems[$i]["id"], $this->con);
- $selectedInstance = $selected->getCcShowInstances($this->con);
+ $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 = $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();
$movedData[] = $data;
@@ -492,8 +485,7 @@ class Application_Model_Scheduler {
$schedId = $selected->getDbId();
if (isset($modifiedMap[$showInstanceId])) {
array_push($modifiedMap[$showInstanceId], $schedId);
- }
- else {
+ } else {
$modifiedMap[$showInstanceId] = array($schedId);
}
}
@@ -504,8 +496,8 @@ class Application_Model_Scheduler {
$this->removeGaps($instance, $schedIds);
- $endProfile = microtime(true);
- Logging::debug("removing gaps from instance $instance:");
+ $endProfile = microtime(true);
+ Logging::debug("removing gaps from instance $instance:");
Logging::debug(floatval($endProfile) - floatval($startProfile));
}
@@ -513,14 +505,14 @@ class Application_Model_Scheduler {
$this->insertAfter($afterItems, $movedData, $adjustSched);
- $endProfile = microtime(true);
- Logging::debug("inserting after removing gaps.");
+ $endProfile = microtime(true);
+ Logging::debug("inserting after removing gaps.");
Logging::debug(floatval($endProfile) - floatval($startProfile));
- $afterInstanceId = $afterInstance->getDbId();
+ $afterInstanceId = $afterInstance->getDbId();
$modified = array_keys($modifiedMap);
//need to adjust shows we have moved items from.
- foreach($modified as $instanceId) {
+ foreach ($modified as $instanceId) {
$instance = CcShowInstancesQuery::create()->findPK($instanceId, $this->con);
$instance->updateScheduleStatus($this->con);
@@ -530,15 +522,14 @@ class Application_Model_Scheduler {
$this->con->commit();
Application_Model_RabbitMq::PushSchedule();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->con->rollback();
throw $e;
}
}
- public function removeItems($scheduledItems, $adjustSched = true) {
-
+ public function removeItems($scheduledItems, $adjustSched = true)
+ {
$showInstances = array();
$this->con->beginTransaction();
@@ -564,7 +555,7 @@ class Application_Model_Scheduler {
$nEpoch = $this->epochNow;
$sEpoch = $removedItem->getDbStarts('U.u');
- $length = bcsub($nEpoch , $sEpoch , 6);
+ $length = bcsub($nEpoch , $sEpoch , 6);
$cliplength = Application_Model_Playlist::secondsToPlaylistTime($length);
$cueinSec = Application_Model_Playlist::playlistTimeToSeconds($removedItem->getDbCueIn());
@@ -575,8 +566,7 @@ class Application_Model_Scheduler {
->setDbClipLength($cliplength)
->setDbEnds($this->nowDT)
->save($this->con);
- }
- else {
+ } else {
$removedItem->delete($this->con);
}
}
@@ -613,8 +603,7 @@ class Application_Model_Scheduler {
$this->con->commit();
Application_Model_RabbitMq::PushSchedule();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->con->rollback();
throw $e;
}
@@ -625,8 +614,8 @@ class Application_Model_Scheduler {
*
* @param $p_id id of the show instance to cancel.
*/
- public function cancelShow($p_id) {
-
+ public function cancelShow($p_id)
+ {
$this->con->beginTransaction();
try {
@@ -635,28 +624,27 @@ class Application_Model_Scheduler {
if (!$instance->getDbRecord()) {
- $items = CcScheduleQuery::create()
- ->filterByDbInstanceId($p_id)
- ->filterByDbEnds($this->nowDT, Criteria::GREATER_THAN)
- ->find($this->con);
+ $items = CcScheduleQuery::create()
+ ->filterByDbInstanceId($p_id)
+ ->filterByDbEnds($this->nowDT, Criteria::GREATER_THAN)
+ ->find($this->con);
if (count($items) > 0) {
- $remove = array();
- $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();
- }
-
+ $remove = array();
+ $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();
+ }
+
$this->removeItems($remove, false);
}
- }
- else {
+ } else {
$rebroadcasts = $instance->getCcShowInstancessRelatedByDbId(null, $this->con);
$rebroadcasts->delete($this->con);
- }
+ }
$instance->setDbEnds($this->nowDT);
$instance->save($this->con);
@@ -666,10 +654,9 @@ class Application_Model_Scheduler {
if ($instance->getDbRecord()) {
Application_Model_RabbitMq::SendMessageToShowRecorder("cancel_recording");
}
- }
- catch (Exception $e) {
- $this->con->rollback();
- throw $e;
+ } catch (Exception $e) {
+ $this->con->rollback();
+ throw $e;
}
}
}
diff --git a/airtime_mvc/application/models/ServiceRegister.php b/airtime_mvc/application/models/ServiceRegister.php
index a0ef4f3eb..84a2feefb 100644
--- a/airtime_mvc/application/models/ServiceRegister.php
+++ b/airtime_mvc/application/models/ServiceRegister.php
@@ -1,11 +1,11 @@
findOneByDbName($p_componentName);
- if ($component == NULL){
+ if ($component == NULL) {
$component = new CcServiceRegister();
$component->setDbName($p_componentName);
}
@@ -14,7 +14,7 @@ class Application_Model_ServiceRegister {
// to allow access via an ipv6 address.
// http://[::1]:2812 does not respond.
// Bug: http://savannah.nongnu.org/bugs/?27608
- if ($p_ipAddress == "::1"){
+ if ($p_ipAddress == "::1") {
$p_ipAddress = "127.0.0.1";
}
diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php
index 53bf8bab4..947077378 100644
--- a/airtime_mvc/application/models/Show.php
+++ b/airtime_mvc/application/models/Show.php
@@ -1,7 +1,7 @@
findPK($this->_showId);
+
return $show->getDbName();
}
@@ -22,25 +23,29 @@ class Application_Model_Show {
Application_Model_RabbitMq::PushSchedule();
}
- public function setAirtimeAuthFlag($flag){
+ public function setAirtimeAuthFlag($flag)
+ {
$show = CcShowQuery::create()->findPK($this->_showId);
$show->setDbLiveStreamUsingAirtimeAuth($flag);
$show->save();
}
- public function setCustomAuthFlag($flag){
+ public function setCustomAuthFlag($flag)
+ {
$show = CcShowQuery::create()->findPK($this->_showId);
$show->setDbLiveStreamUsingCustomAuth($flag);
$show->save();
}
- public function setCustomUsername($username){
+ public function setCustomUsername($username)
+ {
$show = CcShowQuery::create()->findPK($this->_showId);
$show->setDbLiveStreamUser($username);
$show->save();
}
- public function setCustomPassword($password){
+ public function setCustomPassword($password)
+ {
$show = CcShowQuery::create()->findPK($this->_showId);
$show->setDbLiveStreamPass($password);
$show->save();
@@ -49,6 +54,7 @@ class Application_Model_Show {
public function getDescription()
{
$show = CcShowQuery::create()->findPK($this->_showId);
+
return $show->getDbDescription();
}
@@ -61,6 +67,7 @@ class Application_Model_Show {
public function getColor()
{
$show = CcShowQuery::create()->findPK($this->_showId);
+
return $show->getDbColor();
}
@@ -73,6 +80,7 @@ class Application_Model_Show {
public function getUrl()
{
$show = CcShowQuery::create()->findPK($this->_showId);
+
return $show->getDbUrl();
}
@@ -85,6 +93,7 @@ class Application_Model_Show {
public function getGenre()
{
$show = CcShowQuery::create()->findPK($this->_showId);
+
return $show->getDbGenre();
}
@@ -97,6 +106,7 @@ class Application_Model_Show {
public function getBackgroundColor()
{
$show = CcShowQuery::create()->findPK($this->_showId);
+
return $show->getDbBackgroundColor();
}
@@ -113,7 +123,7 @@ class Application_Model_Show {
public function getHosts()
{
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
$sql = "SELECT first_name, last_name
FROM cc_show_hosts LEFT JOIN cc_subjs ON cc_show_hosts.subjs_id = cc_subjs.id
@@ -131,7 +141,7 @@ class Application_Model_Show {
public function getHostsIds()
{
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
$sql = "SELECT subjs_id
FROM cc_show_hosts
@@ -157,7 +167,7 @@ class Application_Model_Show {
public function resizeShow($deltaDay, $deltaMin)
{
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
if ($deltaDay > 0) {
return "Shows can have a max length of 24 hours.";
@@ -166,8 +176,7 @@ class Application_Model_Show {
$hours = $deltaMin/60;
if ($hours > 0) {
$hours = floor($hours);
- }
- else {
+ } else {
$hours = ceil($hours);
}
@@ -205,8 +214,7 @@ class Application_Model_Show {
}
$con->commit();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$con->rollback();
Logging::log("Couldn't update schedule status.");
Logging::log($e->getMessage());
@@ -217,7 +225,7 @@ class Application_Model_Show {
public function cancelShow($day_timestamp)
{
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
$timeinfo = explode(" ", $day_timestamp);
@@ -237,7 +245,7 @@ class Application_Model_Show {
->filterByDbModifiedInstance(false)
->findOne();
- if(is_null($showInstancesRow)){
+ if (is_null($showInstancesRow)) {
$sql = "DELETE FROM cc_show WHERE id = {$this->_showId}";
$con->exec($sql);
}
@@ -260,7 +268,7 @@ class Application_Model_Show {
*/
public function removeUncheckedDaysInstances($p_uncheckedDays)
{
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
//need to convert local doftw to UTC doftw (change made for 2.0 since shows are stored in UTC)
$daysRemovedUTC = array();
@@ -270,11 +278,11 @@ class Application_Model_Show {
->find();
Logging::log("Unchecked days:");
- foreach($p_uncheckedDays as $day) {
+ foreach ($p_uncheckedDays as $day) {
Logging::log($day);
}
- foreach($showDays as $showDay) {
+ foreach ($showDays as $showDay) {
//Logging::log("Local show day is: {$showDay->getDbDay()}");
//Logging::log("First show day is: {$showDay->getDbFirstShow()}");
//Logging::log("Id show days is: {$showDay->getDbId()}");
@@ -313,7 +321,8 @@ class Application_Model_Show {
* @return boolean
* true if originated from recording, otherwise false.
*/
- public function isRecorded(){
+ public function isRecorded()
+ {
$showInstancesRow = CcShowInstancesQuery::create()
->filterByDbShowId($this->getId())
->filterByDbRecord(1)
@@ -351,7 +360,7 @@ class Application_Model_Show {
*/
public function getRebroadcastsAbsolute()
{
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
$showId = $this->getId();
@@ -389,7 +398,7 @@ class Application_Model_Show {
*/
public function getRebroadcastsRelative()
{
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
$showId = $this->getId();
$sql = "SELECT day_offset, start_time FROM cc_show_rebroadcast "
@@ -412,10 +421,9 @@ class Application_Model_Show {
->filterByDbShowId($this->_showId)
->findOne();
- if (!is_null($showDaysRow)){
+ if (!is_null($showDaysRow)) {
return ($showDaysRow->getDbRepeatType() != -1);
- }
- else {
+ } else {
return false;
}
}
@@ -434,9 +442,10 @@ class Application_Model_Show {
->filterByDbShowId($this->_showId)
->findOne();
- if (!is_null($showDaysRow)){
+ if (!is_null($showDaysRow)) {
return $showDaysRow->getDbRepeatType();
} else
+
return -1;
}
@@ -449,7 +458,7 @@ class Application_Model_Show {
*/
public function getRepeatingEndDate()
{
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
$showId = $this->getId();
$sql = "SELECT last_show FROM cc_show_days"
@@ -457,6 +466,7 @@ class Application_Model_Show {
." ORDER BY last_show DESC";
$query = $con->query($sql)->fetchColumn(0);
+
return ($query !== false) ? $query : "";
}
@@ -470,8 +480,9 @@ class Application_Model_Show {
* it cause any scheduled playlists within those show instances to
* be gone for good.
*/
- public function deleteAllInstances(){
- $con = Propel::getConnection();
+ public function deleteAllInstances()
+ {
+ $con = Propel::getConnection();
$timestamp = gmdate("Y-m-d H:i:s");
@@ -487,8 +498,9 @@ class Application_Model_Show {
* Deletes all future rebroadcast instances of the current
* show object from the show_instances table.
*/
- public function deleteAllRebroadcasts(){
- $con = Propel::getConnection();
+ public function deleteAllRebroadcasts()
+ {
+ $con = Propel::getConnection();
$timestamp = gmdate("Y-m-d H:i:s");
@@ -510,12 +522,13 @@ class Application_Model_Show {
* @param string $p_date
* The date which to delete after, if null deletes from the current timestamp.
*/
- public function removeAllInstancesFromDate($p_date=null){
- $con = Propel::getConnection();
+ public function removeAllInstancesFromDate($p_date=null)
+ {
+ $con = Propel::getConnection();
$timestamp = gmdate("Y-m-d H:i:s");
- if(is_null($p_date)) {
+ if (is_null($p_date)) {
$date = new Application_Common_DateHelper;
$p_date = $date->getDate();
}
@@ -542,8 +555,9 @@ class Application_Model_Show {
* @param string $p_date
* The date which to delete before
*/
- public function removeAllInstancesBeforeDate($p_date){
- $con = Propel::getConnection();
+ public function removeAllInstancesBeforeDate($p_date)
+ {
+ $con = Propel::getConnection();
$timestamp = gmdate("Y-m-d H:i:s");
@@ -562,7 +576,8 @@ class Application_Model_Show {
* @return string
* The start date in the format YYYY-MM-DD
*/
- public function getStartDateAndTime(){
+ public function getStartDateAndTime()
+ {
$con = Propel::getConnection();
$showId = $this->getId();
@@ -573,7 +588,7 @@ class Application_Model_Show {
$query = $con->query($sql);
- if ($query->rowCount() == 0){
+ if ($query->rowCount() == 0) {
return "";
} else {
$rows = $query->fetchAll();
@@ -581,6 +596,7 @@ class Application_Model_Show {
$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");
}
}
@@ -591,8 +607,10 @@ class Application_Model_Show {
* @return string
* The start date in the format YYYY-MM-DD
*/
- public function getStartDate(){
+ public function getStartDate()
+ {
list($date,) = explode(" ", $this->getStartDateAndTime());
+
return $date;
}
@@ -603,8 +621,10 @@ class Application_Model_Show {
* The start time in the format HH:MM
*/
- public function getStartTime(){
+ public function getStartTime()
+ {
list(,$time) = explode(" ", $this->getStartDateAndTime());
+
return $time;
}
@@ -615,7 +635,8 @@ class Application_Model_Show {
* @return string
* The end date in the format YYYY-MM-DD
*/
- public function getEndDate(){
+ public function getEndDate()
+ {
$startDate = $this->getStartDate();
$startTime = $this->getStartTime();
$duration = $this->getDuration();
@@ -634,7 +655,8 @@ class Application_Model_Show {
* @return string
* The start time in the format HH:MM:SS
*/
- public function getEndTime(){
+ public function getEndTime()
+ {
$startDate = $this->getStartDate();
$startTime = $this->getStartTime();
$duration = $this->getDuration();
@@ -654,9 +676,11 @@ class Application_Model_Show {
* @return boolean
* true if the StartDate is in the past, false otherwise
*/
- public function isStartDateTimeInPast(){
+ public function isStartDateTimeInPast()
+ {
$date = new Application_Common_DateHelper;
$current_timestamp = $date->getUtcTimestamp();
+
return ($current_timestamp > ($this->getStartDate()." ".$this->getStartTime()));
}
@@ -667,8 +691,9 @@ class Application_Model_Show {
* A simple array containing all ID's of show instance
* scheduled in the future.
*/
- public function getAllFutureInstanceIds(){
- $con = Propel::getConnection();
+ public function getAllFutureInstanceIds()
+ {
+ $con = Propel::getConnection();
$date = new Application_Common_DateHelper;
$timestamp = $date->getTimestamp();
@@ -685,6 +710,7 @@ class Application_Model_Show {
foreach ($rows as $row) {
$instance_ids[] = $row["id"];
}
+
return $instance_ids;
}
@@ -695,9 +721,10 @@ class Application_Model_Show {
* browser.
*
*/
- private function updateDurationTime($p_data){
+ private function updateDurationTime($p_data)
+ {
//need to update cc_show_instances, cc_show_days
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
$date = new Application_Common_DateHelper;
$timestamp = $date->getUtcTimestamp();
@@ -713,12 +740,12 @@ class Application_Model_Show {
."AND ends > TIMESTAMP '$timestamp'";
$con->exec($sql);
-
}
- private function updateStartDateTime($p_data, $p_endDate){
+ private function updateStartDateTime($p_data, $p_endDate)
+ {
//need to update cc_schedule, cc_show_instances, cc_show_days
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
$date = new Application_Common_DateHelper;
$timestamp = $date->getTimestamp();
@@ -727,7 +754,7 @@ class Application_Model_Show {
$sql = "UPDATE cc_show_days "
."SET start_time = TIME '$p_data[add_show_start_time]', "
."first_show = DATE '$p_data[add_show_start_date]', ";
- if (strlen ($p_endDate) == 0){
+ if (strlen ($p_endDate) == 0) {
$sql .= "last_show = NULL ";
} else {
$sql .= "last_show = DATE '$p_endDate' ";
@@ -747,7 +774,7 @@ class Application_Model_Show {
$con->exec($sql);
$showInstanceIds = $this->getAllFutureInstanceIds();
- if (count($showInstanceIds) > 0 && $diff != 0){
+ if (count($showInstanceIds) > 0 && $diff != 0) {
$showIdsImploded = implode(",", $showInstanceIds);
$sql = "UPDATE cc_schedule "
."SET starts = starts + INTERVAL '$diff sec', "
@@ -757,21 +784,24 @@ class Application_Model_Show {
}
}
- public function getDuration($format=false){
+ public function getDuration($format=false)
+ {
$showDay = CcShowDaysQuery::create()->filterByDbShowId($this->getId())->findOne();
- if(!$format){
+ if (!$format) {
return $showDay->getDbDuration();
- }else{
+ } 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';
}
}
- public function getShowDays(){
+ public function getShowDays()
+ {
$showDays = CcShowDaysQuery::create()->filterByDbShowId($this->getId())->find();
$days = array();
- foreach ($showDays as $showDay){
+ foreach ($showDays as $showDay) {
array_push($days, $showDay->getDbDay());
}
@@ -781,7 +811,8 @@ class Application_Model_Show {
/* Only used for shows that aren't repeating.
*
* @return Boolean: true if show has an instance, otherwise false. */
- public function hasInstance(){
+ public function hasInstance()
+ {
return (!is_null($this->getInstance()));
}
@@ -789,7 +820,8 @@ class Application_Model_Show {
*
* @return CcShowInstancesQuery: An propel object representing a
* row in the cc_show_instances table. */
- public function getInstance(){
+ public function getInstance()
+ {
$showInstance = CcShowInstancesQuery::create()
->filterByDbShowId($this->getId())
->findOne();
@@ -800,17 +832,19 @@ class Application_Model_Show {
/**
* returns info about live stream override info
*/
- public function getLiveStreamInfo(){
+ public function getLiveStreamInfo()
+ {
$info = array();
- if($this->_showId == null){
+ if ($this->_showId == null) {
return $info;
- }else{
+ } 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;
}
}
@@ -825,11 +859,11 @@ class Application_Model_Show {
*
* @return Boolean: true if show has an instance on $p_dateTime,
* otherwise false. */
- public function hasInstanceOnDate($p_dateTime){
+ public function hasInstanceOnDate($p_dateTime)
+ {
return (!is_null($this->getInstanceOnDate($p_dateTime)));
}
-
/* Only used for shows that are repeating. Note that this will return
* shows that have been "modified" (does not check if the "modified_instance"
* column is set to true). This is intended behaviour.
@@ -838,7 +872,8 @@ class Application_Model_Show {
*
* @return CcShowInstancesQuery: An propel object representing a
* row in the cc_show_instances table. */
- public function getInstanceOnDate($p_dateTime){
+ public function getInstanceOnDate($p_dateTime)
+ {
$con = Propel::getConnection();
$timestamp = $p_dateTime->format("Y-m-d H:i:s");
@@ -850,23 +885,24 @@ class Application_Model_Show {
$query = $con->query($sql);
$row = ($query !== false) ? $query->fetchColumn(0) : null;
+
return CcShowInstancesQuery::create()
->findPk($row);
}
public function deletePossiblyInvalidInstances($p_data, $p_endDate, $isRecorded, $repeatType)
{
- if ($p_data['add_show_repeats'] != $this->isRepeating()){
+ if ($p_data['add_show_repeats'] != $this->isRepeating()) {
//repeat option was toggled
$this->deleteAllInstances();
}
- if ($p_data['add_show_duration'] != $this->getDuration()){
+ if ($p_data['add_show_duration'] != $this->getDuration()) {
//duration has changed
$this->updateDurationTime($p_data);
}
- if ($p_data['add_show_repeats']){
+ if ($p_data['add_show_repeats']) {
if (($repeatType == 1 || $repeatType == 2) &&
$p_data['add_show_start_date'] != $this->getStartDate()){
@@ -877,28 +913,27 @@ class Application_Model_Show {
$this->deleteAllInstances();
}
- if ($repeatType != $this->getRepeatType()){
+ if ($repeatType != $this->getRepeatType()) {
//repeat type changed.
$this->deleteAllInstances();
} else {
//repeat type is the same, check if the days of the week are the same
$repeatingDaysChanged = false;
$showDaysArray = $this->getShowDays();
- if (count($p_data['add_show_day_check']) == count($showDaysArray)){
+ if (count($p_data['add_show_day_check']) == count($showDaysArray)) {
//same number of days checked, lets see if they are the same numbers
$intersect = array_intersect($p_data['add_show_day_check'], $showDaysArray);
- if (count($intersect) != count($p_data['add_show_day_check'])){
+ if (count($intersect) != count($p_data['add_show_day_check'])) {
$repeatingDaysChanged = true;
}
- }
- else {
+ } else {
$repeatingDaysChanged = true;
}
- if ($repeatingDaysChanged){
+ if ($repeatingDaysChanged) {
$daysRemoved = array_diff($showDaysArray, $p_data['add_show_day_check']);
- if (count($daysRemoved) > 0){
+ if (count($daysRemoved) > 0) {
$this->removeUncheckedDaysInstances($daysRemoved);
}
@@ -910,7 +945,7 @@ class Application_Model_Show {
$newDate = strtotime($p_data['add_show_start_date']);
$oldDate = strtotime($this->getStartDate());
- if ($newDate > $oldDate){
+ if ($newDate > $oldDate) {
$this->removeAllInstancesBeforeDate($p_data['add_show_start_date']);
}
@@ -920,20 +955,19 @@ class Application_Model_Show {
//Check if end date for the repeat option has changed. If so, need to take care
//of deleting possible invalid Show Instances.
- if ((strlen($this->getRepeatingEndDate()) == 0) == $p_data['add_show_no_end']){
+ if ((strlen($this->getRepeatingEndDate()) == 0) == $p_data['add_show_no_end']) {
//show "Never Ends" option was toggled.
- if ($p_data['add_show_no_end']){
- }
- else {
+ if ($p_data['add_show_no_end']) {
+ } else {
$this->removeAllInstancesFromDate($p_endDate);
}
}
- if ($this->getRepeatingEndDate() != $p_data['add_show_end_date']){
+ if ($this->getRepeatingEndDate() != $p_data['add_show_end_date']) {
//end date was changed.
$newDate = strtotime($p_data['add_show_end_date']);
$oldDate = strtotime($this->getRepeatingEndDate());
- if ($newDate < $oldDate){
+ if ($newDate < $oldDate) {
$this->removeAllInstancesFromDate($p_endDate);
}
}
@@ -945,7 +979,7 @@ class Application_Model_Show {
*
* Note: end dates are non inclusive.
*
- * @param array $data
+ * @param array $data
* @return int
* Show ID
*/
@@ -957,14 +991,12 @@ class Application_Model_Show {
if ($data['add_show_no_end']) {
$endDate = NULL;
- }
- else if ($data['add_show_repeats']) {
+ } elseif ($data['add_show_repeats']) {
$endDateTime = new DateTime($data['add_show_end_date']);
//$endDateTime->setTimezone(new DateTimeZone('UTC'));
$endDateTime->add(new DateInterval("P1D"));
$endDate = $endDateTime->format("Y-m-d");
- }
- else {
+ } else {
$endDateTime = new DateTime($data['add_show_start_date']);
//$endDateTime->setTimezone(new DateTimeZone('UTC'));
$endDateTime->add(new DateInterval("P1D"));
@@ -978,14 +1010,14 @@ class Application_Model_Show {
$startDow = date("w", $startDateTime->getTimestamp());
if (!$data['add_show_repeats']) {
$data['add_show_day_check'] = array($startDow);
- } else if ($data['add_show_repeats'] && $data['add_show_day_check'] == "") {
+ } elseif ($data['add_show_repeats'] && $data['add_show_day_check'] == "") {
$data['add_show_day_check'] = array($startDow);
}
//find repeat type or set to a non repeating show.
$repeatType = ($data['add_show_repeats']) ? $data['add_show_repeat_type'] : -1;
- if ($data['add_show_id'] == -1){
+ if ($data['add_show_id'] == -1) {
$ccShow = new CcShow();
} else {
$ccShow = CcShowQuery::create()->findPK($data['add_show_id']);
@@ -1006,19 +1038,19 @@ class Application_Model_Show {
$isRecorded = (isset($data['add_show_record']) && $data['add_show_record']) ? 1 : 0;
- if ($data['add_show_id'] != -1){
+ if ($data['add_show_id'] != -1) {
$show = new Application_Model_Show($showId);
$show->deletePossiblyInvalidInstances($data, $endDate, $isRecorded, $repeatType);
}
//check if we are adding or updating a show, and if updating
//erase all the show's show_days information first.
- if ($data['add_show_id'] != -1){
+ if ($data['add_show_id'] != -1) {
CcShowDaysQuery::create()->filterByDbShowId($data['add_show_id'])->delete();
}
//don't set day for monthly repeat type, it's invalid.
- if ($data['add_show_repeats'] && $data['add_show_repeat_type'] == 2){
+ if ($data['add_show_repeats'] && $data['add_show_repeat_type'] == 2) {
$showDay = new CcShowDays();
$showDay->setDbFirstShow($startDateTime->format("Y-m-d"));
$showDay->setDbLastShow($endDate);
@@ -1033,7 +1065,7 @@ class Application_Model_Show {
foreach ($data['add_show_day_check'] as $day) {
$daysAdd=0;
$startDateTimeClone = clone $startDateTime;
- if ($startDow !== $day){
+ if ($startDow !== $day) {
if ($startDow > $day)
$daysAdd = 6 - $startDow + 1 + $day;
else
@@ -1059,7 +1091,7 @@ class Application_Model_Show {
//check if we are adding or updating a show, and if updating
//erase all the show's future show_rebroadcast information first.
- if (($data['add_show_id'] != -1) && isset($data['add_show_rebroadcast']) && $data['add_show_rebroadcast']){
+ if (($data['add_show_id'] != -1) && isset($data['add_show_rebroadcast']) && $data['add_show_rebroadcast']) {
CcShowRebroadcastQuery::create()
->filterByDbShowId($data['add_show_id'])
->delete();
@@ -1075,8 +1107,7 @@ class Application_Model_Show {
$showRebroad->save();
}
}
- }
- else if ($isRecorded && $data['add_show_rebroadcast'] && ($repeatType == -1)){
+ } elseif ($isRecorded && $data['add_show_rebroadcast'] && ($repeatType == -1)) {
for ($i=1; $i<=10; $i++) {
if ($data['add_show_rebroadcast_date_absolute_'.$i]) {
$con = Propel::getConnection(CcShowPeer::DATABASE_NAME);
@@ -1095,7 +1126,7 @@ class Application_Model_Show {
//check if we are adding or updating a show, and if updating
//erase all the show's show_rebroadcast information first.
- if ($data['add_show_id'] != -1){
+ if ($data['add_show_id'] != -1) {
CcShowHostsQuery::create()->filterByDbShow($data['add_show_id'])->delete();
}
if (is_array($data['add_show_hosts'])) {
@@ -1127,8 +1158,7 @@ class Application_Model_Show {
}
$con->commit();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$con->rollback();
Logging::log("Couldn't update schedule status.");
Logging::log($e->getMessage());
@@ -1137,6 +1167,7 @@ class Application_Model_Show {
Application_Model_Show::populateShowUntil($showId);
Application_Model_RabbitMq::PushSchedule();
+
return $showId;
}
@@ -1178,17 +1209,15 @@ class Application_Model_Show {
* @param DateTime $p_populateUntilDateTime
* DateTime object in UTC time.
*/
- private static function populateShow($p_showDaysRow, $p_populateUntilDateTime) {
- if($p_showDaysRow["repeat_type"] == -1) {
+ private static function populateShow($p_showDaysRow, $p_populateUntilDateTime)
+ {
+ if ($p_showDaysRow["repeat_type"] == -1) {
Application_Model_Show::populateNonRepeatingShow($p_showDaysRow, $p_populateUntilDateTime);
- }
- else if($p_showDaysRow["repeat_type"] == 0) {
+ } elseif ($p_showDaysRow["repeat_type"] == 0) {
Application_Model_Show::populateRepeatingShow($p_showDaysRow, $p_populateUntilDateTime, 'P7D');
- }
- else if($p_showDaysRow["repeat_type"] == 1) {
+ } elseif ($p_showDaysRow["repeat_type"] == 1) {
Application_Model_Show::populateRepeatingShow($p_showDaysRow, $p_populateUntilDateTime, 'P14D');
- }
- else if($p_showDaysRow["repeat_type"] == 2) {
+ } elseif ($p_showDaysRow["repeat_type"] == 2) {
Application_Model_Show::populateRepeatingShow($p_showDaysRow, $p_populateUntilDateTime, 'P1M');
}
Application_Model_RabbitMq::PushSchedule();
@@ -1205,7 +1234,7 @@ class Application_Model_Show {
*/
private static function populateNonRepeatingShow($p_showRow, $p_populateUntilDateTime)
{
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
$show_id = $p_showRow["show_id"];
$first_show = $p_showRow["first_show"]; //non-UTC
@@ -1222,7 +1251,7 @@ class Application_Model_Show {
$currentUtcTimestamp = gmdate("Y-m-d H:i:s");
$show = new Application_Model_Show($show_id);
- if ($show->hasInstance()){
+ if ($show->hasInstance()) {
$ccShowInstance = $show->getInstance();
$newInstance = false;
} else {
@@ -1230,7 +1259,7 @@ class Application_Model_Show {
$newInstance = true;
}
- if ($newInstance || $ccShowInstance->getDbStarts() > $currentUtcTimestamp){
+ if ($newInstance || $ccShowInstance->getDbStarts() > $currentUtcTimestamp) {
$ccShowInstance->setDbShowId($show_id);
$ccShowInstance->setDbStarts($utcStartDateTime);
$ccShowInstance->setDbEnds($utcEndDateTime);
@@ -1241,14 +1270,14 @@ class Application_Model_Show {
$show_instance_id = $ccShowInstance->getDbId();
$showInstance = new Application_Model_ShowInstance($show_instance_id);
- if (!$newInstance){
+ if (!$newInstance) {
$showInstance->correctScheduleStartTimes();
}
$sql = "SELECT * FROM cc_show_rebroadcast WHERE show_id={$show_id}";
$rebroadcasts = $con->query($sql)->fetchAll();
- if ($showInstance->isRecorded()){
+ if ($showInstance->isRecorded()) {
$showInstance->deleteRebroadcasts();
self::createRebroadcastInstances($rebroadcasts, $currentUtcTimestamp, $show_id, $show_instance_id, $start, $duration, $timezone);
}
@@ -1269,7 +1298,7 @@ class Application_Model_Show {
*/
private static function populateRepeatingShow($p_showDaysRow, $p_populateUntilDateTime, $p_interval)
{
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
$show_id = $p_showDaysRow["show_id"];
$next_pop_date = $p_showDaysRow["next_pop_date"];
@@ -1283,7 +1312,7 @@ class Application_Model_Show {
$currentUtcTimestamp = gmdate("Y-m-d H:i:s");
- if(isset($next_pop_date)) {
+ if (isset($next_pop_date)) {
$start = $next_pop_date." ".$start_time;
} else {
$start = $first_show." ".$start_time;
@@ -1303,10 +1332,10 @@ class Application_Model_Show {
list($utcStartDateTime, $utcEndDateTime) = self::createUTCStartEndDateTime($start, $duration, $timezone);
- if ($show->hasInstanceOnDate($utcStartDateTime)){
+ if ($show->hasInstanceOnDate($utcStartDateTime)) {
$ccShowInstance = $show->getInstanceOnDate($utcStartDateTime);
- if ($ccShowInstance->getDbModifiedInstance()){
+ if ($ccShowInstance->getDbModifiedInstance()) {
//show instance on this date has been deleted.
list($start, $utcStartDateTime) = self::advanceRepeatingDate($p_interval, $start, $timezone);
continue;
@@ -1321,7 +1350,7 @@ class Application_Model_Show {
/* When editing the start/end time of a repeating show, we don't want to
* change shows that started in the past. So check the start time.
*/
- if ($newInstance || $ccShowInstance->getDbStarts() > $currentUtcTimestamp){
+ if ($newInstance || $ccShowInstance->getDbStarts() > $currentUtcTimestamp) {
$ccShowInstance->setDbShowId($show_id);
$ccShowInstance->setDbStarts($utcStartDateTime);
$ccShowInstance->setDbEnds($utcEndDateTime);
@@ -1335,7 +1364,7 @@ class Application_Model_Show {
/* If we are updating a show then make sure that the scheduled content within
* the show is updated to the correct time. */
- if (!$newInstance){
+ if (!$newInstance) {
$showInstance->correctScheduleStartTimes();
}
@@ -1348,9 +1377,10 @@ class Application_Model_Show {
Application_Model_Show::setNextPop($start, $show_id, $day);
}
- private static function advanceRepeatingDate($p_interval, $start, $timezone){
+ private static function advanceRepeatingDate($p_interval, $start, $timezone)
+ {
$startDt = new DateTime($start, new DateTimeZone($timezone));
- if ($p_interval == 'P1M'){
+ if ($p_interval == 'P1M') {
/* When adding months, there is a problem if we are on January 31st and add one month with PHP.
* What ends up happening is that since February 31st doesn't exist, the date returned is
* March 3rd. For now let's ignore the day and assume we are always working with the
@@ -1366,7 +1396,7 @@ class Application_Model_Show {
* we are looking for (31st day for example) */
do {
$dt->add(new DateInterval($p_interval));
- } while(!checkdate($dt->format("m"), $startDt->format("d"), $dt->format("Y")));
+ } while (!checkdate($dt->format("m"), $startDt->format("d"), $dt->format("Y")));
$dt->setDate($dt->format("Y"), $dt->format("m"), $startDt->format("d"));
@@ -1411,6 +1441,7 @@ class Application_Model_Show {
$duration = explode(":", $p_duration);
list($hours, $mins) = array_slice($duration, 0, 2);
$endDateTime->add(new DateInterval("PT{$hours}H{$mins}M"));
+
return array($startDateTime, $endDateTime);
}
@@ -1433,14 +1464,14 @@ class Application_Model_Show {
* string of user's timezone "Europe/Prague"
*
*/
- private static function createRebroadcastInstances($p_rebroadcasts, $p_currentUtcTimestamp, $p_showId, $p_showInstanceId, $p_startTime, $p_duration, $p_timezone=null){
-
+ private static function createRebroadcastInstances($p_rebroadcasts, $p_currentUtcTimestamp, $p_showId, $p_showInstanceId, $p_startTime, $p_duration, $p_timezone=null)
+ {
//Y-m-d
//use only the date part of the show start time stamp for the offsets to work properly.
$date = explode(" ", $p_startTime);
$start_date = $date[0];
- foreach($p_rebroadcasts as $rebroadcast) {
+ foreach ($p_rebroadcasts as $rebroadcast) {
$days = explode(" ", $rebroadcast["day_offset"]);
$time = explode(":", $rebroadcast["start_time"]);
@@ -1448,7 +1479,7 @@ class Application_Model_Show {
list($utcStartDateTime, $utcEndDateTime) = Application_Model_Show::createUTCStartEndDateTime($start_date, $p_duration, $p_timezone, $offset);
- if ($utcStartDateTime->format("Y-m-d H:i:s") > $p_currentUtcTimestamp){
+ if ($utcStartDateTime->format("Y-m-d H:i:s") > $p_currentUtcTimestamp) {
$newRebroadcastInstance = new CcShowInstances();
$newRebroadcastInstance->setDbShowId($p_showId);
@@ -1469,13 +1500,13 @@ class Application_Model_Show {
* In UTC time.
* @param DateTime $end_timestamp
* In UTC time.
- * @param unknown_type $excludeInstance
- * @param boolean $onlyRecord
+ * @param unknown_type $excludeInstance
+ * @param boolean $onlyRecord
* @return array
*/
public static function getShows($start_timestamp, $end_timestamp, $excludeInstance=NULL, $onlyRecord=FALSE)
{
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
//UTC DateTime object
$showsPopUntil = Application_Model_Preference::GetShowsPopulatedUntil();
@@ -1500,8 +1531,7 @@ class Application_Model_Show {
$sql = $sql." AND (si1.starts >= '{$start_string}' AND si1.starts < timestamp '{$end_string}')";
$sql = $sql." AND (si1.record = 1)";
- }
- else {
+ } else {
$sql = $sql." AND ((si1.starts >= '{$start_string}' AND si1.starts < '{$end_string}')
OR (si1.ends > '{$start_string}' AND si1.ends <= '{$end_string}')
@@ -1510,7 +1540,7 @@ class Application_Model_Show {
if (isset($excludeInstance)) {
- foreach($excludeInstance as $instance) {
+ foreach ($excludeInstance as $instance) {
$sql_exclude[] = "si1.id != {$instance}";
}
@@ -1520,6 +1550,7 @@ class Application_Model_Show {
}
$result = $con->query($sql)->fetchAll();
+
return $result;
}
@@ -1546,13 +1577,12 @@ class Application_Model_Show {
*/
public static function populateAllShowsInRange($p_startTimestamp, $p_endTimestamp)
{
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
$endTimeString = $p_endTimestamp->format("Y-m-d H:i:s");
if (!is_null($p_startTimestamp)) {
$startTimeString = $p_startTimestamp->format("Y-m-d H:i:s");
- }
- else {
+ } else {
$today_timestamp = new DateTime("now", new DateTimeZone("UTC"));
$startTimeString = $today_timestamp->format("Y-m-d H:i:s");
}
@@ -1605,11 +1635,9 @@ class Application_Model_Show {
if ($p_editable && $show["record"] && $nowEpoch > $startsEpoch) {
$options["editable"] = false;
- }
- else if ($p_editable && $show["rebroadcast"] && $nowEpoch > $parentStartsEpoch) {
- $options["editable"] = false;
- }
- else if ($p_editable && $nowEpoch < $endsEpoch) {
+ } elseif ($p_editable && $show["rebroadcast"] && $nowEpoch > $parentStartsEpoch) {
+ $options["editable"] = false;
+ } elseif ($p_editable && $nowEpoch < $endsEpoch) {
$options["editable"] = true;
}
$events[] = Application_Model_Show::makeFullCalendarEvent($show, $options);
@@ -1622,7 +1650,8 @@ class Application_Model_Show {
* 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.
**/
- private static function getPercentScheduled($p_starts, $p_ends, $p_time_filled){
+ private static function getPercentScheduled($p_starts, $p_ends, $p_time_filled)
+ {
$durationSeconds = (strtotime($p_ends) - strtotime($p_starts));
$time_filled = Application_Model_Schedule::WallTimeToMillisecs($p_time_filled) / 1000;
$percent = ceil(( $time_filled / $durationSeconds) * 100);
@@ -1652,7 +1681,7 @@ class Application_Model_Show {
$event["rebroadcast"] = intval($show["rebroadcast"]);
// get soundcloud_id
- if (!is_null($show["file_id"])){
+ if (!is_null($show["file_id"])) {
$file = Application_Model_StoredFile::Recall($show["file_id"]);
$soundcloud_id = $file->getSoundCloudId();
}
@@ -1677,8 +1706,8 @@ class Application_Model_Show {
/* Takes in a UTC DateTime object.
* Converts this to local time, since cc_show days
* requires local time. */
- public function setShowFirstShow($p_dt){
-
+ public function setShowFirstShow($p_dt)
+ {
//clone object since we are modifying it and it was passed by reference.
$dt = clone $p_dt;
@@ -1697,8 +1726,8 @@ class Application_Model_Show {
/* Takes in a UTC DateTime object
* Converts this to local time, since cc_show days
* requires local time. */
- public function setShowLastShow($p_dt){
-
+ public function setShowLastShow($p_dt)
+ {
//clone object since we are modifying it and it was passed by reference.
$dt = clone $p_dt;
@@ -1719,14 +1748,14 @@ class Application_Model_Show {
* 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)
{
global $CC_CONFIG;
$con = Propel::getConnection();
- if($timeNow == null){
+ if ($timeNow == null) {
$date = new Application_Common_DateHelper;
$timeNow = $date->getUtcTimestamp();
}
@@ -1741,6 +1770,7 @@ class Application_Model_Show {
// Convert back to local timezone
$rows = $con->query($sql)->fetchAll();
+
return $rows;
}
@@ -1851,15 +1881,15 @@ class Application_Model_Show {
* If $limit not given, all shows within the intervals are returns;
* 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 = "0", $timeEnd = "")
{
global $CC_CONFIG;
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
// defaults to retrieving shows from next 2 days if no end time has
// been specified
@@ -1884,6 +1914,7 @@ class Application_Model_Show {
}
$rows = $con->query($sql)->fetchAll();
+
return $rows;
}
@@ -1891,8 +1922,8 @@ class Application_Model_Show {
* Convert the columns given in the array $columnsToConvert in the
* database result $rows to local timezone.
*
- * @param type $rows arrays of arrays containing database query result
- * @param type $columnsToConvert array of column names to convert
+ * @param type $rows arrays of arrays containing database query result
+ * @param type $columnsToConvert array of column names to convert
*/
public static function convertToLocalTimeZone(&$rows, $columnsToConvert)
{
diff --git a/airtime_mvc/application/models/ShowBuilder.php b/airtime_mvc/application/models/ShowBuilder.php
index e4a0603e2..ebad18ca3 100644
--- a/airtime_mvc/application/models/ShowBuilder.php
+++ b/airtime_mvc/application/models/ShowBuilder.php
@@ -3,8 +3,8 @@
require_once 'formatters/LengthFormatter.php';
require_once 'formatters/TimeFilledFormatter.php';
-class Application_Model_ShowBuilder {
-
+class Application_Model_ShowBuilder
+{
private $timezone;
//in UTC timezone
@@ -49,8 +49,8 @@ class Application_Model_ShowBuilder {
* @param DateTime $p_startsDT
* @param DateTime $p_endsDT
*/
- public function __construct($p_startDT, $p_endDT, $p_opts) {
-
+ public function __construct($p_startDT, $p_endDT, $p_opts)
+ {
$this->startDT = $p_startDT;
$this->endDT = $p_endDT;
$this->timezone = date_default_timezone_get();
@@ -60,25 +60,25 @@ class Application_Model_ShowBuilder {
$this->currentShow = false;
}
- private function getUsersShows() {
-
+ private function getUsersShows()
+ {
$shows = array();
- $host_shows = CcShowHostsQuery::create()
- ->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)
- ->filterByDbHost($this->user->getId())
- ->find();
-
- foreach ($host_shows as $host_show) {
- $shows[] = $host_show->getDbShow();
+ $host_shows = CcShowHostsQuery::create()
+ ->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)
+ ->filterByDbHost($this->user->getId())
+ ->find();
+
+ foreach ($host_shows as $host_show) {
+ $shows[] = $host_show->getDbShow();
}
return $shows;
}
//check to see if this row should be editable by the user.
- private function isAllowed($p_item, &$row) {
-
+ private function isAllowed($p_item, &$row)
+ {
//cannot schedule in a recorded show.
if (intval($p_item["si_record"]) === 1) {
return;
@@ -89,7 +89,8 @@ class Application_Model_ShowBuilder {
}
}
- private function getItemColor($p_item, &$row) {
+ private function getItemColor($p_item, &$row)
+ {
$defaultColor = "ffffff";
$defaultBackground = "3366cc";
@@ -107,17 +108,16 @@ class Application_Model_ShowBuilder {
}
//information about whether a track is inside|boundary|outside a show.
- private function getItemStatus($p_item, &$row) {
-
+ private function getItemStatus($p_item, &$row)
+ {
$row["status"] = intval($p_item["playout_status"]);
}
- private function getRowTimestamp($p_item, &$row) {
-
+ private function getRowTimestamp($p_item, &$row)
+ {
if (is_null($p_item["si_last_scheduled"])) {
$ts = 0;
- }
- else {
+ } else {
$dt = new DateTime($p_item["si_last_scheduled"], new DateTimeZone("UTC"));
$ts = intval($dt->format("U"));
}
@@ -130,41 +130,38 @@ class Application_Model_ShowBuilder {
* 1 = current
* 2 = future
*/
- private function getScheduledStatus($p_epochItemStart, $p_epochItemEnd, &$row) {
-
+ 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;
- }
- else if ($row["footer"] === true && $this->epoch_now < $p_epochItemEnd) {
- $row["scheduled"] = 2;
- }
- else if ($row["header"] === true && $this->epoch_now >= $p_epochItemStart) {
+ } elseif ($row["footer"] === true && $this->epoch_now < $p_epochItemEnd) {
+ $row["scheduled"] = 2;
+ } elseif ($row["header"] === true && $this->epoch_now >= $p_epochItemStart) {
$row["scheduled"] = 0;
- }
- else if ($row["header"] === true && $this->epoch_now < $p_epochItemEnd) {
- $row["scheduled"] = 2;
+ } 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;
- }
-
- //item is the currently scheduled item.
- else if ($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;
+ else if ($this->epoch_now > $p_epochItemEnd) {
+ $row["scheduled"] = 0;
}
- //item is in the future.
- else if ($this->epoch_now < $p_epochItemStart) {
- $row["scheduled"] = 2;
- }
+ //item is the currently scheduled item.
+ else if ($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;
+ }
+
+ //item is in the future.
+ else if ($this->epoch_now < $p_epochItemStart) {
+ $row["scheduled"] = 2;
+ }
}
- private function makeHeaderRow($p_item) {
-
+ private function makeHeaderRow($p_item)
+ {
$row = $this->defaultRowArray;
$this->isAllowed($p_item, $row);
$this->getRowTimestamp($p_item, $row);
@@ -177,8 +174,8 @@ class Application_Model_ShowBuilder {
$showEndDT->setTimezone(new DateTimeZone($this->timezone));
$endsEpoch = floatval($showEndDT->format("U.u"));
- //is a rebroadcast show
- if (intval($p_item["si_rebroadcast"]) === 1) {
+ //is a rebroadcast show
+ if (intval($p_item["si_rebroadcast"]) === 1) {
$row["rebroadcast"] = true;
$parentInstance = CcShowInstancesQuery::create()->findPk($p_item["parent_show"]);
@@ -187,15 +184,14 @@ class Application_Model_ShowBuilder {
$dt->setTimezone(new DateTimeZone($this->timezone));
$time = $dt->format("Y-m-d H:i");
- $row["rebroadcast_title"] = "Rebroadcast of {$name} from {$time}";
- }
- else if (intval($p_item["si_record"]) === 1) {
+ $row["rebroadcast_title"] = "Rebroadcast of {$name} from {$time}";
+ } elseif (intval($p_item["si_record"]) === 1) {
$row["record"] = true;
if (Application_Model_Preference::GetUploadToSoundcloudOption()) {
$file = Application_Model_StoredFile::Recall($p_item["si_file_id"]);
if (isset($file)) {
- $sid = $file->getSoundCloudId();
+ $sid = $file->getSoundCloudId();
$row["soundcloud_id"] = $sid;
}
}
@@ -204,8 +200,7 @@ class Application_Model_ShowBuilder {
if ($startsEpoch < $this->epoch_now && $endsEpoch > $this->epoch_now) {
$row["currentShow"] = true;
$this->currentShow = true;
- }
- else {
+ } else {
$this->currentShow = false;
}
@@ -229,7 +224,8 @@ class Application_Model_ShowBuilder {
return $row;
}
- private function makeScheduledItemRow($p_item) {
+ private function makeScheduledItemRow($p_item)
+ {
$row = $this->defaultRowArray;
if (isset($p_item["sched_starts"])) {
@@ -279,34 +275,33 @@ class Application_Model_ShowBuilder {
$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"));
+ $startsEpoch = floatval($showStartDT->format("U.u"));
$endsEpoch = floatval($showEndDT->format("U.u"));
-
+
$this->getScheduledStatus($startsEpoch, $endsEpoch, $row);
- }
- else {
+ } else {
$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;
}
-
- $this->getItemColor($p_item, $row);
- $this->getRowTimestamp($p_item, $row);
+
+ $this->getItemColor($p_item, $row);
+ $this->getRowTimestamp($p_item, $row);
$this->isAllowed($p_item, $row);
return $row;
}
- private function makeFooterRow($p_item) {
-
+ private function makeFooterRow($p_item)
+ {
$row = $this->defaultRowArray;
$row["footer"] = true;
$row["instance"] = intval($p_item["si_id"]);
@@ -321,21 +316,21 @@ class Application_Model_ShowBuilder {
$timeFilled = new TimeFilledFormatter($runtime);
$row["fRuntime"] = $timeFilled->format();
- $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"));
- $showEndDT->setTimezone(new DateTimeZone($this->timezone));
+ $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"));
+ $showEndDT->setTimezone(new DateTimeZone($this->timezone));
$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;
+ if ($this->currentShow === true) {
+ $row["currentShow"] = true;
}
-
+
$this->getScheduledStatus($startsEpoch, $endsEpoch, $row);
- $this->isAllowed($p_item, $row);
+ $this->isAllowed($p_item, $row);
return $row;
}
@@ -346,14 +341,14 @@ class Application_Model_ShowBuilder {
* @return boolean whether the schedule in the show builder's range has been updated.
*
*/
- public function hasBeenUpdatedSince($timestamp, $instances) {
+ public function hasBeenUpdatedSince($timestamp, $instances)
+ {
$outdated = false;
$shows = Application_Model_Show::getShows($this->startDT, $this->endDT);
if ($this->opts["showFilter"] !== 0) {
$include[] = $this->opts["showFilter"];
- }
- else if ($this->opts["myShows"] === 1) {
+ } elseif ($this->opts["myShows"] === 1) {
$include = $this->getUsersShows();
}
@@ -368,17 +363,16 @@ class Application_Model_ShowBuilder {
if (isset($show["last_scheduled"])) {
$dt = new DateTime($show["last_scheduled"], new DateTimeZone("UTC"));
- }
- else {
+ } else {
$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) {
- Logging::debug("timestamp is {$timestamp} show timestamp is {$showTimeStamp}");
- $outdated = true;
- break;
+ Logging::debug("timestamp is {$timestamp} show timestamp is {$showTimeStamp}");
+ $outdated = true;
+ break;
}
}
}
@@ -392,8 +386,8 @@ class Application_Model_ShowBuilder {
return $outdated;
}
- public function GetItems() {
-
+ public function GetItems()
+ {
$current_id = -1;
$display_items = array();
@@ -401,8 +395,7 @@ class Application_Model_ShowBuilder {
if ($this->opts["myShows"] === 1) {
$shows = $this->getUsersShows();
- }
- else if ($this->opts["showFilter"] !== 0) {
+ } elseif ($this->opts["showFilter"] !== 0) {
$shows[] = $this->opts["showFilter"];
}
@@ -439,9 +432,9 @@ class Application_Model_ShowBuilder {
if (isset($row)) {
$display_items[] = $row;
}
-
- if ($current_id !== -1 && !in_array($current_id, $this->showInstances)) {
- $this->showInstances[] = $current_id;
+
+ if ($current_id !== -1 && !in_array($current_id, $this->showInstances)) {
+ $this->showInstances[] = $current_id;
}
}
diff --git a/airtime_mvc/application/models/ShowInstance.php b/airtime_mvc/application/models/ShowInstance.php
index 00a65a06a..9d60ac147 100644
--- a/airtime_mvc/application/models/ShowInstance.php
+++ b/airtime_mvc/application/models/ShowInstance.php
@@ -2,8 +2,8 @@
require_once 'formatters/LengthFormatter.php';
-class Application_Model_ShowInstance {
-
+class Application_Model_ShowInstance
+{
private $_instanceId;
private $_showInstance;
@@ -12,7 +12,7 @@ class Application_Model_ShowInstance {
$this->_instanceId = $instanceId;
$this->_showInstance = CcShowInstancesQuery::create()->findPK($instanceId);
- if (is_null($this->_showInstance)){
+ if (is_null($this->_showInstance)) {
throw new Exception();
}
}
@@ -27,11 +27,13 @@ class Application_Model_ShowInstance {
return $this->_instanceId;
}
- public function getShow(){
+ public function getShow()
+ {
return new Application_Model_Show($this->getShowId());
}
- public function deleteRebroadcasts(){
+ public function deleteRebroadcasts()
+ {
$con = Propel::getConnection();
$timestamp = gmdate("Y-m-d H:i:s");
@@ -62,12 +64,14 @@ class Application_Model_ShowInstance {
public function getName()
{
$show = CcShowQuery::create()->findPK($this->getShowId());
+
return $show->getDbName();
}
public function getGenre()
{
$show = CcShowQuery::create()->findPK($this->getShowId());
+
return $show->getDbGenre();
}
@@ -93,6 +97,7 @@ class Application_Model_ShowInstance {
{
$showStart = $this->getShowInstanceStart();
$showStartExplode = explode(" ", $showStart);
+
return $showStartExplode[0];
}
@@ -113,6 +118,7 @@ class Application_Model_ShowInstance {
public function getSoundCloudFileId()
{
$file = Application_Model_StoredFile::Recall($this->_showInstance->getDbRecordedFile());
+
return $file->getSoundCloudId();
}
@@ -174,7 +180,7 @@ class Application_Model_ShowInstance {
$diff = $showStartsEpoch - $scheduleStartsEpoch;
- if ($diff != 0){
+ if ($diff != 0) {
$sql = "UPDATE cc_schedule"
." SET starts = starts + INTERVAL '$diff' second,"
." ends = ends + INTERVAL '$diff' second"
@@ -199,8 +205,8 @@ class Application_Model_ShowInstance {
* @return $newDateTime
* php DateTime, $dateTime with the added time deltas.
*/
- private static function addDeltas($dateTime, $deltaDay, $deltaMin) {
-
+ private static function addDeltas($dateTime, $deltaDay, $deltaMin)
+ {
$newDateTime = clone $dateTime;
$days = abs($deltaDay);
@@ -211,15 +217,13 @@ class Application_Model_ShowInstance {
if ($deltaDay > 0) {
$newDateTime->add($dayInterval);
- }
- else if ($deltaDay < 0){
+ } elseif ($deltaDay < 0) {
$newDateTime->sub($dayInterval);
}
if ($deltaMin > 0) {
$newDateTime->add($minInterval);
- }
- else if ($deltaMin < 0) {
+ } elseif ($deltaMin < 0) {
$newDateTime->sub($minInterval);
}
@@ -228,7 +232,7 @@ class Application_Model_ShowInstance {
public function moveShow($deltaDay, $deltaMin)
{
- if ($this->getShow()->isRepeating()){
+ if ($this->getShow()->isRepeating()) {
return "Can't drag and drop repeating shows";
}
@@ -286,6 +290,7 @@ class Application_Model_ShowInstance {
//recorded show doesn't exist.
catch (Exception $e) {
$this->_showInstance->delete();
+
return "Show was deleted because recorded show does not exist!";
}
@@ -302,7 +307,7 @@ class Application_Model_ShowInstance {
$this->correctScheduleStartTimes();
$show = new Application_Model_Show($this->getShowId());
- if(!$show->isRepeating() && is_null($this->isRebroadcast())){
+ if (!$show->isRepeating() && is_null($this->isRebroadcast())) {
$show->setShowFirstShow($newStartsDateTime);
$show->setShowLastShow($newEndsDateTime);
}
@@ -317,7 +322,7 @@ class Application_Model_ShowInstance {
*/
public function resizeShow($deltaDay, $deltaMin)
{
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
$hours = $deltaMin/60;
if($hours > 0)
@@ -331,7 +336,7 @@ class Application_Model_ShowInstance {
$starts = $this->getShowInstanceStart();
$ends = $this->getShowInstanceEnd();
- if(strtotime($today_timestamp) > strtotime($starts)) {
+ if (strtotime($today_timestamp) > strtotime($starts)) {
return "can't resize a past show";
}
@@ -346,14 +351,14 @@ class Application_Model_ShowInstance {
$overlap = Application_Model_Show::getShows($utcStartDateTime, $utcEndDateTime);
- if(count($overlap) > 0) {
+ if (count($overlap) > 0) {
return "Should not overlap shows";
}
}
//with overbooking no longer need to check already scheduled content still fits.
//must update length of all rebroadcast instances.
- if($this->isRecorded()) {
+ if ($this->isRecorded()) {
$sql = "UPDATE cc_show_instances SET ends = (ends + interval '{$deltaDay} days' + interval '{$hours}:{$mins}')
WHERE rebroadcast = 1 AND instance_id = {$this->_instanceId}";
$con->exec($sql);
@@ -453,7 +458,7 @@ class Application_Model_ShowInstance {
->filterByDbRebroadcast(0)
->find();
- if (is_null($showInstances)){
+ if (is_null($showInstances)) {
return true;
}
//only 1 show instance left of the show, make it non repeating.
@@ -532,17 +537,15 @@ class Application_Model_ShowInstance {
->delete();
- if ($this->checkToDeleteShow($showId)){
+ if ($this->checkToDeleteShow($showId)) {
CcShowQuery::create()
->filterByDbId($showId)
->delete();
}
- }
- else {
+ } else {
if ($this->isRebroadcast()) {
$this->_showInstance->delete();
- }
- else {
+ } else {
$show->delete();
}
}
@@ -567,8 +570,7 @@ class Application_Model_ShowInstance {
try {
$rebroad = new Application_Model_ShowInstance($rebroadcast->getDbId());
$rebroad->addFileToShow($file_id, false);
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
Logging::log("{$e->getFile()}");
Logging::log("{$e->getLine()}");
Logging::log("{$e->getMessage()}");
@@ -586,8 +588,7 @@ class Application_Model_ShowInstance {
$time_arr[1] = "." . $time_arr[1];
$milliseconds = number_format(round($time_arr[1], 2), 2);
$time = $time_arr[0] . substr($milliseconds, 1);
- }
- else {
+ } else {
$time = $time_arr[0] . ".00";
}
} else {
@@ -601,6 +602,7 @@ class Application_Model_ShowInstance {
public function getTimeScheduledSecs()
{
$time_filled = $this->getTimeScheduled();
+
return Application_Model_Playlist::playlistTimeToSeconds($time_filled);
}
@@ -608,6 +610,7 @@ class Application_Model_ShowInstance {
{
$ends = $this->getShowInstanceEnd(null);
$starts = $this->getShowInstanceStart(null);
+
return intval($ends->format('U')) - intval($starts->format('U'));
}
@@ -643,7 +646,7 @@ class Application_Model_ShowInstance {
public function getShowListContent()
{
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
$sql = "SELECT *
FROM (cc_schedule AS s LEFT JOIN cc_files AS f ON f.id = s.file_id)
@@ -670,7 +673,7 @@ class Application_Model_ShowInstance {
public function getLastAudioItemEnd()
{
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
$sql = "SELECT ends FROM cc_schedule "
."WHERE instance_id = {$this->_instanceId} "
@@ -678,14 +681,16 @@ class Application_Model_ShowInstance {
."LIMIT 1";
$query = $con->query($sql)->fetchColumn(0);
+
return ($query !== false) ? $query : NULL;
}
- public function getShowEndGapTime(){
+ public function getShowEndGapTime()
+ {
$showEnd = $this->getShowInstanceEnd();
$lastItemEnd = $this->getLastAudioItemEnd();
- if (is_null($lastItemEnd)){
+ if (is_null($lastItemEnd)) {
$lastItemEnd = $this->getShowInstanceStart();
}
@@ -695,9 +700,10 @@ class Application_Model_ShowInstance {
return ($diff < 0) ? 0 : $diff;
}
- public static function GetLastShowInstance($p_timeNow){
+ public static function GetLastShowInstance($p_timeNow)
+ {
global $CC_CONFIG;
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
$sql = "SELECT si.id"
." FROM $CC_CONFIG[showInstances] si"
@@ -717,7 +723,7 @@ class Application_Model_ShowInstance {
public static function GetCurrentShowInstance($p_timeNow)
{
global $CC_CONFIG;
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
/* Orderby si.starts descending, because in some cases
* we can have multiple shows overlapping each other. In
@@ -744,7 +750,7 @@ class Application_Model_ShowInstance {
public static function GetNextShowInstance($p_timeNow)
{
global $CC_CONFIG;
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
$sql = "SELECT si.id"
." FROM $CC_CONFIG[showInstances] si"
@@ -767,6 +773,7 @@ class Application_Model_ShowInstance {
global $CC_CONFIG;
$con = Propel::getConnection();
$sql = "SELECT count(*) as cnt FROM $CC_CONFIG[showInstances] WHERE ends < '$day'";
+
return $con->query($sql)->fetchColumn(0);
}
@@ -774,7 +781,7 @@ class Application_Model_ShowInstance {
public static function GetEndTimeOfNextShowWithLiveDJ($p_startTime, $p_endTime)
{
global $CC_CONFIG;
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
$sql = "SELECT ends
FROM cc_show_instances as si
@@ -785,10 +792,11 @@ class Application_Model_ShowInstance {
return $con->query($sql)->fetchAll();
}
- function isRepeating(){
- if ($this->getShow()->isRepeating()){
+ public function isRepeating()
+ {
+ if ($this->getShow()->isRepeating()) {
return true;
- }else{
+ } else {
return false;
}
}
diff --git a/airtime_mvc/application/models/Soundcloud.php b/airtime_mvc/application/models/Soundcloud.php
index d94648267..c993d3a1d 100644
--- a/airtime_mvc/application/models/Soundcloud.php
+++ b/airtime_mvc/application/models/Soundcloud.php
@@ -1,8 +1,8 @@
getToken())
- {
- if(count($tags)) {
+ if ($this->getToken()) {
+ if (count($tags)) {
$tags = join(" ", $tags);
$tags = $tags." ".Application_Model_Preference::GetSoundCloudTags();
- }
- else {
+ } else {
$tags = Application_Model_Preference::GetSoundCloudTags();
}
@@ -46,7 +44,7 @@ class Application_Model_Soundcloud {
);
- if(isset($release)) {
+ if (isset($release)) {
$release = str_replace(" ", "-", $release);
$release = str_replace(":", "-", $release);
@@ -60,8 +58,7 @@ class Application_Model_Soundcloud {
if (isset($genre) && $genre != "") {
$track_data['track[genre]'] = $genre;
- }
- else {
+ } else {
$default_genre = Application_Model_Preference::GetSoundCloudGenre();
if ($default_genre != "") {
$track_data['track[genre]'] = $default_genre;
diff --git a/airtime_mvc/application/models/StoredFile.php b/airtime_mvc/application/models/StoredFile.php
index 8dd20cbd8..abc6bb9b6 100644
--- a/airtime_mvc/application/models/StoredFile.php
+++ b/airtime_mvc/application/models/StoredFile.php
@@ -13,8 +13,8 @@ require_once 'formatters/BitrateFormatter.php';
* @license http://www.gnu.org/licenses/gpl.txt
* @see MetaData
*/
-class Application_Model_StoredFile {
-
+class Application_Model_StoredFile
+{
/**
* @holds propel database object
*/
@@ -60,7 +60,8 @@ class Application_Model_StoredFile {
return $this->_file->getDbId();
}
- public function getGunId() {
+ public function getGunId()
+ {
return $this->_file->getDbGunid();
}
@@ -69,7 +70,8 @@ class Application_Model_StoredFile {
return $this->_file->getDbFtype();
}
- public function getPropelOrm(){
+ public function getPropelOrm()
+ {
return $this->_file;
}
@@ -88,11 +90,10 @@ class Application_Model_StoredFile {
{
if (is_null($p_md)) {
$this->setDbColMetadata();
- }
- else {
+ } else {
$dbMd = array();
- 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 trying to retrieve this value. We could make sure number is within these bounds,
@@ -103,17 +104,17 @@ class Application_Model_StoredFile {
$year = $p_md["MDATA_KEY_YEAR"];
- if (strlen($year) > 4){
+ if (strlen($year) > 4) {
$year = substr($year, 0, 4);
}
- if (!is_numeric($year)){
+ if (!is_numeric($year)) {
$year = 0;
}
$p_md["MDATA_KEY_YEAR"] = $year;
}
foreach ($p_md as $mdConst => $mdValue) {
- if (defined($mdConst)){
+ if (defined($mdConst)) {
$dbMd[constant($mdConst)] = $mdValue;
}
}
@@ -137,11 +138,10 @@ class Application_Model_StoredFile {
$method = "set$propelColumn";
$this->_file->$method(null);
}
- }
- else {
+ } else {
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;
}
if (isset($this->_dbMD[$dbColumn])) {
@@ -183,7 +183,7 @@ class Application_Model_StoredFile {
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])) {
@@ -197,7 +197,7 @@ class Application_Model_StoredFile {
/**
* Get one metadata value.
*
- * @param string $p_category (MDATA_KEY_URL)
+ * @param string $p_category (MDATA_KEY_URL)
* @return string
*/
public function getMetadataValue($p_category)
@@ -210,13 +210,14 @@ class Application_Model_StoredFile {
/**
* Get one metadata value.
*
- * @param string $p_category (url)
+ * @param string $p_category (url)
* @return string
*/
public function getDbColMetadataValue($p_category)
{
$propelColumn = $this->_dbMD[$p_category];
$method = "get$propelColumn";
+
return $this->_file->$method();
}
@@ -290,6 +291,7 @@ class Application_Model_StoredFile {
$res = $con->exec($sql);
$this->state = $p_state;
$this->editedby = $p_editedby;
+
return TRUE;
}
@@ -297,7 +299,8 @@ class Application_Model_StoredFile {
* Returns an array of playlist objects that this file is a part of.
* @return array
*/
- public function getPlaylists() {
+ public function getPlaylists()
+ {
global $CC_CONFIG;
$con = Propel::getConnection();
$sql = "SELECT playlist_id "
@@ -310,6 +313,7 @@ class Application_Model_StoredFile {
$playlists[] = Application_Model_Playlist::Recall($id);
}
}
+
return $playlists;
}
@@ -336,7 +340,7 @@ class Application_Model_StoredFile {
Application_Model_RabbitMq::SendMessageToMediaMonitor("file_delete", $data);
}
- if ($deleteFromPlaylist){
+ if ($deleteFromPlaylist) {
Application_Model_Playlist::DeleteFileFromAllPlaylists($this->getId());
}
// set file_exists falg to false
@@ -355,7 +359,7 @@ class Application_Model_StoredFile {
{
$filepath = $this->getFilePath();
- if ($deleteFromPlaylist){
+ if ($deleteFromPlaylist) {
Application_Model_Playlist::DeleteFileFromAllPlaylists($this->getId());
}
// set file_exists falg to false
@@ -375,8 +379,7 @@ class Application_Model_StoredFile {
if ($mime == "audio/vorbis" || $mime == "application/ogg") {
return "ogg";
- }
- else if ($mime == "audio/mp3" || $mime == "audio/mpeg") {
+ } elseif ($mime == "audio/mp3" || $mime == "audio/mpeg") {
return "mp3";
}
}
@@ -432,16 +435,17 @@ class Application_Model_StoredFile {
* is specified in the airtime.conf config file. If either of these is
* not specified, then use values provided by the $_SERVER global variable.
*/
- public function getFileUrlUsingConfigAddress(){
+ public function getFileUrlUsingConfigAddress()
+ {
global $CC_CONFIG;
- if (isset($CC_CONFIG['baseUrl'])){
+ if (isset($CC_CONFIG['baseUrl'])) {
$serverName = $CC_CONFIG['baseUrl'];
} else {
$serverName = $_SERVER['SERVER_NAME'];
}
- if (isset($CC_CONFIG['basePort'])){
+ if (isset($CC_CONFIG['basePort'])) {
$serverPort = $CC_CONFIG['basePort'];
} else {
$serverPort = $_SERVER['SERVER_PORT'];
@@ -450,8 +454,10 @@ class Application_Model_StoredFile {
return $this->constructGetFileUrl($serverName, $serverPort);
}
- private function constructGetFileUrl($p_serverName, $p_serverPort){
+ private function constructGetFileUrl($p_serverName, $p_serverPort)
+ {
Logging::log("getting media! - 2");
+
return "http://$p_serverName:$p_serverPort/api/get-media/file/".$this->getGunId().".".$this->getFileExtension();
}
@@ -462,6 +468,7 @@ Logging::log("getting media! - 2");
public function getRelativeFileUrl($baseUrl)
{
Logging::log("getting media!");
+
return $baseUrl."/api/get-media/file/".$this->getGunId().".".$this->getFileExtension();
}
@@ -475,19 +482,18 @@ Logging::log("getting media! - 2");
$storedFile = new Application_Model_StoredFile();
$storedFile->_file = $file;
- if(isset($md['MDATA_KEY_FILEPATH'])) {
+ if (isset($md['MDATA_KEY_FILEPATH'])) {
// removed "//" in the path. Always use '/' for path separator
$filepath = str_replace("//", "/", $md['MDATA_KEY_FILEPATH']);
$res = $storedFile->setFilePath($filepath);
if ($res === -1) {
return null;
}
- }
- else {
+ } else {
return null;
}
- if(isset($md)) {
+ if (isset($md)) {
$storedFile->setMetadata($md);
}
@@ -514,25 +520,22 @@ Logging::log("getting media! - 2");
{
if (isset($p_id)) {
$file = CcFilesQuery::create()->findPK(intval($p_id));
- }
- else if (isset($p_gunid)) {
+ } elseif (isset($p_gunid)) {
$file = CcFilesQuery::create()
->filterByDbGunid($p_gunid)
->findOne();
- }
- else if (isset($p_md5sum)) {
- if($exist){
+ } elseif (isset($p_md5sum)) {
+ if ($exist) {
$file = CcFilesQuery::create()
->filterByDbMd5($p_md5sum)
->filterByDbFileExists(true)
->findOne();
- }else{
+ } else {
$file = CcFilesQuery::create()
->filterByDbMd5($p_md5sum)
->findOne();
}
- }
- else if (isset($p_filepath)) {
+ } elseif (isset($p_filepath)) {
$path_info = Application_Model_MusicDir::splitFilePath($p_filepath);
if (is_null($path_info)) {
@@ -544,8 +547,7 @@ Logging::log("getting media! - 2");
->filterByDbDirectory($music_dir->getId())
->filterByDbFilepath($path_info[1])
->findOne();
- }
- else {
+ } else {
return null;
}
@@ -554,14 +556,15 @@ Logging::log("getting media! - 2");
$storedFile->_file = $file;
return $storedFile;
- }
- else {
+ } else {
return null;
}
}
- public function getName(){
+ public function getName()
+ {
$info = pathinfo($this->getFilePath());
+
return $info['filename'];
}
@@ -582,7 +585,7 @@ Logging::log("getting media! - 2");
/**
* Fetch the Application_Model_StoredFile by looking up the MD5 value.
*
- * @param string $p_md5sum
+ * @param string $p_md5sum
* @return Application_Model_StoredFile|NULL
*/
public static function RecallByMd5($p_md5sum, $exist=false)
@@ -593,7 +596,7 @@ Logging::log("getting media! - 2");
/**
* Fetch the Application_Model_StoredFile by looking up its filepath.
*
- * @param string $p_filepath path of file stored in Airtime.
+ * @param string $p_filepath path of file stored in Airtime.
* @return Application_Model_StoredFile|NULL
*/
public static function RecallByFilepath($p_filepath)
@@ -601,7 +604,8 @@ Logging::log("getting media! - 2");
return Application_Model_StoredFile::Recall(null, null, null, $p_filepath);
}
- public static function RecallByPartialFilepath($partial_path){
+ public static function RecallByPartialFilepath($partial_path)
+ {
$path_info = Application_Model_MusicDir::splitFilePath($partial_path);
if (is_null($path_info)) {
@@ -614,16 +618,17 @@ Logging::log("getting media! - 2");
->filterByDbFilepath("$path_info[1]%")
->find();
$res = array();
- foreach ($files as $file){
+ foreach ($files as $file) {
$storedFile = new Application_Model_StoredFile();
$storedFile->_file = $file;
$res[] = $storedFile;
}
+
return $res;
}
- public static function searchLibraryFiles($datatables) {
-
+ public static function searchLibraryFiles($datatables)
+ {
$con = Propel::getConnection(CcFilesPeer::DATABASE_NAME);
$displayColumns = array("id", "track_title", "artist_name", "album_title", "genre", "length",
@@ -639,35 +644,30 @@ Logging::log("getting media! - 2");
if ($key === "id") {
$plSelect[] = "PL.id AS ".$key;
$fileSelect[] = $key;
- }
- else if ($key === "track_title") {
+ } elseif ($key === "track_title") {
$plSelect[] = "name AS ".$key;
$fileSelect[] = $key;
- }
- else if ($key === "ftype") {
+ } elseif ($key === "ftype") {
$plSelect[] = "'playlist'::varchar AS ".$key;
$fileSelect[] = $key;
- }
- else if ($key === "artist_name") {
+ } elseif ($key === "artist_name") {
$plSelect[] = "login AS ".$key;
$fileSelect[] = $key;
}
//same columns in each table.
- else if(in_array($key, array("length", "utime", "mtime"))) {
+ else if (in_array($key, array("length", "utime", "mtime"))) {
$plSelect[] = $key;
$fileSelect[] = $key;
- }
- else if ($key === "year") {
+ } elseif ($key === "year") {
$plSelect[] = "EXTRACT(YEAR FROM utime)::varchar AS ".$key;
$fileSelect[] = "year 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"))){
+ else if (in_array($key, array("track_number", "bit_rate", "sample_rate"))) {
$plSelect[] = "NULL::int AS ".$key;
$fileSelect[] = $key;
- }
- else {
+ } else {
$plSelect[] = "NULL::text AS ".$key;
$fileSelect[] = $key;
}
@@ -725,11 +725,10 @@ Logging::log("getting media! - 2");
//datatable stuff really needs to be pulled out and generalized within the project
//access to zend view methods to access url helpers is needed.
- if($type == "au"){//&& isset( $audioResults )) {
+ if ($type == "au") {//&& isset( $audioResults )) {
$row['audioFile'] = $row['gunid'].".".pathinfo($row['filepath'], PATHINFO_EXTENSION);
$row['image'] = '
';
- }
- else {
+ } else {
$row['image'] = '
';
}
}
@@ -839,7 +838,8 @@ Logging::log("getting media! - 2");
* Check, using disk_free_space, the space available in the $destination_folder folder to see if it has
* enough space to move the $audio_file into and report back to the user if not.
**/
- public static function isEnoughDiskSpaceToCopy($destination_folder, $audio_file){
+ public static function isEnoughDiskSpaceToCopy($destination_folder, $audio_file)
+ {
//check to see if we have enough space in the /organize directory to copy the file
$freeSpace = disk_free_space($destination_folder);
$fileSize = filesize($audio_file);
@@ -847,7 +847,8 @@ Logging::log("getting media! - 2");
return $freeSpace >= $fileSize;
}
- public static function copyFileToStor($p_targetDir, $fileName, $tempname){
+ public static function copyFileToStor($p_targetDir, $fileName, $tempname)
+ {
$audio_file = $p_targetDir . DIRECTORY_SEPARATOR . $tempname;
Logging::log('copyFileToStor: moving file '.$audio_file);
$md5 = md5_file($audio_file);
@@ -861,26 +862,27 @@ Logging::log("getting media! - 2");
}
}
- if (!isset($result)){//The file has no duplicate, so proceed to copy.
+ if (!isset($result)) {//The file has no duplicate, so proceed to copy.
$storDir = Application_Model_MusicDir::getStorDir();
$stor = $storDir->getDirectory();
// check if "organize" dir exists and if not create one
- if(!file_exists($stor."/organize")){
- if(!mkdir($stor."/organize", 0777)){
+ if (!file_exists($stor."/organize")) {
+ if (!mkdir($stor."/organize", 0777)) {
$result = array("code" => 109, "message" => "Failed to create 'organize' directory.");
+
return $result;
}
}
- if (chmod($audio_file, 0644) === false){
+ if (chmod($audio_file, 0644) === false) {
Logging::log("Warning: couldn't change permissions of $audio_file to 0644");
}
//check to see if there is enough space in $stor to continue.
- if (self::isEnoughDiskSpaceToCopy($stor, $audio_file)){
+ if (self::isEnoughDiskSpaceToCopy($stor, $audio_file)) {
$audio_stor = Application_Common_OsPath::join($stor, "organize", $fileName);
- if (self::liquidsoapFilePlayabilityTest($audio_file)){
+ if (self::liquidsoapFilePlayabilityTest($audio_file)) {
Logging::log("copyFileToStor: moving file $audio_file to $audio_stor");
@@ -899,14 +901,15 @@ Logging::log("getting media! - 2");
$result = array("code" => 107, "message" => "The file was not uploaded, there is ".$freeSpace."MB of disk space left and the file you are uploading has a size of ".$fileSize."MB.");
}
}
+
return $result;
}
/*
* Pass the file through Liquidsoap and test if it is readable. Return True if readable, and False otherwise.
*/
- public static function liquidsoapFilePlayabilityTest($audio_file){
-
+ public static function liquidsoapFilePlayabilityTest($audio_file)
+ {
$LIQUIDSOAP_ERRORS = array('TagLib: MPEG::Properties::read() -- Could not find a valid last MPEG frame in the stream.');
// Ask Liquidsoap if file is playable
@@ -915,15 +918,17 @@ Logging::log("getting media! - 2");
exec($command, $output, $rv);
$isError = count($output) > 0 && in_array($output[0], $LIQUIDSOAP_ERRORS);
+
return ($rv == 0 && !$isError);
}
public static function getFileCount()
{
global $CC_CONFIG;
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
$sql = "SELECT count(*) as cnt FROM ".$CC_CONFIG["filesTable"]." WHERE file_exists";
+
return $con->query($sql)->fetchColumn(0);
}
@@ -935,7 +940,7 @@ Logging::log("getting media! - 2");
*/
public static function listAllFiles($dir_id=null, $propelObj=false)
{
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
if ($propelObj) {
$sql = "SELECT m.directory || f.filepath as fp"
@@ -960,7 +965,7 @@ Logging::log("getting media! - 2");
return $results;
}
-
+
//TODO: MERGE THIS FUNCTION AND "listAllFiles" -MK
public static function listAllFiles2($dir_id=null, $limit=null)
{
@@ -969,13 +974,13 @@ Logging::log("getting media! - 2");
$sql = "SELECT id, filepath as fp"
." FROM CC_FILES"
." WHERE directory = $dir_id"
- ." AND file_exists = 'TRUE'";
-
- if (!is_null($limit) && is_int($limit)){
+ ." AND file_exists = 'TRUE'"
+ ." AND replay_gain is NULL";
+ if (!is_null($limit) && is_int($limit)) {
$sql .= " LIMIT $limit";
}
- $rows = $con->query($sql, PDO::FETCH_ASSOC);
+ $rows = $con->query($sql, PDO::FETCH_ASSOC)->fetchAll();
return $rows;
}
@@ -993,6 +998,7 @@ Logging::log("getting media! - 2");
." (soundcloud_upload_time >= (now() - (INTERVAL '1 day')))";
$rows = $con->query($sql)->fetchAll();
+
return count($rows);
} catch (Exception $e) {
header('HTTP/1.0 503 Service Unavailable');
@@ -1008,7 +1014,8 @@ Logging::log("getting media! - 2");
->save();
}
- public function getSoundCloudLinkToFile(){
+ public function getSoundCloudLinkToFile()
+ {
return $this->_file->getDbSoundCloudLinkToFile();
}
@@ -1018,42 +1025,51 @@ Logging::log("getting media! - 2");
->save();
}
- public function getSoundCloudId(){
+ public function getSoundCloudId()
+ {
return $this->_file->getDbSoundCloudId();
}
- public function setSoundCloudErrorCode($code){
+ public function setSoundCloudErrorCode($code)
+ {
$this->_file->setDbSoundCloudErrorCode($code)
->save();
}
- public function getSoundCloudErrorCode(){
+ public function getSoundCloudErrorCode()
+ {
return $this->_file->getDbSoundCloudErrorCode();
}
- public function setSoundCloudErrorMsg($msg){
+ public function setSoundCloudErrorMsg($msg)
+ {
$this->_file->setDbSoundCloudErrorMsg($msg)
->save();
}
- public function getSoundCloudErrorMsg(){
+ public function getSoundCloudErrorMsg()
+ {
return $this->_file->getDbSoundCloudErrorMsg();
}
- public function getDirectory(){
+ public function getDirectory()
+ {
return $this->_file->getDbDirectory();
}
- public function setFileExistsFlag($flag){
+ public function setFileExistsFlag($flag)
+ {
$this->_file->setDbFileExists($flag)
->save();
}
- public function setSoundCloudUploadTime($time){
+ public function setSoundCloudUploadTime($time)
+ {
$this->_file->setDbSoundCloundUploadTime($time)
->save();
}
- public function getFileExistsFlag(){
+ public function getFileExistsFlag()
+ {
return $this->_file->getDbFileExists();
}
@@ -1062,12 +1078,11 @@ Logging::log("getting media! - 2");
global $CC_CONFIG;
$file = $this->_file;
- if(is_null($file)) {
+ if (is_null($file)) {
return "File does not exist";
}
- if(Application_Model_Preference::GetUploadToSoundcloudOption())
- {
- for($i=0; $i<$CC_CONFIG['soundcloud-connection-retries']; $i++) {
+ if (Application_Model_Preference::GetUploadToSoundcloudOption()) {
+ for ($i=0; $i<$CC_CONFIG['soundcloud-connection-retries']; $i++) {
$description = $file->getDbTrackTitle();
$tag = array();
$genre = $file->getDbGenre();
@@ -1079,8 +1094,7 @@ Logging::log("getting media! - 2");
$this->setSoundCloudLinkToFile($soundcloud_res['permalink_url']);
$this->setSoundCloudUploadTime(new DateTime("now"), new DateTimeZone("UTC"));
break;
- }
- catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
+ } catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
$code = $e->getHttpCode();
$msg = $e->getHttpBody();
$temp = explode('"error":',$msg);
@@ -1089,7 +1103,7 @@ Logging::log("getting media! - 2");
$this->setSoundCloudErrorMsg($msg);
// setting sc id to -3 which indicates error
$this->setSoundCloudFileId(SOUNDCLOUD_ERROR);
- if(!in_array($code, array(0, 100))) {
+ if (!in_array($code, array(0, 100))) {
break;
}
}
diff --git a/airtime_mvc/application/models/StreamSetting.php b/airtime_mvc/application/models/StreamSetting.php
index d3db99da9..cdbee0106 100644
--- a/airtime_mvc/application/models/StreamSetting.php
+++ b/airtime_mvc/application/models/StreamSetting.php
@@ -1,6 +1,6 @@
query($sql)->fetchColumn(0);
+
return ($result !== false) ? $result : null;
}
}
@@ -120,11 +121,11 @@ class Application_Model_StreamSetting {
foreach ($rows as $r) {
if ($r['keyname'] == 'master_live_stream_port') {
$exists['master_live_stream_port'] = true;
- } elseif($r['keyname'] == 'master_live_stream_mp') {
+ } elseif ($r['keyname'] == 'master_live_stream_mp') {
$exists['master_live_stream_mp'] = true;
- } elseif($r['keyname'] == 'dj_live_stream_port') {
+ } elseif ($r['keyname'] == 'dj_live_stream_port') {
$exists['dj_live_stream_port'] = true;
- } elseif($r['keyname'] == 'dj_live_stream_mp') {
+ } elseif ($r['keyname'] == 'dj_live_stream_mp') {
$exists['dj_live_stream_mp'] = true;
}
}
@@ -149,6 +150,7 @@ class Application_Model_StreamSetting {
"value"=>self::getDjLiveStreamMountPoint(),
"type"=>"string");
}
+
return $rows;
}
@@ -168,10 +170,10 @@ class Application_Model_StreamSetting {
$v = $d == 1?"true":"false";
$sql = "UPDATE cc_stream_setting SET value='$v' WHERE keyname='$key'";
$con->exec($sql);
- } else if ($key == "output_sound_device_type") {
+ } elseif ($key == "output_sound_device_type") {
$sql = "UPDATE cc_stream_setting SET value='$d' WHERE keyname='$key'";
$con->exec($sql);
- } else if (is_array($d)) {
+ } elseif (is_array($d)) {
$temp = explode('_', $key);
$prefix = $temp[0];
foreach ($d as $k => $v) {
@@ -198,7 +200,7 @@ class Application_Model_StreamSetting {
*/
public static function setIndivisualStreamSetting($data)
{
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
foreach ($data as $keyname => $v) {
$sql = "UPDATE cc_stream_setting SET value='$v' WHERE keyname='$keyname'";
@@ -212,7 +214,7 @@ class Application_Model_StreamSetting {
*/
public static function setLiquidsoapError($stream_id, $msg, $boot_time=null)
{
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
$update_time = Application_Model_Preference::GetStreamUpdateTimestemp();
if ($boot_time == null || $boot_time > $update_time) {
@@ -234,7 +236,7 @@ class Application_Model_StreamSetting {
public static function getLiquidsoapError($stream_id)
{
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
$keyname = "s".$stream_id."_liquidsoap_error";
$sql = "SELECT value FROM cc_stream_setting"
@@ -246,7 +248,7 @@ class Application_Model_StreamSetting {
public static function getStreamEnabled($stream_id)
{
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
$keyname = "s" . $stream_id . "_enable";
$sql = "SELECT value FROM cc_stream_setting"
@@ -257,6 +259,7 @@ class Application_Model_StreamSetting {
} else {
$result = true;
}
+
return $result;
}
@@ -266,7 +269,7 @@ class Application_Model_StreamSetting {
*/
public static function getStreamInfoForDataCollection()
{
- $con = Propel::getConnection();
+ $con = Propel::getConnection();
$out = array();
$enabled_stream = self::getEnabledStreamIds();
@@ -286,6 +289,7 @@ class Application_Model_StreamSetting {
$out[$stream] = $info;
}
}
+
return $out;
}
diff --git a/airtime_mvc/application/models/Subjects.php b/airtime_mvc/application/models/Subjects.php
index 15432d56f..6aa2708a2 100644
--- a/airtime_mvc/application/models/Subjects.php
+++ b/airtime_mvc/application/models/Subjects.php
@@ -14,8 +14,8 @@ define('ALIBERR_BADSMEMB', 21);
* @copyright 2010 Sourcefabric O.P.S.
* @license http://www.gnu.org/licenses/gpl.txt
*/
-class Application_Model_Subjects {
-
+class Application_Model_Subjects
+{
/* ======================================================= public methods */
public static function increaseLoginAttempts($login)
@@ -25,6 +25,7 @@ class Application_Model_Subjects {
$sql = "UPDATE ".$CC_CONFIG['subjTable']." SET login_attempts = login_attempts+1"
." WHERE login='$login'";
$res = $con->exec($sql);
+
return (intval($res) > 0);
}
@@ -35,6 +36,7 @@ class Application_Model_Subjects {
$sql = "UPDATE ".$CC_CONFIG['subjTable']." SET login_attempts = '0'"
." WHERE login='$login'";
$res = $con->exec($sql);
+
return true;
}
@@ -44,8 +46,8 @@ class Application_Model_Subjects {
$con = Propel::getConnection();
$sql = "SELECT login_attempts FROM ".$CC_CONFIG['subjTable']." WHERE login='$login'";
$res = $con->query($sql)->fetchColumn(0);
+
return ($res !== false) ? $res : 0;
}
} // class Subjects
-
diff --git a/airtime_mvc/application/models/Systemstatus.php b/airtime_mvc/application/models/Systemstatus.php
index 6bde9f144..6c97605c2 100644
--- a/airtime_mvc/application/models/Systemstatus.php
+++ b/airtime_mvc/application/models/Systemstatus.php
@@ -3,7 +3,8 @@
class Application_Model_Systemstatus
{
- public static function GetMonitStatus($p_ip){
+ public static function GetMonitStatus($p_ip)
+ {
global $CC_CONFIG;
$monit_user = $CC_CONFIG['monit_user'];
$monit_password = $CC_CONFIG['monit_password'];
@@ -22,8 +23,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;
@@ -33,8 +34,8 @@ class Application_Model_Systemstatus
return $docRoot;
}
- public static function ExtractServiceInformation($p_docRoot, $p_serviceName){
-
+ public static function ExtractServiceInformation($p_docRoot, $p_serviceName)
+ {
$starting = array(
"name"=>"",
"process_id"=>"STARTING...",
@@ -65,76 +66,75 @@ class Application_Model_Systemstatus
);
$data = $notRunning;
-
- if (!is_null($p_docRoot)){
- foreach ($p_docRoot->getElementsByTagName("service") AS $item)
- {
- if ($item->getElementsByTagName("name")->item(0)->nodeValue == $p_serviceName){
+ 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");
- if ($monitor->length > 0){
+ if ($monitor->length > 0) {
$status = $monitor->item(0)->nodeValue;
- if ($status == "2"){
+ if ($status == "2") {
$data = $starting;
- } else if ($status == 1){
+ } elseif ($status == 1) {
//is monitored, but is it running?
$pid = $item->getElementsByTagName("pid");
- if ($pid->length == 0){
+ if ($pid->length == 0) {
$data = $notRunning;
} else {
//running!
}
- } else if ($status == 0){
+ } elseif ($status == 0) {
$data = $notMonitored;
}
}
$process_id = $item->getElementsByTagName("name");
- if ($process_id->length > 0){
+ if ($process_id->length > 0) {
$data["name"] = $process_id->item(0)->nodeValue;
}
$process_id = $item->getElementsByTagName("pid");
- if ($process_id->length > 0){
+ if ($process_id->length > 0) {
$data["process_id"] = $process_id->item(0)->nodeValue;
$data["status"] = 0;
}
$uptime = $item->getElementsByTagName("uptime");
- if ($uptime->length > 0){
+ if ($uptime->length > 0) {
$data["uptime_seconds"] = $uptime->item(0)->nodeValue;
}
$memory = $item->getElementsByTagName("memory");
- if ($memory->length > 0){
+ 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;
}
$cpu = $item->getElementsByTagName("cpu");
- if ($cpu->length > 0){
+ if ($cpu->length > 0) {
$data["cpu_perc"] = $cpu->item(0)->getElementsByTagName("percent")->item(0)->nodeValue."%";
}
break;
}
}
}
+
return $data;
}
- public static function GetPlatformInfo(){
+ public static function GetPlatformInfo()
+ {
$keys = array("release", "machine", "memory", "swap");
- foreach($keys as $key) {
+ foreach ($keys as $key) {
$data[$key] = "UNKNOWN";
}
$docRoot = self::GetMonitStatus("localhost");
- if (!is_null($docRoot)){
- foreach ($docRoot->getElementsByTagName("platform") AS $item)
- {
- foreach($keys as $key) {
+ if (!is_null($docRoot)) {
+ foreach ($docRoot->getElementsByTagName("platform") AS $item) {
+ foreach ($keys as $key) {
$keyElement = $item->getElementsByTagName($key);
- if($keyElement->length > 0) {
+ if ($keyElement->length > 0) {
$data[$key] = $keyElement->item(0)->nodeValue;
}
}
@@ -144,10 +144,10 @@ class Application_Model_Systemstatus
return $data;
}
- public static function GetPypoStatus(){
-
+ public static function GetPypoStatus()
+ {
$component = CcServiceRegisterQuery::create()->findOneByDbName("pypo");
- if (is_null($component)){
+ if (is_null($component)) {
return null;
} else {
$ip = $component->getDbIp();
@@ -159,10 +159,10 @@ class Application_Model_Systemstatus
}
}
- public static function GetLiquidsoapStatus(){
-
+ public static function GetLiquidsoapStatus()
+ {
$component = CcServiceRegisterQuery::create()->findOneByDbName("pypo");
- if (is_null($component)){
+ if (is_null($component)) {
return null;
} else {
$ip = $component->getDbIp();
@@ -174,10 +174,10 @@ class Application_Model_Systemstatus
}
}
- public static function GetMediaMonitorStatus(){
-
+ public static function GetMediaMonitorStatus()
+ {
$component = CcServiceRegisterQuery::create()->findOneByDbName("media-monitor");
- if (is_null($component)){
+ if (is_null($component)) {
return null;
} else {
$ip = $component->getDbIp();
@@ -189,16 +189,17 @@ class Application_Model_Systemstatus
}
}
- public static function GetIcecastStatus(){
+ public static function GetIcecastStatus()
+ {
$docRoot = self::GetMonitStatus("localhost");
$data = self::ExtractServiceInformation($docRoot, "icecast2");
return $data;
}
- public static function GetRabbitMqStatus(){
-
- if (isset($_SERVER["RABBITMQ_HOST"])){
+ public static function GetRabbitMqStatus()
+ {
+ if (isset($_SERVER["RABBITMQ_HOST"])) {
$rabbitmq_host = $_SERVER["RABBITMQ_HOST"];
} else {
$rabbitmq_host = "localhost";
@@ -209,10 +210,11 @@ class Application_Model_Systemstatus
return $data;
}
- public static function GetDiskInfo(){
+ public static function GetDiskInfo()
+ {
$partions = array();
- if (isset($_SERVER['AIRTIME_SRV'])){
+ if (isset($_SERVER['AIRTIME_SRV'])) {
//connect to DB and find how much total space user has allocated.
$totalSpace = Application_Model_Preference::GetDiskQuota();
@@ -229,10 +231,10 @@ class Application_Model_Systemstatus
$musicDirs = Application_Model_MusicDir::getWatchedDirs();
$musicDirs[] = Application_Model_MusicDir::getStorDir();
- foreach($musicDirs as $md){
+ foreach ($musicDirs as $md) {
$totalSpace = disk_total_space($md->getDirectory());
- if (!isset($partitions[$totalSpace])){
+ if (!isset($partitions[$totalSpace])) {
$partitions[$totalSpace] = new StdClass;
$partitions[$totalSpace]->totalSpace = $totalSpace;
$partitions[$totalSpace]->totalFreeSpace = disk_free_space($md->getDirectory());
diff --git a/airtime_mvc/application/models/User.php b/airtime_mvc/application/models/User.php
index c62735050..ffb137ad9 100644
--- a/airtime_mvc/application/models/User.php
+++ b/airtime_mvc/application/models/User.php
@@ -5,8 +5,8 @@ define('UTYPE_ADMIN', 'A');
define('UTYPE_GUEST', 'G');
define('UTYPE_PROGRAM_MANAGER', 'P');
-class Application_Model_User {
-
+class Application_Model_User
+{
private $_userInstance;
public function __construct($userId)
@@ -28,8 +28,8 @@ class Application_Model_User {
}
public function isGuest()
- {
- return $this->getType() == UTYPE_GUEST;
+ {
+ return $this->getType() == UTYPE_GUEST;
}
public function isHost($showId)
@@ -66,7 +66,7 @@ class Application_Model_User {
if (is_array($type)) {
$result = false;
foreach ($type as $t) {
- switch($t){
+ switch ($t) {
case UTYPE_ADMIN:
$result = $this->_userInstance->getDbType() === 'A';
break;
@@ -85,11 +85,12 @@ class Application_Model_User {
}
}
} else {
- switch($type) {
+ switch ($type) {
case UTYPE_ADMIN:
return $this->_userInstance->getDbType() === 'A';
case UTYPE_HOST:
$userId = $this->_userInstance->getDbId();
+
return CcShowHostsQuery::create()->filterByDbShow($showId)->filterByDbHost($userId)->count() > 0;
case UTYPE_PROGRAM_MANAGER:
return $this->_userInstance->getDbType() === 'P';
@@ -154,54 +155,63 @@ class Application_Model_User {
public function getLogin()
{
$user = $this->_userInstance;
+
return $user->getDbLogin();
}
public function getPassword()
{
$user = $this->_userInstance;
+
return $user->getDbPass();
}
public function getFirstName()
{
$user = $this->_userInstance;
+
return $user->getDbFirstName();
}
public function getLastName()
{
$user = $this->_userInstance;
+
return $user->getDbLastName();
}
public function getType()
{
$user = $this->_userInstance;
+
return $user->getDbType();
}
public function getEmail()
{
$user = $this->_userInstance;
+
return $user->getDbEmail();
}
public function getCellPhone()
{
$user = $this->_userInstance;
+
return $user->getDbCellPhone();
}
public function getSkype()
{
$user = $this->_userInstance;
+
return $user->getDbSkypeContact();
}
public function getJabber()
{
$user = $this->_userInstance;
+
return $user->getDbJabberContact();
}
@@ -221,6 +231,7 @@ class Application_Model_User {
private function createUser()
{
$user = new CcSubjs();
+
return $user;
}
@@ -275,6 +286,7 @@ class Application_Model_User {
}
$query = $con->query($sql)->fetchColumn(0);
+
return ($query !== false) ? $query : null;
}
@@ -337,6 +349,7 @@ class Application_Model_User {
//we get here if $userinfo->id is defined, but doesn't exist
//in the database anymore.
Zend_Auth::getInstance()->clearIdentity();
+
return null;
}
}
diff --git a/airtime_mvc/application/views/scripts/api/get-files-without-replay-gain.phtml b/airtime_mvc/application/views/scripts/api/get-files-without-replay-gain.phtml
deleted file mode 100644
index 9d38517bd..000000000
--- a/airtime_mvc/application/views/scripts/api/get-files-without-replay-gain.phtml
+++ /dev/null
@@ -1,8 +0,0 @@
-rows as $row) {
- echo json_encode($row)."\n";
-}
diff --git a/airtime_mvc/build/schema.xml b/airtime_mvc/build/schema.xml
index 1850a6aff..dbc13cf27 100644
--- a/airtime_mvc/build/schema.xml
+++ b/airtime_mvc/build/schema.xml
@@ -98,7 +98,7 @@
-
+
diff --git a/install_minimal/upgrades/airtime-2.2.0/TODO b/install_minimal/upgrades/airtime-2.2.0/TODO
index 7f40b6bb1..037b6cd5f 100644
--- a/install_minimal/upgrades/airtime-2.2.0/TODO
+++ b/install_minimal/upgrades/airtime-2.2.0/TODO
@@ -6,4 +6,4 @@ flac
vorbis-tools
-calculate Replay Gain dB on upgrade.
+calculate Replay Gain dB on upgrade: the default value should be NULL.
diff --git a/python_apps/api_clients/api_client.cfg b/python_apps/api_clients/api_client.cfg
index 1cbf9e322..d6d3c13bc 100644
--- a/python_apps/api_clients/api_client.cfg
+++ b/python_apps/api_clients/api_client.cfg
@@ -96,9 +96,6 @@ update_item_url = 'notify-schedule-group-play/api_key/%%api_key%%/schedule_id/%%
# Update whether an audio clip is currently playing.
update_start_playing_url = 'notify-media-item-start-play/api_key/%%api_key%%/media_id/%%media_id%%/schedule_id/%%schedule_id%%'
-# ???
-generate_range_url = 'generate_range_dp.php'
-
# URL to tell Airtime we want to get stream setting
get_stream_setting = 'get-stream-setting/format/json/api_key/%%api_key%%/'
@@ -113,5 +110,6 @@ update_source_status = 'update-source-status/format/json/api_key/%%api_key%%/sou
get_bootstrap_info = 'get-bootstrap-info/format/json/api_key/%%api_key%%'
-get-files-without-replay-gain = 'get-files-without-replay-gain/api_key/%%api_key%%/dir_id/%%dir_id%%''
+get_files_without_replay_gain = 'get-files-without-replay-gain/api_key/%%api_key%%/dir_id/%%dir_id%%'
+update_replay_gain_value = 'update-replay-gain-value/api_key/%%api_key%%'
diff --git a/python_apps/api_clients/api_client.py b/python_apps/api_clients/api_client.py
index f4c8505e5..3e53f2d32 100644
--- a/python_apps/api_clients/api_client.py
+++ b/python_apps/api_clients/api_client.py
@@ -381,7 +381,9 @@ class AirTimeApiClient():
self.logger.debug("Warning: Sending a request element without a 'mode'")
self.logger.debug("Here is the the request: '%s'" % str(action) )
else: valid_actions.append(action)
- md_list = { i : json.dumps(convert_dict_value_to_utf8(md)) for i,md in enumerate(valid_actions) }
+
+ md_list = dict((i, json.dumps(convert_dict_value_to_utf8(md))) for i,md in enumerate(valid_actions))
+
data = urllib.urlencode(md_list)
req = urllib2.Request(url, data)
response = self.get_response_from_server(req)
@@ -621,15 +623,35 @@ class AirTimeApiClient():
logger = self.logger
try:
- url = "http://%(base_url)s:%(base_port)s/%(api_base)s/%(get-files-without-replay-gain)s/" % (self.config)
+ url = "http://%(base_url)s:%(base_port)s/%(api_base)s/%(get_files_without_replay_gain)s/" % (self.config)
url = url.replace("%%api_key%%", self.config["api_key"])
url = url.replace("%%dir_id%%", dir_id)
+ response = self.get_response_from_server(url)
- file_path = self.get_response_into_file(url)
+ logger.info("update file system mount: %s", response)
+ response = json.loads(response)
+ #file_path = self.get_response_into_file(url)
except Exception, e:
- file_path = None
+ response = None
logger.error('Exception: %s', e)
logger.error("traceback: %s", traceback.format_exc())
- return file_path
+ return response
+ def update_replay_gain_values(self, pairs):
+ """
+ 'pairs' is a list of pairs in (x, y), where x is the file's database row id
+ and y is the file's replay_gain value in dB
+ """
+
+ #http://localhost/api/update-replay-gain-value/
+ try:
+ url = "http://%(base_url)s:%(base_port)s/%(api_base)s/%(update_replay_gain_value)s/" % (self.config)
+ url = url.replace("%%api_key%%", self.config["api_key"])
+ data = urllib.urlencode({'data': json.dumps(pairs)})
+ request = urllib2.Request(url, data)
+
+ self.get_response_from_server(request)
+ except Exception, e:
+ self.logger.error("Exception: %s", e)
+ raise
diff --git a/python_apps/media-monitor2/media/monitor/log.py b/python_apps/media-monitor2/media/monitor/log.py
index 5f1c11597..186adacbd 100644
--- a/python_apps/media-monitor2/media/monitor/log.py
+++ b/python_apps/media-monitor2/media/monitor/log.py
@@ -10,5 +10,6 @@ class Loggable(object):
# TODO : replace this boilerplate with LazyProperty
@LazyProperty
def logger(self):
+ # TODO : Clean this up
if not hasattr(self,"_logger"): self._logger = logging.getLogger('mediamonitor2')
return self._logger
diff --git a/python_apps/media-monitor2/media/update/__init__.py b/python_apps/media-monitor2/media/update/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/python_apps/media-monitor/airtimefilemonitor/replaygain.py b/python_apps/media-monitor2/media/update/replaygain.py
similarity index 100%
rename from python_apps/media-monitor/airtimefilemonitor/replaygain.py
rename to python_apps/media-monitor2/media/update/replaygain.py
diff --git a/python_apps/media-monitor/airtimefilemonitor/replaygainupdater.py b/python_apps/media-monitor2/media/update/replaygainupdater.py
similarity index 59%
rename from python_apps/media-monitor/airtimefilemonitor/replaygainupdater.py
rename to python_apps/media-monitor2/media/update/replaygainupdater.py
index 48d73f58f..f144502ed 100644
--- a/python_apps/media-monitor/airtimefilemonitor/replaygainupdater.py
+++ b/python_apps/media-monitor2/media/update/replaygainupdater.py
@@ -6,16 +6,16 @@ import logging
import json
from api_clients import api_client
-import replaygain
+from media.update import replaygain
class ReplayGainUpdater(Thread):
"""
The purpose of the class is to query the server for a list of files which do not have a ReplayGain
- value calculated. This class will iterate over the list calculate the values, update the server and
- repeat the process until the the server reports there are no files left.
-
- This class will see heavy activity right after a 2.1->2.2 upgrade since 2.2 introduces ReplayGain
+ value calculated. This class will iterate over the list calculate the values, update the server and
+ repeat the process until the server reports there are no files left.
+
+ This class will see heavy activity right after a 2.1->2.2 upgrade since 2.2 introduces ReplayGain
normalization. A fresh install of Airtime 2.2 will see this class not used at all since a file
imported in 2.2 will automatically have its ReplayGain value calculated.
"""
@@ -27,42 +27,32 @@ class ReplayGainUpdater(Thread):
def main(self):
- #TODO
+ #TODO make sure object has 'dirs' attr
directories = self.api_client.list_all_watched_dirs()['dirs']
for dir_id, dir_path in directories.iteritems():
try:
processed_data = []
- #keep getting 100 rows at a time for current music_dir (stor or watched folder).
- #When we get a response with 0 rows, then we will set response to True.
+ #keep getting few rows at a time for current music_dir (stor or watched folder).
+ #When we get a response with 0 rows, then we will set 'finished' to True.
finished = False
while not finished:
# return a list of pairs where the first value is the file's database row id
# and the second value is the filepath
- file_path = self.api_client.get_files_without_replay_gain_value(dir_id)
- print "temp file saved to %s" % file_path
+ files = self.api_client.get_files_without_replay_gain_value(dir_id)
- num_lines = 0
+ for f in files:
+ full_path = os.path.join(dir_path, f['fp'])
+ processed_data.append((f['id'], replaygain.calculate_replay_gain(full_path)))
- with open(file_path) as f:
- for line in f:
- num_lines += 1
- data = json.loads(line.strip())
- track_path = os.path.join(dir_path, data['fp'])
- processed_data.append((data['id'], replaygain.calculate_replay_gain(track_path)))
+ self.api_client.update_replay_gain_values(processed_data)
+ finished = (len(files) == 0)
- if num_lines == 0:
- finished = True
-
- os.remove(file_path)
-
- #send data here
- pass
except Exception, e:
- print e
-
+ self.logger.error(e)
+ self.logger.debug(traceback.format_exc())
def run(self):
try: self.main()
except Exception, e:
@@ -72,7 +62,7 @@ class ReplayGainUpdater(Thread):
if __name__ == "__main__":
try:
rgu = ReplayGainUpdater(logging)
- print rgu.main()
+ rgu.main()
except Exception, e:
print e
print traceback.format_exc()