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,11 +131,12 @@ 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()
{ {
$front = Zend_Controller_Front::getInstance(); $front = Zend_Controller_Front::getInstance();
$router = $front->getRouter(); $router = $front->getRouter();
$router->addRoute( $router->addRoute(

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

@ -152,6 +152,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)
{ {
@ -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

@ -10,31 +10,33 @@ $ccAcl->addRole(new Zend_Acl_Role('G'))
->addRole(new Zend_Acl_Role('A'), 'P'); ->addRole(new Zend_Acl_Role('A'), 'P');
$ccAcl->add(new Zend_Acl_Resource('library')) $ccAcl->add(new Zend_Acl_Resource('library'))
->add(new Zend_Acl_Resource('index')) ->add(new Zend_Acl_Resource('index'))
->add(new Zend_Acl_Resource('user')) ->add(new Zend_Acl_Resource('user'))
->add(new Zend_Acl_Resource('error')) ->add(new Zend_Acl_Resource('error'))
->add(new Zend_Acl_Resource('login')) ->add(new Zend_Acl_Resource('login'))
->add(new Zend_Acl_Resource('playlist')) ->add(new Zend_Acl_Resource('playlist'))
->add(new Zend_Acl_Resource('plupload')) ->add(new Zend_Acl_Resource('plupload'))
->add(new Zend_Acl_Resource('schedule')) ->add(new Zend_Acl_Resource('schedule'))
->add(new Zend_Acl_Resource('api')) ->add(new Zend_Acl_Resource('api'))
->add(new Zend_Acl_Resource('systemstatus')) ->add(new Zend_Acl_Resource('systemstatus'))
->add(new Zend_Acl_Resource('dashboard')) ->add(new Zend_Acl_Resource('dashboard'))
->add(new Zend_Acl_Resource('preference')) ->add(new Zend_Acl_Resource('preference'))
->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')
->allow('G', 'login') ->allow('G', 'login')
->allow('G', 'error') ->allow('G', 'error')
->allow('G', 'showbuilder') ->allow('G', 'showbuilder')
->allow('G', 'api') ->allow('G', 'api')
->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

@ -8,38 +8,38 @@
* the navigation container below. * the navigation container below.
*/ */
$pages = array( $pages = array(
array( array(
'label' => 'Now Playing', 'label' => 'Now Playing',
'module' => 'default', 'module' => 'default',
'controller' => 'Showbuilder', 'controller' => 'Showbuilder',
'action' => 'index', 'action' => 'index',
'resource' => 'showbuilder' 'resource' => 'showbuilder'
), ),
array( array(
'label' => 'Add Media', 'label' => 'Add Media',
'module' => 'default', 'module' => 'default',
'controller' => 'Plupload', 'controller' => 'Plupload',
'action' => 'index', 'action' => 'index',
'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'
), ),
array( array(
'label' => 'Calendar', 'label' => 'Calendar',
'module' => 'default', 'module' => 'default',
'controller' => 'Schedule', 'controller' => 'Schedule',
'action' => 'index', 'action' => 'index',
'resource' => 'schedule' 'resource' => 'schedule'
), ),
array( array(
'label' => 'System', 'label' => 'System',
'uri' => '#', 'uri' => '#',
'resource' => 'preference', 'resource' => 'preference',
'pages' => array( 'pages' => array(
array( array(
'label' => 'Preferences', 'label' => 'Preferences',
@ -51,14 +51,14 @@ $pages = array(
'module' => 'default', 'module' => 'default',
'controller' => 'user', 'controller' => 'user',
'action' => 'add-user', 'action' => 'add-user',
'resource' => 'user' 'resource' => 'user'
), ),
array( array(
'label' => 'Media Folders', 'label' => 'Media Folders',
'module' => 'default', 'module' => 'default',
'controller' => 'Preference', 'controller' => 'Preference',
'action' => 'directory-config', 'action' => 'directory-config',
'id' => 'manage_folder' 'id' => 'manage_folder'
), ),
array( array(
'label' => 'Streams', 'label' => 'Streams',
@ -77,28 +77,28 @@ $pages = array(
'module' => 'default', 'module' => 'default',
'controller' => 'systemstatus', 'controller' => 'systemstatus',
'action' => 'index', 'action' => 'index',
'resource' => 'systemstatus' 'resource' => 'systemstatus'
), ),
array( array(
'label' => 'Playout History', 'label' => 'Playout History',
'module' => 'default', 'module' => 'default',
'controller' => 'playouthistory', 'controller' => 'playouthistory',
'action' => 'index', 'action' => 'index',
'resource' => 'playouthistory' 'resource' => 'playouthistory'
) )
) )
), ),
array( array(
'label' => 'Help', 'label' => 'Help',
'uri' => '#', 'uri' => '#',
'resource' => 'dashboard', 'resource' => 'dashboard',
'pages' => array( 'pages' => array(
array( array(
'label' => 'Getting Started', 'label' => 'Getting Started',
'module' => 'default', 'module' => 'default',
'controller' => 'dashboard', 'controller' => 'dashboard',
'action' => 'help', 'action' => 'help',
'resource' => 'dashboard' 'resource' => 'dashboard'
), ),
array( array(
'label' => 'User Manual', 'label' => 'User Manual',
@ -110,10 +110,10 @@ $pages = array(
'module' => 'default', 'module' => 'default',
'controller' => 'dashboard', 'controller' => 'dashboard',
'action' => 'about', 'action' => 'about',
'resource' => 'dashboard' 'resource' => 'dashboard'
) )
) )
) )
); );

File diff suppressed because it is too large Load diff

View file

@ -20,30 +20,50 @@ class AudiopreviewController extends Zend_Controller_Action
public function audioPreviewAction() public function audioPreviewAction()
{ {
global $CC_CONFIG; global $CC_CONFIG;
$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'],'text/javascript'); $this->view->headScript()->appendFile(
$this->view->headScript()->appendFile($baseUrl.'/js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $baseUrl.'/js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],
$this->view->headLink()->appendStylesheet($baseUrl.'/js/jplayer/skin/jplayer.airtime.audio.preview.css?'.$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'); $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";
} }
$this->view->audioFileID = $audioFileID;
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->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');
} }
@ -55,14 +75,12 @@ class AudiopreviewController extends Zend_Controller_Action
public function playlistPreviewAction() public function playlistPreviewAction()
{ {
global $CC_CONFIG; global $CC_CONFIG;
$playlistIndex = $this->_getParam('playlistIndex'); $playlistIndex = $this->_getParam('playlistIndex');
$playlistID = $this->_getParam('playlistID'); $playlistID = $this->_getParam('playlistID');
$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');
@ -70,7 +88,7 @@ class AudiopreviewController extends Zend_Controller_Action
$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,44 +99,128 @@ class AudiopreviewController extends Zend_Controller_Action
$this->_helper->viewRenderer->setRender('audio-preview'); $this->_helper->viewRenderer->setRender('audio-preview');
} }
/** public function blockPreviewAction()
*Function will load and return the contents of the requested playlist. {
*/ global $CC_CONFIG;
public function getPlaylistAction(){
$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 // 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'); $blockId = $this->_getParam('blockId');
if (!isset($playlistID)){ if (!isset($blockId)) {
return; 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.
*/
public function getPlaylistAction()
{
// disable the view and the layout
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$playlistID = $this->_getParam('playlistID');
if (!isset($playlistID)) {
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) {
$elementMap = array( 'element_title' => isset($track['CcFiles']['track_title'])?$track['CcFiles']['track_title']:"", // if element is a block expand and add
'element_artist' => isset($track['CcFiles']['artist_name'])?$track['CcFiles']['artist_name']:"", $bl = new Application_Model_Block($ele['item_id']);
'element_id' => isset($track['id'])?$track['id']:"", if ($bl->isStatic()) {
'element_position' => isset($track['position'])?$track['position']:"", foreach ($bl->getContents(true) as $track) {
); $result[] = $this->createElementMap($track);
$fileExtension = pathinfo($track['CcFiles']['filepath'], PATHINFO_EXTENSION); }
if (strtolower($fileExtension) === 'mp3'){ }
$elementMap['element_mp3'] = $track['CcFiles']['gunid'].'.'.$fileExtension;
} else if(strtolower($fileExtension) === 'ogg') {
$elementMap['element_oga'] = $track['CcFiles']['gunid'].'.'.$fileExtension;
} else { } else {
//the media was neither mp3 or ogg $result[] = $this->createElementMap($ele);
} }
$result[] = $elementMap;
} }
$this->_helper->json($result); $this->_helper->json($result);
} }
private function createElementMap($track)
{
$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_position' => isset($track['position'])?$track['position']:"",
'mime' => isset($track['mime'])?$track['mime']:""
);
/* If the track type is static we know it must be
* a track because static blocks can only contain
* tracks
*/
if ($track['type'] == 'static') {
$track['type'] = 0;
}
$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");
}
$elementMap['uri'] = "/api/get-media/file/".$track['item_id'];
} else {
$elementMap['uri'] = $track['path'];
}
return $elementMap;
}
/** /**
* Simply sets up the view to play the required show track. * Simply sets up the view to play the required show track.
* Gets the parameters from the request and sets them to the view. * Gets the parameters from the request and sets them to the view.
@ -126,14 +228,12 @@ class AudiopreviewController extends Zend_Controller_Action
public function showPreviewAction() public function showPreviewAction()
{ {
global $CC_CONFIG; global $CC_CONFIG;
$showID = $this->_getParam('showID'); $showID = $this->_getParam('showID');
$showIndex = $this->_getParam('showIndex'); $showIndex = $this->_getParam('showIndex');
$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');
@ -141,18 +241,18 @@ class AudiopreviewController extends Zend_Controller_Action
$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";
} }
$this->view->showID = $showID; $this->view->showID = $showID;
$this->view->showIndex = $showIndex; $this->view->showIndex = $showIndex;
$this->_helper->viewRenderer->setRender('audio-preview'); $this->_helper->viewRenderer->setRender('audio-preview');
} }
/** /**
*Function will load and return the contents of the requested show. *Function will load and return the contents of the requested show.
*/ */
@ -161,32 +261,46 @@ class AudiopreviewController extends Zend_Controller_Action
// 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);
$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 {
throw new Exception("Unknown file type: $mime");
}
$elementMap['uri'] = "/api/get-media/file/".$track['item_id'];
} else { } else {
//the media was neither mp3 or ogg $elementMap['uri'] = $track['filepath'];
} }
$result[] = $elementMap; $result[] = $elementMap;
} }

View file

@ -15,99 +15,97 @@ 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";
//Log table updates //Log table updates
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()
{ {
global $CC_CONFIG; global $CC_CONFIG;
$request = $this->getRequest(); $request = $this->getRequest();
$baseUrl = $request->getBaseUrl(); $baseUrl = $request->getBaseUrl();
$this->view->headLink()->appendStylesheet($baseUrl.'/js/jplayer/skin/jplayer.blue.monday.css?'.$CC_CONFIG['airtime_version']); $this->view->headLink()->appendStylesheet($baseUrl.'/js/jplayer/skin/jplayer.blue.monday.css?'.$CC_CONFIG['airtime_version']);
$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

@ -6,12 +6,12 @@ class ErrorController extends Zend_Controller_Action
public function errorAction() public function errorAction()
{ {
$errors = $this->_getParam('error_handler'); $errors = $this->_getParam('error_handler');
switch ($errors->type) { switch ($errors->type) {
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE: case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER: case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION: case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
// 404 error -- controller or action not found // 404 error -- controller or action not found
$this->getResponse()->setHttpResponseCode(404); $this->getResponse()->setHttpResponseCode(404);
$this->view->message = 'Page not found'; $this->view->message = 'Page not found';
@ -22,17 +22,17 @@ class ErrorController extends Zend_Controller_Action
$this->view->message = 'Application error'; $this->view->message = 'Application error';
break; break;
} }
// Log exception, if logger available // Log exception, if logger available
if ($log = $this->getLog()) { if ($log = $this->getLog()) {
$log->crit($this->view->message, $errors->exception); $log->crit($this->view->message, $errors->exception);
} }
// conditionally display exceptions // conditionally display exceptions
if ($this->getInvokeArg('displayExceptions') == true) { if ($this->getInvokeArg('displayExceptions') == true) {
$this->view->exception = $errors->exception; $this->view->exception = $errors->exception;
} }
$this->view->request = $errors->request; $this->view->request = $errors->request;
} }
@ -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

@ -5,7 +5,7 @@ class IndexController extends Zend_Controller_Action
public function init() public function init()
{ {
} }
public function indexAction() public function indexAction()
@ -14,15 +14,8 @@ class IndexController extends Zend_Controller_Action
} }
public function mainAction() public function mainAction()
{ {
$this->_helper->layout->setLayout('layout'); $this->_helper->layout->setLayout('layout');
} }
} }

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()
@ -39,21 +152,33 @@ class LibraryController 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);
//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
$menu["pl_add"] = array("name"=> "Add to Playlist", "icon" => "add-playlist", "icon" => "copy"); 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");
} elseif ($obj_sess->type === "block") {
$menu["pl_add"] = array("name"=> "Add to Smart Block", "icon" => "add-playlist", "icon" => "copy");
}
} }
} }
if ($isAdminOrPM) { if ($isAdminOrPM) {
@ -63,46 +188,77 @@ 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") {
else if ($type === "playlist") { if ($type === 'playlist') {
$playlist = new Application_Model_Playlist($id); $obj = new Application_Model_Playlist($id);
if ($this->pl_sess->id !== $id && $screen == "playlist") { } elseif ($type === 'block') {
if($isAdminOrPM || $playlist->getCreatorId() == $user->getId()){ $obj = new Application_Model_Block($id);
if (!$obj->isStatic()) {
unset($menu["play"]);
}
if (($isAdminOrPM || $obj->getCreatorId() == $user->getId()) && $screen == "playlist") {
if ($obj_sess->type === "playlist") {
$menu["pl_add"] = array("name"=> "Add to Playlist", "icon" => "add-playlist", "icon" => "copy");
}
}
}
if ($obj_sess->id !== $id && $screen == "playlist") {
if ($isAdminOrPM || $obj->getCreatorId() == $user->getId()) {
$menu["edit"] = array("name"=> "Edit", "icon" => "edit"); $menu["edit"] = array("name"=> "Edit", "icon" => "edit");
} }
} }
if($isAdminOrPM || $playlist->getCreatorId() == $user->getId()){ 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"); $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()) {
//create a menu separator //create a menu separator
$menu["sep1"] = "-----------"; $menu["sep1"] = "-----------";
//create a sub menu for Soundcloud actions. //create a sub menu for Soundcloud actions.
$menu["soundcloud"] = array("name" => "Soundcloud", "icon" => "soundcloud", "items" => array()); $menu["soundcloud"] = array("name" => "Soundcloud", "icon" => "soundcloud", "items" => array());
$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,41 +334,40 @@ 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"/>';
} }
} }
} }
$this->view->sEcho = $r["sEcho"]; $this->view->sEcho = $r["sEcho"];
$this->view->iTotalDisplayRecords = $r["iTotalDisplayRecords"]; $this->view->iTotalDisplayRecords = $r["iTotalDisplayRecords"];
$this->view->iTotalRecords = $r["iTotalRecords"]; $this->view->iTotalRecords = $r["iTotalRecords"];
$this->view->files = $r["aaData"]; $this->view->files = $r["aaData"];
} }
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;
} }
$request = $this->getRequest(); $request = $this->getRequest();
$form = new Application_Form_EditAudioMD(); $form = new Application_Form_EditAudioMD();
@ -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');
@ -247,14 +405,14 @@ class LibraryController extends Zend_Controller_Action
$file = Application_Model_StoredFile::Recall($id); $file = Application_Model_StoredFile::Recall($id);
$this->view->type = $type; $this->view->type = $type;
$md = $file->getMetadata(); $md = $file->getMetadata();
foreach ($md as $key => $value) { foreach ($md as $key => $value) {
if ($key == 'MDATA_KEY_DIRECTORY') { if ($key == 'MDATA_KEY_DIRECTORY') {
$musicDir = Application_Model_MusicDir::getDirByPK($value); $musicDir = Application_Model_MusicDir::getDirByPK($value);
$md['MDATA_KEY_FILEPATH'] = Application_Common_OsPath::join($musicDir->getDirectory(), $md['MDATA_KEY_FILEPATH']); $md['MDATA_KEY_FILEPATH'] = Application_Common_OsPath::join($musicDir->getDirectory(), $md['MDATA_KEY_FILEPATH']);
} }
} }
$formatter = new SamplerateFormatter($md["MDATA_KEY_SAMPLERATE"]); $formatter = new SamplerateFormatter($md["MDATA_KEY_SAMPLERATE"]);
$md["MDATA_KEY_SAMPLERATE"] = $formatter->format(); $md["MDATA_KEY_SAMPLERATE"] = $formatter->format();
@ -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::info($e->getMessage());
Logging::log($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

@ -11,67 +11,61 @@ class LoginController extends Zend_Controller_Action
public function indexAction() public function indexAction()
{ {
global $CC_CONFIG; global $CC_CONFIG;
if (Zend_Auth::getInstance()->hasIdentity()) if (Zend_Auth::getInstance()->hasIdentity()) {
{
$this->_redirect('Showbuilder'); $this->_redirect('Showbuilder');
} }
//uses separate layout without a navigation. //uses separate layout without a navigation.
$this->_helper->layout->setLayout('login'); $this->_helper->layout->setLayout('login');
$error = false; $error = false;
$request = $this->getRequest(); $request = $this->getRequest();
$baseUrl = $request->getBaseUrl(); $baseUrl = $request->getBaseUrl();
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/login/login.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/login/login.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$form = new Application_Form_Login(); $form = new Application_Form_Login();
$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
$authAdapter->setIdentity($username) $authAdapter->setIdentity($username)
->setCredential($password); ->setCredential($password);
$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');
//the default storage is a session with namespace Zend_Auth //the default storage is a session with namespace Zend_Auth
$authStorage = $auth->getStorage(); $authStorage = $auth->getStorage();
$authStorage->write($userInfo); $authStorage->write($userInfo);
Application_Model_LoginAttempts::resetAttempts($_SERVER['REMOTE_ADDR']); Application_Model_LoginAttempts::resetAttempts($_SERVER['REMOTE_ADDR']);
Application_Model_Subjects::resetLoginAttempts($username); Application_Model_Subjects::resetLoginAttempts($username);
$tempSess = new Zend_Session_Namespace("referrer"); $tempSess = new Zend_Session_Namespace("referrer");
$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']);
@ -81,13 +75,13 @@ class LoginController extends Zend_Controller_Action
} }
} }
} }
$this->view->message = $message; $this->view->message = $message;
$this->view->error = $error; $this->view->error = $error;
$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'];
} }
} }
@ -97,103 +91,105 @@ class LoginController extends Zend_Controller_Action
Zend_Auth::getInstance()->clearIdentity(); Zend_Auth::getInstance()->clearIdentity();
$this->_redirect('showbuilder/index'); $this->_redirect('showbuilder/index');
} }
public function passwordRestoreAction() public function passwordRestoreAction()
{ {
global $CC_CONFIG; global $CC_CONFIG;
$request = $this->getRequest(); $request = $this->getRequest();
$baseUrl = $request->getBaseUrl(); $baseUrl = $request->getBaseUrl();
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/login/password-restore.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/login/password-restore.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
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');
$form = new Application_Form_PasswordRestore();
$form = new Application_Form_PasswordRestore();
$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 {
if (!empty($user)) { $user = CcSubjsQuery::create()
$auth = new Application_Model_Auth(); ->filterByDbEmail($form->email->getValue())
->filterByDbLogin($form->username->getValue())
->findOne();
}
if (!empty($user)) {
$auth = new Application_Model_Auth();
$success = $auth->sendPasswordRestoreLink($user, $this->view); $success = $auth->sendPasswordRestoreLink($user, $this->view);
if ($success) { if ($success) {
$this->_helper->redirector('password-restore-after', 'login'); $this->_helper->redirector('password-restore-after', 'login');
} 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.")); }
}
} }
$this->view->form = $form; $this->view->form = $form;
} }
} }
public function passwordRestoreAfterAction() public function passwordRestoreAfterAction()
{ {
//uses separate layout without a navigation. //uses separate layout without a navigation.
$this->_helper->layout->setLayout('login'); $this->_helper->layout->setLayout('login');
} }
public function passwordChangeAction() public function passwordChangeAction()
{ {
//uses separate layout without a navigation. //uses separate layout without a navigation.
$this->_helper->layout->setLayout('login'); $this->_helper->layout->setLayout('login');
$request = $this->getRequest(); $request = $this->getRequest();
$token = $request->getParam("token", false); $token = $request->getParam("token", false);
$user_id = $request->getParam("user_id", 0); $user_id = $request->getParam("user_id", 0);
$form = new Application_Form_PasswordChange(); $form = new Application_Form_PasswordChange();
$auth = new Application_Model_Auth(); $auth = new Application_Model_Auth();
$user = CcSubjsQuery::create()->findPK($user_id); $user = CcSubjsQuery::create()->findPK($user_id);
//check validity of token //check validity of token
if (!$auth->checkToken($user_id, $token, 'password.restore')) { if (!$auth->checkToken($user_id, $token, 'password.restore')) {
Logging::debug("token not valid"); Logging::debug("token not valid");
$this->_helper->redirector('index', 'login'); $this->_helper->redirector('index', 'login');
} }
if ($request->isPost() && $form->isValid($request->getPost())) { if ($request->isPost() && $form->isValid($request->getPost())) {
$user->setDbPass(md5($form->password->getValue())); $user->setDbPass(md5($form->password->getValue()));
$user->save(); $user->save();
$auth->invalidateTokens($user, 'password.restore'); $auth->invalidateTokens($user, 'password.restore');
$zend_auth = Zend_Auth::getInstance(); $zend_auth = Zend_Auth::getInstance();
$zend_auth->clearIdentity(); $zend_auth->clearIdentity();
$authAdapter = Application_Model_Auth::getAuthAdapter(); $authAdapter = Application_Model_Auth::getAuthAdapter();
$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');
//the default storage is a session with namespace Zend_Auth //the default storage is a session with namespace Zend_Auth
$authStorage = $zend_auth->getStorage(); $authStorage = $zend_auth->getStorage();
$authStorage->write($userInfo); $authStorage->write($userInfo);
$this->_helper->redirector('index', 'showbuilder'); $this->_helper->redirector('index', 'showbuilder');
} }
$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,218 +21,274 @@ 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;
return $obj;
} }
private function changePlaylist($pl_id) private function createUpdateResponse($obj)
{ {
if (is_null($pl_id)) { $formatter = new LengthFormatter($obj->getLength());
unset($this->pl_sess->id);
}
else {
$this->pl_sess->id = intval($pl_id);
}
}
private function createUpdateResponse($pl)
{
$formatter = new LengthFormatter($pl->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);
}
else { $this->view->form = $form;
$this->view->html = $this->view->render('playlist/playlist.phtml'); $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);
}
} }
} }
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(); private function wrongTypeToPlaylist($obj)
$baseUrl = $request->getBaseUrl(); {
$this->view->error = "You can only add tracks, smart blocks, and webstreams to playlists.";
$this->view->headScript()->appendFile($baseUrl.'/js/blockui/jquery.blockUI.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->createFullResponse($obj);
$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);
}
} }
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) {
} $this->playlistUnknownError($e);
catch (Exception $e) { }
$this->playlistUnknownError($e);
}
} }
public function deleteAction() public function deleteAction()
{ {
$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 {
catch (PlaylistNotFoundException $e) { Application_Model_Block::deleteBlocks($ids, $userInfo->id);
$this->playlistNotFound(); }
} $this->createFullResponse($obj);
catch (Exception $e) { } catch (PlaylistNoPermissionException $e) {
$this->playlistNoPermission($type);
} 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])) {
catch (PlaylistOutDatedException $e) { if ($id[1] == 'playlist') {
$this->playlistOutdated($pl, $e); throw new WrongTypeToPlaylistException;
} }
catch (PlaylistNotFoundException $e) { }
$this->playlistNotFound(); }
} $obj->addAudioClips($ids, $afterItem, $addType);
catch (Exception $e) { } 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,98 +318,88 @@ 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);
} }
} }
public function setCueAction() public function setCueAction()
{ {
$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);
} }
} }
public function setFadeAction() public function setFadeAction()
{ {
$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);
} }
} }
@ -369,65 +411,147 @@ class PlaylistController extends Zend_Controller_Action
**/ **/
public function setPlaylistFadesAction() public function setPlaylistFadesAction()
{ {
$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');
$description = $this->_getParam('description', "");
$type = $this->_getParam('type');
try { try {
$pl = $this->getPlaylist(); $obj = $this->getPlaylist($type);
$pl->setName($name); $obj->setName(trim($name));
$obj->setDescription($description);
$this->view->description = $description;
$this->view->playlistName = $name; $this->view->playlistName = $name;
$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, true);
catch (PlaylistNotFoundException $e) { } catch (Exception $e) {
$this->playlistNotFound();
}
catch (Exception $e) {
$this->playlistUnknownError($e); $this->playlistUnknownError($e);
} }
} }
public function setPlaylistDescriptionAction() public function saveAction()
{ {
$description = $this->_getParam('description', ""); $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 { try {
$pl = $this->getPlaylist(); $bl = new Application_Model_Block($params['obj_id']);
$pl->setDescription($description);
$this->view->description = $pl->getDescription(); $form = new Application_Form_SmartBlockCriteria();
$this->view->modified = $pl->getLastModified("U"); $form->startForm($params['obj_id']);
} if ($form->isValid($params)) {
catch (PlaylistOutDatedException $e) { $result = $bl->generateSmartBlock($params['data']);
$this->playlistOutdated($pl, $e); die(json_encode(array("result"=>0, "html"=>$this->createFullResponse($bl, true, true))));
} } else {
catch (PlaylistNotFoundException $e) { $this->view->obj = $bl;
$this->playlistNotFound(); $this->view->id = $bl->getId();
} $this->view->form = $form;
catch (Exception $e) { $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); $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,20 +1,20 @@
<?php <?php
class PlayoutHistoryController extends Zend_Controller_Action class PlayouthistoryController extends Zend_Controller_Action
{ {
public function init() public function init()
{ {
$ajaxContext = $this->_helper->getHelper('AjaxContext'); $ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext $ajaxContext
->addActionContext('playout-history-feed', 'json') ->addActionContext('playout-history-feed', 'json')
->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();
//default time is the last 24 hours. //default time is the last 24 hours.
@ -35,50 +35,50 @@ class PlayoutHistoryController extends Zend_Controller_Action
'his_time_end' => $end->format("H:i") 'his_time_end' => $end->format("H:i")
)); ));
$this->view->date_form = $form; $this->view->date_form = $form;
$this->view->headScript()->appendFile($baseUrl.'/js/contextmenu/jquery.contextMenu.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/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/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.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.fnSetFilteringDelay.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/TableTools/js/ZeroClipboard.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/TableTools/js/ZeroClipboard.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/TableTools/js/TableTools.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/TableTools/js/TableTools.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$offset = date("Z") * -1; $offset = date("Z") * -1;
$this->view->headScript()->appendScript("var serverTimezoneOffset = {$offset}; //in seconds"); $this->view->headScript()->appendScript("var serverTimezoneOffset = {$offset}; //in seconds");
$this->view->headScript()->appendFile($baseUrl.'/js/timepicker/jquery.ui.timepicker.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/timepicker/jquery.ui.timepicker.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/buttons/buttons.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/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/utilities/utilities.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/playouthistory/historytable.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/playouthistory/historytable.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headLink()->appendStylesheet($baseUrl.'/js/datatables/plugin/TableTools/css/TableTools.css?'.$CC_CONFIG['airtime_version']); $this->view->headLink()->appendStylesheet($baseUrl.'/js/datatables/plugin/TableTools/css/TableTools.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'/css/jquery.ui.timepicker.css?'.$CC_CONFIG['airtime_version']); $this->view->headLink()->appendStylesheet($baseUrl.'/css/jquery.ui.timepicker.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'/css/playouthistory.css?'.$CC_CONFIG['airtime_version']); $this->view->headLink()->appendStylesheet($baseUrl.'/css/playouthistory.css?'.$CC_CONFIG['airtime_version']);
} }
public function playoutHistoryFeedAction() public function playoutHistoryFeedAction()
{ {
$request = $this->getRequest(); $request = $this->getRequest();
$current_time = time(); $current_time = time();
$params = $request->getParams(); $params = $request->getParams();
$starts_epoch = $request->getParam("start", $current_time - (60*60*24)); $starts_epoch = $request->getParam("start", $current_time - (60*60*24));
$ends_epoch = $request->getParam("end", $current_time); $ends_epoch = $request->getParam("end", $current_time);
$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);
$r = $history->getItems(); $r = $history->getItems();
$this->view->sEcho = $r["sEcho"]; $this->view->sEcho = $r["sEcho"];
$this->view->iTotalDisplayRecords = $r["iTotalDisplayRecords"]; $this->view->iTotalDisplayRecords = $r["iTotalDisplayRecords"];
$this->view->iTotalRecords = $r["iTotalRecords"]; $this->view->iTotalRecords = $r["iTotalRecords"];
$this->view->history = $r["history"]; $this->view->history = $r["history"];
} }
} }

View file

@ -14,7 +14,7 @@ class PluploadController extends Zend_Controller_Action
public function indexAction() public function indexAction()
{ {
global $CC_CONFIG; global $CC_CONFIG;
$request = $this->getRequest(); $request = $this->getRequest();
$baseUrl = $request->getBaseUrl(); $baseUrl = $request->getBaseUrl();
@ -33,18 +33,17 @@ 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

@ -21,9 +21,9 @@ class PreferenceController extends Zend_Controller_Action
public function indexAction() public function indexAction()
{ {
global $CC_CONFIG; global $CC_CONFIG;
$isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; $isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true;
$request = $this->getRequest(); $request = $this->getRequest();
$baseUrl = $request->getBaseUrl(); $baseUrl = $request->getBaseUrl();
@ -41,7 +41,7 @@ class PreferenceController extends Zend_Controller_Action
Application_Model_Preference::SetAllow3rdPartyApi($values["preferences_general"]["thirdPartyApi"]); Application_Model_Preference::SetAllow3rdPartyApi($values["preferences_general"]["thirdPartyApi"]);
Application_Model_Preference::SetTimezone($values["preferences_general"]["timezone"]); Application_Model_Preference::SetTimezone($values["preferences_general"]["timezone"]);
Application_Model_Preference::SetWeekStartDay($values["preferences_general"]["weekStartDay"]); Application_Model_Preference::SetWeekStartDay($values["preferences_general"]["weekStartDay"]);
if (!$isSaas) { if (!$isSaas) {
Application_Model_Preference::SetEnableSystemEmail($values["preferences_email_server"]["enableSystemEmail"]); Application_Model_Preference::SetEnableSystemEmail($values["preferences_email_server"]["enableSystemEmail"]);
Application_Model_Preference::SetSystemEmail($values["preferences_email_server"]["systemEmail"]); Application_Model_Preference::SetSystemEmail($values["preferences_email_server"]["systemEmail"]);
@ -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();
@ -153,23 +154,22 @@ class PreferenceController extends Zend_Controller_Action
$baseUrl = $request->getBaseUrl(); $baseUrl = $request->getBaseUrl();
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/preferences/streamsetting.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/preferences/streamsetting.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; $isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true;
// 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";
} }
} }
@ -189,11 +189,11 @@ class PreferenceController extends Zend_Controller_Action
$form->setSetting($setting); $form->setSetting($setting);
$form->startFrom(); $form->startFrom();
$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($values)) {
if($form->isValid($post_data)){
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');
@ -218,66 +217,63 @@ class PreferenceController extends Zend_Controller_Action
$values['streamFormat'] = $form->getValue('streamFormat'); $values['streamFormat'] = $form->getValue('streamFormat');
Application_Model_StreamSetting::setStreamSetting($values); Application_Model_StreamSetting::setStreamSetting($values);
// 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"]);
if (!$isSaas) { if (!$isSaas) {
if (!Application_Model_Preference::GetMasterDjConnectionUrlOverride()) { if (!Application_Model_Preference::GetMasterDjConnectionUrlOverride()) {
$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 {
Application_Model_Preference::SetMasterDJSourceConnectionURL($values["master_dj_connection_url"]); Application_Model_Preference::SetMasterDJSourceConnectionURL($values["master_dj_connection_url"]);
} }
if (!Application_Model_Preference::GetLiveDjConnectionUrlOverride()) { if (!Application_Model_Preference::GetLiveDjConnectionUrlOverride()) {
$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
Application_Model_Preference::SetStreamUpdateTimestamp(); Application_Model_Preference::SetStreamUpdateTimestamp();
$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");
} }
Application_Model_RabbitMq::SendMessageToPypo("update_stream_setting", $data); Application_Model_RabbitMq::SendMessageToPypo("update_stream_setting", $data);
$this->view->statusMsg = "<div class='success'>Stream Setting Updated.</div>"; $this->view->statusMsg = "<div class='success'>Stream Setting Updated.</div>";
} }
} }
$live_stream_subform->updateVariables(); $live_stream_subform->updateVariables();
$this->view->confirm_pypo_restart_text = "If you change the username or password values for an enabled stream the playout engine will be rebooted and your listeners will hear silence for 5-10 seconds. Changing the following fields will NOT cause a reboot: Stream Label (Global Settings), and Switch Transition Fade(s), Master Username, and Master Password (Input Stream Settings). If Airtime is recording, and if the change causes a playout engine restart, the recording will be interrupted."; $this->view->confirm_pypo_restart_text = "If you change the username or password values for an enabled stream the playout engine will be rebooted and your listeners will hear silence for 5-10 seconds. Changing the following fields will NOT cause a reboot: Stream Label (Global Settings), and Switch Transition Fade(s), Master Username, and Master Password (Input Stream Settings). If Airtime is recording, and if the change causes a playout engine restart, the recording will be interrupted.";
$this->view->num_stream = $num_of_stream; $this->view->num_stream = $num_of_stream;
$this->view->enable_stream_conf = Application_Model_Preference::GetEnableStreamConf(); $this->view->enable_stream_conf = Application_Model_Preference::GetEnableStreamConf();
$this->view->form = $form; $this->view->form = $form;
@ -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,14 +337,14 @@ 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']));
} }
$this->view->subform = $watched_dirs_form->render(); $this->view->subform = $watched_dirs_form->render();
} }
public function rescanWatchDirectoryAction() public function rescanWatchDirectoryAction()
{ {
$dir = Application_Model_MusicDir::getDirByPath($this->getRequest()->getParam("dir")); $dir = Application_Model_MusicDir::getDirByPath($this->getRequest()->getParam("dir"));
@ -373,46 +366,46 @@ 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);
} }
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);
} }
die(); die();
} }
} }

View file

@ -10,16 +10,16 @@ class ScheduleController extends Zend_Controller_Action
$ajaxContext = $this->_helper->getHelper('AjaxContext'); $ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('event-feed', 'json') $ajaxContext->addActionContext('event-feed', 'json')
->addActionContext('make-context-menu', 'json') ->addActionContext('make-context-menu', 'json')
->addActionContext('add-show-dialog', 'json') ->addActionContext('add-show-dialog', 'json')
->addActionContext('add-show', 'json') ->addActionContext('add-show', 'json')
->addActionContext('edit-show', 'json') ->addActionContext('edit-show', 'json')
->addActionContext('move-show', 'json') ->addActionContext('move-show', 'json')
->addActionContext('resize-show', 'json') ->addActionContext('resize-show', 'json')
->addActionContext('delete-show', 'json') ->addActionContext('delete-show', 'json')
->addActionContext('show-content-dialog', 'json') ->addActionContext('show-content-dialog', 'json')
->addActionContext('clear-show', 'json') ->addActionContext('clear-show', 'json')
->addActionContext('get-current-playlist', 'json') ->addActionContext('get-current-playlist', 'json')
->addActionContext('remove-group', 'json') ->addActionContext('remove-group', 'json')
->addActionContext('populate-show-form', 'json') ->addActionContext('populate-show-form', 'json')
->addActionContext('populate-show-instance-form', 'json') ->addActionContext('populate-show-instance-form', 'json')
->addActionContext('cancel-show', 'json') ->addActionContext('cancel-show', 'json')
@ -32,9 +32,10 @@ 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");
} }
public function indexAction() public function indexAction()
@ -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,12 +91,12 @@ 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;
} }
$this->view->headScript()->appendScript("var weekStart = ".Application_Model_Preference::GetWeekStartDay().";"); $this->view->headScript()->appendScript("var weekStart = ".Application_Model_Preference::GetWeekStartDay().";");
} }
@ -105,16 +107,27 @@ class ScheduleController extends Zend_Controller_Action
$end = new DateTime($this->_getParam('end', null)); $end = new DateTime($this->_getParam('end', null));
$end->setTimezone(new DateTimeZone("UTC")); $end->setTimezone(new DateTimeZone("UTC"));
$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);
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);
@ -144,64 +158,66 @@ class ScheduleController extends Zend_Controller_Action
public function resizeShowAction() public function resizeShowAction()
{ {
$deltaDay = $this->_getParam('day'); $deltaDay = $this->_getParam('day');
$deltaMin = $this->_getParam('min'); $deltaMin = $this->_getParam('min');
$showId = $this->_getParam('showId'); $showId = $this->_getParam('showId');
$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);
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);
} }
if (isset($error)) { if (isset($error)) {
$this->view->error = $error; $this->view->error = $error;
} }
} }
public function deleteShowAction() public function deleteShowAction()
{ {
$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);
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){ Logging::info($e->getMessage());
$this->view->show_error = true; $this->view->show_error = true;
return false; return false;
} }
$showInstance->delete(); $showInstance->delete();
$this->view->show_id = $showInstance->getShowId(); $this->view->show_id = $showInstance->getShowId();
} }
} }
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,30 +230,31 @@ 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());
if ($instance->isRecorded() && $epochNow > $showEndLocalDT->getTimestamp()) { if ($instance->isRecorded() && $epochNow > $showEndLocalDT->getTimestamp()) {
$file = $instance->getRecordedFile(); $file = $instance->getRecordedFile();
$fileId = $file->getId(); $fileId = $file->getId();
$menu["view_recorded"] = array("name" => "View Recorded File Metadata", "icon" => "overview", $menu["view_recorded"] = array("name" => "View Recorded File Metadata", "icon" => "overview",
"url" => "/library/edit-file-md/id/".$fileId); "url" => "/library/edit-file-md/id/".$fileId);
} }
if ($epochNow < $showStartLocalDT->getTimestamp()) { if ($epochNow < $showStartLocalDT->getTimestamp()) {
if ( ($isAdminOrPM || $isDJ) if ( ($isAdminOrPM || $isDJ)
&& !$instance->isRecorded() && !$instance->isRecorded()
&& !$instance->isRebroadcast()) { && !$instance->isRebroadcast()) {
@ -257,18 +274,18 @@ class ScheduleController extends Zend_Controller_Action
if ($showEndLocalDT->getTimestamp() <= $epochNow if ($showEndLocalDT->getTimestamp() <= $epochNow
&& $instance->isRecorded() && $instance->isRecorded()
&& Application_Model_Preference::GetUploadToSoundcloudOption()) { && Application_Model_Preference::GetUploadToSoundcloudOption()) {
$file = $instance->getRecordedFile(); $file = $instance->getRecordedFile();
$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);
} }
$text = is_null($scid) ? 'Upload to SoundCloud' : 'Re-upload to SoundCloud'; $text = is_null($scid) ? 'Upload to SoundCloud' : 'Re-upload to SoundCloud';
$menu["soundcloud_upload"] = array("name"=> $text, "icon" => "soundcloud"); $menu["soundcloud_upload"] = array("name"=> $text, "icon" => "soundcloud");
} }
if ($showStartLocalDT->getTimestamp() <= $epochNow && if ($showStartLocalDT->getTimestamp() <= $epochNow &&
@ -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,58 +331,59 @@ 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();
$live_dj = Application_Model_Preference::GetSourceStatus("live_dj"); $live_dj = Application_Model_Preference::GetSourceStatus("live_dj");
$master_dj = Application_Model_Preference::GetSourceStatus("master_dj"); $master_dj = Application_Model_Preference::GetSourceStatus("master_dj");
$scheduled_play_switch = Application_Model_Preference::GetSourceSwitchStatus("scheduled_play"); $scheduled_play_switch = Application_Model_Preference::GetSourceSwitchStatus("scheduled_play");
$live_dj_switch = Application_Model_Preference::GetSourceSwitchStatus("live_dj"); $live_dj_switch = Application_Model_Preference::GetSourceSwitchStatus("live_dj");
$master_dj_switch = Application_Model_Preference::GetSourceSwitchStatus("master_dj"); $master_dj_switch = Application_Model_Preference::GetSourceSwitchStatus("master_dj");
//might not be the correct place to implement this but for now let's just do it here //might not be the correct place to implement this but for now let's just do it here
$source_status['live_dj_source'] = $live_dj; $source_status['live_dj_source'] = $live_dj;
$source_status['master_dj_source'] = $master_dj; $source_status['master_dj_source'] = $master_dj;
$this->view->source_status = $source_status; $this->view->source_status = $source_status;
$switch_status['live_dj_source'] = $live_dj_switch; $switch_status['live_dj_source'] = $live_dj_switch;
$switch_status['master_dj_source'] = $master_dj_switch; $switch_status['master_dj_source'] = $master_dj_switch;
$switch_status['scheduled_play'] = $scheduled_play_switch; $switch_status['scheduled_play'] = $scheduled_play_switch;
$this->view->switch_status = $switch_status; $this->view->switch_status = $switch_status;
$this->view->entries = $range; $this->view->entries = $range;
$this->view->show_name = isset($show[0])?$show[0]["name"]:""; $this->view->show_name = isset($show[0])?$show[0]["name"]:"";
} }
@ -376,44 +392,46 @@ 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);
} }
$this->view->showContent = $show->getShowContent(); $this->view->showContent = $show->getShowContent();
$this->view->timeFilled = $show->getTimeScheduled(); $this->view->timeFilled = $show->getTimeScheduled();
$this->view->percentFilled = $show->getPercentScheduled(); $this->view->percentFilled = $show->getPercentScheduled();
$this->view->chosen = $this->view->render('schedule/scheduled-content.phtml'); $this->view->chosen = $this->view->render('schedule/scheduled-content.phtml');
unset($this->view->showContent); unset($this->view->showContent);
} }
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();
@ -440,53 +458,53 @@ class ScheduleController extends Zend_Controller_Action
// this feature is disabled in 2.1 and should be back in 2.2 // this feature is disabled in 2.1 and should be back in 2.2
/*public function populateShowInstanceFormAction(){ /*public function populateShowInstanceFormAction(){
$formWhat = new Application_Form_AddShowWhat(); $formWhat = new Application_Form_AddShowWhat();
$formWho = new Application_Form_AddShowWho(); $formWho = new Application_Form_AddShowWho();
$formWhen = new Application_Form_AddShowWhen(); $formWhen = new Application_Form_AddShowWhen();
$formRepeats = new Application_Form_AddShowRepeats(); $formRepeats = new Application_Form_AddShowRepeats();
$formStyle = new Application_Form_AddShowStyle(); $formStyle = new Application_Form_AddShowStyle();
$formLive = new Application_Form_AddShowLiveStream(); $formLive = new Application_Form_AddShowLiveStream();
$formWhat->removeDecorator('DtDdWrapper'); $formWhat->removeDecorator('DtDdWrapper');
$formWho->removeDecorator('DtDdWrapper'); $formWho->removeDecorator('DtDdWrapper');
$formWhen->removeDecorator('DtDdWrapper'); $formWhen->removeDecorator('DtDdWrapper');
$formRepeats->removeDecorator('DtDdWrapper'); $formRepeats->removeDecorator('DtDdWrapper');
$formStyle->removeDecorator('DtDdWrapper'); $formStyle->removeDecorator('DtDdWrapper');
$this->view->what = $formWhat; $this->view->what = $formWhat;
$this->view->when = $formWhen; $this->view->when = $formWhen;
$this->view->repeats = $formRepeats; $this->view->repeats = $formRepeats;
$this->view->who = $formWho; $this->view->who = $formWho;
$this->view->style = $formStyle; $this->view->style = $formStyle;
$this->view->live = $formLive; $this->view->live = $formLive;
$this->view->addNewShow = false; $this->view->addNewShow = false;
$showInstanceId = $this->_getParam('id'); $showInstanceId = $this->_getParam('id');
$show_instance = CcShowInstancesQuery::create()->findPK($showInstanceId); $show_instance = CcShowInstancesQuery::create()->findPK($showInstanceId);
$show = new Application_Model_Show($show_instance->getDbShowId()); $show = new Application_Model_Show($show_instance->getDbShowId());
$starts_string = $show_instance->getDbStarts(); $starts_string = $show_instance->getDbStarts();
$ends_string = $show_instance->getDbEnds(); $ends_string = $show_instance->getDbEnds();
$starts_datetime = new DateTime($starts_string, new DateTimeZone("UTC")); $starts_datetime = new DateTime($starts_string, new DateTimeZone("UTC"));
$ends_datetime = new DateTime($ends_string, new DateTimeZone("UTC")); $ends_datetime = new DateTime($ends_string, new DateTimeZone("UTC"));
$starts_datetime->setTimezone(new DateTimeZone(date_default_timezone_get())); $starts_datetime->setTimezone(new DateTimeZone(date_default_timezone_get()));
$ends_datetime->setTimezone(new DateTimeZone(date_default_timezone_get())); $ends_datetime->setTimezone(new DateTimeZone(date_default_timezone_get()));
$instance_duration = $starts_datetime->diff($ends_datetime); $instance_duration = $starts_datetime->diff($ends_datetime);
$formWhat->populate(array('add_show_id' => $show->getId(), $formWhat->populate(array('add_show_id' => $show->getId(),
'add_show_instance_id' => $showInstanceId, 'add_show_instance_id' => $showInstanceId,
'add_show_name' => $show->getName(), 'add_show_name' => $show->getName(),
'add_show_url' => $show->getUrl(), 'add_show_url' => $show->getUrl(),
'add_show_genre' => $show->getGenre(), 'add_show_genre' => $show->getGenre(),
'add_show_description' => $show->getDescription())); 'add_show_description' => $show->getDescription()));
$formWhen->populate(array('add_show_start_date' => $starts_datetime->format("Y-m-d"), $formWhen->populate(array('add_show_start_date' => $starts_datetime->format("Y-m-d"),
'add_show_start_time' => $starts_datetime->format("H:i"), 'add_show_start_time' => $starts_datetime->format("H:i"),
'add_show_end_date_no_repeat' => $ends_datetime->format("Y-m-d"), 'add_show_end_date_no_repeat' => $ends_datetime->format("Y-m-d"),
'add_show_end_time' => $ends_datetime->format("H:i"), 'add_show_end_time' => $ends_datetime->format("H:i"),
'add_show_duration' => $instance_duration->format("%h"))); 'add_show_duration' => $instance_duration->format("%h")));
$formWhat->disable(); $formWhat->disable();
@ -494,13 +512,11 @@ class ScheduleController extends Zend_Controller_Action
$formWhen->disableRepeatCheckbox(); $formWhen->disableRepeatCheckbox();
$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,48 +529,46 @@ 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";
} }
$formWhat = new Application_Form_AddShowWhat(); $formWhat = new Application_Form_AddShowWhat();
$formWho = new Application_Form_AddShowWho(); $formWho = new Application_Form_AddShowWho();
$formWhen = new Application_Form_AddShowWhen(); $formWhen = new Application_Form_AddShowWhen();
$formRepeats = new Application_Form_AddShowRepeats(); $formRepeats = new Application_Form_AddShowRepeats();
$formStyle = new Application_Form_AddShowStyle(); $formStyle = new Application_Form_AddShowStyle();
$formLive = new Application_Form_AddShowLiveStream(); $formLive = new Application_Form_AddShowLiveStream();
$formWhat->removeDecorator('DtDdWrapper'); $formWhat->removeDecorator('DtDdWrapper');
$formWho->removeDecorator('DtDdWrapper'); $formWho->removeDecorator('DtDdWrapper');
$formWhen->removeDecorator('DtDdWrapper'); $formWhen->removeDecorator('DtDdWrapper');
$formRepeats->removeDecorator('DtDdWrapper'); $formRepeats->removeDecorator('DtDdWrapper');
$formStyle->removeDecorator('DtDdWrapper'); $formStyle->removeDecorator('DtDdWrapper');
$this->view->what = $formWhat; $this->view->what = $formWhat;
$this->view->when = $formWhen; $this->view->when = $formWhen;
$this->view->repeats = $formRepeats; $this->view->repeats = $formRepeats;
$this->view->who = $formWho; $this->view->who = $formWho;
$this->view->style = $formStyle; $this->view->style = $formStyle;
$this->view->live = $formLive; $this->view->live = $formLive;
$this->view->addNewShow = false; $this->view->addNewShow = false;
$show = new Application_Model_Show($showInstance->getShowId()); $show = new Application_Model_Show($showInstance->getShowId());
@ -574,17 +588,17 @@ class ScheduleController extends Zend_Controller_Action
$formWhen->populate(array('add_show_start_date' => $startsDateTime->format("Y-m-d"), $formWhen->populate(array('add_show_start_date' => $startsDateTime->format("Y-m-d"),
'add_show_start_time' => $startsDateTime->format("H:i"), 'add_show_start_time' => $startsDateTime->format("H:i"),
'add_show_end_date_no_repeat' => $endsDateTime->format("Y-m-d"), 'add_show_end_date_no_repeat' => $endsDateTime->format("Y-m-d"),
'add_show_end_time' => $endsDateTime->format("H:i"), 'add_show_end_time' => $endsDateTime->format("H:i"),
'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,16 +623,16 @@ 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));
$formStyle->populate(array('add_show_background_color' => $show->getBackgroundColor(), $formStyle->populate(array('add_show_background_color' => $show->getBackgroundColor(),
'add_show_color' => $show->getColor())); 'add_show_color' => $show->getColor()));
$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,46 +690,47 @@ 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"];
} }
//update cc_show //update cc_show
$show = new Application_Model_Show($data["add_show_id"]); $show = new Application_Model_Show($data["add_show_id"]);
$show->setAirtimeAuthFlag($data["cb_airtime_auth"]); $show->setAirtimeAuthFlag($data["cb_airtime_auth"]);
$show->setCustomAuthFlag($data["cb_custom_auth"]); $show->setCustomAuthFlag($data["cb_custom_auth"]);
$show->setCustomUsername($data["custom_username"]); $show->setCustomUsername($data["custom_username"]);
$show->setCustomPassword($data["custom_password"]); $show->setCustomPassword($data["custom_password"]);
$this->view->edit = true; $this->view->edit = true;
} }
/*public function editShowInstanceAction(){ /*public function editShowInstanceAction(){
$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"];
} }
$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 {
@ -723,54 +738,63 @@ class ScheduleController extends Zend_Controller_Action
$this->view->form = $this->view->render('schedule/add-show-form.phtml'); $this->view->form = $this->view->render('schedule/add-show-form.phtml');
} }
}*/ }*/
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;
} }
$validateStartDate = false; $validateStartDate = false;
} }
$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);
$success = Application_Model_Schedule::addUpdateShow($data, $this,
if ($success){ $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));
@ -779,46 +803,53 @@ class ScheduleController extends Zend_Controller_Action
$this->view->form = $this->view->render('schedule/add-show-form.phtml'); $this->view->form = $this->view->render('schedule/add-show-form.phtml');
} }
} }
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,31 +861,29 @@ 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');
try { try {
$scheduler = new Application_Model_Scheduler(); $scheduler = new Application_Model_Scheduler();
$scheduler->cancelShow($id); $scheduler->cancelShow($id);
// 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::info($e->getMessage());
Logging::log($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');
$params = '/format/json/id/#id#/'; $params = '/format/json/id/#id#/';
@ -869,7 +898,7 @@ class ScheduleController extends Zend_Controller_Action
$baseUrl = $this->getRequest()->getBaseUrl(); $baseUrl = $this->getRequest()->getBaseUrl();
$url = $file->getRelativeFileUrl($baseUrl).'/download/true'; $url = $file->getRelativeFileUrl($baseUrl).'/download/true';
$menu[] = array('action' => array('type' => 'gourl', 'url' => $url), $menu[] = array('action' => array('type' => 'gourl', 'url' => $url),
'title' => 'Download'); 'title' => 'Download');
//returns format jjmenu is looking for. //returns format jjmenu is looking for.
die(json_encode($menu)); die(json_encode($menu));
@ -879,50 +908,52 @@ 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'));
} }
/** /**
* 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);
$UTCStartDateTime = $startDateTime->setTimezone(new DateTimeZone('UTC')); $UTCStartDateTime = $startDateTime->setTimezone(new DateTimeZone('UTC'));
$UTCEndDateTime = $endDateTime->setTimezone(new DateTimeZone('UTC')); $UTCEndDateTime = $endDateTime->setTimezone(new DateTimeZone('UTC'));
$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";
} }
echo Zend_Json::encode($result); echo Zend_Json::encode($result);
exit(); exit();
} }
} }

View file

@ -16,142 +16,138 @@ 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 {
$this->view->headScript()->appendScript("localStorage.setItem( 'datatables-timeline', '' );");
} }
else {
$this->view->headScript()->appendScript("localStorage.setItem( 'datatables-timeline', '' );");
}
$this->view->headScript()->appendFile($baseUrl.'/js/contextmenu/jquery.contextMenu.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/js/jquery.dataTables.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.pluginAPI.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.fnSetFilteringDelay.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.ColVis.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.ColReorder.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/datatables/plugin/dataTables.FixedColumns.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/blockui/jquery.blockUI.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/buttons/buttons.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/utilities/utilities.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/library/library.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headLink()->appendStylesheet($baseUrl.'/css/media_library.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'/css/jquery.contextMenu.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'/css/datatables/css/ColVis.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'/css/datatables/css/ColReorder.css?'.$CC_CONFIG['airtime_version']);
$this->view->headScript()->appendFile($baseUrl.'/js/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/blockui/jquery.blockUI.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/buttons/buttons.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/utilities/utilities.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/library/library.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headLink()->appendStylesheet($baseUrl.'/css/media_library.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'/css/jquery.contextMenu.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'/css/datatables/css/ColVis.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'/css/datatables/css/ColReorder.css?'.$CC_CONFIG['airtime_version']);
$this->view->headScript()->appendFile($this->view->baseUrl('/js/airtime/library/events/library_showbuilder.js?'.$CC_CONFIG['airtime_version']),'text/javascript'); $this->view->headScript()->appendFile($this->view->baseUrl('/js/airtime/library/events/library_showbuilder.js?'.$CC_CONFIG['airtime_version']),'text/javascript');
$refer_sses = new Zend_Session_Namespace('referrer'); $refer_sses = new Zend_Session_Namespace('referrer');
if ($request->isPost()) { if ($request->isPost()) {
$form = new Application_Form_RegisterAirtime(); $form = new Application_Form_RegisterAirtime();
$values = $request->getPost(); $values = $request->getPost();
if ($values["Publicise"] != 1 && $form->isValid($values)) { if ($values["Publicise"] != 1 && $form->isValid($values)) {
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');
} } 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"]); Application_Model_Preference::SetStationWebSite($values["StationWebSite"]);
Application_Model_Preference::SetStationWebSite($values["StationWebSite"]); Application_Model_Preference::SetPublicise($values["Publicise"]);
Application_Model_Preference::SetPublicise($values["Publicise"]);
$form->Logo->receive();
$form->Logo->receive(); $imagePath = $form->Logo->getFileName();
$imagePath = $form->Logo->getFileName();
Application_Model_Preference::SetStationCountry($values["Country"]);
Application_Model_Preference::SetStationCountry($values["Country"]); 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); 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 {
} $logo = Application_Model_Preference::GetStationLogo();
else { if ($logo) {
$logo = Application_Model_Preference::GetStationLogo(); $this->view->logoImg = $logo;
if ($logo) { }
$this->view->logoImg = $logo; $this->view->dialog = $form;
} $this->view->headScript()->appendFile($baseUrl.'/js/airtime/nowplaying/register.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->dialog = $form;
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/nowplaying/register.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
}
}
//popup if previous page was login
if ($refer_sses->referrer == 'login' && Application_Model_Preference::ShouldShowPopUp()
&& !Application_Model_Preference::GetSupportFeedback() && $user->isAdmin()){
$form = new Application_Form_RegisterAirtime();
$logo = Application_Model_Preference::GetStationLogo();
if ($logo) {
$this->view->logoImg = $logo;
}
$this->view->dialog = $form;
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/nowplaying/register.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
}
//determine whether to remove/hide/display the library.
$showLib = false;
if (!$user->isGuest()) {
$disableLib = false;
$data = Application_Model_Preference::GetValue("nowplaying_screen", true);
if ($data != "") {
$settings = unserialize($data);
if ($settings["library"] == "true") {
$showLib = true;
}
} }
} }
else {
$disableLib = true; //popup if previous page was login
} if ($refer_sses->referrer == 'login' && Application_Model_Preference::ShouldShowPopUp()
$this->view->disableLib = $disableLib; && !Application_Model_Preference::GetSupportFeedback() && $user->isAdmin()){
$this->view->showLib = $showLib;
$form = new Application_Form_RegisterAirtime();
$logo = Application_Model_Preference::GetStationLogo();
if ($logo) {
$this->view->logoImg = $logo;
}
$this->view->dialog = $form;
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/nowplaying/register.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
}
//determine whether to remove/hide/display the library.
$showLib = false;
if (!$user->isGuest()) {
$disableLib = false;
$data = Application_Model_Preference::getNowPlayingScreenSettings();
if (!is_null($data)) {
if ($data["library"] == "true") {
$showLib = true;
}
}
} else {
$disableLib = true;
}
$this->view->disableLib = $disableLib;
$this->view->showLib = $showLib;
//populate date range form for show builder. //populate date range form for show builder.
$now = time(); $now = time();
$from = $request->getParam("from", $now); $from = $request->getParam("from", $now);
$to = $request->getParam("to", $now + (24*60*60)); $to = $request->getParam("to", $now + (24*60*60));
$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()));
@ -159,8 +155,8 @@ class ShowbuilderController extends Zend_Controller_Action
$form->populate(array( $form->populate(array(
'sb_date_start' => $start->format("Y-m-d"), 'sb_date_start' => $start->format("Y-m-d"),
'sb_time_start' => $start->format("H:i"), 'sb_time_start' => $start->format("H:i"),
'sb_date_end' => $end->format("Y-m-d"), 'sb_date_end' => $end->format("Y-m-d"),
'sb_time_end' => $end->format("H:i") 'sb_time_end' => $end->format("H:i")
)); ));
$this->view->sb_form = $form; $this->view->sb_form = $form;
@ -174,37 +170,36 @@ class ShowbuilderController extends Zend_Controller_Action
$this->view->headLink()->appendStylesheet($baseUrl.'/css/jquery.ui.timepicker.css?'.$CC_CONFIG['airtime_version']); $this->view->headLink()->appendStylesheet($baseUrl.'/css/jquery.ui.timepicker.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'/css/showbuilder.css?'.$CC_CONFIG['airtime_version']); $this->view->headLink()->appendStylesheet($baseUrl.'/css/showbuilder.css?'.$CC_CONFIG['airtime_version']);
} }
public function contextMenuAction() public function contextMenuAction()
{ {
$id = $this->_getParam('id'); $id = $this->_getParam('id');
$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"=> "Remove from show", "icon" => "delete", "url" => "/showbuilder/schedule-remove");
$menu["del"] = array("name"=> "Delete", "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,68 +227,56 @@ 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();
$starts_epoch = $request->getParam("start", $current_time); $starts_epoch = $request->getParam("start", $current_time);
//default ends is 24 hours after starts. //default ends is 24 hours after starts.
$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)); $timestamp = intval($request->getParam("timestamp", -1));
$instances = $request->getParam("instances", array()); $instances = $request->getParam("instances", array());
$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"));
$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);
//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();
$starts_epoch = $request->getParam("start", $current_time); $starts_epoch = $request->getParam("start", $current_time);
//default ends is 24 hours after starts. //default ends is 24 hours after starts.
$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"));
$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

@ -5,10 +5,10 @@ class SystemstatusController extends Zend_Controller_Action
public function init() public function init()
{ {
global $CC_CONFIG; global $CC_CONFIG;
$request = $this->getRequest(); $request = $this->getRequest();
$baseUrl = $request->getBaseUrl(); $baseUrl = $request->getBaseUrl();
$this->view->headScript()->appendFile($baseUrl.'/js/airtime/status/status.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $this->view->headScript()->appendFile($baseUrl.'/js/airtime/status/status.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
} }
@ -22,7 +22,7 @@ class SystemstatusController extends Zend_Controller_Action
); );
$partitions = Application_Model_Systemstatus::GetDiskInfo(); $partitions = Application_Model_Systemstatus::GetDiskInfo();
$this->view->status = new StdClass; $this->view->status = new StdClass;
$this->view->status->services = $services; $this->view->status->services = $services;
$this->view->status->partitions = $partitions; $this->view->status->partitions = $partitions;

View file

@ -13,51 +13,59 @@ class UserController extends Zend_Controller_Action
->initContext(); ->initContext();
} }
public function indexAction()
{
}
public function addUserAction() public function addUserAction()
{ {
global $CC_CONFIG; global $CC_CONFIG;
$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']);
$form = new Application_Form_AddUser(); $form = new Application_Form_AddUser();
$this->view->successMessage = ""; $this->view->successMessage = "";
if ($request->isPost()) { if ($request->isPost()) {
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']);
$user->setSkype($formdata['skype']); $user->setSkype($formdata['skype']);
$user->setJabber($formdata['jabber']); $user->setJabber($formdata['jabber']);
$user->save(); $user->save();
$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>";
@ -65,14 +73,14 @@ class UserController extends Zend_Controller_Action
} }
} }
} }
$this->view->form = $form; $this->view->form = $form;
} }
public function getHostsAction() public function getHostsAction()
{ {
$search = $this->_getParam('term'); $search = $this->_getParam('term');
$res = Application_Model_User::getHosts($search); $res = Application_Model_User::getHosts($search);
$this->view->hosts = Application_Model_User::getHosts($search); $this->view->hosts = Application_Model_User::getHosts($search);
} }
@ -80,7 +88,7 @@ class UserController extends Zend_Controller_Action
{ {
$post = $this->getRequest()->getPost(); $post = $this->getRequest()->getPost();
$users = Application_Model_User::getUsersDataTablesInfo($post); $users = Application_Model_User::getUsersDataTablesInfo($post);
die(json_encode($users)); die(json_encode($users));
} }
@ -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
$user = new Application_Model_User($delId); if ($delId == $userId) {
$this->view->entries = $user->delete(); return;
} }
$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();
} }
} }

View file

@ -11,87 +11,84 @@ class UsersettingsController extends Zend_Controller_Action
->addActionContext('get-library-datatable', 'json') ->addActionContext('get-library-datatable', 'json')
->addActionContext('set-library-datatable', 'json') ->addActionContext('set-library-datatable', 'json')
->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() {
$request = $this->getRequest();
$settings = $request->getParam("settings");
$data = serialize($settings);
Application_Model_Preference::SetValue("nowplaying_screen", $data, true);
}
public function getNowPlayingScreenSettingsAction() {
$data = Application_Model_Preference::GetValue("nowplaying_screen", true);
if ($data != "") {
$this->view->settings = unserialize($data);
}
}
public function setLibraryDatatableAction() {
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("library_datatable", $data, true);
} }
public function getLibraryDatatableAction() { public function getNowPlayingScreenSettingsAction()
{
$data = Application_Model_Preference::GetValue("library_datatable", true); $data = Application_Model_Preference::getNowPlayingScreenSettings();
if ($data != "") { if (!is_null($data)) {
$this->view->settings = unserialize($data); $this->view->settings = $data;
} }
} }
public function setTimelineDatatableAction() { public function setLibraryDatatableAction()
{
$start = microtime(true);
$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("timeline_datatable", $data, true); }
public function getLibraryDatatableAction()
{
$data = Application_Model_Preference::getCurrentLibraryTableSetting();
if (!is_null($data)) {
$this->view->settings = $data;
}
}
public function setTimelineDatatableAction()
{
$request = $this->getRequest();
$settings = $request->getParam("settings");
Application_Model_Preference::setTimelineDatatableSetting($settings);
}
public function getTimelineDatatableAction()
{
$start = microtime(true);
$data = Application_Model_Preference::getTimelineDatatableSetting();
if (!is_null($data)) {
$this->view->settings = $data;
}
$end = microtime(true); $end = microtime(true);
Logging::debug("saving timeline datatables info took:"); Logging::debug("getting timeline datatables info took:");
Logging::debug(floatval($end) - floatval($start)); Logging::debug(floatval($end) - floatval($start));
} }
public function getTimelineDatatableAction() { public function remindmeAction()
{
$start = microtime(true); // unset session
Zend_Session::namespaceUnset('referrer');
$data = Application_Model_Preference::GetValue("timeline_datatable", true); Application_Model_Preference::SetRemindMeDate();
if ($data != "") {
$this->view->settings = unserialize($data);
}
$end = microtime(true);
Logging::debug("getting timeline datatables info took:");
Logging::debug(floatval($end) - floatval($start));
} }
public function remindmeAction() public function remindmeNeverAction()
{ {
// unset session Zend_Session::namespaceUnset('referrer');
Zend_Session::namespaceUnset('referrer'); //pass in true to indicate 'Remind me never' was clicked
Application_Model_Preference::SetRemindMeDate(); Application_Model_Preference::SetRemindMeDate(true);
}
public function donotshowregistrationpopupAction()
{
// unset session
Zend_Session::namespaceUnset('referrer');
} }
}
public function donotshowregistrationpopupAction()
{
// unset session
Zend_Session::namespaceUnset('referrer');
}
}

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

@ -26,8 +26,8 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
**/ **/
public function __construct(Zend_Acl $aclData, $roleName = 'G') public function __construct(Zend_Acl $aclData, $roleName = 'G')
{ {
$this->_errorPage = array('module' => 'default', $this->_errorPage = array('module' => 'default',
'controller' => 'error', 'controller' => 'error',
'action' => 'denied'); 'action' => 'denied');
$this->_roleName = $roleName; $this->_roleName = $roleName;
@ -40,7 +40,7 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
/** /**
* Sets the ACL object * Sets the ACL object
* *
* @param mixed $aclData * @param mixed $aclData
* @return void * @return void
**/ **/
public function setAcl(Zend_Acl $aclData) public function setAcl(Zend_Acl $aclData)
@ -62,29 +62,29 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
* Returns the ACL role used * Returns the ACL role used
* *
* @return string * @return string
* @author * @author
**/ **/
public function getRoleName() public function getRoleName()
{ {
return $this->_roleName; return $this->_roleName;
} }
public function setRoleName($type) public function setRoleName($type)
{ {
$this->_roleName = $type; $this->_roleName = $type;
} }
/** /**
* Sets the error page * Sets the error page
* *
* @param string $action * @param string $action
* @param string $controller * @param string $controller
* @param string $module * @param string $module
* @return void * @return void
**/ **/
public function setErrorPage($action, $controller = 'error', $module = null) public function setErrorPage($action, $controller = 'error', $module = null)
{ {
$this->_errorPage = array('module' => $module, $this->_errorPage = array('module' => $module,
'controller' => $controller, 'controller' => $controller,
'action' => $action); 'action' => $action);
} }
@ -108,58 +108,55 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
**/ **/
public function preDispatch(Zend_Controller_Request_Abstract $request) public function preDispatch(Zend_Controller_Request_Abstract $request)
{ {
$controller = strtolower($request->getControllerName()); $controller = strtolower($request->getControllerName());
if (in_array($controller, array("api", "auth"))){
$this->setRoleName("G");
}
else if (!Zend_Auth::getInstance()->hasIdentity()){
if ($controller !== 'login') {
if ($request->isXmlHttpRequest()) { if (in_array($controller, array("api", "auth"))) {
$url = 'http://'.$request->getHttpHost().'/login'; $this->setRoleName("G");
$json = Zend_Json::encode(array('auth' => false, 'url' => $url)); } elseif (!Zend_Auth::getInstance()->hasIdentity()) {
// Prepare response
$this->getResponse()
->setHttpResponseCode(401)
->setBody($json)
->sendResponse();
//redirectAndExit() cleans up, sends the headers and stops the script if ($controller !== 'login') {
Zend_Controller_Action_HelperBroker::getStaticHelper('redirector')->redirectAndExit();
}
else {
$r = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$r->gotoSimpleAndExit('index', 'login', $request->getModuleName());
}
}
}
else {
$userInfo = Zend_Auth::getInstance()->getStorage()->read(); if ($request->isXmlHttpRequest()) {
$this->setRoleName($userInfo->type);
$url = 'http://'.$request->getHttpHost().'/login';
$json = Zend_Json::encode(array('auth' => false, 'url' => $url));
// Prepare response
$this->getResponse()
->setHttpResponseCode(401)
->setBody($json)
->sendResponse();
//redirectAndExit() cleans up, sends the headers and stops the script
Zend_Controller_Action_HelperBroker::getStaticHelper('redirector')->redirectAndExit();
} else {
$r = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$r->gotoSimpleAndExit('index', 'login', $request->getModuleName());
}
}
} else {
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$this->setRoleName($userInfo->type);
Zend_View_Helper_Navigation_HelperAbstract::setDefaultAcl($this->_acl); Zend_View_Helper_Navigation_HelperAbstract::setDefaultAcl($this->_acl);
Zend_View_Helper_Navigation_HelperAbstract::setDefaultRole($this->_roleName); Zend_View_Helper_Navigation_HelperAbstract::setDefaultRole($this->_roleName);
$resourceName = '';
if ($request->getModuleName() != 'default') { $resourceName = '';
$resourceName .= strtolower($request->getModuleName()) . ':';
}
$resourceName .= $controller; if ($request->getModuleName() != 'default') {
$resourceName .= strtolower($request->getModuleName()) . ':';
}
/** Check if the controller/action can be accessed by the current user */ $resourceName .= $controller;
if (!$this->getAcl()->isAllowed($this->_roleName, $resourceName, $request->getActionName())) {
/** Redirect to access denied page */ /** Check if the controller/action can be accessed by the current user */
$this->denyAccess(); if (!$this->getAcl()->isAllowed($this->_roleName, $resourceName, $request->getActionName())) {
} /** Redirect to access denied page */
} $this->denyAccess();
}
}
} }
/** /**

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');
@ -29,44 +29,42 @@ class Application_Form_AddShowAbsoluteRebroadcastDates extends Zend_Form_SubForm
$this->addElement($text); $this->addElement($text);
} }
} }
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

@ -11,13 +11,13 @@ class Application_Form_AddShowLiveStream extends Zend_Form_SubForm
->setRequired(false) ->setRequired(false)
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
$this->addElement($cb_airtime_auth); $this->addElement($cb_airtime_auth);
$cb_custom_auth = new Zend_Form_Element_Checkbox("cb_custom_auth"); $cb_custom_auth = new Zend_Form_Element_Checkbox("cb_custom_auth");
$cb_custom_auth ->setLabel("Use Custom Authentication:") $cb_custom_auth ->setLabel("Use Custom Authentication:")
->setRequired(false) ->setRequired(false)
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
$this->addElement($cb_custom_auth); $this->addElement($cb_custom_auth);
//custom username //custom username
$custom_username = new Zend_Form_Element_Text('custom_username'); $custom_username = new Zend_Form_Element_Text('custom_username');
$custom_username->setAttrib('class', 'input_text') $custom_username->setAttrib('class', 'input_text')
@ -29,7 +29,7 @@ class Application_Form_AddShowLiveStream extends Zend_Form_SubForm
new ConditionalNotEmpty(array("cb_custom_auth"=>"1")))) new ConditionalNotEmpty(array("cb_custom_auth"=>"1"))))
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
$this->addElement($custom_username); $this->addElement($custom_username);
//custom password //custom password
$custom_password = new Zend_Form_Element_Password('custom_password'); $custom_password = new Zend_Form_Element_Password('custom_password');
$custom_password->setAttrib('class', 'input_text') $custom_password->setAttrib('class', 'input_text')
@ -42,32 +42,34 @@ class Application_Form_AddShowLiveStream extends Zend_Form_SubForm
new ConditionalNotEmpty(array("cb_custom_auth"=>"1")))) new ConditionalNotEmpty(array("cb_custom_auth"=>"1"))))
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
$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";
} }
$this->setDecorators(array( $this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/add-show-live-stream.phtml', "connection_url"=>$connection_url)) array('ViewScript', array('viewScript' => 'form/add-show-live-stream.phtml', "connection_url"=>$connection_url))
)); ));
} }
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

@ -6,28 +6,26 @@ class Application_Form_AddShowRR extends Zend_Form_SubForm
public function init() public function init()
{ {
// Add record element // Add record element
$this->addElement('checkbox', 'add_show_record', array( $this->addElement('checkbox', 'add_show_record', array(
'label' => 'Record from Line In?', 'label' => 'Record from Line In?',
'required' => false, 'required' => false,
)); ));
// Add record element // Add record element
$this->addElement('checkbox', 'add_show_rebroadcast', array( $this->addElement('checkbox', 'add_show_rebroadcast', array(
'label' => 'Rebroadcast?', 'label' => 'Rebroadcast?',
'required' => false, 'required' => false,
)); ));
} }
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');
@ -34,44 +34,42 @@ class Application_Form_AddShowRebroadcastDates extends Zend_Form_SubForm
$this->addElement($text); $this->addElement($text);
} }
} }
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

@ -6,78 +6,78 @@ class Application_Form_AddShowRepeats extends Zend_Form_SubForm
public function init() public function init()
{ {
//Add type select //Add type select
$this->addElement('select', 'add_show_repeat_type', array( $this->addElement('select', 'add_show_repeat_type', array(
'required' => true, 'required' => true,
'label' => 'Repeat Type:', 'label' => 'Repeat Type:',
'class' => ' input_select', 'class' => ' input_select',
'multiOptions' => array( 'multiOptions' => array(
"0" => "weekly", "0" => "weekly",
"1" => "bi-weekly", "1" => "bi-weekly",
"2" => "monthly" "2" => "monthly"
), ),
)); ));
// Add days checkboxes // Add days checkboxes
$this->addElement( $this->addElement(
'multiCheckbox', 'multiCheckbox',
'add_show_day_check', 'add_show_day_check',
array( array(
'label' => 'Select Days:', 'label' => 'Select Days:',
'required' => false, 'required' => false,
'multiOptions' => array( 'multiOptions' => array(
"0" => "Sun", "0" => "Sun",
"1" => "Mon", "1" => "Mon",
"2" => "Tue", "2" => "Tue",
"3" => "Wed", "3" => "Wed",
"4" => "Thu", "4" => "Thu",
"5" => "Fri", "5" => "Fri",
"6" => "Sat", "6" => "Sat",
), ),
)); ));
// Add end date element // Add end date element
$this->addElement('text', 'add_show_end_date', array( $this->addElement('text', 'add_show_end_date', array(
'label' => 'Date End:', 'label' => 'Date End:',
'class' => 'input_text', 'class' => 'input_text',
'value' => date("Y-m-d"), 'value' => date("Y-m-d"),
'required' => false, 'required' => false,
'filters' => array('StringTrim'), 'filters' => array('StringTrim'),
'validators' => array( 'validators' => array(
'NotEmpty', 'NotEmpty',
array('date', false, array('YYYY-MM-DD')) array('date', false, array('YYYY-MM-DD'))
) )
)); ));
// Add no end element // Add no end element
$this->addElement('checkbox', 'add_show_no_end', array( $this->addElement('checkbox', 'add_show_no_end', array(
'label' => 'No End?', 'label' => 'No End?',
'required' => false, 'required' => false,
'checked' => true, 'checked' => true,
)); ));
} }
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

@ -18,14 +18,13 @@ class Application_Form_AddShowStyle extends Zend_Form_SubForm
'viewScript' => 'form/add-show-style.phtml', 'viewScript' => 'form/add-show-style.phtml',
'class' => 'big' 'class' => 'big'
)))); ))));
$bg->setValidators(array( $bg->setValidators(array(
'Hex', 'Hex',
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:',
'class' => 'input_text', 'class' => 'input_text',
@ -38,23 +37,21 @@ class Application_Form_AddShowStyle extends Zend_Form_SubForm
'viewScript' => 'form/add-show-style.phtml', 'viewScript' => 'form/add-show-style.phtml',
'class' => 'big' 'class' => 'big'
)))); ))));
$c->setValidators(array( $c->setValidators(array(
'Hex', 'Hex',
array('stringLength', false, array(6, 6)) array('stringLength', false, array(6, 6))
)); ));
} }
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

@ -4,22 +4,22 @@ class Application_Form_AddShowWhat extends Zend_Form_SubForm
{ {
public function init() public function init()
{ {
// 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.
$this->addElement('hidden', 'add_show_id', array( $this->addElement('hidden', 'add_show_id', array(
'decorators' => array('ViewHelper') 'decorators' => array('ViewHelper')
)); ));
// Hidden element to indicate the instance id of the show // Hidden element to indicate the instance id of the show
// being edited. // being edited.
$this->addElement('hidden', 'add_show_instance_id', array( $this->addElement('hidden', 'add_show_instance_id', array(
'decorators' => array('ViewHelper') 'decorators' => array('ViewHelper')
)); ));
// Add name element // Add name element
$this->addElement('text', 'add_show_name', array( $this->addElement('text', 'add_show_name', array(
'label' => 'Name:', 'label' => 'Name:',
@ -27,8 +27,8 @@ class Application_Form_AddShowWhat extends Zend_Form_SubForm
'required' => true, 'required' => true,
'filters' => array('StringTrim'), 'filters' => array('StringTrim'),
'validators' => array('NotEmpty'), 'validators' => array('NotEmpty'),
'value' => 'Untitled Show', 'value' => 'Untitled Show',
'validators' => array(array('StringLength', false, array(0, $maxLens['name']))) 'validators' => array(array('StringLength', false, array(0, $maxLens['name'])))
)); ));
// Add URL element // Add URL element
@ -46,16 +46,16 @@ class Application_Form_AddShowWhat extends Zend_Form_SubForm
'class' => 'input_text', 'class' => 'input_text',
'required' => false, 'required' => false,
'filters' => array('StringTrim'), 'filters' => array('StringTrim'),
'validators' => array(array('StringLength', false, array(0, $maxLens['genre']))) 'validators' => array(array('StringLength', false, array(0, $maxLens['genre'])))
)); ));
// Add the description element // Add the description element
$this->addElement('textarea', 'add_show_description', array( $this->addElement('textarea', 'add_show_description', array(
'label' => 'Description:', 'label' => 'Description:',
'required' => false, 'required' => false,
'class' => 'input_text_area', 'class' => 'input_text_area',
'validators' => array(array('StringLength', false, array(0, $maxLens['description']))) 'validators' => array(array('StringLength', false, array(0, $maxLens['description'])))
)); ));
$descText = $this->getElement('add_show_description'); $descText = $this->getElement('add_show_description');
@ -65,16 +65,14 @@ 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

@ -8,7 +8,7 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
$this->setDecorators(array( $this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/add-show-when.phtml')) array('ViewScript', array('viewScript' => 'form/add-show-when.phtml'))
)); ));
// Add start date element // Add start date element
$startDate = new Zend_Form_Element_Text('add_show_start_date'); $startDate = new Zend_Form_Element_Text('add_show_start_date');
$startDate->class = 'input_text'; $startDate->class = 'input_text';
@ -22,7 +22,7 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
$startDate->setAttrib('alt', 'date'); $startDate->setAttrib('alt', 'date');
$this->addElement($startDate); $this->addElement($startDate);
// Add start time element // Add start time element
$startTime = new Zend_Form_Element_Text('add_show_start_time'); $startTime = new Zend_Form_Element_Text('add_show_start_time');
$startTime->class = 'input_text'; $startTime->class = 'input_text';
@ -50,7 +50,7 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
$endDate->setAttrib('alt', 'date'); $endDate->setAttrib('alt', 'date');
$this->addElement($endDate); $this->addElement($endDate);
// Add end time element // Add end time element
$endTime = new Zend_Form_Element_Text('add_show_end_time'); $endTime = new Zend_Form_Element_Text('add_show_end_time');
$endTime->class = 'input_text'; $endTime->class = 'input_text';
@ -64,7 +64,7 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
$endTime->setAttrib('alt', 'time'); $endTime->setAttrib('alt', 'time');
$this->addElement($endTime); $this->addElement($endTime);
// Add duration element // Add duration element
$this->addElement('text', 'add_show_duration', array( $this->addElement('text', 'add_show_duration', array(
'label' => 'Duration:', 'label' => 'Duration:',
@ -83,24 +83,25 @@ 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'];
$end_time = $formData['add_show_end_date_no_repeat']." ".$formData['add_show_end_time']; $end_time = $formData['add_show_end_date_no_repeat']." ".$formData['add_show_end_time'];
//DateTime stores $start_time in the current timezone //DateTime stores $start_time in the current timezone
$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'));
@ -109,66 +110,258 @@ 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;
} }
$pattern = '/([0-9][0-9])h ([0-9][0-9])m/'; $pattern = '/([0-9][0-9])h ([0-9][0-9])m/';
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 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(){ 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

@ -10,32 +10,30 @@ class Application_Form_AddShowWho extends Zend_Form_SubForm
'label' => 'Search Users:', 'label' => 'Search Users:',
'class' => 'input_text ui-autocomplete-input', 'class' => 'input_text ui-autocomplete-input',
'required' => false 'required' => false
)); ));
$options = array(); $options = array();
$hosts = Application_Model_User::getHosts(); $hosts = Application_Model_User::getHosts();
foreach ($hosts as $host) { foreach ($hosts as $host) {
$options[$host['index']] = $host['label']; $options[$host['index']] = $host['label'];
} }
//Add hosts selection //Add hosts selection
$hosts = new Zend_Form_Element_MultiCheckbox('add_show_hosts'); $hosts = new Zend_Form_Element_MultiCheckbox('add_show_hosts');
$hosts->setLabel('DJs:') $hosts->setLabel('DJs:')
->setMultiOptions($options); ->setMultiOptions($options);
$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

@ -10,11 +10,11 @@ class Application_Form_AddUser extends Zend_Form
'../application/validate', '../application/validate',
'validate'); 'validate');
* */ * */
$hidden = new Zend_Form_Element_Hidden('user_id'); $hidden = new Zend_Form_Element_Hidden('user_id');
$hidden->setDecorators(array('ViewHelper')); $hidden->setDecorators(array('ViewHelper'));
$this->addElement($hidden); $this->addElement($hidden);
$login = new Zend_Form_Element_Text('login'); $login = new Zend_Form_Element_Text('login');
$login->setLabel('Username:'); $login->setLabel('Username:');
$login->setAttrib('class', 'input_text'); $login->setAttrib('class', 'input_text');
@ -22,7 +22,7 @@ class Application_Form_AddUser extends Zend_Form
$login->addFilter('StringTrim'); $login->addFilter('StringTrim');
//$login->addValidator('UserNameValidate'); //$login->addValidator('UserNameValidate');
$this->addElement($login); $this->addElement($login);
$password = new Zend_Form_Element_Password('password'); $password = new Zend_Form_Element_Password('password');
$password->setLabel('Password:'); $password->setLabel('Password:');
$password->setAttrib('class', 'input_text'); $password->setAttrib('class', 'input_text');
@ -30,21 +30,21 @@ class Application_Form_AddUser extends Zend_Form
$password->addFilter('StringTrim'); $password->addFilter('StringTrim');
$password->addValidator('NotEmpty'); $password->addValidator('NotEmpty');
$this->addElement($password); $this->addElement($password);
$firstName = new Zend_Form_Element_Text('first_name'); $firstName = new Zend_Form_Element_Text('first_name');
$firstName->setLabel('Firstname:'); $firstName->setLabel('Firstname:');
$firstName->setAttrib('class', 'input_text'); $firstName->setAttrib('class', 'input_text');
$firstName->addFilter('StringTrim'); $firstName->addFilter('StringTrim');
$firstName->addValidator('NotEmpty'); $firstName->addValidator('NotEmpty');
$this->addElement($firstName); $this->addElement($firstName);
$lastName = new Zend_Form_Element_Text('last_name'); $lastName = new Zend_Form_Element_Text('last_name');
$lastName->setLabel('Lastname:'); $lastName->setLabel('Lastname:');
$lastName->setAttrib('class', 'input_text'); $lastName->setAttrib('class', 'input_text');
$lastName->addFilter('StringTrim'); $lastName->addFilter('StringTrim');
$lastName->addValidator('NotEmpty'); $lastName->addValidator('NotEmpty');
$this->addElement($lastName); $this->addElement($lastName);
$email = new Zend_Form_Element_Text('email'); $email = new Zend_Form_Element_Text('email');
$email->setLabel('Email:'); $email->setLabel('Email:');
$email->setAttrib('class', 'input_text'); $email->setAttrib('class', 'input_text');
@ -52,7 +52,7 @@ class Application_Form_AddUser extends Zend_Form
$email->setRequired(true); $email->setRequired(true);
$email->addValidator('EmailAddress'); $email->addValidator('EmailAddress');
$this->addElement($email); $this->addElement($email);
$cellPhone = new Zend_Form_Element_Text('cell_phone'); $cellPhone = new Zend_Form_Element_Text('cell_phone');
$cellPhone->setLabel('Mobile Phone:'); $cellPhone->setLabel('Mobile Phone:');
$cellPhone->setAttrib('class', 'input_text'); $cellPhone->setAttrib('class', 'input_text');
@ -79,31 +79,31 @@ class Application_Form_AddUser extends Zend_Form
$select->setMultiOptions(array( $select->setMultiOptions(array(
"G" => "Guest", "G" => "Guest",
"H" => "DJ", "H" => "DJ",
"P" => "Program Manager", "P" => "Program Manager",
"A" => "Admin" "A" => "Admin"
)); ));
$select->setRequired(true); $select->setRequired(true);
$this->addElement($select); $this->addElement($select);
$submit = new Zend_Form_Element_Submit('submit'); $submit = new Zend_Form_Element_Submit('submit');
$submit->setAttrib('class', 'ui-button ui-state-default right-floated'); $submit->setAttrib('class', 'ui-button ui-state-default right-floated');
$submit->setIgnore(true); $submit->setIgnore(true);
$submit->setLabel('Save'); $submit->setLabel('Save');
$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;
} }
} }
return true; return true;
} }
} }

View file

@ -7,21 +7,21 @@ class Application_Form_EditAudioMD extends Zend_Form
// Set the method for the display form to POST // Set the method for the display form to POST
$this->setMethod('post'); $this->setMethod('post');
// Add title field // Add title field
$this->addElement('text', 'track_title', array( $this->addElement('text', 'track_title', array(
'label' => 'Title:', 'label' => 'Title:',
'class' => 'input_text', 'class' => 'input_text',
'filters' => array('StringTrim'), 'filters' => array('StringTrim'),
)); ));
// Add artist field // Add artist field
$this->addElement('text', 'artist_name', array( $this->addElement('text', 'artist_name', array(
'label' => 'Creator:', 'label' => 'Creator:',
'class' => 'input_text', 'class' => 'input_text',
'filters' => array('StringTrim'), 'filters' => array('StringTrim'),
)); ));
// Add album field // Add album field
$this->addElement('text', 'album_title', array( $this->addElement('text', 'album_title', array(
'label' => 'Album:', 'label' => 'Album:',
'class' => 'input_text', 'class' => 'input_text',
@ -32,44 +32,42 @@ 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
$this->addElement('text', 'genre', array( $this->addElement('text', 'genre', array(
'label' => 'Genre:', 'label' => 'Genre:',
'class' => 'input_text', 'class' => 'input_text',
'filters' => array('StringTrim') 'filters' => array('StringTrim')
)); ));
// Add year field // Add year field
$this->addElement('text', 'year', array( $this->addElement('text', 'year', array(
'label' => 'Year:', 'label' => 'Year:',
'class' => 'input_text', 'class' => 'input_text',
'filters' => array('StringTrim'), 'filters' => array('StringTrim'),
'validators' => array( 'validators' => array(
array('date', false, array('YYYY-MM-DD')), array('date', false, array('YYYY-MM-DD')),
array('date', false, array('YYYY-MM')), array('date', false, array('YYYY-MM')),
array('date', false, array('YYYY')) array('date', false, array('YYYY'))
) )
)); ));
// Add label field // Add label field
$this->addElement('text', 'label', array( $this->addElement('text', 'label', array(
'label' => 'Label:', 'label' => 'Label:',
'class' => 'input_text', 'class' => 'input_text',
'filters' => array('StringTrim') 'filters' => array('StringTrim')
)); ));
// Add composer field // Add composer field
$this->addElement('text', 'composer', array( $this->addElement('text', 'composer', array(
'label' => 'Composer:', 'label' => 'Composer:',
'class' => 'input_text', 'class' => 'input_text',
'filters' => array('StringTrim') 'filters' => array('StringTrim')
)); ));
// Add conductor field // Add conductor field
$this->addElement('text', 'conductor', array( $this->addElement('text', 'conductor', array(
'label' => 'Conductor:', 'label' => 'Conductor:',
@ -77,7 +75,7 @@ class Application_Form_EditAudioMD extends Zend_Form
'filters' => array('StringTrim') 'filters' => array('StringTrim')
)); ));
// Add mood field // Add mood field
$this->addElement('text', 'mood', array( $this->addElement('text', 'mood', array(
'label' => 'Mood:', 'label' => 'Mood:',
'class' => 'input_text', 'class' => 'input_text',
@ -122,22 +120,22 @@ class Application_Form_EditAudioMD extends Zend_Form
'filters' => array('StringTrim') 'filters' => array('StringTrim')
)); ));
// 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'
) )
)); ));
// 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

@ -9,8 +9,8 @@ class Application_Form_EmailServerPreferences extends Zend_Form_SubForm
public function init() public function init()
{ {
$isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; $isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true;
$this->isSaas = $isSaas; $this->isSaas = $isSaas;
$this->setDecorators(array( $this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/preferences_email_server.phtml', "isSaas" => $isSaas)) array('ViewScript', array('viewScript' => 'form/preferences_email_server.phtml', "isSaas" => $isSaas))
)); ));
@ -24,7 +24,7 @@ class Application_Form_EmailServerPreferences extends Zend_Form_SubForm
'ViewHelper' 'ViewHelper'
) )
)); ));
$this->addElement('text', 'systemEmail', array( $this->addElement('text', 'systemEmail', array(
'class' => 'input_text', 'class' => 'input_text',
'label' => 'Reset Password \'From\' Email', 'label' => 'Reset Password \'From\' Email',
@ -32,7 +32,7 @@ class Application_Form_EmailServerPreferences extends Zend_Form_SubForm
'readonly' => true, 'readonly' => true,
'decorators' => array('viewHelper') 'decorators' => array('viewHelper')
)); ));
$this->addElement('checkbox', 'configureMailServer', array( $this->addElement('checkbox', 'configureMailServer', array(
'label' => 'Configure Mail Server', 'label' => 'Configure Mail Server',
'required' => false, 'required' => false,
@ -41,7 +41,16 @@ class Application_Form_EmailServerPreferences extends Zend_Form_SubForm
'viewHelper' 'viewHelper'
) )
)); ));
$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,10 +59,12 @@ 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'
))
) )
)); ));
$this->addElement('text', 'email', array( $this->addElement('text', 'email', array(
'class' => 'input_text', 'class' => 'input_text',
'label' => 'Email Address', 'label' => 'Email Address',
@ -62,10 +73,13 @@ 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'
))
) )
)); ));
$this->addElement('password', 'ms_password', array( $this->addElement('password', 'ms_password', array(
'class' => 'input_text', 'class' => 'input_text',
'label' => 'Password', 'label' => 'Password',
@ -74,11 +88,14 @@ 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
)); ));
$port = new Zend_Form_Element_Text('port'); $port = new Zend_Form_Element_Text('port');
$port->class = 'input_text'; $port->class = 'input_text';
$port->setRequired(false) $port->setRequired(false)
@ -86,11 +103,9 @@ class Application_Form_EmailServerPreferences extends Zend_Form_SubForm
->setLabel('Port') ->setLabel('Port')
->setAttrib('readonly', true) ->setAttrib('readonly', true)
->setDecorators(array('viewHelper')); ->setDecorators(array('viewHelper'));
$this->addElement($port); $this->addElement($port);
} }
} }

View file

@ -2,19 +2,19 @@
class Application_Form_GeneralPreferences extends Zend_Form_SubForm class Application_Form_GeneralPreferences extends Zend_Form_SubForm
{ {
private $isSaas; private $isSaas;
public function init() public function init()
{ {
$isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; $isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true;
$this->isSaas = $isSaas; $this->isSaas = $isSaas;
$this->setDecorators(array( $this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/preferences_general.phtml', "isSaas" => $isSaas)) array('ViewScript', array('viewScript' => 'form/preferences_general.phtml', "isSaas" => $isSaas))
)); ));
$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,18 +97,18 @@ class Application_Form_GeneralPreferences extends Zend_Form_SubForm
return $tzlist; return $tzlist;
} }
private function getWeekStartDays()
{
$days = array(
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
);
private function getWeekStartDays() { return $days;
$days = array(
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
);
return $days;
} }
} }

View file

@ -2,33 +2,33 @@
class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
{ {
public function init() public function init()
{ {
global $CC_CONFIG; global $CC_CONFIG;
$isDemo = isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1; $isDemo = isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1;
$isStreamConfigable = Application_Model_Preference::GetEnableStreamConf() == "true"; $isStreamConfigable = Application_Model_Preference::GetEnableStreamConf() == "true";
$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';
} }
// automatic trasition on source disconnection // automatic trasition on source disconnection
$auto_transition = new Zend_Form_Element_Checkbox("auto_transition"); $auto_transition = new Zend_Form_Element_Checkbox("auto_transition");
$auto_transition->setLabel("Auto Switch Off") $auto_transition->setLabel("Auto Switch Off")
->setValue(Application_Model_Preference::GetAutoTransition()) ->setValue(Application_Model_Preference::GetAutoTransition())
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
$this->addElement($auto_transition); $this->addElement($auto_transition);
// automatic switch on upon source connection // automatic switch on upon source connection
$auto_switch = new Zend_Form_Element_Checkbox("auto_switch"); $auto_switch = new Zend_Form_Element_Checkbox("auto_switch");
$auto_switch->setLabel("Auto Switch On") $auto_switch->setLabel("Auto Switch On")
->setValue(Application_Model_Preference::GetAutoSwitch()) ->setValue(Application_Model_Preference::GetAutoSwitch())
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
$this->addElement($auto_switch); $this->addElement($auto_switch);
// Default transition fade // Default transition fade
$transition_fade = new Zend_Form_Element_Text("transition_fade"); $transition_fade = new Zend_Form_Element_Text("transition_fade");
$transition_fade->setLabel("Switch Transition Fade (s)") $transition_fade->setLabel("Switch Transition Fade (s)")
@ -38,33 +38,33 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
->setValue($defaultFade) ->setValue($defaultFade)
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
$this->addElement($transition_fade); $this->addElement($transition_fade);
//Master username //Master username
$master_username = new Zend_Form_Element_Text('master_username'); $master_username = new Zend_Form_Element_Text('master_username');
$master_username->setAttrib('autocomplete', 'off') $master_username->setAttrib('autocomplete', 'off')
->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'));
$this->addElement($master_password); $this->addElement($master_password);
//Master source connection url //Master source connection url
$master_dj_connection_url = new Zend_Form_Element_Text('master_dj_connection_url'); $master_dj_connection_url = new Zend_Form_Element_Text('master_dj_connection_url');
$master_dj_connection_url->setAttrib('readonly', true) $master_dj_connection_url->setAttrib('readonly', true)
@ -72,7 +72,7 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
->setValue(Application_Model_Preference::GetMasterDJSourceConnectionURL()) ->setValue(Application_Model_Preference::GetMasterDJSourceConnectionURL())
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
$this->addElement($master_dj_connection_url); $this->addElement($master_dj_connection_url);
//Show source connection url //Show source connection url
$live_dj_connection_url = new Zend_Form_Element_Text('live_dj_connection_url'); $live_dj_connection_url = new Zend_Form_Element_Text('live_dj_connection_url');
$live_dj_connection_url->setAttrib('readonly', true) $live_dj_connection_url->setAttrib('readonly', true)
@ -80,10 +80,10 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
->setValue(Application_Model_Preference::GetLiveDJSourceConnectionURL()) ->setValue(Application_Model_Preference::GetLiveDJSourceConnectionURL())
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
$this->addElement($live_dj_connection_url); $this->addElement($live_dj_connection_url);
//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)
@ -91,8 +91,8 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
->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'));
$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)
@ -100,9 +100,9 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
array('regex', false, array('/^[^ &<>]+$/', 'messages' => 'Invalid character entered')))) array('regex', false, array('/^[^ &<>]+$/', 'messages' => 'Invalid character entered'))))
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
$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)
@ -110,8 +110,8 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
->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'));
$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,76 +121,77 @@ 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;
$isDemo = isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1; $isDemo = isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1;
$master_dj_connection_url = Application_Model_Preference::GetMasterDJSourceConnectionURL(); $master_dj_connection_url = Application_Model_Preference::GetMasterDJSourceConnectionURL();
$live_dj_connection_url = Application_Model_Preference::GetLiveDJSourceConnectionURL(); $live_dj_connection_url = Application_Model_Preference::GetLiveDJSourceConnectionURL();
$this->setDecorators(array( $this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/preferences_livestream.phtml', 'master_dj_connection_url'=>$master_dj_connection_url, 'live_dj_connection_url'=>$live_dj_connection_url, 'isSaas' => $isSaas, 'isDemo' => $isDemo)) array('ViewScript', array('viewScript' => 'form/preferences_livestream.phtml', 'master_dj_connection_url'=>$master_dj_connection_url, 'live_dj_connection_url'=>$live_dj_connection_url, 'isSaas' => $isSaas, 'isDemo' => $isDemo))
)); ));
} }
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

@ -4,17 +4,17 @@ class Application_Form_Login extends Zend_Form
{ {
public function init() public function init()
{ {
global $CC_CONFIG; global $CC_CONFIG;
// Set the method for the display form to POST // Set the method for the display form to POST
$this->setMethod('post'); $this->setMethod('post');
$this->setDecorators(array( $this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/login.phtml')) array('ViewScript', array('viewScript' => 'form/login.phtml'))
)); ));
// Add username element // Add username element
$this->addElement('text', 'username', array( $this->addElement('text', 'username', array(
'label' => 'Username:', 'label' => 'Username:',
'class' => 'input_text', 'class' => 'input_text',
@ -28,8 +28,8 @@ class Application_Form_Login extends Zend_Form
'ViewHelper' 'ViewHelper'
) )
)); ));
// Add password element // Add password element
$this->addElement('password', 'password', array( $this->addElement('password', 'password', array(
'label' => 'Password:', 'label' => 'Password:',
'class' => 'input_text', 'class' => 'input_text',
@ -43,17 +43,17 @@ class Application_Form_Login extends Zend_Form
'ViewHelper' 'ViewHelper'
) )
)); ));
$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();
} }
// Add the submit button // Add the submit button
$this->addElement('submit', 'submit', array( $this->addElement('submit', 'submit', array(
'ignore' => true, 'ignore' => true,
'label' => 'Login', 'label' => 'Login',
@ -64,13 +64,14 @@ class Application_Form_Login extends Zend_Form
)); ));
} }
public function addRecaptcha(){ public function addRecaptcha()
{
$pubKey = '6Ld4JsISAAAAAIxUKT4IjjOGi3DHqdoH2zk6WkYG'; $pubKey = '6Ld4JsISAAAAAIxUKT4IjjOGi3DHqdoH2zk6WkYG';
$privKey = '6Ld4JsISAAAAAJynYlXdrE4hfTReTSxYFe5szdyv'; $privKey = '6Ld4JsISAAAAAJynYlXdrE4hfTReTSxYFe5szdyv';
$recaptcha = new Zend_Service_ReCaptcha($pubKey, $privKey); $recaptcha = new Zend_Service_ReCaptcha($pubKey, $privKey);
$captcha = new Zend_Form_Element_Captcha('captcha', $captcha = new Zend_Form_Element_Captcha('captcha',
array( array(
'label' => 'Type the characters you see in the picture below.', 'label' => 'Type the characters you see in the picture below.',
@ -84,6 +85,4 @@ class Application_Form_Login extends Zend_Form
$this->addElement($captcha); $this->addElement($captcha);
} }
} }

View file

@ -6,10 +6,10 @@ class Application_Form_PasswordChange extends Zend_Form
{ {
public function init() public function init()
{ {
$this->setDecorators(array( $this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/password-change.phtml')) array('ViewScript', array('viewScript' => 'form/password-change.phtml'))
)); ));
$this->addElement('password', 'password', array( $this->addElement('password', 'password', array(
'label' => 'Password', 'label' => 'Password',
'required' => true, 'required' => true,

View file

@ -6,10 +6,10 @@ class Application_Form_PasswordRestore extends Zend_Form
{ {
public function init() public function init()
{ {
$this->setDecorators(array( $this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/password-restore.phtml')) array('ViewScript', array('viewScript' => 'form/password-restore.phtml'))
)); ));
$this->addElement('text', 'email', array( $this->addElement('text', 'email', array(
'label' => 'E-mail', 'label' => 'E-mail',
'required' => true, 'required' => true,
@ -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,
@ -29,7 +40,7 @@ class Application_Form_PasswordRestore extends Zend_Form
'ViewHelper' 'ViewHelper'
) )
)); ));
$cancel = new Zend_Form_Element_Button("cancel"); $cancel = new Zend_Form_Element_Button("cancel");
$cancel->class = 'ui-button ui-widget ui-state-default ui-button-text-only center'; $cancel->class = 'ui-button ui-widget ui-state-default ui-button-text-only center';
$cancel->setLabel("Cancel") $cancel->setLabel("Cancel")
@ -38,4 +49,4 @@ class Application_Form_PasswordRestore extends Zend_Form
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
$this->addElement($cancel); $this->addElement($cancel);
} }
} }

View file

@ -8,22 +8,22 @@ class Application_Form_Preferences extends Zend_Form
{ {
$this->setAction('/Preference'); $this->setAction('/Preference');
$this->setMethod('post'); $this->setMethod('post');
$isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; $isSaas = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true;
$this->isSaas = $isSaas; $this->isSaas = $isSaas;
$this->setDecorators(array( $this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/preferences.phtml', "isSaas" => $this->isSaas)) array('ViewScript', array('viewScript' => 'form/preferences.phtml', "isSaas" => $this->isSaas))
)); ));
$general_pref = new Application_Form_GeneralPreferences(); $general_pref = new Application_Form_GeneralPreferences();
$this->addSubForm($general_pref, 'preferences_general'); $this->addSubForm($general_pref, 'preferences_general');
if (!$isSaas) { if (!$isSaas) {
$email_pref = new Application_Form_EmailServerPreferences(); $email_pref = new Application_Form_EmailServerPreferences();
$this->addSubForm($email_pref, 'preferences_email_server'); $this->addSubForm($email_pref, 'preferences_email_server');
} }
$soundcloud_pref = new Application_Form_SoundcloudPreferences(); $soundcloud_pref = new Application_Form_SoundcloudPreferences();
$this->addSubForm($soundcloud_pref, 'preferences_soundcloud'); $this->addSubForm($soundcloud_pref, 'preferences_soundcloud');

View file

@ -9,19 +9,22 @@ class Application_Form_RegisterAirtime extends Zend_Form
{ {
$this->setAction('/Showbuilder'); $this->setAction('/Showbuilder');
$this->setMethod('post'); $this->setMethod('post');
$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
$stnName = new Zend_Form_Element_Text("stnName"); $stnName = new Zend_Form_Element_Text("stnName");
$stnName->setLabel("Station Name") $stnName->setLabel("Station Name")
@ -29,14 +32,14 @@ class Application_Form_RegisterAirtime extends Zend_Form
->setValue(Application_Model_Preference::GetStationName()) ->setValue(Application_Model_Preference::GetStationName())
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
$this->addElement($stnName); $this->addElement($stnName);
// Phone number // Phone number
$this->addElement('text', 'Phone', array( $this->addElement('text', 'Phone', array(
'class' => 'input_text', 'class' => 'input_text',
'label' => 'Phone:', 'label' => 'Phone:',
'required' => false, 'required' => false,
'filters' => array('StringTrim'), 'filters' => array('StringTrim'),
'value' => Application_Model_Preference::GetPhone(), 'value' => Application_Model_Preference::GetPhone(),
'decorators' => array( 'decorators' => array(
'ViewHelper' 'ViewHelper'
) )
@ -48,7 +51,7 @@ class Application_Form_RegisterAirtime extends Zend_Form
'label' => 'Email:', 'label' => 'Email:',
'required' => false, 'required' => false,
'filters' => array('StringTrim'), 'filters' => array('StringTrim'),
'value' => Application_Model_Preference::GetEmail(), 'value' => Application_Model_Preference::GetEmail(),
'decorators' => array( 'decorators' => array(
'ViewHelper' 'ViewHelper'
) )
@ -63,20 +66,20 @@ class Application_Form_RegisterAirtime extends Zend_Form
'decorators' => array( 'decorators' => array(
'ViewHelper' 'ViewHelper'
) )
)); ));
// county list dropdown // county list dropdown
$this->addElement('select', 'Country', array( $this->addElement('select', 'Country', array(
'label' => 'Country:', 'label' => 'Country:',
'required' => false, 'required' => false,
'value' => Application_Model_Preference::GetStationCountry(), 'value' => Application_Model_Preference::GetStationCountry(),
'multiOptions' => $country_list, 'multiOptions' => $country_list,
'decorators' => array( 'decorators' => array(
'ViewHelper' 'ViewHelper'
) )
)); ));
// Station city // Station city
$this->addElement('text', 'City', array( $this->addElement('text', 'City', array(
'label' => 'City:', 'label' => 'City:',
'required' => false, 'required' => false,
@ -85,29 +88,29 @@ class Application_Form_RegisterAirtime extends Zend_Form
'decorators' => array( 'decorators' => array(
'ViewHelper' 'ViewHelper'
) )
)); ));
// Station Description // Station Description
$description = new Zend_Form_Element_Textarea('Description'); $description = new Zend_Form_Element_Textarea('Description');
$description->class = 'input_text_area'; $description->class = 'input_text_area';
$description->setLabel('Station Description:') $description->setLabel('Station Description:')
->setRequired(false) ->setRequired(false)
->setValue(Application_Model_Preference::GetStationDescription()) ->setValue(Application_Model_Preference::GetStationDescription())
->setDecorators(array('ViewHelper')) ->setDecorators(array('ViewHelper'))
->setAttrib('ROWS','2') ->setAttrib('ROWS','2')
->setAttrib('COLS','58'); ->setAttrib('COLS','58');
$this->addElement($description); $this->addElement($description);
// Station Logo // Station Logo
$upload = new Zend_Form_Element_File('Logo'); $upload = new Zend_Form_Element_File('Logo');
$upload->setLabel('Station Logo:') $upload->setLabel('Station Logo:')
->setRequired(false) ->setRequired(false)
->setDecorators(array('File')) ->setDecorators(array('File'))
->addValidator('Count', false, 1) ->addValidator('Count', false, 1)
->addValidator('Extension', false, 'jpg,jpeg,png,gif') ->addValidator('Extension', false, 'jpg,jpeg,png,gif')
->addFilter('ImageSize'); ->addFilter('ImageSize');
$this->addElement($upload); $this->addElement($upload);
//enable support feedback //enable support feedback
$this->addElement('checkbox', 'SupportFeedback', array( $this->addElement('checkbox', 'SupportFeedback', array(
'label' => 'Send support feedback', 'label' => 'Send support feedback',
@ -116,52 +119,52 @@ class Application_Form_RegisterAirtime extends Zend_Form
'decorators' => array( 'decorators' => array(
'ViewHelper' 'ViewHelper'
) )
)); ));
// checkbox for publicise // checkbox for publicise
$checkboxPublicise = new Zend_Form_Element_Checkbox("Publicise"); $checkboxPublicise = new Zend_Form_Element_Checkbox("Publicise");
$checkboxPublicise->setLabel('Promote my station on Sourcefabric.org') $checkboxPublicise->setLabel('Promote my station on Sourcefabric.org')
->setRequired(false) ->setRequired(false)
->setDecorators(array('ViewHelper')) ->setDecorators(array('ViewHelper'))
->setValue(Application_Model_Preference::GetPublicise()); ->setValue(Application_Model_Preference::GetPublicise());
$this->addElement($checkboxPublicise); $this->addElement($checkboxPublicise);
// text area for sending detail // text area for sending detail
$this->addElement('textarea', 'SendInfo', array( $this->addElement('textarea', 'SendInfo', array(
'class' => 'sending_textarea', 'class' => 'sending_textarea',
'required' => false, 'required' => false,
'filters' => array('StringTrim'), 'filters' => array('StringTrim'),
'readonly' => true, 'readonly' => true,
'rows' => 5, 'rows' => 5,
'cols' => 61, 'cols' => 61,
'value' => Application_Model_Preference::GetSystemInfo(false, true), 'value' => Application_Model_Preference::GetSystemInfo(false, true),
'decorators' => array( 'decorators' => array(
'ViewHelper' 'ViewHelper'
) )
)); ));
// checkbox for privacy policy // checkbox for privacy policy
$checkboxPrivacy = new Zend_Form_Element_Checkbox("Privacy"); $checkboxPrivacy = new Zend_Form_Element_Checkbox("Privacy");
$checkboxPrivacy->setLabel("By checking this box, I agree to Sourcefabric's <a id=\"link_to_privacy\" href=\"http://www.sourcefabric.org/en/about/policy/\" onclick=\"window.open(this.href); return false;\">privacy policy</a>.") $checkboxPrivacy->setLabel("By checking this box, I agree to Sourcefabric's <a id=\"link_to_privacy\" href=\"http://www.sourcefabric.org/en/about/policy/\" onclick=\"window.open(this.href); return false;\">privacy policy</a>.")
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
$this->addElement($checkboxPrivacy); $this->addElement($checkboxPrivacy);
} }
// overriding isValid function // overriding isValid function
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

@ -30,7 +30,7 @@ class Application_Form_SoundcloudPreferences extends Zend_Form_SubForm
'ViewHelper' 'ViewHelper'
) )
)); ));
//enable downloadable for soundcloud //enable downloadable for soundcloud
$this->addElement('checkbox', 'SoundCloudDownloadbleOption', array( $this->addElement('checkbox', 'SoundCloudDownloadbleOption', array(
'label' => 'Automatically Mark Files "Downloadable" on SoundCloud', 'label' => 'Automatically Mark Files "Downloadable" on SoundCloud',
@ -51,7 +51,7 @@ class Application_Form_SoundcloudPreferences extends Zend_Form_SubForm
'decorators' => array( 'decorators' => array(
'ViewHelper' 'ViewHelper'
), ),
// By default, 'allowEmpty' is true. This means that our custom // By default, 'allowEmpty' is true. This means that our custom
// validators are going to be skipped if this field is empty, // validators are going to be skipped if this field is empty,
// which is something we don't want // which is something we don't want
@ -71,7 +71,7 @@ class Application_Form_SoundcloudPreferences extends Zend_Form_SubForm
'decorators' => array( 'decorators' => array(
'ViewHelper' 'ViewHelper'
), ),
// By default, 'allowEmpty' is true. This means that our custom // By default, 'allowEmpty' is true. This means that our custom
// validators are going to be skipped if this field is empty, // validators are going to be skipped if this field is empty,
// which is something we don't want // which is something we don't want
@ -79,7 +79,7 @@ class Application_Form_SoundcloudPreferences extends Zend_Form_SubForm
'validators' => array( 'validators' => array(
new ConditionalNotEmpty(array('UploadToSoundcloudOption'=>'1')) new ConditionalNotEmpty(array('UploadToSoundcloudOption'=>'1'))
), ),
'renderPassword' => true 'renderPassword' => true
)); ));
// Add the description element // Add the description element
@ -91,7 +91,7 @@ class Application_Form_SoundcloudPreferences extends Zend_Form_SubForm
'decorators' => array( 'decorators' => array(
'ViewHelper' 'ViewHelper'
) )
)); ));
//SoundCloud default genre //SoundCloud default genre
$this->addElement('text', 'SoundCloudGenre', array( $this->addElement('text', 'SoundCloudGenre', array(
@ -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,18 +34,18 @@ 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);
} }
$icecast_vorbis_metadata = new Zend_Form_Element_Checkbox('icecast_vorbis_metadata'); $icecast_vorbis_metadata = new Zend_Form_Element_Checkbox('icecast_vorbis_metadata');
$icecast_vorbis_metadata->setLabel('Icecast Vorbis Metadata') $icecast_vorbis_metadata->setLabel('Icecast Vorbis Metadata')
->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,41 +185,43 @@ 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');
$this->addElement($user); $this->addElement($user);
$liquidsopa_error_msg = '<div class="stream-status status-info"><h3>Getting information from the server...</h3></div>'; $liquidsopa_error_msg = '<div class="stream-status status-info"><h3>Getting information from the server...</h3></div>';
$this->setDecorators(array( $this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/stream-setting-form.phtml', "stream_number"=>$stream_number, "enabled"=>$enable->getValue(), "liquidsoap_error_msg"=>$liquidsopa_error_msg)) array('ViewScript', array('viewScript' => 'form/stream-setting-form.phtml', "stream_number"=>$stream_number, "enabled"=>$enable->getValue(), "liquidsoap_error_msg"=>$liquidsopa_error_msg))
)); ));
} }
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

@ -5,18 +5,18 @@ require_once 'customfilters/ImageSize.php';
class Application_Form_SupportSettings extends Zend_Form class Application_Form_SupportSettings extends Zend_Form
{ {
private $isSass; private $isSass;
public function init() public function init()
{ {
$country_list = Application_Model_Preference::GetCountryList(); $country_list = Application_Model_Preference::GetCountryList();
$isSass = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true; $isSass = Application_Model_Preference::GetPlanLevel() == 'disabled'?false:true;
$this->isSass = $isSass; $this->isSass = $isSass;
$this->setDecorators(array( $this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/support-setting.phtml', "isSaas" => $isSass)), array('ViewScript', array('viewScript' => 'form/support-setting.phtml', "isSaas" => $isSass)),
array('File', array('viewScript' => 'form/support-setting.phtml', 'placement' => false))) array('File', array('viewScript' => 'form/support-setting.phtml', 'placement' => false)))
); );
//Station name //Station name
$this->addElement('text', 'stationName', array( $this->addElement('text', 'stationName', array(
'class' => 'input_text', 'class' => 'input_text',
@ -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'
) )
@ -63,20 +63,20 @@ class Application_Form_SupportSettings extends Zend_Form
'decorators' => array( 'decorators' => array(
'ViewHelper' 'ViewHelper'
) )
)); ));
// county list dropdown // county list dropdown
$this->addElement('select', 'Country', array( $this->addElement('select', 'Country', array(
'label' => 'Country:', 'label' => 'Country:',
'required' => false, 'required' => false,
'value' => Application_Model_Preference::GetStationCountry(), 'value' => Application_Model_Preference::GetStationCountry(),
'multiOptions' => $country_list, 'multiOptions' => $country_list,
'decorators' => array( 'decorators' => array(
'ViewHelper' 'ViewHelper'
) )
)); ));
// Station city // Station city
$this->addElement('text', 'City', array( $this->addElement('text', 'City', array(
'label' => 'City:', 'label' => 'City:',
'required' => false, 'required' => false,
@ -85,31 +85,31 @@ class Application_Form_SupportSettings extends Zend_Form
'decorators' => array( 'decorators' => array(
'ViewHelper' 'ViewHelper'
) )
)); ));
// Station Description // Station Description
$description = new Zend_Form_Element_Textarea('Description'); $description = new Zend_Form_Element_Textarea('Description');
$description->class = 'input_text_area'; $description->class = 'input_text_area';
$description->setLabel('Station Description:') $description->setLabel('Station Description:')
->setRequired(false) ->setRequired(false)
->setValue(Application_Model_Preference::GetStationDescription()) ->setValue(Application_Model_Preference::GetStationDescription())
->setDecorators(array('ViewHelper')) ->setDecorators(array('ViewHelper'))
->setAttrib('ROWS','2') ->setAttrib('ROWS','2')
->setAttrib('COLS','58'); ->setAttrib('COLS','58');
$this->addElement($description); $this->addElement($description);
// Station Logo // Station Logo
$upload = new Zend_Form_Element_File('Logo'); $upload = new Zend_Form_Element_File('Logo');
$upload->setLabel('Station Logo:') $upload->setLabel('Station Logo:')
->setRequired(false) ->setRequired(false)
->setDecorators(array('File')) ->setDecorators(array('File'))
->addValidator('Count', false, 1) ->addValidator('Count', false, 1)
->addValidator('Extension', false, 'jpg,jpeg,png,gif') ->addValidator('Extension', false, 'jpg,jpeg,png,gif')
->addFilter('ImageSize'); ->addFilter('ImageSize');
$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',
@ -118,40 +118,40 @@ class Application_Form_SupportSettings extends Zend_Form
'decorators' => array( 'decorators' => array(
'ViewHelper' 'ViewHelper'
) )
)); ));
// checkbox for publicise // checkbox for publicise
$checkboxPublicise = new Zend_Form_Element_Checkbox("Publicise"); $checkboxPublicise = new Zend_Form_Element_Checkbox("Publicise");
$checkboxPublicise->setLabel('Promote my station on Sourcefabric.org') $checkboxPublicise->setLabel('Promote my station on Sourcefabric.org')
->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);
// text area for sending detail // text area for sending detail
$this->addElement('textarea', 'SendInfo', array( $this->addElement('textarea', 'SendInfo', array(
'class' => 'sending_textarea', 'class' => 'sending_textarea',
'required' => false, 'required' => false,
'filters' => array('StringTrim'), 'filters' => array('StringTrim'),
'readonly' => true, 'readonly' => true,
'cols' => 61, 'cols' => 61,
'rows' => 5, 'rows' => 5,
'value' => Application_Model_Preference::GetSystemInfo(false, true), 'value' => Application_Model_Preference::GetSystemInfo(false, true),
'decorators' => array( 'decorators' => array(
'ViewHelper' 'ViewHelper'
) )
)); ));
// checkbox for privacy policy // checkbox for privacy policy
$checkboxPrivacy = new Zend_Form_Element_Checkbox("Privacy"); $checkboxPrivacy = new Zend_Form_Element_Checkbox("Privacy");
$checkboxPrivacy->setLabel("By checking this box, I agree to Sourcefabric's <a id=\"link_to_privacy\" href=\"http://www.sourcefabric.org/en/about/policy/\" onclick=\"window.open(this.href); return false;\">privacy policy</a>.") $checkboxPrivacy->setLabel("By checking this box, I agree to Sourcefabric's <a id=\"link_to_privacy\" href=\"http://www.sourcefabric.org/en/about/policy/\" onclick=\"window.open(this.href); return false;\">privacy policy</a>.")
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
$this->addElement($checkboxPrivacy); $this->addElement($checkboxPrivacy);
} }
// submit button // submit button
$submit = new Zend_Form_Element_Submit("submit"); $submit = new Zend_Form_Element_Submit("submit");
$submit->class = 'ui-button ui-state-default right-floated'; $submit->class = 'ui-button ui-state-default right-floated';
@ -160,24 +160,24 @@ class Application_Form_SupportSettings extends Zend_Form
->setDecorators(array('ViewHelper')); ->setDecorators(array('ViewHelper'));
$this->addElement($submit); $this->addElement($submit);
} }
// overriding isValid function // overriding isValid function
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);
} }
@ -16,7 +18,7 @@ class Zend_Filter_ImageSize implements Zend_Filter_Interface {
$origWidth = imagesx($image); $origWidth = imagesx($image);
$origHeight = imagesy($image); $origHeight = imagesy($image);
$ratio = max($origWidth, $origHeight) / 600; $ratio = max($origWidth, $origHeight) / 600;
if ($ratio > 1) { if ($ratio > 1) {
// img too big! create a scaled down image // img too big! create a scaled down image
$newWidth = round($origWidth / $ratio); $newWidth = round($origWidth / $ratio);
@ -34,9 +36,7 @@ class Zend_Filter_ImageSize implements Zend_Filter_Interface {
$writeFunc($resized, $value); $writeFunc($resized, $value);
} }
} }
return $value; return $value;
} }
} }
?>

View file

@ -3,37 +3,37 @@
/** /**
* 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(
self::KEY_IS_EMPTY => 'Value is required and can\'t be empty' self::KEY_IS_EMPTY => 'Value is required and can\'t be empty'
); );
protected $_fieldValues; protected $_fieldValues;
/** /**
* Constructs a new ConditionalNotEmpty validator. * Constructs a new ConditionalNotEmpty validator.
* *
* @param array $fieldValues - the names and expected values of the fields we're depending on; * @param array $fieldValues - the names and expected values of the fields we're depending on;
* E.g., if we have a field that should only be validated when two other * E.g., if we have a field that should only be validated when two other
* fields PARENT_1 and PARENT_2 have values of '1' and '0' respectively, then * fields PARENT_1 and PARENT_2 have values of '1' and '0' respectively, then
* $fieldValues should contain ('PARENT_1'=>'1', 'PARENT_2'=>'0') * $fieldValues should contain ('PARENT_1'=>'1', 'PARENT_2'=>'0')
*/ */
public function __construct($fieldValues) public function __construct($fieldValues)
{ {
$this->_fieldValues = $fieldValues; $this->_fieldValues = $fieldValues;
} }
/** /**
* Implements Zend_Validate_Abstract. * Implements Zend_Validate_Abstract.
* Given names and expected values of the fields we're depending on ($_fieldValues), * Given names and expected values of the fields we're depending on ($_fieldValues),
* this function returns true if the expected values doesn't match the actual user input, * this function returns true if the expected values doesn't match the actual user input,
* or if $value is not empty. Returns false otherwise. * or if $value is not empty. Returns false otherwise.
* *
* @param String $value - this field's value * @param String $value - this field's value
* @param array $context - names and values of the rest of the fields in this form * @param array $context - names and values of the rest of the fields in this form
* @return boolean - true if valid; false otherwise * @return boolean - true if valid; false otherwise
*/ */
public function isValid($value, $context = null) public function isValid($value, $context = null)
@ -41,9 +41,9 @@ class ConditionalNotEmpty extends Zend_Validate_Abstract {
if ($value != "") { if ($value != "") {
return true; return true;
} }
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;
} }
@ -53,10 +53,9 @@ class ConditionalNotEmpty extends Zend_Validate_Abstract {
return true; return true;
} }
} }
$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 warn($p_msg)
{
$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->warn("[$file : $function() : line $line] - "
. self::toString($p_msg));
} }
public static function debug($p_msg){ public static function debug($p_msg)
$bt = debug_backtrace(); {
$caller = array_shift($bt); if (!(defined('APPLICATION_ENV') && APPLICATION_ENV == "development")) {
return;
if (defined('APPLICATION_ENV') && APPLICATION_ENV == "development"){
$logger = self::getLogger();
$logger->debug(self::toString($p_msg)." - file:".$caller['file'].":".$caller['line']);
} }
$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,53 +1,55 @@
<?php <?php
class Application_Model_Auth { class Application_Model_Auth
{
const TOKEN_LIFETIME = 'P2D'; // DateInterval syntax const TOKEN_LIFETIME = 'P2D'; // DateInterval syntax
private function generateToken($action, $user_id) private function generateToken($action, $user_id)
{ {
$salt = md5("pro"); $salt = md5("pro");
$token = self::generateRandomString(); $token = self::generateRandomString();
$info = new CcSubjsToken(); $info = new CcSubjsToken();
$info->setDbUserId($user_id); $info->setDbUserId($user_id);
$info->setDbAction($action); $info->setDbAction($action);
$info->setDbToken(sha1($token.$salt)); $info->setDbToken(sha1($token.$salt));
$info->setDbCreated(gmdate('Y-m-d H:i:s')); $info->setDbCreated(gmdate('Y-m-d H:i:s'));
$info->save(); $info->save();
Logging::debug("generated token {$token}"); Logging::debug("generated token {$token}");
return $token; return $token;
} }
public function sendPasswordRestoreLink($user, $view) public function sendPasswordRestoreLink($user, $view)
{ {
$token = $this->generateToken('password.restore', $user->getDbId()); $token = $this->generateToken('password.restore', $user->getDbId());
$e_link_protocol = empty($_SERVER['HTTPS']) ? "http" : "https"; $e_link_protocol = empty($_SERVER['HTTPS']) ? "http" : "https";
$e_link_base = $_SERVER['SERVER_NAME']; $e_link_base = $_SERVER['SERVER_NAME'];
$e_link_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());
return $success;
} return $success;
}
public function invalidateTokens($user, $action)
{ public function invalidateTokens($user, $action)
CcSubjsTokenQuery::create() {
->filterByDbAction($action) CcSubjsTokenQuery::create()
->filterByDbUserId($user->getDbId()) ->filterByDbAction($action)
->delete(); ->filterByDbUserId($user->getDbId())
} ->delete();
}
public function checkToken($user_id, $token, $action) public function checkToken($user_id, $token, $action)
{ {
$salt = md5("pro"); $salt = md5("pro");
$token_info = CcSubjsTokenQuery::create() $token_info = CcSubjsTokenQuery::create()
->filterByDbAction($action) ->filterByDbAction($action)
->filterByDbUserId($user_id) ->filterByDbUserId($user_id)
@ -61,10 +63,10 @@ class Application_Model_Auth {
$now = new DateTime(); $now = new DateTime();
$token_life = new DateInterval(self::TOKEN_LIFETIME); $token_life = new DateInterval(self::TOKEN_LIFETIME);
$token_created = new DateTime($token_info->getDbCreated(), new DateTimeZone("UTC")); $token_created = new DateTime($token_info->getDbCreated(), new DateTimeZone("UTC"));
return $now->sub($token_life)->getTimestamp() < $token_created->getTimestamp(); return $now->sub($token_life)->getTimestamp() < $token_created->getTimestamp();
} }
/** /**
* Gets the adapter for authentication against a database table * Gets the adapter for authentication against a database table
* *
@ -79,15 +81,15 @@ class Application_Model_Auth {
->setIdentityColumn('login') ->setIdentityColumn('login')
->setCredentialColumn('pass') ->setCredentialColumn('pass')
->setCredentialTreatment('MD5(?)'); ->setCredentialTreatment('MD5(?)');
return $authAdapter; return $authAdapter;
} }
/** /**
* Get random string * Get random string
* *
* @param int $length * @param int $length
* @param string $allowed_chars * @param string $allowed_chars
* @return string * @return string
*/ */
final public function generateRandomString($length = 12, $allowed_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') final public function generateRandomString($length = 12, $allowed_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')

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(),
@ -121,8 +125,8 @@ 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,104 +1,224 @@
<?php <?php
class Application_Model_Datatables { class Application_Model_Datatables
{
/* private static function buildWhereClauseForAdvancedSearch($dbname2searchTerm)
* query used to return data for a paginated/searchable datatable. {
*/ $where['clause'] = array();
public static function findEntries($con, $displayColumns, $fromTable, $data, $dataProp = "aaData") $where['params'] = array();
{ foreach ($dbname2searchTerm as $dbname=>$term) {
$where = array(); $isRange = false;
if (strstr($term, '~')) {
if ($data["sSearch"] !== "") { $info = explode('~', $term);
$searchTerms = explode(" ", $data["sSearch"]); 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;
$selectorCount = "SELECT COUNT(*) "; } else if($dbname == 'bit_rate') {
$selectorRows = "SELECT ".join(",", $displayColumns)." "; $input1 = isset($info[0])?intval($info[0]) * 1000:null;
$input2 = isset($info[1])?intval($info[1]) * 1000:null;
$sql = $selectorCount." FROM ".$fromTable; } else {
$sqlTotalRows = $sql; $input1 = isset($info[0])?$info[0]:null;
$input2 = isset($info[1])?$info[1]:null;
if (isset($searchTerms)) { }
$searchCols = array(); $isRange = true;
for ($i = 0; $i < $data["iColumns"]; $i++) { } else {
if ($data["bSearchable_".$i] == "true") { $input1 = $term;
$searchCols[] = $data["mDataProp_{$i}"]; }
}
} if ($isRange) {
$sub = array();
$outerCond = array(); if ($input1 != null) {
$sub[] = $dbname." >= :" . $dbname . "1";
foreach ($searchTerms as $term) { }
$innerCond = array(); if ($input2 != null) {
$sub[] = $dbname." <= :" . $dbname . "2";
foreach ($searchCols as $col) { }
$escapedTerm = pg_escape_string($term); if (!empty($sub)) {
$innerCond[] = "{$col}::text ILIKE '%{$escapedTerm}%'"; $where['clause'][$dbname] = "(".implode(' AND ', $sub).")";
} if ($input1 != null) {
$outerCond[] = "(".join(" OR ", $innerCond).")"; $where['params'][$dbname."1"] = $input1;
} }
$where[] = "(".join(" AND ", $outerCond).")"; if ($input2 != null) {
} $where['params'][$dbname."2"] = $input2;
// End Where clause }
}
// Order By clause } else {
$orderby = array(); if (trim($input1) !== "") {
for ($i = 0; $i < $data["iSortingCols"]; $i++){ $where['clause'][$dbname] = $dbname." ILIKE :" . $dbname."1";
$num = $data["iSortCol_".$i]; $where['params'][$dbname."1"] = "%".$input1."%";
$orderby[] = $data["mDataProp_{$num}"]." ".$data["sSortDir_".$i]; }
} }
$orderby[] = "id"; }
$orderby = join("," , $orderby); return $where;
// End Order By clause }
/*
$displayLength = intval($data["iDisplayLength"]); * query used to return data for a paginated/searchable datatable.
if (count($where) > 0) { */
$where = join(" AND ", $where); public static function findEntries($con, $displayColumns, $fromTable,
$sql = $selectorCount." FROM ".$fromTable." WHERE ".$where; $data, $dataProp = "aaData")
$sqlTotalDisplayRows = $sql; {
$librarySetting =
$sql = $selectorRows." FROM ".$fromTable." WHERE ".$where." ORDER BY ".$orderby; Application_Model_Preference::getCurrentLibraryTableColumnMap();
//$displayColumns[] = 'owner';
//limit the results returned.
if ($displayLength !== -1) { // map that maps original column position to db name
$sql .= " OFFSET ".$data["iDisplayStart"]." LIMIT ".$displayLength; $current2dbname = array();
} // array of search terms
} $orig2searchTerm = array();
else { foreach ($data as $key => $d) {
$sql = $selectorRows." FROM ".$fromTable." ORDER BY ".$orderby; if (strstr($key, "mDataProp_")) {
list($dump, $index) = explode("_", $key);
//limit the results returned. $current2dbname[$index] = $d;
if ($displayLength !== -1) { } elseif (strstr($key, "sSearch_")) {
$sql .= " OFFSET ".$data["iDisplayStart"]." LIMIT ".$displayLength; list($dump, $index) = explode("_", $key);
} $orig2searchTerm[$index] = $d;
} }
}
try {
$r = $con->query($sqlTotalRows); // map that maps dbname to searchTerm
$totalRows = $r->fetchColumn(0); $dbname2searchTerm = array();
foreach ($current2dbname as $currentPos => $dbname) {
if (isset($sqlTotalDisplayRows)) { $new_index = $librarySetting($currentPos);
$r = $con->query($sqlTotalDisplayRows); // TODO : Fix this retarded hack later. Just a band aid for
$totalDisplayRows = $r->fetchColumn(0); // now at least we print some warnings so that we don't
} // forget about this -- cc-4462
else { if ( array_key_exists($new_index, $orig2searchTerm) ) {
$totalDisplayRows = $totalRows; $dbname2searchTerm[$dbname] = $orig2searchTerm[$new_index];
} } else {
Logging::warn("Trying to reorder to unknown index
$r = $con->query($sql); printing as much debugging as possible...");
$r->setFetchMode(PDO::FETCH_ASSOC); $debug = array(
$results = $r->fetchAll(); '$new_index' => $new_index,
} '$currentPos' => $currentPos,
catch (Exception $e) { '$orig2searchTerm' => $orig2searchTerm);
Logging::debug($e->getMessage()); Logging::warn($debug);
} }
}
return array(
"sEcho" => intval($data["sEcho"]), $where = array();
"iTotalDisplayRecords" => intval($totalDisplayRows), /* Holds the parameters for binding after the statement has been
"iTotalRecords" => intval($totalRows), prepared */
$dataProp => $results $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"] !== "") {
$searchTerms = explode(" ", $data["sSearch"]);
}
$selectorCount = "SELECT COUNT(*) ";
$selectorRows = "SELECT ".join(",", $displayColumns)." ";
$sql = $selectorCount." FROM ".$fromTable;
$sqlTotalRows = $sql;
if (isset($searchTerms)) {
$searchCols = array();
for ($i = 0; $i < $data["iColumns"]; $i++) {
if ($data["bSearchable_".$i] == "true") {
$searchCols[] = $data["mDataProp_{$i}"];
}
}
$outerCond = array();
$simpleWhere = array();
foreach ($searchTerms as $term) {
foreach ($searchCols as $col) {
$simpleWhere['clause']["simple_".$col] = "{$col}::text ILIKE :simple_".$col;
$simpleWhere['params']["simple_".$col] = "%".$term."%";
}
$outerCond[] = "(".implode(" OR ", $simpleWhere['clause']).")";
}
$where[] = "(" .implode(" AND ", $outerCond). ")";
$params = array_merge($params, $simpleWhere['params']);
}
// End Where clause
// Order By clause
$orderby = array();
for ($i = 0; $i < $data["iSortingCols"]; $i++) {
$num = $data["iSortCol_".$i];
$orderby[] = $data["mDataProp_{$num}"]." ".$data["sSortDir_".$i];
}
$orderby[] = "id";
$orderby = join("," , $orderby);
// End Order By clause
$displayLength = intval($data["iDisplayLength"]);
$needToBind = false;
if (count($where) > 0) {
$needToBind = true;
$where = join(" OR ", $where);
$sql = $selectorCount." FROM ".$fromTable." WHERE ".$where;
$sqlTotalDisplayRows = $sql;
$sql = $selectorRows." FROM ".$fromTable." WHERE ".$where." ORDER BY ".$orderby;
//limit the results returned.
if ($displayLength !== -1) {
$sql .= " OFFSET ".$data["iDisplayStart"]." LIMIT ".$displayLength;
}
} else {
$sql = $selectorRows." FROM ".$fromTable." ORDER BY ".$orderby;
//limit the results returned.
if ($displayLength !== -1) {
$sql .= " OFFSET ".$data["iDisplayStart"]." LIMIT ".$displayLength;
}
}
try {
$r = $con->query($sqlTotalRows);
$totalRows = $r->fetchColumn(0);
if (isset($sqlTotalDisplayRows)) {
$totalDisplayRows = Application_Common_Database::prepareAndExecute($sqlTotalDisplayRows, $params, 'column');
} else {
$totalDisplayRows = $totalRows;
}
//TODO
if ($needToBind) {
$results = Application_Common_Database::prepareAndExecute($sql, $params);
} else {
$stmt = $con->query($sql);
$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(
"sEcho" => intval($data["sEcho"]),
"iTotalDisplayRecords" => intval($totalDisplayRows),
"iTotalRecords" => intval($totalRows),
$dataProp => $results
);
}
} }

View file

@ -1,47 +1,55 @@
<?php <?php
class Application_Model_Email { class Application_Model_Email
{
/** /**
* Send email * Send email
* *
* @param string $subject * @param string $subject
* @param string $message * @param string $message
* @param mixed $tos * @param mixed $tos
* @return void * @return void
*/ */
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;
} }
$config = array( if ($mailServerRequiresAuth) {
'auth' => 'login', $username = Application_Model_Preference::GetMailServerEmailAddress();
'ssl' => 'ssl', $password = Application_Model_Preference::GetMailServerPassword();
'username' => $username,
'password' => $password $config = array(
); 'auth' => 'login',
'ssl' => 'ssl',
'username' => $username,
'password' => $password
);
} else {
$config = array(
'ssl' => 'tls'
);
}
if (isset($port)) { if (isset($port)) {
$config['port'] = $port; $config['port'] = $port;
} }
$transport = new Zend_Mail_Transport_Smtp($mailServer, $config); $transport = new Zend_Mail_Transport_Smtp($mailServer, $config);
} }
$mail = new Zend_Mail('utf-8'); $mail = new Zend_Mail('utf-8');
$mail->setSubject($subject); $mail->setSubject($subject);
$mail->setBodyText($message); $mail->setBodyText($message);
foreach ((array) $tos as $to) { foreach ((array) $tos as $to) {
$mail->addTo($to); $mail->addTo($to);
} }
@ -60,8 +68,8 @@ class Application_Model_Email {
} catch (Exception $e) { } catch (Exception $e) {
$success = false; $success = false;
} }
} }
return $success; return $success;
} }

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();
@ -26,7 +27,7 @@ class Application_Model_LiveLog
." WHERE state = 'L'" ." WHERE state = 'L'"
." ORDER BY id"; ." ORDER BY id";
$rows = $con->query($sql)->fetchAll(); $rows = $con->query($sql)->fetchAll();
if ($rows != null) { if ($rows != null) {
$last_row = self::UpdateLastLogEndTime(array_pop($rows)); $last_row = self::UpdateLastLogEndTime(array_pop($rows));
array_push($rows, $last_row); array_push($rows, $last_row);
@ -36,7 +37,7 @@ class Application_Model_LiveLog
$con->exec($sql_delete); $con->exec($sql_delete);
} }
} }
$skip = true; $skip = true;
} }
$hours = 0; $hours = 0;
@ -55,13 +56,13 @@ class Application_Model_LiveLog
$intervals[$i] = 0; $intervals[$i] = 0;
} }
} }
// Trim milliseconds (DateInterval does not support) // Trim milliseconds (DateInterval does not support)
$sec = explode(".", $intervals[2]); $sec = explode(".", $intervals[2]);
if (isset($sec[0])) { if (isset($sec[0])) {
$intervals[2] = $sec[0]; $intervals[2] = $sec[0];
} }
$seconds += $intervals[2]; $seconds += $intervals[2];
if ($seconds / 60 >= 1) { if ($seconds / 60 >= 1) {
$minutes += 1; $minutes += 1;
@ -86,21 +87,21 @@ 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;
} }
} }
public static function GetScheduledDuration($p_keepData=false) public static function GetScheduledDuration($p_keepData=false)
{ {
try { try {
$con = Propel::getConnection(); $con = Propel::getConnection();
@ -119,13 +120,12 @@ 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";
$rows = $con->query($sql)->fetchAll(); $rows = $con->query($sql)->fetchAll();
if ($rows != null) { if ($rows != null) {
$last_row = self::UpdateLastLogEndTime(array_pop($rows)); $last_row = self::UpdateLastLogEndTime(array_pop($rows));
array_push($rows, $last_row); array_push($rows, $last_row);
@ -135,7 +135,7 @@ class Application_Model_LiveLog
$con->exec($sql_delete); $con->exec($sql_delete);
} }
} }
$skip = true; $skip = true;
} }
$hours = 0; $hours = 0;
@ -173,7 +173,7 @@ class Application_Model_LiveLog
} }
} }
$clip_length_seconds = $clip_length_intervals[0]*3600 + $clip_length_intervals[1]*60 + $clip_length_intervals[2]; $clip_length_seconds = $clip_length_intervals[0]*3600 + $clip_length_intervals[1]*60 + $clip_length_intervals[2];
$extra_time = $extra_time->format("%H:%i:%s"); $extra_time = $extra_time->format("%H:%i:%s");
//Convert extra_time into seconds; //Convert extra_time into seconds;
$extra_time_intervals = explode(":", $extra_time); $extra_time_intervals = explode(":", $extra_time);
@ -185,28 +185,25 @@ class Application_Model_LiveLog
$extra_time_seconds = $extra_time_intervals[0]*3600 + $extra_time_intervals[1]*60 + $extra_time_intervals[2]; $extra_time_seconds = $extra_time_intervals[0]*3600 + $extra_time_intervals[1]*60 + $extra_time_intervals[2];
$clip_length_seconds -= $extra_time_seconds; $clip_length_seconds -= $extra_time_seconds;
//Convert new clip_length into "H-i-s" format //Convert new clip_length into "H-i-s" format
$clip_length_arr = array(); $clip_length_arr = array();
if ($clip_length_seconds / 3600 >= 1) { if ($clip_length_seconds / 3600 >= 1) {
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,13 +268,15 @@ 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();
$scheduled = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play'); $scheduled = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play');
if ($state == 'L' && $scheduled == 'on') { if ($state == 'L' && $scheduled == 'on') {
self::SetEndTime('S', $dateTime); self::SetEndTime('S', $dateTime);
@ -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);
@ -33,4 +38,4 @@ class Application_Model_LoginAttempts {
$con->exec($sql); $con->exec($sql);
} }
} }
} }

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,52 +40,68 @@ 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();
} }
/** /**
* There are 2 cases where this function can be called. * There are 2 cases where this function can be called.
* 1. When watched dir was removed * 1. When watched dir was removed
* 2. When some dir was watched, but it was unmounted * 2. When some dir was watched, but it was unmounted
* *
* In case of 1, $userAddedWatchedDir should be true * In case of 1, $userAddedWatchedDir should be true
* In case of 2, $userAddedWatchedDir should be false * In case of 2, $userAddedWatchedDir should be false
* *
* When $userAddedWatchedDir is true, it will set "Watched" flag to false * When $userAddedWatchedDir is true, it will set "Watched" flag to false
* otherwise, it will set "Exists" flag to true * otherwise, it will set "Exists" flag to true
*/ */
public function remove($userAddedWatchedDir=true) public function remove($userAddedWatchedDir=true)
{ {
$con = Propel::getConnection();
$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
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' );
$show_instances = $con->query($sql)->fetchAll();
// get all the files on this dir // get all the files on this dir
$sql = "UPDATE cc_files SET file_exists = 'f' WHERE id IN (SELECT f.id FROM cc_music_dirs as md " $sql = <<<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) {
self::setWatchedFlag(false); self::setWatchedFlag(false);
@ -93,7 +109,7 @@ class Application_Model_MusicDir {
self::setExistsFlag(false); self::setExistsFlag(false);
} }
//$res = $this->_dir->delete(); //$res = $this->_dir->delete();
foreach ($show_instances as $show_instance_row) { foreach ($show_instances as $show_instance_row) {
$temp_show = new Application_Model_ShowInstance($show_instance_row["instance_id"]); $temp_show = new Application_Model_ShowInstance($show_instance_row["instance_id"]);
$temp_show->updateScheduledTime(); $temp_show->updateScheduledTime();
@ -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'");
} }
} }
@ -156,59 +174,59 @@ class Application_Model_MusicDir {
/** There are 2 cases where this function can be called. /** There are 2 cases where this function can be called.
* 1. When watched dir was added * 1. When watched dir was added
* 2. When some dir was watched, but it was unmounted somehow, but gets mounted again * 2. When some dir was watched, but it was unmounted somehow, but gets mounted again
* *
* In case of 1, $userAddedWatchedDir should be true * In case of 1, $userAddedWatchedDir should be true
* In case of 2, $userAddedWatchedDir should be false * In case of 2, $userAddedWatchedDir should be false
* *
* When $userAddedWatchedDir is true, it will set "Removed" flag to false * When $userAddedWatchedDir is true, it will set "Removed" flag to false
* otherwise, it will set "Exists" flag to true * otherwise, it will set "Exists" flag to true
* *
* @param $nestedWatch - if true, bypass path check, and Watched to false * @param $nestedWatch - if true, bypass path check, and Watched to false
**/ **/
public static function addDir($p_path, $p_type, $userAddedWatchedDir=true, $nestedWatch=false) public static function addDir($p_path, $p_type, $userAddedWatchedDir=true, $nestedWatch=false)
{ {
if(!is_dir($p_path)){ if (!is_dir($p_path)) {
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);
} }
$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");
} }
@ -217,18 +235,18 @@ class Application_Model_MusicDir {
/** There are 2 cases where this function can be called. /** There are 2 cases where this function can be called.
* 1. When watched dir was added * 1. When watched dir was added
* 2. When some dir was watched, but it was unmounted somehow, but gets mounted again * 2. When some dir was watched, but it was unmounted somehow, but gets mounted again
* *
* In case of 1, $userAddedWatchedDir should be true * In case of 1, $userAddedWatchedDir should be true
* In case of 2, $userAddedWatchedDir should be false * In case of 2, $userAddedWatchedDir should be false
* *
* When $userAddedWatchedDir is true, it will set "Watched" flag to true * When $userAddedWatchedDir is true, it will set "Watched" flag to true
* otherwise, it will set "Exists" flag to true * otherwise, it will set "Exists" flag to true
**/ **/
public static function addWatchedDir($p_path, $userAddedWatchedDir=true, $nestedWatch=false) public static function addWatchedDir($p_path, $userAddedWatchedDir=true, $nestedWatch=false)
{ {
$res = self::addDir($p_path, "watched", $userAddedWatchedDir, $nestedWatch); $res = self::addDir($p_path, "watched", $userAddedWatchedDir, $nestedWatch);
if ($res['code'] == 0){ if ($res['code'] == 0) {
//convert "linked" files (Airtime <= 1.8.2) to watched files. //convert "linked" files (Airtime <= 1.8.2) to watched files.
$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,18 +307,18 @@ 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;
} }
} }
/** /**
* Search and returns watched dirs * Search and returns watched dirs
* *
* @param $exists search condition with exists flag * @param $exists search condition with exists flag
* @param $watched search condition with watched flag * @param $watched search condition with watched flag
*/ */
@ -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;
} }
} }
@ -383,18 +404,18 @@ class Application_Model_MusicDir {
/** There are 2 cases where this function can be called. /** There are 2 cases where this function can be called.
* 1. When watched dir was removed * 1. When watched dir was removed
* 2. When some dir was watched, but it was unmounted * 2. When some dir was watched, but it was unmounted
* *
* In case of 1, $userAddedWatchedDir should be true * In case of 1, $userAddedWatchedDir should be true
* In case of 2, $userAddedWatchedDir should be false * In case of 2, $userAddedWatchedDir should be false
* *
* When $userAddedWatchedDir is true, it will set "Watched" flag to false * When $userAddedWatchedDir is true, it will set "Watched" flag to false
* otherwise, it will set "Exists" flag to true * otherwise, it will set "Exists" flag to true
**/ **/
public static function removeWatchedDir($p_dir, $userAddedWatchedDir=true){ public static function removeWatchedDir($p_dir, $userAddedWatchedDir=true)
{
//make sure that $p_dir has a trailing "/" //make sure that $p_dir has a trailing "/"
$real_path = Application_Common_OsPath::normpath($p_dir)."/"; $real_path = Application_Common_OsPath::normpath($p_dir)."/";
if($real_path != "/"){ if ($real_path != "/") {
$p_dir = $real_path; $p_dir = $real_path;
} }
$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);
} }
} }
@ -412,8 +434,8 @@ class Application_Model_MusicDir {
public static function splitFilePath($p_filepath) public static function splitFilePath($p_filepath)
{ {
$mus_dir = self::getWatchedDirFromFilepath($p_filepath); $mus_dir = self::getWatchedDirFromFilepath($p_filepath);
if(is_null($mus_dir)) { if (is_null($mus_dir)) {
return null; return null;
} }

View file

@ -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.
*/ */
@ -20,17 +20,17 @@ class Application_Model_Playlist {
*/ */
private $id; private $id;
/** /**
* propel object for this playlist. * propel object for this playlist.
*/ */
private $pl; private $pl;
/** /**
* info needed to insert a new playlist element. * info needed to insert a new playlist element.
*/ */
private $plItem = array( private $plItem = array(
"id" => "", "id" => "",
"pos" => "", "pos" => "",
"cliplength" => "", "cliplength" => "",
"cuein" => "00:00:00", "cuein" => "00:00:00",
"cueout" => "00:00:00", "cueout" => "00:00:00",
@ -38,14 +38,13 @@ class Application_Model_Playlist {
"fadeout" => "0.0", "fadeout" => "0.0",
); );
//using propel's phpNames. //using propel's phpNames.
private $categories = array( private $categories = array(
"dc:title" => "Name", "dc:title" => "Name",
"dc:creator" => "Creator", "dc:creator" => "Creator",
"dc:description" => "Description", "dc:description" => "Description",
"dcterms:extent" => "Length" "dcterms:extent" => "Length"
); );
public function __construct($id=null, $con=null) public function __construct($id=null, $con=null)
{ {
@ -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;
} }
@ -90,12 +89,12 @@ class Application_Model_Playlist {
*/ */
public function setName($p_newname) public function setName($p_newname)
{ {
$this->pl->setDbName($p_newname); $this->pl->setDbName($p_newname);
$this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
$this->pl->save($this->con); $this->pl->save($this->con);
} }
/** /**
* Get mnemonic playlist name * Get mnemonic playlist name
* *
* @return string * @return string
@ -107,9 +106,9 @@ class Application_Model_Playlist {
public function setDescription($p_description) public function setDescription($p_description)
{ {
$this->pl->setDbDescription($p_description); $this->pl->setDbDescription($p_description);
$this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC"))); $this->pl->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
$this->pl->save($this->con); $this->pl->save($this->con);
} }
public function getDescription() public function getDescription()
@ -117,75 +116,148 @@ 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();
} }
/** /**
* Get the entire playlist as a two dimentional array, sorted in order of play. * Get the entire playlist as a two dimentional array, sorted in order of play.
* @param boolean $filterFiles if this is true, it will only return files that has * @param boolean $filterFiles if this is true, it will only return files that has
* file_exists flag set to true * file_exists flag set to true
* @return array * @return array
*/ */
public function getContents($filterFiles=false) { public function getContents($filterFiles=false)
{
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']);
$offset += $clipSec;
$offset_cliplength = Application_Common_DateHelper::secondsToPlaylistTime($offset);
//format the length for UI.
if ($row['type'] == 2) {
$bl = new Application_Model_Block($row['item_id']);
$formatter = new LengthFormatter($bl->getLength());
} else {
$formatter = new LengthFormatter($row['length']);
}
$row['length'] = $formatter->format();
$clipSec = Application_Model_Playlist::playlistTimeToSeconds($files[$i]['cliplength']); $formatter = new LengthFormatter($offset_cliplength);
$offset += $clipSec; $row['offset'] = $formatter->format();
$offset_cliplength = Application_Model_Playlist::secondsToPlaylistTime($offset);
//format the length for UI. //format the fades in format 00(.000000)
$formatter = new LengthFormatter($files[$i]['cliplength']); $fades = $this->getFadeInfo($row['position']);
$files[$i]['cliplength'] = $formatter->format(); $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');
$formatter = new LengthFormatter($offset_cliplength); //format original length
$files[$i]['offset'] = $formatter->format(); $formatter = new LengthFormatter($row['orig_length']);
$row['orig_length'] = $formatter->format();
$i++;
} }
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
$fade = substr($fade, 6);
//First get rid of the first six characters 00:00: which will be added back later for db update //Second add .000000 if the fade does't have milliseconds format already
$fade = substr($fade, 6); $dbFadeStrPos = strpos( $fade, '.' );
if ($dbFadeStrPos === false) {
$fade .= '.000000';
} else {
while (strlen($fade) < 9) {
$fade .= '0';
}
}
//Second add .000000 if the fade does't have milliseconds format already //done, just need to set back the formated values
$dbFadeStrPos = strpos( $fade, '.' ); return $fade;
if ( $dbFadeStrPos === False ) }
$fade .= '.000000';
else
while( strlen( $fade ) < 9 )
$fade .= '0';
//done, just need to set back the formated values // returns true/false and ids of dynamic blocks
return $fade; public function hasDynamicBlock()
{
$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. //aggregate column on playlistcontents cliplength column.
public function getLength() { 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 $this->pl->getDbLength(); 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)) {
$entry = $this->plItem; if (($obj instanceof CcFiles && $obj->getDbFileExists()) || $obj instanceof CcWebstream || $obj instanceof CcBlock) {
$entry["id"] = $file->getDbId(); $entry = $this->plItem;
$entry["pos"] = $pos; $entry["id"] = $obj->getDbId();
$entry["cliplength"] = $file->getDbLength(); $entry["pos"] = $pos;
$entry["cueout"] = $file->getDbLength(); $entry["cliplength"] = $obj->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);
@ -416,7 +545,7 @@ class Application_Model_Playlist {
* Remove audioClip from playlist * Remove audioClip from playlist
* *
* @param array $p_items * @param array $p_items
* array of unique item ids to remove from the playlist.. * array of unique item ids to remove from the playlist..
*/ */
public function delAudioClips($p_items) public function delAudioClips($p_items)
{ {
@ -444,53 +573,54 @@ 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)
{
Logging::info("Getting fade info for pos {$pos}");
public function getFadeInfo($pos) { $row = CcPlaylistcontentsQuery::create()
Logging::log("Getting fade info for pos {$pos}");
$row = CcPlaylistcontentsQuery::create()
->joinWith(CcFilesPeer::OM_CLASS) ->joinWith(CcFilesPeer::OM_CLASS)
->filterByDbPlaylistId($this->id) ->filterByDbPlaylistId($this->id)
->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(); }
return array($fadeIn, $fadeOut); //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);
}
/** /**
* Change fadeIn and fadeOut values for playlist Element * Change fadeIn and fadeOut values for playlist Element
* *
* @param int $pos * @param int $pos
* position of audioclip in playlist * position of audioclip in playlist
* @param string $fadeIn * @param string $fadeIn
* new value in ss.ssssss or extent format * new value in ss.ssssss or extent format
* @param string $fadeOut * @param string $fadeOut
* new value in ss.ssssss or extent format * new value in ss.ssssss or extent format
* @return boolean * @return boolean
*/ */
public function changeFadeInfo($id, $fadeIn, $fadeOut) public function changeFadeInfo($id, $fadeIn, $fadeOut)
{ {
//See issue CC-2065, pad the fadeIn and fadeOut so that it is TIME compatable with the DB schema //See issue CC-2065, pad the fadeIn and fadeOut so that it is TIME compatable with the DB schema
//For the top level PlayList either fadeIn or fadeOut will sometimes be Null so need a gaurd against //For the top level PlayList either fadeIn or fadeOut will sometimes be Null so need a gaurd against
//setting it to nonNull for checks down below //setting it to nonNull for checks down below
$fadeIn = $fadeIn?'00:00:'.$fadeIn:$fadeIn; $fadeIn = $fadeIn?'00:00:'.$fadeIn:$fadeIn;
$fadeOut = $fadeOut?'00:00:'.$fadeOut:$fadeOut; $fadeOut = $fadeOut?'00:00:'.$fadeOut:$fadeOut;
$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)
@ -562,11 +689,11 @@ class Application_Model_Playlist {
* Change cueIn/cueOut values for playlist element * Change cueIn/cueOut values for playlist element
* *
* @param int $pos * @param int $pos
* position of audioclip in playlist * position of audioclip in playlist
* @param string $cueIn * @param string $cueIn
* new value in ss.ssssss or extent format * new value in ss.ssssss or extent format
* @param string $cueOut * @param string $cueOut
* new value in ss.ssssss or extent format * new value in ss.ssssss or extent format
* @return boolean or pear error object * @return boolean or pear error object
*/ */
public function changeClipLength($id, $cueIn, $cueOut) public function changeClipLength($id, $cueIn, $cueOut)
@ -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)
{ {
CcPlaylistQuery::create()->findPKs($p_ids)->delete(); $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();
} 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,82 +2,82 @@
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;
//in UTC timezone
private $startDT;
//in UTC timezone
private $endDT;
private $epoch_now;
private $opts;
private $mDataPropMap = array(
"artist" => "file.artist_name",
"title" => "file.track_title",
"played" => "playout.played",
"length" => "file.length",
"composer" => "file.composer",
"copyright" => "file.copyright",
);
public function __construct($p_startDT, $p_endDT, $p_opts) {
$this->con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME);
$this->startDT = $p_startDT;
$this->endDT = $p_endDT;
$this->timezone = date_default_timezone_get();
$this->epoch_now = time();
$this->opts = $p_opts;
}
/*
* map front end mDataProp labels to proper column names for searching etc.
*/
private function translateColumns() {
for ($i = 0; $i < $this->opts["iColumns"]; $i++){
$this->opts["mDataProp_{$i}"] = $this->mDataPropMap[$this->opts["mDataProp_{$i}"]];
}
}
public function getItems() {
$this->translateColumns();
$select = array(
"file.track_title as title",
"file.artist_name as artist",
"playout.played",
"playout.file_id",
"file.composer",
"file.copyright",
"file.length"
);
$start = $this->startDT->format("Y-m-d H:i:s");
$end = $this->endDT->format("Y-m-d H:i:s");
$historyTable = "(
select count(schedule.file_id) as played, schedule.file_id as file_id
from cc_schedule as schedule
where schedule.starts >= '{$start}' and schedule.starts < '{$end}'
and schedule.playout_status > 0 and schedule.media_item_played != FALSE and schedule.broadcasted = 1
group by schedule.file_id
)
AS playout left join cc_files as file on (file.id = playout.file_id)";
$results = Application_Model_Datatables::findEntries($this->con, $select, $historyTable, $this->opts, "history"); //in UTC timezone
private $startDT;
foreach ($results["history"] as &$row) { //in UTC timezone
$formatter = new LengthFormatter($row['length']); private $endDT;
$row['length'] = $formatter->format();
} private $epoch_now;
private $opts;
return $results;
} private $mDataPropMap = array(
} "artist" => "artist_name",
"title" => "track_title",
"played" => "played",
"length" => "length",
"composer" => "composer",
"copyright" => "copyright",
);
public function __construct($p_startDT, $p_endDT, $p_opts)
{
$this->con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME);
$this->startDT = $p_startDT;
$this->endDT = $p_endDT;
$this->timezone = date_default_timezone_get();
$this->epoch_now = time();
$this->opts = $p_opts;
}
/*
* map front end mDataProp labels to proper column names for searching etc.
*/
private function translateColumns()
{
for ($i = 0; $i < $this->opts["iColumns"]; $i++) {
$this->opts["mDataProp_{$i}"] = $this->mDataPropMap[$this->opts["mDataProp_{$i}"]];
}
}
public function getItems()
{
$this->translateColumns();
$select = array(
"file.track_title as title",
"file.artist_name as artist",
"playout.played",
"playout.file_id",
"file.composer",
"file.copyright",
"file.length"
);
$start = $this->startDT->format("Y-m-d H:i:s");
$end = $this->endDT->format("Y-m-d H:i:s");
$historyTable = "(
select count(schedule.file_id) as played, schedule.file_id as file_id
from cc_schedule as schedule
where schedule.starts >= '{$start}' and schedule.starts < '{$end}'
and schedule.playout_status > 0 and schedule.media_item_played != FALSE and schedule.broadcasted = 1
group by schedule.file_id
)
AS playout left join cc_files as file on (file.id = playout.file_id)";
$results = Application_Model_Datatables::findEntries($this->con, $select, $historyTable, $this->opts, "history");
foreach ($results["history"] as &$row) {
$formatter = new LengthFormatter($row['length']);
$row['length'] = $formatter->format();
}
return $results;
}
}

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'));
self::sendMessage($exchange, $data);
$channel->basic_publish($msg, $EXCHANGE);
$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,59 +11,64 @@ 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;
private $nowDT; private $nowDT;
private $user; private $user;
private $checkUserPermissions = true; private $checkUserPermissions = true;
public function __construct() { public function __construct()
{
$this->con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); $this->con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME);
$this->epochNow = microtime(true); //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++) {
$id = $items[$i]["id"]; $id = $items[$i]["id"];
//could be added to the beginning of a show, which sends id = 0; //could be added to the beginning of a show, which sends id = 0;
if ($id > 0) { if ($id > 0) {
$schedInfo[$id] = $items[$i]["instance"]; $schedInfo[$id] = $items[$i]["instance"];
} }
$instanceInfo[$items[$i]["instance"]] = $items[$i]["timestamp"]; $instanceInfo[$items[$i]["instance"]] = $items[$i]["timestamp"];
} }
if (count($instanceInfo) === 0) { if (count($instanceInfo) === 0) {
throw new Exception("Invalid Request."); throw new Exception("Invalid Request.");
} }
$schedIds = array(); $schedIds = array();
if (isset($schedInfo)) { if (isset($schedInfo)) {
$schedIds = array_keys($schedInfo); $schedIds = array_keys($schedInfo);
@ -71,48 +76,48 @@ class Application_Model_Scheduler {
$schedItems = CcScheduleQuery::create()->findPKs($schedIds, $this->con); $schedItems = CcScheduleQuery::create()->findPKs($schedIds, $this->con);
$instanceIds = array_keys($instanceInfo); $instanceIds = array_keys($instanceInfo);
$showInstances = CcShowInstancesQuery::create()->findPKs($instanceIds, $this->con); $showInstances = CcShowInstancesQuery::create()->findPKs($instanceIds, $this->con);
//an item has been deleted //an item has been deleted
if (count($schedIds) !== count($schedItems)) { if (count($schedIds) !== count($schedItems)) {
throw new OutDatedScheduleException("The schedule you're viewing is out of date! (sched mismatch)"); throw new OutDatedScheduleException("The schedule you're viewing is out of date! (sched mismatch)");
} }
//a show has been deleted //a show has been deleted
if (count($instanceIds) !== count($showInstances)) { if (count($instanceIds) !== count($showInstances)) {
throw new OutDatedScheduleException("The schedule you're viewing is out of date! (instance mismatch)"); throw new OutDatedScheduleException("The schedule you're viewing is out of date! (instance mismatch)");
} }
foreach ($schedItems as $schedItem) { foreach ($schedItems as $schedItem) {
$id = $schedItem->getDbId(); $id = $schedItem->getDbId();
$instance = $schedItem->getCcShowInstances($this->con); $instance = $schedItem->getCcShowInstances($this->con);
if (intval($schedInfo[$id]) !== $instance->getDbId()) { if (intval($schedInfo[$id]) !== $instance->getDbId()) {
throw new OutDatedScheduleException("The schedule you're viewing is out of date!"); throw new OutDatedScheduleException("The schedule you're viewing is out of date!");
} }
} }
foreach ($showInstances as $instance) { foreach ($showInstances as $instance) {
$id = $instance->getDbId(); $id = $instance->getDbId();
$show = $instance->getCcShow($this->con); $show = $instance->getCcShow($this->con);
if ($this->checkUserPermissions && $this->user->canSchedule($show->getDbId()) === false) { if ($this->checkUserPermissions && $this->user->canSchedule($show->getDbId()) === false) {
throw new Exception("You are not allowed to schedule show {$show->getDbName()}."); throw new Exception("You are not allowed to schedule show {$show->getDbName()}.");
} }
$showEndEpoch = floatval($instance->getDbEnds("U.u")); $showEndEpoch = floatval($instance->getDbEnds("U.u"));
if ($showEndEpoch < $nowEpoch) { if ($showEndEpoch < $nowEpoch) {
throw new OutDatedScheduleException("The show {$show->getDbName()} is over and cannot be scheduled."); throw new OutDatedScheduleException("The show {$show->getDbName()} is over and cannot be scheduled.");
} }
$ts = intval($instanceInfo[$id]); $ts = intval($instanceInfo[$id]);
$lastSchedTs = intval($instance->getDbLastScheduled("U")) ? : 0; $lastSchedTs = intval($instance->getDbLastScheduled("U")) ? : 0;
if ($ts < $lastSchedTs) { if ($ts < $lastSchedTs) {
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,32 +150,118 @@ 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'];
if (isset($file) && $file->getDbFileExists()) { $data["cliplength"] = $plItem['length'];
$data["cuein"] = $plItem['cuein'];
$data = $this->fileInfo; $data["cueout"] = $plItem['cueout'];
$data["id"] = $plItem->getDbFileId(); $data["fadein"] = $plItem['fadein'];
$data["cliplength"] = $plItem->getDbCliplength(); $data["fadeout"] = $plItem['fadeout'];
$data["cuein"] = $plItem->getDbCuein(); $data["type"] = 0;
$data["cueout"] = $plItem->getDbCueout();
$data["fadein"] = $plItem->getDbFadein();
$data["fadeout"] = $plItem->getDbFadeout();
$files[] = $data; $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()) {
$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["id"] = $id;
$data["cliplength"] = $stream->getDbLength();
$data["cueout"] = $stream->getDbLength();
$data["type"] = 1;
$defaultFade = Application_Model_Preference::GetDefaultFade();
if (isset($defaultFade)) {
//fade is in format SS.uuuuuu
$data["fadein"] = $defaultFade;
$data["fadeout"] = $defaultFade;
}
$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,89 +276,89 @@ 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.
$endEpoch = bcadd($startEpoch , (string) $durationSeconds, 6); $endEpoch = bcadd($startEpoch , (string) $durationSeconds, 6);
$dt = DateTime::createFromFormat("U.u", $endEpoch, new DateTimeZone("UTC")); $dt = DateTime::createFromFormat("U.u", $endEpoch, new DateTimeZone("UTC"));
if ($dt === false) { if ($dt === false) {
//PHP 5.3.2 problem //PHP 5.3.2 problem
$dt = DateTime::createFromFormat("U", intval($endEpoch), new DateTimeZone("UTC")); $dt = DateTime::createFromFormat("U", intval($endEpoch), new DateTimeZone("UTC"));
} }
return $dt; return $dt;
} }
private function findNextStartTime($DT, $instance) { private function findNextStartTime($DT, $instance)
{
$sEpoch = $DT->format("U.u"); $sEpoch = $DT->format("U.u");
$nEpoch = $this->epochNow; $nEpoch = $this->epochNow;
//check for if the show has started. //check for if the show has started.
if (bccomp( $nEpoch , $sEpoch , 6) === 1) { if (bccomp( $nEpoch , $sEpoch , 6) === 1) {
//need some kind of placeholder for cc_schedule. //need some kind of placeholder for cc_schedule.
//playout_status will be -1. //playout_status will be -1.
$nextDT = $this->nowDT; $nextDT = $this->nowDT;
$length = bcsub($nEpoch , $sEpoch , 6); $length = bcsub($nEpoch , $sEpoch , 6);
$cliplength = Application_Model_Playlist::secondsToPlaylistTime($length); $cliplength = Application_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();
$filler->setDbStarts($DT) $filler->setDbStarts($DT)
->setDbEnds($this->nowDT) ->setDbEnds($this->nowDT)
->setDbClipLength($cliplength) ->setDbClipLength($cliplength)
->setDbPlayoutStatus(-1) ->setDbPlayoutStatus(-1)
->setDbInstanceId($instance->getDbId()) ->setDbInstanceId($instance->getDbId())
->save($this->con); ->save($this->con);
} } else {
else { $nextDT = $DT;
$nextDT = $DT;
} }
return $nextDT; return $nextDT;
} }
/* /*
* @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
private function removeGaps($showInstance, $exclude=null) { * there are no gaps between them.
*/
Logging::log("removing gaps from show instance #".$showInstance); public function removeGaps($showInstance, $exclude=null)
{
$instance = CcShowInstancesQuery::create()->findPK($showInstance, $this->con); Logging::info("removing gaps from show instance #".$showInstance);
if (is_null($instance)) {
throw new OutDatedScheduleException("The schedule you're viewing is out of date!"); $instance = CcShowInstancesQuery::create()->findPK($showInstance, $this->con);
} if (is_null($instance)) {
throw new OutDatedScheduleException("The schedule you're viewing is out of date!");
$itemStartDT = $instance->getDbStarts(null);
$schedule = CcScheduleQuery::create()
->filterByDbInstanceId($showInstance)
->filterByDbId($exclude, Criteria::NOT_IN)
->orderByDbStarts()
->find($this->con);
foreach ($schedule as $item) {
$itemEndDT = $this->findEndTime($itemStartDT, $item->getDbClipLength());
$item->setDbStarts($itemStartDT)
->setDbEnds($itemEndDT);
$itemStartDT = $itemEndDT;
} }
$schedule->save($this->con); $itemStartDT = $instance->getDbStarts(null);
$schedule = CcScheduleQuery::create()
->filterByDbInstanceId($showInstance)
->filterByDbId($exclude, Criteria::NOT_IN)
->orderByDbStarts()
->find($this->con);
foreach ($schedule as $item) {
$itemEndDT = $this->findEndTime($itemStartDT, $item->getDbClipLength());
$item->setDbStarts($itemStartDT)
->setDbEnds($itemEndDT);
$itemStartDT = $itemEndDT;
}
$schedule->save($this->con);
} }
/* /*
@ -276,8 +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();
@ -291,20 +381,20 @@ class Application_Model_Scheduler {
} }
$startProfile = microtime(true); $startProfile = microtime(true);
foreach ($scheduleItems as $schedule) { foreach ($scheduleItems as $schedule) {
$id = intval($schedule["id"]); $id = intval($schedule["id"]);
if ($id !== 0) { if ($id !== 0) {
$schedItem = CcScheduleQuery::create()->findPK($id, $this->con); $schedItem = CcScheduleQuery::create()->findPK($id, $this->con);
$instance = $schedItem->getCcShowInstances($this->con); $instance = $schedItem->getCcShowInstances($this->con);
$schedItemEndDT = $schedItem->getDbEnds(null); $schedItemEndDT = $schedItem->getDbEnds(null);
$nextStartDT = $this->findNextStartTime($schedItemEndDT, $instance); $nextStartDT = $this->findNextStartTime($schedItemEndDT, $instance);
} }
//selected empty row to add after //selected empty row to add after
else { else {
$instance = CcShowInstancesQuery::create()->findPK($schedule["instance"], $this->con); $instance = CcShowInstancesQuery::create()->findPK($schedule["instance"], $this->con);
$showStartDT = $instance->getDbStarts(null); $showStartDT = $instance->getDbStarts(null);
@ -316,22 +406,22 @@ class Application_Model_Scheduler {
} }
if ($adjustSched === true) { if ($adjustSched === true) {
$pstart = microtime(true); $pstart = microtime(true);
$followingSchedItems = CcScheduleQuery::create() $followingSchedItems = CcScheduleQuery::create()
->filterByDBStarts($nextStartDT->format("Y-m-d H:i:s.u"), Criteria::GREATER_EQUAL) ->filterByDBStarts($nextStartDT->format("Y-m-d H:i:s.u"), Criteria::GREATER_EQUAL)
->filterByDbInstanceId($instance->getDbId()) ->filterByDbInstanceId($instance->getDbId())
->filterByDbId($excludeIds, Criteria::NOT_IN) ->filterByDbId($excludeIds, Criteria::NOT_IN)
->orderByDbStarts() ->orderByDbStarts()
->find($this->con); ->find($this->con);
$pend = microtime(true); $pend = microtime(true);
Logging::debug("finding all following items."); Logging::debug("finding all following items.");
Logging::debug(floatval($pend) - floatval($pstart)); Logging::debug(floatval($pend) - floatval($pstart));
} }
foreach($schedFiles as $file) { foreach ($schedFiles as $file) {
$endTimeDT = $this->findEndTime($nextStartDT, $file['cliplength']); $endTimeDT = $this->findEndTime($nextStartDT, $file['cliplength']);
@ -339,48 +429,57 @@ 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;
} }
if ($adjustSched === true) { if ($adjustSched === true) {
$pstart = microtime(true); $pstart = microtime(true);
//recalculate the start/end times after the inserted items. //recalculate the start/end times after the inserted items.
foreach ($followingSchedItems as $item) { foreach ($followingSchedItems as $item) {
$endTimeDT = $this->findEndTime($nextStartDT, $item->getDbClipLength()); $endTimeDT = $this->findEndTime($nextStartDT, $item->getDbClipLength());
$item->setDbStarts($nextStartDT); $item->setDbStarts($nextStartDT);
$item->setDbEnds($endTimeDT); $item->setDbEnds($endTimeDT);
$item->save($this->con); $item->save($this->con);
$nextStartDT = $endTimeDT; $nextStartDT = $endTimeDT;
} }
$pend = microtime(true); $pend = microtime(true);
Logging::debug("adjusting all following items."); Logging::debug("adjusting all following items.");
Logging::debug(floatval($pend) - floatval($pstart)); Logging::debug(floatval($pend) - floatval($pstart));
} }
} }
$endProfile = microtime(true); $endProfile = microtime(true);
Logging::debug("finished adding scheduled items."); Logging::debug("finished adding scheduled items.");
Logging::debug(floatval($endProfile) - floatval($startProfile)); Logging::debug(floatval($endProfile) - floatval($startProfile));
//update the status flag in cc_schedule. //update the status flag in cc_schedule.
@ -389,27 +488,26 @@ class Application_Model_Scheduler {
->find($this->con); ->find($this->con);
$startProfile = microtime(true); $startProfile = microtime(true);
foreach ($instances as $instance) { foreach ($instances as $instance) {
$instance->updateScheduleStatus($this->con); $instance->updateScheduleStatus($this->con);
} }
$endProfile = microtime(true); $endProfile = microtime(true);
Logging::debug("updating show instances status."); Logging::debug("updating show instances status.");
Logging::debug(floatval($endProfile) - floatval($startProfile)); Logging::debug(floatval($endProfile) - floatval($startProfile));
$startProfile = microtime(true); $startProfile = microtime(true);
//update the last scheduled timestamp. //update the last scheduled timestamp.
CcShowInstancesQuery::create() CcShowInstancesQuery::create()
->filterByPrimaryKeys($affectedShowInstances) ->filterByPrimaryKeys($affectedShowInstances)
->update(array('DbLastScheduled' => new DateTime("now", new DateTimeZone("UTC"))), $this->con); ->update(array('DbLastScheduled' => new DateTime("now", new DateTimeZone("UTC"))), $this->con);
$endProfile = microtime(true); $endProfile = microtime(true);
Logging::debug("updating last scheduled timestamp."); Logging::debug("updating last scheduled timestamp.");
Logging::debug(floatval($endProfile) - floatval($startProfile)); Logging::debug(floatval($endProfile) - floatval($startProfile));
} } catch (Exception $e) {
catch (Exception $e) {
Logging::debug($e->getMessage()); Logging::debug($e->getMessage());
throw $e; throw $e;
} }
@ -419,14 +517,14 @@ 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();
try { try {
$this->validateRequest($scheduleItems); $this->validateRequest($scheduleItems);
foreach ($mediaItems as $media) { foreach ($mediaItems as $media) {
@ -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,104 +545,101 @@ 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();
$this->con->useDebug(true); $this->con->useDebug(true);
try { try {
$this->validateRequest($selectedItems); $this->validateRequest($selectedItems);
$this->validateRequest($afterItems); $this->validateRequest($afterItems);
$endProfile = microtime(true); $endProfile = microtime(true);
Logging::debug("validating move request took:"); Logging::debug("validating move request took:");
Logging::debug(floatval($endProfile) - floatval($startProfile)); Logging::debug(floatval($endProfile) - floatval($startProfile));
$afterInstance = CcShowInstancesQuery::create()->findPK($afterItems[0]["instance"], $this->con); $afterInstance = CcShowInstancesQuery::create()->findPK($afterItems[0]["instance"], $this->con);
//map show instances to cc_schedule primary keys. //map show instances to cc_schedule primary keys.
$modifiedMap = array(); $modifiedMap = array();
$movedData = array(); $movedData = array();
//prepare each of the selected items. //prepare each of the selected items.
for ($i = 0; $i < count($selectedItems); $i++) { for ($i = 0; $i < count($selectedItems); $i++) {
$selected = CcScheduleQuery::create()->findPk($selectedItems[$i]["id"], $this->con); $selected = CcScheduleQuery::create()->findPk($selectedItems[$i]["id"], $this->con);
$selectedInstance = $selected->getCcShowInstances($this->con); $selectedInstance = $selected->getCcShowInstances($this->con);
$data = $this->fileInfo; $data = $this->fileInfo;
$data["id"] = $selected->getDbFileId(); $data["id"] = $selected->getDbFileId();
$data["cliplength"] = $selected->getDbClipLength(); $data["cliplength"] = $selected->getDbClipLength();
$data["cuein"] = $selected->getDbCueIn(); $data["cuein"] = $selected->getDbCueIn();
$data["cueout"] = $selected->getDbCueOut(); $data["cueout"] = $selected->getDbCueOut();
$data["fadein"] = $selected->getDbFadeIn(); $data["fadein"] = $selected->getDbFadeIn();
$data["fadeout"] = $selected->getDbFadeOut(); $data["fadeout"] = $selected->getDbFadeOut();
$data["sched_id"] = $selected->getDbId(); $data["sched_id"] = $selected->getDbId();
$movedData[] = $data; $movedData[] = $data;
//figure out which items must be removed from calculated show times. //figure out which items must be removed from calculated show times.
$showInstanceId = $selectedInstance->getDbId(); $showInstanceId = $selectedInstance->getDbId();
$schedId = $selected->getDbId(); $schedId = $selected->getDbId();
if (isset($modifiedMap[$showInstanceId])) { if (isset($modifiedMap[$showInstanceId])) {
array_push($modifiedMap[$showInstanceId], $schedId); array_push($modifiedMap[$showInstanceId], $schedId);
} } else {
else {
$modifiedMap[$showInstanceId] = array($schedId); $modifiedMap[$showInstanceId] = array($schedId);
} }
} }
//calculate times excluding the to be moved items. //calculate times excluding the to be moved items.
foreach ($modifiedMap as $instance => $schedIds) { foreach ($modifiedMap as $instance => $schedIds) {
$startProfile = microtime(true); $startProfile = microtime(true);
$this->removeGaps($instance, $schedIds); $this->removeGaps($instance, $schedIds);
$endProfile = microtime(true); $endProfile = microtime(true);
Logging::debug("removing gaps from instance $instance:"); Logging::debug("removing gaps from instance $instance:");
Logging::debug(floatval($endProfile) - floatval($startProfile)); Logging::debug(floatval($endProfile) - floatval($startProfile));
} }
$startProfile = microtime(true); $startProfile = microtime(true);
$this->insertAfter($afterItems, $movedData, $adjustSched); $this->insertAfter($afterItems, $movedData, $adjustSched);
$endProfile = microtime(true); $endProfile = microtime(true);
Logging::debug("inserting after removing gaps."); Logging::debug("inserting after removing gaps.");
Logging::debug(floatval($endProfile) - floatval($startProfile)); Logging::debug(floatval($endProfile) - floatval($startProfile));
$afterInstanceId = $afterInstance->getDbId();
$modified = array_keys($modifiedMap); $modified = array_keys($modifiedMap);
//need to adjust shows we have moved items from. //need to adjust shows we have moved items from.
foreach($modified as $instanceId) { foreach ($modified as $instanceId) {
$instance = CcShowInstancesQuery::create()->findPK($instanceId, $this->con); $instance = CcShowInstancesQuery::create()->findPK($instanceId, $this->con);
$instance->updateScheduleStatus($this->con); $instance->updateScheduleStatus($this->con);
} }
$this->con->useDebug(false); $this->con->useDebug(false);
$this->con->commit(); $this->con->commit();
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();
try { try {
$this->validateRequest($scheduledItems); $this->validateRequest($scheduledItems);
$scheduledIds = array(); $scheduledIds = array();
foreach ($scheduledItems as $item) { foreach ($scheduledItems as $item) {
$scheduledIds[] = $item["id"]; $scheduledIds[] = $item["id"];
@ -555,28 +649,30 @@ class Application_Model_Scheduler {
//check to make sure all items selected are up to date //check to make sure all items selected are up to date
foreach ($removedItems as $removedItem) { foreach ($removedItems as $removedItem) {
$instance = $removedItem->getCcShowInstances($this->con); $instance = $removedItem->getCcShowInstances($this->con);
//check to truncate the currently playing item instead of deleting it. //check to truncate the currently playing item instead of deleting it.
if ($removedItem->isCurrentItem($this->epochNow)) { if ($removedItem->isCurrentItem($this->epochNow)) {
$nEpoch = $this->epochNow; $nEpoch = $this->epochNow;
$sEpoch = $removedItem->getDbStarts('U.u'); $sEpoch = $removedItem->getDbStarts('U.u');
$length = bcsub($nEpoch , $sEpoch , 6); $length = bcsub($nEpoch , $sEpoch , 6);
$cliplength = Application_Model_Playlist::secondsToPlaylistTime($length); $cliplength = Application_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,64 +709,61 @@ 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;
} }
} }
/* /*
* Used for cancelling the current show instance. * Used for cancelling the current show instance.
* *
* @param $p_id id of the show instance to cancel. * @param $p_id id of the show instance to cancel.
*/ */
public function cancelShow($p_id) { public function cancelShow($p_id)
{
$this->con->beginTransaction(); $this->con->beginTransaction();
try { try {
$instance = CcShowInstancesQuery::create()->findPK($p_id); $instance = CcShowInstancesQuery::create()->findPK($p_id);
if (!$instance->getDbRecord()) { if (!$instance->getDbRecord()) {
$items = CcScheduleQuery::create() $items = CcScheduleQuery::create()
->filterByDbInstanceId($p_id) ->filterByDbInstanceId($p_id)
->filterByDbEnds($this->nowDT, Criteria::GREATER_THAN) ->filterByDbEnds($this->nowDT, Criteria::GREATER_THAN)
->find($this->con); ->find($this->con);
if (count($items) > 0) { if (count($items) > 0) {
$remove = array(); $remove = array();
$ts = $this->nowDT->format('U'); $ts = $this->nowDT->format('U');
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();
} }
$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);
} }
$instance->setDbEnds($this->nowDT); $instance->setDbEnds($this->nowDT);
$instance->save($this->con); $instance->save($this->con);
$this->con->commit(); $this->con->commit();
if ($instance->getDbRecord()) { if ($instance->getDbRecord()) {
Application_Model_RabbitMq::SendMessageToShowRecorder("cancel_recording"); Application_Model_RabbitMq::SendMessageToShowRecorder("cancel_recording");
} }
} catch (Exception $e) {
$this->con->rollback();
throw $e;
} }
catch (Exception $e) {
$this->con->rollback();
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,10 +29,10 @@ 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";
} }
$component->setDbIp($p_ipAddress); $component->setDbIp($p_ipAddress);
$component->save(); $component->save();
} }

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
@ -14,85 +14,86 @@ class Application_Model_ShowBuilder {
private $user; private $user;
private $opts; private $opts;
private $pos; private $pos;
private $contentDT; private $contentDT;
private $epoch_now; private $epoch_now;
private $currentShow; private $currentShow;
private $showInstances = array(); private $showInstances = array();
private $defaultRowArray = array( private $defaultRowArray = array(
"header" => false, "header" => false,
"footer" => false, "footer" => false,
"empty" => false, "empty" => false,
"allowed" => false, "allowed" => false,
"id" => 0, "id" => 0,
"instance" => "", "instance" => "",
"starts" => "", "starts" => "",
"ends" => "", "ends" => "",
"runtime" => "", "runtime" => "",
"title" => "", "title" => "",
"creator" => "", "creator" => "",
"album" => "", "album" => "",
"timestamp" => null, "timestamp" => null,
"cuein" => "", "cuein" => "",
"cueout" => "", "cueout" => "",
"fadein" => "", "fadein" => "",
"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()
->setFormatter(ModelCriteria::FORMAT_ON_DEMAND) ->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)
->filterByDbHost($this->user->getId()) ->filterByDbHost($this->user->getId())
->find(); ->find();
foreach ($host_shows as $host_show) { foreach ($host_shows as $host_show) {
$shows[] = $host_show->getDbShow(); $shows[] = $host_show->getDbShow();
} }
return $shows; return $shows;
} }
//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;
} }
if ($this->user->canSchedule($p_item["show_id"]) == true) { if ($this->user->canSchedule($p_item["show_id"]) == true) {
$row["allowed"] = true; $row["allowed"] = true;
} }
} }
private function getItemColor($p_item, &$row) { private function getItemColor($p_item, &$row)
$defaultColor = "ffffff"; {
$defaultColor = "ffffff";
$defaultBackground = "3366cc"; $defaultBackground = "3366cc";
$color = $p_item["show_color"]; $color = $p_item["show_color"];
if ($color === '') { if ($color === '') {
$color = $defaultColor; $color = $defaultColor;
@ -101,70 +102,76 @@ class Application_Model_ShowBuilder {
if ($backgroundColor === '') { if ($backgroundColor === '') {
$backgroundColor = $defaultBackground; $backgroundColor = $defaultBackground;
} }
$row["color"] = $color; $row["color"] = $color;
$row["backgroundColor"] = $backgroundColor; $row["backgroundColor"] = $backgroundColor;
} }
//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"));
} }
$row["timestamp"] = $ts; $row["timestamp"] = $ts;
} }
/* /*
* marks a row's status. * marks a row's status.
* 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) {
$row["scheduled"] = 2;
} }
else if ($row["header"] === true && $this->epoch_now < $p_epochItemEnd) {
$row["scheduled"] = 2;
}
//item is in the past. //item is in the past.
else if ($this->epoch_now > $p_epochItemEnd) { else if ($this->epoch_now > $p_epochItemEnd) {
$row["scheduled"] = 0; $row["scheduled"] = 0;
} }
//item is the currently scheduled item. //item is the currently scheduled item.
else if ($this->epoch_now >= $p_epochItemStart && $this->epoch_now < $p_epochItemEnd) { else if ($this->epoch_now >= $p_epochItemStart && $this->epoch_now < $p_epochItemEnd) {
$row["scheduled"] = 1; $row["scheduled"] = 1;
//how many seconds the view should wait to redraw itself. //how many seconds the view should wait to redraw itself.
$row["refresh"] = $p_epochItemEnd - $this->epoch_now; $row["refresh"] = $p_epochItemEnd - $this->epoch_now;
}
//item is in the future.
else if ($this->epoch_now < $p_epochItemStart) {
$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);
} }
//item is in the future.
else if ($this->epoch_now < $p_epochItemStart) {
$row["scheduled"] = 2;
}
} }
private function makeHeaderRow($p_item) { private function makeHeaderRow($p_item)
{
$row = $this->defaultRowArray; $row = $this->defaultRowArray;
$this->isAllowed($p_item, $row); $this->isAllowed($p_item, $row);
$this->getRowTimestamp($p_item, $row); $this->getRowTimestamp($p_item, $row);
@ -173,55 +180,56 @@ class Application_Model_ShowBuilder {
$showStartDT = new DateTime($p_item["si_starts"], new DateTimeZone("UTC")); $showStartDT = new DateTime($p_item["si_starts"], new DateTimeZone("UTC"));
$showStartDT->setTimezone(new DateTimeZone($this->timezone)); $showStartDT->setTimezone(new DateTimeZone($this->timezone));
$startsEpoch = floatval($showStartDT->format("U.u")); $startsEpoch = floatval($showStartDT->format("U.u"));
$showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC")); $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC"));
$showEndDT->setTimezone(new DateTimeZone($this->timezone)); $showEndDT->setTimezone(new DateTimeZone($this->timezone));
$endsEpoch = floatval($showEndDT->format("U.u")); $endsEpoch = floatval($showEndDT->format("U.u"));
//is a rebroadcast show //is a rebroadcast show
if (intval($p_item["si_rebroadcast"]) === 1) { if (intval($p_item["si_rebroadcast"]) === 1) {
$row["rebroadcast"] = true; $row["rebroadcast"] = true;
$parentInstance = CcShowInstancesQuery::create()->findPk($p_item["parent_show"]); $parentInstance = CcShowInstancesQuery::create()->findPk($p_item["parent_show"]);
$name = $parentInstance->getCcShow()->getDbName(); $name = $parentInstance->getCcShow()->getDbName();
$dt = $parentInstance->getDbStarts(null); $dt = $parentInstance->getDbStarts(null);
$dt->setTimezone(new DateTimeZone($this->timezone)); $dt->setTimezone(new DateTimeZone($this->timezone));
$time = $dt->format("Y-m-d H:i"); $time = $dt->format("Y-m-d H:i");
$row["rebroadcast_title"] = "Rebroadcast of {$name} from {$time}"; $row["rebroadcast_title"] = "Rebroadcast of {$name} from {$time}";
} } 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;
} }
} }
} }
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;
} }
$row["header"] = true; $row["header"] = true;
$row["starts"] = $showStartDT->format("Y-m-d H:i"); $row["starts"] = $showStartDT->format("Y-m-d H:i");
$row["startDate"] = $showStartDT->format("Y-m-d"); $row["startDate"] = $showStartDT->format("Y-m-d");
$row["startTime"] = $showStartDT->format("H:i"); $row["startTime"] = $showStartDT->format("H:i");
$row["refresh"] = floatval($showStartDT->format("U.u")) - $this->epoch_now; $row["refresh"] = floatval($showStartDT->format("U.u")) - $this->epoch_now;
$row["ends"] = $showEndDT->format("Y-m-d H:i"); $row["ends"] = $showEndDT->format("Y-m-d H:i");
$row["endDate"] = $showEndDT->format("Y-m-d"); $row["endDate"] = $showEndDT->format("Y-m-d");
$row["endTime"] = $showEndDT->format("H:i"); $row["endTime"] = $showEndDT->format("H:i");
$row["duration"] = floatval($showEndDT->format("U.u")) - floatval($showStartDT->format("U.u")); $row["duration"] = floatval($showEndDT->format("U.u")) - floatval($showStartDT->format("U.u"));
$row["title"] = $p_item["show_name"]; $row["title"] = $p_item["show_name"];
$row["instance"] = intval($p_item["si_id"]); $row["instance"] = intval($p_item["si_id"]);
$row["image"] = ''; $row["image"] = '';
$this->getScheduledStatus($startsEpoch, $endsEpoch, $row); $this->getScheduledStatus($startsEpoch, $endsEpoch, $row);
$this->contentDT = $showStartDT; $this->contentDT = $showStartDT;
@ -229,162 +237,171 @@ 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"));
$this->getItemStatus($p_item, $row); $this->getItemStatus($p_item, $row);
$startsEpoch = floatval($schedStartDT->format("U.u")); $startsEpoch = floatval($schedStartDT->format("U.u"));
$endsEpoch = floatval($schedEndDT->format("U.u")); $endsEpoch = floatval($schedEndDT->format("U.u"));
$showEndEpoch = floatval($showEndDT->format("U.u")); $showEndEpoch = floatval($showEndDT->format("U.u"));
//don't want an overbooked item to stay marked as current. //don't want an overbooked item to stay marked as current.
$this->getScheduledStatus($startsEpoch, min($endsEpoch, $showEndEpoch), $row); $this->getScheduledStatus($startsEpoch, min($endsEpoch, $showEndEpoch), $row);
$row["id"] = intval($p_item["sched_id"]); $row["id"] = intval($p_item["sched_id"]);
$row["image"] = $p_item["file_exists"]; $row["image"] = $p_item["file_exists"];
$row["instance"] = intval($p_item["si_id"]); $row["instance"] = intval($p_item["si_id"]);
$row["starts"] = $schedStartDT->format("H:i:s"); $row["starts"] = $schedStartDT->format("H:i:s");
$row["ends"] = $schedEndDT->format("H:i:s"); $row["ends"] = $schedEndDT->format("H:i:s");
$formatter = new LengthFormatter($p_item['file_length']);
$row['runtime'] = $formatter->format();
$row["title"] = $p_item["file_track_title"]; $formatter = new LengthFormatter($p_item['file_length']);
$row["creator"] = $p_item["file_artist_name"]; $row['runtime'] = $formatter->format();
$row["album"] = $p_item["file_album_title"];
$row["cuein"] = $p_item["cue_in"]; $row["title"] = $p_item["file_track_title"];
$row["cueout"] = $p_item["cue_out"]; $row["creator"] = $p_item["file_artist_name"];
$row["fadein"] = round(substr($p_item["fade_in"], 6), 6); $row["album"] = $p_item["file_album_title"];
$row["fadeout"] = round(substr($p_item["fade_out"], 6), 6);
$row["cuein"] = $p_item["cue_in"];
$row["pos"] = $this->pos++; $row["cueout"] = $p_item["cue_out"];
$row["fadein"] = round(substr($p_item["fade_in"], 6), 6);
$row["fadeout"] = round(substr($p_item["fade_out"], 6), 6);
$row["pos"] = $this->pos++;
$this->contentDT = $schedEndDT; $this->contentDT = $schedEndDT;
} }
//show is empty or is a special kind of show (recording etc) //show is empty or is a special kind of show (recording etc)
else if (intval($p_item["si_record"]) === 1) { else if (intval($p_item["si_record"]) === 1) {
$row["record"] = true; $row["record"] = true;
$row["instance"] = intval($p_item["si_id"]); $row["instance"] = intval($p_item["si_id"]);
$showStartDT = new DateTime($p_item["si_starts"], new DateTimeZone("UTC")); $showStartDT = new DateTime($p_item["si_starts"], new DateTimeZone("UTC"));
$showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC")); $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC"));
$startsEpoch = floatval($showStartDT->format("U.u")); $startsEpoch = floatval($showStartDT->format("U.u"));
$endsEpoch = floatval($showEndDT->format("U.u")); $endsEpoch = floatval($showEndDT->format("U.u"));
$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"]);
} }
if (intval($p_item["si_rebroadcast"]) === 1) { if (intval($p_item["si_rebroadcast"]) === 1) {
$row["rebroadcast"] = true; $row["rebroadcast"] = true;
} }
if ($this->currentShow === true) { if ($this->currentShow === true) {
$row["currentShow"] = true; $row["currentShow"] = true;
} }
$this->getItemColor($p_item, $row); $this->getItemColor($p_item, $row);
$this->getRowTimestamp($p_item, $row); $this->getRowTimestamp($p_item, $row);
$this->isAllowed($p_item, $row); $this->isAllowed($p_item, $row);
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"]);
$this->getRowTimestamp($p_item, $row); $this->getRowTimestamp($p_item, $row);
$showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC")); $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC"));
$contentDT = $this->contentDT; $contentDT = $this->contentDT;
$runtime = bcsub($contentDT->format("U.u"), $showEndDT->format("U.u"), 6); $runtime = bcsub($contentDT->format("U.u"), $showEndDT->format("U.u"), 6);
$row["runtime"] = $runtime; $row["runtime"] = $runtime;
$timeFilled = new TimeFilledFormatter($runtime); $timeFilled = new TimeFilledFormatter($runtime);
$row["fRuntime"] = $timeFilled->format(); $row["fRuntime"] = $timeFilled->format();
$showStartDT = new DateTime($p_item["si_starts"], new DateTimeZone("UTC")); $showStartDT = new DateTime($p_item["si_starts"], new DateTimeZone("UTC"));
$showStartDT->setTimezone(new DateTimeZone($this->timezone)); $showStartDT->setTimezone(new DateTimeZone($this->timezone));
$startsEpoch = floatval($showStartDT->format("U.u")); $startsEpoch = floatval($showStartDT->format("U.u"));
$showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC")); $showEndDT = new DateTime($p_item["si_ends"], new DateTimeZone("UTC"));
$showEndDT->setTimezone(new DateTimeZone($this->timezone)); $showEndDT->setTimezone(new DateTimeZone($this->timezone));
$endsEpoch = floatval($showEndDT->format("U.u")); $endsEpoch = floatval($showEndDT->format("U.u"));
$row["refresh"] = floatval($showEndDT->format("U.u")) - $this->epoch_now; $row["refresh"] = floatval($showEndDT->format("U.u")) - $this->epoch_now;
if ($this->currentShow === true) { if ($this->currentShow === true) {
$row["currentShow"] = true; $row["currentShow"] = true;
} }
$this->getScheduledStatus($startsEpoch, $endsEpoch, $row); $this->getScheduledStatus($startsEpoch, $endsEpoch, $row);
$this->isAllowed($p_item, $row); $this->isAllowed($p_item, $row);
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();
} }
$currentInstances = array(); $currentInstances = array();
foreach ($shows as $show) { foreach ($shows as $show) {
if (empty($include) || in_array($show["show_id"], $include)) { if (empty($include) || in_array($show["show_id"], $include)) {
$currentInstances[] = $show["instance_id"]; $currentInstances[] = $show["instance_id"];
if (isset($show["last_scheduled"])) { if (isset($show["last_scheduled"])) {
$dt = new DateTime($show["last_scheduled"], new DateTimeZone("UTC")); $dt = new DateTime($show["last_scheduled"],
new DateTimeZone("UTC"));
} else {
$dt = new DateTime($show["created"],
new DateTimeZone("UTC"));
} }
else {
$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,14 +440,16 @@ 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);
$current_id = $item["si_id"]; $current_id = $item["si_id"];
$this->pos = 1; $this->pos = 1;
} }
@ -439,17 +459,21 @@ class Application_Model_ShowBuilder {
if (isset($row)) { if (isset($row)) {
$display_items[] = $row; $display_items[] = $row;
} }
if ($current_id !== -1 && !in_array($current_id, $this->showInstances)) { if ($current_id !== -1 &&
$this->showInstances[] = $current_id; !in_array($current_id, $this->showInstances)) {
$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(){
$con = Propel::getConnection();
public function deleteRebroadcasts()
{
$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,26 +169,33 @@ 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);
$showStartsEpoch = strtotime($this->getShowInstanceStart()); $showStartsEpoch = strtotime($this->getShowInstanceStart());
$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);
@ -370,7 +398,7 @@ class Application_Model_ShowInstance {
$scheduler = new Application_Model_Scheduler(); $scheduler = new Application_Model_Scheduler();
$scheduler->scheduleAfter( $scheduler->scheduleAfter(
array(array("id" => 0, "instance" => $id, "timestamp" => $ts)), array(array("id" => 0, "instance" => $id, "timestamp" => $ts)),
array(array("id" => $pl_id, "type" => "playlist")) array(array("id" => $pl_id, "type" => "playlist"))
); );
} }
@ -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,23 +554,23 @@ 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();
} }
} }
} }
Application_Model_RabbitMq::PushSchedule(); if ($rabbitmqPush) {
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()}");
} }
} }
} }
@ -573,21 +598,20 @@ class Application_Model_ShowInstance {
public function getTimeScheduled() public function getTimeScheduled()
{ {
$time = $this->_showInstance->getDbTimeFilled(); $time = $this->_showInstance->getDbTimeFilled();
if ($time != "00:00:00" && !empty($time)) { if ($time != "00:00:00" && !empty($time)) {
$time_arr = explode(".", $time); $time_arr = explode(".", $time);
if (count($time_arr) > 1) { if (count($time_arr) > 1) {
$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 {
$time = "00:00:00.00"; $time = "00:00:00.00";
} }
return $time; return $time;
} }
@ -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'));
} }
@ -631,22 +657,107 @@ class Application_Model_ShowInstance {
} else { } else {
$returnStr = $hours . ":" . $interval->format("%I:%S") . ".00"; $returnStr = $hours . ":" . $interval->format("%I:%S") . ".00";
} }
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();
}
} }
@ -664,126 +777,120 @@ class Application_Model_ShowInstance {
public function getLastAudioItemEnd() public function getLastAudioItemEnd()
{ {
$con = Propel::getConnection(); $con = Propel::getConnection();
$sql = "SELECT ends FROM cc_schedule " $sql = "SELECT ends FROM cc_schedule "
."WHERE instance_id = {$this->_instanceId} " ."WHERE instance_id = :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');
}
public function getShowEndGapTime(){ return ($query !== false) ? $query : null;
$showEnd = $this->getShowInstanceEnd(); }
$lastItemEnd = $this->getLastAudioItemEnd();
if (is_null($lastItemEnd)){ public function getShowEndGapTime()
$lastItemEnd = $this->getShowInstanceStart(); {
} $showEnd = $this->getShowInstanceEnd();
$lastItemEnd = $this->getLastAudioItemEnd();
if (is_null($lastItemEnd)) {
$diff = strtotime($showEnd) - strtotime($lastItemEnd); $lastItemEnd = $this->getShowInstanceStart();
return ($diff < 0) ? 0 : $diff;
}
public static function GetLastShowInstance($p_timeNow){
global $CC_CONFIG;
$con = Propel::getConnection();
$sql = "SELECT si.id"
." 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;
} }
$diff = strtotime($showEnd) - strtotime($lastItemEnd);
return ($diff < 0) ? 0 : $diff;
}
public static function GetLastShowInstance($p_timeNow)
{
$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' );
return ($id ? new Application_Model_ShowInstance($id) : 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,46 +23,43 @@ 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',
'track[title]' => $filename, 'track[title]' => $filename,
'track[asset_data]' => '@' . $filepath, 'track[asset_data]' => '@' . $filepath,
'track[tag_list]' => $tags, 'track[tag_list]' => $tags,
'track[description]' => $description, 'track[description]' => $description,
'track[downloadable]' => $downloadable, 'track[downloadable]' => $downloadable,
); );
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];
} }
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;
@ -77,14 +75,24 @@ class Application_Model_Soundcloud {
if ($license != "") { if ($license != "") {
$track_data['track[license]'] = $license; $track_data['track[license]'] = $license;
} }
$response = json_decode( $response = json_decode(
$this->_soundcloud->post('tracks', $track_data), $this->_soundcloud->post('tracks', $track_data),
true true
); );
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" $sql = "SELECT value FROM cc_stream_setting"
." WHERE keyname = '$key'"; ." WHERE keyname = :key";
$result = $con->query($sql)->fetchColumn(0);
if ($result == 0) $stmt = $con->prepare($sql);
return ""; $stmt->bindParam(':key', $key);
else {
$sql = "SELECT value FROM cc_stream_setting" if ($stmt->execute()) {
." WHERE keyname = '$key'"; $result = $stmt->fetchColumn(0);
} else {
$result = $con->query($sql)->fetchColumn(0); $msg = implode(',', $stmt->errorInfo());
return ($result !== false) ? $result : NULL; 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,10 +223,13 @@ 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();
foreach ($data as $keyname => $v) { foreach ($data as $keyname => $v) {
$sql = "UPDATE cc_stream_setting SET value='$v' WHERE keyname='$keyname'"; $sql = "UPDATE cc_stream_setting SET value='$v' WHERE keyname='$keyname'";
@ -198,58 +237,93 @@ 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
*/ */
public static function setLiquidsoapError($stream_id, $msg, $boot_time=null) public static function setLiquidsoapError($stream_id, $msg, $boot_time=null)
{ {
$con = Propel::getConnection(); $con = Propel::getConnection();
$update_time = Application_Model_Preference::GetStreamUpdateTimestemp(); $update_time = Application_Model_Preference::GetStreamUpdateTimestemp();
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);
} }
} }
public static function getLiquidsoapError($stream_id) public static function getLiquidsoapError($stream_id)
{ {
$con = Propel::getConnection(); $con = Propel::getConnection();
$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)
{ {
$con = Propel::getConnection(); $con = Propel::getConnection();
$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');
} }
/* /*
@ -258,18 +332,28 @@ class Application_Model_StreamSetting {
*/ */
public static function getStreamInfoForDataCollection() public static function getStreamInfoForDataCollection()
{ {
$con = Propel::getConnection(); $con = Propel::getConnection();
$out = array(); $out = array();
$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,27 +3,28 @@
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'];
$url = "http://$p_ip:2812/_status?format=xml"; $url = "http://$p_ip:2812/_status?format=xml";
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "$monit_user:$monit_password"); curl_setopt($ch, CURLOPT_USERPWD, "$monit_user:$monit_password");
//wait a max of 3 seconds before aborting connection attempt //wait a max of 3 seconds before aborting connection attempt
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
$result = curl_exec($ch); $result = curl_exec($ch);
$info = curl_getinfo($ch); $info = curl_getinfo($ch);
curl_close($ch); curl_close($ch);
$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;
@ -32,9 +33,9 @@ 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...",
@ -43,7 +44,7 @@ class Application_Model_Systemstatus
"memory_perc"=>"0%", "memory_perc"=>"0%",
"memory_kb"=>"0", "memory_kb"=>"0",
"cpu_perc"=>"0%"); "cpu_perc"=>"0%");
$notMonitored = array( $notMonitored = array(
"name"=>$p_serviceName, "name"=>$p_serviceName,
"process_id"=>"NOT MONITORED", "process_id"=>"NOT MONITORED",
@ -53,7 +54,7 @@ class Application_Model_Systemstatus
"memory_kb"=>"0", "memory_kb"=>"0",
"cpu_perc"=>"0%" "cpu_perc"=>"0%"
); );
$notRunning = array( $notRunning = array(
"name"=>$p_serviceName, "name"=>$p_serviceName,
"process_id"=>"FAILED", "process_id"=>"FAILED",
@ -65,140 +66,140 @@ 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;
} }
} }
} }
} }
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();
$docRoot = self::GetMonitStatus($ip); $docRoot = self::GetMonitStatus($ip);
$data = self::ExtractServiceInformation($docRoot, "airtime-playout"); $data = self::ExtractServiceInformation($docRoot, "airtime-playout");
return $data; return $data;
} }
} }
public static function GetLiquidsoapStatus(){
public static function GetLiquidsoapStatus()
{
$component = CcServiceRegisterQuery::create()->findOneByDbName("pypo"); $component = CcServiceRegisterQuery::create()->findOneByDbName("pypo");
if (is_null($component)){ if (is_null($component)) {
return null; return null;
} else { } else {
$ip = $component->getDbIp(); $ip = $component->getDbIp();
$docRoot = self::GetMonitStatus($ip); $docRoot = self::GetMonitStatus($ip);
$data = self::ExtractServiceInformation($docRoot, "airtime-liquidsoap"); $data = self::ExtractServiceInformation($docRoot, "airtime-liquidsoap");
return $data; return $data;
} }
} }
public static function GetMediaMonitorStatus(){
public static function GetMediaMonitorStatus()
{
$component = CcServiceRegisterQuery::create()->findOneByDbName("media-monitor"); $component = CcServiceRegisterQuery::create()->findOneByDbName("media-monitor");
if (is_null($component)){ if (is_null($component)) {
return null; return null;
} else { } else {
$ip = $component->getDbIp(); $ip = $component->getDbIp();
$docRoot = self::GetMonitStatus($ip); $docRoot = self::GetMonitStatus($ip);
$data = self::ExtractServiceInformation($docRoot, "airtime-media-monitor"); $data = self::ExtractServiceInformation($docRoot, "airtime-media-monitor");
return $data; return $data;
} }
} }
public static function GetIcecastStatus(){ public static function GetIcecastStatus()
{
$docRoot = self::GetMonitStatus("localhost"); $docRoot = self::GetMonitStatus("localhost");
$data = self::ExtractServiceInformation($docRoot, "icecast2"); $data = self::ExtractServiceInformation($docRoot, "icecast2");
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";
@ -208,37 +209,38 @@ class Application_Model_Systemstatus
return $data; return $data;
} }
public static function GetDiskInfo(){ public static function GetDiskInfo()
{
$partions = array(); $partions = array();
if (isset($_SERVER['AIRTIME_SRV'])){ if (isset($_SERVER['AIRTIME_SRV'])) {
//connect to DB and find how much total space user has allocated. //connect to DB and find how much total space user has allocated.
$totalSpace = Application_Model_Preference::GetDiskQuota(); $totalSpace = Application_Model_Preference::GetDiskQuota();
$storPath = Application_Model_MusicDir::getStorDir()->getDirectory(); $storPath = Application_Model_MusicDir::getStorDir()->getDirectory();
list($usedSpace,) = preg_split("/[\s]+/", exec("du -bs $storPath")); list($usedSpace,) = preg_split("/[\s]+/", exec("du -bs $storPath"));
$partitions[$totalSpace]->totalSpace = $totalSpace; $partitions[$totalSpace]->totalSpace = $totalSpace;
$partitions[$totalSpace]->totalFreeSpace = $totalSpace - $usedSpace; $partitions[$totalSpace]->totalFreeSpace = $totalSpace - $usedSpace;
Logging::log($partitions[$totalSpace]->totalFreeSpace); Logging::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());
} }
$partitions[$totalSpace]->dirs[] = $md->getDirectory(); $partitions[$totalSpace]->dirs[] = $md->getDirectory();
} }
} }

View file

@ -1,263 +1,319 @@
<?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(); {
$result = false; $type = $this->getType();
$result = false;
if ( $type === UTYPE_ADMIN || if ($type === UTYPE_ADMIN ||
$type === UTYPE_PROGRAM_MANAGER || $type === UTYPE_PROGRAM_MANAGER ||
CcShowHostsQuery::create()->filterByDbShow($p_showId)->filterByDbHost($this->getId())->count() > 0 ) 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; $real_type = $this->_userInstance->getDbType();
case UTYPE_HOST: return in_array($real_type, $type);
$userId = $this->_userInstance->getDbId();
$result = CcShowHostsQuery::create()->filterByDbShow($showId)->filterByDbHost($userId)->count() > 0;
break;
case UTYPE_PROGRAM_MANAGER:
$result = $this->_userInstance->getDbType() === 'P';
break;
}
if($result){
return $result;
}
}
}else{
switch($type){
case UTYPE_ADMIN:
return $this->_userInstance->getDbType() === 'A';
case UTYPE_HOST:
$userId = $this->_userInstance->getDbId();
return CcShowHostsQuery::create()->filterByDbShow($showId)->filterByDbHost($userId)->count() > 0;
case UTYPE_PROGRAM_MANAGER:
return $this->_userInstance->getDbType() === 'P';
}
}
} }
public function setLogin($login){ public function setLogin($login)
{
$user = $this->_userInstance; $user = $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)
{ {
$con = Propel::getConnection(); 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();
$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 = $sql_gen ." WHERE (". $sql_type.") "; $sql_type = join(" OR ", $types);
$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;
} }
$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;
}
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.") "; return ($query !== false) ? $query : null;
}
$query = $con->query($sql)->fetchColumn(0);
return ($query !== false) ? $query : NULL;
} }
public static function getHosts($search=NULL) { public static function getHosts($search=null)
{
return Application_Model_User::getUsers(array('H'), $search); return Application_Model_User::getUsers(array('H'), $search);
} }
public static function getUsersDataTablesInfo($datatables) { public static function getUsersDataTablesInfo($datatables)
{
$con = Propel::getConnection(CcSubjsPeer::DATABASE_NAME); $con = Propel::getConnection(CcSubjsPeer::DATABASE_NAME);
$displayColumns = array("id", "login", "first_name", "last_name", "type"); $displayColumns = array("id", "login", "first_name", "last_name", "type");
$fromTable = "cc_subjs"; $fromTable = "cc_subjs";
@ -273,8 +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;
}
try {
return new self($userinfo->id);
} catch (Exception $e) {
//we get here if $userinfo->id is defined, but doesn't exist
//in the database anymore.
Zend_Auth::getInstance()->clearIdentity();
return null; return null;
} else {
try {
return new self($userinfo->id);
} catch (Exception $e){
//we get here if $userinfo->id is defined, but doesn't exist
//in the database anymore.
Zend_Auth::getInstance()->clearIdentity();
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

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

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