CC-4090: Make code style PSR compliant

-User.php
-removed all trailing whitespace
This commit is contained in:
Martin Konecny 2012-07-10 18:51:32 -04:00
parent 3d243468a7
commit ee3447f903
30 changed files with 1057 additions and 1037 deletions

View File

@ -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'); $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)){ if (!is_null($user)){
$userType = $user->getType(); $userType = $user->getType();
} else { } else {

View File

@ -111,7 +111,7 @@ class LibraryController extends Zend_Controller_Action
//array containing id and type of media to delete. //array containing id and type of media to delete.
$mediaItems = $this->_getParam('media', null); $mediaItems = $this->_getParam('media', null);
$user = Application_Model_User::GetCurrentUser(); $user = Application_Model_User::getCurrentUser();
$isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
$files = array(); $files = array();
@ -204,7 +204,7 @@ class LibraryController extends Zend_Controller_Action
public function editFileMdAction() public function editFileMdAction()
{ {
$user = Application_Model_User::GetCurrentUser(); $user = Application_Model_User::getCurrentUser();
$isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
if(!$isAdminOrPM){ if(!$isAdminOrPM){
return; return;

View File

@ -90,7 +90,7 @@ class ScheduleController extends Zend_Controller_Action
Application_Model_Schedule::createNewFormSections($this->view); 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))){ if($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))){
$this->view->preloadShowForm = true; $this->view->preloadShowForm = true;
@ -689,7 +689,7 @@ class ScheduleController extends Zend_Controller_Action
public function getFormAction() { public function getFormAction() {
$user = Application_Model_User::GetCurrentUser(); $user = Application_Model_User::getCurrentUser();
if($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))){ if($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))){
Application_Model_Schedule::createNewFormSections($this->view); Application_Model_Schedule::createNewFormSections($this->view);
@ -822,7 +822,7 @@ class ScheduleController extends Zend_Controller_Action
public function cancelShowAction() public function cancelShowAction()
{ {
$user = Application_Model_User::GetCurrentUser(); $user = Application_Model_User::getCurrentUser();
if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
$showInstanceId = $this->_getParam('id'); $showInstanceId = $this->_getParam('id');
@ -842,7 +842,7 @@ class ScheduleController extends Zend_Controller_Action
public function cancelCurrentShowAction() public function cancelCurrentShowAction()
{ {
$user = Application_Model_User::GetCurrentUser(); $user = Application_Model_User::getCurrentUser();
if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
$id = $this->_getParam('id'); $id = $this->_getParam('id');

View File

@ -22,7 +22,7 @@ class ShowbuilderController extends Zend_Controller_Action
$request = $this->getRequest(); $request = $this->getRequest();
$baseUrl = $request->getBaseUrl(); $baseUrl = $request->getBaseUrl();
$user = Application_Model_User::GetCurrentUser(); $user = Application_Model_User::getCurrentUser();
$userType = $user->getType(); $userType = $user->getType();
$this->view->headScript()->appendScript("localStorage.setItem( 'user-type', '$userType' );"); $this->view->headScript()->appendScript("localStorage.setItem( 'user-type', '$userType' );");
@ -184,7 +184,7 @@ class ShowbuilderController extends Zend_Controller_Action
$baseUrl = $request->getBaseUrl(); $baseUrl = $request->getBaseUrl();
$menu = array(); $menu = array();
$user = Application_Model_User::GetCurrentUser(); $user = Application_Model_User::getCurrentUser();
$item = CcScheduleQuery::create()->findPK($id); $item = CcScheduleQuery::create()->findPK($id);
$instance = $item->getCcShowInstances(); $instance = $item->getCcShowInstances();

View File

@ -5,7 +5,7 @@ class Application_Form_ShowBuilder extends Zend_Form_SubForm
public function init() public function init()
{ {
$user = Application_Model_User::GetCurrentUser(); $user = Application_Model_User::getCurrentUser();
$this->setDecorators(array( $this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/showbuilder.phtml')) array('ViewScript', array('viewScript' => 'form/showbuilder.phtml'))

View File

@ -1,53 +1,53 @@
<?php <?php
class Application_Model_Auth { class Application_Model_Auth {
const TOKEN_LIFETIME = 'P2D'; // DateInterval syntax const TOKEN_LIFETIME = 'P2D'; // DateInterval syntax
private function generateToken($action, $user_id) private function generateToken($action, $user_id)
{ {
$salt = md5("pro"); $salt = md5("pro");
$token = self::generateRandomString(); $token = self::generateRandomString();
$info = new CcSubjsToken(); $info = new CcSubjsToken();
$info->setDbUserId($user_id); $info->setDbUserId($user_id);
$info->setDbAction($action); $info->setDbAction($action);
$info->setDbToken(sha1($token.$salt)); $info->setDbToken(sha1($token.$salt));
$info->setDbCreated(gmdate('Y-m-d H:i:s')); $info->setDbCreated(gmdate('Y-m-d H:i:s'));
$info->save(); $info->save();
Logging::debug("generated token {$token}"); Logging::debug("generated token {$token}");
return $token; return $token;
} }
public function sendPasswordRestoreLink($user, $view) public function sendPasswordRestoreLink($user, $view)
{ {
$token = $this->generateToken('password.restore', $user->getDbId()); $token = $this->generateToken('password.restore', $user->getDbId());
$e_link_protocol = empty($_SERVER['HTTPS']) ? "http" : "https"; $e_link_protocol = empty($_SERVER['HTTPS']) ? "http" : "https";
$e_link_base = $_SERVER['SERVER_NAME']; $e_link_base = $_SERVER['SERVER_NAME'];
$e_link_path = $view->url(array('user_id' => $user->getDbId(), 'token' => $token), 'password-change'); $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}"; $message = "Click this link: {$e_link_protocol}://{$e_link_base}{$e_link_path}";
$success = Application_Model_Email::send('Airtime Password Reset', $message, $user->getDbEmail()); $success = Application_Model_Email::send('Airtime Password Reset', $message, $user->getDbEmail());
return $success; return $success;
} }
public function invalidateTokens($user, $action) public function invalidateTokens($user, $action)
{ {
CcSubjsTokenQuery::create() CcSubjsTokenQuery::create()
->filterByDbAction($action) ->filterByDbAction($action)
->filterByDbUserId($user->getDbId()) ->filterByDbUserId($user->getDbId())
->delete(); ->delete();
} }
public function checkToken($user_id, $token, $action) public function checkToken($user_id, $token, $action)
{ {
$salt = md5("pro"); $salt = md5("pro");
$token_info = CcSubjsTokenQuery::create() $token_info = CcSubjsTokenQuery::create()
->filterByDbAction($action) ->filterByDbAction($action)
->filterByDbUserId($user_id) ->filterByDbUserId($user_id)
@ -61,10 +61,10 @@ class Application_Model_Auth {
$now = new DateTime(); $now = new DateTime();
$token_life = new DateInterval(self::TOKEN_LIFETIME); $token_life = new DateInterval(self::TOKEN_LIFETIME);
$token_created = new DateTime($token_info->getDbCreated(), new DateTimeZone("UTC")); $token_created = new DateTime($token_info->getDbCreated(), new DateTimeZone("UTC"));
return $now->sub($token_life)->getTimestamp() < $token_created->getTimestamp(); return $now->sub($token_life)->getTimestamp() < $token_created->getTimestamp();
} }
/** /**
* Gets the adapter for authentication against a database table * Gets the adapter for authentication against a database table
* *
@ -79,10 +79,10 @@ class Application_Model_Auth {
->setIdentityColumn('login') ->setIdentityColumn('login')
->setCredentialColumn('pass') ->setCredentialColumn('pass')
->setCredentialTreatment('MD5(?)'); ->setCredentialTreatment('MD5(?)');
return $authAdapter; return $authAdapter;
} }
/** /**
* Get random string * Get random string
* *

View File

@ -121,7 +121,7 @@ class Application_Model_Dashboard
} }
} else { } else {
//return the one that starts sooner. //return the one that starts sooner.
if ($row[0]["starts"] <= $showInstance->getShowInstanceStart()){ if ($row[0]["starts"] <= $showInstance->getShowInstanceStart()){
return array("name"=>$row[0]["artist_name"]." - ".$row[0]["track_title"], return array("name"=>$row[0]["artist_name"]." - ".$row[0]["track_title"],
"starts"=>$row[0]["starts"], "starts"=>$row[0]["starts"],

View File

@ -1,104 +1,104 @@
<?php <?php
class Application_Model_Datatables { class Application_Model_Datatables {
/* /*
* query used to return data for a paginated/searchable datatable. * query used to return data for a paginated/searchable datatable.
*/ */
public static function findEntries($con, $displayColumns, $fromTable, $data, $dataProp = "aaData") public static function findEntries($con, $displayColumns, $fromTable, $data, $dataProp = "aaData")
{ {
$where = array(); $where = array();
if ($data["sSearch"] !== "") { if ($data["sSearch"] !== "") {
$searchTerms = explode(" ", $data["sSearch"]); $searchTerms = explode(" ", $data["sSearch"]);
} }
$selectorCount = "SELECT COUNT(*) "; $selectorCount = "SELECT COUNT(*) ";
$selectorRows = "SELECT ".join(",", $displayColumns)." "; $selectorRows = "SELECT ".join(",", $displayColumns)." ";
$sql = $selectorCount." FROM ".$fromTable; $sql = $selectorCount." FROM ".$fromTable;
$sqlTotalRows = $sql; $sqlTotalRows = $sql;
if (isset($searchTerms)) { if (isset($searchTerms)) {
$searchCols = array(); $searchCols = array();
for ($i = 0; $i < $data["iColumns"]; $i++) { for ($i = 0; $i < $data["iColumns"]; $i++) {
if ($data["bSearchable_".$i] == "true") { if ($data["bSearchable_".$i] == "true") {
$searchCols[] = $data["mDataProp_{$i}"]; $searchCols[] = $data["mDataProp_{$i}"];
} }
} }
$outerCond = array(); $outerCond = array();
foreach ($searchTerms as $term) { foreach ($searchTerms as $term) {
$innerCond = array(); $innerCond = array();
foreach ($searchCols as $col) { foreach ($searchCols as $col) {
$escapedTerm = pg_escape_string($term); $escapedTerm = pg_escape_string($term);
$innerCond[] = "{$col}::text ILIKE '%{$escapedTerm}%'"; $innerCond[] = "{$col}::text ILIKE '%{$escapedTerm}%'";
} }
$outerCond[] = "(".join(" OR ", $innerCond).")"; $outerCond[] = "(".join(" OR ", $innerCond).")";
} }
$where[] = "(".join(" AND ", $outerCond).")"; $where[] = "(".join(" AND ", $outerCond).")";
} }
// End Where clause // End Where clause
// Order By clause // Order By clause
$orderby = array(); $orderby = array();
for ($i = 0; $i < $data["iSortingCols"]; $i++){ for ($i = 0; $i < $data["iSortingCols"]; $i++){
$num = $data["iSortCol_".$i]; $num = $data["iSortCol_".$i];
$orderby[] = $data["mDataProp_{$num}"]." ".$data["sSortDir_".$i]; $orderby[] = $data["mDataProp_{$num}"]." ".$data["sSortDir_".$i];
} }
$orderby[] = "id"; $orderby[] = "id";
$orderby = join("," , $orderby); $orderby = join("," , $orderby);
// End Order By clause // End Order By clause
$displayLength = intval($data["iDisplayLength"]); $displayLength = intval($data["iDisplayLength"]);
if (count($where) > 0) { if (count($where) > 0) {
$where = join(" AND ", $where); $where = join(" AND ", $where);
$sql = $selectorCount." FROM ".$fromTable." WHERE ".$where; $sql = $selectorCount." FROM ".$fromTable." WHERE ".$where;
$sqlTotalDisplayRows = $sql; $sqlTotalDisplayRows = $sql;
$sql = $selectorRows." FROM ".$fromTable." WHERE ".$where." ORDER BY ".$orderby; $sql = $selectorRows." FROM ".$fromTable." WHERE ".$where." ORDER BY ".$orderby;
//limit the results returned. //limit the results returned.
if ($displayLength !== -1) { if ($displayLength !== -1) {
$sql .= " OFFSET ".$data["iDisplayStart"]." LIMIT ".$displayLength; $sql .= " OFFSET ".$data["iDisplayStart"]." LIMIT ".$displayLength;
} }
} }
else { else {
$sql = $selectorRows." FROM ".$fromTable." ORDER BY ".$orderby; $sql = $selectorRows." FROM ".$fromTable." ORDER BY ".$orderby;
//limit the results returned. //limit the results returned.
if ($displayLength !== -1) { if ($displayLength !== -1) {
$sql .= " OFFSET ".$data["iDisplayStart"]." LIMIT ".$displayLength; $sql .= " OFFSET ".$data["iDisplayStart"]." LIMIT ".$displayLength;
} }
} }
try { try {
$r = $con->query($sqlTotalRows); $r = $con->query($sqlTotalRows);
$totalRows = $r->fetchColumn(0); $totalRows = $r->fetchColumn(0);
if (isset($sqlTotalDisplayRows)) { if (isset($sqlTotalDisplayRows)) {
$r = $con->query($sqlTotalDisplayRows); $r = $con->query($sqlTotalDisplayRows);
$totalDisplayRows = $r->fetchColumn(0); $totalDisplayRows = $r->fetchColumn(0);
} }
else { else {
$totalDisplayRows = $totalRows; $totalDisplayRows = $totalRows;
} }
$r = $con->query($sql); $r = $con->query($sql);
$r->setFetchMode(PDO::FETCH_ASSOC); $r->setFetchMode(PDO::FETCH_ASSOC);
$results = $r->fetchAll(); $results = $r->fetchAll();
} }
catch (Exception $e) { catch (Exception $e) {
Logging::debug($e->getMessage()); Logging::debug($e->getMessage());
} }
return array( return array(
"sEcho" => intval($data["sEcho"]), "sEcho" => intval($data["sEcho"]),
"iTotalDisplayRecords" => intval($totalDisplayRows), "iTotalDisplayRecords" => intval($totalDisplayRows),
"iTotalRecords" => intval($totalRows), "iTotalRecords" => intval($totalRows),
$dataProp => $results $dataProp => $results
); );
} }
} }

View File

@ -1,7 +1,7 @@
<?php <?php
class Application_Model_Email { class Application_Model_Email {
/** /**
* Send email * Send email
* *
@ -14,7 +14,7 @@ class Application_Model_Email {
{ {
$mailServerConfigured = Application_Model_Preference::GetMailServerConfigured() == true ? true : false; $mailServerConfigured = Application_Model_Preference::GetMailServerConfigured() == true ? true : false;
$success = true; $success = true;
if ($mailServerConfigured) { if ($mailServerConfigured) {
$username = Application_Model_Preference::GetMailServerEmailAddress(); $username = Application_Model_Preference::GetMailServerEmailAddress();
$password = Application_Model_Preference::GetMailServerPassword(); $password = Application_Model_Preference::GetMailServerPassword();
@ -23,25 +23,25 @@ class Application_Model_Email {
if (!empty($mailServerPort)) { if (!empty($mailServerPort)) {
$port = Application_Model_Preference::GetMailServerPort(); $port = Application_Model_Preference::GetMailServerPort();
} }
$config = array( $config = array(
'auth' => 'login', 'auth' => 'login',
'ssl' => 'ssl', 'ssl' => 'ssl',
'username' => $username, 'username' => $username,
'password' => $password 'password' => $password
); );
if (isset($port)) { if (isset($port)) {
$config['port'] = $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 = new Zend_Mail('utf-8');
$mail->setSubject($subject); $mail->setSubject($subject);
$mail->setBodyText($message); $mail->setBodyText($message);
foreach ((array) $tos as $to) { foreach ((array) $tos as $to) {
$mail->addTo($to); $mail->addTo($to);
} }
@ -60,8 +60,8 @@ class Application_Model_Email {
} catch (Exception $e) { } catch (Exception $e) {
$success = false; $success = false;
} }
} }
return $success; return $success;
} }

View File

@ -26,7 +26,7 @@ class Application_Model_LiveLog
." WHERE state = 'L'" ." WHERE state = 'L'"
." ORDER BY id"; ." ORDER BY id";
$rows = $con->query($sql)->fetchAll(); $rows = $con->query($sql)->fetchAll();
if ($rows != null) { if ($rows != null) {
$last_row = self::UpdateLastLogEndTime(array_pop($rows)); $last_row = self::UpdateLastLogEndTime(array_pop($rows));
array_push($rows, $last_row); array_push($rows, $last_row);
@ -36,7 +36,7 @@ class Application_Model_LiveLog
$con->exec($sql_delete); $con->exec($sql_delete);
} }
} }
$skip = true; $skip = true;
} }
$hours = 0; $hours = 0;
@ -55,13 +55,13 @@ class Application_Model_LiveLog
$intervals[$i] = 0; $intervals[$i] = 0;
} }
} }
// Trim milliseconds (DateInterval does not support) // Trim milliseconds (DateInterval does not support)
$sec = explode(".", $intervals[2]); $sec = explode(".", $intervals[2]);
if (isset($sec[0])) { if (isset($sec[0])) {
$intervals[2] = $sec[0]; $intervals[2] = $sec[0];
} }
$seconds += $intervals[2]; $seconds += $intervals[2];
if ($seconds / 60 >= 1) { if ($seconds / 60 >= 1) {
$minutes += 1; $minutes += 1;
@ -89,7 +89,7 @@ class Application_Model_LiveLog
$minutes = (double)(($hours*60)+$minutes . "." . $seconds[0]); $minutes = (double)(($hours*60)+$minutes . "." . $seconds[0]);
} }
else { else {
$minutes = (double)(($hours*60)+$minutes); $minutes = (double)(($hours*60)+$minutes);
} }
} }
return $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 { try {
$con = Propel::getConnection(); $con = Propel::getConnection();
@ -125,7 +125,7 @@ class Application_Model_LiveLog
." WHERE state = 'S'" ." WHERE state = 'S'"
." ORDER BY id"; ." ORDER BY id";
$rows = $con->query($sql)->fetchAll(); $rows = $con->query($sql)->fetchAll();
if ($rows != null) { if ($rows != null) {
$last_row = self::UpdateLastLogEndTime(array_pop($rows)); $last_row = self::UpdateLastLogEndTime(array_pop($rows));
array_push($rows, $last_row); array_push($rows, $last_row);
@ -135,7 +135,7 @@ class Application_Model_LiveLog
$con->exec($sql_delete); $con->exec($sql_delete);
} }
} }
$skip = true; $skip = true;
} }
$hours = 0; $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]; $clip_length_seconds = $clip_length_intervals[0]*3600 + $clip_length_intervals[1]*60 + $clip_length_intervals[2];
$extra_time = $extra_time->format("%H:%i:%s"); $extra_time = $extra_time->format("%H:%i:%s");
//Convert extra_time into seconds; //Convert extra_time into seconds;
$extra_time_intervals = explode(":", $extra_time); $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]; $extra_time_seconds = $extra_time_intervals[0]*3600 + $extra_time_intervals[1]*60 + $extra_time_intervals[2];
$clip_length_seconds -= $extra_time_seconds; $clip_length_seconds -= $extra_time_seconds;
//Convert new clip_length into "H-i-s" format //Convert new clip_length into "H-i-s" format
$clip_length_arr = array(); $clip_length_arr = array();
if ($clip_length_seconds / 3600 >= 1) { if ($clip_length_seconds / 3600 >= 1) {
@ -276,7 +276,7 @@ class Application_Model_LiveLog
public static function SetNewLogTime($state, $dateTime){ public static function SetNewLogTime($state, $dateTime){
try { try {
$con = Propel::getConnection(); $con = Propel::getConnection();
$scheduled = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play'); $scheduled = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play');
if ($state == 'L' && $scheduled == 'on') { if ($state == 'L' && $scheduled == 'on') {
self::SetEndTime('S', $dateTime); self::SetEndTime('S', $dateTime);

View File

@ -44,35 +44,35 @@ class Application_Model_MusicDir {
$this->_dir->setExists($flag); $this->_dir->setExists($flag);
$this->_dir->save(); $this->_dir->save();
} }
public function setWatchedFlag($flag){ public function setWatchedFlag($flag){
$this->_dir->setWatched($flag); $this->_dir->setWatched($flag);
$this->_dir->save(); $this->_dir->save();
} }
public function getWatchedFlag(){ public function getWatchedFlag(){
return $this->_dir->getWatched(); return $this->_dir->getWatched();
} }
public function getExistsFlag(){ public function getExistsFlag(){
return $this->_dir->getExists(); return $this->_dir->getExists();
} }
/** /**
* There are 2 cases where this function can be called. * There are 2 cases where this function can be called.
* 1. When watched dir was removed * 1. When watched dir was removed
* 2. When some dir was watched, but it was unmounted * 2. When some dir was watched, but it was unmounted
* *
* In case of 1, $userAddedWatchedDir should be true * In case of 1, $userAddedWatchedDir should be true
* In case of 2, $userAddedWatchedDir should be false * In case of 2, $userAddedWatchedDir should be false
* *
* When $userAddedWatchedDir is true, it will set "Watched" flag to false * When $userAddedWatchedDir is true, it will set "Watched" flag to false
* otherwise, it will set "Exists" flag to true * otherwise, it will set "Exists" flag to true
*/ */
public function remove($userAddedWatchedDir=true) public function remove($userAddedWatchedDir=true)
{ {
$con = Propel::getConnection(); $con = Propel::getConnection();
$music_dir_id = $this->getId(); $music_dir_id = $this->getId();
$sql = "SELECT DISTINCT s.instance_id from cc_music_dirs as md " $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"; ." RIGHT JOIN cc_schedule as s on s.file_id = f.id WHERE md.id = $music_dir_id";
$show_instances = $con->query($sql)->fetchAll(); $show_instances = $con->query($sql)->fetchAll();
// get all the files on this dir // 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 " $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)"; ." LEFT JOIN cc_files as f on f.directory = md.id WHERE md.id = $music_dir_id)";
$affected = $con->exec($sql); $affected = $con->exec($sql);
// set RemovedFlag to true // set RemovedFlag to true
if ($userAddedWatchedDir) { if ($userAddedWatchedDir) {
self::setWatchedFlag(false); self::setWatchedFlag(false);
@ -93,7 +93,7 @@ class Application_Model_MusicDir {
self::setExistsFlag(false); self::setExistsFlag(false);
} }
//$res = $this->_dir->delete(); //$res = $this->_dir->delete();
foreach ($show_instances as $show_instance_row) { foreach ($show_instances as $show_instance_row) {
$temp_show = new Application_Model_ShowInstance($show_instance_row["instance_id"]); $temp_show = new Application_Model_ShowInstance($show_instance_row["instance_id"]);
$temp_show->updateScheduledTime(); $temp_show->updateScheduledTime();
@ -133,7 +133,7 @@ class Application_Model_MusicDir {
public static function isPathValid($p_path){ public static function isPathValid($p_path){
$dirs = self::getWatchedDirs(); $dirs = self::getWatchedDirs();
$dirs[] = self::getStorDir(); $dirs[] = self::getStorDir();
foreach ($dirs as $dirObj){ foreach ($dirs as $dirObj){
$dir = $dirObj->getDirectory(); $dir = $dirObj->getDirectory();
$diff = strlen($dir) - strlen($p_path); $diff = strlen($dir) - strlen($p_path);
@ -156,15 +156,15 @@ class Application_Model_MusicDir {
/** There are 2 cases where this function can be called. /** There are 2 cases where this function can be called.
* 1. When watched dir was added * 1. When watched dir was added
* 2. When some dir was watched, but it was unmounted somehow, but gets mounted again * 2. When some dir was watched, but it was unmounted somehow, but gets mounted again
* *
* In case of 1, $userAddedWatchedDir should be true * In case of 1, $userAddedWatchedDir should be true
* In case of 2, $userAddedWatchedDir should be false * In case of 2, $userAddedWatchedDir should be false
* *
* When $userAddedWatchedDir is true, it will set "Removed" flag to false * When $userAddedWatchedDir is true, it will set "Removed" flag to false
* otherwise, it will set "Exists" flag to true * otherwise, it will set "Exists" flag to true
* *
* @param $nestedWatch - if true, bypass path check, and Watched to false * @param $nestedWatch - if true, bypass path check, and Watched to false
**/ **/
public static function addDir($p_path, $p_type, $userAddedWatchedDir=true, $nestedWatch=false) public static function addDir($p_path, $p_type, $userAddedWatchedDir=true, $nestedWatch=false)
{ {
if(!is_dir($p_path)){ if(!is_dir($p_path)){
@ -174,16 +174,16 @@ class Application_Model_MusicDir {
if($real_path != "/"){ if($real_path != "/"){
$p_path = $real_path; $p_path = $real_path;
} }
$exist_dir = self::getDirByPath($p_path); $exist_dir = self::getDirByPath($p_path);
if( $exist_dir == NULL ){ if( $exist_dir == NULL ){
$temp_dir = new CcMusicDirs(); $temp_dir = new CcMusicDirs();
$dir = new Application_Model_MusicDir($temp_dir); $dir = new Application_Model_MusicDir($temp_dir);
}else{ }else{
$dir = $exist_dir; $dir = $exist_dir;
} }
$dir->setType($p_type); $dir->setType($p_type);
$p_path = Application_Common_OsPath::normpath($p_path)."/"; $p_path = Application_Common_OsPath::normpath($p_path)."/";
@ -203,7 +203,7 @@ class Application_Model_MusicDir {
$dir->setExistsFlag(true); $dir->setExistsFlag(true);
} }
$dir->setDirectory($p_path); $dir->setDirectory($p_path);
return array("code"=>0); return array("code"=>0);
} catch (NestedDirectoryException $nde){ } catch (NestedDirectoryException $nde){
$msg = $nde->getMessage(); $msg = $nde->getMessage();
@ -217,17 +217,17 @@ class Application_Model_MusicDir {
/** There are 2 cases where this function can be called. /** There are 2 cases where this function can be called.
* 1. When watched dir was added * 1. When watched dir was added
* 2. When some dir was watched, but it was unmounted somehow, but gets mounted again * 2. When some dir was watched, but it was unmounted somehow, but gets mounted again
* *
* In case of 1, $userAddedWatchedDir should be true * In case of 1, $userAddedWatchedDir should be true
* In case of 2, $userAddedWatchedDir should be false * In case of 2, $userAddedWatchedDir should be false
* *
* When $userAddedWatchedDir is true, it will set "Watched" flag to true * When $userAddedWatchedDir is true, it will set "Watched" flag to true
* otherwise, it will set "Exists" flag to true * otherwise, it will set "Exists" flag to true
**/ **/
public static function addWatchedDir($p_path, $userAddedWatchedDir=true, $nestedWatch=false) public static function addWatchedDir($p_path, $userAddedWatchedDir=true, $nestedWatch=false)
{ {
$res = self::addDir($p_path, "watched", $userAddedWatchedDir, $nestedWatch); $res = self::addDir($p_path, "watched", $userAddedWatchedDir, $nestedWatch);
if ($res['code'] == 0){ if ($res['code'] == 0){
//convert "linked" files (Airtime <= 1.8.2) to watched files. //convert "linked" files (Airtime <= 1.8.2) to watched files.
@ -296,10 +296,10 @@ class Application_Model_MusicDir {
return $mus_dir; return $mus_dir;
} }
} }
/** /**
* Search and returns watched dirs * Search and returns watched dirs
* *
* @param $exists search condition with exists flag * @param $exists search condition with exists flag
* @param $watched search condition with watched 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. /** There are 2 cases where this function can be called.
* 1. When watched dir was removed * 1. When watched dir was removed
* 2. When some dir was watched, but it was unmounted * 2. When some dir was watched, but it was unmounted
* *
* In case of 1, $userAddedWatchedDir should be true * In case of 1, $userAddedWatchedDir should be true
* In case of 2, $userAddedWatchedDir should be false * In case of 2, $userAddedWatchedDir should be false
* *
* When $userAddedWatchedDir is true, it will set "Watched" flag to false * When $userAddedWatchedDir is true, it will set "Watched" flag to false
* otherwise, it will set "Exists" flag to true * otherwise, it will set "Exists" flag to true
**/ **/
public static function removeWatchedDir($p_dir, $userAddedWatchedDir=true){ public static function removeWatchedDir($p_dir, $userAddedWatchedDir=true){
//make sure that $p_dir has a trailing "/" //make sure that $p_dir has a trailing "/"
$real_path = Application_Common_OsPath::normpath($p_dir)."/"; $real_path = Application_Common_OsPath::normpath($p_dir)."/";
if($real_path != "/"){ if($real_path != "/"){
$p_dir = $real_path; $p_dir = $real_path;
@ -412,7 +412,7 @@ class Application_Model_MusicDir {
public static function splitFilePath($p_filepath) public static function splitFilePath($p_filepath)
{ {
$mus_dir = self::getWatchedDirFromFilepath($p_filepath); $mus_dir = self::getWatchedDirFromFilepath($p_filepath);
if(is_null($mus_dir)) { if(is_null($mus_dir)) {
return null; return null;
} }

View File

@ -20,17 +20,17 @@ class Application_Model_Playlist {
*/ */
private $id; private $id;
/** /**
* propel object for this playlist. * propel object for this playlist.
*/ */
private $pl; private $pl;
/** /**
* info needed to insert a new playlist element. * info needed to insert a new playlist element.
*/ */
private $plItem = array( private $plItem = array(
"id" => "", "id" => "",
"pos" => "", "pos" => "",
"cliplength" => "", "cliplength" => "",
"cuein" => "00:00:00", "cuein" => "00:00:00",
"cueout" => "00:00:00", "cueout" => "00:00:00",
@ -38,13 +38,13 @@ class Application_Model_Playlist {
"fadeout" => "0.0", "fadeout" => "0.0",
); );
//using propel's phpNames. //using propel's phpNames.
private $categories = array( private $categories = array(
"dc:title" => "Name", "dc:title" => "Name",
"dc:creator" => "Creator", "dc:creator" => "Creator",
"dc:description" => "Description", "dc:description" => "Description",
"dcterms:extent" => "Length" "dcterms:extent" => "Length"
); );
public function __construct($id=null, $con=null) public function __construct($id=null, $con=null)
@ -90,12 +90,12 @@ class Application_Model_Playlist {
*/ */
public function setName($p_newname) public function setName($p_newname)
{ {
$this->pl->setDbName($p_newname); $this->pl->setDbName($p_newname);
$this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
$this->pl->save($this->con); $this->pl->save($this->con);
} }
/** /**
* Get mnemonic playlist name * Get mnemonic playlist name
* *
* @return string * @return string
@ -107,9 +107,9 @@ class Application_Model_Playlist {
public function setDescription($p_description) public function setDescription($p_description)
{ {
$this->pl->setDbDescription($p_description); $this->pl->setDbDescription($p_description);
$this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
$this->pl->save($this->con); $this->pl->save($this->con);
} }
public function getDescription() public function getDescription()
@ -121,7 +121,7 @@ class Application_Model_Playlist {
return $this->pl->getCcSubjs()->getDbLogin(); return $this->pl->getCcSubjs()->getDbLogin();
} }
public function getCreatorId() { public function getCreatorId() {
return $this->pl->getCcSubjs()->getDbId(); 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. * 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 * @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 * @return array
*/ */
public function getContents($filterFiles=false) { public function getContents($filterFiles=false) {
@ -155,7 +155,7 @@ class Application_Model_Playlist {
$files = array(); $files = array();
$query = CcPlaylistcontentsQuery::create() $query = CcPlaylistcontentsQuery::create()
->filterByDbPlaylistId($this->id); ->filterByDbPlaylistId($this->id);
if($filterFiles){ if($filterFiles){
$query->useCcFilesQuery() $query->useCcFilesQuery()
->filterByDbFileExists(true) ->filterByDbFileExists(true)
@ -416,7 +416,7 @@ class Application_Model_Playlist {
* Remove audioClip from playlist * Remove audioClip from playlist
* *
* @param array $p_items * @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) 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) ->joinWith(CcFilesPeer::OM_CLASS)
->filterByDbPlaylistId($this->id) ->filterByDbPlaylistId($this->id)
->filterByDbPosition($pos) ->filterByDbPosition($pos)
@ -466,24 +466,24 @@ class Application_Model_Playlist {
$fadeIn = $row->getDbFadein(); $fadeIn = $row->getDbFadein();
$fadeOut = $row->getDbFadeout(); $fadeOut = $row->getDbFadeout();
return array($fadeIn, $fadeOut); return array($fadeIn, $fadeOut);
} }
/** /**
* Change fadeIn and fadeOut values for playlist Element * Change fadeIn and fadeOut values for playlist Element
* *
* @param int $pos * @param int $pos
* position of audioclip in playlist * position of audioclip in playlist
* @param string $fadeIn * @param string $fadeIn
* new value in ss.ssssss or extent format * new value in ss.ssssss or extent format
* @param string $fadeOut * @param string $fadeOut
* new value in ss.ssssss or extent format * new value in ss.ssssss or extent format
* @return boolean * @return boolean
*/ */
public function changeFadeInfo($id, $fadeIn, $fadeOut) 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 //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 //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; $fadeIn = $fadeIn?'00:00:'.$fadeIn:$fadeIn;
$fadeOut = $fadeOut?'00:00:'.$fadeOut:$fadeOut; $fadeOut = $fadeOut?'00:00:'.$fadeOut:$fadeOut;
@ -502,8 +502,8 @@ class Application_Model_Playlist {
if (!is_null($fadeIn)) { if (!is_null($fadeIn)) {
$sql = "SELECT INTERVAL '{$fadeIn}' > INTERVAL '{$clipLength}'"; $sql = "SELECT INTERVAL '{$fadeIn}' > INTERVAL '{$clipLength}'";
$r = $this->con->query($sql); $r = $this->con->query($sql);
if ($r->fetchColumn(0)) { if ($r->fetchColumn(0)) {
//"Fade In can't be larger than overall playlength."; //"Fade In can't be larger than overall playlength.";
$fadeIn = $clipLength; $fadeIn = $clipLength;
@ -512,8 +512,8 @@ class Application_Model_Playlist {
} }
if (!is_null($fadeOut)){ if (!is_null($fadeOut)){
$sql = "SELECT INTERVAL '{$fadeOut}' > INTERVAL '{$clipLength}'"; $sql = "SELECT INTERVAL '{$fadeOut}' > INTERVAL '{$clipLength}'";
$r = $this->con->query($sql); $r = $this->con->query($sql);
if ($r->fetchColumn(0)) { if ($r->fetchColumn(0)) {
//Fade Out can't be larger than overall playlength."; //Fade Out can't be larger than overall playlength.";
$fadeOut = $clipLength; $fadeOut = $clipLength;
@ -562,11 +562,11 @@ class Application_Model_Playlist {
* Change cueIn/cueOut values for playlist element * Change cueIn/cueOut values for playlist element
* *
* @param int $pos * @param int $pos
* position of audioclip in playlist * position of audioclip in playlist
* @param string $cueIn * @param string $cueIn
* new value in ss.ssssss or extent format * new value in ss.ssssss or extent format
* @param string $cueOut * @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 * @return boolean or pear error object
*/ */
public function changeClipLength($id, $cueIn, $cueOut) public function changeClipLength($id, $cueIn, $cueOut)
@ -604,23 +604,23 @@ class Application_Model_Playlist {
$cueOut = $origLength; $cueOut = $origLength;
} }
$sql = "SELECT INTERVAL '{$cueIn}' > INTERVAL '{$cueOut}'"; $sql = "SELECT INTERVAL '{$cueIn}' > INTERVAL '{$cueOut}'";
$r = $this->con->query($sql); $r = $this->con->query($sql);
if ($r->fetchColumn(0)) { if ($r->fetchColumn(0)) {
$errArray["error"] = "Can't set cue in to be larger than cue out."; $errArray["error"] = "Can't set cue in to be larger than cue out.";
return $errArray; return $errArray;
} }
$sql = "SELECT INTERVAL '{$cueOut}' > INTERVAL '{$origLength}'"; $sql = "SELECT INTERVAL '{$cueOut}' > INTERVAL '{$origLength}'";
$r = $this->con->query($sql); $r = $this->con->query($sql);
if ($r->fetchColumn(0)){ if ($r->fetchColumn(0)){
$errArray["error"] = "Can't set cue out to be greater than file length."; $errArray["error"] = "Can't set cue out to be greater than file length.";
return $errArray; return $errArray;
} }
$sql = "SELECT INTERVAL '{$cueOut}' - INTERVAL '{$cueIn}'"; $sql = "SELECT INTERVAL '{$cueOut}' - INTERVAL '{$cueIn}'";
$r = $this->con->query($sql); $r = $this->con->query($sql);
$cliplength = $r->fetchColumn(0); $cliplength = $r->fetchColumn(0);
$row->setDbCuein($cueIn); $row->setDbCuein($cueIn);
$row->setDbCueout($cueOut); $row->setDbCueout($cueOut);
@ -629,16 +629,16 @@ class Application_Model_Playlist {
} }
else if (!is_null($cueIn)) { else if (!is_null($cueIn)) {
$sql = "SELECT INTERVAL '{$cueIn}' > INTERVAL '{$oldCueOut}'"; $sql = "SELECT INTERVAL '{$cueIn}' > INTERVAL '{$oldCueOut}'";
$r = $this->con->query($sql); $r = $this->con->query($sql);
if ($r->fetchColumn(0)) { if ($r->fetchColumn(0)) {
$errArray["error"] = "Can't set cue in to be larger than cue out."; $errArray["error"] = "Can't set cue in to be larger than cue out.";
return $errArray; return $errArray;
} }
$sql = "SELECT INTERVAL '{$oldCueOut}' - INTERVAL '{$cueIn}'"; $sql = "SELECT INTERVAL '{$oldCueOut}' - INTERVAL '{$cueIn}'";
$r = $this->con->query($sql); $r = $this->con->query($sql);
$cliplength = $r->fetchColumn(0); $cliplength = $r->fetchColumn(0);
$row->setDbCuein($cueIn); $row->setDbCuein($cueIn);
$row->setDBCliplength($cliplength); $row->setDBCliplength($cliplength);
@ -649,23 +649,23 @@ class Application_Model_Playlist {
$cueOut = $origLength; $cueOut = $origLength;
} }
$sql = "SELECT INTERVAL '{$cueOut}' < INTERVAL '{$oldCueIn}'"; $sql = "SELECT INTERVAL '{$cueOut}' < INTERVAL '{$oldCueIn}'";
$r = $this->con->query($sql); $r = $this->con->query($sql);
if ($r->fetchColumn(0)) { if ($r->fetchColumn(0)) {
$errArray["error"] = "Can't set cue out to be smaller than cue in."; $errArray["error"] = "Can't set cue out to be smaller than cue in.";
return $errArray; return $errArray;
} }
$sql = "SELECT INTERVAL '{$cueOut}' > INTERVAL '{$origLength}'"; $sql = "SELECT INTERVAL '{$cueOut}' > INTERVAL '{$origLength}'";
$r = $this->con->query($sql); $r = $this->con->query($sql);
if ($r->fetchColumn(0)){ if ($r->fetchColumn(0)){
$errArray["error"] = "Can't set cue out to be greater than file length."; $errArray["error"] = "Can't set cue out to be greater than file length.";
return $errArray; return $errArray;
} }
$sql = "SELECT INTERVAL '{$cueOut}' - INTERVAL '{$oldCueIn}'"; $sql = "SELECT INTERVAL '{$cueOut}' - INTERVAL '{$oldCueIn}'";
$r = $this->con->query($sql); $r = $this->con->query($sql);
$cliplength = $r->fetchColumn(0); $cliplength = $r->fetchColumn(0);
$row->setDbCueout($cueOut); $row->setDbCueout($cueOut);
$row->setDBCliplength($cliplength); $row->setDBCliplength($cliplength);
@ -673,15 +673,15 @@ class Application_Model_Playlist {
$cliplength = $row->getDbCliplength(); $cliplength = $row->getDbCliplength();
$sql = "SELECT INTERVAL '{$fadeIn}' > INTERVAL '{$cliplength}'"; $sql = "SELECT INTERVAL '{$fadeIn}' > INTERVAL '{$cliplength}'";
$r = $this->con->query($sql); $r = $this->con->query($sql);
if ($r->fetchColumn(0)){ if ($r->fetchColumn(0)){
$fadeIn = $cliplength; $fadeIn = $cliplength;
$row->setDbFadein($fadeIn); $row->setDbFadein($fadeIn);
} }
$sql = "SELECT INTERVAL '{$fadeOut}' > INTERVAL '{$cliplength}'"; $sql = "SELECT INTERVAL '{$fadeOut}' > INTERVAL '{$cliplength}'";
$r = $this->con->query($sql); $r = $this->con->query($sql);
if ($r->fetchColumn(0)){ if ($r->fetchColumn(0)){
$fadeOut = $cliplength; $fadeOut = $cliplength;
$row->setDbFadein($fadeOut); $row->setDbFadein($fadeOut);

View File

@ -4,80 +4,80 @@ require_once 'formatters/LengthFormatter.php';
class Application_Model_PlayoutHistory { class Application_Model_PlayoutHistory {
private $con; private $con;
private $timezone; private $timezone;
//in UTC timezone //in UTC timezone
private $startDT; private $startDT;
//in UTC timezone //in UTC timezone
private $endDT; private $endDT;
private $epoch_now; private $epoch_now;
private $opts; 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)";
$results = Application_Model_Datatables::findEntries($this->con, $select, $historyTable, $this->opts, "history"); private $mDataPropMap = array(
"artist" => "file.artist_name",
foreach ($results["history"] as &$row) { "title" => "file.track_title",
$formatter = new LengthFormatter($row['length']); "played" => "playout.played",
$row['length'] = $formatter->format(); "length" => "file.length",
} "composer" => "file.composer",
"copyright" => "file.copyright",
return $results; );
}
} 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;
}
}

View File

@ -3,7 +3,7 @@
class Application_Model_Preference class Application_Model_Preference
{ {
public static function setValue($key, $value, $isUserValue = false){ public static function setValue($key, $value, $isUserValue = false){
try { try {
$con = Propel::getConnection(); $con = Propel::getConnection();
@ -27,7 +27,7 @@ class Application_Model_Preference
if($isUserValue) { if($isUserValue) {
$sql .= " AND subjid = '$id'"; $sql .= " AND subjid = '$id'";
} }
$result = $con->query($sql)->fetchColumn(0); $result = $con->query($sql)->fetchColumn(0);
if($value == "") { if($value == "") {
@ -35,7 +35,7 @@ class Application_Model_Preference
}else { }else {
$value = "'$value'"; $value = "'$value'";
} }
if($result == 1) { if($result == 1) {
// result found // result found
if(is_null($id) || !$isUserValue) { if(is_null($id) || !$isUserValue) {
@ -63,7 +63,7 @@ class Application_Model_Preference
} }
$con->exec($sql); $con->exec($sql);
} catch (Exception $e){ } catch (Exception $e){
header('HTTP/1.0 503 Service Unavailable'); header('HTTP/1.0 503 Service Unavailable');
Logging::log("Could not connect to database: ".$e->getMessage()); 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 { try {
$con = Propel::getConnection(); $con = Propel::getConnection();
@ -105,7 +105,7 @@ class Application_Model_Preference
} catch (Exception $e) { } catch (Exception $e) {
header('HTTP/1.0 503 Service Unavailable'); header('HTTP/1.0 503 Service Unavailable');
Logging::log("Could not connect to database: ".$e->getMessage()); Logging::log("Could not connect to database: ".$e->getMessage());
exit; exit;
} }
} }
@ -171,12 +171,12 @@ class Application_Model_Preference
public static function GetDefaultFade() { public static function GetDefaultFade() {
$fade = self::getValue("default_fade"); $fade = self::getValue("default_fade");
if ($fade === "") { if ($fade === "") {
// the default value of the fade is 00.500000 // the default value of the fade is 00.500000
return "00.500000"; return "00.500000";
} }
// we need this function to work with 2.0 version on default_fade value in cc_pref // 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 // it has 00:00:00.000000 format where in 2.1 we have 00.000000 format
if(preg_match("/([0-9]{2}):([0-9]{2}):([0-9]{2}).([0-9]{6})/", $fade, $matches) == 1 && count($matches) == 5){ if(preg_match("/([0-9]{2}):([0-9]{2}):([0-9]{2}).([0-9]{6})/", $fade, $matches) == 1 && count($matches) == 5){
@ -187,7 +187,7 @@ class Application_Model_Preference
$out .= ".$matches[4]"; $out .= ".$matches[4]";
$fade = $out; $fade = $out;
} }
$fade = number_format($fade, 6); $fade = number_format($fade, 6);
//fades need 2 leading zeros for DateTime conversion //fades need 2 leading zeros for DateTime conversion
$fade = str_pad($fade, 9, "0", STR_PAD_LEFT); $fade = str_pad($fade, 9, "0", STR_PAD_LEFT);
@ -298,75 +298,75 @@ class Application_Model_Preference
} }
public static function SetPhone($phone){ public static function SetPhone($phone){
self::setValue("phone", $phone); self::setValue("phone", $phone);
} }
public static function GetPhone(){ public static function GetPhone(){
return self::getValue("phone"); return self::getValue("phone");
} }
public static function SetEmail($email){ public static function SetEmail($email){
self::setValue("email", $email); self::setValue("email", $email);
} }
public static function GetEmail(){ public static function GetEmail(){
return self::getValue("email"); return self::getValue("email");
} }
public static function SetStationWebSite($site){ public static function SetStationWebSite($site){
self::setValue("station_website", $site); self::setValue("station_website", $site);
} }
public static function GetStationWebSite(){ public static function GetStationWebSite(){
return self::getValue("station_website"); return self::getValue("station_website");
} }
public static function SetSupportFeedback($feedback){ public static function SetSupportFeedback($feedback){
self::setValue("support_feedback", $feedback); self::setValue("support_feedback", $feedback);
} }
public static function GetSupportFeedback(){ public static function GetSupportFeedback(){
return self::getValue("support_feedback"); return self::getValue("support_feedback");
} }
public static function SetPublicise($publicise){ public static function SetPublicise($publicise){
self::setValue("publicise", $publicise); self::setValue("publicise", $publicise);
} }
public static function GetPublicise(){ public static function GetPublicise(){
return self::getValue("publicise"); return self::getValue("publicise");
} }
public static function SetRegistered($registered){ public static function SetRegistered($registered){
self::setValue("registered", $registered); self::setValue("registered", $registered);
} }
public static function GetRegistered(){ public static function GetRegistered(){
return self::getValue("registered"); return self::getValue("registered");
} }
public static function SetStationCountry($country){ public static function SetStationCountry($country){
self::setValue("country", $country); self::setValue("country", $country);
} }
public static function GetStationCountry(){ public static function GetStationCountry(){
return self::getValue("country"); return self::getValue("country");
} }
public static function SetStationCity($city){ public static function SetStationCity($city){
self::setValue("city", $city); self::setValue("city", $city);
} }
public static function GetStationCity(){ public static function GetStationCity(){
return self::getValue("city"); return self::getValue("city");
} }
public static function SetStationDescription($description){ public static function SetStationDescription($description){
self::setValue("description", $description); self::setValue("description", $description);
} }
public static function GetStationDescription(){ public static function GetStationDescription(){
return self::getValue("description"); return self::getValue("description");
} }
public static function SetTimezone($timezone){ public static function SetTimezone($timezone){
@ -380,139 +380,139 @@ class Application_Model_Preference
} }
public static function SetStationLogo($imagePath){ public static function SetStationLogo($imagePath){
if(!empty($imagePath)){ if(!empty($imagePath)){
$image = @file_get_contents($imagePath); $image = @file_get_contents($imagePath);
$image = base64_encode($image); $image = base64_encode($image);
self::setValue("logoImage", $image); self::setValue("logoImage", $image);
} }
} }
public static function GetStationLogo(){ public static function GetStationLogo(){
return self::getValue("logoImage"); return self::getValue("logoImage");
} }
public static function GetUniqueId(){ public static function GetUniqueId(){
return self::getValue("uniqueId"); return self::getValue("uniqueId");
} }
public static function GetCountryList() public static function GetCountryList()
{ {
$con = Propel::getConnection(); $con = Propel::getConnection();
$sql = "SELECT * FROM cc_country"; $sql = "SELECT * FROM cc_country";
$res = $con->query($sql)->fetchAll(); $res = $con->query($sql)->fetchAll();
$out = array(); $out = array();
$out[""] = "Select Country"; $out[""] = "Select Country";
foreach($res as $r){ foreach($res as $r){
$out[$r["isocode"]] = $r["name"]; $out[$r["isocode"]] = $r["name"];
} }
return $out; return $out;
} }
public static function GetSystemInfo($returnArray=false, $p_testing=false) public static function GetSystemInfo($returnArray=false, $p_testing=false)
{ {
exec('/usr/bin/airtime-check-system --no-color', $output); exec('/usr/bin/airtime-check-system --no-color', $output);
$output = preg_replace('/\s+/', ' ', $output); $output = preg_replace('/\s+/', ' ', $output);
$systemInfoArray = array(); $systemInfoArray = array();
foreach( $output as $key => &$out){ foreach( $output as $key => &$out){
$info = explode('=', $out); $info = explode('=', $out);
if(isset($info[1])){ if(isset($info[1])){
$key = str_replace(' ', '_', trim($info[0])); $key = str_replace(' ', '_', trim($info[0]));
$key = strtoupper($key); $key = strtoupper($key);
if ($key == 'WEB_SERVER' || $key == 'CPU' || $key == 'OS' || $key == 'TOTAL_RAM' || if ($key == 'WEB_SERVER' || $key == 'CPU' || $key == 'OS' || $key == 'TOTAL_RAM' ||
$key == 'FREE_RAM' || $key == 'AIRTIME_VERSION' || $key == 'KERNAL_VERSION' || $key == 'FREE_RAM' || $key == 'AIRTIME_VERSION' || $key == 'KERNAL_VERSION' ||
$key == 'MACHINE_ARCHITECTURE' || $key == 'TOTAL_MEMORY_MBYTES' || $key == 'TOTAL_SWAP_MBYTES' || $key == 'MACHINE_ARCHITECTURE' || $key == 'TOTAL_MEMORY_MBYTES' || $key == 'TOTAL_SWAP_MBYTES' ||
$key == 'PLAYOUT_ENGINE_CPU_PERC' ) { $key == 'PLAYOUT_ENGINE_CPU_PERC' ) {
if($key == 'AIRTIME_VERSION'){ if($key == 'AIRTIME_VERSION'){
// remove hash tag on the version string // remove hash tag on the version string
$version = explode('+', $info[1]); $version = explode('+', $info[1]);
$systemInfoArray[$key] = $version[0]; $systemInfoArray[$key] = $version[0];
}else{ }else{
$systemInfoArray[$key] = $info[1]; $systemInfoArray[$key] = $info[1];
} }
} }
} }
} }
$outputArray = array();
$outputArray['LIVE_DURATION'] = Application_Model_LiveLog::GetLiveShowDuration($p_testing); $outputArray = array();
$outputArray['SCHEDULED_DURATION'] = Application_Model_LiveLog::GetScheduledDuration($p_testing);
$outputArray['SOUNDCLOUD_ENABLED'] = self::GetUploadToSoundcloudOption(); $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']) { if ($outputArray['SOUNDCLOUD_ENABLED']) {
$outputArray['NUM_SOUNDCLOUD_TRACKS_UPLOADED'] = Application_Model_StoredFile::getSoundCloudUploads(); $outputArray['NUM_SOUNDCLOUD_TRACKS_UPLOADED'] = Application_Model_StoredFile::getSoundCloudUploads();
} else { } else {
$outputArray['NUM_SOUNDCLOUD_TRACKS_UPLOADED'] = NULL; $outputArray['NUM_SOUNDCLOUD_TRACKS_UPLOADED'] = NULL;
} }
$outputArray['STATION_NAME'] = self::GetStationName(); $outputArray['STATION_NAME'] = self::GetStationName();
$outputArray['PHONE'] = self::GetPhone(); $outputArray['PHONE'] = self::GetPhone();
$outputArray['EMAIL'] = self::GetEmail(); $outputArray['EMAIL'] = self::GetEmail();
$outputArray['STATION_WEB_SITE'] = self::GetStationWebSite(); $outputArray['STATION_WEB_SITE'] = self::GetStationWebSite();
$outputArray['STATION_COUNTRY'] = self::GetStationCountry(); $outputArray['STATION_COUNTRY'] = self::GetStationCountry();
$outputArray['STATION_CITY'] = self::GetStationCity(); $outputArray['STATION_CITY'] = self::GetStationCity();
$outputArray['STATION_DESCRIPTION'] = self::GetStationDescription(); $outputArray['STATION_DESCRIPTION'] = self::GetStationDescription();
// get web server info // get web server info
if(isset($systemInfoArray["AIRTIME_VERSION_URL"])){ if(isset($systemInfoArray["AIRTIME_VERSION_URL"])){
$url = $systemInfoArray["AIRTIME_VERSION_URL"]; $url = $systemInfoArray["AIRTIME_VERSION_URL"];
$index = strpos($url,'/api/'); $index = strpos($url,'/api/');
$url = substr($url, 0, $index); $url = substr($url, 0, $index);
$headerInfo = get_headers(trim($url),1); $headerInfo = get_headers(trim($url),1);
$outputArray['WEB_SERVER'] = $headerInfo['Server'][0]; $outputArray['WEB_SERVER'] = $headerInfo['Server'][0];
} }
$outputArray['NUM_OF_USERS'] = Application_Model_User::getUserCount(); $outputArray['NUM_OF_USERS'] = Application_Model_User::getUserCount();
$outputArray['NUM_OF_SONGS'] = Application_Model_StoredFile::getFileCount(); $outputArray['NUM_OF_SONGS'] = Application_Model_StoredFile::getFileCount();
$outputArray['NUM_OF_PLAYLISTS'] = Application_Model_Playlist::getPlaylistCount(); $outputArray['NUM_OF_PLAYLISTS'] = Application_Model_Playlist::getPlaylistCount();
$outputArray['NUM_OF_SCHEDULED_PLAYLISTS'] = Application_Model_Schedule::getSchduledPlaylistCount(); $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['NUM_OF_PAST_SHOWS'] = Application_Model_ShowInstance::GetShowInstanceCount(gmdate("Y-m-d H:i:s"));
$outputArray['UNIQUE_ID'] = self::GetUniqueId(); $outputArray['UNIQUE_ID'] = self::GetUniqueId();
$outputArray['SAAS'] = self::GetPlanLevel(); $outputArray['SAAS'] = self::GetPlanLevel();
if ($outputArray['SAAS'] != 'disabled') { if ($outputArray['SAAS'] != 'disabled') {
$outputArray['TRIAL_END_DATE'] = self::GetTrialEndingDate(); $outputArray['TRIAL_END_DATE'] = self::GetTrialEndingDate();
} else { } else {
$outputArray['TRIAL_END_DATE'] = NULL; $outputArray['TRIAL_END_DATE'] = NULL;
} }
$outputArray['INSTALL_METHOD'] = self::GetInstallMethod(); $outputArray['INSTALL_METHOD'] = self::GetInstallMethod();
$outputArray['NUM_OF_STREAMS'] = self::GetNumOfStreams(); $outputArray['NUM_OF_STREAMS'] = self::GetNumOfStreams();
$outputArray['STREAM_INFO'] = Application_Model_StreamSetting::getStreamInfoForDataCollection(); $outputArray['STREAM_INFO'] = Application_Model_StreamSetting::getStreamInfoForDataCollection();
$outputArray = array_merge($systemInfoArray, $outputArray); $outputArray = array_merge($systemInfoArray, $outputArray);
$outputString = "\n"; $outputString = "\n";
foreach($outputArray as $key => $out){ foreach($outputArray as $key => $out){
if($key == 'TRIAL_END_DATE' && ($out != '' || $out != 'NULL')){ if($key == 'TRIAL_END_DATE' && ($out != '' || $out != 'NULL')){
continue; continue;
} }
if($key == "STREAM_INFO"){ if($key == "STREAM_INFO"){
$outputString .= $key." :\n"; $outputString .= $key." :\n";
foreach($out as $s_info){ foreach($out as $s_info){
foreach($s_info as $k => $v){ foreach($s_info as $k => $v){
$outputString .= "\t".strtoupper($k)." : ".$v."\n"; $outputString .= "\t".strtoupper($k)." : ".$v."\n";
} }
} }
}else if ($key == "SOUNDCLOUD_ENABLED") { }else if ($key == "SOUNDCLOUD_ENABLED") {
if ($out) { if ($out) {
$outputString .= $key." : TRUE\n"; $outputString .= $key." : TRUE\n";
} else if (!$out) { } else if (!$out) {
$outputString .= $key." : FALSE\n"; $outputString .= $key." : FALSE\n";
} }
}else if ($key == "SAAS") { }else if ($key == "SAAS") {
if (strcmp($out, 'disabled')!=0) { if (strcmp($out, 'disabled')!=0) {
$outputString .= $key.' : '.$out."\n"; $outputString .= $key.' : '.$out."\n";
} }
}else{ }else{
$outputString .= $key.' : '.$out."\n"; $outputString .= $key.' : '.$out."\n";
} }
} }
if($returnArray){ if($returnArray){
$outputArray['PROMOTE'] = self::GetPublicise(); $outputArray['PROMOTE'] = self::GetPublicise();
$outputArray['LOGOIMG'] = self::GetStationLogo(); $outputArray['LOGOIMG'] = self::GetStationLogo();
return $outputArray; return $outputArray;
}else{ }else{
return $outputString; return $outputString;
} }
} }
public static function GetInstallMethod(){ public static function GetInstallMethod(){
@ -530,8 +530,8 @@ class Application_Model_Preference
} }
public static function SetRemindMeDate(){ public static function SetRemindMeDate(){
$weekAfter = mktime(0, 0, 0, gmdate("m"), gmdate("d")+7, gmdate("Y")); $weekAfter = mktime(0, 0, 0, gmdate("m"), gmdate("d")+7, gmdate("Y"));
self::setValue("remindme", $weekAfter); self::setValue("remindme", $weekAfter);
} }
public static function GetRemindMeDate(){ public static function GetRemindMeDate(){
@ -679,7 +679,7 @@ class Application_Model_Preference
} }
public static function GetWeekStartDay() { public static function GetWeekStartDay() {
$val = self::getValue("week_start_day"); $val = self::getValue("week_start_day");
if (strlen($val) == 0){ if (strlen($val) == 0){
return "0"; return "0";
} else { } else {
@ -721,7 +721,7 @@ class Application_Model_Preference
/** /**
* Sets the time scale preference (agendaDay/agendaWeek/month) in Calendar. * 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) { public static function SetCalendarTimeScale($timeScale) {
self::setValue("calendar_time_scale", $timeScale, true /* user specific */); self::setValue("calendar_time_scale", $timeScale, true /* user specific */);
@ -736,16 +736,16 @@ class Application_Model_Preference
if(strlen($val) == 0) { if(strlen($val) == 0) {
$val = "month"; $val = "month";
} }
return $val; return $val;
} }
/** /**
* Sets the number of entries to show preference in library under Playlist Builder. * 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) { 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 * Defaults to 10 if no entry exists
*/ */
public static function GetLibraryNumEntries() { 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) { if(strlen($val) == 0) {
$val = "10"; $val = "10";
} }
@ -763,7 +763,7 @@ class Application_Model_Preference
/** /**
* Sets the time interval preference in Calendar. * Sets the time interval preference in Calendar.
* *
* @param $timeInterval new time interval * @param $timeInterval new time interval
*/ */
public static function SetCalendarTimeInterval($timeInterval) { public static function SetCalendarTimeInterval($timeInterval) {
self::setValue("calendar_time_interval", $timeInterval, true /* user specific */); 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 * Defaults to 30 min if no entry exists
*/ */
public static function GetCalendarTimeInterval() { public static function GetCalendarTimeInterval() {
$val = self::getValue("calendar_time_interval", true /* user specific */); $val = self::getValue("calendar_time_interval", true /* user specific */);
if(strlen($val) == 0) { if(strlen($val) == 0) {
$val = "30"; $val = "30";
} }
@ -842,7 +842,7 @@ class Application_Model_Preference
public static function GetMasterDJSourceConnectionURL(){ public static function GetMasterDJSourceConnectionURL(){
return self::getValue("master_dj_source_connection_url"); return self::getValue("master_dj_source_connection_url");
} }
public static function SetLiveDJSourceConnectionURL($value){ public static function SetLiveDJSourceConnectionURL($value){
self::setValue("live_dj_source_connection_url", $value, false); self::setValue("live_dj_source_connection_url", $value, false);
} }
@ -850,55 +850,55 @@ class Application_Model_Preference
public static function GetLiveDJSourceConnectionURL(){ public static function GetLiveDJSourceConnectionURL(){
return self::getValue("live_dj_source_connection_url"); return self::getValue("live_dj_source_connection_url");
} }
/* Source Connection URL override status starts */ /* Source Connection URL override status starts */
public static function GetLiveDjConnectionUrlOverride(){ public static function GetLiveDjConnectionUrlOverride(){
return self::getValue("live_dj_connection_url_override"); return self::getValue("live_dj_connection_url_override");
} }
public static function SetLiveDjConnectionUrlOverride($value){ public static function SetLiveDjConnectionUrlOverride($value){
self::setValue("live_dj_connection_url_override", $value, false); self::setValue("live_dj_connection_url_override", $value, false);
} }
public static function GetMasterDjConnectionUrlOverride(){ public static function GetMasterDjConnectionUrlOverride(){
return self::getValue("master_dj_connection_url_override"); return self::getValue("master_dj_connection_url_override");
} }
public static function SetMasterDjConnectionUrlOverride($value){ public static function SetMasterDjConnectionUrlOverride($value){
self::setValue("master_dj_connection_url_override", $value, false); self::setValue("master_dj_connection_url_override", $value, false);
} }
/* Source Connection URL override status ends */ /* Source Connection URL override status ends */
public static function SetAutoTransition($value){ public static function SetAutoTransition($value){
self::setValue("auto_transition", $value, false); self::setValue("auto_transition", $value, false);
} }
public static function GetAutoTransition(){ public static function GetAutoTransition(){
return self::getValue("auto_transition"); return self::getValue("auto_transition");
} }
public static function SetAutoSwitch($value){ public static function SetAutoSwitch($value){
self::setValue("auto_switch", $value, false); self::setValue("auto_switch", $value, false);
} }
public static function GetAutoSwitch(){ public static function GetAutoSwitch(){
return self::getValue("auto_switch"); return self::getValue("auto_switch");
} }
public static function SetEnableSystemEmail($upload) { public static function SetEnableSystemEmail($upload) {
self::setValue("enable_system_email", $upload); self::setValue("enable_system_email", $upload);
} }
public static function GetEnableSystemEmail() { public static function GetEnableSystemEmail() {
$v = self::getValue("enable_system_email"); $v = self::getValue("enable_system_email");
if ($v === "") { if ($v === "") {
return 0; return 0;
} }
return $v; return $v;
} }
public static function SetSystemEmail($value) { public static function SetSystemEmail($value) {
self::setValue("system_email", $value, false); self::setValue("system_email", $value, false);
} }
@ -906,46 +906,46 @@ class Application_Model_Preference
public static function GetSystemEmail() { public static function GetSystemEmail() {
return self::getValue("system_email"); return self::getValue("system_email");
} }
public static function SetMailServerConfigured($value) { public static function SetMailServerConfigured($value) {
self::setValue("mail_server_configured", $value, false); self::setValue("mail_server_configured", $value, false);
} }
public static function GetMailServerConfigured() { public static function GetMailServerConfigured() {
return self::getValue("mail_server_configured"); return self::getValue("mail_server_configured");
} }
public static function SetMailServer($value) { public static function SetMailServer($value) {
self::setValue("mail_server", $value, false); self::setValue("mail_server", $value, false);
} }
public static function GetMailServer() { public static function GetMailServer() {
return self::getValue("mail_server"); return self::getValue("mail_server");
} }
public static function SetMailServerEmailAddress($value) { public static function SetMailServerEmailAddress($value) {
self::setValue("mail_server_email_address", $value, false); self::setValue("mail_server_email_address", $value, false);
} }
public static function GetMailServerEmailAddress() { public static function GetMailServerEmailAddress() {
return self::getValue("mail_server_email_address"); return self::getValue("mail_server_email_address");
} }
public static function SetMailServerPassword($value) { public static function SetMailServerPassword($value) {
self::setValue("mail_server_password", $value, false); self::setValue("mail_server_password", $value, false);
} }
public static function GetMailServerPassword() { public static function GetMailServerPassword() {
return self::getValue("mail_server_password"); return self::getValue("mail_server_password");
} }
public static function SetMailServerPort($value) { public static function SetMailServerPort($value) {
self::setValue("mail_server_port", $value, false); self::setValue("mail_server_port", $value, false);
} }
public static function GetMailServerPort() { public static function GetMailServerPort() {
return self::getValue("mail_server_port"); return self::getValue("mail_server_port");
} }
/* User specific preferences end */ /* User specific preferences end */
public static function ShouldShowPopUp(){ public static function ShouldShowPopUp(){

View File

@ -61,7 +61,7 @@ class Application_Model_RabbitMq
$channel->close(); $channel->close();
$conn->close(); $conn->close();
} }
public static function SendMessageToShowRecorder($event_type) public static function SendMessageToShowRecorder($event_type)
{ {
global $CC_CONFIG; global $CC_CONFIG;
@ -73,10 +73,10 @@ class Application_Model_RabbitMq
$CC_CONFIG["rabbitmq"]["vhost"]); $CC_CONFIG["rabbitmq"]["vhost"]);
$channel = $conn->channel(); $channel = $conn->channel();
$channel->access_request($CC_CONFIG["rabbitmq"]["vhost"], false, false, true, true); $channel->access_request($CC_CONFIG["rabbitmq"]["vhost"], false, false, true, true);
$EXCHANGE = 'airtime-pypo'; $EXCHANGE = 'airtime-pypo';
$channel->exchange_declare($EXCHANGE, 'direct', false, true); $channel->exchange_declare($EXCHANGE, 'direct', false, true);
$now = new DateTime("@".time()); //in UTC timezone $now = new DateTime("@".time()); //in UTC timezone
$end_timestamp = new DateTime("@".(time() + 3600*2)); //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); $data = json_encode($temp);
$msg = new AMQPMessage($data, array('content_type' => 'text/plain')); $msg = new AMQPMessage($data, array('content_type' => 'text/plain'));
$channel->basic_publish($msg, $EXCHANGE); $channel->basic_publish($msg, $EXCHANGE);
$channel->close(); $channel->close();
$conn->close(); $conn->close();

View File

@ -81,7 +81,7 @@ class Application_Model_Schedule {
/* Alternate SQL...merge conflict and I'm not sure which on is right.... -MK /* 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 $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 '; WHERE ';
*/ */
@ -231,15 +231,15 @@ class Application_Model_Schedule {
return $row; return $row;
} }
/* /*
* *
* @param DateTime $p_startDateTime * @param DateTime $p_startDateTime
* *
* @param DateTime $p_endDateTime * @param DateTime $p_endDateTime
* *
* @return array $scheduledItems * @return array $scheduledItems
* *
*/ */
public static function GetScheduleDetailItems($p_start, $p_end, $p_shows) public static function GetScheduleDetailItems($p_start, $p_end, $p_shows)
{ {
global $CC_CONFIG; global $CC_CONFIG;
@ -279,7 +279,7 @@ class Application_Model_Schedule {
} }
$sql .= " ORDER BY si.starts, sched.starts;"; $sql .= " ORDER BY si.starts, sched.starts;";
Logging::debug($sql); Logging::debug($sql);
$rows = $con->query($sql)->fetchAll(); $rows = $con->query($sql)->fetchAll();
@ -297,17 +297,17 @@ class Application_Model_Schedule {
$live_dj = Application_Model_Preference::GetSourceSwitchStatus('live_dj') == 'on'?true:false; $live_dj = Application_Model_Preference::GetSourceSwitchStatus('live_dj') == 'on'?true:false;
$master_dj = Application_Model_Preference::GetSourceSwitchStatus('master_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; $scheduled_play = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play') == 'on'?true:false;
if(!$live_dj && !$master_dj && $scheduled_play){ if(!$live_dj && !$master_dj && $scheduled_play){
$sql .= ", broadcasted=1"; $sql .= ", broadcasted=1";
} }
$sql .= " WHERE id=$p_id"; $sql .= " WHERE id=$p_id";
$retVal = $con->exec($sql); $retVal = $con->exec($sql);
return $retVal; return $retVal;
} }
public static function UpdateBrodcastedStatus($dateTime, $value){ public static function UpdateBrodcastedStatus($dateTime, $value){
global $CC_CONFIG; global $CC_CONFIG;
$con = Propel::getConnection(); $con = Propel::getConnection();
@ -551,7 +551,7 @@ class Application_Model_Schedule {
$data["media"][$kick_start]['end'] = $kick_start; $data["media"][$kick_start]['end'] = $kick_start;
$data["media"][$kick_start]['event_type'] = "kick_out"; $data["media"][$kick_start]['event_type'] = "kick_out";
$data["media"][$kick_start]['type'] = "event"; $data["media"][$kick_start]['type'] = "event";
if($kick_time !== $switch_off_time){ if($kick_time !== $switch_off_time){
$switch_start = Application_Model_Schedule::AirtimeTimeToPypoTime($switch_off_time); $switch_start = Application_Model_Schedule::AirtimeTimeToPypoTime($switch_off_time);
$data["media"][$switch_start]['start'] = $switch_start; $data["media"][$switch_start]['start'] = $switch_start;
@ -562,16 +562,16 @@ class Application_Model_Schedule {
} }
foreach ($items as $item){ foreach ($items as $item){
$showInstance = CcShowInstancesQuery::create()->findPK($item["instance_id"]); $showInstance = CcShowInstancesQuery::create()->findPK($item["instance_id"]);
$showId = $showInstance->getDbShowId(); $showId = $showInstance->getDbShowId();
$show = CcShowQuery::create()->findPK($showId); $show = CcShowQuery::create()->findPK($showId);
$showName = $show->getDbName(); $showName = $show->getDbName();
$showEndDateTime = new DateTime($item["show_end"], $utcTimeZone); $showEndDateTime = new DateTime($item["show_end"], $utcTimeZone);
$trackStartDateTime = new DateTime($item["start"], $utcTimeZone); $trackStartDateTime = new DateTime($item["start"], $utcTimeZone);
$trackEndDateTime = new DateTime($item["end"], $utcTimeZone); $trackEndDateTime = new DateTime($item["end"], $utcTimeZone);
if ($trackStartDateTime->getTimestamp() > $showEndDateTime->getTimestamp()){ if ($trackStartDateTime->getTimestamp() > $showEndDateTime->getTimestamp()){
continue; continue;
} }
@ -584,10 +584,10 @@ class Application_Model_Schedule {
$item["cue_out"] = $di->format("%H:%i:%s").".000"; $item["cue_out"] = $di->format("%H:%i:%s").".000";
$item["end"] = $showEndDateTime->format("Y-m-d H:i:s"); $item["end"] = $showEndDateTime->format("Y-m-d H:i:s");
} }
$storedFile = Application_Model_StoredFile::Recall($item["file_id"]); $storedFile = Application_Model_StoredFile::Recall($item["file_id"]);
$uri = $storedFile->getFilePath(); $uri = $storedFile->getFilePath();
$start = Application_Model_Schedule::AirtimeTimeToPypoTime($item["start"]); $start = Application_Model_Schedule::AirtimeTimeToPypoTime($item["start"]);
$data["media"][$start] = array( $data["media"][$start] = array(
'id' => $storedFile->getGunid(), 'id' => $storedFile->getGunid(),
@ -614,7 +614,7 @@ class Application_Model_Schedule {
$con = Propel::getConnection(); $con = Propel::getConnection();
$con->exec("TRUNCATE TABLE ".$CC_CONFIG["scheduleTable"]); $con->exec("TRUNCATE TABLE ".$CC_CONFIG["scheduleTable"]);
} }
public static function deleteWithFileId($fileId){ public static function deleteWithFileId($fileId){
global $CC_CONFIG; global $CC_CONFIG;
$con = Propel::getConnection(); $con = Propel::getConnection();
@ -626,18 +626,18 @@ class Application_Model_Schedule {
$isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; $isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true;
$formWhat = new Application_Form_AddShowWhat(); $formWhat = new Application_Form_AddShowWhat();
$formWho = new Application_Form_AddShowWho(); $formWho = new Application_Form_AddShowWho();
$formWhen = new Application_Form_AddShowWhen(); $formWhen = new Application_Form_AddShowWhen();
$formRepeats = new Application_Form_AddShowRepeats(); $formRepeats = new Application_Form_AddShowRepeats();
$formStyle = new Application_Form_AddShowStyle(); $formStyle = new Application_Form_AddShowStyle();
$formLive = new Application_Form_AddShowLiveStream(); $formLive = new Application_Form_AddShowLiveStream();
$formWhat->removeDecorator('DtDdWrapper'); $formWhat->removeDecorator('DtDdWrapper');
$formWho->removeDecorator('DtDdWrapper'); $formWho->removeDecorator('DtDdWrapper');
$formWhen->removeDecorator('DtDdWrapper'); $formWhen->removeDecorator('DtDdWrapper');
$formRepeats->removeDecorator('DtDdWrapper'); $formRepeats->removeDecorator('DtDdWrapper');
$formStyle->removeDecorator('DtDdWrapper'); $formStyle->removeDecorator('DtDdWrapper');
$formLive->removeDecorator('DtDdWrapper'); $formLive->removeDecorator('DtDdWrapper');
$p_view->what = $formWhat; $p_view->what = $formWhat;
$p_view->when = $formWhen; $p_view->when = $formWhen;
@ -646,7 +646,7 @@ class Application_Model_Schedule {
$p_view->style = $formStyle; $p_view->style = $formStyle;
$p_view->live = $formLive; $p_view->live = $formLive;
$formWhat->populate(array('add_show_id' => '-1', $formWhat->populate(array('add_show_id' => '-1',
'add_show_instance_id' => '-1')); 'add_show_instance_id' => '-1'));
$formWhen->populate(array('add_show_start_date' => date("Y-m-d"), $formWhen->populate(array('add_show_start_date' => date("Y-m-d"),
'add_show_start_time' => '00:00', 'add_show_start_time' => '00:00',
@ -671,29 +671,29 @@ class Application_Model_Schedule {
} }
$p_view->addNewShow = true; $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). * 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 * 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 * 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 */ * 2.1 deadline looming, this is OK for now. -Martin */
public static function updateShowInstance($data, $controller){ public static function updateShowInstance($data, $controller){
$isSaas = (Application_Model_Preference::GetPlanLevel() != 'disabled'); $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'); $formWhat = new Application_Form_AddShowWhat();
$formWhen->removeDecorator('DtDdWrapper'); $formWhen = new Application_Form_AddShowWhen();
$formRepeats->removeDecorator('DtDdWrapper'); $formRepeats = new Application_Form_AddShowRepeats();
$formWho->removeDecorator('DtDdWrapper'); $formWho = new Application_Form_AddShowWho();
$formStyle->removeDecorator('DtDdWrapper'); $formStyle = new Application_Form_AddShowStyle();
$formLive->removeDecorator('DtDdWrapper'); $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){ if(!$isSaas){
$formRecord = new Application_Form_AddShowRR(); $formRecord = new Application_Form_AddShowRR();
$formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates();
@ -704,21 +704,21 @@ class Application_Model_Schedule {
$formRebroadcast->removeDecorator('DtDdWrapper'); $formRebroadcast->removeDecorator('DtDdWrapper');
} }
$when = $formWhen->isValid($data); $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 = new DateTime($data['add_show_start_date']." ".$data['add_show_start_time'], new DateTimeZone(date_default_timezone_get()));
$start_dt->setTimezone(new DateTimeZone('UTC')); $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 = 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')); $end_dt->setTimezone(new DateTimeZone('UTC'));
$ccShowInstance = CcShowInstancesQuery::create()->findPK($data["add_show_instance_id"]); $ccShowInstance = CcShowInstancesQuery::create()->findPK($data["add_show_instance_id"]);
$ccShowInstance->setDbStarts($start_dt); $ccShowInstance->setDbStarts($start_dt);
$ccShowInstance->setDbEnds($end_dt); $ccShowInstance->setDbEnds($end_dt);
$ccShowInstance->save(); $ccShowInstance->save();
Application_Model_Schedule::createNewFormSections($controller->view); Application_Model_Schedule::createNewFormSections($controller->view);
return true; return true;
} else { } else {
$formWhat->disable(); $formWhat->disable();
@ -727,36 +727,36 @@ class Application_Model_Schedule {
$formWho->disable(); $formWho->disable();
$formStyle->disable(); $formStyle->disable();
//$formLive->disable(); //$formLive->disable();
$controller->view->what = $formWhat; $controller->view->what = $formWhat;
$controller->view->when = $formWhen; $controller->view->when = $formWhen;
$controller->view->repeats = $formRepeats; $controller->view->repeats = $formRepeats;
$controller->view->who = $formWho; $controller->view->who = $formWho;
$controller->view->style = $formStyle; $controller->view->style = $formStyle;
$controller->view->live = $formLive; $controller->view->live = $formLive;
if(!$isSaas){ if(!$isSaas){
$controller->view->rr = $formRecord; $controller->view->rr = $formRecord;
$controller->view->absoluteRebroadcast = $formAbsoluteRebroadcast; $controller->view->absoluteRebroadcast = $formAbsoluteRebroadcast;
$controller->view->rebroadcast = $formRebroadcast; $controller->view->rebroadcast = $formRebroadcast;
//$formRecord->disable(); //$formRecord->disable();
//$formAbsoluteRebroadcast->disable(); //$formAbsoluteRebroadcast->disable();
//$formRebroadcast->disable(); //$formRebroadcast->disable();
} }
return false; 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). * 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 * 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 * this method to manipulate the view (this should be done inside the controller function). With
* 2.1 deadline looming, this is OK for now. * 2.1 deadline looming, this is OK for now.
* Another clean-up is to move all the form manipulation to the proper form class..... * 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){ public static function addUpdateShow($data, $controller, $validateStartDate, $originalStartDate=null, $update=false, $instanceId=null){
$userInfo = Zend_Auth::getInstance()->getStorage()->read(); $userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id); $user = new Application_Model_User($userInfo->id);
$isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
@ -765,22 +765,22 @@ class Application_Model_Schedule {
$record = false; $record = false;
$formWhat = new Application_Form_AddShowWhat(); $formWhat = new Application_Form_AddShowWhat();
$formWho = new Application_Form_AddShowWho(); $formWho = new Application_Form_AddShowWho();
$formWhen = new Application_Form_AddShowWhen(); $formWhen = new Application_Form_AddShowWhen();
$formRepeats = new Application_Form_AddShowRepeats(); $formRepeats = new Application_Form_AddShowRepeats();
$formStyle = new Application_Form_AddShowStyle(); $formStyle = new Application_Form_AddShowStyle();
$formLive = new Application_Form_AddShowLiveStream(); $formLive = new Application_Form_AddShowLiveStream();
$formWhat->removeDecorator('DtDdWrapper'); $formWhat->removeDecorator('DtDdWrapper');
$formWho->removeDecorator('DtDdWrapper'); $formWho->removeDecorator('DtDdWrapper');
$formWhen->removeDecorator('DtDdWrapper'); $formWhen->removeDecorator('DtDdWrapper');
$formRepeats->removeDecorator('DtDdWrapper'); $formRepeats->removeDecorator('DtDdWrapper');
$formStyle->removeDecorator('DtDdWrapper'); $formStyle->removeDecorator('DtDdWrapper');
$formLive->removeDecorator('DtDdWrapper'); $formLive->removeDecorator('DtDdWrapper');
$what = $formWhat->isValid($data); $what = $formWhat->isValid($data);
$when = $formWhen->isValid($data); $when = $formWhen->isValid($data);
$live = $formLive->isValid($data); $live = $formLive->isValid($data);
if($when) { if($when) {
$when = $formWhen->checkReliantFields($data, $validateStartDate, $originalStartDate, $update, $instanceId); $when = $formWhen->checkReliantFields($data, $validateStartDate, $originalStartDate, $update, $instanceId);
} }
@ -798,11 +798,11 @@ class Application_Model_Schedule {
$mValue = 0; $mValue = 0;
if($hPos !== false){ if($hPos !== false){
$hValue = trim(substr($data["add_show_duration"], 0, $hPos)); $hValue = trim(substr($data["add_show_duration"], 0, $hPos));
} }
if($mPos !== false){ if($mPos !== false){
$hPos = $hPos === FALSE ? 0 : $hPos+1; $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; $data["add_show_duration"] = $hValue.":".$mValue;
@ -821,7 +821,7 @@ class Application_Model_Schedule {
} }
if($data["add_show_repeats"]) { if($data["add_show_repeats"]) {
$repeats = $formRepeats->isValid($data); $repeats = $formRepeats->isValid($data);
if($repeats) { if($repeats) {
$repeats = $formRepeats->checkReliantFields($data); $repeats = $formRepeats->checkReliantFields($data);
} }
@ -857,8 +857,8 @@ class Application_Model_Schedule {
} }
} }
$who = $formWho->isValid($data); $who = $formWho->isValid($data);
$style = $formStyle->isValid($data); $style = $formStyle->isValid($data);
if ($what && $when && $repeats && $who && $style && $live) { if ($what && $when && $repeats && $who && $style && $live) {
if(!$isSaas){ if(!$isSaas){
if($record && $rebroadAb && $rebroad){ if($record && $rebroadAb && $rebroad){
@ -882,7 +882,7 @@ class Application_Model_Schedule {
$controller->view->rebroadcast = $formRebroadcast; $controller->view->rebroadcast = $formRebroadcast;
$controller->view->live = $formLive; $controller->view->live = $formLive;
//$controller->view->addNewShow = !$editShow; //$controller->view->addNewShow = !$editShow;
//$controller->view->form = $controller->view->render('schedule/add-show-form.phtml'); //$controller->view->form = $controller->view->render('schedule/add-show-form.phtml');
return false; return false;
@ -898,14 +898,14 @@ class Application_Model_Schedule {
//$controller->view->newForm = $controller->view->render('schedule/add-show-form.phtml'); //$controller->view->newForm = $controller->view->render('schedule/add-show-form.phtml');
return true; return true;
} }
} else { } else {
$controller->view->what = $formWhat; $controller->view->what = $formWhat;
$controller->view->when = $formWhen; $controller->view->when = $formWhen;
$controller->view->repeats = $formRepeats; $controller->view->repeats = $formRepeats;
$controller->view->who = $formWho; $controller->view->who = $formWho;
$controller->view->style = $formStyle; $controller->view->style = $formStyle;
$controller->view->live = $formLive; $controller->view->live = $formLive;
if(!$isSaas){ if(!$isSaas){
$controller->view->rr = $formRecord; $controller->view->rr = $formRecord;
$controller->view->absoluteRebroadcast = $formAbsoluteRebroadcast; $controller->view->absoluteRebroadcast = $formAbsoluteRebroadcast;
@ -916,14 +916,14 @@ class Application_Model_Schedule {
return false; 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; global $CC_CONFIG;
$overlapping = false; $overlapping = false;
$con = Propel::getConnection(); $con = Propel::getConnection();
if ($update) { if ($update) {
$sql = "SELECT id, starts, ends FROM ".$CC_CONFIG["showInstances"]." $sql = "SELECT id, starts, ends FROM ".$CC_CONFIG["showInstances"]."
where ends <= '{$show_end->format('Y-m-d H:i:s')}' 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"; where ends <= '{$show_end->format('Y-m-d H:i:s')}' order by ends";
} }
$rows = $con->query($sql); $rows = $con->query($sql);
foreach($rows as $row) { foreach($rows as $row) {
$start = new DateTime($row["starts"], new DateTimeZone('UTC')); $start = new DateTime($row["starts"], new DateTimeZone('UTC'));
$end = new DateTime($row["ends"], 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()) { $show_end->getTimestamp() > $start->getTimestamp()) {
$overlapping = true; $overlapping = true;
break; break;

View File

@ -12,46 +12,46 @@ class Application_Model_Scheduler {
"fadeout" => "00:00:00", "fadeout" => "00:00:00",
"sched_id" => null, "sched_id" => null,
); );
private $epochNow; private $epochNow;
private $nowDT; private $nowDT;
private $user; private $user;
private $checkUserPermissions = true; private $checkUserPermissions = true;
public function __construct() { public function __construct() {
$this->con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); $this->con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME);
$this->epochNow = microtime(true); $this->epochNow = microtime(true);
$this->nowDT = DateTime::createFromFormat("U.u", $this->epochNow, new DateTimeZone("UTC")); $this->nowDT = DateTime::createFromFormat("U.u", $this->epochNow, new DateTimeZone("UTC"));
if ($this->nowDT === false){ if ($this->nowDT === false){
// DateTime::createFromFormat does not support millisecond string formatting in PHP 5.3.2 (Ubuntu 10.04). // 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. // In PHP 5.3.3 (Ubuntu 10.10), this has been fixed.
$this->nowDT = DateTime::createFromFormat("U", time(), new DateTimeZone("UTC")); $this->nowDT = DateTime::createFromFormat("U", time(), new DateTimeZone("UTC"));
} }
$this->user = Application_Model_User::GetCurrentUser(); $this->user = Application_Model_User::getCurrentUser();
} }
public function setCheckUserPermissions($value) { public function setCheckUserPermissions($value) {
$this->checkUserPermissions = $value; $this->checkUserPermissions = $value;
} }
/* /*
* make sure any incoming requests for scheduling are ligit. * make sure any incoming requests for scheduling are ligit.
* *
* @param array $items, an array containing pks of cc_schedule items. * @param array $items, an array containing pks of cc_schedule items.
*/ */
private function validateRequest($items) { private function validateRequest($items) {
$nowEpoch = floatval($this->nowDT->format("U.u")); $nowEpoch = floatval($this->nowDT->format("U.u"));
for ($i = 0; $i < count($items); $i++) { for ($i = 0; $i < count($items); $i++) {
$id = $items[$i]["id"]; $id = $items[$i]["id"];
//could be added to the beginning of a show, which sends id = 0; //could be added to the beginning of a show, which sends id = 0;
if ($id > 0) { if ($id > 0) {
$schedInfo[$id] = $items[$i]["instance"]; $schedInfo[$id] = $items[$i]["instance"];
@ -59,11 +59,11 @@ class Application_Model_Scheduler {
$instanceInfo[$items[$i]["instance"]] = $items[$i]["timestamp"]; $instanceInfo[$items[$i]["instance"]] = $items[$i]["timestamp"];
} }
if (count($instanceInfo) === 0) { if (count($instanceInfo) === 0) {
throw new Exception("Invalid Request."); throw new Exception("Invalid Request.");
} }
$schedIds = array(); $schedIds = array();
if (isset($schedInfo)) { if (isset($schedInfo)) {
$schedIds = array_keys($schedInfo); $schedIds = array_keys($schedInfo);
@ -71,41 +71,41 @@ class Application_Model_Scheduler {
$schedItems = CcScheduleQuery::create()->findPKs($schedIds, $this->con); $schedItems = CcScheduleQuery::create()->findPKs($schedIds, $this->con);
$instanceIds = array_keys($instanceInfo); $instanceIds = array_keys($instanceInfo);
$showInstances = CcShowInstancesQuery::create()->findPKs($instanceIds, $this->con); $showInstances = CcShowInstancesQuery::create()->findPKs($instanceIds, $this->con);
//an item has been deleted //an item has been deleted
if (count($schedIds) !== count($schedItems)) { if (count($schedIds) !== count($schedItems)) {
throw new OutDatedScheduleException("The schedule you're viewing is out of date! (sched mismatch)"); throw new OutDatedScheduleException("The schedule you're viewing is out of date! (sched mismatch)");
} }
//a show has been deleted //a show has been deleted
if (count($instanceIds) !== count($showInstances)) { if (count($instanceIds) !== count($showInstances)) {
throw new OutDatedScheduleException("The schedule you're viewing is out of date! (instance mismatch)"); throw new OutDatedScheduleException("The schedule you're viewing is out of date! (instance mismatch)");
} }
foreach ($schedItems as $schedItem) { foreach ($schedItems as $schedItem) {
$id = $schedItem->getDbId(); $id = $schedItem->getDbId();
$instance = $schedItem->getCcShowInstances($this->con); $instance = $schedItem->getCcShowInstances($this->con);
if (intval($schedInfo[$id]) !== $instance->getDbId()) { if (intval($schedInfo[$id]) !== $instance->getDbId()) {
throw new OutDatedScheduleException("The schedule you're viewing is out of date!"); throw new OutDatedScheduleException("The schedule you're viewing is out of date!");
} }
} }
foreach ($showInstances as $instance) { foreach ($showInstances as $instance) {
$id = $instance->getDbId(); $id = $instance->getDbId();
$show = $instance->getCcShow($this->con); $show = $instance->getCcShow($this->con);
if ($this->checkUserPermissions && $this->user->canSchedule($show->getDbId()) === false) { if ($this->checkUserPermissions && $this->user->canSchedule($show->getDbId()) === false) {
throw new Exception("You are not allowed to schedule show {$show->getDbName()}."); throw new Exception("You are not allowed to schedule show {$show->getDbName()}.");
} }
$showEndEpoch = floatval($instance->getDbEnds("U.u")); $showEndEpoch = floatval($instance->getDbEnds("U.u"));
if ($showEndEpoch < $nowEpoch) { if ($showEndEpoch < $nowEpoch) {
throw new OutDatedScheduleException("The show {$show->getDbName()} is over and cannot be scheduled."); throw new OutDatedScheduleException("The show {$show->getDbName()} is over and cannot be scheduled.");
} }
$ts = intval($instanceInfo[$id]); $ts = intval($instanceInfo[$id]);
$lastSchedTs = intval($instance->getDbLastScheduled("U")) ? : 0; $lastSchedTs = intval($instance->getDbLastScheduled("U")) ? : 0;
if ($ts < $lastSchedTs) { if ($ts < $lastSchedTs) {
@ -196,17 +196,17 @@ class Application_Model_Scheduler {
$endEpoch = bcadd($startEpoch , (string) $durationSeconds, 6); $endEpoch = bcadd($startEpoch , (string) $durationSeconds, 6);
$dt = DateTime::createFromFormat("U.u", $endEpoch, new DateTimeZone("UTC")); $dt = DateTime::createFromFormat("U.u", $endEpoch, new DateTimeZone("UTC"));
if ($dt === false) { if ($dt === false) {
//PHP 5.3.2 problem //PHP 5.3.2 problem
$dt = DateTime::createFromFormat("U", intval($endEpoch), new DateTimeZone("UTC")); $dt = DateTime::createFromFormat("U", intval($endEpoch), new DateTimeZone("UTC"));
} }
return $dt; return $dt;
} }
private function findNextStartTime($DT, $instance) { private function findNextStartTime($DT, $instance) {
$sEpoch = $DT->format("U.u"); $sEpoch = $DT->format("U.u");
$nEpoch = $this->epochNow; $nEpoch = $this->epochNow;
@ -215,7 +215,7 @@ class Application_Model_Scheduler {
//need some kind of placeholder for cc_schedule. //need some kind of placeholder for cc_schedule.
//playout_status will be -1. //playout_status will be -1.
$nextDT = $this->nowDT; $nextDT = $this->nowDT;
$length = bcsub($nEpoch , $sEpoch , 6); $length = bcsub($nEpoch , $sEpoch , 6);
$cliplength = Application_Model_Playlist::secondsToPlaylistTime($length); $cliplength = Application_Model_Playlist::secondsToPlaylistTime($length);
@ -231,10 +231,10 @@ class Application_Model_Scheduler {
else { else {
$nextDT = $DT; $nextDT = $DT;
} }
return $nextDT; return $nextDT;
} }
/* /*
* @param int $showInstance * @param int $showInstance
* @param array $exclude * @param array $exclude
@ -267,7 +267,7 @@ class Application_Model_Scheduler {
$itemStartDT = $itemEndDT; $itemStartDT = $itemEndDT;
} }
$schedule->save($this->con); $schedule->save($this->con);
} }
@ -291,20 +291,20 @@ class Application_Model_Scheduler {
} }
$startProfile = microtime(true); $startProfile = microtime(true);
foreach ($scheduleItems as $schedule) { foreach ($scheduleItems as $schedule) {
$id = intval($schedule["id"]); $id = intval($schedule["id"]);
if ($id !== 0) { if ($id !== 0) {
$schedItem = CcScheduleQuery::create()->findPK($id, $this->con); $schedItem = CcScheduleQuery::create()->findPK($id, $this->con);
$instance = $schedItem->getCcShowInstances($this->con); $instance = $schedItem->getCcShowInstances($this->con);
$schedItemEndDT = $schedItem->getDbEnds(null); $schedItemEndDT = $schedItem->getDbEnds(null);
$nextStartDT = $this->findNextStartTime($schedItemEndDT, $instance); $nextStartDT = $this->findNextStartTime($schedItemEndDT, $instance);
} }
//selected empty row to add after //selected empty row to add after
else { else {
$instance = CcShowInstancesQuery::create()->findPK($schedule["instance"], $this->con); $instance = CcShowInstancesQuery::create()->findPK($schedule["instance"], $this->con);
$showStartDT = $instance->getDbStarts(null); $showStartDT = $instance->getDbStarts(null);
@ -316,16 +316,16 @@ class Application_Model_Scheduler {
} }
if ($adjustSched === true) { if ($adjustSched === true) {
$pstart = microtime(true); $pstart = microtime(true);
$followingSchedItems = CcScheduleQuery::create() $followingSchedItems = CcScheduleQuery::create()
->filterByDBStarts($nextStartDT->format("Y-m-d H:i:s.u"), Criteria::GREATER_EQUAL) ->filterByDBStarts($nextStartDT->format("Y-m-d H:i:s.u"), Criteria::GREATER_EQUAL)
->filterByDbInstanceId($instance->getDbId()) ->filterByDbInstanceId($instance->getDbId())
->filterByDbId($excludeIds, Criteria::NOT_IN) ->filterByDbId($excludeIds, Criteria::NOT_IN)
->orderByDbStarts() ->orderByDbStarts()
->find($this->con); ->find($this->con);
$pend = microtime(true); $pend = microtime(true);
Logging::debug("finding all following items."); Logging::debug("finding all following items.");
Logging::debug(floatval($pend) - floatval($pstart)); Logging::debug(floatval($pend) - floatval($pstart));
@ -359,26 +359,26 @@ class Application_Model_Scheduler {
} }
if ($adjustSched === true) { if ($adjustSched === true) {
$pstart = microtime(true); $pstart = microtime(true);
//recalculate the start/end times after the inserted items. //recalculate the start/end times after the inserted items.
foreach ($followingSchedItems as $item) { foreach ($followingSchedItems as $item) {
$endTimeDT = $this->findEndTime($nextStartDT, $item->getDbClipLength()); $endTimeDT = $this->findEndTime($nextStartDT, $item->getDbClipLength());
$item->setDbStarts($nextStartDT); $item->setDbStarts($nextStartDT);
$item->setDbEnds($endTimeDT); $item->setDbEnds($endTimeDT);
$item->save($this->con); $item->save($this->con);
$nextStartDT = $endTimeDT; $nextStartDT = $endTimeDT;
} }
$pend = microtime(true); $pend = microtime(true);
Logging::debug("adjusting all following items."); Logging::debug("adjusting all following items.");
Logging::debug(floatval($pend) - floatval($pstart)); Logging::debug(floatval($pend) - floatval($pstart));
} }
} }
$endProfile = microtime(true); $endProfile = microtime(true);
Logging::debug("finished adding scheduled items."); Logging::debug("finished adding scheduled items.");
Logging::debug(floatval($endProfile) - floatval($startProfile)); Logging::debug(floatval($endProfile) - floatval($startProfile));
@ -389,22 +389,22 @@ class Application_Model_Scheduler {
->find($this->con); ->find($this->con);
$startProfile = microtime(true); $startProfile = microtime(true);
foreach ($instances as $instance) { foreach ($instances as $instance) {
$instance->updateScheduleStatus($this->con); $instance->updateScheduleStatus($this->con);
} }
$endProfile = microtime(true); $endProfile = microtime(true);
Logging::debug("updating show instances status."); Logging::debug("updating show instances status.");
Logging::debug(floatval($endProfile) - floatval($startProfile)); Logging::debug(floatval($endProfile) - floatval($startProfile));
$startProfile = microtime(true); $startProfile = microtime(true);
//update the last scheduled timestamp. //update the last scheduled timestamp.
CcShowInstancesQuery::create() CcShowInstancesQuery::create()
->filterByPrimaryKeys($affectedShowInstances) ->filterByPrimaryKeys($affectedShowInstances)
->update(array('DbLastScheduled' => new DateTime("now", new DateTimeZone("UTC"))), $this->con); ->update(array('DbLastScheduled' => new DateTime("now", new DateTimeZone("UTC"))), $this->con);
$endProfile = microtime(true); $endProfile = microtime(true);
Logging::debug("updating last scheduled timestamp."); Logging::debug("updating last scheduled timestamp.");
Logging::debug(floatval($endProfile) - floatval($startProfile)); Logging::debug(floatval($endProfile) - floatval($startProfile));
@ -426,7 +426,7 @@ class Application_Model_Scheduler {
$schedFiles = array(); $schedFiles = array();
try { try {
$this->validateRequest($scheduleItems); $this->validateRequest($scheduleItems);
foreach ($mediaItems as $media) { foreach ($mediaItems as $media) {
@ -451,31 +451,31 @@ class Application_Model_Scheduler {
public function moveItem($selectedItems, $afterItems, $adjustSched = true) { public function moveItem($selectedItems, $afterItems, $adjustSched = true) {
$startProfile = microtime(true); $startProfile = microtime(true);
$this->con->beginTransaction(); $this->con->beginTransaction();
$this->con->useDebug(true); $this->con->useDebug(true);
try { try {
$this->validateRequest($selectedItems); $this->validateRequest($selectedItems);
$this->validateRequest($afterItems); $this->validateRequest($afterItems);
$endProfile = microtime(true); $endProfile = microtime(true);
Logging::debug("validating move request took:"); Logging::debug("validating move request took:");
Logging::debug(floatval($endProfile) - floatval($startProfile)); Logging::debug(floatval($endProfile) - floatval($startProfile));
$afterInstance = CcShowInstancesQuery::create()->findPK($afterItems[0]["instance"], $this->con); $afterInstance = CcShowInstancesQuery::create()->findPK($afterItems[0]["instance"], $this->con);
//map show instances to cc_schedule primary keys. //map show instances to cc_schedule primary keys.
$modifiedMap = array(); $modifiedMap = array();
$movedData = array(); $movedData = array();
//prepare each of the selected items. //prepare each of the selected items.
for ($i = 0; $i < count($selectedItems); $i++) { for ($i = 0; $i < count($selectedItems); $i++) {
$selected = CcScheduleQuery::create()->findPk($selectedItems[$i]["id"], $this->con); $selected = CcScheduleQuery::create()->findPk($selectedItems[$i]["id"], $this->con);
$selectedInstance = $selected->getCcShowInstances($this->con); $selectedInstance = $selected->getCcShowInstances($this->con);
$data = $this->fileInfo; $data = $this->fileInfo;
$data["id"] = $selected->getDbFileId(); $data["id"] = $selected->getDbFileId();
$data["cliplength"] = $selected->getDbClipLength(); $data["cliplength"] = $selected->getDbClipLength();
@ -484,48 +484,48 @@ class Application_Model_Scheduler {
$data["fadein"] = $selected->getDbFadeIn(); $data["fadein"] = $selected->getDbFadeIn();
$data["fadeout"] = $selected->getDbFadeOut(); $data["fadeout"] = $selected->getDbFadeOut();
$data["sched_id"] = $selected->getDbId(); $data["sched_id"] = $selected->getDbId();
$movedData[] = $data; $movedData[] = $data;
//figure out which items must be removed from calculated show times. //figure out which items must be removed from calculated show times.
$showInstanceId = $selectedInstance->getDbId(); $showInstanceId = $selectedInstance->getDbId();
$schedId = $selected->getDbId(); $schedId = $selected->getDbId();
if (isset($modifiedMap[$showInstanceId])) { if (isset($modifiedMap[$showInstanceId])) {
array_push($modifiedMap[$showInstanceId], $schedId); array_push($modifiedMap[$showInstanceId], $schedId);
} }
else { else {
$modifiedMap[$showInstanceId] = array($schedId); $modifiedMap[$showInstanceId] = array($schedId);
} }
} }
//calculate times excluding the to be moved items. //calculate times excluding the to be moved items.
foreach ($modifiedMap as $instance => $schedIds) { foreach ($modifiedMap as $instance => $schedIds) {
$startProfile = microtime(true); $startProfile = microtime(true);
$this->removeGaps($instance, $schedIds); $this->removeGaps($instance, $schedIds);
$endProfile = microtime(true); $endProfile = microtime(true);
Logging::debug("removing gaps from instance $instance:"); Logging::debug("removing gaps from instance $instance:");
Logging::debug(floatval($endProfile) - floatval($startProfile)); Logging::debug(floatval($endProfile) - floatval($startProfile));
} }
$startProfile = microtime(true); $startProfile = microtime(true);
$this->insertAfter($afterItems, $movedData, $adjustSched); $this->insertAfter($afterItems, $movedData, $adjustSched);
$endProfile = microtime(true); $endProfile = microtime(true);
Logging::debug("inserting after removing gaps."); Logging::debug("inserting after removing gaps.");
Logging::debug(floatval($endProfile) - floatval($startProfile)); Logging::debug(floatval($endProfile) - floatval($startProfile));
$afterInstanceId = $afterInstance->getDbId(); $afterInstanceId = $afterInstance->getDbId();
$modified = array_keys($modifiedMap); $modified = array_keys($modifiedMap);
//need to adjust shows we have moved items from. //need to adjust shows we have moved items from.
foreach($modified as $instanceId) { foreach($modified as $instanceId) {
$instance = CcShowInstancesQuery::create()->findPK($instanceId, $this->con); $instance = CcShowInstancesQuery::create()->findPK($instanceId, $this->con);
$instance->updateScheduleStatus($this->con); $instance->updateScheduleStatus($this->con);
} }
$this->con->useDebug(false); $this->con->useDebug(false);
$this->con->commit(); $this->con->commit();
@ -543,9 +543,9 @@ class Application_Model_Scheduler {
$this->con->beginTransaction(); $this->con->beginTransaction();
try { try {
$this->validateRequest($scheduledItems); $this->validateRequest($scheduledItems);
$scheduledIds = array(); $scheduledIds = array();
foreach ($scheduledItems as $item) { foreach ($scheduledItems as $item) {
$scheduledIds[] = $item["id"]; $scheduledIds[] = $item["id"];
@ -555,25 +555,25 @@ class Application_Model_Scheduler {
//check to make sure all items selected are up to date //check to make sure all items selected are up to date
foreach ($removedItems as $removedItem) { foreach ($removedItems as $removedItem) {
$instance = $removedItem->getCcShowInstances($this->con); $instance = $removedItem->getCcShowInstances($this->con);
//check to truncate the currently playing item instead of deleting it. //check to truncate the currently playing item instead of deleting it.
if ($removedItem->isCurrentItem($this->epochNow)) { if ($removedItem->isCurrentItem($this->epochNow)) {
$nEpoch = $this->epochNow; $nEpoch = $this->epochNow;
$sEpoch = $removedItem->getDbStarts('U.u'); $sEpoch = $removedItem->getDbStarts('U.u');
$length = bcsub($nEpoch , $sEpoch , 6); $length = bcsub($nEpoch , $sEpoch , 6);
$cliplength = Application_Model_Playlist::secondsToPlaylistTime($length); $cliplength = Application_Model_Playlist::secondsToPlaylistTime($length);
$cueinSec = Application_Model_Playlist::playlistTimeToSeconds($removedItem->getDbCueIn()); $cueinSec = Application_Model_Playlist::playlistTimeToSeconds($removedItem->getDbCueIn());
$cueOutSec = bcadd($cueinSec , $length, 6); $cueOutSec = bcadd($cueinSec , $length, 6);
$cueout = Application_Model_Playlist::secondsToPlaylistTime($cueOutSec); $cueout = Application_Model_Playlist::secondsToPlaylistTime($cueOutSec);
$removedItem->setDbCueOut($cueout) $removedItem->setDbCueOut($cueout)
->setDbClipLength($cliplength) ->setDbClipLength($cliplength)
->setDbEnds($this->nowDT) ->setDbEnds($this->nowDT)
->save($this->con); ->save($this->con);
} }
else { else {
@ -619,27 +619,27 @@ class Application_Model_Scheduler {
throw $e; throw $e;
} }
} }
/* /*
* Used for cancelling the current show instance. * Used for cancelling the current show instance.
* *
* @param $p_id id of the show instance to cancel. * @param $p_id id of the show instance to cancel.
*/ */
public function cancelShow($p_id) { public function cancelShow($p_id) {
$this->con->beginTransaction(); $this->con->beginTransaction();
try { try {
$instance = CcShowInstancesQuery::create()->findPK($p_id); $instance = CcShowInstancesQuery::create()->findPK($p_id);
if (!$instance->getDbRecord()) { if (!$instance->getDbRecord()) {
$items = CcScheduleQuery::create() $items = CcScheduleQuery::create()
->filterByDbInstanceId($p_id) ->filterByDbInstanceId($p_id)
->filterByDbEnds($this->nowDT, Criteria::GREATER_THAN) ->filterByDbEnds($this->nowDT, Criteria::GREATER_THAN)
->find($this->con); ->find($this->con);
if (count($items) > 0) { if (count($items) > 0) {
$remove = array(); $remove = array();
$ts = $this->nowDT->format('U'); $ts = $this->nowDT->format('U');
@ -657,12 +657,12 @@ class Application_Model_Scheduler {
$rebroadcasts = $instance->getCcShowInstancessRelatedByDbId(null, $this->con); $rebroadcasts = $instance->getCcShowInstancessRelatedByDbId(null, $this->con);
$rebroadcasts->delete($this->con); $rebroadcasts->delete($this->con);
} }
$instance->setDbEnds($this->nowDT); $instance->setDbEnds($this->nowDT);
$instance->save($this->con); $instance->save($this->con);
$this->con->commit(); $this->con->commit();
if ($instance->getDbRecord()) { if ($instance->getDbRecord()) {
Application_Model_RabbitMq::SendMessageToShowRecorder("cancel_recording"); Application_Model_RabbitMq::SendMessageToShowRecorder("cancel_recording");
} }
@ -670,7 +670,7 @@ class Application_Model_Scheduler {
catch (Exception $e) { catch (Exception $e) {
$this->con->rollback(); $this->con->rollback();
throw $e; throw $e;
} }
} }
} }

View File

@ -17,7 +17,7 @@ class Application_Model_ServiceRegister {
if ($p_ipAddress == "::1"){ if ($p_ipAddress == "::1"){
$p_ipAddress = "127.0.0.1"; $p_ipAddress = "127.0.0.1";
} }
$component->setDbIp($p_ipAddress); $component->setDbIp($p_ipAddress);
$component->save(); $component->save();
} }

View File

@ -21,25 +21,25 @@ class Application_Model_Show {
$show->setDbName($name); $show->setDbName($name);
Application_Model_RabbitMq::PushSchedule(); Application_Model_RabbitMq::PushSchedule();
} }
public function setAirtimeAuthFlag($flag){ public function setAirtimeAuthFlag($flag){
$show = CcShowQuery::create()->findPK($this->_showId); $show = CcShowQuery::create()->findPK($this->_showId);
$show->setDbLiveStreamUsingAirtimeAuth($flag); $show->setDbLiveStreamUsingAirtimeAuth($flag);
$show->save(); $show->save();
} }
public function setCustomAuthFlag($flag){ public function setCustomAuthFlag($flag){
$show = CcShowQuery::create()->findPK($this->_showId); $show = CcShowQuery::create()->findPK($this->_showId);
$show->setDbLiveStreamUsingCustomAuth($flag); $show->setDbLiveStreamUsingCustomAuth($flag);
$show->save(); $show->save();
} }
public function setCustomUsername($username){ public function setCustomUsername($username){
$show = CcShowQuery::create()->findPK($this->_showId); $show = CcShowQuery::create()->findPK($this->_showId);
$show->setDbLiveStreamUser($username); $show->setDbLiveStreamUser($username);
$show->save(); $show->save();
} }
public function setCustomPassword($password){ public function setCustomPassword($password){
$show = CcShowQuery::create()->findPK($this->_showId); $show = CcShowQuery::create()->findPK($this->_showId);
$show->setDbLiveStreamPass($password); $show->setDbLiveStreamPass($password);
@ -303,8 +303,6 @@ class Application_Model_Show {
." AND starts > TIMESTAMP '$timestamp'" ." AND starts > TIMESTAMP '$timestamp'"
." AND show_id = $showId"; ." AND show_id = $showId";
//Logging::log($sql);
$con->exec($sql); $con->exec($sql);
} }
@ -557,7 +555,7 @@ class Application_Model_Show {
$con->exec($sql); $con->exec($sql);
} }
/** /**
* Get the start date of the current show in UTC timezone. * 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 * The start date in the format YYYY-MM-DD
*/ */
public function getStartDate(){ public function getStartDate(){
list($date,) = explode(" ", $this->getStartDateAndTime()); list($date,) = explode(" ", $this->getStartDateAndTime());
return $date; return $date;
} }
/** /**
@ -606,8 +604,8 @@ class Application_Model_Show {
*/ */
public function getStartTime(){ public function getStartTime(){
list(,$time) = explode(" ", $this->getStartDateAndTime()); list(,$time) = explode(" ", $this->getStartDateAndTime());
return $time; return $time;
} }
/** /**
@ -1251,8 +1249,8 @@ class Application_Model_Show {
$rebroadcasts = $con->query($sql)->fetchAll(); $rebroadcasts = $con->query($sql)->fetchAll();
if ($showInstance->isRecorded()){ if ($showInstance->isRecorded()){
$showInstance->deleteRebroadcasts(); $showInstance->deleteRebroadcasts();
self::createRebroadcastInstances($rebroadcasts, $currentUtcTimestamp, $show_id, $show_instance_id, $start, $duration, $timezone); self::createRebroadcastInstances($rebroadcasts, $currentUtcTimestamp, $show_id, $show_instance_id, $start, $duration, $timezone);
} }
} }
} }
@ -1307,13 +1305,13 @@ class Application_Model_Show {
if ($show->hasInstanceOnDate($utcStartDateTime)){ if ($show->hasInstanceOnDate($utcStartDateTime)){
$ccShowInstance = $show->getInstanceOnDate($utcStartDateTime); $ccShowInstance = $show->getInstanceOnDate($utcStartDateTime);
if ($ccShowInstance->getDbModifiedInstance()){ if ($ccShowInstance->getDbModifiedInstance()){
//show instance on this date has been deleted. //show instance on this date has been deleted.
list($start, $utcStartDateTime) = self::advanceRepeatingDate($p_interval, $start, $timezone); list($start, $utcStartDateTime) = self::advanceRepeatingDate($p_interval, $start, $timezone);
continue; continue;
} }
$newInstance = false; $newInstance = false;
} else { } else {
$ccShowInstance = new CcShowInstances(); $ccShowInstance = new CcShowInstances();
@ -1349,7 +1347,7 @@ class Application_Model_Show {
Application_Model_Show::setNextPop($start, $show_id, $day); Application_Model_Show::setNextPop($start, $show_id, $day);
} }
private static function advanceRepeatingDate($p_interval, $start, $timezone){ private static function advanceRepeatingDate($p_interval, $start, $timezone){
$startDt = new DateTime($start, new DateTimeZone($timezone)); $startDt = new DateTime($start, new DateTimeZone($timezone));
if ($p_interval == 'P1M'){ if ($p_interval == 'P1M'){
@ -1369,19 +1367,19 @@ class Application_Model_Show {
do { do {
$dt->add(new DateInterval($p_interval)); $dt->add(new DateInterval($p_interval));
} while(!checkdate($dt->format("m"), $startDt->format("d"), $dt->format("Y"))); } while(!checkdate($dt->format("m"), $startDt->format("d"), $dt->format("Y")));
$dt->setDate($dt->format("Y"), $dt->format("m"), $startDt->format("d")); $dt->setDate($dt->format("Y"), $dt->format("m"), $startDt->format("d"));
} else { } else {
$dt = new DateTime($start, new DateTimeZone($timezone)); $dt = new DateTime($start, new DateTimeZone($timezone));
$dt->add(new DateInterval($p_interval)); $dt->add(new DateInterval($p_interval));
} }
$start = $dt->format("Y-m-d H:i:s"); $start = $dt->format("Y-m-d H:i:s");
$dt->setTimezone(new DateTimeZone('UTC')); $dt->setTimezone(new DateTimeZone('UTC'));
$utcStartDateTime = $dt; $utcStartDateTime = $dt;
return array($start, $utcStartDateTime); return array($start, $utcStartDateTime);
} }
@ -1585,7 +1583,7 @@ class Application_Model_Show {
$days = $interval->format('%a'); $days = $interval->format('%a');
$shows = Application_Model_Show::getShows($p_start, $p_end); $shows = Application_Model_Show::getShows($p_start, $p_end);
$nowEpoch = time(); $nowEpoch = time();
foreach ($shows as $show) { foreach ($shows as $show) {
$options = array(); $options = array();
@ -1594,14 +1592,14 @@ class Application_Model_Show {
if (intval($days) <= 7) { if (intval($days) <= 7) {
$options["percent"] = Application_Model_Show::getPercentScheduled($show["starts"], $show["ends"], $show["time_filled"]); $options["percent"] = Application_Model_Show::getPercentScheduled($show["starts"], $show["ends"], $show["time_filled"]);
} }
if (isset($show["parent_starts"])) { if (isset($show["parent_starts"])) {
$parentStartsDT = new DateTime($show["parent_starts"], new DateTimeZone("UTC")); $parentStartsDT = new DateTime($show["parent_starts"], new DateTimeZone("UTC"));
$parentStartsEpoch = intval($parentStartsDT->format("U")); $parentStartsEpoch = intval($parentStartsDT->format("U"));
} }
$startsDT = new DateTime($show["starts"], new DateTimeZone("UTC")); $startsDT = new DateTime($show["starts"], new DateTimeZone("UTC"));
$endsDT = new DateTime($show["ends"], new DateTimeZone("UTC")); $endsDT = new DateTime($show["ends"], new DateTimeZone("UTC"));
$startsEpoch = intval($startsDT->format("U")); $startsEpoch = intval($startsDT->format("U"));
$endsEpoch = intval($endsDT->format("U")); $endsEpoch = intval($endsDT->format("U"));
@ -1689,7 +1687,7 @@ class Application_Model_Show {
$showDay = CcShowDaysQuery::create() $showDay = CcShowDaysQuery::create()
->filterByDbShowId($this->_showId) ->filterByDbShowId($this->_showId)
->findOne(); ->findOne();
$showDay->setDbFirstShow($dt)->setDbStartTime($dt) $showDay->setDbFirstShow($dt)->setDbStartTime($dt)
->save(); ->save();
@ -1730,7 +1728,7 @@ class Application_Model_Show {
$con = Propel::getConnection(); $con = Propel::getConnection();
if($timeNow == null){ if($timeNow == null){
$date = new Application_Common_DateHelper; $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 //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," $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 si.ends < TIMESTAMP '$p_timeNow' + INTERVAL '2 days'"
." AND modified_instance != TRUE" ." AND modified_instance != TRUE"
." ORDER BY si.starts"; ." ORDER BY si.starts";
$rows = $con->query($sql)->fetchAll(PDO::FETCH_ASSOC); $rows = $con->query($sql)->fetchAll(PDO::FETCH_ASSOC);
$numberOfRows = count($rows); $numberOfRows = count($rows);
@ -1775,7 +1773,7 @@ class Application_Model_Show {
for ($i = 0; $i < $numberOfRows; ++$i) { for ($i = 0; $i < $numberOfRows; ++$i) {
//Find the show that is within the current time. //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)) { && (strtotime($rows[$i]['ends']) > $timeNowAsMillis)) {
if ($i-1 >= 0) { if ($i-1 >= 0) {
$results['previousShow'][0] = array( $results['previousShow'][0] = array(
@ -1842,7 +1840,7 @@ class Application_Model_Show {
"record"=>$rows[$previousShowIndex]['record'], "record"=>$rows[$previousShowIndex]['record'],
"type"=>"show"); "type"=>"show");
} }
return $results; return $results;
} }

View File

@ -14,14 +14,14 @@ class Application_Model_ShowBuilder {
private $user; private $user;
private $opts; private $opts;
private $pos; private $pos;
private $contentDT; private $contentDT;
private $epoch_now; private $epoch_now;
private $currentShow; private $currentShow;
private $showInstances = array(); private $showInstances = array();
private $defaultRowArray = array( private $defaultRowArray = array(
"header" => false, "header" => false,
"footer" => false, "footer" => false,
@ -54,16 +54,16 @@ class Application_Model_ShowBuilder {
$this->startDT = $p_startDT; $this->startDT = $p_startDT;
$this->endDT = $p_endDT; $this->endDT = $p_endDT;
$this->timezone = date_default_timezone_get(); $this->timezone = date_default_timezone_get();
$this->user = Application_Model_User::GetCurrentUser(); $this->user = Application_Model_User::getCurrentUser();
$this->opts = $p_opts; $this->opts = $p_opts;
$this->epoch_now = floatval(microtime(true)); $this->epoch_now = floatval(microtime(true));
$this->currentShow = false; $this->currentShow = false;
} }
private function getUsersShows() { private function getUsersShows() {
$shows = array(); $shows = array();
$host_shows = CcShowHostsQuery::create() $host_shows = CcShowHostsQuery::create()
->setFormatter(ModelCriteria::FORMAT_ON_DEMAND) ->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)
->filterByDbHost($this->user->getId()) ->filterByDbHost($this->user->getId())
@ -72,7 +72,7 @@ class Application_Model_ShowBuilder {
foreach ($host_shows as $host_show) { foreach ($host_shows as $host_show) {
$shows[] = $host_show->getDbShow(); $shows[] = $host_show->getDbShow();
} }
return $shows; return $shows;
} }
@ -84,15 +84,15 @@ class Application_Model_ShowBuilder {
return; return;
} }
if ($this->user->canSchedule($p_item["show_id"]) == true) { if ($this->user->canSchedule($p_item["show_id"]) == true) {
$row["allowed"] = true; $row["allowed"] = true;
} }
} }
private function getItemColor($p_item, &$row) { private function getItemColor($p_item, &$row) {
$defaultColor = "ffffff"; $defaultColor = "ffffff";
$defaultBackground = "3366cc"; $defaultBackground = "3366cc";
$color = $p_item["show_color"]; $color = $p_item["show_color"];
if ($color === '') { if ($color === '') {
$color = $defaultColor; $color = $defaultColor;
@ -101,7 +101,7 @@ class Application_Model_ShowBuilder {
if ($backgroundColor === '') { if ($backgroundColor === '') {
$backgroundColor = $defaultBackground; $backgroundColor = $defaultBackground;
} }
$row["color"] = $color; $row["color"] = $color;
$row["backgroundColor"] = $backgroundColor; $row["backgroundColor"] = $backgroundColor;
} }
@ -123,7 +123,7 @@ class Application_Model_ShowBuilder {
} }
$row["timestamp"] = $ts; $row["timestamp"] = $ts;
} }
/* /*
* marks a row's status. * marks a row's status.
* 0 = past * 0 = past
@ -131,7 +131,7 @@ class Application_Model_ShowBuilder {
* 2 = future * 2 = future
*/ */
private function getScheduledStatus($p_epochItemStart, $p_epochItemEnd, &$row) { private function getScheduledStatus($p_epochItemStart, $p_epochItemEnd, &$row) {
if ($row["footer"] === true && $this->epoch_now > $p_epochItemStart && $this->epoch_now > $p_epochItemEnd) { if ($row["footer"] === true && $this->epoch_now > $p_epochItemStart && $this->epoch_now > $p_epochItemEnd) {
$row["scheduled"] = 0; $row["scheduled"] = 0;
} }
@ -144,7 +144,7 @@ class Application_Model_ShowBuilder {
else if ($row["header"] === true && $this->epoch_now < $p_epochItemEnd) { else if ($row["header"] === true && $this->epoch_now < $p_epochItemEnd) {
$row["scheduled"] = 2; $row["scheduled"] = 2;
} }
//item is in the past. //item is in the past.
else if ($this->epoch_now > $p_epochItemEnd) { else if ($this->epoch_now > $p_epochItemEnd) {
$row["scheduled"] = 0; $row["scheduled"] = 0;
@ -156,7 +156,7 @@ class Application_Model_ShowBuilder {
//how many seconds the view should wait to redraw itself. //how many seconds the view should wait to redraw itself.
$row["refresh"] = $p_epochItemEnd - $this->epoch_now; $row["refresh"] = $p_epochItemEnd - $this->epoch_now;
} }
//item is in the future. //item is in the future.
else if ($this->epoch_now < $p_epochItemStart) { else if ($this->epoch_now < $p_epochItemStart) {
$row["scheduled"] = 2; $row["scheduled"] = 2;
@ -176,31 +176,31 @@ class Application_Model_ShowBuilder {
$showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC")); $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC"));
$showEndDT->setTimezone(new DateTimeZone($this->timezone)); $showEndDT->setTimezone(new DateTimeZone($this->timezone));
$endsEpoch = floatval($showEndDT->format("U.u")); $endsEpoch = floatval($showEndDT->format("U.u"));
//is a rebroadcast show //is a rebroadcast show
if (intval($p_item["si_rebroadcast"]) === 1) { if (intval($p_item["si_rebroadcast"]) === 1) {
$row["rebroadcast"] = true; $row["rebroadcast"] = true;
$parentInstance = CcShowInstancesQuery::create()->findPk($p_item["parent_show"]); $parentInstance = CcShowInstancesQuery::create()->findPk($p_item["parent_show"]);
$name = $parentInstance->getCcShow()->getDbName(); $name = $parentInstance->getCcShow()->getDbName();
$dt = $parentInstance->getDbStarts(null); $dt = $parentInstance->getDbStarts(null);
$dt->setTimezone(new DateTimeZone($this->timezone)); $dt->setTimezone(new DateTimeZone($this->timezone));
$time = $dt->format("Y-m-d H:i"); $time = $dt->format("Y-m-d H:i");
$row["rebroadcast_title"] = "Rebroadcast of {$name} from {$time}"; $row["rebroadcast_title"] = "Rebroadcast of {$name} from {$time}";
} }
else if (intval($p_item["si_record"]) === 1) { else if (intval($p_item["si_record"]) === 1) {
$row["record"] = true; $row["record"] = true;
if (Application_Model_Preference::GetUploadToSoundcloudOption()) { if (Application_Model_Preference::GetUploadToSoundcloudOption()) {
$file = Application_Model_StoredFile::Recall($p_item["si_file_id"]); $file = Application_Model_StoredFile::Recall($p_item["si_file_id"]);
if (isset($file)) { if (isset($file)) {
$sid = $file->getSoundCloudId(); $sid = $file->getSoundCloudId();
$row["soundcloud_id"] = $sid; $row["soundcloud_id"] = $sid;
} }
} }
} }
if ($startsEpoch < $this->epoch_now && $endsEpoch > $this->epoch_now) { if ($startsEpoch < $this->epoch_now && $endsEpoch > $this->epoch_now) {
$row["currentShow"] = true; $row["currentShow"] = true;
$this->currentShow = true; $this->currentShow = true;
@ -221,7 +221,7 @@ class Application_Model_ShowBuilder {
$row["title"] = $p_item["show_name"]; $row["title"] = $p_item["show_name"];
$row["instance"] = intval($p_item["si_id"]); $row["instance"] = intval($p_item["si_id"]);
$row["image"] = ''; $row["image"] = '';
$this->getScheduledStatus($startsEpoch, $endsEpoch, $row); $this->getScheduledStatus($startsEpoch, $endsEpoch, $row);
$this->contentDT = $showStartDT; $this->contentDT = $showStartDT;
@ -254,7 +254,7 @@ class Application_Model_ShowBuilder {
$row["instance"] = intval($p_item["si_id"]); $row["instance"] = intval($p_item["si_id"]);
$row["starts"] = $schedStartDT->format("H:i:s"); $row["starts"] = $schedStartDT->format("H:i:s");
$row["ends"] = $schedEndDT->format("H:i:s"); $row["ends"] = $schedEndDT->format("H:i:s");
$formatter = new LengthFormatter($p_item['file_length']); $formatter = new LengthFormatter($p_item['file_length']);
$row['runtime'] = $formatter->format(); $row['runtime'] = $formatter->format();
@ -266,7 +266,7 @@ class Application_Model_ShowBuilder {
$row["cueout"] = $p_item["cue_out"]; $row["cueout"] = $p_item["cue_out"];
$row["fadein"] = round(substr($p_item["fade_in"], 6), 6); $row["fadein"] = round(substr($p_item["fade_in"], 6), 6);
$row["fadeout"] = round(substr($p_item["fade_out"], 6), 6); $row["fadeout"] = round(substr($p_item["fade_out"], 6), 6);
$row["pos"] = $this->pos++; $row["pos"] = $this->pos++;
$this->contentDT = $schedEndDT; $this->contentDT = $schedEndDT;
@ -275,10 +275,10 @@ class Application_Model_ShowBuilder {
else if (intval($p_item["si_record"]) === 1) { else if (intval($p_item["si_record"]) === 1) {
$row["record"] = true; $row["record"] = true;
$row["instance"] = intval($p_item["si_id"]); $row["instance"] = intval($p_item["si_id"]);
$showStartDT = new DateTime($p_item["si_starts"], new DateTimeZone("UTC")); $showStartDT = new DateTime($p_item["si_starts"], new DateTimeZone("UTC"));
$showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC")); $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC"));
$startsEpoch = floatval($showStartDT->format("U.u")); $startsEpoch = floatval($showStartDT->format("U.u"));
$endsEpoch = floatval($showEndDT->format("U.u")); $endsEpoch = floatval($showEndDT->format("U.u"));
@ -289,7 +289,7 @@ class Application_Model_ShowBuilder {
$row["id"] = 0 ; $row["id"] = 0 ;
$row["instance"] = intval($p_item["si_id"]); $row["instance"] = intval($p_item["si_id"]);
} }
if (intval($p_item["si_rebroadcast"]) === 1) { if (intval($p_item["si_rebroadcast"]) === 1) {
$row["rebroadcast"] = true; $row["rebroadcast"] = true;
} }
@ -320,23 +320,23 @@ class Application_Model_ShowBuilder {
$timeFilled = new TimeFilledFormatter($runtime); $timeFilled = new TimeFilledFormatter($runtime);
$row["fRuntime"] = $timeFilled->format(); $row["fRuntime"] = $timeFilled->format();
$showStartDT = new DateTime($p_item["si_starts"], new DateTimeZone("UTC")); $showStartDT = new DateTime($p_item["si_starts"], new DateTimeZone("UTC"));
$showStartDT->setTimezone(new DateTimeZone($this->timezone)); $showStartDT->setTimezone(new DateTimeZone($this->timezone));
$startsEpoch = floatval($showStartDT->format("U.u")); $startsEpoch = floatval($showStartDT->format("U.u"));
$showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC")); $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC"));
$showEndDT->setTimezone(new DateTimeZone($this->timezone)); $showEndDT->setTimezone(new DateTimeZone($this->timezone));
$endsEpoch = floatval($showEndDT->format("U.u")); $endsEpoch = floatval($showEndDT->format("U.u"));
$row["refresh"] = floatval($showEndDT->format("U.u")) - $this->epoch_now; $row["refresh"] = floatval($showEndDT->format("U.u")) - $this->epoch_now;
if ($this->currentShow === true) { if ($this->currentShow === true) {
$row["currentShow"] = true; $row["currentShow"] = true;
} }
$this->getScheduledStatus($startsEpoch, $endsEpoch, $row); $this->getScheduledStatus($startsEpoch, $endsEpoch, $row);
$this->isAllowed($p_item, $row); $this->isAllowed($p_item, $row);
return $row; return $row;
} }
@ -349,7 +349,7 @@ class Application_Model_ShowBuilder {
public function hasBeenUpdatedSince($timestamp, $instances) { public function hasBeenUpdatedSince($timestamp, $instances) {
$outdated = false; $outdated = false;
$shows = Application_Model_Show::getShows($this->startDT, $this->endDT); $shows = Application_Model_Show::getShows($this->startDT, $this->endDT);
if ($this->opts["showFilter"] !== 0) { if ($this->opts["showFilter"] !== 0) {
$include[] = $this->opts["showFilter"]; $include[] = $this->opts["showFilter"];
} }
@ -357,22 +357,22 @@ class Application_Model_ShowBuilder {
$include = $this->getUsersShows(); $include = $this->getUsersShows();
} }
$currentInstances = array(); $currentInstances = array();
foreach ($shows as $show) { foreach ($shows as $show) {
if (empty($include) || in_array($show["show_id"], $include)) { if (empty($include) || in_array($show["show_id"], $include)) {
$currentInstances[] = $show["instance_id"]; $currentInstances[] = $show["instance_id"];
if (isset($show["last_scheduled"])) { if (isset($show["last_scheduled"])) {
$dt = new DateTime($show["last_scheduled"], new DateTimeZone("UTC")); $dt = new DateTime($show["last_scheduled"], new DateTimeZone("UTC"));
} }
else { else {
$dt = new DateTime($show["created"], new DateTimeZone("UTC")); $dt = new DateTime($show["created"], new DateTimeZone("UTC"));
} }
//check if any of the shows have a more recent timestamp. //check if any of the shows have a more recent timestamp.
$showTimeStamp = intval($dt->format("U")); $showTimeStamp = intval($dt->format("U"));
if ($timestamp < $showTimeStamp) { if ($timestamp < $showTimeStamp) {
@ -411,7 +411,7 @@ class Application_Model_ShowBuilder {
for ($i = 0, $rows = count($scheduled_items); $i < $rows; $i++) { for ($i = 0, $rows = count($scheduled_items); $i < $rows; $i++) {
$item = $scheduled_items[$i]; $item = $scheduled_items[$i];
//don't send back data for filler rows. //don't send back data for filler rows.
if (isset($item["playout_status"]) && $item["playout_status"] < 0) { if (isset($item["playout_status"]) && $item["playout_status"] < 0) {
continue; continue;
@ -425,11 +425,11 @@ class Application_Model_ShowBuilder {
//pass in the previous row as it's the last row for the previous show. //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->makeFooterRow($scheduled_items[$i-1]);
} }
$display_items[] = $this->makeHeaderRow($item); $display_items[] = $this->makeHeaderRow($item);
$current_id = $item["si_id"]; $current_id = $item["si_id"];
$this->pos = 1; $this->pos = 1;
} }
@ -449,7 +449,7 @@ class Application_Model_ShowBuilder {
if (count($scheduled_items) > 0) { if (count($scheduled_items) > 0) {
$display_items[] = $this->makeFooterRow($scheduled_items[count($scheduled_items)-1]); $display_items[] = $this->makeFooterRow($scheduled_items[count($scheduled_items)-1]);
} }
return array("schedule" => $display_items, "showInstances" => $this->showInstances); return array("schedule" => $display_items, "showInstances" => $this->showInstances);
} }
} }

View File

@ -30,7 +30,7 @@ class Application_Model_ShowInstance {
public function getShow(){ public function getShow(){
return new Application_Model_Show($this->getShowId()); return new Application_Model_Show($this->getShowId());
} }
public function deleteRebroadcasts(){ public function deleteRebroadcasts(){
$con = Propel::getConnection(); $con = Propel::getConnection();
@ -42,7 +42,7 @@ class Application_Model_ShowInstance {
." AND instance_id = $instance_id" ." AND instance_id = $instance_id"
." AND rebroadcast = 1"; ." AND rebroadcast = 1";
$con->exec($sql); $con->exec($sql);
} }
/* This function is weird. It should return a boolean, but instead returns /* 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()) { if ($today_timestamp > $newStartsDateTime->getTimestamp()) {
return "Can't move show into past"; return "Can't move show into past";
} }
//check if show is overlapping //check if show is overlapping
$overlapping = Application_Model_Schedule::checkOverlappingShows($newStartsDateTime, $newEndsDateTime, true, $this->getShowInstanceId()); $overlapping = Application_Model_Schedule::checkOverlappingShows($newStartsDateTime, $newEndsDateTime, true, $this->getShowInstanceId());
if ($overlapping) { if ($overlapping) {
return "Cannot schedule overlapping shows"; return "Cannot schedule overlapping shows";
} }
if ($this->isRecorded()) { if ($this->isRecorded()) {
@ -579,7 +579,7 @@ class Application_Model_ShowInstance {
public function getTimeScheduled() public function getTimeScheduled()
{ {
$time = $this->_showInstance->getDbTimeFilled(); $time = $this->_showInstance->getDbTimeFilled();
if ($time != "00:00:00" && !empty($time)) { if ($time != "00:00:00" && !empty($time)) {
$time_arr = explode(".", $time); $time_arr = explode(".", $time);
if (count($time_arr) > 1) { if (count($time_arr) > 1) {
@ -593,7 +593,7 @@ class Application_Model_ShowInstance {
} else { } else {
$time = "00:00:00.00"; $time = "00:00:00.00";
} }
return $time; return $time;
} }
@ -637,7 +637,7 @@ class Application_Model_ShowInstance {
} else { } else {
$returnStr = $hours . ":" . $interval->format("%I:%S") . ".00"; $returnStr = $hours . ":" . $interval->format("%I:%S") . ".00";
} }
return $returnStr; return $returnStr;
} }
@ -670,30 +670,30 @@ class Application_Model_ShowInstance {
public function getLastAudioItemEnd() public function getLastAudioItemEnd()
{ {
$con = Propel::getConnection(); $con = Propel::getConnection();
$sql = "SELECT ends FROM cc_schedule " $sql = "SELECT ends FROM cc_schedule "
."WHERE instance_id = {$this->_instanceId} " ."WHERE instance_id = {$this->_instanceId} "
."ORDER BY ends DESC " ."ORDER BY ends DESC "
."LIMIT 1"; ."LIMIT 1";
$query = $con->query($sql)->fetchColumn(0); $query = $con->query($sql)->fetchColumn(0);
return ($query !== false) ? $query : NULL; return ($query !== false) ? $query : NULL;
} }
public function getShowEndGapTime(){ public function getShowEndGapTime(){
$showEnd = $this->getShowInstanceEnd(); $showEnd = $this->getShowInstanceEnd();
$lastItemEnd = $this->getLastAudioItemEnd(); $lastItemEnd = $this->getLastAudioItemEnd();
if (is_null($lastItemEnd)){ if (is_null($lastItemEnd)){
$lastItemEnd = $this->getShowInstanceStart(); $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){ public static function GetLastShowInstance($p_timeNow){
global $CC_CONFIG; global $CC_CONFIG;
@ -777,14 +777,14 @@ class Application_Model_ShowInstance {
$con = Propel::getConnection(); $con = Propel::getConnection();
$sql = "SELECT ends $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 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) 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"; ORDER BY si.ends";
return $con->query($sql)->fetchAll(); return $con->query($sql)->fetchAll();
} }
function isRepeating(){ function isRepeating(){
if ($this->getShow()->isRepeating()){ if ($this->getShow()->isRepeating()){
return true; return true;

View File

@ -5,7 +5,7 @@ class Application_Model_Soundcloud {
private $_soundcloud; private $_soundcloud;
public function __construct() public function __construct()
{ {
global $CC_CONFIG; global $CC_CONFIG;
@ -35,7 +35,7 @@ class Application_Model_Soundcloud {
} }
$downloadable = Application_Model_Preference::GetSoundCloudDownloadbleOption() == '1'?true:false; $downloadable = Application_Model_Preference::GetSoundCloudDownloadbleOption() == '1'?true:false;
$track_data = array( $track_data = array(
'track[sharing]' => 'private', 'track[sharing]' => 'private',
'track[title]' => $filename, 'track[title]' => $filename,
@ -77,7 +77,7 @@ class Application_Model_Soundcloud {
if ($license != "") { if ($license != "") {
$track_data['track[license]'] = $license; $track_data['track[license]'] = $license;
} }
$response = json_decode( $response = json_decode(
$this->_soundcloud->post('tracks', $track_data), $this->_soundcloud->post('tracks', $track_data),
true true

View File

@ -91,7 +91,7 @@ class Application_Model_StoredFile {
} }
else { else {
$dbMd = array(); $dbMd = array();
if (isset($p_md["MDATA_KEY_YEAR"])){ if (isset($p_md["MDATA_KEY_YEAR"])){
// We need to make sure to clean this value before inserting into database. // 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 // 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 // new garbage value won't cause errors). If the value is 2012-01-01, then substring to
// first 4 digits is an OK result. // first 4 digits is an OK result.
// CC-3771 // CC-3771
$year = $p_md["MDATA_KEY_YEAR"]; $year = $p_md["MDATA_KEY_YEAR"];
if (strlen($year) > 4){ if (strlen($year) > 4){
$year = substr($year, 0, 4); $year = substr($year, 0, 4);
} }
@ -111,7 +111,7 @@ class Application_Model_StoredFile {
} }
$p_md["MDATA_KEY_YEAR"] = $year; $p_md["MDATA_KEY_YEAR"] = $year;
} }
foreach ($p_md as $mdConst => $mdValue) { foreach ($p_md as $mdConst => $mdValue) {
if (defined($mdConst)){ if (defined($mdConst)){
$dbMd[constant($mdConst)] = $mdValue; $dbMd[constant($mdConst)] = $mdValue;
@ -161,9 +161,9 @@ class Application_Model_StoredFile {
* Set metadata element value * Set metadata element value
* *
* @param string $category * @param string $category
* Metadata element by metadata constant * Metadata element by metadata constant
* @param string $value * @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) public function setMetadataValue($p_category, $p_value)
{ {
@ -176,9 +176,9 @@ class Application_Model_StoredFile {
* Set metadata element value * Set metadata element value
* *
* @param string $category * @param string $category
* Metadata element by db column * Metadata element by db column
* @param string $value * @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) public function setDbColMetadataValue($p_category, $p_value)
{ {
@ -245,12 +245,12 @@ class Application_Model_StoredFile {
{ {
$c = get_defined_constants(true); $c = get_defined_constants(true);
$md = array(); $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 * 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 * 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) * into base and relative path)
* */ * */
$dbmd_copy = $this->_dbMD; $dbmd_copy = $this->_dbMD;
@ -273,9 +273,9 @@ class Application_Model_StoredFile {
* Set state of virtual file * Set state of virtual file
* *
* @param string $p_state * @param string $p_state
* 'empty'|'incomplete'|'ready'|'edited' * 'empty'|'incomplete'|'ready'|'edited'
* @param int $p_editedby * @param int $p_editedby
* user id | 'NULL' for clear editedBy field * user id | 'NULL' for clear editedBy field
* @return TRUE * @return TRUE
*/ */
public function setState($p_state, $p_editedby=NULL) 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()); $music_dir = Application_Model_MusicDir::getDirByPK($this->_file->getDbDirectory());
$type = $music_dir->getType(); $type = $music_dir->getType();
if (file_exists($filepath) && $type == "stor") { if (file_exists($filepath) && $type == "stor") {
$data = array("filepath" => $filepath, "delete" => 1); $data = array("filepath" => $filepath, "delete" => 1);
Application_Model_RabbitMq::SendMessageToMediaMonitor("file_delete", $data); Application_Model_RabbitMq::SendMessageToMediaMonitor("file_delete", $data);
@ -343,7 +343,7 @@ class Application_Model_StoredFile {
$this->_file->setDbFileExists(false); $this->_file->setDbFileExists(false);
$this->_file->save(); $this->_file->save();
} }
/** /**
* This function is for when media monitor detects deletion of file * This function is for when media monitor detects deletion of file
* and trying to update airtime side * and trying to update airtime side
@ -367,7 +367,7 @@ class Application_Model_StoredFile {
* Return suitable extension. * Return suitable extension.
* *
* @return string * @return string
* file extension without a dot * file extension without a dot
*/ */
public function getFileExtension() public function getFileExtension()
{ {
@ -395,7 +395,7 @@ class Application_Model_StoredFile {
return $directory.$filepath; return $directory.$filepath;
} }
/** /**
* Set real filename of raw media data * Set real filename of raw media data
* *
@ -500,9 +500,9 @@ Logging::log("getting media! - 2");
* be NULL. * be NULL.
* *
* @param int $p_id * @param int $p_id
* local id * local id
* @param string $p_gunid * @param string $p_gunid
* global unique id of file * global unique id of file
* @param string $p_md5sum * @param string $p_md5sum
* MD5 sum of the file * MD5 sum of the file
* @param boolean $exist * @param boolean $exist
@ -570,7 +570,7 @@ Logging::log("getting media! - 2");
* by gunid. * by gunid.
* *
* @param string $p_gunid * @param string $p_gunid
* global unique id of file * global unique id of file
* @return Application_Model_StoredFile|NULL * @return Application_Model_StoredFile|NULL
*/ */
public static function RecallByGunid($p_gunid) public static function RecallByGunid($p_gunid)
@ -624,7 +624,7 @@ Logging::log("getting media! - 2");
public static function searchLibraryFiles($datatables) { 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", $displayColumns = array("id", "track_title", "artist_name", "album_title", "genre", "length",
"year", "utime", "mtime", "ftype", "track_number", "mood", "bpm", "composer", "info_url", "year", "utime", "mtime", "ftype", "track_number", "mood", "bpm", "composer", "info_url",
@ -871,26 +871,26 @@ Logging::log("getting media! - 2");
return $result; return $result;
} }
} }
if (chmod($audio_file, 0644) === false){ if (chmod($audio_file, 0644) === false){
Logging::log("Warning: couldn't change permissions of $audio_file to 0644"); Logging::log("Warning: couldn't change permissions of $audio_file to 0644");
} }
//check to see if there is enough space in $stor to continue. //check to see if there is enough space in $stor to continue.
if (self::isEnoughDiskSpaceToCopy($stor, $audio_file)){ if (self::isEnoughDiskSpaceToCopy($stor, $audio_file)){
$audio_stor = Application_Common_OsPath::join($stor, "organize", $fileName); $audio_stor = Application_Common_OsPath::join($stor, "organize", $fileName);
if (self::liquidsoapFilePlayabilityTest($audio_file)){ if (self::liquidsoapFilePlayabilityTest($audio_file)){
Logging::log("copyFileToStor: moving file $audio_file to $audio_stor"); 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 //Martin K.: changed to rename: Much less load + quicker since this is an atomic operation
if (@rename($audio_file, $audio_stor) === false) { 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. #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. #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 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."); $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 { } else {
$result = array("code" => 110, "message" => "This file appears to be corrupted and will not be added to media library."); $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; return $result;
} }
/* /*
* Pass the file through Liquidsoap and test if it is readable. Return True if readable, and False otherwise. * Pass the file through Liquidsoap and test if it is readable. Return True if readable, and False otherwise.
*/ */
public static function liquidsoapFilePlayabilityTest($audio_file){ public static function liquidsoapFilePlayabilityTest($audio_file){
$LIQUIDSOAP_ERRORS = array('TagLib: MPEG::Properties::read() -- Could not find a valid last MPEG frame in the stream.'); $LIQUIDSOAP_ERRORS = array('TagLib: MPEG::Properties::read() -- Could not find a valid last MPEG frame in the stream.');
// Ask Liquidsoap if file is playable // Ask Liquidsoap if file is playable
$command = sprintf("/usr/bin/airtime-liquidsoap -c 'output.dummy(audio_to_stereo(single(\"%s\")))' 2>&1", $audio_file); $command = sprintf("/usr/bin/airtime-liquidsoap -c 'output.dummy(audio_to_stereo(single(\"%s\")))' 2>&1", $audio_file);
exec($command, $output, $rv); exec($command, $output, $rv);
$isError = count($output) > 0 && in_array($output[0], $LIQUIDSOAP_ERRORS); $isError = count($output) > 0 && in_array($output[0], $LIQUIDSOAP_ERRORS);
return ($rv == 0 && !$isError); return ($rv == 0 && !$isError);
} }
public static function getFileCount() public static function getFileCount()
{ {
global $CC_CONFIG; global $CC_CONFIG;
@ -960,28 +960,28 @@ Logging::log("getting media! - 2");
return $results; return $results;
} }
/* Gets number of tracks uploaded to /* Gets number of tracks uploaded to
* Soundcloud in the last 24 hours * Soundcloud in the last 24 hours
*/ */
public static function getSoundCloudUploads() public static function getSoundCloudUploads()
{ {
try { try {
$con = Propel::getConnection(); $con = Propel::getConnection();
$sql = "SELECT soundcloud_id as id, soundcloud_upload_time" $sql = "SELECT soundcloud_id as id, soundcloud_upload_time"
." FROM CC_FILES" ." FROM CC_FILES"
." WHERE (id != -2 and id != -3) and" ." WHERE (id != -2 and id != -3) and"
." (soundcloud_upload_time >= (now() - (INTERVAL '1 day')))"; ." (soundcloud_upload_time >= (now() - (INTERVAL '1 day')))";
$rows = $con->query($sql)->fetchAll(); $rows = $con->query($sql)->fetchAll();
return count($rows); return count($rows);
} catch (Exception $e) { } catch (Exception $e) {
header('HTTP/1.0 503 Service Unavailable'); header('HTTP/1.0 503 Service Unavailable');
Logging::log("Could not connect to database."); Logging::log("Could not connect to database.");
exit; exit;
} }
} }
public function setSoundCloudLinkToFile($link_to_file) public function setSoundCloudLinkToFile($link_to_file)
@ -1021,10 +1021,10 @@ Logging::log("getting media! - 2");
public function getSoundCloudErrorMsg(){ public function getSoundCloudErrorMsg(){
return $this->_file->getDbSoundCloudErrorMsg(); return $this->_file->getDbSoundCloudErrorMsg();
} }
public function getDirectory(){ public function getDirectory(){
return $this->_file->getDbDirectory(); return $this->_file->getDbDirectory();
} }
public function setFileExistsFlag($flag){ public function setFileExistsFlag($flag){
$this->_file->setDbFileExists($flag) $this->_file->setDbFileExists($flag)
@ -1032,7 +1032,7 @@ Logging::log("getting media! - 2");
} }
public function setSoundCloudUploadTime($time){ public function setSoundCloudUploadTime($time){
$this->_file->setDbSoundCloundUploadTime($time) $this->_file->setDbSoundCloundUploadTime($time)
->save(); ->save();
} }
public function getFileExistsFlag(){ public function getFileExistsFlag(){

View File

@ -130,23 +130,23 @@ class Application_Model_StreamSetting {
} }
if (!isset($exists["master_live_stream_port"])) { if (!isset($exists["master_live_stream_port"])) {
$rows[] = array("keyname" =>"master_live_stream_port", $rows[] = array("keyname" =>"master_live_stream_port",
"value"=>self::getMasterLiveStreamPort(), "value"=>self::getMasterLiveStreamPort(),
"type"=>"integer"); "type"=>"integer");
} }
if (!isset($exists["master_live_stream_mp"])) { if (!isset($exists["master_live_stream_mp"])) {
$rows[] = array("keyname" =>"master_live_stream_mp", $rows[] = array("keyname" =>"master_live_stream_mp",
"value"=>self::getMasterLiveStreamMountPoint(), "value"=>self::getMasterLiveStreamMountPoint(),
"type"=>"string"); "type"=>"string");
} }
if (!isset($exists["dj_live_stream_port"])) { if (!isset($exists["dj_live_stream_port"])) {
$rows[] = array("keyname" =>"dj_live_stream_port", $rows[] = array("keyname" =>"dj_live_stream_port",
"value"=>self::getDjLiveStreamPort(), "value"=>self::getDjLiveStreamPort(),
"type"=>"integer"); "type"=>"integer");
} }
if (!isset($exists["dj_live_stream_mp"])) { if (!isset($exists["dj_live_stream_mp"])) {
$rows[] = array("keyname" =>"dj_live_stream_mp", $rows[] = array("keyname" =>"dj_live_stream_mp",
"value"=>self::getDjLiveStreamMountPoint(), "value"=>self::getDjLiveStreamMountPoint(),
"type"=>"string"); "type"=>"string");
} }
return $rows; return $rows;
@ -180,7 +180,7 @@ class Application_Model_StreamSetting {
$v = $d['enable'] == 1 ? 'true' : 'false'; $v = $d['enable'] == 1 ? 'true' : 'false';
} }
$v = trim($v); $v = trim($v);
#escape double single quotes CC-3926 #escape double single quotes CC-3926
$v = str_replace("'", "''", $v); $v = str_replace("'", "''", $v);
$sql = "UPDATE cc_stream_setting SET value='$v' WHERE keyname='$keyname'"; $sql = "UPDATE cc_stream_setting SET value='$v' WHERE keyname='$keyname'";

View File

@ -9,15 +9,15 @@ class Application_Model_Systemstatus
$monit_password = $CC_CONFIG['monit_password']; $monit_password = $CC_CONFIG['monit_password'];
$url = "http://$p_ip:2812/_status?format=xml"; $url = "http://$p_ip:2812/_status?format=xml";
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "$monit_user:$monit_password"); curl_setopt($ch, CURLOPT_USERPWD, "$monit_user:$monit_password");
//wait a max of 3 seconds before aborting connection attempt //wait a max of 3 seconds before aborting connection attempt
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
$result = curl_exec($ch); $result = curl_exec($ch);
$info = curl_getinfo($ch); $info = curl_getinfo($ch);
curl_close($ch); curl_close($ch);
@ -32,7 +32,7 @@ class Application_Model_Systemstatus
return $docRoot; return $docRoot;
} }
public static function ExtractServiceInformation($p_docRoot, $p_serviceName){ public static function ExtractServiceInformation($p_docRoot, $p_serviceName){
$starting = array( $starting = array(
@ -43,7 +43,7 @@ class Application_Model_Systemstatus
"memory_perc"=>"0%", "memory_perc"=>"0%",
"memory_kb"=>"0", "memory_kb"=>"0",
"cpu_perc"=>"0%"); "cpu_perc"=>"0%");
$notMonitored = array( $notMonitored = array(
"name"=>$p_serviceName, "name"=>$p_serviceName,
"process_id"=>"NOT MONITORED", "process_id"=>"NOT MONITORED",
@ -53,7 +53,7 @@ class Application_Model_Systemstatus
"memory_kb"=>"0", "memory_kb"=>"0",
"cpu_perc"=>"0%" "cpu_perc"=>"0%"
); );
$notRunning = array( $notRunning = array(
"name"=>$p_serviceName, "name"=>$p_serviceName,
"process_id"=>"FAILED", "process_id"=>"FAILED",
@ -65,7 +65,7 @@ class Application_Model_Systemstatus
); );
$data = $notRunning; $data = $notRunning;
if (!is_null($p_docRoot)){ if (!is_null($p_docRoot)){
foreach ($p_docRoot->getElementsByTagName("service") AS $item) foreach ($p_docRoot->getElementsByTagName("service") AS $item)
{ {
@ -93,7 +93,7 @@ class Application_Model_Systemstatus
if ($process_id->length > 0){ if ($process_id->length > 0){
$data["name"] = $process_id->item(0)->nodeValue; $data["name"] = $process_id->item(0)->nodeValue;
} }
$process_id = $item->getElementsByTagName("pid"); $process_id = $item->getElementsByTagName("pid");
if ($process_id->length > 0){ if ($process_id->length > 0){
$data["process_id"] = $process_id->item(0)->nodeValue; $data["process_id"] = $process_id->item(0)->nodeValue;
@ -104,13 +104,13 @@ class Application_Model_Systemstatus
if ($uptime->length > 0){ if ($uptime->length > 0){
$data["uptime_seconds"] = $uptime->item(0)->nodeValue; $data["uptime_seconds"] = $uptime->item(0)->nodeValue;
} }
$memory = $item->getElementsByTagName("memory"); $memory = $item->getElementsByTagName("memory");
if ($memory->length > 0){ if ($memory->length > 0){
$data["memory_perc"] = $memory->item(0)->getElementsByTagName("percenttotal")->item(0)->nodeValue."%"; $data["memory_perc"] = $memory->item(0)->getElementsByTagName("percenttotal")->item(0)->nodeValue."%";
$data["memory_kb"] = $memory->item(0)->getElementsByTagName("kilobytetotal")->item(0)->nodeValue; $data["memory_kb"] = $memory->item(0)->getElementsByTagName("kilobytetotal")->item(0)->nodeValue;
} }
$cpu = $item->getElementsByTagName("cpu"); $cpu = $item->getElementsByTagName("cpu");
if ($cpu->length > 0){ if ($cpu->length > 0){
$data["cpu_perc"] = $cpu->item(0)->getElementsByTagName("percent")->item(0)->nodeValue."%"; $data["cpu_perc"] = $cpu->item(0)->getElementsByTagName("percent")->item(0)->nodeValue."%";
@ -127,7 +127,7 @@ class Application_Model_Systemstatus
foreach($keys as $key) { foreach($keys as $key) {
$data[$key] = "UNKNOWN"; $data[$key] = "UNKNOWN";
} }
$docRoot = self::GetMonitStatus("localhost"); $docRoot = self::GetMonitStatus("localhost");
if (!is_null($docRoot)){ if (!is_null($docRoot)){
foreach ($docRoot->getElementsByTagName("platform") AS $item) foreach ($docRoot->getElementsByTagName("platform") AS $item)
@ -140,7 +140,7 @@ class Application_Model_Systemstatus
} }
} }
} }
return $data; return $data;
} }
@ -151,14 +151,14 @@ class Application_Model_Systemstatus
return null; return null;
} else { } else {
$ip = $component->getDbIp(); $ip = $component->getDbIp();
$docRoot = self::GetMonitStatus($ip); $docRoot = self::GetMonitStatus($ip);
$data = self::ExtractServiceInformation($docRoot, "airtime-playout"); $data = self::ExtractServiceInformation($docRoot, "airtime-playout");
return $data; return $data;
} }
} }
public static function GetLiquidsoapStatus(){ public static function GetLiquidsoapStatus(){
$component = CcServiceRegisterQuery::create()->findOneByDbName("pypo"); $component = CcServiceRegisterQuery::create()->findOneByDbName("pypo");
@ -166,14 +166,14 @@ class Application_Model_Systemstatus
return null; return null;
} else { } else {
$ip = $component->getDbIp(); $ip = $component->getDbIp();
$docRoot = self::GetMonitStatus($ip); $docRoot = self::GetMonitStatus($ip);
$data = self::ExtractServiceInformation($docRoot, "airtime-liquidsoap"); $data = self::ExtractServiceInformation($docRoot, "airtime-liquidsoap");
return $data; return $data;
} }
} }
public static function GetMediaMonitorStatus(){ public static function GetMediaMonitorStatus(){
$component = CcServiceRegisterQuery::create()->findOneByDbName("media-monitor"); $component = CcServiceRegisterQuery::create()->findOneByDbName("media-monitor");
@ -181,15 +181,15 @@ class Application_Model_Systemstatus
return null; return null;
} else { } else {
$ip = $component->getDbIp(); $ip = $component->getDbIp();
$docRoot = self::GetMonitStatus($ip); $docRoot = self::GetMonitStatus($ip);
$data = self::ExtractServiceInformation($docRoot, "airtime-media-monitor"); $data = self::ExtractServiceInformation($docRoot, "airtime-media-monitor");
return $data; return $data;
} }
} }
public static function GetIcecastStatus(){ public static function GetIcecastStatus(){
$docRoot = self::GetMonitStatus("localhost"); $docRoot = self::GetMonitStatus("localhost");
$data = self::ExtractServiceInformation($docRoot, "icecast2"); $data = self::ExtractServiceInformation($docRoot, "icecast2");
@ -197,7 +197,7 @@ class Application_Model_Systemstatus
} }
public static function GetRabbitMqStatus(){ public static function GetRabbitMqStatus(){
if (isset($_SERVER["RABBITMQ_HOST"])){ if (isset($_SERVER["RABBITMQ_HOST"])){
$rabbitmq_host = $_SERVER["RABBITMQ_HOST"]; $rabbitmq_host = $_SERVER["RABBITMQ_HOST"];
} else { } else {
@ -208,18 +208,18 @@ class Application_Model_Systemstatus
return $data; return $data;
} }
public static function GetDiskInfo(){ public static function GetDiskInfo(){
$partions = array(); $partions = array();
if (isset($_SERVER['AIRTIME_SRV'])){ if (isset($_SERVER['AIRTIME_SRV'])){
//connect to DB and find how much total space user has allocated. //connect to DB and find how much total space user has allocated.
$totalSpace = Application_Model_Preference::GetDiskQuota(); $totalSpace = Application_Model_Preference::GetDiskQuota();
$storPath = Application_Model_MusicDir::getStorDir()->getDirectory(); $storPath = Application_Model_MusicDir::getStorDir()->getDirectory();
list($usedSpace,) = preg_split("/[\s]+/", exec("du -bs $storPath")); list($usedSpace,) = preg_split("/[\s]+/", exec("du -bs $storPath"));
$partitions[$totalSpace]->totalSpace = $totalSpace; $partitions[$totalSpace]->totalSpace = $totalSpace;
$partitions[$totalSpace]->totalFreeSpace = $totalSpace - $usedSpace; $partitions[$totalSpace]->totalFreeSpace = $totalSpace - $usedSpace;
Logging::log($partitions[$totalSpace]->totalFreeSpace); Logging::log($partitions[$totalSpace]->totalFreeSpace);
@ -228,7 +228,7 @@ class Application_Model_Systemstatus
* into the same partitions by comparing the partition sizes. */ * into the same partitions by comparing the partition sizes. */
$musicDirs = Application_Model_MusicDir::getWatchedDirs(); $musicDirs = Application_Model_MusicDir::getWatchedDirs();
$musicDirs[] = Application_Model_MusicDir::getStorDir(); $musicDirs[] = Application_Model_MusicDir::getStorDir();
foreach($musicDirs as $md){ foreach($musicDirs as $md){
$totalSpace = disk_total_space($md->getDirectory()); $totalSpace = disk_total_space($md->getDirectory());
@ -238,7 +238,7 @@ class Application_Model_Systemstatus
$partitions[$totalSpace]->totalFreeSpace = disk_free_space($md->getDirectory()); $partitions[$totalSpace]->totalFreeSpace = disk_free_space($md->getDirectory());
} }
$partitions[$totalSpace]->dirs[] = $md->getDirectory(); $partitions[$totalSpace]->dirs[] = $md->getDirectory();
} }
} }

View File

@ -11,191 +11,220 @@ class Application_Model_User {
public function __construct($userId) public function __construct($userId)
{ {
if (empty($userId)){ if (empty($userId)) {
$this->_userInstance = $this->createUser(); $this->_userInstance = $this->createUser();
} } else {
else {
$this->_userInstance = CcSubjsQuery::create()->findPK($userId); $this->_userInstance = CcSubjsQuery::create()->findPK($userId);
if (is_null($this->_userInstance)){ if (is_null($this->_userInstance)) {
throw new Exception(); throw new Exception();
} }
} }
} }
public function getId() { public function getId()
{
return $this->_userInstance->getDbId(); return $this->_userInstance->getDbId();
} }
public function isGuest() { public function isGuest()
{
return $this->getType() == UTYPE_GUEST; return $this->getType() == UTYPE_GUEST;
} }
public function isHost($showId) { public function isHost($showId)
return $this->isUserType(UTYPE_HOST, $showId); {
return $this->isUserType(UTYPE_HOST, $showId);
} }
public function isPM() { public function isPM()
{
return $this->isUserType(UTYPE_PROGRAM_MANAGER); return $this->isUserType(UTYPE_PROGRAM_MANAGER);
} }
public function isAdmin() { public function isAdmin()
{
return $this->isUserType(UTYPE_ADMIN); return $this->isUserType(UTYPE_ADMIN);
} }
public function canSchedule($p_showId) { public function canSchedule($p_showId)
$type = $this->getType(); {
$result = false; $type = $this->getType();
$result = false;
if ( $type === UTYPE_ADMIN || if ($type === UTYPE_ADMIN ||
$type === UTYPE_PROGRAM_MANAGER || $type === UTYPE_PROGRAM_MANAGER ||
CcShowHostsQuery::create()->filterByDbShow($p_showId)->filterByDbHost($this->getId())->count() > 0 ) CcShowHostsQuery::create()->filterByDbShow($p_showId)->filterByDbHost($this->getId())->count() > 0) {
{ $result = true;
$result = true; }
}
return $result; return $result;
} }
public function isUserType($type, $showId=''){ public function isUserType($type, $showId='')
if(is_array($type)){ {
$result = false; if (is_array($type)) {
foreach($type as $t){ $result = false;
switch($t){ foreach ($type as $t) {
case UTYPE_ADMIN: switch($t){
$result = $this->_userInstance->getDbType() === 'A'; case UTYPE_ADMIN:
break; $result = $this->_userInstance->getDbType() === 'A';
case UTYPE_HOST: break;
$userId = $this->_userInstance->getDbId(); case UTYPE_HOST:
$result = CcShowHostsQuery::create()->filterByDbShow($showId)->filterByDbHost($userId)->count() > 0; $userId = $this->_userInstance->getDbId();
break; $result = CcShowHostsQuery::create()
case UTYPE_PROGRAM_MANAGER: ->filterByDbShow($showId)
$result = $this->_userInstance->getDbType() === 'P'; ->filterByDbHost($userId)->count() > 0;
break; break;
} case UTYPE_PROGRAM_MANAGER:
if($result){ $result = $this->_userInstance->getDbType() === 'P';
return $result; break;
} }
} if ($result) {
}else{ return $result;
switch($type){ }
case UTYPE_ADMIN: }
return $this->_userInstance->getDbType() === 'A'; } else {
case UTYPE_HOST: switch($type) {
$userId = $this->_userInstance->getDbId(); case UTYPE_ADMIN:
return CcShowHostsQuery::create()->filterByDbShow($showId)->filterByDbHost($userId)->count() > 0; return $this->_userInstance->getDbType() === 'A';
case UTYPE_PROGRAM_MANAGER: case UTYPE_HOST:
return $this->_userInstance->getDbType() === 'P'; $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 = $this->_userInstance;
$user->setDbLogin($login); $user->setDbLogin($login);
} }
public function setPassword($password){ public function setPassword($password)
{
$user = $this->_userInstance; $user = $this->_userInstance;
$user->setDbPass(md5($password)); $user->setDbPass(md5($password));
} }
public function setFirstName($firstName){ public function setFirstName($firstName)
{
$user = $this->_userInstance; $user = $this->_userInstance;
$user->setDbFirstName($firstName); $user->setDbFirstName($firstName);
} }
public function setLastName($lastName){ public function setLastName($lastName)
{
$user = $this->_userInstance; $user = $this->_userInstance;
$user->setDbLastName($lastName); $user->setDbLastName($lastName);
} }
public function setType($type){ public function setType($type)
{
$user = $this->_userInstance; $user = $this->_userInstance;
$user->setDbType($type); $user->setDbType($type);
} }
public function setEmail($email){ public function setEmail($email)
{
$user = $this->_userInstance; $user = $this->_userInstance;
$user->setDbEmail(strtolower($email)); $user->setDbEmail(strtolower($email));
} }
public function setCellPhone($cellPhone){ public function setCellPhone($cellPhone)
{
$user = $this->_userInstance; $user = $this->_userInstance;
$user->setDbCellPhone($cellPhone); $user->setDbCellPhone($cellPhone);
} }
public function setSkype($skype){ public function setSkype($skype)
{
$user = $this->_userInstance; $user = $this->_userInstance;
$user->setDbSkypeContact($skype); $user->setDbSkypeContact($skype);
} }
public function setJabber($jabber){ public function setJabber($jabber)
{
$user = $this->_userInstance; $user = $this->_userInstance;
$user->setDbJabberContact($jabber); $user->setDbJabberContact($jabber);
} }
public function getLogin(){ public function getLogin()
{
$user = $this->_userInstance; $user = $this->_userInstance;
return $user->getDbLogin(); return $user->getDbLogin();
} }
public function getPassword(){ public function getPassword()
{
$user = $this->_userInstance; $user = $this->_userInstance;
return $user->getDbPass(); return $user->getDbPass();
} }
public function getFirstName(){ public function getFirstName()
{
$user = $this->_userInstance; $user = $this->_userInstance;
return $user->getDbFirstName(); return $user->getDbFirstName();
} }
public function getLastName(){ public function getLastName()
{
$user = $this->_userInstance; $user = $this->_userInstance;
return $user->getDbLastName(); return $user->getDbLastName();
} }
public function getType(){ public function getType()
{
$user = $this->_userInstance; $user = $this->_userInstance;
return $user->getDbType(); return $user->getDbType();
} }
public function getEmail(){ public function getEmail()
{
$user = $this->_userInstance; $user = $this->_userInstance;
return $user->getDbEmail(); return $user->getDbEmail();
} }
public function getCellPhone(){ public function getCellPhone()
{
$user = $this->_userInstance; $user = $this->_userInstance;
return $user->getDbCellPhone(); return $user->getDbCellPhone();
} }
public function getSkype(){ public function getSkype()
{
$user = $this->_userInstance; $user = $this->_userInstance;
return $user->getDbSkypeContact(); return $user->getDbSkypeContact();
} }
public function getJabber(){ public function getJabber()
{
$user = $this->_userInstance; $user = $this->_userInstance;
return $user->getDbJabberContact(); return $user->getDbJabberContact();
} }
public function save(){ public function save()
{
$this->_userInstance->save(); $this->_userInstance->save();
} }
public function delete(){ public function delete()
if (!$this->_userInstance->isDeleted()) {
if (!$this->_userInstance->isDeleted()) {
$this->_userInstance->delete(); $this->_userInstance->delete();
}
} }
private function createUser() { private function createUser()
{
$user = new CcSubjs(); $user = new CcSubjs();
return $user; return $user;
} }
public static function getUsers($type, $search=NULL) public static function getUsers($type, $search=null)
{ {
$con = Propel::getConnection(); $con = Propel::getConnection();
@ -203,12 +232,11 @@ class Application_Model_User {
$sql = $sql_gen; $sql = $sql_gen;
if (is_array($type)) { if (is_array($type)) {
for($i=0; $i<count($type); $i++) { for ($i=0; $i<count($type); $i++) {
$type[$i] = "type = '{$type[$i]}'"; $type[$i] = "type = '{$type[$i]}'";
} }
$sql_type = join(" OR ", $type); $sql_type = join(" OR ", $type);
} } else {
else {
$sql_type = "type = {$type}"; $sql_type = "type = {$type}";
} }
@ -225,39 +253,40 @@ class Application_Model_User {
return $con->query($sql)->fetchAll();; return $con->query($sql)->fetchAll();;
} }
public static function getUserCount($type=NULL){ public static function getUserCount($type=null)
{
$con = Propel::getConnection(); $con = Propel::getConnection();
$sql = ''; $sql = '';
$sql_gen = "SELECT count(*) AS cnt FROM cc_subjs "; $sql_gen = "SELECT count(*) AS cnt FROM cc_subjs ";
if (!isset($type)) { if (!isset($type)) {
$sql = $sql_gen; $sql = $sql_gen;
} } else {
else{ if (is_array($type)) {
if (is_array($type)) { for ($i=0; $i<count($type); $i++) {
for ($i=0; $i<count($type); $i++) { $type[$i] = "type = '{$type[$i]}'";
$type[$i] = "type = '{$type[$i]}'"; }
} $sql_type = join(" OR ", $type);
$sql_type = join(" OR ", $type); } else {
} $sql_type = "type = {$type}";
else { }
$sql_type = "type = {$type}";
}
$sql = $sql_gen ." WHERE (". $sql_type.") "; $sql = $sql_gen ." WHERE (". $sql_type.") ";
} }
$query = $con->query($sql)->fetchColumn(0); $query = $con->query($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); 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"); $displayColumns = array("id", "login", "first_name", "last_name", "type");
$fromTable = "cc_subjs"; $fromTable = "cc_subjs";
@ -273,8 +302,8 @@ class Application_Model_User {
$res = Application_Model_Datatables::findEntries($con, $displayColumns, $fromTable, $datatables); $res = Application_Model_Datatables::findEntries($con, $displayColumns, $fromTable, $datatables);
// mark record which is for the current user // mark record which is for the current user
foreach($res['aaData'] as &$record){ foreach ($res['aaData'] as &$record) {
if($record['login'] == $username){ if ($record['login'] == $username) {
$record['delete'] = "self"; $record['delete'] = "self";
} else { } else {
$record['delete'] = ""; $record['delete'] = "";
@ -284,7 +313,8 @@ class Application_Model_User {
return $res; return $res;
} }
public static function getUserData($id){ public static function getUserData($id)
{
$con = Propel::getConnection(); $con = Propel::getConnection();
$sql = "SELECT login, first_name, last_name, type, id, email, cell_phone, skype_contact, jabber_contact" $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(); return $con->query($sql)->fetch();
} }
public static function GetUserID($login){ public static function getCurrentUser()
$user = CcSubjsQuery::create()->findOneByDbLogin($login); {
if (is_null($user)){
return -1;
} else {
return $user->getDbId();
}
}
public static function GetCurrentUser() {
$userinfo = Zend_Auth::getInstance()->getStorage()->read(); $userinfo = Zend_Auth::getInstance()->getStorage()->read();
if (is_null($userinfo)){ if (is_null($userinfo)) {
return null; return null;
} else { } else {
try { try {
return new self($userinfo->id); return new self($userinfo->id);
} catch (Exception $e){ } catch (Exception $e) {
//we get here if $userinfo->id is defined, but doesn't exist //we get here if $userinfo->id is defined, but doesn't exist
//in the database anymore. //in the database anymore.
Zend_Auth::getInstance()->clearIdentity(); Zend_Auth::getInstance()->clearIdentity();
return null; return null;
} }

View File

@ -13,7 +13,7 @@
*/ */
class CcFiles extends BaseCcFiles { class CcFiles extends BaseCcFiles {
public function getDbLength($format = "H:i:s.u") public function getDbLength($format = "H:i:s.u")
{ {
return parent::getDbLength($format); return parent::getDbLength($format);
} }

View File

@ -1,10 +1,10 @@
<?php <?php
class Common { class Common {
public static function setTimeInSub($row, $col, $time) public static function setTimeInSub($row, $col, $time)
{ {
$class = get_class($row).'Peer'; $class = get_class($row).'Peer';
$con = Propel::getConnection($class::DATABASE_NAME); $con = Propel::getConnection($class::DATABASE_NAME);

View File

@ -17,8 +17,8 @@ class StoredFileTest extends PHPUnit_TestCase {
|| ($metadata["audio"]["dataformat"] != "mp3") || ($metadata["audio"]["dataformat"] != "mp3")
|| ($metadata["dc:type"] != "Speech")) { || ($metadata["dc:type"] != "Speech")) {
$str = " [dc:description] = " . $metadata["dc:description"] ."\n" $str = " [dc:description] = " . $metadata["dc:description"] ."\n"
. " [audio][dataformat] = " . $metadata["audio"]["dataformat"]."\n" . " [audio][dataformat] = " . $metadata["audio"]["dataformat"]."\n"
. " [dc:type] = ".$metadata["dc:type"]."\n"; . " [dc:type] = ".$metadata["dc:type"]."\n";
$this->fail("Metadata has unexpected values:\n".$str); $this->fail("Metadata has unexpected values:\n".$str);
} }
//var_dump($metadata); //var_dump($metadata);

@ -1 +1 @@
Subproject commit 492242f4bb7367afebbf2f096067cb5a5d3c0449 Subproject commit 0653ec0b89362921f075af96ee8772538b801a7c