Rename airtime_mvc/ to legacy/

This commit is contained in:
jo 2021-10-11 13:43:25 +02:00
parent f0879322c2
commit 3e18d42c8b
1316 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,289 @@
<?php
class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
{
/**
* @var Zend_Acl
**/
protected $_acl;
/**
* @var string
**/
protected $_roleName;
/**
* @var array
**/
protected $_errorPage;
/**
* 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->_roleName = $roleName;
if (null !== $aclData) {
$this->setAcl($aclData);
}
}
/**
* Sets the ACL object
*
* @param mixed $aclData
* @return void
**/
public function setAcl(Zend_Acl $aclData)
{
$this->_acl = $aclData;
}
/**
* Returns the ACL object
*
* @return Zend_Acl
**/
public function getAcl()
{
return $this->_acl;
}
/**
* Returns the ACL role used
*
* @return string
* @author
**/
public function getRoleName()
{
return $this->_roleName;
}
public function setRoleName($type)
{
$this->_roleName = $type;
}
/**
* Sets the error page
*
* @param string $action
* @param string $controller
* @param string $module
* @return void
**/
public function setErrorPage($action, $controller = 'error', $module = 'default')
{
$this->_errorPage = array('module' => $module,
'controller' => $controller,
'action' => $action);
}
/**
* Returns the error page
*
* @return array
**/
public function getErrorPage()
{
return $this->_errorPage;
}
/**
* 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
**/
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()) {
//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 (!$this->verifyAuth()) {
//$this->denyAccess();
//$this->getResponse()->sendResponse();
//$r->gotoSimpleAndExit('index', 'login', $request->getModuleName());
//die();
throw new Zend_Controller_Exception("Incorrect API key", 401);
}
}
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));
// Prepare response
$this->getResponse()
->setHttpResponseCode(401)
->setBody($json)
->sendResponse();
//redirectAndExit() cleans up, sends the headers and stops the script
Zend_Controller_Action_HelperBroker::getStaticHelper('redirector')->redirectAndExit();
} else {
$r = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$r->gotoSimpleAndExit('index', '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");
// 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"];
}
$tokenValid = $this->verifyCSRFToken($token);
if (!$tokenValid) {
$csrf_namespace = new Zend_Session_Namespace('csrf_namespace');
$csrf_namespace->authtoken = sha1(openssl_random_pseudo_bytes(128));
Logging::warn("Invalid CSRF token: $token");
$this->getResponse()
->setHttpResponseCode(401)
->appendBody("ERROR: CSRF token mismatch.")
->sendResponse();
die();
}
}
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$this->setRoleName($userInfo->type);
Zend_View_Helper_Navigation_HelperAbstract::setDefaultAcl($this->_acl);
Zend_View_Helper_Navigation_HelperAbstract::setDefaultRole($this->_roleName);
$resourceName = '';
if ($request->getModuleName() != 'default') {
$resourceName .= strtolower($request->getModuleName()) . ':';
}
$resourceName .= $controller;
/** 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 */
$this->setErrorPage('error403');
$this->denyAccess();
}
}
}
private function verifyAuth() {
if ($this->verifyAPIKey() || $this->isVerifiedDownload()) {
return true;
}
$this->getResponse()
->setHttpResponseCode(401)
->appendBody("ERROR: Incorrect API key.");
return false;
}
/**
* Check if the requested file can be downloaded.
* It should satisfy the following requirements:
* * request path is /rest/media/:id/download
* * download key is correct
* * requested file belongs to the station podcast
*
* @return bool
*/
private function isVerifiedDownload() {
$request = $this->getRequest();
$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"
&& $key === Application_Model_Preference::getStationPodcastDownloadKey()
&& $stationPodcast->hasEpisodeForFile($fileId);
}
private function verifyCSRFToken($token) {
return SecurityHelper::verifyCSRFToken($token);
}
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);
}
/**
* Deny Access Function
* Redirects to errorPage, this can be called from an action using the action helper
*
* @return void
**/
public function denyAccess()
{
$this->_request->setModuleName($this->_errorPage['module']);
$this->_request->setControllerName($this->_errorPage['controller']);
$this->_request->setActionName($this->_errorPage['action']);
}
}

View file

@ -0,0 +1,15 @@
<?php
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";
if (file_exists($maintenanceFile)) {
$request->setModuleName('default')
->setControllerName('index')
->setActionName('maintenance')
->setDispatched(true);
}
}
}

View file

@ -0,0 +1,251 @@
<?php
/** Our standard page layout initialization has to be done via a plugin
* because some of it requires session variables, and some of the routes
* run without a session (like API calls). This is an optimization because
* starting the session adds a fair amount of overhead.
*/
class PageLayoutInitPlugin extends Zend_Controller_Plugin_Abstract
{
protected $_bootstrap = null;
public function __construct($boostrap) {
$this->_bootstrap = $boostrap;
}
/**
* 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)
{
$controller = strtolower($request->getControllerName());
$action = strtolower($request->getActionName());
//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"
))
) {
//Start the session
Zend_Session::start();
Application_Model_Auth::pinSessionToClient(Zend_Auth::getInstance());
//localization configuration
Application_Model_Locale::configureLocalization();
$this->_initGlobals();
$this->_initCsrfNamespace();
$this->_initHeadLink();
$this->_initHeadScript();
$this->_initTitle();
$this->_initTranslationGlobals();
$this->_initViewHelpers();
}
// Skip upgrades and task management when running unit tests
if (getenv("AIRTIME_UNIT_TEST") != 1) {
$taskManager = TaskManager::getInstance();
// Run the upgrade on each request (if it needs to be run)
// We can't afford to wait 7 minutes to run an upgrade: users could
// have several minutes of database errors while waiting for a
// schema change upgrade to happen after a deployment
$taskManager->runTask('UpgradeTask');
// 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") {
$taskManager->runTasks();
}
}
}
protected function _initGlobals()
{
if (!Zend_Session::isStarted()) {
return;
}
$view = $this->_bootstrap->getResource('view');
$baseUrl = Application_Common_OsPath::getBaseDir();
$view->headScript()->appendScript("var baseUrl = '$baseUrl';");
$this->_initTranslationGlobals($view);
$user = Application_Model_User::GetCurrentUser();
if (!is_null($user)) {
$userType = $user->getType();
} else {
$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) {
$extension = '.' . $extension;
}
$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
*/
protected function _initCsrfNamespace()
{
/*
if (!Zend_Session::isStarted()) {
return;
}*/
$csrf_namespace = new Zend_Session_Namespace('csrf_namespace');
// Check if the token exists
if (!$csrf_namespace->authtoken) {
// If we don't have a token, regenerate it and set a 1 week timeout
// Should we log the user out here if the token is expired?
$csrf_namespace->authtoken = sha1(uniqid(rand(), 1));
$csrf_namespace->setExpirationSeconds(168 * 60 * 60);
}
//Here we are closing the session for writing because otherwise no requests
//in this session will be handled in parallel. This gives a major boost to the perceived performance
//of the application (page load times are more consistent, no lock contention).
session_write_close();
//Zend_Session::writeClose(true);
}
/**
* 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
*/
private function _initTranslationGlobals()
{
$view = $this->_bootstrap->getResource('view');
$view->headScript()->appendScript("var PRODUCT_NAME = '" . PRODUCT_NAME . "';");
$view->headScript()->appendScript("var USER_MANUAL_URL = '" . USER_MANUAL_URL . "';");
$view->headScript()->appendScript("var COMPANY_NAME = '" . COMPANY_NAME . "';");
//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_types = Application_Model_Tracktype::getTracktypes();
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 . ";");
}
protected function _initHeadLink()
{
$CC_CONFIG = Config::getConfig();
$view = $this->_bootstrap->getResource('view');
$baseUrl = Application_Common_OsPath::getBaseDir();
$view->headLink(array('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']);
}
protected function _initHeadScript()
{
if (!Zend_Session::isStarted()) {
return;
}
$CC_CONFIG = Config::getConfig();
$view = $this->_bootstrap->getResource('view');
$baseUrl = Application_Common_OsPath::getBaseDir();
$view->headScript()->appendFile($baseUrl . 'js/libs/jquery-1.8.3.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript')
->appendFile($baseUrl . 'js/libs/jquery-ui-1.8.24.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript')
->appendFile($baseUrl . 'js/libs/angular.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript')
->appendFile($baseUrl . 'js/bootstrap/bootstrap.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript')
->appendFile($baseUrl . 'js/libs/underscore-min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript')
->appendFile($baseUrl . 'js/qtip/jquery.qtip.js?' . $CC_CONFIG['airtime_version'], 'text/javascript')
->appendFile($baseUrl . 'js/jplayer/jquery.jplayer.min.js?' . $CC_CONFIG['airtime_version'], 'text/javascript')
->appendFile($baseUrl . 'js/sprintf/sprintf-0.7-beta1.js?' . $CC_CONFIG['airtime_version'], 'text/javascript')
->appendFile($baseUrl . 'js/cookie/js.cookie.js?' . $CC_CONFIG['airtime_version'], 'text/javascript')
->appendFile($baseUrl . 'js/i18n/jquery.i18n.js?' . $CC_CONFIG['airtime_version'], 'text/javascript')
->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'");
//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;
$view->headScript()->appendScript("var serverTimezoneOffset = {$offset}; //in seconds");
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;
$view->headScript()->appendScript("var userTimezoneOffset = {$offset}; //in seconds");
}
//scripts for now playing bar
$view->headScript()->appendFile($baseUrl . 'js/airtime/airtime_bootstrap.js?' . $CC_CONFIG['airtime_version'], 'text/javascript')
->appendFile($baseUrl . 'js/airtime/dashboard/helperfunctions.js?' . $CC_CONFIG['airtime_version'], 'text/javascript')
->appendFile($baseUrl . 'js/airtime/dashboard/dashboard.js?' . $CC_CONFIG['airtime_version'], 'text/javascript')
->appendFile($baseUrl . 'js/airtime/dashboard/versiontooltip.js?' . $CC_CONFIG['airtime_version'], 'text/javascript')
->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');
$user = Application_Model_User::getCurrentUser();
if (!is_null($user)) {
$userType = $user->getType();
} else {
$userType = "";
}
$view->headScript()->appendScript("var userType = '$userType';");
}
protected function _initViewHelpers()
{
$view = $this->_bootstrap->getResource('view');
$view->addHelperPath(APPLICATION_PATH . 'views/helpers', 'Airtime_View_Helper');
}
protected function _initTitle()
{
$view = $this->_bootstrap->getResource('view');
$view->headTitle(Application_Model_Preference::GetHeadTitle());
}
}

View file

@ -0,0 +1,19 @@
<?php
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);
}
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");
}
}
}