freenet-router |
Subversion Repositories: |
Compare with Previous - Blame - Download
<?php
namespace Phem\Environment;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\ORM\EntityManager;
use DoctrineBoot;
use Phem\Core\Collection;
use Phem\Libraries\Forms\Annotations\Relation;
use Phem\Libraries\ResourceLoading\ResourceManager;
use Phem\Libraries\Security\Authentication\MySQLAuthenticationProvider;
use Phem\Libraries\Security\Authorization\IAuthenticationProvider;
use Phem\Libraries\Security\Authorization\IAuthorizationProvider;
use Phem\Libraries\Security\Authorization\MySQLAuthorizationProvider;
use Phem\Libraries\Security\Management\IPermissionManager;
use Phem\Libraries\Security\Management\IUserManager;
use Phem\Libraries\Security\Management\MySQLPermissionManager;
use Phem\Libraries\Security\Management\MySQLTaskManager;
use Phem\Libraries\Security\Management\MySQLUserManager;
use Phem\Libraries\Security\Management\TaskManager;
use ReflectionClass;
use Srovnavac\Models\Entities\File;
use Twig_Environment;
use Twig_Loader_Filesystem;
/**
* This class provides basic global functions for managing sessions, http requests etc.
*
* @author Jakub PetrĹžĂlka <petrzilka@czweb.net>
*/
class EnvironmentManager
{
private static $session;
private static $entityManagers;
private static $linkBuilder;
private static $temporaryVariables = Array();
private static $twig;
/* Resources */
private static $resourceManager;
/* Security */
private static $authenticationProvider;
private static $authorizationProvider;
private static $permissionManager;
private static $taskManager;
private static $userManager;
/**
*
* @return ResourceManager
*/
static function getResourceManager()
{
if (self::$resourceManager == null)
{
self::$resourceManager = new ResourceManager();
}
return self::$resourceManager;
}
/**
*
* @return IAuthenticationProvider
*/
static function getAuthenticationProvider()
{
if (self::$authenticationProvider == null)
{
self::$authenticationProvider = new MySQLAuthenticationProvider();
}
return self::$authenticationProvider;
}
/**
*
* @return IAuthorizationProvider
*/
static function getAuthorizationProvider()
{
if (self::$authorizationProvider == null)
{
self::$authorizationProvider = new MySQLAuthorizationProvider();
}
return self::$authorizationProvider;
}
/**
*
* @return IPermissionManager
*/
static function getPermissionManager()
{
if (self::$permissionManager == null)
{
self::$permissionManager = new MySQLPermissionManager();
}
return self::$permissionManager;
}
/**
*
* @return TaskManager
*/
static function getTaskManager()
{
if (self::$taskManager == null)
{
self::$taskManager = new MySQLTaskManager();
}
return self::$taskManager;
}
/**
*
* @return IUserManager
*/
static function getUserManager()
{
if (self::$userManager == null)
{
self::$userManager = new MySQLUserManager();
}
return self::$userManager;
}
/**
* @param string $key
* @return mixed temporaryVariable
*/
public static
function getVariable($key)
{
if (array_key_exists($key, self::$temporaryVariables))
return self::$temporaryVariables[$key];
else
return null;
}
/**
* @param string $key
* @param mixed $value
* @return mixed temporaryVariable
*/
public static function setVariable($key, $value)
{
if (self::$temporaryVariables == null)
self::$temporaryVariables = Array();
self::$temporaryVariables[$key] = $value;
}
/**
* Converts matching rule to regexp
*
* @param string $matchRule The input match rule
* @return string regexp
*/
private static function parseMatchRule($matchRule)
{
switch ($matchRule)
{
case "word":
return "/[A-Za-z0-9_]/";
default:
return $matchRule;
}
}
/**
*
* Gets the http request variable - from POST or GET method
* (POST has higher priority if both of them are set)
*
* @param string $name Name of the variable
* @param mixed $defaultValue The default value being returned if matchRule check fails or if variable is not set
* @param string $matchRule Matching rule can be [ "word" | regex ]
* @return mixed The value of environment variable with given name
*/
static function getRequestVar($name, $defaultValue = null, $matchRule = null)
{
$regexp = self::parseMatchRule($matchRule);
$var = null;
if (isset($_POST[$name]))
$var = htmlspecialchars($_POST[$name]);
else if (isset($_GET[$name]))
$var = htmlspecialchars($_GET[$name]);
if (($var != null) && ((($matchRule != null) && (preg_match($regexp, $var) > 0)) || ($matchRule == null)))
{
return $var;
} else
{
return $defaultValue;
}
}
/**
* Factory method for accessing the Session object
*
* @return Session The Session object
*/
static function getSession()
{
if (self::$session == null)
{
self::$session = new Session();
}
return self::$session;
}
/**
*
* @return EntityManager Doctrine entity manager
*/
static function getEntityManager($selectedDb = null)
{
if (self::$entityManagers == null)
{
self::$entityManagers = new Collection();
}
$dbConfig = unserialize(DB_CONFIG);
if ($selectedDb == null)
{
$selectedDb = self::getSession()->getVar(ROOT_NAMESPACE . ".selectedDatabase");
}
if ($selectedDb == null)
{
$selectedDb = DB_DEFAULT_CONFIG;
}
if (self::$entityManagers->get($dbConfig[$selectedDb]['name']) == null)
{
$connection = array(
'driver' => 'pdo_mysql',
'host' => DB_HOST,
'dbname' => $dbConfig[$selectedDb]['name'],
'user' => $dbConfig[$selectedDb]['user'],
'password' => $dbConfig[$selectedDb]['password'],
'charset' => 'utf8',
'driverOptions' => array(
1002 => 'SET NAMES utf8')
);
self::$entityManagers->put($dbConfig[$selectedDb]['name'], EntityManager::create($connection, DoctrineBoot::$config));
}
return self::$entityManagers->get($dbConfig[$selectedDb]['name']);
}
/**
*
* @return LinkBuilder
*/
static function getLinkBuilder()
{
if (self::$linkBuilder == null)
{
self::$linkBuilder = new LinkBuilder();
}
return self::$linkBuilder;
}
static function getTwig()
{
if (self::$twig == null)
{
$loader = new Twig_Loader_Filesystem(TEMPLATE_DIR);
$loader->addPath(
FRAMEWORK_DIR . DS .
BUILTIN_RESOURCES_DIR . DS .
BUILTIN_TEMPLATES_DIR
, BUILTIN_TEMPLATES_NAMESPACE
);
$cacheAutoreload = false;
if (defined("TWIG_DEVEL_MODE"))
$cacheAutoreload = true;
$twig = new Twig_Environment($loader, array(
'cache' => TEMPLATE_CACHE_DIR,
'auto_reload' => $cacheAutoreload,
));
self::$twig = $twig;
}
return self::$twig;
}
static function getSubmittedFormData($formName)
{
$formData = array();
foreach ($_POST as $key => $value)
{
if (strpos($key, $formName) == 0)
{
$formData[substr($key, strlen($formName) + 1)]
= $value;
}
}
return $formData;
}
static function getSubmittedFormObject($object = null, $data = null, $prefix = "Phem_")
{
if ($data == null)
$data = self::getSubmittedFormData($prefix);
if (empty($data))
return null;
$className = $data['source'];
unset($data['source']);
if ($object == null)
{
$object = new $className();
}
/* @var $r ReflectionClass */
$r = new ReflectionClass($className);
foreach ($data as $property => $value)
{
$path = explode('_', $property);
if (count($path) == 1)
{
$setMethod = "set" . ucFirst($property);
if ($r->hasMethod($setMethod))
{
$object->$setMethod($value);
unset($data[$property]);
}
}
else
{
$tmp = $object;
foreach ($path as $p)
{
$p = lcfirst($p);
$getMethod = "get" . ucFirst($p);
$setMethod = "set" . ucFirst($p);
if(!method_exists($tmp, $getMethod))
throw new \Exception("Objekt tridy \"" . get_class($tmp) . "\" neobsahuje metodu \"" . $getMethod . "\".");
if (!is_object($tmp->$getMethod()))
{
$rr = new ReflectionClass(get_class($tmp));
$annotationReader = new AnnotationReader();
$annotations = $annotationReader->getPropertyAnnotations($rr->getProperty($p));
foreach ($annotations as $annotation)
{
if ($annotation instanceof Relation)
{
$constructor = $annotation->source;
$tmp->$setMethod(new $constructor());
$tmp = $tmp->$getMethod();
break;
}
}
}
else
{
$tmp = $tmp->$getMethod();
}
/* pokud je to poslednĂ element cesty, nastav hodnotu */
if ($p === lcfirst(end($path)))
{
$tmp->$setMethod($value);
}
}
}
}
return $object;
}
static function closeDbConnection()
{
if (self::$entityManagers != null)
{
foreach (self::$entityManagers as $em)
{
$em->clear();
$em->close();
$em = null;
}
self::$entityManagers = null;
}
}
/**
* Check if the request is allowed AJAX request
*
* @param string $sourceSiteURL the allowed site the request came from (HTTP_REFERER)
* @return boolean
*/
static function validAJAXRequest()
{
if (
// make sure it's an AJAX request
isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
// make sure it has a referrer
isset($_SERVER['HTTP_REFERER']) &&
// make sure it comes from your website
strpos($_SERVER['HTTP_REFERER'], "http://" . $_SERVER['HTTP_HOST']) === 0
)
return true;
else
return false;
}
}