Merge branch '2.2.x'

Conflicts:
	install_minimal/airtime-install
	python_apps/media-monitor/airtimefilemonitor/airtimemetadata.py
This commit is contained in:
Martin Konecny 2012-10-26 00:31:12 -04:00
commit 6500c3312d
750 changed files with 45683 additions and 140897 deletions

2
.gitignore vendored
View file

@ -1,4 +1,2 @@
.* .*
*.pyc *.pyc
/files
build/build.properties

3
.gitmodules vendored
View file

@ -1,3 +0,0 @@
[submodule "python_apps/pypo/liquidsoap_bin"]
path = python_apps/pypo/liquidsoap_bin
url = git://github.com/sourcefabric/airtime-liquidsoap.git

View file

@ -36,7 +36,7 @@
<actionMethod actionName="delete"/> <actionMethod actionName="delete"/>
<actionMethod actionName="contents"/> <actionMethod actionName="contents"/>
<actionMethod actionName="editFileMd"/> <actionMethod actionName="editFileMd"/>
<actionMethod actionName="getFileMetaData"/> <actionMethod actionName="getFileMetadata"/>
</controllerFile> </controllerFile>
<controllerFile controllerName="Plupload"> <controllerFile controllerName="Plupload">
<actionMethod actionName="index"/> <actionMethod actionName="index"/>
@ -304,7 +304,7 @@
<viewScriptFile forActionName="update"/> <viewScriptFile forActionName="update"/>
</viewControllerScriptsDirectory> </viewControllerScriptsDirectory>
<viewControllerScriptsDirectory forControllerName="Library"> <viewControllerScriptsDirectory forControllerName="Library">
<viewScriptFile forActionName="getFileMetaData"/> <viewScriptFile forActionName="getFileMetadata"/>
</viewControllerScriptsDirectory> </viewControllerScriptsDirectory>
<viewControllerScriptsDirectory forControllerName="Nowplaying"> <viewControllerScriptsDirectory forControllerName="Nowplaying">
<viewScriptFile forActionName="dayView"/> <viewScriptFile forActionName="dayView"/>

29
CREDITS
View file

@ -1,3 +1,32 @@
=======
CREDITS
=======
Version 2.2.0
-------------
Martin Konecny (martin.konecny@sourcefabric.org)
Role: Developer Team Lead
Naomi Aro (naomi.aro@sourcefabric.org)
Role: Software Developer
James Moon (james.moon@sourcefabric.org)
Role: Software Developer
Denise Rigato (denise.rigato@sourcefabric.org)
Role: Software Developer
Rudi Grinberg (rudi.grinberg@sourcefabric.org)
Role: Software Developer
Cliff Wang (cliff.wang@sourcefabric.org)
Role: QA
Mikayel Karapetian (michael.karapetian@sourcefabric.org)
Role: QA
Daniel James (daniel.james@sourcefabric.org)
Role: Documentor & QA
======= =======
CREDITS CREDITS
======= =======

View file

@ -1,2 +1,2 @@
PRODUCT_ID=Airtime PRODUCT_ID=Airtime
PRODUCT_RELEASE=2.1.3 PRODUCT_RELEASE=2.2.0

View file

@ -1,25 +1,23 @@
<?php <?php
require_once __DIR__."/logging/Logging.php";
Logging::setLogPath('/var/log/airtime/zendphp.log');
require_once __DIR__."/configs/conf.php"; require_once __DIR__."/configs/conf.php";
require_once __DIR__."/configs/ACL.php"; require_once __DIR__."/configs/ACL.php";
require_once 'propel/runtime/lib/Propel.php'; require_once 'propel/runtime/lib/Propel.php';
Propel::init(__DIR__."/configs/airtime-conf-production.php"); Propel::init(__DIR__."/configs/airtime-conf-production.php");
require_once __DIR__."/configs/constants.php"; require_once __DIR__."/configs/constants.php";
require_once 'Preference.php'; require_once 'Preference.php';
require_once "DateHelper.php"; require_once "DateHelper.php";
require_once "OsPath.php"; require_once "OsPath.php";
require_once "Database.php";
require_once __DIR__.'/controllers/plugins/RabbitMqPlugin.php'; require_once __DIR__.'/controllers/plugins/RabbitMqPlugin.php';
//DateTime in PHP 5.3.0+ need a default timezone set. Set to UTC initially
//in case Application_Model_Preference::GetTimezone fails and creates needs to create
//a log entry. This log entry requires a call to date(), which then complains that
//timezone isn't set. Setting a default timezone allows us to create a a graceful log
//that getting the real timezone failed, without PHP complaining that it cannot log because
//there is no timezone :|.
date_default_timezone_set('UTC'); date_default_timezone_set('UTC');
require_once (APPLICATION_PATH."/logging/Logging.php");
Logging::setLogPath('/var/log/airtime/zendphp.log');
date_default_timezone_set(Application_Model_Preference::GetTimezone()); date_default_timezone_set(Application_Model_Preference::GetTimezone());
global $CC_CONFIG; global $CC_CONFIG;
@ -33,6 +31,7 @@ Zend_Validate::setDefaultNamespaces("Zend");
$front = Zend_Controller_Front::getInstance(); $front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new RabbitMqPlugin()); $front->registerPlugin(new RabbitMqPlugin());
/* The bootstrap class should only be used to initialize actions that return a view. /* The bootstrap class should only be used to initialize actions that return a view.
Actions that return JSON will not use the bootstrap class! */ Actions that return JSON will not use the bootstrap class! */
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
@ -50,13 +49,13 @@ class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
$view = $this->getResource('view'); $view = $this->getResource('view');
$baseUrl = Zend_Controller_Front::getInstance()->getBaseUrl(); $baseUrl = Zend_Controller_Front::getInstance()->getBaseUrl();
$baseDir = dirname($_SERVER['SCRIPT_FILENAME']);
$view->headLink()->appendStylesheet($baseUrl.'/css/redmond/jquery-ui-1.8.8.custom.css?'.$CC_CONFIG['airtime_version']); $view->headLink()->appendStylesheet($baseUrl.'/css/redmond/jquery-ui-1.8.8.custom.css?'.$CC_CONFIG['airtime_version']);
$view->headLink()->appendStylesheet($baseUrl.'/css/pro_dropdown_3.css?'.$CC_CONFIG['airtime_version']); $view->headLink()->appendStylesheet($baseUrl.'/css/pro_dropdown_3.css?'.$CC_CONFIG['airtime_version']);
$view->headLink()->appendStylesheet($baseUrl.'/css/qtip/jquery.qtip.min.css?'.$CC_CONFIG['airtime_version']); $view->headLink()->appendStylesheet($baseUrl.'/css/qtip/jquery.qtip.min.css?'.$CC_CONFIG['airtime_version']);
$view->headLink()->appendStylesheet($baseUrl.'/css/styles.css?'.$CC_CONFIG['airtime_version']); $view->headLink()->appendStylesheet($baseUrl.'/css/styles.css?'.$CC_CONFIG['airtime_version']);
$view->headLink()->appendStylesheet($baseUrl.'/css/masterpanel.css?'.$CC_CONFIG['airtime_version']); $view->headLink()->appendStylesheet($baseUrl.'/css/masterpanel.css?'.$CC_CONFIG['airtime_version']);
$view->headLink()->appendStylesheet($baseUrl.'/css/bootstrap.css?'.$CC_CONFIG['airtime_version']);
} }
protected function _initHeadScript() protected function _initHeadScript()
@ -65,38 +64,35 @@ class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
$view = $this->getResource('view'); $view = $this->getResource('view');
$baseUrl = Zend_Controller_Front::getInstance()->getBaseUrl(); $baseUrl = Zend_Controller_Front::getInstance()->getBaseUrl();
$baseDir = dirname($_SERVER['SCRIPT_FILENAME']);
$view->headScript()->appendFile($baseUrl.'/js/libs/jquery-1.7.2.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/libs/jquery-1.7.2.min.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$view->headScript()->appendFile($baseUrl.'/js/libs/jquery-ui-1.8.18.custom.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/libs/jquery-ui-1.8.18.custom.min.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$view->headScript()->appendFile($baseUrl.'/js/libs/jquery.stickyPanel.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/libs/jquery.stickyPanel.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$view->headScript()->appendFile($baseUrl.'/js/qtip/jquery.qtip.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/qtip/jquery.qtip.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$view->headScript()->appendFile($baseUrl.'/js/jplayer/jquery.jplayer.min.js?'.$CC_CONFIG['airtime_version'], 'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/jplayer/jquery.jplayer.min.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$view->headScript()->appendFile($baseUrl.'/js/sprintf/sprintf-0.7-beta1.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/sprintf/sprintf-0.7-beta1.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$view->headScript()->appendFile($baseUrl.'/js/bootstrap/bootstrap.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$view->headScript()->appendScript("var baseUrl='$baseUrl/'"); $view->headScript()->appendScript("var baseUrl='$baseUrl/'");
//scripts for now playing bar //scripts for now playing bar
$view->headScript()->appendFile($baseUrl.'/js/airtime/airtime_bootstrap.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$view->headScript()->appendFile($baseUrl.'/js/airtime/dashboard/helperfunctions.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/airtime/dashboard/helperfunctions.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$view->headScript()->appendFile($baseUrl.'/js/airtime/dashboard/dashboard.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/airtime/dashboard/dashboard.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$view->headScript()->appendFile($baseUrl.'/js/airtime/dashboard/versiontooltip.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/airtime/dashboard/versiontooltip.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$view->headScript()->appendFile($baseUrl.'/js/airtime/common/common.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/airtime/common/common.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$view->headScript()->appendFile($baseUrl.'/js/airtime/common/audioplaytest.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$user = Application_Model_User::GetCurrentUser(); $user = Application_Model_User::getCurrentUser();
if (!is_null($user)){ if (!is_null($user)){
$userType = $user->getType(); $userType = $user->getType();
} else { } else {
$userType = ""; $userType = "";
} }
$view->headScript()->appendScript("var userType = '$userType';"); $view->headScript()->appendScript("var userType = '$userType';");
if (Application_Model_Preference::GetPlanLevel() != "disabled"
&& !($_SERVER['REQUEST_URI'] == '/Dashboard/stream-player' || $_SERVER['REQUEST_URI'] == '/audiopreview/audio-preview-player')) { if (isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1) {
$client_id = Application_Model_Preference::GetClientId();
$view->headScript()->appendScript("var livechat_client_id = '$client_id';");
$view->headScript()->appendFile($baseUrl . '/js/airtime/common/livechat.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
}
if(isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1){
$view->headScript()->appendFile($baseUrl.'/js/libs/google-analytics.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/libs/google-analytics.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
} }
} }
@ -115,7 +111,11 @@ class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
protected function _initZFDebug() protected function _initZFDebug()
{ {
if (APPLICATION_ENV == "development"){
Zend_Controller_Front::getInstance()->throwExceptions(true);
/*
if (APPLICATION_ENV == "development") {
$autoloader = Zend_Loader_Autoloader::getInstance(); $autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->registerNamespace('ZFDebug'); $autoloader->registerNamespace('ZFDebug');
@ -131,6 +131,7 @@ class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
$frontController = $this->getResource('frontController'); $frontController = $this->getResource('frontController');
$frontController->registerPlugin($debug); $frontController->registerPlugin($debug);
} }
*/
} }
protected function _initRouter() protected function _initRouter()

View file

@ -0,0 +1,57 @@
<?php
class Application_Common_Database
{
public static function prepareAndExecute($sql, array $paramValueMap,
$type='all', $fetchType=PDO::FETCH_ASSOC)
{
$con = Propel::getConnection();
$stmt = $con->prepare($sql);
foreach ($paramValueMap as $param => $v) {
$stmt->bindValue($param, $v);
}
$rows = array();
if ($stmt->execute()) {
if ($type == 'single') {
$rows = $stmt->fetch($fetchType);
} else if ($type == 'column'){
$rows = $stmt->fetchColumn();
} else if ($type == 'all') {
$rows = $stmt->fetchAll($fetchType);
} else if ($type == 'execute') {
$rows = null;
} else {
$msg = "bad type passed: type($type)";
throw new Exception("Error: $msg");
}
} else {
$msg = implode(',', $stmt->errorInfo());
throw new Exception("Error: $msg");
}
return $rows;
}
/*
Wrapper around prepareAndExecute that allows you to use multipe :xx's
in one query. Transforms $sql to :xx1, :xx2, ....
*/
public static function smartPrepareAndExecute($sql, array $params,
$type='all', $fetchType=PDO::FETCH_ASSOC)
{
$new_params = array();
$new_sql = $sql;
foreach ($params as $k => $v) {
$matches_count = substr_count($sql, $k);
if ($matches_count == 0) {
throw new Exception("Argument $k is not inside $sql");
} elseif ($matches_count == 1) {
$new_params[$k] = $new_params[$v];
} else {
foreach ( range(1,$matches_count) as $i ) {
preg_replace( "/$k(\D)/", "$k$i${1}", $sql, 1);
$new_params[ $k.$i ] = $v;
}
}
}
return Application_Common_Database::prepareAndExecute( $new_sql,
$new_params, $type, $fetchType);
}
}

View file

@ -153,6 +153,11 @@ class Application_Common_DateHelper
return strtotime($time2) - strtotime($time1); return strtotime($time2) - strtotime($time1);
} }
public static function TimeAdd($time1, $time2)
{
return strtotime($time2) + strtotime($time1);
}
public static function ConvertMSToHHMMSSmm($time) public static function ConvertMSToHHMMSSmm($time)
{ {
$hours = floor($time / 3600000); $hours = floor($time / 3600000);
@ -305,5 +310,112 @@ class Application_Common_DateHelper
return new DateInterval("PT{$hour}H{$min}M{$sec}S"); return new DateInterval("PT{$hour}H{$min}M{$sec}S");
} }
/**
* returns true or false depending on input is wether in
* valid range of SQL date/time
* @param string $p_datetime
* should be in format of '0000-00-00 00:00:00'
*/
public static function checkDateTimeRangeForSQL($p_datetime){
$info = explode(' ', $p_datetime);
$dateInfo = explode('-', $info[0]);
if (isset($info[1])) {
$timeInfo = explode(':', $info[1]);
}
$retVal = array();
$retVal["success"] = true;
$year = $dateInfo[0];
$month = $dateInfo[1];
$day = $dateInfo[2];
// if year is < 1753 or > 9999 it's out of range
if ($year < 1753) {
$retVal['success'] = false;
$retVal['errMsg'] = "The year '$year' must be within the range of 1753 - 9999";
} else if (!checkdate($month, $day, $year)) {
$retVal['success'] = false;
$retVal['errMsg'] = "'$year-$month-$day' is not a valid date";
} else {
// check time
if (isset($timeInfo)) {
if (isset($timeInfo[0]) && $timeInfo[0] != "") {
$hour = intval($timeInfo[0]);
} else {
$hour = -1;
}
if (isset($timeInfo[1]) && $timeInfo[1] != "") {
$min = intval($timeInfo[1]);
} else {
$min = -1;
}
if (isset($timeInfo[2]) && $timeInfo[2] != "") {
$sec = intval($timeInfo[2]);
} else {
$sec = -1;
}
if ( ($hour < 0 || $hour > 23) || ($min < 0 || $min > 59) || ($sec < 0 || $sec > 59) ) {
$retVal['success'] = false;
$retVal['errMsg'] = "'$timeInfo[0]:$timeInfo[1]:$timeInfo[2]' is not a valid time";
}
}
}
return $retVal;
}
/**
* This function is used for calculations! Don't modify for display purposes!
*
* Convert playlist time value to float seconds
*
* @param string $plt
* playlist interval value (HH:mm:ss.dddddd)
* @return int
* seconds
*/
public static function playlistTimeToSeconds($plt)
{
$arr = preg_split('/:/', $plt);
if (isset($arr[2])) {
return (intval($arr[0])*60 + intval($arr[1]))*60 + floatval($arr[2]);
}
if (isset($arr[1])) {
return intval($arr[0])*60 + floatval($arr[1]);
}
return floatval($arr[0]);
}
/**
* This function is used for calculations! Don't modify for display purposes!
*
* Convert float seconds value to playlist time format
*
* @param float $seconds
* @return string
* interval in playlist time format (HH:mm:ss.d)
*/
public static function secondsToPlaylistTime($p_seconds)
{
$info = explode('.', $p_seconds);
$seconds = $info[0];
if (!isset($info[1])) {
$milliStr = 0;
} else {
$milliStr = $info[1];
}
$hours = floor($seconds / 3600);
$seconds -= $hours * 3600;
$minutes = floor($seconds / 60);
$seconds -= $minutes * 60;
$res = sprintf("%02d:%02d:%02d.%s", $hours, $minutes, $seconds, $milliStr);
return $res;
}
} }

View file

@ -24,7 +24,8 @@ $ccAcl->add(new Zend_Acl_Resource('library'))
->add(new Zend_Acl_Resource('showbuilder')) ->add(new Zend_Acl_Resource('showbuilder'))
->add(new Zend_Acl_Resource('playouthistory')) ->add(new Zend_Acl_Resource('playouthistory'))
->add(new Zend_Acl_Resource('usersettings')) ->add(new Zend_Acl_Resource('usersettings'))
->add(new Zend_Acl_Resource('audiopreview')); ->add(new Zend_Acl_Resource('audiopreview'))
->add(new Zend_Acl_Resource('webstream'));
/** Creating permissions */ /** Creating permissions */
$ccAcl->allow('G', 'index') $ccAcl->allow('G', 'index')
@ -35,6 +36,7 @@ $ccAcl->allow('G', 'index')
->allow('G', 'schedule') ->allow('G', 'schedule')
->allow('G', 'dashboard') ->allow('G', 'dashboard')
->allow('G', 'audiopreview') ->allow('G', 'audiopreview')
->allow('G', 'webstream')
->allow('H', 'preference', 'is-import-in-progress') ->allow('H', 'preference', 'is-import-in-progress')
->allow('H', 'usersettings') ->allow('H', 'usersettings')
->allow('H', 'plupload') ->allow('H', 'plupload')

View file

@ -1,6 +1,6 @@
<?php <?php
// This file generated by Propel 1.5.2 convert-conf target // This file generated by Propel 1.5.2 convert-conf target
// from XML runtime conf file /home/james/src/airtime/airtime_mvc/build/runtime-conf.xml // from XML runtime conf file /home/rudi/Airtime/airtime_mvc/build/runtime-conf.xml
$conf = array ( $conf = array (
'datasources' => 'datasources' =>
array ( array (

View file

@ -1,13 +1,6 @@
<?php <?php
// This file generated by Propel 1.5.2 convert-conf target // This file generated by Propel 1.5.2 convert-conf target
return array ( return array (
'CcAccessTableMap' => 'airtime/map/CcAccessTableMap.php',
'CcAccessPeer' => 'airtime/CcAccessPeer.php',
'CcAccess' => 'airtime/CcAccess.php',
'CcAccessQuery' => 'airtime/CcAccessQuery.php',
'BaseCcAccessPeer' => 'airtime/om/BaseCcAccessPeer.php',
'BaseCcAccess' => 'airtime/om/BaseCcAccess.php',
'BaseCcAccessQuery' => 'airtime/om/BaseCcAccessQuery.php',
'CcMusicDirsTableMap' => 'airtime/map/CcMusicDirsTableMap.php', 'CcMusicDirsTableMap' => 'airtime/map/CcMusicDirsTableMap.php',
'CcMusicDirsPeer' => 'airtime/CcMusicDirsPeer.php', 'CcMusicDirsPeer' => 'airtime/CcMusicDirsPeer.php',
'CcMusicDirs' => 'airtime/CcMusicDirs.php', 'CcMusicDirs' => 'airtime/CcMusicDirs.php',
@ -78,6 +71,27 @@ return array (
'BaseCcPlaylistcontentsPeer' => 'airtime/om/BaseCcPlaylistcontentsPeer.php', 'BaseCcPlaylistcontentsPeer' => 'airtime/om/BaseCcPlaylistcontentsPeer.php',
'BaseCcPlaylistcontents' => 'airtime/om/BaseCcPlaylistcontents.php', 'BaseCcPlaylistcontents' => 'airtime/om/BaseCcPlaylistcontents.php',
'BaseCcPlaylistcontentsQuery' => 'airtime/om/BaseCcPlaylistcontentsQuery.php', 'BaseCcPlaylistcontentsQuery' => 'airtime/om/BaseCcPlaylistcontentsQuery.php',
'CcBlockTableMap' => 'airtime/map/CcBlockTableMap.php',
'CcBlockPeer' => 'airtime/CcBlockPeer.php',
'CcBlock' => 'airtime/CcBlock.php',
'CcBlockQuery' => 'airtime/CcBlockQuery.php',
'BaseCcBlockPeer' => 'airtime/om/BaseCcBlockPeer.php',
'BaseCcBlock' => 'airtime/om/BaseCcBlock.php',
'BaseCcBlockQuery' => 'airtime/om/BaseCcBlockQuery.php',
'CcBlockcontentsTableMap' => 'airtime/map/CcBlockcontentsTableMap.php',
'CcBlockcontentsPeer' => 'airtime/CcBlockcontentsPeer.php',
'CcBlockcontents' => 'airtime/CcBlockcontents.php',
'CcBlockcontentsQuery' => 'airtime/CcBlockcontentsQuery.php',
'BaseCcBlockcontentsPeer' => 'airtime/om/BaseCcBlockcontentsPeer.php',
'BaseCcBlockcontents' => 'airtime/om/BaseCcBlockcontents.php',
'BaseCcBlockcontentsQuery' => 'airtime/om/BaseCcBlockcontentsQuery.php',
'CcBlockcriteriaTableMap' => 'airtime/map/CcBlockcriteriaTableMap.php',
'CcBlockcriteriaPeer' => 'airtime/CcBlockcriteriaPeer.php',
'CcBlockcriteria' => 'airtime/CcBlockcriteria.php',
'CcBlockcriteriaQuery' => 'airtime/CcBlockcriteriaQuery.php',
'BaseCcBlockcriteriaPeer' => 'airtime/om/BaseCcBlockcriteriaPeer.php',
'BaseCcBlockcriteria' => 'airtime/om/BaseCcBlockcriteria.php',
'BaseCcBlockcriteriaQuery' => 'airtime/om/BaseCcBlockcriteriaQuery.php',
'CcPrefTableMap' => 'airtime/map/CcPrefTableMap.php', 'CcPrefTableMap' => 'airtime/map/CcPrefTableMap.php',
'CcPrefPeer' => 'airtime/CcPrefPeer.php', 'CcPrefPeer' => 'airtime/CcPrefPeer.php',
'CcPref' => 'airtime/CcPref.php', 'CcPref' => 'airtime/CcPref.php',
@ -155,4 +169,18 @@ return array (
'BaseCcLiveLogPeer' => 'airtime/om/BaseCcLiveLogPeer.php', 'BaseCcLiveLogPeer' => 'airtime/om/BaseCcLiveLogPeer.php',
'BaseCcLiveLog' => 'airtime/om/BaseCcLiveLog.php', 'BaseCcLiveLog' => 'airtime/om/BaseCcLiveLog.php',
'BaseCcLiveLogQuery' => 'airtime/om/BaseCcLiveLogQuery.php', 'BaseCcLiveLogQuery' => 'airtime/om/BaseCcLiveLogQuery.php',
'CcWebstreamTableMap' => 'airtime/map/CcWebstreamTableMap.php',
'CcWebstreamPeer' => 'airtime/CcWebstreamPeer.php',
'CcWebstream' => 'airtime/CcWebstream.php',
'CcWebstreamQuery' => 'airtime/CcWebstreamQuery.php',
'BaseCcWebstreamPeer' => 'airtime/om/BaseCcWebstreamPeer.php',
'BaseCcWebstream' => 'airtime/om/BaseCcWebstream.php',
'BaseCcWebstreamQuery' => 'airtime/om/BaseCcWebstreamQuery.php',
'CcWebstreamMetadataTableMap' => 'airtime/map/CcWebstreamMetadataTableMap.php',
'CcWebstreamMetadataPeer' => 'airtime/CcWebstreamMetadataPeer.php',
'CcWebstreamMetadata' => 'airtime/CcWebstreamMetadata.php',
'CcWebstreamMetadataQuery' => 'airtime/CcWebstreamMetadataQuery.php',
'BaseCcWebstreamMetadataPeer' => 'airtime/om/BaseCcWebstreamMetadataPeer.php',
'BaseCcWebstreamMetadata' => 'airtime/om/BaseCcWebstreamMetadata.php',
'BaseCcWebstreamMetadataQuery' => 'airtime/om/BaseCcWebstreamMetadataQuery.php',
); );

View file

@ -2,7 +2,7 @@
define('AIRTIME_COPYRIGHT_DATE', '2010-2012'); define('AIRTIME_COPYRIGHT_DATE', '2010-2012');
define('AIRTIME_REST_VERSION', '1.1'); define('AIRTIME_REST_VERSION', '1.1');
define('AIRTIME_API_VERSION', '1.0'); define('AIRTIME_API_VERSION', '1.1');
// Metadata Keys for files // Metadata Keys for files
define('MDATA_KEY_FILEPATH', 'filepath'); define('MDATA_KEY_FILEPATH', 'filepath');
@ -30,12 +30,16 @@ define('MDATA_KEY_BPM', 'bpm');
define('MDATA_KEY_TRACKNUMBER', 'track_number'); define('MDATA_KEY_TRACKNUMBER', 'track_number');
define('MDATA_KEY_CONDUCTOR', 'conductor'); define('MDATA_KEY_CONDUCTOR', 'conductor');
define('MDATA_KEY_LANGUAGE', 'language'); define('MDATA_KEY_LANGUAGE', 'language');
define('MDATA_KEY_REPLAYGAIN', 'replay_gain');
define('MDATA_KEY_OWNER_ID', 'owner_id');
define('UI_MDATA_VALUE_FORMAT_FILE', 'File'); define('UI_MDATA_VALUE_FORMAT_FILE', 'File');
define('UI_MDATA_VALUE_FORMAT_STREAM', 'live stream'); define('UI_MDATA_VALUE_FORMAT_STREAM', 'live stream');
// Session Keys // Session Keys
define('UI_PLAYLIST_SESSNAME', 'PLAYLIST'); define('UI_PLAYLISTCONTROLLER_OBJ_SESSNAME', 'PLAYLISTCONTROLLER_OBJ');
/*define('UI_PLAYLIST_SESSNAME', 'PLAYLIST');
define('UI_BLOCK_SESSNAME', 'BLOCK');*/
// Soundcloud contants // Soundcloud contants

View file

@ -23,9 +23,9 @@ $pages = array(
'resource' => 'plupload' 'resource' => 'plupload'
), ),
array( array(
'label' => 'Playlist Builder', 'label' => 'Library',
'module' => 'default', 'module' => 'default',
'controller' => 'Playlist', 'controller' => 'Library',
'action' => 'index', 'action' => 'index',
'resource' => 'playlist' 'resource' => 'playlist'
), ),

File diff suppressed because it is too large Load diff

View file

@ -24,26 +24,46 @@ class AudiopreviewController extends Zend_Controller_Action
$audioFileID = $this->_getParam('audioFileID'); $audioFileID = $this->_getParam('audioFileID');
$audioFileArtist = $this->_getParam('audioFileArtist'); $audioFileArtist = $this->_getParam('audioFileArtist');
$audioFileTitle = $this->_getParam('audioFileTitle'); $audioFileTitle = $this->_getParam('audioFileTitle');
$type = $this->_getParam('type');
$request = $this->getRequest(); $request = $this->getRequest();
$baseUrl = $request->getBaseUrl(); $baseUrl = $request->getBaseUrl();
$baseDir = dirname($_SERVER['SCRIPT_FILENAME']); $this->view->headScript()->appendFile(
$baseUrl.'/js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile(
$this->view->headLink()->appendStylesheet($baseUrl.'/js/jplayer/skin/jplayer.airtime.audio.preview.css?'.$CC_CONFIG['airtime_version']); $baseUrl.'/js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],
'text/javascript');
$this->view->headLink()->appendStylesheet(
$baseUrl.'/js/jplayer/skin/jplayer.airtime.audio.preview.css?'.$CC_CONFIG['airtime_version']);
$this->_helper->layout->setLayout('audioPlayer'); $this->_helper->layout->setLayout('audioPlayer');
$logo = Application_Model_Preference::GetStationLogo(); $logo = Application_Model_Preference::GetStationLogo();
if($logo){ if ($logo) {
$this->view->logo = "data:image/png;base64,$logo"; $this->view->logo = "data:image/png;base64,$logo";
} else { } else {
$this->view->logo = "$baseUrl/css/images/airtime_logo_jp.png"; $this->view->logo = "$baseUrl/css/images/airtime_logo_jp.png";
} }
if ($type == "audioclip") {
$uri = "/api/get-media/file/".$audioFileID;
$media = Application_Model_StoredFile::Recall($audioFileID);
$mime = $media->getPropelOrm()->getDbMime();
} elseif ($type == "stream") {
$webstream = CcWebstreamQuery::create()->findPk($audioFileID);
$uri = $webstream->getDbUrl();
$mime = $webstream->getDbMime();
} else {
throw new Exception("Unknown type for audio preview!.Type=$type");
}
$this->view->uri = $uri;
$this->view->mime = $mime;
$this->view->audioFileID = $audioFileID; $this->view->audioFileID = $audioFileID;
$this->view->audioFileArtist = $audioFileArtist; $this->view->audioFileArtist = $audioFileArtist;
$this->view->audioFileTitle = $audioFileTitle; $this->view->audioFileTitle = $audioFileTitle;
$this->view->type = $type;
$this->_helper->viewRenderer->setRender('audio-preview'); $this->_helper->viewRenderer->setRender('audio-preview');
} }
@ -62,15 +82,13 @@ class AudiopreviewController extends Zend_Controller_Action
$request = $this->getRequest(); $request = $this->getRequest();
$baseUrl = $request->getBaseUrl(); $baseUrl = $request->getBaseUrl();
$baseDir = dirname($_SERVER['SCRIPT_FILENAME']);
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headLink()->appendStylesheet($baseUrl.'/js/jplayer/skin/jplayer.airtime.audio.preview.css?'.$CC_CONFIG['airtime_version']); $this->view->headLink()->appendStylesheet($baseUrl.'/js/jplayer/skin/jplayer.airtime.audio.preview.css?'.$CC_CONFIG['airtime_version']);
$this->_helper->layout->setLayout('audioPlayer'); $this->_helper->layout->setLayout('audioPlayer');
$logo = Application_Model_Preference::GetStationLogo(); $logo = Application_Model_Preference::GetStationLogo();
if($logo){ if ($logo) {
$this->view->logo = "data:image/png;base64,$logo"; $this->view->logo = "data:image/png;base64,$logo";
} else { } else {
$this->view->logo = "$baseUrl/css/images/airtime_logo_jp.png"; $this->view->logo = "$baseUrl/css/images/airtime_logo_jp.png";
@ -81,42 +99,126 @@ class AudiopreviewController extends Zend_Controller_Action
$this->_helper->viewRenderer->setRender('audio-preview'); $this->_helper->viewRenderer->setRender('audio-preview');
} }
public function blockPreviewAction()
{
global $CC_CONFIG;
$blockIndex = $this->_getParam('blockIndex');
$blockId = $this->_getParam('blockId');
$request = $this->getRequest();
$baseUrl = $request->getBaseUrl();
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headLink()->appendStylesheet($baseUrl.'/js/jplayer/skin/jplayer.airtime.audio.preview.css?'.$CC_CONFIG['airtime_version']);
$this->_helper->layout->setLayout('audioPlayer');
$logo = Application_Model_Preference::GetStationLogo();
if ($logo) {
$this->view->logo = "data:image/png;base64,$logo";
} else {
$this->view->logo = "$baseUrl/css/images/airtime_logo_jp.png";
}
$this->view->blockIndex= $blockIndex;
$this->view->blockId = $blockId;
$this->_helper->viewRenderer->setRender('audio-preview');
}
public function getBlockAction()
{
// disable the view and the layout
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$blockId = $this->_getParam('blockId');
if (!isset($blockId)) {
return;
}
$bl = new Application_Model_Block($blockId);
$result = array();
foreach ($bl->getContents(true) as $ele) {
$result[] = $this->createElementMap($ele);
}
$this->_helper->json($result);
}
/** /**
*Function will load and return the contents of the requested playlist. *Function will load and return the contents of the requested playlist.
*/ */
public function getPlaylistAction(){ public function getPlaylistAction()
{
// disable the view and the layout // disable the view and the layout
$this->view->layout()->disableLayout(); $this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true); $this->_helper->viewRenderer->setNoRender(true);
$playlistID = $this->_getParam('playlistID'); $playlistID = $this->_getParam('playlistID');
if (!isset($playlistID)){ if (!isset($playlistID)) {
return; return;
} }
$pl = new Application_Model_Playlist($playlistID); $pl = new Application_Model_Playlist($playlistID);
$result = Array(); $result = Array();
foreach ( $pl->getContents(true) as $track ){ foreach ($pl->getContents(true) as $ele) {
if ($ele['type'] == 2) {
// if element is a block expand and add
$bl = new Application_Model_Block($ele['item_id']);
if ($bl->isStatic()) {
foreach ($bl->getContents(true) as $track) {
$result[] = $this->createElementMap($track);
}
}
} else {
$result[] = $this->createElementMap($ele);
}
}
$this->_helper->json($result);
}
$elementMap = array( 'element_title' => isset($track['CcFiles']['track_title'])?$track['CcFiles']['track_title']:"", private function createElementMap($track)
'element_artist' => isset($track['CcFiles']['artist_name'])?$track['CcFiles']['artist_name']:"", {
$elementMap = array( 'element_title' => isset($track['track_title'])?$track['track_title']:"",
'element_artist' => isset($track['artist_name'])?$track['artist_name']:"",
'element_id' => isset($track['id'])?$track['id']:"", 'element_id' => isset($track['id'])?$track['id']:"",
'element_position' => isset($track['position'])?$track['position']:"", 'element_position' => isset($track['position'])?$track['position']:"",
'mime' => isset($track['mime'])?$track['mime']:""
); );
$fileExtension = pathinfo($track['CcFiles']['filepath'], PATHINFO_EXTENSION);
if (strtolower($fileExtension) === 'mp3'){ /* If the track type is static we know it must be
$elementMap['element_mp3'] = $track['CcFiles']['gunid'].'.'.$fileExtension; * a track because static blocks can only contain
} else if(strtolower($fileExtension) === 'ogg') { * tracks
$elementMap['element_oga'] = $track['CcFiles']['gunid'].'.'.$fileExtension; */
} else { if ($track['type'] == 'static') {
//the media was neither mp3 or ogg $track['type'] = 0;
} }
$result[] = $elementMap; $elementMap['type'] = $track['type'];
if ($track['type'] == 0) {
$mime = $track['mime'];
//type is file
if (strtolower($mime) === 'audio/mp3') {
$elementMap['element_mp3'] = $track['item_id'];
} elseif (strtolower($mime) === 'audio/ogg') {
$elementMap['element_oga'] = $track['item_id'];
} elseif (strtolower($mime) === 'audio/mp4') {
$elementMap['element_m4a'] = $track['item_id'];
} elseif (strtolower($mime) === 'audio/wav') {
$elementMap['element_wav'] = $track['item_id'];
} elseif (strtolower($mime) === 'audio/x-flac') {
$elementMap['element_flac'] = $track['item_id'];
} else {
throw new Exception("Unknown file type: $mime");
} }
$this->_helper->json($result); $elementMap['uri'] = "/api/get-media/file/".$track['item_id'];
} else {
$elementMap['uri'] = $track['path'];
}
return $elementMap;
} }
/** /**
@ -133,15 +235,13 @@ class AudiopreviewController extends Zend_Controller_Action
$request = $this->getRequest(); $request = $this->getRequest();
$baseUrl = $request->getBaseUrl(); $baseUrl = $request->getBaseUrl();
$baseDir = dirname($_SERVER['SCRIPT_FILENAME']);
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headLink()->appendStylesheet($baseUrl.'/js/jplayer/skin/jplayer.airtime.audio.preview.css?'.$CC_CONFIG['airtime_version']); $this->view->headLink()->appendStylesheet($baseUrl.'/js/jplayer/skin/jplayer.airtime.audio.preview.css?'.$CC_CONFIG['airtime_version']);
$this->_helper->layout->setLayout('audioPlayer'); $this->_helper->layout->setLayout('audioPlayer');
$logo = Application_Model_Preference::GetStationLogo(); $logo = Application_Model_Preference::GetStationLogo();
if ($logo){ if ($logo) {
$this->view->logo = "data:image/png;base64,$logo"; $this->view->logo = "data:image/png;base64,$logo";
} else { } else {
$this->view->logo = "$baseUrl/css/images/airtime_logo_jp.png"; $this->view->logo = "$baseUrl/css/images/airtime_logo_jp.png";
@ -164,29 +264,43 @@ class AudiopreviewController extends Zend_Controller_Action
$showID = $this->_getParam('showID'); $showID = $this->_getParam('showID');
if (!isset($showID)){ if (!isset($showID)) {
return; return;
} }
$showInstance = new Application_Model_ShowInstance($showID); $showInstance = new Application_Model_ShowInstance($showID);
$result = array(); $result = array();
$position = 0; $position = 0;
foreach ($showInstance->getShowListContent() as $track){ foreach ($showInstance->getShowListContent() as $track) {
$elementMap = array( $elementMap = array(
'element_title' => isset($track['track_title']) ? $track['track_title'] : "", 'element_title' => isset($track['track_title']) ? $track['track_title'] : "",
'element_artist' => isset($track['artist_name']) ? $track['artist_name'] : "", 'element_artist' => isset($track['creator']) ? $track['creator'] : "",
'element_position' => $position, 'element_position' => $position,
'element_id' => ++$position, 'element_id' => ++$position,
'mime' => isset($track['mime'])?$track['mime']:""
); );
$fileExtension = pathinfo($track['filepath'], PATHINFO_EXTENSION); $elementMap['type'] = $track['type'];
if (strtolower($fileExtension) === 'mp3'){ if ($track['type'] == 0) {
$elementMap['element_mp3'] = $track['gunid'].'.'.$fileExtension; $mime = $track['mime'];
} else if(strtolower($fileExtension) === 'ogg') { if (strtolower($mime) === 'audio/mp3') {
$elementMap['element_oga'] = $track['gunid'].'.'.$fileExtension; $elementMap['element_mp3'] = $track['item_id'];
} elseif (strtolower($mime) === 'audio/ogg') {
$elementMap['element_oga'] = $track['item_id'];
} elseif (strtolower($mime) === 'audio/mp4') {
$elementMap['element_m4a'] = $track['item_id'];
} elseif (strtolower($mime) === 'audio/wav') {
$elementMap['element_wav'] = $track['item_id'];
} elseif (strtolower($mime) === 'audio/x-flac') {
$elementMap['element_flac'] = $track['item_id'];
} else { } else {
//the media was neither mp3 or ogg throw new Exception("Unknown file type: $mime");
}
$elementMap['uri'] = "/api/get-media/file/".$track['item_id'];
} else {
$elementMap['uri'] = $track['filepath'];
} }
$result[] = $elementMap; $result[] = $elementMap;
} }

View file

@ -16,61 +16,60 @@ class DashboardController extends Zend_Controller_Action
// action body // action body
} }
public function disconnectSourceAction(){ public function disconnectSourceAction()
{
$request = $this->getRequest(); $request = $this->getRequest();
$sourcename = $request->getParam('sourcename'); $sourcename = $request->getParam('sourcename');
$userInfo = Zend_Auth::getInstance()->getStorage()->read(); $userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id); $user = new Application_Model_User($userInfo->id);
$show = Application_Model_Show::GetCurrentShow(); $show = Application_Model_Show::getCurrentShow();
$show_id = isset($show[0]['id'])?$show[0]['id']:0;
$show_id = isset($show['id'])?$show['id']:0;
$source_connected = Application_Model_Preference::GetSourceStatus($sourcename); $source_connected = Application_Model_Preference::GetSourceStatus($sourcename);
if($user->canSchedule($show_id) && $source_connected){ if ($user->canSchedule($show_id) && $source_connected) {
$data = array("sourcename"=>$sourcename); $data = array("sourcename"=>$sourcename);
Application_Model_RabbitMq::SendMessageToPypo("disconnect_source", $data); Application_Model_RabbitMq::SendMessageToPypo("disconnect_source", $data);
}else{ } else {
if($source_connected){ if ($source_connected) {
$this->view->error = "You don't have permission to disconnect source."; $this->view->error = "You don't have permission to disconnect source.";
}else{ } else {
$this->view->error = "There is no source connected to this input."; $this->view->error = "There is no source connected to this input.";
} }
} }
} }
public function switchSourceAction(){ public function switchSourceAction()
$request = $this->getRequest(); {
$sourcename = $this->_getParam('sourcename'); $sourcename = $this->_getParam('sourcename');
$current_status = $this->_getParam('status'); $current_status = $this->_getParam('status');
$userInfo = Zend_Auth::getInstance()->getStorage()->read(); $userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id); $user = new Application_Model_User($userInfo->id);
$show = Application_Model_Show::GetCurrentShow(); $show = Application_Model_Show::getCurrentShow();
$show_id = isset($show[0]['id'])?$show[0]['id']:0; $show_id = isset($show[0]['id'])?$show[0]['id']:0;
$source_connected = Application_Model_Preference::GetSourceStatus($sourcename); $source_connected = Application_Model_Preference::GetSourceStatus($sourcename);
if($user->canSchedule($show_id) && ($source_connected || $sourcename == 'scheduled_play' || $current_status == "on")){ if ($user->canSchedule($show_id) && ($source_connected || $sourcename == 'scheduled_play' || $current_status == "on")) {
$change_status_to = "on"; $change_status_to = "on";
if(strtolower($current_status) == "on"){ if (strtolower($current_status) == "on") {
$change_status_to = "off"; $change_status_to = "off";
} }
$data = array("sourcename"=>$sourcename, "status"=>$change_status_to); $data = array("sourcename"=>$sourcename, "status"=>$change_status_to);
Application_Model_RabbitMq::SendMessageToPypo("switch_source", $data); Application_Model_RabbitMq::SendMessageToPypo("switch_source", $data);
if(strtolower($current_status) == "on"){ if (strtolower($current_status) == "on") {
Application_Model_Preference::SetSourceSwitchStatus($sourcename, "off"); Application_Model_Preference::SetSourceSwitchStatus($sourcename, "off");
$this->view->status = "OFF"; $this->view->status = "OFF";
//Log table updates //Log table updates
Application_Model_LiveLog::SetEndTime($sourcename == 'scheduled_play'?'S':'L', Application_Model_LiveLog::SetEndTime($sourcename == 'scheduled_play'?'S':'L',
new DateTime("now", new DateTimeZone('UTC'))); new DateTime("now", new DateTimeZone('UTC')));
}else{ } else {
Application_Model_Preference::SetSourceSwitchStatus($sourcename, "on"); Application_Model_Preference::SetSourceSwitchStatus($sourcename, "on");
$this->view->status = "ON"; $this->view->status = "ON";
@ -78,22 +77,21 @@ class DashboardController extends Zend_Controller_Action
Application_Model_LiveLog::SetNewLogTime($sourcename == 'scheduled_play'?'S':'L', Application_Model_LiveLog::SetNewLogTime($sourcename == 'scheduled_play'?'S':'L',
new DateTime("now", new DateTimeZone('UTC'))); new DateTime("now", new DateTimeZone('UTC')));
} }
} } else {
else{ if ($source_connected) {
if($source_connected){
$this->view->error = "You don't have permission to switch source."; $this->view->error = "You don't have permission to switch source.";
}else{ } else {
if($sourcename == 'scheduled_play'){ if ($sourcename == 'scheduled_play') {
$this->view->error = "You don't have permission to disconnect source."; $this->view->error = "You don't have permission to disconnect source.";
}else{ } else {
$this->view->error = "There is no source connected to this input."; $this->view->error = "There is no source connected to this input.";
} }
} }
} }
} }
public function switchOffSource(){ public function switchOffSource()
{
} }
public function streamPlayerAction() public function streamPlayerAction()
@ -107,7 +105,7 @@ class DashboardController extends Zend_Controller_Action
$this->_helper->layout->setLayout('bare'); $this->_helper->layout->setLayout('bare');
$logo = Application_Model_Preference::GetStationLogo(); $logo = Application_Model_Preference::GetStationLogo();
if($logo){ if ($logo) {
$this->view->logo = "data:image/png;base64,$logo"; $this->view->logo = "data:image/png;base64,$logo";
} else { } else {
$this->view->logo = "$baseUrl/css/images/airtime_logo_jp.png"; $this->view->logo = "$baseUrl/css/images/airtime_logo_jp.png";
@ -125,4 +123,3 @@ class DashboardController extends Zend_Controller_Action
} }
} }

View file

@ -43,6 +43,7 @@ class ErrorController extends Zend_Controller_Action
return false; return false;
} }
$log = $bootstrap->getResource('Log'); $log = $bootstrap->getResource('Log');
return $log; return $log;
} }
@ -51,8 +52,4 @@ class ErrorController extends Zend_Controller_Action
// action body // action body
} }
} }

View file

@ -19,10 +19,3 @@ class IndexController extends Zend_Controller_Action
} }
} }

View file

@ -7,9 +7,6 @@ require_once 'formatters/BitrateFormatter.php';
class LibraryController extends Zend_Controller_Action class LibraryController extends Zend_Controller_Action
{ {
protected $pl_sess = null;
protected $search_sess = null;
public function init() public function init()
{ {
$ajaxContext = $this->_helper->getHelper('AjaxContext'); $ajaxContext = $this->_helper->getHelper('AjaxContext');
@ -17,14 +14,130 @@ class LibraryController extends Zend_Controller_Action
->addActionContext('delete', 'json') ->addActionContext('delete', 'json')
->addActionContext('delete-group', 'json') ->addActionContext('delete-group', 'json')
->addActionContext('context-menu', 'json') ->addActionContext('context-menu', 'json')
->addActionContext('get-file-meta-data', 'html') ->addActionContext('get-file-metadata', 'html')
->addActionContext('upload-file-soundcloud', 'json') ->addActionContext('upload-file-soundcloud', 'json')
->addActionContext('get-upload-to-soundcloud-status', 'json') ->addActionContext('get-upload-to-soundcloud-status', 'json')
->addActionContext('set-num-entries', 'json') ->addActionContext('set-num-entries', 'json')
->initContext(); ->initContext();
}
$this->pl_sess = new Zend_Session_Namespace(UI_PLAYLIST_SESSNAME); public function indexAction()
$this->search_sess = new Zend_Session_Namespace("search"); {
global $CC_CONFIG;
$request = $this->getRequest();
$baseUrl = $request->getBaseUrl();
$this->view->headScript()->appendFile($baseUrl.'/js/blockui/jquery.blockUI.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/contextmenu/jquery.contextMenu.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/js/jquery.dataTables.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.pluginAPI.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.fnSetFilteringDelay.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.ColVis.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.ColReorder.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.FixedColumns.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.columnFilter.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/buttons/buttons.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/utilities/utilities.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/library/library.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/library/events/library_playlistbuilder.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headLink()->appendStylesheet($baseUrl.'/css/media_library.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'/css/jquery.contextMenu.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'/css/datatables/css/ColVis.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'/css/datatables/css/ColReorder.css?'.$CC_CONFIG['airtime_version']);
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/library/spl.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/playlist/smart_blockbuilder.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headLink()->appendStylesheet($baseUrl.'/css/playlist_builder.css?'.$CC_CONFIG['airtime_version']);
try {
$obj_sess = new Zend_Session_Namespace(UI_PLAYLISTCONTROLLER_OBJ_SESSNAME);
if (isset($obj_sess->id)) {
$objInfo = Application_Model_Library::getObjInfo($obj_sess->type);
Logging::info($obj_sess->id);
Logging::info($obj_sess->type);
$objInfo = Application_Model_Library::getObjInfo($obj_sess->type);
$obj = new $objInfo['className']($obj_sess->id);
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id);
$isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
if ($isAdminOrPM || $obj->getCreatorId() == $userInfo->id) {
$this->view->obj = $obj;
if ($obj_sess->type == "block") {
$form = new Application_Form_SmartBlockCriteria();
$form->startForm($obj_sess->id);
$this->view->form = $form;
}
}
$formatter = new LengthFormatter($obj->getLength());
$this->view->length = $formatter->format();
$this->view->type = $obj_sess->type;
}
} catch (PlaylistNotFoundException $e) {
$this->playlistNotFound($obj_sess->type);
} catch (Exception $e) {
$this->playlistNotFound($obj_sess->type);
Logging::info($e->getMessage());
//$this->playlistUnknownError($e);
}
}
protected function playlistNotFound($p_type)
{
$this->view->error = "$p_type not found";
Logging::info("$p_type not found");
Application_Model_Library::changePlaylist(null, $p_type);
$this->createFullResponse(null);
}
protected function playlistUnknownError($e)
{
$this->view->error = "Something went wrong.";
Logging::info($e->getMessage());
}
protected function createFullResponse($obj = null, $isJson = false)
{
$isBlock = false;
$viewPath = 'playlist/playlist.phtml';
if ($obj instanceof Application_Model_Block) {
$isBlock = true;
$viewPath = 'playlist/smart-block.phtml';
}
if (isset($obj)) {
$formatter = new LengthFormatter($obj->getLength());
$this->view->length = $formatter->format();
if ($isBlock) {
$form = new Application_Form_SmartBlockCriteria();
$form->removeDecorator('DtDdWrapper');
$form->startForm($obj->getId());
$this->view->form = $form;
$this->view->obj = $obj;
$this->view->id = $obj->getId();
if ($isJson) {
return $this->view->render($viewPath);
} else {
$this->view->html = $this->view->render($viewPath);
}
} else {
$this->view->obj = $obj;
$this->view->id = $obj->getId();
$this->view->html = $this->view->render($viewPath);
unset($this->view->obj);
}
} else {
$this->view->html = $this->view->render($viewPath);
}
} }
public function contextMenuAction() public function contextMenuAction()
@ -41,19 +154,31 @@ class LibraryController extends Zend_Controller_Action
$user = new Application_Model_User($userInfo->id); $user = new Application_Model_User($userInfo->id);
//Open a jPlayer window and play the audio clip. //Open a jPlayer window and play the audio clip.
$menu["play"] = array("name"=> "Preview", "icon" => "play"); $menu["play"] = array("name"=> "Preview", "icon" => "play", "disabled" => false);
$isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
$obj_sess = new Zend_Session_Namespace(UI_PLAYLISTCONTROLLER_OBJ_SESSNAME);
if ($type === "audioclip") { if ($type === "audioclip") {
$file = Application_Model_StoredFile::Recall($id); $file = Application_Model_StoredFile::Recall($id);
if (isset($this->pl_sess->id) && $screen == "playlist") { $menu["play"]["mime"] = $file->getPropelOrm()->getDbMime();
// if the user is not admin or pm, check the creator and see if this person owns the playlist
$playlist = new Application_Model_Playlist($this->pl_sess->id); if (isset($obj_sess->id) && $screen == "playlist") {
if($isAdminOrPM || $playlist->getCreatorId() == $user->getId()){ // if the user is not admin or pm, check the creator and see if this person owns the playlist or Block
if ($obj_sess->type == 'playlist') {
$obj = new Application_Model_Playlist($obj_sess->id);
} elseif ($obj_sess->type == 'block') {
$obj = new Application_Model_Block($obj_sess->id);
}
if ($isAdminOrPM || $obj->getCreatorId() == $user->getId()) {
if ($obj_sess->type === "playlist") {
$menu["pl_add"] = array("name"=> "Add to Playlist", "icon" => "add-playlist", "icon" => "copy"); $menu["pl_add"] = array("name"=> "Add to Playlist", "icon" => "add-playlist", "icon" => "copy");
} elseif ($obj_sess->type === "block") {
$menu["pl_add"] = array("name"=> "Add to Smart Block", "icon" => "add-playlist", "icon" => "copy");
}
} }
} }
if ($isAdminOrPM) { if ($isAdminOrPM) {
@ -63,19 +188,47 @@ class LibraryController extends Zend_Controller_Action
$url = $file->getRelativeFileUrl($baseUrl).'/download/true'; $url = $file->getRelativeFileUrl($baseUrl).'/download/true';
$menu["download"] = array("name" => "Download", "icon" => "download", "url" => $url); $menu["download"] = array("name" => "Download", "icon" => "download", "url" => $url);
} elseif ($type === "playlist" || $type === "block") {
if ($type === 'playlist') {
$obj = new Application_Model_Playlist($id);
} elseif ($type === 'block') {
$obj = new Application_Model_Block($id);
if (!$obj->isStatic()) {
unset($menu["play"]);
} }
else if ($type === "playlist") { if (($isAdminOrPM || $obj->getCreatorId() == $user->getId()) && $screen == "playlist") {
$playlist = new Application_Model_Playlist($id); if ($obj_sess->type === "playlist") {
if ($this->pl_sess->id !== $id && $screen == "playlist") { $menu["pl_add"] = array("name"=> "Add to Playlist", "icon" => "add-playlist", "icon" => "copy");
if($isAdminOrPM || $playlist->getCreatorId() == $user->getId()){
$menu["edit"] = array("name"=> "Edit", "icon" => "edit");
} }
} }
if($isAdminOrPM || $playlist->getCreatorId() == $user->getId()){
$menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => "/library/delete");
}
} }
if ($obj_sess->id !== $id && $screen == "playlist") {
if ($isAdminOrPM || $obj->getCreatorId() == $user->getId()) {
$menu["edit"] = array("name"=> "Edit", "icon" => "edit");
}
}
if ($isAdminOrPM || $obj->getCreatorId() == $user->getId()) {
$menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => "/library/delete");
}
} elseif ($type == "stream") {
$webstream = CcWebstreamQuery::create()->findPK($id);
$obj = new Application_Model_Webstream($webstream);
if (isset($obj_sess->id) && $screen == "playlist") {
if ($isAdminOrPM || $obj->getCreatorId() == $user->getId()) {
if ($obj_sess->type === "playlist") {
$menu["pl_add"] = array("name"=> "Add to Playlist", "icon" => "add-playlist", "icon" => "copy");
}
}
}
if ($isAdminOrPM || $obj->getCreatorId() == $user->getId()) {
if ($screen == "playlist") {
$menu["edit"] = array("name"=> "Edit", "icon" => "edit", "url" => "/library/edit-file-md/id/{$id}");
}
$menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => "/library/delete");
}
}
//SOUNDCLOUD MENU OPTIONS //SOUNDCLOUD MENU OPTIONS
if ($type === "audioclip" && Application_Model_Preference::GetUploadToSoundcloudOption()) { if ($type === "audioclip" && Application_Model_Preference::GetUploadToSoundcloudOption()) {
@ -88,21 +241,24 @@ class LibraryController extends Zend_Controller_Action
$scid = $file->getSoundCloudId(); $scid = $file->getSoundCloudId();
if ($scid > 0){ if ($scid > 0) {
$url = $file->getSoundCloudLinkToFile(); $url = $file->getSoundCloudLinkToFile();
$menu["soundcloud"]["items"]["view"] = array("name" => "View on Soundcloud", "icon" => "soundcloud", "url" => $url); $menu["soundcloud"]["items"]["view"] = array("name" => "View on Soundcloud", "icon" => "soundcloud", "url" => $url);
} }
if (!is_null($scid)){ if (!is_null($scid)) {
$text = "Re-upload to SoundCloud"; $text = "Re-upload to SoundCloud";
} } else {
else {
$text = "Upload to SoundCloud"; $text = "Upload to SoundCloud";
} }
$menu["soundcloud"]["items"]["upload"] = array("name" => $text, "icon" => "soundcloud", "url" => "/library/upload-file-soundcloud/id/{$id}"); $menu["soundcloud"]["items"]["upload"] = array("name" => $text, "icon" => "soundcloud", "url" => "/library/upload-file-soundcloud/id/{$id}");
} }
if (empty($menu)) {
$menu["noaction"] = array("name"=>"No action available");
}
$this->view->items = $menu; $this->view->items = $menu;
} }
@ -111,11 +267,13 @@ class LibraryController extends Zend_Controller_Action
//array containing id and type of media to delete. //array containing id and type of media to delete.
$mediaItems = $this->_getParam('media', null); $mediaItems = $this->_getParam('media', null);
$user = Application_Model_User::GetCurrentUser(); $user = Application_Model_User::getCurrentUser();
$isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); //$isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
$files = array(); $files = array();
$playlists = array(); $playlists = array();
$blocks = array();
$streams = array();
$message = null; $message = null;
@ -123,33 +281,34 @@ class LibraryController extends Zend_Controller_Action
if ($media["type"] === "audioclip") { if ($media["type"] === "audioclip") {
$files[] = intval($media["id"]); $files[] = intval($media["id"]);
} } elseif ($media["type"] === "playlist") {
else if ($media["type"] === "playlist") {
$playlists[] = intval($media["id"]); $playlists[] = intval($media["id"]);
} elseif ($media["type"] === "block") {
$blocks[] = intval($media["id"]);
} elseif ($media["type"] === "stream") {
$streams[] = intval($media["id"]);
} }
} }
$hasPermission = true; try {
if (count($playlists)) { Application_Model_Playlist::deletePlaylists($playlists, $user->getId());
// make sure use has permission to delete all playslists in the list } catch (PlaylistNoPermissionException $e) {
if(!$isAdminOrPM){ $this->view->message = "You don't have permission to delete selected items.";
foreach($playlists as $pid){
$pl = new Application_Model_Playlist($pid);
if($pl->getCreatorId() != $user->getId()){
$hasPermission = false;
}
}
}
}
if (!$isAdminOrPM && count($files)) {
$hasPermission = false;
}
if(!$hasPermission){
$this->view->message = "You don't have a permission to delete all playlists/files that are selected.";
return; return;
}else{ }
Application_Model_Playlist::DeletePlaylists($playlists);
try {
Application_Model_Block::deleteBlocks($blocks, $user->getId());
} catch (Exception $e) {
//TODO: warn user that not all blocks could be deleted.
}
try {
Application_Model_Webstream::deleteStreams($streams, $user->getId());
} catch (Exception $e) {
//TODO: warn user that not all streams could be deleted.
Logging::info($e);
} }
foreach ($files as $id) { foreach ($files as $id) {
@ -159,10 +318,10 @@ class LibraryController extends Zend_Controller_Action
if (isset($file)) { if (isset($file)) {
try { try {
$res = $file->delete(true); $res = $file->delete(true);
} } catch (Exception $e) {
//could throw a scheduled in future exception. //could throw a scheduled in future exception.
catch (Exception $e) {
$message = "Could not delete some scheduled files."; $message = "Could not delete some scheduled files.";
Logging::debug($e->getMessage());
} }
} }
} }
@ -175,22 +334,21 @@ class LibraryController extends Zend_Controller_Action
public function contentsFeedAction() public function contentsFeedAction()
{ {
$params = $this->getRequest()->getParams(); $params = $this->getRequest()->getParams();
$r = Application_Model_StoredFile::searchLibraryFiles($params); $r = Application_Model_StoredFile::searchLibraryFiles($params);
//TODO move this to the datatables row callback. //TODO move this to the datatables row callback.
foreach ($r["aaData"] as &$data) { foreach ($r["aaData"] as &$data) {
if ($data['ftype'] == 'audioclip'){ if ($data['ftype'] == 'audioclip') {
$file = Application_Model_StoredFile::Recall($data['id']); $file = Application_Model_StoredFile::Recall($data['id']);
$scid = $file->getSoundCloudId(); $scid = $file->getSoundCloudId();
if ($scid == "-2"){ if ($scid == "-2") {
$data['track_title'] .= '<span class="small-icon progress"/>'; $data['track_title'] .= '<span class="small-icon progress"/>';
} } elseif ($scid == "-3") {
else if ($scid == "-3"){
$data['track_title'] .= '<span class="small-icon sc-error"/>'; $data['track_title'] .= '<span class="small-icon sc-error"/>';
} } elseif (!is_null($scid)) {
else if (!is_null($scid)){
$data['track_title'] .= '<span class="small-icon soundcloud"/>'; $data['track_title'] .= '<span class="small-icon soundcloud"/>';
} }
} }
@ -204,9 +362,9 @@ class LibraryController extends Zend_Controller_Action
public function editFileMdAction() public function editFileMdAction()
{ {
$user = Application_Model_User::GetCurrentUser(); $user = Application_Model_User::getCurrentUser();
$isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
if(!$isAdminOrPM){ if (!$isAdminOrPM) {
return; return;
} }
@ -227,17 +385,17 @@ class LibraryController extends Zend_Controller_Action
// set MDATA_KEY_FILEPATH // set MDATA_KEY_FILEPATH
$data['MDATA_KEY_FILEPATH'] = $file->getFilePath(); $data['MDATA_KEY_FILEPATH'] = $file->getFilePath();
Logging::log($data['MDATA_KEY_FILEPATH']); Logging::info($data['MDATA_KEY_FILEPATH']);
Application_Model_RabbitMq::SendMessageToMediaMonitor("md_update", $data); Application_Model_RabbitMq::SendMessageToMediaMonitor("md_update", $data);
$this->_redirect('playlist/index'); $this->_redirect('Library');
} }
} }
$this->view->form = $form; $this->view->form = $form;
} }
public function getFileMetaDataAction() public function getFileMetadataAction()
{ {
$id = $this->_getParam('id'); $id = $this->_getParam('id');
$type = $this->_getParam('type'); $type = $this->_getParam('type');
@ -266,8 +424,7 @@ class LibraryController extends Zend_Controller_Action
$this->view->md = $md; $this->view->md = $md;
} } elseif ($type == "playlist") {
else if ($type == "playlist") {
$file = new Application_Model_Playlist($id); $file = new Application_Model_Playlist($id);
$this->view->type = $type; $this->view->type = $type;
@ -278,21 +435,47 @@ class LibraryController extends Zend_Controller_Action
$this->view->md = $md; $this->view->md = $md;
$this->view->contents = $file->getContents(); $this->view->contents = $file->getContents();
} elseif ($type == "block") {
$block = new Application_Model_Block($id);
$this->view->type = $type;
$md = $block->getAllPLMetaData();
$formatter = new LengthFormatter($md["dcterms:extent"]);
$md["dcterms:extent"] = $formatter->format();
$this->view->md = $md;
if ($block->isStatic()) {
$this->view->blType = 'Static';
$this->view->contents = $block->getContents();
} else {
$this->view->blType = 'Dynamic';
$this->view->contents = $block->getCriteria();
} }
$this->view->block = $block;
} elseif ($type == "stream") {
$webstream = CcWebstreamQuery::create()->findPK($id);
$ws = new Application_Model_Webstream($webstream);
$md = $ws->getMetadata();
$this->view->md = $md;
$this->view->type = $type;
} }
catch (Exception $e) { } catch (Exception $e) {
Logging::log($e->getMessage()); Logging::info($e->getMessage());
} }
} }
public function uploadFileSoundcloudAction(){ public function uploadFileSoundcloudAction()
{
$id = $this->_getParam('id'); $id = $this->_getParam('id');
$res = exec("/usr/lib/airtime/utils/soundcloud-uploader $id > /dev/null &"); Application_Model_Soundcloud::uploadSoundcloud($id);
// we should die with ui info // we should die with ui info
die(); die();
} }
public function getUploadToSoundcloudStatusAction(){ public function getUploadToSoundcloudStatusAction()
{
$id = $this->_getParam('id'); $id = $this->_getParam('id');
$type = $this->_getParam('type'); $type = $this->_getParam('type');
@ -302,12 +485,13 @@ class LibraryController extends Zend_Controller_Action
$file = $show_instance->getRecordedFile(); $file = $show_instance->getRecordedFile();
$this->view->error_code = $file->getSoundCloudErrorCode(); $this->view->error_code = $file->getSoundCloudErrorCode();
$this->view->error_msg = $file->getSoundCloudErrorMsg(); $this->view->error_msg = $file->getSoundCloudErrorMsg();
} } elseif ($type == "file") {
else if ($type == "file") {
$file = Application_Model_StoredFile::Recall($id); $file = Application_Model_StoredFile::Recall($id);
$this->view->sc_id = $file->getSoundCloudId(); $this->view->sc_id = $file->getSoundCloudId();
$this->view->error_code = $file->getSoundCloudErrorCode(); $this->view->error_code = $file->getSoundCloudErrorCode();
$this->view->error_msg = $file->getSoundCloudErrorMsg(); $this->view->error_msg = $file->getSoundCloudErrorMsg();
} else {
Logging::warn("Trying to upload unknown type: $type with id: $id");
} }
} }
} }

View file

@ -12,8 +12,7 @@ class LoginController extends Zend_Controller_Action
{ {
global $CC_CONFIG; global $CC_CONFIG;
if (Zend_Auth::getInstance()->hasIdentity()) if (Zend_Auth::getInstance()->hasIdentity()) {
{
$this->_redirect('Showbuilder'); $this->_redirect('Showbuilder');
} }
@ -30,21 +29,19 @@ class LoginController extends Zend_Controller_Action
$message = "Please enter your user name and password"; $message = "Please enter your user name and password";
if($request->isPost()) if ($request->isPost()) {
{
// if the post contains recaptcha field, which means form had recaptcha field. // if the post contains recaptcha field, which means form had recaptcha field.
// Hence add the element for validation. // Hence add the element for validation.
if(array_key_exists('recaptcha_response_field', $request->getPost())){ if (array_key_exists('recaptcha_response_field', $request->getPost())) {
$form->addRecaptcha(); $form->addRecaptcha();
} }
if($form->isValid($request->getPost())) if ($form->isValid($request->getPost())) {
{
//get the username and password from the form //get the username and password from the form
$username = $form->getValue('username'); $username = $form->getValue('username');
$password = $form->getValue('password'); $password = $form->getValue('password');
if(Application_Model_Subjects::getLoginAttempts($username) >= 3 && $form->getElement('captcha') == NULL){ if (Application_Model_Subjects::getLoginAttempts($username) >= 3 && $form->getElement('captcha') == NULL) {
$form->addRecaptcha(); $form->addRecaptcha();
}else{ } else {
$authAdapter = Application_Model_Auth::getAuthAdapter(); $authAdapter = Application_Model_Auth::getAuthAdapter();
//pass to the adapter the submitted username and password //pass to the adapter the submitted username and password
@ -53,8 +50,7 @@ class LoginController extends Zend_Controller_Action
$auth = Zend_Auth::getInstance(); $auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter); $result = $auth->authenticate($authAdapter);
if($result->isValid()) if ($result->isValid()) {
{
//all info about this user from the login table omit only the password //all info about this user from the login table omit only the password
$userInfo = $authAdapter->getResultRowObject(null, 'password'); $userInfo = $authAdapter->getResultRowObject(null, 'password');
@ -69,9 +65,7 @@ class LoginController extends Zend_Controller_Action
$tempSess->referrer = 'login'; $tempSess->referrer = 'login';
$this->_redirect('Showbuilder'); $this->_redirect('Showbuilder');
} } else {
else
{
$message = "Wrong username or password provided. Please try again."; $message = "Wrong username or password provided. Please try again.";
Application_Model_Subjects::increaseLoginAttempts($username); Application_Model_Subjects::increaseLoginAttempts($username);
Application_Model_LoginAttempts::increaseAttempts($_SERVER['REMOTE_ADDR']); Application_Model_LoginAttempts::increaseAttempts($_SERVER['REMOTE_ADDR']);
@ -87,7 +81,7 @@ class LoginController extends Zend_Controller_Action
$this->view->form = $form; $this->view->form = $form;
$this->view->airtimeVersion = Application_Model_Preference::GetAirtimeVersion(); $this->view->airtimeVersion = Application_Model_Preference::GetAirtimeVersion();
$this->view->airtimeCopyright = AIRTIME_COPYRIGHT_DATE; $this->view->airtimeCopyright = AIRTIME_COPYRIGHT_DATE;
if(isset($CC_CONFIG['demo'])){ if (isset($CC_CONFIG['demo'])) {
$this->view->demo = $CC_CONFIG['demo']; $this->view->demo = $CC_CONFIG['demo'];
} }
} }
@ -108,8 +102,7 @@ class LoginController extends Zend_Controller_Action
if (!Application_Model_Preference::GetEnableSystemEmail()) { if (!Application_Model_Preference::GetEnableSystemEmail()) {
$this->_redirect('login'); $this->_redirect('login');
} } else {
else {
//uses separate layout without a navigation. //uses separate layout without a navigation.
$this->_helper->layout->setLayout('login'); $this->_helper->layout->setLayout('login');
@ -117,9 +110,16 @@ class LoginController extends Zend_Controller_Action
$request = $this->getRequest(); $request = $this->getRequest();
if ($request->isPost() && $form->isValid($request->getPost())) { if ($request->isPost() && $form->isValid($request->getPost())) {
if (is_null($form->username->getValue()) || $form->username->getValue() == '') {
$user = CcSubjsQuery::create() $user = CcSubjsQuery::create()
->filterByDbEmail($form->email->getValue()) ->filterByDbEmail($form->email->getValue())
->findOne(); ->findOne();
} else {
$user = CcSubjsQuery::create()
->filterByDbEmail($form->email->getValue())
->filterByDbLogin($form->username->getValue())
->findOne();
}
if (!empty($user)) { if (!empty($user)) {
$auth = new Application_Model_Auth(); $auth = new Application_Model_Auth();
@ -130,8 +130,7 @@ class LoginController extends Zend_Controller_Action
} else { } else {
$form->email->addError($this->view->translate("Email could not be sent. Check your mail server settings and ensure it has been configured properly.")); $form->email->addError($this->view->translate("Email could not be sent. Check your mail server settings and ensure it has been configured properly."));
} }
} } else {
else {
$form->email->addError($this->view->translate("Given email not found.")); $form->email->addError($this->view->translate("Given email not found."));
} }
} }
@ -179,7 +178,7 @@ class LoginController extends Zend_Controller_Action
$authAdapter->setIdentity($user->getDbLogin()) $authAdapter->setIdentity($user->getDbLogin())
->setCredential($form->password->getValue()); ->setCredential($form->password->getValue());
$result = $zend_auth->authenticate($authAdapter); $zend_auth->authenticate($authAdapter);
//all info about this user from the login table omit only the password //all info about this user from the login table omit only the password
$userInfo = $authAdapter->getResultRowObject(null, 'password'); $userInfo = $authAdapter->getResultRowObject(null, 'password');
@ -194,6 +193,3 @@ class LoginController extends Zend_Controller_Action
$this->view->form = $form; $this->view->form = $form;
} }
} }

View file

@ -2,7 +2,6 @@
class PlaylistController extends Zend_Controller_Action class PlaylistController extends Zend_Controller_Action
{ {
protected $pl_sess = null;
public function init() public function init()
{ {
@ -22,166 +21,180 @@ class PlaylistController extends Zend_Controller_Action
->addActionContext('set-playlist-description', 'json') ->addActionContext('set-playlist-description', 'json')
->addActionContext('playlist-preview', 'json') ->addActionContext('playlist-preview', 'json')
->addActionContext('get-playlist', 'json') ->addActionContext('get-playlist', 'json')
->addActionContext('save', 'json')
->addActionContext('smart-block-generate', 'json')
->addActionContext('smart-block-shuffle', 'json')
->addActionContext('get-block-info', 'json')
->initContext(); ->initContext();
$this->pl_sess = new Zend_Session_Namespace(UI_PLAYLIST_SESSNAME);
} }
private function getPlaylist() private function getPlaylist($p_type)
{ {
$pl = null; $obj = null;
$objInfo = Application_Model_Library::getObjInfo($p_type);
if (isset($this->pl_sess->id)) { $obj_sess = new Zend_Session_Namespace( UI_PLAYLISTCONTROLLER_OBJ_SESSNAME);
$pl = new Application_Model_Playlist($this->pl_sess->id); if (isset($obj_sess->id)) {
$obj = new $objInfo['className']($obj_sess->id);
$modified = $this->_getParam('modified', null); $modified = $this->_getParam('modified', null);
if ($pl->getLastModified("U") !== $modified) { if ($obj->getLastModified("U") !== $modified) {
$this->createFullResponse($pl); $this->createFullResponse($obj);
throw new PlaylistOutDatedException("You are viewing an older version of {$pl->getName()}"); throw new PlaylistOutDatedException("You are viewing an older version of {$obj->getName()}");
}
}
return $pl;
}
private function changePlaylist($pl_id)
{
if (is_null($pl_id)) {
unset($this->pl_sess->id);
}
else {
$this->pl_sess->id = intval($pl_id);
} }
} }
private function createUpdateResponse($pl) return $obj;
}
private function createUpdateResponse($obj)
{ {
$formatter = new LengthFormatter($pl->getLength()); $formatter = new LengthFormatter($obj->getLength());
$this->view->length = $formatter->format(); $this->view->length = $formatter->format();
$this->view->pl = $pl; $this->view->obj = $obj;
$this->view->contents = $obj->getContents();
$this->view->html = $this->view->render('playlist/update.phtml'); $this->view->html = $this->view->render('playlist/update.phtml');
$this->view->name = $pl->getName(); $this->view->name = $obj->getName();
$this->view->description = $pl->getDescription(); $this->view->description = $obj->getDescription();
$this->view->modified = $pl->getLastModified("U"); $this->view->modified = $obj->getLastModified("U");
unset($this->view->pl); unset($this->view->obj);
} }
private function createFullResponse($pl = null) private function createFullResponse($obj = null, $isJson = false,
$formIsValid = false)
{ {
if (isset($pl)) { $isBlock = false;
$formatter = new LengthFormatter($pl->getLength()); $viewPath = 'playlist/playlist.phtml';
if ($obj instanceof Application_Model_Block) {
$isBlock = true;
$viewPath = 'playlist/smart-block.phtml';
}
if (isset($obj)) {
$formatter = new LengthFormatter($obj->getLength());
$this->view->length = $formatter->format(); $this->view->length = $formatter->format();
$this->view->pl = $pl; if ($isBlock) {
$this->view->id = $pl->getId(); $form = new Application_Form_SmartBlockCriteria();
$this->view->html = $this->view->render('playlist/playlist.phtml'); $form->removeDecorator('DtDdWrapper');
unset($this->view->pl); $form->startForm($obj->getId(), $formIsValid);
$this->view->form = $form;
$this->view->obj = $obj;
$this->view->id = $obj->getId();
if ($isJson) {
return $this->view->render($viewPath);
} else {
$this->view->html = $this->view->render($viewPath);
}
} else {
$this->view->obj = $obj;
$this->view->id = $obj->getId();
$this->view->html = $this->view->render($viewPath);
unset($this->view->obj);
}
} else {
if ($isJson) {
return $this->view->render($viewPath);
} else {
$this->view->html = $this->view->render($viewPath);
} }
else {
$this->view->html = $this->view->render('playlist/playlist.phtml');
} }
} }
private function playlistOutdated($pl, $e) private function playlistOutdated($e)
{ {
$this->view->error = $e->getMessage(); $this->view->error = $e->getMessage();
} }
private function playlistNotFound() private function blockDynamic($obj)
{ {
$this->view->error = "Playlist not found"; $this->view->error = "You cannot add tracks to dynamic blocks.";
$this->createFullResponse($obj);
}
Logging::log("Playlist not found"); private function playlistNotFound($p_type, $p_isJson = false)
$this->changePlaylist(null); {
$p_type = ucfirst($p_type);
$this->view->error = "{$p_type} not found";
Logging::info("{$p_type} not found");
Application_Model_Library::changePlaylist(null, $p_type);
if (!$p_isJson) {
$this->createFullResponse(null);
} else {
die(json_encode(array("error"=>$this->view->error, "result"=>1, "html"=>$this->createFullResponse(null, $p_isJson))));
}
}
private function playlistNoPermission($p_type)
{
$this->view->error = "You don't have permission to delete selected {$p_type}(s).";
$this->changePlaylist(null, $p_type);
$this->createFullResponse(null); $this->createFullResponse(null);
} }
private function playlistUnknownError($e) private function playlistUnknownError($e)
{ {
$this->view->error = "Something went wrong."; $this->view->error = "Something went wrong.";
Logging::info($e->getMessage());
Logging::log("{$e->getFile()}");
Logging::log("{$e->getLine()}");
Logging::log("{$e->getMessage()}");
} }
public function indexAction() private function wrongTypeToBlock($obj)
{ {
global $CC_CONFIG; $this->view->error = "You can only add tracks to smart block.";
$this->createFullResponse($obj);
$request = $this->getRequest();
$baseUrl = $request->getBaseUrl();
$this->view->headScript()->appendFile($baseUrl.'/js/blockui/jquery.blockUI.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/contextmenu/jquery.contextMenu.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/js/jquery.dataTables.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.pluginAPI.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.fnSetFilteringDelay.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.ColVis.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.ColReorder.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.FixedColumns.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/buttons/buttons.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/utilities/utilities.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/library/library.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($this->view->baseUrl('/js/airtime/library/events/library_playlistbuilder.js'),'text/javascript');
$this->view->headLink()->appendStylesheet($baseUrl.'/css/media_library.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'/css/jquery.contextMenu.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'/css/datatables/css/ColVis.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'/css/datatables/css/ColReorder.css?'.$CC_CONFIG['airtime_version']);
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/library/spl.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headLink()->appendStylesheet($baseUrl.'/css/playlist_builder.css?'.$CC_CONFIG['airtime_version']);
try {
if (isset($this->pl_sess->id)) {
$pl = new Application_Model_Playlist($this->pl_sess->id);
$this->view->pl = $pl;
$formatter = new LengthFormatter($pl->getLength());
$this->view->length = $formatter->format();
}
}
catch (PlaylistNotFoundException $e) {
$this->playlistNotFound();
}
catch (Exception $e) {
$this->playlistUnknownError($e);
} }
private function wrongTypeToPlaylist($obj)
{
$this->view->error = "You can only add tracks, smart blocks, and webstreams to playlists.";
$this->createFullResponse($obj);
} }
public function newAction() public function newAction()
{ {
$pl_sess = $this->pl_sess; //$pl_sess = $this->pl_sess;
$userInfo = Zend_Auth::getInstance()->getStorage()->read(); $userInfo = Zend_Auth::getInstance()->getStorage()->read();
$type = $this->_getParam('type');
$pl = new Application_Model_Playlist(); $objInfo = Application_Model_Library::getObjInfo($type);
$pl->setName("Untitled Playlist");
$pl->setPLMetaData('dc:creator', $userInfo->id);
$this->changePlaylist($pl->getId()); $name = 'Untitled Playlist';
$this->createFullResponse($pl); if ($type == 'block') {
$name = 'Untitled Smart Block';
}
$obj = new $objInfo['className']();
$obj->setName($name);
$obj->setMetadata('dc:creator', $userInfo->id);
Application_Model_Library::changePlaylist($obj->getId(), $type);
$this->createFullResponse($obj);
} }
public function editAction() public function editAction()
{ {
$id = $this->_getParam('id', null); $id = $this->_getParam('id', null);
Logging::log("editing playlist {$id}"); $type = $this->_getParam('type');
$objInfo = Application_Model_Library::getObjInfo($type);
Logging::info("editing {$type} {$id}");
if (!is_null($id)) { if (!is_null($id)) {
$this->changePlaylist($id); Application_Model_Library::changePlaylist($id, $type);
} }
try { try {
$pl = new Application_Model_Playlist($id); $obj = new $objInfo['className']($id);
$this->createFullResponse($pl); $this->createFullResponse($obj);
} } catch (PlaylistNotFoundException $e) {
catch (PlaylistNotFoundException $e) {
$this->playlistNotFound(); $this->playlistNotFound();
} } catch (Exception $e) {
catch (Exception $e) {
$this->playlistUnknownError($e); $this->playlistUnknownError($e);
} }
} }
@ -190,50 +203,92 @@ class PlaylistController extends Zend_Controller_Action
{ {
$ids = $this->_getParam('ids'); $ids = $this->_getParam('ids');
$ids = (!is_array($ids)) ? array($ids) : $ids; $ids = (!is_array($ids)) ? array($ids) : $ids;
$pl = null; $type = $this->_getParam('type');
$obj = null;
$objInfo = Application_Model_Library::getObjInfo($type);
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$obj_sess = new Zend_Session_Namespace(
UI_PLAYLISTCONTROLLER_OBJ_SESSNAME);
try { try {
Logging::info("Currently active {$type} {$obj_sess->id}");
Logging::log("Currently active playlist {$this->pl_sess->id}"); if (in_array($obj_sess->id, $ids)) {
if (in_array($this->pl_sess->id, $ids)) { Logging::info("Deleting currently active {$type}");
Logging::log("Deleting currently active playlist"); Application_Model_Library::changePlaylist(null, $type);
$this->changePlaylist(null); } else {
} Logging::info("Not deleting currently active {$type}");
else { $obj = new $objInfo['className']($obj_sess->id);
Logging::log("Not deleting currently active playlist");
$pl = new Application_Model_Playlist($this->pl_sess->id);
} }
Application_Model_Playlist::DeletePlaylists($ids); if (strcmp($objInfo['className'], 'Application_Model_Playlist')==0) {
$this->createFullResponse($pl); Application_Model_Playlist::deletePlaylists($ids, $userInfo->id);
} else {
Application_Model_Block::deleteBlocks($ids, $userInfo->id);
} }
catch (PlaylistNotFoundException $e) { $this->createFullResponse($obj);
$this->playlistNotFound(); } catch (PlaylistNoPermissionException $e) {
} $this->playlistNoPermission($type);
catch (Exception $e) { } catch (BlockNoPermissionException $e) {
$this->playlistNoPermission($type);
} catch (PlaylistNotFoundException $e) {
$this->playlistNotFound($type);
} catch (Exception $e) {
$this->playlistUnknownError($e); $this->playlistUnknownError($e);
} }
} }
public function addItemsAction() public function addItemsAction()
{ {
$ids = $this->_getParam('ids', array()); $ids = $this->_getParam('aItems', array());
$ids = (!is_array($ids)) ? array($ids) : $ids; $ids = (!is_array($ids)) ? array($ids) : $ids;
$afterItem = $this->_getParam('afterItem', null); $afterItem = $this->_getParam('afterItem', null);
$addType = $this->_getParam('type', 'after'); $addType = $this->_getParam('type', 'after');
// this is the obj type of destination
$obj_type = $this->_getParam('obj_type');
try { try {
$pl = $this->getPlaylist(); $obj = $this->getPlaylist($obj_type);
$pl->addAudioClips($ids, $afterItem, $addType); if ($obj_type == 'playlist') {
$this->createUpdateResponse($pl); foreach ($ids as $id) {
if (is_array($id) && isset($id[1])) {
if ($id[1] == 'playlist') {
throw new WrongTypeToPlaylistException;
} }
catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($pl, $e);
} }
catch (PlaylistNotFoundException $e) {
$this->playlistNotFound();
} }
catch (Exception $e) { $obj->addAudioClips($ids, $afterItem, $addType);
} elseif ($obj->isStatic()) {
// if the dest is a block object
//check if any items are playlists
foreach ($ids as $id) {
if (is_array($id) && isset($id[1])) {
if ($id[1] != 'audioclip') {
throw new WrongTypeToBlockException;
}
}
}
$obj->addAudioClips($ids, $afterItem, $addType);
} else {
throw new BlockDynamicException;
}
$this->createUpdateResponse($obj);
} catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($e);
} catch (PlaylistNotFoundException $e) {
$this->playlistNotFound($obj_type);
} catch (WrongTypeToBlockException $e) {
$this->wrongTypeToBlock($obj);
} catch (WrongTypeToPlaylistException $e) {
$this->wrongTypeToPlaylist($obj);
} catch (BlockDynamicException $e) {
$this->blockDynamic($obj);
} catch (BlockNotFoundException $e) {
$this->playlistNotFound($obj_type);
} catch (Exception $e) {
$this->playlistUnknownError($e); $this->playlistUnknownError($e);
} }
} }
@ -243,20 +298,17 @@ class PlaylistController extends Zend_Controller_Action
$ids = $this->_getParam('ids'); $ids = $this->_getParam('ids');
$ids = (!is_array($ids)) ? array($ids) : $ids; $ids = (!is_array($ids)) ? array($ids) : $ids;
$afterItem = $this->_getParam('afterItem', null); $afterItem = $this->_getParam('afterItem', null);
$modified = $this->_getParam('modified'); $type = $this->_getParam('obj_type');
try { try {
$pl = $this->getPlaylist(); $obj = $this->getPlaylist($type);
$pl->moveAudioClips($ids, $afterItem); $obj->moveAudioClips($ids, $afterItem);
$this->createUpdateResponse($pl); $this->createUpdateResponse($obj);
} } catch (PlaylistOutDatedException $e) {
catch (PlaylistOutDatedException $e) { $this->playlistOutdated($e);
$this->playlistOutdated($pl, $e); } catch (PlaylistNotFoundException $e) {
} $this->playlistNotFound($type);
catch (PlaylistNotFoundException $e) { } catch (Exception $e) {
$this->playlistNotFound();
}
catch (Exception $e) {
$this->playlistUnknownError($e); $this->playlistUnknownError($e);
} }
} }
@ -266,19 +318,17 @@ class PlaylistController extends Zend_Controller_Action
$ids = $this->_getParam('ids'); $ids = $this->_getParam('ids');
$ids = (!is_array($ids)) ? array($ids) : $ids; $ids = (!is_array($ids)) ? array($ids) : $ids;
$modified = $this->_getParam('modified'); $modified = $this->_getParam('modified');
$type = $this->_getParam('obj_type');
try { try {
$pl = $this->getPlaylist(); $obj = $this->getPlaylist($type);
$pl->delAudioClips($ids); $obj->delAudioClips($ids);
$this->createUpdateResponse($pl); $this->createUpdateResponse($obj);
} } catch (PlaylistOutDatedException $e) {
catch (PlaylistOutDatedException $e) { $this->playlistOutdated($e);
$this->playlistOutdated($pl, $e); } catch (PlaylistNotFoundException $e) {
} $this->playlistNotFound($type);
catch (PlaylistNotFoundException $e) { } catch (Exception $e) {
$this->playlistNotFound();
}
catch (Exception $e) {
$this->playlistUnknownError($e); $this->playlistUnknownError($e);
} }
} }
@ -288,26 +338,23 @@ class PlaylistController extends Zend_Controller_Action
$id = $this->_getParam('id'); $id = $this->_getParam('id');
$cueIn = $this->_getParam('cueIn', null); $cueIn = $this->_getParam('cueIn', null);
$cueOut = $this->_getParam('cueOut', null); $cueOut = $this->_getParam('cueOut', null);
$type = $this->_getParam('type');
try { try {
$pl = $this->getPlaylist(); $obj = $this->getPlaylist($type);
$response = $pl->changeClipLength($id, $cueIn, $cueOut); $response = $obj->changeClipLength($id, $cueIn, $cueOut);
if (!isset($response["error"])) { if (!isset($response["error"])) {
$this->view->response = $response; $this->view->response = $response;
$this->createUpdateResponse($pl); $this->createUpdateResponse($obj);
} } else {
else {
$this->view->cue_error = $response["error"]; $this->view->cue_error = $response["error"];
} }
} } catch (PlaylistOutDatedException $e) {
catch (PlaylistOutDatedException $e) { $this->playlistOutdated($e);
$this->playlistOutdated($pl, $e); } catch (PlaylistNotFoundException $e) {
} $this->playlistNotFound($type);
catch (PlaylistNotFoundException $e) { } catch (Exception $e) {
$this->playlistNotFound();
}
catch (Exception $e) {
$this->playlistUnknownError($e); $this->playlistUnknownError($e);
} }
} }
@ -317,47 +364,42 @@ class PlaylistController extends Zend_Controller_Action
$id = $this->_getParam('id'); $id = $this->_getParam('id');
$fadeIn = $this->_getParam('fadeIn', null); $fadeIn = $this->_getParam('fadeIn', null);
$fadeOut = $this->_getParam('fadeOut', null); $fadeOut = $this->_getParam('fadeOut', null);
$type = $this->_getParam('type');
try { try {
$pl = $this->getPlaylist(); $obj = $this->getPlaylist($type);
$response = $pl->changeFadeInfo($id, $fadeIn, $fadeOut); $response = $obj->changeFadeInfo($id, $fadeIn, $fadeOut);
if (!isset($response["error"])) { if (!isset($response["error"])) {
$this->createUpdateResponse($pl); $this->createUpdateResponse($obj);
$this->view->response = $response; $this->view->response = $response;
} } else {
else {
$this->view->fade_error = $response["error"]; $this->view->fade_error = $response["error"];
} }
} } catch (PlaylistOutDatedException $e) {
catch (PlaylistOutDatedException $e) { $this->playlistOutdated($e);
$this->playlistOutdated($pl, $e); } catch (PlaylistNotFoundException $e) {
} $this->playlistNotFound($type);
catch (PlaylistNotFoundException $e) { } catch (Exception $e) {
$this->playlistNotFound();
}
catch (Exception $e) {
$this->playlistUnknownError($e); $this->playlistUnknownError($e);
} }
} }
public function getPlaylistFadesAction() public function getPlaylistFadesAction()
{ {
$type = $this->_getParam('type');
try { try {
$pl = $this->getPlaylist(); $obj = $this->getPlaylist($type);
$fades = $pl->getFadeInfo(0); $fades = $obj->getFadeInfo(0);
$this->view->fadeIn = $fades[0]; $this->view->fadeIn = $fades[0];
$fades = $pl->getFadeInfo($pl->getSize()-1); $fades = $obj->getFadeInfo($obj->getSize()-1);
$this->view->fadeOut = $fades[1]; $this->view->fadeOut = $fades[1];
} } catch (PlaylistOutDatedException $e) {
catch (PlaylistOutDatedException $e) { $this->playlistOutdated($e);
$this->playlistOutdated($pl, $e); } catch (PlaylistNotFoundException $e) {
} $this->playlistNotFound($type);
catch (PlaylistNotFoundException $e) { } catch (Exception $e) {
$this->playlistNotFound();
}
catch (Exception $e) {
$this->playlistUnknownError($e); $this->playlistUnknownError($e);
} }
} }
@ -371,63 +413,145 @@ class PlaylistController extends Zend_Controller_Action
{ {
$fadeIn = $this->_getParam('fadeIn', null); $fadeIn = $this->_getParam('fadeIn', null);
$fadeOut = $this->_getParam('fadeOut', null); $fadeOut = $this->_getParam('fadeOut', null);
$type = $this->_getParam('type');
try { try {
$pl = $this->getPlaylist(); $obj = $this->getPlaylist($type);
$pl->setPlaylistfades($fadeIn, $fadeOut); $obj->setfades($fadeIn, $fadeOut);
$this->view->modified = $pl->getLastModified("U"); $this->view->modified = $obj->getLastModified("U");
} } catch (PlaylistOutDatedException $e) {
catch (PlaylistOutDatedException $e) { $this->playlistOutdated($e);
$this->playlistOutdated($pl, $e); } catch (PlaylistNotFoundException $e) {
} $this->playlistNotFound($type);
catch (PlaylistNotFoundException $e) { } catch (Exception $e) {
$this->playlistNotFound();
}
catch (Exception $e) {
$this->playlistUnknownError($e); $this->playlistUnknownError($e);
} }
} }
public function setPlaylistNameAction() public function setPlaylistNameDescAction()
{ {
$name = $this->_getParam('name', 'Unknown Playlist'); $name = $this->_getParam('name', 'Unknown Playlist');
try {
$pl = $this->getPlaylist();
$pl->setName($name);
$this->view->playlistName = $name;
$this->view->modified = $pl->getLastModified("U");
}
catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($pl, $e);
}
catch (PlaylistNotFoundException $e) {
$this->playlistNotFound();
}
catch (Exception $e) {
$this->playlistUnknownError($e);
}
}
public function setPlaylistDescriptionAction()
{
$description = $this->_getParam('description', ""); $description = $this->_getParam('description', "");
$type = $this->_getParam('type');
try { try {
$pl = $this->getPlaylist(); $obj = $this->getPlaylist($type);
$pl->setDescription($description); $obj->setName(trim($name));
$this->view->description = $pl->getDescription(); $obj->setDescription($description);
$this->view->modified = $pl->getLastModified("U"); $this->view->description = $description;
} $this->view->playlistName = $name;
catch (PlaylistOutDatedException $e) { $this->view->modified = $obj->getLastModified("U");
$this->playlistOutdated($pl, $e); } catch (PlaylistOutDatedException $e) {
} $this->playlistOutdated($e);
catch (PlaylistNotFoundException $e) { } catch (PlaylistNotFoundException $e) {
$this->playlistNotFound(); $this->playlistNotFound($type, true);
} } catch (Exception $e) {
catch (Exception $e) {
$this->playlistUnknownError($e); $this->playlistUnknownError($e);
} }
} }
public function saveAction()
{
$request = $this->getRequest();
$params = $request->getPost();
$result = array();
if ($params['type'] == 'block') {
try {
$bl = new Application_Model_Block($params['obj_id']);
} catch (BlockNotFoundException $e) {
$this->playlistNotFound('block', true);
}
$form = new Application_Form_SmartBlockCriteria();
$form->startForm($params['obj_id']);
if ($form->isValid($params)) {
$this->setPlaylistNameDescAction();
$bl->saveSmartBlockCriteria($params['data']);
$result['html'] = $this->createFullResponse($bl, true, true);
$result['result'] = 0;
} else {
$this->view->obj = $bl;
$this->view->id = $bl->getId();
$this->view->form = $form;
$this->view->unsavedName = $params['name'];
$this->view->unsavedDesc = $params['description'];
$viewPath = 'playlist/smart-block.phtml';
$result['html'] = $this->view->render($viewPath);
$result['result'] = 1;
}
} else if ($params['type'] == 'playlist') {
$this->setPlaylistNameDescAction();
}
$result["modified"] = $this->view->modified;
die(json_encode($result));
}
public function smartBlockGenerateAction()
{
$request = $this->getRequest();
$params = $request->getPost();
//make sure block exists
try {
$bl = new Application_Model_Block($params['obj_id']);
$form = new Application_Form_SmartBlockCriteria();
$form->startForm($params['obj_id']);
if ($form->isValid($params)) {
$result = $bl->generateSmartBlock($params['data']);
die(json_encode(array("result"=>0, "html"=>$this->createFullResponse($bl, true, true))));
} else {
$this->view->obj = $bl;
$this->view->id = $bl->getId();
$this->view->form = $form;
$viewPath = 'playlist/smart-block.phtml';
$result['html'] = $this->view->render($viewPath);
$result['result'] = 1;
die(json_encode($result));
}
} catch (BlockNotFoundException $e) {
$this->playlistNotFound('block', true);
} catch (Exception $e) {
$this->playlistUnknownError($e);
}
}
public function smartBlockShuffleAction()
{
$request = $this->getRequest();
$params = $request->getPost();
try {
$bl = new Application_Model_Block($params['obj_id']);
$result = $bl->shuffleSmartBlock();
if ($result['result'] == 0) {
die(json_encode(array("result"=>0, "html"=>$this->createFullResponse($bl, true))));
} else {
die(json_encode($result));
}
} catch (BlockNotFoundException $e) {
$this->playlistNotFound('block', true);
} catch (Exception $e) {
$this->playlistUnknownError($e);
}
}
public function getBlockInfoAction()
{
$request = $this->getRequest();
$params = $request->getPost();
$bl = new Application_Model_Block($params['id']);
if ($bl->isStatic()) {
$out = $bl->getContents();
$out['isStatic'] = true;
} else {
$out = $bl->getCriteria();
$out['isStatic'] = false;
}
die(json_encode($out));
}
} }
class WrongTypeToBlockException extends Exception {}
class WrongTypeToPlaylistException extends Exception {}
class BlockDynamicException extends Exception {}

View file

@ -1,6 +1,6 @@
<?php <?php
class PlayoutHistoryController extends Zend_Controller_Action class PlayouthistoryController extends Zend_Controller_Action
{ {
public function init() public function init()
{ {
@ -69,8 +69,8 @@ class PlayoutHistoryController extends Zend_Controller_Action
$startsDT = DateTime::createFromFormat("U", $starts_epoch, new DateTimeZone("UTC")); $startsDT = DateTime::createFromFormat("U", $starts_epoch, new DateTimeZone("UTC"));
$endsDT = DateTime::createFromFormat("U", $ends_epoch, new DateTimeZone("UTC")); $endsDT = DateTime::createFromFormat("U", $ends_epoch, new DateTimeZone("UTC"));
Logging::log("history starts {$startsDT->format("Y-m-d H:i:s")}"); Logging::info("history starts {$startsDT->format("Y-m-d H:i:s")}");
Logging::log("history ends {$endsDT->format("Y-m-d H:i:s")}"); Logging::info("history ends {$endsDT->format("Y-m-d H:i:s")}");
$history = new Application_Model_PlayoutHistory($startsDT, $endsDT, $params); $history = new Application_Model_PlayoutHistory($startsDT, $endsDT, $params);

View file

@ -34,17 +34,16 @@ class PluploadController extends Zend_Controller_Action
die('{"jsonrpc" : "2.0", "tempfilepath" : "'.$tempFileName.'" }'); die('{"jsonrpc" : "2.0", "tempfilepath" : "'.$tempFileName.'" }');
} }
public function copyfileAction(){ public function copyfileAction()
{
$upload_dir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload"; $upload_dir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
$filename = $this->_getParam('name'); $filename = $this->_getParam('name');
$tempname = $this->_getParam('tempname'); $tempname = $this->_getParam('tempname');
$result = Application_Model_StoredFile::copyFileToStor($upload_dir, $filename, $tempname); $result = Application_Model_StoredFile::copyFileToStor($upload_dir,
$filename, $tempname);
if (!is_null($result)) if (!is_null($result))
die('{"jsonrpc" : "2.0", "error" : {"code": '.$result['code'].', "message" : "'.$result['message'].'"}}'); die('{"jsonrpc" : "2.0", "error" : '.json_encode($result).'}');
die('{"jsonrpc" : "2.0"}'); die('{"jsonrpc" : "2.0"}');
} }
} }

View file

@ -50,6 +50,7 @@ class PreferenceController extends Zend_Controller_Action
Application_Model_Preference::SetMailServerEmailAddress($values["preferences_email_server"]["email"]); Application_Model_Preference::SetMailServerEmailAddress($values["preferences_email_server"]["email"]);
Application_Model_Preference::SetMailServerPassword($values["preferences_email_server"]["ms_password"]); Application_Model_Preference::SetMailServerPassword($values["preferences_email_server"]["ms_password"]);
Application_Model_Preference::SetMailServerPort($values["preferences_email_server"]["port"]); Application_Model_Preference::SetMailServerPort($values["preferences_email_server"]["port"]);
Application_Model_Preference::SetMailServerRequiresAuth($values["preferences_email_server"]["msRequiresAuth"]);
} }
Application_Model_Preference::SetAutoUploadRecordedShowToSoundcloud($values["preferences_soundcloud"]["UseSoundCloud"]); Application_Model_Preference::SetAutoUploadRecordedShowToSoundcloud($values["preferences_soundcloud"]["UseSoundCloud"]);
@ -84,18 +85,18 @@ class PreferenceController extends Zend_Controller_Action
if ($request->isPost()) { if ($request->isPost()) {
$values = $request->getPost(); $values = $request->getPost();
if ($form->isValid($values)) { if ($form->isValid($values)) {
if (!$isSass && $values["Publicise"] != 1){ if (!$isSass && $values["Publicise"] != 1) {
Application_Model_Preference::SetSupportFeedback($values["SupportFeedback"]); Application_Model_Preference::SetSupportFeedback($values["SupportFeedback"]);
Application_Model_Preference::SetPublicise($values["Publicise"]); Application_Model_Preference::SetPublicise($values["Publicise"]);
if(isset($values["Privacy"])){ if (isset($values["Privacy"])) {
Application_Model_Preference::SetPrivacyPolicyCheck($values["Privacy"]); Application_Model_Preference::SetPrivacyPolicyCheck($values["Privacy"]);
} }
}else{ } else {
Application_Model_Preference::SetHeadTitle($values["stationName"], $this->view); Application_Model_Preference::SetHeadTitle($values["stationName"], $this->view);
Application_Model_Preference::SetPhone($values["Phone"]); Application_Model_Preference::SetPhone($values["Phone"]);
Application_Model_Preference::SetEmail($values["Email"]); Application_Model_Preference::SetEmail($values["Email"]);
Application_Model_Preference::SetStationWebSite($values["StationWebSite"]); Application_Model_Preference::SetStationWebSite($values["StationWebSite"]);
if(!$isSass){ if (!$isSass) {
Application_Model_Preference::SetSupportFeedback($values["SupportFeedback"]); Application_Model_Preference::SetSupportFeedback($values["SupportFeedback"]);
Application_Model_Preference::SetPublicise($values["Publicise"]); Application_Model_Preference::SetPublicise($values["Publicise"]);
} }
@ -107,7 +108,7 @@ class PreferenceController extends Zend_Controller_Action
Application_Model_Preference::SetStationCity($values["City"]); Application_Model_Preference::SetStationCity($values["City"]);
Application_Model_Preference::SetStationDescription($values["Description"]); Application_Model_Preference::SetStationDescription($values["Description"]);
Application_Model_Preference::SetStationLogo($imagePath); Application_Model_Preference::SetStationLogo($imagePath);
if(!$isSass && isset($values["Privacy"])){ if (!$isSass && isset($values["Privacy"])) {
Application_Model_Preference::SetPrivacyPolicyCheck($values["Privacy"]); Application_Model_Preference::SetPrivacyPolicyCheck($values["Privacy"]);
} }
} }
@ -115,11 +116,11 @@ class PreferenceController extends Zend_Controller_Action
} }
} }
$logo = Application_Model_Preference::GetStationLogo(); $logo = Application_Model_Preference::GetStationLogo();
if($logo){ if ($logo) {
$this->view->logoImg = $logo; $this->view->logoImg = $logo;
} }
$privacyChecked = false; $privacyChecked = false;
if(Application_Model_Preference::GetPrivacyPolicyCheck() == 1){ if (Application_Model_Preference::GetPrivacyPolicyCheck() == 1) {
$privacyChecked = true; $privacyChecked = true;
} }
$this->view->privacyChecked = $privacyChecked; $this->view->privacyChecked = $privacyChecked;
@ -132,7 +133,7 @@ class PreferenceController extends Zend_Controller_Action
{ {
global $CC_CONFIG; global $CC_CONFIG;
if(Application_Model_Preference::GetPlanLevel() == 'disabled'){ if (Application_Model_Preference::GetPlanLevel() == 'disabled') {
$request = $this->getRequest(); $request = $this->getRequest();
$baseUrl = $request->getBaseUrl(); $baseUrl = $request->getBaseUrl();
@ -159,17 +160,16 @@ class PreferenceController extends Zend_Controller_Action
// get current settings // get current settings
$temp = Application_Model_StreamSetting::getStreamSetting(); $temp = Application_Model_StreamSetting::getStreamSetting();
$setting = array(); $setting = array();
foreach ($temp as $t){ foreach ($temp as $t) {
$setting[$t['keyname']] = $t['value']; $setting[$t['keyname']] = $t['value'];
} }
// get predefined type and bitrate from pref table // get predefined type and bitrate from pref table
$temp_types = Application_Model_Preference::GetStreamType(); $temp_types = Application_Model_Preference::GetStreamType();
$stream_types = array(); $stream_types = array();
foreach ($temp_types as $type){ foreach ($temp_types as $type) {
if(trim($type) == "ogg"){ if (trim($type) == "ogg") {
$temp = "OGG/VORBIS"; $temp = "OGG/VORBIS";
}else{ } else {
$temp = strtoupper(trim($type)); $temp = strtoupper(trim($type));
} }
$stream_types[trim($type)] = $temp; $stream_types[trim($type)] = $temp;
@ -178,8 +178,8 @@ class PreferenceController extends Zend_Controller_Action
$temp_bitrate = Application_Model_Preference::GetStreamBitrate(); $temp_bitrate = Application_Model_Preference::GetStreamBitrate();
$max_bitrate = intval(Application_Model_Preference::GetMaxBitrate()); $max_bitrate = intval(Application_Model_Preference::GetMaxBitrate());
$stream_bitrates = array(); $stream_bitrates = array();
foreach ($temp_bitrate as $type){ foreach ($temp_bitrate as $type) {
if(intval($type) <= $max_bitrate){ if (intval($type) <= $max_bitrate) {
$stream_bitrates[trim($type)] = strtoupper(trim($type))." Kbit/s"; $stream_bitrates[trim($type)] = strtoupper(trim($type))." Kbit/s";
} }
} }
@ -193,7 +193,7 @@ class PreferenceController extends Zend_Controller_Action
$live_stream_subform = new Application_Form_LiveStreamingPreferences(); $live_stream_subform = new Application_Form_LiveStreamingPreferences();
$form->addSubForm($live_stream_subform, "live_stream_subform"); $form->addSubForm($live_stream_subform, "live_stream_subform");
for($i=1; $i<=$num_of_stream; $i++){ for ($i=1; $i<=$num_of_stream; $i++) {
$subform = new Application_Form_StreamSettingSubForm(); $subform = new Application_Form_StreamSettingSubForm();
$subform->setPrefix($i); $subform->setPrefix($i);
$subform->setSetting($setting); $subform->setSetting($setting);
@ -203,12 +203,11 @@ class PreferenceController extends Zend_Controller_Action
$form->addSubForm($subform, "s".$i."_subform"); $form->addSubForm($subform, "s".$i."_subform");
} }
if ($request->isPost()) { if ($request->isPost()) {
$post_data = $request->getPost(); $values = $request->getPost();
$error = false; $error = false;
$values = $post_data;
if($form->isValid($post_data)){ if ($form->isValid($values)) {
if (!$isSaas) { if (!$isSaas) {
$values['output_sound_device'] = $form->getValue('output_sound_device'); $values['output_sound_device'] = $form->getValue('output_sound_device');
$values['output_sound_device_type'] = $form->getValue('output_sound_device_type'); $values['output_sound_device_type'] = $form->getValue('output_sound_device_type');
@ -221,8 +220,8 @@ class PreferenceController extends Zend_Controller_Action
// this goes into cc_pref table // this goes into cc_pref table
Application_Model_Preference::SetStreamLabelFormat($values['streamFormat']); Application_Model_Preference::SetStreamLabelFormat($values['streamFormat']);
Application_Model_Preference::SetLiveSteamMasterUsername($values["master_username"]); Application_Model_Preference::SetLiveStreamMasterUsername($values["master_username"]);
Application_Model_Preference::SetLiveSteamMasterPassword($values["master_password"]); Application_Model_Preference::SetLiveStreamMasterPassword($values["master_password"]);
Application_Model_Preference::SetDefaultTransitionFade($values["transition_fade"]); Application_Model_Preference::SetDefaultTransitionFade($values["transition_fade"]);
Application_Model_Preference::SetAutoTransition($values["auto_transition"]); Application_Model_Preference::SetAutoTransition($values["auto_transition"]);
Application_Model_Preference::SetAutoSwitch($values["auto_switch"]); Application_Model_Preference::SetAutoSwitch($values["auto_switch"]);
@ -232,8 +231,7 @@ class PreferenceController extends Zend_Controller_Action
$master_connection_url = "http://".$_SERVER['SERVER_NAME'].":".$values["master_harbor_input_port"]."/".$values["master_harbor_input_mount_point"]; $master_connection_url = "http://".$_SERVER['SERVER_NAME'].":".$values["master_harbor_input_port"]."/".$values["master_harbor_input_mount_point"];
if (empty($values["master_harbor_input_port"]) || empty($values["master_harbor_input_mount_point"])) { if (empty($values["master_harbor_input_port"]) || empty($values["master_harbor_input_mount_point"])) {
Application_Model_Preference::SetMasterDJSourceConnectionURL('N/A'); Application_Model_Preference::SetMasterDJSourceConnectionURL('N/A');
} } else {
else {
Application_Model_Preference::SetMasterDJSourceConnectionURL($master_connection_url); Application_Model_Preference::SetMasterDJSourceConnectionURL($master_connection_url);
} }
} else { } else {
@ -244,20 +242,18 @@ class PreferenceController extends Zend_Controller_Action
$live_connection_url = "http://".$_SERVER['SERVER_NAME'].":".$values["dj_harbor_input_port"]."/".$values["dj_harbor_input_mount_point"]; $live_connection_url = "http://".$_SERVER['SERVER_NAME'].":".$values["dj_harbor_input_port"]."/".$values["dj_harbor_input_mount_point"];
if (empty($values["dj_harbor_input_port"]) || empty($values["dj_harbor_input_mount_point"])) { if (empty($values["dj_harbor_input_port"]) || empty($values["dj_harbor_input_mount_point"])) {
Application_Model_Preference::SetLiveDJSourceConnectionURL('N/A'); Application_Model_Preference::SetLiveDJSourceConnectionURL('N/A');
} } else {
else {
Application_Model_Preference::SetLiveDJSourceConnectionURL($live_connection_url); Application_Model_Preference::SetLiveDJSourceConnectionURL($live_connection_url);
} }
} } else {
else {
Application_Model_Preference::SetLiveDJSourceConnectionURL($values["live_dj_connection_url"]); Application_Model_Preference::SetLiveDJSourceConnectionURL($values["live_dj_connection_url"]);
} }
// extra info that goes into cc_stream_setting // extra info that goes into cc_stream_setting
Application_Model_StreamSetting::SetMasterLiveSteamPort($values["master_harbor_input_port"]); Application_Model_StreamSetting::setMasterLiveStreamPort($values["master_harbor_input_port"]);
Application_Model_StreamSetting::SetMasterLiveSteamMountPoint($values["master_harbor_input_mount_point"]); Application_Model_StreamSetting::setMasterLiveStreamMountPoint($values["master_harbor_input_mount_point"]);
Application_Model_StreamSetting::SetDJLiveSteamPort($values["dj_harbor_input_port"]); Application_Model_StreamSetting::setDjLiveStreamPort($values["dj_harbor_input_port"]);
Application_Model_StreamSetting::SetDJLiveSteamMountPoint($values["dj_harbor_input_mount_point"]); Application_Model_StreamSetting::setDjLiveStreamMountPoint($values["dj_harbor_input_mount_point"]);
} }
// store stream update timestamp // store stream update timestamp
@ -266,7 +262,7 @@ class PreferenceController extends Zend_Controller_Action
$data = array(); $data = array();
$info = Application_Model_StreamSetting::getStreamSetting(); $info = Application_Model_StreamSetting::getStreamSetting();
$data['setting'] = $info; $data['setting'] = $info;
for($i=1;$i<=$num_of_stream;$i++){ for ($i=1; $i<=$num_of_stream; $i++) {
Application_Model_StreamSetting::setLiquidsoapError($i, "waiting"); Application_Model_StreamSetting::setLiquidsoapError($i, "waiting");
} }
@ -290,19 +286,16 @@ class PreferenceController extends Zend_Controller_Action
$result = array(); $result = array();
if(is_null($path)) if (is_null($path)) {
{
$element = array(); $element = array();
$element["name"] = "path should be specified"; $element["name"] = "path should be specified";
$element["isFolder"] = false; $element["isFolder"] = false;
$element["isError"] = true; $element["isError"] = true;
$result[$path] = $element; $result[$path] = $element;
} } else {
else
{
$path = $path.'/'; $path = $path.'/';
$handle = opendir($path); $handle = opendir($path);
if ($handle !== false){ if ($handle !== false) {
while (false !== ($file = readdir($handle))) { while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") { if ($file != "." && $file != "..") {
//only show directories that aren't private. //only show directories that aren't private.
@ -329,7 +322,7 @@ class PreferenceController extends Zend_Controller_Action
$watched_dirs_form = new Application_Form_WatchedDirPreferences(); $watched_dirs_form = new Application_Form_WatchedDirPreferences();
$res = Application_Model_MusicDir::setStorDir($chosen); $res = Application_Model_MusicDir::setStorDir($chosen);
if($res['code'] != 0){ if ($res['code'] != 0) {
$watched_dirs_form->populate(array('storageFolder' => $chosen)); $watched_dirs_form->populate(array('storageFolder' => $chosen));
$watched_dirs_form->getElement($element)->setErrors(array($res['error'])); $watched_dirs_form->getElement($element)->setErrors(array($res['error']));
} }
@ -344,7 +337,7 @@ class PreferenceController extends Zend_Controller_Action
$watched_dirs_form = new Application_Form_WatchedDirPreferences(); $watched_dirs_form = new Application_Form_WatchedDirPreferences();
$res = Application_Model_MusicDir::addWatchedDir($chosen); $res = Application_Model_MusicDir::addWatchedDir($chosen);
if($res['code'] != 0){ if ($res['code'] != 0) {
$watched_dirs_form->populate(array('watchedFolder' => $chosen)); $watched_dirs_form->populate(array('watchedFolder' => $chosen));
$watched_dirs_form->getElement($element)->setErrors(array($res['error'])); $watched_dirs_form->getElement($element)->setErrors(array($res['error']));
} }
@ -373,22 +366,24 @@ class PreferenceController extends Zend_Controller_Action
$this->view->subform = $watched_dirs_form->render(); $this->view->subform = $watched_dirs_form->render();
} }
public function isImportInProgressAction(){ public function isImportInProgressAction()
{
$now = time(); $now = time();
$res = false; $res = false;
if(Application_Model_Preference::GetImportTimestamp()+10 > $now){ if (Application_Model_Preference::GetImportTimestamp()+10 > $now) {
$res = true; $res = true;
} }
die(json_encode($res)); die(json_encode($res));
} }
public function getLiquidsoapStatusAction(){ public function getLiquidsoapStatusAction()
{
$out = array(); $out = array();
$num_of_stream = intval(Application_Model_Preference::GetNumOfStreams()); $num_of_stream = intval(Application_Model_Preference::GetNumOfStreams());
for($i=1; $i<=$num_of_stream; $i++){ for ($i=1; $i<=$num_of_stream; $i++) {
$status = Application_Model_StreamSetting::getLiquidsoapError($i); $status = Application_Model_StreamSetting::getLiquidsoapError($i);
$status = $status == NULL?"Problem with Liquidsoap...":$status; $status = $status == NULL?"Problem with Liquidsoap...":$status;
if(!Application_Model_StreamSetting::getStreamEnabled($i)){ if (!Application_Model_StreamSetting::getStreamEnabled($i)) {
$status = "N/A"; $status = "N/A";
} }
$out[] = array("id"=>$i, "status"=>$status); $out[] = array("id"=>$i, "status"=>$status);
@ -396,16 +391,17 @@ class PreferenceController extends Zend_Controller_Action
die(json_encode($out)); die(json_encode($out));
} }
public function setSourceConnectionUrlAction(){ public function setSourceConnectionUrlAction()
{
$request = $this->getRequest(); $request = $this->getRequest();
$type = $request->getParam("type", null); $type = $request->getParam("type", null);
$url = urldecode($request->getParam("url", null)); $url = urldecode($request->getParam("url", null));
$override = $request->getParam("override", false); $override = $request->getParam("override", false);
if($type == 'masterdj'){ if ($type == 'masterdj') {
Application_Model_Preference::SetMasterDJSourceConnectionURL($url); Application_Model_Preference::SetMasterDJSourceConnectionURL($url);
Application_Model_Preference::SetMasterDjConnectionUrlOverride($override); Application_Model_Preference::SetMasterDjConnectionUrlOverride($override);
}elseif($type == 'livedj'){ } elseif ($type == 'livedj') {
Application_Model_Preference::SetLiveDJSourceConnectionURL($url); Application_Model_Preference::SetLiveDJSourceConnectionURL($url);
Application_Model_Preference::SetLiveDjConnectionUrlOverride($override); Application_Model_Preference::SetLiveDjConnectionUrlOverride($override);
} }
@ -413,6 +409,3 @@ class PreferenceController extends Zend_Controller_Action
die(); die();
} }
} }

View file

@ -32,6 +32,7 @@ class ScheduleController extends Zend_Controller_Action
->addActionContext('edit-show-instance', 'json') ->addActionContext('edit-show-instance', 'json')
->addActionContext('dj-edit-show', 'json') ->addActionContext('dj-edit-show', 'json')
->addActionContext('calculate-duration', 'json') ->addActionContext('calculate-duration', 'json')
->addActionContext('get-current-show', 'json')
->initContext(); ->initContext();
$this->sched_sess = new Zend_Session_Namespace("schedule"); $this->sched_sess = new Zend_Session_Namespace("schedule");
@ -73,6 +74,7 @@ class ScheduleController extends Zend_Controller_Action
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.ColReorder.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.ColReorder.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.FixedColumns.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.FixedColumns.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.TableTools.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.TableTools.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.columnFilter.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/buttons/buttons.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/buttons/buttons.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($this->view->baseUrl('/js/airtime/library/events/library_showbuilder.js?'.$CC_CONFIG['airtime_version']),'text/javascript'); $this->view->headScript()->appendFile($this->view->baseUrl('/js/airtime/library/events/library_showbuilder.js?'.$CC_CONFIG['airtime_version']),'text/javascript');
@ -89,9 +91,9 @@ class ScheduleController extends Zend_Controller_Action
Application_Model_Schedule::createNewFormSections($this->view); Application_Model_Schedule::createNewFormSections($this->view);
$user = Application_Model_User::GetCurrentUser(); $user = Application_Model_User::getCurrentUser();
if($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))){ if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
$this->view->preloadShowForm = true; $this->view->preloadShowForm = true;
} }
@ -109,12 +111,23 @@ class ScheduleController extends Zend_Controller_Action
$user = new Application_Model_User($userInfo->id); $user = new Application_Model_User($userInfo->id);
if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
$editable = true; $editable = true;
} } else {
else {
$editable = false; $editable = false;
} }
$this->view->events = Application_Model_Show::getFullCalendarEvents($start, $end, $editable); $events = &Application_Model_Show::getFullCalendarEvents($start, $end, $editable);
$this->view->events = $events;
}
public function getCurrentShowAction()
{
$currentShow = Application_Model_Show::getCurrentShow();
if (!empty($currentShow)) {
$this->view->si_id = $currentShow[0]["instance_id"];
$this->view->current_show = true;
} else {
$this->view->current_show = false;
}
} }
public function moveShowAction() public function moveShowAction()
@ -129,8 +142,9 @@ class ScheduleController extends Zend_Controller_Action
if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
try { try {
$showInstance = new Application_Model_ShowInstance($showInstanceId); $showInstance = new Application_Model_ShowInstance($showInstanceId);
} catch (Exception $e){ } catch (Exception $e) {
$this->view->show_error = true; $this->view->show_error = true;
return false; return false;
} }
$error = $showInstance->moveShow($deltaDay, $deltaMin); $error = $showInstance->moveShow($deltaDay, $deltaMin);
@ -151,10 +165,11 @@ class ScheduleController extends Zend_Controller_Action
$user = new Application_Model_User($userInfo->id); $user = new Application_Model_User($userInfo->id);
if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
try{ try {
$show = new Application_Model_Show($showId); $show = new Application_Model_Show($showId);
}catch(Exception $e){ } catch (Exception $e) {
$this->view->show_error = true; $this->view->show_error = true;
return false; return false;
} }
$error = $show->resizeShow($deltaDay, $deltaMin); $error = $show->resizeShow($deltaDay, $deltaMin);
@ -176,9 +191,10 @@ class ScheduleController extends Zend_Controller_Action
try { try {
$showInstance = new Application_Model_ShowInstance($showInstanceId); $showInstance = new Application_Model_ShowInstance($showInstanceId);
} } catch (Exception $e) {
catch(Exception $e){ Logging::info($e->getMessage());
$this->view->show_error = true; $this->view->show_error = true;
return false; return false;
} }
@ -190,18 +206,18 @@ class ScheduleController extends Zend_Controller_Action
public function uploadToSoundCloudAction() public function uploadToSoundCloudAction()
{ {
global $CC_CONFIG;
$show_instance = $this->_getParam('id'); $show_instance = $this->_getParam('id');
try{ try {
$show_inst = new Application_Model_ShowInstance($show_instance); $show_inst = new Application_Model_ShowInstance($show_instance);
}catch(Exception $e){ } catch (Exception $e) {
$this->view->show_error = true; $this->view->show_error = true;
return false; return false;
} }
$file = $show_inst->getRecordedFile(); $file = $show_inst->getRecordedFile();
$id = $file->getId(); $id = $file->getId();
$res = exec("/usr/lib/airtime/utils/soundcloud-uploader $id > /dev/null &"); Application_Model_Soundcloud::uploadSoundcloud($id);
// we should die with ui info // we should die with ui info
die(); die();
} }
@ -214,15 +230,16 @@ class ScheduleController extends Zend_Controller_Action
$userInfo = Zend_Auth::getInstance()->getStorage()->read(); $userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id); $user = new Application_Model_User($userInfo->id);
try{ try {
$instance = new Application_Model_ShowInstance($id); $instance = new Application_Model_ShowInstance($id);
}catch(Exception $e){ } catch (Exception $e) {
$this->view->show_error = true; $this->view->show_error = true;
return false; return false;
} }
$isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
$isDJ = $user->isHost($instance->getShowId()); $isDJ = $user->isHostOfShow($instance->getShowId());
$showStartLocalDT = Application_Common_DateHelper::ConvertToLocalDateTime($instance->getShowInstanceStart()); $showStartLocalDT = Application_Common_DateHelper::ConvertToLocalDateTime($instance->getShowInstanceStart());
$showEndLocalDT = Application_Common_DateHelper::ConvertToLocalDateTime($instance->getShowInstanceEnd()); $showEndLocalDT = Application_Common_DateHelper::ConvertToLocalDateTime($instance->getShowInstanceEnd());
@ -262,7 +279,7 @@ class ScheduleController extends Zend_Controller_Action
$fileId = $file->getId(); $fileId = $file->getId();
$scid = $instance->getSoundCloudFileId(); $scid = $instance->getSoundCloudFileId();
if ($scid > 0){ if ($scid > 0) {
$url = $file->getSoundCloudLinkToFile(); $url = $file->getSoundCloudLinkToFile();
$menu["soundcloud_view"] = array("name" => "View on Soundcloud", "icon" => "soundcloud", "url" => $url); $menu["soundcloud_view"] = array("name" => "View on Soundcloud", "icon" => "soundcloud", "url" => $url);
} }
@ -276,8 +293,7 @@ class ScheduleController extends Zend_Controller_Action
if ($instance->isRecorded()) { if ($instance->isRecorded()) {
$menu["cancel_recorded"] = array("name"=> "Cancel Current Show", "icon" => "delete"); $menu["cancel_recorded"] = array("name"=> "Cancel Current Show", "icon" => "delete");
} } else {
else {
if (!$instance->isRebroadcast()) { if (!$instance->isRebroadcast()) {
$menu["edit"] = array("name"=> "Edit Show", "icon" => "edit", "_type"=>"all", "url" => "/Schedule/populate-show-form"); $menu["edit"] = array("name"=> "Edit Show", "icon" => "edit", "_type"=>"all", "url" => "/Schedule/populate-show-form");
@ -301,8 +317,7 @@ class ScheduleController extends Zend_Controller_Action
$menu["del"]["items"]["single"] = array("name"=> "Delete This Instance", "icon" => "delete", "url" => "/schedule/delete-show"); $menu["del"]["items"]["single"] = array("name"=> "Delete This Instance", "icon" => "delete", "url" => "/schedule/delete-show");
$menu["del"]["items"]["following"] = array("name"=> "Delete This Instance and All Following", "icon" => "delete", "url" => "/schedule/cancel-show"); $menu["del"]["items"]["following"] = array("name"=> "Delete This Instance and All Following", "icon" => "delete", "url" => "/schedule/cancel-show");
} } elseif ($isAdminOrPM) {
else if ($isAdminOrPM){
$menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => "/schedule/delete-show"); $menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => "/schedule/delete-show");
} }
@ -316,38 +331,39 @@ class ScheduleController extends Zend_Controller_Action
$showInstanceId = $this->_getParam('id'); $showInstanceId = $this->_getParam('id');
$userInfo = Zend_Auth::getInstance()->getStorage()->read(); $userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id); $user = new Application_Model_User($userInfo->id);
try{ try {
$show = new Application_Model_ShowInstance($showInstanceId); $show = new Application_Model_ShowInstance($showInstanceId);
}catch(Exception $e){ } catch (Exception $e) {
$this->view->show_error = true; $this->view->show_error = true;
return false; return false;
} }
if($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER, UTYPE_HOST),$show->getShowId())) if($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)) || $user->isHostOfShow($show->getShowId()))
$show->clearShow(); $show->clearShow();
} }
public function getCurrentPlaylistAction() public function getCurrentPlaylistAction()
{ {
$range = Application_Model_Schedule::GetPlayOrderRange(); $range = Application_Model_Schedule::GetPlayOrderRange();
$show = Application_Model_Show::GetCurrentShow(); $show = Application_Model_Show::getCurrentShow();
/* Convert all UTC times to localtime before sending back to user. */ /* Convert all UTC times to localtime before sending back to user. */
if (isset($range["previous"])){ if (isset($range["previous"])) {
$range["previous"]["starts"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["previous"]["starts"]); $range["previous"]["starts"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["previous"]["starts"]);
$range["previous"]["ends"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["previous"]["ends"]); $range["previous"]["ends"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["previous"]["ends"]);
} }
if (isset($range["current"])){ if (isset($range["current"])) {
$range["current"]["starts"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["current"]["starts"]); $range["current"]["starts"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["current"]["starts"]);
$range["current"]["ends"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["current"]["ends"]); $range["current"]["ends"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["current"]["ends"]);
} }
if (isset($range["next"])){ if (isset($range["next"])) {
$range["next"]["starts"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["next"]["starts"]); $range["next"]["starts"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["next"]["starts"]);
$range["next"]["ends"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["next"]["ends"]); $range["next"]["ends"] = Application_Common_DateHelper::ConvertToLocalDateTimeString($range["next"]["ends"]);
} }
Application_Model_Show::ConvertToLocalTimeZone($range["currentShow"], array("starts", "ends", "start_timestamp", "end_timestamp")); Application_Model_Show::convertToLocalTimeZone($range["currentShow"], array("starts", "ends", "start_timestamp", "end_timestamp"));
Application_Model_Show::ConvertToLocalTimeZone($range["nextShow"], array("starts", "ends", "start_timestamp", "end_timestamp")); Application_Model_Show::convertToLocalTimeZone($range["nextShow"], array("starts", "ends", "start_timestamp", "end_timestamp"));
$source_status = array(); $source_status = array();
$switch_status = array(); $switch_status = array();
@ -376,18 +392,18 @@ class ScheduleController extends Zend_Controller_Action
{ {
$showInstanceId = $this->sched_sess->showInstanceId; $showInstanceId = $this->sched_sess->showInstanceId;
$group_id = $this->_getParam('groupId'); $group_id = $this->_getParam('groupId');
$search = $this->_getParam('search', null);
$userInfo = Zend_Auth::getInstance()->getStorage()->read(); $userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id); $user = new Application_Model_User($userInfo->id);
try{ try {
$show = new Application_Model_ShowInstance($showInstanceId); $show = new Application_Model_ShowInstance($showInstanceId);
}catch(Exception $e){ } catch (Exception $e) {
$this->view->show_error = true; $this->view->show_error = true;
return false; return false;
} }
if($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER, UTYPE_HOST),$show->getShowId())) { if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)) || $user->isHostOfShow($show->getShowId())) {
$show->removeGroupFromShow($group_id); $show->removeGroupFromShow($group_id);
} }
@ -401,19 +417,21 @@ class ScheduleController extends Zend_Controller_Action
public function showContentDialogAction() public function showContentDialogAction()
{ {
$showInstanceId = $this->_getParam('id'); $showInstanceId = $this->_getParam('id');
try{ try {
$show = new Application_Model_ShowInstance($showInstanceId); $show = new Application_Model_ShowInstance($showInstanceId);
}catch(Exception $e){ } catch (Exception $e) {
$this->view->show_error = true; $this->view->show_error = true;
return false; return false;
} }
$originalShowId = $show->isRebroadcast(); $originalShowId = $show->isRebroadcast();
if (!is_null($originalShowId)){ if (!is_null($originalShowId)) {
try{ try {
$originalShow = new Application_Model_ShowInstance($originalShowId); $originalShow = new Application_Model_ShowInstance($originalShowId);
}catch(Exception $e){ } catch (Exception $e) {
$this->view->show_error = true; $this->view->show_error = true;
return false; return false;
} }
$originalShowName = $originalShow->getName(); $originalShowName = $originalShow->getName();
@ -495,12 +513,10 @@ class ScheduleController extends Zend_Controller_Action
$formRepeats->disable(); $formRepeats->disable();
$formStyle->disable(); $formStyle->disable();
//$formRecord->disable(); //$formRecord->disable();
//$formAbsoluteRebroadcast->disable(); //$formAbsoluteRebroadcast->disable();
//$formRebroadcast->disable(); //$formRebroadcast->disable();
$this->view->action = "edit-show-instance"; $this->view->action = "edit-show-instance";
$this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); $this->view->newForm = $this->view->render('schedule/add-show-form.phtml');
}*/ }*/
@ -513,26 +529,24 @@ class ScheduleController extends Zend_Controller_Action
$isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; $isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true;
$showInstanceId = $this->_getParam('id'); $showInstanceId = $this->_getParam('id');
// $type is used to determine if this edit is for the specific instance or for all
// repeating shows. It's value is either "instance","rebroadcast", or "all"
$type = $this->_getParam('type');
$this->view->action = "edit-show"; $this->view->action = "edit-show";
try{ try {
$showInstance = new Application_Model_ShowInstance($showInstanceId); $showInstance = new Application_Model_ShowInstance($showInstanceId);
}catch(Exception $e){ } catch (Exception $e) {
$this->view->show_error = true; $this->view->show_error = true;
return false; return false;
} }
$isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
$isDJ = $user->isHost($showInstance->getShowId()); $isDJ = $user->isHostOfShow($showInstance->getShowId());
if(!($isAdminOrPM || $isDJ)) { if (!($isAdminOrPM || $isDJ)) {
return; return;
} }
if($isDJ){ if ($isDJ) {
$this->view->action = "dj-edit-show"; $this->view->action = "dj-edit-show";
} }
@ -579,12 +593,12 @@ class ScheduleController extends Zend_Controller_Action
'add_show_duration' => $show->getDuration(true), 'add_show_duration' => $show->getDuration(true),
'add_show_repeats' => $show->isRepeating() ? 1 : 0)); 'add_show_repeats' => $show->isRepeating() ? 1 : 0));
if ($show->isStartDateTimeInPast()){ if ($show->isStartDateTimeInPast()) {
// for a non-repeating show, we should never allow user to change the start time. // for a non-repeating show, we should never allow user to change the start time.
// for the repeating show, we should allow because the form works as repeating template form // for the repeating show, we should allow because the form works as repeating template form
if(!$showInstance->getShow()->isRepeating()){ if (!$showInstance->getShow()->isRepeating()) {
$formWhen->disableStartDateAndTime(); $formWhen->disableStartDateAndTime();
}else{ } else {
$formWhen->getElement('add_show_start_date')->setOptions(array('disabled' => true)); $formWhen->getElement('add_show_start_date')->setOptions(array('disabled' => true));
} }
} }
@ -592,7 +606,7 @@ class ScheduleController extends Zend_Controller_Action
//need to get the days of the week in the php timezone (for the front end). //need to get the days of the week in the php timezone (for the front end).
$days = array(); $days = array();
$showDays = CcShowDaysQuery::create()->filterByDbShowId($showInstance->getShowId())->find(); $showDays = CcShowDaysQuery::create()->filterByDbShowId($showInstance->getShowId())->find();
foreach($showDays as $showDay){ foreach ($showDays as $showDay) {
$showStartDay = new DateTime($showDay->getDbFirstShow(), new DateTimeZone($showDay->getDbTimezone())); $showStartDay = new DateTime($showDay->getDbFirstShow(), new DateTimeZone($showDay->getDbTimezone()));
$showStartDay->setTimezone(new DateTimeZone(date_default_timezone_get())); $showStartDay->setTimezone(new DateTimeZone(date_default_timezone_get()));
array_push($days, $showStartDay->format('w')); array_push($days, $showStartDay->format('w'));
@ -609,7 +623,7 @@ class ScheduleController extends Zend_Controller_Action
$hosts = array(); $hosts = array();
$showHosts = CcShowHostsQuery::create()->filterByDbShow($showInstance->getShowId())->find(); $showHosts = CcShowHostsQuery::create()->filterByDbShow($showInstance->getShowId())->find();
foreach($showHosts as $showHost){ foreach ($showHosts as $showHost) {
array_push($hosts, $showHost->getDbHost()); array_push($hosts, $showHost->getDbHost());
} }
$formWho->populate(array('add_show_hosts' => $hosts)); $formWho->populate(array('add_show_hosts' => $hosts));
@ -618,7 +632,7 @@ class ScheduleController extends Zend_Controller_Action
$formLive->populate($show->getLiveStreamInfo()); $formLive->populate($show->getLiveStreamInfo());
if(!$isSaas){ if (!$isSaas) {
$formRecord = new Application_Form_AddShowRR(); $formRecord = new Application_Form_AddShowRR();
$formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates();
$formRebroadcast = new Application_Form_AddShowRebroadcastDates(); $formRebroadcast = new Application_Form_AddShowRebroadcastDates();
@ -641,7 +655,7 @@ class ScheduleController extends Zend_Controller_Action
$rebroadcastsRelative = $show->getRebroadcastsRelative(); $rebroadcastsRelative = $show->getRebroadcastsRelative();
$rebroadcastFormValues = array(); $rebroadcastFormValues = array();
$i = 1; $i = 1;
foreach ($rebroadcastsRelative as $rebroadcast){ foreach ($rebroadcastsRelative as $rebroadcast) {
$rebroadcastFormValues["add_show_rebroadcast_date_$i"] = $rebroadcast['day_offset']; $rebroadcastFormValues["add_show_rebroadcast_date_$i"] = $rebroadcast['day_offset'];
$rebroadcastFormValues["add_show_rebroadcast_time_$i"] = Application_Common_DateHelper::removeSecondsFromTime($rebroadcast['start_time']); $rebroadcastFormValues["add_show_rebroadcast_time_$i"] = Application_Common_DateHelper::removeSecondsFromTime($rebroadcast['start_time']);
$i++; $i++;
@ -651,20 +665,20 @@ class ScheduleController extends Zend_Controller_Action
$rebroadcastsAbsolute = $show->getRebroadcastsAbsolute(); $rebroadcastsAbsolute = $show->getRebroadcastsAbsolute();
$rebroadcastAbsoluteFormValues = array(); $rebroadcastAbsoluteFormValues = array();
$i = 1; $i = 1;
foreach ($rebroadcastsAbsolute as $rebroadcast){ foreach ($rebroadcastsAbsolute as $rebroadcast) {
$rebroadcastAbsoluteFormValues["add_show_rebroadcast_date_absolute_$i"] = $rebroadcast['start_date']; $rebroadcastAbsoluteFormValues["add_show_rebroadcast_date_absolute_$i"] = $rebroadcast['start_date'];
$rebroadcastAbsoluteFormValues["add_show_rebroadcast_time_absolute_$i"] = $rebroadcast['start_time']; $rebroadcastAbsoluteFormValues["add_show_rebroadcast_time_absolute_$i"] = $rebroadcast['start_time'];
$i++; $i++;
} }
$formAbsoluteRebroadcast->populate($rebroadcastAbsoluteFormValues); $formAbsoluteRebroadcast->populate($rebroadcastAbsoluteFormValues);
if(!$isAdminOrPM){ if (!$isAdminOrPM) {
$formRecord->disable(); $formRecord->disable();
$formAbsoluteRebroadcast->disable(); $formAbsoluteRebroadcast->disable();
$formRebroadcast->disable(); $formRebroadcast->disable();
} }
} }
if(!$isAdminOrPM){ if (!$isAdminOrPM) {
$formWhat->disable(); $formWhat->disable();
$formWho->disable(); $formWho->disable();
$formWhen->disable(); $formWhen->disable();
@ -676,22 +690,23 @@ class ScheduleController extends Zend_Controller_Action
$this->view->entries = 5; $this->view->entries = 5;
} }
public function getFormAction() { public function getFormAction()
{
$user = Application_Model_User::getCurrentUser();
$user = Application_Model_User::GetCurrentUser(); if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
if($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))){
Application_Model_Schedule::createNewFormSections($this->view); Application_Model_Schedule::createNewFormSections($this->view);
$this->view->form = $this->view->render('schedule/add-show-form.phtml'); $this->view->form = $this->view->render('schedule/add-show-form.phtml');
} }
} }
public function djEditShowAction(){ public function djEditShowAction()
{
$js = $this->_getParam('data'); $js = $this->_getParam('data');
$data = array(); $data = array();
//need to convert from serialized jQuery array. //need to convert from serialized jQuery array.
foreach($js as $j){ foreach ($js as $j) {
$data[$j["name"]] = $j["value"]; $data[$j["name"]] = $j["value"];
} }
@ -710,12 +725,12 @@ class ScheduleController extends Zend_Controller_Action
$data = array(); $data = array();
//need to convert from serialized jQuery array. //need to convert from serialized jQuery array.
foreach($js as $j){ foreach ($js as $j) {
$data[$j["name"]] = $j["value"]; $data[$j["name"]] = $j["value"];
} }
$success = Application_Model_Schedule::updateShowInstance($data, $this); $success = Application_Model_Schedule::updateShowInstance($data, $this);
if ($success){ if ($success) {
$this->view->addNewShow = true; $this->view->addNewShow = true;
$this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); $this->view->newForm = $this->view->render('schedule/add-show-form.phtml');
} else { } else {
@ -724,35 +739,36 @@ class ScheduleController extends Zend_Controller_Action
} }
}*/ }*/
public function editShowAction(){ public function editShowAction()
{
//1) Get add_show_start_date since it might not have been sent //1) Get add_show_start_date since it might not have been sent
$js = $this->_getParam('data'); $js = $this->_getParam('data');
$data = array(); $data = array();
//need to convert from serialized jQuery array. //need to convert from serialized jQuery array.
foreach($js as $j){ foreach ($js as $j) {
$data[$j["name"]] = $j["value"]; $data[$j["name"]] = $j["value"];
} }
$data['add_show_hosts'] = $this->_getParam('hosts'); $data['add_show_hosts'] = $this->_getParam('hosts');
$data['add_show_day_check'] = $this->_getParam('days'); $data['add_show_day_check'] = $this->_getParam('days');
if($data['add_show_day_check'] == "") { if ($data['add_show_day_check'] == "") {
$data['add_show_day_check'] = null; $data['add_show_day_check'] = null;
} }
$show = new Application_Model_Show($data['add_show_id']); $show = new Application_Model_Show($data['add_show_id']);
$validateStartDate = true; $validateStartDate = true;
$validateStartTime = true; $validateStartTime = true;
if (!array_key_exists('add_show_start_date', $data)){ if (!array_key_exists('add_show_start_date', $data)) {
//Changing the start date was disabled, since the //Changing the start date was disabled, since the
//array key does not exist. We need to repopulate this entry from the db. //array key does not exist. We need to repopulate this entry from the db.
//The start date will be returned in UTC time, so lets convert it to local time. //The start date will be returned in UTC time, so lets convert it to local time.
$dt = Application_Common_DateHelper::ConvertToLocalDateTime($show->getStartDateAndTime()); $dt = Application_Common_DateHelper::ConvertToLocalDateTime($show->getStartDateAndTime());
$data['add_show_start_date'] = $dt->format("Y-m-d"); $data['add_show_start_date'] = $dt->format("Y-m-d");
if (!array_key_exists('add_show_start_time', $data)){ if (!array_key_exists('add_show_start_time', $data)) {
$data['add_show_start_time'] = $dt->format("H:i"); $data['add_show_start_time'] = $dt->format("H:i");
$validateStartTime = false; $validateStartTime = false;
} }
@ -761,16 +777,24 @@ class ScheduleController extends Zend_Controller_Action
$data['add_show_record'] = $show->isRecorded(); $data['add_show_record'] = $show->isRecorded();
$origianlShowStartDateTime = Application_Common_DateHelper::ConvertToLocalDateTime($show->getStartDateAndTime()); $origianlShowStartDateTime = Application_Common_DateHelper::ConvertToLocalDateTime($show->getStartDateAndTime());
$success = Application_Model_Schedule::addUpdateShow($data, $this, $validateStartDate, $origianlShowStartDateTime);
if ($success){ $success = Application_Model_Schedule::addUpdateShow($data, $this,
$validateStartDate, $origianlShowStartDateTime, true,
$data['add_show_instance_id']);
if ($success) {
$scheduler = new Application_Model_Scheduler();
$showInstances = CcShowInstancesQuery::create()->filterByDbShowId($data['add_show_id'])->find();
foreach ($showInstances as $si) {
$scheduler->removeGaps($si->getDbId());
}
$this->view->addNewShow = true; $this->view->addNewShow = true;
$this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); $this->view->newForm = $this->view->render('schedule/add-show-form.phtml');
} else { } else {
if (!$validateStartDate){ if (!$validateStartDate) {
$this->view->when->getElement('add_show_start_date')->setOptions(array('disabled' => true)); $this->view->when->getElement('add_show_start_date')->setOptions(array('disabled' => true));
} }
if(!$validateStartTime){ if (!$validateStartTime) {
$this->view->when->getElement('add_show_start_time')->setOptions(array('disabled' => true)); $this->view->when->getElement('add_show_start_time')->setOptions(array('disabled' => true));
} }
$this->view->rr->getElement('add_show_record')->setOptions(array('disabled' => true)); $this->view->rr->getElement('add_show_record')->setOptions(array('disabled' => true));
@ -780,45 +804,52 @@ class ScheduleController extends Zend_Controller_Action
} }
} }
public function addShowAction(){ public function addShowAction()
{
$js = $this->_getParam('data'); $js = $this->_getParam('data');
$data = array(); $data = array();
//need to convert from serialized jQuery array. //need to convert from serialized jQuery array.
foreach($js as $j){ foreach ($js as $j) {
$data[$j["name"]] = $j["value"]; $data[$j["name"]] = $j["value"];
} }
$data['add_show_hosts'] = $this->_getParam('hosts'); $data['add_show_hosts'] = $this->_getParam('hosts');
$data['add_show_day_check'] = $this->_getParam('days'); $data['add_show_day_check'] = $this->_getParam('days');
if($data['add_show_day_check'] == "") { if ($data['add_show_day_check'] == "") {
$data['add_show_day_check'] = null; $data['add_show_day_check'] = null;
} }
$validateStartDate = true; $validateStartDate = true;
$success = Application_Model_Schedule::addUpdateShow($data, $this, $validateStartDate); $success = Application_Model_Schedule::addUpdateShow($data, $this,
$validateStartDate);
if ($success){ if ($success) {
$this->view->addNewShow = true; $this->view->addNewShow = true;
$this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); $this->view->newForm = $this->view->render(
'schedule/add-show-form.phtml');
Logging::debug("Show creation succeeded");
} else { } else {
$this->view->addNewShow = true; $this->view->addNewShow = true;
$this->view->form = $this->view->render('schedule/add-show-form.phtml'); $this->view->form = $this->view->render(
'schedule/add-show-form.phtml');
Logging::debug("Show creation failed");
} }
} }
public function cancelShowAction() public function cancelShowAction()
{ {
$user = Application_Model_User::GetCurrentUser(); $user = Application_Model_User::getCurrentUser();
if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
$showInstanceId = $this->_getParam('id'); $showInstanceId = $this->_getParam('id');
try { try {
$showInstance = new Application_Model_ShowInstance($showInstanceId); $showInstance = new Application_Model_ShowInstance($showInstanceId);
} catch(Exception $e) { } catch (Exception $e) {
$this->view->show_error = true; $this->view->show_error = true;
return false; return false;
} }
$show = new Application_Model_Show($showInstance->getShowId()); $show = new Application_Model_Show($showInstance->getShowId());
@ -830,7 +861,7 @@ class ScheduleController extends Zend_Controller_Action
public function cancelCurrentShowAction() public function cancelCurrentShowAction()
{ {
$user = Application_Model_User::GetCurrentUser(); $user = Application_Model_User::getCurrentUser();
if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
$id = $this->_getParam('id'); $id = $this->_getParam('id');
@ -841,17 +872,15 @@ class ScheduleController extends Zend_Controller_Action
// send kick out source stream signal to pypo // send kick out source stream signal to pypo
$data = array("sourcename"=>"live_dj"); $data = array("sourcename"=>"live_dj");
Application_Model_RabbitMq::SendMessageToPypo("disconnect_source", $data); Application_Model_RabbitMq::SendMessageToPypo("disconnect_source", $data);
} } catch (Exception $e) {
catch (Exception $e) {
$this->view->error = $e->getMessage(); $this->view->error = $e->getMessage();
Logging::log($e->getMessage()); Logging::info($e->getMessage());
Logging::log("{$e->getFile()}");
Logging::log("{$e->getLine()}");
} }
} }
} }
public function contentContextMenuAction(){ public function contentContextMenuAction()
{
global $CC_CONFIG; global $CC_CONFIG;
$id = $this->_getParam('id'); $id = $this->_getParam('id');
@ -879,7 +908,8 @@ class ScheduleController extends Zend_Controller_Action
* Sets the user specific preference for which time scale to use in Calendar. * Sets the user specific preference for which time scale to use in Calendar.
* This is only being used by schedule.js at the moment. * This is only being used by schedule.js at the moment.
*/ */
public function setTimeScaleAction() { public function setTimeScaleAction()
{
Application_Model_Preference::SetCalendarTimeScale($this->_getParam('timeScale')); Application_Model_Preference::SetCalendarTimeScale($this->_getParam('timeScale'));
} }
@ -887,17 +917,19 @@ class ScheduleController extends Zend_Controller_Action
* Sets the user specific preference for which time interval to use in Calendar. * Sets the user specific preference for which time interval to use in Calendar.
* This is only being used by schedule.js at the moment. * This is only being used by schedule.js at the moment.
*/ */
public function setTimeIntervalAction() { public function setTimeIntervalAction()
{
Application_Model_Preference::SetCalendarTimeInterval($this->_getParam('timeInterval')); Application_Model_Preference::SetCalendarTimeInterval($this->_getParam('timeInterval'));
} }
public function calculateDurationAction() { public function calculateDurationAction()
{
global $CC_CONFIG; global $CC_CONFIG;
$startParam = $this->_getParam('startTime'); $startParam = $this->_getParam('startTime');
$endParam = $this->_getParam('endTime'); $endParam = $this->_getParam('endTime');
try{ try {
$startDateTime = new DateTime($startParam); $startDateTime = new DateTime($startParam);
$endDateTime = new DateTime($endParam); $endDateTime = new DateTime($endParam);
@ -907,17 +939,17 @@ class ScheduleController extends Zend_Controller_Action
$duration = $UTCEndDateTime->diff($UTCStartDateTime); $duration = $UTCEndDateTime->diff($UTCStartDateTime);
$day = intval($duration->format('%d')); $day = intval($duration->format('%d'));
if($day > 0){ if ($day > 0) {
$hour = intval($duration->format('%h')); $hour = intval($duration->format('%h'));
$min = intval($duration->format('%i')); $min = intval($duration->format('%i'));
$hour += $day * 24; $hour += $day * 24;
$hour = min($hour, 99); $hour = min($hour, 99);
$sign = $duration->format('%r'); $sign = $duration->format('%r');
$result = sprintf('%s%02dh %02dm', $sign, $hour, $min); $result = sprintf('%s%02dh %02dm', $sign, $hour, $min);
}else{ } else {
$result = $duration->format('%r%Hh %Im'); $result = $duration->format('%r%Hh %Im');
} }
}catch (Exception $e){ } catch (Exception $e) {
$result = "Invalid Date"; $result = "Invalid Date";
} }
@ -925,4 +957,3 @@ class ScheduleController extends Zend_Controller_Action
exit(); exit();
} }
} }

View file

@ -16,32 +16,30 @@ class ShowbuilderController extends Zend_Controller_Action
->initContext(); ->initContext();
} }
public function indexAction() { public function indexAction()
{
global $CC_CONFIG; global $CC_CONFIG;
$request = $this->getRequest(); $request = $this->getRequest();
$baseUrl = $request->getBaseUrl(); $baseUrl = $request->getBaseUrl();
$user = Application_Model_User::GetCurrentUser(); $user = Application_Model_User::getCurrentUser();
$userType = $user->getType(); $userType = $user->getType();
$this->view->headScript()->appendScript("localStorage.setItem( 'user-type', '$userType' );"); $this->view->headScript()->appendScript("localStorage.setItem( 'user-type', '$userType' );");
$data = Application_Model_Preference::GetValue("library_datatable", true); $data = Application_Model_Preference::getCurrentLibraryTableSetting();
if ($data != "") { if (!is_null($data)) {
$libraryTable = json_encode(unserialize($data)); $libraryTable = json_encode($data);
$this->view->headScript()->appendScript("localStorage.setItem( 'datatables-library', JSON.stringify($libraryTable) );"); $this->view->headScript()->appendScript("localStorage.setItem( 'datatables-library', JSON.stringify($libraryTable) );");
} } else {
else {
$this->view->headScript()->appendScript("localStorage.setItem( 'datatables-library', '' );"); $this->view->headScript()->appendScript("localStorage.setItem( 'datatables-library', '' );");
} }
$data = Application_Model_Preference::GetValue("timeline_datatable", true); $data = Application_Model_Preference::getTimelineDatatableSetting();
if ($data != "") { if (!is_null($data)) {
$timelineTable = json_encode(unserialize($data)); $timelineTable = json_encode($data);
$this->view->headScript()->appendScript("localStorage.setItem( 'datatables-timeline', JSON.stringify($timelineTable) );"); $this->view->headScript()->appendScript("localStorage.setItem( 'datatables-timeline', JSON.stringify($timelineTable) );");
} } else {
else {
$this->view->headScript()->appendScript("localStorage.setItem( 'datatables-timeline', '' );"); $this->view->headScript()->appendScript("localStorage.setItem( 'datatables-timeline', '' );");
} }
@ -52,6 +50,7 @@ class ShowbuilderController extends Zend_Controller_Action
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.ColVis.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.ColVis.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.ColReorder.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.ColReorder.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.FixedColumns.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.FixedColumns.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.columnFilter.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/blockui/jquery.blockUI.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/blockui/jquery.blockUI.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/buttons/buttons.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/buttons/buttons.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
@ -79,8 +78,7 @@ class ShowbuilderController extends Zend_Controller_Action
} }
// unset session // unset session
Zend_Session::namespaceUnset('referrer'); Zend_Session::namespaceUnset('referrer');
} } elseif ($values["Publicise"] == '1' && $form->isValid($values)) {
else if ($values["Publicise"] == '1' && $form->isValid($values)) {
Application_Model_Preference::SetHeadTitle($values["stnName"], $this->view); Application_Model_Preference::SetHeadTitle($values["stnName"], $this->view);
Application_Model_Preference::SetPhone($values["Phone"]); Application_Model_Preference::SetPhone($values["Phone"]);
Application_Model_Preference::SetEmail($values["Email"]); Application_Model_Preference::SetEmail($values["Email"]);
@ -96,13 +94,12 @@ class ShowbuilderController extends Zend_Controller_Action
Application_Model_Preference::SetStationLogo($imagePath); Application_Model_Preference::SetStationLogo($imagePath);
Application_Model_Preference::SetSupportFeedback($values["SupportFeedback"]); Application_Model_Preference::SetSupportFeedback($values["SupportFeedback"]);
if (isset($values["Privacy"])){ if (isset($values["Privacy"])) {
Application_Model_Preference::SetPrivacyPolicyCheck($values["Privacy"]); Application_Model_Preference::SetPrivacyPolicyCheck($values["Privacy"]);
} }
// unset session // unset session
Zend_Session::namespaceUnset('referrer'); Zend_Session::namespaceUnset('referrer');
} } else {
else {
$logo = Application_Model_Preference::GetStationLogo(); $logo = Application_Model_Preference::GetStationLogo();
if ($logo) { if ($logo) {
$this->view->logoImg = $logo; $this->view->logoImg = $logo;
@ -130,16 +127,14 @@ class ShowbuilderController extends Zend_Controller_Action
$showLib = false; $showLib = false;
if (!$user->isGuest()) { if (!$user->isGuest()) {
$disableLib = false; $disableLib = false;
$data = Application_Model_Preference::GetValue("nowplaying_screen", true);
if ($data != "") {
$settings = unserialize($data);
if ($settings["library"] == "true") { $data = Application_Model_Preference::getNowPlayingScreenSettings();
if (!is_null($data)) {
if ($data["library"] == "true") {
$showLib = true; $showLib = true;
} }
} }
} } else {
else {
$disableLib = true; $disableLib = true;
} }
$this->view->disableLib = $disableLib; $this->view->disableLib = $disableLib;
@ -152,6 +147,7 @@ class ShowbuilderController extends Zend_Controller_Action
$start = DateTime::createFromFormat("U", $from, new DateTimeZone("UTC")); $start = DateTime::createFromFormat("U", $from, new DateTimeZone("UTC"));
$start->setTimezone(new DateTimeZone(date_default_timezone_get())); $start->setTimezone(new DateTimeZone(date_default_timezone_get()));
$end = DateTime::createFromFormat("U", $to, new DateTimeZone("UTC")); $end = DateTime::createFromFormat("U", $to, new DateTimeZone("UTC"));
$end->setTimezone(new DateTimeZone(date_default_timezone_get())); $end->setTimezone(new DateTimeZone(date_default_timezone_get()));
@ -181,30 +177,29 @@ class ShowbuilderController extends Zend_Controller_Action
$now = floatval(microtime(true)); $now = floatval(microtime(true));
$request = $this->getRequest(); $request = $this->getRequest();
$baseUrl = $request->getBaseUrl();
$menu = array(); $menu = array();
$user = Application_Model_User::GetCurrentUser(); $user = Application_Model_User::getCurrentUser();
$item = CcScheduleQuery::create()->findPK($id); $item = CcScheduleQuery::create()->findPK($id);
$instance = $item->getCcShowInstances(); $instance = $item->getCcShowInstances();
$menu["preview"] = array("name"=> "Preview", "icon" => "play"); $menu["preview"] = array("name"=> "Preview", "icon" => "play");
//select the cursor //select the cursor
$menu["selCurs"] = array("name"=> "Select Cursor","icon" => "select-cursor"); $menu["selCurs"] = array("name"=> "Select cursor","icon" => "select-cursor");
$menu["delCurs"] = array("name"=> "Remove Cursor","icon" => "select-cursor"); $menu["delCurs"] = array("name"=> "Remove cursor","icon" => "select-cursor");
if ($now < floatval($item->getDbEnds("U.u")) && $user->canSchedule($instance->getDbShowId())) { if ($now < floatval($item->getDbEnds("U.u")) && $user->canSchedule($instance->getDbShowId())) {
//remove/truncate the item from the schedule //remove/truncate the item from the schedule
$menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => "/showbuilder/schedule-remove"); $menu["del"] = array("name"=> "Remove from show", "icon" => "delete", "url" => "/showbuilder/schedule-remove");
} }
$this->view->items = $menu; $this->view->items = $menu;
} }
public function builderDialogAction() { public function builderDialogAction()
{
$request = $this->getRequest(); $request = $this->getRequest();
$id = $request->getParam("id"); $id = $request->getParam("id");
@ -212,6 +207,7 @@ class ShowbuilderController extends Zend_Controller_Action
if (is_null($instance)) { if (is_null($instance)) {
$this->view->error = "show does not exist"; $this->view->error = "show does not exist";
return; return;
} }
@ -231,8 +227,8 @@ class ShowbuilderController extends Zend_Controller_Action
$this->view->dialog = $this->view->render('showbuilder/builderDialog.phtml'); $this->view->dialog = $this->view->render('showbuilder/builderDialog.phtml');
} }
public function checkBuilderFeedAction() { public function checkBuilderFeedAction()
{
$request = $this->getRequest(); $request = $this->getRequest();
$current_time = time(); $current_time = time();
@ -252,18 +248,12 @@ class ShowbuilderController extends Zend_Controller_Action
//only send the schedule back if updates have been made. //only send the schedule back if updates have been made.
// -1 default will always call the schedule to be sent back if no timestamp is defined. // -1 default will always call the schedule to be sent back if no timestamp is defined.
if ($showBuilder->hasBeenUpdatedSince($timestamp, $instances)) { $this->view->update = $showBuilder->hasBeenUpdatedSince(
$this->view->update = true; $timestamp, $instances);
}
else {
$this->view->update = false;
}
} }
public function builderFeedAction() { public function builderFeedAction()
{
$start = microtime(true);
$request = $this->getRequest(); $request = $this->getRequest();
$current_time = time(); $current_time = time();
@ -272,7 +262,6 @@ class ShowbuilderController extends Zend_Controller_Action
$ends_epoch = $request->getParam("end", $current_time + (60*60*24)); $ends_epoch = $request->getParam("end", $current_time + (60*60*24));
$show_filter = intval($request->getParam("showFilter", 0)); $show_filter = intval($request->getParam("showFilter", 0));
$my_shows = intval($request->getParam("myShows", 0)); $my_shows = intval($request->getParam("myShows", 0));
$timestamp = intval($request->getParam("timestamp", -1));
$startsDT = DateTime::createFromFormat("U", $starts_epoch, new DateTimeZone("UTC")); $startsDT = DateTime::createFromFormat("U", $starts_epoch, new DateTimeZone("UTC"));
$endsDT = DateTime::createFromFormat("U", $ends_epoch, new DateTimeZone("UTC")); $endsDT = DateTime::createFromFormat("U", $ends_epoch, new DateTimeZone("UTC"));
@ -280,19 +269,14 @@ class ShowbuilderController extends Zend_Controller_Action
$opts = array("myShows" => $my_shows, "showFilter" => $show_filter); $opts = array("myShows" => $my_shows, "showFilter" => $show_filter);
$showBuilder = new Application_Model_ShowBuilder($startsDT, $endsDT, $opts); $showBuilder = new Application_Model_ShowBuilder($startsDT, $endsDT, $opts);
$data = $showBuilder->GetItems(); $data = $showBuilder->getItems();
$this->view->schedule = $data["schedule"]; $this->view->schedule = $data["schedule"];
$this->view->instances = $data["showInstances"]; $this->view->instances = $data["showInstances"];
$this->view->timestamp = $current_time; $this->view->timestamp = $current_time;
$end = microtime(true);
Logging::debug("getting builder feed info took:");
Logging::debug(floatval($end) - floatval($start));
} }
public function scheduleAddAction() { public function scheduleAddAction()
{
$request = $this->getRequest(); $request = $this->getRequest();
$mediaItems = $request->getParam("mediaIds", array()); $mediaItems = $request->getParam("mediaIds", array());
$scheduledItems = $request->getParam("schedIds", array()); $scheduledItems = $request->getParam("schedIds", array());
@ -300,18 +284,12 @@ class ShowbuilderController extends Zend_Controller_Action
try { try {
$scheduler = new Application_Model_Scheduler(); $scheduler = new Application_Model_Scheduler();
$scheduler->scheduleAfter($scheduledItems, $mediaItems); $scheduler->scheduleAfter($scheduledItems, $mediaItems);
} } catch (OutDatedScheduleException $e) {
catch (OutDatedScheduleException $e) {
$this->view->error = $e->getMessage(); $this->view->error = $e->getMessage();
Logging::log($e->getMessage()); Logging::info($e->getMessage());
Logging::log("{$e->getFile()}"); } catch (Exception $e) {
Logging::log("{$e->getLine()}");
}
catch (Exception $e) {
$this->view->error = $e->getMessage(); $this->view->error = $e->getMessage();
Logging::log($e->getMessage()); Logging::info($e->getMessage());
Logging::log("{$e->getFile()}");
Logging::log("{$e->getLine()}");
} }
} }
@ -323,23 +301,17 @@ class ShowbuilderController extends Zend_Controller_Action
try { try {
$scheduler = new Application_Model_Scheduler(); $scheduler = new Application_Model_Scheduler();
$scheduler->removeItems($items); $scheduler->removeItems($items);
} } catch (OutDatedScheduleException $e) {
catch (OutDatedScheduleException $e) {
$this->view->error = $e->getMessage(); $this->view->error = $e->getMessage();
Logging::log($e->getMessage()); Logging::info($e->getMessage());
Logging::log("{$e->getFile()}"); } catch (Exception $e) {
Logging::log("{$e->getLine()}");
}
catch (Exception $e) {
$this->view->error = $e->getMessage(); $this->view->error = $e->getMessage();
Logging::log($e->getMessage()); Logging::info($e->getMessage());
Logging::log("{$e->getFile()}");
Logging::log("{$e->getLine()}");
} }
} }
public function scheduleMoveAction() { public function scheduleMoveAction()
{
$request = $this->getRequest(); $request = $this->getRequest();
$selectedItems = $request->getParam("selectedItem"); $selectedItems = $request->getParam("selectedItem");
$afterItem = $request->getParam("afterItem"); $afterItem = $request->getParam("afterItem");
@ -347,25 +319,18 @@ class ShowbuilderController extends Zend_Controller_Action
try { try {
$scheduler = new Application_Model_Scheduler(); $scheduler = new Application_Model_Scheduler();
$scheduler->moveItem($selectedItems, $afterItem); $scheduler->moveItem($selectedItems, $afterItem);
} } catch (OutDatedScheduleException $e) {
catch (OutDatedScheduleException $e) {
$this->view->error = $e->getMessage(); $this->view->error = $e->getMessage();
Logging::log($e->getMessage()); Logging::info($e->getMessage());
Logging::log("{$e->getFile()}"); } catch (Exception $e) {
Logging::log("{$e->getLine()}");
}
catch (Exception $e) {
$this->view->error = $e->getMessage(); $this->view->error = $e->getMessage();
Logging::log($e->getMessage()); Logging::info($e->getMessage());
Logging::log("{$e->getFile()}");
Logging::log("{$e->getLine()}");
} }
} }
public function scheduleReorderAction() { public function scheduleReorderAction()
{
$request = $this->getRequest(); throw new Exception("this controller is/was a no-op please fix your
code");
$showInstance = $request->getParam("instanceId");
} }
} }

View file

@ -13,10 +13,6 @@ class UserController extends Zend_Controller_Action
->initContext(); ->initContext();
} }
public function indexAction()
{
}
public function addUserAction() public function addUserAction()
{ {
global $CC_CONFIG; global $CC_CONFIG;
@ -24,9 +20,16 @@ class UserController extends Zend_Controller_Action
$request = $this->getRequest(); $request = $this->getRequest();
$baseUrl = $request->getBaseUrl(); $baseUrl = $request->getBaseUrl();
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/js/jquery.dataTables.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $js_files = array(
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.pluginAPI.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); '/js/datatables/js/jquery.dataTables.js?',
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/user/user.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); '/js/datatables/plugin/dataTables.pluginAPI.js?',
'/js/airtime/user/user.js?'
);
foreach ($js_files as $js) {
$this->view->headScript()->appendFile(
$baseUrl.$js.$CC_CONFIG['airtime_version'],'text/javascript');
}
$this->view->headLink()->appendStylesheet($baseUrl.'/css/users.css?'.$CC_CONFIG['airtime_version']); $this->view->headLink()->appendStylesheet($baseUrl.'/css/users.css?'.$CC_CONFIG['airtime_version']);
@ -38,16 +41,21 @@ class UserController extends Zend_Controller_Action
if ($form->isValid($request->getPost())) { if ($form->isValid($request->getPost())) {
$formdata = $form->getValues(); $formdata = $form->getValues();
if(isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1 && $formdata['login'] == 'admin' && $formdata['user_id'] != 0){ if (isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1
&& $formdata['login'] == 'admin'
&& $formdata['user_id'] != 0) {
$this->view->successMessage = "<div class='errors'>Specific action is not allowed in demo version!</div>"; $this->view->successMessage = "<div class='errors'>Specific action is not allowed in demo version!</div>";
} } elseif ($form->validateLogin($formdata)) {
else if ($form->validateLogin($formdata)){
$user = new Application_Model_User($formdata['user_id']); $user = new Application_Model_User($formdata['user_id']);
$user->setFirstName($formdata['first_name']); $user->setFirstName($formdata['first_name']);
$user->setLastName($formdata['last_name']); $user->setLastName($formdata['last_name']);
$user->setLogin($formdata['login']); $user->setLogin($formdata['login']);
if ($formdata['password'] != "xxxxxx") // We don't allow 6 x's as a password.
// The reason is because we that as a password placeholder
// on the client side.
if ($formdata['password'] != "xxxxxx") {
$user->setPassword($formdata['password']); $user->setPassword($formdata['password']);
}
$user->setType($formdata['type']); $user->setType($formdata['type']);
$user->setEmail($formdata['email']); $user->setEmail($formdata['email']);
$user->setCellPhone($formdata['cell_phone']); $user->setCellPhone($formdata['cell_phone']);
@ -57,7 +65,7 @@ class UserController extends Zend_Controller_Action
$form->reset(); $form->reset();
if (strlen($formdata['user_id']) == 0){ if (strlen($formdata['user_id']) == 0) {
$this->view->successMessage = "<div class='success'>User added successfully!</div>"; $this->view->successMessage = "<div class='success'>User added successfully!</div>";
} else { } else {
$this->view->successMessage = "<div class='success'>User updated successfully!</div>"; $this->view->successMessage = "<div class='success'>User updated successfully!</div>";
@ -94,27 +102,43 @@ class UserController extends Zend_Controller_Action
{ {
// action body // action body
$delId = $this->_getParam('id'); $delId = $this->_getParam('id');
$valid_actions = array("delete_cascade", "reassign_to");
$files_action = $this->_getParam('deleted_files');
# TODO : remove this. we only use default for now not to break the UI.
if (!$files_action) { # set default action
$files_action = "reassign_to";
$new_owner = Application_Model_User::getFirstAdmin();
}
# only delete when valid action is selected for the owned files
if (! in_array($files_action, $valid_actions) ) {
return;
}
$userInfo = Zend_Auth::getInstance()->getStorage()->read(); $userInfo = Zend_Auth::getInstance()->getStorage()->read();
$userId = $userInfo->id; $userId = $userInfo->id;
if ($delId != $userId){ # Don't let users delete themselves
if ($delId == $userId) {
return;
}
$user = new Application_Model_User($delId); $user = new Application_Model_User($delId);
# Take care of the user's files by either assigning them to somebody
# or deleting them all
if ($files_action == "delete_cascade") {
$user->deleteAllFiles();
} elseif ($files_action == "reassign_to") {
// TODO : fix code to actually use the line below and pick a
// real owner instead of defaulting to the first found admin
//$new_owner_id = $this->_getParam("new_owner");
//$new_owner = new Application_Model_User($new_owner_id);
$user->donateFilesTo( $new_owner );
Logging::info("Reassign to user {$new_owner->getDbId()}");
}
# Finally delete the user
$this->view->entries = $user->delete(); $this->view->entries = $user->delete();
} }
}
} }

View file

@ -13,67 +13,57 @@ class UsersettingsController extends Zend_Controller_Action
->addActionContext('get-timeline-datatable', 'json') ->addActionContext('get-timeline-datatable', 'json')
->addActionContext('set-timeline-datatable', 'json') ->addActionContext('set-timeline-datatable', 'json')
->addActionContext('remindme', 'json') ->addActionContext('remindme', 'json')
->addActionContext('remindme-never', 'json')
->addActionContext('donotshowregistrationpopup', 'json') ->addActionContext('donotshowregistrationpopup', 'json')
->initContext(); ->initContext();
} }
public function setNowPlayingScreenSettingsAction() { public function setNowPlayingScreenSettingsAction()
{
$request = $this->getRequest(); $request = $this->getRequest();
$settings = $request->getParam("settings"); $settings = $request->getParam("settings");
$data = serialize($settings); Application_Model_Preference::setNowPlayingScreenSettings($settings);
Application_Model_Preference::SetValue("nowplaying_screen", $data, true);
} }
public function getNowPlayingScreenSettingsAction() { public function getNowPlayingScreenSettingsAction()
{
$data = Application_Model_Preference::GetValue("nowplaying_screen", true); $data = Application_Model_Preference::getNowPlayingScreenSettings();
if ($data != "") { if (!is_null($data)) {
$this->view->settings = unserialize($data); $this->view->settings = $data;
} }
} }
public function setLibraryDatatableAction() { public function setLibraryDatatableAction()
{
$request = $this->getRequest(); $request = $this->getRequest();
$settings = $request->getParam("settings"); $settings = $request->getParam("settings");
$data = serialize($settings); Application_Model_Preference::setCurrentLibraryTableSetting($settings);
Application_Model_Preference::SetValue("library_datatable", $data, true);
} }
public function getLibraryDatatableAction() { public function getLibraryDatatableAction()
{
$data = Application_Model_Preference::GetValue("library_datatable", true); $data = Application_Model_Preference::getCurrentLibraryTableSetting();
if ($data != "") { if (!is_null($data)) {
$this->view->settings = unserialize($data); $this->view->settings = $data;
} }
} }
public function setTimelineDatatableAction() { public function setTimelineDatatableAction()
{
$request = $this->getRequest();
$settings = $request->getParam("settings");
Application_Model_Preference::setTimelineDatatableSetting($settings);
}
public function getTimelineDatatableAction()
{
$start = microtime(true); $start = microtime(true);
$request = $this->getRequest(); $data = Application_Model_Preference::getTimelineDatatableSetting();
$settings = $request->getParam("settings"); if (!is_null($data)) {
$this->view->settings = $data;
$data = serialize($settings);
Application_Model_Preference::SetValue("timeline_datatable", $data, true);
$end = microtime(true);
Logging::debug("saving timeline datatables info took:");
Logging::debug(floatval($end) - floatval($start));
}
public function getTimelineDatatableAction() {
$start = microtime(true);
$data = Application_Model_Preference::GetValue("timeline_datatable", true);
if ($data != "") {
$this->view->settings = unserialize($data);
} }
$end = microtime(true); $end = microtime(true);
@ -89,6 +79,13 @@ class UsersettingsController extends Zend_Controller_Action
Application_Model_Preference::SetRemindMeDate(); Application_Model_Preference::SetRemindMeDate();
} }
public function remindmeNeverAction()
{
Zend_Session::namespaceUnset('referrer');
//pass in true to indicate 'Remind me never' was clicked
Application_Model_Preference::SetRemindMeDate(true);
}
public function donotshowregistrationpopupAction() public function donotshowregistrationpopupAction()
{ {
// unset session // unset session

View file

@ -0,0 +1,151 @@
<?php
class WebstreamController extends Zend_Controller_Action
{
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('new', 'json')
->addActionContext('save', 'json')
->addActionContext('edit', 'json')
->addActionContext('delete', 'json')
->initContext();
}
public function newAction()
{
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
if (!$this->isAuthorized(-1)) {
// TODO: this header call does not actually print any error message
header("Status: 401 Not Authorized");
return;
}
$webstream = new CcWebstream();
//we're not saving this primary key in the DB so it's OK to be -1
$webstream->setDbId(-1);
$webstream->setDbName("Untitled Webstream");
$webstream->setDbDescription("");
$webstream->setDbUrl("http://");
$webstream->setDbLength("00:30:00");
$webstream->setDbName("Untitled Webstream");
$webstream->setDbCreatorId($userInfo->id);
$webstream->setDbUtime(new DateTime("now", new DateTimeZone('UTC')));
$webstream->setDbMtime(new DateTime("now", new DateTimeZone('UTC')));
//clear the session in case an old playlist was open: CC-4196
Application_Model_Library::changePlaylist(null, null);
$this->view->obj = new Application_Model_Webstream($webstream);
$this->view->action = "new";
$this->view->html = $this->view->render('webstream/webstream.phtml');
}
public function editAction()
{
$request = $this->getRequest();
$id = $request->getParam("id");
if (is_null($id)) {
throw new Exception("Missing parameter 'id'");
}
$webstream = CcWebstreamQuery::create()->findPK($id);
if ($webstream) {
Application_Model_Library::changePlaylist($id, "stream");
}
$this->view->obj = new Application_Model_Webstream($webstream);
$this->view->action = "edit";
$this->view->html = $this->view->render('webstream/webstream.phtml');
}
public function deleteAction()
{
$request = $this->getRequest();
$id = $request->getParam("ids");
if (!$this->isAuthorized($id)) {
header("Status: 401 Not Authorized");
return;
}
$type = "stream";
Application_Model_Library::changePlaylist(null, $type);
$webstream = CcWebstreamQuery::create()->findPK($id)->delete();
$this->view->obj = null;
$this->view->action = "delete";
$this->view->html = $this->view->render('webstream/webstream.phtml');
}
/*TODO : make a user object be passed a parameter into this function so
that it does not have to be fetched multiple times.*/
public function isAuthorized($webstream_id)
{
$user = Application_Model_User::getCurrentUser();
if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
return true;
}
if ($user->isHost()) {
// not creating a webstream
if ($webstream_id != -1) {
$webstream = CcWebstreamQuery::create()->findPK($webstream_id);
/*we are updating a playlist. Ensure that if the user is a
host/dj, that he has the correct permission.*/
$user = Application_Model_User::getCurrentUser();
//only allow when webstream belongs to the DJ
return $webstream->getDbCreatorId() == $user->getId();
}
/*we are creating a new stream. Don't need to check whether the
DJ/Host owns the stream*/
return true;
} else {
Logging::info( $user );
}
return false;
}
public function saveAction()
{
$request = $this->getRequest();
$id = $request->getParam("id");
$parameters = array();
foreach (array('id','length','name','description','url') as $p) {
$parameters[$p] = trim($request->getParam($p));
}
if (!$this->isAuthorized($id)) {
header("Status: 401 Not Authorized");
return;
}
list($analysis, $mime, $mediaUrl, $di) = Application_Model_Webstream::analyzeFormData($parameters);
try {
if (Application_Model_Webstream::isValid($analysis)) {
$streamId = Application_Model_Webstream::save($parameters, $mime, $mediaUrl, $di);
Application_Model_Library::changePlaylist($streamId, "stream");
$this->view->statusMessage = "<div class='success'>Webstream saved.</div>";
$this->view->streamId = $streamId;
$this->view->length = $di->format("%Hh %Im");
} else {
throw new Exception("isValid returned false");
}
} catch (Exception $e) {
Logging::debug($e->getMessage());
$this->view->statusMessage = "<div class='errors'>Invalid form values.</div>";
$this->view->streamId = -1;
$this->view->analysis = $analysis;
}
}
}

View file

@ -110,11 +110,10 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
{ {
$controller = strtolower($request->getControllerName()); $controller = strtolower($request->getControllerName());
if (in_array($controller, array("api", "auth"))){ if (in_array($controller, array("api", "auth"))) {
$this->setRoleName("G"); $this->setRoleName("G");
} } elseif (!Zend_Auth::getInstance()->hasIdentity()) {
else if (!Zend_Auth::getInstance()->hasIdentity()){
if ($controller !== 'login') { if ($controller !== 'login') {
@ -131,14 +130,12 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
//redirectAndExit() cleans up, sends the headers and stops the script //redirectAndExit() cleans up, sends the headers and stops the script
Zend_Controller_Action_HelperBroker::getStaticHelper('redirector')->redirectAndExit(); Zend_Controller_Action_HelperBroker::getStaticHelper('redirector')->redirectAndExit();
} } else {
else {
$r = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector'); $r = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$r->gotoSimpleAndExit('index', 'login', $request->getModuleName()); $r->gotoSimpleAndExit('index', 'login', $request->getModuleName());
} }
} }
} } else {
else {
$userInfo = Zend_Auth::getInstance()->getStorage()->read(); $userInfo = Zend_Auth::getInstance()->getStorage()->read();
$this->setRoleName($userInfo->type); $this->setRoleName($userInfo->type);

View file

@ -5,11 +5,19 @@ class RabbitMqPlugin extends Zend_Controller_Plugin_Abstract
public function dispatchLoopShutdown() public function dispatchLoopShutdown()
{ {
if (Application_Model_RabbitMq::$doPush) { if (Application_Model_RabbitMq::$doPush) {
$md = array('schedule' => Application_Model_Schedule::GetScheduledPlaylists()); $md = array('schedule' => Application_Model_Schedule::getSchedule());
Application_Model_RabbitMq::SendMessageToPypo("update_schedule", $md); Application_Model_RabbitMq::SendMessageToPypo("update_schedule", $md);
if (!isset($_SERVER['AIRTIME_SRV'])){ if (!isset($_SERVER['AIRTIME_SRV'])) {
Application_Model_RabbitMq::SendMessageToShowRecorder("update_recorder_schedule"); Application_Model_RabbitMq::SendMessageToShowRecorder("update_recorder_schedule");
} }
} }
if (memory_get_peak_usage() > 30*pow(2, 20)) {
Logging::debug("Peak memory usage: "
.(memory_get_peak_usage()/1000000)
." MB while accessing URI ".$_SERVER['REQUEST_URI']);
Logging::debug("Should try to keep memory footprint under 25 MB");
}
} }
} }

View file

@ -9,7 +9,7 @@ class Application_Form_AddShowAbsoluteRebroadcastDates extends Zend_Form_SubForm
array('ViewScript', array('viewScript' => 'form/add-show-rebroadcast-absolute.phtml')) array('ViewScript', array('viewScript' => 'form/add-show-rebroadcast-absolute.phtml'))
)); ));
for($i=1; $i<=10; $i++) { for ($i=1; $i<=10; $i++) {
$text = new Zend_Form_Element_Text("add_show_rebroadcast_date_absolute_$i"); $text = new Zend_Form_Element_Text("add_show_rebroadcast_date_absolute_$i");
$text->setAttrib('class', 'input_text'); $text->setAttrib('class', 'input_text');
@ -30,43 +30,41 @@ class Application_Form_AddShowAbsoluteRebroadcastDates extends Zend_Form_SubForm
} }
} }
public function disable(){ public function disable()
{
$elements = $this->getElements(); $elements = $this->getElements();
foreach ($elements as $element) foreach ($elements as $element) {
{ if ($element->getType() != 'Zend_Form_Element_Hidden') {
if ($element->getType() != 'Zend_Form_Element_Hidden')
{
$element->setAttrib('disabled','disabled'); $element->setAttrib('disabled','disabled');
} }
} }
} }
public function checkReliantFields($formData) { public function checkReliantFields($formData)
{
$noError = true; $noError = true;
for($i=1; $i<=10; $i++) { for ($i=1; $i<=10; $i++) {
$valid = true; $valid = true;
$day = $formData['add_show_rebroadcast_date_absolute_'.$i]; $day = $formData['add_show_rebroadcast_date_absolute_'.$i];
$time = $formData['add_show_rebroadcast_time_absolute_'.$i]; $time = $formData['add_show_rebroadcast_time_absolute_'.$i];
if(trim($day) == "" && trim($time) == "") { if (trim($day) == "" && trim($time) == "") {
continue; continue;
} }
if (trim($day) == ""){ if (trim($day) == "") {
$this->getElement('add_show_rebroadcast_date_absolute_'.$i)->setErrors(array("Day must be specified")); $this->getElement('add_show_rebroadcast_date_absolute_'.$i)->setErrors(array("Day must be specified"));
$valid = false; $valid = false;
} }
if (trim($time) == "") {
if (trim($time) == ""){
$this->getElement('add_show_rebroadcast_time_absolute_'.$i)->setErrors(array("Time must be specified")); $this->getElement('add_show_rebroadcast_time_absolute_'.$i)->setErrors(array("Time must be specified"));
$valid = false; $valid = false;
} }
if($valid === false) { if ($valid === false) {
$noError = false; $noError = false;
continue; continue;
} }
@ -84,7 +82,7 @@ class Application_Form_AddShowAbsoluteRebroadcastDates extends Zend_Form_SubForm
$rebroad_start = $day." ".$formData['add_show_rebroadcast_time_absolute_'.$i]; $rebroad_start = $day." ".$formData['add_show_rebroadcast_time_absolute_'.$i];
$rebroad_start = new DateTime($rebroad_start); $rebroad_start = new DateTime($rebroad_start);
if($rebroad_start < $show_end) { if ($rebroad_start < $show_end) {
$this->getElement('add_show_rebroadcast_time_absolute_'.$i)->setErrors(array("Must wait at least 1 hour to rebroadcast")); $this->getElement('add_show_rebroadcast_time_absolute_'.$i)->setErrors(array("Must wait at least 1 hour to rebroadcast"));
$valid = false; $valid = false;
$noError = false; $noError = false;
@ -94,4 +92,3 @@ class Application_Form_AddShowAbsoluteRebroadcastDates extends Zend_Form_SubForm
return $noError; return $noError;
} }
} }

View file

@ -44,7 +44,7 @@ class Application_Form_AddShowLiveStream extends Zend_Form_SubForm
$this->addElement($custom_password); $this->addElement($custom_password);
$connection_url = Application_Model_Preference::GetLiveDJSourceConnectionURL(); $connection_url = Application_Model_Preference::GetLiveDJSourceConnectionURL();
if(trim($connection_url) == ""){ if (trim($connection_url) == "") {
$connection_url = "N/A"; $connection_url = "N/A";
} }
@ -53,21 +53,23 @@ class Application_Form_AddShowLiveStream extends Zend_Form_SubForm
)); ));
} }
public function isValid($data){ public function isValid($data)
{
$isValid = parent::isValid($data); $isValid = parent::isValid($data);
if($data['cb_custom_auth'] == 1){ if ($data['cb_custom_auth'] == 1) {
if(trim($data['custom_username']) == ''){ if (trim($data['custom_username']) == '') {
$element = $this->getElement("custom_username"); $element = $this->getElement("custom_username");
$element->addError("Username field cannot be empty."); $element->addError("Username field cannot be empty.");
$isValid = false; $isValid = false;
} }
if(trim($data['custom_password']) == ''){ if (trim($data['custom_password']) == '') {
$element = $this->getElement("custom_password"); $element = $this->getElement("custom_password");
$element->addError("Password field cannot be empty."); $element->addError("Password field cannot be empty.");
$isValid = false; $isValid = false;
} }
} }
return $isValid; return $isValid;
} }
} }

View file

@ -18,16 +18,14 @@ class Application_Form_AddShowRR extends Zend_Form_SubForm
)); ));
} }
public function disable(){ public function disable()
{
$elements = $this->getElements(); $elements = $this->getElements();
foreach ($elements as $element) foreach ($elements as $element) {
{ if ($element->getType() != 'Zend_Form_Element_Hidden') {
if ($element->getType() != 'Zend_Form_Element_Hidden')
{
$element->setAttrib('disabled','disabled'); $element->setAttrib('disabled','disabled');
} }
} }
} }
} }

View file

@ -11,11 +11,11 @@ class Application_Form_AddShowRebroadcastDates extends Zend_Form_SubForm
$relativeDates = array(); $relativeDates = array();
$relativeDates[""] = ""; $relativeDates[""] = "";
for($i=0; $i<=30; $i++) { for ($i=0; $i<=30; $i++) {
$relativeDates["$i days"] = "+$i days"; $relativeDates["$i days"] = "+$i days";
} }
for($i=1; $i<=10; $i++) { for ($i=1; $i<=10; $i++) {
$select = new Zend_Form_Element_Select("add_show_rebroadcast_date_$i"); $select = new Zend_Form_Element_Select("add_show_rebroadcast_date_$i");
$select->setAttrib('class', 'input_select'); $select->setAttrib('class', 'input_select');
@ -35,43 +35,41 @@ class Application_Form_AddShowRebroadcastDates extends Zend_Form_SubForm
} }
} }
public function disable(){ public function disable()
{
$elements = $this->getElements(); $elements = $this->getElements();
foreach ($elements as $element) foreach ($elements as $element) {
{ if ($element->getType() != 'Zend_Form_Element_Hidden') {
if ($element->getType() != 'Zend_Form_Element_Hidden')
{
$element->setAttrib('disabled','disabled'); $element->setAttrib('disabled','disabled');
} }
} }
} }
public function checkReliantFields($formData) { public function checkReliantFields($formData)
{
$noError = true; $noError = true;
for($i=1; $i<=10; $i++) { for ($i=1; $i<=10; $i++) {
$valid = true; $valid = true;
$days = $formData['add_show_rebroadcast_date_'.$i]; $days = $formData['add_show_rebroadcast_date_'.$i];
$time = $formData['add_show_rebroadcast_time_'.$i]; $time = $formData['add_show_rebroadcast_time_'.$i];
if(trim($days) == "" && trim($time) == "") { if (trim($days) == "" && trim($time) == "") {
continue; continue;
} }
if (trim($days) == ""){ if (trim($days) == "") {
$this->getElement('add_show_rebroadcast_date_'.$i)->setErrors(array("Day must be specified")); $this->getElement('add_show_rebroadcast_date_'.$i)->setErrors(array("Day must be specified"));
$valid = false; $valid = false;
} }
if (trim($time) == "") {
if (trim($time) == ""){
$this->getElement('add_show_rebroadcast_time_'.$i)->setErrors(array("Time must be specified")); $this->getElement('add_show_rebroadcast_time_'.$i)->setErrors(array("Time must be specified"));
$valid = false; $valid = false;
} }
if($valid === false) { if ($valid === false) {
$noError = false; $noError = false;
continue; continue;
} }
@ -93,7 +91,7 @@ class Application_Form_AddShowRebroadcastDates extends Zend_Form_SubForm
$rebroad_start = new DateTime($rebroad_start); $rebroad_start = new DateTime($rebroad_start);
$rebroad_start->add(new DateInterval("P".$day."D")); $rebroad_start->add(new DateInterval("P".$day."D"));
if($rebroad_start < $show_end) { if ($rebroad_start < $show_end) {
$this->getElement('add_show_rebroadcast_time_'.$i)->setErrors(array("Must wait at least 1 hour to rebroadcast")); $this->getElement('add_show_rebroadcast_time_'.$i)->setErrors(array("Must wait at least 1 hour to rebroadcast"));
$valid = false; $valid = false;
$noError = false; $noError = false;
@ -103,4 +101,3 @@ class Application_Form_AddShowRebroadcastDates extends Zend_Form_SubForm
return $noError; return $noError;
} }
} }

View file

@ -56,28 +56,28 @@ class Application_Form_AddShowRepeats extends Zend_Form_SubForm
)); ));
} }
public function disable(){ public function disable()
{
$elements = $this->getElements(); $elements = $this->getElements();
foreach ($elements as $element) foreach ($elements as $element) {
{ if ($element->getType() != 'Zend_Form_Element_Hidden') {
if ($element->getType() != 'Zend_Form_Element_Hidden')
{
$element->setAttrib('disabled','disabled'); $element->setAttrib('disabled','disabled');
} }
} }
} }
public function checkReliantFields($formData) { public function checkReliantFields($formData)
{
if (!$formData['add_show_no_end']){ if (!$formData['add_show_no_end']) {
$start_timestamp = $formData['add_show_start_date']; $start_timestamp = $formData['add_show_start_date'];
$end_timestamp = $formData['add_show_end_date']; $end_timestamp = $formData['add_show_end_date'];
$start_epoch = strtotime($start_timestamp); $start_epoch = strtotime($start_timestamp);
$end_epoch = strtotime($end_timestamp); $end_epoch = strtotime($end_timestamp);
if($end_epoch < $start_epoch) { if ($end_epoch < $start_epoch) {
$this->getElement('add_show_end_date')->setErrors(array('End date must be after start date')); $this->getElement('add_show_end_date')->setErrors(array('End date must be after start date'));
return false; return false;
} }
} }
@ -86,4 +86,3 @@ class Application_Form_AddShowRepeats extends Zend_Form_SubForm
} }
} }

View file

@ -24,7 +24,6 @@ class Application_Form_AddShowStyle extends Zend_Form_SubForm
array('stringLength', false, array(6, 6)) array('stringLength', false, array(6, 6))
)); ));
// Add show color input // Add show color input
$this->addElement('text', 'add_show_color', array( $this->addElement('text', 'add_show_color', array(
'label' => 'Text Colour:', 'label' => 'Text Colour:',
@ -45,16 +44,14 @@ class Application_Form_AddShowStyle extends Zend_Form_SubForm
)); ));
} }
public function disable(){ public function disable()
{
$elements = $this->getElements(); $elements = $this->getElements();
foreach ($elements as $element) foreach ($elements as $element) {
{ if ($element->getType() != 'Zend_Form_Element_Hidden') {
if ($element->getType() != 'Zend_Form_Element_Hidden')
{
$element->setAttrib('disabled','disabled'); $element->setAttrib('disabled','disabled');
} }
} }
} }
} }

View file

@ -6,7 +6,7 @@ class Application_Form_AddShowWhat extends Zend_Form_SubForm
{ {
// retrieves the length limit for each char field // retrieves the length limit for each char field
// and store to assoc array // and store to assoc array
$maxLens = Application_Model_Show::GetMaxLengths(); $maxLens = Application_Model_Show::getMaxLengths();
// Hidden element to indicate whether the show is new or // Hidden element to indicate whether the show is new or
// whether we are updating an existing show. // whether we are updating an existing show.
@ -66,15 +66,13 @@ class Application_Form_AddShowWhat extends Zend_Form_SubForm
} }
public function disable(){ public function disable()
{
$elements = $this->getElements(); $elements = $this->getElements();
foreach ($elements as $element) foreach ($elements as $element) {
{ if ($element->getType() != 'Zend_Form_Element_Hidden') {
if ($element->getType() != 'Zend_Form_Element_Hidden')
{
$element->setAttrib('disabled','disabled'); $element->setAttrib('disabled','disabled');
} }
} }
} }
} }

View file

@ -83,7 +83,8 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
} }
public function checkReliantFields($formData, $validateStartDate, $originalStartDate=null) { public function checkReliantFields($formData, $validateStartDate, $originalStartDate=null, $update=false, $instanceId=null)
{
$valid = true; $valid = true;
$start_time = $formData['add_show_start_date']." ".$formData['add_show_start_time']; $start_time = $formData['add_show_start_date']." ".$formData['add_show_start_time'];
@ -93,14 +94,14 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
$nowDateTime = new DateTime(); $nowDateTime = new DateTime();
$showStartDateTime = new DateTime($start_time); $showStartDateTime = new DateTime($start_time);
$showEndDateTime = new DateTime($end_time); $showEndDateTime = new DateTime($end_time);
if ($validateStartDate){ if ($validateStartDate) {
if($showStartDateTime->getTimestamp() < $nowDateTime->getTimestamp()) { if ($showStartDateTime->getTimestamp() < $nowDateTime->getTimestamp()) {
$this->getElement('add_show_start_time')->setErrors(array('Cannot create show in the past')); $this->getElement('add_show_start_time')->setErrors(array('Cannot create show in the past'));
$valid = false; $valid = false;
} }
// if edit action, check if original show start time is in the past. CC-3864 // if edit action, check if original show start time is in the past. CC-3864
if($originalStartDate){ if ($originalStartDate) {
if($originalStartDate->getTimestamp() < $nowDateTime->getTimestamp()) { if ($originalStartDate->getTimestamp() < $nowDateTime->getTimestamp()) {
$this->getElement('add_show_start_time')->setValue($originalStartDate->format("H:i")); $this->getElement('add_show_start_time')->setValue($originalStartDate->format("H:i"));
$this->getElement('add_show_start_date')->setValue($originalStartDate->format("Y-m-d")); $this->getElement('add_show_start_date')->setValue($originalStartDate->format("Y-m-d"));
$this->getElement('add_show_start_time')->setErrors(array('Cannot modify start date/time of the show that is already started')); $this->getElement('add_show_start_time')->setErrors(array('Cannot modify start date/time of the show that is already started'));
@ -111,7 +112,7 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
} }
// if end time is in the past, return error // if end time is in the past, return error
if($showEndDateTime->getTimestamp() < $nowDateTime->getTimestamp()) { if ($showEndDateTime->getTimestamp() < $nowDateTime->getTimestamp()) {
$this->getElement('add_show_end_time')->setErrors(array('End date/time cannot be in the past')); $this->getElement('add_show_end_time')->setErrors(array('End date/time cannot be in the past'));
$valid = false; $valid = false;
} }
@ -121,54 +122,246 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
if (preg_match($pattern, $formData['add_show_duration'], $matches) && count($matches) == 3) { if (preg_match($pattern, $formData['add_show_duration'], $matches) && count($matches) == 3) {
$hours = $matches[1]; $hours = $matches[1];
$minutes = $matches[2]; $minutes = $matches[2];
if( $formData["add_show_duration"] == "00h 00m" ) { if ($formData["add_show_duration"] == "00h 00m") {
$this->getElement('add_show_duration')->setErrors(array('Cannot have duration 00h 00m')); $this->getElement('add_show_duration')->setErrors(array('Cannot have duration 00h 00m'));
$valid = false; $valid = false;
}elseif(strpos($formData["add_show_duration"], 'h') !== false && $hours >= 24) { } elseif (strpos($formData["add_show_duration"], 'h') !== false && $hours >= 24) {
if ($hours > 24 || ($hours == 24 && $minutes > 0)) { if ($hours > 24 || ($hours == 24 && $minutes > 0)) {
$this->getElement('add_show_duration')->setErrors(array('Cannot have duration greater than 24h')); $this->getElement('add_show_duration')->setErrors(array('Cannot have duration greater than 24h'));
$valid = false; $valid = false;
} }
}elseif( strstr($formData["add_show_duration"], '-') ){ } elseif ( strstr($formData["add_show_duration"], '-') ) {
$this->getElement('add_show_duration')->setErrors(array('Cannot have duration < 0m')); $this->getElement('add_show_duration')->setErrors(array('Cannot have duration < 0m'));
$valid = false; $valid = false;
} }
} } else {
else {
$valid = false; $valid = false;
} }
/* Check if show is overlapping
* We will only do this check if the show is valid
* upto this point
*/
if ($valid) {
$utc = new DateTimeZone('UTC');
$localTimezone = new DateTimeZone(Application_Model_Preference::GetTimezone());
$show_start = new DateTime($start_time);
$show_start->setTimezone($utc);
$show_end = new DateTime($end_time);
$show_end->setTimezone($utc);
if ($formData["add_show_repeats"]) {
//get repeating show end date
if ($formData["add_show_no_end"]) {
$date = Application_Model_Preference::GetShowsPopulatedUntil();
if (is_null($date)) {
$populateUntilDateTime = new DateTime("now", $utc);
Application_Model_Preference::SetShowsPopulatedUntil($populateUntilDateTime);
} else {
$populateUntilDateTime = clone $date;
}
} elseif (!$formData["add_show_no_end"]) {
$popUntil = $formData["add_show_end_date"]." ".$formData["add_show_end_time"];
$populateUntilDateTime = new DateTime($popUntil);
$populateUntilDateTime->setTimezone($utc);
}
//get repeat interval
if ($formData["add_show_repeat_type"] == 0) {
$interval = 'P7D';
} elseif ($formData["add_show_repeat_type"] == 1) {
$interval = 'P14D';
} elseif ($formData["add_show_repeat_type"] == 2) {
$interval = 'P1M';
}
/* Check first show
* Continue if the first show does not overlap
*/
if ($update) {
$overlapping = Application_Model_Schedule::checkOverlappingShows(
$show_start, $show_end, $update, null, $formData["add_show_id"]);
} else {
$overlapping = Application_Model_Schedule::checkOverlappingShows(
$show_start, $show_end);
}
//$overlapping = Application_Model_Schedule::checkOverlappingShows($show_start, $show_end, $update, $instanceId);
/* Check if repeats overlap with previously scheduled shows
* Do this for each show day
*/
if (!$overlapping) {
$startDow = date("w", $show_start->getTimestamp());
foreach ($formData["add_show_day_check"] as $day) {
$repeatShowStart = clone $show_start;
$repeatShowEnd = clone $show_end;
$daysAdd=0;
if ($startDow !== $day) {
if ($startDow > $day)
$daysAdd = 6 - $startDow + 1 + $day;
else
$daysAdd = $day - $startDow;
/* In case we are crossing daylights saving time we need
* to convert show start and show end to local time before
* adding the interval for the next repeating show
*/
$repeatShowStart->setTimezone($localTimezone);
$repeatShowEnd->setTimezone($localTimezone);
$repeatShowStart->add(new DateInterval("P".$daysAdd."D"));
$repeatShowEnd->add(new DateInterval("P".$daysAdd."D"));
//set back to UTC
$repeatShowStart->setTimezone($utc);
$repeatShowEnd->setTimezone($utc);
}
/* Here we are checking each repeating show by
* the show day.
* (i.e: every wednesday, then every thursday, etc.)
*/
while ($repeatShowStart->getTimestamp() < $populateUntilDateTime->getTimestamp()) {
if ($formData['add_show_id'] == -1) {
//this is a new show
$overlapping = Application_Model_Schedule::checkOverlappingShows(
$repeatShowStart, $repeatShowEnd);
/* If the repeating show is rebroadcasted we need to check
* the rebroadcast dates relative to the repeating show
*/
if (!$overlapping && $formData['add_show_rebroadcast']) {
$overlapping = self::checkRebroadcastDates(
$repeatShowStart, $formData, $hours, $minutes);
}
} else {
$overlapping = Application_Model_Schedule::checkOverlappingShows(
$repeatShowStart, $repeatShowEnd, $update, null, $formData["add_show_id"]);
if (!$overlapping && $formData['add_show_rebroadcast']) {
$overlapping = self::checkRebroadcastDates(
$repeatShowStart, $formData, $hours, $minutes, true);
}
}
if ($overlapping) {
$valid = false;
$this->getElement('add_show_duration')->setErrors(array('Cannot schedule overlapping shows'));
break 1;
} else {
$repeatShowStart->setTimezone($localTimezone);
$repeatShowEnd->setTimezone($localTimezone);
$repeatShowStart->add(new DateInterval($interval));
$repeatShowEnd->add(new DateInterval($interval));
$repeatShowStart->setTimezone($utc);
$repeatShowEnd->setTimezone($utc);
}
}
}
} else {
$valid = false;
$this->getElement('add_show_duration')->setErrors(array('Cannot schedule overlapping shows'));
}
} elseif ($formData["add_show_rebroadcast"]) {
/* Check first show
* Continue if the first show does not overlap
*/
$overlapping = Application_Model_Schedule::checkOverlappingShows($show_start, $show_end, $update, $instanceId);
if (!$overlapping) {
$durationToAdd = "PT".$hours."H".$minutes."M";
for ($i = 1; $i <= 10; $i++) {
if (empty($formData["add_show_rebroadcast_date_absolute_".$i])) break;
$abs_rebroadcast_start = $formData["add_show_rebroadcast_date_absolute_".$i]." ".
$formData["add_show_rebroadcast_time_absolute_".$i];
$rebroadcastShowStart = new DateTime($abs_rebroadcast_start);
$rebroadcastShowStart->setTimezone(new DateTimeZone('UTC'));
$rebroadcastShowEnd = clone $rebroadcastShowStart;
$rebroadcastShowEnd->add(new DateInterval($durationToAdd));
$overlapping = Application_Model_Schedule::checkOverlappingShows($rebroadcastShowStart, $rebroadcastShowEnd, $update, $instanceId);
if ($overlapping) {
$valid = false;
$this->getElement('add_show_duration')->setErrors(array('Cannot schedule overlapping shows'));
break;
}
}
} else {
$valid = false;
$this->getElement('add_show_duration')->setErrors(array('Cannot schedule overlapping shows'));
}
} else {
$overlapping = Application_Model_Schedule::checkOverlappingShows($show_start, $show_end, $update, $instanceId);
if ($overlapping) {
$this->getElement('add_show_duration')->setErrors(array('Cannot schedule overlapping shows'));
$valid = false;
}
}
}
return $valid; return $valid;
} }
public function disable(){ public function checkRebroadcastDates($repeatShowStart, $formData, $hours, $minutes, $showEdit=false) {
$overlapping = false;
for ($i = 1; $i <= 10; $i++) {
if (empty($formData["add_show_rebroadcast_date_".$i])) break;
$rebroadcastShowStart = clone $repeatShowStart;
/* formData is in local time so we need to set the
* show start back to local time
*/
$rebroadcastShowStart->setTimezone(new DateTimeZone(
Application_Model_Preference::GetTimezone()));
$rebroadcastWhenDays = explode(" ", $formData["add_show_rebroadcast_date_".$i]);
$rebroadcastWhenTime = explode(":", $formData["add_show_rebroadcast_time_".$i]);
$rebroadcastShowStart->add(new DateInterval("P".$rebroadcastWhenDays[0]."D"));
$rebroadcastShowStart->setTime($rebroadcastWhenTime[0], $rebroadcastWhenTime[1]);
$rebroadcastShowStart->setTimezone(new DateTimeZone('UTC'));
$rebroadcastShowEnd = clone $rebroadcastShowStart;
$rebroadcastShowEnd->add(new DateInterval("PT".$hours."H".$minutes."M"));
if ($showEdit) {
$overlapping = Application_Model_Schedule::checkOverlappingShows(
$rebroadcastShowStart, $rebroadcastShowEnd, true, null, $formData['add_show_id']);
} else {
$overlapping = Application_Model_Schedule::checkOverlappingShows(
$rebroadcastShowStart, $rebroadcastShowEnd);
}
if ($overlapping) break;
}
return $overlapping;
}
public function disable()
{
$elements = $this->getElements(); $elements = $this->getElements();
foreach ($elements as $element) foreach ($elements as $element) {
{ if ($element->getType() != 'Zend_Form_Element_Hidden') {
if ($element->getType() != 'Zend_Form_Element_Hidden')
{
$element->setAttrib('disabled','disabled'); $element->setAttrib('disabled','disabled');
} }
} }
} }
public function disableRepeatCheckbox(){ public function disableRepeatCheckbox()
{
$element = $this->getElement('add_show_repeats'); $element = $this->getElement('add_show_repeats');
if ($element->getType() != 'Zend_Form_Element_Hidden') if ($element->getType() != 'Zend_Form_Element_Hidden') {
{
$element->setAttrib('disabled','disabled'); $element->setAttrib('disabled','disabled');
} }
} }
public function disableStartDateAndTime(){ public function disableStartDateAndTime()
{
$elements = array($this->getElement('add_show_start_date'), $this->getElement('add_show_start_time')); $elements = array($this->getElement('add_show_start_date'), $this->getElement('add_show_start_time'));
foreach ($elements as $element) foreach ($elements as $element) {
{ if ($element->getType() != 'Zend_Form_Element_Hidden') {
if ($element->getType() != 'Zend_Form_Element_Hidden')
{
$element->setAttrib('disabled','disabled'); $element->setAttrib('disabled','disabled');
} }
} }
} }
} }

View file

@ -27,15 +27,13 @@ class Application_Form_AddShowWho extends Zend_Form_SubForm
$this->addElement($hosts); $this->addElement($hosts);
} }
public function disable(){ public function disable()
{
$elements = $this->getElements(); $elements = $this->getElements();
foreach ($elements as $element) foreach ($elements as $element) {
{ if ($element->getType() != 'Zend_Form_Element_Hidden') {
if ($element->getType() != 'Zend_Form_Element_Hidden')
{
$element->setAttrib('disabled','disabled'); $element->setAttrib('disabled','disabled');
} }
} }
} }
} }

View file

@ -92,13 +92,14 @@ class Application_Form_AddUser extends Zend_Form
$this->addElement($submit); $this->addElement($submit);
} }
public function validateLogin($data){ public function validateLogin($data)
{
if (strlen($data['user_id']) == 0){ if (strlen($data['user_id']) == 0) {
$count = CcSubjsQuery::create()->filterByDbLogin($data['login'])->count(); $count = CcSubjsQuery::create()->filterByDbLogin($data['login'])->count();
if ($count != 0){ if ($count != 0) {
$this->getElement('login')->setErrors(array("Login name is not unique.")); $this->getElement('login')->setErrors(array("Login name is not unique."));
return false; return false;
} }
} }
@ -106,4 +107,3 @@ class Application_Form_AddUser extends Zend_Form
return true; return true;
} }
} }

View file

@ -32,9 +32,7 @@ class Application_Form_EditAudioMD extends Zend_Form
$this->addElement('text', 'track_number', array( $this->addElement('text', 'track_number', array(
'label' => 'Track:', 'label' => 'Track:',
'class' => 'input_text', 'class' => 'input_text',
'filters' => array('StringTrim'), 'filters' => array('StringTrim')
'validators' => array('Int'),
'required' => true
)); ));
// Add genre field // Add genre field
@ -125,7 +123,7 @@ class Application_Form_EditAudioMD extends Zend_Form
// Add the submit button // Add the submit button
$this->addElement('submit', 'submit', array( $this->addElement('submit', 'submit', array(
'ignore' => true, 'ignore' => true,
'class' => 'ui-button ui-state-default', 'class' => 'btn',
'label' => 'Save', 'label' => 'Save',
'decorators' => array( 'decorators' => array(
'ViewHelper' 'ViewHelper'
@ -135,9 +133,9 @@ class Application_Form_EditAudioMD extends Zend_Form
// Add the submit button // Add the submit button
$this->addElement('button', 'cancel', array( $this->addElement('button', 'cancel', array(
'ignore' => true, 'ignore' => true,
'class' => 'ui-button ui-state-default ui-button-text-only md-cancel', 'class' => 'btn md-cancel',
'label' => 'Cancel', 'label' => 'Cancel',
'onclick' => 'javascript:document.location.href = "/Playlist"', 'onclick' => 'javascript:document.location.href = "/Library"',
'decorators' => array( 'decorators' => array(
'ViewHelper' 'ViewHelper'
) )
@ -151,6 +149,4 @@ class Application_Form_EditAudioMD extends Zend_Form
)); ));
} }
} }

View file

@ -42,6 +42,15 @@ class Application_Form_EmailServerPreferences extends Zend_Form_SubForm
) )
)); ));
$this->addElement('checkbox', 'msRequiresAuth', array(
'label' => 'Requires Authentication',
'required' => false,
'value' => Application_Model_Preference::GetMailServerRequiresAuth(),
'decorators' => array(
'viewHelper'
)
));
$this->addElement('text', 'mailServer', array( $this->addElement('text', 'mailServer', array(
'class' => 'input_text', 'class' => 'input_text',
'label' => 'Mail Server', 'label' => 'Mail Server',
@ -50,7 +59,9 @@ class Application_Form_EmailServerPreferences extends Zend_Form_SubForm
'decorators' => array('viewHelper'), 'decorators' => array('viewHelper'),
'allowEmpty' => false, 'allowEmpty' => false,
'validators' => array( 'validators' => array(
new ConditionalNotEmpty(array('configureMailServer'=>'1')) new ConditionalNotEmpty(array(
'configureMailServer' => '1'
))
) )
)); ));
@ -62,7 +73,10 @@ class Application_Form_EmailServerPreferences extends Zend_Form_SubForm
'decorators' => array('viewHelper'), 'decorators' => array('viewHelper'),
'allowEmpty' => false, 'allowEmpty' => false,
'validators' => array( 'validators' => array(
new ConditionalNotEmpty(array('configureMailServer'=>'1')) new ConditionalNotEmpty(array(
'configureMailServer' => '1',
'msRequiresAuth' => '1'
))
) )
)); ));
@ -74,7 +88,10 @@ class Application_Form_EmailServerPreferences extends Zend_Form_SubForm
'decorators' => array('viewHelper'), 'decorators' => array('viewHelper'),
'allowEmpty' => false, 'allowEmpty' => false,
'validators' => array( 'validators' => array(
new ConditionalNotEmpty(array('configureMailServer'=>'1')) new ConditionalNotEmpty(array(
'configureMailServer' => '1',
'msRequiresAuth' => '1'
))
), ),
'renderPassword' => true 'renderPassword' => true
)); ));
@ -91,6 +108,4 @@ class Application_Form_EmailServerPreferences extends Zend_Form_SubForm
} }
} }

View file

@ -14,7 +14,7 @@ class Application_Form_GeneralPreferences extends Zend_Form_SubForm
)); ));
$defaultFade = Application_Model_Preference::GetDefaultFade(); $defaultFade = Application_Model_Preference::GetDefaultFade();
if($defaultFade == ""){ if ($defaultFade == "") {
$defaultFade = '0.500000'; $defaultFade = '0.500000';
} }
@ -24,7 +24,7 @@ class Application_Form_GeneralPreferences extends Zend_Form_SubForm
'label' => 'Station Name', 'label' => 'Station Name',
'required' => false, 'required' => false,
'filters' => array('StringTrim'), 'filters' => array('StringTrim'),
'value' => Application_Model_Preference::GetValue("station_name"), 'value' => Application_Model_Preference::GetStationName(),
'decorators' => array( 'decorators' => array(
'ViewHelper' 'ViewHelper'
) )
@ -70,7 +70,8 @@ class Application_Form_GeneralPreferences extends Zend_Form_SubForm
$this->addElement($week_start_day); $this->addElement($week_start_day);
} }
private function getTimezones(){ private function getTimezones()
{
$regions = array( $regions = array(
'Africa' => DateTimeZone::AFRICA, 'Africa' => DateTimeZone::AFRICA,
'America' => DateTimeZone::AMERICA, 'America' => DateTimeZone::AMERICA,
@ -86,9 +87,9 @@ class Application_Form_GeneralPreferences extends Zend_Form_SubForm
$tzlist = array(); $tzlist = array();
foreach ($regions as $name => $mask){ foreach ($regions as $name => $mask) {
$ids = DateTimeZone::listIdentifiers($mask); $ids = DateTimeZone::listIdentifiers($mask);
foreach ($ids as $id){ foreach ($ids as $id) {
$tzlist[$id] = str_replace("_", " ", $id); $tzlist[$id] = str_replace("_", " ", $id);
} }
} }
@ -96,8 +97,8 @@ class Application_Form_GeneralPreferences extends Zend_Form_SubForm
return $tzlist; return $tzlist;
} }
private function getWeekStartDays()
private function getWeekStartDays() { {
$days = array( $days = array(
'Sunday', 'Sunday',
'Monday', 'Monday',
@ -107,7 +108,7 @@ class Application_Form_GeneralPreferences extends Zend_Form_SubForm
'Friday', 'Friday',
'Saturday' 'Saturday'
); );
return $days; return $days;
} }
} }

View file

@ -11,7 +11,7 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
$isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; $isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true;
$defaultFade = Application_Model_Preference::GetDefaultTransitionFade(); $defaultFade = Application_Model_Preference::GetDefaultTransitionFade();
if($defaultFade == ""){ if ($defaultFade == "") {
$defaultFade = '00.000000'; $defaultFade = '00.000000';
} }
@ -45,21 +45,21 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
->setAllowEmpty(true) ->setAllowEmpty(true)
->setLabel('Master Username') ->setLabel('Master Username')
->setFilters(array('StringTrim')) ->setFilters(array('StringTrim'))
->setValue(Application_Model_Preference::GetLiveSteamMasterUsername()) ->setValue(Application_Model_Preference::GetLiveStreamMasterUsername())
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
$this->addElement($master_username); $this->addElement($master_username);
//Master password //Master password
if($isDemo){ if ($isDemo) {
$master_password = new Zend_Form_Element_Text('master_password'); $master_password = new Zend_Form_Element_Text('master_password');
}else{ } else {
$master_password = new Zend_Form_Element_Password('master_password'); $master_password = new Zend_Form_Element_Password('master_password');
$master_password->setAttrib('renderPassword','true'); $master_password->setAttrib('renderPassword','true');
} }
$master_password->setAttrib('autocomplete', 'off') $master_password->setAttrib('autocomplete', 'off')
->setAttrib('renderPassword','true') ->setAttrib('renderPassword','true')
->setAllowEmpty(true) ->setAllowEmpty(true)
->setValue(Application_Model_Preference::GetLiveSteamMasterPassword()) ->setValue(Application_Model_Preference::GetLiveStreamMasterPassword())
->setLabel('Master Password') ->setLabel('Master Password')
->setFilters(array('StringTrim')) ->setFilters(array('StringTrim'))
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
@ -83,7 +83,7 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
//liquidsoap harbor.input port //liquidsoap harbor.input port
if (!$isSaas) { if (!$isSaas) {
$m_port = Application_Model_StreamSetting::GetMasterLiveSteamPort(); $m_port = Application_Model_StreamSetting::getMasterLiveStreamPort();
$master_dj_port = new Zend_Form_Element_Text('master_harbor_input_port'); $master_dj_port = new Zend_Form_Element_Text('master_harbor_input_port');
$master_dj_port->setLabel("Master Source Port") $master_dj_port->setLabel("Master Source Port")
->setValue($m_port) ->setValue($m_port)
@ -92,7 +92,7 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
$this->addElement($master_dj_port); $this->addElement($master_dj_port);
$m_mount = Application_Model_StreamSetting::GetMasterLiveSteamMountPoint(); $m_mount = Application_Model_StreamSetting::getMasterLiveStreamMountPoint();
$master_dj_mount = new Zend_Form_Element_Text('master_harbor_input_mount_point'); $master_dj_mount = new Zend_Form_Element_Text('master_harbor_input_mount_point');
$master_dj_mount->setLabel("Master Source Mount Point") $master_dj_mount->setLabel("Master Source Mount Point")
->setValue($m_mount) ->setValue($m_mount)
@ -102,7 +102,7 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
$this->addElement($master_dj_mount); $this->addElement($master_dj_mount);
//liquidsoap harbor.input port //liquidsoap harbor.input port
$l_port = Application_Model_StreamSetting::GetDJLiveSteamPort(); $l_port = Application_Model_StreamSetting::getDjLiveStreamPort();
$live_dj_port = new Zend_Form_Element_Text('dj_harbor_input_port'); $live_dj_port = new Zend_Form_Element_Text('dj_harbor_input_port');
$live_dj_port->setLabel("Show Source Port") $live_dj_port->setLabel("Show Source Port")
->setValue($l_port) ->setValue($l_port)
@ -111,7 +111,7 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
$this->addElement($live_dj_port); $this->addElement($live_dj_port);
$l_mount = Application_Model_StreamSetting::GetDJLiveSteamMountPoint(); $l_mount = Application_Model_StreamSetting::getDjLiveStreamMountPoint();
$live_dj_mount = new Zend_Form_Element_Text('dj_harbor_input_mount_point'); $live_dj_mount = new Zend_Form_Element_Text('dj_harbor_input_mount_point');
$live_dj_mount->setLabel("Show Source Mount Point") $live_dj_mount->setLabel("Show Source Mount Point")
->setValue($l_mount) ->setValue($l_mount)
@ -121,19 +121,18 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
$this->addElement($live_dj_mount); $this->addElement($live_dj_mount);
} }
// demo only code // demo only code
if(!$isStreamConfigable){ if (!$isStreamConfigable) {
$elements = $this->getElements(); $elements = $this->getElements();
foreach ($elements as $element) foreach ($elements as $element) {
{ if ($element->getType() != 'Zend_Form_Element_Hidden') {
if ($element->getType() != 'Zend_Form_Element_Hidden')
{
$element->setAttrib("disabled", "disabled"); $element->setAttrib("disabled", "disabled");
} }
} }
} }
} }
public function updateVariables(){ public function updateVariables()
{
global $CC_CONFIG; global $CC_CONFIG;
$isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; $isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true;
@ -146,50 +145,52 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
)); ));
} }
public function isValid($data){ public function isValid($data)
{
$isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; $isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true;
$isValid = parent::isValid($data); $isValid = parent::isValid($data);
if (!$isSaas) { if (!$isSaas) {
$master_harbor_input_port = $data['master_harbor_input_port']; $master_harbor_input_port = $data['master_harbor_input_port'];
$dj_harbor_input_port = $data['dj_harbor_input_port']; $dj_harbor_input_port = $data['dj_harbor_input_port'];
if($master_harbor_input_port == $dj_harbor_input_port && $master_harbor_input_port != ""){ if ($master_harbor_input_port == $dj_harbor_input_port && $master_harbor_input_port != "") {
$element = $this->getElement("dj_harbor_input_port"); $element = $this->getElement("dj_harbor_input_port");
$element->addError("You cannot use same port as Master DJ port."); $element->addError("You cannot use same port as Master DJ port.");
} }
if($master_harbor_input_port != ""){ if ($master_harbor_input_port != "") {
if(is_numeric($master_harbor_input_port)){ if (is_numeric($master_harbor_input_port)) {
if($master_harbor_input_port != Application_Model_StreamSetting::GetMasterLiveSteamPort()){ if ($master_harbor_input_port != Application_Model_StreamSetting::getMasterLiveStreamPort()) {
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$res = socket_bind($sock, 0, $master_harbor_input_port); $res = socket_bind($sock, 0, $master_harbor_input_port);
if(!$res){ if (!$res) {
$element = $this->getElement("master_harbor_input_port"); $element = $this->getElement("master_harbor_input_port");
$element->addError("Port '$master_harbor_input_port' is not available."); $element->addError("Port '$master_harbor_input_port' is not available.");
$isValid = false; $isValid = false;
} }
socket_close($sock); socket_close($sock);
} }
}else{ } else {
$isValid = false; $isValid = false;
} }
} }
if($dj_harbor_input_port != ""){ if ($dj_harbor_input_port != "") {
if(is_numeric($dj_harbor_input_port)){ if (is_numeric($dj_harbor_input_port)) {
if($dj_harbor_input_port != Application_Model_StreamSetting::GetDJLiveSteamPort()){ if ($dj_harbor_input_port != Application_Model_StreamSetting::getDjLiveStreamPort()) {
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$res = socket_bind($sock, 0, $dj_harbor_input_port); $res = socket_bind($sock, 0, $dj_harbor_input_port);
if(!$res){ if (!$res) {
$element = $this->getElement("dj_harbor_input_port"); $element = $this->getElement("dj_harbor_input_port");
$element->addError("Port '$dj_harbor_input_port' is not available."); $element->addError("Port '$dj_harbor_input_port' is not available.");
$isValid = false; $isValid = false;
} }
socket_close($sock); socket_close($sock);
} }
}else{ } else {
$isValid = false; $isValid = false;
} }
} }
} }
return $isValid; return $isValid;
} }

View file

@ -45,10 +45,10 @@ class Application_Form_Login extends Zend_Form
)); ));
$recaptchaNeeded = false; $recaptchaNeeded = false;
if(Application_Model_LoginAttempts::getAttempts($_SERVER['REMOTE_ADDR']) >= 3){ if (Application_Model_LoginAttempts::getAttempts($_SERVER['REMOTE_ADDR']) >= 3) {
$recaptchaNeeded = true; $recaptchaNeeded = true;
} }
if($recaptchaNeeded){ if ($recaptchaNeeded) {
// recaptcha // recaptcha
$this->addRecaptcha(); $this->addRecaptcha();
} }
@ -65,7 +65,8 @@ class Application_Form_Login extends Zend_Form
} }
public function addRecaptcha(){ public function addRecaptcha()
{
$pubKey = '6Ld4JsISAAAAAIxUKT4IjjOGi3DHqdoH2zk6WkYG'; $pubKey = '6Ld4JsISAAAAAIxUKT4IjjOGi3DHqdoH2zk6WkYG';
$privKey = '6Ld4JsISAAAAAJynYlXdrE4hfTReTSxYFe5szdyv'; $privKey = '6Ld4JsISAAAAAJynYlXdrE4hfTReTSxYFe5szdyv';
@ -84,6 +85,4 @@ class Application_Form_Login extends Zend_Form
$this->addElement($captcha); $this->addElement($captcha);
} }
} }

View file

@ -21,6 +21,17 @@ class Application_Form_PasswordRestore extends Zend_Form
) )
)); ));
$this->addElement('text', 'username', array(
'label' => 'Username',
'required' => false,
'filters' => array(
'stringTrim',
),
'decorators' => array(
'ViewHelper'
)
));
$this->addElement('submit', 'submit', array( $this->addElement('submit', 'submit', array(
'label' => 'Restore password', 'label' => 'Restore password',
'ignore' => true, 'ignore' => true,

View file

@ -13,13 +13,16 @@ class Application_Form_RegisterAirtime extends Zend_Form
$country_list = Application_Model_Preference::GetCountryList(); $country_list = Application_Model_Preference::GetCountryList();
$privacyChecked = false; $privacyChecked = false;
if(Application_Model_Preference::GetPrivacyPolicyCheck() == 1){ if (Application_Model_Preference::GetPrivacyPolicyCheck() == 1) {
$privacyChecked = true; $privacyChecked = true;
} }
$this->setDecorators(array( $this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/register-dialog.phtml', 'privacyChecked'=>$privacyChecked)), array('ViewScript', array('viewScript' =>
array('File', array('viewScript' => 'form/register-dialog.phtml', 'placement' => false))) 'form/register-dialog.phtml', 'privacyChecked'=>$privacyChecked)),
array('File', array('viewScript' => 'form/register-dialog.phtml',
'placement' => false)))
); );
// Station Name // Station Name
@ -151,17 +154,17 @@ class Application_Form_RegisterAirtime extends Zend_Form
public function isValid ($data) public function isValid ($data)
{ {
$isValid = parent::isValid($data); $isValid = parent::isValid($data);
if($data['Publicise'] != 1){ if ($data['Publicise'] != 1) {
$isValid = true; $isValid = true;
} }
if(isset($data["Privacy"])){ if (isset($data["Privacy"])) {
$checkPrivacy = $this->getElement('Privacy'); $checkPrivacy = $this->getElement('Privacy');
if($data["SupportFeedback"] == "1" && $data["Privacy"] != "1"){ if ($data["SupportFeedback"] == "1" && $data["Privacy"] != "1") {
$checkPrivacy->addError("You have to agree to privacy policy."); $checkPrivacy->addError("You have to agree to privacy policy.");
$isValid = false; $isValid = false;
} }
} }
return $isValid; return $isValid;
} }
} }

View file

@ -8,6 +8,4 @@ class Application_Form_ScheduleShow extends Zend_Form
/* Form Elements & Other Definitions Here ... */ /* Form Elements & Other Definitions Here ... */
} }
} }

View file

@ -5,7 +5,7 @@ class Application_Form_ShowBuilder extends Zend_Form_SubForm
public function init() public function init()
{ {
$user = Application_Model_User::GetCurrentUser(); $user = Application_Model_User::getCurrentUser();
$this->setDecorators(array( $this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/showbuilder.phtml')) array('ViewScript', array('viewScript' => 'form/showbuilder.phtml'))
@ -67,7 +67,6 @@ class Application_Form_ShowBuilder extends Zend_Form_SubForm
$endTime->setAttrib('alt', 'time'); $endTime->setAttrib('alt', 'time');
$this->addElement($endTime); $this->addElement($endTime);
// add a select to choose a show. // add a select to choose a show.
$showSelect = new Zend_Form_Element_Select("sb_show_filter"); $showSelect = new Zend_Form_Element_Select("sb_show_filter");
$showSelect->setLabel("Show:"); $showSelect->setLabel("Show:");
@ -84,8 +83,8 @@ class Application_Form_ShowBuilder extends Zend_Form_SubForm
} }
} }
private function getShowNames() { private function getShowNames()
{
$showNames = array("0" => "-------------------------"); $showNames = array("0" => "-------------------------");
$shows = CcShowQuery::create() $shows = CcShowQuery::create()

View file

@ -0,0 +1,516 @@
<?php
class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm
{
private $criteriaOptions = array(
0 => "Select criteria",
"album_title" => "Album",
"bit_rate" => "Bit Rate (Kbps)",
"bpm" => "BPM",
"composer" => "Composer",
"conductor" => "Conductor",
"copyright" => "Copyright",
"artist_name" => "Creator",
"encoded_by" => "Encoded By",
"genre" => "Genre",
"isrc_number" => "ISRC",
"label" => "Label",
"language" => "Language",
"mtime" => "Last Modified",
"lptime" => "Last Played",
"length" => "Length",
"mime" => "Mime",
"mood" => "Mood",
"owner_id" => "Owner",
"replay_gain" => "Replay Gain",
"sample_rate" => "Sample Rate (kHz)",
"track_title" => "Title",
"track_number" => "Track Number",
"utime" => "Uploaded",
"info_url" => "Website",
"year" => "Year"
);
private $criteriaTypes = array(
0 => "",
"album_title" => "s",
"bit_rate" => "n",
"bpm" => "n",
"composer" => "s",
"conductor" => "s",
"copyright" => "s",
"artist_name" => "s",
"encoded_by" => "s",
"utime" => "n",
"mtime" => "n",
"lptime" => "n",
"genre" => "s",
"isrc_number" => "s",
"label" => "s",
"language" => "s",
"length" => "n",
"mime" => "s",
"mood" => "s",
"owner_id" => "s",
"replay_gain" => "n",
"sample_rate" => "n",
"track_title" => "s",
"track_number" => "n",
"info_url" => "s",
"year" => "n"
);
private $stringCriteriaOptions = array(
"0" => "Select modifier",
"contains" => "contains",
"does not contain" => "does not contain",
"is" => "is",
"is not" => "is not",
"starts with" => "starts with",
"ends with" => "ends with"
);
private $numericCriteriaOptions = array(
"0" => "Select modifier",
"is" => "is",
"is not" => "is not",
"is greater than" => "is greater than",
"is less than" => "is less than",
"is in the range" => "is in the range"
);
private $limitOptions = array(
"hours" => "hours",
"minutes" => "minutes",
"items" => "items"
);
public function init()
{
}
public function startForm($p_blockId, $p_isValid = false)
{
// load type
$out = CcBlockQuery::create()->findPk($p_blockId);
if ($out->getDbType() == "static") {
$blockType = 0;
} else {
$blockType = 1;
}
$spType = new Zend_Form_Element_Radio('sp_type');
$spType->setLabel('Set smart block type:')
->setDecorators(array('viewHelper'))
->setMultiOptions(array(
'static' => 'Static',
'dynamic' => 'Dynamic'
))
->setValue($blockType);
$this->addElement($spType);
$bl = new Application_Model_Block($p_blockId);
$storedCrit = $bl->getCriteria();
/* $modRoadMap stores the number of same criteria
* Ex: 3 Album titles, and 2 Track titles
* We need to know this so we display the form elements properly
*/
$modRowMap = array();
$openSmartBlockOption = false;
if (!empty($storedCrit)) {
$openSmartBlockOption = true;
}
$criteriaKeys = array();
if (isset($storedCrit["crit"])) {
$criteriaKeys = array_keys($storedCrit["crit"]);
}
$numElements = count($this->criteriaOptions);
for ($i = 0; $i < $numElements; $i++) {
$criteriaType = "";
if (isset($criteriaKeys[$i])) {
$critCount = count($storedCrit["crit"][$criteriaKeys[$i]]);
} else {
$critCount = 1;
}
$modRowMap[$i] = $critCount;
/* Loop through all criteria with the same field
* Ex: all criteria for 'Album'
*/
for ($j = 0; $j < $critCount; $j++) {
/****************** CRITERIA ***********/
if ($j > 0) {
$invisible = ' sp-invisible';
} else {
$invisible = '';
}
$criteria = new Zend_Form_Element_Select("sp_criteria_field_".$i."_".$j);
$criteria->setAttrib('class', 'input_select sp_input_select'.$invisible)
->setValue('Select criteria')
->setDecorators(array('viewHelper'))
->setMultiOptions($this->criteriaOptions);
if ($i != 0 && !isset($criteriaKeys[$i])) {
$criteria->setAttrib('disabled', 'disabled');
}
if (isset($criteriaKeys[$i])) {
$criteriaType = $this->criteriaTypes[$storedCrit["crit"][$criteriaKeys[$i]][$j]["criteria"]];
$criteria->setValue($storedCrit["crit"][$criteriaKeys[$i]][$j]["criteria"]);
}
$this->addElement($criteria);
/****************** MODIFIER ***********/
$criteriaModifers = new Zend_Form_Element_Select("sp_criteria_modifier_".$i."_".$j);
$criteriaModifers->setValue('Select modifier')
->setAttrib('class', 'input_select sp_input_select')
->setDecorators(array('viewHelper'));
if ($i != 0 && !isset($criteriaKeys[$i])) {
$criteriaModifers->setAttrib('disabled', 'disabled');
}
if (isset($criteriaKeys[$i])) {
if ($criteriaType == "s") {
$criteriaModifers->setMultiOptions($this->stringCriteriaOptions);
} else {
$criteriaModifers->setMultiOptions($this->numericCriteriaOptions);
}
$criteriaModifers->setValue($storedCrit["crit"][$criteriaKeys[$i]][$j]["modifier"]);
} else {
$criteriaModifers->setMultiOptions(array('0' => 'Select modifier'));
}
$this->addElement($criteriaModifers);
/****************** VALUE ***********/
$criteriaValue = new Zend_Form_Element_Text("sp_criteria_value_".$i."_".$j);
$criteriaValue->setAttrib('class', 'input_text sp_input_text')
->setDecorators(array('viewHelper'));
if ($i != 0 && !isset($criteriaKeys[$i])) {
$criteriaValue->setAttrib('disabled', 'disabled');
}
if (isset($criteriaKeys[$i])) {
$criteriaValue->setValue($storedCrit["crit"][$criteriaKeys[$i]][$j]["value"]);
}
$this->addElement($criteriaValue);
/****************** EXTRA ***********/
$criteriaExtra = new Zend_Form_Element_Text("sp_criteria_extra_".$i."_".$j);
$criteriaExtra->setAttrib('class', 'input_text sp_extra_input_text')
->setDecorators(array('viewHelper'));
if (isset($criteriaKeys[$i]) && isset($storedCrit["crit"][$criteriaKeys[$i]][$j]["extra"])) {
$criteriaExtra->setValue($storedCrit["crit"][$criteriaKeys[$i]][$j]["extra"]);
$criteriaValue->setAttrib('class', 'input_text sp_extra_input_text');
} else {
$criteriaExtra->setAttrib('disabled', 'disabled');
}
$this->addElement($criteriaExtra);
}//for
}//for
$limit = new Zend_Form_Element_Select('sp_limit_options');
$limit->setAttrib('class', 'sp_input_select')
->setDecorators(array('viewHelper'))
->setMultiOptions($this->limitOptions);
if (isset($storedCrit["limit"])) {
$limit->setValue($storedCrit["limit"]["modifier"]);
}
$this->addElement($limit);
$limitValue = new Zend_Form_Element_Text('sp_limit_value');
$limitValue->setAttrib('class', 'sp_input_text_limit')
->setLabel('Limit to')
->setDecorators(array('viewHelper'));
$this->addElement($limitValue);
if (isset($storedCrit["limit"])) {
$limitValue->setValue($storedCrit["limit"]["value"]);
} else {
// setting default to 1 hour
$limitValue->setValue(1);
}
//getting block content candidate count that meets criteria
$bl = new Application_Model_Block($p_blockId);
if ($p_isValid) {
$files = $bl->getListofFilesMeetCriteria();
$showPoolCount = true;
} else {
$files = null;
$showPoolCount = false;
}
$generate = new Zend_Form_Element_Button('generate_button');
$generate->setAttrib('class', 'btn btn-small');
$generate->setAttrib('title', 'Generate playlist content and save criteria');
$generate->setIgnore(true);
$generate->setLabel('Generate');
$generate->setDecorators(array('viewHelper'));
$this->addElement($generate);
$shuffle = new Zend_Form_Element_Button('shuffle_button');
$shuffle->setAttrib('class', 'btn btn-small');
$shuffle->setAttrib('title', 'Shuffle playlist content');
$shuffle->setIgnore(true);
$shuffle->setLabel('Shuffle');
$shuffle->setDecorators(array('viewHelper'));
$this->addElement($shuffle);
$this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/smart-block-criteria.phtml', "openOption"=> $openSmartBlockOption,
'criteriasLength' => count($this->criteriaOptions), 'poolCount' => $files['count'], 'modRowMap' => $modRowMap,
'showPoolCount' => $showPoolCount))
));
}
public function preValidation($params)
{
$data = Application_Model_Block::organizeSmartPlyalistCriteria($params['data']);
// add elelments that needs to be added
// set multioption for modifier according to creiteria_field
$modRowMap = array();
foreach ($data['criteria'] as $critKey=>$d) {
$count = 1;
foreach ($d as $modKey=>$modInfo) {
if ($modKey == 0) {
$eleCrit = $this->getElement("sp_criteria_field_".$critKey."_".$modKey);
$eleCrit->setValue($this->criteriaOptions[$modInfo['sp_criteria_field']]);
$eleCrit->setAttrib("disabled", null);
$eleMod = $this->getElement("sp_criteria_modifier_".$critKey."_".$modKey);
$criteriaType = $this->criteriaTypes[$modInfo['sp_criteria_field']];
if ($criteriaType == "s") {
$eleMod->setMultiOptions($this->stringCriteriaOptions);
} elseif ($criteriaType == "n") {
$eleMod->setMultiOptions($this->numericCriteriaOptions);
} else {
$eleMod->setMultiOptions(array('0' => 'Select modifier'));
}
$eleMod->setValue($modInfo['sp_criteria_modifier']);
$eleMod->setAttrib("disabled", null);
$eleValue = $this->getElement("sp_criteria_value_".$critKey."_".$modKey);
$eleValue->setValue($modInfo['sp_criteria_value']);
$eleValue->setAttrib("disabled", null);
if (isset($modInfo['sp_criteria_extra'])) {
$eleExtra = $this->getElement("sp_criteria_extra_".$critKey."_".$modKey);
$eleExtra->setValue($modInfo['sp_criteria_extra']);
$eleValue->setAttrib('class', 'input_text sp_extra_input_text');
$eleExtra->setAttrib("disabled", null);
}
} else {
$criteria = new Zend_Form_Element_Select("sp_criteria_field_".$critKey."_".$modKey);
$criteria->setAttrib('class', 'input_select sp_input_select sp-invisible')
->setValue('Select criteria')
->setDecorators(array('viewHelper'))
->setMultiOptions($this->criteriaOptions);
$criteriaType = $this->criteriaTypes[$modInfo['sp_criteria_field']];
$criteria->setValue($this->criteriaOptions[$modInfo['sp_criteria_field']]);
$this->addElement($criteria);
/****************** MODIFIER ***********/
$criteriaModifers = new Zend_Form_Element_Select("sp_criteria_modifier_".$critKey."_".$modKey);
$criteriaModifers->setValue('Select modifier')
->setAttrib('class', 'input_select sp_input_select')
->setDecorators(array('viewHelper'));
if ($criteriaType == "s") {
$criteriaModifers->setMultiOptions($this->stringCriteriaOptions);
} elseif ($criteriaType == "n") {
$criteriaModifers->setMultiOptions($this->numericCriteriaOptions);
} else {
$criteriaModifers->setMultiOptions(array('0' => 'Select modifier'));
}
$criteriaModifers->setValue($modInfo['sp_criteria_modifier']);
$this->addElement($criteriaModifers);
/****************** VALUE ***********/
$criteriaValue = new Zend_Form_Element_Text("sp_criteria_value_".$critKey."_".$modKey);
$criteriaValue->setAttrib('class', 'input_text sp_input_text')
->setDecorators(array('viewHelper'));
$criteriaValue->setValue($modInfo['sp_criteria_value']);
$this->addElement($criteriaValue);
/****************** EXTRA ***********/
$criteriaExtra = new Zend_Form_Element_Text("sp_criteria_extra_".$critKey."_".$modKey);
$criteriaExtra->setAttrib('class', 'input_text sp_extra_input_text')
->setDecorators(array('viewHelper'));
if (isset($modInfo['sp_criteria_extra'])) {
$criteriaExtra->setValue($modInfo['sp_criteria_extra']);
$criteriaValue->setAttrib('class', 'input_text sp_extra_input_text');
} else {
$criteriaExtra->setAttrib('disabled', 'disabled');
}
$this->addElement($criteriaExtra);
$count++;
}
}
$modRowMap[$critKey] = $count;
}
$decorator = $this->getDecorator("ViewScript");
$existingModRow = $decorator->getOption("modRowMap");
foreach ($modRowMap as $key=>$v) {
$existingModRow[$key] = $v;
}
$decorator->setOption("modRowMap", $existingModRow);
// reconstruct the params['criteria'] so we can populate the form
$formData = array();
foreach ($params['data'] as $ele) {
$formData[$ele['name']] = $ele['value'];
}
$this->populate($formData);
return $data;
}
public function isValid($params)
{
$isValid = true;
$data = $this->preValidation($params);
$criteria2PeerMap = array(
0 => "Select criteria",
"album_title" => "DbAlbumTitle",
"artist_name" => "DbArtistName",
"bit_rate" => "DbBitRate",
"bpm" => "DbBpm",
"composer" => "DbComposer",
"conductor" => "DbConductor",
"copyright" => "DbCopyright",
"encoded_by" => "DbEncodedBy",
"utime" => "DbUtime",
"mtime" => "DbMtime",
"lptime" => "DbLPtime",
"genre" => "DbGenre",
"info_url" => "DbInfoUrl",
"isrc_number" => "DbIsrcNumber",
"label" => "DbLabel",
"language" => "DbLanguage",
"length" => "DbLength",
"mime" => "DbMime",
"mood" => "DbMood",
"owner_id" => "DbOwnerId",
"replay_gain" => "DbReplayGain",
"sample_rate" => "DbSampleRate",
"track_title" => "DbTrackTitle",
"track_number" => "DbTrackNumber",
"year" => "DbYear"
);
// things we need to check
// 1. limit value shouldn't be empty and has upperbound of 24 hrs
// 2. sp_criteria or sp_criteria_modifier shouldn't be 0
// 3. validate formate according to DB column type
$multiplier = 1;
$result = 0;
// validation start
if ($data['etc']['sp_limit_options'] == 'hours') {
$multiplier = 60;
}
if ($data['etc']['sp_limit_options'] == 'hours' || $data['etc']['sp_limit_options'] == 'mins') {
$element = $this->getElement("sp_limit_value");
if ($data['etc']['sp_limit_value'] == "" || floatval($data['etc']['sp_limit_value']) <= 0) {
$element->addError("Limit cannot be empty or smaller than 0");
$isValid = false;
} else {
$mins = floatval($data['etc']['sp_limit_value']) * $multiplier;
if ($mins > 1440) {
$element->addError("Limit cannot be more than 24 hrs");
$isValid = false;
}
}
} else {
$element = $this->getElement("sp_limit_value");
if ($data['etc']['sp_limit_value'] == "" || floatval($data['etc']['sp_limit_value']) <= 0) {
$element->addError("Limit cannot be empty or smaller than 0");
$isValid = false;
} elseif (!ctype_digit($data['etc']['sp_limit_value'])) {
$element->addError("The value should be an integer");
$isValid = false;
} elseif (intval($data['etc']['sp_limit_value']) > 500) {
$element->addError("500 is the max item limit value you can set");
$isValid = false;
}
}
if (isset($data['criteria'])) {
foreach ($data['criteria'] as $rowKey=>$row) {
foreach ($row as $key=>$d) {
$element = $this->getElement("sp_criteria_field_".$rowKey."_".$key);
// check for not selected select box
if ($d['sp_criteria_field'] == "0" || $d['sp_criteria_modifier'] == "0") {
$element->addError("You must select Criteria and Modifier");
$isValid = false;
} else {
$column = CcFilesPeer::getTableMap()->getColumnByPhpName($criteria2PeerMap[$d['sp_criteria_field']]);
// validation on type of column
if ($d['sp_criteria_field'] == 'length') {
if (!preg_match("/^(\d{2}):(\d{2}):(\d{2})/", $d['sp_criteria_value'])) {
$element->addError("'Length' should be in '00:00:00' format");
$isValid = false;
}
} elseif ($column->getType() == PropelColumnTypes::TIMESTAMP) {
if (!preg_match("/(\d{4})-(\d{2})-(\d{2})/", $d['sp_criteria_value'])) {
$element->addError("The value should be in timestamp format(eg. 0000-00-00 or 00-00-00 00:00:00");
$isValid = false;
} else {
$result = Application_Common_DateHelper::checkDateTimeRangeForSQL($d['sp_criteria_value']);
if (!$result["success"]) {
// check for if it is in valid range( 1753-01-01 ~ 12/31/9999 )
$element->addError($result["errMsg"]);
$isValid = false;
}
}
if (isset($d['sp_criteria_extra'])) {
if (!preg_match("/(\d{4})-(\d{2})-(\d{2})/", $d['sp_criteria_extra'])) {
$element->addError("The value should be in timestamp format(eg. 0000-00-00 or 00-00-00 00:00:00");
$isValid = false;
} else {
$result = Application_Common_DateHelper::checkDateTimeRangeForSQL($d['sp_criteria_extra']);
if (!$result["success"]) {
// check for if it is in valid range( 1753-01-01 ~ 12/31/9999 )
$element->addError($result["errMsg"]);
$isValid = false;
}
}
}
} elseif ($column->getType() == PropelColumnTypes::INTEGER &&
$d['sp_criteria_field'] != 'owner_id') {
if (!is_numeric($d['sp_criteria_value'])) {
$element->addError("The value has to be numeric");
$isValid = false;
}
// length check
if (intval($d['sp_criteria_value']) >= pow(2,31)) {
$element->addError("The value should be less then 2147483648");
$isValid = false;
}
} elseif ($column->getType() == PropelColumnTypes::VARCHAR) {
if (strlen($d['sp_criteria_value']) > $column->getSize()) {
$element->addError("The value should be less ".$column->getSize()." characters");
$isValid = false;
}
}
}
if ($d['sp_criteria_value'] == "") {
$element->addError("Value cannot be empty");
$isValid = false;
}
}//end foreach
}//for loop
}//if
return $isValid;
}
}

View file

@ -149,6 +149,4 @@ class Application_Form_SoundcloudPreferences extends Zend_Form_SubForm
$this->addElement($select); $this->addElement($select);
} }
} }

View file

@ -9,19 +9,21 @@ class Application_Form_StreamSetting extends Zend_Form
} }
public function setSetting($setting){ public function setSetting($setting)
{
$this->setting = $setting; $this->setting = $setting;
} }
public function startFrom() { public function startFrom()
{
$setting = $this->setting; $setting = $this->setting;
if(Application_Model_Preference::GetPlanLevel() == 'disabled'){ if (Application_Model_Preference::GetPlanLevel() == 'disabled') {
$output_sound_device = new Zend_Form_Element_Checkbox('output_sound_device'); $output_sound_device = new Zend_Form_Element_Checkbox('output_sound_device');
$output_sound_device->setLabel('Hardware Audio Output') $output_sound_device->setLabel('Hardware Audio Output')
->setRequired(false) ->setRequired(false)
->setValue(($setting['output_sound_device'] == "true")?1:0) ->setValue(($setting['output_sound_device'] == "true")?1:0)
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
if (Application_Model_Preference::GetEnableStreamConf() == "false"){ if (Application_Model_Preference::GetEnableStreamConf() == "false") {
$output_sound_device->setAttrib("readonly", true); $output_sound_device->setAttrib("readonly", true);
} }
$this->addElement($output_sound_device); $this->addElement($output_sound_device);
@ -32,7 +34,7 @@ class Application_Form_StreamSetting extends Zend_Form
->setMultiOptions($output_types) ->setMultiOptions($output_types)
->setValue($setting['output_sound_device_type']) ->setValue($setting['output_sound_device_type'])
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
if($setting['output_sound_device'] != "true"){ if ($setting['output_sound_device'] != "true") {
$output_type->setAttrib("disabled", "disabled"); $output_type->setAttrib("disabled", "disabled");
} }
$this->addElement($output_type); $this->addElement($output_type);
@ -43,7 +45,7 @@ class Application_Form_StreamSetting extends Zend_Form
->setRequired(false) ->setRequired(false)
->setValue(($setting['icecast_vorbis_metadata'] == "true")?1:0) ->setValue(($setting['icecast_vorbis_metadata'] == "true")?1:0)
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
if (Application_Model_Preference::GetEnableStreamConf() == "false"){ if (Application_Model_Preference::GetEnableStreamConf() == "false") {
$icecast_vorbis_metadata->setAttrib("readonly", true); $icecast_vorbis_metadata->setAttrib("readonly", true);
} }
$this->addElement($icecast_vorbis_metadata); $this->addElement($icecast_vorbis_metadata);
@ -58,18 +60,20 @@ class Application_Form_StreamSetting extends Zend_Form
$this->addElement($stream_format); $this->addElement($stream_format);
} }
public function isValid($data){ public function isValid($data)
if(isset($data['output_sound_device'])){ {
if (isset($data['output_sound_device'])) {
$d = array(); $d = array();
$d["output_sound_device"] = $data['output_sound_device']; $d["output_sound_device"] = $data['output_sound_device'];
$d["icecast_vorbis_metadata"] = $data['icecast_vorbis_metadata']; $d["icecast_vorbis_metadata"] = $data['icecast_vorbis_metadata'];
if(isset($data['output_sound_device_type'])){ if (isset($data['output_sound_device_type'])) {
$d["output_sound_device_type"] = $data['output_sound_device_type']; $d["output_sound_device_type"] = $data['output_sound_device_type'];
} }
$d["streamFormat"] = $data['streamFormat']; $d["streamFormat"] = $data['streamFormat'];
$this->populate($d); $this->populate($d);
} }
$isValid = parent::isValid($data); $isValid = parent::isValid($data);
return $isValid; return $isValid;
} }
} }

View file

@ -1,5 +1,6 @@
<?php <?php
class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm
{
private $prefix; private $prefix;
private $setting; private $setting;
private $stream_types; private $stream_types;
@ -10,23 +11,28 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{
} }
public function setPrefix($prefix){ public function setPrefix($prefix)
{
$this->prefix = $prefix; $this->prefix = $prefix;
} }
public function setSetting($setting){ public function setSetting($setting)
{
$this->setting = $setting; $this->setting = $setting;
} }
public function setStreamTypes($stream_types){ public function setStreamTypes($stream_types)
{
$this->stream_types = $stream_types; $this->stream_types = $stream_types;
} }
public function setStreamBitrates($stream_bitrates){ public function setStreamBitrates($stream_bitrates)
{
$this->stream_bitrates = $stream_bitrates; $this->stream_bitrates = $stream_bitrates;
} }
public function startForm(){ public function startForm()
{
$prefix = "s".$this->prefix; $prefix = "s".$this->prefix;
$stream_number = $this->prefix; $stream_number = $this->prefix;
$setting = $this->setting; $setting = $this->setting;
@ -36,16 +42,13 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{
$this->setIsArray(true); $this->setIsArray(true);
$this->setElementsBelongTo($prefix."_data"); $this->setElementsBelongTo($prefix."_data");
$disable_all = false; $disable_all = Application_Model_Preference::GetEnableStreamConf() == "false";
if(Application_Model_Preference::GetEnableStreamConf() == "false"){
$disable_all = true;
}
$enable = new Zend_Form_Element_Checkbox('enable'); $enable = new Zend_Form_Element_Checkbox('enable');
$enable->setLabel('Enabled:') $enable->setLabel('Enabled:')
->setValue($setting[$prefix.'_enable'] == 'true' ? 1 : 0) ->setValue($setting[$prefix.'_enable'] == 'true' ? 1 : 0)
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
if($disable_all){ if ($disable_all) {
$enable->setAttrib("disabled", "disabled"); $enable->setAttrib("disabled", "disabled");
} }
$this->addElement($enable); $this->addElement($enable);
@ -55,7 +58,7 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{
->setMultiOptions($stream_types) ->setMultiOptions($stream_types)
->setValue(isset($setting[$prefix.'_type'])?$setting[$prefix.'_type']:0) ->setValue(isset($setting[$prefix.'_type'])?$setting[$prefix.'_type']:0)
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
if($disable_all){ if ($disable_all) {
$type->setAttrib("disabled", "disabled"); $type->setAttrib("disabled", "disabled");
} }
$this->addElement($type); $this->addElement($type);
@ -65,7 +68,7 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{
->setMultiOptions($stream_bitrates) ->setMultiOptions($stream_bitrates)
->setValue(isset($setting[$prefix.'_bitrate'])?$setting[$prefix.'_bitrate']:0) ->setValue(isset($setting[$prefix.'_bitrate'])?$setting[$prefix.'_bitrate']:0)
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
if($disable_all){ if ($disable_all) {
$bitrate->setAttrib("disabled", "disabled"); $bitrate->setAttrib("disabled", "disabled");
} }
$this->addElement($bitrate); $this->addElement($bitrate);
@ -75,18 +78,28 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{
->setMultiOptions(array("icecast"=>"Icecast", "shoutcast"=>"SHOUTcast")) ->setMultiOptions(array("icecast"=>"Icecast", "shoutcast"=>"SHOUTcast"))
->setValue(isset($setting[$prefix.'_output'])?$setting[$prefix.'_output']:"icecast") ->setValue(isset($setting[$prefix.'_output'])?$setting[$prefix.'_output']:"icecast")
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
if($disable_all){ if ($disable_all) {
$output->setAttrib("disabled", "disabled"); $output->setAttrib("disabled", "disabled");
} }
$this->addElement($output); $this->addElement($output);
$channels = new Zend_Form_Element_Select('channels');
$channels->setLabel("Channels:")
->setMultiOptions(array("mono"=>"1 - Mono", "stereo"=>"2 - Stereo"))
->setValue(isset($setting[$prefix.'_channels']) ? $setting[$prefix.'_channels'] : "stereo")
->setDecorators(array('ViewHelper'));
if ($disable_all) {
$channels->setAttrib("disabled", "disabled");
}
$this->addElement($channels);
$host = new Zend_Form_Element_Text('host'); $host = new Zend_Form_Element_Text('host');
$host->setLabel("Server") $host->setLabel("Server")
->setValue(isset($setting[$prefix.'_host'])?$setting[$prefix.'_host']:"") ->setValue(isset($setting[$prefix.'_host'])?$setting[$prefix.'_host']:"")
->setValidators(array( ->setValidators(array(
array('regex', false, array('/^[0-9a-zA-Z-_.]+$/', 'messages' => 'Invalid character entered')))) array('regex', false, array('/^[0-9a-zA-Z-_.]+$/', 'messages' => 'Invalid character entered'))))
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
if($disable_all){ if ($disable_all) {
$host->setAttrib("disabled", "disabled"); $host->setAttrib("disabled", "disabled");
} }
$host->setAttrib('alt', 'domain'); $host->setAttrib('alt', 'domain');
@ -98,7 +111,7 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{
->setValidators(array(new Zend_Validate_Between(array('min'=>0, 'max'=>99999)))) ->setValidators(array(new Zend_Validate_Between(array('min'=>0, 'max'=>99999))))
->addValidator('regex', false, array('pattern'=>'/^[0-9]+$/', 'messages'=>array('regexNotMatch'=>'Only numbers are allowed.'))) ->addValidator('regex', false, array('pattern'=>'/^[0-9]+$/', 'messages'=>array('regexNotMatch'=>'Only numbers are allowed.')))
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
if($disable_all){ if ($disable_all) {
$port->setAttrib("disabled", "disabled"); $port->setAttrib("disabled", "disabled");
} }
$this->addElement($port); $this->addElement($port);
@ -109,7 +122,7 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{
->setValidators(array( ->setValidators(array(
array('regex', false, array('/^[^ &<>]+$/', 'messages' => 'Invalid character entered')))) array('regex', false, array('/^[^ &<>]+$/', 'messages' => 'Invalid character entered'))))
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
if($disable_all){ if ($disable_all) {
$pass->setAttrib("disabled", "disabled"); $pass->setAttrib("disabled", "disabled");
} }
$pass->setAttrib('alt', 'regular_text'); $pass->setAttrib('alt', 'regular_text');
@ -119,7 +132,7 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{
$genre->setLabel("Genre") $genre->setLabel("Genre")
->setValue(isset($setting[$prefix.'_genre'])?$setting[$prefix.'_genre']:"") ->setValue(isset($setting[$prefix.'_genre'])?$setting[$prefix.'_genre']:"")
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
if($disable_all){ if ($disable_all) {
$genre->setAttrib("disabled", "disabled"); $genre->setAttrib("disabled", "disabled");
} }
$this->addElement($genre); $this->addElement($genre);
@ -130,7 +143,7 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{
->setValidators(array( ->setValidators(array(
array('regex', false, array('/^[0-9a-zA-Z\-_.:\/]+$/', 'messages' => 'Invalid character entered')))) array('regex', false, array('/^[0-9a-zA-Z\-_.:\/]+$/', 'messages' => 'Invalid character entered'))))
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
if($disable_all){ if ($disable_all) {
$url->setAttrib("disabled", "disabled"); $url->setAttrib("disabled", "disabled");
} }
$url->setAttrib('alt', 'url'); $url->setAttrib('alt', 'url');
@ -140,7 +153,7 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{
$name->setLabel("Name") $name->setLabel("Name")
->setValue(isset($setting[$prefix.'_name'])?$setting[$prefix.'_name']:"") ->setValue(isset($setting[$prefix.'_name'])?$setting[$prefix.'_name']:"")
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
if($disable_all){ if ($disable_all) {
$name->setAttrib("disabled", "disabled"); $name->setAttrib("disabled", "disabled");
} }
$this->addElement($name); $this->addElement($name);
@ -149,7 +162,7 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{
$description->setLabel("Description") $description->setLabel("Description")
->setValue(isset($setting[$prefix.'_description'])?$setting[$prefix.'_description']:"") ->setValue(isset($setting[$prefix.'_description'])?$setting[$prefix.'_description']:"")
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
if($disable_all){ if ($disable_all) {
$description->setAttrib("disabled", "disabled"); $description->setAttrib("disabled", "disabled");
} }
$this->addElement($description); $this->addElement($description);
@ -160,7 +173,7 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{
->setValidators(array( ->setValidators(array(
array('regex', false, array('/^[^ &<>]+$/', 'messages' => 'Invalid character entered')))) array('regex', false, array('/^[^ &<>]+$/', 'messages' => 'Invalid character entered'))))
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
if($disable_all){ if ($disable_all) {
$mount->setAttrib("disabled", "disabled"); $mount->setAttrib("disabled", "disabled");
} }
$mount->setAttrib('alt', 'regular_text'); $mount->setAttrib('alt', 'regular_text');
@ -172,7 +185,7 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{
->setValidators(array( ->setValidators(array(
array('regex', false, array('/^[^ &<>]+$/', 'messages' => 'Invalid character entered')))) array('regex', false, array('/^[^ &<>]+$/', 'messages' => 'Invalid character entered'))))
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
if($disable_all){ if ($disable_all) {
$user->setAttrib("disabled", "disabled"); $user->setAttrib("disabled", "disabled");
} }
$user->setAttrib('alt', 'regular_text'); $user->setAttrib('alt', 'regular_text');
@ -185,28 +198,30 @@ class Application_Form_StreamSettingSubForm extends Zend_Form_SubForm{
)); ));
} }
public function isValid ($data){ public function isValid ($data)
{
$f_data = $data['s'.$this->prefix."_data"]; $f_data = $data['s'.$this->prefix."_data"];
$isValid = parent::isValid($f_data); $isValid = parent::isValid($f_data);
if($f_data['enable'] == 1){ if ($f_data['enable'] == 1) {
if($f_data['host'] == ''){ if ($f_data['host'] == '') {
$element = $this->getElement("host"); $element = $this->getElement("host");
$element->addError("Server cannot be empty."); $element->addError("Server cannot be empty.");
$isValid = false; $isValid = false;
} }
if($f_data['port'] == ''){ if ($f_data['port'] == '') {
$element = $this->getElement("port"); $element = $this->getElement("port");
$element->addError("Port cannot be empty."); $element->addError("Port cannot be empty.");
$isValid = false; $isValid = false;
} }
if($f_data['output'] == 'icecast'){ if ($f_data['output'] == 'icecast') {
if($f_data['mount'] == ''){ if ($f_data['mount'] == '') {
$element = $this->getElement("mount"); $element = $this->getElement("mount");
$element->addError("Mount cannot be empty with Icecast server."); $element->addError("Mount cannot be empty with Icecast server.");
$isValid = false; $isValid = false;
} }
} }
} }
return $isValid; return $isValid;
} }
} }

View file

@ -24,7 +24,7 @@ class Application_Form_SupportSettings extends Zend_Form
'required' => true, 'required' => true,
'filters' => array('StringTrim'), 'filters' => array('StringTrim'),
'validator' => array('NotEmpty'), 'validator' => array('NotEmpty'),
'value' => Application_Model_Preference::GetValue("station_name"), 'value' => Application_Model_Preference::GetStationName(),
'decorators' => array( 'decorators' => array(
'ViewHelper' 'ViewHelper'
) )
@ -109,7 +109,7 @@ class Application_Form_SupportSettings extends Zend_Form
$upload->setAttrib('accept', 'image/*'); $upload->setAttrib('accept', 'image/*');
$this->addElement($upload); $this->addElement($upload);
if(!$isSass){ if (!$isSass) {
//enable support feedback //enable support feedback
$this->addElement('checkbox', 'SupportFeedback', array( $this->addElement('checkbox', 'SupportFeedback', array(
'label' => 'Send support feedback', 'label' => 'Send support feedback',
@ -126,7 +126,7 @@ class Application_Form_SupportSettings extends Zend_Form
->setRequired(false) ->setRequired(false)
->setDecorators(array('ViewHelper')) ->setDecorators(array('ViewHelper'))
->setValue(Application_Model_Preference::GetPublicise()); ->setValue(Application_Model_Preference::GetPublicise());
if(Application_Model_Preference::GetSupportFeedback() == '0'){ if (Application_Model_Preference::GetSupportFeedback() == '0') {
$checkboxPublicise->setAttrib("disabled", "disabled"); $checkboxPublicise->setAttrib("disabled", "disabled");
} }
$this->addElement($checkboxPublicise); $this->addElement($checkboxPublicise);
@ -165,19 +165,19 @@ class Application_Form_SupportSettings extends Zend_Form
public function isValid ($data) public function isValid ($data)
{ {
$isValid = parent::isValid($data); $isValid = parent::isValid($data);
if(!$this->isSass){ if (!$this->isSass) {
if($data['Publicise'] != 1){ if ($data['Publicise'] != 1) {
$isValid = true; $isValid = true;
} }
if(isset($data["Privacy"])){ if (isset($data["Privacy"])) {
$checkPrivacy = $this->getElement('Privacy'); $checkPrivacy = $this->getElement('Privacy');
if($data["SupportFeedback"] == "1" && $data["Privacy"] != "1"){ if ($data["SupportFeedback"] == "1" && $data["Privacy"] != "1") {
$checkPrivacy->addError("You have to agree to privacy policy."); $checkPrivacy->addError("You have to agree to privacy policy.");
$isValid = false; $isValid = false;
} }
} }
} }
return $isValid; return $isValid;
} }
} }

View file

@ -32,20 +32,20 @@ class Application_Form_WatchedDirPreferences extends Zend_Form_SubForm
)); ));
} }
public function verifyChosenFolder($p_form_element_id) { public function verifyChosenFolder($p_form_element_id)
{
$element = $this->getElement($p_form_element_id); $element = $this->getElement($p_form_element_id);
if (!is_dir($element->getValue())) { if (!is_dir($element->getValue())) {
$element->setErrors(array('Not a valid Directory')); $element->setErrors(array('Not a valid Directory'));
return false; return false;
} } else {
else {
$element->setValue(""); $element->setValue("");
return true; return true;
} }
} }
} }

View file

@ -1,7 +1,9 @@
<?php <?php
class Zend_Filter_ImageSize implements Zend_Filter_Interface { class Zend_Filter_ImageSize implements Zend_Filter_Interface
public function filter($value) { {
public function filter($value)
{
if (!file_exists($value)) { if (!file_exists($value)) {
throw new Zend_Filter_Exception('Image does not exist: ' . $value); throw new Zend_Filter_Exception('Image does not exist: ' . $value);
} }
@ -38,5 +40,3 @@ class Zend_Filter_ImageSize implements Zend_Filter_Interface {
return $value; return $value;
} }
} }
?>

View file

@ -3,8 +3,8 @@
/** /**
* Check if a field is empty but only when specific fields have specific values * Check if a field is empty but only when specific fields have specific values
*/ */
class ConditionalNotEmpty extends Zend_Validate_Abstract { class ConditionalNotEmpty extends Zend_Validate_Abstract
{
const KEY_IS_EMPTY = 'keyIsEmpty'; const KEY_IS_EMPTY = 'keyIsEmpty';
protected $_messageTemplates = array( protected $_messageTemplates = array(
@ -43,7 +43,7 @@ class ConditionalNotEmpty extends Zend_Validate_Abstract {
} }
if (is_array($context)) { if (is_array($context)) {
foreach($this->_fieldValues as $fieldName=>$fieldValue) { foreach ($this->_fieldValues as $fieldName=>$fieldValue) {
if (!isset($context[$fieldName]) || $context[$fieldName] != $fieldValue) { if (!isset($context[$fieldName]) || $context[$fieldName] != $fieldValue) {
return true; return true;
} }
@ -55,8 +55,7 @@ class ConditionalNotEmpty extends Zend_Validate_Abstract {
} }
$this->_error(self::KEY_IS_EMPTY); $this->_error(self::KEY_IS_EMPTY);
return false; return false;
} }
} }
?>

View file

@ -1,6 +1,7 @@
<?php <?php
class PasswordNotEmpty extends ConditionalNotEmpty { class PasswordNotEmpty extends ConditionalNotEmpty
{
public function isValid($value, $context = null) public function isValid($value, $context = null)
{ {
$result = parent::isValid($value, $context); $result = parent::isValid($value, $context);
@ -11,8 +12,7 @@ class PasswordNotEmpty extends ConditionalNotEmpty {
return true; return true;
} }
} }
return $result; return $result;
} }
} }
?>

View file

@ -5,11 +5,12 @@ class Logging {
private static $_logger; private static $_logger;
private static $_path; private static $_path;
public static function getLogger(){ public static function getLogger()
{
if (!isset(self::$_logger)) { if (!isset(self::$_logger)) {
$writer = new Zend_Log_Writer_Stream(self::$_path); $writer = new Zend_Log_Writer_Stream(self::$_path);
if (Zend_Version::compareVersion("1.11") > 0){ if (Zend_Version::compareVersion("1.11") > 0) {
//Running Zend version 1.10 or lower. Need to instantiate our //Running Zend version 1.10 or lower. Need to instantiate our
//own Zend Log class with backported code from 1.11. //own Zend Log class with backported code from 1.11.
require_once __DIR__."/AirtimeLog.php"; require_once __DIR__."/AirtimeLog.php";
@ -22,33 +23,97 @@ class Logging {
return self::$_logger; return self::$_logger;
} }
public static function setLogPath($path){ public static function setLogPath($path)
{
self::$_path = $path; self::$_path = $path;
} }
public static function toString($p_msg){ public static function toString($p_msg)
if (is_array($p_msg) || is_object($p_msg)){ {
if (is_array($p_msg) || is_object($p_msg)) {
return print_r($p_msg, true); return print_r($p_msg, true);
} else { } else {
return $p_msg; return $p_msg;
} }
} }
public static function log($p_msg){ public static function info($p_msg)
{
$bt = debug_backtrace(); $bt = debug_backtrace();
$caller = array_shift($bt); $caller = array_shift($bt);
$file = basename($caller['file']);
$line = $caller['line'];
$caller = array_shift($bt);
$function = $caller['function'];
$logger = self::getLogger(); $logger = self::getLogger();
$logger->info(self::toString($p_msg)." - file:".$caller['file'].":".$caller['line']); $logger->info("[$file : $function() : line $line] - ".self::toString($p_msg));
} }
public static function debug($p_msg){ public static function warn($p_msg)
{
$bt = debug_backtrace(); $bt = debug_backtrace();
$caller = array_shift($bt);
if (defined('APPLICATION_ENV') && APPLICATION_ENV == "development"){ $caller = array_shift($bt);
$file = basename($caller['file']);
$line = $caller['line'];
$caller = array_shift($bt);
$function = $caller['function'];
$logger = self::getLogger(); $logger = self::getLogger();
$logger->debug(self::toString($p_msg)." - file:".$caller['file'].":".$caller['line']); $logger->warn("[$file : $function() : line $line] - "
. self::toString($p_msg));
} }
public static function debug($p_msg)
{
if (!(defined('APPLICATION_ENV') && APPLICATION_ENV == "development")) {
return;
} }
$bt = debug_backtrace();
$caller = array_shift($bt);
$file = basename($caller['file']);
$line = $caller['line'];
$caller = array_shift($bt);
$function = $caller['function'];
$logger = self::getLogger();
$logger->debug("[$file : $function() : line $line] - ".self::toString($p_msg));
}
// kind of like debug but for printing arrays more compactly (skipping
// empty elements
public static function debug_sparse(array $p_msg)
{
Logging::debug("Sparse output:");
Logging::debug( array_filter($p_msg) );
}
public static function enablePropelLogging()
{
$logger = Logging::getLogger();
Propel::setLogger($logger);
$con = Propel::getConnection();
$con->useDebug(true);
$config = Propel::getConfiguration(PropelConfiguration::TYPE_OBJECT);
$config->setParameter('debugpdo.logging.details.method.enabled', true);
$config->setParameter('debugpdo.logging.details.time.enabled', true);
$config->setParameter('debugpdo.logging.details.mem.enabled', true);
}
public static function disablePropelLogging()
{
$con = Propel::getConnection();
$con->useDebug(false);
Propel::setLogger(null);
}
} }

View file

@ -1,7 +1,7 @@
<?php <?php
class Application_Model_Auth { class Application_Model_Auth
{
const TOKEN_LIFETIME = 'P2D'; // DateInterval syntax const TOKEN_LIFETIME = 'P2D'; // DateInterval syntax
private function generateToken($action, $user_id) private function generateToken($action, $user_id)
@ -27,9 +27,11 @@ class Application_Model_Auth {
$e_link_protocol = empty($_SERVER['HTTPS']) ? "http" : "https"; $e_link_protocol = empty($_SERVER['HTTPS']) ? "http" : "https";
$e_link_base = $_SERVER['SERVER_NAME']; $e_link_base = $_SERVER['SERVER_NAME'];
$e_link_port = $_SERVER['SERVER_PORT'];
$e_link_path = $view->url(array('user_id' => $user->getDbId(), 'token' => $token), 'password-change'); $e_link_path = $view->url(array('user_id' => $user->getDbId(), 'token' => $token), 'password-change');
$message = "Click this link: {$e_link_protocol}://{$e_link_base}{$e_link_path}"; $message = "Hi {$user->getDbLogin()}, \n\nClick this link to reset your password: ";
$message .= "{$e_link_protocol}://{$e_link_base}:{$e_link_port}{$e_link_path}";
$success = Application_Model_Email::send('Airtime Password Reset', $message, $user->getDbEmail()); $success = Application_Model_Email::send('Airtime Password Reset', $message, $user->getDbEmail());

File diff suppressed because it is too large Load diff

View file

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

View file

@ -1,13 +1,112 @@
<?php <?php
class Application_Model_Datatables { class Application_Model_Datatables
{
private static function buildWhereClauseForAdvancedSearch($dbname2searchTerm)
{
$where['clause'] = array();
$where['params'] = array();
foreach ($dbname2searchTerm as $dbname=>$term) {
$isRange = false;
if (strstr($term, '~')) {
$info = explode('~', $term);
if ($dbname == 'utime' || $dbname == 'mtime') {
$input1 = isset($info[0])?Application_Common_DateHelper::ConvertToUtcDateTimeString($info[0]):null;
$input2 = isset($info[1])?Application_Common_DateHelper::ConvertToUtcDateTimeString($info[1]):null;
} else if($dbname == 'bit_rate') {
$input1 = isset($info[0])?intval($info[0]) * 1000:null;
$input2 = isset($info[1])?intval($info[1]) * 1000:null;
} else {
$input1 = isset($info[0])?$info[0]:null;
$input2 = isset($info[1])?$info[1]:null;
}
$isRange = true;
} else {
$input1 = $term;
}
if ($isRange) {
$sub = array();
if ($input1 != null) {
$sub[] = $dbname." >= :" . $dbname . "1";
}
if ($input2 != null) {
$sub[] = $dbname." <= :" . $dbname . "2";
}
if (!empty($sub)) {
$where['clause'][$dbname] = "(".implode(' AND ', $sub).")";
if ($input1 != null) {
$where['params'][$dbname."1"] = $input1;
}
if ($input2 != null) {
$where['params'][$dbname."2"] = $input2;
}
}
} else {
if (trim($input1) !== "") {
$where['clause'][$dbname] = $dbname." ILIKE :" . $dbname."1";
$where['params'][$dbname."1"] = "%".$input1."%";
}
}
}
return $where;
}
/* /*
* query used to return data for a paginated/searchable datatable. * query used to return data for a paginated/searchable datatable.
*/ */
public static function findEntries($con, $displayColumns, $fromTable, $data, $dataProp = "aaData") public static function findEntries($con, $displayColumns, $fromTable,
$data, $dataProp = "aaData")
{ {
$librarySetting =
Application_Model_Preference::getCurrentLibraryTableColumnMap();
//$displayColumns[] = 'owner';
// map that maps original column position to db name
$current2dbname = array();
// array of search terms
$orig2searchTerm = array();
foreach ($data as $key => $d) {
if (strstr($key, "mDataProp_")) {
list($dump, $index) = explode("_", $key);
$current2dbname[$index] = $d;
} elseif (strstr($key, "sSearch_")) {
list($dump, $index) = explode("_", $key);
$orig2searchTerm[$index] = $d;
}
}
// map that maps dbname to searchTerm
$dbname2searchTerm = array();
foreach ($current2dbname as $currentPos => $dbname) {
$new_index = $librarySetting($currentPos);
// TODO : Fix this retarded hack later. Just a band aid for
// now at least we print some warnings so that we don't
// forget about this -- cc-4462
if ( array_key_exists($new_index, $orig2searchTerm) ) {
$dbname2searchTerm[$dbname] = $orig2searchTerm[$new_index];
} else {
Logging::warn("Trying to reorder to unknown index
printing as much debugging as possible...");
$debug = array(
'$new_index' => $new_index,
'$currentPos' => $currentPos,
'$orig2searchTerm' => $orig2searchTerm);
Logging::warn($debug);
}
}
$where = array(); $where = array();
/* Holds the parameters for binding after the statement has been
prepared */
$params = array();
if (isset($data['advSearch']) && $data['advSearch'] === 'true') {
$advancedWhere = self::buildWhereClauseForAdvancedSearch($dbname2searchTerm);
if (!empty($advancedWhere['clause'])) {
$where[] = join(" AND ", $advancedWhere['clause']);
$params = $advancedWhere['params'];
}
}
if ($data["sSearch"] !== "") { if ($data["sSearch"] !== "") {
$searchTerms = explode(" ", $data["sSearch"]); $searchTerms = explode(" ", $data["sSearch"]);
@ -19,6 +118,7 @@ class Application_Model_Datatables {
$sql = $selectorCount." FROM ".$fromTable; $sql = $selectorCount." FROM ".$fromTable;
$sqlTotalRows = $sql; $sqlTotalRows = $sql;
if (isset($searchTerms)) { if (isset($searchTerms)) {
$searchCols = array(); $searchCols = array();
for ($i = 0; $i < $data["iColumns"]; $i++) { for ($i = 0; $i < $data["iColumns"]; $i++) {
@ -28,23 +128,24 @@ class Application_Model_Datatables {
} }
$outerCond = array(); $outerCond = array();
$simpleWhere = array();
foreach ($searchTerms as $term) { foreach ($searchTerms as $term) {
$innerCond = array();
foreach ($searchCols as $col) { foreach ($searchCols as $col) {
$escapedTerm = pg_escape_string($term); $simpleWhere['clause']["simple_".$col] = "{$col}::text ILIKE :simple_".$col;
$innerCond[] = "{$col}::text ILIKE '%{$escapedTerm}%'"; $simpleWhere['params']["simple_".$col] = "%".$term."%";
} }
$outerCond[] = "(".join(" OR ", $innerCond).")"; $outerCond[] = "(".implode(" OR ", $simpleWhere['clause']).")";
} }
$where[] = "(".join(" AND ", $outerCond).")"; $where[] = "(" .implode(" AND ", $outerCond). ")";
$params = array_merge($params, $simpleWhere['params']);
} }
// End Where clause // End Where clause
// Order By clause // Order By clause
$orderby = array(); $orderby = array();
for ($i = 0; $i < $data["iSortingCols"]; $i++){ for ($i = 0; $i < $data["iSortingCols"]; $i++) {
$num = $data["iSortCol_".$i]; $num = $data["iSortCol_".$i];
$orderby[] = $data["mDataProp_{$num}"]." ".$data["sSortDir_".$i]; $orderby[] = $data["mDataProp_{$num}"]." ".$data["sSortDir_".$i];
} }
@ -53,8 +154,10 @@ class Application_Model_Datatables {
// End Order By clause // End Order By clause
$displayLength = intval($data["iDisplayLength"]); $displayLength = intval($data["iDisplayLength"]);
$needToBind = false;
if (count($where) > 0) { if (count($where) > 0) {
$where = join(" AND ", $where); $needToBind = true;
$where = join(" OR ", $where);
$sql = $selectorCount." FROM ".$fromTable." WHERE ".$where; $sql = $selectorCount." FROM ".$fromTable." WHERE ".$where;
$sqlTotalDisplayRows = $sql; $sqlTotalDisplayRows = $sql;
@ -64,8 +167,7 @@ class Application_Model_Datatables {
if ($displayLength !== -1) { if ($displayLength !== -1) {
$sql .= " OFFSET ".$data["iDisplayStart"]." LIMIT ".$displayLength; $sql .= " OFFSET ".$data["iDisplayStart"]." LIMIT ".$displayLength;
} }
} } else {
else {
$sql = $selectorRows." FROM ".$fromTable." ORDER BY ".$orderby; $sql = $selectorRows." FROM ".$fromTable." ORDER BY ".$orderby;
//limit the results returned. //limit the results returned.
@ -73,27 +175,45 @@ class Application_Model_Datatables {
$sql .= " OFFSET ".$data["iDisplayStart"]." LIMIT ".$displayLength; $sql .= " OFFSET ".$data["iDisplayStart"]." LIMIT ".$displayLength;
} }
} }
try { try {
$r = $con->query($sqlTotalRows); $r = $con->query($sqlTotalRows);
$totalRows = $r->fetchColumn(0); $totalRows = $r->fetchColumn(0);
if (isset($sqlTotalDisplayRows)) { if (isset($sqlTotalDisplayRows)) {
$r = $con->query($sqlTotalDisplayRows); $totalDisplayRows = Application_Common_Database::prepareAndExecute($sqlTotalDisplayRows, $params, 'column');
$totalDisplayRows = $r->fetchColumn(0); } else {
}
else {
$totalDisplayRows = $totalRows; $totalDisplayRows = $totalRows;
} }
$r = $con->query($sql); //TODO
$r->setFetchMode(PDO::FETCH_ASSOC); if ($needToBind) {
$results = $r->fetchAll(); $results = Application_Common_Database::prepareAndExecute($sql, $params);
} } else {
catch (Exception $e) { $stmt = $con->query($sql);
Logging::debug($e->getMessage()); $stmt->setFetchMode(PDO::FETCH_ASSOC);
$results = $stmt->fetchAll();
} }
// we need to go over all items and fix length for playlist
// in case the playlist contains dynamic block
foreach ($results as &$r) {
//this function is also called for Manage Users so in
//this case there will be no 'ftype'
if (isset($r['ftype'])) {
if ($r['ftype'] == 'playlist') {
$pl = new Application_Model_Playlist($r['id']);
$r['length'] = $pl->getLength();
} elseif ($r['ftype'] == "block") {
$bl = new Application_Model_Block($r['id']);
$r['bl_type'] = $bl->isStatic() ? 'static' : 'dynamic';
$r['length'] = $bl->getLength();
}
}
}
} catch (Exception $e) {
Logging::debug($e->getMessage());
}
return array( return array(
"sEcho" => intval($data["sEcho"]), "sEcho" => intval($data["sEcho"]),
"iTotalDisplayRecords" => intval($totalDisplayRows), "iTotalDisplayRecords" => intval($totalDisplayRows),

View file

@ -1,7 +1,7 @@
<?php <?php
class Application_Model_Email { class Application_Model_Email
{
/** /**
* Send email * Send email
* *
@ -13,23 +13,31 @@ class Application_Model_Email {
public static function send($subject, $message, $tos, $from = null) public static function send($subject, $message, $tos, $from = null)
{ {
$mailServerConfigured = Application_Model_Preference::GetMailServerConfigured() == true ? true : false; $mailServerConfigured = Application_Model_Preference::GetMailServerConfigured() == true ? true : false;
$mailServerRequiresAuth = Application_Model_Preference::GetMailServerRequiresAuth() == true ? true : false;
$success = true; $success = true;
if ($mailServerConfigured) { if ($mailServerConfigured) {
$username = Application_Model_Preference::GetMailServerEmailAddress();
$password = Application_Model_Preference::GetMailServerPassword();
$mailServer = Application_Model_Preference::GetMailServer(); $mailServer = Application_Model_Preference::GetMailServer();
$mailServerPort = Application_Model_Preference::GetMailServerPort(); $mailServerPort = Application_Model_Preference::GetMailServerPort();
if (!empty($mailServerPort)) { if (!empty($mailServerPort)) {
$port = Application_Model_Preference::GetMailServerPort(); $port = $mailServerPort;
} }
if ($mailServerRequiresAuth) {
$username = Application_Model_Preference::GetMailServerEmailAddress();
$password = Application_Model_Preference::GetMailServerPassword();
$config = array( $config = array(
'auth' => 'login', 'auth' => 'login',
'ssl' => 'ssl', 'ssl' => 'ssl',
'username' => $username, 'username' => $username,
'password' => $password 'password' => $password
); );
} else {
$config = array(
'ssl' => 'tls'
);
}
if (isset($port)) { if (isset($port)) {
$config['port'] = $port; $config['port'] = $port;

View file

@ -0,0 +1,36 @@
<?php
class Application_Model_Library
{
public static function getObjInfo($p_type)
{
$info = array();
if (strcmp($p_type, 'playlist')==0) {
$info['className'] = 'Application_Model_Playlist';
} elseif (strcmp($p_type, 'block')==0) {
$info['className'] = 'Application_Model_Block';
} elseif (strcmp($p_type, 'stream')==0) {
$info['className'] = 'Application_Model_Webstream';
} else {
throw new Exception("Unknown object type: '$p_type'");
}
return $info;
}
public static function changePlaylist($p_id, $p_type)
{
$obj_sess = new Zend_Session_Namespace(UI_PLAYLISTCONTROLLER_OBJ_SESSNAME);
if (is_null($p_id) || is_null($p_type)) {
unset($obj_sess->id);
unset($obj_sess->type);
} else {
$obj_sess->id = intval($p_id);
$obj_sess->type = $p_type;
}
}
}

View file

@ -0,0 +1,10 @@
<?php
interface Application_Model_LibraryEditable
{
public function setMetadata($key, $val);
public function setName($name);
public function getLength();
public function getId();
}

View file

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

View file

@ -1,10 +1,12 @@
<?php <?php
class Application_Model_LoginAttempts { class Application_Model_LoginAttempts
public function __construct(){ {
public function __construct()
{
} }
public static function increaseAttempts($ip){ public static function increaseAttempts($ip)
{
$con = Propel::getConnection(); $con = Propel::getConnection();
$sql = "select count(*) from cc_login_attempts WHERE ip='$ip'"; $sql = "select count(*) from cc_login_attempts WHERE ip='$ip'";
$res = $con->query($sql)->fetchColumn(0); $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(); $con = Propel::getConnection();
$sql = "select attempts from cc_login_attempts WHERE ip='$ip'"; $sql = "select attempts from cc_login_attempts WHERE ip='$ip'";
$res = $con->query($sql)->fetchColumn(0); $res = $con->query($sql)->fetchColumn(0);
return $res ? $res : 0; return $res ? $res : 0;
} }
public static function resetAttempts($ip){ public static function resetAttempts($ip)
{
$con = Propel::getConnection(); $con = Propel::getConnection();
$sql = "select count(*) from cc_login_attempts WHERE ip='$ip'"; $sql = "select count(*) from cc_login_attempts WHERE ip='$ip'";
$res = $con->query($sql)->fetchColumn(0); $res = $con->query($sql)->fetchColumn(0);

View file

@ -2,8 +2,8 @@
class NestedDirectoryException extends Exception { } class NestedDirectoryException extends Exception { }
class Application_Model_MusicDir { class Application_Model_MusicDir
{
/** /**
* @holds propel database object * @holds propel database object
*/ */
@ -40,21 +40,25 @@ class Application_Model_MusicDir {
$this->_dir->save(); $this->_dir->save();
} }
public function setExistsFlag($flag){ public function setExistsFlag($flag)
{
$this->_dir->setExists($flag); $this->_dir->setExists($flag);
$this->_dir->save(); $this->_dir->save();
} }
public function setWatchedFlag($flag){ public function setWatchedFlag($flag)
{
$this->_dir->setWatched($flag); $this->_dir->setWatched($flag);
$this->_dir->save(); $this->_dir->save();
} }
public function getWatchedFlag(){ public function getWatchedFlag()
{
return $this->_dir->getWatched(); return $this->_dir->getWatched();
} }
public function getExistsFlag(){ public function getExistsFlag()
{
return $this->_dir->getExists(); return $this->_dir->getExists();
} }
@ -71,20 +75,32 @@ class Application_Model_MusicDir {
*/ */
public function remove($userAddedWatchedDir=true) public function remove($userAddedWatchedDir=true)
{ {
$con = Propel::getConnection();
$music_dir_id = $this->getId(); $music_dir_id = $this->getId();
$sql = "SELECT DISTINCT s.instance_id from cc_music_dirs as md " $sql = <<<SQL
." LEFT JOIN cc_files as f on f.directory = md.id" SELECT DISTINCT s.instance_id
." RIGHT JOIN cc_schedule as s on s.file_id = f.id WHERE md.id = $music_dir_id"; FROM cc_music_dirs AS md
LEFT JOIN cc_files AS f ON f.directory = md.id
$show_instances = $con->query($sql)->fetchAll(); RIGHT JOIN cc_schedule AS s ON s.file_id = f.id
WHERE md.id = :musicDirId;
SQL;
$show_instances = Application_Common_Database::prepareAndExecute($sql,
array( ':musicDirId' => $music_dir_id ), 'all' );
// get all the files on this dir // get all the files on this dir
$sql = "UPDATE cc_files SET file_exists = 'f' WHERE id IN (SELECT f.id FROM cc_music_dirs as md " $sql = <<<SQL
." LEFT JOIN cc_files as f on f.directory = md.id WHERE md.id = $music_dir_id)"; UPDATE cc_files
$affected = $con->exec($sql); SET file_exists = 'f'
WHERE id IN
(SELECT f.id
FROM cc_music_dirs AS md
LEFT JOIN cc_files AS f ON f.directory = md.id
WHERE md.id = :musicDirId);
SQL;
$affected = Application_Common_Database::prepareAndExecute($sql,
array( ':musicDirId' => $music_dir_id ), 'all');
// set RemovedFlag to true // set RemovedFlag to true
if ($userAddedWatchedDir) { if ($userAddedWatchedDir) {
@ -113,8 +129,9 @@ class Application_Model_MusicDir {
* @return boolean * @return boolean
* Returns true if it is the ancestor, false otherwise. * Returns true if it is the ancestor, false otherwise.
*/ */
private static function isAncestorDir($p_dir1, $p_dir2){ private static function isAncestorDir($p_dir1, $p_dir2)
if (strlen($p_dir1) > strlen($p_dir2)){ {
if (strlen($p_dir1) > strlen($p_dir2)) {
return false; return false;
} }
@ -130,23 +147,24 @@ class Application_Model_MusicDir {
* The path we want to validate * The path we want to validate
* @return void * @return void
*/ */
public static function isPathValid($p_path){ public static function isPathValid($p_path)
{
$dirs = self::getWatchedDirs(); $dirs = self::getWatchedDirs();
$dirs[] = self::getStorDir(); $dirs[] = self::getStorDir();
foreach ($dirs as $dirObj){ foreach ($dirs as $dirObj) {
$dir = $dirObj->getDirectory(); $dir = $dirObj->getDirectory();
$diff = strlen($dir) - strlen($p_path); $diff = strlen($dir) - strlen($p_path);
if ($diff == 0){ if ($diff == 0) {
if ($dir == $p_path){ if ($dir == $p_path) {
throw new NestedDirectoryException("'$p_path' is already watched."); throw new NestedDirectoryException("'$p_path' is already watched.");
} }
} else if ($diff > 0){ } elseif ($diff > 0) {
if (self::isAncestorDir($p_path, $dir)){ if (self::isAncestorDir($p_path, $dir)) {
throw new NestedDirectoryException("'$p_path' contains nested watched directory: '$dir'"); throw new NestedDirectoryException("'$p_path' contains nested watched directory: '$dir'");
} }
} else { /* diff < 0*/ } 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'"); throw new NestedDirectoryException("'$p_path' is nested within existing watched directory: '$dir'");
} }
} }
@ -167,37 +185,36 @@ class Application_Model_MusicDir {
**/ **/
public static function addDir($p_path, $p_type, $userAddedWatchedDir=true, $nestedWatch=false) public static function addDir($p_path, $p_type, $userAddedWatchedDir=true, $nestedWatch=false)
{ {
if(!is_dir($p_path)){ if (!is_dir($p_path)) {
return array("code"=>2, "error"=>"'$p_path' is not a valid directory."); return array("code"=>2, "error"=>"'$p_path' is not a valid directory.");
} }
$real_path = Application_Common_OsPath::normpath($p_path)."/"; $real_path = Application_Common_OsPath::normpath($p_path)."/";
if($real_path != "/"){ if ($real_path != "/") {
$p_path = $real_path; $p_path = $real_path;
} }
$exist_dir = self::getDirByPath($p_path); $exist_dir = self::getDirByPath($p_path);
if( $exist_dir == NULL ){ if ($exist_dir == NULL) {
$temp_dir = new CcMusicDirs(); $temp_dir = new CcMusicDirs();
$dir = new Application_Model_MusicDir($temp_dir); $dir = new Application_Model_MusicDir($temp_dir);
}else{ } else {
$dir = $exist_dir; $dir = $exist_dir;
} }
$dir->setType($p_type); $dir->setType($p_type);
$p_path = Application_Common_OsPath::normpath($p_path)."/"; $p_path = Application_Common_OsPath::normpath($p_path)."/";
try { try {
/* isPathValid() checks if path is a substring or a superstring of an /* isPathValid() checks if path is a substring or a superstring of an
* existing dir and if not, throws NestedDirectoryException */ * existing dir and if not, throws NestedDirectoryException */
if(!$nestedWatch){ if (!$nestedWatch) {
self::isPathValid($p_path); self::isPathValid($p_path);
} }
if($userAddedWatchedDir){ if ($userAddedWatchedDir) {
$dir->setWatchedFlag(true); $dir->setWatchedFlag(true);
}else{ } else {
if($nestedWatch){ if ($nestedWatch) {
$dir->setWatchedFlag(false); $dir->setWatchedFlag(false);
} }
$dir->setExistsFlag(true); $dir->setExistsFlag(true);
@ -205,10 +222,11 @@ class Application_Model_MusicDir {
$dir->setDirectory($p_path); $dir->setDirectory($p_path);
return array("code"=>0); return array("code"=>0);
} catch (NestedDirectoryException $nde){ } catch (NestedDirectoryException $nde) {
$msg = $nde->getMessage(); $msg = $nde->getMessage();
return array("code"=>1, "error"=>"$msg"); 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"); return array("code"=>1, "error"=>"'$p_path' is already set as the current storage dir or in the watched folders list");
} }
@ -228,7 +246,7 @@ class Application_Model_MusicDir {
{ {
$res = self::addDir($p_path, "watched", $userAddedWatchedDir, $nestedWatch); $res = self::addDir($p_path, "watched", $userAddedWatchedDir, $nestedWatch);
if ($res['code'] == 0){ if ($res['code'] == 0) {
//convert "linked" files (Airtime <= 1.8.2) to watched files. //convert "linked" files (Airtime <= 1.8.2) to watched files.
$propel_link_dir = CcMusicDirsQuery::create() $propel_link_dir = CcMusicDirsQuery::create()
@ -271,6 +289,7 @@ class Application_Model_MusicDir {
$data["directory"] = $p_path; $data["directory"] = $p_path;
Application_Model_RabbitMq::SendMessageToMediaMonitor("new_watch", $data); Application_Model_RabbitMq::SendMessageToMediaMonitor("new_watch", $data);
} }
return $res; return $res;
} }
@ -288,11 +307,11 @@ class Application_Model_MusicDir {
$dir = CcMusicDirsQuery::create() $dir = CcMusicDirsQuery::create()
->filterByDirectory($p_path) ->filterByDirectory($p_path)
->findOne(); ->findOne();
if($dir == NULL){ if ($dir == NULL) {
return null; return null;
} } else {
else{
$mus_dir = new Application_Model_MusicDir($dir); $mus_dir = new Application_Model_MusicDir($dir);
return $mus_dir; return $mus_dir;
} }
} }
@ -309,15 +328,15 @@ class Application_Model_MusicDir {
$dirs = CcMusicDirsQuery::create() $dirs = CcMusicDirsQuery::create()
->filterByType("watched"); ->filterByType("watched");
if($exists !== null){ if ($exists !== null) {
$dirs = $dirs->filterByExists($exists); $dirs = $dirs->filterByExists($exists);
} }
if($watched !== null){ if ($watched !== null) {
$dirs = $dirs->filterByWatched($watched); $dirs = $dirs->filterByWatched($watched);
} }
$dirs = $dirs->find(); $dirs = $dirs->find();
foreach($dirs as $dir) { foreach ($dirs as $dir) {
$result[] = new Application_Model_MusicDir($dir); $result[] = new Application_Model_MusicDir($dir);
} }
@ -340,23 +359,24 @@ class Application_Model_MusicDir {
// we want to be consistent when storing dir path. // we want to be consistent when storing dir path.
// path should always ends with trailing '/' // path should always ends with trailing '/'
$p_dir = Application_Common_OsPath::normpath($p_dir)."/"; $p_dir = Application_Common_OsPath::normpath($p_dir)."/";
if(!is_dir($p_dir)){ if (!is_dir($p_dir)) {
return array("code"=>2, "error"=>"'$p_dir' is not a valid directory."); 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."); return array("code"=>3, "error"=>"Airtime is currently importing files. Please wait until this is complete before changing the storage directory.");
} }
$dir = self::getStorDir(); $dir = self::getStorDir();
// if $p_dir doesn't exist in DB // if $p_dir doesn't exist in DB
$exist = $dir->getDirByPath($p_dir); $exist = $dir->getDirByPath($p_dir);
if($exist == NULL){ if ($exist == NULL) {
$dir->setDirectory($p_dir); $dir->setDirectory($p_dir);
$dirId = $dir->getId(); $dirId = $dir->getId();
$data = array(); $data = array();
$data["directory"] = $p_dir; $data["directory"] = $p_dir;
$data["dir_id"] = $dirId; $data["dir_id"] = $dirId;
Application_Model_RabbitMq::SendMessageToMediaMonitor("change_stor", $data); Application_Model_RabbitMq::SendMessageToMediaMonitor("change_stor", $data);
return array("code"=>0); 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."); return array("code"=>1, "error"=>"'$p_dir' is already set as the current storage dir or in the watched folders list.");
} }
} }
@ -369,10 +389,11 @@ class Application_Model_MusicDir {
->filterByWatched(true) ->filterByWatched(true)
->find(); ->find();
foreach($dirs as $dir) { foreach ($dirs as $dir) {
$directory = $dir->getDirectory(); $directory = $dir->getDirectory();
if (substr($p_filepath, 0, strlen($directory)) === $directory) { if (substr($p_filepath, 0, strlen($directory)) === $directory) {
$mus_dir = new Application_Model_MusicDir($dir); $mus_dir = new Application_Model_MusicDir($dir);
return $mus_dir; return $mus_dir;
} }
} }
@ -390,11 +411,11 @@ class Application_Model_MusicDir {
* When $userAddedWatchedDir is true, it will set "Watched" flag to false * When $userAddedWatchedDir is true, it will set "Watched" flag to false
* otherwise, it will set "Exists" flag to true * otherwise, it will set "Exists" flag to true
**/ **/
public static function removeWatchedDir($p_dir, $userAddedWatchedDir=true){ public static function removeWatchedDir($p_dir, $userAddedWatchedDir=true)
{
//make sure that $p_dir has a trailing "/" //make sure that $p_dir has a trailing "/"
$real_path = Application_Common_OsPath::normpath($p_dir)."/"; $real_path = Application_Common_OsPath::normpath($p_dir)."/";
if($real_path != "/"){ if ($real_path != "/") {
$p_dir = $real_path; $p_dir = $real_path;
} }
$dir = Application_Model_MusicDir::getDirByPath($p_dir); $dir = Application_Model_MusicDir::getDirByPath($p_dir);
@ -405,6 +426,7 @@ class Application_Model_MusicDir {
$data = array(); $data = array();
$data["directory"] = $p_dir; $data["directory"] = $p_dir;
Application_Model_RabbitMq::SendMessageToMediaMonitor("remove_watch", $data); Application_Model_RabbitMq::SendMessageToMediaMonitor("remove_watch", $data);
return array("code"=>0); return array("code"=>0);
} }
} }
@ -413,7 +435,7 @@ class Application_Model_MusicDir {
{ {
$mus_dir = self::getWatchedDirFromFilepath($p_filepath); $mus_dir = self::getWatchedDirFromFilepath($p_filepath);
if(is_null($mus_dir)) { if (is_null($mus_dir)) {
return null; return null;
} }

View file

@ -8,8 +8,8 @@ require_once 'formatters/LengthFormatter.php';
* @copyright 2010 Sourcefabric O.P.S. * @copyright 2010 Sourcefabric O.P.S.
* @license http://www.gnu.org/licenses/gpl.txt * @license http://www.gnu.org/licenses/gpl.txt
*/ */
class Application_Model_Playlist { class Application_Model_Playlist implements Application_Model_LibraryEditable
{
/** /**
* propel connection object. * propel connection object.
*/ */
@ -46,7 +46,6 @@ class Application_Model_Playlist {
"dcterms:extent" => "Length" "dcterms:extent" => "Length"
); );
public function __construct($id=null, $con=null) public function __construct($id=null, $con=null)
{ {
if (isset($id)) { if (isset($id)) {
@ -55,10 +54,9 @@ class Application_Model_Playlist {
if (is_null($this->pl)) { if (is_null($this->pl)) {
throw new PlaylistNotFoundException(); throw new PlaylistNotFoundException();
} }
} } else {
else {
$this->pl = new CcPlaylist(); $this->pl = new CcPlaylist();
$this->pl->setDbUTime("now", new DateTimeZone("UTC")); $this->pl->setDbUTime(new DateTime("now", new DateTimeZone("UTC")));
$this->pl->save(); $this->pl->save();
} }
@ -79,7 +77,8 @@ class Application_Model_Playlist {
* *
* @return int * @return int
*/ */
public function getId() { public function getId()
{
return $this->id; return $this->id;
} }
@ -117,28 +116,32 @@ class Application_Model_Playlist {
return $this->pl->getDbDescription(); return $this->pl->getDbDescription();
} }
public function getCreator() { public function getCreator()
{
return $this->pl->getCcSubjs()->getDbLogin(); return $this->pl->getCcSubjs()->getDbLogin();
} }
public function getCreatorId() { public function getCreatorId()
{
return $this->pl->getCcSubjs()->getDbId(); return $this->pl->getCcSubjs()->getDbId();
} }
public function setCreator($p_id) { public function setCreator($p_id)
{
$this->pl->setDbCreatorId($p_id); $this->pl->setDbCreatorId($p_id);
$this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
$this->pl->save($this->con); $this->pl->save($this->con);
} }
public function getLastModified($format = null) { public function getLastModified($format = null)
{
//Logging::info($this->pl->getDbMtime($format));
//Logging::info($this->pl);
return $this->pl->getDbMtime($format); return $this->pl->getDbMtime($format);
} }
public function getSize() { public function getSize()
{
return $this->pl->countCcPlaylistcontentss(); return $this->pl->countCcPlaylistcontentss();
} }
@ -148,44 +151,113 @@ class Application_Model_Playlist {
* file_exists flag set to true * file_exists flag set to true
* @return array * @return array
*/ */
public function getContents($filterFiles=false) { public function getContents($filterFiles=false)
{
Logging::info("Getting contents for playlist {$this->id}");
Logging::log("Getting contents for playlist {$this->id}"); $sql = <<<SQL
SELECT *
FROM (
(SELECT pc.id AS id,
pc.type,
pc.position,
pc.cliplength AS LENGTH,
pc.cuein,
pc.cueout,
pc.fadein,
pc.fadeout,
f.id AS item_id,
f.track_title,
f.artist_name AS creator,
f.file_exists AS EXISTS,
f.filepath AS path,
f.length AS orig_length,
f.mime AS mime
FROM cc_playlistcontents AS pc
JOIN cc_files AS f ON pc.file_id=f.id
WHERE pc.playlist_id = :playlist_id1
AND TYPE = 0)
UNION ALL
(SELECT pc.id AS id,
pc.TYPE, pc.position,
pc.cliplength AS LENGTH,
pc.cuein,
pc.cueout,
pc.fadein,
pc.fadeout,
ws.id AS item_id,
(ws.name || ': ' || ws.url) AS title,
sub.login AS creator,
't'::boolean AS EXISTS,
ws.url AS path,
ws.length AS orig_length,
ws.mime as mime
FROM cc_playlistcontents AS pc
JOIN cc_webstream AS ws ON pc.stream_id=ws.id
LEFT JOIN cc_subjs AS sub ON sub.id = ws.creator_id
WHERE pc.playlist_id = :playlist_id2
AND pc.TYPE = 1)
UNION ALL
(SELECT pc.id AS id,
pc.TYPE, pc.position,
pc.cliplength AS LENGTH,
pc.cuein,
pc.cueout,
pc.fadein,
pc.fadeout,
bl.id AS item_id,
bl.name AS title,
sbj.login AS creator,
't'::boolean AS EXISTS,
NULL::text AS path,
bl.length AS orig_length,
NULL::text as mime
FROM cc_playlistcontents AS pc
JOIN cc_block AS bl ON pc.block_id=bl.id
JOIN cc_subjs AS sbj ON bl.creator_id=sbj.id
WHERE pc.playlist_id = :playlist_id3
AND pc.TYPE = 2)) AS temp
ORDER BY temp.position;
SQL;
$files = array(); $rows = Application_Common_Database::prepareAndExecute($sql, array(':playlist_id1'=>$this->id, ':playlist_id2'=>$this->id, ':playlist_id3'=>$this->id));
$query = CcPlaylistcontentsQuery::create()
->filterByDbPlaylistId($this->id);
if($filterFiles){
$query->useCcFilesQuery()
->filterByDbFileExists(true)
->endUse();
}
$query->orderByDbPosition()
->leftJoinWith('CcFiles');
$rows = $query->find($this->con);
$i = 0;
$offset = 0; $offset = 0;
foreach ($rows as $row) { foreach ($rows as &$row) {
$files[$i] = $row->toArray(BasePeer::TYPE_FIELDNAME, true, true); $clipSec = Application_Common_DateHelper::playlistTimeToSeconds($row['length']);
$clipSec = Application_Model_Playlist::playlistTimeToSeconds($files[$i]['cliplength']);
$offset += $clipSec; $offset += $clipSec;
$offset_cliplength = Application_Model_Playlist::secondsToPlaylistTime($offset); $offset_cliplength = Application_Common_DateHelper::secondsToPlaylistTime($offset);
//format the length for UI. //format the length for UI.
$formatter = new LengthFormatter($files[$i]['cliplength']); if ($row['type'] == 2) {
$files[$i]['cliplength'] = $formatter->format(); $bl = new Application_Model_Block($row['item_id']);
$formatter = new LengthFormatter($bl->getLength());
} else {
$formatter = new LengthFormatter($row['length']);
}
$row['length'] = $formatter->format();
$formatter = new LengthFormatter($offset_cliplength); $formatter = new LengthFormatter($offset_cliplength);
$files[$i]['offset'] = $formatter->format(); $row['offset'] = $formatter->format();
$i++; //format the fades in format 00(.000000)
$fades = $this->getFadeInfo($row['position']);
$row['fadein'] = $fades[0];
$row['fadeout'] = $fades[1];
// format the cues in format 00:00:00(.0)
// we need to add the '.0' for cues and not fades
// because propel takes care of this for us
// (we use propel to fetch the fades)
$row['cuein'] = str_pad(substr($row['cuein'], 0, 10), 10, '.0');
$row['cueout'] = str_pad(substr($row['cueout'], 0, 10), 10, '.0');
//format original length
$formatter = new LengthFormatter($row['orig_length']);
$row['orig_length'] = $formatter->format();
} }
return $files; return $rows;
} }
/** /**
@ -193,42 +265,94 @@ class Application_Model_Playlist {
* but this isn't practical since fades shouldn't be very long usuall 1 second or less. This function * 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. * 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 //First get rid of the first six characters 00:00: which will be added back later for db update
$fade = substr($fade, 6); $fade = substr($fade, 6);
//Second add .000000 if the fade does't have milliseconds format already //Second add .000000 if the fade does't have milliseconds format already
$dbFadeStrPos = strpos( $fade, '.' ); $dbFadeStrPos = strpos( $fade, '.' );
if ( $dbFadeStrPos === False ) if ($dbFadeStrPos === false) {
$fade .= '.000000'; $fade .= '.000000';
else } else {
while( strlen( $fade ) < 9 ) while (strlen($fade) < 9) {
$fade .= '0'; $fade .= '0';
}
}
//done, just need to set back the formated values //done, just need to set back the formated values
return $fade; return $fade;
} }
//aggregate column on playlistcontents cliplength column. // returns true/false and ids of dynamic blocks
public function getLength() { public function hasDynamicBlock()
{
return $this->pl->getDbLength(); $ids = $this->getIdsOfDynamicBlocks();
if (count($ids) > 0) {
return true;
} else {
return false;
}
} }
public function getIdsOfDynamicBlocks()
{
$sql = "SELECT bl.id FROM cc_playlistcontents as pc
JOIN cc_block as bl ON pc.type=2 AND pc.block_id=bl.id AND bl.type='dynamic'
WHERE playlist_id=:playlist_id AND pc.type=2";
$result = Application_Common_Database::prepareAndExecute($sql, array(':playlist_id'=>$this->id));
return $result;
}
//aggregate column on playlistcontents cliplength column.
public function getLength()
{
if ($this->hasDynamicBlock()) {
$ids = $this->getIdsOfDynamicBlocks();
$length = $this->pl->getDbLength();
foreach ($ids as $id) {
$bl = new Application_Model_Block($id['id']);
if ($bl->hasItemLimit()) {
return "N/A";
}
}
$formatter = new LengthFormatter($length);
return "~".$formatter->format();
} else {
return $this->pl->getDbLength();
}
}
private function insertPlaylistElement($info) private function insertPlaylistElement($info)
{ {
$row = new CcPlaylistcontents(); $row = new CcPlaylistcontents();
$row->setDbPlaylistId($this->id); $row->setDbPlaylistId($this->id);
$row->setDbFileId($info["id"]);
$row->setDbPosition($info["pos"]); $row->setDbPosition($info["pos"]);
$row->setDbCliplength($info["cliplength"]); $row->setDbCliplength($info["cliplength"]);
$row->setDbCuein($info["cuein"]); $row->setDbCuein($info["cuein"]);
$row->setDbCueout($info["cueout"]); $row->setDbCueout($info["cueout"]);
$row->setDbFadein($info["fadein"]); $row->setDbFadein($info["fadein"]);
$row->setDbFadeout($info["fadeout"]); $row->setDbFadeout($info["fadeout"]);
if ($info["ftype"] == "audioclip") {
$row->setDbFileId($info["id"]);
$type = 0;
} elseif ($info["ftype"] == "stream") {
$row->setDbStreamId($info["id"]);
$type = 1;
} elseif ($info["ftype"] == "block") {
$row->setDbBlockId($info["id"]);
$type = 2;
}
$row->setDbType($type);
$row->save($this->con); $row->save($this->con);
// above save result update on cc_playlist table on length column.
// but $this->pl doesn't get updated automatically
// so we need to manually grab it again from DB so it has updated values
// It is something to do FORMAT_ON_DEMAND( Lazy Loading )
$this->pl = CcPlaylistQuery::create()->findPK($this->id);
} }
/* /*
@ -236,19 +360,31 @@ class Application_Model_Playlist {
*/ */
private function buildEntry($p_item, $pos) private function buildEntry($p_item, $pos)
{ {
$file = CcFilesQuery::create()->findPK($p_item, $this->con); $objType = $p_item[1];
$objId = $p_item[0];
if ($objType == 'audioclip') {
$obj = CcFilesQuery::create()->findPK($objId, $this->con);
} elseif ($objType == "stream") {
$obj = CcWebstreamQuery::create()->findPK($objId, $this->con);
} elseif ($objType == "block") {
$obj = CcBlockQuery::create()->findPK($objId, $this->con);
} else {
throw new Exception("Unknown file type");
}
if (isset($file) && $file->getDbFileExists()) { if (isset($obj)) {
if (($obj instanceof CcFiles && $obj->getDbFileExists()) || $obj instanceof CcWebstream || $obj instanceof CcBlock) {
$entry = $this->plItem; $entry = $this->plItem;
$entry["id"] = $file->getDbId(); $entry["id"] = $obj->getDbId();
$entry["pos"] = $pos; $entry["pos"] = $pos;
$entry["cliplength"] = $file->getDbLength(); $entry["cliplength"] = $obj->getDbLength();
$entry["cueout"] = $file->getDbLength(); $entry["cueout"] = $obj->getDbLength();
$entry["ftype"] = $objType;
}
return $entry; return $entry;
} } else {
else { throw new Exception("trying to add a object that does not exist.");
throw new Exception("trying to add a file that does not exist.");
} }
} }
@ -260,7 +396,7 @@ class Application_Model_Playlist {
* @param string (before|after) $addAfter * @param string (before|after) $addAfter
* whether to add the clips before or after the selected item. * whether to add the clips before or after the selected item.
*/ */
public function addAudioClips($p_items, $p_afterItem=NULL, $addType = 'after') public function addAudioClips($p_items, $p_afterItem=null, $addType = 'after')
{ {
$this->con->beginTransaction(); $this->con->beginTransaction();
$contentsToUpdate = array(); $contentsToUpdate = array();
@ -268,24 +404,20 @@ class Application_Model_Playlist {
try { try {
if (is_numeric($p_afterItem)) { if (is_numeric($p_afterItem)) {
Logging::log("Finding playlist content item {$p_afterItem}"); Logging::info("Finding playlist content item {$p_afterItem}");
$afterItem = CcPlaylistcontentsQuery::create()->findPK($p_afterItem); $afterItem = CcPlaylistcontentsQuery::create()->findPK($p_afterItem);
$index = $afterItem->getDbPosition(); $index = $afterItem->getDbPosition();
Logging::log("index is {$index}"); Logging::info("index is {$index}");
$pos = ($addType == 'after') ? $index + 1 : $index; $pos = ($addType == 'after') ? $index + 1 : $index;
$contentsToUpdate = CcPlaylistcontentsQuery::create() $contentsToUpdate = CcPlaylistcontentsQuery::create()
->filterByDbPlaylistId($this->id) ->filterByDbPlaylistId($this->id)
->filterByDbPosition($pos, Criteria::GREATER_EQUAL) ->filterByDbPosition($pos, Criteria::GREATER_EQUAL)
->orderByDbPosition() ->orderByDbPosition()
->find($this->con); ->find($this->con);
Logging::log("Adding to playlist"); } else {
Logging::log("at position {$pos}");
}
else {
//add to the end of the playlist //add to the end of the playlist
if ($addType == 'after') { if ($addType == 'after') {
@ -307,15 +439,16 @@ class Application_Model_Playlist {
->orderByDbPosition() ->orderByDbPosition()
->find($this->con); ->find($this->con);
Logging::log("Adding to playlist");
Logging::log("at position {$pos}");
} }
foreach($p_items as $ac) { Logging::info("Adding to playlist");
Logging::log("Adding audio file {$ac}"); Logging::info("at position {$pos}");
foreach ($p_items as $ac) {
$res = $this->insertPlaylistElement($this->buildEntry($ac, $pos)); $res = $this->insertPlaylistElement($this->buildEntry($ac, $pos));
$pos = $pos + 1; $pos = $pos + 1;
Logging::info("Adding $ac[1] $ac[0]");
} }
//reset the positions of the remaining items. //reset the positions of the remaining items.
@ -329,8 +462,7 @@ class Application_Model_Playlist {
$this->pl->save($this->con); $this->pl->save($this->con);
$this->con->commit(); $this->con->commit();
} } catch (Exception $e) {
catch (Exception $e) {
$this->con->rollback(); $this->con->rollback();
throw $e; throw $e;
} }
@ -364,33 +496,32 @@ class Application_Model_Playlist {
$pos = 0; $pos = 0;
//moving items to beginning of the playlist. //moving items to beginning of the playlist.
if (is_null($p_afterItem)) { if (is_null($p_afterItem)) {
Logging::log("moving items to beginning of playlist"); Logging::info("moving items to beginning of playlist");
foreach ($contentsToMove as $item) { foreach ($contentsToMove as $item) {
Logging::log("item {$item->getDbId()} to pos {$pos}"); Logging::info("item {$item->getDbId()} to pos {$pos}");
$item->setDbPosition($pos); $item->setDbPosition($pos);
$item->save($this->con); $item->save($this->con);
$pos = $pos + 1; $pos = $pos + 1;
} }
foreach ($otherContent as $item) { foreach ($otherContent as $item) {
Logging::log("item {$item->getDbId()} to pos {$pos}"); Logging::info("item {$item->getDbId()} to pos {$pos}");
$item->setDbPosition($pos); $item->setDbPosition($pos);
$item->save($this->con); $item->save($this->con);
$pos = $pos + 1; $pos = $pos + 1;
} }
} } else {
else { Logging::info("moving items after {$p_afterItem}");
Logging::log("moving items after {$p_afterItem}");
foreach ($otherContent as $item) { foreach ($otherContent as $item) {
Logging::log("item {$item->getDbId()} to pos {$pos}"); Logging::info("item {$item->getDbId()} to pos {$pos}");
$item->setDbPosition($pos); $item->setDbPosition($pos);
$item->save($this->con); $item->save($this->con);
$pos = $pos + 1; $pos = $pos + 1;
if ($item->getDbId() == $p_afterItem) { if ($item->getDbId() == $p_afterItem) {
foreach ($contentsToMove as $move) { foreach ($contentsToMove as $move) {
Logging::log("item {$move->getDbId()} to pos {$pos}"); Logging::info("item {$move->getDbId()} to pos {$pos}");
$move->setDbPosition($pos); $move->setDbPosition($pos);
$move->save($this->con); $move->save($this->con);
$pos = $pos + 1; $pos = $pos + 1;
@ -400,13 +531,11 @@ class Application_Model_Playlist {
} }
$this->con->commit(); $this->con->commit();
} } catch (Exception $e) {
catch (Exception $e) {
$this->con->rollback(); $this->con->rollback();
throw $e; throw $e;
} }
$this->pl = CcPlaylistQuery::create()->findPK($this->id); $this->pl = CcPlaylistQuery::create()->findPK($this->id);
$this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
$this->pl->save($this->con); $this->pl->save($this->con);
@ -444,17 +573,15 @@ class Application_Model_Playlist {
$this->pl->save($this->con); $this->pl->save($this->con);
$this->con->commit(); $this->con->commit();
} } catch (Exception $e) {
catch (Exception $e) {
$this->con->rollback(); $this->con->rollback();
throw $e; throw $e;
} }
} }
public function getFadeInfo($pos)
public function getFadeInfo($pos) { {
Logging::info("Getting fade info for pos {$pos}");
Logging::log("Getting fade info for pos {$pos}");
$row = CcPlaylistcontentsQuery::create() $row = CcPlaylistcontentsQuery::create()
->joinWith(CcFilesPeer::OM_CLASS) ->joinWith(CcFilesPeer::OM_CLASS)
@ -462,9 +589,14 @@ class Application_Model_Playlist {
->filterByDbPosition($pos) ->filterByDbPosition($pos)
->findOne(); ->findOne();
#Propel returns values in form 00.000000 format which is for only seconds. if (!$row) {
$fadeIn = $row->getDbFadein(); return NULL;
$fadeOut = $row->getDbFadeout(); }
//Propel returns values in form 00.000000 format which is for only seconds.
//We only want to display 1 decimal
$fadeIn = substr($row->getDbFadein(), 0, 4);
$fadeOut = substr($row->getDbFadeout(), 0, 4);
return array($fadeIn, $fadeOut); return array($fadeIn, $fadeOut);
} }
@ -489,8 +621,6 @@ class Application_Model_Playlist {
$this->con->beginTransaction(); $this->con->beginTransaction();
$errArray= array();
try { try {
$row = CcPlaylistcontentsQuery::create()->findPK($id); $row = CcPlaylistcontentsQuery::create()->findPK($id);
@ -502,19 +632,17 @@ class Application_Model_Playlist {
if (!is_null($fadeIn)) { if (!is_null($fadeIn)) {
$sql = "SELECT INTERVAL '{$fadeIn}' > INTERVAL '{$clipLength}'"; $sql = "SELECT :fadein::INTERVAL > INTERVAL '{$clipLength}'";
$r = $this->con->query($sql); if (Application_Common_Database::prepareAndExecute($sql, array(':fadein'=>$fadeIn), 'column')) {
if ($r->fetchColumn(0)) {
//"Fade In can't be larger than overall playlength."; //"Fade In can't be larger than overall playlength.";
$fadeIn = $clipLength; $fadeIn = $clipLength;
} }
$row->setDbFadein($fadeIn); $row->setDbFadein($fadeIn);
} }
if (!is_null($fadeOut)){ if (!is_null($fadeOut)) {
$sql = "SELECT INTERVAL '{$fadeOut}' > INTERVAL '{$clipLength}'"; $sql = "SELECT :fadeout::INTERVAL > INTERVAL '{$clipLength}'";
$r = $this->con->query($sql); if (Application_Common_Database::prepareAndExecute($sql, array(':fadeout'=>$fadeOut), 'column')) {
if ($r->fetchColumn(0)) {
//Fade Out can't be larger than overall playlength."; //Fade Out can't be larger than overall playlength.";
$fadeOut = $clipLength; $fadeOut = $clipLength;
} }
@ -526,8 +654,7 @@ class Application_Model_Playlist {
$this->pl->save($this->con); $this->pl->save($this->con);
$this->con->commit(); $this->con->commit();
} } catch (Exception $e) {
catch (Exception $e) {
$this->con->rollback(); $this->con->rollback();
throw $e; throw $e;
} }
@ -535,10 +662,10 @@ class Application_Model_Playlist {
return array("fadeIn" => $fadeIn, "fadeOut" => $fadeOut); return array("fadeIn" => $fadeIn, "fadeOut" => $fadeOut);
} }
public function setPlaylistfades($fadein, $fadeout) { public function setfades($fadein, $fadeout)
{
if (isset($fadein)) { if (isset($fadein)) {
Logging::log("Setting playlist fade in {$fadein}"); Logging::info("Setting playlist fade in {$fadein}");
$row = CcPlaylistcontentsQuery::create() $row = CcPlaylistcontentsQuery::create()
->filterByDbPlaylistId($this->id) ->filterByDbPlaylistId($this->id)
->filterByDbPosition(0) ->filterByDbPosition(0)
@ -548,7 +675,7 @@ class Application_Model_Playlist {
} }
if (isset($fadeout)) { if (isset($fadeout)) {
Logging::log("Setting playlist fade out {$fadeout}"); Logging::info("Setting playlist fade out {$fadeout}");
$row = CcPlaylistcontentsQuery::create() $row = CcPlaylistcontentsQuery::create()
->filterByDbPlaylistId($this->id) ->filterByDbPlaylistId($this->id)
->filterByDbPosition($this->getSize()-1) ->filterByDbPosition($this->getSize()-1)
@ -578,6 +705,7 @@ class Application_Model_Playlist {
try { try {
if (is_null($cueIn) && is_null($cueOut)) { if (is_null($cueIn) && is_null($cueOut)) {
$errArray["error"] = "Cue in and cue out are null."; $errArray["error"] = "Cue in and cue out are null.";
return $errArray; return $errArray;
} }
@ -598,74 +726,69 @@ class Application_Model_Playlist {
$file = $row->getCcFiles($this->con); $file = $row->getCcFiles($this->con);
$origLength = $file->getDbLength(); $origLength = $file->getDbLength();
if (!is_null($cueIn) && !is_null($cueOut)){ if (!is_null($cueIn) && !is_null($cueOut)) {
if ($cueOut === ""){ if ($cueOut === "") {
$cueOut = $origLength; $cueOut = $origLength;
} }
$sql = "SELECT INTERVAL '{$cueIn}' > INTERVAL '{$cueOut}'"; $sql = "SELECT :cueIn::INTERVAL > :cueOut::INTERVAL";
$r = $this->con->query($sql); if (Application_Common_Database::prepareAndExecute($sql, array(':cueIn'=>$cueIn, ':cueOut'=>$cueOut), 'column')) {
if ($r->fetchColumn(0)) {
$errArray["error"] = "Can't set cue in to be larger than cue out."; $errArray["error"] = "Can't set cue in to be larger than cue out.";
return $errArray; return $errArray;
} }
$sql = "SELECT INTERVAL '{$cueOut}' > INTERVAL '{$origLength}'"; $sql = "SELECT :cueOut::INTERVAL > :origLength::INTERVAL";
$r = $this->con->query($sql); if (Application_Common_Database::prepareAndExecute($sql, array(':cueOut'=>$cueOut, ':origLength'=>$origLength), 'column')) {
if ($r->fetchColumn(0)){
$errArray["error"] = "Can't set cue out to be greater than file length."; $errArray["error"] = "Can't set cue out to be greater than file length.";
return $errArray; return $errArray;
} }
$sql = "SELECT INTERVAL '{$cueOut}' - INTERVAL '{$cueIn}'"; $sql = "SELECT :cueOut::INTERVAL - :cueIn::INTERVAL";
$r = $this->con->query($sql); $cliplength = Application_Common_Database::prepareAndExecute($sql, array(':cueOut'=>$cueOut, ':cueIn'=>$cueIn), 'column');
$cliplength = $r->fetchColumn(0);
$row->setDbCuein($cueIn); $row->setDbCuein($cueIn);
$row->setDbCueout($cueOut); $row->setDbCueout($cueOut);
$row->setDBCliplength($cliplength); $row->setDBCliplength($cliplength);
} } elseif (!is_null($cueIn)) {
else if (!is_null($cueIn)) {
$sql = "SELECT INTERVAL '{$cueIn}' > INTERVAL '{$oldCueOut}'"; $sql = "SELECT :cueIn::INTERVAL > :oldCueOut::INTERVAL";
$r = $this->con->query($sql); if (Application_Common_Database::prepareAndExecute($sql, array(':cueIn'=>$cueIn, ':oldCueOut'=>$oldCueOut), 'column')) {
if ($r->fetchColumn(0)) {
$errArray["error"] = "Can't set cue in to be larger than cue out."; $errArray["error"] = "Can't set cue in to be larger than cue out.";
return $errArray; return $errArray;
} }
$sql = "SELECT INTERVAL '{$oldCueOut}' - INTERVAL '{$cueIn}'"; $sql = "SELECT :oldCueOut::INTERVAL - :cueIn::INTERVAL";
$r = $this->con->query($sql); $cliplength = Application_Common_Database::prepareAndExecute($sql, array(':cueIn'=>$cueIn, ':oldCueOut'=>$oldCueOut), 'column');
$cliplength = $r->fetchColumn(0);
$row->setDbCuein($cueIn); $row->setDbCuein($cueIn);
$row->setDBCliplength($cliplength); $row->setDBCliplength($cliplength);
} } elseif (!is_null($cueOut)) {
else if (!is_null($cueOut)) {
if ($cueOut === ""){ if ($cueOut === "") {
$cueOut = $origLength; $cueOut = $origLength;
} }
$sql = "SELECT INTERVAL '{$cueOut}' < INTERVAL '{$oldCueIn}'"; $sql = "SELECT :cueOut::INTERVAL < :oldCueIn::INTERVAL";
$r = $this->con->query($sql); if (Application_Common_Database::prepareAndExecute($sql, array(':cueOut'=>$cueOut, ':oldCueIn'=>$oldCueIn), 'column')) {
if ($r->fetchColumn(0)) {
$errArray["error"] = "Can't set cue out to be smaller than cue in."; $errArray["error"] = "Can't set cue out to be smaller than cue in.";
return $errArray; return $errArray;
} }
$sql = "SELECT INTERVAL '{$cueOut}' > INTERVAL '{$origLength}'"; $sql = "SELECT :cueOut::INTERVAL > :origLength::INTERVAL";
$r = $this->con->query($sql); if (Application_Common_Database::prepareAndExecute($sql, array(':cueOut'=>$cueOut, ':origLength'=>$origLength), 'column')) {
if ($r->fetchColumn(0)){
$errArray["error"] = "Can't set cue out to be greater than file length."; $errArray["error"] = "Can't set cue out to be greater than file length.";
return $errArray; return $errArray;
} }
$sql = "SELECT INTERVAL '{$cueOut}' - INTERVAL '{$oldCueIn}'"; $sql = "SELECT :cueOut::INTERVAL - :oldCueIn::INTERVAL";
$r = $this->con->query($sql); $cliplength = Application_Common_Database::prepareAndExecute($sql, array(':cueOut'=>$cueOut, ':oldCueIn'=>$oldCueIn), 'column');
$cliplength = $r->fetchColumn(0);
$row->setDbCueout($cueOut); $row->setDbCueout($cueOut);
$row->setDBCliplength($cliplength); $row->setDBCliplength($cliplength);
@ -673,16 +796,14 @@ class Application_Model_Playlist {
$cliplength = $row->getDbCliplength(); $cliplength = $row->getDbCliplength();
$sql = "SELECT INTERVAL '{$fadeIn}' > INTERVAL '{$cliplength}'"; $sql = "SELECT :fadeIn::INTERVAL > :cliplength::INTERVAL";
$r = $this->con->query($sql); if (Application_Common_Database::prepareAndExecute($sql, array(':fadeIn'=>$fadeIn, ':cliplength'=>$cliplength), 'column')) {
if ($r->fetchColumn(0)){
$fadeIn = $cliplength; $fadeIn = $cliplength;
$row->setDbFadein($fadeIn); $row->setDbFadein($fadeIn);
} }
$sql = "SELECT INTERVAL '{$fadeOut}' > INTERVAL '{$cliplength}'"; $sql = "SELECT :fadeOut::INTERVAL > :cliplength::INTERVAL";
$r = $this->con->query($sql); if (Application_Common_Database::prepareAndExecute($sql, array(':fadeOut'=>$fadeOut, ':cliplength'=>$cliplength), 'column')) {
if ($r->fetchColumn(0)){
$fadeOut = $cliplength; $fadeOut = $cliplength;
$row->setDbFadein($fadeOut); $row->setDbFadein($fadeOut);
} }
@ -692,8 +813,7 @@ class Application_Model_Playlist {
$this->pl->save($this->con); $this->pl->save($this->con);
$this->con->commit(); $this->con->commit();
} } catch (Exception $e) {
catch (Exception $e) {
$this->con->rollback(); $this->con->rollback();
throw $e; throw $e;
} }
@ -707,7 +827,7 @@ class Application_Model_Playlist {
$categories = $this->categories; $categories = $this->categories;
$md = array(); $md = array();
foreach($categories as $key => $val) { foreach ($categories as $key => $val) {
$method = 'get' . $val; $method = 'get' . $val;
$md[$key] = $this->$method(); $md[$key] = $this->$method();
} }
@ -715,14 +835,15 @@ class Application_Model_Playlist {
return $md; return $md;
} }
public function getPLMetaData($category) public function getMetaData($category)
{ {
$cat = $this->categories[$category]; $cat = $this->categories[$category];
$method = 'get' . $cat; $method = 'get' . $cat;
return $this->$method(); return $this->$method();
} }
public function setPLMetaData($category, $value) public function setMetadata($category, $value)
{ {
$cat = $this->categories[$category]; $cat = $this->categories[$category];
@ -730,62 +851,12 @@ class Application_Model_Playlist {
$this->$method($value); $this->$method($value);
} }
/**
* This function is used for calculations! Don't modify for display purposes!
*
* Convert playlist time value to float seconds
*
* @param string $plt
* playlist interval value (HH:mm:ss.dddddd)
* @return int
* seconds
*/
public static function playlistTimeToSeconds($plt)
{
$arr = preg_split('/:/', $plt);
if (isset($arr[2])) {
return (intval($arr[0])*60 + intval($arr[1]))*60 + floatval($arr[2]);
}
if (isset($arr[1])) {
return intval($arr[0])*60 + floatval($arr[1]);
}
return floatval($arr[0]);
}
/**
* This function is used for calculations! Don't modify for display purposes!
*
* Convert float seconds value to playlist time format
*
* @param float $seconds
* @return string
* interval in playlist time format (HH:mm:ss.d)
*/
public static function secondsToPlaylistTime($p_seconds)
{
$info = explode('.', $p_seconds);
$seconds = $info[0];
if(!isset($info[1])){
$milliStr = 0;
}else{
$milliStr = $info[1];
}
$hours = floor($seconds / 3600);
$seconds -= $hours * 3600;
$minutes = floor($seconds / 60);
$seconds -= $minutes * 60;
$res = sprintf("%02d:%02d:%02d.%s", $hours, $minutes, $seconds, $milliStr);
return $res;
}
public static function getPlaylistCount() public static function getPlaylistCount()
{ {
global $CC_CONFIG; global $CC_CONFIG;
$con = Propel::getConnection(); $con = Propel::getConnection();
$sql = 'SELECT count(*) as cnt FROM '.$CC_CONFIG["playListTable"]; $sql = 'SELECT count(*) as cnt FROM '.$CC_CONFIG["playListTable"];
return $con->query($sql)->fetchColumn(0); return $con->query($sql)->fetchColumn(0);
} }
@ -802,12 +873,52 @@ class Application_Model_Playlist {
* Delete playlists that match the ids.. * Delete playlists that match the ids..
* @param array $p_ids * @param array $p_ids
*/ */
public static function DeletePlaylists($p_ids) public static function deletePlaylists($p_ids, $p_userId)
{ {
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id);
$isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
if (!$isAdminOrPM) {
$leftOver = self::playlistsNotOwnedByUser($p_ids, $p_userId);
if (count($leftOver) == 0) {
CcPlaylistQuery::create()->findPKs($p_ids)->delete(); CcPlaylistQuery::create()->findPKs($p_ids)->delete();
} else {
throw new PlaylistNoPermissionException;
}
} else {
CcPlaylistQuery::create()->findPKs($p_ids)->delete();
}
}
// This function returns that are not owen by $p_user_id among $p_ids
private static function playlistsNotOwnedByUser($p_ids, $p_userId)
{
$ownedByUser = CcPlaylistQuery::create()->filterByDbCreatorId($p_userId)->find()->getData();
$selectedPls = $p_ids;
$ownedPls = array();
foreach ($ownedByUser as $pl) {
if (in_array($pl->getDbId(), $selectedPls)) {
$ownedPls[] = $pl->getDbId();
}
}
$leftOvers = array_diff($selectedPls, $ownedPls);
return $leftOvers;
}
/**
* Delete all files from playlist
* @param int $p_playlistId
*/
public function deleteAllFilesFromPlaylist()
{
CcPlaylistcontentsQuery::create()->findByDbPlaylistId($this->id)->delete();
} }
} // class Playlist } // class Playlist
class PlaylistNotFoundException extends Exception {} class PlaylistNotFoundException extends Exception {}
class PlaylistNoPermissionException extends Exception {}
class PlaylistOutDatedException extends Exception {} class PlaylistOutDatedException extends Exception {}

View file

@ -2,8 +2,8 @@
require_once 'formatters/LengthFormatter.php'; require_once 'formatters/LengthFormatter.php';
class Application_Model_PlayoutHistory { class Application_Model_PlayoutHistory
{
private $con; private $con;
private $timezone; private $timezone;
@ -16,16 +16,16 @@ class Application_Model_PlayoutHistory {
private $opts; private $opts;
private $mDataPropMap = array( private $mDataPropMap = array(
"artist" => "file.artist_name", "artist" => "artist_name",
"title" => "file.track_title", "title" => "track_title",
"played" => "playout.played", "played" => "played",
"length" => "file.length", "length" => "length",
"composer" => "file.composer", "composer" => "composer",
"copyright" => "file.copyright", "copyright" => "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->con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME);
$this->startDT = $p_startDT; $this->startDT = $p_startDT;
$this->endDT = $p_endDT; $this->endDT = $p_endDT;
@ -37,16 +37,16 @@ class Application_Model_PlayoutHistory {
/* /*
* map front end mDataProp labels to proper column names for searching etc. * 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(); $this->translateColumns();
$select = array( $select = array(

File diff suppressed because it is too large Load diff

View file

@ -3,94 +3,72 @@ require_once 'php-amqplib/amqp.inc';
class Application_Model_RabbitMq 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. * 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; {
self::$doPush = true;
}
private static function sendMessage($exchange, $data)
{
global $CC_CONFIG;
$conn = new AMQPConnection($CC_CONFIG["rabbitmq"]["host"],
$CC_CONFIG["rabbitmq"]["port"],
$CC_CONFIG["rabbitmq"]["user"],
$CC_CONFIG["rabbitmq"]["password"],
$CC_CONFIG["rabbitmq"]["vhost"]);
$channel = $conn->channel();
$channel->access_request($CC_CONFIG["rabbitmq"]["vhost"], false, false,
true, true);
$channel->exchange_declare($exchange, 'direct', false, true);
$msg = new AMQPMessage($data, array('content_type' => 'text/plain'));
$channel->basic_publish($msg, $exchange);
$channel->close();
$conn->close();
} }
public static function SendMessageToPypo($event_type, $md) public static function SendMessageToPypo($event_type, $md)
{ {
global $CC_CONFIG;
$md["event_type"] = $event_type; $md["event_type"] = $event_type;
$conn = new AMQPConnection($CC_CONFIG["rabbitmq"]["host"], $exchange = 'airtime-pypo';
$CC_CONFIG["rabbitmq"]["port"],
$CC_CONFIG["rabbitmq"]["user"],
$CC_CONFIG["rabbitmq"]["password"],
$CC_CONFIG["rabbitmq"]["vhost"]);
$channel = $conn->channel();
$channel->access_request($CC_CONFIG["rabbitmq"]["vhost"], false, false, true, true);
$EXCHANGE = 'airtime-pypo';
$channel->exchange_declare($EXCHANGE, 'direct', false, true);
$data = json_encode($md, JSON_FORCE_OBJECT); $data = json_encode($md, JSON_FORCE_OBJECT);
$msg = new AMQPMessage($data, array('content_type' => 'text/plain')); self::sendMessage($exchange, $data);
$channel->basic_publish($msg, $EXCHANGE);
$channel->close();
$conn->close();
} }
public static function SendMessageToMediaMonitor($event_type, $md) public static function SendMessageToMediaMonitor($event_type, $md)
{ {
global $CC_CONFIG;
$md["event_type"] = $event_type; $md["event_type"] = $event_type;
$conn = new AMQPConnection($CC_CONFIG["rabbitmq"]["host"], $exchange = 'airtime-media-monitor';
$CC_CONFIG["rabbitmq"]["port"],
$CC_CONFIG["rabbitmq"]["user"],
$CC_CONFIG["rabbitmq"]["password"],
$CC_CONFIG["rabbitmq"]["vhost"]);
$channel = $conn->channel();
$channel->access_request($CC_CONFIG["rabbitmq"]["vhost"], false, false, true, true);
$EXCHANGE = 'airtime-media-monitor';
$channel->exchange_declare($EXCHANGE, 'direct', false, true);
$data = json_encode($md); $data = json_encode($md);
$msg = new AMQPMessage($data, array('content_type' => 'text/plain')); self::sendMessage($exchange, $data);
$channel->basic_publish($msg, $EXCHANGE);
$channel->close();
$conn->close();
} }
public static function SendMessageToShowRecorder($event_type) public static function SendMessageToShowRecorder($event_type)
{ {
global $CC_CONFIG; $exchange = 'airtime-pypo';
$conn = new AMQPConnection($CC_CONFIG["rabbitmq"]["host"],
$CC_CONFIG["rabbitmq"]["port"],
$CC_CONFIG["rabbitmq"]["user"],
$CC_CONFIG["rabbitmq"]["password"],
$CC_CONFIG["rabbitmq"]["vhost"]);
$channel = $conn->channel();
$channel->access_request($CC_CONFIG["rabbitmq"]["vhost"], false, false, true, true);
$EXCHANGE = 'airtime-pypo';
$channel->exchange_declare($EXCHANGE, 'direct', false, true);
$now = new DateTime("@".time()); //in UTC timezone $now = new DateTime("@".time()); //in UTC timezone
$end_timestamp = new DateTime("@".(time() + 3600*2)); //in UTC timezone $end_timestamp = new DateTime("@".(time() + 3600*2)); //in UTC timezone
$temp = array();
$temp['event_type'] = $event_type; $temp['event_type'] = $event_type;
$temp['server_timezone'] = Application_Model_Preference::GetTimezone(); $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); $temp['shows'] = Application_Model_Show::getShows($now,
$end_timestamp, $onlyRecord=true);
} }
$data = json_encode($temp); $data = json_encode($temp);
$msg = new AMQPMessage($data, array('content_type' => 'text/plain'));
$channel->basic_publish($msg, $EXCHANGE); self::sendMessage($exchange, $data);
$channel->close();
$conn->close();
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,7 @@
<?php <?php
class Application_Model_Scheduler { class Application_Model_Scheduler
{
private $con; private $con;
private $fileInfo = array( private $fileInfo = array(
"id" => "", "id" => "",
@ -11,6 +11,7 @@ class Application_Model_Scheduler {
"fadein" => "00:00:00", "fadein" => "00:00:00",
"fadeout" => "00:00:00", "fadeout" => "00:00:00",
"sched_id" => null, "sched_id" => null,
"type" => 0 //default type of '0' to represent files. type '1' represents a webstream
); );
private $epochNow; private $epochNow;
@ -19,34 +20,38 @@ class Application_Model_Scheduler {
private $checkUserPermissions = true; private $checkUserPermissions = true;
public function __construct() { public function __construct()
{
$this->con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); $this->con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME);
$this->epochNow = microtime(true); //subtracting one because sometimes when we cancel a track, we set its end time
//to epochNow and then send the new schedule to pypo. Sometimes the currently cancelled
//track can still be included in the new schedule because it may have a few ms left to play.
//subtracting 1 second from epochNow resolves this issue.
$this->epochNow = microtime(true)-1;
$this->nowDT = DateTime::createFromFormat("U.u", $this->epochNow, new DateTimeZone("UTC")); $this->nowDT = DateTime::createFromFormat("U.u", $this->epochNow, new DateTimeZone("UTC"));
if ($this->nowDT === false){ if ($this->nowDT === false) {
// DateTime::createFromFormat does not support millisecond string formatting in PHP 5.3.2 (Ubuntu 10.04). // DateTime::createFromFormat does not support millisecond string formatting in PHP 5.3.2 (Ubuntu 10.04).
// In PHP 5.3.3 (Ubuntu 10.10), this has been fixed. // In PHP 5.3.3 (Ubuntu 10.10), this has been fixed.
$this->nowDT = DateTime::createFromFormat("U", time(), new DateTimeZone("UTC")); $this->nowDT = DateTime::createFromFormat("U", time(), new DateTimeZone("UTC"));
} }
$this->user = Application_Model_User::GetCurrentUser(); $this->user = Application_Model_User::getCurrentUser();
} }
public function setCheckUserPermissions($value) { public function setCheckUserPermissions($value)
{
$this->checkUserPermissions = $value; $this->checkUserPermissions = $value;
} }
/* /*
* make sure any incoming requests for scheduling are ligit. * make sure any incoming requests for scheduling are ligit.
* *
* @param array $items, an array containing pks of cc_schedule items. * @param array $items, an array containing pks of cc_schedule items.
*/ */
private function validateRequest($items) { private function validateRequest($items)
{
$nowEpoch = floatval($this->nowDT->format("U.u")); $nowEpoch = floatval($this->nowDT->format("U.u"));
for ($i = 0; $i < count($items); $i++) { for ($i = 0; $i < count($items); $i++) {
@ -109,7 +114,7 @@ class Application_Model_Scheduler {
$ts = intval($instanceInfo[$id]); $ts = intval($instanceInfo[$id]);
$lastSchedTs = intval($instance->getDbLastScheduled("U")) ? : 0; $lastSchedTs = intval($instance->getDbLastScheduled("U")) ? : 0;
if ($ts < $lastSchedTs) { if ($ts < $lastSchedTs) {
Logging::log("ts {$ts} last sched {$lastSchedTs}"); Logging::info("ts {$ts} last sched {$lastSchedTs}");
throw new OutDatedScheduleException("The show {$show->getDbName()} has been previously updated!"); throw new OutDatedScheduleException("The show {$show->getDbName()} has been previously updated!");
} }
} }
@ -121,8 +126,8 @@ class Application_Model_Scheduler {
* *
* @return $files * @return $files
*/ */
private function retrieveMediaFiles($id, $type) { private function retrieveMediaFiles($id, $type)
{
$files = array(); $files = array();
if ($type === "audioclip") { if ($type === "audioclip") {
@ -130,8 +135,7 @@ class Application_Model_Scheduler {
if (is_null($file) || !$file->getDbFileExists()) { if (is_null($file) || !$file->getDbFileExists()) {
throw new Exception("A selected File does not exist!"); throw new Exception("A selected File does not exist!");
} } else {
else {
$data = $this->fileInfo; $data = $this->fileInfo;
$data["id"] = $id; $data["id"] = $id;
$data["cliplength"] = $file->getDbLength(); $data["cliplength"] = $file->getDbLength();
@ -146,33 +150,119 @@ class Application_Model_Scheduler {
$files[] = $data; $files[] = $data;
} }
} } elseif ($type === "playlist") {
else if ($type === "playlist") { $pl = new Application_Model_Playlist($id);
$contents = $pl->getContents();
$contents = CcPlaylistcontentsQuery::create()
->orderByDbPosition()
->filterByDbPlaylistId($id)
->find($this->con);
if (is_null($contents)) {
throw new Exception("A selected Playlist does not exist!");
}
foreach ($contents as $plItem) { foreach ($contents as $plItem) {
if ($plItem['type'] == 0) {
$file = $plItem->getCcFiles($this->con); $data["id"] = $plItem['item_id'];
$data["cliplength"] = $plItem['length'];
$data["cuein"] = $plItem['cuein'];
$data["cueout"] = $plItem['cueout'];
$data["fadein"] = $plItem['fadein'];
$data["fadeout"] = $plItem['fadeout'];
$data["type"] = 0;
$files[] = $data;
} elseif ($plItem['type'] == 1) {
$data["id"] = $plItem['item_id'];
$data["cliplength"] = $plItem['length'];
$data["cuein"] = $plItem['cuein'];
$data["cueout"] = $plItem['cueout'];
$data["fadein"] = "00.500000";//$plItem['fadein'];
$data["fadeout"] = "00.500000";//$plItem['fadeout'];
$data["type"] = 1;
$files[] = $data;
} elseif ($plItem['type'] == 2) {
// if it's a block
$bl = new Application_Model_Block($plItem['item_id']);
if ($bl->isStatic()) {
foreach ($bl->getContents() as $track) {
$data["id"] = $track['item_id'];
$data["cliplength"] = $track['length'];
$data["cuein"] = $track['cuein'];
$data["cueout"] = $track['cueout'];
$data["fadein"] = $track['fadein'];
$data["fadeout"] = $track['fadeout'];
$data["type"] = 0;
$files[] = $data;
}
} else {
$dynamicFiles = $bl->getListOfFilesUnderLimit();
foreach ($dynamicFiles as $fileId=>$f) {
$file = CcFilesQuery::create()->findPk($fileId);
if (isset($file) && $file->getDbFileExists()) { if (isset($file) && $file->getDbFileExists()) {
$data["id"] = $file->getDbId();
$data["cliplength"] = $file->getDbLength();
$data["cuein"] = "00:00:00";
$data["cueout"] = $file->getDbLength();
$defaultFade = Application_Model_Preference::GetDefaultFade();
if (isset($defaultFade)) {
//fade is in format SS.uuuuuu
$data["fadein"] = $defaultFade;
$data["fadeout"] = $defaultFade;
}
$data["type"] = 0;
$files[] = $data;
}
}
}
}
}
} elseif ($type == "stream") {
//need to return
$stream = CcWebstreamQuery::create()->findPK($id, $this->con);
if (is_null($stream) /* || !$file->getDbFileExists() */) {
throw new Exception("A selected File does not exist!");
} else {
$data = $this->fileInfo; $data = $this->fileInfo;
$data["id"] = $plItem->getDbFileId(); $data["id"] = $id;
$data["cliplength"] = $plItem->getDbCliplength(); $data["cliplength"] = $stream->getDbLength();
$data["cuein"] = $plItem->getDbCuein(); $data["cueout"] = $stream->getDbLength();
$data["cueout"] = $plItem->getDbCueout(); $data["type"] = 1;
$data["fadein"] = $plItem->getDbFadein();
$data["fadeout"] = $plItem->getDbFadeout(); $defaultFade = Application_Model_Preference::GetDefaultFade();
if (isset($defaultFade)) {
//fade is in format SS.uuuuuu
$data["fadein"] = $defaultFade;
$data["fadeout"] = $defaultFade;
}
$files[] = $data; $files[] = $data;
} }
} elseif ($type == "block") {
$bl = new Application_Model_Block($id);
if ($bl->isStatic()) {
foreach ($bl->getContents() as $track) {
$data["id"] = $track['item_id'];
$data["cliplength"] = $track['length'];
$data["cuein"] = $track['cuein'];
$data["cueout"] = $track['cueout'];
$data["fadein"] = $track['fadein'];
$data["fadeout"] = $track['fadeout'];
$data["type"] = 0;
$files[] = $data;
}
} else {
$dynamicFiles = $bl->getListOfFilesUnderLimit();
foreach ($dynamicFiles as $fileId=>$f) {
$file = CcFilesQuery::create()->findPk($fileId);
if (isset($file) && $file->getDbFileExists()) {
$data["id"] = $file->getDbId();
$data["cliplength"] = $file->getDbLength();
$data["cuein"] = "00:00:00";
$data["cueout"] = $file->getDbLength();
$defaultFade = Application_Model_Preference::GetDefaultFade();
if (isset($defaultFade)) {
//fade is in format SS.uuuuuu
$data["fadein"] = $defaultFade;
$data["fadeout"] = $defaultFade;
}
$data["type"] = 0;
$files[] = $data;
}
}
} }
} }
@ -186,10 +276,10 @@ class Application_Model_Scheduler {
* *
* @return DateTime endDT in UTC * @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"); $startEpoch = $p_startDT->format("U.u");
$durationSeconds = Application_Model_Playlist::playlistTimeToSeconds($p_duration); $durationSeconds = Application_Common_DateHelper::playlistTimeToSeconds($p_duration);
//add two float numbers to 6 subsecond precision //add two float numbers to 6 subsecond precision
//DateTime::createFromFormat("U.u") will have a problem if there is no decimal in the resulting number. //DateTime::createFromFormat("U.u") will have a problem if there is no decimal in the resulting number.
@ -205,8 +295,8 @@ class Application_Model_Scheduler {
return $dt; return $dt;
} }
private function findNextStartTime($DT, $instance) { private function findNextStartTime($DT, $instance)
{
$sEpoch = $DT->format("U.u"); $sEpoch = $DT->format("U.u");
$nEpoch = $this->epochNow; $nEpoch = $this->epochNow;
@ -217,7 +307,7 @@ class Application_Model_Scheduler {
$nextDT = $this->nowDT; $nextDT = $this->nowDT;
$length = bcsub($nEpoch , $sEpoch , 6); $length = bcsub($nEpoch , $sEpoch , 6);
$cliplength = Application_Model_Playlist::secondsToPlaylistTime($length); $cliplength = Application_Common_DateHelper::secondsToPlaylistTime($length);
//fillers are for only storing a chunk of time space that has already passed. //fillers are for only storing a chunk of time space that has already passed.
$filler = new CcSchedule(); $filler = new CcSchedule();
@ -227,8 +317,7 @@ class Application_Model_Scheduler {
->setDbPlayoutStatus(-1) ->setDbPlayoutStatus(-1)
->setDbInstanceId($instance->getDbId()) ->setDbInstanceId($instance->getDbId())
->save($this->con); ->save($this->con);
} } else {
else {
$nextDT = $DT; $nextDT = $DT;
} }
@ -239,10 +328,12 @@ class Application_Model_Scheduler {
* @param int $showInstance * @param int $showInstance
* @param array $exclude * @param array $exclude
* ids of sched items to remove from the calulation. * ids of sched items to remove from the calulation.
* This function squeezes all items of a show together so that
* there are no gaps between them.
*/ */
private function removeGaps($showInstance, $exclude=null) { public function removeGaps($showInstance, $exclude=null)
{
Logging::log("removing gaps from show instance #".$showInstance); Logging::info("removing gaps from show instance #".$showInstance);
$instance = CcShowInstancesQuery::create()->findPK($showInstance, $this->con); $instance = CcShowInstancesQuery::create()->findPK($showInstance, $this->con);
if (is_null($instance)) { if (is_null($instance)) {
@ -257,7 +348,6 @@ class Application_Model_Scheduler {
->orderByDbStarts() ->orderByDbStarts()
->find($this->con); ->find($this->con);
foreach ($schedule as $item) { foreach ($schedule as $item) {
$itemEndDT = $this->findEndTime($itemStartDT, $item->getDbClipLength()); $itemEndDT = $this->findEndTime($itemStartDT, $item->getDbClipLength());
@ -276,8 +366,8 @@ class Application_Model_Scheduler {
* @param array $fileIds * @param array $fileIds
* @param array $playlistIds * @param array $playlistIds
*/ */
private function insertAfter($scheduleItems, $schedFiles, $adjustSched = true) { private function insertAfter($scheduleItems, $schedFiles, $adjustSched = true)
{
try { try {
$affectedShowInstances = array(); $affectedShowInstances = array();
@ -331,7 +421,7 @@ class Application_Model_Scheduler {
Logging::debug(floatval($pend) - floatval($pstart)); Logging::debug(floatval($pend) - floatval($pstart));
} }
foreach($schedFiles as $file) { foreach ($schedFiles as $file) {
$endTimeDT = $this->findEndTime($nextStartDT, $file['cliplength']); $endTimeDT = $this->findEndTime($nextStartDT, $file['cliplength']);
@ -339,21 +429,30 @@ class Application_Model_Scheduler {
//need to keep same id for resources if we want REST. //need to keep same id for resources if we want REST.
if (isset($file['sched_id'])) { if (isset($file['sched_id'])) {
$sched = CcScheduleQuery::create()->findPK($file['sched_id'], $this->con); $sched = CcScheduleQuery::create()->findPK($file['sched_id'], $this->con);
} } else {
else {
$sched = new CcSchedule(); $sched = new CcSchedule();
} }
Logging::log(print_r($file,true)); Logging::info($file);
$sched->setDbStarts($nextStartDT) $sched->setDbStarts($nextStartDT)
->setDbEnds($endTimeDT) ->setDbEnds($endTimeDT)
->setDbFileId($file['id'])
->setDbCueIn($file['cuein']) ->setDbCueIn($file['cuein'])
->setDbCueOut($file['cueout']) ->setDbCueOut($file['cueout'])
->setDbFadeIn($file['fadein']) ->setDbFadeIn($file['fadein'])
->setDbFadeOut($file['fadeout']) ->setDbFadeOut($file['fadeout'])
->setDbClipLength($file['cliplength']) ->setDbClipLength($file['cliplength'])
->setDbInstanceId($instance->getDbId()) ->setDbInstanceId($instance->getDbId());
->save($this->con);
switch ($file["type"]) {
case 0:
$sched->setDbFileId($file['id']);
break;
case 1:
$sched->setDbStreamId($file['id']);
break;
default: break;
}
$sched->save($this->con);
$nextStartDT = $endTimeDT; $nextStartDT = $endTimeDT;
} }
@ -408,8 +507,7 @@ class Application_Model_Scheduler {
$endProfile = microtime(true); $endProfile = microtime(true);
Logging::debug("updating last scheduled timestamp."); Logging::debug("updating last scheduled timestamp.");
Logging::debug(floatval($endProfile) - floatval($startProfile)); Logging::debug(floatval($endProfile) - floatval($startProfile));
} } catch (Exception $e) {
catch (Exception $e) {
Logging::debug($e->getMessage()); Logging::debug($e->getMessage());
throw $e; throw $e;
} }
@ -419,8 +517,8 @@ class Application_Model_Scheduler {
* @param array $scheduleItems * @param array $scheduleItems
* @param array $mediaItems * @param array $mediaItems
*/ */
public function scheduleAfter($scheduleItems, $mediaItems, $adjustSched = true) { public function scheduleAfter($scheduleItems, $mediaItems, $adjustSched = true)
{
$this->con->beginTransaction(); $this->con->beginTransaction();
$schedFiles = array(); $schedFiles = array();
@ -437,8 +535,7 @@ class Application_Model_Scheduler {
$this->con->commit(); $this->con->commit();
Application_Model_RabbitMq::PushSchedule(); Application_Model_RabbitMq::PushSchedule();
} } catch (Exception $e) {
catch (Exception $e) {
$this->con->rollback(); $this->con->rollback();
throw $e; throw $e;
} }
@ -448,8 +545,8 @@ class Application_Model_Scheduler {
* @param array $selectedItem * @param array $selectedItem
* @param array $afterItem * @param array $afterItem
*/ */
public function moveItem($selectedItems, $afterItems, $adjustSched = true) { public function moveItem($selectedItems, $afterItems, $adjustSched = true)
{
$startProfile = microtime(true); $startProfile = microtime(true);
$this->con->beginTransaction(); $this->con->beginTransaction();
@ -492,8 +589,7 @@ class Application_Model_Scheduler {
$schedId = $selected->getDbId(); $schedId = $selected->getDbId();
if (isset($modifiedMap[$showInstanceId])) { if (isset($modifiedMap[$showInstanceId])) {
array_push($modifiedMap[$showInstanceId], $schedId); array_push($modifiedMap[$showInstanceId], $schedId);
} } else {
else {
$modifiedMap[$showInstanceId] = array($schedId); $modifiedMap[$showInstanceId] = array($schedId);
} }
} }
@ -517,10 +613,9 @@ class Application_Model_Scheduler {
Logging::debug("inserting after removing gaps."); Logging::debug("inserting after removing gaps.");
Logging::debug(floatval($endProfile) - floatval($startProfile)); Logging::debug(floatval($endProfile) - floatval($startProfile));
$afterInstanceId = $afterInstance->getDbId();
$modified = array_keys($modifiedMap); $modified = array_keys($modifiedMap);
//need to adjust shows we have moved items from. //need to adjust shows we have moved items from.
foreach($modified as $instanceId) { foreach ($modified as $instanceId) {
$instance = CcShowInstancesQuery::create()->findPK($instanceId, $this->con); $instance = CcShowInstancesQuery::create()->findPK($instanceId, $this->con);
$instance->updateScheduleStatus($this->con); $instance->updateScheduleStatus($this->con);
@ -530,15 +625,14 @@ class Application_Model_Scheduler {
$this->con->commit(); $this->con->commit();
Application_Model_RabbitMq::PushSchedule(); Application_Model_RabbitMq::PushSchedule();
} } catch (Exception $e) {
catch (Exception $e) {
$this->con->rollback(); $this->con->rollback();
throw $e; throw $e;
} }
} }
public function removeItems($scheduledItems, $adjustSched = true) { public function removeItems($scheduledItems, $adjustSched = true)
{
$showInstances = array(); $showInstances = array();
$this->con->beginTransaction(); $this->con->beginTransaction();
@ -565,18 +659,20 @@ class Application_Model_Scheduler {
$sEpoch = $removedItem->getDbStarts('U.u'); $sEpoch = $removedItem->getDbStarts('U.u');
$length = bcsub($nEpoch , $sEpoch , 6); $length = bcsub($nEpoch , $sEpoch , 6);
$cliplength = Application_Model_Playlist::secondsToPlaylistTime($length); $cliplength = Application_Common_DateHelper::secondsToPlaylistTime($length);
$cueinSec = Application_Model_Playlist::playlistTimeToSeconds($removedItem->getDbCueIn()); $cueinSec = Application_Common_DateHelper::playlistTimeToSeconds($removedItem->getDbCueIn());
$cueOutSec = bcadd($cueinSec , $length, 6); $cueOutSec = bcadd($cueinSec , $length, 6);
$cueout = Application_Model_Playlist::secondsToPlaylistTime($cueOutSec); $cueout = Application_Common_DateHelper::secondsToPlaylistTime($cueOutSec);
//Set DbEnds - 1 second because otherwise there can be a timing issue
//when sending the new schedule to Pypo where Pypo thinks the track is still
//playing.
$removedItem->setDbCueOut($cueout) $removedItem->setDbCueOut($cueout)
->setDbClipLength($cliplength) ->setDbClipLength($cliplength)
->setDbEnds($this->nowDT) ->setDbEnds($this->nowDT)
->save($this->con); ->save($this->con);
} } else {
else {
$removedItem->delete($this->con); $removedItem->delete($this->con);
} }
} }
@ -613,8 +709,7 @@ class Application_Model_Scheduler {
$this->con->commit(); $this->con->commit();
Application_Model_RabbitMq::PushSchedule(); Application_Model_RabbitMq::PushSchedule();
} } catch (Exception $e) {
catch (Exception $e) {
$this->con->rollback(); $this->con->rollback();
throw $e; throw $e;
} }
@ -625,8 +720,8 @@ class Application_Model_Scheduler {
* *
* @param $p_id id of the show instance to cancel. * @param $p_id id of the show instance to cancel.
*/ */
public function cancelShow($p_id) { public function cancelShow($p_id)
{
$this->con->beginTransaction(); $this->con->beginTransaction();
try { try {
@ -644,7 +739,7 @@ class Application_Model_Scheduler {
$remove = array(); $remove = array();
$ts = $this->nowDT->format('U'); $ts = $this->nowDT->format('U');
for($i = 0; $i < count($items); $i++) { for ($i = 0; $i < count($items); $i++) {
$remove[$i]["instance"] = $p_id; $remove[$i]["instance"] = $p_id;
$remove[$i]["timestamp"] = $ts; $remove[$i]["timestamp"] = $ts;
$remove[$i]["id"] = $items[$i]->getDbId(); $remove[$i]["id"] = $items[$i]->getDbId();
@ -652,8 +747,7 @@ class Application_Model_Scheduler {
$this->removeItems($remove, false); $this->removeItems($remove, false);
} }
} } else {
else {
$rebroadcasts = $instance->getCcShowInstancessRelatedByDbId(null, $this->con); $rebroadcasts = $instance->getCcShowInstancessRelatedByDbId(null, $this->con);
$rebroadcasts->delete($this->con); $rebroadcasts->delete($this->con);
} }
@ -666,8 +760,7 @@ class Application_Model_Scheduler {
if ($instance->getDbRecord()) { if ($instance->getDbRecord()) {
Application_Model_RabbitMq::SendMessageToShowRecorder("cancel_recording"); Application_Model_RabbitMq::SendMessageToShowRecorder("cancel_recording");
} }
} } catch (Exception $e) {
catch (Exception $e) {
$this->con->rollback(); $this->con->rollback();
throw $e; throw $e;
} }

View file

@ -1,11 +1,26 @@
<?php <?php
class Application_Model_ServiceRegister { class Application_Model_ServiceRegister
{
public static function GetRemoteIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
//check ip from share internet
$ip=$_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
//to check ip is pass from proxy
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip=$_SERVER['REMOTE_ADDR'];
}
public static function Register($p_componentName, $p_ipAddress){ return $ip;
}
public static function Register($p_componentName, $p_ipAddress)
{
$component = CcServiceRegisterQuery::create()->findOneByDbName($p_componentName); $component = CcServiceRegisterQuery::create()->findOneByDbName($p_componentName);
if ($component == NULL){ if (is_null($component)) {
$component = new CcServiceRegister(); $component = new CcServiceRegister();
$component->setDbName($p_componentName); $component->setDbName($p_componentName);
} }
@ -14,7 +29,7 @@ class Application_Model_ServiceRegister {
// to allow access via an ipv6 address. // to allow access via an ipv6 address.
// http://[::1]:2812 does not respond. // http://[::1]:2812 does not respond.
// Bug: http://savannah.nongnu.org/bugs/?27608 // Bug: http://savannah.nongnu.org/bugs/?27608
if ($p_ipAddress == "::1"){ if ($p_ipAddress == "::1") {
$p_ipAddress = "127.0.0.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/LengthFormatter.php';
require_once 'formatters/TimeFilledFormatter.php'; require_once 'formatters/TimeFilledFormatter.php';
class Application_Model_ShowBuilder { class Application_Model_ShowBuilder
{
private $timezone; private $timezone;
//in UTC timezone //in UTC timezone
@ -42,26 +42,26 @@ class Application_Model_ShowBuilder {
"fadeout" => "", "fadeout" => "",
"image" => false, "image" => false,
"color" => "", //in hex without the '#' sign. "color" => "", //in hex without the '#' sign.
"backgroundColor"=> "", //in hex without the '#' sign. "backgroundColor" => "", //in hex without the '#' sign.
); );
/* /*
* @param DateTime $p_startsDT * @param DateTime $p_startsDT
* @param DateTime $p_endsDT * @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->startDT = $p_startDT;
$this->endDT = $p_endDT; $this->endDT = $p_endDT;
$this->timezone = date_default_timezone_get(); $this->timezone = date_default_timezone_get();
$this->user = Application_Model_User::GetCurrentUser(); $this->user = Application_Model_User::getCurrentUser();
$this->opts = $p_opts; $this->opts = $p_opts;
$this->epoch_now = floatval(microtime(true)); $this->epoch_now = floatval(microtime(true));
$this->currentShow = false; $this->currentShow = false;
} }
private function getUsersShows() { private function getUsersShows()
{
$shows = array(); $shows = array();
$host_shows = CcShowHostsQuery::create() $host_shows = CcShowHostsQuery::create()
@ -77,8 +77,8 @@ class Application_Model_ShowBuilder {
} }
//check to see if this row should be editable by the user. //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. //cannot schedule in a recorded show.
if (intval($p_item["si_record"]) === 1) { if (intval($p_item["si_record"]) === 1) {
return; return;
@ -89,7 +89,8 @@ class Application_Model_ShowBuilder {
} }
} }
private function getItemColor($p_item, &$row) { private function getItemColor($p_item, &$row)
{
$defaultColor = "ffffff"; $defaultColor = "ffffff";
$defaultBackground = "3366cc"; $defaultBackground = "3366cc";
@ -107,17 +108,16 @@ class Application_Model_ShowBuilder {
} }
//information about whether a track is inside|boundary|outside a show. //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"]); $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"])) { if (is_null($p_item["si_last_scheduled"])) {
$ts = 0; $ts = 0;
} } else {
else {
$dt = new DateTime($p_item["si_last_scheduled"], new DateTimeZone("UTC")); $dt = new DateTime($p_item["si_last_scheduled"], new DateTimeZone("UTC"));
$ts = intval($dt->format("U")); $ts = intval($dt->format("U"));
} }
@ -129,19 +129,18 @@ class Application_Model_ShowBuilder {
* 0 = past * 0 = past
* 1 = current * 1 = current
* 2 = future * 2 = future
* TODO : change all of the above to real constants -- RG
*/ */
private function getScheduledStatus($p_epochItemStart, $p_epochItemEnd, &$row) { private function getScheduledStatus($p_epochItemStart, $p_epochItemEnd, &$row)
{
if ($row["footer"] === true && $this->epoch_now > $p_epochItemStart && $this->epoch_now > $p_epochItemEnd) { if ($row["footer"] === true && $this->epoch_now > $p_epochItemStart &&
$this->epoch_now > $p_epochItemEnd) {
$row["scheduled"] = 0; $row["scheduled"] = 0;
} } elseif ($row["footer"] === true && $this->epoch_now < $p_epochItemEnd) {
else if ($row["footer"] === true && $this->epoch_now < $p_epochItemEnd) {
$row["scheduled"] = 2; $row["scheduled"] = 2;
} } elseif ($row["header"] === true && $this->epoch_now >= $p_epochItemStart) {
else if ($row["header"] === true && $this->epoch_now >= $p_epochItemStart) {
$row["scheduled"] = 0; $row["scheduled"] = 0;
} } elseif ($row["header"] === true && $this->epoch_now < $p_epochItemEnd) {
else if ($row["header"] === true && $this->epoch_now < $p_epochItemEnd) {
$row["scheduled"] = 2; $row["scheduled"] = 2;
} }
@ -160,11 +159,19 @@ class Application_Model_ShowBuilder {
//item is in the future. //item is in the future.
else if ($this->epoch_now < $p_epochItemStart) { else if ($this->epoch_now < $p_epochItemStart) {
$row["scheduled"] = 2; $row["scheduled"] = 2;
} else {
Logging::warn("No-op? is this what should happen...printing
debug just in case");
$d = array(
'$p_epochItemStart' => $p_epochItemStart,
'$p_epochItemEnd' => $p_epochItemEnd,
'$row' => $row);
Logging::warn($d);
} }
} }
private function makeHeaderRow($p_item) { private function makeHeaderRow($p_item)
{
$row = $this->defaultRowArray; $row = $this->defaultRowArray;
$this->isAllowed($p_item, $row); $this->isAllowed($p_item, $row);
$this->getRowTimestamp($p_item, $row); $this->getRowTimestamp($p_item, $row);
@ -188,15 +195,17 @@ class Application_Model_ShowBuilder {
$time = $dt->format("Y-m-d H:i"); $time = $dt->format("Y-m-d H:i");
$row["rebroadcast_title"] = "Rebroadcast of {$name} from {$time}"; $row["rebroadcast_title"] = "Rebroadcast of {$name} from {$time}";
} } elseif (intval($p_item["si_record"]) === 1) {
else if (intval($p_item["si_record"]) === 1) {
$row["record"] = true; $row["record"] = true;
if (Application_Model_Preference::GetUploadToSoundcloudOption()) { // at the time of creating on show, the recorded file is not in the DB yet.
$file = Application_Model_StoredFile::Recall($p_item["si_file_id"]); // therefore, 'si_file_id' is null. So we need to check it.
if (Application_Model_Preference::GetUploadToSoundcloudOption() && isset($p_item['si_file_id'])) {
$file = Application_Model_StoredFile::Recall(
$p_item['si_file_id']);
if (isset($file)) { if (isset($file)) {
$sid = $file->getSoundCloudId(); $sid = $file->getSoundCloudId();
$row["soundcloud_id"] = $sid; $row['soundcloud_id'] = $sid;
} }
} }
} }
@ -204,8 +213,7 @@ class Application_Model_ShowBuilder {
if ($startsEpoch < $this->epoch_now && $endsEpoch > $this->epoch_now) { if ($startsEpoch < $this->epoch_now && $endsEpoch > $this->epoch_now) {
$row["currentShow"] = true; $row["currentShow"] = true;
$this->currentShow = true; $this->currentShow = true;
} } else {
else {
$this->currentShow = false; $this->currentShow = false;
} }
@ -229,14 +237,17 @@ class Application_Model_ShowBuilder {
return $row; return $row;
} }
private function makeScheduledItemRow($p_item) { private function makeScheduledItemRow($p_item)
{
$row = $this->defaultRowArray; $row = $this->defaultRowArray;
if (isset($p_item["sched_starts"])) { if (isset($p_item["sched_starts"])) {
$schedStartDT = new DateTime($p_item["sched_starts"], new DateTimeZone("UTC")); $schedStartDT = new DateTime($p_item["sched_starts"],
new DateTimeZone("UTC"));
$schedStartDT->setTimezone(new DateTimeZone($this->timezone)); $schedStartDT->setTimezone(new DateTimeZone($this->timezone));
$schedEndDT = new DateTime($p_item["sched_ends"], new DateTimeZone("UTC")); $schedEndDT = new DateTime($p_item["sched_ends"],
new DateTimeZone("UTC"));
$schedEndDT->setTimezone(new DateTimeZone($this->timezone)); $schedEndDT->setTimezone(new DateTimeZone($this->timezone));
$showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC")); $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC"));
@ -283,8 +294,7 @@ class Application_Model_ShowBuilder {
$endsEpoch = floatval($showEndDT->format("U.u")); $endsEpoch = floatval($showEndDT->format("U.u"));
$this->getScheduledStatus($startsEpoch, $endsEpoch, $row); $this->getScheduledStatus($startsEpoch, $endsEpoch, $row);
} } else {
else {
$row["empty"] = true; $row["empty"] = true;
$row["id"] = 0 ; $row["id"] = 0 ;
$row["instance"] = intval($p_item["si_id"]); $row["instance"] = intval($p_item["si_id"]);
@ -305,8 +315,8 @@ class Application_Model_ShowBuilder {
return $row; return $row;
} }
private function makeFooterRow($p_item) { private function makeFooterRow($p_item)
{
$row = $this->defaultRowArray; $row = $this->defaultRowArray;
$row["footer"] = true; $row["footer"] = true;
$row["instance"] = intval($p_item["si_id"]); $row["instance"] = intval($p_item["si_id"]);
@ -337,23 +347,28 @@ class Application_Model_ShowBuilder {
$this->getScheduledStatus($startsEpoch, $endsEpoch, $row); $this->getScheduledStatus($startsEpoch, $endsEpoch, $row);
$this->isAllowed($p_item, $row); $this->isAllowed($p_item, $row);
if (intval($p_item["si_record"]) === 1) {
$row["record"] = true;
}
return $row; return $row;
} }
/* /*
* @param int $timestamp Unix timestamp in seconds. * @param int $timestamp Unix timestamp in seconds.
* *
* @return boolean whether the schedule in the show builder's range has been updated. * @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; $outdated = false;
$shows = Application_Model_Show::getShows($this->startDT, $this->endDT); $shows = Application_Model_Show::getShows($this->startDT, $this->endDT);
if ($this->opts["showFilter"] !== 0) { if ($this->opts["showFilter"] !== 0) {
$include[] = $this->opts["showFilter"]; $include[] = $this->opts["showFilter"];
} } elseif ($this->opts["myShows"] === 1) {
else if ($this->opts["myShows"] === 1) {
$include = $this->getUsersShows(); $include = $this->getUsersShows();
} }
@ -367,24 +382,26 @@ class Application_Model_ShowBuilder {
$currentInstances[] = $show["instance_id"]; $currentInstances[] = $show["instance_id"];
if (isset($show["last_scheduled"])) { if (isset($show["last_scheduled"])) {
$dt = new DateTime($show["last_scheduled"], new DateTimeZone("UTC")); $dt = new DateTime($show["last_scheduled"],
} new DateTimeZone("UTC"));
else { } else {
$dt = new DateTime($show["created"], new DateTimeZone("UTC")); $dt = new DateTime($show["created"],
new DateTimeZone("UTC"));
} }
//check if any of the shows have a more recent timestamp. //check if any of the shows have a more recent timestamp.
$showTimeStamp = intval($dt->format("U")); $showTimeStamp = intval($dt->format("U"));
if ($timestamp < $showTimeStamp) { if ($timestamp < $showTimeStamp) {
Logging::debug("timestamp is {$timestamp} show timestamp is {$showTimeStamp}");
$outdated = true; $outdated = true;
break; break;
} }
} }
} }
//see if the displayed show instances have changed. (deleted, empty schedule etc) //see if the displayed show instances have changed. (deleted,
if ($outdated === false && count($instances) !== count($currentInstances)) { //empty schedule etc)
if ($outdated === false && count($instances)
!== count($currentInstances)) {
Logging::debug("show instances have changed."); Logging::debug("show instances have changed.");
$outdated = true; $outdated = true;
} }
@ -392,8 +409,8 @@ class Application_Model_ShowBuilder {
return $outdated; return $outdated;
} }
public function GetItems() { public function getItems()
{
$current_id = -1; $current_id = -1;
$display_items = array(); $display_items = array();
@ -401,19 +418,20 @@ class Application_Model_ShowBuilder {
if ($this->opts["myShows"] === 1) { if ($this->opts["myShows"] === 1) {
$shows = $this->getUsersShows(); $shows = $this->getUsersShows();
} } elseif ($this->opts["showFilter"] !== 0) {
else if ($this->opts["showFilter"] !== 0) {
$shows[] = $this->opts["showFilter"]; $shows[] = $this->opts["showFilter"];
} }
$scheduled_items = Application_Model_Schedule::GetScheduleDetailItems($this->startDT->format("Y-m-d H:i:s"), $this->endDT->format("Y-m-d H:i:s"), $shows); $scheduled_items = Application_Model_Schedule::GetScheduleDetailItems(
$this->startDT, $this->endDT, $shows);
for ($i = 0, $rows = count($scheduled_items); $i < $rows; $i++) { for ($i = 0, $rows = count($scheduled_items); $i < $rows; $i++) {
$item = $scheduled_items[$i]; $item = $scheduled_items[$i];
//don't send back data for filler rows. //don't send back data for filler rows.
if (isset($item["playout_status"]) && $item["playout_status"] < 0) { if (isset($item["playout_status"]) &&
$item["playout_status"] < 0) {
continue; continue;
} }
@ -422,8 +440,10 @@ class Application_Model_ShowBuilder {
//make a footer row. //make a footer row.
if ($current_id !== -1) { if ($current_id !== -1) {
//pass in the previous row as it's the last row for the previous show. // pass in the previous row as it's the last row for
$display_items[] = $this->makeFooterRow($scheduled_items[$i-1]); // the previous show.
$display_items[] = $this->makeFooterRow(
$scheduled_items[$i-1]);
} }
$display_items[] = $this->makeHeaderRow($item); $display_items[] = $this->makeHeaderRow($item);
@ -440,16 +460,20 @@ class Application_Model_ShowBuilder {
$display_items[] = $row; $display_items[] = $row;
} }
if ($current_id !== -1 && !in_array($current_id, $this->showInstances)) { if ($current_id !== -1 &&
!in_array($current_id, $this->showInstances)) {
$this->showInstances[] = $current_id; $this->showInstances[] = $current_id;
} }
} }
//make the last footer if there were any scheduled items. //make the last footer if there were any scheduled items.
if (count($scheduled_items) > 0) { if (count($scheduled_items) > 0) {
$display_items[] = $this->makeFooterRow($scheduled_items[count($scheduled_items)-1]); $display_items[] = $this->makeFooterRow($scheduled_items[
count($scheduled_items)-1]);
} }
return array("schedule" => $display_items, "showInstances" => $this->showInstances); return array(
"schedule" => $display_items,
"showInstances" => $this->showInstances);
} }
} }

View file

@ -2,8 +2,8 @@
require_once 'formatters/LengthFormatter.php'; require_once 'formatters/LengthFormatter.php';
class Application_Model_ShowInstance { class Application_Model_ShowInstance
{
private $_instanceId; private $_instanceId;
private $_showInstance; private $_showInstance;
@ -12,7 +12,7 @@ class Application_Model_ShowInstance {
$this->_instanceId = $instanceId; $this->_instanceId = $instanceId;
$this->_showInstance = CcShowInstancesQuery::create()->findPK($instanceId); $this->_showInstance = CcShowInstancesQuery::create()->findPK($instanceId);
if (is_null($this->_showInstance)){ if (is_null($this->_showInstance)) {
throw new Exception(); throw new Exception();
} }
} }
@ -22,27 +22,31 @@ class Application_Model_ShowInstance {
return $this->_showInstance->getDbShowId(); return $this->_showInstance->getDbShowId();
} }
/* TODO: A little inconsistent because other models have a getId() method
to get PK --RG */
public function getShowInstanceId() public function getShowInstanceId()
{ {
return $this->_instanceId; return $this->_instanceId;
} }
public function getShow(){ public function getShow()
{
return new Application_Model_Show($this->getShowId()); return new Application_Model_Show($this->getShowId());
} }
public function deleteRebroadcasts(){ public function deleteRebroadcasts()
$con = Propel::getConnection(); {
$timestamp = gmdate("Y-m-d H:i:s"); $timestamp = gmdate("Y-m-d H:i:s");
$instance_id = $this->getShowInstanceId(); $instance_id = $this->getShowInstanceId();
$sql = <<<SQL
$sql = "DELETE FROM cc_show_instances" DELETE FROM cc_show_instances
." WHERE starts > TIMESTAMP '$timestamp'" WHERE starts > :timestamp::TIMESTAMP
." AND instance_id = $instance_id" AND instance_id = :instanceId
." AND rebroadcast = 1"; AND rebroadcast = 1;
SQL;
$con->exec($sql); Application_Common_Database::prepareAndExecute( $sql, array(
':instanceId' => $instance_id,
':timestamp' => $timestamp), 'execute');
} }
/* This function is weird. It should return a boolean, but instead returns /* This function is weird. It should return a boolean, but instead returns
@ -62,12 +66,14 @@ class Application_Model_ShowInstance {
public function getName() public function getName()
{ {
$show = CcShowQuery::create()->findPK($this->getShowId()); $show = CcShowQuery::create()->findPK($this->getShowId());
return $show->getDbName(); return $show->getDbName();
} }
public function getGenre() public function getGenre()
{ {
$show = CcShowQuery::create()->findPK($this->getShowId()); $show = CcShowQuery::create()->findPK($this->getShowId());
return $show->getDbGenre(); return $show->getDbGenre();
} }
@ -93,6 +99,7 @@ class Application_Model_ShowInstance {
{ {
$showStart = $this->getShowInstanceStart(); $showStart = $this->getShowInstanceStart();
$showStartExplode = explode(" ", $showStart); $showStartExplode = explode(" ", $showStart);
return $showStartExplode[0]; return $showStartExplode[0];
} }
@ -113,6 +120,7 @@ class Application_Model_ShowInstance {
public function getSoundCloudFileId() public function getSoundCloudFileId()
{ {
$file = Application_Model_StoredFile::Recall($this->_showInstance->getDbRecordedFile()); $file = Application_Model_StoredFile::Recall($this->_showInstance->getDbRecordedFile());
return $file->getSoundCloudId(); return $file->getSoundCloudId();
} }
@ -161,12 +169,14 @@ class Application_Model_ShowInstance {
$con = Propel::getConnection(); $con = Propel::getConnection();
$instance_id = $this->getShowInstanceId(); $instance_id = $this->getShowInstanceId();
$sql = "SELECT starts from cc_schedule" $sql = <<<SQL
." WHERE instance_id = $instance_id" SELECT starts
." ORDER BY starts" FROM cc_schedule
." LIMIT 1"; WHERE instance_id = :instanceId
ORDER BY starts LIMIT 1;
$scheduleStarts = $con->query($sql)->fetchColumn(0); SQL;
$scheduleStarts = Application_Common_Database::prepareAndExecute( $sql,
array( ':instanceId' => $instance_id ), 'column' );
if ($scheduleStarts) { if ($scheduleStarts) {
$scheduleStartsEpoch = strtotime($scheduleStarts); $scheduleStartsEpoch = strtotime($scheduleStarts);
@ -174,13 +184,18 @@ class Application_Model_ShowInstance {
$diff = $showStartsEpoch - $scheduleStartsEpoch; $diff = $showStartsEpoch - $scheduleStartsEpoch;
if ($diff != 0){ if ($diff != 0) {
$sql = "UPDATE cc_schedule" $sql = <<<SQL
." SET starts = starts + INTERVAL '$diff' second," UPDATE cc_schedule
." ends = ends + INTERVAL '$diff' second" SET starts = starts + :diff1::INTERVAL SECOND,
." WHERE instance_id = $instance_id"; ends = ends + :diff2::INTERVAL SECOND
WHERE instance_id = :instanceId
$con->exec($sql); SQL;
Application_Common_Database::prepareAndExecute($sql,
array(
':diff1' => $diff,
':diff2' => $diff,
':instanceId' => $instance_id ), 'execute');
} }
} }
Application_Model_RabbitMq::PushSchedule(); Application_Model_RabbitMq::PushSchedule();
@ -199,8 +214,8 @@ class Application_Model_ShowInstance {
* @return $newDateTime * @return $newDateTime
* php DateTime, $dateTime with the added time deltas. * php DateTime, $dateTime with the added time deltas.
*/ */
private static function addDeltas($dateTime, $deltaDay, $deltaMin) { public static function addDeltas($dateTime, $deltaDay, $deltaMin)
{
$newDateTime = clone $dateTime; $newDateTime = clone $dateTime;
$days = abs($deltaDay); $days = abs($deltaDay);
@ -211,15 +226,13 @@ class Application_Model_ShowInstance {
if ($deltaDay > 0) { if ($deltaDay > 0) {
$newDateTime->add($dayInterval); $newDateTime->add($dayInterval);
} } elseif ($deltaDay < 0) {
else if ($deltaDay < 0){
$newDateTime->sub($dayInterval); $newDateTime->sub($dayInterval);
} }
if ($deltaMin > 0) { if ($deltaMin > 0) {
$newDateTime->add($minInterval); $newDateTime->add($minInterval);
} } elseif ($deltaMin < 0) {
else if ($deltaMin < 0) {
$newDateTime->sub($minInterval); $newDateTime->sub($minInterval);
} }
@ -228,7 +241,7 @@ class Application_Model_ShowInstance {
public function moveShow($deltaDay, $deltaMin) public function moveShow($deltaDay, $deltaMin)
{ {
if ($this->getShow()->isRepeating()){ if ($this->getShow()->isRepeating()) {
return "Can't drag and drop repeating shows"; return "Can't drag and drop repeating shows";
} }
@ -257,6 +270,12 @@ class Application_Model_ShowInstance {
return "Can't move show into past"; return "Can't move show into past";
} }
//check if show is overlapping
$overlapping = Application_Model_Schedule::checkOverlappingShows($newStartsDateTime, $newEndsDateTime, true, $this->getShowInstanceId());
if ($overlapping) {
return "Cannot schedule overlapping shows";
}
if ($this->isRecorded()) { if ($this->isRecorded()) {
//rebroadcasts should start at max 1 hour after a recorded show has ended. //rebroadcasts should start at max 1 hour after a recorded show has ended.
@ -280,6 +299,7 @@ class Application_Model_ShowInstance {
//recorded show doesn't exist. //recorded show doesn't exist.
catch (Exception $e) { catch (Exception $e) {
$this->_showInstance->delete(); $this->_showInstance->delete();
return "Show was deleted because recorded show does not exist!"; return "Show was deleted because recorded show does not exist!";
} }
@ -296,7 +316,7 @@ class Application_Model_ShowInstance {
$this->correctScheduleStartTimes(); $this->correctScheduleStartTimes();
$show = new Application_Model_Show($this->getShowId()); $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->setShowFirstShow($newStartsDateTime);
$show->setShowLastShow($newEndsDateTime); $show->setShowLastShow($newEndsDateTime);
} }
@ -304,33 +324,32 @@ class Application_Model_ShowInstance {
Application_Model_RabbitMq::PushSchedule(); Application_Model_RabbitMq::PushSchedule();
} }
/*
* FUNCTION SHOULD NOT BE CALLED
* - we are removing ability to resize just a single show instance
* -please use the resize method on the Show.php class.
*/
public function resizeShow($deltaDay, $deltaMin) public function resizeShow($deltaDay, $deltaMin)
{ {
$con = Propel::getConnection(); $con = Propel::getConnection();
$hours = $deltaMin/60; $hours = $deltaMin / 60;
if($hours > 0)
$hours = floor($hours);
else
$hours = ceil($hours);
$mins = abs($deltaMin%60); $hours = ($hours > 0) ? floor($hours) : ceil($hours);
$mins = abs($deltaMin % 60);
$today_timestamp = gmdate("Y-m-d H:i:s"); $today_timestamp = gmdate("Y-m-d H:i:s");
$starts = $this->getShowInstanceStart(); $starts = $this->getShowInstanceStart();
$ends = $this->getShowInstanceEnd(); $ends = $this->getShowInstanceEnd();
if(strtotime($today_timestamp) > strtotime($starts)) { if (strtotime($today_timestamp) > strtotime($starts)) {
return "can't resize a past show"; return "can't resize a past show";
} }
$sql = "SELECT timestamp '{$ends}' + interval '{$deltaDay} days' + interval '{$hours}:{$mins}'"; //$sql = "SELECT timestamp '{$ends}' + interval '{$deltaDay} days' + interval '{$hours}:{$mins}'";
$new_ends = $con->query($sql)->fetchColumn(0); $sql = "SELECT timestamp :ends + interval :deltaDays + interval :deltaTime";
$now_ends = Application_Common_Database::prepareAndExecute($sql,
array(':ends' => $ends,
':deltaDays' => "$deltaDay days",
':deltaTime' => "{$hours}:{$mins}"), 'column'
);
//only need to check overlap if show increased in size. //only need to check overlap if show increased in size.
if (strtotime($new_ends) > strtotime($ends)) { if (strtotime($new_ends) > strtotime($ends)) {
@ -340,17 +359,26 @@ class Application_Model_ShowInstance {
$overlap = Application_Model_Show::getShows($utcStartDateTime, $utcEndDateTime); $overlap = Application_Model_Show::getShows($utcStartDateTime, $utcEndDateTime);
if(count($overlap) > 0) { if (count($overlap) > 0) {
// TODO : fix ghetto error handling -- RG
return "Should not overlap shows"; return "Should not overlap shows";
} }
} }
//with overbooking no longer need to check already scheduled content still fits. //with overbooking no longer need to check already scheduled content still fits.
//must update length of all rebroadcast instances. //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}') $sql = <<<SQL
WHERE rebroadcast = 1 AND instance_id = {$this->_instanceId}"; UPDATE cc_show_instances
$con->exec($sql); SET ends = (ends + interval :deltaDays + interval :interval)
WHERE rebroadcast = 1
AND instance_id = :instanceId;
SQL;
Application_Common_Database::prepareAndExecute( $sql, array(
':deltaDays' => "$deltaDay days",
':interval' => "$hours:$mins",
':instanceId' => $this->_instanceId ), 'execute');
} }
$this->setShowEnd($new_ends); $this->setShowEnd($new_ends);
@ -447,7 +475,7 @@ class Application_Model_ShowInstance {
->filterByDbRebroadcast(0) ->filterByDbRebroadcast(0)
->find(); ->find();
if (is_null($showInstances)){ if (is_null($showInstances)) {
return true; return true;
} }
//only 1 show instance left of the show, make it non repeating. //only 1 show instance left of the show, make it non repeating.
@ -490,7 +518,7 @@ class Application_Model_ShowInstance {
return false; return false;
} }
public function delete() public function delete($rabbitmqPush = true)
{ {
// see if it was recording show // see if it was recording show
$recording = $this->isRecorded(); $recording = $this->isRecorded();
@ -526,24 +554,24 @@ class Application_Model_ShowInstance {
->delete(); ->delete();
if ($this->checkToDeleteShow($showId)){ if ($this->checkToDeleteShow($showId)) {
CcShowQuery::create() CcShowQuery::create()
->filterByDbId($showId) ->filterByDbId($showId)
->delete(); ->delete();
} }
} } else {
else {
if ($this->isRebroadcast()) { if ($this->isRebroadcast()) {
$this->_showInstance->delete(); $this->_showInstance->delete();
} } else {
else {
$show->delete(); $show->delete();
} }
} }
} }
if ($rabbitmqPush) {
Application_Model_RabbitMq::PushSchedule(); Application_Model_RabbitMq::PushSchedule();
} }
}
public function setRecordedFile($file_id) public function setRecordedFile($file_id)
{ {
@ -561,11 +589,8 @@ class Application_Model_ShowInstance {
try { try {
$rebroad = new Application_Model_ShowInstance($rebroadcast->getDbId()); $rebroad = new Application_Model_ShowInstance($rebroadcast->getDbId());
$rebroad->addFileToShow($file_id, false); $rebroad->addFileToShow($file_id, false);
} } catch (Exception $e) {
catch (Exception $e) { Logging::info($e->getMessage());
Logging::log("{$e->getFile()}");
Logging::log("{$e->getLine()}");
Logging::log("{$e->getMessage()}");
} }
} }
} }
@ -580,8 +605,7 @@ class Application_Model_ShowInstance {
$time_arr[1] = "." . $time_arr[1]; $time_arr[1] = "." . $time_arr[1];
$milliseconds = number_format(round($time_arr[1], 2), 2); $milliseconds = number_format(round($time_arr[1], 2), 2);
$time = $time_arr[0] . substr($milliseconds, 1); $time = $time_arr[0] . substr($milliseconds, 1);
} } else {
else {
$time = $time_arr[0] . ".00"; $time = $time_arr[0] . ".00";
} }
} else { } else {
@ -595,13 +619,15 @@ class Application_Model_ShowInstance {
public function getTimeScheduledSecs() public function getTimeScheduledSecs()
{ {
$time_filled = $this->getTimeScheduled(); $time_filled = $this->getTimeScheduled();
return Application_Model_Playlist::playlistTimeToSeconds($time_filled);
return Application_Common_DateHelper::playlistTimeToSeconds($time_filled);
} }
public function getDurationSecs() public function getDurationSecs()
{ {
$ends = $this->getShowInstanceEnd(null); $ends = $this->getShowInstanceEnd(null);
$starts = $this->getShowInstanceStart(null); $starts = $this->getShowInstanceStart(null);
return intval($ends->format('U')) - intval($starts->format('U')); return intval($ends->format('U')) - intval($starts->format('U'));
} }
@ -635,18 +661,103 @@ class Application_Model_ShowInstance {
return $returnStr; return $returnStr;
} }
public static function getContentCount($p_start, $p_end)
{
$sql = <<<SQL
SELECT instance_id,
count(*) AS instance_count
FROM cc_schedule
WHERE ends > :p_start::TIMESTAMP
AND starts < :p_end::TIMESTAMP
GROUP BY instance_id
SQL;
$counts = Application_Common_Database::prepareAndExecute($sql, array(
':p_start' => $p_start->format("Y-m-d G:i:s"),
':p_end' => $p_end->format("Y-m-d G:i:s"))
, 'all');
$real_counts = array();
foreach ($counts as $c) {
$real_counts[$c['instance_id']] = $c['instance_count'];
}
return $real_counts;
}
public function showEmpty()
{
$sql = <<<SQL
SELECT s.starts
FROM cc_schedule AS s
WHERE s.instance_id = :instance_id
AND s.playout_status >= 0
AND ((s.stream_id IS NOT NULL)
OR (s.file_id IS NOT NULL)) LIMIT 1
SQL;
# TODO : use prepareAndExecute properly
$res = Application_Common_Database::prepareAndExecute($sql,
array( ':instance_id' => $this->_instanceId ), 'all' );
# TODO : A bit retarded. fix this later
foreach ($res as $r) {
return false;
}
return true;
}
public function getShowListContent() public function getShowListContent()
{ {
$con = Propel::getConnection(); $con = Propel::getConnection();
$sql = "SELECT * $sql = <<<SQL
FROM (cc_schedule AS s LEFT JOIN cc_files AS f ON f.id = s.file_id) SELECT *
WHERE s.instance_id = '{$this->_instanceId}' AND s.playout_status >= 0 FROM (
ORDER BY starts"; (SELECT s.starts,
0::INTEGER as type ,
f.id AS item_id,
f.track_title,
f.album_title AS album,
f.genre AS genre,
f.length AS length,
f.artist_name AS creator,
f.file_exists AS EXISTS,
f.filepath AS filepath,
f.mime AS mime
FROM cc_schedule AS s
LEFT JOIN cc_files AS f ON f.id = s.file_id
WHERE s.instance_id = :instance_id1
AND s.playout_status >= 0
AND s.file_id IS NOT NULL)
UNION
(SELECT s.starts,
1::INTEGER as type,
ws.id AS item_id,
(ws.name || ': ' || ws.url) AS title,
null AS album,
null AS genre,
ws.length AS length,
sub.login AS creator,
't'::boolean AS EXISTS,
ws.url AS filepath,
ws.mime as mime
FROM cc_schedule AS s
LEFT JOIN cc_webstream AS ws ON ws.id = s.stream_id
LEFT JOIN cc_subjs AS sub ON ws.creator_id = sub.id
WHERE s.instance_id = :instance_id2
AND s.playout_status >= 0
AND s.stream_id IS NOT NULL)) AS temp
ORDER BY starts;
SQL;
//Logging::log($sql); $stmt = $con->prepare($sql);
$stmt->execute(array(
$results = $con->query($sql)->fetchAll(); ':instance_id1' => $this->_instanceId,
':instance_id2' => $this->_instanceId
));
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as &$row) { foreach ($results as &$row) {
@ -654,8 +765,10 @@ class Application_Model_ShowInstance {
$dt->setTimezone(new DateTimeZone(date_default_timezone_get())); $dt->setTimezone(new DateTimeZone(date_default_timezone_get()));
$row["starts"] = $dt->format("Y-m-d H:i:s"); $row["starts"] = $dt->format("Y-m-d H:i:s");
$formatter = new LengthFormatter($row["clip_length"]); if (isset($row['length'])) {
$row["clip_length"] = $formatter->format(); $formatter = new LengthFormatter($row["length"]);
$row["length"] = $formatter->format();
}
} }
@ -667,19 +780,22 @@ class Application_Model_ShowInstance {
$con = Propel::getConnection(); $con = Propel::getConnection();
$sql = "SELECT ends FROM cc_schedule " $sql = "SELECT ends FROM cc_schedule "
."WHERE instance_id = {$this->_instanceId} " ."WHERE instance_id = :instanceId"
."ORDER BY ends DESC " ."ORDER BY ends DESC "
."LIMIT 1"; ."LIMIT 1";
$query = $con->query($sql)->fetchColumn(0); $query = Application_Common_Database::prepareAndExecute( $sql,
return ($query !== false) ? $query : NULL; array(':instanceId' => $this->_instanceId), 'column');
return ($query !== false) ? $query : null;
} }
public function getShowEndGapTime(){ public function getShowEndGapTime()
{
$showEnd = $this->getShowInstanceEnd(); $showEnd = $this->getShowInstanceEnd();
$lastItemEnd = $this->getLastAudioItemEnd(); $lastItemEnd = $this->getLastAudioItemEnd();
if (is_null($lastItemEnd)){ if (is_null($lastItemEnd)) {
$lastItemEnd = $this->getShowInstanceStart(); $lastItemEnd = $this->getShowInstanceStart();
} }
@ -689,101 +805,92 @@ class Application_Model_ShowInstance {
return ($diff < 0) ? 0 : $diff; return ($diff < 0) ? 0 : $diff;
} }
public static function GetLastShowInstance($p_timeNow){ public static function GetLastShowInstance($p_timeNow)
global $CC_CONFIG; {
$con = Propel::getConnection(); $sql = <<<SQL
SELECT si.id
FROM cc_show_instances si
WHERE si.ends < :timeNow::TIMESTAMP
AND si.modified_instance = 'f'
ORDER BY si.ends DESC LIMIT 1;
SQL;
$id = Application_Common_Database( $sql, array(
':timeNow' => $p_timeNow ), 'column' );
$sql = "SELECT si.id" return ($id ? new Application_Model_ShowInstance($id) : null );
." FROM $CC_CONFIG[showInstances] si"
." WHERE si.ends < TIMESTAMP '$p_timeNow'"
." AND si.modified_instance = 'f'"
." ORDER BY si.ends DESC"
." LIMIT 1";
$id = $con->query($sql)->fetchColumn(0);
if ($id) {
return new Application_Model_ShowInstance($id);
} else {
return null;
}
} }
public static function GetCurrentShowInstance($p_timeNow) public static function GetCurrentShowInstance($p_timeNow)
{ {
global $CC_CONFIG;
$con = Propel::getConnection();
/* Orderby si.starts descending, because in some cases /* Orderby si.starts descending, because in some cases
* we can have multiple shows overlapping each other. In * we can have multiple shows overlapping each other. In
* this case, the show that started later is the one that * this case, the show that started later is the one that
* is actually playing, and so this is the one we want. * is actually playing, and so this is the one we want.
*/ */
$sql = "SELECT si.id" $sql = <<<SQL
." FROM $CC_CONFIG[showInstances] si" SELECT si.id
." WHERE si.starts <= TIMESTAMP '$p_timeNow'" FROM cc_show_instances si
." AND si.ends > TIMESTAMP '$p_timeNow'" WHERE si.starts <= :timeNow1::TIMESTAMP
." AND si.modified_instance = 'f'" AND si.ends > :timeNow2::TIMESTAMP
." ORDER BY si.starts DESC" AND si.modified_instance = 'f'
." LIMIT 1"; ORDER BY si.starts DESC LIMIT 1
SQL;
$id = $con->query($sql)->fetchColumn(0); $id = Application_Common_Database( $sql, array(
if ($id) { ':timeNow1' => $p_timeNow,
return new Application_Model_ShowInstance($id); ':timeNow2' => $p_timeNow ), 'column');
} else {
return null; return ( $id ? new Application_Model_ShowInstance($id) : null );
}
} }
public static function GetNextShowInstance($p_timeNow) public static function GetNextShowInstance($p_timeNow)
{ {
global $CC_CONFIG; $sql = <<<SQL
$con = Propel::getConnection(); SELECT si.id
FROM cc_show_instances si
$sql = "SELECT si.id" WHERE si.starts > :timeNow::TIMESTAMP
." FROM $CC_CONFIG[showInstances] si" AND si.modified_instance = 'f'
." WHERE si.starts > TIMESTAMP '$p_timeNow'" ORDER BY si.starts
." AND si.modified_instance = 'f'" LIMIT 1
." ORDER BY si.starts" SQL;
." LIMIT 1"; $id = Application_Common_Database::prepareAndExecute( $sql,
array( 'timeNow' => $p_timeNow ), 'column' );
$id = $con->query($sql)->fetchColumn(0); return ( $id ? new Application_Model_ShowInstance($id) : null );
if ($id) {
return new Application_Model_ShowInstance($id);
} else {
return null;
}
} }
// returns number of show instances that ends later than $day // returns number of show instances that ends later than $day
public static function GetShowInstanceCount($day) public static function GetShowInstanceCount($day)
{ {
global $CC_CONFIG; $sql = <<<SQL
$con = Propel::getConnection(); SELECT count(*) AS cnt
$sql = "SELECT count(*) as cnt FROM $CC_CONFIG[showInstances] WHERE ends < '$day'"; FROM cc_show_instances
return $con->query($sql)->fetchColumn(0); WHERE ends < :day
SQL;
return Application_Common_Database::prepareAndExecute( $sql,
array( ':day' => $day ), 'column' );
} }
// this returns end timestamp of all shows that are in the range and has live DJ set up // this returns end timestamp of all shows that are in the range and has live DJ set up
public static function GetEndTimeOfNextShowWithLiveDJ($p_startTime, $p_endTime) public static function GetEndTimeOfNextShowWithLiveDJ($p_startTime, $p_endTime)
{ {
global $CC_CONFIG; $sql = <<<SQL
$con = Propel::getConnection(); SELECT ends
FROM cc_show_instances AS si
$sql = "SELECT ends JOIN cc_show AS sh ON si.show_id = sh.id
FROM cc_show_instances as si WHERE si.ends > :startTime::TIMESTAMP
JOIN cc_show as sh ON si.show_id = sh.id AND si.ends < :endTime::TIMESTAMP
WHERE si.ends > '$p_startTime' and si.ends < '$p_endTime' and (sh.live_stream_using_airtime_auth or live_stream_using_custom_auth) AND (sh.live_stream_using_airtime_auth
ORDER BY si.ends"; OR live_stream_using_custom_auth)
ORDER BY si.ends
return $con->query($sql)->fetchAll(); SQL;
return Application_Common_Database::prepareAndExecute( $sql, array(
':startTime' => $p_startTime,
':endTime' => $p_endTime), 'all');
} }
function isRepeating(){ public function isRepeating()
if ($this->getShow()->isRepeating()){ {
return true; return $this->getShow()->isRepeating();
}else{
return false;
}
} }
} }

View file

@ -1,15 +1,16 @@
<?php <?php
require_once 'soundcloud-api/Services/Soundcloud.php'; require_once 'soundcloud-api/Services/Soundcloud.php';
class Application_Model_Soundcloud { class Application_Model_Soundcloud
{
private $_soundcloud; private $_soundcloud;
public function __construct() public function __construct()
{ {
global $CC_CONFIG; global $CC_CONFIG;
$this->_soundcloud = new Services_Soundcloud(
$this->_soundcloud = new Services_Soundcloud($CC_CONFIG['soundcloud-client-id'], $CC_CONFIG['soundcloud-client-secret']); $CC_CONFIG['soundcloud-client-id'],
$CC_CONFIG['soundcloud-client-secret']);
} }
private function getToken() private function getToken()
@ -22,19 +23,18 @@ class Application_Model_Soundcloud {
return $token; return $token;
} }
public function uploadTrack($filepath, $filename, $description, $tags=array(), $release=null, $genre=null) public function uploadTrack($filepath, $filename, $description,
$tags=array(), $release=null, $genre=null)
{ {
if($this->getToken()) if ($this->getToken()) {
{ if (count($tags)) {
if(count($tags)) {
$tags = join(" ", $tags); $tags = join(" ", $tags);
$tags = $tags." ".Application_Model_Preference::GetSoundCloudTags(); $tags = $tags." ".Application_Model_Preference::GetSoundCloudTags();
} } else {
else {
$tags = Application_Model_Preference::GetSoundCloudTags(); $tags = Application_Model_Preference::GetSoundCloudTags();
} }
$downloadable = Application_Model_Preference::GetSoundCloudDownloadbleOption() == '1'?true:false; $downloadable = Application_Model_Preference::GetSoundCloudDownloadbleOption() == '1';
$track_data = array( $track_data = array(
'track[sharing]' => 'private', 'track[sharing]' => 'private',
@ -46,13 +46,12 @@ class Application_Model_Soundcloud {
); );
if(isset($release)) { if (isset($release)) {
$release = str_replace(" ", "-", $release); $release = str_replace(" ", "-", $release);
$release = str_replace(":", "-", $release); $release = str_replace(":", "-", $release);
//YYYY-MM-DD-HH-mm-SS //YYYY-MM-DD-HH-mm-SS
$release = explode("-", $release); $release = explode("-", $release);
$track_data['track[release_year]'] = $release[0]; $track_data['track[release_year]'] = $release[0];
$track_data['track[release_month]'] = $release[1]; $track_data['track[release_month]'] = $release[1];
$track_data['track[release_day]'] = $release[2]; $track_data['track[release_day]'] = $release[2];
@ -60,8 +59,7 @@ class Application_Model_Soundcloud {
if (isset($genre) && $genre != "") { if (isset($genre) && $genre != "") {
$track_data['track[genre]'] = $genre; $track_data['track[genre]'] = $genre;
} } else {
else {
$default_genre = Application_Model_Preference::GetSoundCloudGenre(); $default_genre = Application_Model_Preference::GetSoundCloudGenre();
if ($default_genre != "") { if ($default_genre != "") {
$track_data['track[genre]'] = $default_genre; $track_data['track[genre]'] = $default_genre;
@ -84,7 +82,17 @@ class Application_Model_Soundcloud {
); );
return $response; return $response;
} else {
throw new NoSoundCloundToken();
} }
} }
public static function uploadSoundcloud($id)
{
$cmd = "/usr/lib/airtime/utils/soundcloud-uploader $id > /dev/null &";
Logging::info("Uploading soundcloud with command: $cmd");
exec($cmd);
}
} }
class NoSoundCloundToken extends Exception {}

File diff suppressed because it is too large Load diff

View file

@ -1,51 +1,65 @@
<?php <?php
class Application_Model_StreamSetting { class Application_Model_StreamSetting
{
public static function SetValue($key, $value, $type) public static function setValue($key, $value, $type)
{ {
global $CC_CONFIG;
$con = Propel::getConnection(); $con = Propel::getConnection();
$key = pg_escape_string($key);
$value = pg_escape_string($value);
// Check if key already exists // Check if key already exists
$sql = "SELECT COUNT(*) FROM cc_stream_setting" $sql = "SELECT COUNT(*) FROM cc_stream_setting"
." WHERE keyname = '$key'"; ." WHERE keyname = :key";
$result = $con->query($sql)->fetchColumn(0); $stmt = $con->prepare($sql);
$stmt->bindParam(':key', $key);
if ($stmt->execute()) {
$result = $stmt->fetchColumn(0);
} else {
$msg = implode(',', $stmt->errorInfo());
throw new Exception("Error: $msg");
}
if ($result == 1) { if ($result == 1) {
$sql = "UPDATE cc_stream_setting" $sql = "UPDATE cc_stream_setting"
." SET value = '$value', type='$type'" ." SET value = :value, type = :type"
." WHERE keyname = '$key'"; ." WHERE keyname = :key";
} else { } else {
$sql = "INSERT INTO cc_stream_setting (keyname, value, type)" $sql = "INSERT INTO cc_stream_setting (keyname, value, type)"
." VALUES ('$key', '$value', '$type')"; ." VALUES (:key, :value, :type)";
} }
return $con->exec($sql); $stmt = $con->prepare($sql);
$stmt->bindParam(':key', $key);
$stmt->bindParam(':value', $value);
$stmt->bindParam(':type', $type);
if ($stmt->execute()) {
//do nothing
} else {
$msg = implode(',', $stmt->errorInfo());
throw new Exception("Error: $msg");
}
} }
public static function GetValue($key) public static function getValue($key)
{ {
global $CC_CONFIG;
$con = Propel::getConnection(); $con = Propel::getConnection();
//Check if key already exists //Check if key already exists
$sql = "SELECT COUNT(*) FROM cc_stream_setting"
." WHERE keyname = '$key'";
$result = $con->query($sql)->fetchColumn(0);
if ($result == 0)
return "";
else {
$sql = "SELECT value FROM cc_stream_setting" $sql = "SELECT value FROM cc_stream_setting"
." WHERE keyname = '$key'"; ." WHERE keyname = :key";
$result = $con->query($sql)->fetchColumn(0); $stmt = $con->prepare($sql);
return ($result !== false) ? $result : NULL; $stmt->bindParam(':key', $key);
if ($stmt->execute()) {
$result = $stmt->fetchColumn(0);
} else {
$msg = implode(',', $stmt->errorInfo());
throw new Exception("Error: $msg");
} }
return $result ? $result : "";
} }
/* Returns the id's of all streams that are enabled in an array. An /* Returns the id's of all streams that are enabled in an array. An
@ -65,7 +79,7 @@ class Application_Model_StreamSetting {
$ids[] = substr($row["keyname"], 0, strpos($row["keyname"], "_")); $ids[] = substr($row["keyname"], 0, strpos($row["keyname"], "_"));
} }
//Logging::log(print_r($ids, true)); //Logging::info(print_r($ids, true));
return $ids; return $ids;
} }
@ -92,11 +106,20 @@ class Application_Model_StreamSetting {
public static function getStreamData($p_streamId) public static function getStreamData($p_streamId)
{ {
$con = Propel::getConnection(); $con = Propel::getConnection();
$streamId = pg_escape_string($p_streamId);
$sql = "SELECT * " $sql = "SELECT * "
."FROM cc_stream_setting " ."FROM cc_stream_setting "
."WHERE keyname LIKE '${p_streamId}_%'"; ."WHERE keyname LIKE '{$streamId}_%'";
$stmt = $con->prepare($sql);
if ($stmt->execute()) {
$rows = $stmt->fetchAll();
} else {
$msg = implode(',', $stmt->errorInfo());
throw new Exception("Error: $msg");
}
$rows = $con->query($sql)->fetchAll();
$data = array(); $data = array();
foreach ($rows as $row) { foreach ($rows as $row) {
@ -120,30 +143,51 @@ class Application_Model_StreamSetting {
foreach ($rows as $r) { foreach ($rows as $r) {
if ($r['keyname'] == 'master_live_stream_port') { if ($r['keyname'] == 'master_live_stream_port') {
$exists['master_live_stream_port'] = true; $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; $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; $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; $exists['dj_live_stream_mp'] = true;
} }
} }
if (!isset($exists["master_live_stream_port"])) { if (!isset($exists["master_live_stream_port"])) {
$rows[] = (array("keyname" =>"master_live_stream_port", "value"=>self::GetMasterLiveSteamPort(), "type"=>"integer")); $rows[] = array("keyname" =>"master_live_stream_port",
"value"=>self::getMasterLiveStreamPort(),
"type"=>"integer");
} }
if (!isset($exists["master_live_stream_mp"])) { if (!isset($exists["master_live_stream_mp"])) {
$rows[] = (array("keyname" =>"master_live_stream_mp", "value"=>self::GetMasterLiveSteamMountPoint(), "type"=>"string")); $rows[] = array("keyname" =>"master_live_stream_mp",
"value"=>self::getMasterLiveStreamMountPoint(),
"type"=>"string");
} }
if (!isset($exists["dj_live_stream_port"])) { if (!isset($exists["dj_live_stream_port"])) {
$rows[] = (array("keyname" =>"dj_live_stream_port", "value"=>self::GetDJLiveSteamPort(), "type"=>"integer")); $rows[] = array("keyname" =>"dj_live_stream_port",
"value"=>self::getDjLiveStreamPort(),
"type"=>"integer");
} }
if (!isset($exists["dj_live_stream_mp"])) { if (!isset($exists["dj_live_stream_mp"])) {
$rows[] = (array("keyname" =>"dj_live_stream_mp", "value"=>self::GetDJLiveSteamMountPoint(), "type"=>"string")); $rows[] = array("keyname" =>"dj_live_stream_mp",
"value"=>self::getDjLiveStreamMountPoint(),
"type"=>"string");
} }
return $rows; return $rows;
} }
private static function saveStreamSetting($key, $value)
{
$stream_setting = CcStreamSettingQuery::create()->filterByDbKeyName($key)->findOne();
if (is_null($stream_setting)) {
throw new Exception("Keyname $key does not exist!");
}
$stream_setting->setDbValue($value);
$stream_setting->save();
}
/* /*
* function that take all the information of stream and sets them. * function that take all the information of stream and sets them.
* This is used by stream setting via UI. * This is used by stream setting via UI.
@ -153,31 +197,23 @@ class Application_Model_StreamSetting {
*/ */
public static function setStreamSetting($data) public static function setStreamSetting($data)
{ {
$con = Propel::getConnection(); foreach ($data as $key => $d) {
foreach ($data as $key=>$d) {
if ($key == "output_sound_device" || $key == "icecast_vorbis_metadata") { if ($key == "output_sound_device" || $key == "icecast_vorbis_metadata") {
$v = $d == 1?"true":"false"; $v = ($d == 1) ? "true" : "false";
$sql = "UPDATE cc_stream_setting SET value='$v' WHERE keyname='$key'";
$con->exec($sql); self::saveStreamSetting($key, $v);
} else if ($key == "output_sound_device_type") { } elseif ($key == "output_sound_device_type") {
$sql = "UPDATE cc_stream_setting SET value='$d' WHERE keyname='$key'"; self::saveStreamSetting($key, $d);
$con->exec($sql); } elseif (is_array($d)) {
} else if (is_array($d)) {
$temp = explode('_', $key); $temp = explode('_', $key);
$prefix = $temp[0]; $prefix = $temp[0];
foreach ($d as $k=>$v) { foreach ($d as $k => $v) {
$keyname = $prefix . "_" . $k; $keyname = $prefix . "_" . $k;
if ($k == 'enable') { if ($k == 'enable') {
$v = $d['enable'] == 1 ? 'true' : 'false'; $v = $d['enable'] == 1 ? 'true' : 'false';
} }
$v = trim($v); $v = trim($v);
self::saveStreamSetting($keyname, $v);
#escape double single quotes CC-3926
$v = str_replace("'", "''", $v);
$sql = "UPDATE cc_stream_setting SET value='$v' WHERE keyname='$keyname'";
$con->exec($sql);
} }
} }
} }
@ -187,8 +223,11 @@ class Application_Model_StreamSetting {
* Sets indivisual stream setting. * Sets indivisual stream setting.
* *
* $data - data array. $data is []. * $data - data array. $data is [].
* TODO: Make this SQL a prepared statement!
*
* Do not remove this function. It is called by airtime-system.php
*/ */
public static function setIndivisualStreamSetting($data) public static function setIndividualStreamSetting($data)
{ {
$con = Propel::getConnection(); $con = Propel::getConnection();
@ -198,6 +237,7 @@ class Application_Model_StreamSetting {
} }
} }
/* /*
* Stores liquidsoap status if $boot_time > save time. * Stores liquidsoap status if $boot_time > save time.
* save time is the time that user clicked save on stream setting page * save time is the time that user clicked save on stream setting page
@ -210,17 +250,37 @@ class Application_Model_StreamSetting {
if ($boot_time == null || $boot_time > $update_time) { if ($boot_time == null || $boot_time > $update_time) {
$keyname = "s".$stream_id."_liquidsoap_error"; $keyname = "s".$stream_id."_liquidsoap_error";
$sql = "SELECT COUNT(*) FROM cc_stream_setting" $sql = "SELECT COUNT(*) FROM cc_stream_setting"
." WHERE keyname = '$keyname'"; ." WHERE keyname = :keyname";
$result = $con->query($sql)->fetchColumn(0);
$stmt = $con->prepare($sql);
$stmt->bindParam(':keyname', $keyname);
if ($stmt->execute()) {
$result= $stmt->fetchColumn(0);
} else {
$msg = implode(',', $stmt->errorInfo());
throw new Exception("Error: $msg");
}
if ($result == 1) { if ($result == 1) {
$sql = "UPDATE cc_stream_setting" $sql = "UPDATE cc_stream_setting"
." SET value = '$msg'" ." SET value = :msg"
." WHERE keyname = '$keyname'"; ." WHERE keyname = :keyname";
} else { } else {
$sql = "INSERT INTO cc_stream_setting (keyname, value, type)" $sql = "INSERT INTO cc_stream_setting (keyname, value, type)"
." VALUES ('$keyname', '$msg', 'string')"; ." VALUES (:keyname, :msg, 'string')";
}
$stmt = $con->prepare($sql);
$stmt->bindParam(':keyname', $keyname);
$stmt->bindParam(':msg', $msg);
if ($stmt->execute()) {
//do nothing
} else {
$msg = implode(',', $stmt->errorInfo());
throw new Exception("Error: $msg");
} }
$res = $con->exec($sql);
} }
} }
@ -230,10 +290,19 @@ class Application_Model_StreamSetting {
$keyname = "s".$stream_id."_liquidsoap_error"; $keyname = "s".$stream_id."_liquidsoap_error";
$sql = "SELECT value FROM cc_stream_setting" $sql = "SELECT value FROM cc_stream_setting"
." WHERE keyname = '$keyname'"; ." WHERE keyname = :keyname";
$result = $con->query($sql)->fetchColumn(0);
return ($result !== false) ? $result : NULL; $stmt = $con->prepare($sql);
$stmt->bindParam(':keyname', $keyname);
if ($stmt->execute()) {
$result= $stmt->fetchColumn(0);
} else {
$msg = implode(',', $stmt->errorInfo());
throw new Exception("Error: $msg");
}
return ($result !== false) ? $result : null;
} }
public static function getStreamEnabled($stream_id) public static function getStreamEnabled($stream_id)
@ -242,14 +311,19 @@ class Application_Model_StreamSetting {
$keyname = "s" . $stream_id . "_enable"; $keyname = "s" . $stream_id . "_enable";
$sql = "SELECT value FROM cc_stream_setting" $sql = "SELECT value FROM cc_stream_setting"
." WHERE keyname = '$keyname'"; ." WHERE keyname = :keyname";
$result = $con->query($sql)->fetchColumn(0);
if ($result == 'false') { $stmt = $con->prepare($sql);
$result = false; $stmt->bindParam(':keyname', $keyname);
if ($stmt->execute()) {
$result= $stmt->fetchColumn(0);
} else { } else {
$result = true; $msg = implode(',', $stmt->errorInfo());
throw new Exception("Error: $msg");
} }
return $result;
return ($result != 'false');
} }
/* /*
@ -264,12 +338,22 @@ class Application_Model_StreamSetting {
$enabled_stream = self::getEnabledStreamIds(); $enabled_stream = self::getEnabledStreamIds();
foreach ($enabled_stream as $stream) { foreach ($enabled_stream as $stream) {
$keys = "'".$stream."_output', "."'".$stream."_type', "."'".$stream."_bitrate', "."'".$stream."_host'"; $keys = array("{$stream}_output", "{$stream}_type", "{$stream}_bitrate", "{$stream}_host");
$key_csv = implode(',', $keys);
$sql = "SELECT keyname, value FROM cc_stream_setting" $sql = "SELECT keyname, value FROM cc_stream_setting"
." WHERE keyname IN ($keys)"; ." WHERE keyname IN (:key_csv)";
$stmt = $con->prepare($sql);
$stmt->bindParam(':key_csv', $key_csv);
if ($stmt->execute()) {
$rows = $stmt->fetchAll();
} else {
$msg = implode(',', $stmt->errorInfo());
throw new Exception("Error: $msg");
}
$rows = $con->query($sql)->fetchAll();
$info = array(); $info = array();
foreach ($rows as $r) { foreach ($rows as $r) {
$temp = explode("_", $r['keyname']); $temp = explode("_", $r['keyname']);
@ -277,38 +361,47 @@ class Application_Model_StreamSetting {
$out[$stream] = $info; $out[$stream] = $info;
} }
} }
return $out; return $out;
} }
public static function SetMasterLiveSteamPort($value){ public static function setMasterLiveStreamPort($value)
self::SetValue("master_live_stream_port", $value, "integer"); {
self::setValue("master_live_stream_port", $value, "integer");
} }
public static function GetMasterLiveSteamPort(){ public static function getMasterLiveStreamPort()
return self::GetValue("master_live_stream_port"); {
return self::getValue("master_live_stream_port");
} }
public static function SetMasterLiveSteamMountPoint($value){ public static function setMasterLiveStreamMountPoint($value)
self::SetValue("master_live_stream_mp", $value, "string"); {
self::setValue("master_live_stream_mp", $value, "string");
} }
public static function GetMasterLiveSteamMountPoint(){ public static function getMasterLiveStreamMountPoint()
return self::GetValue("master_live_stream_mp"); {
return self::getValue("master_live_stream_mp");
} }
public static function SetDJLiveSteamPort($value){ public static function setDjLiveStreamPort($value)
self::SetValue("dj_live_stream_port", $value, "integer"); {
self::setValue("dj_live_stream_port", $value, "integer");
} }
public static function GetDJLiveSteamPort(){ public static function getDjLiveStreamPort()
return self::GetValue("dj_live_stream_port"); {
return self::getValue("dj_live_stream_port");
} }
public static function SetDJLiveSteamMountPoint($value){ public static function setDjLiveStreamMountPoint($value)
self::SetValue("dj_live_stream_mp", $value, "string"); {
self::setValue("dj_live_stream_mp", $value, "string");
} }
public static function GetDJLiveSteamMountPoint(){ public static function getDjLiveStreamMountPoint()
return self::GetValue("dj_live_stream_mp"); {
return self::getValue("dj_live_stream_mp");
} }
} }

View file

@ -14,106 +14,10 @@ define('ALIBERR_BADSMEMB', 21);
* @copyright 2010 Sourcefabric O.P.S. * @copyright 2010 Sourcefabric O.P.S.
* @license http://www.gnu.org/licenses/gpl.txt * @license http://www.gnu.org/licenses/gpl.txt
*/ */
class Application_Model_Subjects { class Application_Model_Subjects
{
/* ======================================================= public methods */ /* ======================================================= public methods */
/**
* Check login and password
*
* @param string $login
* @param string $pass
* optional
* @return boolean|int|PEAR_Error
*/
public static function Authenticate($login, $pass='')
{
global $CC_CONFIG;
$con = Propel::getConnection();
$cpass = md5($pass);
$sql = "SELECT id FROM ".$CC_CONFIG['subjTable']
." WHERE login='$login' AND pass='$cpass' AND type='U'"
." LIMIT 1";
$query = $con->query($sql)->fetchColumn(0);
return $query;
}
/**
* Change user password
*
* @param string $login
* @param string $oldpass
* old password (optional for 'superuser mode')
* @param string $pass
* optional
* @param boolean $passenc
* optional, password already encrypted if true
* @return boolean|PEAR_Error
*/
public static function Passwd($login, $oldpass=null, $pass='', $passenc=FALSE)
{
global $CC_CONFIG;
$con = Propel::getConnection();
if (!$passenc) {
$cpass = md5($pass);
} else {
$cpass = $pass;
}
if (!is_null($oldpass)) {
$oldcpass = md5($oldpass);
$oldpCond = "AND pass='$oldcpass'";
} else {
$oldpCond = '';
}
$sql = "UPDATE ".$CC_CONFIG['subjTable']." SET pass='$cpass'"
." WHERE login='$login' $oldpCond AND type='U'";
$con->exec($sql);
return TRUE;
}
/* --------------------------------------------------------------- groups */
/* --------------------------------------------------------- info methods */
/**
* Get subject id from login
*
* @param string $login
* @return int|false
*/
public static function GetSubjId($login)
{
global $CC_CONFIG;
$con = Propel::getConnection();
$sql = "SELECT id FROM ".$CC_CONFIG['subjTable']
." WHERE login='$login'";
$query = $con->query($sql)->fetchColumn(0);
return ($query !== false) ? $query : NULL;
}
/**
* Return true if uid is direct member of gid
*
* @param int $uid
* local user id
* @param int $gid
* local group id
* @return boolean
*/
public static function IsMemberOf($uid, $gid)
{
global $CC_CONFIG;
$con = Propel::getConnection();
$sql = "SELECT count(*) as cnt"
." FROM ".$CC_CONFIG['smembTable']
." WHERE uid='$uid' AND gid='$gid'";
$res = $con->query($sql)->fetchColumn(0);
return (intval($res) > 0);
}
public static function increaseLoginAttempts($login) public static function increaseLoginAttempts($login)
{ {
global $CC_CONFIG; global $CC_CONFIG;
@ -121,6 +25,7 @@ class Application_Model_Subjects {
$sql = "UPDATE ".$CC_CONFIG['subjTable']." SET login_attempts = login_attempts+1" $sql = "UPDATE ".$CC_CONFIG['subjTable']." SET login_attempts = login_attempts+1"
." WHERE login='$login'"; ." WHERE login='$login'";
$res = $con->exec($sql); $res = $con->exec($sql);
return (intval($res) > 0); return (intval($res) > 0);
} }
@ -131,7 +36,8 @@ class Application_Model_Subjects {
$sql = "UPDATE ".$CC_CONFIG['subjTable']." SET login_attempts = '0'" $sql = "UPDATE ".$CC_CONFIG['subjTable']." SET login_attempts = '0'"
." WHERE login='$login'"; ." WHERE login='$login'";
$res = $con->exec($sql); $res = $con->exec($sql);
return TRUE;
return true;
} }
public static function getLoginAttempts($login) public static function getLoginAttempts($login)
@ -140,8 +46,8 @@ class Application_Model_Subjects {
$con = Propel::getConnection(); $con = Propel::getConnection();
$sql = "SELECT login_attempts FROM ".$CC_CONFIG['subjTable']." WHERE login='$login'"; $sql = "SELECT login_attempts FROM ".$CC_CONFIG['subjTable']." WHERE login='$login'";
$res = $con->query($sql)->fetchColumn(0); $res = $con->query($sql)->fetchColumn(0);
return ($res !== false) ? $res : 0; return ($res !== false) ? $res : 0;
} }
} // class Subjects } // class Subjects

View file

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

View file

@ -1,220 +1,290 @@
<?php <?php
define('UTYPE_HOST', 'H'); define('UTYPE_HOST' , 'H');
define('UTYPE_ADMIN', 'A'); define('UTYPE_ADMIN' , 'A');
define('UTYPE_GUEST', 'G'); define('UTYPE_GUEST' , 'G');
define('UTYPE_PROGRAM_MANAGER', 'P'); define('UTYPE_PROGRAM_MANAGER' , 'P');
class Application_Model_User {
class Application_Model_User
{
private $_userInstance; private $_userInstance;
public function __construct($userId) public function __construct($userId)
{ {
if (empty($userId)){ if (empty($userId)) {
$this->_userInstance = $this->createUser(); $this->_userInstance = $this->createUser();
} } else {
else {
$this->_userInstance = CcSubjsQuery::create()->findPK($userId); $this->_userInstance = CcSubjsQuery::create()->findPK($userId);
if (is_null($this->_userInstance)){ if (is_null($this->_userInstance)) {
throw new Exception(); throw new Exception();
} }
} }
} }
public function getId() { public function getId()
{
return $this->_userInstance->getDbId(); return $this->_userInstance->getDbId();
} }
public function isGuest() { public function isGuest()
{
return $this->getType() == UTYPE_GUEST; return $this->getType() == UTYPE_GUEST;
} }
public function isHost($showId) { public function isHostOfShow($showId)
return $this->isUserType(UTYPE_HOST, $showId); {
$userId = $this->_userInstance->getDbId();
return CcShowHostsQuery::create()
->filterByDbShow($showId)
->filterByDbHost($userId)->count() > 0;
} }
public function isPM() { public function isHost()
{
return $this->isUserType(UTYPE_HOST);
}
public function isPM()
{
return $this->isUserType(UTYPE_PROGRAM_MANAGER); return $this->isUserType(UTYPE_PROGRAM_MANAGER);
} }
public function isAdmin() { public function isAdmin()
{
return $this->isUserType(UTYPE_ADMIN); return $this->isUserType(UTYPE_ADMIN);
} }
public function canSchedule($p_showId) { public function canSchedule($p_showId)
{
$type = $this->getType(); $type = $this->getType();
$result = false; $result = false;
if ( $type === UTYPE_ADMIN || if ($type === UTYPE_ADMIN ||
$type === UTYPE_PROGRAM_MANAGER || $type === UTYPE_PROGRAM_MANAGER ||
CcShowHostsQuery::create()->filterByDbShow($p_showId)->filterByDbHost($this->getId())->count() > 0 ) self::isHostOfShow($p_showId)) {
{
$result = true; $result = true;
} }
return $result; return $result;
} }
public function isUserType($type, $showId=''){ // TODO : refactor code to only accept arrays for isUserType and
if(is_array($type)){ // simplify code even further
$result = false; public function isUserType($type)
foreach($type as $t){ {
switch($t){ if (!is_array($type)) {
case UTYPE_ADMIN: $type = array($type);
$result = $this->_userInstance->getDbType() === 'A';
break;
case UTYPE_HOST:
$userId = $this->_userInstance->getDbId();
$result = CcShowHostsQuery::create()->filterByDbShow($showId)->filterByDbHost($userId)->count() > 0;
break;
case UTYPE_PROGRAM_MANAGER:
$result = $this->_userInstance->getDbType() === 'P';
break;
}
if($result){
return $result;
}
}
}else{
switch($type){
case UTYPE_ADMIN:
return $this->_userInstance->getDbType() === 'A';
case UTYPE_HOST:
$userId = $this->_userInstance->getDbId();
return CcShowHostsQuery::create()->filterByDbShow($showId)->filterByDbHost($userId)->count() > 0;
case UTYPE_PROGRAM_MANAGER:
return $this->_userInstance->getDbType() === 'P';
}
} }
$real_type = $this->_userInstance->getDbType();
return in_array($real_type, $type);
} }
public function setLogin($login){ public function setLogin($login)
{
$user = $this->_userInstance; $user = $this->_userInstance;
$user->setDbLogin($login); $user->setDbLogin($login);
} }
public function setPassword($password){ public function setPassword($password)
{
$user = $this->_userInstance; $user = $this->_userInstance;
$user->setDbPass(md5($password)); $user->setDbPass(md5($password));
} }
public function setFirstName($firstName){ public function setFirstName($firstName)
{
$user = $this->_userInstance; $user = $this->_userInstance;
$user->setDbFirstName($firstName); $user->setDbFirstName($firstName);
} }
public function setLastName($lastName){ public function setLastName($lastName)
{
$user = $this->_userInstance; $user = $this->_userInstance;
$user->setDbLastName($lastName); $user->setDbLastName($lastName);
} }
public function setType($type){ public function setType($type)
{
$user = $this->_userInstance; $user = $this->_userInstance;
$user->setDbType($type); $user->setDbType($type);
} }
public function setEmail($email){ public function setEmail($email)
{
$user = $this->_userInstance; $user = $this->_userInstance;
$user->setDbEmail(strtolower($email)); $user->setDbEmail(strtolower($email));
} }
public function setCellPhone($cellPhone){ public function setCellPhone($cellPhone)
{
$user = $this->_userInstance; $user = $this->_userInstance;
$user->setDbCellPhone($cellPhone); $user->setDbCellPhone($cellPhone);
} }
public function setSkype($skype){ public function setSkype($skype)
{
$user = $this->_userInstance; $user = $this->_userInstance;
$user->setDbSkypeContact($skype); $user->setDbSkypeContact($skype);
} }
public function setJabber($jabber){ public function setJabber($jabber)
{
$user = $this->_userInstance; $user = $this->_userInstance;
$user->setDbJabberContact($jabber); $user->setDbJabberContact($jabber);
} }
public function getLogin(){ public function getLogin()
{
$user = $this->_userInstance; $user = $this->_userInstance;
return $user->getDbLogin(); return $user->getDbLogin();
} }
public function getPassword(){ public function getPassword()
{
$user = $this->_userInstance; $user = $this->_userInstance;
return $user->getDbPass(); return $user->getDbPass();
} }
public function getFirstName(){ public function getFirstName()
{
$user = $this->_userInstance; $user = $this->_userInstance;
return $user->getDbFirstName(); return $user->getDbFirstName();
} }
public function getLastName(){ public function getLastName()
{
$user = $this->_userInstance; $user = $this->_userInstance;
return $user->getDbLastName(); return $user->getDbLastName();
} }
public function getType(){ public function getType()
{
$user = $this->_userInstance; $user = $this->_userInstance;
return $user->getDbType(); return $user->getDbType();
} }
public function getEmail(){ public function getEmail()
{
$user = $this->_userInstance; $user = $this->_userInstance;
return $user->getDbEmail(); return $user->getDbEmail();
} }
public function getCellPhone(){ public function getCellPhone()
{
$user = $this->_userInstance; $user = $this->_userInstance;
return $user->getDbCellPhone(); return $user->getDbCellPhone();
} }
public function getSkype(){ public function getSkype()
{
$user = $this->_userInstance; $user = $this->_userInstance;
return $user->getDbSkypeContact(); return $user->getDbSkypeContact();
} }
public function getJabber(){ public function getJabber()
{
$user = $this->_userInstance; $user = $this->_userInstance;
return $user->getDbJabberContact(); return $user->getDbJabberContact();
} }
public function save(){ public function save()
{
$this->_userInstance->save(); $this->_userInstance->save();
} }
public function delete(){ public function delete()
if (!$this->_userInstance->isDeleted()) {
if (!$this->_userInstance->isDeleted()) {
$this->_userInstance->delete(); $this->_userInstance->delete();
} }
}
public function getOwnedFiles()
{
$user = $this->_userInstance;
// do we need a find call at the end here?
return $user->getCcFilessRelatedByDbOwnerId();
}
private function createUser() { public function donateFilesTo($user) // $user is object not user id
{
$my_files = $this->getOwnedFiles();
foreach ($my_files as $file) {
$file->reassignTo($user);
}
}
public function deleteAllFiles()
{
$my_files = $this->getOwnedFiles();
foreach ($files as $file) {
$file->delete();
}
}
private function createUser()
{
$user = new CcSubjs(); $user = new CcSubjs();
return $user; return $user;
} }
public static function getUsers($type, $search=NULL) public static function getUsersOfType($type)
{
return CcSubjsQuery::create()->filterByDbType($type)->find();
}
public static function getFirstAdmin() {
$admins = Application_Model_User::getUsersOfType('A');
if (count($admins) > 0) { // found admin => pick first one
return $admins[0];
} else {
Logging::warn("Warning. no admins found in database");
return null;
}
}
public static function getFirstAdminId()
{
$admin = self::getFirstAdmin();
if ($admin) {
return $admin->getDbId();
} else {
return null;
}
}
public static function getUsers(array $type, $search=null)
{ {
$con = Propel::getConnection(); $con = Propel::getConnection();
$sql_gen = "SELECT login AS value, login AS label, id as index FROM cc_subjs "; $sql_gen = "SELECT login AS value, login AS label, id as index FROM cc_subjs ";
$sql = $sql_gen; $sql = $sql_gen;
if (is_array($type)) { $types = array();
for($i=0; $i<count($type); $i++) { $params = array();
$type[$i] = "type = '{$type[$i]}'"; for ($i=0; $i<count($type); $i++) {
} $p = ":type{$i}";
$sql_type = join(" OR ", $type); $types[] = "type = $p";
} $params[$p] = $type[$i];
else {
$sql_type = "type = {$type}";
} }
$sql_type = join(" OR ", $types);
$sql = $sql_gen ." WHERE (". $sql_type.") "; $sql = $sql_gen ." WHERE (". $sql_type.") ";
if (!is_null($search)) { if (!is_null($search)) {
//need to use addslashes for 'LIKE' values
$search = addslashes($search);
$like = "login ILIKE '%{$search}%'"; $like = "login ILIKE '%{$search}%'";
$sql = $sql . " AND ".$like; $sql = $sql . " AND ".$like;
@ -222,40 +292,26 @@ class Application_Model_User {
$sql = $sql ." ORDER BY login"; $sql = $sql ." ORDER BY login";
return $con->query($sql)->fetchAll();; return Application_Common_Database::prepareAndExecute($sql, $params, "all");
} }
public static function getUserCount($type=NULL){ public static function getUserCount()
{
$con = Propel::getConnection(); $con = Propel::getConnection();
$sql = ''; $sql_gen = "SELECT count(*) AS cnt FROM cc_subjs";
$sql_gen = "SELECT count(*) AS cnt FROM cc_subjs ";
if (!isset($type)) { $query = $con->query($sql_gen)->fetchColumn(0);
$sql = $sql_gen;
} return ($query !== false) ? $query : null;
else{
if (is_array($type)) {
for ($i=0; $i<count($type); $i++) {
$type[$i] = "type = '{$type[$i]}'";
}
$sql_type = join(" OR ", $type);
}
else {
$sql_type = "type = {$type}";
} }
$sql = $sql_gen ." WHERE (". $sql_type.") "; public static function getHosts($search=null)
} {
$query = $con->query($sql)->fetchColumn(0);
return ($query !== false) ? $query : NULL;
}
public static function getHosts($search=NULL) {
return Application_Model_User::getUsers(array('H'), $search); return Application_Model_User::getUsers(array('H'), $search);
} }
public static function getUsersDataTablesInfo($datatables) { public static function getUsersDataTablesInfo($datatables)
{
$con = Propel::getConnection(CcSubjsPeer::DATABASE_NAME); $con = Propel::getConnection(CcSubjsPeer::DATABASE_NAME);
@ -273,8 +329,8 @@ class Application_Model_User {
$res = Application_Model_Datatables::findEntries($con, $displayColumns, $fromTable, $datatables); $res = Application_Model_Datatables::findEntries($con, $displayColumns, $fromTable, $datatables);
// mark record which is for the current user // mark record which is for the current user
foreach($res['aaData'] as &$record){ foreach ($res['aaData'] as &$record) {
if($record['login'] == $username){ if ($record['login'] == $username) {
$record['delete'] = "self"; $record['delete'] = "self";
} else { } else {
$record['delete'] = ""; $record['delete'] = "";
@ -284,39 +340,32 @@ class Application_Model_User {
return $res; return $res;
} }
public static function getUserData($id){ public static function getUserData($id)
$con = Propel::getConnection(); {
$sql = <<<SQL
$sql = "SELECT login, first_name, last_name, type, id, email, cell_phone, skype_contact, jabber_contact" SELECT login, first_name, last_name, type, id, email, cell_phone, skype_contact,
." FROM cc_subjs" jabber_contact
." WHERE id = $id"; FROM cc_subjs
WHERE id = :id
return $con->query($sql)->fetch(); SQL;
return Application_Common_Database::prepareAndExecute($sql, array(
":id" => $id), 'single');
} }
public static function GetUserID($login){ public static function getCurrentUser()
$user = CcSubjsQuery::create()->findOneByDbLogin($login); {
if (is_null($user)){
return -1;
} else {
return $user->getDbId();
}
}
public static function GetCurrentUser() {
$userinfo = Zend_Auth::getInstance()->getStorage()->read(); $userinfo = Zend_Auth::getInstance()->getStorage()->read();
if (is_null($userinfo)) {
if (is_null($userinfo)){
return null; return null;
} else { }
try { try {
return new self($userinfo->id); return new self($userinfo->id);
} catch (Exception $e){ } catch (Exception $e) {
//we get here if $userinfo->id is defined, but doesn't exist //we get here if $userinfo->id is defined, but doesn't exist
//in the database anymore. //in the database anymore.
Zend_Auth::getInstance()->clearIdentity(); Zend_Auth::getInstance()->clearIdentity();
return null; return null;
} }
} }
}
} }

View file

@ -0,0 +1,372 @@
<?php
class Application_Model_Webstream implements Application_Model_LibraryEditable
{
private $id;
public function __construct($webstream)
{
//TODO: hacky...
if (is_int($webstream)) {
$this->webstream = CcWebstreamQuery::create()->findPK($webstream);
if (is_null($this->webstream)) {
throw new Exception();
}
} else {
$this->webstream = $webstream;
}
}
public function getOrm()
{
return $this->webstream;
}
public function getName()
{
return $this->webstream->getDbName();
}
public function getId()
{
return $this->webstream->getDbId();
}
public function getCreatorId()
{
return $this->Webstream->getCcSubjs()->getDbId();
}
public function getLastModified($p_type)
{
return $this->webstream->getDbMtime();
}
public function getDefaultLength()
{
$dateString = $this->webstream->getDbLength();
$arr = explode(":", $dateString);
if (count($arr) == 3) {
list($hours, $min, $sec) = $arr;
$di = new DateInterval("PT{$hours}H{$min}M{$sec}S");
return $di->format("%Hh %Im");
}
return "";
}
public function getLength()
{
return $this->getDefaultLength();
}
public function getDescription()
{
return $this->webstream->getDbDescription();
}
public function getUrl()
{
return $this->webstream->getDbUrl();
}
public function getMetadata()
{
$subjs = CcSubjsQuery::create()->findPK($this->webstream->getDbCreatorId());
$username = $subjs->getDbLogin();
return array(
"name" => $this->webstream->getDbName(),
"length" => $this->webstream->getDbLength(),
"description" => $this->webstream->getDbDescription(),
"login" => $username,
"url" => $this->webstream->getDbUrl(),
);
}
public static function deleteStreams($p_ids, $p_userId)
{
$leftOver = self::streamsNotOwnedByUser($p_ids, $p_userId);
if (count($leftOver) == 0) {
CcWebstreamQuery::create()->findPKs($p_ids)->delete();
} else {
throw new Exception("Invalid user permissions");
}
}
// This function returns that are not owen by $p_user_id among $p_ids
private static function streamsNotOwnedByUser($p_ids, $p_userId)
{
$ownedByUser = CcWebstreamQuery::create()->filterByDbCreatorId($p_userId)->find()->getData();
$ownedStreams = array();
foreach ($ownedByUser as $pl) {
if (in_array($pl->getDbId(), $p_ids)) {
$ownedStreams[] = $pl->getDbId();
}
}
$leftOvers = array_diff($p_ids, $ownedStreams);
return $leftOvers;
}
public static function analyzeFormData($parameters)
{
$valid = array("length" => array(true, ''),
"url" => array(true, ''),
"name" => array(true, ''));
$di = null;
$length = $parameters["length"];
$result = preg_match("/^(?:([0-9]{1,2})h)?\s*(?:([0-9]{1,2})m)?$/", $length, $matches);
$invalid_date_interval = false;
if ($result == 1 && count($matches) == 2) {
$hours = $matches[1];
$minutes = 0;
} elseif ($result == 1 && count($matches) == 3) {
$hours = $matches[1];
$minutes = $matches[2];
} else {
$invalid_date_interval = true;
}
if (!$invalid_date_interval) {
//Due to the way our Regular Expression is set up, we could have $minutes or $hours
//not set. Do simple test here
if (!is_numeric($hours)) {
$hours = 0;
}
if (!is_numeric($minutes)) {
$minutes = 0;
}
//minutes cannot be over 59. Need to convert anything > 59 minutes into hours.
$hours += intval($minutes/60);
$minutes = $minutes%60;
$di = new DateInterval("PT{$hours}H{$minutes}M");
$totalMinutes = $di->h * 60 + $di->i;
if ($totalMinutes == 0) {
$valid['length'][0] = false;
$valid['length'][1] = 'Length needs to be greater than 0 minutes';
}
} else {
$valid['length'][0] = false;
$valid['length'][1] = 'Length should be of form "00h 00m"';
}
$url = $parameters["url"];
//simple validator that checks to make sure that the url starts with
//http(s),
//and that the domain is at least 1 letter long
$result = preg_match("/^(http|https):\/\/.+/", $url, $matches);
$mime = null;
$mediaUrl = null;
if ($result == 0) {
$valid['url'][0] = false;
$valid['url'][1] = 'URL should be of form "http://domain"';
} elseif (strlen($url) > 512) {
$valid['url'][0] = false;
$valid['url'][1] = 'URL should be 512 characters or less';
} else {
try {
list($mime, $content_length_found) = self::discoverStreamMime($url);
if (is_null($mime)) {
throw new Exception("No MIME type found for webstream.");
}
$mediaUrl = self::getMediaUrl($url, $mime, $content_length_found);
if (preg_match("/(x-mpegurl)|(xspf\+xml)|(pls\+xml)/", $mime)) {
list($mime, $content_length_found) = self::discoverStreamMime($mediaUrl);
}
} catch (Exception $e) {
$valid['url'][0] = false;
$valid['url'][1] = $e->getMessage();
}
}
$name = $parameters["name"];
if (strlen($name) == 0) {
$valid['name'][0] = false;
$valid['name'][1] = 'Webstream name cannot be empty';
}
$id = $parameters["id"];
return array($valid, $mime, $mediaUrl, $di);
}
public static function isValid($analysis)
{
foreach ($analysis as $k => $v) {
if ($v[0] === false) {
return false;
}
}
return true;
}
// TODO : Fix this interface
//This function should not be defined in the interface.
public function setMetadata($key, $val)
{
throw new Exception("Not implemented.");
}
public function setName($name)
{
$this->webstream->setDbName($name);
}
public function setLastPlayed($timestamp)
{
$this->webstream->setDbLPtime($timestamp);
$this->webstream->save();
}
private static function getUrlData($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// grab URL and pass it to the browser
//TODO: What if invalid url?
$content = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
return $content;
}
private static function getXspfUrl($url)
{
$content = self::getUrlData($url);
$dom = new DOMDocument;
//TODO: What if invalid xml?
$dom->loadXML($content);
$tracks = $dom->getElementsByTagName('track');
foreach ($tracks as $track) {
$locations = $track->getElementsByTagName('location');
foreach ($locations as $loc) {
return $loc->nodeValue;
}
}
throw new Exception("Could not parse XSPF playlist");
}
private static function getPlsUrl($url)
{
$content = self::getUrlData($url);
$ini = parse_ini_string($content, true);
if ($ini !== false && isset($ini["playlist"]) && isset($ini["playlist"]["File1"])) {
return $ini["playlist"]["File1"];
}
throw new Exception("Could not parse PLS playlist");
}
private static function getM3uUrl($url)
{
$content = self::getUrlData($url);
//split into lines:
$delim = "\n";
if (strpos($content, "\r\n") !== false) {
$delim = "\r\n";
}
$lines = explode("$delim", $content);
#$lines = preg_split('/$\R?^/m', $content);
if (count($lines) > 0) {
return $lines[0];
}
throw new Exception("Could not parse M3U playlist");
}
private static function getMediaUrl($url, $mime, $content_length_found)
{
if (preg_match("/x-mpegurl/", $mime)) {
$media_url = self::getM3uUrl($url);
} elseif (preg_match("/xspf\+xml/", $mime)) {
$media_url = self::getXspfUrl($url);
} elseif (preg_match("/pls\+xml/", $mime)) {
$media_url = self::getPlsUrl($url);
} elseif (preg_match("/(mpeg|ogg)/", $mime)) {
if ($content_length_found) {
throw new Exception("Invalid webstream - This appears to be a file download.");
}
$media_url = $url;
} else {
throw new Exception("Unrecognized stream type: $mime");
}
return $media_url;
}
private static function discoverStreamMime($url)
{
//TODO: What if invalid URL?
$headers = get_headers($url);
$mime = null;
$content_length_found = false;
foreach ($headers as $h) {
if (preg_match("/^content-type:/i", $h)) {
list(, $value) = explode(":", $h, 2);
$mime = trim($value);
}
if (preg_match("/^content-length:/i", $h)) {
$content_length_found = true;
}
}
return array($mime, $content_length_found);
}
public static function save($parameters, $mime, $mediaUrl, $di)
{
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$id = $parameters['id'];
if ($id != -1) {
$webstream = CcWebstreamQuery::create()->findPK($id);
} else {
$webstream = new CcWebstream();
}
$webstream->setDbName($parameters["name"]);
$webstream->setDbDescription($parameters["description"]);
$webstream->setDbUrl($mediaUrl);
$dblength = $di->format("%H:%I");
$webstream->setDbLength($dblength);
$webstream->setDbCreatorId($userInfo->id);
$webstream->setDbUtime(new DateTime("now", new DateTimeZone('UTC')));
$webstream->setDbMtime(new DateTime("now", new DateTimeZone('UTC')));
$ws = new Application_Model_Webstream($webstream);
$webstream->setDbMime($mime);
$webstream->save();
return $webstream->getDbId();
}
}

View file

@ -0,0 +1,100 @@
<?php
/**
* Skeleton subclass for representing a row from the 'cc_block' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
* @package propel.generator.airtime
*/
class CcBlock extends BaseCcBlock {
/**
* Get the [optionally formatted] temporal [utime] column value.
*
*
* @param string $format The date/time format string (either date()-style or strftime()-style).
* If format is NULL, then the raw DateTime object will be returned.
* @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL
* @throws PropelException - if unable to parse/validate the date/time value.
*/
public function getDbUtime($format = 'Y-m-d H:i:s')
{
if ($this->utime === null) {
return null;
}
try {
$dt = new DateTime($this->utime, new DateTimeZone("UTC"));
} catch (Exception $x) {
throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->utime, true), $x);
}
if ($format === null) {
// Because propel.useDateTimeClass is TRUE, we return a DateTime object.
return $dt;
} elseif (strpos($format, '%') !== false) {
return strftime($format, $dt->format('U'));
} else {
return $dt->format($format);
}
}
/**
* Get the [optionally formatted] temporal [mtime] column value.
*
*
* @param string $format The date/time format string (either date()-style or strftime()-style).
* If format is NULL, then the raw DateTime object will be returned.
* @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL
* @throws PropelException - if unable to parse/validate the date/time value.
*/
public function getDbMtime($format = 'Y-m-d H:i:s')
{
if ($this->mtime === null) {
return null;
}
try {
$dt = new DateTime($this->mtime, new DateTimeZone("UTC"));
} catch (Exception $x) {
throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->mtime, true), $x);
}
if ($format === null) {
// Because propel.useDateTimeClass is TRUE, we return a DateTime object.
return $dt;
} elseif (strpos($format, '%') !== false) {
return strftime($format, $dt->format('U'));
} else {
return $dt->format($format);
}
}
/**
* Computes the value of the aggregate column length
* Overridden to provide a default of 00:00:00 if the block is empty.
*
* @param PropelPDO $con A connection object
*
* @return mixed The scalar result from the aggregate query
*/
public function computeDbLength(PropelPDO $con)
{
$stmt = $con->prepare('SELECT SUM(cliplength) FROM "cc_blockcontents" WHERE cc_blockcontents.BLOCK_ID = :p1');
$stmt->bindValue(':p1', $this->getDbId());
$stmt->execute();
$length = $stmt->fetchColumn();
if (is_null($length)) {
$length = "00:00:00";
}
return $length;
}
} // CcBlock

View file

@ -3,7 +3,7 @@
/** /**
* Skeleton subclass for performing query and update operations on the 'cc_perms' table. * Skeleton subclass for performing query and update operations on the 'cc_block' table.
* *
* *
* *
@ -13,6 +13,6 @@
* *
* @package propel.generator.airtime * @package propel.generator.airtime
*/ */
class CcPermsPeer extends BaseCcPermsPeer { class CcBlockPeer extends BaseCcBlockPeer {
} // CcPermsPeer } // CcBlockPeer

View file

@ -3,7 +3,7 @@
/** /**
* Skeleton subclass for performing query and update operations on the 'cc_perms' table. * Skeleton subclass for performing query and update operations on the 'cc_block' table.
* *
* *
* *
@ -13,6 +13,6 @@
* *
* @package propel.generator.airtime * @package propel.generator.airtime
*/ */
class CcPermsQuery extends BaseCcPermsQuery { class CcBlockQuery extends BaseCcBlockQuery {
} // CcPermsQuery } // CcBlockQuery

View file

@ -0,0 +1,113 @@
<?php
/**
* Skeleton subclass for representing a row from the 'cc_blockcontents' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
* @package propel.generator.airtime
*/
class CcBlockcontents extends BaseCcBlockcontents {
/**
* Get the [optionally formatted] temporal [fadein] column value.
*
* @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL
* @throws PropelException - if unable to parse/validate the date/time value.
*/
public function getDbFadein($format = "s.u")
{
return parent::getDbFadein($format);
}
/**
* Get the [optionally formatted] temporal [fadein] column value.
*
* @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL
* @throws PropelException - if unable to parse/validate the date/time value.
*/
public function getDbFadeout($format = "s.u")
{
return parent::getDbFadeout($format);
}
/**
*
* @param String in format SS.uuuuuu, Datetime, or DateTime accepted string.
*
* @return CcBlockcontents The current object (for fluent API support)
*/
public function setDbFadein($v)
{
$microsecond = 0;
if ($v instanceof DateTime) {
$dt = $v;
}
else if (preg_match('/^[0-9]{1,2}(\.\d{1,6})?$/', $v)) {
// in php 5.3.2 createFromFormat() with "u" is not supported(bug)
// Hence we need to do parsing.
$info = explode('.', $v);
$microsecond = $info[1];
$dt = DateTime::createFromFormat("s", $info[0]);
}
else {
try {
$dt = new DateTime($v);
} catch (Exception $x) {
throw new PropelException('Error parsing date/time value: ' . var_export($v, true), $x);
}
}
if ($microsecond == 0) {
$this->fadein = $dt->format('H:i:s.u');
} else {
$this->fadein = $dt->format('H:i:s').".".$microsecond;
}
$this->modifiedColumns[] = CcBlockcontentsPeer::FADEIN;
return $this;
} // setDbFadein()
/**
*
* @param String in format SS.uuuuuu, Datetime, or DateTime accepted string.
*
* @return CcBlockcontents The current object (for fluent API support)
*/
public function setDbFadeout($v)
{
$microsecond = 0;
if ($v instanceof DateTime) {
$dt = $v;
}
else if (preg_match('/^[0-9]{1,2}(\.\d{1,6})?$/', $v)) {
// in php 5.3.2 createFromFormat() with "u" is not supported(bug)
// Hence we need to do parsing.
$info = explode('.', $v);
$microsecond = $info[1];
$dt = DateTime::createFromFormat("s", $info[0]);
}
else {
try {
$dt = new DateTime($v);
} catch (Exception $x) {
throw new PropelException('Error parsing date/time value: ' . var_export($v, true), $x);
}
}
if ($microsecond == 0) {
$this->fadeout = $dt->format('H:i:s.u');
} else {
$this->fadeout = $dt->format('H:i:s').".".$microsecond;
}
$this->modifiedColumns[] = CcBlockcontentsPeer::FADEOUT;
return $this;
} // setDbFadeout()
} // CcBlockcontents

View file

@ -3,7 +3,7 @@
/** /**
* Skeleton subclass for performing query and update operations on the 'cc_access' table. * Skeleton subclass for performing query and update operations on the 'cc_blockcontents' table.
* *
* *
* *
@ -13,6 +13,6 @@
* *
* @package propel.generator.airtime * @package propel.generator.airtime
*/ */
class CcAccessPeer extends BaseCcAccessPeer { class CcBlockcontentsPeer extends BaseCcBlockcontentsPeer {
} // CcAccessPeer } // CcBlockcontentsPeer

View file

@ -0,0 +1,18 @@
<?php
/**
* Skeleton subclass for performing query and update operations on the 'cc_blockcontents' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
* @package propel.generator.airtime
*/
class CcBlockcontentsQuery extends BaseCcBlockcontentsQuery {
} // CcBlockcontentsQuery

View file

@ -3,7 +3,7 @@
/** /**
* Skeleton subclass for representing a row from the 'cc_backup' table. * Skeleton subclass for representing a row from the 'cc_blockcriteria' table.
* *
* *
* *
@ -13,6 +13,6 @@
* *
* @package propel.generator.airtime * @package propel.generator.airtime
*/ */
class CcBackup extends BaseCcBackup { class CcBlockcriteria extends BaseCcBlockcriteria {
} // CcBackup } // CcBlockcriteria

View file

@ -3,7 +3,7 @@
/** /**
* Skeleton subclass for performing query and update operations on the 'cc_access' table. * Skeleton subclass for performing query and update operations on the 'cc_blockcriteria' table.
* *
* *
* *
@ -13,6 +13,6 @@
* *
* @package propel.generator.airtime * @package propel.generator.airtime
*/ */
class CcAccessQuery extends BaseCcAccessQuery { class CcBlockcriteriaPeer extends BaseCcBlockcriteriaPeer {
} // CcAccessQuery } // CcBlockcriteriaPeer

View file

@ -0,0 +1,18 @@
<?php
/**
* Skeleton subclass for performing query and update operations on the 'cc_blockcriteria' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
* @package propel.generator.airtime
*/
class CcBlockcriteriaQuery extends BaseCcBlockcriteriaQuery {
} // CcBlockcriteriaQuery

View file

@ -30,7 +30,8 @@ class CcFiles extends BaseCcFiles {
$dt = new DateTime($v); $dt = new DateTime($v);
} catch (Exception $x) { } catch (Exception $x) {
throw new PropelException('Error parsing date/time value: ' . var_export($v, true), $x); throw new PropelException('Error parsing date/time value: ' .
var_export($v, true), $x);
} }
} }
@ -40,5 +41,10 @@ class CcFiles extends BaseCcFiles {
return $this; return $this;
} }
public function reassignTo($user)
{
$this->setDbOwnerId( $user->getDbId() );
$this->save();
}
} // CcFiles } // CcFiles

View file

@ -43,11 +43,16 @@ class CcPlaylistcontents extends BaseCcPlaylistcontents {
*/ */
public function setDbFadein($v) public function setDbFadein($v)
{ {
$microsecond = 0;
if ($v instanceof DateTime) { if ($v instanceof DateTime) {
$dt = $v; $dt = $v;
} }
else if (preg_match('/^[0-9]{1,2}(\.\d{1,6})?$/', $v)) { else if (preg_match('/^[0-9]{1,2}(\.\d{1,6})?$/', $v)) {
$dt = DateTime::createFromFormat("s.u", $v); // in php 5.3.2 createFromFormat() with "u" is not supported(bug)
// Hence we need to do parsing.
$info = explode('.', $v);
$microsecond = $info[1];
$dt = DateTime::createFromFormat("s", $info[0]);
} }
else { else {
try { try {
@ -57,7 +62,11 @@ class CcPlaylistcontents extends BaseCcPlaylistcontents {
} }
} }
if ($microsecond == 0) {
$this->fadein = $dt->format('H:i:s.u'); $this->fadein = $dt->format('H:i:s.u');
} else {
$this->fadein = $dt->format('H:i:s').".".$microsecond;
}
$this->modifiedColumns[] = CcPlaylistcontentsPeer::FADEIN; $this->modifiedColumns[] = CcPlaylistcontentsPeer::FADEIN;
return $this; return $this;
@ -71,11 +80,16 @@ class CcPlaylistcontents extends BaseCcPlaylistcontents {
*/ */
public function setDbFadeout($v) public function setDbFadeout($v)
{ {
$microsecond = 0;
if ($v instanceof DateTime) { if ($v instanceof DateTime) {
$dt = $v; $dt = $v;
} }
else if (preg_match('/^[0-9]{1,2}(\.\d{1,6})?$/', $v)) { else if (preg_match('/^[0-9]{1,2}(\.\d{1,6})?$/', $v)) {
$dt = DateTime::createFromFormat("s.u", $v); // in php 5.3.2 createFromFormat() with "u" is not supported(bug)
// Hence we need to do parsing.
$info = explode('.', $v);
$microsecond = $info[1];
$dt = DateTime::createFromFormat("s", $info[0]);
} }
else { else {
try { try {
@ -85,7 +99,11 @@ class CcPlaylistcontents extends BaseCcPlaylistcontents {
} }
} }
if ($microsecond == 0) {
$this->fadeout = $dt->format('H:i:s.u'); $this->fadeout = $dt->format('H:i:s.u');
} else {
$this->fadeout = $dt->format('H:i:s').".".$microsecond;
}
$this->modifiedColumns[] = CcPlaylistcontentsPeer::FADEOUT; $this->modifiedColumns[] = CcPlaylistcontentsPeer::FADEOUT;
return $this; return $this;

View file

@ -3,7 +3,7 @@
/** /**
* Skeleton subclass for representing a row from the 'cc_access' table. * Skeleton subclass for representing a row from the 'cc_playlistcriteria' table.
* *
* *
* *
@ -13,6 +13,6 @@
* *
* @package propel.generator.airtime * @package propel.generator.airtime
*/ */
class CcAccess extends BaseCcAccess { class CcPlaylistcriteria extends BaseCcPlaylistcriteria {
} // CcAccess } // CcPlaylistcriteria

View file

@ -3,7 +3,7 @@
/** /**
* Skeleton subclass for performing query and update operations on the 'cc_playlistcontents' table. * Skeleton subclass for performing query and update operations on the 'cc_playlistcriteria' table.
* *
* *
* *
@ -13,6 +13,6 @@
* *
* @package propel.generator.airtime * @package propel.generator.airtime
*/ */
class CcPlaylistcontentsPeer extends BaseCcPlaylistcontentsPeer { class CcPlaylistcriteriaPeer extends BaseCcPlaylistcriteriaPeer {
} // CcPlaylistcontentsPeer } // CcPlaylistcriteriaPeer

Some files were not shown because too many files have changed in this diff Show more