CC-4090: Make code style PSR compliant

-run psr-cs-fixer
This commit is contained in:
Martin Konecny 2012-07-15 21:17:13 -04:00
parent 5661872034
commit 794cf2c845
40 changed files with 2017 additions and 1874 deletions

View file

@ -1,7 +1,7 @@
<?php
class Application_Model_Auth {
class Application_Model_Auth
{
const TOKEN_LIFETIME = 'P2D'; // DateInterval syntax
private function generateToken($action, $user_id)
@ -86,8 +86,8 @@ class Application_Model_Auth {
/**
* Get random string
*
* @param int $length
* @param string $allowed_chars
* @param int $length
* @param string $allowed_chars
* @return string
*/
final public function generateRandomString($length = 12, $allowed_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')

View file

@ -3,7 +3,8 @@
class Application_Model_Dashboard
{
public static function GetPreviousItem($p_timeNow){
public static function GetPreviousItem($p_timeNow)
{
//get previous show and previous item in the schedule table.
//Compare the two and if the last show was recorded and started
//after the last item in the schedule table, then return the show's
@ -12,8 +13,8 @@ class Application_Model_Dashboard
$showInstance = Application_Model_ShowInstance::GetLastShowInstance($p_timeNow);
$row = Application_Model_Schedule::GetLastScheduleItem($p_timeNow);
if (is_null($showInstance)){
if (count($row) == 0){
if (is_null($showInstance)) {
if (count($row) == 0) {
return null;
} else {
return array("name"=>$row[0]["artist_name"]." - ".$row[0]["track_title"],
@ -22,8 +23,8 @@ class Application_Model_Dashboard
}
} else {
if (count($row) == 0){
if ($showInstance->isRecorded()){
if (count($row) == 0) {
if ($showInstance->isRecorded()) {
//last item is a show instance
return array("name"=>$showInstance->getName(),
"starts"=>$showInstance->getShowInstanceStart(),
@ -33,7 +34,7 @@ class Application_Model_Dashboard
}
} else {
//return the one that started later.
if ($row[0]["starts"] >= $showInstance->getShowInstanceStart()){
if ($row[0]["starts"] >= $showInstance->getShowInstanceStart()) {
return array("name"=>$row[0]["artist_name"]." - ".$row[0]["track_title"],
"starts"=>$row[0]["starts"],
"ends"=>$row[0]["ends"]);
@ -46,7 +47,8 @@ class Application_Model_Dashboard
}
}
public static function GetCurrentItem($p_timeNow){
public static function GetCurrentItem($p_timeNow)
{
//get previous show and previous item in the schedule table.
//Compare the two and if the last show was recorded and started
//after the last item in the schedule table, then return the show's
@ -54,26 +56,27 @@ class Application_Model_Dashboard
$row = array();
$showInstance = Application_Model_ShowInstance::GetCurrentShowInstance($p_timeNow);
if (!is_null($showInstance)){
if (!is_null($showInstance)) {
$instanceId = $showInstance->getShowInstanceId();
$row = Application_Model_Schedule::GetCurrentScheduleItem($p_timeNow, $instanceId);
}
if (is_null($showInstance)){
if (count($row) == 0){
if (is_null($showInstance)) {
if (count($row) == 0) {
return null;
} else {
/* Should never reach here, but lets return the track information
* just in case we allow tracks to be scheduled without a show
* in the future.
*/
return array("name"=>$row[0]["artist_name"]." - ".$row[0]["track_title"],
"starts"=>$row[0]["starts"],
"ends"=>$row[0]["ends"]);
}
} else {
if (count($row) == 0){
if (count($row) == 0) {
//last item is a show instance
if ($showInstance->isRecorded()){
if ($showInstance->isRecorded()) {
return array("name"=>$showInstance->getName(),
"starts"=>$showInstance->getShowInstanceStart(),
"ends"=>$showInstance->getShowInstanceEnd(),
@ -92,7 +95,8 @@ class Application_Model_Dashboard
}
}
public static function GetNextItem($p_timeNow){
public static function GetNextItem($p_timeNow)
{
//get previous show and previous item in the schedule table.
//Compare the two and if the last show was recorded and started
//after the last item in the schedule table, then return the show's
@ -101,8 +105,8 @@ class Application_Model_Dashboard
$showInstance = Application_Model_ShowInstance::GetNextShowInstance($p_timeNow);
$row = Application_Model_Schedule::GetNextScheduleItem($p_timeNow);
if (is_null($showInstance)){
if (count($row) == 0){
if (is_null($showInstance)) {
if (count($row) == 0) {
return null;
} else {
return array("name"=>$row[0]["artist_name"]." - ".$row[0]["track_title"],
@ -110,8 +114,8 @@ class Application_Model_Dashboard
"ends"=>$row[0]["ends"]);
}
} else {
if (count($row) == 0){
if ($showInstance->isRecorded()){
if (count($row) == 0) {
if ($showInstance->isRecorded()) {
//last item is a show instance
return array("name"=>$showInstance->getName(),
"starts"=>$showInstance->getShowInstanceStart(),
@ -122,7 +126,7 @@ class Application_Model_Dashboard
} else {
//return the one that starts sooner.
if ($row[0]["starts"] <= $showInstance->getShowInstanceStart()){
if ($row[0]["starts"] <= $showInstance->getShowInstanceStart()) {
return array("name"=>$row[0]["artist_name"]." - ".$row[0]["track_title"],
"starts"=>$row[0]["starts"],
"ends"=>$row[0]["ends"]);

View file

@ -1,7 +1,7 @@
<?php
class Application_Model_Datatables {
class Application_Model_Datatables
{
/*
* query used to return data for a paginated/searchable datatable.
*/
@ -44,7 +44,7 @@ class Application_Model_Datatables {
// Order By clause
$orderby = array();
for ($i = 0; $i < $data["iSortingCols"]; $i++){
for ($i = 0; $i < $data["iSortingCols"]; $i++) {
$num = $data["iSortCol_".$i];
$orderby[] = $data["mDataProp_{$num}"]." ".$data["sSortDir_".$i];
}
@ -64,8 +64,7 @@ class Application_Model_Datatables {
if ($displayLength !== -1) {
$sql .= " OFFSET ".$data["iDisplayStart"]." LIMIT ".$displayLength;
}
}
else {
} else {
$sql = $selectorRows." FROM ".$fromTable." ORDER BY ".$orderby;
//limit the results returned.
@ -81,16 +80,14 @@ class Application_Model_Datatables {
if (isset($sqlTotalDisplayRows)) {
$r = $con->query($sqlTotalDisplayRows);
$totalDisplayRows = $r->fetchColumn(0);
}
else {
} else {
$totalDisplayRows = $totalRows;
}
$r = $con->query($sql);
$r->setFetchMode(PDO::FETCH_ASSOC);
$results = $r->fetchAll();
}
catch (Exception $e) {
} catch (Exception $e) {
Logging::debug($e->getMessage());
}

View file

@ -1,13 +1,13 @@
<?php
class Application_Model_Email {
class Application_Model_Email
{
/**
* Send email
*
* @param string $subject
* @param string $message
* @param mixed $tos
* @param string $subject
* @param string $message
* @param mixed $tos
* @return void
*/
public static function send($subject, $message, $tos, $from = null)

View file

@ -3,7 +3,8 @@
class Application_Model_LiveLog
{
public static function GetLiveShowDuration($p_keepData=false) {
public static function GetLiveShowDuration($p_keepData=false)
{
try {
$con = Propel::getConnection();
@ -86,12 +87,12 @@ class Application_Model_LiveLog
//Trim milliseconds
$seconds = explode(".", $seconds);
if (isset($seconds[0])) {
$minutes = (double)(($hours*60)+$minutes . "." . $seconds[0]);
}
else {
$minutes = (double)(($hours*60)+$minutes);
$minutes = (double) (($hours*60)+$minutes . "." . $seconds[0]);
} else {
$minutes = (double) (($hours*60)+$minutes);
}
}
return $minutes;
} catch (Exception $e) {
header('HTTP/1.0 503 Service Unavailable');
@ -119,8 +120,7 @@ class Application_Model_LiveLog
$last_row = self::UpdateLastLogEndTime(array_pop($rows));
array_push($rows, $last_row);
$skip = false;
}
else {
} else {
$sql = "SELECT * FROM CC_LIVE_LOG"
." WHERE state = 'S'"
." ORDER BY id";
@ -191,22 +191,19 @@ class Application_Model_LiveLog
if ($clip_length_seconds / 3600 >= 1) {
array_push($clip_length_arr, str_pad(floor($clip_length_seconds / 3600), 2, "0", STR_PAD_LEFT));
$clip_length_seconds -= floor($clip_length_seconds / 3600);
}
else {
} else {
array_push($clip_length_arr, "00");
}
if ($clip_length_seconds / 60 >= 1) {
array_push($clip_length_arr, str_pad(floor($clip_length_seconds / 60), 2, "0", STR_PAD_LEFT));
$clip_length_seconds -= floor($clip_length_seconds / 60);
}
else {
} else {
array_push($clip_length_arr, "00");
}
array_push($clip_length_arr, str_pad($clip_length_seconds, 2, "0", STR_PAD_LEFT));
$clip_length = implode(":", $clip_length_arr);
}
else {
} else {
$clip_length = $track['clip_length'];
}
@ -248,12 +245,12 @@ class Application_Model_LiveLog
$seconds = explode(".", $seconds);
if (isset($seconds[0])) {
$minutes = (double)(($hours*60)+$minutes . "." . $seconds[0]);
}
else {
$minutes = (double)(($hours*60)+$minutes);
$minutes = (double) (($hours*60)+$minutes . "." . $seconds[0]);
} else {
$minutes = (double) (($hours*60)+$minutes);
}
}
return $minutes;
} catch (Exception $e) {
header('HTTP/1.0 503 Service Unavailable');
@ -262,7 +259,8 @@ class Application_Model_LiveLog
}
}
public static function UpdateLastLogEndTime($log) {
public static function UpdateLastLogEndTime($log)
{
if ($log['end_time'] == null) {
$current_time = new DateTime("now", new DateTimeZone('UTC'));
$log['end_time'] = $current_time;
@ -270,10 +268,12 @@ class Application_Model_LiveLog
self::SetEndTime($log['state'], $current_time, true);
self::SetNewLogTime($log['state'], $current_time);
}
return $log;
}
public static function SetNewLogTime($state, $dateTime){
public static function SetNewLogTime($state, $dateTime)
{
try {
$con = Propel::getConnection();
@ -293,7 +293,7 @@ class Application_Model_LiveLog
$sql_insert = "INSERT INTO CC_LIVE_LOG (state, start_time)"
." VALUES ('$state', '{$dateTime->format("Y-m-d H:i:s")}')";
$con->exec($sql_insert);
if($state == "S"){
if ($state == "S") {
// if scheduled play source is getting broadcasted
Application_Model_Schedule::UpdateBrodcastedStatus($dateTime, 1);
}
@ -306,7 +306,8 @@ class Application_Model_LiveLog
}
}
public static function SetEndTime($state, $dateTime, $override=false){
public static function SetEndTime($state, $dateTime, $override=false)
{
try {
$con = Propel::getConnection();

View file

@ -1,10 +1,12 @@
<?php
class Application_Model_LoginAttempts {
public function __construct(){
class Application_Model_LoginAttempts
{
public function __construct()
{
}
public static function increaseAttempts($ip){
public static function increaseAttempts($ip)
{
$con = Propel::getConnection();
$sql = "select count(*) from cc_login_attempts WHERE ip='$ip'";
$res = $con->query($sql)->fetchColumn(0);
@ -17,14 +19,17 @@ class Application_Model_LoginAttempts {
}
}
public static function getAttempts($ip){
public static function getAttempts($ip)
{
$con = Propel::getConnection();
$sql = "select attempts from cc_login_attempts WHERE ip='$ip'";
$res = $con->query($sql)->fetchColumn(0);
return $res ? $res : 0;
}
public static function resetAttempts($ip){
public static function resetAttempts($ip)
{
$con = Propel::getConnection();
$sql = "select count(*) from cc_login_attempts WHERE ip='$ip'";
$res = $con->query($sql)->fetchColumn(0);
@ -33,4 +38,4 @@ class Application_Model_LoginAttempts {
$con->exec($sql);
}
}
}
}

View file

@ -2,8 +2,8 @@
class NestedDirectoryException extends Exception { }
class Application_Model_MusicDir {
class Application_Model_MusicDir
{
/**
* @holds propel database object
*/
@ -40,21 +40,25 @@ class Application_Model_MusicDir {
$this->_dir->save();
}
public function setExistsFlag($flag){
public function setExistsFlag($flag)
{
$this->_dir->setExists($flag);
$this->_dir->save();
}
public function setWatchedFlag($flag){
public function setWatchedFlag($flag)
{
$this->_dir->setWatched($flag);
$this->_dir->save();
}
public function getWatchedFlag(){
public function getWatchedFlag()
{
return $this->_dir->getWatched();
}
public function getExistsFlag(){
public function getExistsFlag()
{
return $this->_dir->getExists();
}
@ -113,8 +117,9 @@ class Application_Model_MusicDir {
* @return boolean
* Returns true if it is the ancestor, false otherwise.
*/
private static function isAncestorDir($p_dir1, $p_dir2){
if (strlen($p_dir1) > strlen($p_dir2)){
private static function isAncestorDir($p_dir1, $p_dir2)
{
if (strlen($p_dir1) > strlen($p_dir2)) {
return false;
}
@ -130,23 +135,24 @@ class Application_Model_MusicDir {
* The path we want to validate
* @return void
*/
public static function isPathValid($p_path){
public static function isPathValid($p_path)
{
$dirs = self::getWatchedDirs();
$dirs[] = self::getStorDir();
foreach ($dirs as $dirObj){
foreach ($dirs as $dirObj) {
$dir = $dirObj->getDirectory();
$diff = strlen($dir) - strlen($p_path);
if ($diff == 0){
if ($dir == $p_path){
if ($diff == 0) {
if ($dir == $p_path) {
throw new NestedDirectoryException("'$p_path' is already watched.");
}
} else if ($diff > 0){
if (self::isAncestorDir($p_path, $dir)){
} elseif ($diff > 0) {
if (self::isAncestorDir($p_path, $dir)) {
throw new NestedDirectoryException("'$p_path' contains nested watched directory: '$dir'");
}
} else { /* diff < 0*/
if (self::isAncestorDir($dir, $p_path)){
if (self::isAncestorDir($dir, $p_path)) {
throw new NestedDirectoryException("'$p_path' is nested within existing watched directory: '$dir'");
}
}
@ -167,37 +173,36 @@ class Application_Model_MusicDir {
**/
public static function addDir($p_path, $p_type, $userAddedWatchedDir=true, $nestedWatch=false)
{
if(!is_dir($p_path)){
if (!is_dir($p_path)) {
return array("code"=>2, "error"=>"'$p_path' is not a valid directory.");
}
$real_path = Application_Common_OsPath::normpath($p_path)."/";
if($real_path != "/"){
if ($real_path != "/") {
$p_path = $real_path;
}
$exist_dir = self::getDirByPath($p_path);
if( $exist_dir == NULL ){
if ($exist_dir == NULL) {
$temp_dir = new CcMusicDirs();
$dir = new Application_Model_MusicDir($temp_dir);
}else{
} else {
$dir = $exist_dir;
}
$dir->setType($p_type);
$p_path = Application_Common_OsPath::normpath($p_path)."/";
try {
/* isPathValid() checks if path is a substring or a superstring of an
* existing dir and if not, throws NestedDirectoryException */
if(!$nestedWatch){
if (!$nestedWatch) {
self::isPathValid($p_path);
}
if($userAddedWatchedDir){
if ($userAddedWatchedDir) {
$dir->setWatchedFlag(true);
}else{
if($nestedWatch){
} else {
if ($nestedWatch) {
$dir->setWatchedFlag(false);
}
$dir->setExistsFlag(true);
@ -205,10 +210,11 @@ class Application_Model_MusicDir {
$dir->setDirectory($p_path);
return array("code"=>0);
} catch (NestedDirectoryException $nde){
} catch (NestedDirectoryException $nde) {
$msg = $nde->getMessage();
return array("code"=>1, "error"=>"$msg");
} catch(Exception $e){
} catch (Exception $e) {
return array("code"=>1, "error"=>"'$p_path' is already set as the current storage dir or in the watched folders list");
}
@ -228,7 +234,7 @@ class Application_Model_MusicDir {
{
$res = self::addDir($p_path, "watched", $userAddedWatchedDir, $nestedWatch);
if ($res['code'] == 0){
if ($res['code'] == 0) {
//convert "linked" files (Airtime <= 1.8.2) to watched files.
$propel_link_dir = CcMusicDirsQuery::create()
@ -271,6 +277,7 @@ class Application_Model_MusicDir {
$data["directory"] = $p_path;
Application_Model_RabbitMq::SendMessageToMediaMonitor("new_watch", $data);
}
return $res;
}
@ -288,11 +295,11 @@ class Application_Model_MusicDir {
$dir = CcMusicDirsQuery::create()
->filterByDirectory($p_path)
->findOne();
if($dir == NULL){
if ($dir == NULL) {
return null;
}
else{
} else {
$mus_dir = new Application_Model_MusicDir($dir);
return $mus_dir;
}
}
@ -309,15 +316,15 @@ class Application_Model_MusicDir {
$dirs = CcMusicDirsQuery::create()
->filterByType("watched");
if($exists !== null){
if ($exists !== null) {
$dirs = $dirs->filterByExists($exists);
}
if($watched !== null){
if ($watched !== null) {
$dirs = $dirs->filterByWatched($watched);
}
$dirs = $dirs->find();
foreach($dirs as $dir) {
foreach ($dirs as $dir) {
$result[] = new Application_Model_MusicDir($dir);
}
@ -340,23 +347,24 @@ class Application_Model_MusicDir {
// we want to be consistent when storing dir path.
// path should always ends with trailing '/'
$p_dir = Application_Common_OsPath::normpath($p_dir)."/";
if(!is_dir($p_dir)){
if (!is_dir($p_dir)) {
return array("code"=>2, "error"=>"'$p_dir' is not a valid directory.");
}else if(Application_Model_Preference::GetImportTimestamp()+10 > time()){
} elseif (Application_Model_Preference::GetImportTimestamp()+10 > time()) {
return array("code"=>3, "error"=>"Airtime is currently importing files. Please wait until this is complete before changing the storage directory.");
}
$dir = self::getStorDir();
// if $p_dir doesn't exist in DB
$exist = $dir->getDirByPath($p_dir);
if($exist == NULL){
if ($exist == NULL) {
$dir->setDirectory($p_dir);
$dirId = $dir->getId();
$data = array();
$data["directory"] = $p_dir;
$data["dir_id"] = $dirId;
Application_Model_RabbitMq::SendMessageToMediaMonitor("change_stor", $data);
return array("code"=>0);
}else{
} else {
return array("code"=>1, "error"=>"'$p_dir' is already set as the current storage dir or in the watched folders list.");
}
}
@ -369,10 +377,11 @@ class Application_Model_MusicDir {
->filterByWatched(true)
->find();
foreach($dirs as $dir) {
foreach ($dirs as $dir) {
$directory = $dir->getDirectory();
if (substr($p_filepath, 0, strlen($directory)) === $directory) {
$mus_dir = new Application_Model_MusicDir($dir);
return $mus_dir;
}
}
@ -390,11 +399,11 @@ class Application_Model_MusicDir {
* When $userAddedWatchedDir is true, it will set "Watched" flag to false
* otherwise, it will set "Exists" flag to true
**/
public static function removeWatchedDir($p_dir, $userAddedWatchedDir=true){
public static function removeWatchedDir($p_dir, $userAddedWatchedDir=true)
{
//make sure that $p_dir has a trailing "/"
$real_path = Application_Common_OsPath::normpath($p_dir)."/";
if($real_path != "/"){
if ($real_path != "/") {
$p_dir = $real_path;
}
$dir = Application_Model_MusicDir::getDirByPath($p_dir);
@ -405,6 +414,7 @@ class Application_Model_MusicDir {
$data = array();
$data["directory"] = $p_dir;
Application_Model_RabbitMq::SendMessageToMediaMonitor("remove_watch", $data);
return array("code"=>0);
}
}
@ -413,7 +423,7 @@ class Application_Model_MusicDir {
{
$mus_dir = self::getWatchedDirFromFilepath($p_filepath);
if(is_null($mus_dir)) {
if (is_null($mus_dir)) {
return null;
}

View file

@ -8,8 +8,8 @@ require_once 'formatters/LengthFormatter.php';
* @copyright 2010 Sourcefabric O.P.S.
* @license http://www.gnu.org/licenses/gpl.txt
*/
class Application_Model_Playlist {
class Application_Model_Playlist
{
/**
* propel connection object.
*/
@ -55,8 +55,7 @@ class Application_Model_Playlist {
if (is_null($this->pl)) {
throw new PlaylistNotFoundException();
}
}
else {
} else {
$this->pl = new CcPlaylist();
$this->pl->setDbUTime("now", new DateTimeZone("UTC"));
$this->pl->save();
@ -79,7 +78,8 @@ class Application_Model_Playlist {
*
* @return int
*/
public function getId() {
public function getId()
{
return $this->id;
}
@ -117,28 +117,30 @@ class Application_Model_Playlist {
return $this->pl->getDbDescription();
}
public function getCreator() {
public function getCreator()
{
return $this->pl->getCcSubjs()->getDbLogin();
}
public function getCreatorId() {
public function getCreatorId()
{
return $this->pl->getCcSubjs()->getDbId();
}
public function setCreator($p_id) {
public function setCreator($p_id)
{
$this->pl->setDbCreatorId($p_id);
$this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
$this->pl->save($this->con);
}
public function getLastModified($format = null) {
public function getLastModified($format = null)
{
return $this->pl->getDbMtime($format);
}
public function getSize() {
public function getSize()
{
return $this->pl->countCcPlaylistcontentss();
}
@ -148,15 +150,15 @@ class Application_Model_Playlist {
* file_exists flag set to true
* @return array
*/
public function getContents($filterFiles=false) {
public function getContents($filterFiles=false)
{
Logging::log("Getting contents for playlist {$this->id}");
$files = array();
$query = CcPlaylistcontentsQuery::create()
->filterByDbPlaylistId($this->id);
if($filterFiles){
if ($filterFiles) {
$query->useCcFilesQuery()
->filterByDbFileExists(true)
->endUse();
@ -193,8 +195,8 @@ class Application_Model_Playlist {
* but this isn't practical since fades shouldn't be very long usuall 1 second or less. This function
* will normalize the fade so that it looks like 00.000000 to the user.
**/
public function normalizeFade($fade) {
public function normalizeFade($fade)
{
//First get rid of the first six characters 00:00: which will be added back later for db update
$fade = substr($fade, 6);
@ -211,12 +213,11 @@ class Application_Model_Playlist {
}
//aggregate column on playlistcontents cliplength column.
public function getLength() {
public function getLength()
{
return $this->pl->getDbLength();
}
private function insertPlaylistElement($info)
{
$row = new CcPlaylistcontents();
@ -246,8 +247,7 @@ class Application_Model_Playlist {
$entry["cueout"] = $file->getDbLength();
return $entry;
}
else {
} else {
throw new Exception("trying to add a file that does not exist.");
}
}
@ -275,7 +275,6 @@ class Application_Model_Playlist {
Logging::log("index is {$index}");
$pos = ($addType == 'after') ? $index + 1 : $index;
$contentsToUpdate = CcPlaylistcontentsQuery::create()
->filterByDbPlaylistId($this->id)
->filterByDbPosition($pos, Criteria::GREATER_EQUAL)
@ -284,8 +283,7 @@ class Application_Model_Playlist {
Logging::log("Adding to playlist");
Logging::log("at position {$pos}");
}
else {
} else {
//add to the end of the playlist
if ($addType == 'after') {
@ -311,7 +309,7 @@ class Application_Model_Playlist {
Logging::log("at position {$pos}");
}
foreach($p_items as $ac) {
foreach ($p_items as $ac) {
Logging::log("Adding audio file {$ac}");
$res = $this->insertPlaylistElement($this->buildEntry($ac, $pos));
@ -329,8 +327,7 @@ class Application_Model_Playlist {
$this->pl->save($this->con);
$this->con->commit();
}
catch (Exception $e) {
} catch (Exception $e) {
$this->con->rollback();
throw $e;
}
@ -378,8 +375,7 @@ class Application_Model_Playlist {
$item->save($this->con);
$pos = $pos + 1;
}
}
else {
} else {
Logging::log("moving items after {$p_afterItem}");
foreach ($otherContent as $item) {
@ -400,13 +396,11 @@ class Application_Model_Playlist {
}
$this->con->commit();
}
catch (Exception $e) {
} catch (Exception $e) {
$this->con->rollback();
throw $e;
}
$this->pl = CcPlaylistQuery::create()->findPK($this->id);
$this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
$this->pl->save($this->con);
@ -444,16 +438,14 @@ class Application_Model_Playlist {
$this->pl->save($this->con);
$this->con->commit();
}
catch (Exception $e) {
} catch (Exception $e) {
$this->con->rollback();
throw $e;
}
}
public function getFadeInfo($pos) {
public function getFadeInfo($pos)
{
Logging::log("Getting fade info for pos {$pos}");
$row = CcPlaylistcontentsQuery::create()
@ -465,6 +457,7 @@ class Application_Model_Playlist {
#Propel returns values in form 00.000000 format which is for only seconds.
$fadeIn = $row->getDbFadein();
$fadeOut = $row->getDbFadeout();
return array($fadeIn, $fadeOut);
}
@ -510,7 +503,7 @@ class Application_Model_Playlist {
}
$row->setDbFadein($fadeIn);
}
if (!is_null($fadeOut)){
if (!is_null($fadeOut)) {
$sql = "SELECT INTERVAL '{$fadeOut}' > INTERVAL '{$clipLength}'";
$r = $this->con->query($sql);
@ -526,8 +519,7 @@ class Application_Model_Playlist {
$this->pl->save($this->con);
$this->con->commit();
}
catch (Exception $e) {
} catch (Exception $e) {
$this->con->rollback();
throw $e;
}
@ -535,8 +527,8 @@ class Application_Model_Playlist {
return array("fadeIn" => $fadeIn, "fadeOut" => $fadeOut);
}
public function setPlaylistfades($fadein, $fadeout) {
public function setPlaylistfades($fadein, $fadeout)
{
if (isset($fadein)) {
Logging::log("Setting playlist fade in {$fadein}");
$row = CcPlaylistcontentsQuery::create()
@ -578,6 +570,7 @@ class Application_Model_Playlist {
try {
if (is_null($cueIn) && is_null($cueOut)) {
$errArray["error"] = "Cue in and cue out are null.";
return $errArray;
}
@ -598,9 +591,9 @@ class Application_Model_Playlist {
$file = $row->getCcFiles($this->con);
$origLength = $file->getDbLength();
if (!is_null($cueIn) && !is_null($cueOut)){
if (!is_null($cueIn) && !is_null($cueOut)) {
if ($cueOut === ""){
if ($cueOut === "") {
$cueOut = $origLength;
}
@ -608,13 +601,15 @@ class Application_Model_Playlist {
$r = $this->con->query($sql);
if ($r->fetchColumn(0)) {
$errArray["error"] = "Can't set cue in to be larger than cue out.";
return $errArray;
}
$sql = "SELECT INTERVAL '{$cueOut}' > INTERVAL '{$origLength}'";
$r = $this->con->query($sql);
if ($r->fetchColumn(0)){
if ($r->fetchColumn(0)) {
$errArray["error"] = "Can't set cue out to be greater than file length.";
return $errArray;
}
@ -626,13 +621,13 @@ class Application_Model_Playlist {
$row->setDbCueout($cueOut);
$row->setDBCliplength($cliplength);
}
else if (!is_null($cueIn)) {
} elseif (!is_null($cueIn)) {
$sql = "SELECT INTERVAL '{$cueIn}' > INTERVAL '{$oldCueOut}'";
$r = $this->con->query($sql);
if ($r->fetchColumn(0)) {
$errArray["error"] = "Can't set cue in to be larger than cue out.";
return $errArray;
}
@ -642,10 +637,9 @@ class Application_Model_Playlist {
$row->setDbCuein($cueIn);
$row->setDBCliplength($cliplength);
}
else if (!is_null($cueOut)) {
} elseif (!is_null($cueOut)) {
if ($cueOut === ""){
if ($cueOut === "") {
$cueOut = $origLength;
}
@ -653,13 +647,15 @@ class Application_Model_Playlist {
$r = $this->con->query($sql);
if ($r->fetchColumn(0)) {
$errArray["error"] = "Can't set cue out to be smaller than cue in.";
return $errArray;
}
$sql = "SELECT INTERVAL '{$cueOut}' > INTERVAL '{$origLength}'";
$r = $this->con->query($sql);
if ($r->fetchColumn(0)){
if ($r->fetchColumn(0)) {
$errArray["error"] = "Can't set cue out to be greater than file length.";
return $errArray;
}
@ -675,14 +671,14 @@ class Application_Model_Playlist {
$sql = "SELECT INTERVAL '{$fadeIn}' > INTERVAL '{$cliplength}'";
$r = $this->con->query($sql);
if ($r->fetchColumn(0)){
if ($r->fetchColumn(0)) {
$fadeIn = $cliplength;
$row->setDbFadein($fadeIn);
}
$sql = "SELECT INTERVAL '{$fadeOut}' > INTERVAL '{$cliplength}'";
$r = $this->con->query($sql);
if ($r->fetchColumn(0)){
if ($r->fetchColumn(0)) {
$fadeOut = $cliplength;
$row->setDbFadein($fadeOut);
}
@ -692,8 +688,7 @@ class Application_Model_Playlist {
$this->pl->save($this->con);
$this->con->commit();
}
catch (Exception $e) {
} catch (Exception $e) {
$this->con->rollback();
throw $e;
}
@ -707,7 +702,7 @@ class Application_Model_Playlist {
$categories = $this->categories;
$md = array();
foreach($categories as $key => $val) {
foreach ($categories as $key => $val) {
$method = 'get' . $val;
$md[$key] = $this->$method();
}
@ -719,6 +714,7 @@ class Application_Model_Playlist {
{
$cat = $this->categories[$category];
$method = 'get' . $cat;
return $this->$method();
}
@ -749,6 +745,7 @@ class Application_Model_Playlist {
if (isset($arr[1])) {
return intval($arr[0])*60 + floatval($arr[1]);
}
return floatval($arr[0]);
}
@ -758,7 +755,7 @@ class Application_Model_Playlist {
*
* Convert float seconds value to playlist time format
*
* @param float $seconds
* @param float $seconds
* @return string
* interval in playlist time format (HH:mm:ss.d)
*/
@ -766,9 +763,9 @@ class Application_Model_Playlist {
{
$info = explode('.', $p_seconds);
$seconds = $info[0];
if(!isset($info[1])){
if (!isset($info[1])) {
$milliStr = 0;
}else{
} else {
$milliStr = $info[1];
}
$hours = floor($seconds / 3600);
@ -786,6 +783,7 @@ class Application_Model_Playlist {
global $CC_CONFIG;
$con = Propel::getConnection();
$sql = 'SELECT count(*) as cnt FROM '.$CC_CONFIG["playListTable"];
return $con->query($sql)->fetchColumn(0);
}

View file

@ -2,16 +2,16 @@
require_once 'formatters/LengthFormatter.php';
class Application_Model_PlayoutHistory {
class Application_Model_PlayoutHistory
{
private $con;
private $timezone;
//in UTC timezone
private $startDT;
//in UTC timezone
private $timezone;
//in UTC timezone
private $startDT;
//in UTC timezone
private $endDT;
private $epoch_now;
private $opts;
@ -24,12 +24,12 @@ class Application_Model_PlayoutHistory {
"copyright" => "file.copyright",
);
public function __construct($p_startDT, $p_endDT, $p_opts) {
public function __construct($p_startDT, $p_endDT, $p_opts)
{
$this->con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME);
$this->startDT = $p_startDT;
$this->endDT = $p_endDT;
$this->timezone = date_default_timezone_get();
$this->startDT = $p_startDT;
$this->endDT = $p_endDT;
$this->timezone = date_default_timezone_get();
$this->epoch_now = time();
$this->opts = $p_opts;
}
@ -37,16 +37,16 @@ class Application_Model_PlayoutHistory {
/*
* map front end mDataProp labels to proper column names for searching etc.
*/
private function translateColumns() {
private function translateColumns()
{
for ($i = 0; $i < $this->opts["iColumns"]; $i++) {
for ($i = 0; $i < $this->opts["iColumns"]; $i++){
$this->opts["mDataProp_{$i}"] = $this->mDataPropMap[$this->opts["mDataProp_{$i}"]];
$this->opts["mDataProp_{$i}"] = $this->mDataPropMap[$this->opts["mDataProp_{$i}"]];
}
}
public function getItems() {
public function getItems()
{
$this->translateColumns();
$select = array(
@ -61,20 +61,20 @@ class Application_Model_PlayoutHistory {
$start = $this->startDT->format("Y-m-d H:i:s");
$end = $this->endDT->format("Y-m-d H:i:s");
$historyTable = "(
select count(schedule.file_id) as played, schedule.file_id as file_id
from cc_schedule as schedule
$historyTable = "(
select count(schedule.file_id) as played, schedule.file_id as file_id
from cc_schedule as schedule
where schedule.starts >= '{$start}' and schedule.starts < '{$end}'
and schedule.playout_status > 0 and schedule.media_item_played != FALSE and schedule.broadcasted = 1
group by schedule.file_id
)
and schedule.playout_status > 0 and schedule.media_item_played != FALSE and schedule.broadcasted = 1
group by schedule.file_id
)
AS playout left join cc_files as file on (file.id = playout.file_id)";
$results = Application_Model_Datatables::findEntries($this->con, $select, $historyTable, $this->opts, "history");
foreach ($results["history"] as &$row) {
$formatter = new LengthFormatter($row['length']);
$formatter = new LengthFormatter($row['length']);
$row['length'] = $formatter->format();
}

File diff suppressed because it is too large Load diff

View file

@ -3,12 +3,13 @@ require_once 'php-amqplib/amqp.inc';
class Application_Model_RabbitMq
{
static public $doPush = FALSE;
public static $doPush = FALSE;
/**
* Sets a flag to push the schedule at the end of the request.
*/
public static function PushSchedule() {
public static function PushSchedule()
{
Application_Model_RabbitMq::$doPush = TRUE;
}
@ -82,7 +83,7 @@ class Application_Model_RabbitMq
$temp['event_type'] = $event_type;
$temp['server_timezone'] = Application_Model_Preference::GetTimezone();
if($event_type == "update_recorder_schedule"){
if ($event_type == "update_recorder_schedule") {
$temp['shows'] = Application_Model_Show::getShows($now, $end_timestamp, $excludeInstance=NULL, $onlyRecord=TRUE);
}
$data = json_encode($temp);
@ -93,4 +94,3 @@ class Application_Model_RabbitMq
$conn->close();
}
}

View file

@ -1,7 +1,7 @@
<?php
class Application_Model_Schedule {
class Application_Model_Schedule
{
/**
* Return TRUE if file is going to be played in the future.
*
@ -24,13 +24,13 @@ class Application_Model_Schedule {
/**
* Returns data related to the scheduled items.
*
* @param int $p_prev
* @param int $p_next
* @param int $p_prev
* @param int $p_next
* @return date
*/
public static function GetPlayOrderRange($p_prev = 1, $p_next = 1)
{
if (!is_int($p_prev) || !is_int($p_next)){
if (!is_int($p_prev) || !is_int($p_next)) {
//must enter integers to specify ranges
return array();
}
@ -70,8 +70,8 @@ class Application_Model_Schedule {
public static function GetPrevCurrentNext($p_previousShowID, $p_currentShowID, $p_nextShowID, $p_timeNow)
{
if ($p_previousShowID == null && $p_currentShowID == null && $p_nextShowID == null)
return;
return;
global $CC_CONFIG;
$con = Propel::getConnection();
@ -85,12 +85,12 @@ class Application_Model_Schedule {
WHERE ';
*/
if (isset($p_previousShowID)){
if (isset($p_previousShowID)) {
if (isset($p_nextShowID) || isset($p_currentShowID))
$sql .= '(';
$sql .= 'st.instance_id = '.$p_previousShowID;
}
if ($p_currentShowID != null){
if ($p_currentShowID != null) {
if ($p_previousShowID != null)
$sql .= ' OR ';
else if($p_nextShowID != null)
@ -117,13 +117,13 @@ class Application_Model_Schedule {
$results['next'] = null;
$timeNowAsMillis = strtotime($p_timeNow);
for( $i = 0; $i < $numberOfRows; ++$i ){
for ($i = 0; $i < $numberOfRows; ++$i) {
// if the show is overbooked, then update the track end time to the end of the show time.
if($rows[$i]['ends'] > $rows[$i]["show_ends"]){
if ($rows[$i]['ends'] > $rows[$i]["show_ends"]) {
$rows[$i]['ends'] = $rows[$i]["show_ends"];
}
if ((strtotime($rows[$i]['starts']) <= $timeNowAsMillis) && (strtotime($rows[$i]['ends']) >= $timeNowAsMillis)){
if ( $i - 1 >= 0){
if ((strtotime($rows[$i]['starts']) <= $timeNowAsMillis) && (strtotime($rows[$i]['ends']) >= $timeNowAsMillis)) {
if ($i - 1 >= 0) {
$results['previous'] = array("name"=>$rows[$i-1]["artist_name"]." - ".$rows[$i-1]["track_title"],
"starts"=>$rows[$i-1]["starts"],
"ends"=>$rows[$i-1]["ends"],
@ -135,7 +135,7 @@ class Application_Model_Schedule {
"media_item_played"=>$rows[$i]["media_item_played"],
"record"=>0,
"type"=>'track');
if ( isset($rows[$i+1])){
if ( isset($rows[$i+1])) {
$results['next'] = array("name"=>$rows[$i+1]["artist_name"]." - ".$rows[$i+1]["track_title"],
"starts"=>$rows[$i+1]["starts"],
"ends"=>$rows[$i+1]["ends"],
@ -161,10 +161,12 @@ class Application_Model_Schedule {
"starts"=>$rows[$previousIndex]["starts"],
"ends"=>$rows[$previousIndex]["ends"]);;
}
return $results;
}
public static function GetLastScheduleItem($p_timeNow){
public static function GetLastScheduleItem($p_timeNow)
{
global $CC_CONFIG;
$con = Propel::getConnection();
$sql = "SELECT"
@ -182,11 +184,13 @@ class Application_Model_Schedule {
." LIMIT 1";
$row = $con->query($sql)->fetchAll();
return $row;
}
public static function GetCurrentScheduleItem($p_timeNow, $p_instanceId){
public static function GetCurrentScheduleItem($p_timeNow, $p_instanceId)
{
global $CC_CONFIG;
$con = Propel::getConnection();
/* Note that usually there will be one result returned. In some
@ -207,10 +211,12 @@ class Application_Model_Schedule {
." LIMIT 1";
$row = $con->query($sql)->fetchAll();
return $row;
}
public static function GetNextScheduleItem($p_timeNow){
public static function GetNextScheduleItem($p_timeNow)
{
global $CC_CONFIG;
$con = Propel::getConnection();
$sql = "SELECT"
@ -228,6 +234,7 @@ class Application_Model_Schedule {
." LIMIT 1";
$row = $con->query($sql)->fetchAll();
return $row;
}
@ -273,7 +280,6 @@ class Application_Model_Schedule {
OR (si.ends > '{$p_start}' AND si.ends <= '{$p_end}')
OR (si.starts <= '{$p_start}' AND si.ends >= '{$p_end}'))";
if (count($p_shows) > 0) {
$sql .= " AND show_id IN (".implode(",", $p_shows).")";
}
@ -283,6 +289,7 @@ class Application_Model_Schedule {
Logging::debug($sql);
$rows = $con->query($sql)->fetchAll();
return $rows;
}
@ -298,17 +305,19 @@ class Application_Model_Schedule {
$master_dj = Application_Model_Preference::GetSourceSwitchStatus('master_dj') == 'on'?true:false;
$scheduled_play = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play') == 'on'?true:false;
if(!$live_dj && !$master_dj && $scheduled_play){
if (!$live_dj && !$master_dj && $scheduled_play) {
$sql .= ", broadcasted=1";
}
$sql .= " WHERE id=$p_id";
$retVal = $con->exec($sql);
return $retVal;
}
public static function UpdateBrodcastedStatus($dateTime, $value){
public static function UpdateBrodcastedStatus($dateTime, $value)
{
global $CC_CONFIG;
$con = Propel::getConnection();
$now = $dateTime->format("Y-m-d H:i:s");
@ -316,6 +325,7 @@ class Application_Model_Schedule {
." SET broadcasted=$value"
." WHERE starts <= '$now' AND ends >= '$now'";
$retVal = $con->exec($sql);
return $retVal;
}
@ -324,15 +334,15 @@ class Application_Model_Schedule {
global $CC_CONFIG;
$con = Propel::getConnection();
$sql = "SELECT count(*) as cnt FROM ".$CC_CONFIG['scheduleTable'];
return $con->query($sql)->fetchColumn(0);
}
/**
* Convert a time string in the format "YYYY-MM-DD HH:mm:SS"
* to "YYYY-MM-DD-HH-mm-SS".
*
* @param string $p_time
* @param string $p_time
* @return string
*/
private static function AirtimeTimeToPypoTime($p_time)
@ -340,6 +350,7 @@ class Application_Model_Schedule {
$p_time = substr($p_time, 0, 19);
$p_time = str_replace(" ", "-", $p_time);
$p_time = str_replace(":", "-", $p_time);
return $p_time;
}
@ -347,19 +358,20 @@ class Application_Model_Schedule {
* Convert a time string in the format "YYYY-MM-DD-HH-mm-SS" to
* "YYYY-MM-DD HH:mm:SS".
*
* @param string $p_time
* @param string $p_time
* @return string
*/
private static function PypoTimeToAirtimeTime($p_time)
{
$t = explode("-", $p_time);
return $t[0]."-".$t[1]."-".$t[2]." ".$t[3].":".$t[4].":00";
}
/**
* Return true if the input string is in the format YYYY-MM-DD-HH-mm
*
* @param string $p_time
* @param string $p_time
* @return boolean
*/
public static function ValidPypoTimeFormat($p_time)
@ -373,6 +385,7 @@ class Application_Model_Schedule {
return false;
}
}
return true;
}
@ -380,7 +393,7 @@ class Application_Model_Schedule {
* Converts a time value as a string (with format HH:MM:SS.mmmmmm) to
* millisecs.
*
* @param string $p_time
* @param string $p_time
* @return int
*/
public static function WallTimeToMillisecs($p_time)
@ -397,16 +410,16 @@ class Application_Model_Schedule {
$seconds = intval($t[2]);
}
$ret = $millisecs + ($seconds * 1000) + ($t[1] * 60 * 1000) + ($t[0] * 60 * 60 * 1000);
return $ret;
}
/**
* Compute the difference between two times in the format "HH:MM:SS.mmmmmm".
* Note: currently only supports calculating millisec differences.
*
* @param string $p_time1
* @param string $p_time2
* @param string $p_time1
* @param string $p_time2
* @return double
*/
private static function TimeDiff($p_time1, $p_time2)
@ -423,6 +436,7 @@ class Application_Model_Schedule {
$millisec2 = intval($millisec2);
$diff = abs($millisec1 - $millisec2)/1000;
}
return $diff;
}
@ -442,7 +456,8 @@ class Application_Model_Schedule {
* Returns null if nothing found, else an array of associative
* arrays representing each row.
*/
public static function GetItems($p_startTime, $p_endTime) {
public static function GetItems($p_startTime, $p_endTime)
{
global $CC_CONFIG;
$con = Propel::getConnection();
@ -464,7 +479,6 @@ class Application_Model_Schedule {
." LEFT JOIN $CC_CONFIG[filesTable] AS f"
." ON st.file_id = f.id";
$predicates = " WHERE st.ends > '$p_startTime'"
." AND st.starts < '$p_endTime'"
." AND st.playout_status > 0"
@ -475,7 +489,7 @@ class Application_Model_Schedule {
$rows = $con->query($sql)->fetchAll();
if (count($rows) < 3){
if (count($rows) < 3) {
Logging::debug("Get Schedule: Less than 3 results returned. Doing another query since we need a minimum of 3 results.");
$dt = new DateTime("@".time());
@ -496,8 +510,8 @@ class Application_Model_Schedule {
return $rows;
}
public static function GetScheduledPlaylists($p_fromDateTime = null, $p_toDateTime = null){
public static function GetScheduledPlaylists($p_fromDateTime = null, $p_toDateTime = null)
{
global $CC_CONFIG;
/* if $p_fromDateTime and $p_toDateTime function parameters are null, then set range
@ -513,7 +527,7 @@ class Application_Model_Schedule {
$cache_ahead_hours = $CC_CONFIG["cache_ahead_hours"];
if (is_numeric($cache_ahead_hours)){
if (is_numeric($cache_ahead_hours)) {
//make sure we are not dealing with a float
$cache_ahead_hours = intval($cache_ahead_hours);
} else {
@ -536,7 +550,7 @@ class Application_Model_Schedule {
$data["media"] = array();
$kick_times = Application_Model_ShowInstance::GetEndTimeOfNextShowWithLiveDJ($range_start, $range_end);
foreach($kick_times as $kick_time_info){
foreach ($kick_times as $kick_time_info) {
$kick_time = $kick_time_info['ends'];
$temp = explode('.', Application_Model_Preference::GetDefaultTransitionFade());
// we round down transition time since PHP cannot handle millisecond. We need to
@ -552,7 +566,7 @@ class Application_Model_Schedule {
$data["media"][$kick_start]['event_type'] = "kick_out";
$data["media"][$kick_start]['type'] = "event";
if($kick_time !== $switch_off_time){
if ($kick_time !== $switch_off_time) {
$switch_start = Application_Model_Schedule::AirtimeTimeToPypoTime($switch_off_time);
$data["media"][$switch_start]['start'] = $switch_start;
$data["media"][$switch_start]['end'] = $switch_start;
@ -561,7 +575,7 @@ class Application_Model_Schedule {
}
}
foreach ($items as $item){
foreach ($items as $item) {
$showInstance = CcShowInstancesQuery::create()->findPK($item["instance_id"]);
$showId = $showInstance->getDbShowId();
@ -572,13 +586,13 @@ class Application_Model_Schedule {
$trackStartDateTime = new DateTime($item["start"], $utcTimeZone);
$trackEndDateTime = new DateTime($item["end"], $utcTimeZone);
if ($trackStartDateTime->getTimestamp() > $showEndDateTime->getTimestamp()){
if ($trackStartDateTime->getTimestamp() > $showEndDateTime->getTimestamp()) {
continue;
}
/* Note: cue_out and end are always the same. */
/* TODO: Not all tracks will have "show_end" */
if ($trackEndDateTime->getTimestamp() > $showEndDateTime->getTimestamp()){
if ($trackEndDateTime->getTimestamp() > $showEndDateTime->getTimestamp()) {
$di = $trackStartDateTime->diff($showEndDateTime);
$item["cue_out"] = $di->format("%H:%i:%s").".000";
@ -615,14 +629,16 @@ class Application_Model_Schedule {
$con->exec("TRUNCATE TABLE ".$CC_CONFIG["scheduleTable"]);
}
public static function deleteWithFileId($fileId){
public static function deleteWithFileId($fileId)
{
global $CC_CONFIG;
$con = Propel::getConnection();
$sql = "DELETE FROM ".$CC_CONFIG["scheduleTable"]." WHERE file_id=$fileId";
$res = $con->query($sql);
}
public static function createNewFormSections($p_view){
public static function createNewFormSections($p_view)
{
$isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true;
$formWhat = new Application_Form_AddShowWhat();
@ -656,7 +672,7 @@ class Application_Model_Schedule {
$formRepeats->populate(array('add_show_end_date' => date("Y-m-d")));
if(!$isSaas){
if (!$isSaas) {
$formRecord = new Application_Form_AddShowRR();
$formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates();
$formRebroadcast = new Application_Form_AddShowRebroadcastDates();
@ -677,7 +693,8 @@ class Application_Model_Schedule {
* There is still lots of clean-up to do. For example we shouldn't be passing $controller into
* this method to manipulate the view (this should be done inside the controller function). With
* 2.1 deadline looming, this is OK for now. -Martin */
public static function updateShowInstance($data, $controller){
public static function updateShowInstance($data, $controller)
{
$isSaas = (Application_Model_Preference::GetPlanLevel() != 'disabled');
$formWhat = new Application_Form_AddShowWhat();
@ -694,7 +711,7 @@ class Application_Model_Schedule {
$formStyle->removeDecorator('DtDdWrapper');
$formLive->removeDecorator('DtDdWrapper');
if(!$isSaas){
if (!$isSaas) {
$formRecord = new Application_Form_AddShowRR();
$formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates();
$formRebroadcast = new Application_Form_AddShowRebroadcastDates();
@ -705,7 +722,7 @@ class Application_Model_Schedule {
}
$when = $formWhen->isValid($data);
if($when && $formWhen->checkReliantFields($data, true, null, true)) {
if ($when && $formWhen->checkReliantFields($data, true, null, true)) {
$start_dt = new DateTime($data['add_show_start_date']." ".$data['add_show_start_time'], new DateTimeZone(date_default_timezone_get()));
$start_dt->setTimezone(new DateTimeZone('UTC'));
@ -734,7 +751,7 @@ class Application_Model_Schedule {
$controller->view->who = $formWho;
$controller->view->style = $formStyle;
$controller->view->live = $formLive;
if(!$isSaas){
if (!$isSaas) {
$controller->view->rr = $formRecord;
$controller->view->absoluteRebroadcast = $formAbsoluteRebroadcast;
$controller->view->rebroadcast = $formRebroadcast;
@ -743,6 +760,7 @@ class Application_Model_Schedule {
//$formAbsoluteRebroadcast->disable();
//$formRebroadcast->disable();
}
return false;
}
}
@ -755,8 +773,8 @@ class Application_Model_Schedule {
* Another clean-up is to move all the form manipulation to the proper form class.....
* -Martin
*/
public static function addUpdateShow($data, $controller, $validateStartDate, $originalStartDate=null, $update=false, $instanceId=null){
public static function addUpdateShow($data, $controller, $validateStartDate, $originalStartDate=null, $update=false, $instanceId=null)
{
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id);
$isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
@ -781,7 +799,7 @@ class Application_Model_Schedule {
$what = $formWhat->isValid($data);
$when = $formWhen->isValid($data);
$live = $formLive->isValid($data);
if($when) {
if ($when) {
$when = $formWhen->checkReliantFields($data, $validateStartDate, $originalStartDate, $update, $instanceId);
}
@ -797,17 +815,17 @@ class Application_Model_Schedule {
$hValue = 0;
$mValue = 0;
if($hPos !== false){
if ($hPos !== false) {
$hValue = trim(substr($data["add_show_duration"], 0, $hPos));
}
if($mPos !== false){
if ($mPos !== false) {
$hPos = $hPos === FALSE ? 0 : $hPos+1;
$mValue = trim(substr($data["add_show_duration"], $hPos, -1 ));
}
$data["add_show_duration"] = $hValue.":".$mValue;
if(!$isSaas){
if (!$isSaas) {
$formRecord = new Application_Form_AddShowRR();
$formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates();
$formRebroadcast = new Application_Form_AddShowRebroadcastDates();
@ -820,19 +838,19 @@ class Application_Model_Schedule {
$record = $formRecord->isValid($data);
}
if($data["add_show_repeats"]) {
if ($data["add_show_repeats"]) {
$repeats = $formRepeats->isValid($data);
if($repeats) {
if ($repeats) {
$repeats = $formRepeats->checkReliantFields($data);
}
if(!$isSaas){
if (!$isSaas) {
$formAbsoluteRebroadcast->reset();
//make it valid, results don't matter anyways.
$rebroadAb = 1;
if ($data["add_show_rebroadcast"]) {
$rebroad = $formRebroadcast->isValid($data);
if($rebroad) {
if ($rebroad) {
$rebroad = $formRebroadcast->checkReliantFields($data);
}
} else {
@ -841,14 +859,14 @@ class Application_Model_Schedule {
}
} else {
$repeats = 1;
if(!$isSaas){
if (!$isSaas) {
$formRebroadcast->reset();
//make it valid, results don't matter anyways.
$rebroad = 1;
if ($data["add_show_rebroadcast"]) {
$rebroadAb = $formAbsoluteRebroadcast->isValid($data);
if($rebroadAb) {
if ($rebroadAb) {
$rebroadAb = $formAbsoluteRebroadcast->checkReliantFields($data);
}
} else {
@ -860,8 +878,8 @@ class Application_Model_Schedule {
$who = $formWho->isValid($data);
$style = $formStyle->isValid($data);
if ($what && $when && $repeats && $who && $style && $live) {
if(!$isSaas){
if($record && $rebroadAb && $rebroad){
if (!$isSaas) {
if ($record && $rebroadAb && $rebroad) {
if ($isAdminOrPM) {
Application_Model_Show::create($data);
}
@ -906,7 +924,7 @@ class Application_Model_Schedule {
$controller->view->style = $formStyle;
$controller->view->live = $formLive;
if(!$isSaas){
if (!$isSaas) {
$controller->view->rr = $formRecord;
$controller->view->absoluteRebroadcast = $formAbsoluteRebroadcast;
$controller->view->rebroadcast = $formRebroadcast;
@ -917,7 +935,8 @@ class Application_Model_Schedule {
}
}
public static function checkOverlappingShows($show_start, $show_end, $update=false, $instanceId=null) {
public static function checkOverlappingShows($show_start, $show_end, $update=false, $instanceId=null)
{
global $CC_CONFIG;
$overlapping = false;
@ -934,7 +953,7 @@ class Application_Model_Schedule {
}
$rows = $con->query($sql);
foreach($rows as $row) {
foreach ($rows as $row) {
$start = new DateTime($row["starts"], new DateTimeZone('UTC'));
$end = new DateTime($row["ends"], new DateTimeZone('UTC'));
@ -944,6 +963,7 @@ class Application_Model_Schedule {
break;
}
}
return $overlapping;
}
}

View file

@ -1,7 +1,7 @@
<?php
class Application_Model_Scheduler {
class Application_Model_Scheduler
{
private $con;
private $fileInfo = array(
"id" => "",
@ -19,14 +19,14 @@ class Application_Model_Scheduler {
private $checkUserPermissions = true;
public function __construct() {
public function __construct()
{
$this->con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME);
$this->epochNow = microtime(true);
$this->nowDT = DateTime::createFromFormat("U.u", $this->epochNow, new DateTimeZone("UTC"));
if ($this->nowDT === false){
if ($this->nowDT === false) {
// DateTime::createFromFormat does not support millisecond string formatting in PHP 5.3.2 (Ubuntu 10.04).
// In PHP 5.3.3 (Ubuntu 10.10), this has been fixed.
$this->nowDT = DateTime::createFromFormat("U", time(), new DateTimeZone("UTC"));
@ -35,18 +35,18 @@ class Application_Model_Scheduler {
$this->user = Application_Model_User::getCurrentUser();
}
public function setCheckUserPermissions($value) {
public function setCheckUserPermissions($value)
{
$this->checkUserPermissions = $value;
}
/*
* make sure any incoming requests for scheduling are ligit.
*
* @param array $items, an array containing pks of cc_schedule items.
*/
private function validateRequest($items) {
/*
* make sure any incoming requests for scheduling are ligit.
*
* @param array $items, an array containing pks of cc_schedule items.
*/
private function validateRequest($items)
{
$nowEpoch = floatval($this->nowDT->format("U.u"));
for ($i = 0; $i < count($items); $i++) {
@ -57,7 +57,7 @@ class Application_Model_Scheduler {
$schedInfo[$id] = $items[$i]["instance"];
}
$instanceInfo[$items[$i]["instance"]] = $items[$i]["timestamp"];
$instanceInfo[$items[$i]["instance"]] = $items[$i]["timestamp"];
}
if (count($instanceInfo) === 0) {
@ -73,21 +73,21 @@ class Application_Model_Scheduler {
$showInstances = CcShowInstancesQuery::create()->findPKs($instanceIds, $this->con);
//an item has been deleted
if (count($schedIds) !== count($schedItems)) {
throw new OutDatedScheduleException("The schedule you're viewing is out of date! (sched mismatch)");
if (count($schedIds) !== count($schedItems)) {
throw new OutDatedScheduleException("The schedule you're viewing is out of date! (sched mismatch)");
}
//a show has been deleted
if (count($instanceIds) !== count($showInstances)) {
throw new OutDatedScheduleException("The schedule you're viewing is out of date! (instance mismatch)");
//a show has been deleted
if (count($instanceIds) !== count($showInstances)) {
throw new OutDatedScheduleException("The schedule you're viewing is out of date! (instance mismatch)");
}
foreach ($schedItems as $schedItem) {
$id = $schedItem->getDbId();
$instance = $schedItem->getCcShowInstances($this->con);
if (intval($schedInfo[$id]) !== $instance->getDbId()) {
throw new OutDatedScheduleException("The schedule you're viewing is out of date!");
if (intval($schedInfo[$id]) !== $instance->getDbId()) {
throw new OutDatedScheduleException("The schedule you're viewing is out of date!");
}
}
@ -96,23 +96,23 @@ class Application_Model_Scheduler {
$id = $instance->getDbId();
$show = $instance->getCcShow($this->con);
if ($this->checkUserPermissions && $this->user->canSchedule($show->getDbId()) === false) {
throw new Exception("You are not allowed to schedule show {$show->getDbName()}.");
if ($this->checkUserPermissions && $this->user->canSchedule($show->getDbId()) === false) {
throw new Exception("You are not allowed to schedule show {$show->getDbName()}.");
}
$showEndEpoch = floatval($instance->getDbEnds("U.u"));
if ($showEndEpoch < $nowEpoch) {
throw new OutDatedScheduleException("The show {$show->getDbName()} is over and cannot be scheduled.");
$showEndEpoch = floatval($instance->getDbEnds("U.u"));
if ($showEndEpoch < $nowEpoch) {
throw new OutDatedScheduleException("The show {$show->getDbName()} is over and cannot be scheduled.");
}
$ts = intval($instanceInfo[$id]);
$lastSchedTs = intval($instance->getDbLastScheduled("U")) ? : 0;
$lastSchedTs = intval($instance->getDbLastScheduled("U")) ? : 0;
if ($ts < $lastSchedTs) {
Logging::log("ts {$ts} last sched {$lastSchedTs}");
throw new OutDatedScheduleException("The show {$show->getDbName()} has been previously updated!");
Logging::log("ts {$ts} last sched {$lastSchedTs}");
throw new OutDatedScheduleException("The show {$show->getDbName()} has been previously updated!");
}
}
}
}
/*
@ -121,8 +121,8 @@ class Application_Model_Scheduler {
*
* @return $files
*/
private function retrieveMediaFiles($id, $type) {
private function retrieveMediaFiles($id, $type)
{
$files = array();
if ($type === "audioclip") {
@ -130,8 +130,7 @@ class Application_Model_Scheduler {
if (is_null($file) || !$file->getDbFileExists()) {
throw new Exception("A selected File does not exist!");
}
else {
} else {
$data = $this->fileInfo;
$data["id"] = $id;
$data["cliplength"] = $file->getDbLength();
@ -146,8 +145,7 @@ class Application_Model_Scheduler {
$files[] = $data;
}
}
else if ($type === "playlist") {
} elseif ($type === "playlist") {
$contents = CcPlaylistcontentsQuery::create()
->orderByDbPosition()
@ -186,8 +184,8 @@ class Application_Model_Scheduler {
*
* @return DateTime endDT in UTC
*/
private function findEndTime($p_startDT, $p_duration) {
private function findEndTime($p_startDT, $p_duration)
{
$startEpoch = $p_startDT->format("U.u");
$durationSeconds = Application_Model_Playlist::playlistTimeToSeconds($p_duration);
@ -205,70 +203,68 @@ class Application_Model_Scheduler {
return $dt;
}
private function findNextStartTime($DT, $instance) {
$sEpoch = $DT->format("U.u");
private function findNextStartTime($DT, $instance)
{
$sEpoch = $DT->format("U.u");
$nEpoch = $this->epochNow;
//check for if the show has started.
if (bccomp( $nEpoch , $sEpoch , 6) === 1) {
//need some kind of placeholder for cc_schedule.
//playout_status will be -1.
//check for if the show has started.
if (bccomp( $nEpoch , $sEpoch , 6) === 1) {
//need some kind of placeholder for cc_schedule.
//playout_status will be -1.
$nextDT = $this->nowDT;
$length = bcsub($nEpoch , $sEpoch , 6);
$cliplength = Application_Model_Playlist::secondsToPlaylistTime($length);
//fillers are for only storing a chunk of time space that has already passed.
$filler = new CcSchedule();
$filler->setDbStarts($DT)
->setDbEnds($this->nowDT)
->setDbClipLength($cliplength)
->setDbPlayoutStatus(-1)
->setDbInstanceId($instance->getDbId())
->save($this->con);
}
else {
$nextDT = $DT;
$length = bcsub($nEpoch , $sEpoch , 6);
$cliplength = Application_Model_Playlist::secondsToPlaylistTime($length);
//fillers are for only storing a chunk of time space that has already passed.
$filler = new CcSchedule();
$filler->setDbStarts($DT)
->setDbEnds($this->nowDT)
->setDbClipLength($cliplength)
->setDbPlayoutStatus(-1)
->setDbInstanceId($instance->getDbId())
->save($this->con);
} else {
$nextDT = $DT;
}
return $nextDT;
}
/*
* @param int $showInstance
* @param array $exclude
* ids of sched items to remove from the calulation.
*/
private function removeGaps($showInstance, $exclude=null) {
Logging::log("removing gaps from show instance #".$showInstance);
$instance = CcShowInstancesQuery::create()->findPK($showInstance, $this->con);
if (is_null($instance)) {
throw new OutDatedScheduleException("The schedule you're viewing is out of date!");
}
$itemStartDT = $instance->getDbStarts(null);
$schedule = CcScheduleQuery::create()
->filterByDbInstanceId($showInstance)
->filterByDbId($exclude, Criteria::NOT_IN)
->orderByDbStarts()
->find($this->con);
foreach ($schedule as $item) {
$itemEndDT = $this->findEndTime($itemStartDT, $item->getDbClipLength());
$item->setDbStarts($itemStartDT)
->setDbEnds($itemEndDT);
$itemStartDT = $itemEndDT;
/*
* @param int $showInstance
* @param array $exclude
* ids of sched items to remove from the calulation.
*/
private function removeGaps($showInstance, $exclude=null)
{
Logging::log("removing gaps from show instance #".$showInstance);
$instance = CcShowInstancesQuery::create()->findPK($showInstance, $this->con);
if (is_null($instance)) {
throw new OutDatedScheduleException("The schedule you're viewing is out of date!");
}
$schedule->save($this->con);
$itemStartDT = $instance->getDbStarts(null);
$schedule = CcScheduleQuery::create()
->filterByDbInstanceId($showInstance)
->filterByDbId($exclude, Criteria::NOT_IN)
->orderByDbStarts()
->find($this->con);
foreach ($schedule as $item) {
$itemEndDT = $this->findEndTime($itemStartDT, $item->getDbClipLength());
$item->setDbStarts($itemStartDT)
->setDbEnds($itemEndDT);
$itemStartDT = $itemEndDT;
}
$schedule->save($this->con);
}
/*
@ -276,8 +272,8 @@ class Application_Model_Scheduler {
* @param array $fileIds
* @param array $playlistIds
*/
private function insertAfter($scheduleItems, $schedFiles, $adjustSched = true) {
private function insertAfter($scheduleItems, $schedFiles, $adjustSched = true)
{
try {
$affectedShowInstances = array();
@ -326,12 +322,12 @@ class Application_Model_Scheduler {
->orderByDbStarts()
->find($this->con);
$pend = microtime(true);
Logging::debug("finding all following items.");
$pend = microtime(true);
Logging::debug("finding all following items.");
Logging::debug(floatval($pend) - floatval($pstart));
}
foreach($schedFiles as $file) {
foreach ($schedFiles as $file) {
$endTimeDT = $this->findEndTime($nextStartDT, $file['cliplength']);
@ -339,8 +335,7 @@ class Application_Model_Scheduler {
//need to keep same id for resources if we want REST.
if (isset($file['sched_id'])) {
$sched = CcScheduleQuery::create()->findPK($file['sched_id'], $this->con);
}
else {
} else {
$sched = new CcSchedule();
}
Logging::log(print_r($file,true));
@ -374,13 +369,13 @@ class Application_Model_Scheduler {
}
$pend = microtime(true);
Logging::debug("adjusting all following items.");
Logging::debug("adjusting all following items.");
Logging::debug(floatval($pend) - floatval($pstart));
}
}
$endProfile = microtime(true);
Logging::debug("finished adding scheduled items.");
$endProfile = microtime(true);
Logging::debug("finished adding scheduled items.");
Logging::debug(floatval($endProfile) - floatval($startProfile));
//update the status flag in cc_schedule.
@ -394,8 +389,8 @@ class Application_Model_Scheduler {
$instance->updateScheduleStatus($this->con);
}
$endProfile = microtime(true);
Logging::debug("updating show instances status.");
$endProfile = microtime(true);
Logging::debug("updating show instances status.");
Logging::debug(floatval($endProfile) - floatval($startProfile));
$startProfile = microtime(true);
@ -405,11 +400,10 @@ class Application_Model_Scheduler {
->filterByPrimaryKeys($affectedShowInstances)
->update(array('DbLastScheduled' => new DateTime("now", new DateTimeZone("UTC"))), $this->con);
$endProfile = microtime(true);
Logging::debug("updating last scheduled timestamp.");
$endProfile = microtime(true);
Logging::debug("updating last scheduled timestamp.");
Logging::debug(floatval($endProfile) - floatval($startProfile));
}
catch (Exception $e) {
} catch (Exception $e) {
Logging::debug($e->getMessage());
throw $e;
}
@ -419,8 +413,8 @@ class Application_Model_Scheduler {
* @param array $scheduleItems
* @param array $mediaItems
*/
public function scheduleAfter($scheduleItems, $mediaItems, $adjustSched = true) {
public function scheduleAfter($scheduleItems, $mediaItems, $adjustSched = true)
{
$this->con->beginTransaction();
$schedFiles = array();
@ -437,8 +431,7 @@ class Application_Model_Scheduler {
$this->con->commit();
Application_Model_RabbitMq::PushSchedule();
}
catch (Exception $e) {
} catch (Exception $e) {
$this->con->rollback();
throw $e;
}
@ -448,8 +441,8 @@ class Application_Model_Scheduler {
* @param array $selectedItem
* @param array $afterItem
*/
public function moveItem($selectedItems, $afterItems, $adjustSched = true) {
public function moveItem($selectedItems, $afterItems, $adjustSched = true)
{
$startProfile = microtime(true);
$this->con->beginTransaction();
@ -460,11 +453,11 @@ class Application_Model_Scheduler {
$this->validateRequest($selectedItems);
$this->validateRequest($afterItems);
$endProfile = microtime(true);
Logging::debug("validating move request took:");
$endProfile = microtime(true);
Logging::debug("validating move request took:");
Logging::debug(floatval($endProfile) - floatval($startProfile));
$afterInstance = CcShowInstancesQuery::create()->findPK($afterItems[0]["instance"], $this->con);
$afterInstance = CcShowInstancesQuery::create()->findPK($afterItems[0]["instance"], $this->con);
//map show instances to cc_schedule primary keys.
$modifiedMap = array();
@ -473,16 +466,16 @@ class Application_Model_Scheduler {
//prepare each of the selected items.
for ($i = 0; $i < count($selectedItems); $i++) {
$selected = CcScheduleQuery::create()->findPk($selectedItems[$i]["id"], $this->con);
$selectedInstance = $selected->getCcShowInstances($this->con);
$selected = CcScheduleQuery::create()->findPk($selectedItems[$i]["id"], $this->con);
$selectedInstance = $selected->getCcShowInstances($this->con);
$data = $this->fileInfo;
$data["id"] = $selected->getDbFileId();
$data["cliplength"] = $selected->getDbClipLength();
$data["cuein"] = $selected->getDbCueIn();
$data["cueout"] = $selected->getDbCueOut();
$data["fadein"] = $selected->getDbFadeIn();
$data["fadeout"] = $selected->getDbFadeOut();
$data = $this->fileInfo;
$data["id"] = $selected->getDbFileId();
$data["cliplength"] = $selected->getDbClipLength();
$data["cuein"] = $selected->getDbCueIn();
$data["cueout"] = $selected->getDbCueOut();
$data["fadein"] = $selected->getDbFadeIn();
$data["fadeout"] = $selected->getDbFadeOut();
$data["sched_id"] = $selected->getDbId();
$movedData[] = $data;
@ -492,8 +485,7 @@ class Application_Model_Scheduler {
$schedId = $selected->getDbId();
if (isset($modifiedMap[$showInstanceId])) {
array_push($modifiedMap[$showInstanceId], $schedId);
}
else {
} else {
$modifiedMap[$showInstanceId] = array($schedId);
}
}
@ -504,8 +496,8 @@ class Application_Model_Scheduler {
$this->removeGaps($instance, $schedIds);
$endProfile = microtime(true);
Logging::debug("removing gaps from instance $instance:");
$endProfile = microtime(true);
Logging::debug("removing gaps from instance $instance:");
Logging::debug(floatval($endProfile) - floatval($startProfile));
}
@ -513,14 +505,14 @@ class Application_Model_Scheduler {
$this->insertAfter($afterItems, $movedData, $adjustSched);
$endProfile = microtime(true);
Logging::debug("inserting after removing gaps.");
$endProfile = microtime(true);
Logging::debug("inserting after removing gaps.");
Logging::debug(floatval($endProfile) - floatval($startProfile));
$afterInstanceId = $afterInstance->getDbId();
$afterInstanceId = $afterInstance->getDbId();
$modified = array_keys($modifiedMap);
//need to adjust shows we have moved items from.
foreach($modified as $instanceId) {
foreach ($modified as $instanceId) {
$instance = CcShowInstancesQuery::create()->findPK($instanceId, $this->con);
$instance->updateScheduleStatus($this->con);
@ -530,15 +522,14 @@ class Application_Model_Scheduler {
$this->con->commit();
Application_Model_RabbitMq::PushSchedule();
}
catch (Exception $e) {
} catch (Exception $e) {
$this->con->rollback();
throw $e;
}
}
public function removeItems($scheduledItems, $adjustSched = true) {
public function removeItems($scheduledItems, $adjustSched = true)
{
$showInstances = array();
$this->con->beginTransaction();
@ -564,7 +555,7 @@ class Application_Model_Scheduler {
$nEpoch = $this->epochNow;
$sEpoch = $removedItem->getDbStarts('U.u');
$length = bcsub($nEpoch , $sEpoch , 6);
$length = bcsub($nEpoch , $sEpoch , 6);
$cliplength = Application_Model_Playlist::secondsToPlaylistTime($length);
$cueinSec = Application_Model_Playlist::playlistTimeToSeconds($removedItem->getDbCueIn());
@ -575,8 +566,7 @@ class Application_Model_Scheduler {
->setDbClipLength($cliplength)
->setDbEnds($this->nowDT)
->save($this->con);
}
else {
} else {
$removedItem->delete($this->con);
}
}
@ -613,8 +603,7 @@ class Application_Model_Scheduler {
$this->con->commit();
Application_Model_RabbitMq::PushSchedule();
}
catch (Exception $e) {
} catch (Exception $e) {
$this->con->rollback();
throw $e;
}
@ -625,8 +614,8 @@ class Application_Model_Scheduler {
*
* @param $p_id id of the show instance to cancel.
*/
public function cancelShow($p_id) {
public function cancelShow($p_id)
{
$this->con->beginTransaction();
try {
@ -635,28 +624,27 @@ class Application_Model_Scheduler {
if (!$instance->getDbRecord()) {
$items = CcScheduleQuery::create()
->filterByDbInstanceId($p_id)
->filterByDbEnds($this->nowDT, Criteria::GREATER_THAN)
->find($this->con);
$items = CcScheduleQuery::create()
->filterByDbInstanceId($p_id)
->filterByDbEnds($this->nowDT, Criteria::GREATER_THAN)
->find($this->con);
if (count($items) > 0) {
$remove = array();
$ts = $this->nowDT->format('U');
for($i = 0; $i < count($items); $i++) {
$remove[$i]["instance"] = $p_id;
$remove[$i]["timestamp"] = $ts;
$remove[$i]["id"] = $items[$i]->getDbId();
}
$remove = array();
$ts = $this->nowDT->format('U');
for ($i = 0; $i < count($items); $i++) {
$remove[$i]["instance"] = $p_id;
$remove[$i]["timestamp"] = $ts;
$remove[$i]["id"] = $items[$i]->getDbId();
}
$this->removeItems($remove, false);
}
}
else {
} else {
$rebroadcasts = $instance->getCcShowInstancessRelatedByDbId(null, $this->con);
$rebroadcasts->delete($this->con);
}
}
$instance->setDbEnds($this->nowDT);
$instance->save($this->con);
@ -666,10 +654,9 @@ class Application_Model_Scheduler {
if ($instance->getDbRecord()) {
Application_Model_RabbitMq::SendMessageToShowRecorder("cancel_recording");
}
}
catch (Exception $e) {
$this->con->rollback();
throw $e;
} catch (Exception $e) {
$this->con->rollback();
throw $e;
}
}
}

View file

@ -1,11 +1,11 @@
<?php
class Application_Model_ServiceRegister {
public static function Register($p_componentName, $p_ipAddress){
class Application_Model_ServiceRegister
{
public static function Register($p_componentName, $p_ipAddress)
{
$component = CcServiceRegisterQuery::create()->findOneByDbName($p_componentName);
if ($component == NULL){
if ($component == NULL) {
$component = new CcServiceRegister();
$component->setDbName($p_componentName);
}
@ -14,7 +14,7 @@ class Application_Model_ServiceRegister {
// to allow access via an ipv6 address.
// http://[::1]:2812 does not respond.
// Bug: http://savannah.nongnu.org/bugs/?27608
if ($p_ipAddress == "::1"){
if ($p_ipAddress == "::1") {
$p_ipAddress = "127.0.0.1";
}

File diff suppressed because it is too large Load diff

View file

@ -3,8 +3,8 @@
require_once 'formatters/LengthFormatter.php';
require_once 'formatters/TimeFilledFormatter.php';
class Application_Model_ShowBuilder {
class Application_Model_ShowBuilder
{
private $timezone;
//in UTC timezone
@ -49,8 +49,8 @@ class Application_Model_ShowBuilder {
* @param DateTime $p_startsDT
* @param DateTime $p_endsDT
*/
public function __construct($p_startDT, $p_endDT, $p_opts) {
public function __construct($p_startDT, $p_endDT, $p_opts)
{
$this->startDT = $p_startDT;
$this->endDT = $p_endDT;
$this->timezone = date_default_timezone_get();
@ -60,25 +60,25 @@ class Application_Model_ShowBuilder {
$this->currentShow = false;
}
private function getUsersShows() {
private function getUsersShows()
{
$shows = array();
$host_shows = CcShowHostsQuery::create()
->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)
->filterByDbHost($this->user->getId())
->find();
foreach ($host_shows as $host_show) {
$shows[] = $host_show->getDbShow();
$host_shows = CcShowHostsQuery::create()
->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)
->filterByDbHost($this->user->getId())
->find();
foreach ($host_shows as $host_show) {
$shows[] = $host_show->getDbShow();
}
return $shows;
}
//check to see if this row should be editable by the user.
private function isAllowed($p_item, &$row) {
private function isAllowed($p_item, &$row)
{
//cannot schedule in a recorded show.
if (intval($p_item["si_record"]) === 1) {
return;
@ -89,7 +89,8 @@ class Application_Model_ShowBuilder {
}
}
private function getItemColor($p_item, &$row) {
private function getItemColor($p_item, &$row)
{
$defaultColor = "ffffff";
$defaultBackground = "3366cc";
@ -107,17 +108,16 @@ class Application_Model_ShowBuilder {
}
//information about whether a track is inside|boundary|outside a show.
private function getItemStatus($p_item, &$row) {
private function getItemStatus($p_item, &$row)
{
$row["status"] = intval($p_item["playout_status"]);
}
private function getRowTimestamp($p_item, &$row) {
private function getRowTimestamp($p_item, &$row)
{
if (is_null($p_item["si_last_scheduled"])) {
$ts = 0;
}
else {
} else {
$dt = new DateTime($p_item["si_last_scheduled"], new DateTimeZone("UTC"));
$ts = intval($dt->format("U"));
}
@ -130,41 +130,38 @@ class Application_Model_ShowBuilder {
* 1 = current
* 2 = future
*/
private function getScheduledStatus($p_epochItemStart, $p_epochItemEnd, &$row) {
private function getScheduledStatus($p_epochItemStart, $p_epochItemEnd, &$row)
{
if ($row["footer"] === true && $this->epoch_now > $p_epochItemStart && $this->epoch_now > $p_epochItemEnd) {
$row["scheduled"] = 0;
}
else if ($row["footer"] === true && $this->epoch_now < $p_epochItemEnd) {
$row["scheduled"] = 2;
}
else if ($row["header"] === true && $this->epoch_now >= $p_epochItemStart) {
} elseif ($row["footer"] === true && $this->epoch_now < $p_epochItemEnd) {
$row["scheduled"] = 2;
} elseif ($row["header"] === true && $this->epoch_now >= $p_epochItemStart) {
$row["scheduled"] = 0;
}
else if ($row["header"] === true && $this->epoch_now < $p_epochItemEnd) {
$row["scheduled"] = 2;
} elseif ($row["header"] === true && $this->epoch_now < $p_epochItemEnd) {
$row["scheduled"] = 2;
}
//item is in the past.
else if ($this->epoch_now > $p_epochItemEnd) {
$row["scheduled"] = 0;
}
//item is the currently scheduled item.
else if ($this->epoch_now >= $p_epochItemStart && $this->epoch_now < $p_epochItemEnd) {
$row["scheduled"] = 1;
//how many seconds the view should wait to redraw itself.
$row["refresh"] = $p_epochItemEnd - $this->epoch_now;
else if ($this->epoch_now > $p_epochItemEnd) {
$row["scheduled"] = 0;
}
//item is in the future.
else if ($this->epoch_now < $p_epochItemStart) {
$row["scheduled"] = 2;
}
//item is the currently scheduled item.
else if ($this->epoch_now >= $p_epochItemStart && $this->epoch_now < $p_epochItemEnd) {
$row["scheduled"] = 1;
//how many seconds the view should wait to redraw itself.
$row["refresh"] = $p_epochItemEnd - $this->epoch_now;
}
//item is in the future.
else if ($this->epoch_now < $p_epochItemStart) {
$row["scheduled"] = 2;
}
}
private function makeHeaderRow($p_item) {
private function makeHeaderRow($p_item)
{
$row = $this->defaultRowArray;
$this->isAllowed($p_item, $row);
$this->getRowTimestamp($p_item, $row);
@ -177,8 +174,8 @@ class Application_Model_ShowBuilder {
$showEndDT->setTimezone(new DateTimeZone($this->timezone));
$endsEpoch = floatval($showEndDT->format("U.u"));
//is a rebroadcast show
if (intval($p_item["si_rebroadcast"]) === 1) {
//is a rebroadcast show
if (intval($p_item["si_rebroadcast"]) === 1) {
$row["rebroadcast"] = true;
$parentInstance = CcShowInstancesQuery::create()->findPk($p_item["parent_show"]);
@ -187,15 +184,14 @@ class Application_Model_ShowBuilder {
$dt->setTimezone(new DateTimeZone($this->timezone));
$time = $dt->format("Y-m-d H:i");
$row["rebroadcast_title"] = "Rebroadcast of {$name} from {$time}";
}
else if (intval($p_item["si_record"]) === 1) {
$row["rebroadcast_title"] = "Rebroadcast of {$name} from {$time}";
} elseif (intval($p_item["si_record"]) === 1) {
$row["record"] = true;
if (Application_Model_Preference::GetUploadToSoundcloudOption()) {
$file = Application_Model_StoredFile::Recall($p_item["si_file_id"]);
if (isset($file)) {
$sid = $file->getSoundCloudId();
$sid = $file->getSoundCloudId();
$row["soundcloud_id"] = $sid;
}
}
@ -204,8 +200,7 @@ class Application_Model_ShowBuilder {
if ($startsEpoch < $this->epoch_now && $endsEpoch > $this->epoch_now) {
$row["currentShow"] = true;
$this->currentShow = true;
}
else {
} else {
$this->currentShow = false;
}
@ -229,7 +224,8 @@ class Application_Model_ShowBuilder {
return $row;
}
private function makeScheduledItemRow($p_item) {
private function makeScheduledItemRow($p_item)
{
$row = $this->defaultRowArray;
if (isset($p_item["sched_starts"])) {
@ -279,34 +275,33 @@ class Application_Model_ShowBuilder {
$showStartDT = new DateTime($p_item["si_starts"], new DateTimeZone("UTC"));
$showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC"));
$startsEpoch = floatval($showStartDT->format("U.u"));
$startsEpoch = floatval($showStartDT->format("U.u"));
$endsEpoch = floatval($showEndDT->format("U.u"));
$this->getScheduledStatus($startsEpoch, $endsEpoch, $row);
}
else {
} else {
$row["empty"] = true;
$row["id"] = 0 ;
$row["instance"] = intval($p_item["si_id"]);
}
if (intval($p_item["si_rebroadcast"]) === 1) {
$row["rebroadcast"] = true;
if (intval($p_item["si_rebroadcast"]) === 1) {
$row["rebroadcast"] = true;
}
if ($this->currentShow === true) {
$row["currentShow"] = true;
}
$this->getItemColor($p_item, $row);
$this->getRowTimestamp($p_item, $row);
$this->getItemColor($p_item, $row);
$this->getRowTimestamp($p_item, $row);
$this->isAllowed($p_item, $row);
return $row;
}
private function makeFooterRow($p_item) {
private function makeFooterRow($p_item)
{
$row = $this->defaultRowArray;
$row["footer"] = true;
$row["instance"] = intval($p_item["si_id"]);
@ -321,21 +316,21 @@ class Application_Model_ShowBuilder {
$timeFilled = new TimeFilledFormatter($runtime);
$row["fRuntime"] = $timeFilled->format();
$showStartDT = new DateTime($p_item["si_starts"], new DateTimeZone("UTC"));
$showStartDT->setTimezone(new DateTimeZone($this->timezone));
$startsEpoch = floatval($showStartDT->format("U.u"));
$showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC"));
$showEndDT->setTimezone(new DateTimeZone($this->timezone));
$showStartDT = new DateTime($p_item["si_starts"], new DateTimeZone("UTC"));
$showStartDT->setTimezone(new DateTimeZone($this->timezone));
$startsEpoch = floatval($showStartDT->format("U.u"));
$showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC"));
$showEndDT->setTimezone(new DateTimeZone($this->timezone));
$endsEpoch = floatval($showEndDT->format("U.u"));
$row["refresh"] = floatval($showEndDT->format("U.u")) - $this->epoch_now;
$row["refresh"] = floatval($showEndDT->format("U.u")) - $this->epoch_now;
if ($this->currentShow === true) {
$row["currentShow"] = true;
if ($this->currentShow === true) {
$row["currentShow"] = true;
}
$this->getScheduledStatus($startsEpoch, $endsEpoch, $row);
$this->isAllowed($p_item, $row);
$this->isAllowed($p_item, $row);
return $row;
}
@ -346,14 +341,14 @@ class Application_Model_ShowBuilder {
* @return boolean whether the schedule in the show builder's range has been updated.
*
*/
public function hasBeenUpdatedSince($timestamp, $instances) {
public function hasBeenUpdatedSince($timestamp, $instances)
{
$outdated = false;
$shows = Application_Model_Show::getShows($this->startDT, $this->endDT);
if ($this->opts["showFilter"] !== 0) {
$include[] = $this->opts["showFilter"];
}
else if ($this->opts["myShows"] === 1) {
} elseif ($this->opts["myShows"] === 1) {
$include = $this->getUsersShows();
}
@ -368,17 +363,16 @@ class Application_Model_ShowBuilder {
if (isset($show["last_scheduled"])) {
$dt = new DateTime($show["last_scheduled"], new DateTimeZone("UTC"));
}
else {
} else {
$dt = new DateTime($show["created"], new DateTimeZone("UTC"));
}
//check if any of the shows have a more recent timestamp.
$showTimeStamp = intval($dt->format("U"));
$showTimeStamp = intval($dt->format("U"));
if ($timestamp < $showTimeStamp) {
Logging::debug("timestamp is {$timestamp} show timestamp is {$showTimeStamp}");
$outdated = true;
break;
Logging::debug("timestamp is {$timestamp} show timestamp is {$showTimeStamp}");
$outdated = true;
break;
}
}
}
@ -392,8 +386,8 @@ class Application_Model_ShowBuilder {
return $outdated;
}
public function GetItems() {
public function GetItems()
{
$current_id = -1;
$display_items = array();
@ -401,8 +395,7 @@ class Application_Model_ShowBuilder {
if ($this->opts["myShows"] === 1) {
$shows = $this->getUsersShows();
}
else if ($this->opts["showFilter"] !== 0) {
} elseif ($this->opts["showFilter"] !== 0) {
$shows[] = $this->opts["showFilter"];
}
@ -439,9 +432,9 @@ class Application_Model_ShowBuilder {
if (isset($row)) {
$display_items[] = $row;
}
if ($current_id !== -1 && !in_array($current_id, $this->showInstances)) {
$this->showInstances[] = $current_id;
if ($current_id !== -1 && !in_array($current_id, $this->showInstances)) {
$this->showInstances[] = $current_id;
}
}

View file

@ -2,8 +2,8 @@
require_once 'formatters/LengthFormatter.php';
class Application_Model_ShowInstance {
class Application_Model_ShowInstance
{
private $_instanceId;
private $_showInstance;
@ -12,7 +12,7 @@ class Application_Model_ShowInstance {
$this->_instanceId = $instanceId;
$this->_showInstance = CcShowInstancesQuery::create()->findPK($instanceId);
if (is_null($this->_showInstance)){
if (is_null($this->_showInstance)) {
throw new Exception();
}
}
@ -27,11 +27,13 @@ class Application_Model_ShowInstance {
return $this->_instanceId;
}
public function getShow(){
public function getShow()
{
return new Application_Model_Show($this->getShowId());
}
public function deleteRebroadcasts(){
public function deleteRebroadcasts()
{
$con = Propel::getConnection();
$timestamp = gmdate("Y-m-d H:i:s");
@ -62,12 +64,14 @@ class Application_Model_ShowInstance {
public function getName()
{
$show = CcShowQuery::create()->findPK($this->getShowId());
return $show->getDbName();
}
public function getGenre()
{
$show = CcShowQuery::create()->findPK($this->getShowId());
return $show->getDbGenre();
}
@ -93,6 +97,7 @@ class Application_Model_ShowInstance {
{
$showStart = $this->getShowInstanceStart();
$showStartExplode = explode(" ", $showStart);
return $showStartExplode[0];
}
@ -113,6 +118,7 @@ class Application_Model_ShowInstance {
public function getSoundCloudFileId()
{
$file = Application_Model_StoredFile::Recall($this->_showInstance->getDbRecordedFile());
return $file->getSoundCloudId();
}
@ -174,7 +180,7 @@ class Application_Model_ShowInstance {
$diff = $showStartsEpoch - $scheduleStartsEpoch;
if ($diff != 0){
if ($diff != 0) {
$sql = "UPDATE cc_schedule"
." SET starts = starts + INTERVAL '$diff' second,"
." ends = ends + INTERVAL '$diff' second"
@ -199,8 +205,8 @@ class Application_Model_ShowInstance {
* @return $newDateTime
* php DateTime, $dateTime with the added time deltas.
*/
private static function addDeltas($dateTime, $deltaDay, $deltaMin) {
private static function addDeltas($dateTime, $deltaDay, $deltaMin)
{
$newDateTime = clone $dateTime;
$days = abs($deltaDay);
@ -211,15 +217,13 @@ class Application_Model_ShowInstance {
if ($deltaDay > 0) {
$newDateTime->add($dayInterval);
}
else if ($deltaDay < 0){
} elseif ($deltaDay < 0) {
$newDateTime->sub($dayInterval);
}
if ($deltaMin > 0) {
$newDateTime->add($minInterval);
}
else if ($deltaMin < 0) {
} elseif ($deltaMin < 0) {
$newDateTime->sub($minInterval);
}
@ -228,7 +232,7 @@ class Application_Model_ShowInstance {
public function moveShow($deltaDay, $deltaMin)
{
if ($this->getShow()->isRepeating()){
if ($this->getShow()->isRepeating()) {
return "Can't drag and drop repeating shows";
}
@ -286,6 +290,7 @@ class Application_Model_ShowInstance {
//recorded show doesn't exist.
catch (Exception $e) {
$this->_showInstance->delete();
return "Show was deleted because recorded show does not exist!";
}
@ -302,7 +307,7 @@ class Application_Model_ShowInstance {
$this->correctScheduleStartTimes();
$show = new Application_Model_Show($this->getShowId());
if(!$show->isRepeating() && is_null($this->isRebroadcast())){
if (!$show->isRepeating() && is_null($this->isRebroadcast())) {
$show->setShowFirstShow($newStartsDateTime);
$show->setShowLastShow($newEndsDateTime);
}
@ -317,7 +322,7 @@ class Application_Model_ShowInstance {
*/
public function resizeShow($deltaDay, $deltaMin)
{
$con = Propel::getConnection();
$con = Propel::getConnection();
$hours = $deltaMin/60;
if($hours > 0)
@ -331,7 +336,7 @@ class Application_Model_ShowInstance {
$starts = $this->getShowInstanceStart();
$ends = $this->getShowInstanceEnd();
if(strtotime($today_timestamp) > strtotime($starts)) {
if (strtotime($today_timestamp) > strtotime($starts)) {
return "can't resize a past show";
}
@ -346,14 +351,14 @@ class Application_Model_ShowInstance {
$overlap = Application_Model_Show::getShows($utcStartDateTime, $utcEndDateTime);
if(count($overlap) > 0) {
if (count($overlap) > 0) {
return "Should not overlap shows";
}
}
//with overbooking no longer need to check already scheduled content still fits.
//must update length of all rebroadcast instances.
if($this->isRecorded()) {
if ($this->isRecorded()) {
$sql = "UPDATE cc_show_instances SET ends = (ends + interval '{$deltaDay} days' + interval '{$hours}:{$mins}')
WHERE rebroadcast = 1 AND instance_id = {$this->_instanceId}";
$con->exec($sql);
@ -453,7 +458,7 @@ class Application_Model_ShowInstance {
->filterByDbRebroadcast(0)
->find();
if (is_null($showInstances)){
if (is_null($showInstances)) {
return true;
}
//only 1 show instance left of the show, make it non repeating.
@ -532,17 +537,15 @@ class Application_Model_ShowInstance {
->delete();
if ($this->checkToDeleteShow($showId)){
if ($this->checkToDeleteShow($showId)) {
CcShowQuery::create()
->filterByDbId($showId)
->delete();
}
}
else {
} else {
if ($this->isRebroadcast()) {
$this->_showInstance->delete();
}
else {
} else {
$show->delete();
}
}
@ -567,8 +570,7 @@ class Application_Model_ShowInstance {
try {
$rebroad = new Application_Model_ShowInstance($rebroadcast->getDbId());
$rebroad->addFileToShow($file_id, false);
}
catch (Exception $e) {
} catch (Exception $e) {
Logging::log("{$e->getFile()}");
Logging::log("{$e->getLine()}");
Logging::log("{$e->getMessage()}");
@ -586,8 +588,7 @@ class Application_Model_ShowInstance {
$time_arr[1] = "." . $time_arr[1];
$milliseconds = number_format(round($time_arr[1], 2), 2);
$time = $time_arr[0] . substr($milliseconds, 1);
}
else {
} else {
$time = $time_arr[0] . ".00";
}
} else {
@ -601,6 +602,7 @@ class Application_Model_ShowInstance {
public function getTimeScheduledSecs()
{
$time_filled = $this->getTimeScheduled();
return Application_Model_Playlist::playlistTimeToSeconds($time_filled);
}
@ -608,6 +610,7 @@ class Application_Model_ShowInstance {
{
$ends = $this->getShowInstanceEnd(null);
$starts = $this->getShowInstanceStart(null);
return intval($ends->format('U')) - intval($starts->format('U'));
}
@ -643,7 +646,7 @@ class Application_Model_ShowInstance {
public function getShowListContent()
{
$con = Propel::getConnection();
$con = Propel::getConnection();
$sql = "SELECT *
FROM (cc_schedule AS s LEFT JOIN cc_files AS f ON f.id = s.file_id)
@ -670,7 +673,7 @@ class Application_Model_ShowInstance {
public function getLastAudioItemEnd()
{
$con = Propel::getConnection();
$con = Propel::getConnection();
$sql = "SELECT ends FROM cc_schedule "
."WHERE instance_id = {$this->_instanceId} "
@ -678,14 +681,16 @@ class Application_Model_ShowInstance {
."LIMIT 1";
$query = $con->query($sql)->fetchColumn(0);
return ($query !== false) ? $query : NULL;
}
public function getShowEndGapTime(){
public function getShowEndGapTime()
{
$showEnd = $this->getShowInstanceEnd();
$lastItemEnd = $this->getLastAudioItemEnd();
if (is_null($lastItemEnd)){
if (is_null($lastItemEnd)) {
$lastItemEnd = $this->getShowInstanceStart();
}
@ -695,9 +700,10 @@ class Application_Model_ShowInstance {
return ($diff < 0) ? 0 : $diff;
}
public static function GetLastShowInstance($p_timeNow){
public static function GetLastShowInstance($p_timeNow)
{
global $CC_CONFIG;
$con = Propel::getConnection();
$con = Propel::getConnection();
$sql = "SELECT si.id"
." FROM $CC_CONFIG[showInstances] si"
@ -717,7 +723,7 @@ class Application_Model_ShowInstance {
public static function GetCurrentShowInstance($p_timeNow)
{
global $CC_CONFIG;
$con = Propel::getConnection();
$con = Propel::getConnection();
/* Orderby si.starts descending, because in some cases
* we can have multiple shows overlapping each other. In
@ -744,7 +750,7 @@ class Application_Model_ShowInstance {
public static function GetNextShowInstance($p_timeNow)
{
global $CC_CONFIG;
$con = Propel::getConnection();
$con = Propel::getConnection();
$sql = "SELECT si.id"
." FROM $CC_CONFIG[showInstances] si"
@ -767,6 +773,7 @@ class Application_Model_ShowInstance {
global $CC_CONFIG;
$con = Propel::getConnection();
$sql = "SELECT count(*) as cnt FROM $CC_CONFIG[showInstances] WHERE ends < '$day'";
return $con->query($sql)->fetchColumn(0);
}
@ -774,7 +781,7 @@ class Application_Model_ShowInstance {
public static function GetEndTimeOfNextShowWithLiveDJ($p_startTime, $p_endTime)
{
global $CC_CONFIG;
$con = Propel::getConnection();
$con = Propel::getConnection();
$sql = "SELECT ends
FROM cc_show_instances as si
@ -785,10 +792,11 @@ class Application_Model_ShowInstance {
return $con->query($sql)->fetchAll();
}
function isRepeating(){
if ($this->getShow()->isRepeating()){
public function isRepeating()
{
if ($this->getShow()->isRepeating()) {
return true;
}else{
} else {
return false;
}
}

View file

@ -1,8 +1,8 @@
<?php
require_once 'soundcloud-api/Services/Soundcloud.php';
class Application_Model_Soundcloud {
class Application_Model_Soundcloud
{
private $_soundcloud;
public function __construct()
@ -24,13 +24,11 @@ class Application_Model_Soundcloud {
public function uploadTrack($filepath, $filename, $description, $tags=array(), $release=null, $genre=null)
{
if($this->getToken())
{
if(count($tags)) {
if ($this->getToken()) {
if (count($tags)) {
$tags = join(" ", $tags);
$tags = $tags." ".Application_Model_Preference::GetSoundCloudTags();
}
else {
} else {
$tags = Application_Model_Preference::GetSoundCloudTags();
}
@ -46,7 +44,7 @@ class Application_Model_Soundcloud {
);
if(isset($release)) {
if (isset($release)) {
$release = str_replace(" ", "-", $release);
$release = str_replace(":", "-", $release);
@ -60,8 +58,7 @@ class Application_Model_Soundcloud {
if (isset($genre) && $genre != "") {
$track_data['track[genre]'] = $genre;
}
else {
} else {
$default_genre = Application_Model_Preference::GetSoundCloudGenre();
if ($default_genre != "") {
$track_data['track[genre]'] = $default_genre;

View file

@ -13,8 +13,8 @@ require_once 'formatters/BitrateFormatter.php';
* @license http://www.gnu.org/licenses/gpl.txt
* @see MetaData
*/
class Application_Model_StoredFile {
class Application_Model_StoredFile
{
/**
* @holds propel database object
*/
@ -60,7 +60,8 @@ class Application_Model_StoredFile {
return $this->_file->getDbId();
}
public function getGunId() {
public function getGunId()
{
return $this->_file->getDbGunid();
}
@ -69,7 +70,8 @@ class Application_Model_StoredFile {
return $this->_file->getDbFtype();
}
public function getPropelOrm(){
public function getPropelOrm()
{
return $this->_file;
}
@ -88,11 +90,10 @@ class Application_Model_StoredFile {
{
if (is_null($p_md)) {
$this->setDbColMetadata();
}
else {
} else {
$dbMd = array();
if (isset($p_md["MDATA_KEY_YEAR"])){
if (isset($p_md["MDATA_KEY_YEAR"])) {
// We need to make sure to clean this value before inserting into database.
// If value is outside of range [-2^31, 2^31-1] then postgresl will throw error
// when trying to retrieve this value. We could make sure number is within these bounds,
@ -103,17 +104,17 @@ class Application_Model_StoredFile {
$year = $p_md["MDATA_KEY_YEAR"];
if (strlen($year) > 4){
if (strlen($year) > 4) {
$year = substr($year, 0, 4);
}
if (!is_numeric($year)){
if (!is_numeric($year)) {
$year = 0;
}
$p_md["MDATA_KEY_YEAR"] = $year;
}
foreach ($p_md as $mdConst => $mdValue) {
if (defined($mdConst)){
if (defined($mdConst)) {
$dbMd[constant($mdConst)] = $mdValue;
}
}
@ -137,11 +138,10 @@ class Application_Model_StoredFile {
$method = "set$propelColumn";
$this->_file->$method(null);
}
}
else {
} else {
foreach ($p_md as $dbColumn => $mdValue) {
//don't blank out name, defaults to original filename on first insertion to database.
if($dbColumn == "track_title" && (is_null($mdValue) || $mdValue == "")) {
if ($dbColumn == "track_title" && (is_null($mdValue) || $mdValue == "")) {
continue;
}
if (isset($this->_dbMD[$dbColumn])) {
@ -183,7 +183,7 @@ class Application_Model_StoredFile {
public function setDbColMetadataValue($p_category, $p_value)
{
//don't blank out name, defaults to original filename on first insertion to database.
if($p_category == "track_title" && (is_null($p_value) || $p_value == "")) {
if ($p_category == "track_title" && (is_null($p_value) || $p_value == "")) {
return;
}
if (isset($this->_dbMD[$p_category])) {
@ -197,7 +197,7 @@ class Application_Model_StoredFile {
/**
* Get one metadata value.
*
* @param string $p_category (MDATA_KEY_URL)
* @param string $p_category (MDATA_KEY_URL)
* @return string
*/
public function getMetadataValue($p_category)
@ -210,13 +210,14 @@ class Application_Model_StoredFile {
/**
* Get one metadata value.
*
* @param string $p_category (url)
* @param string $p_category (url)
* @return string
*/
public function getDbColMetadataValue($p_category)
{
$propelColumn = $this->_dbMD[$p_category];
$method = "get$propelColumn";
return $this->_file->$method();
}
@ -290,6 +291,7 @@ class Application_Model_StoredFile {
$res = $con->exec($sql);
$this->state = $p_state;
$this->editedby = $p_editedby;
return TRUE;
}
@ -297,7 +299,8 @@ class Application_Model_StoredFile {
* Returns an array of playlist objects that this file is a part of.
* @return array
*/
public function getPlaylists() {
public function getPlaylists()
{
global $CC_CONFIG;
$con = Propel::getConnection();
$sql = "SELECT playlist_id "
@ -310,6 +313,7 @@ class Application_Model_StoredFile {
$playlists[] = Application_Model_Playlist::Recall($id);
}
}
return $playlists;
}
@ -336,7 +340,7 @@ class Application_Model_StoredFile {
Application_Model_RabbitMq::SendMessageToMediaMonitor("file_delete", $data);
}
if ($deleteFromPlaylist){
if ($deleteFromPlaylist) {
Application_Model_Playlist::DeleteFileFromAllPlaylists($this->getId());
}
// set file_exists falg to false
@ -355,7 +359,7 @@ class Application_Model_StoredFile {
{
$filepath = $this->getFilePath();
if ($deleteFromPlaylist){
if ($deleteFromPlaylist) {
Application_Model_Playlist::DeleteFileFromAllPlaylists($this->getId());
}
// set file_exists falg to false
@ -375,8 +379,7 @@ class Application_Model_StoredFile {
if ($mime == "audio/vorbis" || $mime == "application/ogg") {
return "ogg";
}
else if ($mime == "audio/mp3" || $mime == "audio/mpeg") {
} elseif ($mime == "audio/mp3" || $mime == "audio/mpeg") {
return "mp3";
}
}
@ -432,16 +435,17 @@ class Application_Model_StoredFile {
* is specified in the airtime.conf config file. If either of these is
* not specified, then use values provided by the $_SERVER global variable.
*/
public function getFileUrlUsingConfigAddress(){
public function getFileUrlUsingConfigAddress()
{
global $CC_CONFIG;
if (isset($CC_CONFIG['baseUrl'])){
if (isset($CC_CONFIG['baseUrl'])) {
$serverName = $CC_CONFIG['baseUrl'];
} else {
$serverName = $_SERVER['SERVER_NAME'];
}
if (isset($CC_CONFIG['basePort'])){
if (isset($CC_CONFIG['basePort'])) {
$serverPort = $CC_CONFIG['basePort'];
} else {
$serverPort = $_SERVER['SERVER_PORT'];
@ -450,8 +454,10 @@ class Application_Model_StoredFile {
return $this->constructGetFileUrl($serverName, $serverPort);
}
private function constructGetFileUrl($p_serverName, $p_serverPort){
private function constructGetFileUrl($p_serverName, $p_serverPort)
{
Logging::log("getting media! - 2");
return "http://$p_serverName:$p_serverPort/api/get-media/file/".$this->getGunId().".".$this->getFileExtension();
}
@ -462,6 +468,7 @@ Logging::log("getting media! - 2");
public function getRelativeFileUrl($baseUrl)
{
Logging::log("getting media!");
return $baseUrl."/api/get-media/file/".$this->getGunId().".".$this->getFileExtension();
}
@ -475,19 +482,18 @@ Logging::log("getting media! - 2");
$storedFile = new Application_Model_StoredFile();
$storedFile->_file = $file;
if(isset($md['MDATA_KEY_FILEPATH'])) {
if (isset($md['MDATA_KEY_FILEPATH'])) {
// removed "//" in the path. Always use '/' for path separator
$filepath = str_replace("//", "/", $md['MDATA_KEY_FILEPATH']);
$res = $storedFile->setFilePath($filepath);
if ($res === -1) {
return null;
}
}
else {
} else {
return null;
}
if(isset($md)) {
if (isset($md)) {
$storedFile->setMetadata($md);
}
@ -514,25 +520,22 @@ Logging::log("getting media! - 2");
{
if (isset($p_id)) {
$file = CcFilesQuery::create()->findPK(intval($p_id));
}
else if (isset($p_gunid)) {
} elseif (isset($p_gunid)) {
$file = CcFilesQuery::create()
->filterByDbGunid($p_gunid)
->findOne();
}
else if (isset($p_md5sum)) {
if($exist){
} elseif (isset($p_md5sum)) {
if ($exist) {
$file = CcFilesQuery::create()
->filterByDbMd5($p_md5sum)
->filterByDbFileExists(true)
->findOne();
}else{
} else {
$file = CcFilesQuery::create()
->filterByDbMd5($p_md5sum)
->findOne();
}
}
else if (isset($p_filepath)) {
} elseif (isset($p_filepath)) {
$path_info = Application_Model_MusicDir::splitFilePath($p_filepath);
if (is_null($path_info)) {
@ -544,8 +547,7 @@ Logging::log("getting media! - 2");
->filterByDbDirectory($music_dir->getId())
->filterByDbFilepath($path_info[1])
->findOne();
}
else {
} else {
return null;
}
@ -554,14 +556,15 @@ Logging::log("getting media! - 2");
$storedFile->_file = $file;
return $storedFile;
}
else {
} else {
return null;
}
}
public function getName(){
public function getName()
{
$info = pathinfo($this->getFilePath());
return $info['filename'];
}
@ -582,7 +585,7 @@ Logging::log("getting media! - 2");
/**
* Fetch the Application_Model_StoredFile by looking up the MD5 value.
*
* @param string $p_md5sum
* @param string $p_md5sum
* @return Application_Model_StoredFile|NULL
*/
public static function RecallByMd5($p_md5sum, $exist=false)
@ -593,7 +596,7 @@ Logging::log("getting media! - 2");
/**
* Fetch the Application_Model_StoredFile by looking up its filepath.
*
* @param string $p_filepath path of file stored in Airtime.
* @param string $p_filepath path of file stored in Airtime.
* @return Application_Model_StoredFile|NULL
*/
public static function RecallByFilepath($p_filepath)
@ -601,7 +604,8 @@ Logging::log("getting media! - 2");
return Application_Model_StoredFile::Recall(null, null, null, $p_filepath);
}
public static function RecallByPartialFilepath($partial_path){
public static function RecallByPartialFilepath($partial_path)
{
$path_info = Application_Model_MusicDir::splitFilePath($partial_path);
if (is_null($path_info)) {
@ -614,16 +618,17 @@ Logging::log("getting media! - 2");
->filterByDbFilepath("$path_info[1]%")
->find();
$res = array();
foreach ($files as $file){
foreach ($files as $file) {
$storedFile = new Application_Model_StoredFile();
$storedFile->_file = $file;
$res[] = $storedFile;
}
return $res;
}
public static function searchLibraryFiles($datatables) {
public static function searchLibraryFiles($datatables)
{
$con = Propel::getConnection(CcFilesPeer::DATABASE_NAME);
$displayColumns = array("id", "track_title", "artist_name", "album_title", "genre", "length",
@ -639,35 +644,30 @@ Logging::log("getting media! - 2");
if ($key === "id") {
$plSelect[] = "PL.id AS ".$key;
$fileSelect[] = $key;
}
else if ($key === "track_title") {
} elseif ($key === "track_title") {
$plSelect[] = "name AS ".$key;
$fileSelect[] = $key;
}
else if ($key === "ftype") {
} elseif ($key === "ftype") {
$plSelect[] = "'playlist'::varchar AS ".$key;
$fileSelect[] = $key;
}
else if ($key === "artist_name") {
} elseif ($key === "artist_name") {
$plSelect[] = "login AS ".$key;
$fileSelect[] = $key;
}
//same columns in each table.
else if(in_array($key, array("length", "utime", "mtime"))) {
else if (in_array($key, array("length", "utime", "mtime"))) {
$plSelect[] = $key;
$fileSelect[] = $key;
}
else if ($key === "year") {
} elseif ($key === "year") {
$plSelect[] = "EXTRACT(YEAR FROM utime)::varchar AS ".$key;
$fileSelect[] = "year AS ".$key;
}
//need to cast certain data as ints for the union to search on.
else if (in_array($key, array("track_number", "bit_rate", "sample_rate"))){
else if (in_array($key, array("track_number", "bit_rate", "sample_rate"))) {
$plSelect[] = "NULL::int AS ".$key;
$fileSelect[] = $key;
}
else {
} else {
$plSelect[] = "NULL::text AS ".$key;
$fileSelect[] = $key;
}
@ -725,11 +725,10 @@ Logging::log("getting media! - 2");
//datatable stuff really needs to be pulled out and generalized within the project
//access to zend view methods to access url helpers is needed.
if($type == "au"){//&& isset( $audioResults )) {
if ($type == "au") {//&& isset( $audioResults )) {
$row['audioFile'] = $row['gunid'].".".pathinfo($row['filepath'], PATHINFO_EXTENSION);
$row['image'] = '<img title="Track preview" src="/css/images/icon_audioclip.png">';
}
else {
} else {
$row['image'] = '<img title="Playlist preview" src="/css/images/icon_playlist.png">';
}
}
@ -839,7 +838,8 @@ Logging::log("getting media! - 2");
* Check, using disk_free_space, the space available in the $destination_folder folder to see if it has
* enough space to move the $audio_file into and report back to the user if not.
**/
public static function isEnoughDiskSpaceToCopy($destination_folder, $audio_file){
public static function isEnoughDiskSpaceToCopy($destination_folder, $audio_file)
{
//check to see if we have enough space in the /organize directory to copy the file
$freeSpace = disk_free_space($destination_folder);
$fileSize = filesize($audio_file);
@ -847,7 +847,8 @@ Logging::log("getting media! - 2");
return $freeSpace >= $fileSize;
}
public static function copyFileToStor($p_targetDir, $fileName, $tempname){
public static function copyFileToStor($p_targetDir, $fileName, $tempname)
{
$audio_file = $p_targetDir . DIRECTORY_SEPARATOR . $tempname;
Logging::log('copyFileToStor: moving file '.$audio_file);
$md5 = md5_file($audio_file);
@ -861,26 +862,27 @@ Logging::log("getting media! - 2");
}
}
if (!isset($result)){//The file has no duplicate, so proceed to copy.
if (!isset($result)) {//The file has no duplicate, so proceed to copy.
$storDir = Application_Model_MusicDir::getStorDir();
$stor = $storDir->getDirectory();
// check if "organize" dir exists and if not create one
if(!file_exists($stor."/organize")){
if(!mkdir($stor."/organize", 0777)){
if (!file_exists($stor."/organize")) {
if (!mkdir($stor."/organize", 0777)) {
$result = array("code" => 109, "message" => "Failed to create 'organize' directory.");
return $result;
}
}
if (chmod($audio_file, 0644) === false){
if (chmod($audio_file, 0644) === false) {
Logging::log("Warning: couldn't change permissions of $audio_file to 0644");
}
//check to see if there is enough space in $stor to continue.
if (self::isEnoughDiskSpaceToCopy($stor, $audio_file)){
if (self::isEnoughDiskSpaceToCopy($stor, $audio_file)) {
$audio_stor = Application_Common_OsPath::join($stor, "organize", $fileName);
if (self::liquidsoapFilePlayabilityTest($audio_file)){
if (self::liquidsoapFilePlayabilityTest($audio_file)) {
Logging::log("copyFileToStor: moving file $audio_file to $audio_stor");
@ -899,14 +901,15 @@ Logging::log("getting media! - 2");
$result = array("code" => 107, "message" => "The file was not uploaded, there is ".$freeSpace."MB of disk space left and the file you are uploading has a size of ".$fileSize."MB.");
}
}
return $result;
}
/*
* Pass the file through Liquidsoap and test if it is readable. Return True if readable, and False otherwise.
*/
public static function liquidsoapFilePlayabilityTest($audio_file){
public static function liquidsoapFilePlayabilityTest($audio_file)
{
$LIQUIDSOAP_ERRORS = array('TagLib: MPEG::Properties::read() -- Could not find a valid last MPEG frame in the stream.');
// Ask Liquidsoap if file is playable
@ -915,15 +918,17 @@ Logging::log("getting media! - 2");
exec($command, $output, $rv);
$isError = count($output) > 0 && in_array($output[0], $LIQUIDSOAP_ERRORS);
return ($rv == 0 && !$isError);
}
public static function getFileCount()
{
global $CC_CONFIG;
$con = Propel::getConnection();
$con = Propel::getConnection();
$sql = "SELECT count(*) as cnt FROM ".$CC_CONFIG["filesTable"]." WHERE file_exists";
return $con->query($sql)->fetchColumn(0);
}
@ -935,7 +940,7 @@ Logging::log("getting media! - 2");
*/
public static function listAllFiles($dir_id=null, $propelObj=false)
{
$con = Propel::getConnection();
$con = Propel::getConnection();
if ($propelObj) {
$sql = "SELECT m.directory || f.filepath as fp"
@ -960,7 +965,7 @@ Logging::log("getting media! - 2");
return $results;
}
//TODO: MERGE THIS FUNCTION AND "listAllFiles" -MK
public static function listAllFiles2($dir_id=null, $limit=null)
{
@ -970,12 +975,13 @@ Logging::log("getting media! - 2");
." FROM CC_FILES"
." WHERE directory = $dir_id"
." AND file_exists = 'TRUE'";
if (!is_null($limit) && is_int($limit)){
if (!is_null($limit) && is_int($limit)) {
$sql .= " LIMIT $limit";
}
$rows = $con->query($sql, PDO::FETCH_ASSOC);
return $rows;
}
@ -993,6 +999,7 @@ Logging::log("getting media! - 2");
." (soundcloud_upload_time >= (now() - (INTERVAL '1 day')))";
$rows = $con->query($sql)->fetchAll();
return count($rows);
} catch (Exception $e) {
header('HTTP/1.0 503 Service Unavailable');
@ -1008,7 +1015,8 @@ Logging::log("getting media! - 2");
->save();
}
public function getSoundCloudLinkToFile(){
public function getSoundCloudLinkToFile()
{
return $this->_file->getDbSoundCloudLinkToFile();
}
@ -1018,42 +1026,51 @@ Logging::log("getting media! - 2");
->save();
}
public function getSoundCloudId(){
public function getSoundCloudId()
{
return $this->_file->getDbSoundCloudId();
}
public function setSoundCloudErrorCode($code){
public function setSoundCloudErrorCode($code)
{
$this->_file->setDbSoundCloudErrorCode($code)
->save();
}
public function getSoundCloudErrorCode(){
public function getSoundCloudErrorCode()
{
return $this->_file->getDbSoundCloudErrorCode();
}
public function setSoundCloudErrorMsg($msg){
public function setSoundCloudErrorMsg($msg)
{
$this->_file->setDbSoundCloudErrorMsg($msg)
->save();
}
public function getSoundCloudErrorMsg(){
public function getSoundCloudErrorMsg()
{
return $this->_file->getDbSoundCloudErrorMsg();
}
public function getDirectory(){
public function getDirectory()
{
return $this->_file->getDbDirectory();
}
public function setFileExistsFlag($flag){
public function setFileExistsFlag($flag)
{
$this->_file->setDbFileExists($flag)
->save();
}
public function setSoundCloudUploadTime($time){
public function setSoundCloudUploadTime($time)
{
$this->_file->setDbSoundCloundUploadTime($time)
->save();
}
public function getFileExistsFlag(){
public function getFileExistsFlag()
{
return $this->_file->getDbFileExists();
}
@ -1062,12 +1079,11 @@ Logging::log("getting media! - 2");
global $CC_CONFIG;
$file = $this->_file;
if(is_null($file)) {
if (is_null($file)) {
return "File does not exist";
}
if(Application_Model_Preference::GetUploadToSoundcloudOption())
{
for($i=0; $i<$CC_CONFIG['soundcloud-connection-retries']; $i++) {
if (Application_Model_Preference::GetUploadToSoundcloudOption()) {
for ($i=0; $i<$CC_CONFIG['soundcloud-connection-retries']; $i++) {
$description = $file->getDbTrackTitle();
$tag = array();
$genre = $file->getDbGenre();
@ -1079,8 +1095,7 @@ Logging::log("getting media! - 2");
$this->setSoundCloudLinkToFile($soundcloud_res['permalink_url']);
$this->setSoundCloudUploadTime(new DateTime("now"), new DateTimeZone("UTC"));
break;
}
catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
$code = $e->getHttpCode();
$msg = $e->getHttpBody();
$temp = explode('"error":',$msg);
@ -1089,7 +1104,7 @@ Logging::log("getting media! - 2");
$this->setSoundCloudErrorMsg($msg);
// setting sc id to -3 which indicates error
$this->setSoundCloudFileId(SOUNDCLOUD_ERROR);
if(!in_array($code, array(0, 100))) {
if (!in_array($code, array(0, 100))) {
break;
}
}

View file

@ -1,6 +1,6 @@
<?php
class Application_Model_StreamSetting {
class Application_Model_StreamSetting
{
public static function setValue($key, $value, $type)
{
global $CC_CONFIG;
@ -30,7 +30,7 @@ class Application_Model_StreamSetting {
public static function getValue($key)
{
global $CC_CONFIG;
$con = Propel::getConnection();
$con = Propel::getConnection();
//Check if key already exists
$sql = "SELECT COUNT(*) FROM cc_stream_setting"
@ -44,6 +44,7 @@ class Application_Model_StreamSetting {
." WHERE keyname = '$key'";
$result = $con->query($sql)->fetchColumn(0);
return ($result !== false) ? $result : null;
}
}
@ -120,11 +121,11 @@ class Application_Model_StreamSetting {
foreach ($rows as $r) {
if ($r['keyname'] == 'master_live_stream_port') {
$exists['master_live_stream_port'] = true;
} elseif($r['keyname'] == 'master_live_stream_mp') {
} elseif ($r['keyname'] == 'master_live_stream_mp') {
$exists['master_live_stream_mp'] = true;
} elseif($r['keyname'] == 'dj_live_stream_port') {
} elseif ($r['keyname'] == 'dj_live_stream_port') {
$exists['dj_live_stream_port'] = true;
} elseif($r['keyname'] == 'dj_live_stream_mp') {
} elseif ($r['keyname'] == 'dj_live_stream_mp') {
$exists['dj_live_stream_mp'] = true;
}
}
@ -149,6 +150,7 @@ class Application_Model_StreamSetting {
"value"=>self::getDjLiveStreamMountPoint(),
"type"=>"string");
}
return $rows;
}
@ -168,10 +170,10 @@ class Application_Model_StreamSetting {
$v = $d == 1?"true":"false";
$sql = "UPDATE cc_stream_setting SET value='$v' WHERE keyname='$key'";
$con->exec($sql);
} else if ($key == "output_sound_device_type") {
} elseif ($key == "output_sound_device_type") {
$sql = "UPDATE cc_stream_setting SET value='$d' WHERE keyname='$key'";
$con->exec($sql);
} else if (is_array($d)) {
} elseif (is_array($d)) {
$temp = explode('_', $key);
$prefix = $temp[0];
foreach ($d as $k => $v) {
@ -198,7 +200,7 @@ class Application_Model_StreamSetting {
*/
public static function setIndivisualStreamSetting($data)
{
$con = Propel::getConnection();
$con = Propel::getConnection();
foreach ($data as $keyname => $v) {
$sql = "UPDATE cc_stream_setting SET value='$v' WHERE keyname='$keyname'";
@ -212,7 +214,7 @@ class Application_Model_StreamSetting {
*/
public static function setLiquidsoapError($stream_id, $msg, $boot_time=null)
{
$con = Propel::getConnection();
$con = Propel::getConnection();
$update_time = Application_Model_Preference::GetStreamUpdateTimestemp();
if ($boot_time == null || $boot_time > $update_time) {
@ -234,7 +236,7 @@ class Application_Model_StreamSetting {
public static function getLiquidsoapError($stream_id)
{
$con = Propel::getConnection();
$con = Propel::getConnection();
$keyname = "s".$stream_id."_liquidsoap_error";
$sql = "SELECT value FROM cc_stream_setting"
@ -246,7 +248,7 @@ class Application_Model_StreamSetting {
public static function getStreamEnabled($stream_id)
{
$con = Propel::getConnection();
$con = Propel::getConnection();
$keyname = "s" . $stream_id . "_enable";
$sql = "SELECT value FROM cc_stream_setting"
@ -257,6 +259,7 @@ class Application_Model_StreamSetting {
} else {
$result = true;
}
return $result;
}
@ -266,7 +269,7 @@ class Application_Model_StreamSetting {
*/
public static function getStreamInfoForDataCollection()
{
$con = Propel::getConnection();
$con = Propel::getConnection();
$out = array();
$enabled_stream = self::getEnabledStreamIds();
@ -286,6 +289,7 @@ class Application_Model_StreamSetting {
$out[$stream] = $info;
}
}
return $out;
}

View file

@ -14,8 +14,8 @@ define('ALIBERR_BADSMEMB', 21);
* @copyright 2010 Sourcefabric O.P.S.
* @license http://www.gnu.org/licenses/gpl.txt
*/
class Application_Model_Subjects {
class Application_Model_Subjects
{
/* ======================================================= public methods */
public static function increaseLoginAttempts($login)
@ -25,6 +25,7 @@ class Application_Model_Subjects {
$sql = "UPDATE ".$CC_CONFIG['subjTable']." SET login_attempts = login_attempts+1"
." WHERE login='$login'";
$res = $con->exec($sql);
return (intval($res) > 0);
}
@ -35,6 +36,7 @@ class Application_Model_Subjects {
$sql = "UPDATE ".$CC_CONFIG['subjTable']." SET login_attempts = '0'"
." WHERE login='$login'";
$res = $con->exec($sql);
return true;
}
@ -44,8 +46,8 @@ class Application_Model_Subjects {
$con = Propel::getConnection();
$sql = "SELECT login_attempts FROM ".$CC_CONFIG['subjTable']." WHERE login='$login'";
$res = $con->query($sql)->fetchColumn(0);
return ($res !== false) ? $res : 0;
}
} // class Subjects

View file

@ -3,7 +3,8 @@
class Application_Model_Systemstatus
{
public static function GetMonitStatus($p_ip){
public static function GetMonitStatus($p_ip)
{
global $CC_CONFIG;
$monit_user = $CC_CONFIG['monit_user'];
$monit_password = $CC_CONFIG['monit_password'];
@ -22,8 +23,8 @@ class Application_Model_Systemstatus
curl_close($ch);
$docRoot = null;
if ($result !== FALSE && $info["http_code"] === 200){
if ($result != ""){
if ($result !== FALSE && $info["http_code"] === 200) {
if ($result != "") {
$xmlDoc = new DOMDocument();
$xmlDoc->loadXML($result);
$docRoot = $xmlDoc->documentElement;
@ -33,8 +34,8 @@ class Application_Model_Systemstatus
return $docRoot;
}
public static function ExtractServiceInformation($p_docRoot, $p_serviceName){
public static function ExtractServiceInformation($p_docRoot, $p_serviceName)
{
$starting = array(
"name"=>"",
"process_id"=>"STARTING...",
@ -65,76 +66,75 @@ class Application_Model_Systemstatus
);
$data = $notRunning;
if (!is_null($p_docRoot)){
foreach ($p_docRoot->getElementsByTagName("service") AS $item)
{
if ($item->getElementsByTagName("name")->item(0)->nodeValue == $p_serviceName){
if (!is_null($p_docRoot)) {
foreach ($p_docRoot->getElementsByTagName("service") AS $item) {
if ($item->getElementsByTagName("name")->item(0)->nodeValue == $p_serviceName) {
$monitor = $item->getElementsByTagName("monitor");
if ($monitor->length > 0){
if ($monitor->length > 0) {
$status = $monitor->item(0)->nodeValue;
if ($status == "2"){
if ($status == "2") {
$data = $starting;
} else if ($status == 1){
} elseif ($status == 1) {
//is monitored, but is it running?
$pid = $item->getElementsByTagName("pid");
if ($pid->length == 0){
if ($pid->length == 0) {
$data = $notRunning;
} else {
//running!
}
} else if ($status == 0){
} elseif ($status == 0) {
$data = $notMonitored;
}
}
$process_id = $item->getElementsByTagName("name");
if ($process_id->length > 0){
if ($process_id->length > 0) {
$data["name"] = $process_id->item(0)->nodeValue;
}
$process_id = $item->getElementsByTagName("pid");
if ($process_id->length > 0){
if ($process_id->length > 0) {
$data["process_id"] = $process_id->item(0)->nodeValue;
$data["status"] = 0;
}
$uptime = $item->getElementsByTagName("uptime");
if ($uptime->length > 0){
if ($uptime->length > 0) {
$data["uptime_seconds"] = $uptime->item(0)->nodeValue;
}
$memory = $item->getElementsByTagName("memory");
if ($memory->length > 0){
if ($memory->length > 0) {
$data["memory_perc"] = $memory->item(0)->getElementsByTagName("percenttotal")->item(0)->nodeValue."%";
$data["memory_kb"] = $memory->item(0)->getElementsByTagName("kilobytetotal")->item(0)->nodeValue;
}
$cpu = $item->getElementsByTagName("cpu");
if ($cpu->length > 0){
if ($cpu->length > 0) {
$data["cpu_perc"] = $cpu->item(0)->getElementsByTagName("percent")->item(0)->nodeValue."%";
}
break;
}
}
}
return $data;
}
public static function GetPlatformInfo(){
public static function GetPlatformInfo()
{
$keys = array("release", "machine", "memory", "swap");
foreach($keys as $key) {
foreach ($keys as $key) {
$data[$key] = "UNKNOWN";
}
$docRoot = self::GetMonitStatus("localhost");
if (!is_null($docRoot)){
foreach ($docRoot->getElementsByTagName("platform") AS $item)
{
foreach($keys as $key) {
if (!is_null($docRoot)) {
foreach ($docRoot->getElementsByTagName("platform") AS $item) {
foreach ($keys as $key) {
$keyElement = $item->getElementsByTagName($key);
if($keyElement->length > 0) {
if ($keyElement->length > 0) {
$data[$key] = $keyElement->item(0)->nodeValue;
}
}
@ -144,10 +144,10 @@ class Application_Model_Systemstatus
return $data;
}
public static function GetPypoStatus(){
public static function GetPypoStatus()
{
$component = CcServiceRegisterQuery::create()->findOneByDbName("pypo");
if (is_null($component)){
if (is_null($component)) {
return null;
} else {
$ip = $component->getDbIp();
@ -159,10 +159,10 @@ class Application_Model_Systemstatus
}
}
public static function GetLiquidsoapStatus(){
public static function GetLiquidsoapStatus()
{
$component = CcServiceRegisterQuery::create()->findOneByDbName("pypo");
if (is_null($component)){
if (is_null($component)) {
return null;
} else {
$ip = $component->getDbIp();
@ -174,10 +174,10 @@ class Application_Model_Systemstatus
}
}
public static function GetMediaMonitorStatus(){
public static function GetMediaMonitorStatus()
{
$component = CcServiceRegisterQuery::create()->findOneByDbName("media-monitor");
if (is_null($component)){
if (is_null($component)) {
return null;
} else {
$ip = $component->getDbIp();
@ -189,16 +189,17 @@ class Application_Model_Systemstatus
}
}
public static function GetIcecastStatus(){
public static function GetIcecastStatus()
{
$docRoot = self::GetMonitStatus("localhost");
$data = self::ExtractServiceInformation($docRoot, "icecast2");
return $data;
}
public static function GetRabbitMqStatus(){
if (isset($_SERVER["RABBITMQ_HOST"])){
public static function GetRabbitMqStatus()
{
if (isset($_SERVER["RABBITMQ_HOST"])) {
$rabbitmq_host = $_SERVER["RABBITMQ_HOST"];
} else {
$rabbitmq_host = "localhost";
@ -209,10 +210,11 @@ class Application_Model_Systemstatus
return $data;
}
public static function GetDiskInfo(){
public static function GetDiskInfo()
{
$partions = array();
if (isset($_SERVER['AIRTIME_SRV'])){
if (isset($_SERVER['AIRTIME_SRV'])) {
//connect to DB and find how much total space user has allocated.
$totalSpace = Application_Model_Preference::GetDiskQuota();
@ -229,10 +231,10 @@ class Application_Model_Systemstatus
$musicDirs = Application_Model_MusicDir::getWatchedDirs();
$musicDirs[] = Application_Model_MusicDir::getStorDir();
foreach($musicDirs as $md){
foreach ($musicDirs as $md) {
$totalSpace = disk_total_space($md->getDirectory());
if (!isset($partitions[$totalSpace])){
if (!isset($partitions[$totalSpace])) {
$partitions[$totalSpace] = new StdClass;
$partitions[$totalSpace]->totalSpace = $totalSpace;
$partitions[$totalSpace]->totalFreeSpace = disk_free_space($md->getDirectory());

View file

@ -5,8 +5,8 @@ define('UTYPE_ADMIN', 'A');
define('UTYPE_GUEST', 'G');
define('UTYPE_PROGRAM_MANAGER', 'P');
class Application_Model_User {
class Application_Model_User
{
private $_userInstance;
public function __construct($userId)
@ -28,8 +28,8 @@ class Application_Model_User {
}
public function isGuest()
{
return $this->getType() == UTYPE_GUEST;
{
return $this->getType() == UTYPE_GUEST;
}
public function isHost($showId)
@ -66,7 +66,7 @@ class Application_Model_User {
if (is_array($type)) {
$result = false;
foreach ($type as $t) {
switch($t){
switch ($t) {
case UTYPE_ADMIN:
$result = $this->_userInstance->getDbType() === 'A';
break;
@ -85,11 +85,12 @@ class Application_Model_User {
}
}
} else {
switch($type) {
switch ($type) {
case UTYPE_ADMIN:
return $this->_userInstance->getDbType() === 'A';
case UTYPE_HOST:
$userId = $this->_userInstance->getDbId();
return CcShowHostsQuery::create()->filterByDbShow($showId)->filterByDbHost($userId)->count() > 0;
case UTYPE_PROGRAM_MANAGER:
return $this->_userInstance->getDbType() === 'P';
@ -154,54 +155,63 @@ class Application_Model_User {
public function getLogin()
{
$user = $this->_userInstance;
return $user->getDbLogin();
}
public function getPassword()
{
$user = $this->_userInstance;
return $user->getDbPass();
}
public function getFirstName()
{
$user = $this->_userInstance;
return $user->getDbFirstName();
}
public function getLastName()
{
$user = $this->_userInstance;
return $user->getDbLastName();
}
public function getType()
{
$user = $this->_userInstance;
return $user->getDbType();
}
public function getEmail()
{
$user = $this->_userInstance;
return $user->getDbEmail();
}
public function getCellPhone()
{
$user = $this->_userInstance;
return $user->getDbCellPhone();
}
public function getSkype()
{
$user = $this->_userInstance;
return $user->getDbSkypeContact();
}
public function getJabber()
{
$user = $this->_userInstance;
return $user->getDbJabberContact();
}
@ -221,6 +231,7 @@ class Application_Model_User {
private function createUser()
{
$user = new CcSubjs();
return $user;
}
@ -275,6 +286,7 @@ class Application_Model_User {
}
$query = $con->query($sql)->fetchColumn(0);
return ($query !== false) ? $query : null;
}
@ -337,6 +349,7 @@ class Application_Model_User {
//we get here if $userinfo->id is defined, but doesn't exist
//in the database anymore.
Zend_Auth::getInstance()->clearIdentity();
return null;
}
}