From ee3447f903a7d0a65b50216fe0884d7f2c8a16eb Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Tue, 10 Jul 2012 18:51:32 -0400 Subject: [PATCH] CC-4090: Make code style PSR compliant -User.php -removed all trailing whitespace --- airtime_mvc/application/Bootstrap.php | 2 +- .../controllers/LibraryController.php | 4 +- .../controllers/ScheduleController.php | 8 +- .../controllers/ShowbuilderController.php | 4 +- airtime_mvc/application/forms/ShowBuilder.php | 2 +- airtime_mvc/application/models/Auth.php | 90 ++-- airtime_mvc/application/models/Dashboard.php | 2 +- airtime_mvc/application/models/Datatables.php | 200 ++++----- airtime_mvc/application/models/Email.php | 18 +- airtime_mvc/application/models/LiveLog.php | 22 +- airtime_mvc/application/models/MusicDir.php | 66 +-- airtime_mvc/application/models/Playlist.php | 118 +++--- .../application/models/PlayoutHistory.php | 152 +++---- airtime_mvc/application/models/Preference.php | 398 +++++++++--------- airtime_mvc/application/models/RabbitMq.php | 8 +- airtime_mvc/application/models/Schedule.php | 188 ++++----- airtime_mvc/application/models/Scheduler.php | 182 ++++---- .../application/models/ServiceRegister.php | 2 +- airtime_mvc/application/models/Show.php | 54 ++- .../application/models/ShowBuilder.php | 86 ++-- .../application/models/ShowInstance.php | 52 +-- airtime_mvc/application/models/Soundcloud.php | 6 +- airtime_mvc/application/models/StoredFile.php | 90 ++-- .../application/models/StreamSetting.php | 18 +- .../application/models/Systemstatus.php | 58 +-- airtime_mvc/application/models/User.php | 248 ++++++----- .../application/models/airtime/CcFiles.php | 2 +- .../application/models/airtime/Common.php | 8 +- .../models/tests/StoredFileTests.php | 4 +- python_apps/pypo/liquidsoap_bin | 2 +- 30 files changed, 1057 insertions(+), 1037 deletions(-) diff --git a/airtime_mvc/application/Bootstrap.php b/airtime_mvc/application/Bootstrap.php index 8e9f875e8..af8cff19a 100644 --- a/airtime_mvc/application/Bootstrap.php +++ b/airtime_mvc/application/Bootstrap.php @@ -83,7 +83,7 @@ class Bootstrap extends Zend_Application_Bootstrap_Bootstrap $view->headScript()->appendFile($baseUrl.'/js/airtime/common/common.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); - $user = Application_Model_User::GetCurrentUser(); + $user = Application_Model_User::getCurrentUser(); if (!is_null($user)){ $userType = $user->getType(); } else { diff --git a/airtime_mvc/application/controllers/LibraryController.php b/airtime_mvc/application/controllers/LibraryController.php index 99fdd923f..27411cf0f 100644 --- a/airtime_mvc/application/controllers/LibraryController.php +++ b/airtime_mvc/application/controllers/LibraryController.php @@ -111,7 +111,7 @@ class LibraryController extends Zend_Controller_Action //array containing id and type of media to delete. $mediaItems = $this->_getParam('media', null); - $user = Application_Model_User::GetCurrentUser(); + $user = Application_Model_User::getCurrentUser(); $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); $files = array(); @@ -204,7 +204,7 @@ class LibraryController extends Zend_Controller_Action public function editFileMdAction() { - $user = Application_Model_User::GetCurrentUser(); + $user = Application_Model_User::getCurrentUser(); $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); if(!$isAdminOrPM){ return; diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index f7293d4ab..5185ceb8a 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -90,7 +90,7 @@ class ScheduleController extends Zend_Controller_Action Application_Model_Schedule::createNewFormSections($this->view); - $user = Application_Model_User::GetCurrentUser(); + $user = Application_Model_User::getCurrentUser(); if($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))){ $this->view->preloadShowForm = true; @@ -689,7 +689,7 @@ class ScheduleController extends Zend_Controller_Action public function getFormAction() { - $user = Application_Model_User::GetCurrentUser(); + $user = Application_Model_User::getCurrentUser(); if($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))){ Application_Model_Schedule::createNewFormSections($this->view); @@ -822,7 +822,7 @@ class ScheduleController extends Zend_Controller_Action public function cancelShowAction() { - $user = Application_Model_User::GetCurrentUser(); + $user = Application_Model_User::getCurrentUser(); if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { $showInstanceId = $this->_getParam('id'); @@ -842,7 +842,7 @@ class ScheduleController extends Zend_Controller_Action public function cancelCurrentShowAction() { - $user = Application_Model_User::GetCurrentUser(); + $user = Application_Model_User::getCurrentUser(); if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { $id = $this->_getParam('id'); diff --git a/airtime_mvc/application/controllers/ShowbuilderController.php b/airtime_mvc/application/controllers/ShowbuilderController.php index 11669b8a2..8b8370528 100644 --- a/airtime_mvc/application/controllers/ShowbuilderController.php +++ b/airtime_mvc/application/controllers/ShowbuilderController.php @@ -22,7 +22,7 @@ class ShowbuilderController extends Zend_Controller_Action $request = $this->getRequest(); $baseUrl = $request->getBaseUrl(); - $user = Application_Model_User::GetCurrentUser(); + $user = Application_Model_User::getCurrentUser(); $userType = $user->getType(); $this->view->headScript()->appendScript("localStorage.setItem( 'user-type', '$userType' );"); @@ -184,7 +184,7 @@ class ShowbuilderController extends Zend_Controller_Action $baseUrl = $request->getBaseUrl(); $menu = array(); - $user = Application_Model_User::GetCurrentUser(); + $user = Application_Model_User::getCurrentUser(); $item = CcScheduleQuery::create()->findPK($id); $instance = $item->getCcShowInstances(); diff --git a/airtime_mvc/application/forms/ShowBuilder.php b/airtime_mvc/application/forms/ShowBuilder.php index f1e1ed3fa..3e551fa24 100644 --- a/airtime_mvc/application/forms/ShowBuilder.php +++ b/airtime_mvc/application/forms/ShowBuilder.php @@ -5,7 +5,7 @@ class Application_Form_ShowBuilder extends Zend_Form_SubForm public function init() { - $user = Application_Model_User::GetCurrentUser(); + $user = Application_Model_User::getCurrentUser(); $this->setDecorators(array( array('ViewScript', array('viewScript' => 'form/showbuilder.phtml')) diff --git a/airtime_mvc/application/models/Auth.php b/airtime_mvc/application/models/Auth.php index cc3cfe4cf..12a3bfe33 100644 --- a/airtime_mvc/application/models/Auth.php +++ b/airtime_mvc/application/models/Auth.php @@ -1,53 +1,53 @@ setDbUserId($user_id); - $info->setDbAction($action); - $info->setDbToken(sha1($token.$salt)); - $info->setDbCreated(gmdate('Y-m-d H:i:s')); - $info->save(); - - Logging::debug("generated token {$token}"); - - return $token; - } - - public function sendPasswordRestoreLink($user, $view) - { + + const TOKEN_LIFETIME = 'P2D'; // DateInterval syntax + + private function generateToken($action, $user_id) + { + $salt = md5("pro"); + $token = self::generateRandomString(); + + $info = new CcSubjsToken(); + $info->setDbUserId($user_id); + $info->setDbAction($action); + $info->setDbToken(sha1($token.$salt)); + $info->setDbCreated(gmdate('Y-m-d H:i:s')); + $info->save(); + + Logging::debug("generated token {$token}"); + + return $token; + } + + public function sendPasswordRestoreLink($user, $view) + { $token = $this->generateToken('password.restore', $user->getDbId()); - + $e_link_protocol = empty($_SERVER['HTTPS']) ? "http" : "https"; $e_link_base = $_SERVER['SERVER_NAME']; $e_link_path = $view->url(array('user_id' => $user->getDbId(), 'token' => $token), 'password-change'); - + $message = "Click this link: {$e_link_protocol}://{$e_link_base}{$e_link_path}"; - - $success = Application_Model_Email::send('Airtime Password Reset', $message, $user->getDbEmail()); - - return $success; - } - - public function invalidateTokens($user, $action) - { - CcSubjsTokenQuery::create() - ->filterByDbAction($action) - ->filterByDbUserId($user->getDbId()) - ->delete(); - } - + + $success = Application_Model_Email::send('Airtime Password Reset', $message, $user->getDbEmail()); + + return $success; + } + + public function invalidateTokens($user, $action) + { + CcSubjsTokenQuery::create() + ->filterByDbAction($action) + ->filterByDbUserId($user->getDbId()) + ->delete(); + } + public function checkToken($user_id, $token, $action) { - $salt = md5("pro"); - + $salt = md5("pro"); + $token_info = CcSubjsTokenQuery::create() ->filterByDbAction($action) ->filterByDbUserId($user_id) @@ -61,10 +61,10 @@ class Application_Model_Auth { $now = new DateTime(); $token_life = new DateInterval(self::TOKEN_LIFETIME); $token_created = new DateTime($token_info->getDbCreated(), new DateTimeZone("UTC")); - + return $now->sub($token_life)->getTimestamp() < $token_created->getTimestamp(); - } - + } + /** * Gets the adapter for authentication against a database table * @@ -79,10 +79,10 @@ class Application_Model_Auth { ->setIdentityColumn('login') ->setCredentialColumn('pass') ->setCredentialTreatment('MD5(?)'); - + return $authAdapter; } - + /** * Get random string * diff --git a/airtime_mvc/application/models/Dashboard.php b/airtime_mvc/application/models/Dashboard.php index 9236ab2c6..7fb270b74 100644 --- a/airtime_mvc/application/models/Dashboard.php +++ b/airtime_mvc/application/models/Dashboard.php @@ -121,7 +121,7 @@ class Application_Model_Dashboard } } else { //return the one that starts sooner. - + if ($row[0]["starts"] <= $showInstance->getShowInstanceStart()){ return array("name"=>$row[0]["artist_name"]." - ".$row[0]["track_title"], "starts"=>$row[0]["starts"], diff --git a/airtime_mvc/application/models/Datatables.php b/airtime_mvc/application/models/Datatables.php index 84b47ec6b..227b8b645 100644 --- a/airtime_mvc/application/models/Datatables.php +++ b/airtime_mvc/application/models/Datatables.php @@ -1,104 +1,104 @@ 0) { - $where = join(" AND ", $where); - $sql = $selectorCount." FROM ".$fromTable." WHERE ".$where; - $sqlTotalDisplayRows = $sql; - - $sql = $selectorRows." FROM ".$fromTable." WHERE ".$where." ORDER BY ".$orderby; - - //limit the results returned. - if ($displayLength !== -1) { - $sql .= " OFFSET ".$data["iDisplayStart"]." LIMIT ".$displayLength; - } - } - else { - $sql = $selectorRows." FROM ".$fromTable." ORDER BY ".$orderby; - - //limit the results returned. - if ($displayLength !== -1) { - $sql .= " OFFSET ".$data["iDisplayStart"]." LIMIT ".$displayLength; - } - } - - try { - $r = $con->query($sqlTotalRows); - $totalRows = $r->fetchColumn(0); - - if (isset($sqlTotalDisplayRows)) { - $r = $con->query($sqlTotalDisplayRows); - $totalDisplayRows = $r->fetchColumn(0); - } - else { - $totalDisplayRows = $totalRows; - } - - $r = $con->query($sql); - $r->setFetchMode(PDO::FETCH_ASSOC); - $results = $r->fetchAll(); - } - catch (Exception $e) { - Logging::debug($e->getMessage()); - } - - return array( - "sEcho" => intval($data["sEcho"]), - "iTotalDisplayRecords" => intval($totalDisplayRows), - "iTotalRecords" => intval($totalRows), - $dataProp => $results - ); - } + + /* + * query used to return data for a paginated/searchable datatable. + */ + public static function findEntries($con, $displayColumns, $fromTable, $data, $dataProp = "aaData") + { + $where = array(); + + if ($data["sSearch"] !== "") { + $searchTerms = explode(" ", $data["sSearch"]); + } + + $selectorCount = "SELECT COUNT(*) "; + $selectorRows = "SELECT ".join(",", $displayColumns)." "; + + $sql = $selectorCount." FROM ".$fromTable; + $sqlTotalRows = $sql; + + if (isset($searchTerms)) { + $searchCols = array(); + for ($i = 0; $i < $data["iColumns"]; $i++) { + if ($data["bSearchable_".$i] == "true") { + $searchCols[] = $data["mDataProp_{$i}"]; + } + } + + $outerCond = array(); + + foreach ($searchTerms as $term) { + $innerCond = array(); + + foreach ($searchCols as $col) { + $escapedTerm = pg_escape_string($term); + $innerCond[] = "{$col}::text ILIKE '%{$escapedTerm}%'"; + } + $outerCond[] = "(".join(" OR ", $innerCond).")"; + } + $where[] = "(".join(" AND ", $outerCond).")"; + } + // End Where clause + + // Order By clause + $orderby = array(); + for ($i = 0; $i < $data["iSortingCols"]; $i++){ + $num = $data["iSortCol_".$i]; + $orderby[] = $data["mDataProp_{$num}"]." ".$data["sSortDir_".$i]; + } + $orderby[] = "id"; + $orderby = join("," , $orderby); + // End Order By clause + + $displayLength = intval($data["iDisplayLength"]); + if (count($where) > 0) { + $where = join(" AND ", $where); + $sql = $selectorCount." FROM ".$fromTable." WHERE ".$where; + $sqlTotalDisplayRows = $sql; + + $sql = $selectorRows." FROM ".$fromTable." WHERE ".$where." ORDER BY ".$orderby; + + //limit the results returned. + if ($displayLength !== -1) { + $sql .= " OFFSET ".$data["iDisplayStart"]." LIMIT ".$displayLength; + } + } + else { + $sql = $selectorRows." FROM ".$fromTable." ORDER BY ".$orderby; + + //limit the results returned. + if ($displayLength !== -1) { + $sql .= " OFFSET ".$data["iDisplayStart"]." LIMIT ".$displayLength; + } + } + + try { + $r = $con->query($sqlTotalRows); + $totalRows = $r->fetchColumn(0); + + if (isset($sqlTotalDisplayRows)) { + $r = $con->query($sqlTotalDisplayRows); + $totalDisplayRows = $r->fetchColumn(0); + } + else { + $totalDisplayRows = $totalRows; + } + + $r = $con->query($sql); + $r->setFetchMode(PDO::FETCH_ASSOC); + $results = $r->fetchAll(); + } + catch (Exception $e) { + Logging::debug($e->getMessage()); + } + + return array( + "sEcho" => intval($data["sEcho"]), + "iTotalDisplayRecords" => intval($totalDisplayRows), + "iTotalRecords" => intval($totalRows), + $dataProp => $results + ); + } } diff --git a/airtime_mvc/application/models/Email.php b/airtime_mvc/application/models/Email.php index 30b4cc190..64c4a4356 100644 --- a/airtime_mvc/application/models/Email.php +++ b/airtime_mvc/application/models/Email.php @@ -1,7 +1,7 @@ 'login', 'ssl' => 'ssl', 'username' => $username, 'password' => $password ); - + if (isset($port)) { $config['port'] = $port; } - - $transport = new Zend_Mail_Transport_Smtp($mailServer, $config); + + $transport = new Zend_Mail_Transport_Smtp($mailServer, $config); } $mail = new Zend_Mail('utf-8'); $mail->setSubject($subject); $mail->setBodyText($message); - + foreach ((array) $tos as $to) { $mail->addTo($to); } @@ -60,8 +60,8 @@ class Application_Model_Email { } catch (Exception $e) { $success = false; } - } - + } + return $success; } diff --git a/airtime_mvc/application/models/LiveLog.php b/airtime_mvc/application/models/LiveLog.php index 5635f1e66..e60589327 100644 --- a/airtime_mvc/application/models/LiveLog.php +++ b/airtime_mvc/application/models/LiveLog.php @@ -26,7 +26,7 @@ class Application_Model_LiveLog ." WHERE state = 'L'" ." ORDER BY id"; $rows = $con->query($sql)->fetchAll(); - + if ($rows != null) { $last_row = self::UpdateLastLogEndTime(array_pop($rows)); array_push($rows, $last_row); @@ -36,7 +36,7 @@ class Application_Model_LiveLog $con->exec($sql_delete); } } - $skip = true; + $skip = true; } $hours = 0; @@ -55,13 +55,13 @@ class Application_Model_LiveLog $intervals[$i] = 0; } } - + // Trim milliseconds (DateInterval does not support) $sec = explode(".", $intervals[2]); if (isset($sec[0])) { $intervals[2] = $sec[0]; } - + $seconds += $intervals[2]; if ($seconds / 60 >= 1) { $minutes += 1; @@ -89,7 +89,7 @@ class Application_Model_LiveLog $minutes = (double)(($hours*60)+$minutes . "." . $seconds[0]); } else { - $minutes = (double)(($hours*60)+$minutes); + $minutes = (double)(($hours*60)+$minutes); } } return $minutes; @@ -100,7 +100,7 @@ class Application_Model_LiveLog } } - public static function GetScheduledDuration($p_keepData=false) + public static function GetScheduledDuration($p_keepData=false) { try { $con = Propel::getConnection(); @@ -125,7 +125,7 @@ class Application_Model_LiveLog ." WHERE state = 'S'" ." ORDER BY id"; $rows = $con->query($sql)->fetchAll(); - + if ($rows != null) { $last_row = self::UpdateLastLogEndTime(array_pop($rows)); array_push($rows, $last_row); @@ -135,7 +135,7 @@ class Application_Model_LiveLog $con->exec($sql_delete); } } - $skip = true; + $skip = true; } $hours = 0; @@ -173,7 +173,7 @@ class Application_Model_LiveLog } } $clip_length_seconds = $clip_length_intervals[0]*3600 + $clip_length_intervals[1]*60 + $clip_length_intervals[2]; - + $extra_time = $extra_time->format("%H:%i:%s"); //Convert extra_time into seconds; $extra_time_intervals = explode(":", $extra_time); @@ -185,7 +185,7 @@ class Application_Model_LiveLog $extra_time_seconds = $extra_time_intervals[0]*3600 + $extra_time_intervals[1]*60 + $extra_time_intervals[2]; $clip_length_seconds -= $extra_time_seconds; - + //Convert new clip_length into "H-i-s" format $clip_length_arr = array(); if ($clip_length_seconds / 3600 >= 1) { @@ -276,7 +276,7 @@ class Application_Model_LiveLog public static function SetNewLogTime($state, $dateTime){ try { $con = Propel::getConnection(); - + $scheduled = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play'); if ($state == 'L' && $scheduled == 'on') { self::SetEndTime('S', $dateTime); diff --git a/airtime_mvc/application/models/MusicDir.php b/airtime_mvc/application/models/MusicDir.php index 70609fad3..f4fd92802 100644 --- a/airtime_mvc/application/models/MusicDir.php +++ b/airtime_mvc/application/models/MusicDir.php @@ -44,35 +44,35 @@ class Application_Model_MusicDir { $this->_dir->setExists($flag); $this->_dir->save(); } - + public function setWatchedFlag($flag){ $this->_dir->setWatched($flag); $this->_dir->save(); } - + public function getWatchedFlag(){ return $this->_dir->getWatched(); } - + public function getExistsFlag(){ return $this->_dir->getExists(); } - - /** + + /** * There are 2 cases where this function can be called. * 1. When watched dir was removed * 2. When some dir was watched, but it was unmounted - * + * * In case of 1, $userAddedWatchedDir should be true * In case of 2, $userAddedWatchedDir should be false - * + * * When $userAddedWatchedDir is true, it will set "Watched" flag to false * otherwise, it will set "Exists" flag to true - */ + */ public function remove($userAddedWatchedDir=true) { $con = Propel::getConnection(); - + $music_dir_id = $this->getId(); $sql = "SELECT DISTINCT s.instance_id from cc_music_dirs as md " @@ -80,12 +80,12 @@ class Application_Model_MusicDir { ." RIGHT JOIN cc_schedule as s on s.file_id = f.id WHERE md.id = $music_dir_id"; $show_instances = $con->query($sql)->fetchAll(); - + // get all the files on this dir $sql = "UPDATE cc_files SET file_exists = 'f' WHERE id IN (SELECT f.id FROM cc_music_dirs as md " ." LEFT JOIN cc_files as f on f.directory = md.id WHERE md.id = $music_dir_id)"; $affected = $con->exec($sql); - + // set RemovedFlag to true if ($userAddedWatchedDir) { self::setWatchedFlag(false); @@ -93,7 +93,7 @@ class Application_Model_MusicDir { self::setExistsFlag(false); } //$res = $this->_dir->delete(); - + foreach ($show_instances as $show_instance_row) { $temp_show = new Application_Model_ShowInstance($show_instance_row["instance_id"]); $temp_show->updateScheduledTime(); @@ -133,7 +133,7 @@ class Application_Model_MusicDir { public static function isPathValid($p_path){ $dirs = self::getWatchedDirs(); $dirs[] = self::getStorDir(); - + foreach ($dirs as $dirObj){ $dir = $dirObj->getDirectory(); $diff = strlen($dir) - strlen($p_path); @@ -156,15 +156,15 @@ class Application_Model_MusicDir { /** There are 2 cases where this function can be called. * 1. When watched dir was added * 2. When some dir was watched, but it was unmounted somehow, but gets mounted again - * + * * In case of 1, $userAddedWatchedDir should be true * In case of 2, $userAddedWatchedDir should be false - * + * * When $userAddedWatchedDir is true, it will set "Removed" flag to false * otherwise, it will set "Exists" flag to true - * + * * @param $nestedWatch - if true, bypass path check, and Watched to false - **/ + **/ public static function addDir($p_path, $p_type, $userAddedWatchedDir=true, $nestedWatch=false) { if(!is_dir($p_path)){ @@ -174,16 +174,16 @@ class Application_Model_MusicDir { if($real_path != "/"){ $p_path = $real_path; } - + $exist_dir = self::getDirByPath($p_path); - + if( $exist_dir == NULL ){ $temp_dir = new CcMusicDirs(); $dir = new Application_Model_MusicDir($temp_dir); }else{ $dir = $exist_dir; } - + $dir->setType($p_type); $p_path = Application_Common_OsPath::normpath($p_path)."/"; @@ -203,7 +203,7 @@ class Application_Model_MusicDir { $dir->setExistsFlag(true); } $dir->setDirectory($p_path); - + return array("code"=>0); } catch (NestedDirectoryException $nde){ $msg = $nde->getMessage(); @@ -217,17 +217,17 @@ class Application_Model_MusicDir { /** There are 2 cases where this function can be called. * 1. When watched dir was added * 2. When some dir was watched, but it was unmounted somehow, but gets mounted again - * + * * In case of 1, $userAddedWatchedDir should be true * In case of 2, $userAddedWatchedDir should be false - * + * * When $userAddedWatchedDir is true, it will set "Watched" flag to true * otherwise, it will set "Exists" flag to true - **/ + **/ public static function addWatchedDir($p_path, $userAddedWatchedDir=true, $nestedWatch=false) { $res = self::addDir($p_path, "watched", $userAddedWatchedDir, $nestedWatch); - + if ($res['code'] == 0){ //convert "linked" files (Airtime <= 1.8.2) to watched files. @@ -296,10 +296,10 @@ class Application_Model_MusicDir { return $mus_dir; } } - + /** * Search and returns watched dirs - * + * * @param $exists search condition with exists flag * @param $watched search condition with watched flag */ @@ -383,16 +383,16 @@ class Application_Model_MusicDir { /** There are 2 cases where this function can be called. * 1. When watched dir was removed * 2. When some dir was watched, but it was unmounted - * + * * In case of 1, $userAddedWatchedDir should be true * In case of 2, $userAddedWatchedDir should be false - * + * * When $userAddedWatchedDir is true, it will set "Watched" flag to false * otherwise, it will set "Exists" flag to true - **/ + **/ public static function removeWatchedDir($p_dir, $userAddedWatchedDir=true){ - - //make sure that $p_dir has a trailing "/" + + //make sure that $p_dir has a trailing "/" $real_path = Application_Common_OsPath::normpath($p_dir)."/"; if($real_path != "/"){ $p_dir = $real_path; @@ -412,7 +412,7 @@ class Application_Model_MusicDir { public static function splitFilePath($p_filepath) { $mus_dir = self::getWatchedDirFromFilepath($p_filepath); - + if(is_null($mus_dir)) { return null; } diff --git a/airtime_mvc/application/models/Playlist.php b/airtime_mvc/application/models/Playlist.php index 70710f567..86985b1b3 100644 --- a/airtime_mvc/application/models/Playlist.php +++ b/airtime_mvc/application/models/Playlist.php @@ -20,17 +20,17 @@ class Application_Model_Playlist { */ private $id; - /** + /** * propel object for this playlist. */ - private $pl; + private $pl; - /** + /** * info needed to insert a new playlist element. */ - private $plItem = array( + private $plItem = array( "id" => "", - "pos" => "", + "pos" => "", "cliplength" => "", "cuein" => "00:00:00", "cueout" => "00:00:00", @@ -38,13 +38,13 @@ class Application_Model_Playlist { "fadeout" => "0.0", ); - //using propel's phpNames. - private $categories = array( - "dc:title" => "Name", - "dc:creator" => "Creator", - "dc:description" => "Description", - "dcterms:extent" => "Length" - ); + //using propel's phpNames. + private $categories = array( + "dc:title" => "Name", + "dc:creator" => "Creator", + "dc:description" => "Description", + "dcterms:extent" => "Length" + ); public function __construct($id=null, $con=null) @@ -90,12 +90,12 @@ class Application_Model_Playlist { */ public function setName($p_newname) { - $this->pl->setDbName($p_newname); - $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); - $this->pl->save($this->con); + $this->pl->setDbName($p_newname); + $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); + $this->pl->save($this->con); } - /** + /** * Get mnemonic playlist name * * @return string @@ -107,9 +107,9 @@ class Application_Model_Playlist { public function setDescription($p_description) { - $this->pl->setDbDescription($p_description); - $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); - $this->pl->save($this->con); + $this->pl->setDbDescription($p_description); + $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); + $this->pl->save($this->con); } public function getDescription() @@ -121,7 +121,7 @@ class Application_Model_Playlist { return $this->pl->getCcSubjs()->getDbLogin(); } - + public function getCreatorId() { return $this->pl->getCcSubjs()->getDbId(); } @@ -145,7 +145,7 @@ class Application_Model_Playlist { /** * Get the entire playlist as a two dimentional array, sorted in order of play. * @param boolean $filterFiles if this is true, it will only return files that has - * file_exists flag set to true + * file_exists flag set to true * @return array */ public function getContents($filterFiles=false) { @@ -155,7 +155,7 @@ class Application_Model_Playlist { $files = array(); $query = CcPlaylistcontentsQuery::create() ->filterByDbPlaylistId($this->id); - + if($filterFiles){ $query->useCcFilesQuery() ->filterByDbFileExists(true) @@ -416,7 +416,7 @@ class Application_Model_Playlist { * Remove audioClip from playlist * * @param array $p_items - * array of unique item ids to remove from the playlist.. + * array of unique item ids to remove from the playlist.. */ public function delAudioClips($p_items) { @@ -452,11 +452,11 @@ class Application_Model_Playlist { } - public function getFadeInfo($pos) { + public function getFadeInfo($pos) { - Logging::log("Getting fade info for pos {$pos}"); + Logging::log("Getting fade info for pos {$pos}"); - $row = CcPlaylistcontentsQuery::create() + $row = CcPlaylistcontentsQuery::create() ->joinWith(CcFilesPeer::OM_CLASS) ->filterByDbPlaylistId($this->id) ->filterByDbPosition($pos) @@ -466,24 +466,24 @@ class Application_Model_Playlist { $fadeIn = $row->getDbFadein(); $fadeOut = $row->getDbFadeout(); return array($fadeIn, $fadeOut); - } + } /** * Change fadeIn and fadeOut values for playlist Element * * @param int $pos - * position of audioclip in playlist + * position of audioclip in playlist * @param string $fadeIn - * new value in ss.ssssss or extent format + * new value in ss.ssssss or extent format * @param string $fadeOut - * new value in ss.ssssss or extent format + * new value in ss.ssssss or extent format * @return boolean */ public function changeFadeInfo($id, $fadeIn, $fadeOut) { //See issue CC-2065, pad the fadeIn and fadeOut so that it is TIME compatable with the DB schema //For the top level PlayList either fadeIn or fadeOut will sometimes be Null so need a gaurd against - //setting it to nonNull for checks down below + //setting it to nonNull for checks down below $fadeIn = $fadeIn?'00:00:'.$fadeIn:$fadeIn; $fadeOut = $fadeOut?'00:00:'.$fadeOut:$fadeOut; @@ -502,8 +502,8 @@ class Application_Model_Playlist { if (!is_null($fadeIn)) { - $sql = "SELECT INTERVAL '{$fadeIn}' > INTERVAL '{$clipLength}'"; - $r = $this->con->query($sql); + $sql = "SELECT INTERVAL '{$fadeIn}' > INTERVAL '{$clipLength}'"; + $r = $this->con->query($sql); if ($r->fetchColumn(0)) { //"Fade In can't be larger than overall playlength."; $fadeIn = $clipLength; @@ -512,8 +512,8 @@ class Application_Model_Playlist { } if (!is_null($fadeOut)){ - $sql = "SELECT INTERVAL '{$fadeOut}' > INTERVAL '{$clipLength}'"; - $r = $this->con->query($sql); + $sql = "SELECT INTERVAL '{$fadeOut}' > INTERVAL '{$clipLength}'"; + $r = $this->con->query($sql); if ($r->fetchColumn(0)) { //Fade Out can't be larger than overall playlength."; $fadeOut = $clipLength; @@ -562,11 +562,11 @@ class Application_Model_Playlist { * Change cueIn/cueOut values for playlist element * * @param int $pos - * position of audioclip in playlist + * position of audioclip in playlist * @param string $cueIn - * new value in ss.ssssss or extent format + * new value in ss.ssssss or extent format * @param string $cueOut - * new value in ss.ssssss or extent format + * new value in ss.ssssss or extent format * @return boolean or pear error object */ public function changeClipLength($id, $cueIn, $cueOut) @@ -604,23 +604,23 @@ class Application_Model_Playlist { $cueOut = $origLength; } - $sql = "SELECT INTERVAL '{$cueIn}' > INTERVAL '{$cueOut}'"; - $r = $this->con->query($sql); + $sql = "SELECT INTERVAL '{$cueIn}' > INTERVAL '{$cueOut}'"; + $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); + $sql = "SELECT INTERVAL '{$cueOut}' > INTERVAL '{$origLength}'"; + $r = $this->con->query($sql); if ($r->fetchColumn(0)){ $errArray["error"] = "Can't set cue out to be greater than file length."; return $errArray; } - $sql = "SELECT INTERVAL '{$cueOut}' - INTERVAL '{$cueIn}'"; - $r = $this->con->query($sql); - $cliplength = $r->fetchColumn(0); + $sql = "SELECT INTERVAL '{$cueOut}' - INTERVAL '{$cueIn}'"; + $r = $this->con->query($sql); + $cliplength = $r->fetchColumn(0); $row->setDbCuein($cueIn); $row->setDbCueout($cueOut); @@ -629,16 +629,16 @@ class Application_Model_Playlist { } else if (!is_null($cueIn)) { - $sql = "SELECT INTERVAL '{$cueIn}' > INTERVAL '{$oldCueOut}'"; - $r = $this->con->query($sql); + $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; } $sql = "SELECT INTERVAL '{$oldCueOut}' - INTERVAL '{$cueIn}'"; - $r = $this->con->query($sql); - $cliplength = $r->fetchColumn(0); + $r = $this->con->query($sql); + $cliplength = $r->fetchColumn(0); $row->setDbCuein($cueIn); $row->setDBCliplength($cliplength); @@ -649,23 +649,23 @@ class Application_Model_Playlist { $cueOut = $origLength; } - $sql = "SELECT INTERVAL '{$cueOut}' < INTERVAL '{$oldCueIn}'"; - $r = $this->con->query($sql); + $sql = "SELECT INTERVAL '{$cueOut}' < INTERVAL '{$oldCueIn}'"; + $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); + $sql = "SELECT INTERVAL '{$cueOut}' > INTERVAL '{$origLength}'"; + $r = $this->con->query($sql); if ($r->fetchColumn(0)){ $errArray["error"] = "Can't set cue out to be greater than file length."; return $errArray; } $sql = "SELECT INTERVAL '{$cueOut}' - INTERVAL '{$oldCueIn}'"; - $r = $this->con->query($sql); - $cliplength = $r->fetchColumn(0); + $r = $this->con->query($sql); + $cliplength = $r->fetchColumn(0); $row->setDbCueout($cueOut); $row->setDBCliplength($cliplength); @@ -673,15 +673,15 @@ class Application_Model_Playlist { $cliplength = $row->getDbCliplength(); - $sql = "SELECT INTERVAL '{$fadeIn}' > INTERVAL '{$cliplength}'"; - $r = $this->con->query($sql); + $sql = "SELECT INTERVAL '{$fadeIn}' > INTERVAL '{$cliplength}'"; + $r = $this->con->query($sql); if ($r->fetchColumn(0)){ $fadeIn = $cliplength; $row->setDbFadein($fadeIn); } - $sql = "SELECT INTERVAL '{$fadeOut}' > INTERVAL '{$cliplength}'"; - $r = $this->con->query($sql); + $sql = "SELECT INTERVAL '{$fadeOut}' > INTERVAL '{$cliplength}'"; + $r = $this->con->query($sql); if ($r->fetchColumn(0)){ $fadeOut = $cliplength; $row->setDbFadein($fadeOut); diff --git a/airtime_mvc/application/models/PlayoutHistory.php b/airtime_mvc/application/models/PlayoutHistory.php index a5e4b9fb1..6dad4bee3 100644 --- a/airtime_mvc/application/models/PlayoutHistory.php +++ b/airtime_mvc/application/models/PlayoutHistory.php @@ -4,80 +4,80 @@ require_once 'formatters/LengthFormatter.php'; class Application_Model_PlayoutHistory { - private $con; - private $timezone; - - //in UTC timezone - private $startDT; - //in UTC timezone - private $endDT; - - private $epoch_now; - private $opts; - - private $mDataPropMap = array( - "artist" => "file.artist_name", - "title" => "file.track_title", - "played" => "playout.played", - "length" => "file.length", - "composer" => "file.composer", - "copyright" => "file.copyright", - ); - - 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->epoch_now = time(); - $this->opts = $p_opts; - } - - /* - * map front end mDataProp labels to proper column names for searching etc. - */ - private function translateColumns() { - - for ($i = 0; $i < $this->opts["iColumns"]; $i++){ - - $this->opts["mDataProp_{$i}"] = $this->mDataPropMap[$this->opts["mDataProp_{$i}"]]; - } - } - - public function getItems() { - - $this->translateColumns(); - - $select = array( - "file.track_title as title", - "file.artist_name as artist", - "playout.played", - "playout.file_id", - "file.composer", - "file.copyright", - "file.length" - ); - - $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 - 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 - ) - AS playout left join cc_files as file on (file.id = playout.file_id)"; + private $con; + private $timezone; + + //in UTC timezone + private $startDT; + //in UTC timezone + private $endDT; + + private $epoch_now; + private $opts; - $results = Application_Model_Datatables::findEntries($this->con, $select, $historyTable, $this->opts, "history"); - - foreach ($results["history"] as &$row) { - $formatter = new LengthFormatter($row['length']); - $row['length'] = $formatter->format(); - } - - return $results; - } -} \ No newline at end of file + private $mDataPropMap = array( + "artist" => "file.artist_name", + "title" => "file.track_title", + "played" => "playout.played", + "length" => "file.length", + "composer" => "file.composer", + "copyright" => "file.copyright", + ); + + 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->epoch_now = time(); + $this->opts = $p_opts; + } + + /* + * map front end mDataProp labels to proper column names for searching etc. + */ + private function translateColumns() { + + for ($i = 0; $i < $this->opts["iColumns"]; $i++){ + + $this->opts["mDataProp_{$i}"] = $this->mDataPropMap[$this->opts["mDataProp_{$i}"]]; + } + } + + public function getItems() { + + $this->translateColumns(); + + $select = array( + "file.track_title as title", + "file.artist_name as artist", + "playout.played", + "playout.file_id", + "file.composer", + "file.copyright", + "file.length" + ); + + $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 + 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 + ) + 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']); + $row['length'] = $formatter->format(); + } + + return $results; + } +} diff --git a/airtime_mvc/application/models/Preference.php b/airtime_mvc/application/models/Preference.php index dab365005..582058d7c 100644 --- a/airtime_mvc/application/models/Preference.php +++ b/airtime_mvc/application/models/Preference.php @@ -3,7 +3,7 @@ class Application_Model_Preference { - public static function setValue($key, $value, $isUserValue = false){ + public static function setValue($key, $value, $isUserValue = false){ try { $con = Propel::getConnection(); @@ -27,7 +27,7 @@ class Application_Model_Preference if($isUserValue) { $sql .= " AND subjid = '$id'"; } - + $result = $con->query($sql)->fetchColumn(0); if($value == "") { @@ -35,7 +35,7 @@ class Application_Model_Preference }else { $value = "'$value'"; } - + if($result == 1) { // result found if(is_null($id) || !$isUserValue) { @@ -63,7 +63,7 @@ class Application_Model_Preference } $con->exec($sql); - + } catch (Exception $e){ header('HTTP/1.0 503 Service Unavailable'); Logging::log("Could not connect to database: ".$e->getMessage()); @@ -72,7 +72,7 @@ class Application_Model_Preference } - public static function getValue($key, $isUserValue = false){ + public static function getValue($key, $isUserValue = false){ try { $con = Propel::getConnection(); @@ -105,7 +105,7 @@ class Application_Model_Preference } catch (Exception $e) { header('HTTP/1.0 503 Service Unavailable'); Logging::log("Could not connect to database: ".$e->getMessage()); - exit; + exit; } } @@ -171,12 +171,12 @@ class Application_Model_Preference public static function GetDefaultFade() { $fade = self::getValue("default_fade"); - + if ($fade === "") { // the default value of the fade is 00.500000 return "00.500000"; } - + // 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){ @@ -187,7 +187,7 @@ class Application_Model_Preference $out .= ".$matches[4]"; $fade = $out; } - + $fade = number_format($fade, 6); //fades need 2 leading zeros for DateTime conversion $fade = str_pad($fade, 9, "0", STR_PAD_LEFT); @@ -298,75 +298,75 @@ class Application_Model_Preference } public static function SetPhone($phone){ - self::setValue("phone", $phone); + self::setValue("phone", $phone); } public static function GetPhone(){ - return self::getValue("phone"); + return self::getValue("phone"); } - public static function SetEmail($email){ - self::setValue("email", $email); + public static function SetEmail($email){ + self::setValue("email", $email); } public static function GetEmail(){ - return self::getValue("email"); + return self::getValue("email"); } - public static function SetStationWebSite($site){ - self::setValue("station_website", $site); + public static function SetStationWebSite($site){ + self::setValue("station_website", $site); } public static function GetStationWebSite(){ - return self::getValue("station_website"); + return self::getValue("station_website"); } - public static function SetSupportFeedback($feedback){ - self::setValue("support_feedback", $feedback); + public static function SetSupportFeedback($feedback){ + self::setValue("support_feedback", $feedback); } public static function GetSupportFeedback(){ - return self::getValue("support_feedback"); + return self::getValue("support_feedback"); } - public static function SetPublicise($publicise){ - self::setValue("publicise", $publicise); + public static function SetPublicise($publicise){ + self::setValue("publicise", $publicise); } public static function GetPublicise(){ - return self::getValue("publicise"); + return self::getValue("publicise"); } - public static function SetRegistered($registered){ - self::setValue("registered", $registered); + public static function SetRegistered($registered){ + self::setValue("registered", $registered); } public static function GetRegistered(){ - return self::getValue("registered"); + return self::getValue("registered"); } - public static function SetStationCountry($country){ - self::setValue("country", $country); + public static function SetStationCountry($country){ + self::setValue("country", $country); } public static function GetStationCountry(){ - return self::getValue("country"); + return self::getValue("country"); } - public static function SetStationCity($city){ - self::setValue("city", $city); + public static function SetStationCity($city){ + self::setValue("city", $city); } - public static function GetStationCity(){ - return self::getValue("city"); + public static function GetStationCity(){ + return self::getValue("city"); } - public static function SetStationDescription($description){ - self::setValue("description", $description); + public static function SetStationDescription($description){ + self::setValue("description", $description); } - public static function GetStationDescription(){ - return self::getValue("description"); + public static function GetStationDescription(){ + return self::getValue("description"); } public static function SetTimezone($timezone){ @@ -380,139 +380,139 @@ class Application_Model_Preference } public static function SetStationLogo($imagePath){ - if(!empty($imagePath)){ - $image = @file_get_contents($imagePath); - $image = base64_encode($image); - self::setValue("logoImage", $image); - } + if(!empty($imagePath)){ + $image = @file_get_contents($imagePath); + $image = base64_encode($image); + self::setValue("logoImage", $image); + } } - public static function GetStationLogo(){ - return self::getValue("logoImage"); + public static function GetStationLogo(){ + return self::getValue("logoImage"); } public static function GetUniqueId(){ - return self::getValue("uniqueId"); + return self::getValue("uniqueId"); } public static function GetCountryList() { - $con = Propel::getConnection(); - $sql = "SELECT * FROM cc_country"; - $res = $con->query($sql)->fetchAll(); - $out = array(); - $out[""] = "Select Country"; - foreach($res as $r){ - $out[$r["isocode"]] = $r["name"]; - } - return $out; + $con = Propel::getConnection(); + $sql = "SELECT * FROM cc_country"; + $res = $con->query($sql)->fetchAll(); + $out = array(); + $out[""] = "Select Country"; + foreach($res as $r){ + $out[$r["isocode"]] = $r["name"]; + } + return $out; } public static function GetSystemInfo($returnArray=false, $p_testing=false) { - exec('/usr/bin/airtime-check-system --no-color', $output); - $output = preg_replace('/\s+/', ' ', $output); + exec('/usr/bin/airtime-check-system --no-color', $output); + $output = preg_replace('/\s+/', ' ', $output); - $systemInfoArray = array(); - foreach( $output as $key => &$out){ - $info = explode('=', $out); - if(isset($info[1])){ - $key = str_replace(' ', '_', trim($info[0])); - $key = strtoupper($key); - if ($key == 'WEB_SERVER' || $key == 'CPU' || $key == 'OS' || $key == 'TOTAL_RAM' || - $key == 'FREE_RAM' || $key == 'AIRTIME_VERSION' || $key == 'KERNAL_VERSION' || - $key == 'MACHINE_ARCHITECTURE' || $key == 'TOTAL_MEMORY_MBYTES' || $key == 'TOTAL_SWAP_MBYTES' || - $key == 'PLAYOUT_ENGINE_CPU_PERC' ) { - if($key == 'AIRTIME_VERSION'){ - // remove hash tag on the version string - $version = explode('+', $info[1]); - $systemInfoArray[$key] = $version[0]; - }else{ - $systemInfoArray[$key] = $info[1]; - } - } - } - } - - $outputArray = array(); + $systemInfoArray = array(); + foreach( $output as $key => &$out){ + $info = explode('=', $out); + if(isset($info[1])){ + $key = str_replace(' ', '_', trim($info[0])); + $key = strtoupper($key); + if ($key == 'WEB_SERVER' || $key == 'CPU' || $key == 'OS' || $key == 'TOTAL_RAM' || + $key == 'FREE_RAM' || $key == 'AIRTIME_VERSION' || $key == 'KERNAL_VERSION' || + $key == 'MACHINE_ARCHITECTURE' || $key == 'TOTAL_MEMORY_MBYTES' || $key == 'TOTAL_SWAP_MBYTES' || + $key == 'PLAYOUT_ENGINE_CPU_PERC' ) { + if($key == 'AIRTIME_VERSION'){ + // remove hash tag on the version string + $version = explode('+', $info[1]); + $systemInfoArray[$key] = $version[0]; + }else{ + $systemInfoArray[$key] = $info[1]; + } + } + } + } - $outputArray['LIVE_DURATION'] = Application_Model_LiveLog::GetLiveShowDuration($p_testing); - $outputArray['SCHEDULED_DURATION'] = Application_Model_LiveLog::GetScheduledDuration($p_testing); - $outputArray['SOUNDCLOUD_ENABLED'] = self::GetUploadToSoundcloudOption(); + $outputArray = array(); + + $outputArray['LIVE_DURATION'] = Application_Model_LiveLog::GetLiveShowDuration($p_testing); + $outputArray['SCHEDULED_DURATION'] = Application_Model_LiveLog::GetScheduledDuration($p_testing); + $outputArray['SOUNDCLOUD_ENABLED'] = self::GetUploadToSoundcloudOption(); if ($outputArray['SOUNDCLOUD_ENABLED']) { - $outputArray['NUM_SOUNDCLOUD_TRACKS_UPLOADED'] = Application_Model_StoredFile::getSoundCloudUploads(); + $outputArray['NUM_SOUNDCLOUD_TRACKS_UPLOADED'] = Application_Model_StoredFile::getSoundCloudUploads(); } else { $outputArray['NUM_SOUNDCLOUD_TRACKS_UPLOADED'] = NULL; } - $outputArray['STATION_NAME'] = self::GetStationName(); - $outputArray['PHONE'] = self::GetPhone(); - $outputArray['EMAIL'] = self::GetEmail(); - $outputArray['STATION_WEB_SITE'] = self::GetStationWebSite(); - $outputArray['STATION_COUNTRY'] = self::GetStationCountry(); - $outputArray['STATION_CITY'] = self::GetStationCity(); - $outputArray['STATION_DESCRIPTION'] = self::GetStationDescription(); + $outputArray['STATION_NAME'] = self::GetStationName(); + $outputArray['PHONE'] = self::GetPhone(); + $outputArray['EMAIL'] = self::GetEmail(); + $outputArray['STATION_WEB_SITE'] = self::GetStationWebSite(); + $outputArray['STATION_COUNTRY'] = self::GetStationCountry(); + $outputArray['STATION_CITY'] = self::GetStationCity(); + $outputArray['STATION_DESCRIPTION'] = self::GetStationDescription(); - // get web server info - if(isset($systemInfoArray["AIRTIME_VERSION_URL"])){ - $url = $systemInfoArray["AIRTIME_VERSION_URL"]; + // get web server info + if(isset($systemInfoArray["AIRTIME_VERSION_URL"])){ + $url = $systemInfoArray["AIRTIME_VERSION_URL"]; $index = strpos($url,'/api/'); $url = substr($url, 0, $index); $headerInfo = get_headers(trim($url),1); $outputArray['WEB_SERVER'] = $headerInfo['Server'][0]; - } + } - $outputArray['NUM_OF_USERS'] = Application_Model_User::getUserCount(); - $outputArray['NUM_OF_SONGS'] = Application_Model_StoredFile::getFileCount(); - $outputArray['NUM_OF_PLAYLISTS'] = Application_Model_Playlist::getPlaylistCount(); - $outputArray['NUM_OF_SCHEDULED_PLAYLISTS'] = Application_Model_Schedule::getSchduledPlaylistCount(); - $outputArray['NUM_OF_PAST_SHOWS'] = Application_Model_ShowInstance::GetShowInstanceCount(gmdate("Y-m-d H:i:s")); - $outputArray['UNIQUE_ID'] = self::GetUniqueId(); - $outputArray['SAAS'] = self::GetPlanLevel(); - if ($outputArray['SAAS'] != 'disabled') { - $outputArray['TRIAL_END_DATE'] = self::GetTrialEndingDate(); - } else { + $outputArray['NUM_OF_USERS'] = Application_Model_User::getUserCount(); + $outputArray['NUM_OF_SONGS'] = Application_Model_StoredFile::getFileCount(); + $outputArray['NUM_OF_PLAYLISTS'] = Application_Model_Playlist::getPlaylistCount(); + $outputArray['NUM_OF_SCHEDULED_PLAYLISTS'] = Application_Model_Schedule::getSchduledPlaylistCount(); + $outputArray['NUM_OF_PAST_SHOWS'] = Application_Model_ShowInstance::GetShowInstanceCount(gmdate("Y-m-d H:i:s")); + $outputArray['UNIQUE_ID'] = self::GetUniqueId(); + $outputArray['SAAS'] = self::GetPlanLevel(); + if ($outputArray['SAAS'] != 'disabled') { + $outputArray['TRIAL_END_DATE'] = self::GetTrialEndingDate(); + } else { $outputArray['TRIAL_END_DATE'] = NULL; } - $outputArray['INSTALL_METHOD'] = self::GetInstallMethod(); - $outputArray['NUM_OF_STREAMS'] = self::GetNumOfStreams(); - $outputArray['STREAM_INFO'] = Application_Model_StreamSetting::getStreamInfoForDataCollection(); + $outputArray['INSTALL_METHOD'] = self::GetInstallMethod(); + $outputArray['NUM_OF_STREAMS'] = self::GetNumOfStreams(); + $outputArray['STREAM_INFO'] = Application_Model_StreamSetting::getStreamInfoForDataCollection(); - $outputArray = array_merge($systemInfoArray, $outputArray); + $outputArray = array_merge($systemInfoArray, $outputArray); - $outputString = "\n"; - foreach($outputArray as $key => $out){ - if($key == 'TRIAL_END_DATE' && ($out != '' || $out != 'NULL')){ - continue; - } - if($key == "STREAM_INFO"){ - $outputString .= $key." :\n"; - foreach($out as $s_info){ - foreach($s_info as $k => $v){ - $outputString .= "\t".strtoupper($k)." : ".$v."\n"; - } - } - }else if ($key == "SOUNDCLOUD_ENABLED") { - if ($out) { - $outputString .= $key." : TRUE\n"; - } else if (!$out) { - $outputString .= $key." : FALSE\n"; - } - }else if ($key == "SAAS") { + $outputString = "\n"; + foreach($outputArray as $key => $out){ + if($key == 'TRIAL_END_DATE' && ($out != '' || $out != 'NULL')){ + continue; + } + if($key == "STREAM_INFO"){ + $outputString .= $key." :\n"; + foreach($out as $s_info){ + foreach($s_info as $k => $v){ + $outputString .= "\t".strtoupper($k)." : ".$v."\n"; + } + } + }else if ($key == "SOUNDCLOUD_ENABLED") { + if ($out) { + $outputString .= $key." : TRUE\n"; + } else if (!$out) { + $outputString .= $key." : FALSE\n"; + } + }else if ($key == "SAAS") { if (strcmp($out, 'disabled')!=0) { $outputString .= $key.' : '.$out."\n"; } - }else{ - $outputString .= $key.' : '.$out."\n"; - } - } - if($returnArray){ - $outputArray['PROMOTE'] = self::GetPublicise(); - $outputArray['LOGOIMG'] = self::GetStationLogo(); - return $outputArray; - }else{ - return $outputString; - } + }else{ + $outputString .= $key.' : '.$out."\n"; + } + } + if($returnArray){ + $outputArray['PROMOTE'] = self::GetPublicise(); + $outputArray['LOGOIMG'] = self::GetStationLogo(); + return $outputArray; + }else{ + return $outputString; + } } public static function GetInstallMethod(){ @@ -530,8 +530,8 @@ class Application_Model_Preference } public static function SetRemindMeDate(){ - $weekAfter = mktime(0, 0, 0, gmdate("m"), gmdate("d")+7, gmdate("Y")); - self::setValue("remindme", $weekAfter); + $weekAfter = mktime(0, 0, 0, gmdate("m"), gmdate("d")+7, gmdate("Y")); + self::setValue("remindme", $weekAfter); } public static function GetRemindMeDate(){ @@ -679,7 +679,7 @@ class Application_Model_Preference } public static function GetWeekStartDay() { - $val = self::getValue("week_start_day"); + $val = self::getValue("week_start_day"); if (strlen($val) == 0){ return "0"; } else { @@ -721,7 +721,7 @@ class Application_Model_Preference /** * Sets the time scale preference (agendaDay/agendaWeek/month) in Calendar. * - * @param $timeScale new time scale + * @param $timeScale new time scale */ public static function SetCalendarTimeScale($timeScale) { self::setValue("calendar_time_scale", $timeScale, true /* user specific */); @@ -736,16 +736,16 @@ class Application_Model_Preference if(strlen($val) == 0) { $val = "month"; } - return $val; + return $val; } /** * Sets the number of entries to show preference in library under Playlist Builder. * - * @param $numEntries new number of entries to show + * @param $numEntries new number of entries to show */ public static function SetLibraryNumEntries($numEntries) { - self::setValue("library_num_entries", $numEntries, true /* user specific */); + self::setValue("library_num_entries", $numEntries, true /* user specific */); } /** @@ -753,7 +753,7 @@ class Application_Model_Preference * Defaults to 10 if no entry exists */ public static function GetLibraryNumEntries() { - $val = self::getValue("library_num_entries", true /* user specific */); + $val = self::getValue("library_num_entries", true /* user specific */); if(strlen($val) == 0) { $val = "10"; } @@ -763,7 +763,7 @@ class Application_Model_Preference /** * Sets the time interval preference in Calendar. * - * @param $timeInterval new time interval + * @param $timeInterval new time interval */ public static function SetCalendarTimeInterval($timeInterval) { self::setValue("calendar_time_interval", $timeInterval, true /* user specific */); @@ -774,7 +774,7 @@ class Application_Model_Preference * Defaults to 30 min if no entry exists */ public static function GetCalendarTimeInterval() { - $val = self::getValue("calendar_time_interval", true /* user specific */); + $val = self::getValue("calendar_time_interval", true /* user specific */); if(strlen($val) == 0) { $val = "30"; } @@ -842,7 +842,7 @@ class Application_Model_Preference public static function GetMasterDJSourceConnectionURL(){ return self::getValue("master_dj_source_connection_url"); } - + public static function SetLiveDJSourceConnectionURL($value){ self::setValue("live_dj_source_connection_url", $value, false); } @@ -850,55 +850,55 @@ class Application_Model_Preference public static function GetLiveDJSourceConnectionURL(){ return self::getValue("live_dj_source_connection_url"); } - + /* Source Connection URL override status starts */ public static function GetLiveDjConnectionUrlOverride(){ return self::getValue("live_dj_connection_url_override"); } - + public static function SetLiveDjConnectionUrlOverride($value){ self::setValue("live_dj_connection_url_override", $value, false); } - + public static function GetMasterDjConnectionUrlOverride(){ return self::getValue("master_dj_connection_url_override"); } - + 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){ self::setValue("auto_transition", $value, false); } - + public static function GetAutoTransition(){ return self::getValue("auto_transition"); } - + public static function SetAutoSwitch($value){ self::setValue("auto_switch", $value, false); } - + public static function GetAutoSwitch(){ return self::getValue("auto_switch"); } - + 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; } - + public static function SetSystemEmail($value) { self::setValue("system_email", $value, false); } @@ -906,46 +906,46 @@ class Application_Model_Preference 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() { - return self::getValue("mail_server_configured"); - } - - public static function SetMailServer($value) { - self::setValue("mail_server", $value, false); - } - - public static function GetMailServer() { - return self::getValue("mail_server"); - } - - public static function SetMailServerEmailAddress($value) { - self::setValue("mail_server_email_address", $value, false); - } - - public static function GetMailServerEmailAddress() { - return self::getValue("mail_server_email_address"); - } - - public static function SetMailServerPassword($value) { - self::setValue("mail_server_password", $value, false); - } - - public static function GetMailServerPassword() { - return self::getValue("mail_server_password"); - } - - public static function SetMailServerPort($value) { - self::setValue("mail_server_port", $value, false); - } - - public static function GetMailServerPort() { - return self::getValue("mail_server_port"); - } + self::setValue("mail_server_configured", $value, false); + } + + public static function GetMailServerConfigured() { + return self::getValue("mail_server_configured"); + } + + public static function SetMailServer($value) { + self::setValue("mail_server", $value, false); + } + + public static function GetMailServer() { + return self::getValue("mail_server"); + } + + public static function SetMailServerEmailAddress($value) { + self::setValue("mail_server_email_address", $value, false); + } + + public static function GetMailServerEmailAddress() { + return self::getValue("mail_server_email_address"); + } + + public static function SetMailServerPassword($value) { + self::setValue("mail_server_password", $value, false); + } + + public static function GetMailServerPassword() { + return self::getValue("mail_server_password"); + } + + public static function SetMailServerPort($value) { + self::setValue("mail_server_port", $value, false); + } + + public static function GetMailServerPort() { + return self::getValue("mail_server_port"); + } /* User specific preferences end */ public static function ShouldShowPopUp(){ diff --git a/airtime_mvc/application/models/RabbitMq.php b/airtime_mvc/application/models/RabbitMq.php index 4e00da379..973cc34a2 100644 --- a/airtime_mvc/application/models/RabbitMq.php +++ b/airtime_mvc/application/models/RabbitMq.php @@ -61,7 +61,7 @@ class Application_Model_RabbitMq $channel->close(); $conn->close(); } - + public static function SendMessageToShowRecorder($event_type) { global $CC_CONFIG; @@ -73,10 +73,10 @@ class Application_Model_RabbitMq $CC_CONFIG["rabbitmq"]["vhost"]); $channel = $conn->channel(); $channel->access_request($CC_CONFIG["rabbitmq"]["vhost"], false, false, true, true); - + $EXCHANGE = 'airtime-pypo'; $channel->exchange_declare($EXCHANGE, 'direct', false, true); - + $now = new DateTime("@".time()); //in UTC timezone $end_timestamp = new DateTime("@".(time() + 3600*2)); //in UTC timezone @@ -87,7 +87,7 @@ class Application_Model_RabbitMq } $data = json_encode($temp); $msg = new AMQPMessage($data, array('content_type' => 'text/plain')); - + $channel->basic_publish($msg, $EXCHANGE); $channel->close(); $conn->close(); diff --git a/airtime_mvc/application/models/Schedule.php b/airtime_mvc/application/models/Schedule.php index 9f2e3ddb9..be0f52238 100644 --- a/airtime_mvc/application/models/Schedule.php +++ b/airtime_mvc/application/models/Schedule.php @@ -81,7 +81,7 @@ class Application_Model_Schedule { /* Alternate SQL...merge conflict and I'm not sure which on is right.... -MK $sql = 'Select ft.artist_name, ft.track_title, st.starts as starts, st.ends as ends, st.media_item_played as media_item_played, si.ends as show_ends - FROM cc_schedule st LEFT JOIN cc_files ft ON st.file_id = ft.id + FROM cc_schedule st LEFT JOIN cc_files ft ON st.file_id = ft.id WHERE '; */ @@ -231,15 +231,15 @@ class Application_Model_Schedule { return $row; } - /* - * - * @param DateTime $p_startDateTime - * - * @param DateTime $p_endDateTime - * - * @return array $scheduledItems - * - */ + /* + * + * @param DateTime $p_startDateTime + * + * @param DateTime $p_endDateTime + * + * @return array $scheduledItems + * + */ public static function GetScheduleDetailItems($p_start, $p_end, $p_shows) { global $CC_CONFIG; @@ -279,7 +279,7 @@ class Application_Model_Schedule { } $sql .= " ORDER BY si.starts, sched.starts;"; - + Logging::debug($sql); $rows = $con->query($sql)->fetchAll(); @@ -297,17 +297,17 @@ class Application_Model_Schedule { $live_dj = Application_Model_Preference::GetSourceSwitchStatus('live_dj') == 'on'?true:false; $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){ $sql .= ", broadcasted=1"; } - + $sql .= " WHERE id=$p_id"; - + $retVal = $con->exec($sql); return $retVal; } - + public static function UpdateBrodcastedStatus($dateTime, $value){ global $CC_CONFIG; $con = Propel::getConnection(); @@ -551,7 +551,7 @@ class Application_Model_Schedule { $data["media"][$kick_start]['end'] = $kick_start; $data["media"][$kick_start]['event_type'] = "kick_out"; $data["media"][$kick_start]['type'] = "event"; - + if($kick_time !== $switch_off_time){ $switch_start = Application_Model_Schedule::AirtimeTimeToPypoTime($switch_off_time); $data["media"][$switch_start]['start'] = $switch_start; @@ -562,16 +562,16 @@ class Application_Model_Schedule { } foreach ($items as $item){ - + $showInstance = CcShowInstancesQuery::create()->findPK($item["instance_id"]); $showId = $showInstance->getDbShowId(); $show = CcShowQuery::create()->findPK($showId); $showName = $show->getDbName(); - + $showEndDateTime = new DateTime($item["show_end"], $utcTimeZone); $trackStartDateTime = new DateTime($item["start"], $utcTimeZone); $trackEndDateTime = new DateTime($item["end"], $utcTimeZone); - + if ($trackStartDateTime->getTimestamp() > $showEndDateTime->getTimestamp()){ continue; } @@ -584,10 +584,10 @@ class Application_Model_Schedule { $item["cue_out"] = $di->format("%H:%i:%s").".000"; $item["end"] = $showEndDateTime->format("Y-m-d H:i:s"); } - + $storedFile = Application_Model_StoredFile::Recall($item["file_id"]); $uri = $storedFile->getFilePath(); - + $start = Application_Model_Schedule::AirtimeTimeToPypoTime($item["start"]); $data["media"][$start] = array( 'id' => $storedFile->getGunid(), @@ -614,7 +614,7 @@ class Application_Model_Schedule { $con = Propel::getConnection(); $con->exec("TRUNCATE TABLE ".$CC_CONFIG["scheduleTable"]); } - + public static function deleteWithFileId($fileId){ global $CC_CONFIG; $con = Propel::getConnection(); @@ -626,18 +626,18 @@ class Application_Model_Schedule { $isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; $formWhat = new Application_Form_AddShowWhat(); - $formWho = new Application_Form_AddShowWho(); - $formWhen = new Application_Form_AddShowWhen(); - $formRepeats = new Application_Form_AddShowRepeats(); - $formStyle = new Application_Form_AddShowStyle(); - $formLive = new Application_Form_AddShowLiveStream(); + $formWho = new Application_Form_AddShowWho(); + $formWhen = new Application_Form_AddShowWhen(); + $formRepeats = new Application_Form_AddShowRepeats(); + $formStyle = new Application_Form_AddShowStyle(); + $formLive = new Application_Form_AddShowLiveStream(); - $formWhat->removeDecorator('DtDdWrapper'); - $formWho->removeDecorator('DtDdWrapper'); - $formWhen->removeDecorator('DtDdWrapper'); - $formRepeats->removeDecorator('DtDdWrapper'); - $formStyle->removeDecorator('DtDdWrapper'); - $formLive->removeDecorator('DtDdWrapper'); + $formWhat->removeDecorator('DtDdWrapper'); + $formWho->removeDecorator('DtDdWrapper'); + $formWhen->removeDecorator('DtDdWrapper'); + $formRepeats->removeDecorator('DtDdWrapper'); + $formStyle->removeDecorator('DtDdWrapper'); + $formLive->removeDecorator('DtDdWrapper'); $p_view->what = $formWhat; $p_view->when = $formWhen; @@ -646,7 +646,7 @@ class Application_Model_Schedule { $p_view->style = $formStyle; $p_view->live = $formLive; - $formWhat->populate(array('add_show_id' => '-1', + $formWhat->populate(array('add_show_id' => '-1', 'add_show_instance_id' => '-1')); $formWhen->populate(array('add_show_start_date' => date("Y-m-d"), 'add_show_start_time' => '00:00', @@ -671,29 +671,29 @@ class Application_Model_Schedule { } $p_view->addNewShow = true; } - - /* This function is responsible for handling the case where an individual + + /* This function is responsible for handling the case where an individual * show instance in a repeating show was edited (via the context menu in the Calendar). * 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){ $isSaas = (Application_Model_Preference::GetPlanLevel() != 'disabled'); - - $formWhat = new Application_Form_AddShowWhat(); - $formWhen = new Application_Form_AddShowWhen(); - $formRepeats = new Application_Form_AddShowRepeats(); - $formWho = new Application_Form_AddShowWho(); - $formStyle = new Application_Form_AddShowStyle(); - $formLive = new Application_Form_AddShowLiveStream(); - $formWhat->removeDecorator('DtDdWrapper'); - $formWhen->removeDecorator('DtDdWrapper'); - $formRepeats->removeDecorator('DtDdWrapper'); - $formWho->removeDecorator('DtDdWrapper'); - $formStyle->removeDecorator('DtDdWrapper'); - $formLive->removeDecorator('DtDdWrapper'); - + $formWhat = new Application_Form_AddShowWhat(); + $formWhen = new Application_Form_AddShowWhen(); + $formRepeats = new Application_Form_AddShowRepeats(); + $formWho = new Application_Form_AddShowWho(); + $formStyle = new Application_Form_AddShowStyle(); + $formLive = new Application_Form_AddShowLiveStream(); + + $formWhat->removeDecorator('DtDdWrapper'); + $formWhen->removeDecorator('DtDdWrapper'); + $formRepeats->removeDecorator('DtDdWrapper'); + $formWho->removeDecorator('DtDdWrapper'); + $formStyle->removeDecorator('DtDdWrapper'); + $formLive->removeDecorator('DtDdWrapper'); + if(!$isSaas){ $formRecord = new Application_Form_AddShowRR(); $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); @@ -704,21 +704,21 @@ class Application_Model_Schedule { $formRebroadcast->removeDecorator('DtDdWrapper'); } $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')); - + $end_dt = new DateTime($data['add_show_end_date_no_repeat']." ".$data['add_show_end_time'], new DateTimeZone(date_default_timezone_get())); $end_dt->setTimezone(new DateTimeZone('UTC')); - + $ccShowInstance = CcShowInstancesQuery::create()->findPK($data["add_show_instance_id"]); $ccShowInstance->setDbStarts($start_dt); $ccShowInstance->setDbEnds($end_dt); - $ccShowInstance->save(); - + $ccShowInstance->save(); + Application_Model_Schedule::createNewFormSections($controller->view); - + return true; } else { $formWhat->disable(); @@ -727,36 +727,36 @@ class Application_Model_Schedule { $formWho->disable(); $formStyle->disable(); //$formLive->disable(); - + $controller->view->what = $formWhat; $controller->view->when = $formWhen; $controller->view->repeats = $formRepeats; $controller->view->who = $formWho; $controller->view->style = $formStyle; - $controller->view->live = $formLive; + $controller->view->live = $formLive; if(!$isSaas){ $controller->view->rr = $formRecord; $controller->view->absoluteRebroadcast = $formAbsoluteRebroadcast; $controller->view->rebroadcast = $formRebroadcast; - + //$formRecord->disable(); //$formAbsoluteRebroadcast->disable(); //$formRebroadcast->disable(); } return false; - } + } } - - /* This function is responsible for handling the case where the entire show (not a single show instance) + + /* This function is responsible for handling the case where the entire show (not a single show instance) * was edited (via the context menu in the Calendar). * 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. * Another clean-up is to move all the form manipulation to the proper form class..... - * -Martin + * -Martin */ 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)); @@ -765,22 +765,22 @@ class Application_Model_Schedule { $record = false; $formWhat = new Application_Form_AddShowWhat(); - $formWho = new Application_Form_AddShowWho(); - $formWhen = new Application_Form_AddShowWhen(); - $formRepeats = new Application_Form_AddShowRepeats(); - $formStyle = new Application_Form_AddShowStyle(); - $formLive = new Application_Form_AddShowLiveStream(); + $formWho = new Application_Form_AddShowWho(); + $formWhen = new Application_Form_AddShowWhen(); + $formRepeats = new Application_Form_AddShowRepeats(); + $formStyle = new Application_Form_AddShowStyle(); + $formLive = new Application_Form_AddShowLiveStream(); - $formWhat->removeDecorator('DtDdWrapper'); - $formWho->removeDecorator('DtDdWrapper'); - $formWhen->removeDecorator('DtDdWrapper'); - $formRepeats->removeDecorator('DtDdWrapper'); - $formStyle->removeDecorator('DtDdWrapper'); - $formLive->removeDecorator('DtDdWrapper'); + $formWhat->removeDecorator('DtDdWrapper'); + $formWho->removeDecorator('DtDdWrapper'); + $formWhen->removeDecorator('DtDdWrapper'); + $formRepeats->removeDecorator('DtDdWrapper'); + $formStyle->removeDecorator('DtDdWrapper'); + $formLive->removeDecorator('DtDdWrapper'); - $what = $formWhat->isValid($data); - $when = $formWhen->isValid($data); - $live = $formLive->isValid($data); + $what = $formWhat->isValid($data); + $when = $formWhen->isValid($data); + $live = $formLive->isValid($data); if($when) { $when = $formWhen->checkReliantFields($data, $validateStartDate, $originalStartDate, $update, $instanceId); } @@ -798,11 +798,11 @@ class Application_Model_Schedule { $mValue = 0; if($hPos !== false){ - $hValue = trim(substr($data["add_show_duration"], 0, $hPos)); + $hValue = trim(substr($data["add_show_duration"], 0, $hPos)); } if($mPos !== false){ $hPos = $hPos === FALSE ? 0 : $hPos+1; - $mValue = trim(substr($data["add_show_duration"], $hPos, -1 )); + $mValue = trim(substr($data["add_show_duration"], $hPos, -1 )); } $data["add_show_duration"] = $hValue.":".$mValue; @@ -821,7 +821,7 @@ class Application_Model_Schedule { } if($data["add_show_repeats"]) { - $repeats = $formRepeats->isValid($data); + $repeats = $formRepeats->isValid($data); if($repeats) { $repeats = $formRepeats->checkReliantFields($data); } @@ -857,8 +857,8 @@ class Application_Model_Schedule { } } - $who = $formWho->isValid($data); - $style = $formStyle->isValid($data); + $who = $formWho->isValid($data); + $style = $formStyle->isValid($data); if ($what && $when && $repeats && $who && $style && $live) { if(!$isSaas){ if($record && $rebroadAb && $rebroad){ @@ -882,7 +882,7 @@ class Application_Model_Schedule { $controller->view->rebroadcast = $formRebroadcast; $controller->view->live = $formLive; //$controller->view->addNewShow = !$editShow; - + //$controller->view->form = $controller->view->render('schedule/add-show-form.phtml'); return false; @@ -898,14 +898,14 @@ class Application_Model_Schedule { //$controller->view->newForm = $controller->view->render('schedule/add-show-form.phtml'); return true; } - } else { + } else { $controller->view->what = $formWhat; $controller->view->when = $formWhen; $controller->view->repeats = $formRepeats; $controller->view->who = $formWho; $controller->view->style = $formStyle; $controller->view->live = $formLive; - + if(!$isSaas){ $controller->view->rr = $formRecord; $controller->view->absoluteRebroadcast = $formAbsoluteRebroadcast; @@ -916,14 +916,14 @@ class Application_Model_Schedule { return false; } } - - 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; - + $con = Propel::getConnection(); - + if ($update) { $sql = "SELECT id, starts, ends FROM ".$CC_CONFIG["showInstances"]." where ends <= '{$show_end->format('Y-m-d H:i:s')}' @@ -933,12 +933,12 @@ class Application_Model_Schedule { where ends <= '{$show_end->format('Y-m-d H:i:s')}' order by ends"; } $rows = $con->query($sql); - + foreach($rows as $row) { $start = new DateTime($row["starts"], new DateTimeZone('UTC')); $end = new DateTime($row["ends"], new DateTimeZone('UTC')); - if ($show_start->getTimestamp() < $end->getTimestamp() && + if ($show_start->getTimestamp() < $end->getTimestamp() && $show_end->getTimestamp() > $start->getTimestamp()) { $overlapping = true; break; diff --git a/airtime_mvc/application/models/Scheduler.php b/airtime_mvc/application/models/Scheduler.php index 3e7a39aa7..6e8e21278 100644 --- a/airtime_mvc/application/models/Scheduler.php +++ b/airtime_mvc/application/models/Scheduler.php @@ -12,46 +12,46 @@ class Application_Model_Scheduler { "fadeout" => "00:00:00", "sched_id" => null, ); - + private $epochNow; private $nowDT; private $user; - + private $checkUserPermissions = true; 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){ // DateTime::createFromFormat does not support millisecond string formatting in PHP 5.3.2 (Ubuntu 10.04). // In PHP 5.3.3 (Ubuntu 10.10), this has been fixed. $this->nowDT = DateTime::createFromFormat("U", time(), new DateTimeZone("UTC")); - } - - $this->user = Application_Model_User::GetCurrentUser(); + } + + $this->user = Application_Model_User::getCurrentUser(); } - + 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) { - + $nowEpoch = floatval($this->nowDT->format("U.u")); - + for ($i = 0; $i < count($items); $i++) { $id = $items[$i]["id"]; - + //could be added to the beginning of a show, which sends id = 0; if ($id > 0) { $schedInfo[$id] = $items[$i]["instance"]; @@ -59,11 +59,11 @@ class Application_Model_Scheduler { $instanceInfo[$items[$i]["instance"]] = $items[$i]["timestamp"]; } - + if (count($instanceInfo) === 0) { throw new Exception("Invalid Request."); } - + $schedIds = array(); if (isset($schedInfo)) { $schedIds = array_keys($schedInfo); @@ -71,41 +71,41 @@ class Application_Model_Scheduler { $schedItems = CcScheduleQuery::create()->findPKs($schedIds, $this->con); $instanceIds = array_keys($instanceInfo); $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)"); } - + //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!"); } } - + foreach ($showInstances as $instance) { - + $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()}."); } - + $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; if ($ts < $lastSchedTs) { @@ -196,17 +196,17 @@ class Application_Model_Scheduler { $endEpoch = bcadd($startEpoch , (string) $durationSeconds, 6); $dt = DateTime::createFromFormat("U.u", $endEpoch, new DateTimeZone("UTC")); - + if ($dt === false) { //PHP 5.3.2 problem $dt = DateTime::createFromFormat("U", intval($endEpoch), new DateTimeZone("UTC")); } - + return $dt; } - + private function findNextStartTime($DT, $instance) { - + $sEpoch = $DT->format("U.u"); $nEpoch = $this->epochNow; @@ -215,7 +215,7 @@ class Application_Model_Scheduler { //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); @@ -231,10 +231,10 @@ class Application_Model_Scheduler { else { $nextDT = $DT; } - + return $nextDT; } - + /* * @param int $showInstance * @param array $exclude @@ -267,7 +267,7 @@ class Application_Model_Scheduler { $itemStartDT = $itemEndDT; } - + $schedule->save($this->con); } @@ -291,20 +291,20 @@ class Application_Model_Scheduler { } $startProfile = microtime(true); - + foreach ($scheduleItems as $schedule) { $id = intval($schedule["id"]); - + if ($id !== 0) { $schedItem = CcScheduleQuery::create()->findPK($id, $this->con); $instance = $schedItem->getCcShowInstances($this->con); - + $schedItemEndDT = $schedItem->getDbEnds(null); $nextStartDT = $this->findNextStartTime($schedItemEndDT, $instance); } //selected empty row to add after else { - + $instance = CcShowInstancesQuery::create()->findPK($schedule["instance"], $this->con); $showStartDT = $instance->getDbStarts(null); @@ -316,16 +316,16 @@ class Application_Model_Scheduler { } if ($adjustSched === true) { - + $pstart = microtime(true); - + $followingSchedItems = CcScheduleQuery::create() ->filterByDBStarts($nextStartDT->format("Y-m-d H:i:s.u"), Criteria::GREATER_EQUAL) ->filterByDbInstanceId($instance->getDbId()) ->filterByDbId($excludeIds, Criteria::NOT_IN) ->orderByDbStarts() ->find($this->con); - + $pend = microtime(true); Logging::debug("finding all following items."); Logging::debug(floatval($pend) - floatval($pstart)); @@ -359,26 +359,26 @@ class Application_Model_Scheduler { } if ($adjustSched === true) { - + $pstart = microtime(true); - + //recalculate the start/end times after the inserted items. foreach ($followingSchedItems as $item) { - + $endTimeDT = $this->findEndTime($nextStartDT, $item->getDbClipLength()); $item->setDbStarts($nextStartDT); $item->setDbEnds($endTimeDT); $item->save($this->con); - $nextStartDT = $endTimeDT; + $nextStartDT = $endTimeDT; } - + $pend = microtime(true); Logging::debug("adjusting all following items."); Logging::debug(floatval($pend) - floatval($pstart)); } } - + $endProfile = microtime(true); Logging::debug("finished adding scheduled items."); Logging::debug(floatval($endProfile) - floatval($startProfile)); @@ -389,22 +389,22 @@ class Application_Model_Scheduler { ->find($this->con); $startProfile = microtime(true); - + foreach ($instances as $instance) { $instance->updateScheduleStatus($this->con); } - + $endProfile = microtime(true); Logging::debug("updating show instances status."); Logging::debug(floatval($endProfile) - floatval($startProfile)); $startProfile = microtime(true); - + //update the last scheduled timestamp. CcShowInstancesQuery::create() ->filterByPrimaryKeys($affectedShowInstances) ->update(array('DbLastScheduled' => new DateTime("now", new DateTimeZone("UTC"))), $this->con); - + $endProfile = microtime(true); Logging::debug("updating last scheduled timestamp."); Logging::debug(floatval($endProfile) - floatval($startProfile)); @@ -426,7 +426,7 @@ class Application_Model_Scheduler { $schedFiles = array(); try { - + $this->validateRequest($scheduleItems); foreach ($mediaItems as $media) { @@ -451,31 +451,31 @@ class Application_Model_Scheduler { public function moveItem($selectedItems, $afterItems, $adjustSched = true) { $startProfile = microtime(true); - + $this->con->beginTransaction(); $this->con->useDebug(true); - + try { - + $this->validateRequest($selectedItems); $this->validateRequest($afterItems); - + $endProfile = microtime(true); Logging::debug("validating move request took:"); Logging::debug(floatval($endProfile) - floatval($startProfile)); $afterInstance = CcShowInstancesQuery::create()->findPK($afterItems[0]["instance"], $this->con); - + //map show instances to cc_schedule primary keys. $modifiedMap = array(); $movedData = array(); - + //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); - + $data = $this->fileInfo; $data["id"] = $selected->getDbFileId(); $data["cliplength"] = $selected->getDbClipLength(); @@ -484,48 +484,48 @@ class Application_Model_Scheduler { $data["fadein"] = $selected->getDbFadeIn(); $data["fadeout"] = $selected->getDbFadeOut(); $data["sched_id"] = $selected->getDbId(); - + $movedData[] = $data; - + //figure out which items must be removed from calculated show times. $showInstanceId = $selectedInstance->getDbId(); $schedId = $selected->getDbId(); if (isset($modifiedMap[$showInstanceId])) { - array_push($modifiedMap[$showInstanceId], $schedId); + array_push($modifiedMap[$showInstanceId], $schedId); } else { $modifiedMap[$showInstanceId] = array($schedId); } - } + } //calculate times excluding the to be moved items. foreach ($modifiedMap as $instance => $schedIds) { $startProfile = microtime(true); - + $this->removeGaps($instance, $schedIds); - + $endProfile = microtime(true); Logging::debug("removing gaps from instance $instance:"); Logging::debug(floatval($endProfile) - floatval($startProfile)); } - + $startProfile = microtime(true); - + $this->insertAfter($afterItems, $movedData, $adjustSched); - + $endProfile = microtime(true); Logging::debug("inserting after removing gaps."); Logging::debug(floatval($endProfile) - floatval($startProfile)); - + $afterInstanceId = $afterInstance->getDbId(); $modified = array_keys($modifiedMap); //need to adjust shows we have moved items from. foreach($modified as $instanceId) { - + $instance = CcShowInstancesQuery::create()->findPK($instanceId, $this->con); $instance->updateScheduleStatus($this->con); } - + $this->con->useDebug(false); $this->con->commit(); @@ -543,9 +543,9 @@ class Application_Model_Scheduler { $this->con->beginTransaction(); try { - + $this->validateRequest($scheduledItems); - + $scheduledIds = array(); foreach ($scheduledItems as $item) { $scheduledIds[] = $item["id"]; @@ -555,25 +555,25 @@ class Application_Model_Scheduler { //check to make sure all items selected are up to date foreach ($removedItems as $removedItem) { - + $instance = $removedItem->getCcShowInstances($this->con); - + //check to truncate the currently playing item instead of deleting it. if ($removedItem->isCurrentItem($this->epochNow)) { - + $nEpoch = $this->epochNow; $sEpoch = $removedItem->getDbStarts('U.u'); - + $length = bcsub($nEpoch , $sEpoch , 6); $cliplength = Application_Model_Playlist::secondsToPlaylistTime($length); - + $cueinSec = Application_Model_Playlist::playlistTimeToSeconds($removedItem->getDbCueIn()); $cueOutSec = bcadd($cueinSec , $length, 6); $cueout = Application_Model_Playlist::secondsToPlaylistTime($cueOutSec); - + $removedItem->setDbCueOut($cueout) ->setDbClipLength($cliplength) - ->setDbEnds($this->nowDT) + ->setDbEnds($this->nowDT) ->save($this->con); } else { @@ -619,27 +619,27 @@ class Application_Model_Scheduler { throw $e; } } - + /* * Used for cancelling the current show instance. - * + * * @param $p_id id of the show instance to cancel. */ public function cancelShow($p_id) { - + $this->con->beginTransaction(); - + try { - + $instance = CcShowInstancesQuery::create()->findPK($p_id); - + if (!$instance->getDbRecord()) { - + $items = CcScheduleQuery::create() ->filterByDbInstanceId($p_id) ->filterByDbEnds($this->nowDT, Criteria::GREATER_THAN) ->find($this->con); - + if (count($items) > 0) { $remove = array(); $ts = $this->nowDT->format('U'); @@ -657,12 +657,12 @@ class Application_Model_Scheduler { $rebroadcasts = $instance->getCcShowInstancessRelatedByDbId(null, $this->con); $rebroadcasts->delete($this->con); } - + $instance->setDbEnds($this->nowDT); $instance->save($this->con); - + $this->con->commit(); - + if ($instance->getDbRecord()) { Application_Model_RabbitMq::SendMessageToShowRecorder("cancel_recording"); } @@ -670,7 +670,7 @@ class Application_Model_Scheduler { 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 47c647829..a0ef4f3eb 100644 --- a/airtime_mvc/application/models/ServiceRegister.php +++ b/airtime_mvc/application/models/ServiceRegister.php @@ -17,7 +17,7 @@ class Application_Model_ServiceRegister { if ($p_ipAddress == "::1"){ $p_ipAddress = "127.0.0.1"; } - + $component->setDbIp($p_ipAddress); $component->save(); } diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index 9d7c5c00e..53bf8bab4 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -21,25 +21,25 @@ class Application_Model_Show { $show->setDbName($name); Application_Model_RabbitMq::PushSchedule(); } - + public function setAirtimeAuthFlag($flag){ $show = CcShowQuery::create()->findPK($this->_showId); $show->setDbLiveStreamUsingAirtimeAuth($flag); $show->save(); } - + public function setCustomAuthFlag($flag){ $show = CcShowQuery::create()->findPK($this->_showId); $show->setDbLiveStreamUsingCustomAuth($flag); $show->save(); } - + public function setCustomUsername($username){ $show = CcShowQuery::create()->findPK($this->_showId); $show->setDbLiveStreamUser($username); $show->save(); } - + public function setCustomPassword($password){ $show = CcShowQuery::create()->findPK($this->_showId); $show->setDbLiveStreamPass($password); @@ -303,8 +303,6 @@ class Application_Model_Show { ." AND starts > TIMESTAMP '$timestamp'" ." AND show_id = $showId"; - //Logging::log($sql); - $con->exec($sql); } @@ -557,7 +555,7 @@ class Application_Model_Show { $con->exec($sql); } - + /** * Get the start date of the current show in UTC timezone. * @@ -594,8 +592,8 @@ class Application_Model_Show { * The start date in the format YYYY-MM-DD */ public function getStartDate(){ - list($date,) = explode(" ", $this->getStartDateAndTime()); - return $date; + list($date,) = explode(" ", $this->getStartDateAndTime()); + return $date; } /** @@ -606,8 +604,8 @@ class Application_Model_Show { */ public function getStartTime(){ - list(,$time) = explode(" ", $this->getStartDateAndTime()); - return $time; + list(,$time) = explode(" ", $this->getStartDateAndTime()); + return $time; } /** @@ -1251,8 +1249,8 @@ class Application_Model_Show { $rebroadcasts = $con->query($sql)->fetchAll(); if ($showInstance->isRecorded()){ - $showInstance->deleteRebroadcasts(); - self::createRebroadcastInstances($rebroadcasts, $currentUtcTimestamp, $show_id, $show_instance_id, $start, $duration, $timezone); + $showInstance->deleteRebroadcasts(); + self::createRebroadcastInstances($rebroadcasts, $currentUtcTimestamp, $show_id, $show_instance_id, $start, $duration, $timezone); } } } @@ -1307,13 +1305,13 @@ class Application_Model_Show { if ($show->hasInstanceOnDate($utcStartDateTime)){ $ccShowInstance = $show->getInstanceOnDate($utcStartDateTime); - + if ($ccShowInstance->getDbModifiedInstance()){ //show instance on this date has been deleted. list($start, $utcStartDateTime) = self::advanceRepeatingDate($p_interval, $start, $timezone); continue; } - + $newInstance = false; } else { $ccShowInstance = new CcShowInstances(); @@ -1349,7 +1347,7 @@ class Application_Model_Show { Application_Model_Show::setNextPop($start, $show_id, $day); } - + private static function advanceRepeatingDate($p_interval, $start, $timezone){ $startDt = new DateTime($start, new DateTimeZone($timezone)); if ($p_interval == 'P1M'){ @@ -1369,19 +1367,19 @@ class Application_Model_Show { do { $dt->add(new DateInterval($p_interval)); } while(!checkdate($dt->format("m"), $startDt->format("d"), $dt->format("Y"))); - + $dt->setDate($dt->format("Y"), $dt->format("m"), $startDt->format("d")); - + } else { $dt = new DateTime($start, new DateTimeZone($timezone)); $dt->add(new DateInterval($p_interval)); } - + $start = $dt->format("Y-m-d H:i:s"); $dt->setTimezone(new DateTimeZone('UTC')); $utcStartDateTime = $dt; - + return array($start, $utcStartDateTime); } @@ -1585,7 +1583,7 @@ class Application_Model_Show { $days = $interval->format('%a'); $shows = Application_Model_Show::getShows($p_start, $p_end); $nowEpoch = time(); - + foreach ($shows as $show) { $options = array(); @@ -1594,14 +1592,14 @@ class Application_Model_Show { if (intval($days) <= 7) { $options["percent"] = Application_Model_Show::getPercentScheduled($show["starts"], $show["ends"], $show["time_filled"]); } - + if (isset($show["parent_starts"])) { $parentStartsDT = new DateTime($show["parent_starts"], new DateTimeZone("UTC")); $parentStartsEpoch = intval($parentStartsDT->format("U")); } $startsDT = new DateTime($show["starts"], new DateTimeZone("UTC")); $endsDT = new DateTime($show["ends"], new DateTimeZone("UTC")); - + $startsEpoch = intval($startsDT->format("U")); $endsEpoch = intval($endsDT->format("U")); @@ -1689,7 +1687,7 @@ class Application_Model_Show { $showDay = CcShowDaysQuery::create() ->filterByDbShowId($this->_showId) ->findOne(); - + $showDay->setDbFirstShow($dt)->setDbStartTime($dt) ->save(); @@ -1730,7 +1728,7 @@ class Application_Model_Show { $con = Propel::getConnection(); if($timeNow == null){ $date = new Application_Common_DateHelper; - $timeNow = $date->getUtcTimestamp(); + $timeNow = $date->getUtcTimestamp(); } //TODO, returning starts + ends twice (once with an alias). Unify this after the 2.0 release. --Martin $sql = "SELECT si.starts as start_timestamp, si.ends as end_timestamp, s.name," @@ -1763,7 +1761,7 @@ class Application_Model_Show { ." AND si.ends < TIMESTAMP '$p_timeNow' + INTERVAL '2 days'" ." AND modified_instance != TRUE" ." ORDER BY si.starts"; - + $rows = $con->query($sql)->fetchAll(PDO::FETCH_ASSOC); $numberOfRows = count($rows); @@ -1775,7 +1773,7 @@ class Application_Model_Show { for ($i = 0; $i < $numberOfRows; ++$i) { //Find the show that is within the current time. - if ((strtotime($rows[$i]['starts']) <= $timeNowAsMillis) + if ((strtotime($rows[$i]['starts']) <= $timeNowAsMillis) && (strtotime($rows[$i]['ends']) > $timeNowAsMillis)) { if ($i-1 >= 0) { $results['previousShow'][0] = array( @@ -1842,7 +1840,7 @@ class Application_Model_Show { "record"=>$rows[$previousShowIndex]['record'], "type"=>"show"); } - + return $results; } diff --git a/airtime_mvc/application/models/ShowBuilder.php b/airtime_mvc/application/models/ShowBuilder.php index 650734e2d..e4a0603e2 100644 --- a/airtime_mvc/application/models/ShowBuilder.php +++ b/airtime_mvc/application/models/ShowBuilder.php @@ -14,14 +14,14 @@ class Application_Model_ShowBuilder { private $user; private $opts; - + private $pos; private $contentDT; private $epoch_now; private $currentShow; - + private $showInstances = array(); - + private $defaultRowArray = array( "header" => false, "footer" => false, @@ -54,16 +54,16 @@ class Application_Model_ShowBuilder { $this->startDT = $p_startDT; $this->endDT = $p_endDT; $this->timezone = date_default_timezone_get(); - $this->user = Application_Model_User::GetCurrentUser(); + $this->user = Application_Model_User::getCurrentUser(); $this->opts = $p_opts; $this->epoch_now = floatval(microtime(true)); $this->currentShow = false; } - + private function getUsersShows() { - + $shows = array(); - + $host_shows = CcShowHostsQuery::create() ->setFormatter(ModelCriteria::FORMAT_ON_DEMAND) ->filterByDbHost($this->user->getId()) @@ -72,7 +72,7 @@ class Application_Model_ShowBuilder { foreach ($host_shows as $host_show) { $shows[] = $host_show->getDbShow(); } - + return $shows; } @@ -84,15 +84,15 @@ class Application_Model_ShowBuilder { return; } - if ($this->user->canSchedule($p_item["show_id"]) == true) { + if ($this->user->canSchedule($p_item["show_id"]) == true) { $row["allowed"] = true; - } + } } - + private function getItemColor($p_item, &$row) { $defaultColor = "ffffff"; $defaultBackground = "3366cc"; - + $color = $p_item["show_color"]; if ($color === '') { $color = $defaultColor; @@ -101,7 +101,7 @@ class Application_Model_ShowBuilder { if ($backgroundColor === '') { $backgroundColor = $defaultBackground; } - + $row["color"] = $color; $row["backgroundColor"] = $backgroundColor; } @@ -123,7 +123,7 @@ class Application_Model_ShowBuilder { } $row["timestamp"] = $ts; } - + /* * marks a row's status. * 0 = past @@ -131,7 +131,7 @@ class Application_Model_ShowBuilder { * 2 = future */ 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; } @@ -144,7 +144,7 @@ class Application_Model_ShowBuilder { else if ($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; @@ -156,7 +156,7 @@ class Application_Model_ShowBuilder { //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; @@ -176,31 +176,31 @@ class Application_Model_ShowBuilder { $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC")); $showEndDT->setTimezone(new DateTimeZone($this->timezone)); $endsEpoch = floatval($showEndDT->format("U.u")); - + //is a rebroadcast show if (intval($p_item["si_rebroadcast"]) === 1) { $row["rebroadcast"] = true; - + $parentInstance = CcShowInstancesQuery::create()->findPk($p_item["parent_show"]); $name = $parentInstance->getCcShow()->getDbName(); $dt = $parentInstance->getDbStarts(null); $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["record"] = true; - + if (Application_Model_Preference::GetUploadToSoundcloudOption()) { $file = Application_Model_StoredFile::Recall($p_item["si_file_id"]); if (isset($file)) { $sid = $file->getSoundCloudId(); $row["soundcloud_id"] = $sid; - } + } } } - + if ($startsEpoch < $this->epoch_now && $endsEpoch > $this->epoch_now) { $row["currentShow"] = true; $this->currentShow = true; @@ -221,7 +221,7 @@ class Application_Model_ShowBuilder { $row["title"] = $p_item["show_name"]; $row["instance"] = intval($p_item["si_id"]); $row["image"] = ''; - + $this->getScheduledStatus($startsEpoch, $endsEpoch, $row); $this->contentDT = $showStartDT; @@ -254,7 +254,7 @@ class Application_Model_ShowBuilder { $row["instance"] = intval($p_item["si_id"]); $row["starts"] = $schedStartDT->format("H:i:s"); $row["ends"] = $schedEndDT->format("H:i:s"); - + $formatter = new LengthFormatter($p_item['file_length']); $row['runtime'] = $formatter->format(); @@ -266,7 +266,7 @@ class Application_Model_ShowBuilder { $row["cueout"] = $p_item["cue_out"]; $row["fadein"] = round(substr($p_item["fade_in"], 6), 6); $row["fadeout"] = round(substr($p_item["fade_out"], 6), 6); - + $row["pos"] = $this->pos++; $this->contentDT = $schedEndDT; @@ -275,10 +275,10 @@ class Application_Model_ShowBuilder { else if (intval($p_item["si_record"]) === 1) { $row["record"] = true; $row["instance"] = intval($p_item["si_id"]); - + $showStartDT = new DateTime($p_item["si_starts"], new DateTimeZone("UTC")); $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC")); - + $startsEpoch = floatval($showStartDT->format("U.u")); $endsEpoch = floatval($showEndDT->format("U.u")); @@ -289,7 +289,7 @@ class Application_Model_ShowBuilder { $row["id"] = 0 ; $row["instance"] = intval($p_item["si_id"]); } - + if (intval($p_item["si_rebroadcast"]) === 1) { $row["rebroadcast"] = true; } @@ -320,23 +320,23 @@ 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)); $endsEpoch = floatval($showEndDT->format("U.u")); - + $row["refresh"] = floatval($showEndDT->format("U.u")) - $this->epoch_now; - + if ($this->currentShow === true) { $row["currentShow"] = true; } $this->getScheduledStatus($startsEpoch, $endsEpoch, $row); $this->isAllowed($p_item, $row); - + return $row; } @@ -349,7 +349,7 @@ class Application_Model_ShowBuilder { 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"]; } @@ -357,22 +357,22 @@ class Application_Model_ShowBuilder { $include = $this->getUsersShows(); } - - + + $currentInstances = array(); foreach ($shows as $show) { - + if (empty($include) || in_array($show["show_id"], $include)) { $currentInstances[] = $show["instance_id"]; - + if (isset($show["last_scheduled"])) { $dt = new DateTime($show["last_scheduled"], new DateTimeZone("UTC")); } 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")); if ($timestamp < $showTimeStamp) { @@ -411,7 +411,7 @@ class Application_Model_ShowBuilder { for ($i = 0, $rows = count($scheduled_items); $i < $rows; $i++) { $item = $scheduled_items[$i]; - + //don't send back data for filler rows. if (isset($item["playout_status"]) && $item["playout_status"] < 0) { continue; @@ -425,11 +425,11 @@ class Application_Model_ShowBuilder { //pass in the previous row as it's the last row for the previous show. $display_items[] = $this->makeFooterRow($scheduled_items[$i-1]); } - + $display_items[] = $this->makeHeaderRow($item); $current_id = $item["si_id"]; - + $this->pos = 1; } @@ -449,7 +449,7 @@ class Application_Model_ShowBuilder { if (count($scheduled_items) > 0) { $display_items[] = $this->makeFooterRow($scheduled_items[count($scheduled_items)-1]); } - + return array("schedule" => $display_items, "showInstances" => $this->showInstances); } } diff --git a/airtime_mvc/application/models/ShowInstance.php b/airtime_mvc/application/models/ShowInstance.php index e3134a527..00a65a06a 100644 --- a/airtime_mvc/application/models/ShowInstance.php +++ b/airtime_mvc/application/models/ShowInstance.php @@ -30,7 +30,7 @@ class Application_Model_ShowInstance { public function getShow(){ return new Application_Model_Show($this->getShowId()); } - + public function deleteRebroadcasts(){ $con = Propel::getConnection(); @@ -42,7 +42,7 @@ class Application_Model_ShowInstance { ." AND instance_id = $instance_id" ." AND rebroadcast = 1"; - $con->exec($sql); + $con->exec($sql); } /* This function is weird. It should return a boolean, but instead returns @@ -256,11 +256,11 @@ class Application_Model_ShowInstance { if ($today_timestamp > $newStartsDateTime->getTimestamp()) { return "Can't move show into past"; } - + //check if show is overlapping $overlapping = Application_Model_Schedule::checkOverlappingShows($newStartsDateTime, $newEndsDateTime, true, $this->getShowInstanceId()); if ($overlapping) { - return "Cannot schedule overlapping shows"; + return "Cannot schedule overlapping shows"; } if ($this->isRecorded()) { @@ -579,7 +579,7 @@ class Application_Model_ShowInstance { public function getTimeScheduled() { $time = $this->_showInstance->getDbTimeFilled(); - + if ($time != "00:00:00" && !empty($time)) { $time_arr = explode(".", $time); if (count($time_arr) > 1) { @@ -593,7 +593,7 @@ class Application_Model_ShowInstance { } else { $time = "00:00:00.00"; } - + return $time; } @@ -637,7 +637,7 @@ class Application_Model_ShowInstance { } else { $returnStr = $hours . ":" . $interval->format("%I:%S") . ".00"; } - + return $returnStr; } @@ -670,30 +670,30 @@ class Application_Model_ShowInstance { public function getLastAudioItemEnd() { - $con = Propel::getConnection(); + $con = Propel::getConnection(); - $sql = "SELECT ends FROM cc_schedule " - ."WHERE instance_id = {$this->_instanceId} " - ."ORDER BY ends DESC " - ."LIMIT 1"; + $sql = "SELECT ends FROM cc_schedule " + ."WHERE instance_id = {$this->_instanceId} " + ."ORDER BY ends DESC " + ."LIMIT 1"; - $query = $con->query($sql)->fetchColumn(0); + $query = $con->query($sql)->fetchColumn(0); return ($query !== false) ? $query : NULL; - } + } public function getShowEndGapTime(){ - $showEnd = $this->getShowInstanceEnd(); - $lastItemEnd = $this->getLastAudioItemEnd(); + $showEnd = $this->getShowInstanceEnd(); + $lastItemEnd = $this->getLastAudioItemEnd(); - if (is_null($lastItemEnd)){ - $lastItemEnd = $this->getShowInstanceStart(); - } + if (is_null($lastItemEnd)){ + $lastItemEnd = $this->getShowInstanceStart(); + } - $diff = strtotime($showEnd) - strtotime($lastItemEnd); + $diff = strtotime($showEnd) - strtotime($lastItemEnd); - return ($diff < 0) ? 0 : $diff; - } + return ($diff < 0) ? 0 : $diff; + } public static function GetLastShowInstance($p_timeNow){ global $CC_CONFIG; @@ -777,14 +777,14 @@ class Application_Model_ShowInstance { $con = Propel::getConnection(); $sql = "SELECT ends - FROM cc_show_instances as si + FROM cc_show_instances as si JOIN cc_show as sh ON si.show_id = sh.id - WHERE si.ends > '$p_startTime' and si.ends < '$p_endTime' and (sh.live_stream_using_airtime_auth or live_stream_using_custom_auth) - ORDER BY si.ends"; + WHERE si.ends > '$p_startTime' and si.ends < '$p_endTime' and (sh.live_stream_using_airtime_auth or live_stream_using_custom_auth) + ORDER BY si.ends"; return $con->query($sql)->fetchAll(); } - + function isRepeating(){ if ($this->getShow()->isRepeating()){ return true; diff --git a/airtime_mvc/application/models/Soundcloud.php b/airtime_mvc/application/models/Soundcloud.php index d8286988f..d94648267 100644 --- a/airtime_mvc/application/models/Soundcloud.php +++ b/airtime_mvc/application/models/Soundcloud.php @@ -5,7 +5,7 @@ class Application_Model_Soundcloud { private $_soundcloud; - public function __construct() + public function __construct() { global $CC_CONFIG; @@ -35,7 +35,7 @@ class Application_Model_Soundcloud { } $downloadable = Application_Model_Preference::GetSoundCloudDownloadbleOption() == '1'?true:false; - + $track_data = array( 'track[sharing]' => 'private', 'track[title]' => $filename, @@ -77,7 +77,7 @@ class Application_Model_Soundcloud { if ($license != "") { $track_data['track[license]'] = $license; } - + $response = json_decode( $this->_soundcloud->post('tracks', $track_data), true diff --git a/airtime_mvc/application/models/StoredFile.php b/airtime_mvc/application/models/StoredFile.php index 3eae3b6fa..b6699bce1 100644 --- a/airtime_mvc/application/models/StoredFile.php +++ b/airtime_mvc/application/models/StoredFile.php @@ -91,7 +91,7 @@ class Application_Model_StoredFile { } else { $dbMd = array(); - + 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 @@ -100,9 +100,9 @@ class Application_Model_StoredFile { // new garbage value won't cause errors). If the value is 2012-01-01, then substring to // first 4 digits is an OK result. // CC-3771 - + $year = $p_md["MDATA_KEY_YEAR"]; - + if (strlen($year) > 4){ $year = substr($year, 0, 4); } @@ -111,7 +111,7 @@ class Application_Model_StoredFile { } $p_md["MDATA_KEY_YEAR"] = $year; } - + foreach ($p_md as $mdConst => $mdValue) { if (defined($mdConst)){ $dbMd[constant($mdConst)] = $mdValue; @@ -161,9 +161,9 @@ class Application_Model_StoredFile { * Set metadata element value * * @param string $category - * Metadata element by metadata constant + * Metadata element by metadata constant * @param string $value - * value to store, if NULL then delete record + * value to store, if NULL then delete record */ public function setMetadataValue($p_category, $p_value) { @@ -176,9 +176,9 @@ class Application_Model_StoredFile { * Set metadata element value * * @param string $category - * Metadata element by db column + * Metadata element by db column * @param string $value - * value to store, if NULL then delete record + * value to store, if NULL then delete record */ public function setDbColMetadataValue($p_category, $p_value) { @@ -245,12 +245,12 @@ class Application_Model_StoredFile { { $c = get_defined_constants(true); $md = array(); - - /* Create a copy of dbMD here and create a "filepath" key inside of + + /* Create a copy of dbMD here and create a "filepath" key inside of * it. The reason we do this here, instead of creating this key inside - * dbMD is because "filepath" isn't really metadata, and we don't want + * dbMD is because "filepath" isn't really metadata, and we don't want * filepath updated everytime the metadata changes. Also it needs extra - * processing before we can write it to the database (needs to be split + * processing before we can write it to the database (needs to be split * into base and relative path) * */ $dbmd_copy = $this->_dbMD; @@ -273,9 +273,9 @@ class Application_Model_StoredFile { * Set state of virtual file * * @param string $p_state - * 'empty'|'incomplete'|'ready'|'edited' + * 'empty'|'incomplete'|'ready'|'edited' * @param int $p_editedby - * user id | 'NULL' for clear editedBy field + * user id | 'NULL' for clear editedBy field * @return TRUE */ public function setState($p_state, $p_editedby=NULL) @@ -330,7 +330,7 @@ class Application_Model_StoredFile { $music_dir = Application_Model_MusicDir::getDirByPK($this->_file->getDbDirectory()); $type = $music_dir->getType(); - + if (file_exists($filepath) && $type == "stor") { $data = array("filepath" => $filepath, "delete" => 1); Application_Model_RabbitMq::SendMessageToMediaMonitor("file_delete", $data); @@ -343,7 +343,7 @@ class Application_Model_StoredFile { $this->_file->setDbFileExists(false); $this->_file->save(); } - + /** * This function is for when media monitor detects deletion of file * and trying to update airtime side @@ -367,7 +367,7 @@ class Application_Model_StoredFile { * Return suitable extension. * * @return string - * file extension without a dot + * file extension without a dot */ public function getFileExtension() { @@ -395,7 +395,7 @@ class Application_Model_StoredFile { return $directory.$filepath; } - + /** * Set real filename of raw media data * @@ -500,9 +500,9 @@ Logging::log("getting media! - 2"); * be NULL. * * @param int $p_id - * local id + * local id * @param string $p_gunid - * global unique id of file + * global unique id of file * @param string $p_md5sum * MD5 sum of the file * @param boolean $exist @@ -570,7 +570,7 @@ Logging::log("getting media! - 2"); * by gunid. * * @param string $p_gunid - * global unique id of file + * global unique id of file * @return Application_Model_StoredFile|NULL */ public static function RecallByGunid($p_gunid) @@ -624,7 +624,7 @@ Logging::log("getting media! - 2"); public static function searchLibraryFiles($datatables) { - $con = Propel::getConnection(CcFilesPeer::DATABASE_NAME); + $con = Propel::getConnection(CcFilesPeer::DATABASE_NAME); $displayColumns = array("id", "track_title", "artist_name", "album_title", "genre", "length", "year", "utime", "mtime", "ftype", "track_number", "mood", "bpm", "composer", "info_url", @@ -871,26 +871,26 @@ Logging::log("getting media! - 2"); return $result; } } - + 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)){ $audio_stor = Application_Common_OsPath::join($stor, "organize", $fileName); if (self::liquidsoapFilePlayabilityTest($audio_file)){ - + Logging::log("copyFileToStor: moving file $audio_file to $audio_stor"); - + //Martin K.: changed to rename: Much less load + quicker since this is an atomic operation if (@rename($audio_file, $audio_stor) === false) { #something went wrong likely there wasn't enough space in the audio_stor to move the file too. #warn the user that the file wasn't uploaded and they should check if there is enough disk space. unlink($audio_file);//remove the file after failed rename $result = array("code" => 108, "message" => "The file was not uploaded, this error can occur if the computer hard drive does not have enough disk space."); - } + } } else { $result = array("code" => 110, "message" => "This file appears to be corrupted and will not be added to media library."); } @@ -901,23 +901,23 @@ Logging::log("getting media! - 2"); } 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){ - + $LIQUIDSOAP_ERRORS = array('TagLib: MPEG::Properties::read() -- Could not find a valid last MPEG frame in the stream.'); - + // Ask Liquidsoap if file is playable $command = sprintf("/usr/bin/airtime-liquidsoap -c 'output.dummy(audio_to_stereo(single(\"%s\")))' 2>&1", $audio_file); - + exec($command, $output, $rv); - + $isError = count($output) > 0 && in_array($output[0], $LIQUIDSOAP_ERRORS); - return ($rv == 0 && !$isError); + return ($rv == 0 && !$isError); } - + public static function getFileCount() { global $CC_CONFIG; @@ -960,28 +960,28 @@ Logging::log("getting media! - 2"); return $results; } - + /* Gets number of tracks uploaded to * Soundcloud in the last 24 hours */ public static function getSoundCloudUploads() { try { - $con = Propel::getConnection(); - - $sql = "SELECT soundcloud_id as id, soundcloud_upload_time" + $con = Propel::getConnection(); + + $sql = "SELECT soundcloud_id as id, soundcloud_upload_time" ." FROM CC_FILES" ." WHERE (id != -2 and id != -3) and" ." (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'); Logging::log("Could not connect to database."); - exit; + exit; } - + } public function setSoundCloudLinkToFile($link_to_file) @@ -1021,10 +1021,10 @@ Logging::log("getting media! - 2"); public function getSoundCloudErrorMsg(){ return $this->_file->getDbSoundCloudErrorMsg(); } - + public function getDirectory(){ - return $this->_file->getDbDirectory(); - } + return $this->_file->getDbDirectory(); + } public function setFileExistsFlag($flag){ $this->_file->setDbFileExists($flag) @@ -1032,7 +1032,7 @@ Logging::log("getting media! - 2"); } public function setSoundCloudUploadTime($time){ $this->_file->setDbSoundCloundUploadTime($time) - ->save(); + ->save(); } public function getFileExistsFlag(){ diff --git a/airtime_mvc/application/models/StreamSetting.php b/airtime_mvc/application/models/StreamSetting.php index e62d1173f..d3db99da9 100644 --- a/airtime_mvc/application/models/StreamSetting.php +++ b/airtime_mvc/application/models/StreamSetting.php @@ -130,23 +130,23 @@ class Application_Model_StreamSetting { } if (!isset($exists["master_live_stream_port"])) { - $rows[] = array("keyname" =>"master_live_stream_port", - "value"=>self::getMasterLiveStreamPort(), + $rows[] = array("keyname" =>"master_live_stream_port", + "value"=>self::getMasterLiveStreamPort(), "type"=>"integer"); } if (!isset($exists["master_live_stream_mp"])) { - $rows[] = array("keyname" =>"master_live_stream_mp", - "value"=>self::getMasterLiveStreamMountPoint(), + $rows[] = array("keyname" =>"master_live_stream_mp", + "value"=>self::getMasterLiveStreamMountPoint(), "type"=>"string"); } if (!isset($exists["dj_live_stream_port"])) { - $rows[] = array("keyname" =>"dj_live_stream_port", - "value"=>self::getDjLiveStreamPort(), + $rows[] = array("keyname" =>"dj_live_stream_port", + "value"=>self::getDjLiveStreamPort(), "type"=>"integer"); } if (!isset($exists["dj_live_stream_mp"])) { - $rows[] = array("keyname" =>"dj_live_stream_mp", - "value"=>self::getDjLiveStreamMountPoint(), + $rows[] = array("keyname" =>"dj_live_stream_mp", + "value"=>self::getDjLiveStreamMountPoint(), "type"=>"string"); } return $rows; @@ -180,7 +180,7 @@ class Application_Model_StreamSetting { $v = $d['enable'] == 1 ? 'true' : 'false'; } $v = trim($v); - + #escape double single quotes CC-3926 $v = str_replace("'", "''", $v); $sql = "UPDATE cc_stream_setting SET value='$v' WHERE keyname='$keyname'"; diff --git a/airtime_mvc/application/models/Systemstatus.php b/airtime_mvc/application/models/Systemstatus.php index fd798bc57..6bde9f144 100644 --- a/airtime_mvc/application/models/Systemstatus.php +++ b/airtime_mvc/application/models/Systemstatus.php @@ -9,15 +9,15 @@ class Application_Model_Systemstatus $monit_password = $CC_CONFIG['monit_password']; $url = "http://$p_ip:2812/_status?format=xml"; - - $ch = curl_init(); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_URL, $url); + + $ch = curl_init(); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_USERPWD, "$monit_user:$monit_password"); //wait a max of 3 seconds before aborting connection attempt curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3); $result = curl_exec($ch); - + $info = curl_getinfo($ch); curl_close($ch); @@ -32,7 +32,7 @@ class Application_Model_Systemstatus return $docRoot; } - + public static function ExtractServiceInformation($p_docRoot, $p_serviceName){ $starting = array( @@ -43,7 +43,7 @@ class Application_Model_Systemstatus "memory_perc"=>"0%", "memory_kb"=>"0", "cpu_perc"=>"0%"); - + $notMonitored = array( "name"=>$p_serviceName, "process_id"=>"NOT MONITORED", @@ -53,7 +53,7 @@ class Application_Model_Systemstatus "memory_kb"=>"0", "cpu_perc"=>"0%" ); - + $notRunning = array( "name"=>$p_serviceName, "process_id"=>"FAILED", @@ -65,7 +65,7 @@ class Application_Model_Systemstatus ); $data = $notRunning; - + if (!is_null($p_docRoot)){ foreach ($p_docRoot->getElementsByTagName("service") AS $item) { @@ -93,7 +93,7 @@ class Application_Model_Systemstatus if ($process_id->length > 0){ $data["name"] = $process_id->item(0)->nodeValue; } - + $process_id = $item->getElementsByTagName("pid"); if ($process_id->length > 0){ $data["process_id"] = $process_id->item(0)->nodeValue; @@ -104,13 +104,13 @@ class Application_Model_Systemstatus if ($uptime->length > 0){ $data["uptime_seconds"] = $uptime->item(0)->nodeValue; } - + $memory = $item->getElementsByTagName("memory"); if ($memory->length > 0){ $data["memory_perc"] = $memory->item(0)->getElementsByTagName("percenttotal")->item(0)->nodeValue."%"; $data["memory_kb"] = $memory->item(0)->getElementsByTagName("kilobytetotal")->item(0)->nodeValue; } - + $cpu = $item->getElementsByTagName("cpu"); if ($cpu->length > 0){ $data["cpu_perc"] = $cpu->item(0)->getElementsByTagName("percent")->item(0)->nodeValue."%"; @@ -127,7 +127,7 @@ class Application_Model_Systemstatus foreach($keys as $key) { $data[$key] = "UNKNOWN"; } - + $docRoot = self::GetMonitStatus("localhost"); if (!is_null($docRoot)){ foreach ($docRoot->getElementsByTagName("platform") AS $item) @@ -140,7 +140,7 @@ class Application_Model_Systemstatus } } } - + return $data; } @@ -151,14 +151,14 @@ class Application_Model_Systemstatus return null; } else { $ip = $component->getDbIp(); - + $docRoot = self::GetMonitStatus($ip); $data = self::ExtractServiceInformation($docRoot, "airtime-playout"); return $data; } } - + public static function GetLiquidsoapStatus(){ $component = CcServiceRegisterQuery::create()->findOneByDbName("pypo"); @@ -166,14 +166,14 @@ class Application_Model_Systemstatus return null; } else { $ip = $component->getDbIp(); - + $docRoot = self::GetMonitStatus($ip); $data = self::ExtractServiceInformation($docRoot, "airtime-liquidsoap"); return $data; } } - + public static function GetMediaMonitorStatus(){ $component = CcServiceRegisterQuery::create()->findOneByDbName("media-monitor"); @@ -181,15 +181,15 @@ class Application_Model_Systemstatus return null; } else { $ip = $component->getDbIp(); - + $docRoot = self::GetMonitStatus($ip); $data = self::ExtractServiceInformation($docRoot, "airtime-media-monitor"); return $data; } } - - public static function GetIcecastStatus(){ + + public static function GetIcecastStatus(){ $docRoot = self::GetMonitStatus("localhost"); $data = self::ExtractServiceInformation($docRoot, "icecast2"); @@ -197,7 +197,7 @@ class Application_Model_Systemstatus } public static function GetRabbitMqStatus(){ - + if (isset($_SERVER["RABBITMQ_HOST"])){ $rabbitmq_host = $_SERVER["RABBITMQ_HOST"]; } else { @@ -208,18 +208,18 @@ class Application_Model_Systemstatus return $data; } - + public static function GetDiskInfo(){ $partions = array(); - + if (isset($_SERVER['AIRTIME_SRV'])){ //connect to DB and find how much total space user has allocated. $totalSpace = Application_Model_Preference::GetDiskQuota(); - + $storPath = Application_Model_MusicDir::getStorDir()->getDirectory(); - + list($usedSpace,) = preg_split("/[\s]+/", exec("du -bs $storPath")); - + $partitions[$totalSpace]->totalSpace = $totalSpace; $partitions[$totalSpace]->totalFreeSpace = $totalSpace - $usedSpace; Logging::log($partitions[$totalSpace]->totalFreeSpace); @@ -228,7 +228,7 @@ class Application_Model_Systemstatus * into the same partitions by comparing the partition sizes. */ $musicDirs = Application_Model_MusicDir::getWatchedDirs(); $musicDirs[] = Application_Model_MusicDir::getStorDir(); - + foreach($musicDirs as $md){ $totalSpace = disk_total_space($md->getDirectory()); @@ -238,7 +238,7 @@ class Application_Model_Systemstatus $partitions[$totalSpace]->totalFreeSpace = disk_free_space($md->getDirectory()); } - + $partitions[$totalSpace]->dirs[] = $md->getDirectory(); } } diff --git a/airtime_mvc/application/models/User.php b/airtime_mvc/application/models/User.php index cb0e8fa00..c62735050 100644 --- a/airtime_mvc/application/models/User.php +++ b/airtime_mvc/application/models/User.php @@ -11,191 +11,220 @@ class Application_Model_User { public function __construct($userId) { - if (empty($userId)){ + if (empty($userId)) { $this->_userInstance = $this->createUser(); - } - else { + } else { $this->_userInstance = CcSubjsQuery::create()->findPK($userId); - if (is_null($this->_userInstance)){ + if (is_null($this->_userInstance)) { throw new Exception(); } } } - public function getId() { + public function getId() + { return $this->_userInstance->getDbId(); } - public function isGuest() { + public function isGuest() + { return $this->getType() == UTYPE_GUEST; } - public function isHost($showId) { - return $this->isUserType(UTYPE_HOST, $showId); + public function isHost($showId) + { + return $this->isUserType(UTYPE_HOST, $showId); } - public function isPM() { + public function isPM() + { return $this->isUserType(UTYPE_PROGRAM_MANAGER); } - public function isAdmin() { + public function isAdmin() + { return $this->isUserType(UTYPE_ADMIN); } - public function canSchedule($p_showId) { - $type = $this->getType(); - $result = false; + public function canSchedule($p_showId) + { + $type = $this->getType(); + $result = false; - if ( $type === UTYPE_ADMIN || + if ($type === UTYPE_ADMIN || $type === UTYPE_PROGRAM_MANAGER || - CcShowHostsQuery::create()->filterByDbShow($p_showId)->filterByDbHost($this->getId())->count() > 0 ) - { - $result = true; - } + CcShowHostsQuery::create()->filterByDbShow($p_showId)->filterByDbHost($this->getId())->count() > 0) { + $result = true; + } - return $result; + return $result; } - public function isUserType($type, $showId=''){ - if(is_array($type)){ - $result = false; - foreach($type as $t){ - switch($t){ - case UTYPE_ADMIN: - $result = $this->_userInstance->getDbType() === 'A'; - break; - case UTYPE_HOST: - $userId = $this->_userInstance->getDbId(); - $result = CcShowHostsQuery::create()->filterByDbShow($showId)->filterByDbHost($userId)->count() > 0; - break; - case UTYPE_PROGRAM_MANAGER: - $result = $this->_userInstance->getDbType() === 'P'; - break; - } - if($result){ - return $result; - } - } - }else{ - 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'; - } - } + public function isUserType($type, $showId='') + { + if (is_array($type)) { + $result = false; + foreach ($type as $t) { + switch($t){ + case UTYPE_ADMIN: + $result = $this->_userInstance->getDbType() === 'A'; + break; + case UTYPE_HOST: + $userId = $this->_userInstance->getDbId(); + $result = CcShowHostsQuery::create() + ->filterByDbShow($showId) + ->filterByDbHost($userId)->count() > 0; + break; + case UTYPE_PROGRAM_MANAGER: + $result = $this->_userInstance->getDbType() === 'P'; + break; + } + if ($result) { + return $result; + } + } + } else { + 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'; + } + } } - public function setLogin($login){ + public function setLogin($login) + { $user = $this->_userInstance; $user->setDbLogin($login); } - public function setPassword($password){ + public function setPassword($password) + { $user = $this->_userInstance; $user->setDbPass(md5($password)); } - public function setFirstName($firstName){ + public function setFirstName($firstName) + { $user = $this->_userInstance; $user->setDbFirstName($firstName); } - public function setLastName($lastName){ + public function setLastName($lastName) + { $user = $this->_userInstance; $user->setDbLastName($lastName); } - public function setType($type){ + public function setType($type) + { $user = $this->_userInstance; $user->setDbType($type); } - public function setEmail($email){ + public function setEmail($email) + { $user = $this->_userInstance; $user->setDbEmail(strtolower($email)); } - - public function setCellPhone($cellPhone){ + + public function setCellPhone($cellPhone) + { $user = $this->_userInstance; $user->setDbCellPhone($cellPhone); } - public function setSkype($skype){ + public function setSkype($skype) + { $user = $this->_userInstance; $user->setDbSkypeContact($skype); } - public function setJabber($jabber){ + public function setJabber($jabber) + { $user = $this->_userInstance; $user->setDbJabberContact($jabber); } - public function getLogin(){ + public function getLogin() + { $user = $this->_userInstance; return $user->getDbLogin(); } - public function getPassword(){ + public function getPassword() + { $user = $this->_userInstance; return $user->getDbPass(); } - public function getFirstName(){ + public function getFirstName() + { $user = $this->_userInstance; return $user->getDbFirstName(); } - public function getLastName(){ + public function getLastName() + { $user = $this->_userInstance; return $user->getDbLastName(); } - public function getType(){ + public function getType() + { $user = $this->_userInstance; return $user->getDbType(); } - public function getEmail(){ + public function getEmail() + { $user = $this->_userInstance; return $user->getDbEmail(); } - - public function getCellPhone(){ + + public function getCellPhone() + { $user = $this->_userInstance; return $user->getDbCellPhone(); } - public function getSkype(){ + public function getSkype() + { $user = $this->_userInstance; return $user->getDbSkypeContact(); } - public function getJabber(){ + public function getJabber() + { $user = $this->_userInstance; return $user->getDbJabberContact(); } - public function save(){ + public function save() + { $this->_userInstance->save(); } - public function delete(){ - if (!$this->_userInstance->isDeleted()) + public function delete() + { + if (!$this->_userInstance->isDeleted()) { $this->_userInstance->delete(); + } } - private function createUser() { + private function createUser() + { $user = new CcSubjs(); return $user; } - public static function getUsers($type, $search=NULL) + public static function getUsers($type, $search=null) { $con = Propel::getConnection(); @@ -203,12 +232,11 @@ class Application_Model_User { $sql = $sql_gen; if (is_array($type)) { - for($i=0; $iquery($sql)->fetchAll();; } - public static function getUserCount($type=NULL){ + public static function getUserCount($type=null) + { $con = Propel::getConnection(); $sql = ''; $sql_gen = "SELECT count(*) AS cnt FROM cc_subjs "; if (!isset($type)) { - $sql = $sql_gen; - } - else{ - if (is_array($type)) { - for ($i=0; $iquery($sql)->fetchColumn(0); - return ($query !== false) ? $query : NULL; + return ($query !== false) ? $query : null; } - public static function getHosts($search=NULL) { + public static function getHosts($search=null) + { return Application_Model_User::getUsers(array('H'), $search); } - public static function getUsersDataTablesInfo($datatables) { + public static function getUsersDataTablesInfo($datatables) + { - $con = Propel::getConnection(CcSubjsPeer::DATABASE_NAME); + $con = Propel::getConnection(CcSubjsPeer::DATABASE_NAME); $displayColumns = array("id", "login", "first_name", "last_name", "type"); $fromTable = "cc_subjs"; @@ -273,8 +302,8 @@ class Application_Model_User { $res = Application_Model_Datatables::findEntries($con, $displayColumns, $fromTable, $datatables); // mark record which is for the current user - foreach($res['aaData'] as &$record){ - if($record['login'] == $username){ + foreach ($res['aaData'] as &$record) { + if ($record['login'] == $username) { $record['delete'] = "self"; } else { $record['delete'] = ""; @@ -284,7 +313,8 @@ class Application_Model_User { return $res; } - public static function getUserData($id){ + public static function getUserData($id) + { $con = Propel::getConnection(); $sql = "SELECT login, first_name, last_name, type, id, email, cell_phone, skype_contact, jabber_contact" @@ -294,26 +324,18 @@ class Application_Model_User { return $con->query($sql)->fetch(); } - public static function GetUserID($login){ - $user = CcSubjsQuery::create()->findOneByDbLogin($login); - if (is_null($user)){ - return -1; - } else { - return $user->getDbId(); - } - } - - public static function GetCurrentUser() { + public static function getCurrentUser() + { $userinfo = Zend_Auth::getInstance()->getStorage()->read(); - - if (is_null($userinfo)){ + + if (is_null($userinfo)) { return null; } else { try { return new self($userinfo->id); - } catch (Exception $e){ + } catch (Exception $e) { //we get here if $userinfo->id is defined, but doesn't exist - //in the database anymore. + //in the database anymore. Zend_Auth::getInstance()->clearIdentity(); return null; } diff --git a/airtime_mvc/application/models/airtime/CcFiles.php b/airtime_mvc/application/models/airtime/CcFiles.php index 7558c611b..58f79ee67 100644 --- a/airtime_mvc/application/models/airtime/CcFiles.php +++ b/airtime_mvc/application/models/airtime/CcFiles.php @@ -13,7 +13,7 @@ */ class CcFiles extends BaseCcFiles { - public function getDbLength($format = "H:i:s.u") + public function getDbLength($format = "H:i:s.u") { return parent::getDbLength($format); } diff --git a/airtime_mvc/application/models/airtime/Common.php b/airtime_mvc/application/models/airtime/Common.php index 3e13c7fa3..5845b2b29 100644 --- a/airtime_mvc/application/models/airtime/Common.php +++ b/airtime_mvc/application/models/airtime/Common.php @@ -1,10 +1,10 @@ fail("Metadata has unexpected values:\n".$str); } //var_dump($metadata); diff --git a/python_apps/pypo/liquidsoap_bin b/python_apps/pypo/liquidsoap_bin index 492242f4b..0653ec0b8 160000 --- a/python_apps/pypo/liquidsoap_bin +++ b/python_apps/pypo/liquidsoap_bin @@ -1 +1 @@ -Subproject commit 492242f4bb7367afebbf2f096067cb5a5d3c0449 +Subproject commit 0653ec0b89362921f075af96ee8772538b801a7c