Format code using php-cs-fixer

This commit is contained in:
jo 2021-10-11 16:10:47 +02:00
parent 43d7dc92cd
commit d52c6184b9
352 changed files with 17473 additions and 17041 deletions

View File

@ -1,8 +1,9 @@
<?php
require_once CONFIG_PATH . "conf.php";
require_once CONFIG_PATH . 'conf.php';
$CC_CONFIG = Config::getConfig();
require_once CONFIG_PATH . "ACL.php";
require_once CONFIG_PATH . 'ACL.php';
// Since we initialize the database during the configuration check,
// check the $configRun global to avoid reinitializing unnecessarily
@ -10,15 +11,16 @@ if (!isset($configRun) || !$configRun) {
Propel::init(CONFIG_PATH . 'airtime-conf-production.php');
}
require_once CONFIG_PATH . "constants.php";
require_once CONFIG_PATH . 'constants.php';
Logging::setLogPath(LIBRETIME_LOG_DIR . '/zendphp.log');
Zend_Session::setOptions(array('strict' => true));
Zend_Session::setOptions(['strict' => true]);
Config::setAirtimeVersion();
require_once (CONFIG_PATH . 'navigation.php');
Zend_Validate::setDefaultNamespaces("Zend");
require_once CONFIG_PATH . 'navigation.php';
Zend_Validate::setDefaultNamespaces('Zend');
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new RabbitMqPlugin());
@ -36,7 +38,7 @@ class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
}
/**
* initialize front controller
* initialize front controller.
*
* This is call ZFrontController to ensure it is executed last in the bootstrap process.
*/
@ -53,11 +55,12 @@ class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
$router->addRoute(
'password-change',
new Zend_Controller_Router_Route('password-change/:user_id/:token', array(
new Zend_Controller_Router_Route('password-change/:user_id/:token', [
'module' => 'default',
'controller' => 'login',
'action' => 'password-change',
)));
])
);
}
public function _initPlugins()
@ -67,4 +70,3 @@ class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
$front->registerPlugin(new PageLayoutInitPlugin($this));
}
}

View File

@ -5,22 +5,27 @@
// but the default installation configs are likely to be installed by
// amature users on the setup that does not have https. Forcing
// cookie_secure on non https would result in confusing login problems.
if(!empty($_SERVER['HTTPS'])) {
if (!empty($_SERVER['HTTPS'])) {
ini_set('session.cookie_secure', '1');
}
ini_set('session.cookie_httponly', '1');
error_reporting(E_ALL|E_STRICT);
error_reporting(E_ALL | E_STRICT);
function exception_error_handler($errno, $errstr, $errfile, $errline) {
function exception_error_handler($errno, $errstr, $errfile, $errline)
{
//Check if the statement that threw this error wanted its errors to be
//suppressed. If so then return without with throwing exception.
if (0 === error_reporting()) return;
if (0 === error_reporting()) {
return;
}
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
return false;
}
set_error_handler("exception_error_handler");
set_error_handler('exception_error_handler');
// Define application environment
defined('APPLICATION_ENV')
@ -30,10 +35,10 @@ defined('VERBOSE_STACK_TRACE')
|| define('VERBOSE_STACK_TRACE', (getenv('VERBOSE_STACK_TRACE') ? getenv('VERBOSE_STACK_TRACE') : true));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
set_include_path(implode(PATH_SEPARATOR, [
get_include_path(),
realpath(LIB_PATH)
)));
realpath(LIB_PATH),
]));
set_include_path(APPLICATION_PATH . 'common' . PATH_SEPARATOR . get_include_path());
set_include_path(APPLICATION_PATH . 'common/enum' . PATH_SEPARATOR . get_include_path());
@ -65,12 +70,12 @@ require_once 'autoload.php';
/** Zend_Application */
$application = new Zend_Application(
APPLICATION_ENV,
CONFIG_PATH . 'application.ini',
true
APPLICATION_ENV,
CONFIG_PATH . 'application.ini',
true
);
require_once(APPLICATION_PATH . "logging/Logging.php");
require_once APPLICATION_PATH . 'logging/Logging.php';
Logging::setLogPath(LIBRETIME_LOG_DIR . '/zendphp.log');
Logging::setupParseErrorLogging();
@ -79,14 +84,15 @@ try {
$sapi_type = php_sapi_name();
if (substr($sapi_type, 0, 3) == 'cli') {
set_include_path(APPLICATION_PATH . PATH_SEPARATOR . get_include_path());
require_once("Bootstrap.php");
require_once 'Bootstrap.php';
} else {
$application->bootstrap()->run();
}
} catch (Exception $e) {
if ($e->getCode() == 401)
{
if ($e->getCode() == 401) {
header($_SERVER['SERVER_PROTOCOL'] . ' 401 Unauthorized', true, 401);
return;
}
@ -95,14 +101,14 @@ try {
if (VERBOSE_STACK_TRACE) {
echo $e->getMessage();
echo "<pre>";
echo '<pre>';
echo $e->getTraceAsString();
echo "</pre>";
echo '</pre>';
Logging::error($e->getMessage());
Logging::error($e->getTraceAsString());
} else {
Logging::error($e->getTrace());
}
throw $e;
}

View File

@ -1,9 +1,9 @@
<?php
/**
* Auth adaptor for FreeIPA
* Auth adaptor for FreeIPA.
*/
class LibreTime_Auth_Adaptor_FreeIpa implements Zend_Auth_Adapter_Interface {
class LibreTime_Auth_Adaptor_FreeIpa implements Zend_Auth_Adapter_Interface
{
/**
* @var string
*/
@ -18,36 +18,44 @@ class LibreTime_Auth_Adaptor_FreeIpa implements Zend_Auth_Adapter_Interface {
private $user;
/**
* username from form
* username from form.
*
* @param mixed $username
*
* @return self
*/
function setIdentity($username) {
public function setIdentity($username)
{
$this->username = $username;
return $this;
}
/**
* password from form
* password from form.
*
* This is ignored by FreeIPA but needs to get passed for completeness
*
* @param mixed $password
*
* @return self
*/
function setCredential($password) {
public function setCredential($password)
{
$this->password = $password;
return $this;
}
/**
* Check if apache logged the user and get data from ldap
* Check if apache logged the user and get data from ldap.
*
* @return Zend_Auth_Result
*/
function authenticate()
public function authenticate()
{
if (array_key_exists('EXTERNAL_AUTH_ERROR', $_SERVER)) {
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE, null, array($_SERVER['EXTERNAL_AUTH_ERROR']));
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE, null, [$_SERVER['EXTERNAL_AUTH_ERROR']]);
}
if (!array_key_exists('REMOTE_USER', $_SERVER)) {
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE, null);
@ -56,7 +64,7 @@ class LibreTime_Auth_Adaptor_FreeIpa implements Zend_Auth_Adapter_Interface {
$remoteUser = $_SERVER['REMOTE_USER'];
$subj = CcSubjsQuery::create()->findOneByDbLogin($remoteUser);
$subjId =null;
$subjId = null;
if ($subj) {
$subjId = $subj->getDBId();
}
@ -89,6 +97,7 @@ class LibreTime_Auth_Adaptor_FreeIpa implements Zend_Auth_Adapter_Interface {
$user->setJabber($userInfo['jabber']);
$user->save();
$this->user = $user;
try {
return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $user);
} catch (Exception $e) {
@ -98,20 +107,22 @@ class LibreTime_Auth_Adaptor_FreeIpa implements Zend_Auth_Adapter_Interface {
}
/**
* return dummy object for internal auth handling
*
* return dummy object for internal auth handling.
*
* we need to build a dummpy object since the auth layer knows nothing about the db
*
* @return stdClass
*/
public function getResultRowObject() {
$o = new \stdClass;
public function getResultRowObject()
{
$o = new \stdClass();
$o->id = $this->user->getId();
$o->username = $this->user->getLogin();
$o->password = $this->user->getPassword();
$o->real_name = implode(' ', array($this->user->getFirstName(), $this->user->getLastName()));
$o->username = $this->user->getLogin();
$o->password = $this->user->getPassword();
$o->real_name = implode(' ', [$this->user->getFirstName(), $this->user->getLastName()]);
$o->type = $this->user->getType();
$o->login = $this->user->getLogin();
return $o;
}
}

View File

@ -10,7 +10,7 @@ class FileStorageBackend extends StorageBackend
public function getDownloadURLs($resourceId, $contentDispositionFilename)
{
return "";
return '';
}
public function deletePhysicalFile($resourceId)
@ -20,11 +20,11 @@ class FileStorageBackend extends StorageBackend
public function deleteAllCloudFileObjects()
{
return "";
return '';
}
public function getFilePrefix()
{
return "";
return '';
}
}

View File

@ -1,10 +1,7 @@
<?php
/**
*
* Controls access to the storage backend class where a file is stored.
*
*/
class ProxyStorageBackend extends StorageBackend
{
@ -13,6 +10,8 @@ class ProxyStorageBackend extends StorageBackend
/**
* Receives the file's storage backend and instantiates the appropriate
* object.
*
* @param mixed $storageBackend
*/
public function __construct($storageBackend)
{
@ -21,7 +20,7 @@ class ProxyStorageBackend extends StorageBackend
// The storage backend in the airtime.conf directly corresponds to
// the name of the class that implements it, so we can create the
// right backend object dynamically:
if ($storageBackend == "file") {
if ($storageBackend == 'file') {
$this->storageBackend = new FileStorageBackend();
} else {
$this->storageBackend = new $storageBackend($CC_CONFIG[$storageBackend]);
@ -42,7 +41,7 @@ class ProxyStorageBackend extends StorageBackend
{
$this->storageBackend->deletePhysicalFile($resourceId);
}
public function deleteAllCloudFileObjects()
{
$this->storageBackend->deleteAllCloudFileObjects();

View File

@ -1,7 +1,6 @@
<?php
/**
*
* Provides access to file objects stored on a specific storage backend.
*/
abstract class StorageBackend
@ -9,14 +8,16 @@ abstract class StorageBackend
private $bucket;
private $accessKey;
private $secretKey;
/** Returns the file object's URL to the storage backend it is located on. */
abstract public function getAbsoluteFilePath($resourceId);
/** Returns the file object's signed URL. The URL must be signed since they
/** Returns the file object's signed URL. The URL must be signed since they.
* @param mixed $resourceId
* @param mixed $contentDispositionFilename
* privately stored on the storage backend. */
abstract public function getDownloadURLs($resourceId, $contentDispositionFilename);
/** Deletes the file from the storage backend. */
abstract public function deletePhysicalFile($resourceId);
@ -31,27 +32,27 @@ abstract class StorageBackend
{
return $this->bucket;
}
protected function setBucket($bucket)
{
$this->bucket = $bucket;
}
protected function getAccessKey()
{
return $this->accessKey;
}
protected function setAccessKey($accessKey)
{
$this->accessKey = $accessKey;
}
protected function getSecretKey()
{
return $this->secretKey;
}
protected function setSecretKey($secretKey)
{
$this->secretKey = $secretKey;

View File

@ -1,30 +1,33 @@
<?php
class AutoPlaylistManager {
class AutoPlaylistManager
{
/**
* @var int how often, in seconds, to check for and ingest new podcast episodes
*/
private static $_AUTOPLAYLIST_POLL_INTERVAL_SECONDS = 60; // 10 minutes
/**
* Check whether $_AUTOPLAYLIST_POLL_INTERVAL_SECONDS have passed since the last call to
* buildAutoPlaylist
* buildAutoPlaylist.
*
* @return bool true if $_AUTOPLAYLIST_POLL_INTERVAL_SECONDS has passed since the last check
*/
public static function hasAutoPlaylistPollIntervalPassed() {
public static function hasAutoPlaylistPollIntervalPassed()
{
$lastPolled = Application_Model_Preference::getAutoPlaylistPollLock();
return empty($lastPolled) || (microtime(true) > $lastPolled + self::$_AUTOPLAYLIST_POLL_INTERVAL_SECONDS);
}
/**
* Find all shows with autoplaylists who have yet to have their playlists built and added to the schedule
*
/**
* Find all shows with autoplaylists who have yet to have their playlists built and added to the schedule.
*/
public static function buildAutoPlaylist() {
public static function buildAutoPlaylist()
{
$autoPlaylists = static::_upcomingAutoPlaylistShows();
foreach ($autoPlaylists as $autoplaylist) {
// creates a ShowInstance object to build the playlist in from the ShowInstancesQuery Object
// creates a ShowInstance object to build the playlist in from the ShowInstancesQuery Object
$si = new Application_Model_ShowInstance($autoplaylist->getDbId());
$playlistid = $si->GetAutoPlaylistId();
// call the addPlaylist to show function and don't check for user permission to avoid call to non-existant user object
@ -45,7 +48,7 @@ class AutoPlaylistManager {
//Logging::info('adding intro');
$si->addPlaylistToShowStart($introplaylistid, false);
}
while(!$full) {
while (!$full) {
// we do not want to try to schedule an empty playlist
if ($playlistid != null) {
$si->addPlaylistToShow($playlistid, false);
@ -53,8 +56,7 @@ class AutoPlaylistManager {
$ps = $si->getPercentScheduled();
if ($ps > 100) {
$full = true;
}
elseif (!$repeatuntilfull) {
} elseif (!$repeatuntilfull) {
break;
}
// we want to avoid an infinite loop if all of the playlists are null
@ -84,26 +86,28 @@ class AutoPlaylistManager {
}
/**
* Find all show instances starting in the next hour with autoplaylists not yet added to the schedule
* Find all show instances starting in the next hour with autoplaylists not yet added to the schedule.
*
* @return PropelObjectCollection collection of ShowInstance objects
* that have unbuilt autoplaylists
*/
protected static function _upcomingAutoPlaylistShows() {
//setting now so that past shows aren't referenced
$now = new DateTime("now", new DateTimeZone("UTC"));
// only build playlists for shows that start up to an hour from now
$future = clone $now;
$future->add(new DateInterval('PT1H'));
protected static function _upcomingAutoPlaylistShows()
{
//setting now so that past shows aren't referenced
$now = new DateTime('now', new DateTimeZone('UTC'));
// only build playlists for shows that start up to an hour from now
$future = clone $now;
$future->add(new DateInterval('PT1H'));
return CcShowInstancesQuery::create()
->filterByDbModifiedInstance(false)
->filterByDbStarts($now,Criteria::GREATER_THAN)
->filterByDbStarts($future,Criteria::LESS_THAN)
->filterByDbStarts($now, Criteria::GREATER_THAN)
->filterByDbStarts($future, Criteria::LESS_THAN)
->useCcShowQuery('a', 'left join')
->filterByDbHasAutoPlaylist(true)
->filterByDbHasAutoPlaylist(true)
->endUse()
->filterByDbAutoPlaylistBuilt(false)
->find();
->find()
;
}
}

View File

@ -1,6 +1,5 @@
<?php
class CORSHelper
{
public static function enableCrossOriginRequests(&$request, &$response)
@ -9,11 +8,12 @@ class CORSHelper
$origin = $request->getHeader('Origin');
$allowedOrigins = self::getAllowedOrigins($request);
if ((!(preg_match("/https?:\/\/localhost/", $origin) === 1)) && ($origin != "") &&
(!in_array($origin, $allowedOrigins))
if ((!(preg_match("/https?:\/\/localhost/", $origin) === 1)) && ($origin != '')
&& (!in_array($origin, $allowedOrigins))
) {
//Don't allow CORS from other domains to prevent XSS.
Logging::error("request origin '{$origin}' is not in allowed '" . implode(', ', $allowedOrigins) . "'!");
throw new Zend_Controller_Action_Exception('Forbidden', 403);
}
//Allow AJAX requests from configured websites. We use this to allow other pages to use LibreTimes API.
@ -23,14 +23,14 @@ class CORSHelper
}
/**
* Get all allowed origins
* Get all allowed origins.
*
* @param Request $request request object
*/
public static function getAllowedOrigins($request)
{
$allowedCorsUrls = array_map(
function($v) { return trim($v); },
function ($v) { return trim($v); },
explode(PHP_EOL, Application_Model_Preference::GetAllowedCorsUrls())
);
@ -41,8 +41,8 @@ class CORSHelper
$portString = '';
if (
$scheme == 'https' && $port != 443 ||
$scheme == 'http' && $port != 80
$scheme == 'https' && $port != 443
|| $scheme == 'http' && $port != 80
) {
$portString = sprintf(':%s', $port);
}
@ -52,8 +52,9 @@ class CORSHelper
$host,
$portString
);
return array_merge($allowedCorsUrls, array(
$requestedUrl
));
return array_merge($allowedCorsUrls, [
$requestedUrl,
]);
}
}

View File

@ -1,7 +1,7 @@
<?php
class CeleryManager {
class CeleryManager
{
/**
* @var int milliseconds (for compatibility with celery) until we consider a message to have timed out
*/
@ -21,31 +21,34 @@ class CeleryManager {
private static $_pendingTasks;
/**
* Connect to the Celery daemon via amqp
* Connect to the Celery daemon via amqp.
*
* @param $config array the airtime configuration array
* @param $exchange string the amqp exchange name
* @param $queue string the amqp queue name
*
* @return Celery the Celery connection object
*
* @throws Exception when a connection error occurs
*
* @return Celery the Celery connection object
*/
private static function _setupCeleryExchange($config, $exchange, $queue) {
return new Celery($config["rabbitmq"]["host"],
$config["rabbitmq"]["user"],
$config["rabbitmq"]["password"],
$config["rabbitmq"]["vhost"],
$exchange, // Exchange name
private static function _setupCeleryExchange($config, $exchange, $queue)
{
return new Celery(
$config['rabbitmq']['host'],
$config['rabbitmq']['user'],
$config['rabbitmq']['password'],
$config['rabbitmq']['vhost'],
$exchange, // Exchange name
$queue, // Binding/queue
$config["rabbitmq"]["port"],
false,
true, // Persistent messages
self::$_CELERY_MESSAGE_TIMEOUT); // Result expiration
$config['rabbitmq']['port'],
false,
true, // Persistent messages
self::$_CELERY_MESSAGE_TIMEOUT
); // Result expiration
}
/**
* Send an amqp message to Celery the airtime-celery daemon to perform a task
* Send an amqp message to Celery the airtime-celery daemon to perform a task.
*
* @param $task string the Celery task name
* @param $exchange string the amqp exchange name
@ -54,65 +57,71 @@ class CeleryManager {
* @return string the task identifier for the started Celery task so we can fetch the
* results asynchronously later
*/
public static function sendCeleryMessage($task, $exchange, $data) {
public static function sendCeleryMessage($task, $exchange, $data)
{
$config = Config::getConfig();
$queue = $routingKey = $exchange;
$c = self::_setupCeleryExchange($config, $exchange, $queue); // Use the exchange name for the queue
$result = $c->PostTask($task, $data, true, $routingKey); // and routing key
return $result->getId();
}
/**
* Given a task name and identifier, check the Celery results queue for any
* corresponding messages
* corresponding messages.
*
* @param $task CeleryTasks the Celery task object
*
* @return array the message response array
*
* @throws CeleryException when no message is found
* @throws CeleryTimeoutException when no message is found and more than
* $_CELERY_MESSAGE_TIMEOUT milliseconds have passed
*
* @return array the message response array
*/
private static function getAsyncResultMessage($task) {
private static function getAsyncResultMessage($task)
{
$config = Config::getConfig();
$queue = self::$_CELERY_RESULTS_EXCHANGE . "." . $task;
$queue = self::$_CELERY_RESULTS_EXCHANGE . '.' . $task;
$c = self::_setupCeleryExchange($config, self::$_CELERY_RESULTS_EXCHANGE, $queue);
$message = $c->getAsyncResultMessage($task->getDbName(), $task->getDbTaskId());
// If the message isn't ready yet (Celery hasn't finished the task), throw an exception.
if ($message == FALSE) {
if ($message == false) {
if (static::_checkMessageTimeout($task)) {
// If the task times out, mark it as failed. We don't want to remove the
// track reference here in case it was a deletion that failed, for example.
$task->setDbStatus(CELERY_FAILED_STATUS)->save();
throw new CeleryTimeoutException("Celery task " . $task->getDbName()
. " with ID " . $task->getDbTaskId() . " timed out");
} else {
// The message hasn't timed out, but it's still false, which means it hasn't been
// sent back from Celery yet.
throw new CeleryException("Waiting on Celery task " . $task->getDbName()
. " with ID " . $task->getDbTaskId());
throw new CeleryTimeoutException('Celery task ' . $task->getDbName()
. ' with ID ' . $task->getDbTaskId() . ' timed out');
}
// The message hasn't timed out, but it's still false, which means it hasn't been
// sent back from Celery yet.
throw new CeleryException('Waiting on Celery task ' . $task->getDbName()
. ' with ID ' . $task->getDbTaskId());
}
return $message;
}
/**
* Check to see if there are any pending tasks for this service
* Check to see if there are any pending tasks for this service.
*
* @param string $taskName the name of the task to poll for
* @param string $serviceName the name of the service to poll for
*
* @return bool true if there are any pending tasks, otherwise false
*/
public static function isBrokerTaskQueueEmpty($taskName = "", $serviceName = "") {
public static function isBrokerTaskQueueEmpty($taskName = '', $serviceName = '')
{
self::$_pendingTasks = static::_getPendingTasks($taskName, $serviceName);
return empty(self::$_pendingTasks);
}
/**
* Poll the message queue for this service to see if any tasks with the given name have completed
* Poll the message queue for this service to see if any tasks with the given name have completed.
*
* If we find any completed tasks, adjust the ThirdPartyTrackReferences table accordingly
*
@ -121,7 +130,8 @@ class CeleryManager {
* @param string $taskName the name of the task to poll for
* @param string $serviceName the name of the service to poll for
*/
public static function pollBrokerTaskQueue($taskName = "", $serviceName = "") {
public static function pollBrokerTaskQueue($taskName = '', $serviceName = '')
{
$pendingTasks = empty(self::$_pendingTasks) ? static::_getPendingTasks($taskName, $serviceName)
: self::$_pendingTasks;
foreach ($pendingTasks as $task) {
@ -141,7 +151,7 @@ class CeleryManager {
}
/**
* Return a collection of all pending CeleryTasks for this service or task
* Return a collection of all pending CeleryTasks for this service or task.
*
* @param string $taskName the name of the task to find
* @param string $serviceName the name of the service to find
@ -149,10 +159,12 @@ class CeleryManager {
* @return PropelCollection any pending CeleryTasks results for this service
* or task if taskName is provided
*/
protected static function _getPendingTasks($taskName, $serviceName) {
protected static function _getPendingTasks($taskName, $serviceName)
{
$query = CeleryTasksQuery::create()
->filterByDbStatus(CELERY_PENDING_STATUS)
->filterByDbTaskId('', Criteria::NOT_EQUAL);
->filterByDbTaskId('', Criteria::NOT_EQUAL)
;
if (!empty($taskName)) {
$query->filterByDbName($taskName);
}
@ -160,52 +172,57 @@ class CeleryManager {
$query->useThirdPartyTrackReferencesQuery()
->filterByDbService($serviceName)->endUse();
}
return $query->joinThirdPartyTrackReferences()
->with('ThirdPartyTrackReferences')->find();
}
/**
* Get a Celery task message from the results queue
* Get a Celery task message from the results queue.
*
* @param $task CeleryTasks the Celery task object
*
* @return object the task message object
*
* @throws CeleryException when the result message for this task is still pending
* @throws CeleryException when the result message for this task is still pending
* @throws CeleryTimeoutException when the result message for this task no longer exists
*
* @return object the task message object
*/
protected static function _getTaskMessage($task) {
protected static function _getTaskMessage($task)
{
$message = self::getAsyncResultMessage($task);
return json_decode($message['body']);
}
/**
* Process a message from the results queue
* Process a message from the results queue.
*
* @param $task CeleryTasks Celery task object
* @param $message mixed async message object from php-celery
*/
protected static function _processTaskMessage($task, $message) {
protected static function _processTaskMessage($task, $message)
{
$ref = $task->getThirdPartyTrackReferences(); // ThirdPartyTrackReferences join
$service = CeleryServiceFactory::getService($ref->getDbService());
$service->updateTrackReference($task, $ref->getDbId(), json_decode($message->result), $message->status);
}
/**
* Check if a task message has been unreachable for more our timeout time
* Check if a task message has been unreachable for more our timeout time.
*
* @param $task CeleryTasks the Celery task object
*
* @return bool true if the dispatch time is empty or it's been more than our timeout time
* since the message was dispatched, otherwise false
*/
protected static function _checkMessageTimeout($task) {
$utc = new DateTimeZone("UTC");
protected static function _checkMessageTimeout($task)
{
$utc = new DateTimeZone('UTC');
$dispatchTime = new DateTime($task->getDbDispatchTime(), $utc);
$now = new DateTime("now", $utc);
$now = new DateTime('now', $utc);
$timeoutSeconds = self::$_CELERY_MESSAGE_TIMEOUT / 1000; // Convert from milliseconds
$timeoutInterval = new DateInterval("PT" . $timeoutSeconds . "S");
return (empty($dispatchTime) || $dispatchTime->add($timeoutInterval) <= $now);
}
$timeoutInterval = new DateInterval('PT' . $timeoutSeconds . 'S');
return empty($dispatchTime) || $dispatchTime->add($timeoutInterval) <= $now;
}
}

View File

@ -1,18 +1,20 @@
<?php
class Application_Common_Database
{
const SINGLE = 'single';
const COLUMN = 'column';
const ALL = 'all';
const EXECUTE = 'execute';
const ROW_COUNT = 'row_count';
public const SINGLE = 'single';
public const COLUMN = 'column';
public const ALL = 'all';
public const EXECUTE = 'execute';
public const ROW_COUNT = 'row_count';
public static function prepareAndExecute($sql,
array $paramValueMap = array(),
$type=self::ALL,
$fetchType=PDO::FETCH_ASSOC,
$con=null)
{
public static function prepareAndExecute(
$sql,
array $paramValueMap = [],
$type = self::ALL,
$fetchType = PDO::FETCH_ASSOC,
$con = null
) {
if (is_null($con)) {
$con = Propel::getConnection();
}
@ -20,51 +22,64 @@ class Application_Common_Database
foreach ($paramValueMap as $param => $v) {
$stmt->bindValue($param, $v);
}
$rows = array();
$rows = [];
if ($stmt->execute()) {
if ($type == self::SINGLE) {
$rows = $stmt->fetch($fetchType);
} else if ($type == self::COLUMN){
} elseif ($type == self::COLUMN) {
$rows = $stmt->fetchColumn();
} else if ($type == self::ALL) {
} elseif ($type == self::ALL) {
$rows = $stmt->fetchAll($fetchType);
} else if ($type == self::EXECUTE) {
} elseif ($type == self::EXECUTE) {
$rows = null;
} else if ($type == self::ROW_COUNT) {
} elseif ($type == self::ROW_COUNT) {
$rows = $stmt->rowCount();
} else {
$msg = "bad type passed: type($type)";
throw new Exception("Error: $msg");
$msg = "bad type passed: type({$type})";
throw new Exception("Error: {$msg}");
}
} else {
$msg = implode(',', $stmt->errorInfo());
throw new Exception("Error: $msg");
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;
public static function smartPrepareAndExecute(
$sql,
array $params,
$type = 'all',
$fetchType = PDO::FETCH_ASSOC
) {
$new_params = [];
$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) {
throw new Exception("Argument {$k} is not inside {$sql}");
}
if ($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;
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);
return Application_Common_Database::prepareAndExecute(
$new_sql,
$new_params,
$type,
$fetchType
);
}
}

View File

@ -4,55 +4,55 @@ class Application_Common_DateHelper
{
private $_dateTime;
function __construct()
public function __construct()
{
$this->_dateTime = date("U");
$this->_dateTime = date('U');
}
/**
* Get time of object construction in the format
* YYYY-MM-DD HH:mm:ss
* YYYY-MM-DD HH:mm:ss.
*/
function getTimestamp()
public function getTimestamp()
{
return date(DEFAULT_TIMESTAMP_FORMAT, $this->_dateTime);
}
/**
* Get time of object construction in the format
* YYYY-MM-DD HH:mm:ss
* YYYY-MM-DD HH:mm:ss.
*/
function getUtcTimestamp()
public function getUtcTimestamp()
{
return gmdate(DEFAULT_TIMESTAMP_FORMAT, $this->_dateTime);
}
/**
* Get date of object construction in the format
* YYYY-MM-DD
* YYYY-MM-DD.
*/
function getDate()
public function getDate()
{
return gmdate("Y-m-d", $this->_dateTime);
return gmdate('Y-m-d', $this->_dateTime);
}
/**
* Get time of object construction in the format
* HH:mm:ss
* HH:mm:ss.
*/
function getTime()
public function getTime()
{
return gmdate("H:i:s", $this->_dateTime);
return gmdate('H:i:s', $this->_dateTime);
}
/** Get the abbreviated timezone for the currently logged in user.
/** Get the abbreviated timezone for the currently logged in user.
* @return A string containing the short form of the timezone set in the preferences for the current user (eg. EST, CEST, etc.)
*/
public static function getUserTimezoneAbbreviation()
{
return self::getTimezoneAbbreviation(Application_Model_Preference::GetUserTimezone());
}
/** Get the abbreviated timezone string of the timezone the station is set to.
* @return A string containing the short form of the station's timezone (eg. EST, CEST, etc.)
*/
@ -60,104 +60,104 @@ class Application_Common_DateHelper
{
return self::getTimezoneAbbreviation(Application_Model_Preference::GetDefaultTimezone());
}
private static function getTimezoneAbbreviation($fullTimeZoneName)
{
$timeZone = new DateTimeZone($fullTimeZoneName);
$now = new DateTime("now", $timeZone);
return $now->format("T");
$now = new DateTime('now', $timeZone);
return $now->format('T');
}
public static function getUserTimezoneOffset()
{
$userTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
$now = new DateTime("now", $userTimezone);
return $now->format("Z");
$now = new DateTime('now', $userTimezone);
return $now->format('Z');
}
public static function getStationTimezoneOffset()
{
$stationTimezone = new DateTimeZone(Application_Model_Preference::GetDefaultTimezone());
$now = new DateTime("now", $stationTimezone);
return $now->format("Z");
$now = new DateTime('now', $stationTimezone);
return $now->format('Z');
}
/**
*
* @return DateTime - YYYY-MM-DD 00:00 in station timezone of today
*/
public static function getTodayStationStartDateTime()
{
$stationTimezone = new DateTimeZone(Application_Model_Preference::GetDefaultTimezone());
$now = new DateTime("now", $stationTimezone);
$now = new DateTime('now', $stationTimezone);
$now->setTime(0, 0, 0);
return $now;
}
/**
*
* @return DateTime - YYYY-MM-DD 00:00 in station timezone of tomorrow
*/
public static function getTodayStationEndDateTime()
{
$stationTimezone = new DateTimeZone(Application_Model_Preference::GetDefaultTimezone());
$now = new DateTime("now", $stationTimezone);
$now->add(new DateInterval("P1D"));
$now = new DateTime('now', $stationTimezone);
$now->add(new DateInterval('P1D'));
$now->setTime(0, 0, 0);
return $now;
}
/**
*
/**
* @return DateTime - YYYY-MM-DD 00:00 in station timezone
*/
public static function getWeekStartDateTime()
{
$now = self::getTodayStationStartDateTime();
// our week starts on monday, but php week starts on sunday.
$day = $now->format('w');
if ($day == 0) {
$day = 7;
}
$dayDiff = $day - 1;
if ($dayDiff > 0) {
$now->sub(new DateInterval("P{$dayDiff}D"));
}
return $now;
}
/**
* This function formats a time by removing seconds
* This function formats a time by removing seconds.
*
* When we receive a time from the database we get the
* format "hh:mm:ss". But when dealing with show times, we
* do not care about the seconds.
*
* @param int $p_dateTime
* The value which to format.
* The value which to format
*
* @return int
* The timestamp with the new format "hh:mm", or
* the original input parameter, if it does not have
* the correct format.
* The timestamp with the new format "hh:mm", or
* the original input parameter, if it does not have
* the correct format
*/
public static function removeSecondsFromTime($p_dateTime)
{
//Format is in hh:mm:ss. We want hh:mm
$timeExplode = explode(":", $p_dateTime);
$timeExplode = explode(':', $p_dateTime);
if (count($timeExplode) == 3)
return $timeExplode[0].":".$timeExplode[1];
else
return $p_dateTime;
if (count($timeExplode) == 3) {
return $timeExplode[0] . ':' . $timeExplode[1];
}
return $p_dateTime;
}
/* Given a track length in the format HH:MM:SS.mm, we want to
@ -170,172 +170,180 @@ class Application_Common_DateHelper
* @return float
* The input parameter converted to seconds.
*/
public static function calculateLengthInSeconds($p_time){
if (2 !== substr_count($p_time, ":")){
public static function calculateLengthInSeconds($p_time)
{
if (2 !== substr_count($p_time, ':')) {
return false;
}
if (1 === substr_count($p_time, ".")){
list($hhmmss, $ms) = explode(".", $p_time);
if (1 === substr_count($p_time, '.')) {
list($hhmmss, $ms) = explode('.', $p_time);
} else {
$hhmmss = $p_time;
$ms = 0;
}
list($hours, $minutes, $seconds) = explode(":", $hhmmss);
$totalSeconds = ($hours*3600 + $minutes*60 + $seconds).".$ms";
list($hours, $minutes, $seconds) = explode(':', $hhmmss);
$totalSeconds = ($hours * 3600 + $minutes * 60 + $seconds) . ".{$ms}";
return round($totalSeconds, 3);
}
/**
* returns true or false depending on input is wether in
* valid range of SQL date/time
* valid range of SQL date/time.
*
* @param string $p_datetime
* should be in format of '0000-00-00 00:00:00'
* should be in format of '0000-00-00 00:00:00'
*/
public static function checkDateTimeRangeForSQL($p_datetime){
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;
$retVal = [];
$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'] = sprintf(_("The year %s must be within the range of 1753 - 9999"), $year);
} else if (!checkdate($month, $day, $year)) {
$retVal['errMsg'] = sprintf(_('The year %s must be within the range of 1753 - 9999'), $year);
} elseif (!checkdate($month, $day, $year)) {
$retVal['success'] = false;
$retVal['errMsg'] = sprintf(_("%s-%s-%s is not a valid date"), $year, $month, $day);
$retVal['errMsg'] = sprintf(_('%s-%s-%s is not a valid date'), $year, $month, $day);
} else {
// check time
if (isset($timeInfo)) {
if (isset($timeInfo[0]) && $timeInfo[0] != "") {
if (isset($timeInfo[0]) && $timeInfo[0] != '') {
$hour = intval($timeInfo[0]);
} else {
$hour = -1;
}
if (isset($timeInfo[1]) && $timeInfo[1] != "") {
if (isset($timeInfo[1]) && $timeInfo[1] != '') {
$min = intval($timeInfo[1]);
} else {
$min = -1;
}
if (isset($timeInfo[2]) && $timeInfo[2] != "") {
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) ) {
if (($hour < 0 || $hour > 23) || ($min < 0 || $min > 59) || ($sec < 0 || $sec > 59)) {
$retVal['success'] = false;
$retVal['errMsg'] = sprintf(_("%s:%s:%s is not a valid time"), $timeInfo[0], $timeInfo[1] ,$timeInfo[2]);
$retVal['errMsg'] = sprintf(_('%s:%s:%s is not a valid time'), $timeInfo[0], $timeInfo[1], $timeInfo[2]);
}
}
}
return $retVal;
}
/*
* @param $datetime string Y-m-d H:i:s in UTC timezone
*
*
* @return string in $format default Y-m-d H:i:s in station timezone
*/
public static function UTCStringToStationTimezoneString($datetime, $format=DEFAULT_TIMESTAMP_FORMAT) {
public static function UTCStringToStationTimezoneString($datetime, $format = DEFAULT_TIMESTAMP_FORMAT)
{
$stationTimezone = new DateTimeZone(Application_Model_Preference::GetDefaultTimezone());
$utcTimezone = new DateTimeZone("UTC");
$utcTimezone = new DateTimeZone('UTC');
$d = new DateTime($datetime, $utcTimezone);
$d->setTimezone($stationTimezone);
return $d->format($format);
}
/*
* @param $datetime string Y-m-d H:i:s in UTC timezone
*
* @return string Y-m-d H:i:s in user's timezone
*/
public static function UTCStringToUserTimezoneString($datetime, $format=DEFAULT_TIMESTAMP_FORMAT) {
public static function UTCStringToUserTimezoneString($datetime, $format = DEFAULT_TIMESTAMP_FORMAT)
{
$userTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
$utcTimezone = new DateTimeZone("UTC");
$utcTimezone = new DateTimeZone('UTC');
$d = new DateTime($datetime, $utcTimezone);
$d->setTimezone($userTimezone);
return $d->format($format);
}
/*
* @param $datetime string Y-m-d H:i:s in user timezone
*
* @return string Y-m-d H:i:s in UTC timezone
*/
public static function UserTimezoneStringToUTCString($datetime, $format=DEFAULT_TIMESTAMP_FORMAT) {
public static function UserTimezoneStringToUTCString($datetime, $format = DEFAULT_TIMESTAMP_FORMAT)
{
$userTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
$utcTimezone = new DateTimeZone("UTC");
$utcTimezone = new DateTimeZone('UTC');
$d = new DateTime($datetime, $userTimezone);
$d->setTimezone($utcTimezone);
return $d->format($format);
}
/**
* Convert the columns given in the array $columnsToConvert in the
* database result $rows to local timezone.
*
* @param array $rows arrays of arrays containing database query result
* @param array $columnsToConvert array of column names to convert
* @param string (station|user) convert to either station or user timezone.
* @param string (station|user) convert to either station or user timezone
* @param mixed $domain
*/
public static function convertTimestamps(&$rows, $columnsToConvert, $domain="station")
public static function convertTimestamps(&$rows, $columnsToConvert, $domain = 'station')
{
if (!is_array($rows)) {
return;
}
$converter = "UTCStringTo".ucfirst($domain)."TimezoneString";
$converter = 'UTCStringTo' . ucfirst($domain) . 'TimezoneString';
foreach ($rows as &$row) {
foreach ($columnsToConvert as $column) {
$row[$column] = self::$converter($row[$column]);
}
}
}
/**
* Convert the columns given in the array $columnsToConvert in the
* database result $rows to local timezone.
*
* @param array $rows arrays of arrays containing database query result
* @param array $columnsToConvert array of column names to convert
* @param string $timezone convert to the given timezone.
* @param array $rows arrays of arrays containing database query result
* @param array $columnsToConvert array of column names to convert
* @param string $timezone convert to the given timezone
* @param string $format time format to convert to
*/
public static function convertTimestampsToTimezone(&$rows, $columnsToConvert, $timezone, $format=DEFAULT_TIMESTAMP_FORMAT)
public static function convertTimestampsToTimezone(&$rows, $columnsToConvert, $timezone, $format = DEFAULT_TIMESTAMP_FORMAT)
{
$timezone = strtolower($timezone);
// Check that the timezone is valid and rows is an array
if (!is_array($rows)) {
return;
}
foreach ($rows as &$row) {
if (is_array($row)) {
foreach ($columnsToConvert as $column) {
if (array_key_exists($column, $row)) {
$newTimezone = new DateTimeZone($timezone);
$utcTimezone = new DateTimeZone("UTC");
$utcTimezone = new DateTimeZone('UTC');
$d = new DateTime($row[$column], $utcTimezone);
$d->setTimezone($newTimezone);
$row[$column] = $d->format($format);
@ -345,85 +353,92 @@ class Application_Common_DateHelper
}
}
}
/**
* Return the end date time in the given timezone
* Return the end date time in the given timezone.
*
* @param mixed $timezoneString
* @param mixed $days
*
* @return DateTime
*/
public static function getEndDateTime($timezoneString, $days)
{
$timezone = new DateTimeZone($timezoneString);
$now = new DateTime("now", $timezone);
$now->add(new DateInterval("P".$days."D"));
$now = new DateTime('now', $timezone);
$now->add(new DateInterval('P' . $days . 'D'));
$now->setTime(0, 0, 0);
return $now;
}
/**
* Return a formatted string representing the
* given datetime in the given timezone
* given datetime in the given timezone.
*
* @param unknown $datetime the time to convert
* @param unknown $timezone the timezone to convert to
* @param string $format the formatted string
* @param unknown $datetime the time to convert
* @param unknown $timezone the timezone to convert to
* @param string $format the formatted string
*/
public static function UTCStringToTimezoneString($datetime, $timezone, $format=DEFAULT_TIMESTAMP_FORMAT) {
$d = new DateTime($datetime, new DateTimeZone("UTC"));
public static function UTCStringToTimezoneString($datetime, $timezone, $format = DEFAULT_TIMESTAMP_FORMAT)
{
$d = new DateTime($datetime, new DateTimeZone('UTC'));
$timezone = strtolower($timezone);
$newTimezone = new DateTimeZone($timezone);
$d->setTimezone($newTimezone);
return $d->format($format);
}
/**
* Return the timezone offset in seconds for the given timezone
* Return the timezone offset in seconds for the given timezone.
*
* @param unknown $userDefinedTimezone the timezone used to determine the offset
*/
public static function getTimezoneOffset($userDefinedTimezone) {
public static function getTimezoneOffset($userDefinedTimezone)
{
$now = new DateTimeZone($userDefinedTimezone);
$d = new DateTime("now", $now);
return $d->format("Z");
$d = new DateTime('now', $now);
return $d->format('Z');
}
/**
* 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)
* playlist interval value (HH:mm:ss.dddddd)
*
* @return int
* seconds
* seconds
*/
public static function playlistTimeToSeconds($plt)
{
$arr = preg_split('/:/', $plt);
$arr = preg_split('/:/', $plt);
if (isset($arr[2])) {
return (intval($arr[0])*60 + intval($arr[1]))*60 + floatval($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 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
* @param float $seconds
* @param mixed $p_seconds
*
* @return string
* interval in playlist time format (HH:mm:ss.d)
* interval in playlist time format (HH:mm:ss.d)
*/
public static function secondsToPlaylistTime($p_seconds)
{
@ -438,27 +453,29 @@ class Application_Common_DateHelper
$seconds -= $hours * 3600;
$minutes = floor($seconds / 60);
$seconds -= $minutes * 60;
$res = sprintf("%02d:%02d:%02d.%s", $hours, $minutes, $seconds, $milliStr);
return $res;
return sprintf('%02d:%02d:%02d.%s', $hours, $minutes, $seconds, $milliStr);
}
/**
* Returns date fields from give start and end teimstamp strings
* if no start or end parameter is passed start will be set to 1
* in the past and end to now
* if no start or end parameter is passed start will be set to 1
* in the past and end to now.
*
* @param string startTimestamp Y-m-d H:i:s
* @param string endTImestamp Y-m-d H:i:s
* @param string timezone (ex UTC) of the start and end parameters
* @param mixed $startTimestamp
* @param mixed $endTimestamp
* @param mixed $timezone
*
* @return array (start DateTime, end DateTime) in UTC timezone
*/
public static function getStartEnd($startTimestamp, $endTimestamp, $timezone)
{
$prefTimezone = Application_Model_Preference::GetTimezone();
$utcTimezone = new DateTimeZone("UTC");
$utcNow = new DateTime("now", $utcTimezone);
$utcTimezone = new DateTimeZone('UTC');
$utcNow = new DateTime('now', $utcTimezone);
if (empty($timezone)) {
$userTimezone = new DateTimeZone($prefTimezone);
@ -469,33 +486,29 @@ class Application_Common_DateHelper
// default to 1 day
if (empty($startTimestamp) || empty($endTimestamp)) {
$startsDT = clone $utcNow;
$startsDT->sub(new DateInterval("P1D"));
$startsDT->sub(new DateInterval('P1D'));
$endsDT = clone $utcNow;
} else {
try {
$startsDT = new DateTime($startTimestamp, $userTimezone);
$startsDT->setTimezone($utcTimezone);
$endsDT = new DateTime($endTimestamp, $userTimezone);
$endsDT->setTimezone($utcTimezone);
if ($startsDT > $endsDT) {
throw new Exception("start greater than end");
throw new Exception('start greater than end');
}
}
catch (Exception $e) {
} catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
$startsDT = clone $utcNow;
$startsDT->sub(new DateInterval("P1D"));
$startsDT->sub(new DateInterval('P1D'));
$endsDT = clone $utcNow;
}
}
return array($startsDT, $endsDT);
return [$startsDT, $endsDT];
}
}

View File

@ -1,78 +1,81 @@
<?php
class FileDataHelper {
public static function getAudioMimeTypeArray() {
return array(
"audio/ogg" => "ogg",
"application/ogg" => "ogg",
"audio/vorbis" => "ogg",
"audio/mp3" => "mp3",
"audio/mpeg" => "mp3",
"audio/mpeg3" => "mp3",
"audio/x-aac" => "aac",
"audio/aac" => "aac",
"audio/aacp" => "aac",
"audio/mp4" => "m4a",
"video/mp4" => "mp4",
"audio/x-flac" => "flac",
"audio/flac" => "flac",
"audio/wav" => "wav",
"audio/x-wav" => "wav",
"audio/mp2" => "mp2",
"audio/mp1" => "mp1",
"audio/x-ms-wma" => "wma",
"audio/basic" => "au",
);
class FileDataHelper
{
public static function getAudioMimeTypeArray()
{
return [
'audio/ogg' => 'ogg',
'application/ogg' => 'ogg',
'audio/vorbis' => 'ogg',
'audio/mp3' => 'mp3',
'audio/mpeg' => 'mp3',
'audio/mpeg3' => 'mp3',
'audio/x-aac' => 'aac',
'audio/aac' => 'aac',
'audio/aacp' => 'aac',
'audio/mp4' => 'm4a',
'video/mp4' => 'mp4',
'audio/x-flac' => 'flac',
'audio/flac' => 'flac',
'audio/wav' => 'wav',
'audio/x-wav' => 'wav',
'audio/mp2' => 'mp2',
'audio/mp1' => 'mp1',
'audio/x-ms-wma' => 'wma',
'audio/basic' => 'au',
];
}
/**
* We want to throw out invalid data and process the upload successfully
* at all costs, so check the data and sanitize it if necessary
* at all costs, so check the data and sanitize it if necessary.
*
* @param array $data array containing new file metadata
*/
public static function sanitizeData(&$data)
{
if (array_key_exists("track_number", $data)) {
if (array_key_exists('track_number', $data)) {
// If the track number isn't numeric, this will return 0
$data["track_number"] = intval($data["track_number"]);
$data['track_number'] = intval($data['track_number']);
}
if (array_key_exists("year", $data)) {
if (array_key_exists('year', $data)) {
// If the track number isn't numeric, this will return 0
$data["year"] = intval($data["year"]);
$data['year'] = intval($data['year']);
}
if (array_key_exists("bpm", $data)) {
if (array_key_exists('bpm', $data)) {
//Some BPM tags are silly and include the word "BPM". Let's strip that...
$data["bpm"] = str_ireplace("BPM", "", $data["bpm"]);
$data['bpm'] = str_ireplace('BPM', '', $data['bpm']);
// This will convert floats to ints too.
$data["bpm"] = intval($data["bpm"]);
$data['bpm'] = intval($data['bpm']);
}
}
/**
* Return a suitable extension for the given file
* Return a suitable extension for the given file.
*
* @param string $mime
*
* @return string file extension with(!) a dot (for convenience)
*
* @throws Exception
*
* @return string file extension with(!) a dot (for convenience)
*/
public static function getFileExtensionFromMime($mime)
{
$mime = trim(strtolower($mime));
try {
return ('.' . static::getAudioMimeTypeArray()[$mime]);
return '.' . static::getAudioMimeTypeArray()[$mime];
} catch (Exception $e) {
throw new Exception("Unknown file type: $mime");
throw new Exception("Unknown file type: {$mime}");
}
}
/**
* Gets data URI from artwork file
* Gets data URI from artwork file.
*
* @param string $file
* @param int $size
* @param int $size
* @param string $filepath
*
* @return string Data URI for artwork
@ -80,29 +83,30 @@ class FileDataHelper {
public static function getArtworkData($file, $size, $filepath = false)
{
$baseUrl = Application_Common_HTTPHelper::getStationUrl();
$default = $baseUrl . "css/images/no-cover.jpg";
$default = $baseUrl . 'css/images/no-cover.jpg';
if ($filepath != false) {
$path = $filepath . $file . "-" . $size;
$path = $filepath . $file . '-' . $size;
if (!file_exists($path)) {
$get_file_content = $default;
} else {
$get_file_content = file_get_contents($path);
$get_file_content = file_get_contents($path);
}
} else {
$storDir = Application_Model_MusicDir::getStorDir();
$path = $storDir->getDirectory() . $file . "-" . $size;
$path = $storDir->getDirectory() . $file . '-' . $size;
if (!file_exists($path)) {
$get_file_content = $default;
} else {
$get_file_content = file_get_contents($path);
$get_file_content = file_get_contents($path);
}
}
return $get_file_content;
}
/**
* Add artwork file
* Add artwork file.
*
* @param string $analyzeFile
* @param string $filename
@ -118,53 +122,53 @@ class FileDataHelper {
$getFileInfo = $getID3->analyze($analyzeFile);
} else {
$getFileInfo = [];
Logging::error("Failed to load getid3 library. Please upgrade Libretime.");
Logging::error('Failed to load getid3 library. Please upgrade Libretime.');
}
if(isset($getFileInfo['comments']['picture'][0])) {
if (isset($getFileInfo['comments']['picture'][0])) {
$get_img = '';
$timestamp = time();
$mime = $getFileInfo['comments']['picture'][0]['image_mime'];
$Image = 'data:' . $mime . ';charset=utf-8;base64,' . base64_encode($getFileInfo['comments']['picture'][0]['data']);
$base64 = @$Image;
$get_img = "";
$timestamp = time();
$mime = $getFileInfo['comments']['picture'][0]['image_mime'];
$Image = 'data:'.$mime.';charset=utf-8;base64,'.base64_encode($getFileInfo['comments']['picture'][0]['data']);
$base64 = @$Image;
if (!file_exists($importDir . '/' . 'artwork/')) {
if (!mkdir($importDir . '/' . 'artwork/', 0777, true)) {
Logging::error('Failed to create artwork directory.');
if (!file_exists($importDir . "/" . "artwork/")) {
if (!mkdir($importDir . "/" . "artwork/", 0777, true)) {
Logging::error("Failed to create artwork directory.");
throw new Exception("Failed to create artwork directory.");
}
}
throw new Exception('Failed to create artwork directory.');
}
}
$path_parts = pathinfo($filename);
$file = $importDir . "artwork/" . $path_parts['filename'];
$path_parts = pathinfo($filename);
$file = $importDir . 'artwork/' . $path_parts['filename'];
//Save Data URI
if (file_put_contents($file, $base64)) {
$get_img = $DbPath . "artwork/". $path_parts['filename'];
} else {
Logging::error("Could not save Data URI");
}
if ($mime == "image/png") {
$ext = 'png';
} elseif ($mime == "image/gif") {
$ext = 'gif';
} elseif ($mime == "image/bmp") {
$ext = 'bmp';
} else {
$ext = 'jpg';
}
self::resizeGroup($file, $ext);
//Save Data URI
if (file_put_contents($file, $base64)) {
$get_img = $DbPath . 'artwork/' . $path_parts['filename'];
} else {
Logging::error('Could not save Data URI');
}
if ($mime == 'image/png') {
$ext = 'png';
} elseif ($mime == 'image/gif') {
$ext = 'gif';
} elseif ($mime == 'image/bmp') {
$ext = 'bmp';
} else {
$ext = 'jpg';
}
self::resizeGroup($file, $ext);
} else {
$get_img = '';
$get_img = '';
}
return $get_img;
}
/**
* Reset artwork
* Reset artwork.
*
* @param string $trackid
*
@ -178,7 +182,7 @@ class FileDataHelper {
$storDir = Application_Model_MusicDir::getStorDir();
$fp = $storDir->getDirectory();
$dbAudioPath = $md["MDATA_KEY_FILEPATH"];
$dbAudioPath = $md['MDATA_KEY_FILEPATH'];
$fullpath = $fp . $dbAudioPath;
if (class_exists('getID3')) {
@ -186,49 +190,48 @@ class FileDataHelper {
$getFileInfo = $getID3->analyze($fullpath);
} else {
$getFileInfo = [];
Logging::error("Failed to load getid3 library. Please upgrade Libretime.");
Logging::error('Failed to load getid3 library. Please upgrade Libretime.');
}
if(isset($getFileInfo['comments']['picture'][0])) {
if (isset($getFileInfo['comments']['picture'][0])) {
$get_img = '';
$mime = $getFileInfo['comments']['picture'][0]['image_mime'];
$Image = 'data:' . $getFileInfo['comments']['picture'][0]['image_mime'] . ';charset=utf-8;base64,' . base64_encode($getFileInfo['comments']['picture'][0]['data']);
$base64 = @$Image;
$get_img = "";
$mime = $getFileInfo['comments']['picture'][0]['image_mime'];
$Image = 'data:'.$getFileInfo['comments']['picture'][0]['image_mime'].';charset=utf-8;base64,'.base64_encode($getFileInfo['comments']['picture'][0]['data']);
$base64 = @$Image;
$audioPath = dirname($fullpath);
$dbPath = dirname($dbAudioPath);
$path_parts = pathinfo($fullpath);
$file = $path_parts['filename'];
$audioPath = dirname($fullpath);
$dbPath = dirname($dbAudioPath);
$path_parts = pathinfo($fullpath);
$file = $path_parts['filename'];
//Save Data URI
if (file_put_contents($audioPath . '/' . $file, $base64)) {
$get_img = $dbPath . '/' . $file;
} else {
Logging::error('Could not save Data URI');
}
//Save Data URI
if (file_put_contents($audioPath . "/" . $file, $base64)) {
$get_img = $dbPath . "/" . $file;
} else {
Logging::error("Could not save Data URI");
}
$rfile = $audioPath . "/" . $file;
if ($mime == "image/png") {
$ext = 'png';
} elseif ($mime == "image/gif") {
$ext = 'gif';
} elseif ($mime == "image/bmp") {
$ext = 'bmp';
} else {
$ext = 'jpg';
}
self::resizeGroup($rfile, $ext);
$rfile = $audioPath . '/' . $file;
if ($mime == 'image/png') {
$ext = 'png';
} elseif ($mime == 'image/gif') {
$ext = 'gif';
} elseif ($mime == 'image/bmp') {
$ext = 'bmp';
} else {
$ext = 'jpg';
}
self::resizeGroup($rfile, $ext);
} else {
$get_img = "";
$get_img = '';
}
return $get_img;
}
/**
* Upload artwork
* Upload artwork.
*
* @param string $trackid
* @param string $data
@ -243,16 +246,13 @@ class FileDataHelper {
$storDir = Application_Model_MusicDir::getStorDir();
$fp = $storDir->getDirectory();
$dbAudioPath = $md["MDATA_KEY_FILEPATH"];
$dbAudioPath = $md['MDATA_KEY_FILEPATH'];
$fullpath = $fp . $dbAudioPath;
if ($data == "0") {
$get_img = "";
if ($data == '0') {
$get_img = '';
self::removeArtwork($trackid, $data);
} else {
$base64 = @$data;
$mime = explode(';', $base64)[0];
@ -262,32 +262,33 @@ class FileDataHelper {
$file = $path_parts['filename'];
//Save Data URI
if (file_put_contents($audioPath . "/" . $file, $base64)) {
$get_img = $dbPath . "/" . $file;
if (file_put_contents($audioPath . '/' . $file, $base64)) {
$get_img = $dbPath . '/' . $file;
} else {
Logging::error("Could not save Data URI");
Logging::error('Could not save Data URI');
}
$rfile = $audioPath . "/" . $file;
$rfile = $audioPath . '/' . $file;
if ($mime == "data:image/png") {
if ($mime == 'data:image/png') {
$ext = 'png';
} elseif ($mime == "data:image/gif") {
} elseif ($mime == 'data:image/gif') {
$ext = 'gif';
} elseif ($mime == "data:image/bmp") {
$ext = 'bmp';
} elseif ($mime == 'data:image/bmp') {
$ext = 'bmp';
} else {
$ext = 'jpg';
$ext = 'jpg';
}
self::resizeGroup($rfile, $ext);
}
return $get_img;
}
/**
* Deletes just the artwork.
*
* Deletes just the artwork
* @param mixed $trackid
*/
public static function removeArtwork($trackid)
{
@ -297,144 +298,143 @@ class FileDataHelper {
$storDir = Application_Model_MusicDir::getStorDir();
$fp = $storDir->getDirectory();
$dbAudioPath = $md["MDATA_KEY_ARTWORK"];
$dbAudioPath = $md['MDATA_KEY_ARTWORK'];
$fullpath = $fp . $dbAudioPath;
if (file_exists($fullpath)) {
foreach (glob("$fullpath*", GLOB_NOSORT) as $filename) {
foreach (glob("{$fullpath}*", GLOB_NOSORT) as $filename) {
unlink($filename);
}
} else {
throw new Exception("Could not locate file ".$filepath);
throw new Exception('Could not locate file ' . $filepath);
}
return "";
return '';
}
/**
* Resize artwork group
* Resize artwork group.
*
* @param string $file
* @param string $ext
*/
public static function resizeGroup($file, $ext)
{
if (file_exists($file)) {
self::resizeImage($file, $file . '-32.jpg', $ext, 32, 100);
self::resizeImage($file, $file . '-64.jpg', $ext, 64, 100);
self::resizeImage($file, $file . '-128.jpg', $ext, 128, 100);
self::resizeImage($file, $file . '-256.jpg', $ext, 256, 100);
self::resizeImage($file, $file . '-512.jpg', $ext, 512, 100);
self::imgToDataURI($file . '-32.jpg', $file . '-32');
self::imgToDataURI($file . '-64.jpg', $file . '-64');
self::imgToDataURI($file . '-128.jpg', $file . '-128');
self::imgToDataURI($file . '-256.jpg', $file . '-256');
} else {
Logging::error("The file $file does not exist");
}
if (file_exists($file)) {
self::resizeImage($file, $file . '-32.jpg', $ext, 32, 100);
self::resizeImage($file, $file . '-64.jpg', $ext, 64, 100);
self::resizeImage($file, $file . '-128.jpg', $ext, 128, 100);
self::resizeImage($file, $file . '-256.jpg', $ext, 256, 100);
self::resizeImage($file, $file . '-512.jpg', $ext, 512, 100);
self::imgToDataURI($file . '-32.jpg', $file . '-32');
self::imgToDataURI($file . '-64.jpg', $file . '-64');
self::imgToDataURI($file . '-128.jpg', $file . '-128');
self::imgToDataURI($file . '-256.jpg', $file . '-256');
} else {
Logging::error("The file {$file} does not exist");
}
}
/**
* Render image
* Used in API to render JPEG
* Used in API to render JPEG.
*
* @param string $file
*/
public static function renderImage($file)
{
$im = @imagecreatefromjpeg($file);
header('Content-Type: image/jpeg');
$img = $im;
imagejpeg($img);
imagedestroy($img);
$im = @imagecreatefromjpeg($file);
header('Content-Type: image/jpeg');
$img = $im;
imagejpeg($img);
imagedestroy($img);
}
/**
* Render Data URI
* Used in API to render Data URI
* Used in API to render Data URI.
*
* @param string $dataFile
*/
public static function renderDataURI($dataFile)
{
if($filecontent = file_get_contents($dataFile) !== false){
$image = @file_get_contents($dataFile);
$image = base64_encode($image);
if (!$image || $image === '') {
return;
}
$blob = base64_decode($image);
$f = finfo_open();
$mime_type = finfo_buffer($f, $blob, FILEINFO_MIME_TYPE);
finfo_close($f);
header("Content-Type: " . $mime_type);
echo $blob;
} else {
return;
}
if ($filecontent = file_get_contents($dataFile) !== false) {
$image = @file_get_contents($dataFile);
$image = base64_encode($image);
if (!$image || $image === '') {
return;
}
$blob = base64_decode($image);
$f = finfo_open();
$mime_type = finfo_buffer($f, $blob, FILEINFO_MIME_TYPE);
finfo_close($f);
header('Content-Type: ' . $mime_type);
echo $blob;
} else {
return;
}
}
/**
* Resize Image
* Resize Image.
*
* @param string $orig_filename
* @param string $converted_filename
* @param string $ext
* @param string $size Default: 500
* @param string $quality Default: 75
*
* @param string $size Default: 500
* @param string $quality Default: 75
*/
public static function resizeImage($orig_filename, $converted_filename, $ext, $size=500, $quality=75)
public static function resizeImage($orig_filename, $converted_filename, $ext, $size = 500, $quality = 75)
{
$get_cont = file_get_contents($orig_filename);
if ($ext == "png") {
$im = @imagecreatefrompng($get_cont);
} elseif ($ext == "gif") {
$im = @imagecreatefromgif($get_cont);
} else {
$im = @imagecreatefromjpeg($get_cont);
}
$get_cont = file_get_contents($orig_filename);
if ($ext == 'png') {
$im = @imagecreatefrompng($get_cont);
} elseif ($ext == 'gif') {
$im = @imagecreatefromgif($get_cont);
} else {
$im = @imagecreatefromjpeg($get_cont);
}
// if one of those bombs, create an error image instead
if (!$im) {
$im = imagecreatetruecolor(150, 30);
$bgc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
imagestring($im, 1, 5, 5, 'Error loading ' . $converted_filename, $tc);
}
// scale if appropriate
if ($size){
$im = imagescale($im , $size);
}
// if one of those bombs, create an error image instead
if (!$im) {
$im = imagecreatetruecolor(150, 30);
$bgc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
imagestring($im, 1, 5, 5, 'Error loading ' . $converted_filename, $tc);
}
$img = $im;
imagejpeg($img, $converted_filename, $quality);
imagedestroy($img);
// scale if appropriate
if ($size) {
$im = imagescale($im, $size);
}
$img = $im;
imagejpeg($img, $converted_filename, $quality);
imagedestroy($img);
}
/**
* Convert image to Data URI
* Convert image to Data URI.
*
* @param string $orig_filename
* @param string $conv_filename
*/
public static function imgToDataURI($orig_filename, $conv_filename)
{
$file = file_get_contents($orig_filename);
$Image = 'data:image/jpeg;charset=utf-8;base64,'.base64_encode($file);
$base64 = @$Image;
$file = file_get_contents($orig_filename);
$Image = 'data:image/jpeg;charset=utf-8;base64,' . base64_encode($file);
$base64 = @$Image;
//Save Data URI
if (file_put_contents($conv_filename, $base64)) {
} else {
Logging::error("Could not save Data URI");
}
//Save Data URI
if (file_put_contents($conv_filename, $base64)) {
} else {
Logging::error('Could not save Data URI');
}
}
/**
* Track Type
* Track Type.
*
* @return string Track type key value
*/
@ -443,10 +443,10 @@ class FileDataHelper {
if (isset($_COOKIE['tt_upload'])) {
$tt = $_COOKIE['tt_upload'];
} else {
// Use default track type
$tt = Application_Model_Preference::GetTrackTypeDefault();
// Use default track type
$tt = Application_Model_Preference::GetTrackTypeDefault();
}
return $tt;
}
}

View File

@ -12,11 +12,10 @@ class Application_Common_FileIO
*
* @param string $filePath - the full filepath or URL pointing to the location of the file
* @param string $mimeType - the file's mime type. Defaults to 'audio/mp3'
* @param integer $size - the file size, in bytes
* @return void
* @param int $size - the file size, in bytes
*
* @link https://groups.google.com/d/msg/jplayer/nSM2UmnSKKA/Hu76jDZS4xcJ
* @link http://php.net/manual/en/function.readfile.php#86244
* @see https://groups.google.com/d/msg/jplayer/nSM2UmnSKKA/Hu76jDZS4xcJ
* @see http://php.net/manual/en/function.readfile.php#86244
*/
public static function smartReadFile($filePath, $size, $mimeType)
{
@ -36,12 +35,11 @@ class Application_Common_FileIO
}
if ($size <= 0) {
throw new Exception("Invalid file size returned for file at $filePath");
throw new Exception("Invalid file size returned for file at {$filePath}");
}
$begin = 0;
$end = $size - 1;
$end = $size - 1;
ob_start(); //Must start a buffer here for these header() functions
@ -59,14 +57,14 @@ class Application_Common_FileIO
} else {
header('HTTP/1.1 200 OK');
}
header("Content-Type: $mimeType");
header("Content-Transfer-Encoding: binary");
header("Content-Type: {$mimeType}");
header('Content-Transfer-Encoding: binary');
header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Accept-Ranges: bytes');
header('Content-Length:' . (($end - $begin) + 1));
if (isset($_SERVER['HTTP_RANGE'])) {
header("Content-Range: bytes $begin-$end/$size");
header("Content-Range: bytes {$begin}-{$end}/{$size}");
}
//We can have multiple levels of output buffering. Need to
@ -76,15 +74,13 @@ class Application_Common_FileIO
ob_end_flush();
}
//These two lines were removed from Airtime 2.5.x at some point after Libretime forked from Airtime.
//These lines allow seek to work for files.
//Issue #349
$cur = $begin;
fseek($fm,$begin,0);
fseek($fm, $begin, 0);
while(!feof($fm) && (connection_status() == 0) && ($cur <= $end)) {
while (!feof($fm) && (connection_status() == 0) && ($cur <= $end)) {
echo fread($fm, 1024 * 8);
}
fclose($fm);

View File

@ -3,25 +3,27 @@
class Application_Common_HTTPHelper
{
/**
* Returns start and end DateTime vars from given
* HTTP Request object
* Returns start and end DateTime vars from given
* HTTP Request object.
*
* @param Request
* @param mixed $request
*
* @return array(start DateTime, end DateTime)
*/
public static function getStartEndFromRequest($request)
{
return Application_Common_DateHelper::getStartEnd(
$request->getParam("start", null),
$request->getParam("end", null),
$request->getParam("timezone", null)
$request->getParam('start', null),
$request->getParam('end', null),
$request->getParam('timezone', null)
);
}
/**
* Construct the base station URL
* Construct the base station URL.
*
* @param boolean $secured whether or not to use HTTPS
* @param bool $secured whether or not to use HTTPS
*
* @return string the station URL
*/
@ -34,84 +36,89 @@ class Application_Common_HTTPHelper
$forceSSL = $CC_CONFIG['forceSSL'];
$configProtocol = $CC_CONFIG['protocol'];
if (empty($baseDir)) {
$baseDir = "/";
$baseDir = '/';
}
if ($baseDir[0] != "/") {
$baseDir = "/" . $baseDir;
if ($baseDir[0] != '/') {
$baseDir = '/' . $baseDir;
}
if (substr($baseDir, -1) != "/") {
$baseDir = $baseDir . "/";
if (substr($baseDir, -1) != '/') {
$baseDir = $baseDir . '/';
}
# Set in reverse order of preference. ForceSSL configuration takes absolute preference, then
# the protocol set in config. If neither are set, the port is used to determine the scheme
$scheme = "http";
if ($secured && $basePort == "443") {
$scheme = "https";
// Set in reverse order of preference. ForceSSL configuration takes absolute preference, then
// the protocol set in config. If neither are set, the port is used to determine the scheme
$scheme = 'http';
if ($secured && $basePort == '443') {
$scheme = 'https';
}
if (!empty($configProtocol)) {
$scheme = $configProtocol;
$scheme = $configProtocol;
}
if ($forceSSL) {
$scheme = "https";
$scheme = 'https';
}
$portStr = "";
if (($scheme == "http" && $basePort !== "80")
|| ($scheme == "https" && $basePort !== "443")) {
$portStr = ":${basePort}";
$portStr = '';
if (($scheme == 'http' && $basePort !== '80')
|| ($scheme == 'https' && $basePort !== '443')) {
$portStr = ":{$basePort}";
}
$stationUrl = "$scheme://${baseUrl}${portStr}${baseDir}";
return $stationUrl;
return "{$scheme}://{$baseUrl}{$portStr}{$baseDir}";
}
/**
* Execute a cURL POST
* Execute a cURL POST.
*
* @param string $url the URL to POST to
* @param string[] $userPwd array of user args of the form ['user', 'pwd']
* @param array $formData array of form data kwargs
* @param string $url the URL to POST to
* @param string[] $userPwd array of user args of the form ['user', 'pwd']
* @param array $formData array of form data kwargs
*
* @return mixed the cURL result
*/
public static function doPost($url, $userPwd, $formData) {
$params = "";
foreach($formData as $key=>$value) {
$params .= $key.'='.$value.'&';
public static function doPost($url, $userPwd, $formData)
{
$params = '';
foreach ($formData as $key => $value) {
$params .= $key . '=' . $value . '&';
}
rtrim($params, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_USERPWD, implode(':', $userPwd));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
}
class ZendActionHttpException extends Exception {
class ZendActionHttpException extends Exception
{
/**
* @param Zend_Controller_Action $action
* @param int $statusCode
* @param string $message
* @param int $code
* @param Exception $previous
* @param int $statusCode
* @param string $message
* @param int $code
* @param Exception $previous
*
* @throws Zend_Controller_Response_Exception
*/
public function __construct(Zend_Controller_Action $action, $statusCode, $message,
$code = 0, Exception $previous = null) {
Logging::error("Error in action " . $action->getRequest()->getActionName()
. " with status code $statusCode: $message");
public function __construct(
Zend_Controller_Action $action,
$statusCode,
$message,
$code = 0,
Exception $previous = null
) {
Logging::error('Error in action ' . $action->getRequest()->getActionName()
. " with status code {$statusCode}: {$message}");
$action->getResponse()
->setHttpResponseCode($statusCode)
->appendBody($message);
->appendBody($message)
;
parent::__construct($message, $code, $previous);
}
}

View File

@ -2,15 +2,16 @@
// Global functions for translating domain-specific strings
class Application_Common_LocaleHelper {
class Application_Common_LocaleHelper
{
/**
* Return an array of all ISO 639-1 language codes and their corresponding translated language names
* Return an array of all ISO 639-1 language codes and their corresponding translated language names.
*
* @return array the array of language codes to names
*/
public static function getISO6391LanguageCodes() {
/**
public static function getISO6391LanguageCodes()
{
/*
* From: http://www.binarytides.com/php-array-of-iso-639-1-language-codes-and-names/
*
* ISO 639-1 Language Codes
@ -18,7 +19,7 @@ class Application_Common_LocaleHelper {
* 1. http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
* 2. http://blog.xoundboy.com/?p=235
*/
return array(
return [
'en' => _('English'),
'aa' => _('Afar'),
'ab' => _('Abkhazian'),
@ -154,7 +155,6 @@ class Application_Common_LocaleHelper {
'yo' => _('Yoruba'),
'zh' => _('Chinese'),
'zu' => _('Zulu'),
);
];
}
}

View File

@ -1,59 +1,68 @@
<?php
class Application_Common_OsPath{
class Application_Common_OsPath
{
// this function is from http://stackoverflow.com/questions/2670299/is-there-a-php-equivalent-function-to-the-python-os-path-normpath
public static function normpath($path)
{
if (empty($path))
if (empty($path)) {
return '.';
if (strpos($path, '/') === 0)
}
if (strpos($path, '/') === 0) {
$initial_slashes = true;
else
} else {
$initial_slashes = false;
}
if (
($initial_slashes) &&
(strpos($path, '//') === 0) &&
(strpos($path, '///') === false)
)
($initial_slashes)
&& (strpos($path, '//') === 0)
&& (strpos($path, '///') === false)
) {
$initial_slashes = 2;
}
$initial_slashes = (int) $initial_slashes;
$comps = explode('/', $path);
$new_comps = array();
foreach ($comps as $comp)
{
if (in_array($comp, array('', '.')))
$new_comps = [];
foreach ($comps as $comp) {
if (in_array($comp, ['', '.'])) {
continue;
}
if (
($comp != '..') ||
(!$initial_slashes && !$new_comps) ||
($new_comps && (end($new_comps) == '..'))
)
($comp != '..')
|| (!$initial_slashes && !$new_comps)
|| ($new_comps && (end($new_comps) == '..'))
) {
array_push($new_comps, $comp);
elseif ($new_comps)
} elseif ($new_comps) {
array_pop($new_comps);
}
}
$comps = $new_comps;
$path = implode('/', $comps);
if ($initial_slashes)
if ($initial_slashes) {
$path = str_repeat('/', $initial_slashes) . $path;
if ($path)
}
if ($path) {
return $path;
else
return '.';
}
/* Similar to the os.path.join python method
* http://stackoverflow.com/a/1782990/276949 */
public static function join() {
$args = func_get_args();
$paths = array();
foreach($args as $arg) {
$paths = array_merge($paths, (array)$arg);
}
foreach($paths as &$path) {
return '.';
}
/* Similar to the os.path.join python method
* http://stackoverflow.com/a/1782990/276949 */
public static function join()
{
$args = func_get_args();
$paths = [];
foreach ($args as $arg) {
$paths = array_merge($paths, (array) $arg);
}
foreach ($paths as &$path) {
$path = trim($path, DIRECTORY_SEPARATOR);
}
@ -63,34 +72,33 @@ class Application_Common_OsPath{
return join(DIRECTORY_SEPARATOR, $paths);
}
public static function getBaseDir() {
public static function getBaseDir()
{
$CC_CONFIG = Config::getConfig();
$baseUrl = $CC_CONFIG['baseDir'];
if ($baseUrl[0] != "/") {
$baseUrl = "/".$baseUrl;
if ($baseUrl[0] != '/') {
$baseUrl = '/' . $baseUrl;
}
if ($baseUrl[strlen($baseUrl) -1] != "/") {
$baseUrl = $baseUrl."/";
if ($baseUrl[strlen($baseUrl) - 1] != '/') {
$baseUrl = $baseUrl . '/';
}
return $baseUrl;
}
public static function formatDirectoryWithDirectorySeparators($dir)
{
if ($dir[0] != "/") {
$dir = "/".$dir;
if ($dir[0] != '/') {
$dir = '/' . $dir;
}
if ($dir[strlen($dir) -1] != "/") {
$dir = $dir."/";
if ($dir[strlen($dir) - 1] != '/') {
$dir = $dir . '/';
}
return $dir;
}
}

View File

@ -1,7 +1,7 @@
<?php
class PodcastManager {
class PodcastManager
{
/**
* @var int how often, in seconds, to check for and ingest new podcast episodes
*/
@ -9,23 +9,26 @@ class PodcastManager {
/**
* Check whether $_PODCAST_POLL_INTERVAL_SECONDS have passed since the last call to
* downloadNewestEpisodes
* downloadNewestEpisodes.
*
* @return bool true if $_PODCAST_POLL_INTERVAL_SECONDS has passed since the last check
*/
public static function hasPodcastPollIntervalPassed() {
public static function hasPodcastPollIntervalPassed()
{
$lastPolled = Application_Model_Preference::getPodcastPollLock();
return empty($lastPolled) || (microtime(true) > $lastPolled + self::$_PODCAST_POLL_INTERVAL_SECONDS);
}
/**
* Find all podcasts flagged for automatic ingest whose most recent episode has
* yet to be downloaded and download it with Celery
* yet to be downloaded and download it with Celery.
*
* @throws InvalidPodcastException
* @throws PodcastNotFoundException
*/
public static function downloadNewestEpisodes() {
public static function downloadNewestEpisodes()
{
$autoIngestPodcasts = static::_getAutoIngestPodcasts();
$service = new Application_Service_PodcastEpisodeService();
foreach ($autoIngestPodcasts as $podcast) {
@ -46,59 +49,67 @@ class PodcastManager {
/**
* Given an ImportedPodcast, find all uningested episodes since the last automatic ingest,
* and add them to a given episodes array
* and add them to a given episodes array.
*
* @param ImportedPodcast $podcast the podcast to search
* @param Application_Service_PodcastEpisodeService $service podcast episode service object
* @param ImportedPodcast $podcast the podcast to search
* @param Application_Service_PodcastEpisodeService $service podcast episode service object
*
* @return array array of episodes to append be downloaded
*/
protected static function _findUningestedEpisodes($podcast, $service) {
protected static function _findUningestedEpisodes($podcast, $service)
{
$episodeList = $service->getPodcastEpisodes($podcast->getDbPodcastId());
$episodes = array();
usort($episodeList, array(__CLASS__, "_sortByEpisodePubDate"));
for ($i = 0; $i < sizeof($episodeList); $i++) {
$episodes = [];
usort($episodeList, [__CLASS__, '_sortByEpisodePubDate']);
for ($i = 0; $i < sizeof($episodeList); ++$i) {
$episodeData = $episodeList[$i];
$ts = $podcast->getDbAutoIngestTimestamp();
// If the timestamp for this podcast is empty (no previous episodes have been ingested) and there are no
// episodes in the list of episodes to ingest, don't skip this episode - we should try to ingest the
// most recent episode when the user first sets the podcast to automatic ingest.
// If the publication date of this episode is before the ingest timestamp, we don't need to ingest it
if ((empty($ts) && ($i > 0)) || strtotime($episodeData["pub_date"]) < strtotime($ts)) {
if ((empty($ts) && ($i > 0)) || strtotime($episodeData['pub_date']) < strtotime($ts)) {
continue;
}
$episode = PodcastEpisodesQuery::create()->findOneByDbEpisodeGuid($episodeData["guid"]);
$episode = PodcastEpisodesQuery::create()->findOneByDbEpisodeGuid($episodeData['guid']);
// Make sure there's no existing episode placeholder or import, and that the data is non-empty
if (empty($episode) && !empty($episodeData)) {
$placeholder = $service->addPlaceholder($podcast->getDbPodcastId(), $episodeData);
array_push($episodes, $placeholder);
}
}
return $episodes;
}
/**
* Find all podcasts flagged for automatic ingest
* Find all podcasts flagged for automatic ingest.
*
* @return PropelObjectCollection collection of ImportedPodcast objects
* flagged for automatic ingest
*/
protected static function _getAutoIngestPodcasts() {
protected static function _getAutoIngestPodcasts()
{
return ImportedPodcastQuery::create()
->filterByDbAutoIngest(true)
->find();
->find()
;
}
/**
* Custom sort function for podcast episodes
* Custom sort function for podcast episodes.
*
* @param array $a first episode array to compare
* @param array $b second episode array to compare
*
* @return bool boolean for ordering
*/
protected static function _sortByEpisodePubDate($a, $b) {
if ($a["pub_date"] == $b["pub_date"]) return 0;
return (strtotime($a["pub_date"]) < strtotime($b["pub_date"])) ? 1 : -1; // Descending order
}
protected static function _sortByEpisodePubDate($a, $b)
{
if ($a['pub_date'] == $b['pub_date']) {
return 0;
}
return (strtotime($a['pub_date']) < strtotime($b['pub_date'])) ? 1 : -1; // Descending order
}
}

View File

@ -1,23 +1,26 @@
<?php
class SecurityHelper {
public static function htmlescape_recursive(&$arr) {
class SecurityHelper
{
public static function htmlescape_recursive(&$arr)
{
foreach ($arr as $key => $val) {
if (is_array($val)) {
self::htmlescape_recursive($arr[$key]);
} else if (is_string($val)) {
} elseif (is_string($val)) {
$arr[$key] = htmlspecialchars($val, ENT_QUOTES);
}
}
return $arr;
}
public static function verifyCSRFToken($observedToken) {
public static function verifyCSRFToken($observedToken)
{
$current_namespace = new Zend_Session_Namespace('csrf_namespace');
$observed_csrf_token = $observedToken;
$expected_csrf_token = $current_namespace->authtoken;
return ($observed_csrf_token == $expected_csrf_token);
return $observed_csrf_token == $expected_csrf_token;
}
}
}

View File

@ -2,7 +2,8 @@
class SessionHelper
{
public static function reopenSessionForWriting() {
public static function reopenSessionForWriting()
{
//PHP will send double Set-Cookie headers if we reopen the
//session for writing, and this breaks IE8 and some other browsers.
//This hacky workaround prevents double headers. Background here:
@ -10,4 +11,4 @@ class SessionHelper
ini_set('session.cache_limiter', null);
session_start(); // Reopen the session for writing (without resending the Set-Cookie header)
}
}
}

View File

@ -1,52 +1,54 @@
<?php
/**
* Class TaskManager
* Class TaskManager.
*
* Background class for 'asynchronous' task management for Airtime stations
*/
final class TaskManager {
final class TaskManager
{
/**
* @var array tasks to be run. Maps task names to a boolean value denoting
* whether the task has been checked/run
*/
protected $_taskList;
private $_taskList;
/**
* @var TaskManager singleton instance object
*/
protected static $_instance;
private static $_instance;
/**
* @var int TASK_INTERVAL_SECONDS how often, in seconds, to run the TaskManager tasks
*/
const TASK_INTERVAL_SECONDS = 30;
public const TASK_INTERVAL_SECONDS = 30;
/**
*
* @var $con PDO Propel connection object
* @var PDO Propel connection object
*/
private $_con;
/**
* Private constructor so class is uninstantiable
* Private constructor so class is uninstantiable.
*/
private function __construct() {
private function __construct()
{
foreach (TaskFactory::getTasks() as $k => $task) {
$this->_taskList[$task] = false;
}
}
/**
* Get the singleton instance of this class
* Get the singleton instance of this class.
*
* @return TaskManager the TaskManager instance
*/
public static function getInstance() {
public static function getInstance()
{
if (!self::$_instance) {
self::$_instance = new TaskManager();
}
return self::$_instance;
}
@ -55,7 +57,8 @@ final class TaskManager {
*
* @param string $taskName the ENUM name of the task to be run
*/
public function runTask($taskName) {
public function runTask($taskName)
{
$task = TaskFactory::getTask($taskName);
if ($task && $task->shouldBeRun()) {
$task->run();
@ -75,7 +78,8 @@ final class TaskManager {
* which, assuming enough time has passed, is updated before running
* the tasks.
*/
public function runTasks() {
public function runTasks()
{
// If there is data in auth storage, this could be a user request
// so we should just return to avoid blocking
if ($this->_isUserSessionRequest()) {
@ -83,12 +87,14 @@ final class TaskManager {
}
$this->_con = Propel::getConnection(CcPrefPeer::DATABASE_NAME);
$this->_con->beginTransaction();
try {
$lock = $this->_getLock();
if ($lock && (microtime(true) < ($lock['valstr'] + self::TASK_INTERVAL_SECONDS))) {
// Propel caches the database connection and uses it persistently, so if we don't
// use commit() here, we end up blocking other queries made within this request
$this->_con->commit();
return;
}
$this->_updateLock($lock);
@ -97,6 +103,7 @@ final class TaskManager {
// We get here if there are simultaneous requests trying to fetch the lock row
$this->_con->rollBack();
Logging::warn($e->getMessage());
return;
}
foreach ($this->_taskList as $task => $hasTaskRun) {
@ -107,22 +114,24 @@ final class TaskManager {
}
/**
* Check if the current session is a user request
* Check if the current session is a user request.
*
* @return bool true if there is a Zend_Auth object in the current session,
* otherwise false
*/
private function _isUserSessionRequest() {
private function _isUserSessionRequest()
{
if (!Zend_Session::isStarted()) {
return false;
}
$auth = Zend_Auth::getInstance();
$data = $auth->getStorage()->read();
return !empty($data);
}
/**
* Get the task_manager_lock from cc_pref with a row-level lock for atomicity
* Get the task_manager_lock from cc_pref with a row-level lock for atomicity.
*
* The lock is exclusive (prevent reads) and will only last for the duration
* of the transaction. We add NOWAIT so reads on the row during the transaction
@ -130,108 +139,108 @@ final class TaskManager {
*
* @return array|bool an array containing the row values, or false on failure
*/
private function _getLock() {
private function _getLock()
{
$sql = "SELECT * FROM cc_pref WHERE keystr='task_manager_lock' LIMIT 1 FOR UPDATE NOWAIT";
$st = $this->_con->prepare($sql);
$st->execute();
return $st->fetch();
}
/**
* Update and commit the new lock value, or insert it if it doesn't exist
* Update and commit the new lock value, or insert it if it doesn't exist.
*
* @param $lock array cc_pref lock row values
*/
private function _updateLock($lock) {
private function _updateLock($lock)
{
$sql = empty($lock) ? "INSERT INTO cc_pref (keystr, valstr) VALUES ('task_manager_lock', :value)"
: "UPDATE cc_pref SET valstr=:value WHERE keystr='task_manager_lock'";
$st = $this->_con->prepare($sql);
$st->execute(array(":value" => microtime(true)));
$st->execute([':value' => microtime(true)]);
}
}
/**
* Interface AirtimeTask Interface for task operations
* Interface AirtimeTask Interface for task operations.
*/
interface AirtimeTask {
interface AirtimeTask
{
/**
* Check whether the task should be run
* Check whether the task should be run.
*
* @return bool true if the task needs to be run, otherwise false
*/
public function shouldBeRun();
/**
* Run the task
*
* @return void
* Run the task.
*/
public function run();
}
/**
* Class UpgradeTask
* Class UpgradeTask.
*
* Checks the current Airtime version and runs any outstanding upgrades
*/
class UpgradeTask implements AirtimeTask {
class UpgradeTask implements AirtimeTask
{
/**
* Check the current Airtime schema version to see if an upgrade should be run
* Check the current Airtime schema version to see if an upgrade should be run.
*
* @return bool true if an upgrade is needed
*/
public function shouldBeRun() {
public function shouldBeRun()
{
return UpgradeManager::checkIfUpgradeIsNeeded();
}
/**
* Run all upgrades above the current schema version
* Run all upgrades above the current schema version.
*/
public function run() {
public function run()
{
UpgradeManager::doUpgrade();
}
}
/**
* Class CeleryTask
* Class CeleryTask.
*
* Checks the Celery broker task queue and runs callbacks for completed tasks
*/
class CeleryTask implements AirtimeTask {
class CeleryTask implements AirtimeTask
{
/**
* Check the ThirdPartyTrackReferences table to see if there are any pending tasks
* Check the ThirdPartyTrackReferences table to see if there are any pending tasks.
*
* @return bool true if there are pending tasks in ThirdPartyTrackReferences
*/
public function shouldBeRun() {
public function shouldBeRun()
{
return !CeleryManager::isBrokerTaskQueueEmpty();
}
/**
* Poll the task queue for any completed Celery tasks
* Poll the task queue for any completed Celery tasks.
*/
public function run() {
public function run()
{
CeleryManager::pollBrokerTaskQueue();
}
}
/**
* Class AutoPlaylistTask
* Class AutoPlaylistTask.
*
* Checks for shows with an autoplaylist that needs to be filled in
*
*/
class AutoPlaylistTask implements AirtimeTask
{
/**
* Checks whether or not the autoplaylist polling interval has passed
* Checks whether or not the autoplaylist polling interval has passed.
*
* @return bool true if the autoplaylist polling interval has passed
*/
@ -241,7 +250,7 @@ class AutoPlaylistTask implements AirtimeTask
}
/**
* Schedule the autoplaylist for the shows
* Schedule the autoplaylist for the shows.
*/
public function run()
{
@ -250,123 +259,133 @@ class AutoPlaylistTask implements AirtimeTask
}
/**
* Class PodcastTask
* Class PodcastTask.
*
* Checks podcasts marked for automatic ingest and downloads any new episodes
* since the task was last run
*/
class PodcastTask implements AirtimeTask {
class PodcastTask implements AirtimeTask
{
/**
* Check whether or not the podcast polling interval has passed
* Check whether or not the podcast polling interval has passed.
*
* @return bool true if the podcast polling interval has passed
*/
public function shouldBeRun() {
public function shouldBeRun()
{
$overQuota = Application_Model_Systemstatus::isDiskOverQuota();
return !$overQuota && PodcastManager::hasPodcastPollIntervalPassed();
}
/**
* Download the latest episode for all podcasts flagged for automatic ingest
* Download the latest episode for all podcasts flagged for automatic ingest.
*/
public function run() {
public function run()
{
PodcastManager::downloadNewestEpisodes();
}
}
/**
* Class ImportTask
* Class ImportTask.
*/
class ImportCleanupTask implements AirtimeTask {
class ImportCleanupTask implements AirtimeTask
{
/**
* Check if there are any files that have been stuck
* in Pending status for over an hour
* in Pending status for over an hour.
*
* @return bool true if there are any files stuck pending,
* otherwise false
*/
public function shouldBeRun() {
public function shouldBeRun()
{
return Application_Service_MediaService::areFilesStuckInPending();
}
/**
* Clean up stuck imports by changing their import status to Failed
* Clean up stuck imports by changing their import status to Failed.
*/
public function run() {
public function run()
{
Application_Service_MediaService::clearStuckPendingImports();
}
}
/**
* Class StationPodcastTask
* Class StationPodcastTask.
*
* Checks the Station podcast rollover timer and resets allotted
* downloads if enough time has passed (default: 1 month)
*/
class StationPodcastTask implements AirtimeTask {
const STATION_PODCAST_RESET_TIMER_SECONDS = 2.628e+6; // 1 month
class StationPodcastTask implements AirtimeTask
{
public const STATION_PODCAST_RESET_TIMER_SECONDS = 2.628e+6; // 1 month
/**
* Check whether or not the download counter for the station podcast should be reset
* Check whether or not the download counter for the station podcast should be reset.
*
* @return bool true if enough time has passed
*/
public function shouldBeRun() {
public function shouldBeRun()
{
$lastReset = Application_Model_Preference::getStationPodcastDownloadResetTimer();
return empty($lastReset) || (microtime(true) > ($lastReset + self::STATION_PODCAST_RESET_TIMER_SECONDS));
}
/**
* Reset the station podcast download counter
* Reset the station podcast download counter.
*/
public function run() {
public function run()
{
Application_Model_Preference::resetStationPodcastDownloadCounter();
Application_Model_Preference::setStationPodcastDownloadResetTimer(microtime(true));
}
}
/**
* Class TaskFactory Factory class to abstract task instantiation
* Class TaskFactory Factory class to abstract task instantiation.
*/
class TaskFactory {
class TaskFactory
{
/**
* Check if the class with the given name implements AirtimeTask
* Check if the class with the given name implements AirtimeTask.
*
* @param $c string class name
*
* @return bool true if the class $c implements AirtimeTask
*/
private static function _isTask($c) {
private static function _isTask($c)
{
return array_key_exists('AirtimeTask', class_implements($c));
}
/**
* Filter all declared classes to get all classes implementing the AirtimeTask interface
* Filter all declared classes to get all classes implementing the AirtimeTask interface.
*
* @return array all classes implementing the AirtimeTask interface
*/
public static function getTasks() {
return array_filter(get_declared_classes(), array(__CLASS__, "_isTask"));
public static function getTasks()
{
return array_filter(get_declared_classes(), [__CLASS__, '_isTask']);
}
/**
* Get an AirtimeTask based on class name
* Get an AirtimeTask based on class name.
*
* @param $task string name of the class implementing AirtimeTask to construct
*
* @return AirtimeTask|null return a task of the given type or null if no corresponding task exists
* @return null|AirtimeTask return a task of the given type or null if no corresponding task exists
*/
public static function getTask($task) {
public static function getTask($task)
{
// Try to get a valid class name from the given string
if (!class_exists($task)) $task = str_replace(' ', '', ucwords($task)) . "Task";
if (!class_exists($task)) {
$task = str_replace(' ', '', ucwords($task)) . 'Task';
}
return class_exists($task) ? new $task() : null;
}
}

View File

@ -4,7 +4,7 @@ class Application_Common_Timezone
{
public static function getTimezones()
{
$regions = array(
$regions = [
'Africa' => DateTimeZone::AFRICA,
'America' => DateTimeZone::AMERICA,
'Antarctica' => DateTimeZone::ANTARCTICA,
@ -15,15 +15,15 @@ class Application_Common_Timezone
'Europe' => DateTimeZone::EUROPE,
'Indian' => DateTimeZone::INDIAN,
'Pacific' => DateTimeZone::PACIFIC,
'UTC' => DateTimeZone::UTC
);
'UTC' => DateTimeZone::UTC,
];
$tzlist = array(NULL => _("Use station default"));
$tzlist = [null => _('Use station default')];
foreach ($regions as $name => $mask) {
$ids = DateTimeZone::listIdentifiers($mask);
foreach ($ids as $id) {
$tzlist[$id] = str_replace("_", " ", $id);
$tzlist[$id] = str_replace('_', ' ', $id);
}
}

View File

@ -9,7 +9,7 @@ class Application_Common_TuneIn
public static function sendMetadataToTunein($title, $artist)
{
$credQryStr = self::getCredentialsQueryString();
$metadataQryStr = "&title=".$title."&artist=".$artist."&commercial=false";
$metadataQryStr = '&title=' . $title . '&artist=' . $artist . '&commercial=false';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, TUNEIN_API_URL . $credQryStr . $metadataQryStr);
@ -19,26 +19,25 @@ class Application_Common_TuneIn
$xmlResponse = curl_exec($ch);
if (curl_error($ch)) {
Logging::error("Failed to reach TuneIn: ". curl_errno($ch)." - ". curl_error($ch) . " - " . curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
Logging::error('Failed to reach TuneIn: ' . curl_errno($ch) . ' - ' . curl_error($ch) . ' - ' . curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
}
curl_close($ch);
$xmlObj = new SimpleXMLElement($xmlResponse);
if (!$xmlObj || $xmlObj->head->status != "200") {
Logging::info("Error occurred pushing metadata to TuneIn:");
if (!$xmlObj || $xmlObj->head->status != '200') {
Logging::info('Error occurred pushing metadata to TuneIn:');
Logging::info($xmlResponse);
} else if ($xmlObj->head->status == "200") {
} elseif ($xmlObj->head->status == '200') {
Application_Model_Preference::setLastTuneinMetadataUpdate(time());
}
}
private static function getCredentialsQueryString() {
private static function getCredentialsQueryString()
{
$tuneInStationID = Application_Model_Preference::getTuneinStationId();
$tuneInPartnerID = Application_Model_Preference::getTuneinPartnerId();
$tuneInPartnerKey = Application_Model_Preference::getTuneinPartnerKey();
return "?partnerId=".$tuneInPartnerID."&partnerKey=".$tuneInPartnerKey."&id=".$tuneInStationID;
return '?partnerId=' . $tuneInPartnerID . '&partnerKey=' . $tuneInPartnerKey . '&id=' . $tuneInStationID;
}
}

View File

@ -2,12 +2,12 @@
class Application_Common_UsabilityHints
{
/**
* @param $userPath User's current location in Airtime (i.e. /Plupload)
*
* @return string
*/
public static function getUsabilityHint($userPath=null)
public static function getUsabilityHint($userPath = null)
{
// We want to display hints in this order:
// 1. Check if files are uploaded
@ -42,17 +42,16 @@ class Application_Common_UsabilityHints
if (strpos(strtolower($userPath), 'showbuilder') !== false) {
$userIsOnShowbuilderPage = true;
}
} else {
// If $userPath is not set the request came from inside Airtime so
// we can use Zend's Front Controller to get the user's current location.
$currentController = strtolower(Zend_Controller_Front::getInstance()->getRequest()->getControllerName());
if ($currentController == "schedule") {
if ($currentController == 'schedule') {
$userIsOnCalendarPage = true;
}
if ($currentController == "plupload") {
if ($currentController == 'plupload') {
$userIsOnAddMediaPage = true;
}
@ -63,48 +62,59 @@ class Application_Common_UsabilityHints
if (self::zeroFilesUploaded()) {
if ($userIsOnAddMediaPage) {
return _("Upload some tracks below to add them to your library!");
} else {
return sprintf(_("It looks like you haven't uploaded any audio files yet. %sUpload a file now%s."),
"<a href=\"/plupload\">",
"</a>");
return _('Upload some tracks below to add them to your library!');
}
} else if (!self::isFutureOrCurrentShowScheduled()) {
return sprintf(
_("It looks like you haven't uploaded any audio files yet. %sUpload a file now%s."),
'<a href="/plupload">',
'</a>'
);
}
if (!self::isFutureOrCurrentShowScheduled()) {
if ($userIsOnCalendarPage) {
return _("Click the 'New Show' button and fill out the required fields.");
} else {
return sprintf(_("It looks like you don't have any shows scheduled. %sCreate a show now%s."),
"<a href=\"/schedule\">",
"</a>");
}
} else if (self::isCurrentShowEmpty()) {
return sprintf(
_("It looks like you don't have any shows scheduled. %sCreate a show now%s."),
'<a href="/schedule">',
'</a>'
);
}
if (self::isCurrentShowEmpty()) {
// If the current show is linked users cannot add content to it so we have to provide a different message.
if (self::isCurrentShowLinked()) {
if ($userIsOnCalendarPage) {
return _("To start broadcasting, cancel the current linked show by clicking on it and selecting 'Cancel Show'.");
} else {
return sprintf(_("Linked shows need to be filled with tracks before it starts. To start broadcasting cancel the current linked show and schedule an unlinked show.
%sCreate an unlinked show now%s."), "<a href=\"/schedule\">", "</a>");
}
} else {
if ($userIsOnCalendarPage) {
return _("To start broadcasting, click on the current show and select 'Schedule Tracks'");
} else {
return sprintf(_("It looks like the current show needs more tracks. %sAdd tracks to your show now%s."),
"<a href=\"/schedule\">",
"</a>");
}
return sprintf(_('Linked shows need to be filled with tracks before it starts. To start broadcasting cancel the current linked show and schedule an unlinked show.
%sCreate an unlinked show now%s.'), '<a href="/schedule">', '</a>');
}
} else if (!self::getCurrentShow() && self::isNextShowEmpty()) {
if ($userIsOnCalendarPage) {
return _("To start broadcasting, click on the current show and select 'Schedule Tracks'");
}
return sprintf(
_('It looks like the current show needs more tracks. %sAdd tracks to your show now%s.'),
'<a href="/schedule">',
'</a>'
);
}
if (!self::getCurrentShow() && self::isNextShowEmpty()) {
if ($userIsOnCalendarPage) {
return _("Click on the show starting next and select 'Schedule Tracks'");
} else {
return sprintf(_("It looks like the next show is empty. %sAdd tracks to your show now%s."),
"<a href=\"/schedule\">",
"</a>");
}
return sprintf(
_('It looks like the next show is empty. %sAdd tracks to your show now%s.'),
'<a href="/schedule">',
'</a>'
);
}
return "";
return '';
}
/**
@ -115,13 +125,14 @@ class Application_Common_UsabilityHints
$fileCount = CcFilesQuery::create()
->filterByDbFileExists(true)
->filterByDbHidden(false)
->count();
->count()
;
if ($fileCount == 0) {
return true;
} else {
return false;
}
return false;
}
/**
@ -135,9 +146,9 @@ class Application_Common_UsabilityHints
if (is_null($futureShow) && is_null($currentShow)) {
return false;
} else {
return true;
}
return true;
}
private static function isCurrentShowEmpty()
@ -146,18 +157,18 @@ class Application_Common_UsabilityHints
if (is_null($currentShow)) {
return false;
} else {
$now = new DateTime("now", new DateTimeZone("UTC"));
$scheduledTracks = CcScheduleQuery::create()
->filterByDbInstanceId($currentShow->getDbId())
->filterByDbEnds($now, Criteria::GREATER_EQUAL)
->find();
if ($scheduledTracks->count() == 0) {
return true;
} else {
return false;
}
}
$now = new DateTime('now', new DateTimeZone('UTC'));
$scheduledTracks = CcScheduleQuery::create()
->filterByDbInstanceId($currentShow->getDbId())
->filterByDbEnds($now, Criteria::GREATER_EQUAL)
->find()
;
if ($scheduledTracks->count() == 0) {
return true;
}
return false;
}
private static function isNextShowEmpty()
@ -166,40 +177,42 @@ class Application_Common_UsabilityHints
if (is_null($futureShow)) {
return false;
} else {
$now = new DateTime("now", new DateTimeZone("UTC"));
$scheduledTracks = CcScheduleQuery::create()
->filterByDbInstanceId($futureShow->getDbId())
->filterByDbStarts($now, Criteria::GREATER_EQUAL)
->find();
if ($scheduledTracks->count() == 0) {
return true;
} else {
return false;
}
}
$now = new DateTime('now', new DateTimeZone('UTC'));
$scheduledTracks = CcScheduleQuery::create()
->filterByDbInstanceId($futureShow->getDbId())
->filterByDbStarts($now, Criteria::GREATER_EQUAL)
->find()
;
if ($scheduledTracks->count() == 0) {
return true;
}
return false;
}
private static function getCurrentShow()
{
$now = new DateTime("now", new DateTimeZone("UTC"));
$now = new DateTime('now', new DateTimeZone('UTC'));
return CcShowInstancesQuery::create()
->filterByDbStarts($now, Criteria::LESS_THAN)
->filterByDbEnds($now, Criteria::GREATER_THAN)
->filterByDbModifiedInstance(false)
->findOne();
->findOne()
;
}
private static function getNextFutureShow()
{
$now = new DateTime("now", new DateTimeZone("UTC"));
$now = new DateTime('now', new DateTimeZone('UTC'));
return CcShowInstancesQuery::create()
->filterByDbStarts($now, Criteria::GREATER_THAN)
->filterByDbModifiedInstance(false)
->orderByDbStarts()
->findOne();
->findOne()
;
}
private static function isCurrentShowLinked()
@ -208,14 +221,15 @@ class Application_Common_UsabilityHints
if (!is_null($currentShow)) {
$show = CcShowQuery::create()
->filterByDbId($currentShow->getDbShowId())
->findOne();
->findOne()
;
if ($show->isLinked()) {
return true;
} else {
return false;
}
} else {
return false;
}
return false;
}
}

View File

@ -1,6 +1,6 @@
<?php
define("DAYS_PER_WEEK", 7);
define('DAYS_PER_WEEK', 7);
class WidgetHelper
{
@ -9,11 +9,11 @@ class WidgetHelper
//weekStart is in station time.
$weekStartDateTime = Application_Common_DateHelper::getWeekStartDateTime();
$dow = array("monday", "tuesday", "wednesday", "thursday", "friday",
"saturday", "sunday", "nextmonday", "nexttuesday", "nextwednesday",
"nextthursday", "nextfriday", "nextsaturday", "nextsunday");
$dow = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday',
'saturday', 'sunday', 'nextmonday', 'nexttuesday', 'nextwednesday',
'nextthursday', 'nextfriday', 'nextsaturday', 'nextsunday', ];
$result = array();
$result = [];
// default to the station timezone
$timezone = Application_Model_Preference::GetDefaultTimezone();
@ -24,11 +24,11 @@ class WidgetHelper
$timezone = $userDefinedTimezone;
}
}
$utcTimezone = new DateTimeZone("UTC");
$utcTimezone = new DateTimeZone('UTC');
$weekStartDateTime->setTimezone($utcTimezone);
$utcDayStart = $weekStartDateTime->format(DEFAULT_TIMESTAMP_FORMAT);
for ($i = 0; $i < 14; $i++) {
for ($i = 0; $i < 14; ++$i) {
//have to be in station timezone when adding 1 day for daylight savings.
$weekStartDateTime->setTimezone(new DateTimeZone($timezone));
$weekStartDateTime->add(new DateInterval('P1D'));
@ -37,13 +37,13 @@ class WidgetHelper
$weekStartDateTime->setTimezone($utcTimezone);
$utcDayEnd = $weekStartDateTime->format(DEFAULT_TIMESTAMP_FORMAT);
$shows = Application_Model_Show::getNextShows($utcDayStart, "ALL", $utcDayEnd);
$shows = Application_Model_Show::getNextShows($utcDayStart, 'ALL', $utcDayEnd);
$utcDayStart = $utcDayEnd;
// convert to user-defined timezone, or default to station
Application_Common_DateHelper::convertTimestampsToTimezone(
$shows,
array("starts", "ends", "start_timestamp","end_timestamp"),
['starts', 'ends', 'start_timestamp', 'end_timestamp'],
$timezone
);
@ -61,7 +61,7 @@ class WidgetHelper
/**
* Returns a weeks worth of shows in UTC, and an info array of the current week's days.
* Returns an array of two arrays:
* Returns an array of two arrays:.
*
* The first array is 7 consecutive week days, starting with the current day.
*
@ -77,11 +77,11 @@ class WidgetHelper
*/
public static function getWeekInfoV2()
{
$weekStartDateTime = new DateTime("now", new DateTimeZone(Application_Model_Preference::GetTimezone()));
$weekStartDateTime = new DateTime('now', new DateTimeZone(Application_Model_Preference::GetTimezone()));
$result = array();
$result = [];
$utcTimezone = new DateTimeZone("UTC");
$utcTimezone = new DateTimeZone('UTC');
$weekStartDateTime->setTimezone($utcTimezone);
@ -90,23 +90,23 @@ class WidgetHelper
// schedule widget data to account for show date changes when
// converting their start day/time to the client's local timezone.
$showQueryDateRangeStart = clone $weekStartDateTime;
$showQueryDateRangeStart->sub(new DateInterval("P1D"));
$showQueryDateRangeStart->sub(new DateInterval('P1D'));
$showQueryDateRangeStart->setTime(0, 0, 0);
for ($dayOfWeekCounter = 0; $dayOfWeekCounter < DAYS_PER_WEEK; $dayOfWeekCounter++) {
$dateParse = date_parse($weekStartDateTime->format("Y-m-d H:i:s"));
for ($dayOfWeekCounter = 0; $dayOfWeekCounter < DAYS_PER_WEEK; ++$dayOfWeekCounter) {
$dateParse = date_parse($weekStartDateTime->format('Y-m-d H:i:s'));
// Associate data to its date so that when we convert this array
// to json the order remains the same - in chronological order.
// We also format the key to be for example: "2015-6-1" to match
// javascript date formats so it's easier to sort the shows by day.
$result["weekDays"][$weekStartDateTime->format("Y-n-j")] = array();
$result["weekDays"][$weekStartDateTime->format("Y-n-j")]["dayOfMonth"] = $dateParse["day"];
$result["weekDays"][$weekStartDateTime->format("Y-n-j")]["dayOfWeek"] = strtoupper(_(date("D", $weekStartDateTime->getTimestamp())));
$result['weekDays'][$weekStartDateTime->format('Y-n-j')] = [];
$result['weekDays'][$weekStartDateTime->format('Y-n-j')]['dayOfMonth'] = $dateParse['day'];
$result['weekDays'][$weekStartDateTime->format('Y-n-j')]['dayOfWeek'] = strtoupper(_(date('D', $weekStartDateTime->getTimestamp())));
// Shows scheduled for this day will get added to this array when
// we convert the show times to the client's local timezone in weekly-program.phtml
$result["weekDays"][$weekStartDateTime->format("Y-n-j")]["shows"] = array();
$result['weekDays'][$weekStartDateTime->format('Y-n-j')]['shows'] = [];
// $weekStartDateTime has to be in station timezone when adding 1 day for daylight savings.
// TODO: is this necessary since we set the time to "00:00" ?
@ -127,21 +127,22 @@ class WidgetHelper
$showQueryDateRangeEnd->setTime(23, 59, 0);
$shows = Application_Model_Show::getNextShows(
$showQueryDateRangeStart->format("Y-m-d H:i:s"),
"ALL",
$showQueryDateRangeEnd->format("Y-m-d H:i:s"));
$showQueryDateRangeStart->format('Y-m-d H:i:s'),
'ALL',
$showQueryDateRangeEnd->format('Y-m-d H:i:s')
);
// Convert each start and end time string to DateTime objects
// so we can get a real timestamp. The timestamps will be used
// to convert into javascript Date objects.
foreach($shows as &$show) {
$dtStarts = new DateTime($show["starts"], new DateTimeZone("UTC"));
$show["starts_timestamp"] = $dtStarts->getTimestamp();
foreach ($shows as &$show) {
$dtStarts = new DateTime($show['starts'], new DateTimeZone('UTC'));
$show['starts_timestamp'] = $dtStarts->getTimestamp();
$dtEnds = new DateTime($show["ends"], new DateTimeZone("UTC"));
$show["ends_timestamp"] = $dtEnds->getTimestamp();
$dtEnds = new DateTime($show['ends'], new DateTimeZone('UTC'));
$show['ends_timestamp'] = $dtEnds->getTimestamp();
}
$result["shows"] = $shows;
$result['shows'] = $shows;
// convert image paths to point to api endpoints
//TODO: do we need this here?
@ -152,7 +153,7 @@ class WidgetHelper
/**
* Recursively find image_path keys in the various $result subarrays,
* and convert them to point to the show-logo endpoint
* and convert them to point to the show-logo endpoint.
*
* @param unknown $arr the array to search
*/
@ -163,9 +164,9 @@ class WidgetHelper
foreach ($arr as &$a) {
if (is_array($a)) {
if (array_key_exists("image_path", $a)) {
$a["image_path"] = $a["image_path"] && $a["image_path"] !== '' ?
Application_Common_HTTPHelper::getStationUrl()."api/show-logo?id=".$a["id"] : '';
if (array_key_exists('image_path', $a)) {
$a['image_path'] = $a['image_path'] && $a['image_path'] !== '' ?
Application_Common_HTTPHelper::getStationUrl() . 'api/show-logo?id=' . $a['id'] : '';
} else {
self::findAndConvertPaths($a);
}

View File

@ -1,12 +1,11 @@
<?php
final class HttpRequestType {
const GET = "GET";
const POST = "POST";
const PUT = "PUT";
const DELETE = "DELETE";
const PATCH = "PATCH";
const OPTIONS = "OPTIONS";
}
final class HttpRequestType
{
public const GET = 'GET';
public const POST = 'POST';
public const PUT = 'PUT';
public const DELETE = 'DELETE';
public const PATCH = 'PATCH';
public const OPTIONS = 'OPTIONS';
}

View File

@ -1,17 +1,17 @@
<?php
final class MediaType {
final class MediaType
{
public const __default = self::FILE;
const __default = self::FILE;
public const FILE = 1;
public const PLAYLIST = 2;
public const BLOCK = 3;
public const WEBSTREAM = 4;
public const PODCAST = 5;
const FILE = 1;
const PLAYLIST = 2;
const BLOCK = 3;
const WEBSTREAM = 4;
const PODCAST = 5;
public static function getDefault() {
public static function getDefault()
{
return static::__default;
}
}
}

View File

@ -1,31 +1,30 @@
<?php
interface OAuth2 {
interface OAuth2
{
/**
* Check whether an OAuth access token exists
* Check whether an OAuth access token exists.
*
* @return bool true if an access token exists, otherwise false
*/
public function hasAccessToken();
/**
* Get the OAuth authorization URL
* Get the OAuth authorization URL.
*
* @return string the authorization URL
*/
public function getAuthorizeUrl();
/**
* Request a new OAuth access token and store it in CcPref
* Request a new OAuth access token and store it in CcPref.
*
* @param $code string exchange authorization code for access token
*/
public function requestNewAccessToken($code);
/**
* Regenerate the OAuth access token
* Regenerate the OAuth access token.
*/
public function accessTokenRefresh();
}
}

View File

@ -1,27 +1,20 @@
<?php
interface OAuth2Controller {
interface OAuth2Controller
{
/**
* Send user to a third-party service to authorize before being redirected
*
* @return void
* Send user to a third-party service to authorize before being redirected.
*/
public function authorizeAction();
/**
* Clear the previously saved request token from the preferences
*
* @return void
* Clear the previously saved request token from the preferences.
*/
public function deauthorizeAction();
/**
* Called when user successfully completes third-party authorization
* Store the returned request token for future requests
*
* @return void
* Store the returned request token for future requests.
*/
public function redirectAction();
}
}

View File

@ -1,28 +1,23 @@
<?php
interface Publish {
interface Publish
{
/**
* Publish the file with the given file ID
* Publish the file with the given file ID.
*
* @param int $fileId ID of the file to be published
*
* @return void
*/
public function publish($fileId);
/**
* Unpublish the file with the given file ID
* Unpublish the file with the given file ID.
*
* @param int $fileId ID of the file to be unpublished
*
* @return void
*/
public function unpublish($fileId);
/**
* Fetch the publication status for the file with the given ID
* Fetch the publication status for the file with the given ID.
*
* @param int $fileId the ID of the file to check
*
@ -32,5 +27,4 @@ interface Publish {
* 2 if the source is unreachable (disconnected)
*/
public function getPublishStatus($fileId);
}
}

View File

@ -3,28 +3,28 @@
* Created by PhpStorm.
* User: asantoni
* Date: 11/09/15
* Time: 2:47 PM
* Time: 2:47 PM.
*/
class AirtimeTableView {
private static function _getTableJavaScriptDependencies() {
class AirtimeTableView
{
private static function _getTableJavaScriptDependencies()
{
return ['js/airtime/widgets/table.js',
'js/datatables/js/jquery.dataTables.js',
'js/datatables/plugin/dataTables.pluginAPI.js',
'js/datatables/plugin/dataTables.fnSetFilteringDelay.js',
'js/datatables/plugin/dataTables.ColVis.js',
'js/datatables/plugin/dataTables.colReorder.min.js?',
'js/datatables/plugin/dataTables.FixedColumns.js',
'js/datatables/plugin/dataTables.FixedHeader.js',
'js/datatables/plugin/dataTables.columnFilter.js?'];
'js/datatables/js/jquery.dataTables.js',
'js/datatables/plugin/dataTables.pluginAPI.js',
'js/datatables/plugin/dataTables.fnSetFilteringDelay.js',
'js/datatables/plugin/dataTables.ColVis.js',
'js/datatables/plugin/dataTables.colReorder.min.js?',
'js/datatables/plugin/dataTables.FixedColumns.js',
'js/datatables/plugin/dataTables.FixedHeader.js',
'js/datatables/plugin/dataTables.columnFilter.js?', ];
}
public static function injectTableJavaScriptDependencies(&$headScript, $baseUrl, $airtimeVersion)
{
$deps = self::_getTableJavaScriptDependencies();
for ($i = 0; $i < count($deps); $i++) {
$headScript->appendFile($baseUrl . $deps[$i] .'?'. $airtimeVersion, 'text/javascript');
for ($i = 0; $i < count($deps); ++$i) {
$headScript->appendFile($baseUrl . $deps[$i] . '?' . $airtimeVersion, 'text/javascript');
}
}
}
}

View File

@ -1,90 +1,91 @@
<?php
$ccAcl = new Zend_Acl();
$ccAcl->addRole(new Zend_Acl_Role('G'))
->addRole(new Zend_Acl_Role('H'), 'G')
->addRole(new Zend_Acl_Role('P'), 'H')
->addRole(new Zend_Acl_Role('A'), 'P')
->addRole(new Zend_Acl_Role('S'), 'A');
->addRole(new Zend_Acl_Role('H'), 'G')
->addRole(new Zend_Acl_Role('P'), 'H')
->addRole(new Zend_Acl_Role('A'), 'P')
->addRole(new Zend_Acl_Role('S'), 'A')
;
$ccAcl->add(new Zend_Acl_Resource('library'))
->add(new Zend_Acl_Resource('index'))
->add(new Zend_Acl_Resource('user'))
->add(new Zend_Acl_Resource('tracktype'))
->add(new Zend_Acl_Resource('error'))
->add(new Zend_Acl_Resource('login'))
->add(new Zend_Acl_Resource('playlist'))
->add(new Zend_Acl_Resource('plupload'))
->add(new Zend_Acl_Resource('schedule'))
->add(new Zend_Acl_Resource('api'))
->add(new Zend_Acl_Resource('systemstatus'))
->add(new Zend_Acl_Resource('dashboard'))
->add(new Zend_Acl_Resource('preference'))
->add(new Zend_Acl_Resource('showbuilder'))
->add(new Zend_Acl_Resource('playouthistory'))
->add(new Zend_Acl_Resource('playouthistorytemplate'))
->add(new Zend_Acl_Resource('listenerstat'))
->add(new Zend_Acl_Resource('showlistenerstat'))
->add(new Zend_Acl_Resource('usersettings'))
->add(new Zend_Acl_Resource('audiopreview'))
->add(new Zend_Acl_Resource('webstream'))
->add(new Zend_Acl_Resource('locale'))
->add(new Zend_Acl_Resource('upgrade'))
->add(new Zend_Acl_Resource('downgrade'))
->add(new Zend_Acl_Resource('rest:media'))
->add(new Zend_Acl_Resource('rest:show-image'))
->add(new Zend_Acl_Resource('rest:podcast'))
->add(new Zend_Acl_Resource('rest:podcast-episodes'))
->add(new Zend_Acl_Resource('podcast'))
->add(new Zend_Acl_Resource('player'))
->add(new Zend_Acl_Resource('render'))
->add(new Zend_Acl_Resource('embeddablewidgets'))
->add(new Zend_Acl_Resource('setup'))
->add(new Zend_Acl_Resource('feeds'));
->add(new Zend_Acl_Resource('index'))
->add(new Zend_Acl_Resource('user'))
->add(new Zend_Acl_Resource('tracktype'))
->add(new Zend_Acl_Resource('error'))
->add(new Zend_Acl_Resource('login'))
->add(new Zend_Acl_Resource('playlist'))
->add(new Zend_Acl_Resource('plupload'))
->add(new Zend_Acl_Resource('schedule'))
->add(new Zend_Acl_Resource('api'))
->add(new Zend_Acl_Resource('systemstatus'))
->add(new Zend_Acl_Resource('dashboard'))
->add(new Zend_Acl_Resource('preference'))
->add(new Zend_Acl_Resource('showbuilder'))
->add(new Zend_Acl_Resource('playouthistory'))
->add(new Zend_Acl_Resource('playouthistorytemplate'))
->add(new Zend_Acl_Resource('listenerstat'))
->add(new Zend_Acl_Resource('showlistenerstat'))
->add(new Zend_Acl_Resource('usersettings'))
->add(new Zend_Acl_Resource('audiopreview'))
->add(new Zend_Acl_Resource('webstream'))
->add(new Zend_Acl_Resource('locale'))
->add(new Zend_Acl_Resource('upgrade'))
->add(new Zend_Acl_Resource('downgrade'))
->add(new Zend_Acl_Resource('rest:media'))
->add(new Zend_Acl_Resource('rest:show-image'))
->add(new Zend_Acl_Resource('rest:podcast'))
->add(new Zend_Acl_Resource('rest:podcast-episodes'))
->add(new Zend_Acl_Resource('podcast'))
->add(new Zend_Acl_Resource('player'))
->add(new Zend_Acl_Resource('render'))
->add(new Zend_Acl_Resource('embeddablewidgets'))
->add(new Zend_Acl_Resource('setup'))
->add(new Zend_Acl_Resource('feeds'))
;
/** Creating permissions */
// Creating permissions
$ccAcl->allow('G', 'index')
->allow('G', 'login')
->allow('G', 'error')
->allow('G', 'user', 'edit-user')
->allow('G', 'showbuilder')
->allow('G', 'render')
->allow('G', 'api')
->allow('G', 'schedule')
->allow('G', 'dashboard')
->allow('G', 'audiopreview')
->allow('G', 'webstream')
->allow('G', 'locale')
->allow('G', 'upgrade')
->allow('G', 'downgrade')
->allow('G', 'rest:show-image', 'get')
->allow('G', 'rest:media', 'get')
->allow('G', 'rest:podcast', 'get')
->allow('G', 'rest:podcast-episodes', 'get')
->allow('G', 'setup')
->allow('G', 'embeddablewidgets')
->allow('G', 'feeds')
->allow('H', 'rest:show-image')
->allow('H', 'rest:media')
->allow('H', 'rest:podcast')
->allow('H', 'rest:podcast-episodes')
->allow('H', 'podcast')
->allow('H', 'preference', 'is-import-in-progress')
->allow('H', 'usersettings')
->allow('H', 'plupload')
->allow('H', 'library')
->allow('H', 'playlist')
->allow('H', 'playouthistory')
->allow('H', 'listenerstat')
->allow('H', 'showlistenerstat')
->allow('A', 'playouthistorytemplate')
->allow('A', 'user')
->allow('A', 'tracktype')
->allow('A', 'systemstatus')
->allow('A', 'preference');
->allow('G', 'login')
->allow('G', 'error')
->allow('G', 'user', 'edit-user')
->allow('G', 'showbuilder')
->allow('G', 'render')
->allow('G', 'api')
->allow('G', 'schedule')
->allow('G', 'dashboard')
->allow('G', 'audiopreview')
->allow('G', 'webstream')
->allow('G', 'locale')
->allow('G', 'upgrade')
->allow('G', 'downgrade')
->allow('G', 'rest:show-image', 'get')
->allow('G', 'rest:media', 'get')
->allow('G', 'rest:podcast', 'get')
->allow('G', 'rest:podcast-episodes', 'get')
->allow('G', 'setup')
->allow('G', 'embeddablewidgets')
->allow('G', 'feeds')
->allow('H', 'rest:show-image')
->allow('H', 'rest:media')
->allow('H', 'rest:podcast')
->allow('H', 'rest:podcast-episodes')
->allow('H', 'podcast')
->allow('H', 'preference', 'is-import-in-progress')
->allow('H', 'usersettings')
->allow('H', 'plupload')
->allow('H', 'library')
->allow('H', 'playlist')
->allow('H', 'playouthistory')
->allow('H', 'listenerstat')
->allow('H', 'showlistenerstat')
->allow('A', 'playouthistorytemplate')
->allow('A', 'user')
->allow('A', 'tracktype')
->allow('A', 'systemstatus')
->allow('A', 'preference')
;
$aclPlugin = new Zend_Controller_Plugin_Acl($ccAcl);

View File

@ -1,4 +1,5 @@
<?php
// This file generated by Propel 1.5.2 convert-conf target
// from XML runtime conf file /home/james/src/airtime/legacy/build/runtime-conf.xml
@ -15,20 +16,18 @@ $dbname = $CC_CONFIG['dsn']['database'];
$dbuser = $CC_CONFIG['dsn']['username'];
$dbpass = $CC_CONFIG['dsn']['password'];
$conf = array (
'datasources' =>
array (
'airtime' =>
array (
'adapter' => 'pgsql',
'connection' =>
array (
'dsn' => "pgsql:host=$dbhost;port=5432;dbname=$dbname;user=$dbuser;password=$dbpass",
),
),
'default' => 'airtime',
),
'generator_version' => '1.7.0',
);
$conf['classmap'] = include(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'classmap-airtime-conf.php');
$conf = [
'datasources' => [
'airtime' => [
'adapter' => 'pgsql',
'connection' => [
'dsn' => "pgsql:host={$dbhost};port=5432;dbname={$dbname};user={$dbuser};password={$dbpass}",
],
],
'default' => 'airtime',
],
'generator_version' => '1.7.0',
];
$conf['classmap'] = include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'classmap-airtime-conf.php';
return $conf;

View File

@ -1,28 +1,25 @@
<?php
// This file generated by Propel 1.7.0 convert-conf target
// from XML runtime conf file /vagrant/legacy/build/runtime-conf.xml
$conf = array (
'datasources' =>
array (
'airtime' =>
array (
'adapter' => 'pgsql',
'connection' =>
array (
'dsn' => 'pgsql:host=localhost;port=5432;dbname=airtime;user=airtime;password=airtime',
),
),
'airtime_test' =>
array (
'adapter' => 'pgsql',
'connection' =>
array (
'dsn' => 'pgsql:host=localhost;port=5432;dbname=airtime_test;user=airtime;password=airtime',
),
),
'default' => 'airtime',
),
'generator_version' => '1.7.0',
);
$conf['classmap'] = include(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'classmap-airtime-conf.php');
return $conf;
$conf = [
'datasources' => [
'airtime' => [
'adapter' => 'pgsql',
'connection' => [
'dsn' => 'pgsql:host=localhost;port=5432;dbname=airtime;user=airtime;password=airtime',
],
],
'airtime_test' => [
'adapter' => 'pgsql',
'connection' => [
'dsn' => 'pgsql:host=localhost;port=5432;dbname=airtime_test;user=airtime;password=airtime',
],
],
'default' => 'airtime',
],
'generator_version' => '1.7.0',
];
$conf['classmap'] = include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'classmap-airtime-conf.php';
return $conf;

View File

@ -1,284 +1,285 @@
<?php
// This file generated by Propel 1.7.0 convert-conf target
return array (
'BaseCcBlock' => 'airtime/om/BaseCcBlock.php',
'BaseCcBlockPeer' => 'airtime/om/BaseCcBlockPeer.php',
'BaseCcBlockQuery' => 'airtime/om/BaseCcBlockQuery.php',
'BaseCcBlockcontents' => 'airtime/om/BaseCcBlockcontents.php',
'BaseCcBlockcontentsPeer' => 'airtime/om/BaseCcBlockcontentsPeer.php',
'BaseCcBlockcontentsQuery' => 'airtime/om/BaseCcBlockcontentsQuery.php',
'BaseCcBlockcriteria' => 'airtime/om/BaseCcBlockcriteria.php',
'BaseCcBlockcriteriaPeer' => 'airtime/om/BaseCcBlockcriteriaPeer.php',
'BaseCcBlockcriteriaQuery' => 'airtime/om/BaseCcBlockcriteriaQuery.php',
'BaseCcCountry' => 'airtime/om/BaseCcCountry.php',
'BaseCcCountryPeer' => 'airtime/om/BaseCcCountryPeer.php',
'BaseCcCountryQuery' => 'airtime/om/BaseCcCountryQuery.php',
'BaseCcFiles' => 'airtime/om/BaseCcFiles.php',
'BaseCcFilesPeer' => 'airtime/om/BaseCcFilesPeer.php',
'BaseCcFilesQuery' => 'airtime/om/BaseCcFilesQuery.php',
'BaseCcListenerCount' => 'airtime/om/BaseCcListenerCount.php',
'BaseCcListenerCountPeer' => 'airtime/om/BaseCcListenerCountPeer.php',
'BaseCcListenerCountQuery' => 'airtime/om/BaseCcListenerCountQuery.php',
'BaseCcLiveLog' => 'airtime/om/BaseCcLiveLog.php',
'BaseCcLiveLogPeer' => 'airtime/om/BaseCcLiveLogPeer.php',
'BaseCcLiveLogQuery' => 'airtime/om/BaseCcLiveLogQuery.php',
'BaseCcLoginAttempts' => 'airtime/om/BaseCcLoginAttempts.php',
'BaseCcLoginAttemptsPeer' => 'airtime/om/BaseCcLoginAttemptsPeer.php',
'BaseCcLoginAttemptsQuery' => 'airtime/om/BaseCcLoginAttemptsQuery.php',
'BaseCcMountName' => 'airtime/om/BaseCcMountName.php',
'BaseCcMountNamePeer' => 'airtime/om/BaseCcMountNamePeer.php',
'BaseCcMountNameQuery' => 'airtime/om/BaseCcMountNameQuery.php',
'BaseCcMusicDirs' => 'airtime/om/BaseCcMusicDirs.php',
'BaseCcMusicDirsPeer' => 'airtime/om/BaseCcMusicDirsPeer.php',
'BaseCcMusicDirsQuery' => 'airtime/om/BaseCcMusicDirsQuery.php',
'BaseCcPerms' => 'airtime/om/BaseCcPerms.php',
'BaseCcPermsPeer' => 'airtime/om/BaseCcPermsPeer.php',
'BaseCcPermsQuery' => 'airtime/om/BaseCcPermsQuery.php',
'BaseCcPlaylist' => 'airtime/om/BaseCcPlaylist.php',
'BaseCcPlaylistPeer' => 'airtime/om/BaseCcPlaylistPeer.php',
'BaseCcPlaylistQuery' => 'airtime/om/BaseCcPlaylistQuery.php',
'BaseCcPlaylistcontents' => 'airtime/om/BaseCcPlaylistcontents.php',
'BaseCcPlaylistcontentsPeer' => 'airtime/om/BaseCcPlaylistcontentsPeer.php',
'BaseCcPlaylistcontentsQuery' => 'airtime/om/BaseCcPlaylistcontentsQuery.php',
'BaseCcPlayoutHistory' => 'airtime/om/BaseCcPlayoutHistory.php',
'BaseCcPlayoutHistoryMetaData' => 'airtime/om/BaseCcPlayoutHistoryMetaData.php',
'BaseCcPlayoutHistoryMetaDataPeer' => 'airtime/om/BaseCcPlayoutHistoryMetaDataPeer.php',
'BaseCcPlayoutHistoryMetaDataQuery' => 'airtime/om/BaseCcPlayoutHistoryMetaDataQuery.php',
'BaseCcPlayoutHistoryPeer' => 'airtime/om/BaseCcPlayoutHistoryPeer.php',
'BaseCcPlayoutHistoryQuery' => 'airtime/om/BaseCcPlayoutHistoryQuery.php',
'BaseCcPlayoutHistoryTemplate' => 'airtime/om/BaseCcPlayoutHistoryTemplate.php',
'BaseCcPlayoutHistoryTemplateField' => 'airtime/om/BaseCcPlayoutHistoryTemplateField.php',
'BaseCcPlayoutHistoryTemplateFieldPeer' => 'airtime/om/BaseCcPlayoutHistoryTemplateFieldPeer.php',
'BaseCcPlayoutHistoryTemplateFieldQuery' => 'airtime/om/BaseCcPlayoutHistoryTemplateFieldQuery.php',
'BaseCcPlayoutHistoryTemplatePeer' => 'airtime/om/BaseCcPlayoutHistoryTemplatePeer.php',
'BaseCcPlayoutHistoryTemplateQuery' => 'airtime/om/BaseCcPlayoutHistoryTemplateQuery.php',
'BaseCcPref' => 'airtime/om/BaseCcPref.php',
'BaseCcPrefPeer' => 'airtime/om/BaseCcPrefPeer.php',
'BaseCcPrefQuery' => 'airtime/om/BaseCcPrefQuery.php',
'BaseCcSchedule' => 'airtime/om/BaseCcSchedule.php',
'BaseCcSchedulePeer' => 'airtime/om/BaseCcSchedulePeer.php',
'BaseCcScheduleQuery' => 'airtime/om/BaseCcScheduleQuery.php',
'BaseCcServiceRegister' => 'airtime/om/BaseCcServiceRegister.php',
'BaseCcServiceRegisterPeer' => 'airtime/om/BaseCcServiceRegisterPeer.php',
'BaseCcServiceRegisterQuery' => 'airtime/om/BaseCcServiceRegisterQuery.php',
'BaseCcSess' => 'airtime/om/BaseCcSess.php',
'BaseCcSessPeer' => 'airtime/om/BaseCcSessPeer.php',
'BaseCcSessQuery' => 'airtime/om/BaseCcSessQuery.php',
'BaseCcShow' => 'airtime/om/BaseCcShow.php',
'BaseCcShowDays' => 'airtime/om/BaseCcShowDays.php',
'BaseCcShowDaysPeer' => 'airtime/om/BaseCcShowDaysPeer.php',
'BaseCcShowDaysQuery' => 'airtime/om/BaseCcShowDaysQuery.php',
'BaseCcShowHosts' => 'airtime/om/BaseCcShowHosts.php',
'BaseCcShowHostsPeer' => 'airtime/om/BaseCcShowHostsPeer.php',
'BaseCcShowHostsQuery' => 'airtime/om/BaseCcShowHostsQuery.php',
'BaseCcShowInstances' => 'airtime/om/BaseCcShowInstances.php',
'BaseCcShowInstancesPeer' => 'airtime/om/BaseCcShowInstancesPeer.php',
'BaseCcShowInstancesQuery' => 'airtime/om/BaseCcShowInstancesQuery.php',
'BaseCcShowPeer' => 'airtime/om/BaseCcShowPeer.php',
'BaseCcShowQuery' => 'airtime/om/BaseCcShowQuery.php',
'BaseCcShowRebroadcast' => 'airtime/om/BaseCcShowRebroadcast.php',
'BaseCcShowRebroadcastPeer' => 'airtime/om/BaseCcShowRebroadcastPeer.php',
'BaseCcShowRebroadcastQuery' => 'airtime/om/BaseCcShowRebroadcastQuery.php',
'BaseCcStreamSetting' => 'airtime/om/BaseCcStreamSetting.php',
'BaseCcStreamSettingPeer' => 'airtime/om/BaseCcStreamSettingPeer.php',
'BaseCcStreamSettingQuery' => 'airtime/om/BaseCcStreamSettingQuery.php',
'BaseCcTracktypes' => 'airtime/om/BaseCcTracktypes.php',
'BaseCcTracktypesPeer' => 'airtime/om/BaseCcTracktypesPeer.php',
'BaseCcTracktypesQuery' => 'airtime/om/BaseCcTracktypesQuery.php',
'BaseCcSubjs' => 'airtime/om/BaseCcSubjs.php',
'BaseCcSubjsPeer' => 'airtime/om/BaseCcSubjsPeer.php',
'BaseCcSubjsQuery' => 'airtime/om/BaseCcSubjsQuery.php',
'BaseCcSubjsToken' => 'airtime/om/BaseCcSubjsToken.php',
'BaseCcSubjsTokenPeer' => 'airtime/om/BaseCcSubjsTokenPeer.php',
'BaseCcSubjsTokenQuery' => 'airtime/om/BaseCcSubjsTokenQuery.php',
'BaseCcTimestamp' => 'airtime/om/BaseCcTimestamp.php',
'BaseCcTimestampPeer' => 'airtime/om/BaseCcTimestampPeer.php',
'BaseCcTimestampQuery' => 'airtime/om/BaseCcTimestampQuery.php',
'BaseCcWebstream' => 'airtime/om/BaseCcWebstream.php',
'BaseCcWebstreamMetadata' => 'airtime/om/BaseCcWebstreamMetadata.php',
'BaseCcWebstreamMetadataPeer' => 'airtime/om/BaseCcWebstreamMetadataPeer.php',
'BaseCcWebstreamMetadataQuery' => 'airtime/om/BaseCcWebstreamMetadataQuery.php',
'BaseCcWebstreamPeer' => 'airtime/om/BaseCcWebstreamPeer.php',
'BaseCcWebstreamQuery' => 'airtime/om/BaseCcWebstreamQuery.php',
'BaseCeleryTasks' => 'airtime/om/BaseCeleryTasks.php',
'BaseCeleryTasksPeer' => 'airtime/om/BaseCeleryTasksPeer.php',
'BaseCeleryTasksQuery' => 'airtime/om/BaseCeleryTasksQuery.php',
'BaseCloudFile' => 'airtime/om/BaseCloudFile.php',
'BaseCloudFilePeer' => 'airtime/om/BaseCloudFilePeer.php',
'BaseCloudFileQuery' => 'airtime/om/BaseCloudFileQuery.php',
'BaseImportedPodcast' => 'airtime/om/BaseImportedPodcast.php',
'BaseImportedPodcastPeer' => 'airtime/om/BaseImportedPodcastPeer.php',
'BaseImportedPodcastQuery' => 'airtime/om/BaseImportedPodcastQuery.php',
'BasePodcast' => 'airtime/om/BasePodcast.php',
'BasePodcastEpisodes' => 'airtime/om/BasePodcastEpisodes.php',
'BasePodcastEpisodesPeer' => 'airtime/om/BasePodcastEpisodesPeer.php',
'BasePodcastEpisodesQuery' => 'airtime/om/BasePodcastEpisodesQuery.php',
'BasePodcastPeer' => 'airtime/om/BasePodcastPeer.php',
'BasePodcastQuery' => 'airtime/om/BasePodcastQuery.php',
'BaseStationPodcast' => 'airtime/om/BaseStationPodcast.php',
'BaseStationPodcastPeer' => 'airtime/om/BaseStationPodcastPeer.php',
'BaseStationPodcastQuery' => 'airtime/om/BaseStationPodcastQuery.php',
'BaseThirdPartyTrackReferences' => 'airtime/om/BaseThirdPartyTrackReferences.php',
'BaseThirdPartyTrackReferencesPeer' => 'airtime/om/BaseThirdPartyTrackReferencesPeer.php',
'BaseThirdPartyTrackReferencesQuery' => 'airtime/om/BaseThirdPartyTrackReferencesQuery.php',
'CcBlock' => 'airtime/CcBlock.php',
'CcBlockPeer' => 'airtime/CcBlockPeer.php',
'CcBlockQuery' => 'airtime/CcBlockQuery.php',
'CcBlockTableMap' => 'airtime/map/CcBlockTableMap.php',
'CcBlockcontents' => 'airtime/CcBlockcontents.php',
'CcBlockcontentsPeer' => 'airtime/CcBlockcontentsPeer.php',
'CcBlockcontentsQuery' => 'airtime/CcBlockcontentsQuery.php',
'CcBlockcontentsTableMap' => 'airtime/map/CcBlockcontentsTableMap.php',
'CcBlockcriteria' => 'airtime/CcBlockcriteria.php',
'CcBlockcriteriaPeer' => 'airtime/CcBlockcriteriaPeer.php',
'CcBlockcriteriaQuery' => 'airtime/CcBlockcriteriaQuery.php',
'CcBlockcriteriaTableMap' => 'airtime/map/CcBlockcriteriaTableMap.php',
'CcCountry' => 'airtime/CcCountry.php',
'CcCountryPeer' => 'airtime/CcCountryPeer.php',
'CcCountryQuery' => 'airtime/CcCountryQuery.php',
'CcCountryTableMap' => 'airtime/map/CcCountryTableMap.php',
'CcFiles' => 'airtime/CcFiles.php',
'CcFilesPeer' => 'airtime/CcFilesPeer.php',
'CcFilesQuery' => 'airtime/CcFilesQuery.php',
'CcFilesTableMap' => 'airtime/map/CcFilesTableMap.php',
'CcListenerCount' => 'airtime/CcListenerCount.php',
'CcListenerCountPeer' => 'airtime/CcListenerCountPeer.php',
'CcListenerCountQuery' => 'airtime/CcListenerCountQuery.php',
'CcListenerCountTableMap' => 'airtime/map/CcListenerCountTableMap.php',
'CcLiveLog' => 'airtime/CcLiveLog.php',
'CcLiveLogPeer' => 'airtime/CcLiveLogPeer.php',
'CcLiveLogQuery' => 'airtime/CcLiveLogQuery.php',
'CcLiveLogTableMap' => 'airtime/map/CcLiveLogTableMap.php',
'CcLoginAttempts' => 'airtime/CcLoginAttempts.php',
'CcLoginAttemptsPeer' => 'airtime/CcLoginAttemptsPeer.php',
'CcLoginAttemptsQuery' => 'airtime/CcLoginAttemptsQuery.php',
'CcLoginAttemptsTableMap' => 'airtime/map/CcLoginAttemptsTableMap.php',
'CcMountName' => 'airtime/CcMountName.php',
'CcMountNamePeer' => 'airtime/CcMountNamePeer.php',
'CcMountNameQuery' => 'airtime/CcMountNameQuery.php',
'CcMountNameTableMap' => 'airtime/map/CcMountNameTableMap.php',
'CcMusicDirs' => 'airtime/CcMusicDirs.php',
'CcMusicDirsPeer' => 'airtime/CcMusicDirsPeer.php',
'CcMusicDirsQuery' => 'airtime/CcMusicDirsQuery.php',
'CcMusicDirsTableMap' => 'airtime/map/CcMusicDirsTableMap.php',
'CcPerms' => 'airtime/CcPerms.php',
'CcPermsPeer' => 'airtime/CcPermsPeer.php',
'CcPermsQuery' => 'airtime/CcPermsQuery.php',
'CcPermsTableMap' => 'airtime/map/CcPermsTableMap.php',
'CcPlaylist' => 'airtime/CcPlaylist.php',
'CcPlaylistPeer' => 'airtime/CcPlaylistPeer.php',
'CcPlaylistQuery' => 'airtime/CcPlaylistQuery.php',
'CcPlaylistTableMap' => 'airtime/map/CcPlaylistTableMap.php',
'CcPlaylistcontents' => 'airtime/CcPlaylistcontents.php',
'CcPlaylistcontentsPeer' => 'airtime/CcPlaylistcontentsPeer.php',
'CcPlaylistcontentsQuery' => 'airtime/CcPlaylistcontentsQuery.php',
'CcPlaylistcontentsTableMap' => 'airtime/map/CcPlaylistcontentsTableMap.php',
'CcPlayoutHistory' => 'airtime/CcPlayoutHistory.php',
'CcPlayoutHistoryMetaData' => 'airtime/CcPlayoutHistoryMetaData.php',
'CcPlayoutHistoryMetaDataPeer' => 'airtime/CcPlayoutHistoryMetaDataPeer.php',
'CcPlayoutHistoryMetaDataQuery' => 'airtime/CcPlayoutHistoryMetaDataQuery.php',
'CcPlayoutHistoryMetaDataTableMap' => 'airtime/map/CcPlayoutHistoryMetaDataTableMap.php',
'CcPlayoutHistoryPeer' => 'airtime/CcPlayoutHistoryPeer.php',
'CcPlayoutHistoryQuery' => 'airtime/CcPlayoutHistoryQuery.php',
'CcPlayoutHistoryTableMap' => 'airtime/map/CcPlayoutHistoryTableMap.php',
'CcPlayoutHistoryTemplate' => 'airtime/CcPlayoutHistoryTemplate.php',
'CcPlayoutHistoryTemplateField' => 'airtime/CcPlayoutHistoryTemplateField.php',
'CcPlayoutHistoryTemplateFieldPeer' => 'airtime/CcPlayoutHistoryTemplateFieldPeer.php',
'CcPlayoutHistoryTemplateFieldQuery' => 'airtime/CcPlayoutHistoryTemplateFieldQuery.php',
'CcPlayoutHistoryTemplateFieldTableMap' => 'airtime/map/CcPlayoutHistoryTemplateFieldTableMap.php',
'CcPlayoutHistoryTemplatePeer' => 'airtime/CcPlayoutHistoryTemplatePeer.php',
'CcPlayoutHistoryTemplateQuery' => 'airtime/CcPlayoutHistoryTemplateQuery.php',
'CcPlayoutHistoryTemplateTableMap' => 'airtime/map/CcPlayoutHistoryTemplateTableMap.php',
'CcPref' => 'airtime/CcPref.php',
'CcPrefPeer' => 'airtime/CcPrefPeer.php',
'CcPrefQuery' => 'airtime/CcPrefQuery.php',
'CcPrefTableMap' => 'airtime/map/CcPrefTableMap.php',
'CcSchedule' => 'airtime/CcSchedule.php',
'CcSchedulePeer' => 'airtime/CcSchedulePeer.php',
'CcScheduleQuery' => 'airtime/CcScheduleQuery.php',
'CcScheduleTableMap' => 'airtime/map/CcScheduleTableMap.php',
'CcServiceRegister' => 'airtime/CcServiceRegister.php',
'CcServiceRegisterPeer' => 'airtime/CcServiceRegisterPeer.php',
'CcServiceRegisterQuery' => 'airtime/CcServiceRegisterQuery.php',
'CcServiceRegisterTableMap' => 'airtime/map/CcServiceRegisterTableMap.php',
'CcSess' => 'airtime/CcSess.php',
'CcSessPeer' => 'airtime/CcSessPeer.php',
'CcSessQuery' => 'airtime/CcSessQuery.php',
'CcSessTableMap' => 'airtime/map/CcSessTableMap.php',
'CcShow' => 'airtime/CcShow.php',
'CcShowDays' => 'airtime/CcShowDays.php',
'CcShowDaysPeer' => 'airtime/CcShowDaysPeer.php',
'CcShowDaysQuery' => 'airtime/CcShowDaysQuery.php',
'CcShowDaysTableMap' => 'airtime/map/CcShowDaysTableMap.php',
'CcShowHosts' => 'airtime/CcShowHosts.php',
'CcShowHostsPeer' => 'airtime/CcShowHostsPeer.php',
'CcShowHostsQuery' => 'airtime/CcShowHostsQuery.php',
'CcShowHostsTableMap' => 'airtime/map/CcShowHostsTableMap.php',
'CcShowInstances' => 'airtime/CcShowInstances.php',
'CcShowInstancesPeer' => 'airtime/CcShowInstancesPeer.php',
'CcShowInstancesQuery' => 'airtime/CcShowInstancesQuery.php',
'CcShowInstancesTableMap' => 'airtime/map/CcShowInstancesTableMap.php',
'CcShowPeer' => 'airtime/CcShowPeer.php',
'CcShowQuery' => 'airtime/CcShowQuery.php',
'CcShowRebroadcast' => 'airtime/CcShowRebroadcast.php',
'CcShowRebroadcastPeer' => 'airtime/CcShowRebroadcastPeer.php',
'CcShowRebroadcastQuery' => 'airtime/CcShowRebroadcastQuery.php',
'CcShowRebroadcastTableMap' => 'airtime/map/CcShowRebroadcastTableMap.php',
'CcShowTableMap' => 'airtime/map/CcShowTableMap.php',
'CcStreamSetting' => 'airtime/CcStreamSetting.php',
'CcStreamSettingPeer' => 'airtime/CcStreamSettingPeer.php',
'CcStreamSettingQuery' => 'airtime/CcStreamSettingQuery.php',
'CcStreamSettingTableMap' => 'airtime/map/CcStreamSettingTableMap.php',
'CcTracktypes' => 'airtime/CcTracktypes.php',
'CcTracktypesPeer' => 'airtime/CcTracktypesPeer.php',
'CcTracktypesQuery' => 'airtime/CcTracktypesQuery.php',
'CcTracktypesTableMap' => 'airtime/map/CcTracktypesTableMap.php',
'CcSubjs' => 'airtime/CcSubjs.php',
'CcSubjsPeer' => 'airtime/CcSubjsPeer.php',
'CcSubjsQuery' => 'airtime/CcSubjsQuery.php',
'CcSubjsTableMap' => 'airtime/map/CcSubjsTableMap.php',
'CcSubjsToken' => 'airtime/CcSubjsToken.php',
'CcSubjsTokenPeer' => 'airtime/CcSubjsTokenPeer.php',
'CcSubjsTokenQuery' => 'airtime/CcSubjsTokenQuery.php',
'CcSubjsTokenTableMap' => 'airtime/map/CcSubjsTokenTableMap.php',
'CcTimestamp' => 'airtime/CcTimestamp.php',
'CcTimestampPeer' => 'airtime/CcTimestampPeer.php',
'CcTimestampQuery' => 'airtime/CcTimestampQuery.php',
'CcTimestampTableMap' => 'airtime/map/CcTimestampTableMap.php',
'CcWebstream' => 'airtime/CcWebstream.php',
'CcWebstreamMetadata' => 'airtime/CcWebstreamMetadata.php',
'CcWebstreamMetadataPeer' => 'airtime/CcWebstreamMetadataPeer.php',
'CcWebstreamMetadataQuery' => 'airtime/CcWebstreamMetadataQuery.php',
'CcWebstreamMetadataTableMap' => 'airtime/map/CcWebstreamMetadataTableMap.php',
'CcWebstreamPeer' => 'airtime/CcWebstreamPeer.php',
'CcWebstreamQuery' => 'airtime/CcWebstreamQuery.php',
'CcWebstreamTableMap' => 'airtime/map/CcWebstreamTableMap.php',
'CeleryTasks' => 'airtime/CeleryTasks.php',
'CeleryTasksPeer' => 'airtime/CeleryTasksPeer.php',
'CeleryTasksQuery' => 'airtime/CeleryTasksQuery.php',
'CeleryTasksTableMap' => 'airtime/map/CeleryTasksTableMap.php',
'CloudFile' => 'airtime/CloudFile.php',
'CloudFilePeer' => 'airtime/CloudFilePeer.php',
'CloudFileQuery' => 'airtime/CloudFileQuery.php',
'CloudFileTableMap' => 'airtime/map/CloudFileTableMap.php',
'ImportedPodcast' => 'airtime/ImportedPodcast.php',
'ImportedPodcastPeer' => 'airtime/ImportedPodcastPeer.php',
'ImportedPodcastQuery' => 'airtime/ImportedPodcastQuery.php',
'ImportedPodcastTableMap' => 'airtime/map/ImportedPodcastTableMap.php',
'Podcast' => 'airtime/Podcast.php',
'PodcastEpisodes' => 'airtime/PodcastEpisodes.php',
'PodcastEpisodesPeer' => 'airtime/PodcastEpisodesPeer.php',
'PodcastEpisodesQuery' => 'airtime/PodcastEpisodesQuery.php',
'PodcastEpisodesTableMap' => 'airtime/map/PodcastEpisodesTableMap.php',
'PodcastPeer' => 'airtime/PodcastPeer.php',
'PodcastQuery' => 'airtime/PodcastQuery.php',
'PodcastTableMap' => 'airtime/map/PodcastTableMap.php',
'StationPodcast' => 'airtime/StationPodcast.php',
'StationPodcastPeer' => 'airtime/StationPodcastPeer.php',
'StationPodcastQuery' => 'airtime/StationPodcastQuery.php',
'StationPodcastTableMap' => 'airtime/map/StationPodcastTableMap.php',
'ThirdPartyTrackReferences' => 'airtime/ThirdPartyTrackReferences.php',
'ThirdPartyTrackReferencesPeer' => 'airtime/ThirdPartyTrackReferencesPeer.php',
'ThirdPartyTrackReferencesQuery' => 'airtime/ThirdPartyTrackReferencesQuery.php',
'ThirdPartyTrackReferencesTableMap' => 'airtime/map/ThirdPartyTrackReferencesTableMap.php',
);
return [
'BaseCcBlock' => 'airtime/om/BaseCcBlock.php',
'BaseCcBlockPeer' => 'airtime/om/BaseCcBlockPeer.php',
'BaseCcBlockQuery' => 'airtime/om/BaseCcBlockQuery.php',
'BaseCcBlockcontents' => 'airtime/om/BaseCcBlockcontents.php',
'BaseCcBlockcontentsPeer' => 'airtime/om/BaseCcBlockcontentsPeer.php',
'BaseCcBlockcontentsQuery' => 'airtime/om/BaseCcBlockcontentsQuery.php',
'BaseCcBlockcriteria' => 'airtime/om/BaseCcBlockcriteria.php',
'BaseCcBlockcriteriaPeer' => 'airtime/om/BaseCcBlockcriteriaPeer.php',
'BaseCcBlockcriteriaQuery' => 'airtime/om/BaseCcBlockcriteriaQuery.php',
'BaseCcCountry' => 'airtime/om/BaseCcCountry.php',
'BaseCcCountryPeer' => 'airtime/om/BaseCcCountryPeer.php',
'BaseCcCountryQuery' => 'airtime/om/BaseCcCountryQuery.php',
'BaseCcFiles' => 'airtime/om/BaseCcFiles.php',
'BaseCcFilesPeer' => 'airtime/om/BaseCcFilesPeer.php',
'BaseCcFilesQuery' => 'airtime/om/BaseCcFilesQuery.php',
'BaseCcListenerCount' => 'airtime/om/BaseCcListenerCount.php',
'BaseCcListenerCountPeer' => 'airtime/om/BaseCcListenerCountPeer.php',
'BaseCcListenerCountQuery' => 'airtime/om/BaseCcListenerCountQuery.php',
'BaseCcLiveLog' => 'airtime/om/BaseCcLiveLog.php',
'BaseCcLiveLogPeer' => 'airtime/om/BaseCcLiveLogPeer.php',
'BaseCcLiveLogQuery' => 'airtime/om/BaseCcLiveLogQuery.php',
'BaseCcLoginAttempts' => 'airtime/om/BaseCcLoginAttempts.php',
'BaseCcLoginAttemptsPeer' => 'airtime/om/BaseCcLoginAttemptsPeer.php',
'BaseCcLoginAttemptsQuery' => 'airtime/om/BaseCcLoginAttemptsQuery.php',
'BaseCcMountName' => 'airtime/om/BaseCcMountName.php',
'BaseCcMountNamePeer' => 'airtime/om/BaseCcMountNamePeer.php',
'BaseCcMountNameQuery' => 'airtime/om/BaseCcMountNameQuery.php',
'BaseCcMusicDirs' => 'airtime/om/BaseCcMusicDirs.php',
'BaseCcMusicDirsPeer' => 'airtime/om/BaseCcMusicDirsPeer.php',
'BaseCcMusicDirsQuery' => 'airtime/om/BaseCcMusicDirsQuery.php',
'BaseCcPerms' => 'airtime/om/BaseCcPerms.php',
'BaseCcPermsPeer' => 'airtime/om/BaseCcPermsPeer.php',
'BaseCcPermsQuery' => 'airtime/om/BaseCcPermsQuery.php',
'BaseCcPlaylist' => 'airtime/om/BaseCcPlaylist.php',
'BaseCcPlaylistPeer' => 'airtime/om/BaseCcPlaylistPeer.php',
'BaseCcPlaylistQuery' => 'airtime/om/BaseCcPlaylistQuery.php',
'BaseCcPlaylistcontents' => 'airtime/om/BaseCcPlaylistcontents.php',
'BaseCcPlaylistcontentsPeer' => 'airtime/om/BaseCcPlaylistcontentsPeer.php',
'BaseCcPlaylistcontentsQuery' => 'airtime/om/BaseCcPlaylistcontentsQuery.php',
'BaseCcPlayoutHistory' => 'airtime/om/BaseCcPlayoutHistory.php',
'BaseCcPlayoutHistoryMetaData' => 'airtime/om/BaseCcPlayoutHistoryMetaData.php',
'BaseCcPlayoutHistoryMetaDataPeer' => 'airtime/om/BaseCcPlayoutHistoryMetaDataPeer.php',
'BaseCcPlayoutHistoryMetaDataQuery' => 'airtime/om/BaseCcPlayoutHistoryMetaDataQuery.php',
'BaseCcPlayoutHistoryPeer' => 'airtime/om/BaseCcPlayoutHistoryPeer.php',
'BaseCcPlayoutHistoryQuery' => 'airtime/om/BaseCcPlayoutHistoryQuery.php',
'BaseCcPlayoutHistoryTemplate' => 'airtime/om/BaseCcPlayoutHistoryTemplate.php',
'BaseCcPlayoutHistoryTemplateField' => 'airtime/om/BaseCcPlayoutHistoryTemplateField.php',
'BaseCcPlayoutHistoryTemplateFieldPeer' => 'airtime/om/BaseCcPlayoutHistoryTemplateFieldPeer.php',
'BaseCcPlayoutHistoryTemplateFieldQuery' => 'airtime/om/BaseCcPlayoutHistoryTemplateFieldQuery.php',
'BaseCcPlayoutHistoryTemplatePeer' => 'airtime/om/BaseCcPlayoutHistoryTemplatePeer.php',
'BaseCcPlayoutHistoryTemplateQuery' => 'airtime/om/BaseCcPlayoutHistoryTemplateQuery.php',
'BaseCcPref' => 'airtime/om/BaseCcPref.php',
'BaseCcPrefPeer' => 'airtime/om/BaseCcPrefPeer.php',
'BaseCcPrefQuery' => 'airtime/om/BaseCcPrefQuery.php',
'BaseCcSchedule' => 'airtime/om/BaseCcSchedule.php',
'BaseCcSchedulePeer' => 'airtime/om/BaseCcSchedulePeer.php',
'BaseCcScheduleQuery' => 'airtime/om/BaseCcScheduleQuery.php',
'BaseCcServiceRegister' => 'airtime/om/BaseCcServiceRegister.php',
'BaseCcServiceRegisterPeer' => 'airtime/om/BaseCcServiceRegisterPeer.php',
'BaseCcServiceRegisterQuery' => 'airtime/om/BaseCcServiceRegisterQuery.php',
'BaseCcSess' => 'airtime/om/BaseCcSess.php',
'BaseCcSessPeer' => 'airtime/om/BaseCcSessPeer.php',
'BaseCcSessQuery' => 'airtime/om/BaseCcSessQuery.php',
'BaseCcShow' => 'airtime/om/BaseCcShow.php',
'BaseCcShowDays' => 'airtime/om/BaseCcShowDays.php',
'BaseCcShowDaysPeer' => 'airtime/om/BaseCcShowDaysPeer.php',
'BaseCcShowDaysQuery' => 'airtime/om/BaseCcShowDaysQuery.php',
'BaseCcShowHosts' => 'airtime/om/BaseCcShowHosts.php',
'BaseCcShowHostsPeer' => 'airtime/om/BaseCcShowHostsPeer.php',
'BaseCcShowHostsQuery' => 'airtime/om/BaseCcShowHostsQuery.php',
'BaseCcShowInstances' => 'airtime/om/BaseCcShowInstances.php',
'BaseCcShowInstancesPeer' => 'airtime/om/BaseCcShowInstancesPeer.php',
'BaseCcShowInstancesQuery' => 'airtime/om/BaseCcShowInstancesQuery.php',
'BaseCcShowPeer' => 'airtime/om/BaseCcShowPeer.php',
'BaseCcShowQuery' => 'airtime/om/BaseCcShowQuery.php',
'BaseCcShowRebroadcast' => 'airtime/om/BaseCcShowRebroadcast.php',
'BaseCcShowRebroadcastPeer' => 'airtime/om/BaseCcShowRebroadcastPeer.php',
'BaseCcShowRebroadcastQuery' => 'airtime/om/BaseCcShowRebroadcastQuery.php',
'BaseCcStreamSetting' => 'airtime/om/BaseCcStreamSetting.php',
'BaseCcStreamSettingPeer' => 'airtime/om/BaseCcStreamSettingPeer.php',
'BaseCcStreamSettingQuery' => 'airtime/om/BaseCcStreamSettingQuery.php',
'BaseCcTracktypes' => 'airtime/om/BaseCcTracktypes.php',
'BaseCcTracktypesPeer' => 'airtime/om/BaseCcTracktypesPeer.php',
'BaseCcTracktypesQuery' => 'airtime/om/BaseCcTracktypesQuery.php',
'BaseCcSubjs' => 'airtime/om/BaseCcSubjs.php',
'BaseCcSubjsPeer' => 'airtime/om/BaseCcSubjsPeer.php',
'BaseCcSubjsQuery' => 'airtime/om/BaseCcSubjsQuery.php',
'BaseCcSubjsToken' => 'airtime/om/BaseCcSubjsToken.php',
'BaseCcSubjsTokenPeer' => 'airtime/om/BaseCcSubjsTokenPeer.php',
'BaseCcSubjsTokenQuery' => 'airtime/om/BaseCcSubjsTokenQuery.php',
'BaseCcTimestamp' => 'airtime/om/BaseCcTimestamp.php',
'BaseCcTimestampPeer' => 'airtime/om/BaseCcTimestampPeer.php',
'BaseCcTimestampQuery' => 'airtime/om/BaseCcTimestampQuery.php',
'BaseCcWebstream' => 'airtime/om/BaseCcWebstream.php',
'BaseCcWebstreamMetadata' => 'airtime/om/BaseCcWebstreamMetadata.php',
'BaseCcWebstreamMetadataPeer' => 'airtime/om/BaseCcWebstreamMetadataPeer.php',
'BaseCcWebstreamMetadataQuery' => 'airtime/om/BaseCcWebstreamMetadataQuery.php',
'BaseCcWebstreamPeer' => 'airtime/om/BaseCcWebstreamPeer.php',
'BaseCcWebstreamQuery' => 'airtime/om/BaseCcWebstreamQuery.php',
'BaseCeleryTasks' => 'airtime/om/BaseCeleryTasks.php',
'BaseCeleryTasksPeer' => 'airtime/om/BaseCeleryTasksPeer.php',
'BaseCeleryTasksQuery' => 'airtime/om/BaseCeleryTasksQuery.php',
'BaseCloudFile' => 'airtime/om/BaseCloudFile.php',
'BaseCloudFilePeer' => 'airtime/om/BaseCloudFilePeer.php',
'BaseCloudFileQuery' => 'airtime/om/BaseCloudFileQuery.php',
'BaseImportedPodcast' => 'airtime/om/BaseImportedPodcast.php',
'BaseImportedPodcastPeer' => 'airtime/om/BaseImportedPodcastPeer.php',
'BaseImportedPodcastQuery' => 'airtime/om/BaseImportedPodcastQuery.php',
'BasePodcast' => 'airtime/om/BasePodcast.php',
'BasePodcastEpisodes' => 'airtime/om/BasePodcastEpisodes.php',
'BasePodcastEpisodesPeer' => 'airtime/om/BasePodcastEpisodesPeer.php',
'BasePodcastEpisodesQuery' => 'airtime/om/BasePodcastEpisodesQuery.php',
'BasePodcastPeer' => 'airtime/om/BasePodcastPeer.php',
'BasePodcastQuery' => 'airtime/om/BasePodcastQuery.php',
'BaseStationPodcast' => 'airtime/om/BaseStationPodcast.php',
'BaseStationPodcastPeer' => 'airtime/om/BaseStationPodcastPeer.php',
'BaseStationPodcastQuery' => 'airtime/om/BaseStationPodcastQuery.php',
'BaseThirdPartyTrackReferences' => 'airtime/om/BaseThirdPartyTrackReferences.php',
'BaseThirdPartyTrackReferencesPeer' => 'airtime/om/BaseThirdPartyTrackReferencesPeer.php',
'BaseThirdPartyTrackReferencesQuery' => 'airtime/om/BaseThirdPartyTrackReferencesQuery.php',
'CcBlock' => 'airtime/CcBlock.php',
'CcBlockPeer' => 'airtime/CcBlockPeer.php',
'CcBlockQuery' => 'airtime/CcBlockQuery.php',
'CcBlockTableMap' => 'airtime/map/CcBlockTableMap.php',
'CcBlockcontents' => 'airtime/CcBlockcontents.php',
'CcBlockcontentsPeer' => 'airtime/CcBlockcontentsPeer.php',
'CcBlockcontentsQuery' => 'airtime/CcBlockcontentsQuery.php',
'CcBlockcontentsTableMap' => 'airtime/map/CcBlockcontentsTableMap.php',
'CcBlockcriteria' => 'airtime/CcBlockcriteria.php',
'CcBlockcriteriaPeer' => 'airtime/CcBlockcriteriaPeer.php',
'CcBlockcriteriaQuery' => 'airtime/CcBlockcriteriaQuery.php',
'CcBlockcriteriaTableMap' => 'airtime/map/CcBlockcriteriaTableMap.php',
'CcCountry' => 'airtime/CcCountry.php',
'CcCountryPeer' => 'airtime/CcCountryPeer.php',
'CcCountryQuery' => 'airtime/CcCountryQuery.php',
'CcCountryTableMap' => 'airtime/map/CcCountryTableMap.php',
'CcFiles' => 'airtime/CcFiles.php',
'CcFilesPeer' => 'airtime/CcFilesPeer.php',
'CcFilesQuery' => 'airtime/CcFilesQuery.php',
'CcFilesTableMap' => 'airtime/map/CcFilesTableMap.php',
'CcListenerCount' => 'airtime/CcListenerCount.php',
'CcListenerCountPeer' => 'airtime/CcListenerCountPeer.php',
'CcListenerCountQuery' => 'airtime/CcListenerCountQuery.php',
'CcListenerCountTableMap' => 'airtime/map/CcListenerCountTableMap.php',
'CcLiveLog' => 'airtime/CcLiveLog.php',
'CcLiveLogPeer' => 'airtime/CcLiveLogPeer.php',
'CcLiveLogQuery' => 'airtime/CcLiveLogQuery.php',
'CcLiveLogTableMap' => 'airtime/map/CcLiveLogTableMap.php',
'CcLoginAttempts' => 'airtime/CcLoginAttempts.php',
'CcLoginAttemptsPeer' => 'airtime/CcLoginAttemptsPeer.php',
'CcLoginAttemptsQuery' => 'airtime/CcLoginAttemptsQuery.php',
'CcLoginAttemptsTableMap' => 'airtime/map/CcLoginAttemptsTableMap.php',
'CcMountName' => 'airtime/CcMountName.php',
'CcMountNamePeer' => 'airtime/CcMountNamePeer.php',
'CcMountNameQuery' => 'airtime/CcMountNameQuery.php',
'CcMountNameTableMap' => 'airtime/map/CcMountNameTableMap.php',
'CcMusicDirs' => 'airtime/CcMusicDirs.php',
'CcMusicDirsPeer' => 'airtime/CcMusicDirsPeer.php',
'CcMusicDirsQuery' => 'airtime/CcMusicDirsQuery.php',
'CcMusicDirsTableMap' => 'airtime/map/CcMusicDirsTableMap.php',
'CcPerms' => 'airtime/CcPerms.php',
'CcPermsPeer' => 'airtime/CcPermsPeer.php',
'CcPermsQuery' => 'airtime/CcPermsQuery.php',
'CcPermsTableMap' => 'airtime/map/CcPermsTableMap.php',
'CcPlaylist' => 'airtime/CcPlaylist.php',
'CcPlaylistPeer' => 'airtime/CcPlaylistPeer.php',
'CcPlaylistQuery' => 'airtime/CcPlaylistQuery.php',
'CcPlaylistTableMap' => 'airtime/map/CcPlaylistTableMap.php',
'CcPlaylistcontents' => 'airtime/CcPlaylistcontents.php',
'CcPlaylistcontentsPeer' => 'airtime/CcPlaylistcontentsPeer.php',
'CcPlaylistcontentsQuery' => 'airtime/CcPlaylistcontentsQuery.php',
'CcPlaylistcontentsTableMap' => 'airtime/map/CcPlaylistcontentsTableMap.php',
'CcPlayoutHistory' => 'airtime/CcPlayoutHistory.php',
'CcPlayoutHistoryMetaData' => 'airtime/CcPlayoutHistoryMetaData.php',
'CcPlayoutHistoryMetaDataPeer' => 'airtime/CcPlayoutHistoryMetaDataPeer.php',
'CcPlayoutHistoryMetaDataQuery' => 'airtime/CcPlayoutHistoryMetaDataQuery.php',
'CcPlayoutHistoryMetaDataTableMap' => 'airtime/map/CcPlayoutHistoryMetaDataTableMap.php',
'CcPlayoutHistoryPeer' => 'airtime/CcPlayoutHistoryPeer.php',
'CcPlayoutHistoryQuery' => 'airtime/CcPlayoutHistoryQuery.php',
'CcPlayoutHistoryTableMap' => 'airtime/map/CcPlayoutHistoryTableMap.php',
'CcPlayoutHistoryTemplate' => 'airtime/CcPlayoutHistoryTemplate.php',
'CcPlayoutHistoryTemplateField' => 'airtime/CcPlayoutHistoryTemplateField.php',
'CcPlayoutHistoryTemplateFieldPeer' => 'airtime/CcPlayoutHistoryTemplateFieldPeer.php',
'CcPlayoutHistoryTemplateFieldQuery' => 'airtime/CcPlayoutHistoryTemplateFieldQuery.php',
'CcPlayoutHistoryTemplateFieldTableMap' => 'airtime/map/CcPlayoutHistoryTemplateFieldTableMap.php',
'CcPlayoutHistoryTemplatePeer' => 'airtime/CcPlayoutHistoryTemplatePeer.php',
'CcPlayoutHistoryTemplateQuery' => 'airtime/CcPlayoutHistoryTemplateQuery.php',
'CcPlayoutHistoryTemplateTableMap' => 'airtime/map/CcPlayoutHistoryTemplateTableMap.php',
'CcPref' => 'airtime/CcPref.php',
'CcPrefPeer' => 'airtime/CcPrefPeer.php',
'CcPrefQuery' => 'airtime/CcPrefQuery.php',
'CcPrefTableMap' => 'airtime/map/CcPrefTableMap.php',
'CcSchedule' => 'airtime/CcSchedule.php',
'CcSchedulePeer' => 'airtime/CcSchedulePeer.php',
'CcScheduleQuery' => 'airtime/CcScheduleQuery.php',
'CcScheduleTableMap' => 'airtime/map/CcScheduleTableMap.php',
'CcServiceRegister' => 'airtime/CcServiceRegister.php',
'CcServiceRegisterPeer' => 'airtime/CcServiceRegisterPeer.php',
'CcServiceRegisterQuery' => 'airtime/CcServiceRegisterQuery.php',
'CcServiceRegisterTableMap' => 'airtime/map/CcServiceRegisterTableMap.php',
'CcSess' => 'airtime/CcSess.php',
'CcSessPeer' => 'airtime/CcSessPeer.php',
'CcSessQuery' => 'airtime/CcSessQuery.php',
'CcSessTableMap' => 'airtime/map/CcSessTableMap.php',
'CcShow' => 'airtime/CcShow.php',
'CcShowDays' => 'airtime/CcShowDays.php',
'CcShowDaysPeer' => 'airtime/CcShowDaysPeer.php',
'CcShowDaysQuery' => 'airtime/CcShowDaysQuery.php',
'CcShowDaysTableMap' => 'airtime/map/CcShowDaysTableMap.php',
'CcShowHosts' => 'airtime/CcShowHosts.php',
'CcShowHostsPeer' => 'airtime/CcShowHostsPeer.php',
'CcShowHostsQuery' => 'airtime/CcShowHostsQuery.php',
'CcShowHostsTableMap' => 'airtime/map/CcShowHostsTableMap.php',
'CcShowInstances' => 'airtime/CcShowInstances.php',
'CcShowInstancesPeer' => 'airtime/CcShowInstancesPeer.php',
'CcShowInstancesQuery' => 'airtime/CcShowInstancesQuery.php',
'CcShowInstancesTableMap' => 'airtime/map/CcShowInstancesTableMap.php',
'CcShowPeer' => 'airtime/CcShowPeer.php',
'CcShowQuery' => 'airtime/CcShowQuery.php',
'CcShowRebroadcast' => 'airtime/CcShowRebroadcast.php',
'CcShowRebroadcastPeer' => 'airtime/CcShowRebroadcastPeer.php',
'CcShowRebroadcastQuery' => 'airtime/CcShowRebroadcastQuery.php',
'CcShowRebroadcastTableMap' => 'airtime/map/CcShowRebroadcastTableMap.php',
'CcShowTableMap' => 'airtime/map/CcShowTableMap.php',
'CcStreamSetting' => 'airtime/CcStreamSetting.php',
'CcStreamSettingPeer' => 'airtime/CcStreamSettingPeer.php',
'CcStreamSettingQuery' => 'airtime/CcStreamSettingQuery.php',
'CcStreamSettingTableMap' => 'airtime/map/CcStreamSettingTableMap.php',
'CcTracktypes' => 'airtime/CcTracktypes.php',
'CcTracktypesPeer' => 'airtime/CcTracktypesPeer.php',
'CcTracktypesQuery' => 'airtime/CcTracktypesQuery.php',
'CcTracktypesTableMap' => 'airtime/map/CcTracktypesTableMap.php',
'CcSubjs' => 'airtime/CcSubjs.php',
'CcSubjsPeer' => 'airtime/CcSubjsPeer.php',
'CcSubjsQuery' => 'airtime/CcSubjsQuery.php',
'CcSubjsTableMap' => 'airtime/map/CcSubjsTableMap.php',
'CcSubjsToken' => 'airtime/CcSubjsToken.php',
'CcSubjsTokenPeer' => 'airtime/CcSubjsTokenPeer.php',
'CcSubjsTokenQuery' => 'airtime/CcSubjsTokenQuery.php',
'CcSubjsTokenTableMap' => 'airtime/map/CcSubjsTokenTableMap.php',
'CcTimestamp' => 'airtime/CcTimestamp.php',
'CcTimestampPeer' => 'airtime/CcTimestampPeer.php',
'CcTimestampQuery' => 'airtime/CcTimestampQuery.php',
'CcTimestampTableMap' => 'airtime/map/CcTimestampTableMap.php',
'CcWebstream' => 'airtime/CcWebstream.php',
'CcWebstreamMetadata' => 'airtime/CcWebstreamMetadata.php',
'CcWebstreamMetadataPeer' => 'airtime/CcWebstreamMetadataPeer.php',
'CcWebstreamMetadataQuery' => 'airtime/CcWebstreamMetadataQuery.php',
'CcWebstreamMetadataTableMap' => 'airtime/map/CcWebstreamMetadataTableMap.php',
'CcWebstreamPeer' => 'airtime/CcWebstreamPeer.php',
'CcWebstreamQuery' => 'airtime/CcWebstreamQuery.php',
'CcWebstreamTableMap' => 'airtime/map/CcWebstreamTableMap.php',
'CeleryTasks' => 'airtime/CeleryTasks.php',
'CeleryTasksPeer' => 'airtime/CeleryTasksPeer.php',
'CeleryTasksQuery' => 'airtime/CeleryTasksQuery.php',
'CeleryTasksTableMap' => 'airtime/map/CeleryTasksTableMap.php',
'CloudFile' => 'airtime/CloudFile.php',
'CloudFilePeer' => 'airtime/CloudFilePeer.php',
'CloudFileQuery' => 'airtime/CloudFileQuery.php',
'CloudFileTableMap' => 'airtime/map/CloudFileTableMap.php',
'ImportedPodcast' => 'airtime/ImportedPodcast.php',
'ImportedPodcastPeer' => 'airtime/ImportedPodcastPeer.php',
'ImportedPodcastQuery' => 'airtime/ImportedPodcastQuery.php',
'ImportedPodcastTableMap' => 'airtime/map/ImportedPodcastTableMap.php',
'Podcast' => 'airtime/Podcast.php',
'PodcastEpisodes' => 'airtime/PodcastEpisodes.php',
'PodcastEpisodesPeer' => 'airtime/PodcastEpisodesPeer.php',
'PodcastEpisodesQuery' => 'airtime/PodcastEpisodesQuery.php',
'PodcastEpisodesTableMap' => 'airtime/map/PodcastEpisodesTableMap.php',
'PodcastPeer' => 'airtime/PodcastPeer.php',
'PodcastQuery' => 'airtime/PodcastQuery.php',
'PodcastTableMap' => 'airtime/map/PodcastTableMap.php',
'StationPodcast' => 'airtime/StationPodcast.php',
'StationPodcastPeer' => 'airtime/StationPodcastPeer.php',
'StationPodcastQuery' => 'airtime/StationPodcastQuery.php',
'StationPodcastTableMap' => 'airtime/map/StationPodcastTableMap.php',
'ThirdPartyTrackReferences' => 'airtime/ThirdPartyTrackReferences.php',
'ThirdPartyTrackReferencesPeer' => 'airtime/ThirdPartyTrackReferencesPeer.php',
'ThirdPartyTrackReferencesQuery' => 'airtime/ThirdPartyTrackReferencesQuery.php',
'ThirdPartyTrackReferencesTableMap' => 'airtime/map/ThirdPartyTrackReferencesTableMap.php',
];

View File

@ -6,20 +6,22 @@
require_once __DIR__ . '/constants.php';
class Config {
private static $CC_CONFIG = null;
class Config
{
private static $CC_CONFIG;
private static $rootDir;
public static function loadConfig() {
self::$rootDir = __DIR__."/../..";
$CC_CONFIG = array(
/* ================================================ storage configuration */
"rootDir" => self::$rootDir
);
public static function loadConfig()
{
self::$rootDir = __DIR__ . '/../..';
$CC_CONFIG = [
// ================================================ storage configuration
'rootDir' => self::$rootDir,
];
//In the unit testing environment, LIBRETIME_CONF_DIR will our local airtime.conf in legacy/application/test/conf:
$filename = isset($_SERVER['AIRTIME_CONF']) ? $_SERVER['AIRTIME_CONF'] : LIBRETIME_CONF_DIR . "/airtime.conf";
$filename = isset($_SERVER['AIRTIME_CONF']) ? $_SERVER['AIRTIME_CONF'] : LIBRETIME_CONF_DIR . '/airtime.conf';
$values = parse_ini_file($filename, true);
// Name of the web server user
@ -31,7 +33,7 @@ class Config {
$CC_CONFIG['basePort'] = $values['general']['base_port'];
$CC_CONFIG['stationId'] = $values['general']['station_id'];
$CC_CONFIG['phpDir'] = $values['general']['airtime_dir'];
$CC_CONFIG['forceSSL'] = isset($values['general']['force_ssl']) ? Config::isYesValue($values['general']['force_ssl']) : FALSE;
$CC_CONFIG['forceSSL'] = isset($values['general']['force_ssl']) ? Config::isYesValue($values['general']['force_ssl']) : false;
$CC_CONFIG['protocol'] = isset($values['general']['protocol']) ? $values['general']['protocol'] : '';
if (isset($values['general']['dev_env'])) {
$CC_CONFIG['dev_env'] = $values['general']['dev_env'];
@ -53,10 +55,10 @@ class Config {
// Tells us where file uploads will be uploaded to.
// It will either be set to a cloud storage backend or local file storage.
$CC_CONFIG["current_backend"] = $values["current_backend"]["storage_backend"];
$CC_CONFIG['current_backend'] = $values['current_backend']['storage_backend'];
$CC_CONFIG['cache_ahead_hours'] = $values['general']['cache_ahead_hours'];
// Database config
$CC_CONFIG['dsn']['username'] = $values['database']['dbuser'];
$CC_CONFIG['dsn']['password'] = $values['database']['dbpass'];
@ -64,7 +66,7 @@ class Config {
$CC_CONFIG['dsn']['phptype'] = 'pgsql';
$CC_CONFIG['dsn']['database'] = $values['database']['dbname'];
$CC_CONFIG['apiKey'] = array($values['general']['api_key']);
$CC_CONFIG['apiKey'] = [$values['general']['api_key']];
if (isset($values['facebook']['facebook_app_id'])) {
$CC_CONFIG['facebook-app-id'] = $values['facebook']['facebook_app_id'];
@ -87,35 +89,44 @@ class Config {
$CC_CONFIG['ldap_filter_field'] = $values['ldap']['filter_field'];
}
if(isset($values['demo']['demo'])){
if (isset($values['demo']['demo'])) {
$CC_CONFIG['demo'] = $values['demo']['demo'];
}
self::$CC_CONFIG = $CC_CONFIG;
}
public static function setAirtimeVersion() {
$version = @file_get_contents(self::$rootDir."/../VERSION");
public static function setAirtimeVersion()
{
$version = @file_get_contents(self::$rootDir . '/../VERSION');
if (!$version) {
// fallback to constant from constants.php if no other info is available
$version = LIBRETIME_MAJOR_VERSION;
}
self::$CC_CONFIG['airtime_version'] = trim($version);
}
public static function getConfig() {
public static function getConfig()
{
if (is_null(self::$CC_CONFIG)) {
self::loadConfig();
}
return self::$CC_CONFIG;
}
/**
* Check if the string is one of 'yes' or 'true' (case insensitive).
*
* @param mixed $value
*/
public static function isYesValue($value)
{
if (is_bool($value)) return $value;
if (!is_string($value)) return false;
if (is_bool($value)) {
return $value;
}
if (!is_string($value)) {
return false;
}
return in_array(strtolower($value), ['yes', 'true']);
}

View File

@ -7,21 +7,21 @@
* along with steps to fix them if they're not found or misconfigured.
*/
$phpDependencies = checkPhpDependencies();
$externalServices = checkExternalServices();
$postgres = $phpDependencies["postgres"];
$phpDependencies = checkPhpDependencies();
$externalServices = checkExternalServices();
$postgres = $phpDependencies['postgres'];
$database = $externalServices["database"];
$rabbitmq = $externalServices["rabbitmq"];
$database = $externalServices['database'];
$rabbitmq = $externalServices['rabbitmq'];
$pypo = $externalServices["pypo"];
$liquidsoap = $externalServices["liquidsoap"];
$analyzer = $externalServices["analyzer"];
$celery = $externalServices['celery'];
$api = $externalServices['api'];
$pypo = $externalServices['pypo'];
$liquidsoap = $externalServices['liquidsoap'];
$analyzer = $externalServices['analyzer'];
$celery = $externalServices['celery'];
$api = $externalServices['api'];
$r1 = array_reduce($phpDependencies, "booleanReduce", true);
$r2 = array_reduce($externalServices, "booleanReduce", true);
$r1 = array_reduce($phpDependencies, 'booleanReduce', true);
$r2 = array_reduce($externalServices, 'booleanReduce', true);
$result = $r1 && $r2;
?>
<html>
@ -100,20 +100,21 @@ $result = $r1 && $r2;
PHP Dependencies
</caption>
<tbody>
<tr class="<?=$postgres ? 'success' : 'danger';?>">
<tr class="<?php echo $postgres ? 'success' : 'danger'; ?>">
<td class="component">
Postgres
</td>
<td class="description">
PDO and PostgreSQL libraries
</td>
<td class="solution <?php if ($postgres) {echo 'check';?>">
<td class="solution <?php if ($postgres) {
echo 'check'; ?>">
<?php
} else {
?>">
} else {
?>">
Try running <code>sudo apt-get install php5-pgsql</code>
<?php
}
}
?>
</td>
</tr>
@ -125,33 +126,35 @@ $result = $r1 && $r2;
External Services
</caption>
<tbody>
<tr class="<?=$database ? 'success' : 'danger';?>">
<tr class="<?php echo $database ? 'success' : 'danger'; ?>">
<td class="component">
Database
</td>
<td class="description">
Database configuration for Airtime
</td>
<td class="solution <?php if ($database) {echo 'check';?>">
<td class="solution <?php if ($database) {
echo 'check'; ?>">
<?php
} else {
?>">
} else {
?>">
Make sure you aren't missing any of the Postgres dependencies in the table above.
If your dependencies check out, make sure your database configuration settings in
<code>/etc/airtime.conf</code> are correct and the Airtime database was installed correctly.
<?php
}
}
?>
</td>
</tr>
<tr class="<?=$rabbitmq ? 'success' : 'danger';?>">
<tr class="<?php echo $rabbitmq ? 'success' : 'danger'; ?>">
<td class="component">
RabbitMQ
</td>
<td class="description">
RabbitMQ configuration for Airtime
</td>
<td class="solution <?php if ($rabbitmq) {echo 'check';?>">
<td class="solution <?php if ($rabbitmq) {
echo 'check'; ?>">
<?php
} else {
?>">
@ -164,101 +167,106 @@ $result = $r1 && $r2;
?>
</td>
</tr>
<tr class="<?=$analyzer ? 'success' : 'danger';?>">
<tr class="<?php echo $analyzer ? 'success' : 'danger'; ?>">
<td class="component">
Media Analyzer
</td>
<td class="description">
<?php echo _("LibreTime media analyzer service") ?>
<?php echo _('LibreTime media analyzer service'); ?>
</td>
<td class="solution <?php if ($analyzer) {echo 'check';?>">
<td class="solution <?php if ($analyzer) {
echo 'check'; ?>">
<?php
} else {
?>">
<?php echo _("Check that the libretime-analyzer service is installed correctly in ") ?><code>/etc/systemd/system/</code>,
<?php echo _(" and ensure that it's running with ") ?>
<?php echo _('Check that the libretime-analyzer service is installed correctly in '); ?><code>/etc/systemd/system/</code>,
<?php echo _(" and ensure that it's running with "); ?>
<br/><code>systemctl status libretime-analyzer</code><br/>
<?php echo _("If not, try ") ?><br/><code>sudo systemctl restart libretime-analyzer</code>
<?php echo _('If not, try '); ?><br/><code>sudo systemctl restart libretime-analyzer</code>
<?php
}
?>
</td>
</tr>
<tr class="<?=$pypo ? 'success' : 'danger';?>">
<tr class="<?php echo $pypo ? 'success' : 'danger'; ?>">
<td class="component">
Pypo
</td>
<td class="description">
<?php echo _("LibreTime playout service") ?>
<?php echo _('LibreTime playout service'); ?>
</td>
<td class="solution <?php if ($pypo) {echo 'check';?>">
<td class="solution <?php if ($pypo) {
echo 'check'; ?>">
<?php
} else {
?>">
<?php echo _("Check that the libretime-playout service is installed correctly in ") ?><code>/etc/systemd/system/</code>,
<?php echo _(" and ensure that it's running with ") ?>
<?php echo _('Check that the libretime-playout service is installed correctly in '); ?><code>/etc/systemd/system/</code>,
<?php echo _(" and ensure that it's running with "); ?>
<br/><code>systemctl status libretime-playout</code><br/>
<?php echo _("If not, try ") ?><br/><code>sudo systemctl restart libretime-playout</code>
<?php echo _('If not, try '); ?><br/><code>sudo systemctl restart libretime-playout</code>
<?php
}
?>
</td>
</tr>
<tr class="<?=$liquidsoap ? 'success' : 'danger';?>">
<tr class="<?php echo $liquidsoap ? 'success' : 'danger'; ?>">
<td class="component">
Liquidsoap
</td>
<td class="description">
<?php echo _("LibreTime liquidsoap service") ?>
<?php echo _('LibreTime liquidsoap service'); ?>
</td>
<td class="solution <?php if ($liquidsoap) {echo 'check';?>" >
<td class="solution <?php if ($liquidsoap) {
echo 'check'; ?>" >
<?php
} else {
?>">
<?php echo _("Check that the libretime-liquidsoap service is installed correctly in ") ?><code>/etc/systemd/system/</code>,
<?php echo _(" and ensure that it's running with ") ?>
<?php echo _('Check that the libretime-liquidsoap service is installed correctly in '); ?><code>/etc/systemd/system/</code>,
<?php echo _(" and ensure that it's running with "); ?>
<br/><code>systemctl status libretime-liquidsoap</code><br/>
<?php echo _("If not, try ") ?><br/><code>sudo systemctl restart libretime-liquidsoap</code>
<?php echo _('If not, try '); ?><br/><code>sudo systemctl restart libretime-liquidsoap</code>
<?php
}
?>
</td>
</tr>
<tr class="<?=$celery ? 'success' : 'danger';?>">
<tr class="<?php echo $celery ? 'success' : 'danger'; ?>">
<td class="component">
Celery
</td>
<td class="description">
<?php echo _("LibreTime Celery Task service") ?>
<?php echo _('LibreTime Celery Task service'); ?>
</td>
<td class="solution <?php if ($celery) {echo 'check';?>" >
<td class="solution <?php if ($celery) {
echo 'check'; ?>" >
<?php
} else {
?>">
<?php echo _("Check that the libretime-celery service is installed correctly in ") ?><code>/etc/systemd/system/</code>,
<?php echo _(" and ensure that it's running with ") ?>
<?php echo _('Check that the libretime-celery service is installed correctly in '); ?><code>/etc/systemd/system/</code>,
<?php echo _(" and ensure that it's running with "); ?>
<br/><code>systemctl status libretime-celery</code><br/>
<?php echo _("If not, try ") ?><br/><code>sudo systemctl restart libretime-celery</code>
<?php echo _('If not, try '); ?><br/><code>sudo systemctl restart libretime-celery</code>
<?php
}
?>
</td>
</tr>
<tr class="<?=$api ? 'success' : 'danger';?>">
<tr class="<?php echo $api ? 'success' : 'danger'; ?>">
<td class="component">
API
</td>
<td class="description">
<?php echo _("LibreTime API service") ?>
<?php echo _('LibreTime API service'); ?>
</td>
<td class="solution <?php if ($api) {echo 'check';?>" >
<td class="solution <?php if ($api) {
echo 'check'; ?>" >
<?php
} else {
?>">
<?php echo _("Check that the libretime-api service is installed correctly in ") ?><code>/etc/init.d/</code>,
<?php echo _(" and ensure that it's running with ") ?>
<?php echo _('Check that the libretime-api service is installed correctly in '); ?><code>/etc/init.d/</code>,
<?php echo _(" and ensure that it's running with "); ?>
<br/><code>systemctl status libretime-api</code><br/>
<?php echo _("If not, try ") ?><br/><code>sudo systemctl restart libretime-api</code>
<?php echo _('If not, try '); ?><br/><code>sudo systemctl restart libretime-api</code>
<?php
}
?>
@ -277,7 +285,7 @@ $result = $r1 && $r2;
$first = true;
foreach ($extensions as $ext) {
if (!$first) {
echo " | ";
echo ' | ';
} else {
$first = false;
}

View File

@ -1,36 +1,36 @@
<?php
define('PRODUCT_NAME' , 'LibreTime');
define('PRODUCT_SITE_URL' , 'http://libretime.org');
define('PRODUCT_NAME', 'LibreTime');
define('PRODUCT_SITE_URL', 'http://libretime.org');
define('SAAS_PRODUCT_BRANDING_NAME', 'LibreTime');
define('SAAS_LOGIN_REFERRER', 'http://libretime.org');
define('COMPANY_NAME' , 'LibreTime Community');
define('COMPANY_SUFFIX' , '');
define('COMPANY_SITE' , 'libretime.org');
define('COMPANY_SITE_URL' , 'http://libretime.org');
define('SUPPORT_ADDRESS' , 'https://discourse.libretime.org/');
define('COMPANY_NAME', 'LibreTime Community');
define('COMPANY_SUFFIX', '');
define('COMPANY_SITE', 'libretime.org');
define('COMPANY_SITE_URL', 'http://libretime.org');
define('SUPPORT_ADDRESS', 'https://discourse.libretime.org/');
define('HELP_URL' , 'https://discourse.libretime.org/');
define('WHOS_USING_URL' , 'https://github.com/orgs/LibreTime/people');
define('TERMS_AND_CONDITIONS_URL' , 'https://github.com/LibreTime/libretime/blob/master/README.md');
define('PRIVACY_POLICY_URL' , 'https://github.com/LibreTime/code-of-conduct/blob/master/CODE_OF_CONDUCT.md');
define('USER_MANUAL_URL' , 'http://libretime.org/docs');
define('ABOUT_AIRTIME_URL' , 'http://libretime.org');
define('LIBRETIME_CONTRIBUTE_URL' , 'https://libretime.org/contribute');
define('LIBRETIME_DISCOURSE_URL' , 'https://discourse.libretime.org');
define('UI_REVAMP_EMBED_URL' , 'https://www.youtube.com/embed/nqpNnCKGluY');
define('LIBRETIME_WHATS_NEW_URL' , 'https://github.com/LibreTime/libretime/releases');
define('LIBRETIME_UPDATE_FEED' , 'https://github.com/LibreTime/libretime/releases.atom');
define('LIBRETIME_EMAIL_FROM' , 'noreply@libretime.org');
define('HELP_URL', 'https://discourse.libretime.org/');
define('WHOS_USING_URL', 'https://github.com/orgs/LibreTime/people');
define('TERMS_AND_CONDITIONS_URL', 'https://github.com/LibreTime/libretime/blob/master/README.md');
define('PRIVACY_POLICY_URL', 'https://github.com/LibreTime/code-of-conduct/blob/master/CODE_OF_CONDUCT.md');
define('USER_MANUAL_URL', 'http://libretime.org/docs');
define('ABOUT_AIRTIME_URL', 'http://libretime.org');
define('LIBRETIME_CONTRIBUTE_URL', 'https://libretime.org/contribute');
define('LIBRETIME_DISCOURSE_URL', 'https://discourse.libretime.org');
define('UI_REVAMP_EMBED_URL', 'https://www.youtube.com/embed/nqpNnCKGluY');
define('LIBRETIME_WHATS_NEW_URL', 'https://github.com/LibreTime/libretime/releases');
define('LIBRETIME_UPDATE_FEED', 'https://github.com/LibreTime/libretime/releases.atom');
define('LIBRETIME_EMAIL_FROM', 'noreply@libretime.org');
define('LICENSE_VERSION' , 'GNU AGPL v.3');
define('LICENSE_URL' , 'http://www.gnu.org/licenses/agpl-3.0-standalone.html');
define('LICENSE_VERSION', 'GNU AGPL v.3');
define('LICENSE_URL', 'http://www.gnu.org/licenses/agpl-3.0-standalone.html');
define('AIRTIME_COPYRIGHT_DATE' , '2010-2015');
define('AIRTIME_REST_VERSION' , '1.1');
define('AIRTIME_API_VERSION' , '1.1');
define('AIRTIME_COPYRIGHT_DATE', '2010-2015');
define('AIRTIME_REST_VERSION', '1.1');
define('AIRTIME_API_VERSION', '1.1');
// XXX: it's important that we upgrade this on major version bumps, usually users get more exact info from VERSION in airtime root dir
define('LIBRETIME_MAJOR_VERSION', '3');
@ -49,48 +49,48 @@ define('DEFAULT_SHOW_COLOR', '76aca5');
define('DEFAULT_INTERVAL_FORMAT', 'H:i:s.u');
// Metadata Keys for files
define('MDATA_KEY_FILEPATH' , 'filepath');
define('MDATA_KEY_DIRECTORY' , 'directory');
define('MDATA_KEY_MD5' , 'md5');
define('MDATA_KEY_TITLE' , 'track_title');
define('MDATA_KEY_CREATOR' , 'artist_name');
define('MDATA_KEY_SOURCE' , 'album_title');
define('MDATA_KEY_DURATION' , 'length');
define('MDATA_KEY_MIME' , 'mime');
define('MDATA_KEY_FTYPE' , 'ftype');
define('MDATA_KEY_URL' , 'info_url');
define('MDATA_KEY_GENRE' , 'genre');
define('MDATA_KEY_MOOD' , 'mood');
define('MDATA_KEY_LABEL' , 'label');
define('MDATA_KEY_COMPOSER' , 'composer');
define('MDATA_KEY_DESCRIPTION' , 'description');
define('MDATA_KEY_SAMPLERATE' , 'sample_rate');
define('MDATA_KEY_BITRATE' , 'bit_rate');
define('MDATA_KEY_ENCODER' , 'encoded_by');
define('MDATA_KEY_ISRC' , 'isrc_number');
define('MDATA_KEY_COPYRIGHT' , 'copyright');
define('MDATA_KEY_YEAR' , 'year');
define('MDATA_KEY_BPM' , 'bpm');
define('MDATA_KEY_TRACKNUMBER' , 'track_number');
define('MDATA_KEY_CONDUCTOR' , 'conductor');
define('MDATA_KEY_LANGUAGE' , 'language');
define('MDATA_KEY_REPLAYGAIN' , 'replay_gain');
define('MDATA_KEY_OWNER_ID' , 'owner_id');
define('MDATA_KEY_CUE_IN' , 'cuein');
define('MDATA_KEY_CUE_OUT' , 'cueout');
define('MDATA_KEY_ARTWORK' , 'artwork');
define('MDATA_KEY_FILEPATH', 'filepath');
define('MDATA_KEY_DIRECTORY', 'directory');
define('MDATA_KEY_MD5', 'md5');
define('MDATA_KEY_TITLE', 'track_title');
define('MDATA_KEY_CREATOR', 'artist_name');
define('MDATA_KEY_SOURCE', 'album_title');
define('MDATA_KEY_DURATION', 'length');
define('MDATA_KEY_MIME', 'mime');
define('MDATA_KEY_FTYPE', 'ftype');
define('MDATA_KEY_URL', 'info_url');
define('MDATA_KEY_GENRE', 'genre');
define('MDATA_KEY_MOOD', 'mood');
define('MDATA_KEY_LABEL', 'label');
define('MDATA_KEY_COMPOSER', 'composer');
define('MDATA_KEY_DESCRIPTION', 'description');
define('MDATA_KEY_SAMPLERATE', 'sample_rate');
define('MDATA_KEY_BITRATE', 'bit_rate');
define('MDATA_KEY_ENCODER', 'encoded_by');
define('MDATA_KEY_ISRC', 'isrc_number');
define('MDATA_KEY_COPYRIGHT', 'copyright');
define('MDATA_KEY_YEAR', 'year');
define('MDATA_KEY_BPM', 'bpm');
define('MDATA_KEY_TRACKNUMBER', 'track_number');
define('MDATA_KEY_CONDUCTOR', 'conductor');
define('MDATA_KEY_LANGUAGE', 'language');
define('MDATA_KEY_REPLAYGAIN', 'replay_gain');
define('MDATA_KEY_OWNER_ID', 'owner_id');
define('MDATA_KEY_CUE_IN', 'cuein');
define('MDATA_KEY_CUE_OUT', 'cueout');
define('MDATA_KEY_ARTWORK', 'artwork');
define('MDATA_KEY_ARTWORK_DATA', 'artwork_data');
define('MDATA_KEY_TRACK_TYPE' , 'track_type');
define('MDATA_KEY_TRACK_TYPE', 'track_type');
define('UI_MDATA_VALUE_FORMAT_FILE' , 'File');
define('UI_MDATA_VALUE_FORMAT_STREAM' , 'live stream');
define('UI_MDATA_VALUE_FORMAT_FILE', 'File');
define('UI_MDATA_VALUE_FORMAT_STREAM', 'live stream');
//User types
define('UTYPE_HOST' , 'H');
define('UTYPE_ADMIN' , 'A');
define('UTYPE_SUPERADMIN' , 'S');
define('UTYPE_GUEST' , 'G');
define('UTYPE_PROGRAM_MANAGER' , 'P');
define('UTYPE_HOST', 'H');
define('UTYPE_ADMIN', 'A');
define('UTYPE_SUPERADMIN', 'S');
define('UTYPE_GUEST', 'G');
define('UTYPE_PROGRAM_MANAGER', 'P');
//Constants for playout history template fields
define('TEMPLATE_DATE', 'date');
@ -110,7 +110,7 @@ define('UI_BLOCK_SESSNAME', 'BLOCK');*/
define('SENTRY_CONFIG_PATH', LIBRETIME_CONF_DIR . '/sentry.airtime_web.ini');
//TuneIn integration
define("TUNEIN_API_URL", "http://air.radiotime.com/Playing.ashx");
define('TUNEIN_API_URL', 'http://air.radiotime.com/Playing.ashx');
// Celery
define('CELERY_PENDING_STATUS', 'PENDING');

View File

@ -5,6 +5,6 @@
* yet available because airtime.conf hasn't been updated yet. This situation ends up throwing a lot of errors to stdout.
* airtime*/
require_once("conf.php");
require_once 'conf.php';
$CC_CONFIG = Config::getConfig();

View File

@ -1,6 +1,6 @@
<?php
/**
* Navigation container (config/array)
* Navigation container (config/array).
*
* Each element in the array will be passed to
* Zend_Navigation_Page::factory() when constructing
@ -12,7 +12,7 @@
* strings stay plain en for now. They get retranslated
* in the menu.phtml script when they are output.
*/
$pages = array();
$pages = [];
// Disable My podcasts
// See https://github.com/LibreTime/libretime/issues/1320
// $pages[] = array(
@ -23,175 +23,173 @@ $pages = array();
// 'resource' => 'podcast',
// 'class' => '<i class="icon-music icon-white"></i>'
// );
$pages[] = array(
'label' => _('Radio Page'),
'uri' => '/',
'resource' => '',
'class' => '<i class="icon-globe icon-white"></i>',
'pages' => array(),
'visible' => false
);
$pages[] = array(
'label' => _('Calendar'),
'module' => 'default',
$pages[] = [
'label' => _('Radio Page'),
'uri' => '/',
'resource' => '',
'class' => '<i class="icon-globe icon-white"></i>',
'pages' => [],
'visible' => false,
];
$pages[] = [
'label' => _('Calendar'),
'module' => 'default',
'controller' => 'schedule',
'action' => 'index',
'resource' => 'schedule',
'class' => '<i class="icon-calendar icon-white"></i>'
);
$pages[] = array(
'label' => _('Widgets'),
'module' => 'default',
'action' => 'index',
'resource' => 'schedule',
'class' => '<i class="icon-calendar icon-white"></i>',
];
$pages[] = [
'label' => _('Widgets'),
'module' => 'default',
'controller' => 'embeddablewidgets',
'action' => 'player',
'resource' => 'embeddablewidgets',
'class' => '<i class="icon-wrench icon-white"></i>',
'action' => 'player',
'resource' => 'embeddablewidgets',
'class' => '<i class="icon-wrench icon-white"></i>',
'title' => 'Widgets',
'pages' => array(
array(
'label' => _('Player'),
'module' => 'default',
'pages' => [
[
'label' => _('Player'),
'module' => 'default',
'controller' => 'embeddablewidgets',
'action' => 'player',
),
array(
'label' => _('Weekly Schedule'),
'module' => 'default',
'action' => 'player',
],
[
'label' => _('Weekly Schedule'),
'module' => 'default',
'controller' => 'embeddablewidgets',
'action' => 'schedule',
)
)
);
$pages[] = array(
'label' => _("Settings"),
'action' => 'schedule',
],
],
];
$pages[] = [
'label' => _('Settings'),
'action' => 'edit-user',
'module' => 'default',
'controller' => 'user',
'class' => '<i class="icon-cog icon-white"></i>',
'title' => 'Settings',
'pages' => array(
array(
'label' => _('General'),
'module' => 'default',
'pages' => [
[
'label' => _('General'),
'module' => 'default',
'controller' => 'preference',
'resource' => 'preference'
),
array(
'resource' => 'preference',
],
[
'label' => _('My Profile'),
'controller' => 'user',
'action' => 'edit-user'
),
array(
'label' => _('Users'),
'module' => 'default',
'action' => 'edit-user',
],
[
'label' => _('Users'),
'module' => 'default',
'controller' => 'user',
'action' => 'add-user',
'resource' => 'user'
),array(
'label' => _('Track Types'),
'module' => 'default',
'action' => 'add-user',
'resource' => 'user',
], [
'label' => _('Track Types'),
'module' => 'default',
'controller' => 'tracktype',
'action' => 'add-tracktype',
'resource' => 'tracktype'
),
array(
'label' => _('Streams'),
'module' => 'default',
'action' => 'add-tracktype',
'resource' => 'tracktype',
],
[
'label' => _('Streams'),
'module' => 'default',
'controller' => 'preference',
'action' => 'stream-setting',
'resource' => 'preference'
),
array(
'label' => _('Status'),
'module' => 'default',
'action' => 'stream-setting',
'resource' => 'preference',
],
[
'label' => _('Status'),
'module' => 'default',
'controller' => 'systemstatus',
'action' => 'index',
'resource' => 'systemstatus'
),
)
);
$pages[] = array(
'label' => _("Analytics"),
'module' => 'default',
'action' => 'index',
'resource' => 'systemstatus',
],
],
];
$pages[] = [
'label' => _('Analytics'),
'module' => 'default',
'controller' => 'playouthistory',
'action' => 'index',
'resource' => 'playouthistory',
'class' => '<i class="icon-signal icon-white"></i>',
'action' => 'index',
'resource' => 'playouthistory',
'class' => '<i class="icon-signal icon-white"></i>',
'title' => 'Analytics',
'pages' => array(
array(
'label' => _('Playout History'),
'module' => 'default',
'pages' => [
[
'label' => _('Playout History'),
'module' => 'default',
'controller' => 'playouthistory',
'action' => 'index',
'resource' => 'playouthistory'
),
array(
'label' => _('History Templates'),
'module' => 'default',
'action' => 'index',
'resource' => 'playouthistory',
],
[
'label' => _('History Templates'),
'module' => 'default',
'controller' => 'playouthistorytemplate',
'action' => 'index',
'resource' => 'playouthistorytemplate'
),
array(
'label' => _('Listener Stats'),
'module' => 'default',
'action' => 'index',
'resource' => 'playouthistorytemplate',
],
[
'label' => _('Listener Stats'),
'module' => 'default',
'controller' => 'listenerstat',
'action' => 'index',
'resource' => 'listenerstat'
),
array(
'label' => _('Show Listener Stats'),
'module' => 'default',
'action' => 'index',
'resource' => 'listenerstat',
],
[
'label' => _('Show Listener Stats'),
'module' => 'default',
'controller' => 'listenerstat',
'action' => 'show',
'resource' => 'showlistenerstat'
),
)
);
$pages[] = array(
'label' => _('Help'),
'action' => 'show',
'resource' => 'showlistenerstat',
],
],
];
$pages[] = [
'label' => _('Help'),
'controller' => 'dashboard',
'action' => 'help',
'resource' => 'dashboard',
'class' => '<i class="icon-question-sign icon-white"></i>',
'title' => 'Help',
'pages' => array(
array(
'label' => _('Getting Started'),
'module' => 'default',
'action' => 'help',
'resource' => 'dashboard',
'class' => '<i class="icon-question-sign icon-white"></i>',
'title' => 'Help',
'pages' => [
[
'label' => _('Getting Started'),
'module' => 'default',
'controller' => 'dashboard',
'action' => 'help',
'resource' => 'dashboard'
),
array(
'label' => _('User Manual'),
'uri' => USER_MANUAL_URL,
'target' => "_blank"
),
array(
'label' => _('Get Help Online'),
'uri' => LIBRETIME_DISCOURSE_URL,
'target' => "_blank"
),
array(
'label' => _('Contribute to LibreTime'),
'uri' => LIBRETIME_CONTRIBUTE_URL,
'target' => "_blank"
),
array(
'label' => _('What\'s New?'),
'uri' => LIBRETIME_WHATS_NEW_URL,
'target' => "_blank"
)
)
);
'action' => 'help',
'resource' => 'dashboard',
],
[
'label' => _('User Manual'),
'uri' => USER_MANUAL_URL,
'target' => '_blank',
],
[
'label' => _('Get Help Online'),
'uri' => LIBRETIME_DISCOURSE_URL,
'target' => '_blank',
],
[
'label' => _('Contribute to LibreTime'),
'uri' => LIBRETIME_CONTRIBUTE_URL,
'target' => '_blank',
],
[
'label' => _('What\'s New?'),
'uri' => LIBRETIME_WHATS_NEW_URL,
'target' => '_blank',
],
],
];
// Create container from array
$container = new Zend_Navigation($pages);
$container->id = "nav";
$container->id = 'nav';
//store it in the registry:
Zend_Registry::set('Zend_Navigation', $container);

File diff suppressed because it is too large Load Diff

View File

@ -6,11 +6,12 @@ class AudiopreviewController extends Zend_Controller_Action
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('show-preview', 'json')
->addActionContext('audio-preview', 'json')
->addActionContext('get-show', 'json')
->addActionContext('playlist-preview', 'json')
->addActionContext('get-playlist', 'json')
->initContext();
->addActionContext('audio-preview', 'json')
->addActionContext('get-show', 'json')
->addActionContext('playlist-preview', 'json')
->addActionContext('get-playlist', 'json')
->initContext()
;
}
/**
@ -21,50 +22,51 @@ class AudiopreviewController extends Zend_Controller_Action
{
$CC_CONFIG = Config::getConfig();
$audioFileID = $this->_getParam('audioFileID');
$audioFileID = $this->_getParam('audioFileID');
$type = $this->_getParam('type');
$baseUrl = Application_Common_OsPath::getBaseDir();
$this->view->headScript()->appendFile(
$baseUrl.'js/airtime/audiopreview/preview_jplayer.js?'.$CC_CONFIG['airtime_version'],
'text/javascript');
$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');
$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']);
$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";
$this->view->logo = "data:image/png;base64,{$logo}";
} else {
$this->view->logo = $baseUrl."css/images/airtime_logo_jp.png";
$this->view->logo = $baseUrl . 'css/images/airtime_logo_jp.png';
}
if ($type == "audioclip") {
if ($type == 'audioclip') {
$media = Application_Model_StoredFile::RecallById($audioFileID);
$uri = $baseUrl."api/get-media/file/".$audioFileID;
$mime = $media->getPropelOrm()->getDbMime();
$uri = $baseUrl . 'api/get-media/file/' . $audioFileID;
$mime = $media->getPropelOrm()->getDbMime();
$this->view->audioFileArtist = htmlspecialchars($media->getPropelOrm()->getDbArtistName());
$this->view->audioFileTitle = htmlspecialchars($media->getPropelOrm()->getDbTrackTitle());
} elseif ($type == "stream") {
$this->view->audioFileTitle = htmlspecialchars($media->getPropelOrm()->getDbTrackTitle());
} elseif ($type == 'stream') {
$webstream = CcWebstreamQuery::create()->findPk($audioFileID);
$uri = $webstream->getDbUrl();
$mime = $webstream->getDbMime();
$this->view->audioFileTitle = htmlspecialchars($webstream->getDbName());
$uri = $webstream->getDbUrl();
$mime = $webstream->getDbMime();
$this->view->audioFileTitle = htmlspecialchars($webstream->getDbName());
} else {
throw new Exception("Unknown type for audio preview!.Type=$type");
throw new Exception("Unknown type for audio preview!.Type={$type}");
}
$this->view->uri = $uri;
$this->view->mime = $mime;
$this->view->audioFileID = $audioFileID;
$this->view->uri = $uri;
$this->view->mime = $mime;
$this->view->audioFileID = $audioFileID;
$this->view->type = $type;
$this->view->type = $type;
$this->_helper->viewRenderer->setRender('audio-preview');
}
@ -82,18 +84,18 @@ class AudiopreviewController extends Zend_Controller_Action
$baseUrl = Application_Common_OsPath::getBaseDir();
$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->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";
$this->view->logo = "data:image/png;base64,{$logo}";
} else {
$this->view->logo = $baseUrl."css/images/airtime_logo_jp.png";
$this->view->logo = $baseUrl . 'css/images/airtime_logo_jp.png';
}
$this->view->playlistIndex= $playlistIndex;
$this->view->playlistIndex = $playlistIndex;
$this->view->playlistID = $playlistID;
$this->_helper->viewRenderer->setRender('audio-preview');
@ -108,22 +110,23 @@ class AudiopreviewController extends Zend_Controller_Action
$baseUrl = Application_Common_OsPath::getBaseDir();
$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->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";
$this->view->logo = "data:image/png;base64,{$logo}";
} else {
$this->view->logo = $baseUrl."css/images/airtime_logo_jp.png";
$this->view->logo = $baseUrl . 'css/images/airtime_logo_jp.png';
}
$this->view->blockIndex= $blockIndex;
$this->view->blockIndex = $blockIndex;
$this->view->blockId = $blockId;
$this->_helper->viewRenderer->setRender('audio-preview');
}
public function getBlockAction()
{
// disable the view and the layout
@ -137,12 +140,13 @@ class AudiopreviewController extends Zend_Controller_Action
}
$bl = new Application_Model_Block($blockId);
$result = array();
$result = [];
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.
*/
@ -159,7 +163,7 @@ class AudiopreviewController extends Zend_Controller_Action
}
$pl = new Application_Model_Playlist($playlistID);
$result = Array();
$result = [];
foreach ($pl->getContents(true) as $ele) {
if ($ele['type'] == 2) {
@ -181,12 +185,12 @@ class AudiopreviewController extends Zend_Controller_Action
{
$baseUrl = Application_Common_OsPath::getBaseDir();
$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']:""
);
$elementMap = ['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
@ -199,13 +203,14 @@ class AudiopreviewController extends Zend_Controller_Action
if ($track['type'] == 0) {
$mime = trim(strtolower($track['mime']));
try {
$elementMap['element_' . FileDataHelper::getAudioMimeTypeArray()[$mime]] = $track['item_id'];
} catch (Exception $e) {
throw new Exception("Unknown file type: $mime");
throw new Exception("Unknown file type: {$mime}");
}
$elementMap['uri'] = $baseUrl."api/get-media/file/".$track['item_id'];
$elementMap['uri'] = $baseUrl . 'api/get-media/file/' . $track['item_id'];
} else {
$elementMap['uri'] = $track['path'];
}
@ -226,16 +231,16 @@ class AudiopreviewController extends Zend_Controller_Action
$baseUrl = Application_Common_OsPath::getBaseDir();
$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->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";
$this->view->logo = "data:image/png;base64,{$logo}";
} 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;
@ -261,28 +266,28 @@ class AudiopreviewController extends Zend_Controller_Action
}
$showInstance = new Application_Model_ShowInstance($showID);
$result = array();
$result = [];
$position = 0;
foreach ($showInstance->getShowListContent() as $track) {
$elementMap = array(
'element_title' => isset($track['track_title']) ? $track['track_title'] : "",
'element_artist' => isset($track['creator']) ? $track['creator'] : "",
$elementMap = [
'element_title' => isset($track['track_title']) ? $track['track_title'] : '',
'element_artist' => isset($track['creator']) ? $track['creator'] : '',
'element_position' => $position,
'element_id' => ++$position,
'mime' => isset($track['mime'])?$track['mime']:""
);
'mime' => isset($track['mime']) ? $track['mime'] : '',
];
$elementMap['type'] = $track['type'];
if ($track['type'] == 0) {
$mime = trim(strtolower($track['mime']));
try {
$elementMap['element_' . FileDataHelper::getAudioMimeTypeArray()[$mime]] = $track['item_id'];
} catch (Exception $e) {
throw new Exception("Unknown file type: $mime");
throw new Exception("Unknown file type: {$mime}");
}
$elementMap['uri'] = $baseUrl."api/get-media/file/".$track['item_id'];
$elementMap['uri'] = $baseUrl . 'api/get-media/file/' . $track['item_id'];
} else {
$elementMap['uri'] = $track['filepath'];
}
@ -290,6 +295,5 @@ class AudiopreviewController extends Zend_Controller_Action
}
$this->_helper->json($result);
}
}

View File

@ -2,13 +2,13 @@
class DashboardController extends Zend_Controller_Action
{
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('switch-source', 'json')
->addActionContext('disconnect-source', 'json')
->initContext();
->addActionContext('disconnect-source', 'json')
->initContext()
;
}
public function indexAction()
@ -24,17 +24,17 @@ class DashboardController extends Zend_Controller_Action
$user = new Application_Model_User($userInfo->id);
$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);
if ($user->canSchedule($show_id) && $source_connected) {
$data = array("sourcename"=>$sourcename);
Application_Model_RabbitMq::SendMessageToPypo("disconnect_source", $data);
$data = ['sourcename' => $sourcename];
Application_Model_RabbitMq::SendMessageToPypo('disconnect_source', $data);
} else {
if ($source_connected) {
$this->view->error = _("You don't have permission to disconnect source.");
} else {
$this->view->error = _("There is no source connected to this input.");
$this->view->error = _('There is no source connected to this input.');
}
}
}
@ -48,33 +48,36 @@ class DashboardController extends Zend_Controller_Action
$user = new Application_Model_User($userInfo->id);
$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);
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") {
$change_status_to = "off";
if (strtolower($current_status) == 'on') {
$change_status_to = 'off';
}
$data = array("sourcename"=>$sourcename, "status"=>$change_status_to);
Application_Model_RabbitMq::SendMessageToPypo("switch_source", $data);
if (strtolower($current_status) == "on") {
Application_Model_Preference::SetSourceSwitchStatus($sourcename, "off");
$this->view->status = "OFF";
$data = ['sourcename' => $sourcename, 'status' => $change_status_to];
Application_Model_RabbitMq::SendMessageToPypo('switch_source', $data);
if (strtolower($current_status) == 'on') {
Application_Model_Preference::SetSourceSwitchStatus($sourcename, 'off');
$this->view->status = 'OFF';
//Log table updates
Application_Model_LiveLog::SetEndTime($sourcename == 'scheduled_play'?'S':'L',
new DateTime("now", new DateTimeZone('UTC')));
Application_Model_LiveLog::SetEndTime(
$sourcename == 'scheduled_play' ? 'S' : 'L',
new DateTime('now', new DateTimeZone('UTC'))
);
} else {
Application_Model_Preference::SetSourceSwitchStatus($sourcename, "on");
$this->view->status = "ON";
Application_Model_Preference::SetSourceSwitchStatus($sourcename, 'on');
$this->view->status = 'ON';
//Log table updates
Application_Model_LiveLog::SetNewLogTime($sourcename == 'scheduled_play'?'S':'L',
new DateTime("now", new DateTimeZone('UTC')));
Application_Model_LiveLog::SetNewLogTime(
$sourcename == 'scheduled_play' ? 'S' : 'L',
new DateTime('now', new DateTimeZone('UTC'))
);
}
} else {
if ($source_connected) {
@ -83,7 +86,7 @@ class DashboardController extends Zend_Controller_Action
if ($sourcename == 'scheduled_play') {
$this->view->error = _("You don't have permission to disconnect source.");
} else {
$this->view->error = _("There is no source connected to this input.");
$this->view->error = _('There is no source connected to this input.');
}
}
}
@ -95,11 +98,11 @@ class DashboardController extends Zend_Controller_Action
$baseUrl = Application_Common_OsPath::getBaseDir();
$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('livestream');
$logo = Application_Model_Preference::GetStationLogo();
$this->view->logo = "data:image/png;base64,".$logo;
$this->view->logo = 'data:image/png;base64,' . $logo;
}
public function helpAction()
@ -124,7 +127,6 @@ class DashboardController extends Zend_Controller_Action
$headScript = $this->view->headScript();
AirtimeTableView::injectTableJavaScriptDependencies($headScript, $baseUrl, $CC_CONFIG['airtime_version']);
$this->view->headScript()->appendFile($baseUrl.'js/airtime/widgets/table-example.js?'.$CC_CONFIG['airtime_version']);
$this->view->headScript()->appendFile($baseUrl . 'js/airtime/widgets/table-example.js?' . $CC_CONFIG['airtime_version']);
}
}

View File

@ -2,13 +2,15 @@
class EmbedController extends Zend_Controller_Action
{
public function init() {
public function init()
{
// translate widgets to station default language
$locale = Application_Model_Preference::GetDefaultLocale();
if ($locale) {
Application_Model_Locale::configureLocalization($locale);
}
}
/**
* This is the action that is called to insert the player onto a web page.
* It passes all the js and css files to the view, as well as all the
@ -25,45 +27,45 @@ class EmbedController extends Zend_Controller_Action
$request = $this->getRequest();
$this->view->playerhtml5_js = "/js/airtime/player/playerhtml5.js?".$CC_CONFIG['airtime_version'];
$this->view->jquery = "/js/libs/jquery-1.10.2.min.js";
$this->view->metadata_api_url = "/api/live-info";
$this->view->playerhtml5_js = '/js/airtime/player/playerhtml5.js?' . $CC_CONFIG['airtime_version'];
$this->view->jquery = '/js/libs/jquery-1.10.2.min.js';
$this->view->metadata_api_url = '/api/live-info';
$this->view->player_title = json_encode($this->view->escape($request->getParam('title')));
$this->view->jquery_i18n = "/js/i18n/jquery.i18n.js?";
$this->view->jquery_i18n = '/js/i18n/jquery.i18n.js?';
$styleParam = $request->getParam('style');
$player_style = isset($styleParam) ? $styleParam : "basic";
if ($player_style == "premium") {
$this->view->css = "/css/radio-page/premium_player.css?".$CC_CONFIG['airtime_version'];
$player_style = isset($styleParam) ? $styleParam : 'basic';
if ($player_style == 'premium') {
$this->view->css = '/css/radio-page/premium_player.css?' . $CC_CONFIG['airtime_version'];
} else {
$this->view->css = "/css/player.css?".$CC_CONFIG['airtime_version'];
$this->view->css = '/css/player.css?' . $CC_CONFIG['airtime_version'];
}
$this->view->player_style = $player_style;
$stream = $request->getParam('stream');
$streamData = Application_Model_StreamSetting::getEnabledStreamData();
$availableMobileStreams = array();
$availableDesktopStreams = array();
$availableMobileStreams = [];
$availableDesktopStreams = [];
if ($stream == "auto") {
$this->view->playerMode = "auto";
$this->view->streamURL = json_encode("");
if ($stream == 'auto') {
$this->view->playerMode = 'auto';
$this->view->streamURL = json_encode('');
foreach ($streamData as $s) {
if ($s["mobile"]) {
if ($s['mobile']) {
array_push($availableMobileStreams, $s);
} else if (!$s["mobile"]) {
} elseif (!$s['mobile']) {
array_push($availableDesktopStreams, $s);
}
}
} else if ($stream == "file") {
$this->view->playerMode = "file";
$this->view->streamURL = json_encode($request->getParam("file_url"));
$this->view->codec = $request->getParam("file_codec");
} elseif ($stream == 'file') {
$this->view->playerMode = 'file';
$this->view->streamURL = json_encode($request->getParam('file_url'));
$this->view->codec = $request->getParam('file_codec');
} elseif (!empty($stream)) {
$this->view->playerMode = "manual";
$this->view->playerMode = 'manual';
$selectedStreamData = $streamData[$stream];
$this->view->streamURL = json_encode($selectedStreamData["url"]);
$this->view->codec = $selectedStreamData["codec"];
$this->view->streamURL = json_encode($selectedStreamData['url']);
$this->view->codec = $selectedStreamData['codec'];
}
$this->view->availableMobileStreams = json_encode($availableMobileStreams);
$this->view->availableDesktopStreams = json_encode($availableDesktopStreams);
@ -77,23 +79,23 @@ class EmbedController extends Zend_Controller_Action
$request = $this->getRequest();
$this->view->angular = Application_Common_HTTPHelper::getStationUrl() . 'js/libs/angular.min.js?'.$CC_CONFIG['airtime_version'];
$this->view->angular = Application_Common_HTTPHelper::getStationUrl() . 'js/libs/angular.min.js?' . $CC_CONFIG['airtime_version'];
$widgetStyle = $request->getParam('style');
if ($widgetStyle == "premium") {
$this->view->widgetStyle = "premium";
$this->view->css = "/css/embed/weekly-schedule-widget.css?" . $CC_CONFIG['airtime_version'];
if ($widgetStyle == 'premium') {
$this->view->widgetStyle = 'premium';
$this->view->css = '/css/embed/weekly-schedule-widget.css?' . $CC_CONFIG['airtime_version'];
} else {
$this->view->widgetStyle = "basic";
$this->view->css = "/css/embed/weekly-schedule-widget-basic.css?" . $CC_CONFIG['airtime_version'];
$this->view->widgetStyle = 'basic';
$this->view->css = '/css/embed/weekly-schedule-widget-basic.css?' . $CC_CONFIG['airtime_version'];
}
$this->view->jquery = "/js/libs/jquery-1.8.3.min.js?".$CC_CONFIG['airtime_version'];
$this->view->jquery = '/js/libs/jquery-1.8.3.min.js?' . $CC_CONFIG['airtime_version'];
$weeklyScheduleData = WidgetHelper::getWeekInfoV2();
$this->view->schedule_data = json_encode($weeklyScheduleData);
$currentDay = new DateTime("now", new DateTimeZone(Application_Model_Preference::GetTimezone()));
$currentDay = new DateTime('now', new DateTimeZone(Application_Model_Preference::GetTimezone()));
//day of the month without leading zeros (1 to 31)
$this->view->currentDayOfMonth = $currentDay->format("j");
$this->view->currentDayOfMonth = $currentDay->format('j');
}
}

View File

@ -2,10 +2,8 @@
class EmbeddableWidgetsController extends Zend_Controller_Action
{
public function init()
{
}
public function playerAction()
@ -14,8 +12,8 @@ class EmbeddableWidgetsController extends Zend_Controller_Action
$CC_CONFIG = Config::getConfig();
$baseUrl = Application_Common_OsPath::getBaseDir();
$this->view->headLink()->appendStylesheet($baseUrl.'css/player-form.css?'.$CC_CONFIG['airtime_version']);
$this->view->headScript()->appendFile($baseUrl.'js/airtime/player/player.js?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl . 'css/player-form.css?' . $CC_CONFIG['airtime_version']);
$this->view->headScript()->appendFile($baseUrl . 'js/airtime/player/player.js?' . $CC_CONFIG['airtime_version']);
$form = new Application_Form_Player();
@ -25,9 +23,9 @@ class EmbeddableWidgetsController extends Zend_Controller_Action
if ($numEnabledStreams > 0 && $apiEnabled) {
$this->view->player_form = $form;
} else {
$this->view->player_error_msg = _("To configure and use the embeddable player you must:<br><br>
$this->view->player_error_msg = _('To configure and use the embeddable player you must:<br><br>
1. Enable at least one MP3, AAC, or OGG stream under Settings -> Streams<br>
2. Enable the Public LibreTime API under Settings -> Preferences");
2. Enable the Public LibreTime API under Settings -> Preferences');
}
}
@ -38,8 +36,8 @@ class EmbeddableWidgetsController extends Zend_Controller_Action
$apiEnabled = Application_Model_Preference::GetAllow3rdPartyApi();
if (!$apiEnabled) {
$this->view->weekly_schedule_error_msg = _("To use the embeddable weekly schedule widget you must:<br><br>
Enable the Public LibreTime API under Settings -> Preferences");
$this->view->weekly_schedule_error_msg = _('To use the embeddable weekly schedule widget you must:<br><br>
Enable the Public LibreTime API under Settings -> Preferences');
}
}
@ -51,15 +49,15 @@ class EmbeddableWidgetsController extends Zend_Controller_Action
$apiEnabled = Application_Model_Preference::GetAllow3rdPartyApi();
if (!$apiEnabled) {
$this->view->facebook_error_msg = _("To add the Radio Tab to your Facebook Page, you must first:<br><br>
Enable the Public LibreTime API under Settings -> Preferences");
$this->view->facebook_error_msg = _('To add the Radio Tab to your Facebook Page, you must first:<br><br>
Enable the Public LibreTime API under Settings -> Preferences');
}
$CC_CONFIG = Config::getConfig();
$baseUrl = Application_Common_OsPath::getBaseDir();
$facebookAppId = $CC_CONFIG['facebook-app-id'];
$this->view->headScript()->appendScript("var FACEBOOK_APP_ID = " . json_encode($facebookAppId) . ";");
$this->view->headScript()->appendScript('var FACEBOOK_APP_ID = ' . json_encode($facebookAppId) . ';');
$this->view->headScript()->appendFile($baseUrl . 'js/airtime/common/facebook.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
}
@ -78,7 +76,7 @@ class EmbeddableWidgetsController extends Zend_Controller_Action
}
$values = $request->getPost();
$facebookPageIds = json_decode($values["pages"]);
$facebookPageIds = json_decode($values['pages']);
$CC_CONFIG = Config::getConfig();
$facebookMicroserviceUrl = $CC_CONFIG['facebook-app-url'];
@ -86,14 +84,15 @@ class EmbeddableWidgetsController extends Zend_Controller_Action
//Post the page tab ID and station subdomain to the social microservice so that mapping can be saved
//in a database.
foreach ($facebookPageIds as $facebookPageId)
{
$postfields = array();
$postfields["facebookPageId"] = $facebookPageId;
$postfields["stationId"] = $CC_CONFIG['stationId'];
foreach ($facebookPageIds as $facebookPageId) {
$postfields = [];
$postfields['facebookPageId'] = $facebookPageId;
$postfields['stationId'] = $CC_CONFIG['stationId'];
$query_string = "";
foreach ($postfields as $k => $v) $query_string .= "$k=".urlencode($v)."&";
$query_string = '';
foreach ($postfields as $k => $v) {
$query_string .= "{$k}=" . urlencode($v) . '&';
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $facebookMicroserviceUrl);
@ -102,21 +101,18 @@ class EmbeddableWidgetsController extends Zend_Controller_Action
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_USERPWD, ":$facebookMicroserviceApiKey");
curl_setopt($ch, CURLOPT_USERPWD, ":{$facebookMicroserviceApiKey}");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$jsondata = curl_exec($ch);
if (curl_error($ch)) {
throw new Exception("Failed to reach server in " . __FUNCTION__ . ": "
throw new Exception('Failed to reach server in ' . __FUNCTION__ . ': '
. curl_errno($ch) . ' - ' . curl_error($ch) . ' - ' . curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
}
curl_close($ch);
}
//$arr = json_decode($jsondata, true); # Decode JSON String
}
}

View File

@ -1,6 +1,7 @@
<?php
class ErrorController extends Zend_Controller_Action {
class ErrorController extends Zend_Controller_Action
{
public function init()
{
//The default layout includes the Dashboard header, which may contain private information.
@ -18,7 +19,8 @@ class ErrorController extends Zend_Controller_Action {
}
}
public function errorAction() {
public function errorAction()
{
$errors = $this->_getParam('error_handler');
if ($errors) {
@ -27,21 +29,27 @@ class ErrorController extends Zend_Controller_Action {
Logging::error($errors->exception->getTraceAsString());
switch ($errors->type) {
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE :
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER :
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
$this->error404Action();
break;
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION :
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
$this->error400Action();
break;
default :
default:
$this->error500Action();
break;
}
} else {
//$exceptions = $this->_getAllParams();
//Logging::error($exceptions);
$this->error404Action();
return;
}
@ -51,7 +59,7 @@ class ErrorController extends Zend_Controller_Action {
$log->crit($this->view->message, $errors->exception);
}*/
//Logging that actually works: -- Albert
Logging::error($this->view->message . ": " . $errors->exception);
Logging::error($this->view->message . ': ' . $errors->exception);
// conditionally display exceptions
if ($this->getInvokeArg('displayExceptions') == true) {
@ -68,50 +76,51 @@ class ErrorController extends Zend_Controller_Action {
$this->view->headLink()->appendStylesheet($staticBaseDir . 'css/styles.css?' . $CC_CONFIG['airtime_version']);
}
public function getLog() {
public function getLog()
{
$bootstrap = $this->getInvokeArg('bootstrap');
if (!$bootstrap->hasPluginResource('Log')) {
return false;
}
$log = $bootstrap->getResource('Log');
return $log;
return $bootstrap->getResource('Log');
}
/**
* 404 error - route or controller
* 404 error - route or controller.
*/
public function error404Action() {
public function error404Action()
{
$this->_helper->viewRenderer('error');
$this->getResponse()->setHttpResponseCode(404);
$this->view->message = _('Page not found.');
}
/**
* 400 error - no such action
* 400 error - no such action.
*/
public function error400Action() {
public function error400Action()
{
$this->_helper->viewRenderer('error-400');
$this->getResponse()->setHttpResponseCode(400);
$this->view->message = _('The requested action is not supported.');
}
/**
* 403 error - permission denied
* 403 error - permission denied.
*/
public function error403Action() {
public function error403Action()
{
$this->_helper->viewRenderer('error-403');
$this->getResponse()->setHttpResponseCode(403);
$this->view->message = _('You do not have permission to access this resource.');
}
/**
* 500 error - internal server error
* 500 error - internal server error.
*/
public function error500Action() {
public function error500Action()
{
$this->_helper->viewRenderer('error-500');
$this->getResponse()->setHttpResponseCode(500);

View File

@ -11,9 +11,10 @@ class FeedsController extends Zend_Controller_Action
$response = $this->getResponse();
if ((Application_Model_Preference::getStationPodcastPrivacy()
&& $request->getParam("sharing_token") != Application_Model_Preference::getStationPodcastDownloadKey())
&& $request->getParam('sharing_token') != Application_Model_Preference::getStationPodcastDownloadKey())
&& !RestAuth::verifyAuth(true, false, $this)) {
$response->setHttpResponseCode(401);
return;
}
@ -21,23 +22,23 @@ class FeedsController extends Zend_Controller_Action
$rssData = Application_Service_PodcastService::createStationRssFeed();
$mimeType = "text/xml";
header("Content-Type: $mimeType; charset=UTF-8");
$mimeType = 'text/xml';
header("Content-Type: {$mimeType}; charset=UTF-8");
if (isset($_SERVER['HTTP_RANGE'])) {
header('HTTP/1.1 206 Partial Content');
} else {
header('HTTP/1.1 200 OK');
}
header("Content-Type: $mimeType");
header("Content-Transfer-Encoding: binary");
header("Content-Type: {$mimeType}");
header('Content-Transfer-Encoding: binary');
header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Accept-Ranges: bytes');
$size = strlen($rssData);
$begin = 0;
$end = $size - 1;
$end = $size - 1;
//ob_start(); //Must start a buffer here for these header() functions
@ -53,10 +54,10 @@ class FeedsController extends Zend_Controller_Action
if ($size > 0) {
header('Content-Length:' . (($end - $begin) + 1));
if (isset($_SERVER['HTTP_RANGE'])) {
header("Content-Range: bytes $begin-$end/$size");
header("Content-Range: bytes {$begin}-{$end}/{$size}");
}
}
echo $rssData;
}
}
}

View File

@ -2,10 +2,8 @@
class IndexController extends Zend_Controller_Action
{
public function init()
{
}
public function indexAction()
@ -17,20 +15,20 @@ class IndexController extends Zend_Controller_Action
$this->view->headScript()->appendFile($baseUrl . 'js/i18n/jquery.i18n.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'locale/general-translation-table?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendScript("$.i18n.setDictionary(general_dict)");
$this->view->headScript()->appendScript("var baseUrl='$baseUrl'");
$this->view->headScript()->appendScript('$.i18n.setDictionary(general_dict)');
$this->view->headScript()->appendScript("var baseUrl='{$baseUrl}'");
//jplayer
$this->view->headScript()->appendFile($baseUrl.'js/jplayer/jquery.jplayer.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/jplayer/jplayer.playlist.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/jplayer/jquery.jplayer.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/jplayer/jplayer.playlist.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headLink()->setStylesheet($baseUrl.'css/radio-page/radio-page.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'css/embed/weekly-schedule-widget.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'css/radio-page/station-podcast.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'css/bootstrap.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->setStylesheet($baseUrl . 'css/radio-page/radio-page.css?' . $CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl . 'css/embed/weekly-schedule-widget.css?' . $CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl . 'css/radio-page/station-podcast.css?' . $CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl . 'css/bootstrap.css?' . $CC_CONFIG['airtime_version']);
//jplayer control buttons
$this->view->headLink()->appendStylesheet($baseUrl.'css/redmond/jquery-ui-1.8.8.custom.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl . 'css/redmond/jquery-ui-1.8.8.custom.css?' . $CC_CONFIG['airtime_version']);
$this->_helper->layout->setLayout('radio-page');
@ -51,7 +49,7 @@ class IndexController extends Zend_Controller_Action
$this->view->stationUrl = Application_Common_HTTPHelper::getStationUrl();
$displayRadioPageLoginButtonValue = Application_Model_Preference::getRadioPageDisplayLoginButton();
if ($displayRadioPageLoginButtonValue == "") {
if ($displayRadioPageLoginButtonValue == '') {
$displayRadioPageLoginButtonValue = true;
}
$this->view->displayLoginButton = $displayRadioPageLoginButtonValue;
@ -59,21 +57,21 @@ class IndexController extends Zend_Controller_Action
//station feed episodes
$stationPodcastId = Application_Model_Preference::getStationPodcastId();
$podcastEpisodesService = new Application_Service_PodcastEpisodeService();
$episodes = $podcastEpisodesService->getPodcastEpisodes($stationPodcastId, 0, 0, PodcastEpisodesPeer::PUBLICATION_DATE, "DESC");
$episodes = $podcastEpisodesService->getPodcastEpisodes($stationPodcastId, 0, 0, PodcastEpisodesPeer::PUBLICATION_DATE, 'DESC');
foreach ($episodes as $e => $v) {
$episodes[$e]["CcFiles"]["track_title"] = htmlspecialchars($v["CcFiles"]["track_title"], ENT_QUOTES);
$episodes[$e]["CcFiles"]["artist_name"] = htmlspecialchars($v["CcFiles"]["artist_name"], ENT_QUOTES);
$episodes[$e]['CcFiles']['track_title'] = htmlspecialchars($v['CcFiles']['track_title'], ENT_QUOTES);
$episodes[$e]['CcFiles']['artist_name'] = htmlspecialchars($v['CcFiles']['artist_name'], ENT_QUOTES);
$pubDate = explode(" ", $v["publication_date"]);
$episodes[$e]["publication_date"] = $pubDate[0];
$pubDate = explode(' ', $v['publication_date']);
$episodes[$e]['publication_date'] = $pubDate[0];
$length = explode(".", $v["CcFiles"]["length"]);
$episodes[$e]["CcFiles"]["length"] = $length[0];
$length = explode('.', $v['CcFiles']['length']);
$episodes[$e]['CcFiles']['length'] = $length[0];
$episodes[$e]["mime"] = FileDataHelper::getAudioMimeTypeArray()[$v["CcFiles"]["mime"]];
$episodes[$e]['mime'] = FileDataHelper::getAudioMimeTypeArray()[$v['CcFiles']['mime']];
if (is_null($v["CcFiles"]["description"])) {
$episodes[$e]["CcFiles"]["description"] = "";
if (is_null($v['CcFiles']['description'])) {
$episodes[$e]['CcFiles']['description'] = '';
}
}
@ -87,9 +85,8 @@ class IndexController extends Zend_Controller_Action
$this->view->stationPodcastRssUrl = $url;
$stationName = Application_Model_Preference::GetStationName();
$this->view->podcastTitle = sprintf(_("%s Podcast"), !empty($stationName) ? $stationName : $CC_CONFIG["stationId"]);
$this->view->emptyPodcastMessage = _("No tracks have been published yet.");
$this->view->podcastTitle = sprintf(_('%s Podcast'), !empty($stationName) ? $stationName : $CC_CONFIG['stationId']);
$this->view->emptyPodcastMessage = _('No tracks have been published yet.');
}
public function mainAction()
@ -101,5 +98,4 @@ class IndexController extends Zend_Controller_Action
{
$this->getResponse()->setHttpResponseCode(503);
}
}

View File

@ -2,40 +2,40 @@
class LibraryController extends Zend_Controller_Action
{
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('contents-feed', 'json')
->addActionContext('delete', 'json')
->addActionContext('duplicate', 'json')
->addActionContext('duplicate-block', 'json')
->addActionContext('delete-group', 'json')
->addActionContext('context-menu', 'json')
->addActionContext('get-file-metadata', 'html')
->addActionContext('set-num-entries', 'json')
->addActionContext('edit-file-md', 'json')
->addActionContext('publish-dialog', 'html')
->initContext();
->addActionContext('delete', 'json')
->addActionContext('duplicate', 'json')
->addActionContext('duplicate-block', 'json')
->addActionContext('delete-group', 'json')
->addActionContext('context-menu', 'json')
->addActionContext('get-file-metadata', 'html')
->addActionContext('set-num-entries', 'json')
->addActionContext('edit-file-md', 'json')
->addActionContext('publish-dialog', 'html')
->initContext()
;
}
public function indexAction()
{
$this->_redirect("showbuilder");
$this->_redirect('showbuilder');
}
protected function playlistNotFound($p_type)
{
$this->view->error = sprintf(_("%s not found"), $p_type);
$this->view->error = sprintf(_('%s not found'), $p_type);
Logging::info("$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.");
$this->view->error = _('Something went wrong.');
Logging::info($e->getMessage());
}
@ -62,9 +62,8 @@ class LibraryController extends Zend_Controller_Action
$this->view->id = $obj->getId();
if ($isJson) {
return $this->view->render($viewPath);
} else {
$this->view->html = $this->view->render($viewPath);
}
$this->view->html = $this->view->render($viewPath);
} else {
$this->view->obj = $obj;
$this->view->id = $obj->getId();
@ -84,24 +83,24 @@ class LibraryController extends Zend_Controller_Action
//playlist||timeline
$screen = $this->_getParam('screen');
$menu = array();
$menu = [];
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id);
//Open a jPlayer window and play the audio clip.
$menu["play"] = array("name"=> _("Preview"), "icon" => "play", "disabled" => false);
$menu['play'] = ['name' => _('Preview'), 'icon' => 'play', 'disabled' => false];
$isAdminOrPM = $user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
$isAdminOrPM = $user->isUserType([UTYPE_SUPERADMIN, 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::RecallById($id);
$menu["play"]["mime"] = $file->getPropelOrm()->getDbMime();
$menu['play']['mime'] = $file->getPropelOrm()->getDbMime();
if (isset($obj_sess->id) && $screen == "playlist") {
if (isset($obj_sess->id) && $screen == 'playlist') {
// if the user is not admin or pm, check the creator and see if this person owns the playlist or Block
if ($obj_sess->type == 'playlist') {
$obj = new Application_Model_Playlist($obj_sess->id);
@ -109,16 +108,16 @@ class LibraryController extends Zend_Controller_Action
$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" && $obj->isStatic()) {
$menu["pl_add"] = array("name"=> _("Add to Smart Block"), "icon" => "add-playlist", "icon" => "copy");
if ($obj_sess->type === 'playlist') {
$menu['pl_add'] = ['name' => _('Add to Playlist'), 'icon' => 'add-playlist', 'icon' => 'copy'];
} elseif ($obj_sess->type === 'block' && $obj->isStatic()) {
$menu['pl_add'] = ['name' => _('Add to Smart Block'), 'icon' => 'add-playlist', 'icon' => 'copy'];
}
}
}
if ($isAdminOrPM || $file->getFileOwnerId() == $user->getId()) {
$menu["del"] = array("name"=> _("Delete"), "icon" => "delete", "url" => $baseUrl."library/delete");
$menu["edit"] = array("name"=> _("Edit..."), "icon" => "edit", "url" => $baseUrl."library/edit-file-md/id/{$id}");
$menu['del'] = ['name' => _('Delete'), 'icon' => 'delete', 'url' => $baseUrl . 'library/delete'];
$menu['edit'] = ['name' => _('Edit...'), 'icon' => 'edit', 'url' => $baseUrl . "library/edit-file-md/id/{$id}"];
// Disable My podcasts
// See https://github.com/LibreTime/libretime/issues/1320
// $menu["publish"] = array("name"=> _("Publish..."), "url" => $baseUrl."library/publish/id/{$id}");
@ -128,58 +127,57 @@ class LibraryController extends Zend_Controller_Action
// and not the cloud_file id (if applicable) for track download.
// Our application logic (StoredFile.php) will determine if the track
// is a cloud_file and handle it appropriately.
$url = $baseUrl."api/get-media/file/$id/download/true";
$menu["download"] = array("name" => _("Download"), "icon" => "download", "url" => $url);
} elseif ($type === "playlist" || $type === "block") {
$url = $baseUrl . "api/get-media/file/{$id}/download/true";
$menu['download'] = ['name' => _('Download'), 'icon' => 'download', 'url' => $url];
} elseif ($type === 'playlist' || $type === 'block') {
if ($type === 'playlist') {
$obj = new Application_Model_Playlist($id);
$menu["duplicate"] = array("name" => _("Duplicate Playlist"), "icon" => "edit", "url" => $baseUrl."library/duplicate");
$menu['duplicate'] = ['name' => _('Duplicate Playlist'), 'icon' => 'edit', 'url' => $baseUrl . 'library/duplicate'];
} elseif ($type === 'block') {
$obj = new Application_Model_Block($id);
$menu["duplicate"] = array("name" => _("Duplicate Smartblock"), "icon" => "edit", "url" => $baseUrl."library/duplicate-block");
$menu['duplicate'] = ['name' => _('Duplicate Smartblock'), 'icon' => 'edit', 'url' => $baseUrl . 'library/duplicate-block'];
if (!$obj->isStatic()) {
unset($menu["play"]);
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 (($isAdminOrPM || $obj->getCreatorId() == $user->getId()) && $screen == 'playlist') {
if ($obj_sess->type === 'playlist') {
$menu['pl_add'] = ['name' => _('Add to Playlist'), 'icon' => 'add-playlist', 'icon' => 'copy'];
}
}
}
if ($obj_sess->id !== $id && $screen == "playlist") {
if ($obj_sess->id !== $id && $screen == 'playlist') {
if ($isAdminOrPM || $obj->getCreatorId() == $user->getId()) {
$menu["edit"] = array("name"=> _("Edit..."), "icon" => "edit");
$menu['edit'] = ['name' => _('Edit...'), 'icon' => 'edit'];
}
}
if ($isAdminOrPM || $obj->getCreatorId() == $user->getId()) {
$menu["del"] = array("name"=> _("Delete"), "icon" => "delete", "url" => $baseUrl."library/delete");
$menu['del'] = ['name' => _('Delete'), 'icon' => 'delete', 'url' => $baseUrl . 'library/delete'];
}
} elseif ($type == "stream") {
} elseif ($type == 'stream') {
$webstream = CcWebstreamQuery::create()->findPK($id);
$obj = new Application_Model_Webstream($webstream);
$menu["play"]["mime"] = $webstream->getDbMime();
$menu['play']['mime'] = $webstream->getDbMime();
if (isset($obj_sess->id) && $screen == "playlist") {
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 ($obj_sess->type === 'playlist') {
$menu['pl_add'] = ['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" => $baseUrl."library/edit-file-md/id/{$id}");
if ($screen == 'playlist') {
$menu['edit'] = ['name' => _('Edit...'), 'icon' => 'edit', 'url' => $baseUrl . "library/edit-file-md/id/{$id}"];
}
$menu["del"] = array("name"=> _("Delete"), "icon" => "delete", "url" => $baseUrl."library/delete");
$menu['del'] = ['name' => _('Delete'), 'icon' => 'delete', 'url' => $baseUrl . 'library/delete'];
}
}
if (empty($menu)) {
$menu["noaction"] = array("name"=>_("No action available"));
$menu['noaction'] = ['name' => _('No action available')];
}
$this->view->items = $menu;
@ -193,24 +191,23 @@ class LibraryController extends Zend_Controller_Action
$user = Application_Model_User::getCurrentUser();
//$isAdminOrPM = $user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
$files = array();
$playlists = array();
$blocks = array();
$streams = array();
$files = [];
$playlists = [];
$blocks = [];
$streams = [];
$message = null;
$noPermissionMsg = _("You don't have permission to delete selected items.");
foreach ($mediaItems as $media) {
if ($media["type"] === "audioclip") {
$files[] = intval($media["id"]);
} elseif ($media["type"] === "playlist") {
$playlists[] = intval($media["id"]);
} elseif ($media["type"] === "block") {
$blocks[] = intval($media["id"]);
} elseif ($media["type"] === "stream") {
$streams[] = intval($media["id"]);
if ($media['type'] === 'audioclip') {
$files[] = intval($media['id']);
} elseif ($media['type'] === 'playlist') {
$playlists[] = intval($media['id']);
} elseif ($media['type'] === 'block') {
$blocks[] = intval($media['id']);
} elseif ($media['type'] === 'stream') {
$streams[] = intval($media['id']);
}
}
@ -245,11 +242,11 @@ class LibraryController extends Zend_Controller_Action
} catch (FileNoPermissionException $e) {
$message = $noPermissionMsg;
} catch (DeleteScheduledFileException $e) {
$message = _("Could not delete file because it is scheduled in the future.");
$message = _('Could not delete file because it is scheduled in the future.');
} catch (Exception $e) {
//could throw a scheduled in future exception.
$message = _("Could not delete file(s).");
Logging::info($message.": ".$e->getMessage());
$message = _('Could not delete file(s).');
Logging::info($message . ': ' . $e->getMessage());
}
}
}
@ -260,7 +257,8 @@ class LibraryController extends Zend_Controller_Action
}
// duplicate playlist
public function duplicateAction(){
public function duplicateAction()
{
$params = $this->getRequest()->getParams();
$id = $params['id'];
Logging::info($params);
@ -272,9 +270,9 @@ class LibraryController extends Zend_Controller_Action
foreach ($contents as &$c) {
if ($c['type'] == '0') {
$c[1] = 'audioclip';
} else if ($c['type'] == '2') {
} elseif ($c['type'] == '2') {
$c[1] = 'block';
} else if ($c['type'] == '1') {
} elseif ($c['type'] == '1') {
$c[1] = 'stream';
}
$c[0] = $c['item_id'];
@ -285,16 +283,17 @@ class LibraryController extends Zend_Controller_Action
$newPl->setCreator(Application_Model_User::getCurrentUser()->getId());
$newPl->setDescription($originalPl->getDescription());
list($plFadeIn, ) = $originalPl->getFadeInfo(0);
list(, $plFadeOut) = $originalPl->getFadeInfo($originalPl->getSize()-1);
list($plFadeIn) = $originalPl->getFadeInfo(0);
list(, $plFadeOut) = $originalPl->getFadeInfo($originalPl->getSize() - 1);
$newPl->setfades($plFadeIn, $plFadeOut);
$newPl->setName(sprintf(_("Copy of %s"), $originalPl->getName()));
$newPl->setName(sprintf(_('Copy of %s'), $originalPl->getName()));
}
// duplicate smartblock
public function duplicateBlockAction(){
Logging::info("duplicate smartblock functionality not yet implemented");
public function duplicateBlockAction()
{
Logging::info('duplicate smartblock functionality not yet implemented');
$params = $this->getRequest()->getParams();
$id = $params['id'];
Logging::info($params);
@ -305,8 +304,7 @@ class LibraryController extends Zend_Controller_Action
$newBl->setDescription($originalBl->getDescription());
if ($originalBl->isStatic()) {
$newBl->saveType('static');
}
else {
} else {
$newBl->saveType('dynamic');
}
// the issue here is that the format that getCriteria provides is different from the format the saveCriteria
@ -324,28 +322,27 @@ class LibraryController extends Zend_Controller_Action
$row->setDbBlockId($newBl->getId());
$row->save();
}
$newBl->setName(sprintf(_("Copy of %s"), $originalBl->getName()));
$newBl->setName(sprintf(_('Copy of %s'), $originalBl->getName()));
}
public function contentsFeedAction()
{
$params = $this->getRequest()->getParams();
# terrible name for the method below. it does not only search files.
// terrible name for the method below. it does not only search files.
$r = Application_Model_StoredFile::searchLibraryFiles($params);
$this->view->sEcho = $r["sEcho"];
$this->view->iTotalDisplayRecords = $r["iTotalDisplayRecords"];
$this->view->iTotalRecords = $r["iTotalRecords"];
$this->view->files = SecurityHelper::htmlescape_recursive($r["aaData"]);
$this->view->sEcho = $r['sEcho'];
$this->view->iTotalDisplayRecords = $r['iTotalDisplayRecords'];
$this->view->iTotalRecords = $r['iTotalRecords'];
$this->view->files = SecurityHelper::htmlescape_recursive($r['aaData']);
}
public function editFileMdAction()
{
$user = Application_Model_User::getCurrentUser();
$isAdminOrPM = $user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
$isAdmin = $user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN));
$isAdminOrPM = $user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER]);
$isAdmin = $user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN]);
$request = $this->getRequest();
@ -368,27 +365,26 @@ class LibraryController extends Zend_Controller_Action
}
if ($request->isPost()) {
$js = $this->_getParam('data');
$serialized = array();
$serialized = [];
//need to convert from serialized jQuery array.
foreach ($js as $j) {
//on edit, if no artwork is set and audiofile has image, automatically add it
if ($j["name"] == "artwork") {
if ($j["value"] == null || $j["value"] == ''){
$serialized["artwork"] = FileDataHelper::resetArtwork($file_id);
if ($j['name'] == 'artwork') {
if ($j['value'] == null || $j['value'] == '') {
$serialized['artwork'] = FileDataHelper::resetArtwork($file_id);
}
} elseif ($j["name"] == "set_artwork") {
if ($j["value"] != null || $j["value"] != ''){
$serialized["artwork"] = FileDataHelper::setArtwork($file_id, $j["value"] );
} elseif ($j['name'] == 'set_artwork') {
if ($j['value'] != null || $j['value'] != '') {
$serialized['artwork'] = FileDataHelper::setArtwork($file_id, $j['value']);
}
} elseif ($j["name"] == "remove_artwork") {
if ($j["value"] == 1){
} elseif ($j['name'] == 'remove_artwork') {
if ($j['value'] == 1) {
$remove_artwork = true;
$serialized["artwork"] = FileDataHelper::removeArtwork($file_id);
$serialized['artwork'] = FileDataHelper::removeArtwork($file_id);
}
} else {
$serialized[$j["name"]] = $j["value"];
$serialized[$j['name']] = $j['value'];
}
}
@ -418,7 +414,7 @@ class LibraryController extends Zend_Controller_Action
$type = $this->_getParam('type');
try {
if ($type == "audioclip") {
if ($type == 'audioclip') {
$file = Application_Model_StoredFile::RecallById($id);
$this->view->type = $type;
$md = $file->getMetadata();
@ -430,35 +426,33 @@ class LibraryController extends Zend_Controller_Action
}
}
$formatter = new SamplerateFormatter($md["MDATA_KEY_SAMPLERATE"]);
$md["MDATA_KEY_SAMPLERATE"] = $formatter->format();
$formatter = new SamplerateFormatter($md['MDATA_KEY_SAMPLERATE']);
$md['MDATA_KEY_SAMPLERATE'] = $formatter->format();
$formatter = new BitrateFormatter($md["MDATA_KEY_BITRATE"]);
$md["MDATA_KEY_BITRATE"] = $formatter->format();
$formatter = new BitrateFormatter($md['MDATA_KEY_BITRATE']);
$md['MDATA_KEY_BITRATE'] = $formatter->format();
$formatter = new LengthFormatter($md["MDATA_KEY_DURATION"]);
$md["MDATA_KEY_DURATION"] = $formatter->format();
$formatter = new LengthFormatter($md['MDATA_KEY_DURATION']);
$md['MDATA_KEY_DURATION'] = $formatter->format();
$this->view->md = $md;
} elseif ($type == "playlist") {
} elseif ($type == 'playlist') {
$file = new Application_Model_Playlist($id);
$this->view->type = $type;
$md = $file->getAllPLMetaData();
$formatter = new LengthFormatter($md["dcterms:extent"]);
$md["dcterms:extent"] = $formatter->format();
$formatter = new LengthFormatter($md['dcterms:extent']);
$md['dcterms:extent'] = $formatter->format();
$this->view->md = $md;
$this->view->contents = $file->getContents();
} elseif ($type == "block") {
} 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();
$formatter = new LengthFormatter($md['dcterms:extent']);
$md['dcterms:extent'] = $formatter->format();
$this->view->md = $md;
if ($block->isStatic()) {
@ -469,7 +463,7 @@ class LibraryController extends Zend_Controller_Action
$this->view->contents = $block->getCriteria();
}
$this->view->block = $block;
} elseif ($type == "stream") {
} elseif ($type == 'stream') {
$webstream = CcWebstreamQuery::create()->findPK($id);
$ws = new Application_Model_Webstream($webstream);
@ -483,7 +477,8 @@ class LibraryController extends Zend_Controller_Action
}
}
public function publishDialogAction() {
public function publishDialogAction()
{
$this->_helper->layout->disableLayout();
//This just spits out publish-dialog.phtml!
}

View File

@ -6,10 +6,11 @@ class ListenerstatController extends Zend_Controller_Action
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext
->addActionContext('get-data', 'json')
->initContext();
->addActionContext('get-data', 'json')
->initContext()
;
}
public function indexAction()
{
$CC_CONFIG = Config::getConfig();
@ -19,14 +20,14 @@ class ListenerstatController extends Zend_Controller_Action
Zend_Layout::getMvcInstance()->assign('parent_page', 'Analytics');
$this->view->headScript()->appendFile($baseUrl.'js/flot/jquery.flot.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/flot/jquery.flot.crosshair.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/flot/jquery.flot.resize.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/airtime/listenerstat/listenerstat.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/utilities/utilities.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headLink()->appendStylesheet($baseUrl.'css/jquery.ui.timepicker.css?'.$CC_CONFIG['airtime_version']);
$this->view->headScript()->appendFile($baseUrl . 'js/flot/jquery.flot.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/flot/jquery.flot.crosshair.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/flot/jquery.flot.resize.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/airtime/listenerstat/listenerstat.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/utilities/utilities.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headLink()->appendStylesheet($baseUrl . 'css/jquery.ui.timepicker.css?' . $CC_CONFIG['airtime_version']);
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($request);
$userTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
@ -34,20 +35,20 @@ class ListenerstatController extends Zend_Controller_Action
$endsDT->setTimezone($userTimezone);
$form = new Application_Form_DateRange();
$form->populate(array(
'his_date_start' => $startsDT->format("Y-m-d"),
'his_time_start' => $startsDT->format("H:i"),
'his_date_end' => $endsDT->format("Y-m-d"),
'his_time_end' => $endsDT->format("H:i")
));
$form->populate([
'his_date_start' => $startsDT->format('Y-m-d'),
'his_time_start' => $startsDT->format('H:i'),
'his_date_end' => $endsDT->format('Y-m-d'),
'his_time_end' => $endsDT->format('H:i'),
]);
$errorStatus = Application_Model_StreamSetting::GetAllListenerStatErrors();
Logging::info($errorStatus);
$out = array();
$out = [];
foreach ($errorStatus as $v) {
$key = explode('_listener_stat_error', $v['keyname']);
if ($v['value'] != 'OK') {
$v['value'] = _("Please make sure admin user/password is correct on Settings->Streams page.");
$v['value'] = _('Please make sure admin user/password is correct on Settings->Streams page.');
}
$out[$key[0]] = $v['value'];
}
@ -55,7 +56,9 @@ class ListenerstatController extends Zend_Controller_Action
$this->view->errorStatus = $out;
$this->view->date_form = $form;
}
public function showAction() {
public function showAction()
{
$CC_CONFIG = Config::getConfig();
$request = $this->getRequest();
@ -63,20 +66,18 @@ class ListenerstatController extends Zend_Controller_Action
$headScript = $this->view->headScript();
AirtimeTableView::injectTableJavaScriptDependencies($headScript, $baseUrl, $CC_CONFIG['airtime_version']);
Zend_Layout::getMvcInstance()->assign('parent_page', 'Analytics');
$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/utilities/utilities.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/airtime/listenerstat/showlistenerstat.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/utilities/utilities.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/airtime/listenerstat/showlistenerstat.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headLink()->appendStylesheet($baseUrl.'css/datatables/css/ColVis.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'css/datatables/css/dataTables.colReorder.min.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/show_analytics.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/dataTables.colReorder.min.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/show_analytics.css' . $CC_CONFIG['airtime_version']);
$user = Application_Model_User::getCurrentUser();
if ($user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
if ($user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER])) {
$this->view->showAllShows = true;
}
$data = [];
@ -88,42 +89,56 @@ class ListenerstatController extends Zend_Controller_Action
$userTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
$startsDT->setTimezone($userTimezone);
$endsDT->setTimezone($userTimezone);
$form->populate(array(
'his_date_start' => $startsDT->format("Y-m-d"),
'his_time_start' => $startsDT->format("H:i"),
'his_date_end' => $endsDT->format("Y-m-d"),
'his_time_end' => $endsDT->format("H:i")
));
$form->populate([
'his_date_start' => $startsDT->format('Y-m-d'),
'his_time_start' => $startsDT->format('H:i'),
'his_date_end' => $endsDT->format('Y-m-d'),
'his_time_end' => $endsDT->format('H:i'),
]);
$this->view->date_form = $form;
}
public function getDataAction(){
public function getDataAction()
{
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($this->getRequest());
$data = Application_Model_ListenerStat::getDataPointsWithinRange($startsDT->format(DEFAULT_TIMESTAMP_FORMAT),
$endsDT->format(DEFAULT_TIMESTAMP_FORMAT));
$data = Application_Model_ListenerStat::getDataPointsWithinRange(
$startsDT->format(DEFAULT_TIMESTAMP_FORMAT),
$endsDT->format(DEFAULT_TIMESTAMP_FORMAT)
);
$this->_helper->json->sendJson($data);
}
public function getShowDataAction(){
public function getShowDataAction()
{
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($this->getRequest());
$show_id = $this->getRequest()->getParam("show_id", null);
$data = Application_Model_ListenerStat::getShowDataPointsWithinRange($startsDT->format(DEFAULT_TIMESTAMP_FORMAT),
$endsDT->format(DEFAULT_TIMESTAMP_FORMAT),$show_id);
$show_id = $this->getRequest()->getParam('show_id', null);
$data = Application_Model_ListenerStat::getShowDataPointsWithinRange(
$startsDT->format(DEFAULT_TIMESTAMP_FORMAT),
$endsDT->format(DEFAULT_TIMESTAMP_FORMAT),
$show_id
);
$this->_helper->json->sendJson($data);
}
public function getAllShowData(){
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($this->getRequest());
$data = Application_Model_ListenerStat::getAllShowDataPointsWithinRange($startsDT->format(DEFAULT_TIMESTAMP_FORMAT),
$endsDT->format(DEFAULT_TIMESTAMP_FORMAT));
return $data;
public function getAllShowData()
{
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($this->getRequest());
return Application_Model_ListenerStat::getAllShowDataPointsWithinRange(
$startsDT->format(DEFAULT_TIMESTAMP_FORMAT),
$endsDT->format(DEFAULT_TIMESTAMP_FORMAT)
);
}
public function getAllShowDataAction(){
public function getAllShowDataAction()
{
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($this->getRequest());
$show_id = $this->getRequest()->getParam("show_id", null);
$data = Application_Model_ListenerStat::getAllShowDataPointsWithinRange($startsDT->format(DEFAULT_TIMESTAMP_FORMAT),
$endsDT->format(DEFAULT_TIMESTAMP_FORMAT));
$show_id = $this->getRequest()->getParam('show_id', null);
$data = Application_Model_ListenerStat::getAllShowDataPointsWithinRange(
$startsDT->format(DEFAULT_TIMESTAMP_FORMAT),
$endsDT->format(DEFAULT_TIMESTAMP_FORMAT)
);
$this->_helper->json->sendJson($data);
}
}

View File

@ -6,499 +6,493 @@ final class LocaleController extends Zend_Controller_Action
{
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
header("Content-type: text/javascript");
header('Content-type: text/javascript');
$locale = Application_Model_Preference::GetLocale();
echo "var datatables_dict =" .
file_get_contents(Application_Common_OsPath::join(
echo 'var datatables_dict =' .
file_get_contents(
Application_Common_OsPath::join(
//$_SERVER["DOCUMENT_ROOT"],
dirname(__FILE__) . "/../../public/", // Fixing this... -- Albert
"js/datatables/i18n/",
$locale.".txt")
dirname(__FILE__) . '/../../public/', // Fixing this... -- Albert
'js/datatables/i18n/',
$locale . '.txt'
)
);
}
public function generalTranslationTableAction()
{
$translations = array (
$translations = [
//common/common.js
"Audio Player" => _("Audio Player"),
"Something went wrong!" => _("Something went wrong!"),
'Audio Player' => _('Audio Player'),
'Something went wrong!' => _('Something went wrong!'),
//dashboard/dashboard.js
"Recording:" => _("Recording:"),
"Master Stream" => _("Master Stream"),
"Live Stream" => _("Live Stream"),
"Nothing Scheduled" => _("Nothing Scheduled"),
"Current Show:" => _("Current Show:"),
"Current" => _("Current"),
'Recording:' => _('Recording:'),
'Master Stream' => _('Master Stream'),
'Live Stream' => _('Live Stream'),
'Nothing Scheduled' => _('Nothing Scheduled'),
'Current Show:' => _('Current Show:'),
'Current' => _('Current'),
//dashboard/versiontooltip.js
"You are running the latest version" => _("You are running the latest version"),
"New version available: " => _("New version available: "),
"You have a pre-release version of LibreTime intalled." => _("You have a pre-release version of LibreTime intalled."),
"A patch update for your LibreTime installation is available." => _("A patch update for your LibreTime installation is available."),
"A feature update for your LibreTime installation is available." => _("A feature update for your LibreTime installation is available."),
"A major update for your LibreTime installation is available." => _("A major update for your LibreTime installation is available."),
"Multiple major updates for LibreTime installation are available. Please upgrade as soon as possible." => _("Multiple major updates for LibreTime installation are available. Please upgrade as soon as possible."),
'You are running the latest version' => _('You are running the latest version'),
'New version available: ' => _('New version available: '),
'You have a pre-release version of LibreTime intalled.' => _('You have a pre-release version of LibreTime intalled.'),
'A patch update for your LibreTime installation is available.' => _('A patch update for your LibreTime installation is available.'),
'A feature update for your LibreTime installation is available.' => _('A feature update for your LibreTime installation is available.'),
'A major update for your LibreTime installation is available.' => _('A major update for your LibreTime installation is available.'),
'Multiple major updates for LibreTime installation are available. Please upgrade as soon as possible.' => _('Multiple major updates for LibreTime installation are available. Please upgrade as soon as possible.'),
//library/events/library_playlistbuilder.js
"Add to current playlist" => _("Add to current playlist"),
"Add to current smart block" => _("Add to current smart block"),
"Adding 1 Item" => _("Adding 1 Item"),
"Adding %s Items" => _("Adding %s Items"),
"You can only add tracks to smart blocks." => _("You can only add tracks to smart blocks."),
"You can only add tracks, smart blocks, and webstreams to playlists." => _("You can only add tracks, smart blocks, and webstreams to playlists."),
'Add to current playlist' => _('Add to current playlist'),
'Add to current smart block' => _('Add to current smart block'),
'Adding 1 Item' => _('Adding 1 Item'),
'Adding %s Items' => _('Adding %s Items'),
'You can only add tracks to smart blocks.' => _('You can only add tracks to smart blocks.'),
'You can only add tracks, smart blocks, and webstreams to playlists.' => _('You can only add tracks, smart blocks, and webstreams to playlists.'),
//library/events/library_showbuilder.js
//already in library/events/library_playlistbuilder.js
"Please select a cursor position on timeline." => _("Please select a cursor position on timeline."),
'Please select a cursor position on timeline.' => _('Please select a cursor position on timeline.'),
"You haven't added any tracks" => _("You haven't added any tracks"),
"You haven't added any playlists" => _("You haven't added any playlists"),
"You haven't added any podcasts" => _("You haven't added any podcasts"),
"You haven't added any smart blocks" => _("You haven't added any smart blocks"),
"You haven't added any webstreams" => _("You haven't added any webstreams"),
"Learn about tracks" => _("Learn about tracks"),
"Learn about playlists" => _("Learn about playlists"),
"Learn about podcasts" => _("Learn about podcasts"),
"Learn about smart blocks" => _("Learn about smart blocks"),
"Learn about webstreams" => _("Learn about webstreams"),
'Learn about tracks' => _('Learn about tracks'),
'Learn about playlists' => _('Learn about playlists'),
'Learn about podcasts' => _('Learn about podcasts'),
'Learn about smart blocks' => _('Learn about smart blocks'),
'Learn about webstreams' => _('Learn about webstreams'),
"Click 'New' to create one." => _("Click 'New' to create one."),
//"Adding 1 Item" => _("Adding 1 Item"),
//"Adding %s Items" => _("Adding %s Items"),
//library/library.js
"Add" => _("Add"),
"New" => _("New"),
"Edit" => _("Edit"),
"Add to Schedule" => _("Add to Schedule"),
"Add to next show" => _("Add to next show"),
"Add to current show" => _("Add to current show"),
"Add after selected items" => _("Add after selected items"),
"Delete" => _("Delete"),
"Publish" => _("Publish"),
"Remove" => _("Remove"),
"Edit Metadata" => _("Edit Metadata"),
"Add to selected show" => _("Add to selected show"),
"Select" => _("Select"),
"Select this page" => _("Select this page"),
"Deselect this page" => _("Deselect this page"),
"Deselect all" => _("Deselect all"),
"Are you sure you want to delete the selected item(s)?" => _("Are you sure you want to delete the selected item(s)?"),
"Scheduled" => _("Scheduled"),
"Tracks" => _("Tracks"),
"Playlist" => _("Playlist"),
"Title" => _("Title"),
"Creator" => _("Creator"),
"Album" => _("Album"),
"Bit Rate" => _("Bit Rate"),
"BPM" => _("BPM"),
"Composer" => _("Composer"),
"Conductor" => _("Conductor"),
"Copyright" => _("Copyright"),
"Encoded By" => _("Encoded By"),
"Genre" => _("Genre"),
"ISRC" => _("ISRC"),
"Label" => _("Label"),
"Language" => _("Language"),
"Last Modified" => _("Last Modified"),
"Last Played" => _("Last Played"),
"Length" => _("Length"),
"Mime" => _("Mime"),
"Mood" => _("Mood"),
"Owner" => _("Owner"),
"Replay Gain" => _("Replay Gain"),
"Sample Rate" => _("Sample Rate"),
"Track Number" => _("Track Number"),
"Uploaded" => _("Uploaded"),
"Website" => _("Website"),
"Year" => _("Year"),
"Loading..." => _("Loading..."),
"All" => _("All"),
"Files" => _("Files"),
"Playlists" => _("Playlists"),
"Smart Blocks" => _("Smart Blocks"),
"Web Streams" => _("Web Streams"),
"Unknown type: " => _("Unknown type: "),
"Are you sure you want to delete the selected item?" => _("Are you sure you want to delete the selected item?"),
"Uploading in progress..." => _("Uploading in progress..."),
"Retrieving data from the server..." => _("Retrieving data from the server..."),
'Add' => _('Add'),
'New' => _('New'),
'Edit' => _('Edit'),
'Add to Schedule' => _('Add to Schedule'),
'Add to next show' => _('Add to next show'),
'Add to current show' => _('Add to current show'),
'Add after selected items' => _('Add after selected items'),
'Delete' => _('Delete'),
'Publish' => _('Publish'),
'Remove' => _('Remove'),
'Edit Metadata' => _('Edit Metadata'),
'Add to selected show' => _('Add to selected show'),
'Select' => _('Select'),
'Select this page' => _('Select this page'),
'Deselect this page' => _('Deselect this page'),
'Deselect all' => _('Deselect all'),
'Are you sure you want to delete the selected item(s)?' => _('Are you sure you want to delete the selected item(s)?'),
'Scheduled' => _('Scheduled'),
'Tracks' => _('Tracks'),
'Playlist' => _('Playlist'),
'Title' => _('Title'),
'Creator' => _('Creator'),
'Album' => _('Album'),
'Bit Rate' => _('Bit Rate'),
'BPM' => _('BPM'),
'Composer' => _('Composer'),
'Conductor' => _('Conductor'),
'Copyright' => _('Copyright'),
'Encoded By' => _('Encoded By'),
'Genre' => _('Genre'),
'ISRC' => _('ISRC'),
'Label' => _('Label'),
'Language' => _('Language'),
'Last Modified' => _('Last Modified'),
'Last Played' => _('Last Played'),
'Length' => _('Length'),
'Mime' => _('Mime'),
'Mood' => _('Mood'),
'Owner' => _('Owner'),
'Replay Gain' => _('Replay Gain'),
'Sample Rate' => _('Sample Rate'),
'Track Number' => _('Track Number'),
'Uploaded' => _('Uploaded'),
'Website' => _('Website'),
'Year' => _('Year'),
'Loading...' => _('Loading...'),
'All' => _('All'),
'Files' => _('Files'),
'Playlists' => _('Playlists'),
'Smart Blocks' => _('Smart Blocks'),
'Web Streams' => _('Web Streams'),
'Unknown type: ' => _('Unknown type: '),
'Are you sure you want to delete the selected item?' => _('Are you sure you want to delete the selected item?'),
'Uploading in progress...' => _('Uploading in progress...'),
'Retrieving data from the server...' => _('Retrieving data from the server...'),
//library/podcast.js
"Import" => _("Import"),
"Imported?" => _("Imported?"),
"View" => _("View"),
"Error code: " => _("Error code: "),
"Error msg: " => _("Error msg: "),
"Input must be a positive number" => _("Input must be a positive number"),
"Input must be a number" => _("Input must be a number"),
"Input must be in the format: yyyy-mm-dd" => _("Input must be in the format: yyyy-mm-dd"),
"Input must be in the format: hh:mm:ss.t" => _("Input must be in the format: hh:mm:ss.t"),
"My Podcast" => _("My Podcast"),
'Import' => _('Import'),
'Imported?' => _('Imported?'),
'View' => _('View'),
'Error code: ' => _('Error code: '),
'Error msg: ' => _('Error msg: '),
'Input must be a positive number' => _('Input must be a positive number'),
'Input must be a number' => _('Input must be a number'),
'Input must be in the format: yyyy-mm-dd' => _('Input must be in the format: yyyy-mm-dd'),
'Input must be in the format: hh:mm:ss.t' => _('Input must be in the format: hh:mm:ss.t'),
'My Podcast' => _('My Podcast'),
//library/plupload.js
"You are currently uploading files. %sGoing to another screen will cancel the upload process. %sAre you sure you want to leave the page?"
=> _("You are currently uploading files. %sGoing to another screen will cancel the upload process. %sAre you sure you want to leave the page?"),
'You are currently uploading files. %sGoing to another screen will cancel the upload process. %sAre you sure you want to leave the page?' => _('You are currently uploading files. %sGoing to another screen will cancel the upload process. %sAre you sure you want to leave the page?'),
//library/spl.js
"Open Media Builder" => _("Open Media Builder"),
'Open Media Builder' => _('Open Media Builder'),
"please put in a time '00:00:00 (.0)'" => _("please put in a time '00:00:00 (.0)'"),
"Please enter a valid time in seconds. Eg. 0.5'" => _("Please enter a valid time in seconds. Eg. 0.5"),
"Your browser does not support playing this file type: " => _("Your browser does not support playing this file type: "),
"Dynamic block is not previewable" => _("Dynamic block is not previewable"),
"Limit to: " => _("Limit to: "),
"Playlist saved" => _("Playlist saved"),
"Playlist shuffled" => _("Playlist shuffled"),
"Airtime is unsure about the status of this file. This can happen when the file is on a remote drive that is unaccessible or the file is in a directory that isn't 'watched' anymore."
=> _("Airtime is unsure about the status of this file. This can happen when the file is on a remote drive that is unaccessible or the file is in a directory that isn't 'watched' anymore."),
"Please enter a valid time in seconds. Eg. 0.5'" => _('Please enter a valid time in seconds. Eg. 0.5'),
'Your browser does not support playing this file type: ' => _('Your browser does not support playing this file type: '),
'Dynamic block is not previewable' => _('Dynamic block is not previewable'),
'Limit to: ' => _('Limit to: '),
'Playlist saved' => _('Playlist saved'),
'Playlist shuffled' => _('Playlist shuffled'),
"Airtime is unsure about the status of this file. This can happen when the file is on a remote drive that is unaccessible or the file is in a directory that isn't 'watched' anymore." => _("Airtime is unsure about the status of this file. This can happen when the file is on a remote drive that is unaccessible or the file is in a directory that isn't 'watched' anymore."),
//listenerstat/listenerstat.js
"Listener Count on %s: %s" => _("Listener Count on %s: %s"),
'Listener Count on %s: %s' => _('Listener Count on %s: %s'),
//nowplaying/register.js
"Remind me in 1 week" => _("Remind me in 1 week"),
"Remind me never" => _("Remind me never"),
"Yes, help Airtime" => _("Yes, help Airtime"),
"Image must be one of jpg, jpeg, png, or gif" => _("Image must be one of jpg, jpeg, png, or gif"),
'Remind me in 1 week' => _('Remind me in 1 week'),
'Remind me never' => _('Remind me never'),
'Yes, help Airtime' => _('Yes, help Airtime'),
'Image must be one of jpg, jpeg, png, or gif' => _('Image must be one of jpg, jpeg, png, or gif'),
//playlist/smart_blockbuilder.js
"A static smart block will save the criteria and generate the block content immediately. This allows you to edit and view it in the Library before adding it to a show."
=> _("A static smart block will save the criteria and generate the block content immediately. This allows you to edit and view it in the Library before adding it to a show."),
"A dynamic smart block will only save the criteria. The block content will get generated upon adding it to a show. You will not be able to view and edit the content in the Library."
=> _("A dynamic smart block will only save the criteria. The block content will get generated upon adding it to a show. You will not be able to view and edit the content in the Library."),
"The desired block length will not be reached if %s cannot find enough unique tracks to match your criteria. Enable this option if you wish to allow tracks to be added multiple times to the smart block."
=> _("The desired block length will not be reached if %s cannot find enough unique tracks to match your criteria. Enable this option if you wish to allow tracks to be added multiple times to the smart block."),
"Smart block shuffled" => _("Smart block shuffled"),
"Smart block generated and criteria saved" => _("Smart block generated and criteria saved"),
"Smart block saved" => _("Smart block saved"),
"Processing..." => _("Processing..."),
"Select modifier" => _("Select modifier"),
"contains" => _("contains"),
"does not contain" => _("does not contain"),
"is" => _("is"),
"is not" => _("is not"),
"starts with" => _("starts with"),
"ends with" => _("ends with"),
"is greater than" => _("is greater than"),
"is less than" => _("is less than"),
"is in the range" => _("is in the range"),
"Preview" => _("Preview"),
"Generate" => _("Generate"),
//preferences/musicdirs.js
"Choose Storage Folder" => _("Choose Storage Folder"),
"Choose Folder to Watch" => _("Choose Folder to Watch"),
"Are you sure you want to change the storage folder?\nThis will remove the files from your Airtime library!"
=> _("Are you sure you want to change the storage folder?\nThis will remove the files from your Airtime library!"),
"Manage Media Folders" => _("Manage Media Folders"),
"Are you sure you want to remove the watched folder?" => _("Are you sure you want to remove the watched folder?"),
"This path is currently not accessible." => _("This path is currently not accessible."),
'A static smart block will save the criteria and generate the block content immediately. This allows you to edit and view it in the Library before adding it to a show.' => _('A static smart block will save the criteria and generate the block content immediately. This allows you to edit and view it in the Library before adding it to a show.'),
'A dynamic smart block will only save the criteria. The block content will get generated upon adding it to a show. You will not be able to view and edit the content in the Library.' => _('A dynamic smart block will only save the criteria. The block content will get generated upon adding it to a show. You will not be able to view and edit the content in the Library.'),
'The desired block length will not be reached if %s cannot find enough unique tracks to match your criteria. Enable this option if you wish to allow tracks to be added multiple times to the smart block.' => _('The desired block length will not be reached if %s cannot find enough unique tracks to match your criteria. Enable this option if you wish to allow tracks to be added multiple times to the smart block.'),
'Smart block shuffled' => _('Smart block shuffled'),
'Smart block generated and criteria saved' => _('Smart block generated and criteria saved'),
'Smart block saved' => _('Smart block saved'),
'Processing...' => _('Processing...'),
'Select modifier' => _('Select modifier'),
'contains' => _('contains'),
'does not contain' => _('does not contain'),
'is' => _('is'),
'is not' => _('is not'),
'starts with' => _('starts with'),
'ends with' => _('ends with'),
'is greater than' => _('is greater than'),
'is less than' => _('is less than'),
'is in the range' => _('is in the range'),
'Preview' => _('Preview'),
'Generate' => _('Generate'),
//preferences/musicdirs.js
'Choose Storage Folder' => _('Choose Storage Folder'),
'Choose Folder to Watch' => _('Choose Folder to Watch'),
"Are you sure you want to change the storage folder?\nThis will remove the files from your Airtime library!" => _("Are you sure you want to change the storage folder?\nThis will remove the files from your Airtime library!"),
'Manage Media Folders' => _('Manage Media Folders'),
'Are you sure you want to remove the watched folder?' => _('Are you sure you want to remove the watched folder?'),
'This path is currently not accessible.' => _('This path is currently not accessible.'),
//preferences/streamsetting.js
"Some stream types require extra configuration. Details about enabling %sAAC+ Support%s or %sOpus Support%s are provided." => _("Some stream types require extra configuration. Details about enabling %sAAC+ Support%s or %sOpus Support%s are provided."),
"Connected to the streaming server" => _("Connected to the streaming server"),
"The stream is disabled" => _("The stream is disabled"),
"Getting information from the server..." => _("Getting information from the server..."),
"Can not connect to the streaming server" => _("Can not connect to the streaming server"),
"If %s is behind a router or firewall, you may need to configure port forwarding and this field information will be incorrect. In this case you will need to manually update this field so it shows the correct host/port/mount that your DJ's need to connect to. The allowed range is between 1024 and 49151."
=> _("If %s is behind a router or firewall, you may need to configure port forwarding and this field information will be incorrect. In this case you will need to manually update this field so it shows the correct host/port/mount that your DJ's need to connect to. The allowed range is between 1024 and 49151."),
"For more details, please read the %s%s Manual%s" => _("For more details, please read the %s%s Manual%s"),
"Check this option to enable metadata for OGG streams (stream metadata is the track title, artist, and show name that is displayed in an audio player). VLC and mplayer have a serious bug when playing an OGG/VORBIS stream that has metadata information enabled: they will disconnect from the stream after every song. If you are using an OGG stream and your listeners do not require support for these audio players, then feel free to enable this option."
=> _("Check this option to enable metadata for OGG streams (stream metadata is the track title, artist, and show name that is displayed in an audio player). VLC and mplayer have a serious bug when playing an OGG/VORBIS stream that has metadata information enabled: they will disconnect from the stream after every song. If you are using an OGG stream and your listeners do not require support for these audio players, then feel free to enable this option."),
"Check this box to automatically switch off Master/Show source upon source disconnection." => _("Check this box to automatically switch off Master/Show source upon source disconnection."),
"Check this box to automatically switch on Master/Show source upon source connection." => _("Check this box to automatically switch on Master/Show source upon source connection."),
'Some stream types require extra configuration. Details about enabling %sAAC+ Support%s or %sOpus Support%s are provided.' => _('Some stream types require extra configuration. Details about enabling %sAAC+ Support%s or %sOpus Support%s are provided.'),
'Connected to the streaming server' => _('Connected to the streaming server'),
'The stream is disabled' => _('The stream is disabled'),
'Getting information from the server...' => _('Getting information from the server...'),
'Can not connect to the streaming server' => _('Can not connect to the streaming server'),
"If %s is behind a router or firewall, you may need to configure port forwarding and this field information will be incorrect. In this case you will need to manually update this field so it shows the correct host/port/mount that your DJ's need to connect to. The allowed range is between 1024 and 49151." => _("If %s is behind a router or firewall, you may need to configure port forwarding and this field information will be incorrect. In this case you will need to manually update this field so it shows the correct host/port/mount that your DJ's need to connect to. The allowed range is between 1024 and 49151."),
'For more details, please read the %s%s Manual%s' => _('For more details, please read the %s%s Manual%s'),
'Check this option to enable metadata for OGG streams (stream metadata is the track title, artist, and show name that is displayed in an audio player). VLC and mplayer have a serious bug when playing an OGG/VORBIS stream that has metadata information enabled: they will disconnect from the stream after every song. If you are using an OGG stream and your listeners do not require support for these audio players, then feel free to enable this option.' => _('Check this option to enable metadata for OGG streams (stream metadata is the track title, artist, and show name that is displayed in an audio player). VLC and mplayer have a serious bug when playing an OGG/VORBIS stream that has metadata information enabled: they will disconnect from the stream after every song. If you are using an OGG stream and your listeners do not require support for these audio players, then feel free to enable this option.'),
'Check this box to automatically switch off Master/Show source upon source disconnection.' => _('Check this box to automatically switch off Master/Show source upon source disconnection.'),
'Check this box to automatically switch on Master/Show source upon source connection.' => _('Check this box to automatically switch on Master/Show source upon source connection.'),
"If your Icecast server expects a username of 'source', this field can be left blank." => _("If your Icecast server expects a username of 'source', this field can be left blank."),
"If your live streaming client does not ask for a username, this field should be 'source'." => _("If your live streaming client does not ask for a username, this field should be 'source'."),
"WARNING: This will restart your stream and may cause a short dropout for your listeners!" => _("WARNING: This will restart your stream and may cause a short dropout for your listeners!"),
"This is the admin username and password for Icecast/SHOUTcast to get listener statistics." => _("This is the admin username and password for Icecast/SHOUTcast to get listener statistics."),
'WARNING: This will restart your stream and may cause a short dropout for your listeners!' => _('WARNING: This will restart your stream and may cause a short dropout for your listeners!'),
'This is the admin username and password for Icecast/SHOUTcast to get listener statistics.' => _('This is the admin username and password for Icecast/SHOUTcast to get listener statistics.'),
//preferences/support-setting.js
"Image must be one of jpg, jpeg, png, or gif" => _("Image must be one of jpg, jpeg, png, or gif"),
'Image must be one of jpg, jpeg, png, or gif' => _('Image must be one of jpg, jpeg, png, or gif'),
//schedule/add-show.js
"Warning: You cannot change this field while the show is currently playing" => _("Warning: You cannot change this field while the show is currently playing"),
"No result found" => _("No result found"),
"This follows the same security pattern for the shows: only users assigned to the show can connect." => _("This follows the same security pattern for the shows: only users assigned to the show can connect."),
"Specify custom authentication which will work only for this show." => _("Specify custom authentication which will work only for this show."),
'Warning: You cannot change this field while the show is currently playing' => _('Warning: You cannot change this field while the show is currently playing'),
'No result found' => _('No result found'),
'This follows the same security pattern for the shows: only users assigned to the show can connect.' => _('This follows the same security pattern for the shows: only users assigned to the show can connect.'),
'Specify custom authentication which will work only for this show.' => _('Specify custom authentication which will work only for this show.'),
"If your live streaming client does not ask for a username, this field should be 'source'." => _("If your live streaming client does not ask for a username, this field should be 'source'."),
"The show instance doesn't exist anymore!" => _("The show instance doesn't exist anymore!"),
"Warning: Shows cannot be re-linked" => _("Warning: Shows cannot be re-linked"),
"By linking your repeating shows any media items scheduled in any repeat show will also get scheduled in the other repeat shows" => _("By linking your repeating shows any media items scheduled in any repeat show will also get scheduled in the other repeat shows"),
"Timezone is set to the station timezone by default. Shows in the calendar will be displayed in your local time defined by the Interface Timezone in your user settings." => _("Timezone is set to the station timezone by default. Shows in the calendar will be displayed in your local time defined by the Interface Timezone in your user settings."),
'Warning: Shows cannot be re-linked' => _('Warning: Shows cannot be re-linked'),
'By linking your repeating shows any media items scheduled in any repeat show will also get scheduled in the other repeat shows' => _('By linking your repeating shows any media items scheduled in any repeat show will also get scheduled in the other repeat shows'),
'Timezone is set to the station timezone by default. Shows in the calendar will be displayed in your local time defined by the Interface Timezone in your user settings.' => _('Timezone is set to the station timezone by default. Shows in the calendar will be displayed in your local time defined by the Interface Timezone in your user settings.'),
//schedule/full-calendar-functions
//already in schedule/add-show.js
//"The show instance doesn't exist anymore!" => _("The show instance doesn't exist anymore!"),
"Show" => _("Show"),
"Show is empty" => _("Show is empty"),
"1m" => _("1m"),
"5m" => _("5m"),
"10m" => _("10m"),
"15m" => _("15m"),
"30m" => _("30m"),
"60m" => _("60m"),
"Uploading in progress..." => _("Uploading in progress..."),
"Retreiving data from the server..." => _("Retreiving data from the server..."),
"This show has no scheduled content." => _("This show has no scheduled content."),
"This show is not completely filled with content." => _("This show is not completely filled with content."),
'Show' => _('Show'),
'Show is empty' => _('Show is empty'),
'1m' => _('1m'),
'5m' => _('5m'),
'10m' => _('10m'),
'15m' => _('15m'),
'30m' => _('30m'),
'60m' => _('60m'),
'Uploading in progress...' => _('Uploading in progress...'),
'Retreiving data from the server...' => _('Retreiving data from the server...'),
'This show has no scheduled content.' => _('This show has no scheduled content.'),
'This show is not completely filled with content.' => _('This show is not completely filled with content.'),
//already in schedule/add-show.js
//"The show instance doesn"t exist anymore!" => _("The show instance doesn"t exist anymore!"),
//schedule/schedule.js
"January" => _("January"),
"February" => _("February"),
"March" => _("March"),
"April" => _("April"),
"May" => _("May"),
"June" => _("June"),
"July" => _("July"),
"August" => _("August"),
"September" => _("September"),
"October" => _("October"),
"November" => _("November"),
"December" => _("December"),
"Jan" => _("Jan"),
"Feb" => _("Feb"),
"Mar" => _("Mar"),
"Apr" => _("Apr"),
"May" => _("May"),
"Jun" => _("Jun"),
"Jul" => _("Jul"),
"Aug" => _("Aug"),
"Sep" => _("Sep"),
"Oct" => _("Oct"),
"Nov" => _("Nov"),
"Dec" => _("Dec"),
"Today" => _("Today"),
"Day" => _("Day"),
"Week" => _("Week"),
"Month" => _("Month"),
"Sunday" => _("Sunday"),
"Monday" => _("Monday"),
"Tuesday" => _("Tuesday"),
"Wednesday" => _("Wednesday"),
"Thursday" => _("Thursday"),
"Friday" => _("Friday"),
"Saturday" => _("Saturday"),
"Sun" => _("Sun"),
"Mon" => _("Mon"),
"Tue" => _("Tue"),
"Wed" => _("Wed"),
"Thu" => _("Thu"),
"Fri" => _("Fri"),
"Sat" => _("Sat"),
"Shows longer than their scheduled time will be cut off by a following show." => _("Shows longer than their scheduled time will be cut off by a following show."),
"Cancel Current Show?" => _("Cancel Current Show?"),
"Stop recording current show?" => _("Stop recording current show?"),
"Ok" => _("Ok"),
"Contents of Show" => _("Contents of Show"),
'January' => _('January'),
'February' => _('February'),
'March' => _('March'),
'April' => _('April'),
'May' => _('May'),
'June' => _('June'),
'July' => _('July'),
'August' => _('August'),
'September' => _('September'),
'October' => _('October'),
'November' => _('November'),
'December' => _('December'),
'Jan' => _('Jan'),
'Feb' => _('Feb'),
'Mar' => _('Mar'),
'Apr' => _('Apr'),
'May' => _('May'),
'Jun' => _('Jun'),
'Jul' => _('Jul'),
'Aug' => _('Aug'),
'Sep' => _('Sep'),
'Oct' => _('Oct'),
'Nov' => _('Nov'),
'Dec' => _('Dec'),
'Today' => _('Today'),
'Day' => _('Day'),
'Week' => _('Week'),
'Month' => _('Month'),
'Sunday' => _('Sunday'),
'Monday' => _('Monday'),
'Tuesday' => _('Tuesday'),
'Wednesday' => _('Wednesday'),
'Thursday' => _('Thursday'),
'Friday' => _('Friday'),
'Saturday' => _('Saturday'),
'Sun' => _('Sun'),
'Mon' => _('Mon'),
'Tue' => _('Tue'),
'Wed' => _('Wed'),
'Thu' => _('Thu'),
'Fri' => _('Fri'),
'Sat' => _('Sat'),
'Shows longer than their scheduled time will be cut off by a following show.' => _('Shows longer than their scheduled time will be cut off by a following show.'),
'Cancel Current Show?' => _('Cancel Current Show?'),
'Stop recording current show?' => _('Stop recording current show?'),
'Ok' => _('Ok'),
'Contents of Show' => _('Contents of Show'),
//already in schedule/add-show.js
//"The show instance doesn"t exist anymore!" => _("The show instance doesn"t exist anymore!"),
"Remove all content?" => _("Remove all content?"),
'Remove all content?' => _('Remove all content?'),
//showbuilder/builder.js
"Delete selected item(s)?" => _("Delete selected item(s)?"),
"Start" => _("Start"),
"End" => _("End"),
"Duration" => _("Duration"),
"Filtering out " => _("Filtering out "),
" of " => _(" of "),
" records" => _(" records"),
"There are no shows scheduled during the specified time period." => _("There are no shows scheduled during the specified time period."),
'Delete selected item(s)?' => _('Delete selected item(s)?'),
'Start' => _('Start'),
'End' => _('End'),
'Duration' => _('Duration'),
'Filtering out ' => _('Filtering out '),
' of ' => _(' of '),
' records' => _(' records'),
'There are no shows scheduled during the specified time period.' => _('There are no shows scheduled during the specified time period.'),
//already in library/library.js
//"Title" => _("Title"),
//"Creator" => _("Creator"),
//"Album" => _("Album"),
//"Mime" => _("Mime"),
"Cue In" => _("Cue In"),
"Cue Out" => _("Cue Out"),
"Fade In" => _("Fade In"),
"Fade Out" => _("Fade Out"),
"Show Empty" => _("Show Empty"),
"Recording From Line In" => _("Recording From Line In"),
"Track preview" => _("Track preview"),
'Cue In' => _('Cue In'),
'Cue Out' => _('Cue Out'),
'Fade In' => _('Fade In'),
'Fade Out' => _('Fade Out'),
'Show Empty' => _('Show Empty'),
'Recording From Line In' => _('Recording From Line In'),
'Track preview' => _('Track preview'),
//already in library/spl.js
//"Airtime is unsure about the status of this file. This can happen when the file is on a remote drive that is unaccessible or the file is in a directory that isn"t "watched" anymore."
//=> _("Airtime is unsure about the status of this file. This can happen when the file is on a remote drive that is unaccessible or the file is in a directory that isn"t "watched" anymore."),
"Cannot schedule outside a show." => _("Cannot schedule outside a show."),
"Moving 1 Item" => _("Moving 1 Item"),
"Moving %s Items" => _("Moving %s Items"),
"Save" => _("Save"),
"Cancel" => _("Cancel"),
"Fade Editor" => _("Fade Editor"),
"Cue Editor" => _("Cue Editor"),
"Waveform features are available in a browser supporting the Web Audio API" => _("Waveform features are available in a browser supporting the Web Audio API"),
//=> _("Airtime is unsure about the status of this file. This can happen when the file is on a remote drive that is unaccessible or the file is in a directory that isn"t "watched" anymore."),
'Cannot schedule outside a show.' => _('Cannot schedule outside a show.'),
'Moving 1 Item' => _('Moving 1 Item'),
'Moving %s Items' => _('Moving %s Items'),
'Save' => _('Save'),
'Cancel' => _('Cancel'),
'Fade Editor' => _('Fade Editor'),
'Cue Editor' => _('Cue Editor'),
'Waveform features are available in a browser supporting the Web Audio API' => _('Waveform features are available in a browser supporting the Web Audio API'),
//already in library/library.js
//"Select" => _("Select"),
"Select all" => _("Select all"),
"Select none" => _("Select none"),
"Trim overbooked shows" => _("Trim overbooked shows"),
"Remove selected scheduled items" => _("Remove selected scheduled items"),
"Jump to the current playing track" => _("Jump to the current playing track"),
"Jump to Current" => _("Jump to Current"),
"Cancel current show" => _("Cancel current show"),
'Select all' => _('Select all'),
'Select none' => _('Select none'),
'Trim overbooked shows' => _('Trim overbooked shows'),
'Remove selected scheduled items' => _('Remove selected scheduled items'),
'Jump to the current playing track' => _('Jump to the current playing track'),
'Jump to Current' => _('Jump to Current'),
'Cancel current show' => _('Cancel current show'),
//already in schedule/schedule.js
//"Cancel Current Show?" => _("Cancel Current Show?"),
"Stop recording current show?" => _("Stop recording current show?"),
'Stop recording current show?' => _('Stop recording current show?'),
//showbuilder/main_builder.js
"Open library to add or remove content" => _("Open library to add or remove content"),
"Add / Remove Content" => _("Add / Remove Content"),
'Open library to add or remove content' => _('Open library to add or remove content'),
'Add / Remove Content' => _('Add / Remove Content'),
//status/status.js
"in use" => _("in use"),
"Disk" => _("Disk"),
'in use' => _('in use'),
'Disk' => _('Disk'),
//serverbrowse/serverbrowse.js
"Look in" => _("Look in"),
"Cancel" => _("Cancel"),
"Open" => _("Open"),
'Look in' => _('Look in'),
'Cancel' => _('Cancel'),
'Open' => _('Open'),
//user/user.js
"Admin" => _("Admin"),
"DJ" => _("DJ"),
"Program Manager" => _("Program Manager"),
"Guest" => _("Guest"),
"Guests can do the following:" => _("Guests can do the following:"),
"View schedule" => _("View schedule"),
"View show content" => _("View show content"),
"DJs can do the following:" => _("DJs can do the following:"),
"Manage assigned show content" => _("Manage assigned show content"),
"Import media files" => _("Import media files"),
"Create playlists, smart blocks, and webstreams" => _("Create playlists, smart blocks, and webstreams"),
"Manage their own library content" => _("Manage their own library content"),
"Program Managers can do the following:" => _("Program Managers can do the following:"),
"View and manage show content" => _("View and manage show content"),
"Schedule shows" => _("Schedule shows"),
"Manage all library content" => _("Manage all library content"),
"Admins can do the following:" => _("Admins can do the following:"),
"Manage preferences" => _("Manage preferences"),
"Manage users" => _("Manage users"),
"Manage watched folders" => _("Manage watched folders"),
"Send support feedback" => _("Send support feedback"),
"View system status" => _("View system status"),
"Access playout history" => _("Access playout history"),
"View listener stats" => _("View listener stats"),
'Admin' => _('Admin'),
'DJ' => _('DJ'),
'Program Manager' => _('Program Manager'),
'Guest' => _('Guest'),
'Guests can do the following:' => _('Guests can do the following:'),
'View schedule' => _('View schedule'),
'View show content' => _('View show content'),
'DJs can do the following:' => _('DJs can do the following:'),
'Manage assigned show content' => _('Manage assigned show content'),
'Import media files' => _('Import media files'),
'Create playlists, smart blocks, and webstreams' => _('Create playlists, smart blocks, and webstreams'),
'Manage their own library content' => _('Manage their own library content'),
'Program Managers can do the following:' => _('Program Managers can do the following:'),
'View and manage show content' => _('View and manage show content'),
'Schedule shows' => _('Schedule shows'),
'Manage all library content' => _('Manage all library content'),
'Admins can do the following:' => _('Admins can do the following:'),
'Manage preferences' => _('Manage preferences'),
'Manage users' => _('Manage users'),
'Manage watched folders' => _('Manage watched folders'),
'Send support feedback' => _('Send support feedback'),
'View system status' => _('View system status'),
'Access playout history' => _('Access playout history'),
'View listener stats' => _('View listener stats'),
//dataTables/ColVis.js
"Show / hide columns" => _("Show / hide columns"),
"Columns" => _("Columns"),
'Show / hide columns' => _('Show / hide columns'),
'Columns' => _('Columns'),
//datatables.columnFilter.js
"From {from} to {to}" => _("From {from} to {to}"),
"kbps" => _("kbps"),
"yyyy-mm-dd" => _("yyyy-mm-dd"),
"hh:mm:ss.t" => _("hh:mm:ss.t"),
"kHz" => _("kHz"),
'From {from} to {to}' => _('From {from} to {to}'),
'kbps' => _('kbps'),
'yyyy-mm-dd' => _('yyyy-mm-dd'),
'hh:mm:ss.t' => _('hh:mm:ss.t'),
'kHz' => _('kHz'),
//datepicker
//months are already in schedule/schedule.js
"Su" => _("Su"),
"Mo" => _("Mo"),
"Tu" => _("Tu"),
"We" => _("We"),
"Th" => _("Th"),
"Fr" => _("Fr"),
"Sa" => _("Sa"),
"Close" => _("Close"),
'Su' => _('Su'),
'Mo' => _('Mo'),
'Tu' => _('Tu'),
'We' => _('We'),
'Th' => _('Th'),
'Fr' => _('Fr'),
'Sa' => _('Sa'),
'Close' => _('Close'),
//timepicker
"Hour" => _("Hour"),
"Minute" => _("Minute"),
"Done" => _("Done"),
'Hour' => _('Hour'),
'Minute' => _('Minute'),
'Done' => _('Done'),
//plupload ships with translation files but a lot are incomplete
//so we will keep them here to prevent incomplete translations
"Select files" => _("Select files"),
"Add files to the upload queue and click the start button." => _("Add files to the upload queue and click the start button."),
"Filename" => _("Add files to the upload queue and click the start button."),
"Status" => _("Status"),
"Size" => _("Status"),
"Add Files" => _("Add Files"),
"Stop Upload" => _("Stop Upload"),
"Start upload" => _("Start upload"),
"Add files" => _("Add files"),
"Uploaded %d/%d files"=> _("Uploaded %d/%d files"),
"N/A" => _("N/A"),
"Drag files here." => _("Drag files here."),
"File extension error." => _("File extension error."),
"File size error." => _("File size error."),
"File count error." => _("File count error."),
"Init error." => _("Init error."),
"HTTP Error." => _("HTTP Error."),
"Security error." => _("Security error."),
"Generic error." => _("Generic error."),
"IO error." => _("IO error."),
"File: %s" => _("File: %s"),
"Close" => _("Close"),
"%d files queued" => _("%d files queued"),
"File: %f, size: %s, max file size: %m" => _("File: %f, size: %s, max file size: %m"),
'Select files' => _('Select files'),
'Add files to the upload queue and click the start button.' => _('Add files to the upload queue and click the start button.'),
'Filename' => _('Add files to the upload queue and click the start button.'),
'Status' => _('Status'),
'Size' => _('Status'),
'Add Files' => _('Add Files'),
'Stop Upload' => _('Stop Upload'),
'Start upload' => _('Start upload'),
'Add files' => _('Add files'),
'Uploaded %d/%d files' => _('Uploaded %d/%d files'),
'N/A' => _('N/A'),
'Drag files here.' => _('Drag files here.'),
'File extension error.' => _('File extension error.'),
'File size error.' => _('File size error.'),
'File count error.' => _('File count error.'),
'Init error.' => _('Init error.'),
'HTTP Error.' => _('HTTP Error.'),
'Security error.' => _('Security error.'),
'Generic error.' => _('Generic error.'),
'IO error.' => _('IO error.'),
'File: %s' => _('File: %s'),
'Close' => _('Close'),
'%d files queued' => _('%d files queued'),
'File: %f, size: %s, max file size: %m' => _('File: %f, size: %s, max file size: %m'),
"Upload URL might be wrong or doesn't exist" => _("Upload URL might be wrong or doesn't exist"),
"Error: File too large: " => _("Error: File too large: "),
"Error: Invalid file extension: " => _("Error: Invalid file extension: "),
'Error: File too large: ' => _('Error: File too large: '),
'Error: Invalid file extension: ' => _('Error: Invalid file extension: '),
//history translations
"Set Default" => _("Set Default"),
"Create Entry" => _("Create Entry"),
"Edit History Record" => _("Edit History Record"),
"No Show" => _("No Show"),
"All" => _("All"),
"Copied %s row%s to the clipboard" => _("Copied %s row%s to the clipboard"),
'Set Default' => _('Set Default'),
'Create Entry' => _('Create Entry'),
'Edit History Record' => _('Edit History Record'),
'No Show' => _('No Show'),
'All' => _('All'),
'Copied %s row%s to the clipboard' => _('Copied %s row%s to the clipboard'),
"%sPrint view%sPlease use your browser's print function to print this table. Press escape when finished." => _("%sPrint view%sPlease use your browser's print function to print this table. Press escape when finished."),
"New Show" => _("New Show"),
"New Log Entry" => _("New Log Entry"),
'New Show' => _('New Show'),
'New Log Entry' => _('New Log Entry'),
//Datatables:
"No data available in table" => _("No data available in table"),
"(filtered from _MAX_ total entries)" => _("(filtered from _MAX_ total entries)"),
": activate to sort column ascending",
": activate to sort column descending",
'No data available in table' => _('No data available in table'),
'(filtered from _MAX_ total entries)' => _('(filtered from _MAX_ total entries)'),
': activate to sort column ascending',
': activate to sort column descending',
//End of datatables
//New entries from .js "" => _(""),
"First" => _("First"),
"Last" => _("Last"),
"Next" => _("Next"),
"Previous" => _("Previous"),
"Search:" => _("Search:"),
"No matching records found" => _("No matching records found"),
"Drag tracks here from the library" => _("Drag tracks here from the library"),
"No tracks were played during the selected time period." => _("No tracks were played during the selected time period."),
"Unpublish" => _("Unpublish"),
"No matching results found." => _("No matching results found."),
"Author" => _("Author"),
"Description" => _("Description"),
"Link" => _("Link"),
"Publication Date" => _("Publication Date"),
"Import Status" => _("Import Status"),
"Actions" => _("Actions"),
"Delete from Library" => _("Delete from Library"),
"Successfully imported" => _("Successfully imported"),
"No matching records found" => _("No matching records found"),
"Show _MENU_" => _("Show _MENU_"),
"Show _MENU_ entries" => _("Show _MENU_ entries"),
"Showing _START_ to _END_ of _TOTAL_ entries" => _("Showing _START_ to _END_ of _TOTAL_ entries"),
"Showing _START_ to _END_ of _TOTAL_ tracks" => _("Showing _START_ to _END_ of _TOTAL_ tracks"),
"Showing _START_ to _END_ of _TOTAL_ track types" => _("Showing _START_ to _END_ of _TOTAL_ track types"),
"Showing _START_ to _END_ of _TOTAL_ users" => _("Showing _START_ to _END_ of _TOTAL_ users"),
"Showing 0 to 0 of 0 entries" => _("Showing 0 to 0 of 0 entries"),
"Showing 0 to 0 of 0 tracks" => _("Showing 0 to 0 of 0 tracks"),
"Showing 0 to 0 of 0 track types" => _("Showing 0 to 0 of 0 track types"),
"(filtered from _MAX_ total track types)" => _("(filtered from _MAX_ total track types)"),
//"This is used for tracks containing music." => _("This is used for tracks containing music."),
"Are you sure you want to delete this tracktype?" => _("Are you sure you want to delete this tracktype?"),
"No track types were found." => _("No track types were found."),
"No track types found" => _("No track types found"),
"No matching track types found" => _("No matching track types found"),
"Enabled" => _("Enabled"),
"Disabled" => _("Disabled"),
"Cancel upload" => _("Cancel upload"),
"Type" => _("Type"),
"Autoloading playlists' contents are added to shows one hour before the show airs. <a target='_blank' href='http://libretime.org/docs/playlists'>More information</a>" => _("Autoloading playlists' contents are added to shows one hour before the show airs. <a target='_blank' href='http://libretime.org/docs/playlists'>More information</a>"),
"Podcast settings saved" => _("Podcast settings saved"),
"Are you sure you want to delete this user?" => _("Are you sure you want to delete this user?"),
"Can't delete yourself!" => _("Can't delete yourself!"),
"You haven't published any episodes!" => _("You haven't published any episodes!"),
"You can publish your uploaded content from the 'Tracks' view." => _("You can publish your uploaded content from the 'Tracks' view."),
"Try it now" => _("Try it now"),
"<p>If this option is unchecked, the smartblock will schedule as many tracks as can be played out <strong>in their entirety</strong> within the specified duration. This will usually result in audio playback that is slightly less than the specified duration.</p><p>If this option is checked, the smartblock will also schedule one final track which will overflow the specified duration. This final track may be cut off mid-way if the show into which the smartblock is added finishes.</p>" => _("<p>If this option is unchecked, the smartblock will schedule as many tracks as can be played out <strong>in their entirety</strong> within the specified duration. This will usually result in audio playback that is slightly less than the specified duration.</p><p>If this option is checked, the smartblock will also schedule one final track which will overflow the specified duration. This final track may be cut off mid-way if the show into which the smartblock is added finishes.</p>"),
"Playlist preview" => _("Playlist preview"),
"Smart Block" => _("Smart Block"),
"Webstream preview" => _("Webstream preview"),
"You don't have permission to view the library." => _("You don't have permission to view the library."),
"Now" => _("Now"),
"Click 'New' to create one now." => _("Click 'New' to create one now."),
"Click 'Upload' to add some now." => _("Click 'Upload' to add some now."),
"Feed URL" => _("Feed URL"),
"Import Date" => _("Import Date"),
"Add New Podcast" => _("Add New Podcast"),
"Cannot schedule outside a show.\nTry creating a show first." => _("Cannot schedule outside a show.\nTry creating a show first."),
"No files have been uploaded yet." => _("No files have been uploaded yet."),
//"Value is required and can't be empty" => _("Value is required and can't be empty"),
//"mute" => _("mute"),
//"max volume" => _("max volume"),
//New entries from .js "" => _(""),
'First' => _('First'),
'Last' => _('Last'),
'Next' => _('Next'),
'Previous' => _('Previous'),
'Search:' => _('Search:'),
'No matching records found' => _('No matching records found'),
'Drag tracks here from the library' => _('Drag tracks here from the library'),
'No tracks were played during the selected time period.' => _('No tracks were played during the selected time period.'),
'Unpublish' => _('Unpublish'),
'No matching results found.' => _('No matching results found.'),
'Author' => _('Author'),
'Description' => _('Description'),
'Link' => _('Link'),
'Publication Date' => _('Publication Date'),
'Import Status' => _('Import Status'),
'Actions' => _('Actions'),
'Delete from Library' => _('Delete from Library'),
'Successfully imported' => _('Successfully imported'),
'No matching records found' => _('No matching records found'),
'Show _MENU_' => _('Show _MENU_'),
'Show _MENU_ entries' => _('Show _MENU_ entries'),
'Showing _START_ to _END_ of _TOTAL_ entries' => _('Showing _START_ to _END_ of _TOTAL_ entries'),
'Showing _START_ to _END_ of _TOTAL_ tracks' => _('Showing _START_ to _END_ of _TOTAL_ tracks'),
'Showing _START_ to _END_ of _TOTAL_ track types' => _('Showing _START_ to _END_ of _TOTAL_ track types'),
'Showing _START_ to _END_ of _TOTAL_ users' => _('Showing _START_ to _END_ of _TOTAL_ users'),
'Showing 0 to 0 of 0 entries' => _('Showing 0 to 0 of 0 entries'),
'Showing 0 to 0 of 0 tracks' => _('Showing 0 to 0 of 0 tracks'),
'Showing 0 to 0 of 0 track types' => _('Showing 0 to 0 of 0 track types'),
'(filtered from _MAX_ total track types)' => _('(filtered from _MAX_ total track types)'),
//"This is used for tracks containing music." => _("This is used for tracks containing music."),
'Are you sure you want to delete this tracktype?' => _('Are you sure you want to delete this tracktype?'),
'No track types were found.' => _('No track types were found.'),
'No track types found' => _('No track types found'),
'No matching track types found' => _('No matching track types found'),
'Enabled' => _('Enabled'),
'Disabled' => _('Disabled'),
'Cancel upload' => _('Cancel upload'),
'Type' => _('Type'),
"Autoloading playlists' contents are added to shows one hour before the show airs. <a target='_blank' href='http://libretime.org/docs/playlists'>More information</a>" => _("Autoloading playlists' contents are added to shows one hour before the show airs. <a target='_blank' href='http://libretime.org/docs/playlists'>More information</a>"),
'Podcast settings saved' => _('Podcast settings saved'),
'Are you sure you want to delete this user?' => _('Are you sure you want to delete this user?'),
"Can't delete yourself!" => _("Can't delete yourself!"),
"You haven't published any episodes!" => _("You haven't published any episodes!"),
"You can publish your uploaded content from the 'Tracks' view." => _("You can publish your uploaded content from the 'Tracks' view."),
'Try it now' => _('Try it now'),
'<p>If this option is unchecked, the smartblock will schedule as many tracks as can be played out <strong>in their entirety</strong> within the specified duration. This will usually result in audio playback that is slightly less than the specified duration.</p><p>If this option is checked, the smartblock will also schedule one final track which will overflow the specified duration. This final track may be cut off mid-way if the show into which the smartblock is added finishes.</p>' => _('<p>If this option is unchecked, the smartblock will schedule as many tracks as can be played out <strong>in their entirety</strong> within the specified duration. This will usually result in audio playback that is slightly less than the specified duration.</p><p>If this option is checked, the smartblock will also schedule one final track which will overflow the specified duration. This final track may be cut off mid-way if the show into which the smartblock is added finishes.</p>'),
'Playlist preview' => _('Playlist preview'),
'Smart Block' => _('Smart Block'),
'Webstream preview' => _('Webstream preview'),
"You don't have permission to view the library." => _("You don't have permission to view the library."),
'Now' => _('Now'),
"Click 'New' to create one now." => _("Click 'New' to create one now."),
"Click 'Upload' to add some now." => _("Click 'Upload' to add some now."),
'Feed URL' => _('Feed URL'),
'Import Date' => _('Import Date'),
'Add New Podcast' => _('Add New Podcast'),
"Cannot schedule outside a show.\nTry creating a show first." => _("Cannot schedule outside a show.\nTry creating a show first."),
'No files have been uploaded yet.' => _('No files have been uploaded yet.'),
//"Value is required and can't be empty" => _("Value is required and can't be empty"),
//"mute" => _("mute"),
//"max volume" => _("max volume"),
//embed player
"On Air" => _("On Air"),
"Off Air" => _("Off Air"),
"Offline" => _("Offline"),
"Nothing scheduled" => _("Nothing scheduled"),
"Click 'Add' to create one now." => _("Click 'Add' to create one now.")
);
'On Air' => _('On Air'),
'Off Air' => _('Off Air'),
'Offline' => _('Offline'),
'Nothing scheduled' => _('Nothing scheduled'),
"Click 'Add' to create one now." => _("Click 'Add' to create one now."),
];
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
header("Content-Type: text/javascript");
echo "var general_dict=" . json_encode($translations);
header('Content-Type: text/javascript');
echo 'var general_dict=' . json_encode($translations);
}
}

View File

@ -2,35 +2,32 @@
class LoginController extends Zend_Controller_Action
{
public function init()
{
$CC_CONFIG = Config::getConfig();
$baseUrl = Application_Common_OsPath::getBaseDir();
$this->view->headLink(array('rel' => 'icon', 'href' => $baseUrl . 'favicon.ico?' . $CC_CONFIG['airtime_version'], 'type' => 'image/x-icon'), 'PREPEND')
$this->view->headLink(['rel' => 'icon', 'href' => $baseUrl . 'favicon.ico?' . $CC_CONFIG['airtime_version'], 'type' => 'image/x-icon'], 'PREPEND')
->appendStylesheet($baseUrl . 'css/bootstrap.css?' . $CC_CONFIG['airtime_version'])
->appendStylesheet($baseUrl . 'css/redmond/jquery-ui-1.8.8.custom.css?' . $CC_CONFIG['airtime_version'])
->appendStylesheet($baseUrl . 'css/styles.css?' . $CC_CONFIG['airtime_version']);
->appendStylesheet($baseUrl . 'css/styles.css?' . $CC_CONFIG['airtime_version'])
;
}
public function indexAction()
{
$CC_CONFIG = Config::getConfig();
$request = $this->getRequest();
$response = $this->getResponse();
$stationLocale = Application_Model_Preference::GetDefaultLocale();
//Enable AJAX requests from www.airtime.pro for the sign-in process.
CORSHelper::enableCrossOriginRequests($request, $response);
Application_Model_Locale::configureLocalization($request->getcookie('airtime_locale', $stationLocale));
if (Zend_Session::isStarted()) {
//Open the session for writing, because we close it for writing by default in Bootstrap.php as an optimization.
SessionHelper::reopenSessionForWriting();
@ -46,19 +43,17 @@ class LoginController extends Zend_Controller_Action
$this->_helper->layout->setLayout('login');
$this->view->error = false;
$baseUrl = Application_Common_OsPath::getBaseDir();
$form = new Application_Form_Login();
$message = _("Please enter your username and password.");
$message = _('Please enter your username and password.');
if ($request->isPost()) {
//Open the session for writing, because we close it for writing by default in Bootstrap.php as an optimization.
//session_start();
if ($form->isValid($request->getPost())) {
//get the username and password from the form
$username = $form->getValue('username');
@ -69,8 +64,9 @@ class LoginController extends Zend_Controller_Action
//pass to the adapter the submitted username and password
$authAdapter->setIdentity($username)
->setCredential($password);
->setCredential($password)
;
$result = $auth->authenticate($authAdapter);
if ($result->isValid()) {
Zend_Session::regenerateId();
@ -142,11 +138,12 @@ class LoginController extends Zend_Controller_Action
if (empty($username)) {
$query->filterByDbEmail($email);
} else if (empty($email)) {
} elseif (empty($email)) {
$query->filterByDbLogin($username);
} else {
$query->filterByDbEmail($email)
->filterByDbLogin($username);
->filterByDbLogin($username)
;
}
$user = $query->findOne();
@ -157,13 +154,13 @@ class LoginController extends Zend_Controller_Action
if ($success) {
$this->_helper->redirector('password-restore-after', 'login');
} 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 {
$form->email->addError($this->view->translate(_("That username or email address could not be found.")));
$form->email->addError($this->view->translate(_('That username or email address could not be found.')));
}
} else { //Form is not valid
$form->email->addError($this->view->translate(_("There was a problem with the username or email address you entered.")));
$form->email->addError($this->view->translate(_('There was a problem with the username or email address you entered.')));
}
}
@ -174,7 +171,7 @@ class LoginController extends Zend_Controller_Action
{
$request = $this->getRequest();
$stationLocale = Application_Model_Preference::GetDefaultLocale();
Application_Model_Locale::configureLocalization($request->getcookie('airtime_locale', $stationLocale));
//uses separate layout without a navigation.
@ -187,25 +184,24 @@ class LoginController extends Zend_Controller_Action
$this->_helper->layout->setLayout('login');
$request = $this->getRequest();
$token = $request->getParam("token", false);
$user_id = $request->getParam("user_id", 0);
$token = $request->getParam('token', false);
$user_id = $request->getParam('user_id', 0);
$form = new Application_Form_PasswordChange();
$auth = new Application_Model_Auth();
$user = CcSubjsQuery::create()->findPK($user_id);
$stationLocale = Application_Model_Preference::GetDefaultLocale();
Application_Model_Locale::configureLocalization($request->getcookie('airtime_locale', $stationLocale));
//check validity of token
if (!$auth->checkToken($user_id, $token, 'password.restore')) {
Logging::debug("token not valid");
Logging::debug('token not valid');
$this->_helper->redirector('index', 'login');
}
if ($request->isPost() && $form->isValid($request->getPost())) {
$user->setDbPass(md5($form->password->getValue()));
$user->save();
@ -216,7 +212,8 @@ class LoginController extends Zend_Controller_Action
$authAdapter = Application_Model_Auth::getAuthAdapter();
$authAdapter->setIdentity($user->getDbLogin())
->setCredential($form->password->getValue());
->setCredential($form->password->getValue())
;
$zend_auth->authenticate($authAdapter);
@ -234,18 +231,20 @@ class LoginController extends Zend_Controller_Action
}
/**
* populates view with results from a login error and adds a new form
* populates view with results from a login error and adds a new form.
*
* @param string $username user that failed to login
*
* @param String $username user that failed to login
* @return new form
*/
private function loginError($username)
{
$this->view->message = _("Wrong username or password provided. Please try again.");
$this->view->message = _('Wrong username or password provided. Please try again.');
Application_Model_Subjects::increaseLoginAttempts($username);
Application_Model_LoginAttempts::increaseAttempts($_SERVER['REMOTE_ADDR']);
$form = new Application_Form_Login();
$form = new Application_Form_Login();
$this->view->error = true;
return $form;
}
}

View File

@ -1,37 +1,36 @@
<?php
class PlaylistController extends Zend_Controller_Action
{
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('add-items', 'json')
->addActionContext('move-items', 'json')
->addActionContext('delete-items', 'json')
->addActionContext('set-fade', 'json')
->addActionContext('set-crossfade', 'json')
->addActionContext('set-cue', 'json')
->addActionContext('new', 'json')
->addActionContext('edit', 'json')
->addActionContext('delete', 'json')
->addActionContext('close-playlist', 'json')
->addActionContext('play', 'json')
->addActionContext('set-playlist-fades', 'json')
->addActionContext('get-playlist-fades', 'json')
->addActionContext('set-playlist-name', 'json')
->addActionContext('set-playlist-description', 'json')
->addActionContext('playlist-preview', 'json')
->addActionContext('get-playlist', 'json')
->addActionContext('save', 'json')
->addActionContext('smart-block-generate', 'json')
->addActionContext('smart-block-shuffle', 'json')
->addActionContext('get-block-info', 'json')
->addActionContext('shuffle', 'json')
->addActionContext('empty-content', 'json')
->addActionContext('change-playlist', 'json')
->initContext();
->addActionContext('move-items', 'json')
->addActionContext('delete-items', 'json')
->addActionContext('set-fade', 'json')
->addActionContext('set-crossfade', 'json')
->addActionContext('set-cue', 'json')
->addActionContext('new', 'json')
->addActionContext('edit', 'json')
->addActionContext('delete', 'json')
->addActionContext('close-playlist', 'json')
->addActionContext('play', 'json')
->addActionContext('set-playlist-fades', 'json')
->addActionContext('get-playlist-fades', 'json')
->addActionContext('set-playlist-name', 'json')
->addActionContext('set-playlist-description', 'json')
->addActionContext('playlist-preview', 'json')
->addActionContext('get-playlist', 'json')
->addActionContext('save', 'json')
->addActionContext('smart-block-generate', 'json')
->addActionContext('smart-block-shuffle', 'json')
->addActionContext('get-block-info', 'json')
->addActionContext('shuffle', 'json')
->addActionContext('empty-content', 'json')
->addActionContext('change-playlist', 'json')
->initContext()
;
//This controller writes to the session all over the place, so we're going to reopen it for writing here.
SessionHelper::reopenSessionForWriting();
@ -48,9 +47,10 @@ class PlaylistController extends Zend_Controller_Action
$obj = new $objInfo['className']($obj_sess->id);
$modified = $this->_getParam('modified', null);
if ($obj->getLastModified("U") !== $modified) {
if ($obj->getLastModified('U') !== $modified) {
$this->createFullResponse($obj);
throw new PlaylistOutDatedException(sprintf(_("You are viewing an older version of %s"), $obj->getName()));
throw new PlaylistOutDatedException(sprintf(_('You are viewing an older version of %s'), $obj->getName()));
}
}
@ -71,20 +71,23 @@ class PlaylistController extends Zend_Controller_Action
$this->view->html = $this->view->render('playlist/update.phtml');
$this->view->name = $obj->getName();
$this->view->description = $obj->getDescription();
$this->view->modified = $obj->getLastModified("U");
$this->view->modified = $obj->getLastModified('U');
unset($this->view->obj);
}
private function createFullResponse($obj = null, $isJson = false,
$formIsValid = false)
{
private function createFullResponse(
$obj = null,
$isJson = false,
$formIsValid = false
) {
$user = Application_Model_User::getCurrentUser();
$isAdminOrPM = $user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
$isAdminOrPM = $user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER]);
if (!$isAdminOrPM && $obj->getCreatorId() != $user->getId()) {
$this->view->objType = $obj instanceof Application_Model_Block ? "block" : "playlist";
$this->view->objType = $obj instanceof Application_Model_Block ? 'block' : 'playlist';
$this->view->obj = $obj;
$this->view->html = $this->view->render('playlist/permission-denied.phtml');
return;
}
@ -109,26 +112,24 @@ class PlaylistController extends Zend_Controller_Action
if ($isJson) {
return $this->view->render($viewPath);
} else {
$this->view->html = $this->view->render($viewPath);
}
$this->view->html = $this->view->render($viewPath);
} else {
$this->view->obj = $obj;
//$this->view->type = "pl";
$this->view->id = $obj->getId();
if ($isJson) {
return $this->view->html = $this->view->render($viewPath);
} else {
$this->view->html = $this->view->render($viewPath);
}
$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);
}
$this->view->html = $this->view->render($viewPath);
}
}
@ -139,22 +140,22 @@ class PlaylistController extends Zend_Controller_Action
private function blockDynamic($obj)
{
$this->view->error = _("You cannot add tracks to dynamic blocks.");
$this->view->error = _('You cannot add tracks to dynamic blocks.');
$this->createFullResponse($obj);
}
private function playlistNotFound($p_type, $p_isJson = false)
{
$p_type = ucfirst($p_type);
$this->view->error = sprintf(_("%s not found"), $p_type);
$this->view->error = sprintf(_('%s not found'), $p_type);
Logging::info("{$p_type} not found");
Application_Model_Library::changePlaylist(null, $p_type);
if (!$p_isJson) {
$this->createFullResponse(null);
} else {
$this->_helper->json->sendJson(array("error"=>$this->view->error, "result"=>1, "html"=>$this->createFullResponse(null, $p_isJson)));
$this->_helper->json->sendJson(['error' => $this->view->error, 'result' => 1, 'html' => $this->createFullResponse(null, $p_isJson)]);
}
}
@ -167,19 +168,19 @@ class PlaylistController extends Zend_Controller_Action
private function playlistUnknownError($e)
{
$this->view->error = _("Something went wrong.");
$this->view->error = _('Something went wrong.');
Logging::info($e->getMessage());
}
private function wrongTypeToBlock($obj)
{
$this->view->error = _("You can only add tracks to smart block.");
$this->view->error = _('You can only add tracks to smart block.');
$this->createFullResponse($obj);
}
private function wrongTypeToPlaylist($obj)
{
$this->view->error = _("You can only add tracks, smart blocks, and webstreams to playlists.");
$this->view->error = _('You can only add tracks, smart blocks, and webstreams to playlists.');
$this->createFullResponse($obj);
}
@ -204,7 +205,8 @@ class PlaylistController extends Zend_Controller_Action
$this->createFullResponse($obj);
}
public function changePlaylistAction() {
public function changePlaylistAction()
{
$this->view->layout()->disableLayout(); // Don't inject the standard Now Playing header.
$this->_helper->viewRenderer->setNoRender(true); // Don't use (phtml) templates
@ -236,30 +238,31 @@ class PlaylistController extends Zend_Controller_Action
public function deleteAction()
{
$ids = $this->_getParam('ids');
$ids = (!is_array($ids)) ? array($ids) : $ids;
$ids = $this->_getParam('ids');
$ids = (!is_array($ids)) ? [$ids] : $ids;
$type = $this->_getParam('type');
$obj = null;
$obj = null;
$objInfo = Application_Model_Library::getObjInfo($type);
$objInfo = Application_Model_Library::getObjInfo($type);
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$obj_sess = new Zend_Session_Namespace(
UI_PLAYLISTCONTROLLER_OBJ_SESSNAME);
UI_PLAYLISTCONTROLLER_OBJ_SESSNAME
);
try {
Logging::info("Currently active {$type} {$obj_sess->id}");
if (in_array($obj_sess->id, $ids)) {
Logging::info("Deleting currently active {$type}");
// Application_Model_Library::changePlaylist(null, $type);
// Application_Model_Library::changePlaylist(null, $type);
} else {
Logging::info("Not deleting currently active {$type}");
$obj = new $objInfo['className']($obj_sess->id);
}
if (strcmp($objInfo['className'], 'Application_Model_Playlist')==0) {
if (strcmp($objInfo['className'], 'Application_Model_Playlist') == 0) {
Application_Model_Playlist::deletePlaylists($ids, $userInfo->id);
} else {
Application_Model_Block::deleteBlocks($ids, $userInfo->id);
@ -276,7 +279,8 @@ class PlaylistController extends Zend_Controller_Action
}
}
public function closePlaylistAction() {
public function closePlaylistAction()
{
$type = $this->_getParam('type');
$obj = null;
Application_Model_Library::changePlaylist($obj, $type);
@ -285,8 +289,8 @@ class PlaylistController extends Zend_Controller_Action
public function addItemsAction()
{
$ids = $this->_getParam('aItems', array());
$ids = (!is_array($ids)) ? array($ids) : $ids;
$ids = $this->_getParam('aItems', []);
$ids = (!is_array($ids)) ? [$ids] : $ids;
$afterItem = $this->_getParam('afterItem', null);
$addType = $this->_getParam('type', 'after');
// this is the obj type of destination
@ -298,7 +302,7 @@ class PlaylistController extends Zend_Controller_Action
foreach ($ids as $id) {
if (is_array($id) && isset($id[1])) {
if ($id[1] == 'playlist') {
throw new WrongTypeToPlaylistException;
throw new WrongTypeToPlaylistException();
}
}
}
@ -309,13 +313,13 @@ class PlaylistController extends Zend_Controller_Action
foreach ($ids as $id) {
if (is_array($id) && isset($id[1])) {
if ($id[1] != 'audioclip') {
throw new WrongTypeToBlockException;
throw new WrongTypeToBlockException();
}
}
}
$obj->addAudioClips($ids, $afterItem, $addType);
} else {
throw new BlockDynamicException;
throw new BlockDynamicException();
}
$this->createUpdateResponse($obj);
} catch (PlaylistOutDatedException $e) {
@ -338,7 +342,7 @@ class PlaylistController extends Zend_Controller_Action
public function moveItemsAction()
{
$ids = $this->_getParam('ids');
$ids = (!is_array($ids)) ? array($ids) : $ids;
$ids = (!is_array($ids)) ? [$ids] : $ids;
$afterItem = $this->_getParam('afterItem', null);
$type = $this->_getParam('obj_type');
@ -358,7 +362,7 @@ class PlaylistController extends Zend_Controller_Action
public function deleteItemsAction()
{
$ids = $this->_getParam('ids');
$ids = (!is_array($ids)) ? array($ids) : $ids;
$ids = (!is_array($ids)) ? [$ids] : $ids;
$modified = $this->_getParam('modified');
$type = $this->_getParam('obj_type');
@ -374,10 +378,11 @@ class PlaylistController extends Zend_Controller_Action
$this->playlistUnknownError($e);
}
}
public function emptyContentAction()
{
$type = $this->_getParam('obj_type');
try {
$obj = $this->getPlaylist($type);
if ($type == 'playlist') {
@ -406,12 +411,12 @@ class PlaylistController extends Zend_Controller_Action
$obj = $this->getPlaylist($type);
$response = $obj->changeClipLength($id, $cueIn, $cueOut);
if (!isset($response["error"])) {
if (!isset($response['error'])) {
$this->view->response = $response;
$this->createUpdateResponse($obj);
} else {
$this->view->cue_error = $response["error"];
$this->view->code = $response["type"];
$this->view->cue_error = $response['error'];
$this->view->code = $response['type'];
}
} catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($e);
@ -433,11 +438,11 @@ class PlaylistController extends Zend_Controller_Action
$obj = $this->getPlaylist($type);
$response = $obj->changeFadeInfo($id, $fadeIn, $fadeOut);
if (!isset($response["error"])) {
if (!isset($response['error'])) {
$this->createUpdateResponse($obj);
$this->view->response = $response;
} else {
$this->view->fade_error = $response["error"];
$this->view->fade_error = $response['error'];
}
} catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($e);
@ -447,7 +452,7 @@ class PlaylistController extends Zend_Controller_Action
$this->playlistUnknownError($e);
}
}
public function setCrossfadeAction()
{
$id1 = $this->_getParam('id1', null);
@ -456,15 +461,15 @@ class PlaylistController extends Zend_Controller_Action
$fadeIn = $this->_getParam('fadeIn', 0);
$fadeOut = $this->_getParam('fadeOut', 0);
$offset = $this->_getParam('offset', 0);
try {
$obj = $this->getPlaylist($type);
$response = $obj->createCrossfade($id1, $fadeOut, $id2, $fadeIn, $offset);
if (!isset($response["error"])) {
if (!isset($response['error'])) {
$this->createUpdateResponse($obj);
} else {
$this->view->error = $response["error"];
$this->view->error = $response['error'];
}
} catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($e);
@ -478,12 +483,13 @@ class PlaylistController extends Zend_Controller_Action
public function getPlaylistFadesAction()
{
$type = $this->_getParam('type');
try {
$obj = $this->getPlaylist($type);
$fades = $obj->getFadeInfo(0);
$this->view->fadeIn = $fades[0];
$fades = $obj->getFadeInfo($obj->getSize()-1);
$fades = $obj->getFadeInfo($obj->getSize() - 1);
$this->view->fadeOut = $fades[1];
} catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($e);
@ -498,7 +504,7 @@ class PlaylistController extends Zend_Controller_Action
* The playlist fades are stored in the elements themselves.
* The fade in is set to the first elements fade in and
* the fade out is set to the last elements fade out.
**/
*/
public function setPlaylistFadesAction()
{
$fadeIn = $this->_getParam('fadeIn', null);
@ -508,7 +514,7 @@ class PlaylistController extends Zend_Controller_Action
try {
$obj = $this->getPlaylist($type);
$obj->setfades($fadeIn, $fadeOut);
$this->view->modified = $obj->getLastModified("U");
$this->view->modified = $obj->getLastModified('U');
} catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($e);
} catch (PlaylistNotFoundException $e) {
@ -521,7 +527,7 @@ class PlaylistController extends Zend_Controller_Action
public function setPlaylistNameDescAction()
{
$name = $this->_getParam('name', _('Unknown Playlist'));
$description = $this->_getParam('description', "");
$description = $this->_getParam('description', '');
$type = $this->_getParam('type');
try {
@ -530,7 +536,7 @@ class PlaylistController extends Zend_Controller_Action
$obj->setDescription($description);
$this->view->description = $description;
$this->view->playlistName = $name;
$this->view->modified = $obj->getLastModified("U");
$this->view->modified = $obj->getLastModified('U');
} catch (PlaylistOutDatedException $e) {
$this->playlistOutdated($e);
} catch (PlaylistNotFoundException $e) {
@ -544,7 +550,7 @@ class PlaylistController extends Zend_Controller_Action
{
$request = $this->getRequest();
$params = $request->getPost();
$result = array();
$result = [];
if ($params['type'] == 'block') {
try {
@ -559,9 +565,7 @@ class PlaylistController extends Zend_Controller_Action
$bl->saveSmartBlockCriteria($params['data']);
$this->createUpdateResponse($bl, true);
$this->view->result = 0;
/*
$result['html'] = $this->createFullResponse($bl, true, true);
*/
// $result['html'] = $this->createFullResponse($bl, true, true);
} else {
$this->view->form = $form;
$this->view->unsavedName = $params['name'];
@ -575,14 +579,13 @@ class PlaylistController extends Zend_Controller_Action
$this->view->name = $bl->getName();
//$this->view->type = "sb";
$this->view->id = $bl->getId();
$this->view->modified = $bl->getLastModified("U");
} else if ($params['type'] == 'playlist') {
$this->view->modified = $bl->getLastModified('U');
} elseif ($params['type'] == 'playlist') {
$this->setPlaylistNameDescAction();
$this->view->modified = $this->view->modified;
$this->view->name = $params['name'];
}
//$this->_helper->json->sendJson($result);
}
@ -590,18 +593,18 @@ class PlaylistController extends Zend_Controller_Action
{
$request = $this->getRequest();
$params = $request->getPost();
//make sure block exists
try {
$bl = new Application_Model_Block($params['obj_id']);
$form = new Application_Form_SmartBlockCriteria();
$form->startForm($params['obj_id']);
if ($form->isValid($params)) {
$result = $bl->generateSmartBlock($params['data']);
$this->view->result = $result['result'];
$this->createUpdateResponse($bl, true);
#$this->_helper->json->sendJson(array("result"=>0, "html"=>$this->createFullResponse($bl, true, true)));
//$this->_helper->json->sendJson(array("result"=>0, "html"=>$this->createFullResponse($bl, true, true)));
} else {
$this->view->obj = $bl;
$this->view->id = $bl->getId();
@ -620,12 +623,13 @@ class PlaylistController extends Zend_Controller_Action
{
$request = $this->getRequest();
$params = $request->getPost();
try {
$bl = new Application_Model_Block($params['obj_id']);
$result = $bl->shuffleSmartBlock();
$this->view->result = $result["result"];
$this->createUpdateResponse($bl,true);
$this->view->result = $result['result'];
$this->createUpdateResponse($bl, true);
/*
if ($result['result'] == 0) {
@ -643,17 +647,18 @@ class PlaylistController extends Zend_Controller_Action
$this->playlistUnknownError($e);
}
}
public function shuffleAction()
{
$request = $this->getRequest();
$params = $request->getPost();
try {
$pl = new Application_Model_Playlist($params['obj_id']);
$result = $pl->shuffle();
$this->view->result = $result["result"];
$this->createUpdateResponse($pl,true);
$this->view->result = $result['result'];
$this->createUpdateResponse($pl, true);
/*
if ($result['result'] == 0) {
$this->_helper->json->sendJson(array(
@ -685,6 +690,12 @@ class PlaylistController extends Zend_Controller_Action
$this->_helper->json->sendJson($out);
}
}
class WrongTypeToBlockException extends Exception {}
class WrongTypeToPlaylistException extends Exception {}
class BlockDynamicException extends Exception {}
class WrongTypeToBlockException extends Exception
{
}
class WrongTypeToPlaylistException extends Exception
{
}
class BlockDynamicException extends Exception
{
}

View File

@ -16,9 +16,10 @@ class PlayouthistoryController extends Zend_Controller_Action
->addActionContext('delete-list-items', 'json')
->addActionContext('update-list-item', 'json')
->addActionContext('update-file-item', 'json')
->initContext();
->initContext()
;
}
public function indexAction()
{
$CC_CONFIG = Config::getConfig();
@ -27,48 +28,48 @@ class PlayouthistoryController extends Zend_Controller_Action
Zend_Layout::getMvcInstance()->assign('parent_page', 'Analytics');
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($this->getRequest());
$userTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
$startsDT->setTimezone($userTimezone);
$endsDT->setTimezone($userTimezone);
$form = new Application_Form_DateRange();
$form->populate(array(
'his_date_start' => $startsDT->format("Y-m-d"),
'his_time_start' => $startsDT->format("H:i"),
'his_date_end' => $endsDT->format("Y-m-d"),
'his_time_end' => $endsDT->format("H:i")
));
$form->populate([
'his_date_start' => $startsDT->format('Y-m-d'),
'his_time_start' => $startsDT->format('H:i'),
'his_date_end' => $endsDT->format('Y-m-d'),
'his_time_end' => $endsDT->format('H:i'),
]);
$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/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/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/timepicker/jquery.ui.timepicker.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/bootstrap-datetime/bootstrap-datetimepicker.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/libs/CSVexport.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/libs/pdfmake.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/libs/vfs_fonts.min.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/timepicker/jquery.ui.timepicker.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/bootstrap-datetime/bootstrap-datetimepicker.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/libs/CSVexport.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/libs/pdfmake.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/libs/vfs_fonts.min.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.'css/bootstrap-datetimepicker.min.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/history_styles.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'css/jquery.contextMenu.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl . 'css/bootstrap-datetimepicker.min.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/history_styles.css?' . $CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl . 'css/jquery.contextMenu.css?' . $CC_CONFIG['airtime_version']);
//set datatables columns for display of data.
$historyService = new Application_Service_HistoryService();
$columns = json_encode($historyService->getDatatablesLogSheetColumns());
$script = "localStorage.setItem( 'datatables-historyitem-aoColumns', JSON.stringify($columns) ); ";
$script = "localStorage.setItem( 'datatables-historyitem-aoColumns', JSON.stringify({$columns}) ); ";
$columns = json_encode($historyService->getDatatablesFileSummaryColumns());
$script.= "localStorage.setItem( 'datatables-historyfile-aoColumns', JSON.stringify($columns) );";
$script .= "localStorage.setItem( 'datatables-historyfile-aoColumns', JSON.stringify({$columns}) );";
$this->view->headScript()->appendScript($script);
$user = Application_Model_User::getCurrentUser();
@ -77,109 +78,104 @@ class PlayouthistoryController extends Zend_Controller_Action
public function fileHistoryFeedAction()
{
try {
$request = $this->getRequest();
$params = $request->getParams();
$instance = $request->getParam("instance_id", null);
try {
$request = $this->getRequest();
$params = $request->getParams();
$instance = $request->getParam('instance_id', null);
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($request);
$historyService = new Application_Service_HistoryService();
$r = $historyService->getFileSummaryData($startsDT, $endsDT, $params);
$historyService = new Application_Service_HistoryService();
$r = $historyService->getFileSummaryData($startsDT, $endsDT, $params);
$this->view->sEcho = $r["sEcho"];
$this->view->iTotalDisplayRecords = $r["iTotalDisplayRecords"];
$this->view->iTotalRecords = $r["iTotalRecords"];
$this->view->history = $r["history"];
$this->view->sEcho = $r['sEcho'];
$this->view->iTotalDisplayRecords = $r['iTotalDisplayRecords'];
$this->view->iTotalRecords = $r['iTotalRecords'];
$this->view->history = $r['history'];
$this->view->history = SecurityHelper::htmlescape_recursive($this->view->history);
}
catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
} catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
}
}
public function itemHistoryFeedAction()
{
try {
$request = $this->getRequest();
$params = $request->getParams();
$instance = $request->getParam("instance_id", null);
try {
$request = $this->getRequest();
$params = $request->getParams();
$instance = $request->getParam('instance_id', null);
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($request);
$historyService = new Application_Service_HistoryService();
$r = $historyService->getPlayedItemData($startsDT, $endsDT, $params, $instance);
$this->view->sEcho = $r["sEcho"];
$this->view->iTotalDisplayRecords = $r["iTotalDisplayRecords"];
$this->view->iTotalRecords = $r["iTotalRecords"];
$this->view->history = $r["history"];
$historyService = new Application_Service_HistoryService();
$r = $historyService->getPlayedItemData($startsDT, $endsDT, $params, $instance);
$this->view->sEcho = $r['sEcho'];
$this->view->iTotalDisplayRecords = $r['iTotalDisplayRecords'];
$this->view->iTotalRecords = $r['iTotalRecords'];
$this->view->history = $r['history'];
$this->view->history = SecurityHelper::htmlescape_recursive($this->view->history);
} catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
}
catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
}
}
public function showHistoryFeedAction()
{
try {
$request = $this->getRequest();
$params = $request->getParams();
$instance = $request->getParam("instance_id", null);
try {
$request = $this->getRequest();
$params = $request->getParams();
$instance = $request->getParam('instance_id', null);
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($request);
$historyService = new Application_Service_HistoryService();
$shows = $historyService->getShowList($startsDT, $endsDT);
$historyService = new Application_Service_HistoryService();
$shows = $historyService->getShowList($startsDT, $endsDT);
$shows = SecurityHelper::htmlescape_recursive($shows);
$this->_helper->json->sendJson($shows);
}
catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
}
$this->_helper->json->sendJson($shows);
} catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
}
}
public function editFileItemAction()
{
$file_id = $this->_getParam('id');
$file_id = $this->_getParam('id');
$historyService = new Application_Service_HistoryService();
$form = $historyService->makeHistoryFileForm($file_id);
$historyService = new Application_Service_HistoryService();
$form = $historyService->makeHistoryFileForm($file_id);
$this->view->form = $form;
$this->view->dialog = $this->view->render('playouthistory/dialog.phtml');
$this->view->form = $form;
$this->view->dialog = $this->view->render('playouthistory/dialog.phtml');
unset($this->view->form);
unset($this->view->form);
}
public function createListItemAction()
{
try {
$request = $this->getRequest();
$params = $request->getPost();
Logging::info($params);
try {
$request = $this->getRequest();
$params = $request->getPost();
Logging::info($params);
$historyService = new Application_Service_HistoryService();
$json = $historyService->createPlayedItem($params);
$historyService = new Application_Service_HistoryService();
$json = $historyService->createPlayedItem($params);
if (isset($json["form"])) {
$this->view->form = $json["form"];
$json["form"] = $this->view->render('playouthistory/dialog.phtml');
if (isset($json['form'])) {
$this->view->form = $json['form'];
$json['form'] = $this->view->render('playouthistory/dialog.phtml');
unset($this->view->form);
}
unset($this->view->form);
}
$this->_helper->json->sendJson($json);
}
catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
$this->_helper->json->sendJson($json);
} catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
}
}
@ -200,43 +196,42 @@ class PlayouthistoryController extends Zend_Controller_Action
public function deleteListItemAction()
{
$history_id = $this->_getParam('id');
$history_id = $this->_getParam('id');
$historyService = new Application_Service_HistoryService();
$historyService->deletePlayedItem($history_id);
$historyService = new Application_Service_HistoryService();
$historyService->deletePlayedItem($history_id);
}
public function deleteListItemsAction()
{
$history_ids = $this->_getParam('ids');
$history_ids = $this->_getParam('ids');
$historyService = new Application_Service_HistoryService();
$historyService->deletePlayedItems($history_ids);
$historyService = new Application_Service_HistoryService();
$historyService->deletePlayedItems($history_ids);
}
public function updateListItemAction()
{
try {
$request = $this->getRequest();
$params = $request->getPost();
Logging::info($params);
try {
$request = $this->getRequest();
$params = $request->getPost();
Logging::info($params);
$historyService = new Application_Service_HistoryService();
$json = $historyService->editPlayedItem($params);
$historyService = new Application_Service_HistoryService();
$json = $historyService->editPlayedItem($params);
if (isset($json["form"])) {
$this->view->form = $json["form"];
$json["form"] = $this->view->render('playouthistory/dialog.phtml');
if (isset($json['form'])) {
$this->view->form = $json['form'];
$json['form'] = $this->view->render('playouthistory/dialog.phtml');
unset($this->view->form);
}
unset($this->view->form);
}
$this->_helper->json->sendJson($json);
}
catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
}
$this->_helper->json->sendJson($json);
} catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
}
}
public function updateFileItemAction()
@ -245,9 +240,9 @@ class PlayouthistoryController extends Zend_Controller_Action
$params = $request->getPost();
Logging::info($params);
$historyService = new Application_Service_HistoryService();
$json = $historyService->editPlayedFile($params);
$historyService = new Application_Service_HistoryService();
$json = $historyService->editPlayedFile($params);
$this->_helper->json->sendJson($json);
$this->_helper->json->sendJson($json);
}
}

View File

@ -10,138 +10,133 @@ class PlayouthistorytemplateController extends Zend_Controller_Action
->addActionContext('update-template', 'json')
->addActionContext('delete-template', 'json')
->addActionContext('set-template-default', 'json')
->initContext();
}
public function indexAction()
{
$CC_CONFIG = Config::getConfig();
$baseUrl = Application_Common_OsPath::getBaseDir();
->initContext()
;
}
Zend_Layout::getMvcInstance()->assign('parent_page', 'Analytics');
$this->view->headScript()->appendFile($baseUrl.'js/airtime/playouthistory/template.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headLink()->appendStylesheet($baseUrl.'css/history_styles.css?'.$CC_CONFIG['airtime_version']);
$historyService = new Application_Service_HistoryService();
$this->view->template_list = $historyService->getListItemTemplates();
$this->view->template_file = $historyService->getFileTemplates();
$this->view->configured = $historyService->getConfiguredTemplateIds();
}
public function configureTemplateAction() {
$CC_CONFIG = Config::getConfig();
$baseUrl = Application_Common_OsPath::getBaseDir();
public function indexAction()
{
$CC_CONFIG = Config::getConfig();
$baseUrl = Application_Common_OsPath::getBaseDir();
Zend_Layout::getMvcInstance()->assign('parent_page', 'Analytics');
$this->view->headScript()->appendFile($baseUrl.'js/airtime/playouthistory/configuretemplate.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headLink()->appendStylesheet($baseUrl.'css/history_styles.css?'.$CC_CONFIG['airtime_version']);
try {
$templateId = $this->_getParam('id');
$historyService = new Application_Service_HistoryService();
$template = $historyService->loadTemplate($templateId);
$templateType = $template["type"];
$supportedTypes = $historyService->getSupportedTemplateTypes();
if (!in_array($templateType, $supportedTypes)) {
throw new Exception("Error: $templateType is not supported.");
}
$getMandatoryFields = "mandatory".ucfirst($templateType)."Fields";
$mandatoryFields = $historyService->$getMandatoryFields();
$this->view->template_id = $templateId;
$this->view->template_name = $template["name"];
$this->view->template_fields = $template["fields"];
$this->view->template_type = $templateType;
$this->view->fileMD = $historyService->getFileMetadataTypes();
$this->view->fields = $historyService->getFieldTypes();
$this->view->required_fields = $mandatoryFields;
$this->view->configured = $historyService->getConfiguredTemplateIds();
}
catch (Exception $e) {
Logging::info("Error?");
Logging::info($e);
Logging::info($e->getMessage());
$this->_forward('index', 'playouthistorytemplate');
}
}
public function createTemplateAction()
{
$templateType = $this->_getParam('type', null);
$request = $this->getRequest();
$params = $request->getPost();
try {
$historyService = new Application_Service_HistoryService();
$supportedTypes = $historyService->getSupportedTemplateTypes();
if (!in_array($templateType, $supportedTypes)) {
throw new Exception("Error: $templateType is not supported.");
}
$id = $historyService->createTemplate($params);
$this->view->url = $this->view->baseUrl("Playouthistorytemplate/configure-template/id/{$id}");
}
catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
$this->view->error = $e->getMessage();
}
}
public function setTemplateDefaultAction()
{
$templateId = $this->_getParam('id', null);
try {
$historyService = new Application_Service_HistoryService();
$historyService->setConfiguredTemplate($templateId);
}
catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
}
}
public function updateTemplateAction()
{
$templateId = $this->_getParam('id', null);
$name = $this->_getParam('name', null);
$fields = $this->_getParam('fields', array());
try {
$historyService = new Application_Service_HistoryService();
$historyService->updateItemTemplate($templateId, $name, $fields);
}
catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
}
}
public function deleteTemplateAction()
{
$templateId = $this->_getParam('id');
try {
$historyService = new Application_Service_HistoryService();
$historyService->deleteTemplate($templateId);
}
catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
}
}
}
Zend_Layout::getMvcInstance()->assign('parent_page', 'Analytics');
$this->view->headScript()->appendFile($baseUrl . 'js/airtime/playouthistory/template.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headLink()->appendStylesheet($baseUrl . 'css/history_styles.css?' . $CC_CONFIG['airtime_version']);
$historyService = new Application_Service_HistoryService();
$this->view->template_list = $historyService->getListItemTemplates();
$this->view->template_file = $historyService->getFileTemplates();
$this->view->configured = $historyService->getConfiguredTemplateIds();
}
public function configureTemplateAction()
{
$CC_CONFIG = Config::getConfig();
$baseUrl = Application_Common_OsPath::getBaseDir();
Zend_Layout::getMvcInstance()->assign('parent_page', 'Analytics');
$this->view->headScript()->appendFile($baseUrl . 'js/airtime/playouthistory/configuretemplate.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headLink()->appendStylesheet($baseUrl . 'css/history_styles.css?' . $CC_CONFIG['airtime_version']);
try {
$templateId = $this->_getParam('id');
$historyService = new Application_Service_HistoryService();
$template = $historyService->loadTemplate($templateId);
$templateType = $template['type'];
$supportedTypes = $historyService->getSupportedTemplateTypes();
if (!in_array($templateType, $supportedTypes)) {
throw new Exception("Error: {$templateType} is not supported.");
}
$getMandatoryFields = 'mandatory' . ucfirst($templateType) . 'Fields';
$mandatoryFields = $historyService->{$getMandatoryFields}();
$this->view->template_id = $templateId;
$this->view->template_name = $template['name'];
$this->view->template_fields = $template['fields'];
$this->view->template_type = $templateType;
$this->view->fileMD = $historyService->getFileMetadataTypes();
$this->view->fields = $historyService->getFieldTypes();
$this->view->required_fields = $mandatoryFields;
$this->view->configured = $historyService->getConfiguredTemplateIds();
} catch (Exception $e) {
Logging::info('Error?');
Logging::info($e);
Logging::info($e->getMessage());
$this->_forward('index', 'playouthistorytemplate');
}
}
public function createTemplateAction()
{
$templateType = $this->_getParam('type', null);
$request = $this->getRequest();
$params = $request->getPost();
try {
$historyService = new Application_Service_HistoryService();
$supportedTypes = $historyService->getSupportedTemplateTypes();
if (!in_array($templateType, $supportedTypes)) {
throw new Exception("Error: {$templateType} is not supported.");
}
$id = $historyService->createTemplate($params);
$this->view->url = $this->view->baseUrl("Playouthistorytemplate/configure-template/id/{$id}");
} catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
$this->view->error = $e->getMessage();
}
}
public function setTemplateDefaultAction()
{
$templateId = $this->_getParam('id', null);
try {
$historyService = new Application_Service_HistoryService();
$historyService->setConfiguredTemplate($templateId);
} catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
}
}
public function updateTemplateAction()
{
$templateId = $this->_getParam('id', null);
$name = $this->_getParam('name', null);
$fields = $this->_getParam('fields', []);
try {
$historyService = new Application_Service_HistoryService();
$historyService->updateItemTemplate($templateId, $name, $fields);
} catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
}
}
public function deleteTemplateAction()
{
$templateId = $this->_getParam('id');
try {
$historyService = new Application_Service_HistoryService();
$historyService->deleteTemplate($templateId);
} catch (Exception $e) {
Logging::info($e);
Logging::info($e->getMessage());
}
}
}

View File

@ -5,9 +5,10 @@ class PluploadController extends Zend_Controller_Action
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('upload', 'json')
->addActionContext('recent-uploads', 'json')
->initContext();
$ajaxContext->addActionContext('upload', 'json')
->addActionContext('recent-uploads', 'json')
->initContext()
;
}
public function indexAction()
@ -17,16 +18,16 @@ class PluploadController extends Zend_Controller_Action
$baseUrl = Application_Common_OsPath::getBaseDir();
$locale = Application_Model_Preference::GetLocale();
$this->view->headScript()->appendFile($baseUrl.'js/datatables/js/jquery.dataTables.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/plupload/plupload.full.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/plupload/jquery.plupload.queue.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/airtime/library/plupload.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/plupload/i18n/'.$locale.'.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/libs/dropzone.min.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/plupload/plupload.full.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/plupload/jquery.plupload.queue.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/airtime/library/plupload.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/plupload/i18n/' . $locale . '.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/libs/dropzone.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headLink()->appendStylesheet($baseUrl.'css/plupload.queue.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'css/addmedia.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'css/dashboard.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl . 'css/plupload.queue.css?' . $CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl . 'css/addmedia.css?' . $CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl . 'css/dashboard.css?' . $CC_CONFIG['airtime_version']);
$this->view->quotaLimitReached = false;
if (Application_Model_Systemstatus::isDiskOverQuota()) {
@ -60,56 +61,56 @@ class PluploadController extends Zend_Controller_Action
$observed_csrf_token = $this->_getParam('csrf_token');
$expected_csrf_token = $current_namespace->authtoken;
if($observed_csrf_token == $expected_csrf_token){
$upload_dir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
if ($observed_csrf_token == $expected_csrf_token) {
$upload_dir = ini_get('upload_tmp_dir') . DIRECTORY_SEPARATOR . 'plupload';
$tempFilePath = Application_Model_StoredFile::uploadFile($upload_dir);
$tempFileName = basename($tempFilePath);
$this->_helper->json->sendJson(array("jsonrpc" => "2.0", "tempfilepath" => $tempFileName));
}else{
$this->_helper->json->sendJson(array("jsonrpc" => "2.0", "valid" => false, "error" => "CSRF token did not match."));
$this->_helper->json->sendJson(['jsonrpc' => '2.0', 'tempfilepath' => $tempFileName]);
} else {
$this->_helper->json->sendJson(['jsonrpc' => '2.0', 'valid' => false, 'error' => 'CSRF token did not match.']);
}
}
public function recentUploadsAction()
{
$request = $this->getRequest();
$filter = $request->getParam('uploadFilter', "all");
$request = $this->getRequest();
$filter = $request->getParam('uploadFilter', 'all');
$limit = intval($request->getParam('iDisplayLength', 10));
$rowStart = intval($request->getParam('iDisplayStart', 0));
$recentUploadsQuery = CcFilesQuery::create();
//old propel 1.5 to reuse this query item (for counts/finds)
$recentUploadsQuery->keepQuery(true);
//Hide deleted files
$recentUploadsQuery->filterByDbFileExists(true);
$numTotalRecentUploads = $recentUploadsQuery->count();
$numTotalDisplayUploads = $numTotalRecentUploads;
if ($filter == "pending") {
if ($filter == 'pending') {
$recentUploadsQuery->filterByDbImportStatus(1);
$numTotalDisplayUploads = $recentUploadsQuery->count();
} else if ($filter == "failed") {
} elseif ($filter == 'failed') {
$recentUploadsQuery->filterByDbImportStatus(2);
$numTotalDisplayUploads = $recentUploadsQuery->count();
//TODO: Consider using array('min' => 200)) or something if we have multiple errors codes for failure.
}
$recentUploads = $recentUploadsQuery
->orderByDbUtime(Criteria::DESC)
->offset($rowStart)
->limit($limit)
->find();
$uploadsArray = array();
$utcTimezone = new DateTimeZone("UTC");
->orderByDbUtime(Criteria::DESC)
->offset($rowStart)
->limit($limit)
->find()
;
$uploadsArray = [];
$utcTimezone = new DateTimeZone('UTC');
$displayTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
foreach ($recentUploads as $upload)
{
foreach ($recentUploads as $upload) {
$upload = $upload->toArray(BasePeer::TYPE_FIELDNAME);
//TODO: $this->sanitizeResponse($upload));
$upload['utime'] = new DateTime($upload['utime'], $utcTimezone);
@ -119,7 +120,7 @@ class PluploadController extends Zend_Controller_Action
//TODO: Invoke sanitization here (MediaController's removeBlacklist stuff)
array_push($uploadsArray, $upload);
}
$this->view->sEcho = intval($request->getParam('sEcho'));
$this->view->iTotalDisplayRecords = $numTotalDisplayUploads;
$this->view->iTotalRecords = $numTotalRecentUploads;
@ -127,7 +128,7 @@ class PluploadController extends Zend_Controller_Action
}
/**
* get configured upload max size from php
* get configured upload max size from php.
*
* Pinched from Drupal: https://github.com/drupal/drupal/blob/4204b0b29a7318008f10765cf88114bf3ed21c32/core/includes/file.inc#L1099
*
@ -135,10 +136,10 @@ class PluploadController extends Zend_Controller_Action
* way. I'm adding the method here since it's part of their core and I did
* not find an easy way to grab that thrrough composer in an isolated way.
*/
private function file_upload_max_size() {
private function file_upload_max_size()
{
static $max_size = -1;
if ($max_size < 0) {
// Start with post_max_size.
$max_size = $this->bytes_to_int(ini_get('post_max_size'));
@ -149,19 +150,23 @@ class PluploadController extends Zend_Controller_Action
$max_size = $upload_max;
}
}
return $max_size;
}
/**
* Pinched from Drupal: https://github.com/drupal/drupal/blob/4204b0b29a7318008f10765cf88114bf3ed21c32/core/lib/Drupal/Component/Utility/Bytes.php#L27
* Pinched from Drupal: https://github.com/drupal/drupal/blob/4204b0b29a7318008f10765cf88114bf3ed21c32/core/lib/Drupal/Component/Utility/Bytes.php#L27.
*
* This is the real point of importing the Drupal solution. They have done
* an implementation for figuring out what the user specified in the
* post_max_size and upload_max_size configuration. Sadly php does not
* support a nice way to get at the results of this config after it is
* parsed by the engine, hence the below hack.
*
* @param mixed $size
*/
private function bytes_to_int($size) {
private function bytes_to_int($size)
{
// Remove the non-unit characters from the size.
$unit = preg_replace('/[^bkmgtpezy]/i', '', $size);
// Remove the non-numeric characters from the size.
@ -170,8 +175,8 @@ class PluploadController extends Zend_Controller_Action
// Find the position of the unit in the ordered string which is the power
// of magnitude to multiply a kilobyte by.
return round($size * pow(1024, stripos('bkmgtpezy', $unit[0])));
} else {
return round($size);
}
return round($size);
}
}

View File

@ -1,36 +1,36 @@
<?php
class PodcastController extends Zend_Controller_Action {
public function init() {
class PodcastController extends Zend_Controller_Action
{
public function init()
{
$CC_CONFIG = Config::getConfig();
$baseUrl = Application_Common_OsPath::getBaseDir();
$headScript = $this->view->headScript();
AirtimeTableView::injectTableJavaScriptDependencies($headScript, $baseUrl, $CC_CONFIG['airtime_version']);
$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_showbuilder.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_showbuilder.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/airtime/widgets/table.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/airtime/library/podcast.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/airtime/widgets/table.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/airtime/library/podcast.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headLink()->appendStylesheet($baseUrl.'css/datatables/css/ColVis.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'css/datatables/css/dataTables.colReorder.min.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/dataTables.colReorder.min.css?' . $CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'css/station_podcast.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'css/dashboard.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl . 'css/station_podcast.css?' . $CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl . 'css/dashboard.css?' . $CC_CONFIG['airtime_version']);
}
/**
* Renders the Station podcast view
* Renders the Station podcast view.
*/
public function stationAction() {
public function stationAction()
{
$stationPodcastId = Application_Model_Preference::getStationPodcastId();
$podcast = Application_Service_PodcastService::getPodcastById($stationPodcastId);
$this->view->podcast = json_encode($podcast);
$this->view->form = new Application_Form_StationPodcast();
}
}

View File

@ -2,21 +2,21 @@
class PreferenceController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
// Initialize action controller here
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('server-browse', 'json')
->addActionContext('change-stor-directory', 'json')
->addActionContext('reload-watch-directory', 'json')
->addActionContext('remove-watch-directory', 'json')
->addActionContext('is-import-in-progress', 'json')
->addActionContext('change-stream-setting', 'json')
->addActionContext('get-liquidsoap-status', 'json')
->addActionContext('set-source-connection-url', 'json')
->addActionContext('get-admin-password-status', 'json')
->initContext();
->addActionContext('change-stor-directory', 'json')
->addActionContext('reload-watch-directory', 'json')
->addActionContext('remove-watch-directory', 'json')
->addActionContext('is-import-in-progress', 'json')
->addActionContext('change-stream-setting', 'json')
->addActionContext('get-liquidsoap-status', 'json')
->addActionContext('set-source-connection-url', 'json')
->addActionContext('get-admin-password-status', 'json')
->initContext()
;
}
public function indexAction()
@ -28,54 +28,53 @@ class PreferenceController extends Zend_Controller_Action
$baseUrl = Application_Common_OsPath::getBaseDir();
$this->view->headScript()->appendFile($baseUrl.'js/airtime/preferences/preferences.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->statusMsg = "";
$this->view->headScript()->appendFile($baseUrl . 'js/airtime/preferences/preferences.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->statusMsg = '';
$form = new Application_Form_Preferences();
$values = array();
$values = [];
SessionHelper::reopenSessionForWriting();
if ($request->isPost()) {
$values = $request->getPost();
if ($form->isValid($values))
{
Application_Model_Preference::SetHeadTitle($values["stationName"], $this->view);
Application_Model_Preference::SetStationDescription($values["stationDescription"]);
Application_Model_Preference::SetTrackTypeDefault($values["tracktypeDefault"]);
Application_Model_Preference::SetDefaultCrossfadeDuration($values["stationDefaultCrossfadeDuration"]);
Application_Model_Preference::SetDefaultFadeIn($values["stationDefaultFadeIn"]);
Application_Model_Preference::SetDefaultFadeOut($values["stationDefaultFadeOut"]);
Application_Model_Preference::SetPodcastAlbumOverride($values["podcastAlbumOverride"]);
Application_Model_Preference::SetPodcastAutoSmartblock($values["podcastAutoSmartblock"]);
Application_Model_Preference::SetIntroPlaylist($values["introPlaylistSelect"]);
Application_Model_Preference::SetOutroPlaylist($values["outroPlaylistSelect"]);
Application_Model_Preference::SetAllow3rdPartyApi($values["thirdPartyApi"]);
Application_Model_Preference::SetAllowedCorsUrls($values["allowedCorsUrls"]);
Application_Model_Preference::SetDefaultLocale($values["locale"]);
Application_Model_Preference::SetDefaultTimezone($values["timezone"]);
Application_Model_Preference::SetWeekStartDay($values["weekStartDay"]);
Application_Model_Preference::setRadioPageDisplayLoginButton($values["radioPageLoginButton"]);
Application_Model_Preference::SetFeaturePreviewMode($values["featurePreviewMode"]);
if ($form->isValid($values)) {
Application_Model_Preference::SetHeadTitle($values['stationName'], $this->view);
Application_Model_Preference::SetStationDescription($values['stationDescription']);
Application_Model_Preference::SetTrackTypeDefault($values['tracktypeDefault']);
Application_Model_Preference::SetDefaultCrossfadeDuration($values['stationDefaultCrossfadeDuration']);
Application_Model_Preference::SetDefaultFadeIn($values['stationDefaultFadeIn']);
Application_Model_Preference::SetDefaultFadeOut($values['stationDefaultFadeOut']);
Application_Model_Preference::SetPodcastAlbumOverride($values['podcastAlbumOverride']);
Application_Model_Preference::SetPodcastAutoSmartblock($values['podcastAutoSmartblock']);
Application_Model_Preference::SetIntroPlaylist($values['introPlaylistSelect']);
Application_Model_Preference::SetOutroPlaylist($values['outroPlaylistSelect']);
Application_Model_Preference::SetAllow3rdPartyApi($values['thirdPartyApi']);
Application_Model_Preference::SetAllowedCorsUrls($values['allowedCorsUrls']);
Application_Model_Preference::SetDefaultLocale($values['locale']);
Application_Model_Preference::SetDefaultTimezone($values['timezone']);
Application_Model_Preference::SetWeekStartDay($values['weekStartDay']);
Application_Model_Preference::setRadioPageDisplayLoginButton($values['radioPageLoginButton']);
Application_Model_Preference::SetFeaturePreviewMode($values['featurePreviewMode']);
$logoUploadElement = $form->getSubForm('preferences_general')->getElement('stationLogo');
$logoUploadElement->receive();
$imagePath = $logoUploadElement->getFileName();
// Only update the image logo if the new logo is non-empty
if (!empty($imagePath) && $imagePath != "") {
if (!empty($imagePath) && $imagePath != '') {
Application_Model_Preference::SetStationLogo($imagePath);
}
Application_Model_Preference::setTuneinEnabled($values["enable_tunein"]);
Application_Model_Preference::setTuneinStationId($values["tunein_station_id"]);
Application_Model_Preference::setTuneinPartnerKey($values["tunein_partner_key"]);
Application_Model_Preference::setTuneinPartnerId($values["tunein_partner_id"]);
Application_Model_Preference::setTuneinEnabled($values['enable_tunein']);
Application_Model_Preference::setTuneinStationId($values['tunein_station_id']);
Application_Model_Preference::setTuneinPartnerKey($values['tunein_partner_key']);
Application_Model_Preference::setTuneinPartnerId($values['tunein_partner_id']);
$this->view->statusMsg = "<div class='success'>". _("Preferences updated.")."</div>";
$this->view->statusMsg = "<div class='success'>" . _('Preferences updated.') . '</div>';
$form = new Application_Form_Preferences();
$this->view->form = $form;
//$this->_helper->json->sendJson(array("valid"=>"true", "html"=>$this->view->render('preference/index.phtml')));
//$this->_helper->json->sendJson(array("valid"=>"true", "html"=>$this->view->render('preference/index.phtml')));
} else {
$this->view->form = $form;
//$this->_helper->json->sendJson(array("valid"=>"false", "html"=>$this->view->render('preference/index.phtml')));
@ -86,7 +85,8 @@ class PreferenceController extends Zend_Controller_Action
$this->view->form = $form;
}
public function stationPodcastSettingsAction() {
public function stationPodcastSettingsAction()
{
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
@ -101,11 +101,11 @@ class PreferenceController extends Zend_Controller_Action
$stationPodcast = PodcastQuery::create()->findOneByDbId(Application_Model_Preference::getStationPodcastId());
$key = Application_Model_Preference::getStationPodcastDownloadKey();
$url = Application_Common_HTTPHelper::getStationUrl() .
(((int) $values->stationPodcastPrivacy) ? "feeds/station-rss?sharing_token=$key" : "feeds/station-rss");
(((int) $values->stationPodcastPrivacy) ? "feeds/station-rss?sharing_token={$key}" : 'feeds/station-rss');
$stationPodcast->setDbUrl($url)->save();
Application_Model_Preference::setStationPodcastPrivacy($values->stationPodcastPrivacy);
$this->_helper->json->sendJson(array("url" => $url));
$this->_helper->json->sendJson(['url' => $url]);
}
public function directoryConfigAction()
@ -122,11 +122,12 @@ class PreferenceController extends Zend_Controller_Action
if (!SecurityHelper::verifyCSRFToken($this->_getParam('csrf_token'))) {
Logging::error(__FILE__ . ': Invalid CSRF token');
$this->_helper->json->sendJson(array("jsonrpc" => "2.0", "valid" => false, "error" => "CSRF token did not match."));
$this->_helper->json->sendJson(['jsonrpc' => '2.0', 'valid' => false, 'error' => 'CSRF token did not match.']);
return;
}
Application_Model_Preference::SetStationLogo("");
Application_Model_Preference::SetStationLogo('');
}
public function streamSettingAction()
@ -139,17 +140,17 @@ class PreferenceController extends Zend_Controller_Action
$baseUrl = Application_Common_OsPath::getBaseDir();
$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');
SessionHelper::reopenSessionForWriting();
$name_map = array(
'ogg' => 'Ogg Vorbis',
'fdkaac' => 'AAC+',
'aac' => 'AAC',
'opus' => 'Opus',
'mp3' => 'MP3',
);
$name_map = [
'ogg' => 'Ogg Vorbis',
'fdkaac' => 'AAC+',
'aac' => 'AAC',
'opus' => 'Opus',
'mp3' => 'MP3',
];
$num_of_stream = intval(Application_Model_Preference::GetNumOfStreams());
$form = new Application_Form_StreamSetting();
@ -160,11 +161,11 @@ class PreferenceController extends Zend_Controller_Action
$form->addElement($csrf_element);
$live_stream_subform = new Application_Form_LiveStreamingPreferences();
$form->addSubForm($live_stream_subform, "live_stream_subform");
$form->addSubForm($live_stream_subform, 'live_stream_subform');
// get predefined type and bitrate from pref table
$temp_types = Application_Model_Preference::GetStreamType();
$stream_types = array();
$stream_types = [];
foreach ($temp_types as $type) {
$type = strtolower(trim($type));
if (isset($name_map[$type])) {
@ -177,10 +178,10 @@ class PreferenceController extends Zend_Controller_Action
$temp_bitrate = Application_Model_Preference::GetStreamBitrate();
$max_bitrate = intval(Application_Model_Preference::GetMaxBitrate());
$stream_bitrates = array();
$stream_bitrates = [];
foreach ($temp_bitrate as $type) {
if (intval($type) <= $max_bitrate) {
$stream_bitrates[trim($type)] = strtoupper(trim($type))." kbit/s";
$stream_bitrates[trim($type)] = strtoupper(trim($type)) . ' kbit/s';
}
}
@ -188,7 +189,7 @@ class PreferenceController extends Zend_Controller_Action
$setting = Application_Model_StreamSetting::getStreamSetting();
$form->setSetting($setting);
for ($i=1; $i<=$num_of_stream; $i++) {
for ($i = 1; $i <= $num_of_stream; ++$i) {
$subform = new Application_Form_StreamSettingSubForm();
$subform->setPrefix($i);
$subform->setSetting($setting);
@ -196,7 +197,7 @@ class PreferenceController extends Zend_Controller_Action
$subform->setStreamBitrates($stream_bitrates);
$subform->startForm();
$subform->toggleState();
$form->addSubForm($subform, "s".$i."_subform");
$form->addSubForm($subform, 's' . $i . '_subform');
}
$live_stream_subform->updateVariables();
@ -208,36 +209,36 @@ class PreferenceController extends Zend_Controller_Action
* $form->isValid() is expecting it in
*/
$postData = explode('&', $params['data']);
$s1_data = array();
$s2_data = array();
$s3_data = array();
$s4_data = array();
$values = array();
foreach($postData as $k=>$v) {
$s1_data = [];
$s2_data = [];
$s3_data = [];
$s4_data = [];
$values = [];
foreach ($postData as $k => $v) {
$v = explode('=', urldecode($v));
if (strpos($v[0], "s1_data") !== false) {
if (strpos($v[0], 's1_data') !== false) {
/* In this case $v[0] may be 's1_data[enable]' , for example.
* We only want the 'enable' part
*/
preg_match('/\[(.*)\]/', $v[0], $matches);
$s1_data[$matches[1]] = $v[1];
} elseif (strpos($v[0], "s2_data") !== false) {
} elseif (strpos($v[0], 's2_data') !== false) {
preg_match('/\[(.*)\]/', $v[0], $matches);
$s2_data[$matches[1]] = $v[1];
} elseif (strpos($v[0], "s3_data") !== false) {
preg_match('/\[(.*)\]/', $v[0], $matches);
} elseif (strpos($v[0], 's3_data') !== false) {
preg_match('/\[(.*)\]/', $v[0], $matches);
$s3_data[$matches[1]] = $v[1];
} elseif (strpos($v[0], "s4_data") !== false) {
preg_match('/\[(.*)\]/', $v[0], $matches);
} elseif (strpos($v[0], 's4_data') !== false) {
preg_match('/\[(.*)\]/', $v[0], $matches);
$s4_data[$matches[1]] = $v[1];
} else {
$values[$v[0]] = $v[1];
}
}
$values["s1_data"] = $s1_data;
$values["s2_data"] = $s2_data;
$values["s3_data"] = $s3_data;
$values["s4_data"] = $s4_data;
$values['s1_data'] = $s1_data;
$values['s2_data'] = $s2_data;
$values['s3_data'] = $s3_data;
$values['s4_data'] = $s4_data;
if ($form->isValid($values)) {
Application_Model_StreamSetting::setStreamSetting($values);
@ -245,68 +246,67 @@ class PreferenceController extends Zend_Controller_Action
/* If the admin password values are empty then we should not
* set the pseudo password ('xxxxxx') on the front-end
*/
$s1_set_admin_pass = !empty($values["s1_data"]["admin_pass"]);
$s2_set_admin_pass = !empty($values["s2_data"]["admin_pass"]);
$s3_set_admin_pass = !empty($values["s3_data"]["admin_pass"]);
$s4_set_admin_pass = !empty($values["s4_data"]["admin_pass"]);
$s1_set_admin_pass = !empty($values['s1_data']['admin_pass']);
$s2_set_admin_pass = !empty($values['s2_data']['admin_pass']);
$s3_set_admin_pass = !empty($values['s3_data']['admin_pass']);
$s4_set_admin_pass = !empty($values['s4_data']['admin_pass']);
// this goes into cc_pref table
$this->setStreamPreferences($values);
// compare new values with current value
$changeRGenabled = Application_Model_Preference::GetEnableReplayGain() != $values["enableReplayGain"];
$changeRGmodifier = Application_Model_Preference::getReplayGainModifier() != $values["replayGainModifier"];
$changeRGenabled = Application_Model_Preference::GetEnableReplayGain() != $values['enableReplayGain'];
$changeRGmodifier = Application_Model_Preference::getReplayGainModifier() != $values['replayGainModifier'];
if ($changeRGenabled || $changeRGmodifier) {
Application_Model_Preference::SetEnableReplayGain($values["enableReplayGain"]);
Application_Model_Preference::setReplayGainModifier($values["replayGainModifier"]);
$md = array('schedule' => Application_Model_Schedule::getSchedule());
Application_Model_RabbitMq::SendMessageToPypo("update_schedule", $md);
Application_Model_Preference::SetEnableReplayGain($values['enableReplayGain']);
Application_Model_Preference::setReplayGainModifier($values['replayGainModifier']);
$md = ['schedule' => Application_Model_Schedule::getSchedule()];
Application_Model_RabbitMq::SendMessageToPypo('update_schedule', $md);
//Application_Model_RabbitMq::PushSchedule();
}
// pulling this from the 2.5.x branch
if (!Application_Model_Preference::GetMasterDjConnectionUrlOverride()) {
$master_connection_url = "http://".$_SERVER['SERVER_NAME'].":".$values["master_source_port"].$values["master_source_mount"];
if (empty($values["master_source_port"]) || empty($values["master_source_mount"])) {
$master_connection_url = 'http://' . $_SERVER['SERVER_NAME'] . ':' . $values['master_source_port'] . $values['master_source_mount'];
if (empty($values['master_source_port']) || empty($values['master_source_mount'])) {
Application_Model_Preference::SetMasterDJSourceConnectionURL('N/A');
} else {
Application_Model_Preference::SetMasterDJSourceConnectionURL($master_connection_url);
}
} else {
Application_Model_Preference::SetMasterDJSourceConnectionURL($values["master_source_host"]);
Application_Model_Preference::SetMasterDJSourceConnectionURL($values['master_source_host']);
}
if (!Application_Model_Preference::GetLiveDjConnectionUrlOverride()) {
$live_connection_url = "http://".$_SERVER['SERVER_NAME'].":".$values["show_source_port"].$values["show_source_mount"];
if (empty($values["show_source_port"]) || empty($values["show_source_mount"])) {
$live_connection_url = 'http://' . $_SERVER['SERVER_NAME'] . ':' . $values['show_source_port'] . $values['show_source_mount'];
if (empty($values['show_source_port']) || empty($values['show_source_mount'])) {
Application_Model_Preference::SetLiveDJSourceConnectionURL('N/A');
} else {
Application_Model_Preference::SetLiveDJSourceConnectionURL($live_connection_url);
}
} else {
Application_Model_Preference::SetLiveDJSourceConnectionURL($values["show_source_host"]);
Application_Model_Preference::SetLiveDJSourceConnectionURL($values['show_source_host']);
}
Application_Model_StreamSetting::setMasterLiveStreamPort($values["master_source_port"]);
Application_Model_StreamSetting::setMasterLiveStreamMountPoint($values["master_source_mount"]);
Application_Model_StreamSetting::setDjLiveStreamPort($values["show_source_port"]);
Application_Model_StreamSetting::setDjLiveStreamMountPoint($values["show_source_mount"]);
Application_Model_StreamSetting::setMasterLiveStreamPort($values['master_source_port']);
Application_Model_StreamSetting::setMasterLiveStreamMountPoint($values['master_source_mount']);
Application_Model_StreamSetting::setDjLiveStreamPort($values['show_source_port']);
Application_Model_StreamSetting::setDjLiveStreamMountPoint($values['show_source_mount']);
Application_Model_StreamSetting::setOffAirMeta($values['offAirMeta']);
// store stream update timestamp
Application_Model_Preference::SetStreamUpdateTimestamp();
$data = array();
$data = [];
$info = Application_Model_StreamSetting::getStreamSetting();
$data['setting'] = $info;
for ($i=1; $i<=$num_of_stream; $i++) {
Application_Model_StreamSetting::setLiquidsoapError($i, "waiting");
for ($i = 1; $i <= $num_of_stream; ++$i) {
Application_Model_StreamSetting::setLiquidsoapError($i, 'waiting');
}
Application_Model_RabbitMq::SendMessageToPypo("update_stream_setting", $data);
$this->view->statusMsg = "<div class='success'>"._("Stream Setting Updated.")."</div>";
Application_Model_RabbitMq::SendMessageToPypo('update_stream_setting', $data);
$this->view->statusMsg = "<div class='success'>" . _('Stream Setting Updated.') . '</div>';
}
}
@ -315,61 +315,61 @@ class PreferenceController extends Zend_Controller_Action
$this->view->form = $form;
if ($request->isPost()) {
if ($form->isValid($values)) {
$this->_helper->json->sendJson(array(
"valid" => "true",
"html" => $this->view->render('preference/stream-setting.phtml'),
"s1_set_admin_pass" => $s1_set_admin_pass,
"s2_set_admin_pass" => $s2_set_admin_pass,
"s3_set_admin_pass" => $s3_set_admin_pass,
"s4_set_admin_pass" => $s4_set_admin_pass,
));
$this->_helper->json->sendJson([
'valid' => 'true',
'html' => $this->view->render('preference/stream-setting.phtml'),
's1_set_admin_pass' => $s1_set_admin_pass,
's2_set_admin_pass' => $s2_set_admin_pass,
's3_set_admin_pass' => $s3_set_admin_pass,
's4_set_admin_pass' => $s4_set_admin_pass,
]);
} else {
$this->_helper->json->sendJson(array("valid" => "false", "html" => $this->view->render('preference/stream-setting.phtml')));
$this->_helper->json->sendJson(['valid' => 'false', 'html' => $this->view->render('preference/stream-setting.phtml')]);
}
}
}
/**
* Set stream settings preferences
* Set stream settings preferences.
*
* @param array $values stream setting preference values
*/
private function setStreamPreferences($values) {
private function setStreamPreferences($values)
{
Application_Model_Preference::setUsingCustomStreamSettings($values['customStreamSettings']);
Application_Model_Preference::SetStreamLabelFormat($values['streamFormat']);
Application_Model_Preference::SetLiveStreamMasterUsername($values["master_username"]);
Application_Model_Preference::SetLiveStreamMasterPassword($values["master_password"]);
Application_Model_Preference::SetDefaultTransitionFade($values["transition_fade"]);
Application_Model_Preference::SetAutoTransition($values["auto_transition"]);
Application_Model_Preference::SetAutoSwitch($values["auto_switch"]);
Application_Model_Preference::SetLiveStreamMasterUsername($values['master_username']);
Application_Model_Preference::SetLiveStreamMasterPassword($values['master_password']);
Application_Model_Preference::SetDefaultTransitionFade($values['transition_fade']);
Application_Model_Preference::SetAutoTransition($values['auto_transition']);
Application_Model_Preference::SetAutoSwitch($values['auto_switch']);
}
public function serverBrowseAction()
{
$request = $this->getRequest();
$path = $request->getParam("path", null);
$path = $request->getParam('path', null);
$result = array();
$result = [];
if (is_null($path)) {
$element = array();
$element["name"] = _("path should be specified");
$element["isFolder"] = false;
$element["isError"] = true;
$element = [];
$element['name'] = _('path should be specified');
$element['isFolder'] = false;
$element['isError'] = true;
$result[$path] = $element;
} else {
$path = $path.'/';
$path = $path . '/';
$handle = opendir($path);
if ($handle !== false) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if ($file != '.' && $file != '..') {
//only show directories that aren't private.
if (is_dir($path.$file) && substr($file, 0, 1) != ".") {
$element = array();
$element["name"] = $file;
$element["isFolder"] = true;
$element["isError"] = false;
if (is_dir($path . $file) && substr($file, 0, 1) != '.') {
$element = [];
$element['name'] = $file;
$element['isFolder'] = true;
$element['isError'] = false;
$result[$file] = $element;
}
}
@ -383,14 +383,14 @@ class PreferenceController extends Zend_Controller_Action
public function changeStorDirectoryAction()
{
$chosen = $this->getRequest()->getParam("dir");
$element = $this->getRequest()->getParam("element");
$chosen = $this->getRequest()->getParam('dir');
$element = $this->getRequest()->getParam('element');
$watched_dirs_form = new Application_Form_WatchedDirPreferences();
$res = Application_Model_MusicDir::setStorDir($chosen);
if ($res['code'] != 0) {
$watched_dirs_form->populate(array('storageFolder' => $chosen));
$watched_dirs_form->getElement($element)->setErrors(array($res['error']));
$watched_dirs_form->populate(['storageFolder' => $chosen]);
$watched_dirs_form->getElement($element)->setErrors([$res['error']]);
}
$this->view->subform = $watched_dirs_form->render();
@ -398,14 +398,14 @@ class PreferenceController extends Zend_Controller_Action
public function reloadWatchDirectoryAction()
{
$chosen = $this->getRequest()->getParam("dir");
$element = $this->getRequest()->getParam("element");
$chosen = $this->getRequest()->getParam('dir');
$element = $this->getRequest()->getParam('element');
$watched_dirs_form = new Application_Form_WatchedDirPreferences();
$res = Application_Model_MusicDir::addWatchedDir($chosen);
if ($res['code'] != 0) {
$watched_dirs_form->populate(array('watchedFolder' => $chosen));
$watched_dirs_form->getElement($element)->setErrors(array($res['error']));
$watched_dirs_form->populate(['watchedFolder' => $chosen]);
$watched_dirs_form->getElement($element)->setErrors([$res['error']]);
}
$this->view->subform = $watched_dirs_form->render();
@ -415,17 +415,17 @@ class PreferenceController extends Zend_Controller_Action
{
$dir_path = $this->getRequest()->getParam('dir');
$dir = Application_Model_MusicDir::getDirByPath($dir_path);
$data = array( 'directory' => $dir->getDirectory(),
'id' => $dir->getId());
$data = ['directory' => $dir->getDirectory(),
'id' => $dir->getId(), ];
Application_Model_RabbitMq::SendMessageToMediaMonitor('rescan_watch', $data);
Logging::info("Unhiding all files belonging to:: $dir_path");
Logging::info("Unhiding all files belonging to:: {$dir_path}");
$dir->unhideFiles();
$this->_helper->json->sendJson(null);
}
public function removeWatchDirectoryAction()
{
$chosen = $this->getRequest()->getParam("dir");
$chosen = $this->getRequest()->getParam('dir');
$dir = Application_Model_MusicDir::removeWatchedDir($chosen);
@ -437,7 +437,7 @@ class PreferenceController extends Zend_Controller_Action
{
$now = time();
$res = false;
if (Application_Model_Preference::GetImportTimestamp()+10 > $now) {
if (Application_Model_Preference::GetImportTimestamp() + 10 > $now) {
$res = true;
}
$this->_helper->json->sendJson($res);
@ -445,15 +445,15 @@ class PreferenceController extends Zend_Controller_Action
public function getLiquidsoapStatusAction()
{
$out = array();
$out = [];
$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 = $status == NULL?_("Problem with Liquidsoap..."):$status;
$status = $status == null ? _('Problem with Liquidsoap...') : $status;
if (!Application_Model_StreamSetting::getStreamEnabled($i)) {
$status = "N/A";
$status = 'N/A';
}
$out[] = array("id"=>$i, "status"=>$status);
$out[] = ['id' => $i, 'status' => $status];
}
$this->_helper->json->sendJson($out);
}
@ -463,9 +463,9 @@ class PreferenceController extends Zend_Controller_Action
SessionHelper::reopenSessionForWriting();
$request = $this->getRequest();
$type = $request->getParam("type", null);
$url = urldecode($request->getParam("url", null));
$override = $request->getParam("override", false);
$type = $request->getParam('type', null);
$url = urldecode($request->getParam('url', null));
$override = $request->getParam('override', false);
if ($type == 'masterdj') {
Application_Model_Preference::SetMasterDJSourceConnectionURL($url);
@ -482,13 +482,13 @@ class PreferenceController extends Zend_Controller_Action
{
SessionHelper::reopenSessionForWriting();
$out = array();
$out = [];
$num_of_stream = intval(Application_Model_Preference::GetNumOfStreams());
for ($i=1; $i<=$num_of_stream; $i++) {
if (Application_Model_StreamSetting::getAdminPass('s'.$i)=='') {
$out["s".$i] = false;
for ($i = 1; $i <= $num_of_stream; ++$i) {
if (Application_Model_StreamSetting::getAdminPass('s' . $i) == '') {
$out['s' . $i] = false;
} else {
$out["s".$i] = true;
$out['s' . $i] = true;
}
}
$this->_helper->json->sendJson($out);
@ -501,7 +501,8 @@ class PreferenceController extends Zend_Controller_Action
if (!SecurityHelper::verifyCSRFToken($this->_getParam('csrf_token'))) {
Logging::error(__FILE__ . ': Invalid CSRF token');
$this->_helper->json->sendJson(array("jsonrpc" => "2.0", "valid" => false, "error" => "CSRF token did not match."));
$this->_helper->json->sendJson(['jsonrpc' => '2.0', 'valid' => false, 'error' => 'CSRF token did not match.']);
return;
}
@ -510,8 +511,10 @@ class PreferenceController extends Zend_Controller_Action
$method = $_SERVER['REQUEST_METHOD'];
if (!($method == 'POST')) {
$this->getResponse()
->setHttpResponseCode(405)
->appendBody(_("Request method not accepted") . ": $method");
->setHttpResponseCode(405)
->appendBody(_('Request method not accepted') . ": {$method}")
;
return;
}
@ -520,16 +523,19 @@ class PreferenceController extends Zend_Controller_Action
$this->deleteStoredFiles();
$this->getResponse()
->setHttpResponseCode(200)
->appendBody("OK");
->setHttpResponseCode(200)
->appendBody('OK')
;
}
private function deleteFutureScheduleItems() {
$utcTimezone = new DateTimeZone("UTC");
$nowDateTime = new DateTime("now", $utcTimezone);
private function deleteFutureScheduleItems()
{
$utcTimezone = new DateTimeZone('UTC');
$nowDateTime = new DateTime('now', $utcTimezone);
$scheduleItems = CcScheduleQuery::create()
->filterByDbEnds($nowDateTime->format(DEFAULT_TIMESTAMP_FORMAT), Criteria::GREATER_THAN)
->find();
->find()
;
// Delete all the schedule items
foreach ($scheduleItems as $i) {
@ -549,20 +555,22 @@ class PreferenceController extends Zend_Controller_Action
}
}
private function deleteCloudFiles() {
private function deleteCloudFiles()
{
try {
$CC_CONFIG = Config::getConfig();
foreach ($CC_CONFIG["supportedStorageBackends"] as $storageBackend) {
foreach ($CC_CONFIG['supportedStorageBackends'] as $storageBackend) {
$proxyStorageBackend = new ProxyStorageBackend($storageBackend);
$proxyStorageBackend->deleteAllCloudFileObjects();
}
} catch(Exception $e) {
} catch (Exception $e) {
Logging::info($e->getMessage());
}
}
private function deleteStoredFiles() {
private function deleteStoredFiles()
{
// Delete all files from the database
$files = CcFilesQuery::create()->find();
foreach ($files as $file) {
@ -572,5 +580,4 @@ class PreferenceController extends Zend_Controller_Action
$storedFile->delete(true);
}
}
}

View File

@ -1,8 +1,9 @@
<?php
class RenderController extends Zend_Controller_Action {
public function init() {
class RenderController extends Zend_Controller_Action
{
public function init()
{
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
@ -12,9 +13,9 @@ class RenderController extends Zend_Controller_Action {
$this->view->csrf = $csrf_element;
}
public function podcastUrlDialogAction() {
public function podcastUrlDialogAction()
{
$path = 'podcast/podcast_url_dialog.phtml';
$this->_helper->json->sendJson(array("html"=>$this->view->render($path)));
$this->_helper->json->sendJson(['html' => $this->view->render($path)]);
}
}
}

View File

@ -2,43 +2,43 @@
class ScheduleController extends Zend_Controller_Action
{
protected $sched_sess = null;
protected $sched_sess;
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('event-feed', 'json')
->addActionContext('event-feed-preload', 'json')
->addActionContext('make-context-menu', 'json')
->addActionContext('add-show-dialog', 'json')
->addActionContext('add-show', 'json')
->addActionContext('edit-show', 'json')
->addActionContext('move-show', 'json')
->addActionContext('resize-show', 'json')
->addActionContext('delete-show-instance', 'json')
->addActionContext('show-content-dialog', 'json')
->addActionContext('clear-show', 'json')
->addActionContext('get-current-playlist', 'json')
->addActionContext('remove-group', 'json')
->addActionContext('populate-show-form', 'json')
->addActionContext('populate-repeating-show-instance-form', 'json')
->addActionContext('delete-show', 'json')
->addActionContext('cancel-current-show', 'json')
->addActionContext('get-form', 'json')
->addActionContext('upload-to-sound-cloud', 'json')
->addActionContext('content-context-menu', 'json')
->addActionContext('set-time-scale', 'json')
->addActionContext('set-time-interval', 'json')
->addActionContext('edit-repeating-show-instance', 'json')
->addActionContext('dj-edit-show', 'json')
->addActionContext('calculate-duration', 'json')
->addActionContext('get-current-show', 'json')
->addActionContext('update-future-is-scheduled', 'json')
->addActionContext('localize-start-end-time', 'json')
->initContext();
->addActionContext('event-feed-preload', 'json')
->addActionContext('make-context-menu', 'json')
->addActionContext('add-show-dialog', 'json')
->addActionContext('add-show', 'json')
->addActionContext('edit-show', 'json')
->addActionContext('move-show', 'json')
->addActionContext('resize-show', 'json')
->addActionContext('delete-show-instance', 'json')
->addActionContext('show-content-dialog', 'json')
->addActionContext('clear-show', 'json')
->addActionContext('get-current-playlist', 'json')
->addActionContext('remove-group', 'json')
->addActionContext('populate-show-form', 'json')
->addActionContext('populate-repeating-show-instance-form', 'json')
->addActionContext('delete-show', 'json')
->addActionContext('cancel-current-show', 'json')
->addActionContext('get-form', 'json')
->addActionContext('upload-to-sound-cloud', 'json')
->addActionContext('content-context-menu', 'json')
->addActionContext('set-time-scale', 'json')
->addActionContext('set-time-interval', 'json')
->addActionContext('edit-repeating-show-instance', 'json')
->addActionContext('dj-edit-show', 'json')
->addActionContext('calculate-duration', 'json')
->addActionContext('get-current-show', 'json')
->addActionContext('update-future-is-scheduled', 'json')
->addActionContext('localize-start-end-time', 'json')
->initContext()
;
$this->sched_sess = new Zend_Session_Namespace("schedule");
$this->sched_sess = new Zend_Session_Namespace('schedule');
}
public function indexAction()
@ -53,66 +53,66 @@ class ScheduleController extends Zend_Controller_Action
$events = json_encode($scheduleController->view->events);
$this->view->headScript()->appendScript(
"var calendarPref = {};\n".
"calendarPref.weekStart = ".Application_Model_Preference::GetWeekStartDay().";\n".
"calendarPref.timestamp = ".time().";\n".
"calendarPref.timezoneOffset = ".Application_Common_DateHelper::getUserTimezoneOffset().";\n".
"calendarPref.timeScale = '".Application_Model_Preference::GetCalendarTimeScale()."';\n".
"calendarPref.timeInterval = ".Application_Model_Preference::GetCalendarTimeInterval().";\n".
"calendarPref.weekStartDay = ".Application_Model_Preference::GetWeekStartDay().";\n".
"var calendarEvents = $events;"
"var calendarPref = {};\n" .
'calendarPref.weekStart = ' . Application_Model_Preference::GetWeekStartDay() . ";\n" .
'calendarPref.timestamp = ' . time() . ";\n" .
'calendarPref.timezoneOffset = ' . Application_Common_DateHelper::getUserTimezoneOffset() . ";\n" .
"calendarPref.timeScale = '" . Application_Model_Preference::GetCalendarTimeScale() . "';\n" .
'calendarPref.timeInterval = ' . Application_Model_Preference::GetCalendarTimeInterval() . ";\n" .
'calendarPref.weekStartDay = ' . Application_Model_Preference::GetWeekStartDay() . ";\n" .
"var calendarEvents = {$events};"
);
$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');
//full-calendar-functions.js requires this variable, so that datePicker widget can be offset to server time instead of client time
//this should be as a default, however with our new drop down timezone changing for shows, we should reset this offset then??
$this->view->headScript()->appendScript("var timezoneOffset = ".Application_Common_DateHelper::getStationTimezoneOffset()."; //in seconds");
$this->view->headScript()->appendScript('var timezoneOffset = ' . Application_Common_DateHelper::getStationTimezoneOffset() . '; //in seconds');
//set offset to ensure it loads last
$this->view->headScript()->offsetSetFile(90, $baseUrl.'js/airtime/schedule/full-calendar-functions.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->offsetSetFile(90, $baseUrl . 'js/airtime/schedule/full-calendar-functions.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/fullcalendar/fullcalendar.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/colorpicker/js/colorpicker.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/fullcalendar/fullcalendar.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/colorpicker/js/colorpicker.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
// This block needs to be added before the add-show.js script
$this->view->headScript()->appendFile($baseUrl.'js/libs/dayjs.min.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/libs/utc.min.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/libs/timezone.min.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/libs/dayjs.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/libs/utc.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/libs/timezone.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/airtime/schedule/add-show.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->offsetSetFile(100, $baseUrl.'js/airtime/schedule/schedule.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/schedule/add-show.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->offsetSetFile(100, $baseUrl . 'js/airtime/schedule/schedule.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->headLink()->appendStylesheet($baseUrl.'css/jquery.ui.timepicker.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'css/fullcalendar.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'css/colorpicker/css/colorpicker.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'css/add-show.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'css/jquery.contextMenu.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/fullcalendar.css?' . $CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl . 'css/colorpicker/css/colorpicker.css?' . $CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl . 'css/add-show.css?' . $CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl . 'css/jquery.contextMenu.css?' . $CC_CONFIG['airtime_version']);
//Start Show builder JS/CSS requirements
$headScript = $this->view->headScript();
AirtimeTableView::injectTableJavaScriptDependencies($headScript, $baseUrl, $CC_CONFIG['airtime_version']);
$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/buttons/buttons.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/airtime/library/events/library_showbuilder.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/showbuilder/builder.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/library/events/library_showbuilder.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/showbuilder/builder.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/dataTables.colReorder.min.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'css/showbuilder.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl.'css/dashboard.css?'.$CC_CONFIG['airtime_version']);
$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/dataTables.colReorder.min.css?' . $CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl . 'css/showbuilder.css?' . $CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl . 'css/dashboard.css?' . $CC_CONFIG['airtime_version']);
//End Show builder JS/CSS requirements
$this->createShowFormAction(true);
$user = Application_Model_User::getCurrentUser();
if ($user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
if ($user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER])) {
$this->view->preloadShowForm = true;
}
@ -127,12 +127,15 @@ class ScheduleController extends Zend_Controller_Action
$userTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
$start = new DateTime($this->_getParam('start', null), $userTimezone);
$start->setTimezone(new DateTimeZone("UTC"));
$start->setTimezone(new DateTimeZone('UTC'));
$end = new DateTime($this->_getParam('end', null), $userTimezone);
$end->setTimezone(new DateTimeZone("UTC"));
$end->setTimezone(new DateTimeZone('UTC'));
$events = &Application_Model_Show::getFullCalendarEvents($start, $end,
$currentUser->isAdminOrPM());
$events = &Application_Model_Show::getFullCalendarEvents(
$start,
$end,
$currentUser->isAdminOrPM()
);
$this->view->events = $events;
}
@ -141,17 +144,17 @@ class ScheduleController extends Zend_Controller_Action
{
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id);
$editable = $user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
$editable = $user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER]);
$calendar_interval = Application_Model_Preference::GetCalendarTimeScale();
if ($calendar_interval == "agendaDay") {
if ($calendar_interval == 'agendaDay') {
list($start, $end) = Application_Model_Show::getStartEndCurrentDayView();
} else if ($calendar_interval == "agendaWeek") {
} elseif ($calendar_interval == 'agendaWeek') {
list($start, $end) = Application_Model_Show::getStartEndCurrentWeekView();
} else if ($calendar_interval == "month") {
} elseif ($calendar_interval == 'month') {
list($start, $end) = Application_Model_Show::getStartEndCurrentMonthPlusView();
} else {
Logging::error("Invalid Calendar Interval '$calendar_interval'");
Logging::error("Invalid Calendar Interval '{$calendar_interval}'");
}
$events = &Application_Model_Show::getFullCalendarEvents($start, $end, $editable);
@ -162,7 +165,7 @@ class ScheduleController extends Zend_Controller_Action
{
$currentShow = Application_Model_Show::getCurrentShow();
if (!empty($currentShow)) {
$this->view->si_id = $currentShow[0]["instance_id"];
$this->view->si_id = $currentShow[0]['instance_id'];
$this->view->current_show = true;
} else {
$this->view->current_show = false;
@ -174,20 +177,22 @@ class ScheduleController extends Zend_Controller_Action
$deltaDay = $this->_getParam('day');
$deltaMin = $this->_getParam('min');
$log_vars = array();
$log_vars["url"] = $_SERVER['HTTP_HOST'];
$log_vars["action"] = "schedule/move-show";
$log_vars["params"] = array();
$log_vars["params"]["instance id"] = $this->_getParam('showInstanceId');
$log_vars["params"]["delta day"] = $deltaDay;
$log_vars["params"]["delta minute"] = $deltaMin;
$log_vars = [];
$log_vars['url'] = $_SERVER['HTTP_HOST'];
$log_vars['action'] = 'schedule/move-show';
$log_vars['params'] = [];
$log_vars['params']['instance id'] = $this->_getParam('showInstanceId');
$log_vars['params']['delta day'] = $deltaDay;
$log_vars['params']['delta minute'] = $deltaMin;
Logging::info($log_vars);
try {
$service_calendar = new Application_Service_CalendarService(
$this->_getParam('showInstanceId'));
$this->_getParam('showInstanceId')
);
} catch (Exception $e) {
$this->view->show_error = true;
return false;
}
@ -204,19 +209,19 @@ class ScheduleController extends Zend_Controller_Action
$showId = $this->_getParam('showId');
$instanceId = $this->_getParam('instanceId');
$log_vars = array();
$log_vars["url"] = $_SERVER['HTTP_HOST'];
$log_vars["action"] = "schedule/resize-show";
$log_vars["params"] = array();
$log_vars["params"]["instance id"] = $instanceId;
$log_vars["params"]["delta day"] = $deltaDay;
$log_vars["params"]["delta minute"] = $deltaMin;
$log_vars = [];
$log_vars['url'] = $_SERVER['HTTP_HOST'];
$log_vars['action'] = 'schedule/resize-show';
$log_vars['params'] = [];
$log_vars['params']['instance id'] = $instanceId;
$log_vars['params']['delta day'] = $deltaDay;
$log_vars['params']['delta minute'] = $deltaMin;
Logging::info($log_vars);
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$user = new Application_Model_User($userInfo->id);
if ($user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
if ($user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER])) {
try {
$show = new Application_Model_Show($showId);
} catch (Exception $e) {
@ -236,11 +241,11 @@ class ScheduleController extends Zend_Controller_Action
{
$instanceId = $this->_getParam('id');
$log_vars = array();
$log_vars["url"] = $_SERVER['HTTP_HOST'];
$log_vars["action"] = "schedule/delete-show-instance";
$log_vars["params"] = array();
$log_vars["params"]["instance id"] = $instanceId;
$log_vars = [];
$log_vars['url'] = $_SERVER['HTTP_HOST'];
$log_vars['action'] = 'schedule/delete-show-instance';
$log_vars['params'] = [];
$log_vars['params']['instance id'] = $instanceId;
Logging::info($log_vars);
$service_show = new Application_Service_ShowService();
@ -265,17 +270,18 @@ class ScheduleController extends Zend_Controller_Action
{
$instanceId = $this->_getParam('id');
$log_vars = array();
$log_vars["url"] = $_SERVER['HTTP_HOST'];
$log_vars["action"] = "schedule/clear-show";
$log_vars["params"] = array();
$log_vars["params"]["instance id"] = $instanceId;
$log_vars = [];
$log_vars['url'] = $_SERVER['HTTP_HOST'];
$log_vars['action'] = 'schedule/clear-show';
$log_vars['params'] = [];
$log_vars['params']['instance id'] = $instanceId;
Logging::info($log_vars);
$service_scheduler = new Application_Service_SchedulerService();
if (!$service_scheduler->emptyShowContent($instanceId)) {
$this->view->show_error = true;
return false;
}
}
@ -288,7 +294,7 @@ class ScheduleController extends Zend_Controller_Action
$front = Zend_Controller_Front::getInstance();
$scheduleController = new ScheduleController($front->getRequest(), $front->getResponse());
$scheduleController->getCurrentPlaylistAction();
echo(json_encode($scheduleController->view));
echo json_encode($scheduleController->view);
}
public function getCurrentPlaylistAction()
@ -297,49 +303,49 @@ class ScheduleController extends Zend_Controller_Action
$show = Application_Model_Show::getCurrentShow();
/* Convert all UTC times to localtime before sending back to user. */
$range["schedulerTime"] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range["schedulerTime"]);
// Convert all UTC times to localtime before sending back to user.
$range['schedulerTime'] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range['schedulerTime']);
if (isset($range["previous"])) {
$range["previous"]["starts"] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range["previous"]["starts"]);
$range["previous"]["ends"] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range["previous"]["ends"]);
if (isset($range['previous'])) {
$range['previous']['starts'] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range['previous']['starts']);
$range['previous']['ends'] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range['previous']['ends']);
}
if (isset($range["current"])) {
if (isset($range["current"]["metadata"])) {
$get_artwork = FileDataHelper::getArtworkData($range["current"]["metadata"]["artwork"], 256);
$range["current"]["metadata"]["artwork_data"] = $get_artwork;
if (isset($range['current'])) {
if (isset($range['current']['metadata'])) {
$get_artwork = FileDataHelper::getArtworkData($range['current']['metadata']['artwork'], 256);
$range['current']['metadata']['artwork_data'] = $get_artwork;
}
$range["current"]["starts"] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range["current"]["starts"]);
$range["current"]["ends"] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range["current"]["ends"]);
$range['current']['starts'] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range['current']['starts']);
$range['current']['ends'] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range['current']['ends']);
}
if (isset($range["next"])) {
$range["next"]["starts"] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range["next"]["starts"]);
$range["next"]["ends"] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range["next"]["ends"]);
if (isset($range['next'])) {
$range['next']['starts'] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range['next']['starts']);
$range['next']['ends'] = Application_Common_DateHelper::UTCStringToUserTimezoneString($range['next']['ends']);
}
Application_Common_DateHelper::convertTimestamps(
$range["currentShow"],
array("starts", "ends", "start_timestamp", "end_timestamp"),
"user"
$range['currentShow'],
['starts', 'ends', 'start_timestamp', 'end_timestamp'],
'user'
);
Application_Common_DateHelper::convertTimestamps(
$range["nextShow"],
array("starts", "ends", "start_timestamp", "end_timestamp"),
"user"
$range['nextShow'],
['starts', 'ends', 'start_timestamp', 'end_timestamp'],
'user'
);
//TODO: Add timezone and timezoneOffset back into the ApiController's results.
$range["timezone"] = Application_Common_DateHelper::getUserTimezoneAbbreviation();
$range["timezoneOffset"] = Application_Common_DateHelper::getUserTimezoneOffset();
$range['timezone'] = Application_Common_DateHelper::getUserTimezoneAbbreviation();
$range['timezoneOffset'] = Application_Common_DateHelper::getUserTimezoneOffset();
$source_status = array();
$switch_status = array();
$live_dj = Application_Model_Preference::GetSourceStatus("live_dj");
$master_dj = Application_Model_Preference::GetSourceStatus("master_dj");
$source_status = [];
$switch_status = [];
$live_dj = Application_Model_Preference::GetSourceStatus('live_dj');
$master_dj = Application_Model_Preference::GetSourceStatus('master_dj');
$scheduled_play_switch = Application_Model_Preference::GetSourceSwitchStatus("scheduled_play");
$live_dj_switch = Application_Model_Preference::GetSourceSwitchStatus("live_dj");
$master_dj_switch = Application_Model_Preference::GetSourceSwitchStatus("master_dj");
$scheduled_play_switch = Application_Model_Preference::GetSourceSwitchStatus('scheduled_play');
$live_dj_switch = Application_Model_Preference::GetSourceSwitchStatus('live_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
$source_status['live_dj_source'] = $live_dj;
@ -352,12 +358,13 @@ class ScheduleController extends Zend_Controller_Action
$this->view->switch_status = $switch_status;
$this->view->entries = $range;
$this->view->show_name = isset($show[0])?$show[0]["name"]:"";
$this->view->show_name = isset($show[0]) ? $show[0]['name'] : '';
}
public function showContentDialogAction()
{
$showInstanceId = $this->_getParam('id');
try {
$show = new Application_Model_ShowInstance($showInstanceId);
} catch (Exception $e) {
@ -380,14 +387,16 @@ class ScheduleController extends Zend_Controller_Action
//convert from UTC to user's timezone for display.
$displayTimeZone = new DateTimeZone(Application_Model_Preference::GetTimezone());
$originalDateTime = new DateTime($originalShowStart, new DateTimeZone("UTC"));
$originalDateTime = new DateTime($originalShowStart, new DateTimeZone('UTC'));
$originalDateTime->setTimezone($displayTimeZone);
$this->view->additionalShowInfo =
sprintf(_("Rebroadcast of show %s from %s at %s"),
sprintf(
_('Rebroadcast of show %s from %s at %s'),
$originalShowName,
$originalDateTime->format("l, F jS"),
$originalDateTime->format("G:i"));
$originalDateTime->format('l, F jS'),
$originalDateTime->format('G:i')
);
}
$this->view->showLength = $show->getShowLength();
$this->view->timeFilled = $show->getTimeScheduled();
@ -409,7 +418,7 @@ class ScheduleController extends Zend_Controller_Action
$service_showForm->delegateShowInstanceFormPopulation($forms);
$this->view->addNewShow = false;
$this->view->action = "edit-repeating-show-instance";
$this->view->action = 'edit-repeating-show-instance';
$this->view->newForm = $this->view->render('schedule/add-show-form.phtml');
}
@ -434,7 +443,7 @@ class ScheduleController extends Zend_Controller_Action
}
}
$this->view->action = "edit-show";
$this->view->action = 'edit-show';
$this->view->newForm = $this->view->render('schedule/add-show-form.phtml');
$this->view->entries = 5;
}
@ -451,26 +460,29 @@ class ScheduleController extends Zend_Controller_Action
}
}
public function editRepeatingShowInstanceAction(){
public function editRepeatingShowInstanceAction()
{
$js = $this->_getParam('data');
$data = array();
$data = [];
//need to convert from serialized jQuery array.
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');
$log_vars = array();
$log_vars["url"] = $_SERVER['HTTP_HOST'];
$log_vars["action"] = "schedule/edit-repeating-show-instance";
$log_vars["params"] = array();
$log_vars["params"]["form_data"] = $data;
$log_vars = [];
$log_vars['url'] = $_SERVER['HTTP_HOST'];
$log_vars['action'] = 'schedule/edit-repeating-show-instance';
$log_vars['params'] = [];
$log_vars['params']['form_data'] = $data;
Logging::info($log_vars);
$service_showForm = new Application_Service_ShowFormService(
$data["add_show_id"], $data["add_show_instance_id"]);
$data['add_show_id'],
$data['add_show_instance_id']
);
$service_show = new Application_Service_ShowService(null, $data);
$forms = $this->createShowFormAction();
@ -478,23 +490,28 @@ class ScheduleController extends Zend_Controller_Action
list($data, $validateStartDate, $validateStartTime, $originalShowStartDateTime) =
$service_showForm->preEditShowValidationCheck($data);
if ($service_showForm->validateShowForms($forms, $data, $validateStartDate,
$originalShowStartDateTime, true, $data["add_show_instance_id"])) {
if ($service_showForm->validateShowForms(
$forms,
$data,
$validateStartDate,
$originalShowStartDateTime,
true,
$data['add_show_instance_id']
)) {
$service_show->editRepeatingShowInstance($data);
$this->view->addNewShow = true;
$this->view->newForm = $this->view->render('schedule/add-show-form.phtml');
} else {
} else {
if (!$validateStartDate) {
$this->view->when->getElement('add_show_start_date')->setOptions(array('disabled' => true));
$this->view->when->getElement('add_show_start_date')->setOptions(['disabled' => true]);
}
if (!$validateStartTime) {
$this->view->when->getElement('add_show_start_time')->setOptions(array('disabled' => true));
$this->view->when->getElement('add_show_start_time')->setOptions(['disabled' => true]);
}
$this->view->rr->getElement('add_show_record')->setOptions(array('disabled' => true));
$this->view->rr->getElement('add_show_record')->setOptions(['disabled' => true]);
$this->view->addNewShow = false;
$this->view->action = "edit-repeating-show-instance";
$this->view->action = 'edit-repeating-show-instance';
$this->view->form = $this->view->render('schedule/add-show-form.phtml');
}
}
@ -502,30 +519,31 @@ class ScheduleController extends Zend_Controller_Action
public function editShowAction()
{
$js = $this->_getParam('data');
$data = array();
$data = [];
//need to convert from serialized jQuery array.
foreach ($js as $j) {
$data[$j["name"]] = $j["value"];
$data[$j['name']] = $j['value'];
}
$service_showForm = new Application_Service_ShowFormService(
$data["add_show_id"]);
$data['add_show_id']
);
$service_show = new Application_Service_ShowService(null, $data, true);
//TODO: move this to js
$data['add_show_hosts'] = $this->_getParam('hosts');
$data['add_show_day_check'] = $this->_getParam('days');
$data['add_show_hosts'] = $this->_getParam('hosts');
$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;
}
$log_vars = array();
$log_vars["url"] = $_SERVER['HTTP_HOST'];
$log_vars["action"] = "schedule/edit-show";
$log_vars["params"] = array();
$log_vars["params"]["form_data"] = $data;
$log_vars = [];
$log_vars['url'] = $_SERVER['HTTP_HOST'];
$log_vars['action'] = 'schedule/edit-show';
$log_vars['params'] = [];
$log_vars['params']['form_data'] = $data;
Logging::info($log_vars);
$forms = $this->createShowFormAction();
@ -533,24 +551,30 @@ class ScheduleController extends Zend_Controller_Action
list($data, $validateStartDate, $validateStartTime, $originalShowStartDateTime) =
$service_showForm->preEditShowValidationCheck($data);
if ($service_showForm->validateShowForms($forms, $data, $validateStartDate,
$originalShowStartDateTime, true, $data["add_show_instance_id"])) {
if ($service_showForm->validateShowForms(
$forms,
$data,
$validateStartDate,
$originalShowStartDateTime,
true,
$data['add_show_instance_id']
)) {
// Get the show ID from the show service to pass as a parameter to the RESTful ShowImageController
$this->view->showId = $service_show->addUpdateShow($data);
$this->view->addNewShow = true;
$this->view->addNewShow = true;
$this->view->newForm = $this->view->render('schedule/add-show-form.phtml');
} else {
if (!$validateStartDate) {
$this->view->when->getElement('add_show_start_date')->setOptions(array('disabled' => true));
$this->view->when->getElement('add_show_start_date')->setOptions(['disabled' => true]);
}
if (!$validateStartTime) {
$this->view->when->getElement('add_show_start_time')->setOptions(array('disabled' => true));
$this->view->when->getElement('add_show_start_time')->setOptions(['disabled' => true]);
}
//$this->view->rr->getElement('add_show_record')->setOptions(array('disabled' => true));
$this->view->addNewShow = false;
$this->view->action = "edit-show";
$this->view->action = 'edit-show';
$this->view->form = $this->view->render('schedule/add-show-form.phtml');
}
}
@ -560,63 +584,61 @@ class ScheduleController extends Zend_Controller_Action
$service_showForm = new Application_Service_ShowFormService(null);
$js = $this->_getParam('data');
$data = array();
$data = [];
//need to convert from serialized jQuery array.
foreach ($js as $j) {
$data[$j["name"]] = $j["value"];
$data[$j['name']] = $j['value'];
}
$service_show = new Application_Service_ShowService(null, $data);
// TODO: move this to js
$data['add_show_hosts'] = $this->_getParam('hosts');
$data['add_show_day_check'] = $this->_getParam('days');
$data['add_show_hosts'] = $this->_getParam('hosts');
$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;
}
$log_vars = array();
$log_vars["url"] = $_SERVER['HTTP_HOST'];
$log_vars["action"] = "schedule/add-show";
$log_vars["params"] = array();
$log_vars["params"]["form_data"] = $data;
$log_vars = [];
$log_vars['url'] = $_SERVER['HTTP_HOST'];
$log_vars['action'] = 'schedule/add-show';
$log_vars['params'] = [];
$log_vars['params']['form_data'] = $data;
Logging::info($log_vars);
$forms = $this->createShowFormAction();
$this->view->addNewShow = true;
if ($data['add_show_start_now'] == "now") {
if ($data['add_show_start_now'] == 'now') {
//have to use the timezone the user has entered in the form to check past/present
$showTimezone = new DateTimeZone($data["add_show_timezone"]);
$nowDateTime = new DateTime("now", $showTimezone);
$showTimezone = new DateTimeZone($data['add_show_timezone']);
$nowDateTime = new DateTime('now', $showTimezone);
//$showStartDateTime = new DateTime($start_time, $showTimezone);
//$showEndDateTime = new DateTime($end_time, $showTimezone);
$data['add_show_start_time'] = $nowDateTime->format("H:i");
$data['add_show_start_date'] = $nowDateTime->format("Y-m-d");
$data['add_show_start_time'] = $nowDateTime->format('H:i');
$data['add_show_start_date'] = $nowDateTime->format('Y-m-d');
}
if ($service_showForm->validateShowForms($forms, $data)) {
// Get the show ID from the show service to pass as a parameter to the RESTful ShowImageController
$this->view->showId = $service_show->addUpdateShow($data);
// Get the show ID from the show service to pass as a parameter to the RESTful ShowImageController
$this->view->showId = $service_show->addUpdateShow($data);
//send new show forms to the user
$this->createShowFormAction(true);
$this->view->newForm = $this->view->render('schedule/add-show-form.phtml');
Logging::debug("Show creation succeeded");
Logging::debug('Show creation succeeded');
} else {
$this->view->form = $this->view->render('schedule/add-show-form.phtml');
Logging::debug("Show creation failed");
$this->view->form = $this->view->render('schedule/add-show-form.phtml');
Logging::debug('Show creation failed');
}
}
public function createShowFormAction($populateDefaults=false)
public function createShowFormAction($populateDefaults = false)
{
$service_showForm = new Application_Service_ShowFormService();
@ -625,19 +647,22 @@ class ScheduleController extends Zend_Controller_Action
// populate forms with default values
if ($populateDefaults) {
$service_showForm->populateNewShowForms(
$forms["what"], $forms["when"], $forms["repeats"]);
$forms['what'],
$forms['when'],
$forms['repeats']
);
}
$this->view->what = $forms["what"];
$this->view->autoplaylist = $forms["autoplaylist"];
$this->view->when = $forms["when"];
$this->view->repeats = $forms["repeats"];
$this->view->live = $forms["live"];
$this->view->rr = $forms["record"];
$this->view->absoluteRebroadcast = $forms["abs_rebroadcast"];
$this->view->rebroadcast = $forms["rebroadcast"];
$this->view->who = $forms["who"];
$this->view->style = $forms["style"];
$this->view->what = $forms['what'];
$this->view->autoplaylist = $forms['autoplaylist'];
$this->view->when = $forms['when'];
$this->view->repeats = $forms['repeats'];
$this->view->live = $forms['live'];
$this->view->rr = $forms['record'];
$this->view->absoluteRebroadcast = $forms['abs_rebroadcast'];
$this->view->rebroadcast = $forms['rebroadcast'];
$this->view->who = $forms['who'];
$this->view->style = $forms['style'];
return $forms;
}
@ -646,11 +671,11 @@ class ScheduleController extends Zend_Controller_Action
{
$instanceId = $this->_getParam('id');
$log_vars = array();
$log_vars["url"] = $_SERVER['HTTP_HOST'];
$log_vars["action"] = "schedule/delete-show";
$log_vars["params"] = array();
$log_vars["params"]["instance id"] = $instanceId;
$log_vars = [];
$log_vars['url'] = $_SERVER['HTTP_HOST'];
$log_vars['action'] = 'schedule/delete-show';
$log_vars['params'] = [];
$log_vars['params']['instance id'] = $instanceId;
Logging::info($log_vars);
$service_show = new Application_Service_ShowService();
@ -664,16 +689,16 @@ class ScheduleController extends Zend_Controller_Action
public function cancelCurrentShowAction()
{
$log_vars = array();
$log_vars["url"] = $_SERVER['HTTP_HOST'];
$log_vars["action"] = "schedule/cancel-current-show";
$log_vars["params"] = array();
$log_vars["params"]["instance id"] = $this->_getParam('id');
$log_vars = [];
$log_vars['url'] = $_SERVER['HTTP_HOST'];
$log_vars['action'] = 'schedule/cancel-current-show';
$log_vars['params'] = [];
$log_vars['params']['instance id'] = $this->_getParam('id');
Logging::info($log_vars);
$user = Application_Model_User::getCurrentUser();
if ($user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
if ($user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER])) {
$id = $this->_getParam('id');
try {
@ -681,8 +706,8 @@ class ScheduleController extends Zend_Controller_Action
$scheduler->cancelShow($id);
Application_Model_StoredFile::updatePastFilesIsScheduled();
// send kick out source stream signal to pypo
$data = array("sourcename"=>"live_dj");
Application_Model_RabbitMq::SendMessageToPypo("disconnect_source", $data);
$data = ['sourcename' => 'live_dj'];
Application_Model_RabbitMq::SendMessageToPypo('disconnect_source', $data);
} catch (Exception $e) {
$this->view->error = $e->getMessage();
Logging::info($e->getMessage());
@ -705,10 +730,10 @@ class ScheduleController extends Zend_Controller_Action
$file = Application_Model_StoredFile::RecallById($file_id);
$baseUrl = $this->getRequest()->getBaseUrl();
$url = $file->getRelativeFileUrl($baseUrl).'download/true';
$menu = array();
$menu[] = array('action' => array('type' => 'gourl', 'url' => $url),
'title' => _('Download'));
$url = $file->getRelativeFileUrl($baseUrl) . 'download/true';
$menu = [];
$menu[] = ['action' => ['type' => 'gourl', 'url' => $url],
'title' => _('Download'), ];
//returns format jjmenu is looking for.
$this->_helper->json->sendJson($menu);
@ -723,7 +748,7 @@ class ScheduleController extends Zend_Controller_Action
Application_Model_Preference::SetCalendarTimeScale($this->_getParam('timeScale'));
}
/**
/**
* Sets the user specific preference for which time interval to use in Calendar.
* This is only being used by schedule.js at the moment.
*/
@ -734,14 +759,15 @@ class ScheduleController extends Zend_Controller_Action
public function calculateDurationAction()
{
$start = $this->_getParam('startTime');
$end = $this->_getParam('endTime');
$timezone = $this->_getParam('timezone');
$start = $this->_getParam('startTime');
$end = $this->_getParam('endTime');
$timezone = $this->_getParam('timezone');
$service_showForm = new Application_Service_ShowFormService();
$result = $service_showForm->calculateDuration($start, $end, $timezone);
echo Zend_Json::encode($result);
exit();
}
@ -752,22 +778,29 @@ class ScheduleController extends Zend_Controller_Action
$scheduleService = new Application_Service_SchedulerService();
$redrawLibTable = $scheduleService->updateFutureIsScheduled($schedId, false);
$this->_helper->json->sendJson(array("redrawLibTable" => $redrawLibTable));
$this->_helper->json->sendJson(['redrawLibTable' => $redrawLibTable]);
}
public function localizeStartEndTimeAction()
{
$newTimezone = $this->_getParam('newTimezone');
$oldTimezone = $this->_getParam('oldTimezone');
$localTime = array();
$localTime = [];
$localTime["start"] = Application_Service_ShowFormService::localizeDateTime(
$this->_getParam('startDate'), $this->_getParam('startTime'), $newTimezone, $oldTimezone);
$localTime['start'] = Application_Service_ShowFormService::localizeDateTime(
$this->_getParam('startDate'),
$this->_getParam('startTime'),
$newTimezone,
$oldTimezone
);
$localTime["end"] = Application_Service_ShowFormService::localizeDateTime(
$this->_getParam('endDate'), $this->_getParam('endTime'), $newTimezone, $oldTimezone);
$localTime['end'] = Application_Service_ShowFormService::localizeDateTime(
$this->_getParam('endDate'),
$this->_getParam('endTime'),
$newTimezone,
$oldTimezone
);
$this->_helper->json->sendJson($localTime);
}
}

View File

@ -1,7 +1,6 @@
<?php
/** This class displays the Language and Timezone setup popup dialog that you see on first run. */
class SetupController extends Zend_Controller_Action
{
public function init()
@ -19,18 +18,17 @@ class SetupController extends Zend_Controller_Action
$form = new Application_Form_SetupLanguageTimezone();
if ($request->isPost()) {
$formData = $request->getPost();
if ($form->isValid($formData)) {
$userService = new Application_Service_UserService();
$currentUser = $userService->getCurrentUser();
$currentUserId = $currentUser->getDbId();
Application_Model_Preference::SetUserTimezone($formData["setup_timezone"], $currentUserId);
Application_Model_Preference::SetDefaultTimezone($formData["setup_timezone"]);
Application_Model_Preference::SetUserLocale($formData["setup_language"], $currentUserId);
Application_Model_Preference::SetDefaultLocale($formData["setup_language"]);
Application_Model_Preference::SetUserTimezone($formData['setup_timezone'], $currentUserId);
Application_Model_Preference::SetDefaultTimezone($formData['setup_timezone']);
Application_Model_Preference::SetUserLocale($formData['setup_language'], $currentUserId);
Application_Model_Preference::SetDefaultLocale($formData['setup_language']);
Application_Model_Preference::setLangTimezoneSetupComplete(true);
@ -39,5 +37,4 @@ class SetupController extends Zend_Controller_Action
}
$this->_redirect('/showbuilder');
}
}
}

View File

@ -2,18 +2,18 @@
class ShowbuilderController extends Zend_Controller_Action
{
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('schedule-move', 'json')
->addActionContext('schedule-add', 'json')
->addActionContext('schedule-remove', 'json')
->addActionContext('builder-dialog', 'json')
->addActionContext('check-builder-feed', 'json')
->addActionContext('builder-feed', 'json')
->addActionContext('context-menu', 'json')
->initContext();
->addActionContext('schedule-add', 'json')
->addActionContext('schedule-remove', 'json')
->addActionContext('builder-dialog', 'json')
->addActionContext('check-builder-feed', 'json')
->addActionContext('builder-feed', 'json')
->addActionContext('context-menu', 'json')
->initContext()
;
}
public function indexAction()
@ -24,46 +24,46 @@ class ShowbuilderController extends Zend_Controller_Action
//$this->_helper->layout->setLayout("showbuilder");
$this->view->headScript()->appendScript("localStorage.setItem( 'user-type', '$userType' );");
$this->view->headScript()->appendScript("localStorage.setItem( 'user-type', '{$userType}' );");
$this->view->headLink()->appendStylesheet($baseUrl . 'css/redmond/jquery-ui-1.8.8.custom.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/contextmenu/jquery.contextMenu.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/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->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/dataTables.colReorder.min.css?'.$CC_CONFIG['airtime_version']);
$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_showbuilder.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/dataTables.colReorder.min.css?' . $CC_CONFIG['airtime_version']);
$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_showbuilder.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$headScript = $this->view->headScript();
AirtimeTableView::injectTableJavaScriptDependencies($headScript, $baseUrl, $CC_CONFIG['airtime_version']);
// PLUPLOAD
$this->view->headScript()->appendFile($baseUrl.'js/libs/dropzone.min.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/libs/dropzone.min.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/showbuilder/tabs.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/airtime/showbuilder/builder.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/airtime/showbuilder/main_builder.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/showbuilder/tabs.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/airtime/showbuilder/builder.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/airtime/showbuilder/main_builder.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
// MEDIA BUILDER
$this->view->headScript()->appendFile($baseUrl.'js/libs/dayjs.min.js','text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/libs/utc.min.js','text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/libs/timezone.min.js','text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/airtime/library/spl.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/airtime/library/podcast.js?'.$CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl.'js/airtime/library/publish.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']);
$this->view->headScript()->appendFile($baseUrl . 'js/libs/dayjs.min.js', 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/libs/utc.min.js', 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/libs/timezone.min.js', 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/airtime/library/spl.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/airtime/library/podcast.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/airtime/library/publish.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']);
$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/dashboard.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/dashboard.css?' . $CC_CONFIG['airtime_version']);
$csrf_namespace = new Zend_Session_Namespace('csrf_namespace');
$csrf_element = new Zend_Form_Element_Hidden('csrf');
@ -72,27 +72,27 @@ class ShowbuilderController extends Zend_Controller_Action
$request = $this->getRequest();
//populate date range form for show builder.
$now = time();
$from = $request->getParam("from", $now);
$to = $request->getParam("to", $now + (3*60*60));
$now = time();
$from = $request->getParam('from', $now);
$to = $request->getParam('to', $now + (3 * 60 * 60));
$utcTimezone = new DateTimeZone("UTC");
$utcTimezone = new DateTimeZone('UTC');
$displayTimeZone = new DateTimeZone(Application_Model_Preference::GetTimezone());
$start = DateTime::createFromFormat("U", $from, $utcTimezone);
$start = DateTime::createFromFormat('U', $from, $utcTimezone);
$start->setTimezone($displayTimeZone);
$end = DateTime::createFromFormat("U", $to, $utcTimezone);
$end = DateTime::createFromFormat('U', $to, $utcTimezone);
$end->setTimezone($displayTimeZone);
$this->checkAndShowSetupPopup($request);
$form = new Application_Form_ShowBuilder();
$form->populate(array(
'sb_date_start' => $start->format("Y-m-d"),
'sb_time_start' => $start->format("H:i"),
'sb_date_end' => $end->format("Y-m-d"),
'sb_time_end' => $end->format("H:i")
));
$form->populate([
'sb_date_start' => $start->format('Y-m-d'),
'sb_time_start' => $start->format('H:i'),
'sb_date_end' => $end->format('Y-m-d'),
'sb_time_end' => $end->format('H:i'),
]);
$this->view->sb_form = $form;
}
@ -106,15 +106,15 @@ class ShowbuilderController extends Zend_Controller_Action
$previousPage = strtolower($request->getHeader('Referer'));
$userService = new Application_Service_UserService();
$currentUser = $userService->getCurrentUser();
$previousPageWasLoginScreen = (strpos($previousPage, 'login') !== false) ||
(strpos($previousPage, SAAS_LOGIN_REFERRER) !== false);
$previousPageWasLoginScreen = (strpos($previousPage, 'login') !== false)
|| (strpos($previousPage, SAAS_LOGIN_REFERRER) !== false);
// If current user is Super Admin, and they came from the login page,
// and they have not seen the setup popup before
if ($currentUser->isSuperAdmin() && $previousPageWasLoginScreen && empty($setupComplete)) {
$lang_tz_popup_form = new Application_Form_SetupLanguageTimezone();
$this->view->lang_tz_popup_form = $lang_tz_popup_form;
$this->view->headScript()->appendFile($baseUrl.'js/airtime/nowplaying/lang-timezone-setup.js?'.$CC_CONFIG['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/airtime/nowplaying/lang-timezone-setup.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
}
}
@ -126,22 +126,21 @@ class ShowbuilderController extends Zend_Controller_Action
$now = floatval(microtime(true));
$request = $this->getRequest();
$menu = array();
$menu = [];
$user = Application_Model_User::getCurrentUser();
$item = CcScheduleQuery::create()->findPK($id);
$instance = $item->getCcShowInstances();
$menu["preview"] = array("name"=> _("Preview"), "icon" => "play");
$menu['preview'] = ['name' => _('Preview'), 'icon' => 'play'];
//select the cursor
$menu["selCurs"] = array("name"=> _("Select cursor"),"icon" => "select-cursor");
$menu["delCurs"] = array("name"=> _("Remove cursor"),"icon" => "select-cursor");
if ($now < floatval($item->getDbEnds("U.u")) && $user->canSchedule($instance->getDbShowId())) {
$menu['selCurs'] = ['name' => _('Select cursor'), 'icon' => 'select-cursor'];
$menu['delCurs'] = ['name' => _('Remove cursor'), 'icon' => 'select-cursor'];
if ($now < floatval($item->getDbEnds('U.u')) && $user->canSchedule($instance->getDbShowId())) {
//remove/truncate the item from the schedule
$menu["del"] = array("name"=> _("Delete"), "icon" => "delete", "url" => $baseUrl."showbuilder/schedule-remove");
$menu['del'] = ['name' => _('Delete'), 'icon' => 'delete', 'url' => $baseUrl . 'showbuilder/schedule-remove'];
}
$this->view->items = $menu;
@ -150,12 +149,12 @@ class ShowbuilderController extends Zend_Controller_Action
public function builderDialogAction()
{
$request = $this->getRequest();
$id = $request->getParam("id");
$id = $request->getParam('id');
$instance = CcShowInstancesQuery::create()->findPK($id);
if (is_null($instance)) {
$this->view->error = _("show does not exist");
$this->view->error = _('show does not exist');
return;
}
@ -176,12 +175,12 @@ class ShowbuilderController extends Zend_Controller_Action
$this->view->end = $end_time;
$form = new Application_Form_ShowBuilder();
$form->populate(array(
'sb_date_start' => $start->format("Y-m-d"),
'sb_time_start' => $start->format("H:i"),
'sb_date_end' => $end->format("Y-m-d"),
'sb_time_end' => $end->format("H:i")
));
$form->populate([
'sb_date_start' => $start->format('Y-m-d'),
'sb_time_start' => $start->format('H:i'),
'sb_date_end' => $end->format('Y-m-d'),
'sb_time_end' => $end->format('H:i'),
]);
$this->view->sb_form = $form;
@ -191,41 +190,43 @@ class ShowbuilderController extends Zend_Controller_Action
public function checkBuilderFeedAction()
{
$request = $this->getRequest();
$show_filter = intval($request->getParam("showFilter", 0));
$my_shows = intval($request->getParam("myShows", 0));
$timestamp = intval($request->getParam("timestamp", -1));
$instances = $request->getParam("instances", array());
$show_filter = intval($request->getParam('showFilter', 0));
$my_shows = intval($request->getParam('myShows', 0));
$timestamp = intval($request->getParam('timestamp', -1));
$instances = $request->getParam('instances', []);
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($request);
$opts = array("myShows" => $my_shows, "showFilter" => $show_filter);
$opts = ['myShows' => $my_shows, 'showFilter' => $show_filter];
$showBuilder = new Application_Model_ShowBuilder($startsDT, $endsDT, $opts);
//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.
$this->view->update = $showBuilder->hasBeenUpdatedSince(
$timestamp, $instances);
$timestamp,
$instances
);
}
public function builderFeedAction()
{
$current_time = time();
$current_time = time();
$request = $this->getRequest();
$show_filter = intval($request->getParam("showFilter", 0));
$show_instance_filter = intval($request->getParam("showInstanceFilter", 0));
$my_shows = intval($request->getParam("myShows", 0));
$show_filter = intval($request->getParam('showFilter', 0));
$show_instance_filter = intval($request->getParam('showInstanceFilter', 0));
$my_shows = intval($request->getParam('myShows', 0));
list($startsDT, $endsDT) = Application_Common_HTTPHelper::getStartEndFromRequest($request);
$opts = array("myShows" => $my_shows,
"showFilter" => $show_filter,
"showInstanceFilter" => $show_instance_filter);
$opts = ['myShows' => $my_shows,
'showFilter' => $show_filter,
'showInstanceFilter' => $show_instance_filter, ];
$showBuilder = new Application_Model_ShowBuilder($startsDT, $endsDT, $opts);
$data = $showBuilder->getItems();
$this->view->schedule = $data["schedule"];
$this->view->instances = $data["showInstances"];
$this->view->schedule = $data['schedule'];
$this->view->instances = $data['showInstances'];
$this->view->timestamp = $current_time;
}
@ -233,15 +234,15 @@ class ShowbuilderController extends Zend_Controller_Action
{
$request = $this->getRequest();
$mediaItems = $request->getParam("mediaIds", array());
$scheduledItems = $request->getParam("schedIds", array());
$mediaItems = $request->getParam('mediaIds', []);
$scheduledItems = $request->getParam('schedIds', []);
$log_vars = array();
$log_vars["url"] = $_SERVER['HTTP_HOST'];
$log_vars["action"] = "showbuilder/schedule-add";
$log_vars["params"] = array();
$log_vars["params"]["media_items"] = $mediaItems;
$log_vars["params"]["scheduled_items"] = $scheduledItems;
$log_vars = [];
$log_vars['url'] = $_SERVER['HTTP_HOST'];
$log_vars['action'] = 'showbuilder/schedule-add';
$log_vars['params'] = [];
$log_vars['params']['media_items'] = $mediaItems;
$log_vars['params']['scheduled_items'] = $scheduledItems;
Logging::info($log_vars);
try {
@ -259,13 +260,13 @@ class ShowbuilderController extends Zend_Controller_Action
public function scheduleRemoveAction()
{
$request = $this->getRequest();
$items = $request->getParam("items", array());
$items = $request->getParam('items', []);
$log_vars = array();
$log_vars["url"] = $_SERVER['HTTP_HOST'];
$log_vars["action"] = "showbuilder/schedule-remove";
$log_vars["params"] = array();
$log_vars["params"]["removed_items"] = $items;
$log_vars = [];
$log_vars['url'] = $_SERVER['HTTP_HOST'];
$log_vars['action'] = 'showbuilder/schedule-remove';
$log_vars['params'] = [];
$log_vars['params']['removed_items'] = $items;
Logging::info($log_vars);
try {
@ -283,8 +284,8 @@ class ShowbuilderController extends Zend_Controller_Action
public function scheduleMoveAction()
{
$request = $this->getRequest();
$selectedItems = $request->getParam("selectedItem");
$afterItem = $request->getParam("afterItem");
$selectedItems = $request->getParam('selectedItem');
$afterItem = $request->getParam('afterItem');
/*
$log_vars = array();
@ -310,7 +311,6 @@ class ShowbuilderController extends Zend_Controller_Action
public function scheduleReorderAction()
{
throw new Exception("this controller is/was a no-op please fix your code");
throw new Exception('this controller is/was a no-op please fix your code');
}
}

View File

@ -1,12 +1,14 @@
<?php
class SystemstatusController extends Zend_Controller_Action
{
private $version;
public function init()
{
$config = Config::getConfig();
$baseUrl = Application_Common_OsPath::getBaseDir();
$this->view->headScript()->appendFile($baseUrl.'js/airtime/status/status.js?'.$config['airtime_version'],'text/javascript');
$this->view->headScript()->appendFile($baseUrl . 'js/airtime/status/status.js?' . $config['airtime_version'], 'text/javascript');
$this->version = $config['airtime_version'];
}
@ -15,7 +17,7 @@ class SystemstatusController extends Zend_Controller_Action
Zend_Layout::getMvcInstance()->assign('parent_page', 'Settings');
$partitions = Application_Model_Systemstatus::GetDiskInfo();
$this->view->status = new StdClass;
$this->view->status = new StdClass();
$this->view->status->partitions = $partitions;
$this->view->version = $this->version;
}

View File

@ -1,10 +1,10 @@
<?php
/**
* Class ThirdPartyController abstract superclass for third-party service authorization
* Class ThirdPartyController abstract superclass for third-party service authorization.
*/
abstract class ThirdPartyController extends Zend_Controller_Action {
abstract class ThirdPartyController extends Zend_Controller_Action
{
/**
* @var string base url and port for redirection
*/
@ -16,15 +16,13 @@ abstract class ThirdPartyController extends Zend_Controller_Action {
protected $_service;
/**
* Disable controller rendering and initialize
*
* @return void
* Disable controller rendering and initialize.
*/
public function init() {
public function init()
{
$this->_baseUrl = Application_Common_HTTPHelper::getStationUrl();
$this->view->layout()->disableLayout(); // Don't inject the standard Now Playing header.
$this->_helper->viewRenderer->setNoRender(true); // Don't use (phtml) templates
}
}
}

View File

@ -2,14 +2,14 @@
class TracktypeController extends Zend_Controller_Action
{
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('get-tracktype-data-table-info', 'json')
->addActionContext('get-tracktype-data', 'json')
->addActionContext('remove-tracktype', 'json')
->initContext();
->addActionContext('get-tracktype-data', 'json')
->addActionContext('remove-tracktype', 'json')
->initContext()
;
}
public function addTracktypeAction()
@ -25,57 +25,58 @@ class TracktypeController extends Zend_Controller_Action
$baseUrl = Application_Common_OsPath::getBaseDir();
$js_files = array(
$js_files = [
'js/datatables/js/jquery.dataTables.js?',
'js/datatables/plugin/dataTables.pluginAPI.js?',
'js/airtime/tracktype/tracktype.js?'
);
'js/airtime/tracktype/tracktype.js?',
];
foreach ($js_files as $js) {
$this->view->headScript()->appendFile(
$baseUrl.$js.$CC_CONFIG['airtime_version'],'text/javascript');
$baseUrl . $js . $CC_CONFIG['airtime_version'],
'text/javascript'
);
}
$this->view->headLink()->appendStylesheet($baseUrl.'css/tracktypes.css?'.$CC_CONFIG['airtime_version']);
$this->view->headLink()->appendStylesheet($baseUrl . 'css/tracktypes.css?' . $CC_CONFIG['airtime_version']);
$form = new Application_Form_AddTracktype();
$this->view->successMessage = "";
$this->view->successMessage = '';
if ($request->isPost()) {
$params = $request->getPost();
$postData = explode('&', $params['data']);
$formData = array();
foreach($postData as $k=>$v) {
$formData = [];
foreach ($postData as $k => $v) {
$v = explode('=', $v);
$formData[$v[0]] = urldecode($v[1]);
}
if ($form->validateCode($formData)) {
$tracktype = new Application_Model_Tracktype($formData['tracktype_id']);
if (empty($formData['tracktype_id'])) {
$tracktype->setCode($formData['code']);
}
$tracktype->setTypeName($formData['type_name']);
$tracktype->setDescription($formData['description']);
$tracktype->setVisibility($formData['visibility']);
$tracktype->save();
if ($form->validateCode($formData)) {
$tracktype = new Application_Model_Tracktype($formData['tracktype_id']);
if (empty($formData['tracktype_id'])) {
$tracktype->setCode($formData['code']);
}
$tracktype->setTypeName($formData['type_name']);
$tracktype->setDescription($formData['description']);
$tracktype->setVisibility($formData['visibility']);
$tracktype->save();
$form->reset();
$this->view->form = $form;
$form->reset();
$this->view->form = $form;
if (strlen($formData['tracktype_id']) == 0) {
$this->view->successMessage = "<div class='success'>"._("Track Type added successfully!")."</div>";
} else {
$this->view->successMessage = "<div class='success'>"._("Track Type updated successfully!")."</div>";
}
$this->_helper->json->sendJson(array("valid"=>"true", "html"=>$this->view->render('tracktype/add-tracktype.phtml')));
if (strlen($formData['tracktype_id']) == 0) {
$this->view->successMessage = "<div class='success'>" . _('Track Type added successfully!') . '</div>';
} else {
$this->view->form = $form;
$this->_helper->json->sendJson(array("valid"=>"false", "html"=>$this->view->render('tracktype/add-tracktype.phtml')));
$this->view->successMessage = "<div class='success'>" . _('Track Type updated successfully!') . '</div>';
}
$this->_helper->json->sendJson(['valid' => 'true', 'html' => $this->view->render('tracktype/add-tracktype.phtml')]);
} else {
$this->view->form = $form;
$this->_helper->json->sendJson(['valid' => 'false', 'html' => $this->view->render('tracktype/add-tracktype.phtml')]);
}
}
$this->view->form = $form;
@ -102,8 +103,7 @@ class TracktypeController extends Zend_Controller_Action
$tracktype = new Application_Model_Tracktype($delId);
# Delete the track type
// Delete the track type
$this->view->entries = $tracktype->delete();
}
}

View File

@ -6,7 +6,7 @@ class UpgradeController extends Zend_Controller_Action
{
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
if (!RestAuth::verifyAuth(true, false, $this)) {
return;
}
@ -16,23 +16,25 @@ class UpgradeController extends Zend_Controller_Action
if (!$didWePerformAnUpgrade) {
$this->getResponse()
->setHttpResponseCode(200)
->appendBody("No upgrade was performed. The current schema version is " . Application_Model_Preference::GetSchemaVersion() . ".<br>");
->setHttpResponseCode(200)
->appendBody('No upgrade was performed. The current schema version is ' . Application_Model_Preference::GetSchemaVersion() . '.<br>')
;
} else {
$this->getResponse()
->setHttpResponseCode(200)
->appendBody("Upgrade to Airtime schema version " . Application_Model_Preference::GetSchemaVersion() . " OK<br>");
->setHttpResponseCode(200)
->appendBody('Upgrade to Airtime schema version ' . Application_Model_Preference::GetSchemaVersion() . ' OK<br>')
;
}
}
catch (Exception $e)
{
} catch (Exception $e) {
$this->getResponse()
->setHttpResponseCode(400)
->appendBody($e->getMessage());
->setHttpResponseCode(400)
->appendBody($e->getMessage())
;
}
}
public function downgradeAction() {
public function downgradeAction()
{
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
@ -41,7 +43,7 @@ class UpgradeController extends Zend_Controller_Action
}
$request = $this->getRequest();
$toVersion = $request->getParam("version");
$toVersion = $request->getParam('version');
try {
$downgradePerformed = UpgradeManager::doDowngrade($toVersion);
@ -49,17 +51,19 @@ class UpgradeController extends Zend_Controller_Action
if (!$downgradePerformed) {
$this->getResponse()
->setHttpResponseCode(200)
->appendBody("No downgrade was performed. The current schema version is " . Application_Model_Preference::GetSchemaVersion() . ".<br>");
->appendBody('No downgrade was performed. The current schema version is ' . Application_Model_Preference::GetSchemaVersion() . '.<br>')
;
} else {
$this->getResponse()
->setHttpResponseCode(200)
->appendBody("Downgrade to Airtime schema version " . Application_Model_Preference::GetSchemaVersion() . " OK<br>");
->appendBody('Downgrade to Airtime schema version ' . Application_Model_Preference::GetSchemaVersion() . ' OK<br>')
;
}
} catch (Exception $e) {
$this->getResponse()
->setHttpResponseCode(400)
->appendBody($e->getMessage());
->appendBody($e->getMessage())
;
}
}
}

View File

@ -2,16 +2,16 @@
class UserController extends Zend_Controller_Action
{
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('get-hosts', 'json')
->addActionContext('get-user-data-table-info', 'json')
->addActionContext('get-user-data', 'json')
->addActionContext('remove-user', 'json')
->addActionContext('edit-user', 'json')
->initContext();
->addActionContext('get-user-data-table-info', 'json')
->addActionContext('get-user-data', 'json')
->addActionContext('remove-user', 'json')
->addActionContext('edit-user', 'json')
->initContext()
;
}
public function addUserAction()
@ -27,34 +27,35 @@ class UserController extends Zend_Controller_Action
$baseUrl = Application_Common_OsPath::getBaseDir();
$js_files = array(
$js_files = [
'js/datatables/js/jquery.dataTables.js?',
'js/datatables/plugin/dataTables.pluginAPI.js?',
'js/airtime/user/user.js?'
);
'js/airtime/user/user.js?',
];
foreach ($js_files as $js) {
$this->view->headScript()->appendFile(
$baseUrl.$js.$CC_CONFIG['airtime_version'],'text/javascript');
$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();
$this->view->successMessage = "";
$this->view->successMessage = '';
if ($request->isPost()) {
$params = $request->getPost();
$postData = explode('&', $params['data']);
$formData = array();
foreach($postData as $k=>$v) {
$formData = [];
foreach ($postData as $k => $v) {
$v = explode('=', $v);
$formData[$v[0]] = urldecode($v[1]);
}
if ($form->isValid($formData)) {
if ($form->validateLogin($formData)) {
$user = new Application_Model_User($formData['user_id']);
if (empty($formData['user_id'])) {
@ -65,7 +66,7 @@ class UserController extends Zend_Controller_Action
// 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") {
if ($formData['password'] != 'xxxxxx') {
$user->setPassword($formData['password']);
}
if (array_key_exists('type', $formData)) {
@ -83,19 +84,19 @@ class UserController extends Zend_Controller_Action
$this->view->form = $form;
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 {
$this->view->successMessage = "<div class='success'>"._("User updated successfully!")."</div>";
$this->view->successMessage = "<div class='success'>" . _('User updated successfully!') . '</div>';
}
$this->_helper->json->sendJson(array("valid"=>"true", "html"=>$this->view->render('user/add-user.phtml')));
$this->_helper->json->sendJson(['valid' => 'true', 'html' => $this->view->render('user/add-user.phtml')]);
} else {
$this->view->form = $form;
$this->_helper->json->sendJson(array("valid"=>"false", "html"=>$this->view->render('user/add-user.phtml')));
$this->_helper->json->sendJson(['valid' => 'false', 'html' => $this->view->render('user/add-user.phtml')]);
}
} else {
$this->view->form = $form;
$this->_helper->json->sendJson(array("valid"=>"false", "html"=>$this->view->render('user/add-user.phtml')));
$this->_helper->json->sendJson(['valid' => 'false', 'html' => $this->view->render('user/add-user.phtml')]);
}
}
@ -104,7 +105,7 @@ class UserController extends Zend_Controller_Action
public function getHostsAction()
{
$search = $this->_getParam('term');
$search = $this->_getParam('term');
$this->view->hosts = Application_Model_User::getHosts($search);
}
@ -121,7 +122,7 @@ class UserController extends Zend_Controller_Action
$id = $this->_getParam('id');
$this->view->entries = Application_Model_User::GetUserData($id);
}
public function editUserAction()
{
Zend_Layout::getMvcInstance()->assign('parent_page', 'Settings');
@ -132,16 +133,16 @@ class UserController extends Zend_Controller_Action
$form = new Application_Form_EditUser();
if ($request->isPost()) {
$formData = $request->getPost();
if ($form->isValid($formData) &&
$form->validateLogin($formData['cu_login'], $formData['cu_user_id'])) {
if ($form->isValid($formData)
&& $form->validateLogin($formData['cu_login'], $formData['cu_user_id'])) {
$user = new Application_Model_User($formData['cu_user_id']);
//Stupid hack because our schema enforces non-null first_name
//even though by default the admin user has no first name... (....)
if (Application_Model_User::getCurrentUser()->isSuperAdmin()) {
if (empty($formData['cu_first_name'])) {
$formData['cu_first_name'] = "admin";
$formData['cu_last_name'] = "admin"; //ditto, avoid non-null DB constraint
if (empty($formData['cu_first_name'])) {
$formData['cu_first_name'] = 'admin';
$formData['cu_last_name'] = 'admin'; //ditto, avoid non-null DB constraint
}
}
if (isset($formData['cu_first_name'])) {
@ -154,8 +155,8 @@ class UserController extends Zend_Controller_Action
// We don't allow 6 x's as a password.
// The reason is because we use that as a password placeholder
// on the client side.
if (array_key_exists('cu_password', $formData) && ($formData['cu_password'] != "xxxxxx") &&
(!empty($formData['cu_password']))) {
if (array_key_exists('cu_password', $formData) && ($formData['cu_password'] != 'xxxxxx')
&& (!empty($formData['cu_password']))) {
$user->setPassword($formData['cu_password']);
}
@ -185,7 +186,7 @@ class UserController extends Zend_Controller_Action
//reinitialize form so language gets translated
$form = new Application_Form_EditUser();
$this->view->successMessage = "<div class='success'>"._("Settings updated successfully!")."</div>";
$this->view->successMessage = "<div class='success'>" . _('Settings updated successfully!') . '</div>';
}
$this->view->form = $form;
$this->view->html = $this->view->render('user/edit-user.phtml');
@ -198,49 +199,48 @@ class UserController extends Zend_Controller_Action
{
// action body
$delId = $this->_getParam('id');
$valid_actions = array("delete_cascade", "reassign_to");
$valid_actions = ['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($delId);
// 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($delId);
}
# only delete when valid action is selected for the owned files
if (! in_array($files_action, $valid_actions) ) {
// 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();
$userId = $userInfo->id;
# Don't let users delete themselves
// Don't let users delete themselves
if ($delId == $userId) {
return;
}
$user = new Application_Model_User($delId);
// Don't allow super admins to be deleted.
if ($user->isSuperAdmin())
{
if ($user->isSuperAdmin()) {
return;
}
# Take care of the user's files by either assigning them to somebody
# or deleting them all
if ($files_action == "delete_cascade") {
// 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") {
} 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 );
$user->donateFilesTo($new_owner);
Logging::info("Reassign to user {$new_owner->getDbId()}");
}
# Finally delete the user
// Finally delete the user
$this->view->entries = $user->delete();
}
}

View File

@ -1,28 +1,29 @@
<?php
class UsersettingsController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
// Initialize action controller here
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('get-now-playing-screen-settings', 'json')
->addActionContext('set-now-playing-screen-settings', 'json')
->addActionContext('get-library-datatable', 'json')
->addActionContext('set-library-datatable', 'json')
->addActionContext('get-timeline-datatable', 'json')
->addActionContext('set-timeline-datatable', 'json')
->addActionContext('remindme', 'json')
->addActionContext('remindme-never', 'json')
->addActionContext('donotshowregistrationpopup', 'json')
->addActionContext('set-library-screen-settings', 'json')
->initContext();
->addActionContext('set-now-playing-screen-settings', 'json')
->addActionContext('get-library-datatable', 'json')
->addActionContext('set-library-datatable', 'json')
->addActionContext('get-timeline-datatable', 'json')
->addActionContext('set-timeline-datatable', 'json')
->addActionContext('remindme', 'json')
->addActionContext('remindme-never', 'json')
->addActionContext('donotshowregistrationpopup', 'json')
->addActionContext('set-library-screen-settings', 'json')
->initContext()
;
}
public function setNowPlayingScreenSettingsAction()
{
$request = $this->getRequest();
$settings = $request->getParam("settings");
$settings = $request->getParam('settings');
Application_Model_Preference::setNowPlayingScreenSettings($settings);
}
@ -38,7 +39,7 @@ class UsersettingsController extends Zend_Controller_Action
public function setLibraryDatatableAction()
{
$request = $this->getRequest();
$settings = $request->getParam("settings");
$settings = $request->getParam('settings');
Application_Model_Preference::setCurrentLibraryTableSetting($settings);
}
@ -56,7 +57,7 @@ class UsersettingsController extends Zend_Controller_Action
public function setTimelineDatatableAction()
{
$request = $this->getRequest();
$settings = $request->getParam("settings");
$settings = $request->getParam('settings');
Application_Model_Preference::setTimelineDatatableSetting($settings);
}
@ -76,7 +77,7 @@ class UsersettingsController extends Zend_Controller_Action
Zend_Session::namespaceUnset('referrer');
Application_Model_Preference::SetRemindMeDate();
}
public function remindmeNeverAction()
{
SessionHelper::reopenSessionForWriting();
@ -95,7 +96,7 @@ class UsersettingsController extends Zend_Controller_Action
public function setLibraryScreenSettingsAction()
{
$request = $this->getRequest();
$settings = $request->getParam("settings");
$settings = $request->getParam('settings');
Application_Model_Preference::setLibraryScreenSettings($settings);
}
}

View File

@ -6,10 +6,11 @@ class WebstreamController extends Zend_Controller_Action
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('new', 'json')
->addActionContext('save', 'json')
->addActionContext('edit', 'json')
->addActionContext('delete', 'json')
->initContext();
->addActionContext('save', 'json')
->addActionContext('edit', 'json')
->addActionContext('delete', 'json')
->initContext()
;
}
public function newAction()
@ -17,7 +18,8 @@ class WebstreamController extends Zend_Controller_Action
$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");
header('Status: 401 Not Authorized');
return;
}
@ -25,20 +27,20 @@ class WebstreamController extends Zend_Controller_Action
//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->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')));
$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->action = 'new';
$this->view->html = $this->view->render('webstream/webstream.phtml');
}
@ -46,57 +48,57 @@ class WebstreamController extends Zend_Controller_Action
{
$request = $this->getRequest();
$id = $request->getParam("id");
$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");
Application_Model_Library::changePlaylist($id, 'stream');
}
$obj = new Application_Model_Webstream($webstream);
$user = Application_Model_User::getCurrentUser();
$isAdminOrPM = $user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
$isAdminOrPM = $user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER]);
if (!$isAdminOrPM && $webstream->getDbCreatorId() != $user->getId()) {
$this->view->objType = "webstream";
$this->view->type = "webstream";
$this->view->objType = 'webstream';
$this->view->type = 'webstream';
$this->view->obj = $obj;
$this->view->id = $id;
$this->view->html = $this->view->render('playlist/permission-denied.phtml');
return;
}
$this->view->obj = $obj;
$this->view->type = "webstream";
$this->view->type = 'webstream';
$this->view->id = $id;
$this->view->action = "edit";
$this->view->action = 'edit';
$this->view->html = $this->view->render('webstream/webstream.phtml');
}
public function deleteAction()
{
$request = $this->getRequest();
$id = $request->getParam("ids");
$id = $request->getParam('ids');
if (!$this->isAuthorized($id)) {
header("Status: 401 Not Authorized");
header('Status: 401 Not Authorized');
return;
}
$type = "stream";
$type = 'stream';
Application_Model_Library::changePlaylist(null, $type);
$webstream = CcWebstreamQuery::create()->findPK($id)->delete();
$this->view->obj = null;
$this->view->action = "delete";
$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
@ -104,7 +106,7 @@ class WebstreamController extends Zend_Controller_Action
public function isAuthorized($webstream_id)
{
$user = Application_Model_User::getCurrentUser();
if ($user->isUserType(array(UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) {
if ($user->isUserType([UTYPE_SUPERADMIN, UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER])) {
return true;
}
@ -121,9 +123,9 @@ class WebstreamController extends Zend_Controller_Action
/*we are creating a new stream. Don't need to check whether the
DJ/Host owns the stream*/
return true;
} else {
Logging::info( $user );
}
Logging::info($user);
return false;
}
@ -131,35 +133,36 @@ class WebstreamController extends Zend_Controller_Action
{
$request = $this->getRequest();
$id = $request->getParam("id");
$id = $request->getParam('id');
$parameters = array();
foreach (array('id','length','name','description','url') as $p) {
$parameters = [];
foreach (['id', 'length', 'name', 'description', 'url'] as $p) {
$parameters[$p] = trim($request->getParam($p));
}
if (!$this->isAuthorized($id)) {
header("Status: 401 Not Authorized");
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");
Application_Model_Library::changePlaylist($streamId, 'stream');
$this->view->statusMessage = "<div class='success'>"._("Webstream saved.")."</div>";
$this->view->statusMessage = "<div class='success'>" . _('Webstream saved.') . '</div>';
$this->view->streamId = $streamId;
$this->view->length = $di->format("%Hh %Im");
$this->view->length = $di->format('%Hh %Im');
} else {
throw new Exception("isValid returned false");
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->statusMessage = "<div class='errors'>" . _('Invalid form values.') . '</div>';
$this->view->streamId = -1;
$this->view->analysis = $analysis;
}

View File

@ -4,31 +4,30 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
{
/**
* @var Zend_Acl
**/
*/
protected $_acl;
/**
* @var string
**/
*/
protected $_roleName;
/**
* @var array
**/
*/
protected $_errorPage;
/**
* Constructor
* Constructor.
*
* @param mixed $aclData
* @param $roleName
* @return void
**/
*/
public function __construct(Zend_Acl $aclData, $roleName = 'G')
{
$this->_errorPage = array('module' => 'default',
'controller' => 'error',
'action' => 'error');
$this->_errorPage = ['module' => 'default',
'controller' => 'error',
'action' => 'error', ];
$this->_roleName = $roleName;
@ -38,32 +37,32 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
}
/**
* Sets the ACL object
* Sets the ACL object.
*
* @param mixed $aclData
* @return void
**/
* @param mixed $aclData
*/
public function setAcl(Zend_Acl $aclData)
{
$this->_acl = $aclData;
}
/**
* Returns the ACL object
* Returns the ACL object.
*
* @return Zend_Acl
**/
*/
public function getAcl()
{
return $this->_acl;
}
/**
* Returns the ACL role used
* Returns the ACL role used.
*
* @return string
*
* @author
**/
*/
public function getRoleName()
{
return $this->_roleName;
@ -75,25 +74,24 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
}
/**
* Sets the error page
* Sets the error page.
*
* @param string $action
* @param string $controller
* @param string $module
* @return void
**/
* @param string $action
* @param string $controller
* @param string $module
*/
public function setErrorPage($action, $controller = 'error', $module = 'default')
{
$this->_errorPage = array('module' => $module,
'controller' => $controller,
'action' => $action);
$this->_errorPage = ['module' => $module,
'controller' => $controller,
'action' => $action, ];
}
/**
* Returns the error page
* Returns the error page.
*
* @return array
**/
*/
public function getErrorPage()
{
return $this->_errorPage;
@ -102,82 +100,73 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
/**
* Predispatch
* Checks if the current user identified by roleName has rights to the requested url (module/controller/action)
* If not, it will call denyAccess to be redirected to errorPage
*
* @return void
**/
* If not, it will call denyAccess to be redirected to errorPage.
*/
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$controller = strtolower($request->getControllerName());
if (in_array($controller, array(
"index",
"login",
"api",
"auth",
"error",
"locale",
"upgrade",
"embed",
"feeds"
)))
{
$this->setRoleName("G");
}
elseif (Zend_Session::isStarted() && !Zend_Auth::getInstance()->hasIdentity()) {
if (in_array($controller, [
'index',
'login',
'api',
'auth',
'error',
'locale',
'upgrade',
'embed',
'feeds',
])) {
$this->setRoleName('G');
} elseif (Zend_Session::isStarted() && !Zend_Auth::getInstance()->hasIdentity()) {
//The controller uses sessions but we don't have an identity yet.
// If we don't have an identity and we're making a RESTful request,
// we need to do API key verification
if ($request->getModuleName() == "rest") {
if ($request->getModuleName() == 'rest') {
if (!$this->verifyAuth()) {
//$this->denyAccess();
//$this->getResponse()->sendResponse();
//$r->gotoSimpleAndExit('index', 'login', $request->getModuleName());
//die();
throw new Zend_Controller_Exception("Incorrect API key", 401);
throw new Zend_Controller_Exception('Incorrect API key', 401);
}
}
else //Non-REST, regular Airtime web app requests
{
} else { //Non-REST, regular Airtime web app requests
// Redirect user to the landing page if they are trying to
// access a resource that requires a valid session.
// Skip the redirection if they are already on the landing page
// or the login page.
if ($controller !== 'index' && $controller !== 'login') {
if ($request->isXmlHttpRequest()) {
$url = 'http://'.$request->getHttpHost().'/';
$json = Zend_Json::encode(array('auth' => false, 'url' => $url));
$url = 'http://' . $request->getHttpHost() . '/';
$json = Zend_Json::encode(['auth' => false, 'url' => $url]);
// Prepare response
$this->getResponse()
->setHttpResponseCode(401)
->setBody($json)
->sendResponse();
->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', 'index', $request->getModuleName());
}
}
}
}
} else { //We have a session/identity.
// If we have an identity and we're making a RESTful request,
// we need to check the CSRF token
if ($_SERVER['REQUEST_METHOD'] != "GET" && $request->getModuleName() == "rest") {
$token = $request->getParam("csrf_token");
if ($_SERVER['REQUEST_METHOD'] != 'GET' && $request->getModuleName() == 'rest') {
$token = $request->getParam('csrf_token');
// PUT requests don't parameterize the data in the body, so we can't
// fetch it with getParam or getPost; instead we have to parse the body and
// check for the token in the JSON. (Hopefully we can find a better way to do this) -- Duncan
if (empty($token)) {
$token = json_decode($this->getRequest()->getRawBody(), true)["csrf_token"];
$token = json_decode($this->getRequest()->getRawBody(), true)['csrf_token'];
}
$tokenValid = $this->verifyCSRFToken($token);
@ -185,15 +174,17 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
$csrf_namespace = new Zend_Session_Namespace('csrf_namespace');
$csrf_namespace->authtoken = sha1(openssl_random_pseudo_bytes(128));
Logging::warn("Invalid CSRF token: $token");
Logging::warn("Invalid CSRF token: {$token}");
$this->getResponse()
->setHttpResponseCode(401)
->appendBody("ERROR: CSRF token mismatch.")
->sendResponse();
die();
->setHttpResponseCode(401)
->appendBody('ERROR: CSRF token mismatch.')
->sendResponse()
;
exit();
}
}
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$this->setRoleName($userInfo->type);
@ -208,28 +199,32 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
$resourceName .= $controller;
/** Check if the controller/action can be accessed by the current user */
// Check if the controller/action can be accessed by the current user
if (!$this->getAcl()->has($resourceName)) {
$this->setErrorPage('error404');
$this->denyAccess();
} else if (!$this->getAcl()->isAllowed($this->_roleName,
$resourceName,
$request->getActionName())) {
/** Redirect to access denied page */
} elseif (!$this->getAcl()->isAllowed(
$this->_roleName,
$resourceName,
$request->getActionName()
)) {
// Redirect to access denied page
$this->setErrorPage('error403');
$this->denyAccess();
}
}
}
private function verifyAuth() {
private function verifyAuth()
{
if ($this->verifyAPIKey() || $this->isVerifiedDownload()) {
return true;
}
$this->getResponse()
->setHttpResponseCode(401)
->appendBody("ERROR: Incorrect API key.");
->appendBody('ERROR: Incorrect API key.')
;
return false;
}
@ -239,47 +234,50 @@ class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
* It should satisfy the following requirements:
* * request path is /rest/media/:id/download
* * download key is correct
* * requested file belongs to the station podcast
* * requested file belongs to the station podcast.
*
* @return bool
*/
private function isVerifiedDownload() {
private function isVerifiedDownload()
{
$request = $this->getRequest();
$fileId = $request->getParam("id");
$key = $request->getParam("download_key");
$fileId = $request->getParam('id');
$key = $request->getParam('download_key');
$module = $request->getModuleName();
$controller = $request->getControllerName();
$action = $request->getActionName();
$stationPodcast = StationPodcastQuery::create()
->findOneByDbPodcastId(Application_Model_Preference::getStationPodcastId());
return $module == "rest" && $controller == "media" && $action == "download"
->findOneByDbPodcastId(Application_Model_Preference::getStationPodcastId())
;
return $module == 'rest' && $controller == 'media' && $action == 'download'
&& $key === Application_Model_Preference::getStationPodcastDownloadKey()
&& $stationPodcast->hasEpisodeForFile($fileId);
}
private function verifyCSRFToken($token) {
private function verifyCSRFToken($token)
{
return SecurityHelper::verifyCSRFToken($token);
}
private function verifyAPIKey() {
private function verifyAPIKey()
{
// The API key is passed in via HTTP "basic authentication":
// http://en.wikipedia.org/wiki/Basic_access_authentication
$CC_CONFIG = Config::getConfig();
// Decode the API key that was passed to us in the HTTP request.
$authHeader = $this->getRequest()->getHeader("Authorization");
$encodedRequestApiKey = substr($authHeader, strlen("Basic "));
$encodedStoredApiKey = base64_encode($CC_CONFIG["apiKey"][0] . ":");
return ($encodedRequestApiKey === $encodedStoredApiKey);
$authHeader = $this->getRequest()->getHeader('Authorization');
$encodedRequestApiKey = substr($authHeader, strlen('Basic '));
$encodedStoredApiKey = base64_encode($CC_CONFIG['apiKey'][0] . ':');
return $encodedRequestApiKey === $encodedStoredApiKey;
}
/**
* Deny Access Function
* Redirects to errorPage, this can be called from an action using the action helper
*
* @return void
**/
* Redirects to errorPage, this can be called from an action using the action helper.
*/
public function denyAccess()
{
$this->_request->setModuleName($this->_errorPage['module']);

View File

@ -2,14 +2,16 @@
class Zend_Controller_Plugin_Maintenance extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request) {
$maintenanceFile = isset($_SERVER['AIRTIME_BASE']) ? $_SERVER['AIRTIME_BASE']."maintenance.txt" : "/tmp/maintenance.txt";
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$maintenanceFile = isset($_SERVER['AIRTIME_BASE']) ? $_SERVER['AIRTIME_BASE'] . 'maintenance.txt' : '/tmp/maintenance.txt';
if (file_exists($maintenanceFile)) {
$request->setModuleName('default')
->setControllerName('index')
->setActionName('maintenance')
->setDispatched(true);
->setControllerName('index')
->setActionName('maintenance')
->setDispatched(true)
;
}
}
}
}

View File

@ -7,9 +7,10 @@
*/
class PageLayoutInitPlugin extends Zend_Controller_Plugin_Abstract
{
protected $_bootstrap = null;
protected $_bootstrap;
public function __construct($boostrap) {
public function __construct($boostrap)
{
$this->_bootstrap = $boostrap;
}
@ -17,7 +18,7 @@ class PageLayoutInitPlugin extends Zend_Controller_Plugin_Abstract
* Start the session depending on which controller your request is going to.
* We start the session explicitly here so that we can avoid starting sessions
* needlessly for (stateless) requests to the API.
* @param Zend_Controller_Request_Abstract $request
*
* @throws Zend_Session_Exception
*/
public function routeShutdown(Zend_Controller_Request_Abstract $request)
@ -27,15 +28,15 @@ class PageLayoutInitPlugin extends Zend_Controller_Plugin_Abstract
//List of controllers where we don't need a session, and we don't need
//all the standard HTML / JS boilerplate.
if (!in_array($controller, array(
"index", //Radio Page
"api",
"auth",
"error",
"upgrade",
"embed",
"feeds"
))
if (!in_array($controller, [
'index', //Radio Page
'api',
'auth',
'error',
'upgrade',
'embed',
'feeds',
])
) {
//Start the session
Zend_Session::start();
@ -54,7 +55,7 @@ class PageLayoutInitPlugin extends Zend_Controller_Plugin_Abstract
}
// Skip upgrades and task management when running unit tests
if (getenv("AIRTIME_UNIT_TEST") != 1) {
if (getenv('AIRTIME_UNIT_TEST') != 1) {
$taskManager = TaskManager::getInstance();
// Run the upgrade on each request (if it needs to be run)
@ -66,7 +67,7 @@ class PageLayoutInitPlugin extends Zend_Controller_Plugin_Abstract
// Piggyback the TaskManager onto API calls. This provides guaranteed consistency
// (there is at least one API call made from pypo to Airtime every 7 minutes) and
// greatly reduces the chances of lock contention on cc_pref while the TaskManager runs
if ($controller == "api") {
if ($controller == 'api') {
$taskManager->runTasks();
}
}
@ -81,29 +82,29 @@ class PageLayoutInitPlugin extends Zend_Controller_Plugin_Abstract
$view = $this->_bootstrap->getResource('view');
$baseUrl = Application_Common_OsPath::getBaseDir();
$view->headScript()->appendScript("var baseUrl = '$baseUrl';");
$view->headScript()->appendScript("var baseUrl = '{$baseUrl}';");
$this->_initTranslationGlobals($view);
$user = Application_Model_User::GetCurrentUser();
if (!is_null($user)) {
$userType = $user->getType();
} else {
$userType = "";
$userType = '';
}
$view->headScript()->appendScript("var userType = '$userType';");
$view->headScript()->appendScript("var userType = '{$userType}';");
// Dropzone also accept file extensions and doesn't correctly extract certain mimetypes (eg. FLAC - try it),
// so we append the file extensions to the list of mimetypes and that makes it work.
$mimeTypes = FileDataHelper::getAudioMimeTypeArray();
$fileExtensions = array_values($mimeTypes);
foreach($fileExtensions as &$extension) {
foreach ($fileExtensions as &$extension) {
$extension = '.' . $extension;
}
$view->headScript()->appendScript("var acceptedMimeTypes = " . json_encode(array_merge(array_keys($mimeTypes), $fileExtensions)) . ";");
$view->headScript()->appendScript('var acceptedMimeTypes = ' . json_encode(array_merge(array_keys($mimeTypes), $fileExtensions)) . ';');
}
/**
* Create a global namespace to hold a session token for CSRF prevention
* Create a global namespace to hold a session token for CSRF prevention.
*/
protected function _initCsrfNamespace()
{
@ -131,7 +132,7 @@ class PageLayoutInitPlugin extends Zend_Controller_Plugin_Abstract
/**
* Ideally, globals should be written to a single js file once
* from a php init function. This will save us from having to
* reinitialize them every request
* reinitialize them every request.
*/
private function _initTranslationGlobals()
{
@ -142,18 +143,18 @@ class PageLayoutInitPlugin extends Zend_Controller_Plugin_Abstract
//Each page refresh or tab open has uniqID, not to be used for security
$view->headScript()->appendScript("var UNIQID = '" . uniqid() . "';");
$track_type_options = array();
$track_type_options = [];
$track_types = Application_Model_Tracktype::getTracktypes();
array_multisort(array_map(function($element) {
array_multisort(array_map(function ($element) {
return $element['type_name'];
}, $track_types), SORT_ASC, $track_types);
foreach ($track_types as $key => $tt) {
$track_type_options[$tt['code']] = $tt['type_name'];
}
$ttarr = json_encode($track_type_options, JSON_FORCE_OBJECT);
$view->headScript()->appendScript("var TRACKTYPES = " . $ttarr . ";");
$view->headScript()->appendScript('var TRACKTYPES = ' . $ttarr . ';');
}
protected function _initHeadLink()
@ -164,14 +165,15 @@ class PageLayoutInitPlugin extends Zend_Controller_Plugin_Abstract
$baseUrl = Application_Common_OsPath::getBaseDir();
$view->headLink(array('rel' => 'icon', 'href' => $baseUrl . 'favicon.ico?' . $CC_CONFIG['airtime_version'], 'type' => 'image/x-icon'), 'PREPEND')
$view->headLink(['rel' => 'icon', 'href' => $baseUrl . 'favicon.ico?' . $CC_CONFIG['airtime_version'], 'type' => 'image/x-icon'], 'PREPEND')
->appendStylesheet($baseUrl . 'css/bootstrap.css?' . $CC_CONFIG['airtime_version'])
->appendStylesheet($baseUrl . 'css/redmond/jquery-ui-1.8.8.custom.css?' . $CC_CONFIG['airtime_version'])
->appendStylesheet($baseUrl . 'css/pro_dropdown_3.css?' . $CC_CONFIG['airtime_version'])
->appendStylesheet($baseUrl . 'css/qtip/jquery.qtip.min.css?' . $CC_CONFIG['airtime_version'])
->appendStylesheet($baseUrl . 'css/styles.css?' . $CC_CONFIG['airtime_version'])
->appendStylesheet($baseUrl . 'css/masterpanel.css?' . $CC_CONFIG['airtime_version'])
->appendStylesheet($baseUrl . 'css/tipsy/jquery.tipsy.css?' . $CC_CONFIG['airtime_version']);
->appendStylesheet($baseUrl . 'css/tipsy/jquery.tipsy.css?' . $CC_CONFIG['airtime_version'])
;
}
protected function _initHeadScript()
@ -200,20 +202,21 @@ class PageLayoutInitPlugin extends Zend_Controller_Plugin_Abstract
->appendFile($baseUrl . 'locale/general-translation-table?' . $CC_CONFIG['airtime_version'], 'text/javascript')
->appendFile($baseUrl . 'locale/datatables-translation-table?' . $CC_CONFIG['airtime_version'], 'text/javascript')
->appendScript("$.i18n.setDictionary(general_dict)")
->appendScript("var baseUrl='$baseUrl'");
->appendScript('$.i18n.setDictionary(general_dict)')
->appendScript("var baseUrl='{$baseUrl}'")
;
//These timezones are needed to adjust javascript Date objects on the client to make sense to the user's set timezone
//or the server's set timezone.
$serverTimeZone = new DateTimeZone(Application_Model_Preference::GetDefaultTimezone());
$now = new DateTime("now", $serverTimeZone);
$offset = $now->format("Z") * -1;
$now = new DateTime('now', $serverTimeZone);
$offset = $now->format('Z') * -1;
$view->headScript()->appendScript("var serverTimezoneOffset = {$offset}; //in seconds");
if (class_exists("Zend_Auth", false) && Zend_Auth::getInstance()->hasIdentity()) {
if (class_exists('Zend_Auth', false) && Zend_Auth::getInstance()->hasIdentity()) {
$userTimeZone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
$now = new DateTime("now", $userTimeZone);
$offset = $now->format("Z") * -1;
$now = new DateTime('now', $userTimeZone);
$offset = $now->format('Z') * -1;
$view->headScript()->appendScript("var userTimezoneOffset = {$offset}; //in seconds");
}
@ -225,16 +228,17 @@ class PageLayoutInitPlugin extends Zend_Controller_Plugin_Abstract
->appendFile($baseUrl . 'js/tipsy/jquery.tipsy.js?' . $CC_CONFIG['airtime_version'], 'text/javascript')
->appendFile($baseUrl . 'js/airtime/common/common.js?' . $CC_CONFIG['airtime_version'], 'text/javascript')
->appendFile($baseUrl . 'js/airtime/common/audioplaytest.js?' . $CC_CONFIG['airtime_version'], 'text/javascript');
->appendFile($baseUrl . 'js/airtime/common/audioplaytest.js?' . $CC_CONFIG['airtime_version'], 'text/javascript')
;
$user = Application_Model_User::getCurrentUser();
if (!is_null($user)) {
$userType = $user->getType();
} else {
$userType = "";
$userType = '';
}
$view->headScript()->appendScript("var userType = '$userType';");
$view->headScript()->appendScript("var userType = '{$userType}';");
}
protected function _initViewHelpers()

View File

@ -5,15 +5,15 @@ class RabbitMqPlugin extends Zend_Controller_Plugin_Abstract
public function dispatchLoopShutdown()
{
if (Application_Model_RabbitMq::$doPush) {
$md = array('schedule' => Application_Model_Schedule::getSchedule());
Application_Model_RabbitMq::SendMessageToPypo("update_schedule", $md);
$md = ['schedule' => Application_Model_Schedule::getSchedule()];
Application_Model_RabbitMq::SendMessageToPypo('update_schedule', $md);
}
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");
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

@ -2,30 +2,28 @@
class Application_Form_AddShowAbsoluteRebroadcastDates extends Zend_Form_SubForm
{
public function init()
{
$this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/add-show-rebroadcast-absolute.phtml'))
));
$this->setDecorators([
['ViewScript', ['viewScript' => 'form/add-show-rebroadcast-absolute.phtml']],
]);
for ($i=1; $i<=10; $i++) {
$text = new Zend_Form_Element_Text("add_show_rebroadcast_date_absolute_$i");
for ($i = 1; $i <= 10; ++$i) {
$text = new Zend_Form_Element_Text("add_show_rebroadcast_date_absolute_{$i}");
$text->setAttrib('class', 'input_text');
$text->addFilter('StringTrim');
$text->addValidator('date', false, array('YYYY-MM-DD'));
$text->addValidator('date', false, ['YYYY-MM-DD']);
$text->setRequired(false);
$text->setDecorators(array('ViewHelper'));
$text->setDecorators(['ViewHelper']);
$this->addElement($text);
$text = new Zend_Form_Element_Text("add_show_rebroadcast_time_absolute_$i");
$text = new Zend_Form_Element_Text("add_show_rebroadcast_time_absolute_{$i}");
$text->setAttrib('class', 'input_text');
$text->addFilter('StringTrim');
$text->addValidator('date', false, array('HH:mm'));
$text->addValidator('regex', false, array('/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')));
$text->addValidator('date', false, ['HH:mm']);
$text->addValidator('regex', false, ['/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')]);
$text->setRequired(false);
$text->setDecorators(array('ViewHelper'));
$text->setDecorators(['ViewHelper']);
$this->addElement($text);
}
}
@ -35,63 +33,64 @@ class Application_Form_AddShowAbsoluteRebroadcastDates extends Zend_Form_SubForm
$elements = $this->getElements();
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
$element->setAttrib('disabled','disabled');
$element->setAttrib('disabled', 'disabled');
}
}
}
public function isValid($formData) {
public function isValid($formData)
{
if (parent::isValid($formData)) {
return $this->checkReliantFields($formData);
} else {
return false;
return $this->checkReliantFields($formData);
}
return false;
}
public function checkReliantFields($formData)
{
$noError = true;
for ($i=1; $i<=10; $i++) {
for ($i = 1; $i <= 10; ++$i) {
$valid = true;
$day = $formData['add_show_rebroadcast_date_absolute_'.$i];
$time = $formData['add_show_rebroadcast_time_absolute_'.$i];
$day = $formData['add_show_rebroadcast_date_absolute_' . $i];
$time = $formData['add_show_rebroadcast_time_absolute_' . $i];
if (trim($day) == "" && trim($time) == "") {
if (trim($day) == '' && trim($time) == '') {
continue;
}
if (trim($day) == "") {
$this->getElement('add_show_rebroadcast_date_absolute_'.$i)->setErrors(array(_("Day must be specified")));
if (trim($day) == '') {
$this->getElement('add_show_rebroadcast_date_absolute_' . $i)->setErrors([_('Day must be specified')]);
$valid = false;
}
if (trim($time) == "") {
$this->getElement('add_show_rebroadcast_time_absolute_'.$i)->setErrors(array(_("Time must be specified")));
if (trim($time) == '') {
$this->getElement('add_show_rebroadcast_time_absolute_' . $i)->setErrors([_('Time must be specified')]);
$valid = false;
}
if ($valid === false) {
$noError = false;
continue;
}
$show_start_time = $formData['add_show_start_date']." ".$formData['add_show_start_time'];
$show_start_time = $formData['add_show_start_date'] . ' ' . $formData['add_show_start_time'];
$show_end = new DateTime($show_start_time);
$duration = $formData['add_show_duration'];
$duration = explode(":", $duration);
$duration = explode(':', $duration);
$show_end->add(new DateInterval("PT$duration[0]H"));
$show_end->add(new DateInterval("PT$duration[1]M"));
$show_end->add(new DateInterval("PT1H"));//min time to wait until a rebroadcast
$show_end->add(new DateInterval("PT{$duration[0]}H"));
$show_end->add(new DateInterval("PT{$duration[1]}M"));
$show_end->add(new DateInterval('PT1H')); //min time to wait until a rebroadcast
$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);
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([_('Must wait at least 1 hour to rebroadcast')]);
$valid = false;
$noError = false;
}

View File

@ -4,9 +4,9 @@ class Application_Form_AddShowAutoPlaylist extends Zend_Form_SubForm
{
public function init()
{
$this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/add-show-autoplaylist.phtml'))
));
$this->setDecorators([
['ViewScript', ['viewScript' => 'form/add-show-autoplaylist.phtml']],
]);
$notEmptyValidator = Application_Form_Helper_ValidationTypes::overrideNotEmptyValidator();
// retrieves the length limit for each char field
@ -14,26 +14,26 @@ class Application_Form_AddShowAutoPlaylist extends Zend_Form_SubForm
$maxLens = Application_Model_Show::getMaxLengths();
// Add autoplaylist checkbox element
$this->addElement('checkbox', 'add_show_has_autoplaylist', array(
'label' => _('Add Autoloading Playlist ?'),
'required' => false,
'class' => 'input_text',
'decorators' => array('ViewHelper')
));
$autoPlaylistSelect = new Zend_Form_Element_Select("add_show_autoplaylist_id");
$autoPlaylistSelect->setLabel(_("Select Playlist"));
$this->addElement('checkbox', 'add_show_has_autoplaylist', [
'label' => _('Add Autoloading Playlist ?'),
'required' => false,
'class' => 'input_text',
'decorators' => ['ViewHelper'],
]);
$autoPlaylistSelect = new Zend_Form_Element_Select('add_show_autoplaylist_id');
$autoPlaylistSelect->setLabel(_('Select Playlist'));
$autoPlaylistSelect->setMultiOptions(Application_Model_Library::getPlaylistNames(true));
$autoPlaylistSelect->setValue(null);
$autoPlaylistSelect->setDecorators(array('ViewHelper'));
$autoPlaylistSelect->setDecorators(['ViewHelper']);
$this->addElement($autoPlaylistSelect);
// Add autoplaylist checkbox element
$this->addElement('checkbox', 'add_show_autoplaylist_repeat', array(
'label' => _('Repeat Playlist Until Show is Full ?'),
'required' => false,
'class' => 'input_text',
'decorators' => array('ViewHelper')
));
$this->addElement('checkbox', 'add_show_autoplaylist_repeat', [
'label' => _('Repeat Playlist Until Show is Full ?'),
'required' => false,
'class' => 'input_text',
'decorators' => ['ViewHelper'],
]);
}
public function disable()
@ -41,7 +41,7 @@ class Application_Form_AddShowAutoPlaylist extends Zend_Form_SubForm
$elements = $this->getElements();
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
$element->setAttrib('disabled','disabled');
$element->setAttrib('disabled', 'disabled');
}
}
}
@ -51,7 +51,7 @@ class Application_Form_AddShowAutoPlaylist extends Zend_Form_SubForm
$elements = $this->getElements();
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
$element->setAttrib('readonly','readonly');
$element->setAttrib('readonly', 'readonly');
}
}
}

View File

@ -4,41 +4,44 @@ require_once 'customvalidators/ConditionalNotEmpty.php';
class Application_Form_AddShowLiveStream extends Zend_Form_SubForm
{
public function init()
{
$cb_airtime_auth = new Zend_Form_Element_Checkbox("cb_airtime_auth");
$cb_airtime_auth->setLabel(sprintf(_("Use %s Authentication:"), PRODUCT_NAME))
->setChecked(true)
->setRequired(false);
$cb_airtime_auth = new Zend_Form_Element_Checkbox('cb_airtime_auth');
$cb_airtime_auth->setLabel(sprintf(_('Use %s Authentication:'), PRODUCT_NAME))
->setChecked(true)
->setRequired(false)
;
$this->addElement($cb_airtime_auth);
$cb_custom_auth = new Zend_Form_Element_Checkbox("cb_custom_auth");
$cb_custom_auth ->setLabel(_("Use Custom Authentication:"))
->setRequired(false);
$cb_custom_auth = new Zend_Form_Element_Checkbox('cb_custom_auth');
$cb_custom_auth->setLabel(_('Use Custom Authentication:'))
->setRequired(false)
;
$this->addElement($cb_custom_auth);
//custom username
$custom_username = new Zend_Form_Element_Text('custom_username');
$custom_username->setAttrib('class', 'input_text')
->setAttrib('autocomplete', 'off')
->setAllowEmpty(true)
->setLabel(_('Custom Username'))
->setFilters(array('StringTrim'))
->setValidators(array(
new ConditionalNotEmpty(array("cb_custom_auth"=>"1"))));
->setAttrib('autocomplete', 'off')
->setAllowEmpty(true)
->setLabel(_('Custom Username'))
->setFilters(['StringTrim'])
->setValidators([
new ConditionalNotEmpty(['cb_custom_auth' => '1']), ])
;
$this->addElement($custom_username);
//custom password
$custom_password = new Zend_Form_Element_Password('custom_password');
$custom_password->setAttrib('class', 'input_text')
->setAttrib('autocomplete', 'off')
->setAttrib('renderPassword','true')
->setAllowEmpty(true)
->setLabel(_('Custom Password'))
->setFilters(array('StringTrim'))
->setValidators(array(
new ConditionalNotEmpty(array("cb_custom_auth"=>"1"))));
->setAttrib('autocomplete', 'off')
->setAttrib('renderPassword', 'true')
->setAllowEmpty(true)
->setLabel(_('Custom Password'))
->setFilters(['StringTrim'])
->setValidators([
new ConditionalNotEmpty(['cb_custom_auth' => '1']), ])
;
$this->addElement($custom_password);
$showSourceParams = parse_url(Application_Model_Preference::GetLiveDJSourceConnectionURL());
@ -47,25 +50,29 @@ class Application_Form_AddShowLiveStream extends Zend_Form_SubForm
$showSourceHost = new Zend_Form_Element_Text('show_source_host');
$showSourceHost->setAttrib('readonly', true)
->setLabel(_('Host:'))
->setValue(isset($showSourceParams["host"])?$showSourceParams["host"]:"");
->setValue(isset($showSourceParams['host']) ? $showSourceParams['host'] : '')
;
$this->addElement($showSourceHost);
$showSourcePort = new Zend_Form_Element_Text('show_source_port');
$showSourcePort->setAttrib('readonly', true)
->setLabel(_('Port:'))
->setValue(isset($showSourceParams["port"])?$showSourceParams["port"]:"");
->setValue(isset($showSourceParams['port']) ? $showSourceParams['port'] : '')
;
$this->addElement($showSourcePort);
$showSourceMount = new Zend_Form_Element_Text('show_source_mount');
$showSourceMount->setAttrib('readonly', true)
->setLabel(_('Mount:'))
->setValue(isset($showSourceParams["path"])?$showSourceParams["path"]:"");
->setValue(isset($showSourceParams['path']) ? $showSourceParams['path'] : '')
;
$this->addElement($showSourceMount);
$this->setDecorators(
array(
array('ViewScript', array('viewScript' => 'form/add-show-live-stream.phtml'))
));
[
['ViewScript', ['viewScript' => 'form/add-show-live-stream.phtml']],
]
);
}
public function isValid($data)
@ -74,13 +81,13 @@ class Application_Form_AddShowLiveStream extends Zend_Form_SubForm
if ($data['cb_custom_auth'] == 1) {
if (trim($data['custom_username']) == '') {
$element = $this->getElement("custom_username");
$element->addError(_("Username field cannot be empty."));
$element = $this->getElement('custom_username');
$element->addError(_('Username field cannot be empty.'));
$isValid = false;
}
if (trim($data['custom_password']) == '') {
$element = $this->getElement("custom_password");
$element->addError(_("Password field cannot be empty."));
$element = $this->getElement('custom_password');
$element->addError(_('Password field cannot be empty.'));
$isValid = false;
}
}
@ -93,7 +100,7 @@ class Application_Form_AddShowLiveStream extends Zend_Form_SubForm
$elements = $this->getElements();
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
$element->setAttrib('disabled','disabled');
$element->setAttrib('disabled', 'disabled');
}
}
}

View File

@ -2,20 +2,19 @@
class Application_Form_AddShowRR extends Zend_Form_SubForm
{
public function init()
{
// Add record element
$this->addElement('checkbox', 'add_show_record', array(
'label' => _('Record from Line In?'),
'required' => false,
));
$this->addElement('checkbox', 'add_show_record', [
'label' => _('Record from Line In?'),
'required' => false,
]);
// Add record element
$this->addElement('checkbox', 'add_show_rebroadcast', array(
'label' => _('Rebroadcast?'),
'required' => false,
));
$this->addElement('checkbox', 'add_show_rebroadcast', [
'label' => _('Rebroadcast?'),
'required' => false,
]);
}
public function disable()
@ -23,9 +22,8 @@ class Application_Form_AddShowRR extends Zend_Form_SubForm
$elements = $this->getElements();
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
$element->setAttrib('disabled','disabled');
$element->setAttrib('disabled', 'disabled');
}
}
}
}

View File

@ -2,35 +2,33 @@
class Application_Form_AddShowRebroadcastDates extends Zend_Form_SubForm
{
public function init()
{
$this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/add-show-rebroadcast.phtml'))
));
$this->setDecorators([
['ViewScript', ['viewScript' => 'form/add-show-rebroadcast.phtml']],
]);
$relativeDates = array();
$relativeDates[""] = "";
for ($i=0; $i<=30; $i++) {
$relativeDates["$i days"] = "+$i "._("days");
$relativeDates = [];
$relativeDates[''] = '';
for ($i = 0; $i <= 30; ++$i) {
$relativeDates["{$i} days"] = "+{$i} " . _('days');
}
for ($i=1; $i<=10; $i++) {
$select = new Zend_Form_Element_Select("add_show_rebroadcast_date_$i");
for ($i = 1; $i <= 10; ++$i) {
$select = new Zend_Form_Element_Select("add_show_rebroadcast_date_{$i}");
$select->setAttrib('class', 'input_select');
$select->setMultiOptions($relativeDates);
$select->setRequired(false);
$select->setDecorators(array('ViewHelper'));
$select->setDecorators(['ViewHelper']);
$this->addElement($select);
$text = new Zend_Form_Element_Text("add_show_rebroadcast_time_$i");
$text = new Zend_Form_Element_Text("add_show_rebroadcast_time_{$i}");
$text->setAttrib('class', 'input_text');
$text->addFilter('StringTrim');
$text->addValidator('date', false, array('HH:mm'));
$text->addValidator('regex', false, array('/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')));
$text->addValidator('date', false, ['HH:mm']);
$text->addValidator('regex', false, ['/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')]);
$text->setRequired(false);
$text->setDecorators(array('ViewHelper'));
$text->setDecorators(['ViewHelper']);
$this->addElement($text);
}
}
@ -40,67 +38,68 @@ class Application_Form_AddShowRebroadcastDates extends Zend_Form_SubForm
$elements = $this->getElements();
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
$element->setAttrib('disabled','disabled');
$element->setAttrib('disabled', 'disabled');
}
}
}
public function isValid($formData) {
public function isValid($formData)
{
if (parent::isValid($formData)) {
return $this->checkReliantFields($formData);
} else {
return false;
return $this->checkReliantFields($formData);
}
return false;
}
public function checkReliantFields($formData)
{
$noError = true;
for ($i=1; $i<=10; $i++) {
for ($i = 1; $i <= 10; ++$i) {
$valid = true;
$days = $formData['add_show_rebroadcast_date_'.$i];
$time = $formData['add_show_rebroadcast_time_'.$i];
$days = $formData['add_show_rebroadcast_date_' . $i];
$time = $formData['add_show_rebroadcast_time_' . $i];
if (trim($days) == "" && trim($time) == "") {
if (trim($days) == '' && trim($time) == '') {
continue;
}
if (trim($days) == "") {
$this->getElement('add_show_rebroadcast_date_'.$i)->setErrors(array(_("Day must be specified")));
if (trim($days) == '') {
$this->getElement('add_show_rebroadcast_date_' . $i)->setErrors([_('Day must be specified')]);
$valid = false;
}
if (trim($time) == "") {
$this->getElement('add_show_rebroadcast_time_'.$i)->setErrors(array(_("Time must be specified")));
if (trim($time) == '') {
$this->getElement('add_show_rebroadcast_time_' . $i)->setErrors([_('Time must be specified')]);
$valid = false;
}
if ($valid === false) {
$noError = false;
continue;
}
$days = explode(" ", $days);
$days = explode(' ', $days);
$day = $days[0];
$show_start_time = $formData['add_show_start_date']." ".$formData['add_show_start_time'];
$show_start_time = $formData['add_show_start_date'] . ' ' . $formData['add_show_start_time'];
$show_end = new DateTime($show_start_time);
$duration = $formData['add_show_duration'];
$duration = explode(":", $duration);
$duration = explode(':', $duration);
$show_end->add(new DateInterval("PT$duration[0]H"));
$show_end->add(new DateInterval("PT$duration[1]M"));
$show_end->add(new DateInterval("PT1H"));//min time to wait until a rebroadcast
$show_end->add(new DateInterval("PT{$duration[0]}H"));
$show_end->add(new DateInterval("PT{$duration[1]}M"));
$show_end->add(new DateInterval('PT1H')); //min time to wait until a rebroadcast
$rebroad_start = $formData['add_show_start_date']." ".$formData['add_show_rebroadcast_time_'.$i];
$rebroad_start = $formData['add_show_start_date'] . ' ' . $formData['add_show_rebroadcast_time_' . $i];
$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) {
$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([_('Must wait at least 1 hour to rebroadcast')]);
$valid = false;
$noError = false;
}

View File

@ -2,74 +2,75 @@
class Application_Form_AddShowRepeats extends Zend_Form_SubForm
{
public function init()
{
$linked = new Zend_Form_Element_Checkbox("add_show_linked");
$linked->setLabel(_("Link:"));
$linked = new Zend_Form_Element_Checkbox('add_show_linked');
$linked->setLabel(_('Link:'));
$this->addElement($linked);
//Add type select
$this->addElement('select', 'add_show_repeat_type', array(
$this->addElement('select', 'add_show_repeat_type', [
'required' => true,
'label' => _('Repeat Type:'),
'class' => ' input_select',
'multiOptions' => array(
"0" => _("weekly"),
"1" => _("every 2 weeks"),
"4" => _("every 3 weeks"),
"5" => _("every 4 weeks"),
"2" => _("monthly")
),
));
'multiOptions' => [
'0' => _('weekly'),
'1' => _('every 2 weeks'),
'4' => _('every 3 weeks'),
'5' => _('every 4 weeks'),
'2' => _('monthly'),
],
]);
// Add days checkboxes
$this->addElement(
'multiCheckbox',
'add_show_day_check',
array(
[
'label' => _('Select Days:'),
'required' => false,
'multiOptions' => array(
"0" => _("Sun"),
"1" => _("Mon"),
"2" => _("Tue"),
"3" => _("Wed"),
"4" => _("Thu"),
"5" => _("Fri"),
"6" => _("Sat"),
),
));
'multiOptions' => [
'0' => _('Sun'),
'1' => _('Mon'),
'2' => _('Tue'),
'3' => _('Wed'),
'4' => _('Thu'),
'5' => _('Fri'),
'6' => _('Sat'),
],
]
);
$repeatMonthlyType = new Zend_Form_Element_Radio("add_show_monthly_repeat_type");
$repeatMonthlyType
->setLabel(_("Repeat By:"))
->setRequired(true)
->setMultiOptions(
array(2 => _("day of the month"), 3 => _("day of the week")))
->setValue(2);
$this->addElement($repeatMonthlyType);
$repeatMonthlyType = new Zend_Form_Element_Radio('add_show_monthly_repeat_type');
$repeatMonthlyType
->setLabel(_('Repeat By:'))
->setRequired(true)
->setMultiOptions(
[2 => _('day of the month'), 3 => _('day of the week')]
)
->setValue(2)
;
$this->addElement($repeatMonthlyType);
// Add end date element
$this->addElement('text', 'add_show_end_date', array(
'label' => _('Date End:'),
'class' => 'input_text',
'value' => date("Y-m-d"),
'required' => false,
'filters' => array('StringTrim'),
'validators' => array(
$this->addElement('text', 'add_show_end_date', [
'label' => _('Date End:'),
'class' => 'input_text',
'value' => date('Y-m-d'),
'required' => false,
'filters' => ['StringTrim'],
'validators' => [
'NotEmpty',
array('date', false, array('YYYY-MM-DD'))
)
));
['date', false, ['YYYY-MM-DD']],
],
]);
// Add no end element
$this->addElement('checkbox', 'add_show_no_end', array(
'label' => _('No End?'),
'required' => false,
$this->addElement('checkbox', 'add_show_no_end', [
'label' => _('No End?'),
'required' => false,
'checked' => true,
));
]);
}
public function disable()
@ -77,17 +78,18 @@ class Application_Form_AddShowRepeats extends Zend_Form_SubForm
$elements = $this->getElements();
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
$element->setAttrib('disabled','disabled');
$element->setAttrib('disabled', 'disabled');
}
}
}
public function isValid($formData) {
if (parent::isValid($formData)) {
public function isValid($formData)
{
if (parent::isValid($formData)) {
return $this->checkReliantFields($formData);
} else {
return false;
}
return false;
}
public function checkReliantFields($formData)
@ -96,24 +98,25 @@ class Application_Form_AddShowRepeats extends Zend_Form_SubForm
$start_timestamp = $formData['add_show_start_date'];
$end_timestamp = $formData['add_show_end_date'];
$showTimeZone = new DateTimeZone($formData['add_show_timezone']);
//We're assuming all data is valid at this point (timezone, etc.).
$startDate = new DateTime($start_timestamp, $showTimeZone);
$endDate = new DateTime($end_timestamp, $showTimeZone);
if ($endDate < $startDate) {
$this->getElement('add_show_end_date')->setErrors(array(_('End date must be after start date')));
$this->getElement('add_show_end_date')->setErrors([_('End date must be after start date')]);
return false;
}
return true;
}
if (!isset($formData['add_show_day_check'])) {
$this->getElement('add_show_day_check')->setErrors(array(_('Please select a repeat day')));
$this->getElement('add_show_day_check')->setErrors([_('Please select a repeat day')]);
}
return true;
}
}

View File

@ -4,102 +4,103 @@ require_once 'customfilters/ImageSize.php';
class Application_Form_AddShowStyle extends Zend_Form_SubForm
{
public function init()
{
// Add show background-color input
$this->addElement('text', 'add_show_background_color', array(
'label' => _('Background Colour:'),
'class' => 'input_text',
'filters' => array('StringTrim')
));
// Add show background-color input
$this->addElement('text', 'add_show_background_color', [
'label' => _('Background Colour:'),
'class' => 'input_text',
'filters' => ['StringTrim'],
]);
$bg = $this->getElement('add_show_background_color');
$bg->setDecorators(array(array('ViewScript', array(
$bg->setDecorators([['ViewScript', [
'viewScript' => 'form/add-show-style.phtml',
'class' => 'big'
))));
'class' => 'big',
]]]);
$stringLengthValidator = Application_Form_Helper_ValidationTypes::overrideStringLengthValidator(6, 6);
$bg->setValidators(array(
'Hex', $stringLengthValidator
));
$bg->setValidators([
'Hex', $stringLengthValidator,
]);
// Add show color input
$this->addElement('text', 'add_show_color', array(
'label' => _('Text Colour:'),
'class' => 'input_text',
'filters' => array('StringTrim')
));
// Add show color input
$this->addElement('text', 'add_show_color', [
'label' => _('Text Colour:'),
'class' => 'input_text',
'filters' => ['StringTrim'],
]);
$c = $this->getElement('add_show_color');
$c->setDecorators(array(array('ViewScript', array(
$c->setDecorators([['ViewScript', [
'viewScript' => 'form/add-show-style.phtml',
'class' => 'big'
))));
'class' => 'big',
]]]);
$c->setValidators([
'Hex', $stringLengthValidator,
]);
$c->setValidators(array(
'Hex', $stringLengthValidator
));
// Show the current logo
$this->addElement('image', 'add_show_logo_current', array(
'label' => _('Current Logo:'),
));
$this->addElement('image', 'add_show_logo_current', [
'label' => _('Current Logo:'),
]);
$logo = $this->getElement('add_show_logo_current');
$logo->setDecorators(array(
array('ViewScript', array(
'viewScript' => 'form/add-show-style.phtml',
'class' => 'big'
))
));
$logo->setDecorators([
['ViewScript', [
'viewScript' => 'form/add-show-style.phtml',
'class' => 'big',
]],
]);
// Since we need to use a Zend_Form_Element_Image proto, disable it
$logo->setAttrib('disabled','disabled');
$logo->setAttrib('disabled', 'disabled');
// Button to remove the current logo
$this->addElement('button', 'add_show_logo_current_remove', array(
'label' => '<span class="ui-button-text">' . _('Remove') . '</span>',
'class' => 'ui-button ui-state-default ui-button-text-only',
'escape' => false
));
$this->addElement('button', 'add_show_logo_current_remove', [
'label' => '<span class="ui-button-text">' . _('Remove') . '</span>',
'class' => 'ui-button ui-state-default ui-button-text-only',
'escape' => false,
]);
// Add show image input
$upload = new Zend_Form_Element_File('add_show_logo');
$upload->setLabel(_('Show Logo:'))
->setRequired(false)
->setDecorators(array('File', array('ViewScript', array(
'viewScript' => 'form/add-show-style.phtml',
'class' => 'big',
'placement' => false
))))
->addValidator('Count', false, 1)
->addValidator('Extension', false, 'jpg,jpeg,png,gif')
->addFilter('ImageSize');
->setRequired(false)
->setDecorators(['File', ['ViewScript', [
'viewScript' => 'form/add-show-style.phtml',
'class' => 'big',
'placement' => false,
]]])
->addValidator('Count', false, 1)
->addValidator('Extension', false, 'jpg,jpeg,png,gif')
->addFilter('ImageSize')
;
$this->addElement($upload);
// Add image preview
$this->addElement('image', 'add_show_logo_preview', array(
'label' => _('Logo Preview:'),
));
$this->addElement('image', 'add_show_logo_preview', [
'label' => _('Logo Preview:'),
]);
$preview = $this->getElement('add_show_logo_preview');
$preview->setDecorators(array(array('ViewScript', array(
'viewScript' => 'form/add-show-style.phtml',
'class' => 'big'
))));
$preview->setAttrib('disabled','disabled');
$preview->setDecorators([['ViewScript', [
'viewScript' => 'form/add-show-style.phtml',
'class' => 'big',
]]]);
$preview->setAttrib('disabled', 'disabled');
$csrf_namespace = new Zend_Session_Namespace('csrf_namespace');
$csrf_element = new Zend_Form_Element_Hidden('csrf');
$csrf_element->setValue($csrf_namespace->authtoken)
->setRequired('true')
->removeDecorator('HtmlTag')
->removeDecorator('Label');
->removeDecorator('Label')
;
$this->addElement($csrf_element);
}
@ -110,14 +111,14 @@ class Application_Form_AddShowStyle extends Zend_Form_SubForm
if ($element->getType() != 'Zend_Form_Element_Hidden'
// We should still be able to remove the show logo
&& $element->getName() != 'add_show_logo_current_remove') {
$element->setAttrib('disabled','disabled');
$element->setAttrib('disabled', 'disabled');
}
}
}
public function hideShowLogo() {
public function hideShowLogo()
{
$this->removeElement('add_show_logo');
$this->removeElement('add_show_logo_preview');
}
}

View File

@ -11,78 +11,78 @@ class Application_Form_AddShowWhat extends Zend_Form_SubForm
// Hidden element to indicate whether the show is new or
// whether we are updating an existing show.
$this->addElement('hidden', 'add_show_id', array(
'decorators' => array('ViewHelper')
));
$this->addElement('hidden', 'add_show_id', [
'decorators' => ['ViewHelper'],
]);
// Hidden element to indicate the instance id of the show
// being edited.
$this->addElement('hidden', 'add_show_instance_id', array(
'decorators' => array('ViewHelper')
));
$this->addElement('hidden', 'add_show_instance_id', [
'decorators' => ['ViewHelper'],
]);
// Add name element
$this->addElement('text', 'add_show_name', array(
'label' => _('Name:'),
'class' => 'input_text',
'required' => true,
'filters' => array('StringTrim'),
'value' => _('Untitled Show'),
'validators' => array($notEmptyValidator, array('StringLength', false, array(0, $maxLens['name'])))
));
$this->addElement('text', 'add_show_name', [
'label' => _('Name:'),
'class' => 'input_text',
'required' => true,
'filters' => ['StringTrim'],
'value' => _('Untitled Show'),
'validators' => [$notEmptyValidator, ['StringLength', false, [0, $maxLens['name']]]],
]);
// Add URL element
$this->addElement('text', 'add_show_url', array(
'label' => _('URL:'),
'class' => 'input_text',
'required' => false,
'filters' => array('StringTrim'),
'validators' => array($notEmptyValidator, array('StringLength', false, array(0, $maxLens['url'])))
));
// Add URL element
$this->addElement('text', 'add_show_url', [
'label' => _('URL:'),
'class' => 'input_text',
'required' => false,
'filters' => ['StringTrim'],
'validators' => [$notEmptyValidator, ['StringLength', false, [0, $maxLens['url']]]],
]);
// Add genre element
$this->addElement('text', 'add_show_genre', array(
'label' => _('Genre:'),
'class' => 'input_text',
'required' => false,
'filters' => array('StringTrim'),
'validators' => array(array('StringLength', false, array(0, $maxLens['genre'])))
));
// Add genre element
$this->addElement('text', 'add_show_genre', [
'label' => _('Genre:'),
'class' => 'input_text',
'required' => false,
'filters' => ['StringTrim'],
'validators' => [['StringLength', false, [0, $maxLens['genre']]]],
]);
// Add the description element
$this->addElement('textarea', 'add_show_description', array(
'label' => _('Description:'),
'required' => false,
'class' => 'input_text_area',
'validators' => array(array('StringLength', false, array(0, $maxLens['description'])))
));
// Add the description element
$this->addElement('textarea', 'add_show_description', [
'label' => _('Description:'),
'required' => false,
'class' => 'input_text_area',
'validators' => [['StringLength', false, [0, $maxLens['description']]]],
]);
$descText = $this->getElement('add_show_description');
$descText->setDecorators(array(array('ViewScript', array(
$descText->setDecorators([['ViewScript', [
'viewScript' => 'form/add-show-block.phtml',
'class' => 'block-display'
))));
'class' => 'block-display',
]]]);
// Add the instance description
$this->addElement('textarea', 'add_show_instance_description', array(
'label' => _('Instance Description:'),
'required' => false,
'class' => 'input_text_area',
'validators' => array(array('StringLength', false, array(0, $maxLens['description'])))
));
$this->addElement('textarea', 'add_show_instance_description', [
'label' => _('Instance Description:'),
'required' => false,
'class' => 'input_text_area',
'validators' => [['StringLength', false, [0, $maxLens['description']]]],
]);
$instanceDesc = $this->getElement('add_show_instance_description');
$instanceDesc->setDecorators(array(array('ViewScript', array(
'viewScript' => 'form/add-show-block.phtml',
'class' => 'block-display'
))));
$instanceDesc->setAttrib('disabled','disabled');
$instanceDesc->setDecorators([['ViewScript', [
'viewScript' => 'form/add-show-block.phtml',
'class' => 'block-display',
]]]);
$instanceDesc->setAttrib('disabled', 'disabled');
}
/**
* Enable the instance description when editing a show instance
* Enable the instance description when editing a show instance.
*/
public function enableInstanceDesc()
{
@ -97,7 +97,7 @@ class Application_Form_AddShowWhat extends Zend_Form_SubForm
$elements = $this->getElements();
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
$element->setAttrib('disabled','disabled');
$element->setAttrib('disabled', 'disabled');
}
}
}
@ -107,7 +107,7 @@ class Application_Form_AddShowWhat extends Zend_Form_SubForm
$elements = $this->getElements();
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
$element->setAttrib('readonly','readonly');
$element->setAttrib('readonly', 'readonly');
}
}
}

View File

@ -2,45 +2,45 @@
class Application_Form_AddShowWhen extends Zend_Form_SubForm
{
public function init()
{
$this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/add-show-when.phtml'))
));
$this->setDecorators([
['ViewScript', ['viewScript' => 'form/add-show-when.phtml']],
]);
$notEmptyValidator = Application_Form_Helper_ValidationTypes::overrideNotEmptyValidator();
$dateValidator = Application_Form_Helper_ValidationTypes::overrrideDateValidator("YYYY-MM-DD");
$dateValidator = Application_Form_Helper_ValidationTypes::overrrideDateValidator('YYYY-MM-DD');
$regexValidator = Application_Form_Helper_ValidationTypes::overrideRegexValidator(
"/^[0-2]?[0-9]:[0-5][0-9]$/",
_("'%value%' does not fit the time format 'HH:mm'"));
'/^[0-2]?[0-9]:[0-5][0-9]$/',
_("'%value%' does not fit the time format 'HH:mm'")
);
// Add start date element
$startNow = new Zend_Form_Element_Radio('add_show_start_now');
$startNow->setRequired(false)
->setLabel(_('Start Time:'))
->addMultiOptions(array(
->addMultiOptions([
'now' => _('Now'),
'future' => _('In the Future:')
))
'future' => _('In the Future:'),
])
->setValue('future')
->setDecorators(array('ViewHelper'));
->setDecorators(['ViewHelper'])
;
//$startDate->setAttrib('alt', 'date');
$this->addElement($startNow);
// Add start date element
$startDate = new Zend_Form_Element_Text('add_show_start_date');
$startDate->class = 'input_text';
$startDate->setRequired(true)
->setLabel(_('In the Future:'))
->setValue(date("Y-m-d"))
->setFilters(array('StringTrim'))
->setValidators(array(
$notEmptyValidator,
$dateValidator))
->setDecorators(array('ViewHelper'));
->setLabel(_('In the Future:'))
->setValue(date('Y-m-d'))
->setFilters(['StringTrim'])
->setValidators([
$notEmptyValidator,
$dateValidator, ])
->setDecorators(['ViewHelper'])
;
$startDate->setAttrib('alt', 'date');
$this->addElement($startDate);
@ -48,12 +48,12 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
$startTime = new Zend_Form_Element_Text('add_show_start_time');
$startTime->class = 'input_text';
$startTime->setRequired(true)
->setValue('00:00')
->setFilters(array('StringTrim'))
->setValidators(array(
$notEmptyValidator,
$regexValidator
))->setDecorators(array('ViewHelper'));
->setValue('00:00')
->setFilters(['StringTrim'])
->setValidators([
$notEmptyValidator,
$regexValidator,
])->setDecorators(['ViewHelper']);
$startTime->setAttrib('alt', 'time');
$this->addElement($startTime);
@ -61,13 +61,14 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
$endDate = new Zend_Form_Element_Text('add_show_end_date_no_repeat');
$endDate->class = 'input_text';
$endDate->setRequired(true)
->setLabel(_('End Time:'))
->setValue(date("Y-m-d"))
->setFilters(array('StringTrim'))
->setValidators(array(
$notEmptyValidator,
$dateValidator))
->setDecorators(array('ViewHelper'));
->setLabel(_('End Time:'))
->setValue(date('Y-m-d'))
->setFilters(['StringTrim'])
->setValidators([
$notEmptyValidator,
$dateValidator, ])
->setDecorators(['ViewHelper'])
;
$endDate->setAttrib('alt', 'date');
$this->addElement($endDate);
@ -75,76 +76,87 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
$endTime = new Zend_Form_Element_Text('add_show_end_time');
$endTime->class = 'input_text';
$endTime->setRequired(true)
->setValue('01:00')
->setFilters(array('StringTrim'))
->setValidators(array(
$notEmptyValidator,
$regexValidator))
->setDecorators(array('ViewHelper'));
->setValue('01:00')
->setFilters(['StringTrim'])
->setValidators([
$notEmptyValidator,
$regexValidator, ])
->setDecorators(['ViewHelper'])
;
$endTime->setAttrib('alt', 'time');
$this->addElement($endTime);
// Add duration element
$this->addElement('text', 'add_show_duration', array(
'label' => _('Duration:'),
'class' => 'input_text',
'value' => '01h 00m',
'readonly' => true,
'decorators' => array('ViewHelper')
));
$this->addElement('text', 'add_show_duration', [
'label' => _('Duration:'),
'class' => 'input_text',
'value' => '01h 00m',
'readonly' => true,
'decorators' => ['ViewHelper'],
]);
$timezone = new Zend_Form_Element_Select('add_show_timezone');
$timezone->setRequired(true)
->setLabel(_("Timezone:"))
->setMultiOptions(Application_Common_Timezone::getTimezones())
->setValue(Application_Model_Preference::GetUserTimezone())
->setAttrib('class', 'input_select add_show_input_select')
->setDecorators(array('ViewHelper'));
->setLabel(_('Timezone:'))
->setMultiOptions(Application_Common_Timezone::getTimezones())
->setValue(Application_Model_Preference::GetUserTimezone())
->setAttrib('class', 'input_select add_show_input_select')
->setDecorators(['ViewHelper'])
;
$this->addElement($timezone);
// Add repeats element
$this->addElement('checkbox', 'add_show_repeats', array(
'label' => _('Repeats?'),
'required' => false,
'decorators' => array('ViewHelper')
));
$this->addElement('checkbox', 'add_show_repeats', [
'label' => _('Repeats?'),
'required' => false,
'decorators' => ['ViewHelper'],
]);
}
public function isWhenFormValid($formData, $validateStartDate, $originalStartDate,
$update, $instanceId) {
public function isWhenFormValid(
$formData,
$validateStartDate,
$originalStartDate,
$update,
$instanceId
) {
if (parent::isValid($formData)) {
return self::checkReliantFields($formData, $validateStartDate,
$originalStartDate, $update, $instanceId);
} else {
return false;
return self::checkReliantFields(
$formData,
$validateStartDate,
$originalStartDate,
$update,
$instanceId
);
}
return false;
}
public function checkReliantFields($formData, $validateStartDate, $originalStartDate=null, $update=false, $instanceId=null)
public function checkReliantFields($formData, $validateStartDate, $originalStartDate = null, $update = false, $instanceId = null)
{
$valid = true;
$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'];
$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'];
//have to use the timezone the user has entered in the form to check past/present
$showTimezone = new DateTimeZone($formData["add_show_timezone"]);
$nowDateTime = new DateTime("now", $showTimezone);
$showTimezone = new DateTimeZone($formData['add_show_timezone']);
$nowDateTime = new DateTime('now', $showTimezone);
$showStartDateTime = new DateTime($start_time, $showTimezone);
$showEndDateTime = new DateTime($end_time, $showTimezone);
if ($validateStartDate && ($formData['add_show_start_now'] != "now")) {
if ($validateStartDate && ($formData['add_show_start_now'] != 'now')) {
if ($showStartDateTime < $nowDateTime) {
$this->getElement('add_show_start_time')->setErrors(array(_('Cannot create show in the past')));
$this->getElement('add_show_start_time')->setErrors([_('Cannot create show in the past')]);
$valid = false;
}
// if edit action, check if original show start time is in the past. CC-3864
if ($originalStartDate) {
if ($originalStartDate < $nowDateTime) {
$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_time')->setErrors(array(_('Cannot modify start date/time of the show that is already started')));
$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_time')->setErrors([_('Cannot modify start date/time of the show that is already started')]);
$this->disableStartDateAndTime();
$valid = false;
}
@ -153,7 +165,7 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
// if end time is in the past, return error
if ($showEndDateTime < $nowDateTime) {
$this->getElement('add_show_end_time')->setErrors(array(_('End date/time cannot be in the past')));
$this->getElement('add_show_end_time')->setErrors([_('End date/time cannot be in the past')]);
$valid = false;
}
@ -161,75 +173,71 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
$duration = $showStartDateTime->diff($showEndDateTime);
if ($showStartDateTime > $showEndDateTime) {
$this->getElement('add_show_duration')->setErrors(array(_('Cannot have duration < 0m')));
$valid = false;
$this->getElement('add_show_duration')->setErrors([_('Cannot have duration < 0m')]);
$valid = false;
} elseif ($showStartDateTime == $showEndDateTime) {
$this->getElement('add_show_duration')->setErrors([_('Cannot have duration 00h 00m')]);
$valid = false;
} elseif (intval($duration->format('%d')) > 0
&& (intval($duration->format('%h')) > 0
|| intval($duration->format('%i')) > 0
|| intval($duration->format('%s')) > 0)) {
$this->getElement('add_show_duration')->setErrors([_('Cannot have duration greater than 24h')]);
$valid = false;
}
else if ($showStartDateTime == $showEndDateTime) {
$this->getElement('add_show_duration')->setErrors(array(_('Cannot have duration 00h 00m')));
$valid = false;
}
else if (intval($duration->format('%d')) > 0 &&
(intval($duration->format('%h')) > 0
|| intval($duration->format('%i')) > 0
|| intval($duration->format('%s')) > 0)) {
$this->getElement('add_show_duration')->setErrors(array(_('Cannot have duration greater than 24h')));
$valid = false;
}
/* We need to know the show duration broken down into hours and minutes
* They are used for checking overlapping shows and for validating
* rebroadcast instances
*/
$hours = $duration->format("%h");
$minutes = $duration->format("%i");
$hours = $duration->format('%h');
$minutes = $duration->format('%i');
/* Check if show is overlapping
* We will only do this check if the show is valid
* upto this point
*/
if ($valid) {
//we need to know the start day of the week in show's local timezome
$startDow = $showStartDateTime->format("w");
//we need to know the start day of the week in show's local timezome
$startDow = $showStartDateTime->format('w');
$utc = new DateTimeZone('UTC');
$showStartDateTime->setTimezone($utc);
$showEndDateTime->setTimezone($utc);
if ($formData["add_show_repeats"]) {
if ($formData['add_show_repeats']) {
//get repeating show end date
if ($formData["add_show_no_end"]) {
if ($formData['add_show_no_end']) {
$date = Application_Model_Preference::GetShowsPopulatedUntil();
if (is_null($date)) {
$populateUntilDateTime = new DateTime("now", $utc);
$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"];
} elseif (!$formData['add_show_no_end']) {
$popUntil = $formData['add_show_end_date'] . ' ' . $formData['add_show_end_time'];
$populateUntilDateTime = new DateTime($popUntil, $showTimezone);
$populateUntilDateTime->setTimezone($utc);
}
//get repeat interval
if ($formData["add_show_repeat_type"] == 0) {
if ($formData['add_show_repeat_type'] == 0) {
$interval = 'P7D';
} elseif ($formData["add_show_repeat_type"] == 1) {
} elseif ($formData['add_show_repeat_type'] == 1) {
$interval = 'P14D';
} elseif ($formData["add_show_repeat_type"] == 4) {
} elseif ($formData['add_show_repeat_type'] == 4) {
$interval = 'P21D';
} elseif ($formData["add_show_repeat_type"] == 5) {
} elseif ($formData['add_show_repeat_type'] == 5) {
$interval = 'P28D';
} elseif ($formData["add_show_repeat_type"] == 2 && $formData["add_show_monthly_repeat_type"] == 2) {
} elseif ($formData['add_show_repeat_type'] == 2 && $formData['add_show_monthly_repeat_type'] == 2) {
$interval = 'P1M';
} elseif ($formData["add_show_repeat_type"] == 2 && $formData["add_show_monthly_repeat_type"] == 3) {
} elseif ($formData['add_show_repeat_type'] == 2 && $formData['add_show_monthly_repeat_type'] == 3) {
list($weekNumberOfMonth, $dayOfWeek) =
Application_Service_ShowService::getMonthlyWeeklyRepeatInterval(
new DateTime($start_time, $showTimezone));
new DateTime($start_time, $showTimezone)
);
}
/* Check first show
@ -237,30 +245,37 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
*/
if ($update) {
$overlapping = Application_Model_Schedule::checkOverlappingShows(
$showStartDateTime, $showEndDateTime, $update, null, $formData["add_show_id"]);
$showStartDateTime,
$showEndDateTime,
$update,
null,
$formData['add_show_id']
);
} else {
$overlapping = Application_Model_Schedule::checkOverlappingShows(
$showStartDateTime, $showEndDateTime);
$showStartDateTime,
$showEndDateTime
);
}
/* Check if repeats overlap with previously scheduled shows
* Do this for each show day
*/
if (!$overlapping) {
if (!isset($formData['add_show_day_check'])) {
return false;
}
foreach ($formData["add_show_day_check"] as $day) {
foreach ($formData['add_show_day_check'] as $day) {
$repeatShowStart = clone $showStartDateTime;
$repeatShowEnd = clone $showEndDateTime;
$daysAdd=0;
$daysAdd = 0;
if ($startDow !== $day) {
if ($startDow > $day)
if ($startDow > $day) {
$daysAdd = 6 - $startDow + 1 + $day;
else
} 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
@ -268,8 +283,8 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
*/
$repeatShowStart->setTimezone($showTimezone);
$repeatShowEnd->setTimezone($showTimezone);
$repeatShowStart->add(new DateInterval("P".$daysAdd."D"));
$repeatShowEnd->add(new DateInterval("P".$daysAdd."D"));
$repeatShowStart->add(new DateInterval('P' . $daysAdd . 'D'));
$repeatShowEnd->add(new DateInterval('P' . $daysAdd . 'D'));
//set back to UTC
$repeatShowStart->setTimezone($utc);
$repeatShowEnd->setTimezone($utc);
@ -282,49 +297,58 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
if ($formData['add_show_id'] == -1) {
//this is a new show
$overlapping = Application_Model_Schedule::checkOverlappingShows(
$repeatShowStart, $repeatShowEnd);
$repeatShowStart,
$repeatShowEnd
);
} else {
$overlapping = Application_Model_Schedule::checkOverlappingShows(
$repeatShowStart, $repeatShowEnd, $update, null, $formData["add_show_id"]);
$repeatShowStart,
$repeatShowEnd,
$update,
null,
$formData['add_show_id']
);
}
if ($overlapping) {
$valid = false;
$this->getElement('add_show_duration')->setErrors(array(_('Cannot schedule overlapping shows')));
break 1;
$this->getElement('add_show_duration')->setErrors([_('Cannot schedule overlapping shows')]);
break;
}
if ($formData['add_show_repeat_type'] == 2 && $formData['add_show_monthly_repeat_type'] == 3) {
$monthlyWeeklyStart = new DateTime(
$repeatShowStart->format('Y-m'),
new DateTimeZone('UTC')
);
$monthlyWeeklyStart->add(new DateInterval('P1M'));
$repeatShowStart = clone Application_Service_ShowService::getNextMonthlyWeeklyRepeatDate(
$monthlyWeeklyStart,
$formData['add_show_timezone'],
$formData['add_show_start_time'],
$weekNumberOfMonth,
$dayOfWeek
);
$repeatShowEnd = clone $repeatShowStart;
$repeatShowEnd->add(new DateInterval('PT' . $hours . 'H' . $minutes . 'M'));
} else {
if ($formData["add_show_repeat_type"] == 2 && $formData["add_show_monthly_repeat_type"] == 3) {
$monthlyWeeklyStart = new DateTime($repeatShowStart->format("Y-m"),
new DateTimeZone("UTC"));
$monthlyWeeklyStart->add(new DateInterval("P1M"));
$repeatShowStart = clone Application_Service_ShowService::getNextMonthlyWeeklyRepeatDate(
$monthlyWeeklyStart,
$formData["add_show_timezone"],
$formData['add_show_start_time'],
$weekNumberOfMonth,
$dayOfWeek);
$repeatShowEnd = clone $repeatShowStart;
$repeatShowEnd->add(new DateInterval("PT".$hours."H".$minutes."M"));
} else {
$repeatShowStart->setTimezone($showTimezone);
$repeatShowEnd->setTimezone($showTimezone);
$repeatShowStart->add(new DateInterval($interval));
$repeatShowEnd->add(new DateInterval($interval));
$repeatShowStart->setTimezone($utc);
$repeatShowEnd->setTimezone($utc);
}
$repeatShowStart->setTimezone($showTimezone);
$repeatShowEnd->setTimezone($showTimezone);
$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')));
$this->getElement('add_show_duration')->setErrors([_('Cannot schedule overlapping shows')]);
}
} else {
$overlapping = Application_Model_Schedule::checkOverlappingShows($showStartDateTime, $showEndDateTime, $update, $instanceId);
$overlapping = Application_Model_Schedule::checkOverlappingShows($showStartDateTime, $showEndDateTime, $update, $instanceId);
if ($overlapping) {
$this->getElement('add_show_duration')->setErrors(array(_('Cannot schedule overlapping shows')));
$this->getElement('add_show_duration')->setErrors([_('Cannot schedule overlapping shows')]);
$valid = false;
}
}
@ -333,34 +357,47 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
return $valid;
}
public function checkRebroadcastDates($repeatShowStart, $formData, $hours, $minutes, $showEdit=false) {
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;
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(
$formData["add_show_timezone"]));
$rebroadcastWhenDays = explode(" ", $formData["add_show_rebroadcast_date_".$i]);
$rebroadcastWhenTime = explode(":", $formData["add_show_rebroadcast_time_".$i]);
$rebroadcastShowStart->add(new DateInterval("P".$rebroadcastWhenDays[0]."D"));
$formData['add_show_timezone']
));
$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"));
$rebroadcastShowEnd->add(new DateInterval('PT' . $hours . 'H' . $minutes . 'M'));
if ($showEdit) {
$overlapping = Application_Model_Schedule::checkOverlappingShows(
$rebroadcastShowStart, $rebroadcastShowEnd, true, null, $formData['add_show_id']);
$rebroadcastShowStart,
$rebroadcastShowEnd,
true,
null,
$formData['add_show_id']
);
} else {
$overlapping = Application_Model_Schedule::checkOverlappingShows(
$rebroadcastShowStart, $rebroadcastShowEnd);
$rebroadcastShowStart,
$rebroadcastShowEnd
);
}
if ($overlapping) break;
if ($overlapping) {
break;
}
}
return $overlapping;
@ -371,7 +408,7 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
$elements = $this->getElements();
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
$element->setAttrib('disabled','disabled');
$element->setAttrib('disabled', 'disabled');
}
}
}
@ -380,16 +417,16 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm
{
$element = $this->getElement('add_show_repeats');
if ($element->getType() != 'Zend_Form_Element_Hidden') {
$element->setAttrib('disabled','disabled');
$element->setAttrib('disabled', 'disabled');
}
}
public function disableStartDateAndTime()
{
$elements = array($this->getElement('add_show_start_date'), $this->getElement('add_show_start_time'));
$elements = [$this->getElement('add_show_start_date'), $this->getElement('add_show_start_time')];
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
$element->setAttrib('disabled','disabled');
$element->setAttrib('disabled', 'disabled');
}
}
}

View File

@ -2,17 +2,16 @@
class Application_Form_AddShowWho extends Zend_Form_SubForm
{
public function init()
{
// Add hosts autocomplete
$this->addElement('text', 'add_show_hosts_autocomplete', array(
'label' => _('Search Users:'),
'class' => 'input_text ui-autocomplete-input',
'required' => false
));
$this->addElement('text', 'add_show_hosts_autocomplete', [
'label' => _('Search Users:'),
'class' => 'input_text ui-autocomplete-input',
'required' => false,
]);
$options = array();
$options = [];
$hosts = Application_Model_User::getHosts();
foreach ($hosts as $host) {
@ -22,7 +21,8 @@ class Application_Form_AddShowWho extends Zend_Form_SubForm
//Add hosts selection
$hosts = new Zend_Form_Element_MultiCheckbox('add_show_hosts');
$hosts->setLabel(_('DJs:'))
->setMultiOptions($options);
->setMultiOptions($options)
;
$this->addElement($hosts);
}
@ -32,7 +32,7 @@ class Application_Form_AddShowWho extends Zend_Form_SubForm
$elements = $this->getElements();
foreach ($elements as $element) {
if ($element->getType() != 'Zend_Form_Element_Hidden') {
$element->setAttrib('disabled','disabled');
$element->setAttrib('disabled', 'disabled');
}
}
}

View File

@ -2,7 +2,6 @@
class Application_Form_AddTracktype extends Zend_Form
{
public function init()
{
$notEmptyValidator = Application_Form_Helper_ValidationTypes::overrideNotEmptyValidator();
@ -10,12 +9,12 @@ class Application_Form_AddTracktype extends Zend_Form
$this->setAttrib('id', 'tracktype_form');
$hidden = new Zend_Form_Element_Hidden('tracktype_id');
$hidden->setDecorators(array('ViewHelper'));
$hidden->setDecorators(['ViewHelper']);
$this->addElement($hidden);
$this->addElement('hash', 'csrf', array(
'salt' => 'unique'
));
$this->addElement('hash', 'csrf', [
'salt' => 'unique',
]);
$typeName = new Zend_Form_Element_Text('type_name');
$typeName->setLabel(_('Type Name:'));
@ -34,10 +33,11 @@ class Application_Form_AddTracktype extends Zend_Form
$description = new Zend_Form_Element_Textarea('description');
$description->setLabel(_('Description:'))
->setFilters(array('StringTrim'))
->setValidators(array(
new Zend_Validate_StringLength(array('max' => 200))
));
->setFilters(['StringTrim'])
->setValidators([
new Zend_Validate_StringLength(['max' => 200]),
])
;
$description->setAttrib('class', 'input_text');
$description->addFilter('StringTrim');
$this->addElement($description);
@ -46,10 +46,10 @@ class Application_Form_AddTracktype extends Zend_Form
$visibility->setLabel(_('Visibility:'));
$visibility->setAttrib('class', 'input_select');
$visibility->setAttrib('style', 'width: 40%');
$visibility->setMultiOptions(array(
"0" => _("Disabled"),
"1" => _("Enabled")
));
$visibility->setMultiOptions([
'0' => _('Disabled'),
'1' => _('Enabled'),
]);
//$visibility->getValue();
$visibility->setRequired(true);
$this->addElement($visibility);
@ -67,7 +67,7 @@ class Application_Form_AddTracktype extends Zend_Form
$count = CcTracktypesQuery::create()->filterByDbCode($data['code'])->count();
if ($count != 0) {
$this->getElement('code')->setErrors(array(_("Code is not unique.")));
$this->getElement('code')->setErrors([_('Code is not unique.')]);
return false;
}
@ -75,5 +75,4 @@ class Application_Form_AddTracktype extends Zend_Form
return true;
}
}

View File

@ -2,7 +2,6 @@
class Application_Form_AddUser extends Zend_Form
{
public function init()
{
/*
@ -13,16 +12,16 @@ class Application_Form_AddUser extends Zend_Form
$notEmptyValidator = Application_Form_Helper_ValidationTypes::overrideNotEmptyValidator();
$emailValidator = Application_Form_Helper_ValidationTypes::overrideEmailAddressValidator();
$notDemoValidator = new Application_Validate_NotDemoValidate();
$this->setAttrib('id', 'user_form');
$hidden = new Zend_Form_Element_Hidden('user_id');
$hidden->setDecorators(array('ViewHelper'));
$hidden->setDecorators(['ViewHelper']);
$this->addElement($hidden);
$this->addElement('hash', 'csrf', array(
'salt' => 'unique'
));
$this->addElement('hash', 'csrf', [
'salt' => 'unique',
]);
$login = new Zend_Form_Element_Text('login');
$login->setLabel(_('Username:'));
@ -94,12 +93,12 @@ class Application_Form_AddUser extends Zend_Form
$select->setLabel(_('User Type:'));
$select->setAttrib('class', 'input_select');
$select->setAttrib('style', 'width: 40%');
$select->setMultiOptions(array(
"G" => _("Guest"),
"H" => _("DJ"),
"P" => _("Program Manager"),
"A" => _("Admin"),
));
$select->setMultiOptions([
'G' => _('Guest'),
'H' => _('DJ'),
'P' => _('Program Manager'),
'A' => _('Admin'),
]);
$select->setRequired(false);
$this->addElement($select);
@ -116,7 +115,7 @@ class Application_Form_AddUser extends Zend_Form
$count = CcSubjsQuery::create()->filterByDbLogin($data['login'])->count();
if ($count != 0) {
$this->getElement('login')->setErrors(array(_("Login name is not unique.")));
$this->getElement('login')->setErrors([_('Login name is not unique.')]);
return false;
}
@ -127,10 +126,13 @@ class Application_Form_AddUser extends Zend_Form
// We need to add the password identical validator here in case
// Zend version is less than 1.10.5
public function isValid($data) {
public function isValid($data)
{
$passwordIdenticalValidator = Application_Form_Helper_ValidationTypes::overridePasswordIdenticalValidator(
$data['password']);
$data['password']
);
$this->getElement('passwordVerify')->addValidator($passwordIdenticalValidator);
return parent::isValid($data);
}
}

View File

@ -1,21 +1,20 @@
<?php
class Application_Form_DangerousPreferences extends Zend_Form_SubForm {
public function init() {
$this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/preferences_danger.phtml'))
));
class Application_Form_DangerousPreferences extends Zend_Form_SubForm
{
public function init()
{
$this->setDecorators([
['ViewScript', ['viewScript' => 'form/preferences_danger.phtml']],
]);
$clearLibrary = new Zend_Form_Element_Button('clear_library');
$clearLibrary->setLabel(_('Delete All Tracks in Library'));
//$submit->removeDecorator('Label');
$clearLibrary->setAttribs(array('class'=>'btn centered'));
$clearLibrary->setAttribs(['class' => 'btn centered']);
$clearLibrary->setAttrib('onclick', 'deleteAllFiles();');
$clearLibrary->removeDecorator('DtDdWrapper');
$this->addElement($clearLibrary);
}
}

View File

@ -2,24 +2,24 @@
class Application_Form_DateRange extends Zend_Form_SubForm
{
public function init()
{
$this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/daterange.phtml'))
));
$this->setDecorators([
['ViewScript', ['viewScript' => 'form/daterange.phtml']],
]);
// Add start date element
$startDate = new Zend_Form_Element_Text('his_date_start');
$startDate->class = 'input_text';
$startDate->setRequired(true)
->setLabel(_('Date Start:'))
->setValue(date("Y-m-d"))
->setFilters(array('StringTrim'))
->setValidators(array(
'NotEmpty',
array('date', false, array('YYYY-MM-DD'))))
->setDecorators(array('ViewHelper'));
->setLabel(_('Date Start:'))
->setValue(date('Y-m-d'))
->setFilters(['StringTrim'])
->setValidators([
'NotEmpty',
['date', false, ['YYYY-MM-DD']], ])
->setDecorators(['ViewHelper'])
;
$startDate->setAttrib('alt', 'date');
$this->addElement($startDate);
@ -27,13 +27,14 @@ class Application_Form_DateRange extends Zend_Form_SubForm
$startTime = new Zend_Form_Element_Text('his_time_start');
$startTime->class = 'input_text';
$startTime->setRequired(true)
->setValue('00:00')
->setFilters(array('StringTrim'))
->setValidators(array(
'NotEmpty',
array('date', false, array('HH:mm')),
array('regex', false, array('/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')))))
->setDecorators(array('ViewHelper'));
->setValue('00:00')
->setFilters(['StringTrim'])
->setValidators([
'NotEmpty',
['date', false, ['HH:mm']],
['regex', false, ['/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')]], ])
->setDecorators(['ViewHelper'])
;
$startTime->setAttrib('alt', 'time');
$this->addElement($startTime);
@ -41,13 +42,14 @@ class Application_Form_DateRange extends Zend_Form_SubForm
$endDate = new Zend_Form_Element_Text('his_date_end');
$endDate->class = 'input_text';
$endDate->setRequired(true)
->setLabel(_('Date End:'))
->setValue(date("Y-m-d"))
->setFilters(array('StringTrim'))
->setValidators(array(
'NotEmpty',
array('date', false, array('YYYY-MM-DD'))))
->setDecorators(array('ViewHelper'));
->setLabel(_('Date End:'))
->setValue(date('Y-m-d'))
->setFilters(['StringTrim'])
->setValidators([
'NotEmpty',
['date', false, ['YYYY-MM-DD']], ])
->setDecorators(['ViewHelper'])
;
$endDate->setAttrib('alt', 'date');
$this->addElement($endDate);
@ -55,13 +57,14 @@ class Application_Form_DateRange extends Zend_Form_SubForm
$endTime = new Zend_Form_Element_Text('his_time_end');
$endTime->class = 'input_text';
$endTime->setRequired(true)
->setValue('01:00')
->setFilters(array('StringTrim'))
->setValidators(array(
'NotEmpty',
array('date', false, array('HH:mm')),
array('regex', false, array('/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')))))
->setDecorators(array('ViewHelper'));
->setValue('01:00')
->setFilters(['StringTrim'])
->setValidators([
'NotEmpty',
['date', false, ['HH:mm']],
['regex', false, ['/^[0-2]?[0-9]:[0-5][0-9]$/', 'messages' => _('Invalid character entered')]], ])
->setDecorators(['ViewHelper'])
;
$endTime->setAttrib('alt', 'time');
$this->addElement($endTime);
}

View File

@ -2,46 +2,48 @@
class Application_Form_EditAudioMD extends Zend_Form
{
public function init() {}
public function init()
{
}
public function startForm($p_id)
{
$baseUrl = Application_Common_OsPath::getBaseDir();
// Set the method for the display form to POST
// Set the method for the display form to POST
$this->setMethod('post');
$file_id = new Zend_Form_Element_Hidden('file_id');
$file_id->setValue($p_id);
$file_id->addDecorator('HtmlTag', array('tag' => 'div', 'style' => 'display:none'));
$file_id->addDecorator('HtmlTag', ['tag' => 'div', 'style' => 'display:none']);
$file_id->removeDecorator('Label');
$file_id->setAttrib('class', 'obj_id');
$this->addElement($file_id);
// Add artwork hidden field
$artwork = new Zend_Form_Element_Hidden('artwork');
$artwork->class = 'input_text artwork_'. $p_id;
$artwork->setFilters(array('StringTrim'))
->setValidators(array(
new Zend_Validate_StringLength(array('max' => 2048))
));
$file_id->addDecorator('HtmlTag', array('tag' => 'div', 'style' => 'display:none'));
$artwork->class = 'input_text artwork_' . $p_id;
$artwork->setFilters(['StringTrim'])
->setValidators([
new Zend_Validate_StringLength(['max' => 2048]),
])
;
$file_id->addDecorator('HtmlTag', ['tag' => 'div', 'style' => 'display:none']);
$file_id->removeDecorator('Label');
$file_id->setAttrib('class', 'artwork');
$this->addElement($artwork);
// Set artwork hidden field
$set_artwork = new Zend_Form_Element_Hidden('set_artwork');
$set_artwork->class = 'input_text set_artwork_'. $p_id;
$file_id->addDecorator('HtmlTag', array('tag' => 'div', 'style' => 'display:none'));
$set_artwork->class = 'input_text set_artwork_' . $p_id;
$file_id->addDecorator('HtmlTag', ['tag' => 'div', 'style' => 'display:none']);
$file_id->removeDecorator('Label');
$file_id->setAttrib('class', 'set_artwork');
$this->addElement($set_artwork);
// Remove artwork hidden field
$remove_artwork = new Zend_Form_Element_Hidden('remove_artwork');
$remove_artwork->class = 'input_text remove_artwork_'. $p_id;
$file_id->addDecorator('HtmlTag', array('tag' => 'div', 'style' => 'display:none'));
$remove_artwork->class = 'input_text remove_artwork_' . $p_id;
$file_id->addDecorator('HtmlTag', ['tag' => 'div', 'style' => 'display:none']);
$file_id->removeDecorator('Label');
$file_id->setAttrib('class', 'remove_artwork');
$this->addElement($remove_artwork);
@ -50,35 +52,37 @@ class Application_Form_EditAudioMD extends Zend_Form
$track_title = new Zend_Form_Element_Text('track_title');
$track_title->class = 'input_text';
$track_title->setLabel(_('Title:'))
->setFilters(array('StringTrim'))
->setValidators(array(
new Zend_Validate_StringLength(array('max' => 512))
));
->setFilters(['StringTrim'])
->setValidators([
new Zend_Validate_StringLength(['max' => 512]),
])
;
$this->addElement($track_title);
// Add artist field
$artist_name = new Zend_Form_Element_Text('artist_name');
$artist_name->class = 'input_text';
$artist_name->setLabel(_('Creator:'))
->setFilters(array('StringTrim'))
->setValidators(array(
new Zend_Validate_StringLength(array('max' => 512))
));
->setFilters(['StringTrim'])
->setValidators([
new Zend_Validate_StringLength(['max' => 512]),
])
;
$this->addElement($artist_name);
// Add album field
$album_title = new Zend_Form_Element_Text('album_title');
$album_title->class = 'input_text';
$album_title->setLabel(_('Album:'))
->setFilters(array('StringTrim'))
->setValidators(array(
new Zend_Validate_StringLength(array('max' => 512))
));
->setFilters(['StringTrim'])
->setValidators([
new Zend_Validate_StringLength(['max' => 512]),
])
;
$this->addElement($album_title);
// Add album field
$user_options = array();
$user_options = [];
$users = Application_Model_User::getNonGuestUsers();
foreach ($users as $host) {
@ -92,14 +96,14 @@ class Application_Form_EditAudioMD extends Zend_Form
$this->addelement($owner_id);
// Add track type dropdown
$track_type_options = array();
$track_type_options = [];
$track_types = Application_Model_Tracktype::getTracktypes();
array_multisort(array_map(function($element) {
array_multisort(array_map(function ($element) {
return $element['type_name'];
}, $track_types), SORT_ASC, $track_types);
$track_type_options[""] = _('Select a Type');
$track_type_options[''] = _('Select a Type');
foreach ($track_types as $key => $tt) {
$track_type_options[$tt['code']] = $tt['type_name'];
}
@ -114,189 +118,204 @@ class Application_Form_EditAudioMD extends Zend_Form
$description = new Zend_Form_Element_Textarea('description');
$description->class = 'input_text';
$description->setLabel(_('Description:'))
->setFilters(array('StringTrim'))
->setValidators(array(
new Zend_Validate_StringLength(array('max' => 512))
));
->setFilters(['StringTrim'])
->setValidators([
new Zend_Validate_StringLength(['max' => 512]),
])
;
$this->addElement($description);
// Add track number field
$track_number = new Zend_Form_Element('track_number');
$track_number->class = 'input_text';
$track_number->setLabel('Track Number:')
->setFilters(array('StringTrim'))
->setValidators(array(new Zend_Validate_Int()));
->setFilters(['StringTrim'])
->setValidators([new Zend_Validate_Int()])
;
$this->addElement($track_number);
// Add genre field
$genre = new Zend_Form_Element('genre');
$genre->class = 'input_text';
$genre->setLabel(_('Genre:'))
->setFilters(array('StringTrim'))
->setValidators(array(
new Zend_Validate_StringLength(array('max' => 64))
));
->setFilters(['StringTrim'])
->setValidators([
new Zend_Validate_StringLength(['max' => 64]),
])
;
$this->addElement($genre);
// Add year field
$year = new Zend_Form_Element_Text('year');
$year->class = 'input_text';
$year->setLabel(_('Year:'))
->setFilters(array('StringTrim'))
->setValidators(array(
new Zend_Validate_StringLength(array('max' => 10)),
Application_Form_Helper_ValidationTypes::overrrideDateValidator("YYYY-MM-DD"),
Application_Form_Helper_ValidationTypes::overrrideDateValidator("YYYY-MM"),
Application_Form_Helper_ValidationTypes::overrrideDateValidator("YYYY")
));
->setFilters(['StringTrim'])
->setValidators([
new Zend_Validate_StringLength(['max' => 10]),
Application_Form_Helper_ValidationTypes::overrrideDateValidator('YYYY-MM-DD'),
Application_Form_Helper_ValidationTypes::overrrideDateValidator('YYYY-MM'),
Application_Form_Helper_ValidationTypes::overrrideDateValidator('YYYY'),
])
;
$this->addElement($year);
// Add label field
$label = new Zend_Form_Element('label');
$label->class = 'input_text';
$label->setLabel(_('Label:'))
->setFilters(array('StringTrim'))
->setValidators(array(
new Zend_Validate_StringLength(array('max' => 512))
));
->setFilters(['StringTrim'])
->setValidators([
new Zend_Validate_StringLength(['max' => 512]),
])
;
$this->addElement($label);
// Add composer field
$composer = new Zend_Form_Element('composer');
$composer->class = 'input_text';
$composer->setLabel(_('Composer:'))
->setFilters(array('StringTrim'))
->setValidators(array(
new Zend_Validate_StringLength(array('max' => 512))
));
->setFilters(['StringTrim'])
->setValidators([
new Zend_Validate_StringLength(['max' => 512]),
])
;
$this->addElement($composer);
// Add conductor field
$conductor = new Zend_Form_Element('conductor');
$conductor->class = 'input_text';
$conductor->setLabel(_('Conductor:'))
->setFilters(array('StringTrim'))
->setValidators(array(
new Zend_Validate_StringLength(array('max' => 512))
));
->setFilters(['StringTrim'])
->setValidators([
new Zend_Validate_StringLength(['max' => 512]),
])
;
$this->addElement($conductor);
// Add mood field
$mood = new Zend_Form_Element('mood');
$mood->class = 'input_text';
$mood->setLabel(_('Mood:'))
->setFilters(array('StringTrim'))
->setValidators(array(
new Zend_Validate_StringLength(array('max' => 64))
));
->setFilters(['StringTrim'])
->setValidators([
new Zend_Validate_StringLength(['max' => 64]),
])
;
$this->addElement($mood);
// Add bmp field
$bpm = new Zend_Form_Element_Text('bpm');
$bpm->class = 'input_text';
$bpm->setLabel(_('BPM:'))
->setFilters(array('StringTrim'))
->setValidators(array(
new Zend_Validate_StringLength(array('min'=>0,'max' => 8)),
new Zend_Validate_Digits()));
->setFilters(['StringTrim'])
->setValidators([
new Zend_Validate_StringLength(['min' => 0, 'max' => 8]),
new Zend_Validate_Digits(), ])
;
$this->addElement($bpm);
// Add copyright field
$copyright = new Zend_Form_Element('copyright');
$copyright->class = 'input_text';
$copyright->setLabel(_('Copyright:'))
->setFilters(array('StringTrim'))
->setValidators(array(
new Zend_Validate_StringLength(array('max' => 512))
));
->setFilters(['StringTrim'])
->setValidators([
new Zend_Validate_StringLength(['max' => 512]),
])
;
$this->addElement($copyright);
// Add isrc number field
$isrc_number = new Zend_Form_Element('isrc_number');
$isrc_number->class = 'input_text';
$isrc_number->setLabel(_('ISRC Number:'))
->setFilters(array('StringTrim'))
->setValidators(array(
new Zend_Validate_StringLength(array('max' => 512))
));
->setFilters(['StringTrim'])
->setValidators([
new Zend_Validate_StringLength(['max' => 512]),
])
;
$this->addElement($isrc_number);
// Add website field
$info_url = new Zend_Form_Element('info_url');
$info_url->class = 'input_text';
$info_url->setLabel(_('Website:'))
->setFilters(array('StringTrim'))
->setValidators(array(
new Zend_Validate_StringLength(array('max' => 512))
));
->setFilters(['StringTrim'])
->setValidators([
new Zend_Validate_StringLength(['max' => 512]),
])
;
$this->addElement($info_url);
// Add language field
$language = new Zend_Form_Element('language');
$language->class = 'input_text';
$language->setLabel(_('Language:'))
->setFilters(array('StringTrim'))
->setValidators(array(
new Zend_Validate_StringLength(array('max' => 512))
));
->setFilters(['StringTrim'])
->setValidators([
new Zend_Validate_StringLength(['max' => 512]),
])
;
$this->addElement($language);
$validCuePattern = '/^(?:[0-9]{1,2}:)?(?:[0-9]{1,2}:)?[0-9]{1,6}(\.\d{1,6})?$/';
$cueIn = new Zend_Form_Element_Text('cuein');
$cueIn->class = 'input_text';
$cueIn->setLabel("Cue In:");
$cueIn->setLabel('Cue In:');
$cueInValidator = Application_Form_Helper_ValidationTypes::overrideRegexValidator(
$validCuePattern, _(sprintf("Specify cue in time in the format %s", "(hh:mm:)ss(.dddddd)"))
$validCuePattern,
_(sprintf('Specify cue in time in the format %s', '(hh:mm:)ss(.dddddd)'))
);
$cueIn->setValidators(array($cueInValidator));
$cueIn->setValidators([$cueInValidator]);
$this->addElement($cueIn);
$cueOut = new Zend_Form_Element_Text('cueout');
$cueOut->class = 'input_text';
$cueOut->setLabel('Cue Out:');
$cueOutValidator = Application_Form_Helper_ValidationTypes::overrideRegexValidator(
$validCuePattern, _(sprintf("Specify cue out time in the format %s", "(hh:mm:)ss(.dddddd)"))
$validCuePattern,
_(sprintf('Specify cue out time in the format %s', '(hh:mm:)ss(.dddddd)'))
);
$cueOut->setValidators(array($cueOutValidator));
$cueOut->setValidators([$cueOutValidator]);
$this->addElement($cueOut);
// Add the cancel button
$this->addElement('button', 'editmdcancel', array(
'ignore' => true,
'class' => 'btn md-cancel',
'label' => _('Cancel'),
'decorators' => array(
'ViewHelper'
)
));
$this->addElement('button', 'editmdcancel', [
'ignore' => true,
'class' => 'btn md-cancel',
'label' => _('Cancel'),
'decorators' => [
'ViewHelper',
],
]);
// Add the submit button
$this->addElement('button', 'editmdsave', array(
'ignore' => true,
'class' => 'btn md-save',
'label' => _('Save'),
'decorators' => array(
'ViewHelper'
)
));
$this->addElement('button', 'editmdsave', [
'ignore' => true,
'class' => 'btn md-save',
'label' => _('Save'),
'decorators' => [
'ViewHelper',
],
]);
// Button to open the publish dialog
$this->addElement('button', 'publishdialog', array(
'ignore' => true,
'class' => 'btn md-publish',
'label' => _('Publish...'),
'decorators' => array(
'ViewHelper'
)
));
$this->addElement('button', 'publishdialog', [
'ignore' => true,
'class' => 'btn md-publish',
'label' => _('Publish...'),
'decorators' => [
'ViewHelper',
],
]);
$this->addDisplayGroup(array('publishdialog', 'editmdsave', 'editmdcancel'), 'submitButtons', array(
'decorators' => array(
$this->addDisplayGroup(['publishdialog', 'editmdsave', 'editmdcancel'], 'submitButtons', [
'decorators' => [
'FormElements',
'DtDdWrapper'
)
));
'DtDdWrapper',
],
]);
}
public function makeReadOnly()
@ -306,13 +325,14 @@ class Application_Form_EditAudioMD extends Zend_Form
}
}
public function removeOwnerEdit() {
public function removeOwnerEdit()
{
$this->removeElement('owner_id');
}
public function removeActionButtons()
{
$this->removeElement('editmdsave');
$this->removeElement('editmdcancel');
}
}

View File

@ -2,210 +2,205 @@
class Application_Form_EditHistory extends Zend_Form
{
const VALIDATE_DATETIME_FORMAT = 'yyyy-MM-dd HH:mm:ss';
//this is used by the javascript widget, unfortunately h/H is opposite from Zend.
const TIMEPICKER_DATETIME_FORMAT = 'yyyy-MM-dd hh:mm:ss';
public const VALIDATE_DATETIME_FORMAT = 'yyyy-MM-dd HH:mm:ss';
//this is used by the javascript widget, unfortunately h/H is opposite from Zend.
public const TIMEPICKER_DATETIME_FORMAT = 'yyyy-MM-dd hh:mm:ss';
const VALIDATE_DATE_FORMAT = 'yyyy-MM-dd';
const VALIDATE_TIME_FORMAT = 'HH:mm:ss';
public const VALIDATE_DATE_FORMAT = 'yyyy-MM-dd';
public const VALIDATE_TIME_FORMAT = 'HH:mm:ss';
const ITEM_TYPE = "type";
const ITEM_CLASS = "class";
const ITEM_OPTIONS = "options";
const ITEM_ID_SUFFIX = "name";
public const ITEM_TYPE = 'type';
public const ITEM_CLASS = 'class';
public const ITEM_OPTIONS = 'options';
public const ITEM_ID_SUFFIX = 'name';
const TEXT_INPUT_CLASS = "input_text";
public const TEXT_INPUT_CLASS = 'input_text';
private $formElTypes = array(
TEMPLATE_DATE => array(
"class" => "Zend_Form_Element_Text",
"attrs" => array(
"class" => self::TEXT_INPUT_CLASS
),
"validators" => array(
array(
"class" => "Zend_Validate_Date",
"params" => array(
"format" => self::VALIDATE_DATE_FORMAT
)
)
),
"filters" => array(
"StringTrim"
)
),
TEMPLATE_TIME => array(
"class" => "Zend_Form_Element_Text",
"attrs" => array(
"class" => self::TEXT_INPUT_CLASS
),
"validators" => array(
array(
"class" => "Zend_Validate_Date",
"params" => array(
"format" => self::VALIDATE_TIME_FORMAT
)
)
),
"filters" => array(
"StringTrim"
)
),
TEMPLATE_DATETIME => array(
"class" => "Zend_Form_Element_Text",
"attrs" => array(
"class" => self::TEXT_INPUT_CLASS
),
"validators" => array(
array(
"class" => "Zend_Validate_Date",
"params" => array(
"format" => self::VALIDATE_DATETIME_FORMAT
)
)
),
"filters" => array(
"StringTrim"
)
),
TEMPLATE_STRING => array(
"class" => "Zend_Form_Element_Text",
"attrs" => array(
"class" => self::TEXT_INPUT_CLASS
),
"filters" => array(
"StringTrim"
)
),
TEMPLATE_BOOLEAN => array(
"class" => "Zend_Form_Element_Checkbox",
"validators" => array(
array(
"class" => "Zend_Validate_InArray",
"options" => array(
"haystack" => array(0,1)
)
)
)
),
TEMPLATE_INT => array(
"class" => "Zend_Form_Element_Text",
"validators" => array(
array(
"class" => "Zend_Validate_Int",
)
),
"attrs" => array(
"class" => self::TEXT_INPUT_CLASS
)
),
TEMPLATE_FLOAT => array(
"class" => "Zend_Form_Element_Text",
"attrs" => array(
"class" => self::TEXT_INPUT_CLASS
),
"validators" => array(
array(
"class" => "Zend_Validate_Float",
)
)
),
);
private $formElTypes = [
TEMPLATE_DATE => [
'class' => 'Zend_Form_Element_Text',
'attrs' => [
'class' => self::TEXT_INPUT_CLASS,
],
'validators' => [
[
'class' => 'Zend_Validate_Date',
'params' => [
'format' => self::VALIDATE_DATE_FORMAT,
],
],
],
'filters' => [
'StringTrim',
],
],
TEMPLATE_TIME => [
'class' => 'Zend_Form_Element_Text',
'attrs' => [
'class' => self::TEXT_INPUT_CLASS,
],
'validators' => [
[
'class' => 'Zend_Validate_Date',
'params' => [
'format' => self::VALIDATE_TIME_FORMAT,
],
],
],
'filters' => [
'StringTrim',
],
],
TEMPLATE_DATETIME => [
'class' => 'Zend_Form_Element_Text',
'attrs' => [
'class' => self::TEXT_INPUT_CLASS,
],
'validators' => [
[
'class' => 'Zend_Validate_Date',
'params' => [
'format' => self::VALIDATE_DATETIME_FORMAT,
],
],
],
'filters' => [
'StringTrim',
],
],
TEMPLATE_STRING => [
'class' => 'Zend_Form_Element_Text',
'attrs' => [
'class' => self::TEXT_INPUT_CLASS,
],
'filters' => [
'StringTrim',
],
],
TEMPLATE_BOOLEAN => [
'class' => 'Zend_Form_Element_Checkbox',
'validators' => [
[
'class' => 'Zend_Validate_InArray',
'options' => [
'haystack' => [0, 1],
],
],
],
],
TEMPLATE_INT => [
'class' => 'Zend_Form_Element_Text',
'validators' => [
[
'class' => 'Zend_Validate_Int',
],
],
'attrs' => [
'class' => self::TEXT_INPUT_CLASS,
],
],
TEMPLATE_FLOAT => [
'class' => 'Zend_Form_Element_Text',
'attrs' => [
'class' => self::TEXT_INPUT_CLASS,
],
'validators' => [
[
'class' => 'Zend_Validate_Float',
],
],
],
];
public function init() {
$history_id = new Zend_Form_Element_Hidden($this::ID_PREFIX.'id');
$history_id->setValidators(array(
new Zend_Validate_Int()
));
$history_id->setDecorators(array('ViewHelper'));
$this->addElement($history_id);
$dynamic_attrs = new Zend_Form_SubForm();
$this->addSubForm($dynamic_attrs, $this::ID_PREFIX.'template');
// Add the submit button
$this->addElement('button', $this::ID_PREFIX.'save', array(
'ignore' => true,
'class' => 'btn '.$this::ID_PREFIX.'save',
'label' => _('Save'),
'decorators' => array(
'ViewHelper'
)
));
// Add the cancel button
$this->addElement('button', $this::ID_PREFIX.'cancel', array(
'ignore' => true,
'class' => 'btn '.$this::ID_PREFIX.'cancel',
'label' => _('Cancel'),
'decorators' => array(
'ViewHelper'
)
));
}
public function init()
{
$history_id = new Zend_Form_Element_Hidden($this::ID_PREFIX . 'id');
$history_id->setValidators([
new Zend_Validate_Int(),
]);
$history_id->setDecorators(['ViewHelper']);
$this->addElement($history_id);
public function createFromTemplate($template, $required) {
$dynamic_attrs = new Zend_Form_SubForm();
$this->addSubForm($dynamic_attrs, $this::ID_PREFIX . 'template');
$templateSubForm = $this->getSubForm($this::ID_PREFIX.'template');
// Add the submit button
$this->addElement('button', $this::ID_PREFIX . 'save', [
'ignore' => true,
'class' => 'btn ' . $this::ID_PREFIX . 'save',
'label' => _('Save'),
'decorators' => [
'ViewHelper',
],
]);
for ($i = 0, $len = count($template); $i < $len; $i++) {
// Add the cancel button
$this->addElement('button', $this::ID_PREFIX . 'cancel', [
'ignore' => true,
'class' => 'btn ' . $this::ID_PREFIX . 'cancel',
'label' => _('Cancel'),
'decorators' => [
'ViewHelper',
],
]);
}
$item = $template[$i];
//don't dynamically add this as it should be included in the
//init() function already if it should show up in the UI..
if (in_array($item["name"], $required)) {
continue;
}
public function createFromTemplate($template, $required)
{
$templateSubForm = $this->getSubForm($this::ID_PREFIX . 'template');
$formElType = $this->formElTypes[$item[self::ITEM_TYPE]];
for ($i = 0, $len = count($template); $i < $len; ++$i) {
$item = $template[$i];
//don't dynamically add this as it should be included in the
//init() function already if it should show up in the UI..
if (in_array($item['name'], $required)) {
continue;
}
$label = $item[self::ITEM_ID_SUFFIX];
$id = $this::ID_PREFIX.$label;
$el = new $formElType[self::ITEM_CLASS]($id);
$el->setLabel($item["label"]);
$formElType = $this->formElTypes[$item[self::ITEM_TYPE]];
if (isset($formElType["attrs"])) {
$label = $item[self::ITEM_ID_SUFFIX];
$id = $this::ID_PREFIX . $label;
$el = new $formElType[self::ITEM_CLASS]($id);
$el->setLabel($item['label']);
$attrs = $formElType["attrs"];
if (isset($formElType['attrs'])) {
$attrs = $formElType['attrs'];
foreach ($attrs as $key => $value) {
$el->setAttrib($key, $value);
}
}
foreach ($attrs as $key => $value) {
$el->setAttrib($key, $value);
}
}
if (isset($formElType["filters"])) {
if (isset($formElType['filters'])) {
$filters = $formElType['filters'];
$filters = $formElType["filters"];
foreach ($filters as $filter) {
$el->addFilter($filter);
}
}
foreach ($filters as $filter) {
$el->addFilter($filter);
}
}
if (isset($formElType['validators'])) {
$validators = $formElType['validators'];
if (isset($formElType["validators"])) {
foreach ($validators as $index => $arr) {
$options = isset($arr[self::ITEM_OPTIONS]) ? $arr[self::ITEM_OPTIONS] : null;
$validator = new $arr[self::ITEM_CLASS]($options);
$validators = $formElType["validators"];
//extra validator info
if (isset($arr['params'])) {
foreach ($arr['params'] as $key => $value) {
$method = 'set' . ucfirst($key);
$validator->{$method}($value);
}
}
foreach ($validators as $index => $arr) {
$options = isset($arr[self::ITEM_OPTIONS]) ? $arr[self::ITEM_OPTIONS] : null;
$validator = new $arr[self::ITEM_CLASS]($options);
$el->addValidator($validator);
}
}
//extra validator info
if (isset($arr["params"])) {
foreach ($arr["params"] as $key => $value) {
$method = "set".ucfirst($key);
$validator->$method($value);
}
}
$el->addValidator($validator);
}
}
$el->setDecorators(array('ViewHelper'));
$templateSubForm->addElement($el);
}
}
}
$el->setDecorators(['ViewHelper']);
$templateSubForm->addElement($el);
}
}
}

View File

@ -2,21 +2,21 @@
class Application_Form_EditHistoryFile extends Application_Form_EditHistory
{
const ID_PREFIX = "his_file_";
public function init() {
parent::init();
public const ID_PREFIX = 'his_file_';
$this->setDecorators(
array(
array('ViewScript', array('viewScript' => 'form/edit-history-file.phtml'))
)
);
}
public function createFromTemplate($template, $required) {
parent::createFromTemplate($template, $required);
}
}
public function init()
{
parent::init();
$this->setDecorators(
[
['ViewScript', ['viewScript' => 'form/edit-history-file.phtml']],
]
);
}
public function createFromTemplate($template, $required)
{
parent::createFromTemplate($template, $required);
}
}

View File

@ -2,65 +2,65 @@
class Application_Form_EditHistoryItem extends Application_Form_EditHistory
{
const ID_PREFIX = "his_item_";
public const ID_PREFIX = 'his_item_';
public function init() {
public function init()
{
parent::init();
parent::init();
$this->setDecorators([
'PrepareElements',
['ViewScript', ['viewScript' => 'form/edit-history-item.phtml']],
]);
$this->setDecorators(array(
'PrepareElements',
array('ViewScript', array('viewScript' => 'form/edit-history-item.phtml'))
));
/*
$instance = new Zend_Form_Element_Select("instance_id");
$instance->setLabel(_("Choose Show Instance"));
$instance->setMultiOptions(array("0" => "-----------"));
$instance->setValue(0);
$instance->setDecorators(array('ViewHelper'));
$this->addElement($instance);
*/
/*
$instance = new Zend_Form_Element_Select("instance_id");
$instance->setLabel(_("Choose Show Instance"));
$instance->setMultiOptions(array("0" => "-----------"));
$instance->setValue(0);
$instance->setDecorators(array('ViewHelper'));
$this->addElement($instance);
*/
$starts = new Zend_Form_Element_Text(self::ID_PREFIX . 'starts');
$starts->setValidators([
new Zend_Validate_Date(self::VALIDATE_DATETIME_FORMAT),
]);
$starts->setAttrib('class', self::TEXT_INPUT_CLASS . ' datepicker');
$starts->setAttrib('data-format', self::TIMEPICKER_DATETIME_FORMAT);
$starts->addFilter('StringTrim');
$starts->setLabel(_('Start Time'));
$starts->setDecorators(['ViewHelper']);
$starts->setRequired(true);
$this->addElement($starts);
$starts = new Zend_Form_Element_Text(self::ID_PREFIX.'starts');
$starts->setValidators(array(
new Zend_Validate_Date(self::VALIDATE_DATETIME_FORMAT)
));
$starts->setAttrib('class', self::TEXT_INPUT_CLASS." datepicker");
$starts->setAttrib('data-format', self::TIMEPICKER_DATETIME_FORMAT);
$starts->addFilter('StringTrim');
$starts->setLabel(_('Start Time'));
$starts->setDecorators(array('ViewHelper'));
$starts->setRequired(true);
$this->addElement($starts);
$ends = new Zend_Form_Element_Text(self::ID_PREFIX . 'ends');
$ends->setValidators([
new Zend_Validate_Date(self::VALIDATE_DATETIME_FORMAT),
]);
$ends->setAttrib('class', self::TEXT_INPUT_CLASS . ' datepicker');
$ends->setAttrib('data-format', self::TIMEPICKER_DATETIME_FORMAT);
$ends->addFilter('StringTrim');
$ends->setLabel(_('End Time'));
$ends->setDecorators(['ViewHelper']);
//$ends->setRequired(true);
$this->addElement($ends);
}
$ends = new Zend_Form_Element_Text(self::ID_PREFIX.'ends');
$ends->setValidators(array(
new Zend_Validate_Date(self::VALIDATE_DATETIME_FORMAT)
));
$ends->setAttrib('class', self::TEXT_INPUT_CLASS." datepicker");
$ends->setAttrib('data-format', self::TIMEPICKER_DATETIME_FORMAT);
$ends->addFilter('StringTrim');
$ends->setLabel(_('End Time'));
$ends->setDecorators(array('ViewHelper'));
//$ends->setRequired(true);
$this->addElement($ends);
}
public function createFromTemplate($template, $required)
{
parent::createFromTemplate($template, $required);
}
public function createFromTemplate($template, $required) {
public function populateShowInstances($possibleInstances, $default)
{
$possibleInstances['0'] = _('No Show');
parent::createFromTemplate($template, $required);
}
public function populateShowInstances($possibleInstances, $default) {
$possibleInstances["0"] = _("No Show");
$instance = new Zend_Form_Element_Select("his_instance_select");
//$instance->setLabel(_("Choose Show Instance"));
$instance->setMultiOptions($possibleInstances);
$instance->setValue($default);
$instance->setDecorators(array('ViewHelper'));
$this->addElement($instance);
}
}
$instance = new Zend_Form_Element_Select('his_instance_select');
//$instance->setLabel(_("Choose Show Instance"));
$instance->setMultiOptions($possibleInstances);
$instance->setValue($default);
$instance->setDecorators(['ViewHelper']);
$this->addElement($instance);
}
}

View File

@ -2,7 +2,6 @@
class Application_Form_EditUser extends Zend_Form
{
public function init()
{
/*
@ -17,39 +16,39 @@ class Application_Form_EditUser extends Zend_Form
$notEmptyValidator = Application_Form_Helper_ValidationTypes::overrideNotEmptyValidator();
$emailValidator = Application_Form_Helper_ValidationTypes::overrideEmailAddressValidator();
$notDemoValidator = new Application_Validate_NotDemoValidate();
$this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/edit-user.phtml', "currentUser" => $currentUser->getLogin()))));
$this->setDecorators([
['ViewScript', ['viewScript' => 'form/edit-user.phtml', 'currentUser' => $currentUser->getLogin()]], ]);
$this->setAttrib('id', 'current-user-form');
$csrf_namespace = new Zend_Session_Namespace('csrf_namespace');
$csrf_element = new Zend_Form_Element_Hidden('csrf');
$csrf_element->setValue($csrf_namespace->authtoken)->setRequired('true')->removeDecorator('HtmlTag')->removeDecorator('Label');
$this->addElement($csrf_element);
$hidden = new Zend_Form_Element_Hidden('cu_user_id');
$hidden->setDecorators(array('ViewHelper'));
$hidden->setValue($userData["id"]);
$hidden->setDecorators(['ViewHelper']);
$hidden->setValue($userData['id']);
$this->addElement($hidden);
$login = new Zend_Form_Element_Text('cu_login');
$login->setLabel(_('Username:'));
$login->setValue($userData["login"]);
$login->setValue($userData['login']);
$login->setAttrib('class', 'input_text');
$login->setAttrib('readonly', 'readonly');
$login->setRequired(true);
$login->addValidator($notEmptyValidator);
$login->addFilter('StringTrim');
$login->setDecorators(array('viewHelper'));
$login->setDecorators(['viewHelper']);
$this->addElement($login);
$password = new Zend_Form_Element_Password('cu_password');
$password->setLabel(_('Password:'));
$password->setAttrib('class', 'input_text');
$password->setRequired(true);
$password->addFilter('StringTrim');
$password->addValidator($notEmptyValidator);
$password->setDecorators(array('viewHelper'));
$password->setDecorators(['viewHelper']);
$this->addElement($password);
$passwordVerify = new Zend_Form_Element_Password('cu_passwordVerify');
@ -59,91 +58,94 @@ class Application_Form_EditUser extends Zend_Form
$passwordVerify->addFilter('StringTrim');
$passwordVerify->addValidator($notEmptyValidator);
$passwordVerify->addValidator($notDemoValidator);
$passwordVerify->setDecorators(array('viewHelper'));
$passwordVerify->setDecorators(['viewHelper']);
$this->addElement($passwordVerify);
$firstName = new Zend_Form_Element_Text('cu_first_name');
$firstName->setLabel(_('Firstname:'));
$firstName->setValue($userData["first_name"]);
$firstName->setValue($userData['first_name']);
$firstName->setAttrib('class', 'input_text');
$firstName->addFilter('StringTrim');
$firstName->setDecorators(array('viewHelper'));
$firstName->setDecorators(['viewHelper']);
$this->addElement($firstName);
$lastName = new Zend_Form_Element_Text('cu_last_name');
$lastName->setLabel(_('Lastname:'));
$lastName->setValue($userData["last_name"]);
$lastName->setValue($userData['last_name']);
$lastName->setAttrib('class', 'input_text');
$lastName->addFilter('StringTrim');
$lastName->setDecorators(array('viewHelper'));
$lastName->setDecorators(['viewHelper']);
$this->addElement($lastName);
$email = new Zend_Form_Element_Text('cu_email');
$email->setLabel(_('Email:'));
$email->setValue($userData["email"]);
$email->setValue($userData['email']);
$email->setAttrib('class', 'input_text');
$email->addFilter('StringTrim');
$email->setRequired(true);
$email->addValidator($notEmptyValidator);
$email->addValidator($emailValidator);
$email->setDecorators(array('viewHelper'));
$email->setDecorators(['viewHelper']);
$this->addElement($email);
$cellPhone = new Zend_Form_Element_Text('cu_cell_phone');
$cellPhone->setLabel(_('Mobile Phone:'));
$cellPhone->setValue($userData["cell_phone"]);
$cellPhone->setValue($userData['cell_phone']);
$cellPhone->setAttrib('class', 'input_text');
$cellPhone->addFilter('StringTrim');
$cellPhone->setDecorators(array('viewHelper'));
$cellPhone->setDecorators(['viewHelper']);
$this->addElement($cellPhone);
$skype = new Zend_Form_Element_Text('cu_skype');
$skype->setLabel(_('Skype:'));
$skype->setValue($userData["skype_contact"]);
$skype->setValue($userData['skype_contact']);
$skype->setAttrib('class', 'input_text');
$skype->addFilter('StringTrim');
$skype->setDecorators(array('viewHelper'));
$skype->setDecorators(['viewHelper']);
$this->addElement($skype);
$jabber = new Zend_Form_Element_Text('cu_jabber');
$jabber->setLabel(_('Jabber:'));
$jabber->setValue($userData["jabber_contact"]);
$jabber->setValue($userData['jabber_contact']);
$jabber->setAttrib('class', 'input_text');
$jabber->addFilter('StringTrim');
$jabber->addValidator($emailValidator);
$jabber->setDecorators(array('viewHelper'));
$jabber->setDecorators(['viewHelper']);
$this->addElement($jabber);
$locale = new Zend_Form_Element_Select("cu_locale");
$locale->setLabel(_("Language:"));
$locale = new Zend_Form_Element_Select('cu_locale');
$locale->setLabel(_('Language:'));
$locale->setMultiOptions(Application_Model_Locale::getLocales());
$locale->setValue(Application_Model_Preference::GetUserLocale());
$locale->setDecorators(array('ViewHelper'));
$locale->setDecorators(['ViewHelper']);
$this->addElement($locale);
$stationTz = Application_Model_Preference::GetDefaultTimezone();
$userTz = Application_Model_Preference::GetUserTimezone();
$timezone = new Zend_Form_Element_Select("cu_timezone");
$timezone->setLabel(_("Interface Timezone:"));
$timezone = new Zend_Form_Element_Select('cu_timezone');
$timezone->setLabel(_('Interface Timezone:'));
$timezone->setMultiOptions(Application_Common_Timezone::getTimezones());
$timezone->setValue($userTz == $stationTz ? null : $userTz);
$timezone->setDecorators(array('ViewHelper'));
$timezone->setDecorators(['ViewHelper']);
$this->addElement($timezone);
}
public function validateLogin($p_login, $p_userId) {
public function validateLogin($p_login, $p_userId)
{
$count = CcSubjsQuery::create()
->filterByDbLogin($p_login)
->filterByDbId($p_userId, Criteria::NOT_EQUAL)
->count();
->count()
;
if ($count != 0) {
$this->getElement('cu_login')->setErrors(array(_("Login name is not unique.")));
$this->getElement('cu_login')->setErrors([_('Login name is not unique.')]);
return false;
} else {
return true;
}
return true;
}
// We need to add the password identical validator here in case
@ -152,9 +154,11 @@ class Application_Form_EditUser extends Zend_Form
{
if (isset($data['cu_password'])) {
$passwordIdenticalValidator = Application_Form_Helper_ValidationTypes::overridePasswordIdenticalValidator(
$data['cu_password']);
$data['cu_password']
);
$this->getElement('cu_passwordVerify')->addValidator($passwordIdenticalValidator);
}
return parent::isValid($data);
}
}

View File

@ -6,7 +6,6 @@ require_once 'customfilters/ImageSize.php';
class Application_Form_GeneralPreferences extends Zend_Form_SubForm
{
public function init()
{
$maxLens = Application_Model_Show::getMaxLengths();
@ -14,40 +13,41 @@ class Application_Form_GeneralPreferences extends Zend_Form_SubForm
$notEmptyValidator = Application_Form_Helper_ValidationTypes::overrideNotEmptyValidator();
$rangeValidator = Application_Form_Helper_ValidationTypes::overrideBetweenValidator(0, 59.9);
$this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/preferences_general.phtml'))
));
$this->setDecorators([
['ViewScript', ['viewScript' => 'form/preferences_general.phtml']],
]);
$defaultFadeIn = Application_Model_Preference::GetDefaultFadeIn();
$defaultFadeOut = Application_Model_Preference::GetDefaultFadeOut();
//Station name
$this->addElement('text', 'stationName', array(
$this->addElement('text', 'stationName', [
'class' => 'input_text',
'label' => _('Station Name'),
'required' => false,
'filters' => array('StringTrim'),
'filters' => ['StringTrim'],
'value' => Application_Model_Preference::GetStationName(),
));
]);
// Station description
$stationDescription = new Zend_Form_Element_Textarea("stationDescription");
$stationDescription = new Zend_Form_Element_Textarea('stationDescription');
$stationDescription->setLabel(_('Station Description'));
$stationDescription->setValue(Application_Model_Preference::GetStationDescription());
$stationDescription->setRequired(false);
$stationDescription->setValidators(array(array('StringLength', false, array(0, $maxLens['description']))));
$stationDescription->setValidators([['StringLength', false, [0, $maxLens['description']]]]);
$stationDescription->setAttrib('rows', 4);
$this->addElement($stationDescription);
// Station Logo
$stationLogoUpload = new Zend_Form_Element_File('stationLogo');
$stationLogoUpload->setLabel(_('Station Logo:'))
->setDescription(_("Note: Anything larger than 600x600 will be resized."))
->setDescription(_('Note: Anything larger than 600x600 will be resized.'))
->setRequired(false)
->addValidator('Count', false, 1)
->addValidator('Extension', false, 'jpg,jpeg,png,gif')
->setMaxFileSize(1000000)
->addFilter('ImageSize');
->addFilter('ImageSize')
;
$stationLogoUpload->setAttrib('accept', 'image/*');
$this->addElement($stationLogoUpload);
@ -59,94 +59,94 @@ class Application_Form_GeneralPreferences extends Zend_Form_SubForm
$this->addElement($stationLogoRemove);
//Default station crossfade duration
$this->addElement('text', 'stationDefaultCrossfadeDuration', array(
$this->addElement('text', 'stationDefaultCrossfadeDuration', [
'class' => 'input_text',
'label' => _('Default Crossfade Duration (s):'),
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
$rangeValidator,
$notEmptyValidator,
array('regex', false, array('/^[0-9]+(\.\d+)?$/', 'messages' => _('Please enter a time in seconds (eg. 0.5)')))
),
'filters' => ['StringTrim'],
'validators' => [
$rangeValidator,
$notEmptyValidator,
['regex', false, ['/^[0-9]+(\.\d+)?$/', 'messages' => _('Please enter a time in seconds (eg. 0.5)')]],
],
'value' => Application_Model_Preference::GetDefaultCrossfadeDuration(),
));
]);
//Default station fade in
$this->addElement('text', 'stationDefaultFadeIn', array(
$this->addElement('text', 'stationDefaultFadeIn', [
'class' => 'input_text',
'label' => _('Default Fade In (s):'),
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
'filters' => ['StringTrim'],
'validators' => [
$rangeValidator,
$notEmptyValidator,
array('regex', false, array('/^[0-9]+(\.\d+)?$/', 'messages' => _('Please enter a time in seconds (eg. 0.5)')))
),
['regex', false, ['/^[0-9]+(\.\d+)?$/', 'messages' => _('Please enter a time in seconds (eg. 0.5)')]],
],
'value' => $defaultFadeIn,
));
]);
//Default station fade out
$this->addElement('text', 'stationDefaultFadeOut', array(
$this->addElement('text', 'stationDefaultFadeOut', [
'class' => 'input_text',
'label' => _('Default Fade Out (s):'),
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
'filters' => ['StringTrim'],
'validators' => [
$rangeValidator,
$notEmptyValidator,
array('regex', false, array('/^[0-9]+(\.\d+)?$/', 'messages' => _('Please enter a time in seconds (eg. 0.5)')))
),
['regex', false, ['/^[0-9]+(\.\d+)?$/', 'messages' => _('Please enter a time in seconds (eg. 0.5)')]],
],
'value' => $defaultFadeOut,
));
]);
$tracktypeDefault = new Zend_Form_Element_Select("tracktypeDefault");
$tracktypeDefault->setLabel(_("Track Type Upload Default"));
$tracktypeDefault = new Zend_Form_Element_Select('tracktypeDefault');
$tracktypeDefault->setLabel(_('Track Type Upload Default'));
$tracktypeDefault->setMultiOptions(Application_Model_Library::getTracktypes());
$tracktypeDefault->setValue(Application_Model_Preference::GetTrackTypeDefault());
$this->addElement($tracktypeDefault);
// add intro playlist select here
$introPlaylistSelect = new Zend_Form_Element_Select("introPlaylistSelect");
$introPlaylistSelect->setLabel(_("Intro Autoloading Playlist"));
$introPlaylistSelect = new Zend_Form_Element_Select('introPlaylistSelect');
$introPlaylistSelect->setLabel(_('Intro Autoloading Playlist'));
$introPlaylistSelect->setMultiOptions(Application_Model_Library::getPlaylistNames(true));
$introPlaylistSelect->setValue(Application_Model_Preference::GetIntroPlaylist());
$this->addElement($introPlaylistSelect);
$outroPlaylistSelect = new Zend_Form_Element_Select("outroPlaylistSelect");
$outroPlaylistSelect->setLabel(_("Outro Autoloading Playlist"));
$outroPlaylistSelect = new Zend_Form_Element_Select('outroPlaylistSelect');
$outroPlaylistSelect->setLabel(_('Outro Autoloading Playlist'));
$outroPlaylistSelect->setMultiOptions(Application_Model_Library::getPlaylistNames(true));
$outroPlaylistSelect->setValue(Application_Model_Preference::GetOutroPlaylist());
$this->addElement($outroPlaylistSelect);
$podcast_album_override = new Zend_Form_Element_Radio('podcastAlbumOverride');
$podcast_album_override->setLabel(_('Overwrite Podcast Episode Metatags'));
$podcast_album_override->setMultiOptions(array(
_("Disabled"),
_("Enabled"),
));
$podcast_album_override->setMultiOptions([
_('Disabled'),
_('Enabled'),
]);
$podcast_album_override->setValue(Application_Model_Preference::GetPodcastAlbumOverride());
$podcast_album_override->setDescription(_('Enabling this feature will cause podcast episode tracks to have their Artist, Title, and Album metatags set from podcast feed values. Note that enabling this feature is recommended in order to ensure reliable scheduling of episodes via smartblocks.'));
$podcast_album_override->setSeparator(' '); //No <br> between radio buttons
$podcast_album_override->addDecorator('HtmlTag', array('tag' => 'dd',
'id'=>"podcastAlbumOverride-element",
$podcast_album_override->addDecorator('HtmlTag', ['tag' => 'dd',
'id' => 'podcastAlbumOverride-element',
'class' => 'radio-inline-list',
));
]);
$this->addElement($podcast_album_override);
$podcast_auto_smartblock = new Zend_Form_Element_Radio('podcastAutoSmartblock');
$podcast_auto_smartblock->setLabel(_('Generate a smartblock and a playlist upon creation of a new podcast'));
$podcast_auto_smartblock->setMultiOptions(array(
_("Disabled"),
_("Enabled"),
));
$podcast_auto_smartblock->setMultiOptions([
_('Disabled'),
_('Enabled'),
]);
$podcast_auto_smartblock->setValue(Application_Model_Preference::GetPodcastAutoSmartblock());
$podcast_auto_smartblock->setDescription(_('If this option is enabled, a new smartblock and playlist matching the newest track of a podcast will be generated immediately upon creation of a new podcast. Note that the "Overwrite Podcast Episode Metatags" feature must also be enabled in order for smartblocks to reliably find episodes.'));
$podcast_auto_smartblock->setSeparator(' '); //No <br> between radio buttons
$podcast_auto_smartblock->addDecorator('HtmlTag', array('tag' => 'dd',
'id'=>"podcastAutoSmartblock-element",
$podcast_auto_smartblock->addDecorator('HtmlTag', ['tag' => 'dd',
'id' => 'podcastAutoSmartblock-element',
'class' => 'radio-inline-list',
));
]);
$this->addElement($podcast_auto_smartblock);
//TODO add and insert Podcast Smartblock and Playlist autogenerate options
@ -154,19 +154,19 @@ class Application_Form_GeneralPreferences extends Zend_Form_SubForm
$third_party_api = new Zend_Form_Element_Radio('thirdPartyApi');
$third_party_api->setLabel(_('Public LibreTime API'));
$third_party_api->setDescription(_('Required for embeddable schedule widget.'));
$third_party_api->setMultiOptions(array(
_("Disabled"),
_("Enabled"),
));
$third_party_api->setMultiOptions([
_('Disabled'),
_('Enabled'),
]);
$third_party_api->setValue(Application_Model_Preference::GetAllow3rdPartyApi());
$third_party_api->setDescription(_('Enabling this feature will allow LibreTime to provide schedule data
to external widgets that can be embedded in your website.'));
$third_party_api->setSeparator(' '); //No <br> between radio buttons
//$third_party_api->addDecorator(new Zend_Form_Decorator_Label(array('tag' => 'dd', 'class' => 'radio-inline-list')));
$third_party_api->addDecorator('HtmlTag', array('tag' => 'dd',
'id'=>"thirdPartyApi-element",
'class' => 'radio-inline-list',
));
$third_party_api->addDecorator('HtmlTag', ['tag' => 'dd',
'id' => 'thirdPartyApi-element',
'class' => 'radio-inline-list',
]);
$this->addElement($third_party_api);
$allowedCorsUrlsValue = Application_Model_Preference::GetAllowedCorsUrls();
@ -176,69 +176,67 @@ class Application_Form_GeneralPreferences extends Zend_Form_SubForm
$allowedCorsUrls->setValue($allowedCorsUrlsValue);
$this->addElement($allowedCorsUrls);
$locale = new Zend_Form_Element_Select("locale");
$locale->setLabel(_("Default Language"));
$locale = new Zend_Form_Element_Select('locale');
$locale->setLabel(_('Default Language'));
$locale->setMultiOptions(Application_Model_Locale::getLocales());
$locale->setValue(Application_Model_Preference::GetDefaultLocale());
$this->addElement($locale);
/* Form Element for setting the Timezone */
$timezone = new Zend_Form_Element_Select("timezone");
$timezone->setLabel(_("Station Timezone"));
// Form Element for setting the Timezone
$timezone = new Zend_Form_Element_Select('timezone');
$timezone->setLabel(_('Station Timezone'));
$timezone->setMultiOptions(Application_Common_Timezone::getTimezones());
$timezone->setValue(Application_Model_Preference::GetDefaultTimezone());
$this->addElement($timezone);
/* Form Element for setting which day is the start of the week */
$week_start_day = new Zend_Form_Element_Select("weekStartDay");
$week_start_day->setLabel(_("Week Starts On"));
// Form Element for setting which day is the start of the week
$week_start_day = new Zend_Form_Element_Select('weekStartDay');
$week_start_day->setLabel(_('Week Starts On'));
$week_start_day->setMultiOptions($this->getWeekStartDays());
$week_start_day->setValue(Application_Model_Preference::GetWeekStartDay());
$this->addElement($week_start_day);
$radioPageLoginButton = new Zend_Form_Element_Checkbox("radioPageLoginButton");
$radioPageLoginButton->setDecorators(array(
$radioPageLoginButton = new Zend_Form_Element_Checkbox('radioPageLoginButton');
$radioPageLoginButton->setDecorators([
'ViewHelper',
'Errors',
'Label'
));
'Label',
]);
$displayRadioPageLoginButtonValue = Application_Model_Preference::getRadioPageDisplayLoginButton();
if ($displayRadioPageLoginButtonValue == "") {
if ($displayRadioPageLoginButtonValue == '') {
$displayRadioPageLoginButtonValue = true;
}
$radioPageLoginButton->addDecorator('Label', array("class" => "enable-tunein"));
$radioPageLoginButton->setLabel(_("Display login button on your Radio Page?"));
$radioPageLoginButton->addDecorator('Label', ['class' => 'enable-tunein']);
$radioPageLoginButton->setLabel(_('Display login button on your Radio Page?'));
$radioPageLoginButton->setValue($displayRadioPageLoginButtonValue);
$this->addElement($radioPageLoginButton);
$feature_preview_mode = new Zend_Form_Element_Radio('featurePreviewMode');
$feature_preview_mode->setLabel(_('Feature Previews'));
$feature_preview_mode->setMultiOptions(array(
_("Disabled"),
_("Enabled"),
));
$feature_preview_mode->setMultiOptions([
_('Disabled'),
_('Enabled'),
]);
$feature_preview_mode->setValue(Application_Model_Preference::GetFeaturePreviewMode());
$feature_preview_mode->setDescription(_('Enable this to opt-in to test new features.'));
$feature_preview_mode->setSeparator(' '); //No <br> between radio buttons
$feature_preview_mode->addDecorator('HtmlTag', array('tag' => 'dd',
'id'=>"featurePreviewMode-element",
$feature_preview_mode->addDecorator('HtmlTag', ['tag' => 'dd',
'id' => 'featurePreviewMode-element',
'class' => 'radio-inline-list',
));
]);
$this->addElement($feature_preview_mode);
}
private function getWeekStartDays()
{
$days = array(
return [
_('Sunday'),
_('Monday'),
_('Tuesday'),
_('Wednesday'),
_('Thursday'),
_('Friday'),
_('Saturday')
);
return $days;
_('Saturday'),
];
}
}

View File

@ -2,7 +2,6 @@
class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
{
public function init()
{
$CC_CONFIG = Config::getConfig();
@ -10,29 +9,32 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
$defaultFade = Application_Model_Preference::GetDefaultTransitionFade();
$this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/preferences_livestream.phtml')),
));
$this->setDecorators([
['ViewScript', ['viewScript' => 'form/preferences_livestream.phtml']],
]);
// automatic trasition on source disconnection
$auto_transition = new Zend_Form_Element_Checkbox("auto_transition");
$auto_transition->setLabel(_("Auto Switch Off:"))
->setValue(Application_Model_Preference::GetAutoTransition());
$auto_transition = new Zend_Form_Element_Checkbox('auto_transition');
$auto_transition->setLabel(_('Auto Switch Off:'))
->setValue(Application_Model_Preference::GetAutoTransition())
;
$this->addElement($auto_transition);
// automatic switch on upon source connection
$auto_switch = new Zend_Form_Element_Checkbox("auto_switch");
$auto_switch->setLabel(_("Auto Switch On:"))
->setValue(Application_Model_Preference::GetAutoSwitch());
$auto_switch = new Zend_Form_Element_Checkbox('auto_switch');
$auto_switch->setLabel(_('Auto Switch On:'))
->setValue(Application_Model_Preference::GetAutoSwitch())
;
$this->addElement($auto_switch);
// Default transition fade
$transition_fade = new Zend_Form_Element_Text("transition_fade");
$transition_fade->setLabel(_("Switch Transition Fade (s):"))
->setFilters(array('StringTrim'))
->addValidator('regex', false, array('/^\d*(\.\d+)?$/',
'messages' => _('Please enter a time in seconds (eg. 0.5)')))
->setValue($defaultFade);
$transition_fade = new Zend_Form_Element_Text('transition_fade');
$transition_fade->setLabel(_('Switch Transition Fade (s):'))
->setFilters(['StringTrim'])
->addValidator('regex', false, ['/^\d*(\.\d+)?$/',
'messages' => _('Please enter a time in seconds (eg. 0.5)'), ])
->setValue($defaultFade)
;
$this->addElement($transition_fade);
//Master username
@ -40,8 +42,9 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
$master_username->setAttrib('autocomplete', 'off')
->setAllowEmpty(true)
->setLabel(_('Username:'))
->setFilters(array('StringTrim'))
->setValue(Application_Model_Preference::GetLiveStreamMasterUsername());
->setFilters(['StringTrim'])
->setValue(Application_Model_Preference::GetLiveStreamMasterUsername())
;
$this->addElement($master_username);
//Master password
@ -56,7 +59,8 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
->setAllowEmpty(true)
->setValue(Application_Model_Preference::GetLiveStreamMasterPassword())
->setLabel(_('Password:'))
->setFilters(array('StringTrim'));
->setFilters(['StringTrim'])
;
$this->addElement($master_password);
$masterSourceParams = parse_url(Application_Model_Preference::GetMasterDJSourceConnectionURL());
@ -65,10 +69,10 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
$masterSourceHost = new Zend_Form_Element_Text('master_source_host');
$masterSourceHost->setLabel(_('Master Source Host:'))
->setAttrib('readonly', true)
->setValue(Application_Model_Preference::GetMasterDJSourceConnectionURL());
->setValue(Application_Model_Preference::GetMasterDJSourceConnectionURL())
;
$this->addElement($masterSourceHost);
//liquidsoap harbor.input port
$betweenValidator = Application_Form_Helper_ValidationTypes::overrideBetweenValidator(1024, 49151);
@ -77,19 +81,19 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
$masterSourcePort = new Zend_Form_Element_Text('master_source_port');
$masterSourcePort->setLabel(_('Master Source Port:'))
->setValue($m_port)
->setValidators(array($betweenValidator))
->addValidator('regex', false, array('pattern'=>'/^[0-9]+$/', 'messages'=>array('regexNotMatch'=>_('Only numbers are allowed.'))));
$this->addElement($masterSourcePort);
->setValidators([$betweenValidator])
->addValidator('regex', false, ['pattern' => '/^[0-9]+$/', 'messages' => ['regexNotMatch' => _('Only numbers are allowed.')]])
;
$this->addElement($masterSourcePort);
$m_mount = Application_Model_StreamSetting::getMasterLiveStreamMountPoint();
$masterSourceMount = new Zend_Form_Element_Text('master_source_mount');
$masterSourceMount->setLabel(_('Master Source Mount:'))
->setValue($m_mount)
->setValidators(array(
array('regex', false, array('/^[^ &<>]+$/', 'messages' => _('Invalid character entered')))));
->setValidators([
['regex', false, ['/^[^ &<>]+$/', 'messages' => _('Invalid character entered')]], ])
;
$this->addElement($masterSourceMount);
$showSourceParams = parse_url(Application_Model_Preference::GetLiveDJSourceConnectionURL());
@ -98,7 +102,8 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
$showSourceHost = new Zend_Form_Element_Text('show_source_host');
$showSourceHost->setLabel(_('Show Source Host:'))
->setAttrib('readonly', true)
->setValue(Application_Model_Preference::GetLiveDJSourceConnectionURL());
->setValue(Application_Model_Preference::GetLiveDJSourceConnectionURL())
;
$this->addElement($showSourceHost);
//liquidsoap harbor.input port
@ -107,16 +112,18 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
$showSourcePort = new Zend_Form_Element_Text('show_source_port');
$showSourcePort->setLabel(_('Show Source Port:'))
->setValue($l_port)
->setValidators(array($betweenValidator))
->addValidator('regex', false, array('pattern' => '/^[0-9]+$/', 'messages' => array('regexNotMatch' => _('Only numbers are allowed.'))));
->setValidators([$betweenValidator])
->addValidator('regex', false, ['pattern' => '/^[0-9]+$/', 'messages' => ['regexNotMatch' => _('Only numbers are allowed.')]])
;
$this->addElement($showSourcePort);
$l_mount = Application_Model_StreamSetting::getDjLiveStreamMountPoint();
$showSourceMount = new Zend_Form_Element_Text('show_source_mount');
$showSourceMount->setLabel(_('Show Source Mount:'))
->setValue($l_mount)
->setValidators(array(
array('regex', false, array('/^[^ &<>]+$/', 'messages' => _('Invalid character entered')))));
->setValidators([
['regex', false, ['/^[^ &<>]+$/', 'messages' => _('Invalid character entered')]], ])
;
$this->addElement($showSourceMount);
}
@ -129,20 +136,20 @@ class Application_Form_LiveStreamingPreferences extends Zend_Form_SubForm
$showSourceParams = parse_url(Application_Model_Preference::GetLiveDJSourceConnectionURL());
$this->setDecorators(
array(
array('ViewScript',
array(
[
['ViewScript',
[
'viewScript' => 'form/preferences_livestream.phtml',
'master_source_host' => isset($masterSourceHost) ? Application_Model_Preference::GetMasterDJSourceConnectionURL() : "",
'master_source_port' => isset($masterSourcePort) ? Application_Model_StreamSetting::getMasterLiveStreamPort() : "",
'master_source_mount' => isset($masterSourceMount) ? Application_Model_StreamSetting::getMasterLiveStreamMountPoint() : "",
'show_source_host' => isset($showSourceHost) ? Application_Model_Preference::GetLiveDJSourceConnectionURL() : "",
'show_source_port' => isset($showSourcePort) ? Application_Model_StreamSetting::getDjLiveStreamPort() : "",
'show_source_mount' => isset($showSourceMount) ? Application_Model_StreamSetting::getDjLiveStreamMountPoint() : "",
'master_source_host' => isset($masterSourceHost) ? Application_Model_Preference::GetMasterDJSourceConnectionURL() : '',
'master_source_port' => isset($masterSourcePort) ? Application_Model_StreamSetting::getMasterLiveStreamPort() : '',
'master_source_mount' => isset($masterSourceMount) ? Application_Model_StreamSetting::getMasterLiveStreamMountPoint() : '',
'show_source_host' => isset($showSourceHost) ? Application_Model_Preference::GetLiveDJSourceConnectionURL() : '',
'show_source_port' => isset($showSourcePort) ? Application_Model_StreamSetting::getDjLiveStreamPort() : '',
'show_source_mount' => isset($showSourceMount) ? Application_Model_StreamSetting::getDjLiveStreamMountPoint() : '',
'isDemo' => $isDemo,
)
)
)
],
],
]
);
}
}

View File

@ -2,7 +2,6 @@
class Application_Form_Login extends Zend_Form
{
public function init()
{
$CC_CONFIG = Config::getConfig();
@ -19,73 +18,73 @@ class Application_Form_Login extends Zend_Form
foreach (CORSHelper::getAllowedOrigins($request) as $safeOrigin) {
if ($this->startsWith($safeOrigin, $refererUrl)) {
$originIsSafe = true;
break;
}
}
}
if (!$originIsSafe) {
$this->addElement('hash', 'csrf', array(
'salt' => 'unique'
));
$this->addElement('hash', 'csrf', [
'salt' => 'unique',
]);
}
$this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/login.phtml'))
));
$this->setDecorators([
['ViewScript', ['viewScript' => 'form/login.phtml']],
]);
// Add username element
$username = new Zend_Form_Element_Text("username");
$username = new Zend_Form_Element_Text('username');
$username->setLabel(_('Username:'))
->setAttribs(array(
->setAttribs([
'autofocus' => 'true',
'class' => 'input_text',
'required' => 'true'))
->setValue((isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1)?'admin':'')
'required' => 'true', ])
->setValue((isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1) ? 'admin' : '')
->addFilter('StringTrim')
->setDecorators(array('ViewHelper'))
->setValidators(array('NotEmpty'));
->setDecorators(['ViewHelper'])
->setValidators(['NotEmpty'])
;
$this->addElement($username);
// Add password element
$this->addElement('password', 'password', array(
'label' => _('Password:'),
'class' => 'input_text',
'required' => true,
'value' => (isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1)?'admin':'',
'filters' => array('StringTrim'),
'validators' => array(
$this->addElement('password', 'password', [
'label' => _('Password:'),
'class' => 'input_text',
'required' => true,
'value' => (isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1) ? 'admin' : '',
'filters' => ['StringTrim'],
'validators' => [
'NotEmpty',
),
'decorators' => array(
'ViewHelper'
)
));
$locale = new Zend_Form_Element_Select("locale");
$locale->setLabel(_("Language:"));
],
'decorators' => [
'ViewHelper',
],
]);
$locale = new Zend_Form_Element_Select('locale');
$locale->setLabel(_('Language:'));
$locale->setMultiOptions(Application_Model_Locale::getLocales());
$locale->setDecorators(array('ViewHelper'));
$locale->setDecorators(['ViewHelper']);
$this->addElement($locale);
$this->setDefaults(array(
"locale" => Application_Model_Locale::getUserLocale()
));
$this->setDefaults([
'locale' => Application_Model_Locale::getUserLocale(),
]);
// Add the submit button
$this->addElement('submit', 'submit', array(
'ignore' => true,
'label' => _('Login'),
'class' => 'ui-button ui-widget ui-state-default ui-button-text-only center',
'decorators' => array(
'ViewHelper'
)
));
$this->addElement('submit', 'submit', [
'ignore' => true,
'label' => _('Login'),
'class' => 'ui-button ui-widget ui-state-default ui-button-text-only center',
'decorators' => [
'ViewHelper',
],
]);
}
/**
* tests if a string starts with a given string
* tests if a string starts with a given string.
*
* This method was pinched as is from phing since it was the only line of code
* actually used from phing. I'm not 100% convinced why it was deemed necessary
@ -102,10 +101,10 @@ class Application_Form_Login extends Zend_Form
*/
private function startsWith($check, $string)
{
if ($check === "" || $check === $string) {
if ($check === '' || $check === $string) {
return true;
} else {
return (strpos($string, $check) === 0) ? true : false;
}
return (strpos($string, $check) === 0) ? true : false;
}
}

View File

@ -1,51 +1,49 @@
<?php
/**
*/
class Application_Form_PasswordChange extends Zend_Form
{
public function init()
{
$this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/password-change.phtml'))
));
$this->setDecorators([
['ViewScript', ['viewScript' => 'form/password-change.phtml']],
]);
$notEmptyValidator = Application_Form_Helper_ValidationTypes::overrideNotEmptyValidator();
$stringLengthValidator = Application_Form_Helper_ValidationTypes::overrideStringLengthValidator(6, 80);
$this->addElement('password', 'password', array(
$this->addElement('password', 'password', [
'label' => _('Password'),
'required' => true,
'filters' => array('stringTrim'),
'validators' => array($notEmptyValidator,
$stringLengthValidator),
'decorators' => array(
'ViewHelper'
)
));
'filters' => ['stringTrim'],
'validators' => [$notEmptyValidator,
$stringLengthValidator, ],
'decorators' => [
'ViewHelper',
],
]);
$this->addElement('password', 'password_confirm', array(
$this->addElement('password', 'password_confirm', [
'label' => _('Confirm new password'),
'required' => true,
'filters' => array('stringTrim'),
'validators' => array(
'filters' => ['stringTrim'],
'validators' => [
new Zend_Validate_Callback(function ($value, $context) {
return $value == $context['password'];
}),
),
'errorMessages' => array(_("Password confirmation does not match your password.")),
'decorators' => array(
'ViewHelper'
)
));
],
'errorMessages' => [_('Password confirmation does not match your password.')],
'decorators' => [
'ViewHelper',
],
]);
$this->addElement('submit', 'submit', array(
$this->addElement('submit', 'submit', [
'label' => _('Save'),
'ignore' => true,
'class' => 'ui-button ui-widget ui-state-default ui-button-text-only center',
'decorators' => array(
'ViewHelper'
)
));
'decorators' => [
'ViewHelper',
],
]);
}
}

View File

@ -1,52 +1,51 @@
<?php
/**
*/
class Application_Form_PasswordRestore extends Zend_Form
{
public function init()
{
$this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/password-restore.phtml'))
));
$this->setDecorators([
['ViewScript', ['viewScript' => 'form/password-restore.phtml']],
]);
$this->addElement('text', 'email', array(
$this->addElement('text', 'email', [
'label' => _('Email'),
'required' => true,
'filters' => array(
'filters' => [
'stringTrim',
),
'decorators' => array(
'ViewHelper'
)
));
],
'decorators' => [
'ViewHelper',
],
]);
$this->addElement('text', 'username', array(
$this->addElement('text', 'username', [
'label' => _('Username'),
'required' => false,
'filters' => array(
'filters' => [
'stringTrim',
),
'decorators' => array(
'ViewHelper'
)
));
],
'decorators' => [
'ViewHelper',
],
]);
$this->addElement('submit', 'submit', array(
$this->addElement('submit', 'submit', [
'label' => _('Reset password'),
'ignore' => true,
'class' => 'ui-button ui-widget ui-state-default ui-button-text-only center',
'decorators' => array(
'ViewHelper'
)
));
'decorators' => [
'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->setLabel(_("Back"))
->setIgnore(True)
->setAttrib('onclick', 'window.location = ' . Zend_Controller_Front::getInstance()->getBaseUrl('login'))
->setDecorators(array('ViewHelper'));
$cancel->setLabel(_('Back'))
->setIgnore(true)
->setAttrib('onclick', 'window.location = ' . Zend_Controller_Front::getInstance()->getBaseUrl('login'))
->setDecorators(['ViewHelper'])
;
$this->addElement($cancel);
}
}

View File

@ -1,48 +1,48 @@
<?php
define("OPUS", "opus");
define('OPUS', 'opus');
class Application_Form_Player extends Zend_Form_SubForm
{
public function init()
{
$this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/player.phtml'))
));
$this->setDecorators([
['ViewScript', ['viewScript' => 'form/player.phtml']],
]);
$title = new Zend_Form_Element_Text('player_title');
$title->setValue(_('Now Playing'));
$title->setLabel(_('Title:'));
$title->setDecorators(array(
$title->setDecorators([
'ViewHelper',
'Errors',
'Label'
));
$title->addDecorator('Label', array('class' => 'player-title'));
'Label',
]);
$title->addDecorator('Label', ['class' => 'player-title']);
$this->addElement($title);
$streamMode = new Zend_Form_Element_Radio('player_stream_mode');
$streamMode->setLabel(_('Select Stream:'));
$streamMode->setMultiOptions(
array(
"auto" => _("Auto detect the most appropriate stream to use."),
"manual" => _("Select a stream:")
)
[
'auto' => _('Auto detect the most appropriate stream to use.'),
'manual' => _('Select a stream:'),
]
);
$streamMode->setValue("auto");
$streamMode->setValue('auto');
$this->addElement($streamMode);
$streamURL = new Zend_Form_Element_Radio('player_stream_url');
$opusStreamCount = 0;
$urlOptions = Array();
foreach(Application_Model_StreamSetting::getEnabledStreamData() as $stream => $data) {
$urlOptions[$stream] = strtoupper($data["codec"])." - ".$data["bitrate"]."kbps";
if ($data["mobile"]) {
$urlOptions[$stream] .= _(" - Mobile friendly");
$urlOptions = [];
foreach (Application_Model_StreamSetting::getEnabledStreamData() as $stream => $data) {
$urlOptions[$stream] = strtoupper($data['codec']) . ' - ' . $data['bitrate'] . 'kbps';
if ($data['mobile']) {
$urlOptions[$stream] .= _(' - Mobile friendly');
}
if ($data["codec"] == OPUS) {
$opusStreamCount += 1;
$urlOptions[$stream] .= _(" - The player does not support Opus streams.");
if ($data['codec'] == OPUS) {
++$opusStreamCount;
$urlOptions[$stream] .= _(' - The player does not support Opus streams.');
}
}
$streamURL->setMultiOptions(
@ -53,35 +53,35 @@ class Application_Form_Player extends Zend_Form_SubForm
foreach ($urlOptions as $o => $v) {
if (strpos(strtolower($v), OPUS) !== false) {
continue;
} else {
$streamURL->setValue($o);
break;
}
$streamURL->setValue($o);
break;
}
$streamURL->setAttrib('numberOfEnabledStreams', sizeof($urlOptions)-$opusStreamCount);
$streamURL->setAttrib('numberOfEnabledStreams', sizeof($urlOptions) - $opusStreamCount);
$streamURL->removeDecorator('label');
$this->addElement($streamURL);
$embedSrc = new Zend_Form_Element_Textarea('player_embed_src');
$embedSrc->setAttrib("readonly", "readonly");
$embedSrc->setAttrib("class", "embed-player-text-box");
$embedSrc->setAttrib('readonly', 'readonly');
$embedSrc->setAttrib('class', 'embed-player-text-box');
$embedSrc->setAttrib('cols', '40')
->setAttrib('rows', '4');
$embedSrc->setLabel(_("Embeddable code:"));
->setAttrib('rows', '4')
;
$embedSrc->setLabel(_('Embeddable code:'));
$embedSrc->setDescription(_("Copy this code and paste it into your website's HTML to embed the player in your site."));
$embedSrc->setValue('<iframe frameborder="0" width="280" height="216" src="'.Application_Common_HTTPHelper::getStationUrl().'embed/player?stream=auto&title=Now Playing"></iframe>');
$embedSrc->setValue('<iframe frameborder="0" width="280" height="216" src="' . Application_Common_HTTPHelper::getStationUrl() . 'embed/player?stream=auto&title=Now Playing"></iframe>');
$this->addElement($embedSrc);
$previewLabel = new Zend_Form_Element_Text('player_preview_label');
$previewLabel->setLabel(_("Preview:"));
$previewLabel->setDecorators(array(
$previewLabel->setLabel(_('Preview:'));
$previewLabel->setDecorators([
'ViewHelper',
'Errors',
'Label'
));
$previewLabel->addDecorator('Label', array('class' => 'preview-label'));
'Label',
]);
$previewLabel->addDecorator('Label', ['class' => 'preview-label']);
$this->addElement($previewLabel);
}
}

View File

@ -1,22 +1,22 @@
<?php
class Application_Form_PodcastPreferences extends Zend_Form_SubForm {
public function init() {
class Application_Form_PodcastPreferences extends Zend_Form_SubForm
{
public function init()
{
$isPrivate = Application_Model_Preference::getStationPodcastPrivacy();
$stationPodcastPrivacy = new Zend_Form_Element_Radio("stationPodcastPrivacy");
$stationPodcastPrivacy = new Zend_Form_Element_Radio('stationPodcastPrivacy');
$stationPodcastPrivacy->setLabel(_('Feed Privacy'));
$stationPodcastPrivacy->setMultiOptions(array(
_("Public"),
_("Private"),
));
$stationPodcastPrivacy->setMultiOptions([
_('Public'),
_('Private'),
]);
$stationPodcastPrivacy->setSeparator(' ');
$stationPodcastPrivacy->addDecorator('HtmlTag', array('tag' => 'dd',
'id'=>"stationPodcastPrivacy-element",
$stationPodcastPrivacy->addDecorator('HtmlTag', ['tag' => 'dd',
'id' => 'stationPodcastPrivacy-element',
'class' => 'radio-inline-list',
));
]);
$stationPodcastPrivacy->setValue($isPrivate);
$this->addElement($stationPodcastPrivacy);
}
}
}

View File

@ -6,9 +6,9 @@ class Application_Form_Preferences extends Zend_Form
{
$baseUrl = Application_Common_OsPath::getBaseDir();
$this->setDecorators(array(
array('ViewScript', array('viewScript' => 'form/preferences.phtml'))
));
$this->setDecorators([
['ViewScript', ['viewScript' => 'form/preferences.phtml']],
]);
$general_pref = new Application_Form_GeneralPreferences();
@ -36,7 +36,7 @@ class Application_Form_Preferences extends Zend_Form
$submit = new Zend_Form_Element_Submit('submit');
$submit->setLabel(_('Save'));
//$submit->removeDecorator('Label');
$submit->setAttribs(array('class'=>'btn right-floated'));
$submit->setAttribs(['class' => 'btn right-floated']);
$submit->removeDecorator('DtDdWrapper');
$this->addElement($submit);

View File

@ -2,10 +2,8 @@
class Application_Form_ScheduleShow extends Zend_Form
{
public function init()
{
/* Form Elements & Other Definitions Here ... */
// Form Elements & Other Definitions Here ...
}
}

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