public function transformContent()
 {
     $appKey = $this->getAppKey();
     $newsManager = $this->getNewsManager();
     $newsList = $newsManager->getNewsByPage(null, 'DESC', $appKey);
     if (count($newsList) === 0) {
         $this->getTemplate('noentry')->transformOnPlace();
         return;
     }
     $Cfg = $this->getConfiguration('APF\\extensions\\news', 'news.ini');
     $allowHtml = $Cfg->getSection('General')->getValue('AllowHtml') == 'TRUE' ? true : false;
     $List = $this->getIterator('list');
     $Data = [];
     // retrieve the charset from the registry to guarantee interoperability!
     $charset = Registry::retrieve('APF\\core', 'Charset');
     foreach ($newsList as &$news) {
         $Date = new \DateTime($news->getProperty('CreationTimestamp'));
         $Author = '';
         if ($news->getAuthor() !== '') {
             $authorTpl = $this->getTemplate('author');
             $authorTpl->setPlaceHolder('authorname', $news->getAuthor());
             $Author = $authorTpl->transformTemplate();
         }
         $Text = $allowHtml ? $news->getText() : htmlentities($news->getText(), ENT_QUOTES, $charset, false);
         $Data[] = ['title' => htmlentities($news->getTitle(), ENT_QUOTES, $charset, false), 'text' => $Text, 'date' => $Date->format('d.m.Y H:i:s'), 'author' => $Author];
     }
     $List->fillDataContainer($Data);
     $List->setPlaceHolder('pager', $this->buildPager($appKey));
     $List->transformOnPlace();
 }
Esempio n. 2
0
 /**
  * Returns the value of the cache config attribute or throws an exception,
  * in case the attribute is not given within the attributes array.
  *
  * @param string $name The name of the desired attribute.
  *
  * @return string Value of the attribute.
  * @throws InvalidArgumentException In case the desired attribute is not defined.
  *
  * @author Christian Achatz
  * @version
  * Version 0.1, 24.11.2008<br />
  */
 protected function getConfigAttribute($name)
 {
     $value = $this->configuration->getValue($name);
     if ($value == null) {
         $env = Registry::retrieve('APF\\core', 'Environment');
         throw new InvalidArgumentException('[' . get_class($this) . '::getConfigAttribute()] The configuration directive "' . $name . '" is not present or empty. ' . 'Please check your cache configuration ("' . $env . '_cacheconfig.ini") for namespace ' . '"APF\\tools\\cache" and context "' . $this->getContext() . '" or consult the documentation!', E_USER_ERROR);
     }
     return $value;
 }
Esempio n. 3
0
 public function transformContent()
 {
     $appKey = $this->getAppKey();
     $form = $this->getForm('edit');
     $cfg = $this->getConfiguration('APF\\extensions\\news', 'labels.ini');
     $lang = $cfg->getSection($this->getLanguage());
     $newsManager = $this->getNewsManager();
     // If an id is given, an existing news should be updated,
     // so we check here if it really exists.
     $editId = $this->getRequest()->getParameter('editnewsid');
     $news = null;
     if ($editId !== null && $editId !== '') {
         $news = $newsManager->getNewsById((int) $editId);
         if ($news === null) {
             $this->getTemplate('notfound')->transformOnPlace();
             return;
         }
     }
     // Get the form elements we need later
     $formTitle = $form->getFormElementByID('news-edit-title');
     $formText = $form->getFormElementByID('news-edit-text');
     $formUser = $form->getFormElementByID('news-edit-user');
     $button = $form->getFormElementByName('send');
     // If input is valid, save the news.
     if ($form->isSent() && $form->isValid()) {
         if (!isset($news)) {
             $news = new News();
             $news->setAppKey($appKey);
         }
         $news->setTitle($formTitle->getAttribute('value'));
         $news->setAuthor($formUser->getAttribute('value'));
         $news->setText($formText->getContent());
         $newsManager->saveNews($news);
     }
     // Pre-fill form elements if an existing news should be updated
     // and take care of the right text of the button.
     if ($editId !== null && $editId !== '') {
         $buttonValue = $lang->getValue('Form.Button.Edit');
         // retrieve the charset from the registry to guarantee interoperability!
         $charset = Registry::retrieve('APF\\core', 'Charset');
         $formTitle->setAttribute('value', htmlspecialchars($news->getTitle(), ENT_QUOTES, $charset, false));
         $formUser->setAttribute('value', htmlspecialchars($news->getAuthor(), ENT_QUOTES, $charset, false));
         $formText->setContent(htmlspecialchars($news->getText(), ENT_QUOTES, $charset, false));
     } else {
         $buttonValue = $lang->getValue('Form.Button.New');
         // Clear form inputs
         if ($form->isSent() && $form->isValid()) {
             $formText->setContent('');
             $formTitle->setAttribute('value', '');
             $formUser->setAttribute('value', '');
         }
     }
     $button->setAttribute('value', $buttonValue);
     $form->transformOnPlace();
 }
Esempio n. 4
0
 /**
  * Returns the cache manager instance by the desired config section.
  *
  * @param string $configSection the config section.
  *
  * @return CacheManager The desired cache manager instance.
  * @throws InvalidArgumentException In case the given config section cannot be resolved.
  *
  * @author Christian Achatz
  * @version
  * Version 0.1, 22.11.2008<br />
  * Version 0.2, 04.08.2010 (Bug-fix: initializing two cache managers failed due to wrong service mode)<br />
  * Version 0.3, 24.06.2014 (ID#207: directly injecting configuration instead of re-mapping)<br />
  */
 public function &getCacheManager($configSection)
 {
     if (!isset($this->cacheManagerCache[$configSection])) {
         // load config
         $config = $this->getConfiguration('APF\\tools\\cache', 'cacheconfig.ini');
         if (!$config->hasSection($configSection)) {
             $env = Registry::retrieve('APF\\core', 'Environment');
             throw new InvalidArgumentException('[CacheManagerFabric::getCacheManager()] The desired config section "' . $configSection . '" does not exist within the cache configuration. Please check ' . 'your cache configuration ("' . $env . '_cacheconfig.ini") for namespace ' . '"APF\\tools\\cache" and context "' . $this->context . '"!', E_USER_ERROR);
         }
         // create cache manager
         $this->cacheManagerCache[$configSection] = $this->getServiceObject(CacheManager::class, [], APFService::SERVICE_TYPE_NORMAL);
         $this->cacheManagerCache[$configSection]->init($config->getSection($configSection));
     }
     return $this->cacheManagerCache[$configSection];
 }
Esempio n. 5
0
 /**
  * Implements the functionality to retrieve a language dependent value form a
  * configuration file. Checks the attributes needed for displaying data.
  *
  * @return string The desired translation text.
  * @throws InvalidArgumentException In case of parameter issues.
  *
  * @author Christian Achatz
  * @version
  * Version 0.1, 21.04.2006<br />
  * Version 0.2, 17.10.2008 (Enhanced error messages)<br />
  * Version 0.3, 12.03.2016 (ID#287: refactoring and implementation update to new place holder scheme)<br />
  */
 public function transform()
 {
     $namespace = $this->getRequiredAttribute('namespace');
     $configName = $this->getRequiredAttribute('config');
     $entry = $this->getRequiredAttribute('entry');
     // get configuration values
     $config = $this->getConfiguration($namespace, $configName);
     $value = $config->getSection($this->getLanguage())->getValue($entry);
     if ($value === null) {
         // get environment variable from registry to have nice exception message
         $env = Registry::retrieve('APF\\core', 'Environment');
         throw new InvalidArgumentException('[' . get_class($this) . '::transform()] Given entry "' . $entry . '" is not defined in section "' . $this->getLanguage() . '" in configuration "' . $env . '_' . $configName . '" in namespace "' . $namespace . '" and context "' . $this->getContext() . '"!', E_USER_ERROR);
     }
     return $this->replace($value);
 }
 public function handleException(Exception $exception)
 {
     // fill attributes
     $this->exceptionNumber = $exception->getCode();
     $this->exceptionMessage = $exception->getMessage();
     $this->exceptionFile = $exception->getFile();
     $this->exceptionLine = $exception->getLine();
     $this->exceptionTrace = $exception->getTrace();
     $this->exceptionType = get_class($exception);
     // log exception
     $this->logException();
     // redirect to configured page
     $url = Registry::retrieve('APF\\core\\exceptionhandler', 'ProductionExceptionRedirectUrl', '/');
     header('Location: ' . $url, null, 302);
     exit(0);
 }
Esempio n. 7
0
 public function transformContent()
 {
     $appKey = $this->getAppKey();
     $newsManager = $this->getNewsManager();
     $Count = $newsManager->getNewsCount($appKey);
     $NewsList = $newsManager->getNews(0, $Count, 'DESC', $appKey);
     if (count($NewsList) === 0) {
         $this->getTemplate('noentry')->transformOnPlace();
         return;
     }
     $dataArray = [];
     // retrieve the charset from the registry to guarantee interoperability!
     $charset = Registry::retrieve('APF\\core', 'Charset');
     foreach ($NewsList as &$News) {
         $dataArray[] = ['Title' => htmlentities($News->getTitle(), ENT_QUOTES, $charset, false), 'Date' => $News->getProperty('CreationTimestamp'), 'LinkEdit' => LinkGenerator::generateUrl(Url::fromCurrent()->mergeQuery(['backendview' => 'edit', 'editnewsid' => (int) $News->getObjectId()])), 'LinkDelete' => LinkGenerator::generateUrl(Url::fromCurrent()->mergeQuery(['backendview' => 'delete', 'deletenewsid' => (int) $News->getObjectId()]))];
     }
     $I = $this->getIterator('newslist');
     $I->fillDataContainer($dataArray);
     $I->transformOnPlace();
 }
 /**
  * Displays the exception page.
  *
  * @author Christian Achatz
  * @version
  * Version 0.1, 21.02.2009<br />
  */
 public function transformContent()
 {
     // get the exception trace, init output buffer
     $document = $this->getDocument();
     $exceptions = $document->getAttribute('trace');
     $buffer = (string) '';
     // get template
     $templateExceptionEntry = $this->getTemplate('ExceptionEntry');
     // generate stacktrace
     for ($i = 0; $i < count($exceptions); $i++) {
         if (isset($exceptions[$i]['function'])) {
             $templateExceptionEntry->setPlaceHolder('Function', $exceptions[$i]['function']);
         }
         if (isset($exceptions[$i]['line'])) {
             $templateExceptionEntry->setPlaceHolder('Line', $exceptions[$i]['line']);
         }
         if (isset($exceptions[$i]['file'])) {
             $templateExceptionEntry->setPlaceHolder('File', $exceptions[$i]['file']);
         }
         if (isset($exceptions[$i]['class'])) {
             $templateExceptionEntry->setPlaceHolder('Class', $exceptions[$i]['class']);
         }
         if (isset($exceptions[$i]['type'])) {
             $templateExceptionEntry->setPlaceHolder('Type', $exceptions[$i]['type']);
         }
         $buffer .= $templateExceptionEntry->transformTemplate();
     }
     $this->setPlaceHolder('Stacktrace', $buffer);
     $this->setPlaceHolder('ExceptionID', $document->getAttribute('id'));
     $this->setPlaceHolder('ExceptionType', $document->getAttribute('type'));
     $this->setPlaceHolder('ExceptionMessage', htmlspecialchars($document->getAttribute('message'), ENT_QUOTES, Registry::retrieve('APF\\core', 'Charset'), false));
     $this->setPlaceHolder('ExceptionNumber', $document->getAttribute('number'));
     $this->setPlaceHolder('ExceptionFile', $document->getAttribute('file'));
     $this->setPlaceHolder('ExceptionLine', $document->getAttribute('line'));
     $this->setPlaceHolder('GenerationDate', date('r'));
 }
 /**
  * Loads a statement file and auto-replaces the params applied as arguments.
  *
  * @param string $namespace The namespace of the statement file.
  * @param string $name The name of the statement's file body (e.g. load_entries.sql).
  * @param array $params An associative array with param names and their respective values.
  *
  * @return string The prepared statement.
  * @throws DatabaseHandlerException In case the statement file cannot be loaded.
  *
  * @author Christian Achatz
  * @version
  * Version 0.1, 03.02.2011<br />
  */
 protected function getPreparedStatement($namespace, $name, array $params = [])
 {
     try {
         $config = $this->getConfiguration($namespace, $name);
     } catch (ConfigurationException $e) {
         $env = Registry::retrieve('APF\\core', 'Environment');
         throw new DatabaseHandlerException('[' . get_class($this) . '->getPreparedStatement()] There\'s ' . 'no statement file with name "' . $env . '_' . $name . '" for given ' . 'namespace "' . $namespace . '" and current context "' . $this->getContext() . '"! Root cause: ' . $e->getMessage(), E_USER_ERROR, $e);
     }
     /* @var $config StatementConfiguration */
     $statement = $config->getStatement();
     // replace statement param by a escaped value
     if (count($params) > 0) {
         foreach ($params as $key => $value) {
             $statement = str_replace('[' . $key . ']', $this->escapeValue($value), $statement);
         }
     }
     return $statement;
 }
Esempio n. 10
0
 /**
  * Convenience method for deleting a configuration depending on APF DOM attributes and
  * the current environment.
  *
  * @param string $namespace The namespace of the configuration.
  * @param string $name The name of the configuration including it's extension.
  *
  * @author Ralf Schubert
  * @version
  * Version 0.1, 27.07.2011<br />
  */
 protected function deleteConfiguration($namespace, $name)
 {
     ConfigurationManager::deleteConfiguration($namespace, $this->getContext(), $this->getLanguage(), Registry::retrieve('APF\\core', 'Environment'), $name);
 }
Esempio n. 11
0
\APF\core\loader\RootClassLoader::addLoader(new \APF\core\loader\StandardClassLoader('APF', $apfClassLoaderRootPath, $apfClassLoaderConfigurationRootPath));
spl_autoload_register(['\\APF\\core\\loader\\RootClassLoader', 'load']);
// register the APF error handler to be able to easily configure the error handling mechanism
GlobalExceptionHandler::registerExceptionHandler(new DefaultExceptionHandler());
GlobalExceptionHandler::enable();
// let PHP raise and display all errors to be able to handle them suitable by the APF error handler.
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('html_errors', 'off');
// register the APF error handler to be able to easily configure the error handling mechanism
GlobalErrorHandler::registerErrorHandler(new DefaultErrorHandler());
GlobalErrorHandler::enable();
// Define base parameters of the framework's core and tools layer
Registry::register('APF\\core', 'Environment', 'DEFAULT');
Registry::register('APF\\core', 'InternalLogTarget', 'apf');
Registry::register('APF\\core', 'Charset', 'UTF-8');
// set up configuration provider to let the developer customize it later on
ConfigurationManager::registerProvider('ini', new IniConfigurationProvider());
// configure logger (outside namespace'd file! otherwise initialization will not work)
register_shutdown_function(function () {
    /* @var $logger Logger */
    $logger = Singleton::getInstance(Logger::class);
    $logger->flushLogBuffer();
});
// Set up default link scheme configuration. In case url rewriting is required, please
// specify another link scheme within your application bootstrap file.
LinkGenerator::setLinkScheme(new DefaultLinkScheme());
// Add the front controller filter that is a wrapper on the front controller's input
// filters concerning thr url rewriting configuration. In case rewriting is required,
// please specify another input filter within your application bootstrap file according
// to your url mapping requirements (e.g. use the ChainedUrlRewritingInputFilter included
 * The APF is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * The APF is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with the APF. If not, see http://www.gnu.org/licenses/lgpl-3.0.txt.
 * -->
 */
echo 'This is a sample setup script, that must be adapted to your requirements! ' . 'Please do not use as is to avoid unexpected results! :)';
exit(0);
// include APF bootstrap file
require './APF/core/bootstrap.php';
// configure the registry if desired
use APF\core\registry\Registry;
Registry::register('APF\\core', 'Environment', '{ENVIRONMENT}');
use APF\modules\genericormapper\data\tools\GenericORMapperDomainObjectGenerator;
// create setup tool
$generator = new GenericORMapperDomainObjectGenerator();
// set context (important for the configuration files!)
$generator->setContext('{CONTEXT}');
// initialize mapping configuration
$generator->addMappingConfiguration('{CONFIG_NAMESPACE}', '{CONFIG_NAME_AFFIX}');
// initialize domain object configuration
$generator->addDomainObjectsConfiguration('{CONFIG_NAMESPACE}', '{CONFIG_NAME_AFFIX}');
$generator->generateServiceObjects();
Esempio n. 13
0
 /**
  * Escapes special characters with respect to the php.ini settings.
  *
  * @param string $string The string to escape the special characters within.
  *
  * @return string The escaped string.
  *
  * @author Christian Schäfer
  * @version
  * Version 0.1, 11.01.2005<br />
  */
 public static function escapeSpecialCharacters($string)
 {
     return addslashes(htmlspecialchars($string, ENT_QUOTES, Registry::retrieve('APF\\core', 'Charset'), false));
 }
Esempio n. 14
0
 /**
  * Creates a string representation of the given attributes list, using a
  * white list to especially include attributes.
  *
  * @param array $attributes The list of attributes to convert to an xml string.
  * @param array $whiteList The list of attributes, the string may contain.
  *
  * @return string The xml attributes string.
  *
  * @author Christian Achatz
  * @version
  * Version 0.1, 13.02.2010 (Replaced old implementation with the white list feature.)<br />
  * Version 0.2, 27.11.2013 (Added default data-* attribute support to ease white list maintenance)<br />
  */
 protected function getAttributesAsString(array $attributes, array $whiteList = [])
 {
     $attributeParts = [];
     // process white list entries only, when attribute is given
     // code duplication is done here due to performance reasons!!!
     $charset = Registry::retrieve('APF\\core', 'Charset');
     if (count($whiteList) > 0) {
         foreach ($attributes as $name => $value) {
             // allow "data-*" attributes by default to not deal with complicated white list configuration
             if (strpos($name, 'data-') !== false || in_array($name, $whiteList)) {
                 $attributeParts[] = $name . '="' . htmlspecialchars($value, ENT_QUOTES, $charset, false) . '"';
             }
         }
     } else {
         foreach ($attributes as $name => $value) {
             $attributeParts[] = $name . '="' . htmlspecialchars($value, ENT_QUOTES, $charset, false) . '"';
         }
     }
     return implode(' ', $attributeParts);
 }
Esempio n. 15
0
 public function transformForm()
 {
     $t = Singleton::getInstance(BenchmarkTimer::class);
     /* @var $t BenchmarkTimer */
     $id = '(HtmlFormTag) ' . $this->getObjectId() . '::transformForm()';
     $t->start($id);
     // add action attribute if not set
     $action = $this->getAttribute(self::ACTION_ATTRIBUTE_NAME);
     if ($action === null) {
         $this->setAttribute(self::ACTION_ATTRIBUTE_NAME, $this->getRequest()->getRequestUri());
     }
     // ID#239: always encode action attribute when present to secure custom actions as well as auto-generated ones
     $this->setAttribute(self::ACTION_ATTRIBUTE_NAME, htmlspecialchars($this->getAttribute(self::ACTION_ATTRIBUTE_NAME), ENT_QUOTES, Registry::retrieve('APF\\core', 'Charset'), false));
     // transform the form including all child tags
     $htmlCode = (string) '<form ';
     $htmlCode .= $this->getAttributesAsString($this->attributes, $this->attributeWhiteList);
     $htmlCode .= '>';
     // ID#281: add hidden form fields with URL get parameters for GET forms for convenience reasons
     if ($this->getAttribute(self::METHOD_ATTRIBUTE_NAME) === self::METHOD_GET_VALUE_NAME && $this->getAttribute(self::SUBMIT_ACTION_URL_PARAMS_ATTRIBUTE_NAME) === 'true') {
         $url = Url::fromString($this->getAttribute(self::ACTION_ATTRIBUTE_NAME));
         $queryParams = $url->getQuery();
         if (count($queryParams) > 0) {
             $hiddenFieldMarker = '';
             foreach ($queryParams as $name => $value) {
                 $control = $this->createFormElement($this, 'form:hidden', ['name' => $name, 'value' => $value]);
                 $hiddenFieldMarker .= '<' . $control->getObjectId() . ' />';
             }
             // prepend fields to preserve parameter order
             $this->content = $hiddenFieldMarker . $this->content;
         }
     }
     if (count($this->children) > 0) {
         foreach ($this->children as &$child) {
             $childId = '(' . get_class($child) . ') ' . $child->getObjectId() . '::transform()';
             $t->start($childId);
             $this->content = str_replace('<' . $child->getObjectId() . ' />', $child->transform(), $this->content);
             $t->stop($childId);
         }
     }
     $htmlCode .= $this->content;
     $htmlCode .= '</form>';
     $t->stop($id);
     return $htmlCode;
 }
Esempio n. 16
0
 /**
  * Sanitizes a generated URL to avoid XSS. Attack vector is to injecting XSS code as a URL parameter name
  * with an application that directly passes the URL to the generated HTML code even if the
  * XssProtectionInputFilter is used.
  *
  * @param string $url The url to sanitize.
  *
  * @return string The sanitized url.
  */
 protected function sanitizeUrl($url)
 {
     return strip_tags(html_entity_decode($url, ENT_QUOTES, Registry::retrieve('APF\\core', 'Charset')));
 }
Esempio n. 17
0
 /**
  * Returns the initialized handler for the desired connection key. Caches connections, that
  * were created previously.
  * <p/>
  * Using the database driver instance id, you can force the ConnectionManager to create
  * several connections with the same connection key. Please be careful with this feature,
  * since it may significantly decrease performance!
  *
  * @param string $connectionKey Desired configuration section.
  * @param string $instanceId The id of the database driver instance.
  *
  * @return AbstractDatabaseHandler An instance of a connection layer implementation.
  * @throws InvalidArgumentException In case of missing configuration.
  *
  * @author Christian Achatz, Tobias Lückel (megger)
  * @version
  * Version 0.1, 09.11.2007<br />
  * Version 0.2, 23.02.2008<br />
  * Version 0.3, 24.02.2008 (Introduced caching)<br />
  * Version 0.4, 21.06.2008 (Replaced APPS__ENVIRONMENT with a value from the Registry)<br />
  * Version 0.5, 05.10.2008 (Bug-fix: usage of two or more identical connections (e.g. of type MySQLx) led to interferences. Thus, service object usage was changed)<br />
  * Version 0.6, 30.01.2009 (Added a check, that the old MySQLHandler cannot be used with the ConnectionManager. Doing so leads to bad connection interference!)<br />
  * Version 0.7, 22.03.2009 (Added the context to the error message, to ease debugging)<br />
  * Version 0.8, 20.09.2009 (Removed check for MySQLHandler usage, due to removal of the MySQLHandler)<br />
  * Version 0.9, 07.05.2012 (Introduced connection identifier to enable multiple connections for the same connection key)<br />
  */
 public function &getConnection($connectionKey, $instanceId = 'default')
 {
     // check, if connection was already created
     $cacheKey = $connectionKey . $instanceId;
     if (isset($this->connections[$cacheKey])) {
         return $this->connections[$cacheKey];
     }
     // TODO decide whether database connections must be fully qualified in the future as well (e.g. like DI services)
     $config = $this->getConfiguration('APF\\core\\database', 'connections.' . self::$configurationExtension);
     if (!$config->hasSection($connectionKey)) {
         $env = Registry::retrieve('APF\\core', 'Environment');
         throw new InvalidArgumentException('[ConnectionManager::getConnection()] The given ' . 'configuration section ("' . $connectionKey . '") does not exist in configuration file "' . $env . '_connections.ini" in namespace "APF\\core\\database" for context "' . $this->context . '"!', E_USER_ERROR);
     }
     // get config section
     $section = $config->getSection($connectionKey);
     // re-map options to array to be able to initialize the database connection using the service manager
     $options = [];
     foreach ($section->getValueNames() as $key) {
         $options[$key] = $section->getValue($key);
     }
     // create the connection lazily
     $this->connections[$cacheKey] = $this->getServiceObject($section->getValue('Type'), [], APFService::SERVICE_TYPE_NORMAL);
     $this->connections[$cacheKey]->init($options);
     return $this->connections[$cacheKey];
 }
Esempio n. 18
0
 /**
  * Adds an action to the front controller action stack. Please note, that the namespace of
  * the namespace of the action config is added the current context. The name of the
  * config file is concatenated by the current environment and the string
  * <em>*_actionconfig.ini</em>.
  *
  * @param string $namespace Namespace of the action.
  * @param string $name Name of the action (section key of the config file).
  * @param array $params (Input-)params of the action.
  *
  * @throws InvalidArgumentException In case the action cannot be found within the appropriate
  * configuration or the action implementation classes are not available.
  *
  * @author Christian Achatz
  * @version
  * Version 0.1, 05.06.2007<br />
  * Version 0.2, 01.07.2007<br />
  * Version 0.3, 02.09.2007<br />
  * Version 0.4, 08.09.2007 (Bug-fix: input params from config are now evaluated)<br />
  * Version 0.5, 08.11.2007 (Changed action stack construction to hash offsets)<br />
  * Version 0.6, 21.06.2008 (Replaced APPS__ENVIRONMENT constant with a value from the Registry)<br />
  * Version 0.7, 27.09.2010 (Removed synthetic "actions" sub-namespace)<br />
  * Version 0.8, 09.04.2011 (Made input implementation optional, removed separate action and input class file definition)<br />
  * Version 0.9. 20.08.2013 Jan Wiese (Added support for actions generated by thw DIServiceManager)<br />
  */
 public function addAction($namespace, $name, array $params = [])
 {
     // re-map namespace
     $namespace = $this->getActionNamespaceByURLString($namespace);
     // load the action configuration
     $config = $this->getConfiguration($namespace, 'actionconfig.ini');
     // throw exception, in case the action config is not present
     if (!$config->hasSection($name)) {
         $env = Registry::retrieve('APF\\core', 'Environment');
         throw new InvalidArgumentException('[Frontcontroller::addAction()] No config ' . 'section for action key "' . $name . '" available in configuration file "' . $env . '_actionconfig.ini" in namespace "' . $namespace . '" and context "' . $this->getContext() . '"!', E_USER_ERROR);
     }
     $actionConfig = $config->getSection($name);
     // evaluate which method to use: simple object or di service
     $actionServiceName = $actionConfig->getValue('ActionServiceName');
     $actionServiceNamespace = $actionConfig->getValue('ActionServiceNamespace');
     if (!(empty($actionServiceName) || empty($actionServiceNamespace))) {
         // use di service
         try {
             $action = DIServiceManager::getServiceObject($actionServiceNamespace, $actionServiceName, $this->getContext(), $this->getLanguage());
         } catch (Exception $e) {
             throw new InvalidArgumentException('[Frontcontroller::addAction()] Action could not
         be created using DIServiceManager with service name "' . $actionServiceName . '" and service
         namespace "' . $actionServiceNamespace . '". Please check your action and service
         configuration files! Message from DIServiceManager was: ' . $e->getMessage(), $e->getCode());
         }
     } else {
         // use simple object
         // include action implementation
         $actionClass = $actionConfig->getValue('ActionClass');
         // check for class being present
         if (!class_exists($actionClass)) {
             throw new InvalidArgumentException('[Frontcontroller::addAction()] Action class with name "' . $actionClass . '" could not be found. Please check your action configuration file!', E_USER_ERROR);
         }
         // init action
         $action = new $actionClass();
         /* @var $action Action */
         $action->setContext($this->getContext());
         $action->setLanguage($this->getLanguage());
     }
     // init action
     $action->setActionNamespace($namespace);
     $action->setActionName($name);
     // check for custom input implementation
     $inputClass = $actionConfig->getValue('InputClass');
     // include input implementation in case a custom implementation is desired
     if (empty($inputClass)) {
         $inputClass = FrontcontrollerInput::class;
     }
     // check for class being present
     if (!class_exists($inputClass)) {
         throw new InvalidArgumentException('[Frontcontroller::addAction()] Input class with name "' . $inputClass . '" could not be found. Please check your action configuration file!', E_USER_ERROR);
     }
     // init input
     $input = new $inputClass();
     /* @var $input FrontcontrollerInput */
     // merge input params with the configured params (params included in the URL are kept!)
     $input->setParameters(array_merge($this->generateParamsFromInputConfig($actionConfig->getValue('InputParams')), $params));
     $input->setAction($action);
     $action->setInput($input);
     // set the frontcontroller as a parent object to the action
     $action->setFrontController($this);
     // add the action as a child
     $this->actionStack[] = $action;
     // ID#83: Sort actions to allow prioritization of actions. This is done using
     // uksort() in order to both respect Action::getPriority()
     // and the order of registration for equivalence groups.
     uksort($this->actionStack, [$this, 'sortActions']);
 }
Esempio n. 19
0
 /**
  * @public
  * @depends testRegisterReadonlyMethod
  *
  * Tests default usage of the retrieve method
  *
  * @return void
  *
  * @author Florian Horn
  * @version
  * Version 0.1, 17.12.2011<br />
  */
 public function testRetrieveMethod()
 {
     Registry::register(self::$REGISTRY_NAMESPACE, self::$REGISTRY_NAME, self::$REGISTRY_VALUE, true);
     $sReturnValue = Registry::retrieve(self::$REGISTRY_NAMESPACE, self::$REGISTRY_NAME);
     $this->assertEquals(self::$REGISTRY_VALUE, $sReturnValue);
     $sReturnValue = Registry::retrieve(self::$REGISTRY_NAMESPACE, self::$REGISTRY_NAME, self::$REGISTRY_DEFAULT_VALUE);
     $this->assertEquals(self::$REGISTRY_VALUE, $sReturnValue);
     $sReturnValue = Registry::retrieve(self::$REGISTRY_NAMESPACE . '42', self::$REGISTRY_NAME);
     $this->assertNull($sReturnValue);
     $sReturnValue = Registry::retrieve(self::$REGISTRY_NAMESPACE . '42', self::$REGISTRY_NAME, self::$REGISTRY_DEFAULT_VALUE);
     $this->assertEquals(self::$REGISTRY_DEFAULT_VALUE, $sReturnValue);
     $sReturnValue = Registry::retrieve(self::$REGISTRY_NAMESPACE, self::$REGISTRY_NAME . '42');
     $this->assertNull($sReturnValue);
     $sReturnValue = Registry::retrieve(self::$REGISTRY_NAMESPACE, self::$REGISTRY_NAME . '42', self::$REGISTRY_DEFAULT_VALUE);
     $this->assertEquals(self::$REGISTRY_DEFAULT_VALUE, $sReturnValue);
     $sReturnValue = Registry::retrieve(self::$REGISTRY_NAMESPACE . '42', self::$REGISTRY_NAME . '42');
     $this->assertNull($sReturnValue);
     $sReturnValue = Registry::retrieve(self::$REGISTRY_NAMESPACE . '42', self::$REGISTRY_NAME . '42', self::$REGISTRY_DEFAULT_VALUE);
     $this->assertEquals(self::$REGISTRY_DEFAULT_VALUE, $sReturnValue);
 }
Esempio n. 20
0
 public function testThresholdOverride2()
 {
     $logger = new Logger();
     $target = Registry::retrieve('APF\\core', 'InternalLogTarget');
     $writer = new RecordingLogWriter();
     $logger->addLogWriter($target, $writer);
     $logger->setLogThreshold(Logger::$LOGGER_THRESHOLD_ERROR);
     // log all in case more than 20 errors or more than 1 fatal comes up
     $logger->setThresholdOverride([LogEntry::SEVERITY_ERROR => 20, LogEntry::SEVERITY_FATAL => 1]);
     // test than one fatal overrides
     $logger->logEntry($target, self::LOG_MESSAGE_ONE, LogEntry::SEVERITY_FATAL);
     $logger->logEntry($target, self::LOG_MESSAGE_ONE, LogEntry::SEVERITY_DEBUG);
     $logger->logEntry($target, self::LOG_MESSAGE_ONE, LogEntry::SEVERITY_INFO);
     $logger->logEntry($target, self::LOG_MESSAGE_ONE, LogEntry::SEVERITY_WARNING);
     $logger->logEntry($target, self::LOG_MESSAGE_ONE, LogEntry::SEVERITY_ERROR);
     $logger->flushLogBuffer();
     $actual = $writer->getEntries();
     $this->assertNotEmpty($actual);
     $this->assertCount(5, $actual);
 }
 /**
  * Creates a log entry containing the exception occurred.
  *
  * @author Christian Achatz
  * @version
  * Version 0.1, 21.02.2009<br />
  */
 protected function logException()
 {
     $message = '[' . $this->generateExceptionID() . '] ' . $this->exceptionMessage . ' (Number: ' . $this->exceptionNumber . ', File: ' . $this->exceptionFile . ', Line: ' . $this->exceptionLine . ')';
     $log = Singleton::getInstance(Logger::class);
     /* @var $log Logger */
     $log->addEntry(new SimpleLogEntry(Registry::retrieve('APF\\core', 'InternalLogTarget'), $message, LogEntry::SEVERITY_ERROR));
 }
Esempio n. 22
0
 public function filter($input)
 {
     return htmlentities(str_replace('&amp;', '&', $input), null, Registry::retrieve('APF\\core', 'Charset'));
 }
 public function __construct()
 {
     $this->charset = Registry::retrieve('APF\\core', 'Charset');
 }
Esempio n. 24
0
 /**
  * Initializes the logger.
  * <p/>
  * Please be aware, that starting with release 1.15 DEBUG and TRACE statements
  * are not automatically written to the log file due to the default severity
  * threshold configuration.
  *
  * @author Christian Achatz
  * @version
  * Version 0.1, 29.03.2007<br />
  * Version 0.2, 02.04.2007<br />
  * Version 0.3, 21.06.2008<br />
  * Version 0.4, 14.08.2008 (LogDir initialization was moved do the flushLogBuffer() method)<br />
  * Version 0.5, 12.01.2013 (Moved log dir initialization to log writer)<br />
  */
 public function __construct()
 {
     $this->logThreshold = self::$LOGGER_THRESHOLD_WARN;
     // By default, a file-based log writer is initialized.
     // Please note, that the writer's target name can be configured
     // within the Registry for all framework-related log statements.
     $this->addLogWriter(Registry::retrieve('APF\\core', 'InternalLogTarget'), new FileLogWriter(str_replace('\\', '/', getcwd()) . '/logs'));
 }
Esempio n. 25
0
 /**
  * Loads the service configuration.
  *
  * @param string $configNamespace The namespace of the service (a.k.a. config namespace).
  * @param string $context The context of the current application.
  * @param string $language The language of the current application.
  * @param string $cacheKey The cache key to check/find configuration in configuration cache
  *
  * @return Configuration The appropriate configuration.
  *
  * @author Christian Achatz
  * @version
  * Version 0.1, 04.10.2010<br />
  * Version 0.2, 15.07.2012 Jan Wiese (Introduced configuration cache and $cacheKey parameter)<br />
  */
 private static function getServiceConfiguration($configNamespace, $context, $language, $cacheKey)
 {
     // return cached version as much as possible to gain performance
     if (isset(self::$SERVICE_CONFIG_CACHE[$cacheKey])) {
         return self::$SERVICE_CONFIG_CACHE[$cacheKey];
     }
     self::$SERVICE_CONFIG_CACHE[$cacheKey] = ConfigurationManager::loadConfiguration($configNamespace, $context, $language, Registry::retrieve('APF\\core', 'Environment'), 'serviceobjects.' . self::$configurationExtension);
     return self::$SERVICE_CONFIG_CACHE[$cacheKey];
 }