Example #1
0
 private function __construct()
 {
     //获取环境参数
     $this->env = Environment::getInstance()->get();
     //HTTP request headers (retains HTTP_ prefix to match $_SERVER)
     $this->headers = Headers::extract($_SERVER);
 }
Example #2
0
 /**
  * Initialize app
  */
 public function run()
 {
     if (!isset($this->container['env']) || is_null($this->container['env'])) {
         $this->container['env'] = Environment::getInstance();
     }
     if (!isset($this->container['akismet']) || is_null($this->container['akismet'])) {
         // Initialize Akismet
         $connector = new \Riv\Service\Akismet\Connector\Curl();
         $this->container['akismet'] = new \Riv\Service\Akismet\Akismet($connector);
     }
     if (!isset($this->container['email']) || is_null($this->container['email'])) {
         // Initialize email
         $transport = \Swift_MailTransport::newInstance();
         $this->container['email'] = \Swift_Mailer::newInstance($transport);
     }
     if (!isset($this->container['cache']) || is_null($this->container['cache'])) {
         if (defined('CACHE_FOLDER')) {
             $driver = new \Stash\Driver\FileSystem(array('path' => CACHE_FOLDER));
         } else {
             $driver = new \Stash\Driver\FileSystem();
         }
         $this->container['cache'] = new \Stash\Pool($driver);
     }
     if (!isset($this->container['currentuser']) || is_null($this->container['currentuser'])) {
         $this->container['currentuser'] = new CurrentUser();
     }
     if (!isset($this->container['db']) || !$this->container['db'] instanceof \ezSQL_mysqli) {
         throw new \Exception('No db setup');
     }
     if (!isset($this->container['safesql']) || !$this->container['safesql'] instanceof \SafeSQL_MySQLi) {
         throw new \Exception('No safesql setup');
     }
 }
Example #3
0
 /**
  * @param DC_General $dc
  */
 public function renderPreviewView(EnvironmentInterface $environment)
 {
     /** @var EventDispatcher $eventDispatcher */
     $eventDispatcher = $GLOBALS['container']['event-dispatcher'];
     $eventDispatcher->dispatch(ContaoEvents::SYSTEM_LOAD_LANGUAGE_FILE, new LoadLanguageFileEvent('avisota_message_preview'));
     $eventDispatcher->dispatch(ContaoEvents::SYSTEM_LOAD_LANGUAGE_FILE, new LoadLanguageFileEvent('orm_avisota_message'));
     $input = \Input::getInstance();
     $messageRepository = EntityHelper::getRepository('Avisota\\Contao:Message');
     $messageId = IdSerializer::fromSerialized($input->get('id') ? $input->get('id') : $input->get('pid'));
     $message = $messageRepository->find($messageId->getId());
     if (!$message) {
         $environment = \Environment::getInstance();
         $eventDispatcher->dispatch(ContaoEvents::CONTROLLER_REDIRECT, new RedirectEvent(preg_replace('#&(act=preview|id=[a-f0-9\\-]+)#', '', $environment->request)));
     }
     $modules = new \StringBuilder();
     /** @var \Avisota\Contao\Message\Core\Send\SendModuleInterface $module */
     foreach ($GLOBALS['AVISOTA_SEND_MODULE'] as $className) {
         $class = new \ReflectionClass($className);
         $module = $class->newInstance();
         $modules->append($module->run($message));
     }
     $context = array('message' => $message, 'modules' => $modules);
     $template = new \TwigTemplate('avisota/backend/preview', 'html5');
     return $template->parse($context);
 }
 protected static function authenticateBackendUser()
 {
     $objUser = self::getUser();
     // work around as the TL_PATH constant is set after this routine has been run.
     // if this is not in place, BackendUser::authenticate() will redirect us to
     // http://domain.tldtl_path/contao/index.php
     // if no user is properly logged in (note the missing slash in the middle right after .tld).
     // We also have to fix up the "script" parameter, as this one will otherwise try to redirect from
     // "contao/index.php" to "/contao/index.php" therefore creating an infinite redirect loop.
     $Env = Environment::getInstance();
     // issue #66 - contao/install.php is not working anymore. Thanks to Stefan Lindecke (@lindesbs)
     if (strpos($Env->request, "install.php") !== false) {
         return;
     }
     // Fix issue #397 - the security patch rendered our redirect method non working (websitePath can now be null).
     $path = constant('TL_PATH') ?: $GLOBALS['TL_CONFIG']['websitePath'];
     $Env->base = $Env->url . $path . '/';
     $Env->script = preg_replace('/^' . preg_quote($path, '/') . '\\/?/i', '', $Env->scriptName);
     // Bugfix: If the user is not authenticated, contao will redirect to contao/index.php
     // But in this moment the TL_PATH is not defined, so the $this->Environment->request
     // generate a url without replacing the basepath(TL_PATH) with an empty string.
     if (!defined(TL_PATH)) {
         define('TL_PATH', $path);
     }
     // TODO: double, triple and quadro check that this is really safe context here.
     $objUser->authenticate();
     // restore initial settings.
     $Env->base = null;
     $Env->script = null;
 }
    public function load(AbstractMetaModel $environment_metamodel, array $filters = NULL) {
        LogHelper::log_notice(t('Loading Environment Meta Model from settings.php ...'));

        $datasourceCount = 0;

        $configurationDataSources = Environment::getInstance()->getConfigurationSection('Data Sources');
        if (isset($configurationDataSources)) {
            foreach ($configurationDataSources as $namespace => $sourceDataSources) {
                foreach ($sourceDataSources as $datasourceName => $sourceDataSource) {
                    $datasourceName = NameSpaceHelper::resolveNameSpace($namespace, $datasourceName);

                    $datasource = new DataSourceMetaData();
                    $datasource->name = $datasourceName;
                    $datasource->initializeFrom($sourceDataSource);
                    // it is possible that configuration contains 'readonly' property. We need to honor it
                    // ... and only when it is not set we mark the data source as read only
                    if (!isset($datasource->readonly)) {
                        $datasource->readonly = TRUE;
                    }

                    $environment_metamodel->registerDataSource($datasource);

                    $datasourceCount++;
                }
            }
        }

        LogHelper::log_info(t('Processed @datasourceCount data sources', array('@datasourceCount' => $datasourceCount)));
    }
Example #6
0
 public function constx($value)
 {
     $symbol = "__?__";
     $this->symbolManager->setSymbol($symbol);
     Environment::getInstance()->attach($symbol, $value);
     return $this;
 }
Example #7
0
 /**
  * Initialize object stack.
  *
  * @return void
  */
 public static function intializeObjectStack()
 {
     \Config::getInstance();
     \Environment::getInstance();
     \Input::getInstance();
     static::getUser();
     \Database::getInstance();
 }
Example #8
0
 public function createPublicEmptyRecipient(CreatePublicEmptyRecipientEvent $event)
 {
     if ($event->getRecipient()) {
         return;
     }
     $environment = \Environment::getInstance();
     $event->setRecipient(new MutableRecipient('noreply@' . $environment->host));
 }
Example #9
0
 public function __construct()
 {
     parent::__construct();
     $this->handlerConfigurations = module_invoke_all('dc_cache');
     // preparing default value for cache entry expiration time
     $cacheConfigurationSection = Environment::getInstance()->getConfigurationSection('Cache');
     if (isset($cacheConfigurationSection['Entry Expiration']['Default'])) {
         AbstractCacheHandler::$DEFAULT__ENTRY_EXPIRATION = $cacheConfigurationSection['Entry Expiration']['Default'];
     }
 }
 protected function execute(Message $message, \BackendUser $user)
 {
     global $container;
     /** @var \Symfony\Component\EventDispatcher\EventDispatcher $eventDispatcher */
     $eventDispatcher = $GLOBALS['container']['event-dispatcher'];
     $input = \Input::getInstance();
     $user = $input->get('recipient_user');
     /** @var \Doctrine\DBAL\Connection $connection */
     $connection = $container['doctrine.connection.default'];
     $queryBuilder = $connection->createQueryBuilder();
     /** @var \Doctrine\DBAL\Statement $statement */
     $statement = $queryBuilder->select('u.*')->from('tl_user', 'u')->where('id=:id')->setParameter(':id', $user)->execute();
     $userData = $statement->fetch();
     if (!$userData) {
         $_SESSION['AVISOTA_SEND_PREVIEW_TO_USER_EMPTY'] = true;
         header('Location: ' . $url);
         exit;
     }
     $idSerializer = new IdSerializer();
     $idSerializer->setDataProviderName('orm_avisota_message');
     $idSerializer->setId($message->getId());
     $pidSerializer = new IdSerializer();
     $pidSerializer->setDataProviderName('orm_avisota_message_category');
     $pidSerializer->setId($message->getCategory()->getId());
     $environment = Environment::getInstance();
     $url = sprintf('%scontao/main.php?do=avisota_newsletter&table=orm_avisota_message&act=preview&id=%s&pid=%s', $environment->base, $idSerializer->getSerialized(), $pidSerializer->getSerialized());
     if ($message->getCategory()->getViewOnlinePage()) {
         $event = new LoadLanguageFileEvent('avisota_message');
         $eventDispatcher->dispatch(ContaoEvents::SYSTEM_LOAD_LANGUAGE_FILE, $event);
         $viewOnlineLink = sprintf($GLOBALS['TL_LANG']['avisota_message']['viewOnline'], $url);
     } else {
         $viewOnlineLink = false;
     }
     $event = new \Avisota\Contao\Core\Event\CreateFakeRecipientEvent($message);
     $eventDispatcher->dispatch(\Avisota\Contao\Core\CoreEvents::CREATE_FAKE_RECIPIENT, $event);
     $recipient = $event->getRecipient();
     $recipient->setEmail($userData['email']);
     $additionalData = array('view_online_link' => $viewOnlineLink);
     /** @var \Avisota\Contao\Message\Core\Renderer\MessageRendererInterface $renderer */
     $renderer = $container['avisota.message.renderer'];
     $messageTemplate = $renderer->renderMessage($message);
     $messageMail = $messageTemplate->render($recipient, $additionalData);
     /** @var \Avisota\Transport\TransportInterface $transport */
     $transport = $GLOBALS['container']['avisota.transport.' . $message->getQueue()->getTransport()->getId()];
     $transport->send($messageMail);
     $event = new \ContaoCommunityAlliance\Contao\Bindings\Events\System\LoadLanguageFileEvent('avisota_message_preview');
     $eventDispatcher->dispatch(\ContaoCommunityAlliance\Contao\Bindings\ContaoEvents::SYSTEM_LOAD_LANGUAGE_FILE, $event);
     $_SESSION['TL_CONFIRM'][] = sprintf($GLOBALS['TL_LANG']['avisota_message_preview']['previewSend'], $recipient->getEmail());
     header('Location: ' . $url);
     exit;
 }
 public function setUp()
 {
     parent::setUp();
     Configure::write('debug', 0);
     $this->Environment = Environment::getInstance();
     $envs = array(array('name' => 'staging', 'params' => array('SERVER_NAME' => 'example.tld'), 'config' => array('debug' => 2, 'Session.name' => 'staging-session', 'security' => 'low'), 'callable' => null), array('name' => 'production', 'params' => array('SERVER_NAME' => 'production.tld', 'SERVER_ADDR' => '8.8.8.8'), 'config' => array('debug' => 1, 'Session.name' => 'production-session'), 'callable' => null), array('name' => 'preproduction', 'params' => array('SERVER_NAME' => array('preproduction.tld', 'preprod.local')), 'config' => array('debug' => 1, 'Session.name' => 'preproduction-session'), 'callable' => function () {
         Configure::write('Environment.callback', true);
     }), array('name' => 'dev1', 'params' => false, 'config' => array(), 'callable' => null), array('name' => 'dev2', 'params' => array('is_bool' => 'Hello, World!'), 'config' => array(), 'callable' => array()));
     foreach ($envs as $env) {
         Environment::configure($env['name'], $env['params'], $env['config'], $env['callable']);
     }
     Configure::read('Environment.setup', false);
     $_SERVER['CAKE_ENV'] = null;
 }
 /**
  * This initializes the Contao Singleton object stack as it must be,
  * when using singletons within the config.php file of an Extension.
  *
  * @return void
  */
 protected static function initializeContaoObjectStack()
 {
     // all of these getInstance calls are neccessary to keep the instance stack intact
     // and therefore prevent an Exception in unknown on line 0.
     // Hopefully this will get fixed with Contao Reloaded or Contao 3.
     Config::getInstance();
     Environment::getInstance();
     Input::getInstance();
     // request token became available in 2.11
     if (version_compare(TL_VERSION, '2.11', '>=')) {
         RequestToken::getInstance();
     }
     self::getUser();
     Database::getInstance();
 }
Example #13
0
 public function addLinksToTemplate(\FrontendTemplate $objTemplate, \stdClass $objConfig, $intParent)
 {
     $objTemplate->LinksToUs = array();
     $objEnvironment = \Environment::getInstance();
     $folder = \FilesModel::findByPk($objConfig->bannerFolder);
     $bannerFolder = TL_ROOT . "/" . $folder->path;
     $handle = opendir($bannerFolder);
     while ($file = readdir($handle)) {
         $filelist[] = $file;
     }
     asort($filelist);
     $count = 0;
     if ($objConfig->template == '') {
         $objConfig->template = 'links2us_banner';
     }
     $objEntry = new \FrontendTemplate($objConfig->template);
     while (list($a, $file) = each($filelist)) {
         if (exif_imagetype($bannerFolder . "/" . $file) == IMAGETYPE_GIF || exif_imagetype($bannerFolder . "/" . $file) == IMAGETYPE_JPEG || exif_imagetype($bannerFolder . "/" . $file) == IMAGETYPE_PNG) {
             if ($objConfig->bannerSize) {
                 $dimension = getimagesize($bannerFolder . "/" . $file);
                 $dimensionXL = $GLOBALS['TL_LANG']['MSC']['size'] . $dimension[0] . "x" . $dimension[1];
                 $bannerInfo = $dimensionXL;
             }
             if ($objConfig->bannerByte) {
                 $filesize = filesize($bannerFolder . "/" . $file);
                 $filesize = number_format($filesize / 1024, 2);
                 $filesizeXL = $GLOBALS['TL_LANG']['MSC']['bytes'] . $filesize . "kb";
                 $bannerInfo = $filesizeXL;
             }
             if ($objConfig->bannerSize && $objConfig->bannerByte) {
                 $bannerInfo = $dimensionXL . " ( " . $filesize . "kb ) ";
             }
             $objEntry->bannerSRC = $objEnvironment->base . $folder->path . "/" . $file;
             $objEntry->bCount = $count;
             $objEntry->toClipboard = $objConfig->toClipboard;
             $objEntry->bannerInfo = $bannerInfo;
             $arrLinkBanners[] = $objEntry->parse();
             ++$count;
         }
     }
     $objTemplate->backLink = $objConfig->backLink;
     $objTemplate->LinkBanners = $arrLinkBanners;
     $objTemplate->color = ' ' . $objConfig->modColor;
     $objTemplate->TeaserText = $objConfig->TeaserText;
     $objTemplate->displayTextLink = $objConfig->displayTextLink;
     $objTemplate->CopytoClip = $objConfig->toClipboard;
     $objTemplate->backInfo = '<p class="backlink">Links2Us by <a href="http://jedo-style.de">jedo Style</a></p>';
 }
Example #14
0
 /**
  * Initialize the composer environment.
  */
 public static function initialize()
 {
     if (version_compare(PHP_VERSION, COMPOSER_MIN_PHPVERSION, '<')) {
         return;
     }
     if (TL_MODE == 'BE') {
         $GLOBALS['TL_HOOKS']['loadLanguageFile']['composer'] = array('ContaoCommunityAlliance\\Contao\\Composer\\Client', 'disableOldClientHook');
         $input = \Input::getInstance();
         if ($input->get('do') == 'repository_manager') {
             $environment = \Environment::getInstance();
             header('Location: ' . $environment->base . 'contao/main.php?do=composer');
             exit;
         }
     }
     static::registerVendorClassLoader();
 }
Example #15
0
 private function __construct($entrance)
 {
     //创建config
     $this->AppDefaultConfig = $this->AppDefaultConfig();
     //入口配置
     $this->ent = $entrance;
     //获取环境参数
     $this->env = Environment::getInstance()->get();
     //HTTP request headers (retains HTTP_ prefix to match $_SERVER)
     $this->headers = Headers::extract($_SERVER);
     //获取app 配置
     $file = $this->ent['CONF_FILE'] = $this->ent['CONF_FILE'] ?: 'Conf.php';
     $this->app = G($this->ent['APP_PATH'] . $file);
     //所有配置的模块列表
     $modulelist = $this->ent['modulelist'] ?: $this->app['modulelist'];
     $modulelist = is_array($modulelist) ? $modulelist : [];
     $this->modulelist = array_keys($modulelist);
 }
 /**
  * Generate the pagination menu and return it as HTML string
  *
  * @param string
  *
  * @return string
  */
 public function generate($strSeparator = '')
 {
     $this->intTotalPages = $this->intRows;
     // Return if there is only one page
     if ($this->intTotalPages < 2 || $this->intRows < 1) {
         return '';
     }
     $this->intPage = -1;
     $strRequest = rawurldecode(\Environment::getInstance()->request);
     foreach ($this->arrLinks as $intPage => $strLink) {
         if ($strRequest == rawurldecode($strLink)) {
             $this->intPage = $intPage + 1;
             break;
         }
     }
     if ($this->intPage == -1) {
         return '';
     }
     if ($this->intPage > $this->intTotalPages) {
         $this->intPage = $this->intTotalPages;
     }
     $this->Template = new TwigFrontendTemplate('pagination');
     $this->Template->hasFirst = $this->hasFirst();
     $this->Template->hasPrevious = $this->hasPrevious();
     $this->Template->hasNext = $this->hasNext();
     $this->Template->hasLast = $this->hasLast();
     $this->Template->items = $this->getItems();
     $this->Template->page = $this->intPage;
     $this->Template->total = $this->intTotalPages;
     $this->Template->first = array('page' => 1, 'link' => $this->lblFirst, 'href' => $this->arrLinks[0]);
     $this->Template->previous = array('page' => $this->intPage - 1, 'link' => $this->lblPrevious, 'href' => $this->arrLinks[$this->intPage - 2]);
     $this->Template->next = array('page' => $this->intPage + 1, 'link' => $this->lblNext, 'href' => $this->arrLinks[$this->intPage]);
     $this->Template->last = array('page' => $this->intTotalPages, 'link' => $this->lblLast, 'href' => $this->arrLinks[count($this->arrLinks) - 1]);
     global $objPage;
     $strTagClose = $objPage->outputFormat == 'xhtml' ? ' />' : '>';
     // Add rel="prev" and rel="next" links (see #3515)
     if ($this->hasPrevious()) {
         $GLOBALS['TL_HEAD'][] = '<link rel="prev" href="' . $this->linkToPage($this->intPage - 1) . '"' . $strTagClose;
     }
     if ($this->hasNext()) {
         $GLOBALS['TL_HEAD'][] = '<link rel="next" href="' . $this->linkToPage($this->intPage + 1) . '"' . $strTagClose;
     }
     return $this->Template->parse();
 }
Example #17
0
 public function label_callback($row, $label, DataContainer $dc, $args)
 {
     // status
     $args[0] = '<img width="16" height="16" src="system/modules/abonnement/html/' . $GLOBALS['TL_LANG']['tl_abo_order']['statusReference'][$args[0]]['icon'] . '" title="' . $GLOBALS['TL_LANG']['tl_abo_order']['statusReference'][$args[0]]['label'] . '">';
     /*
     // created (date)
     $args[1] = date("d.m.Y",$args[1]);
     */
     // abo
     $objAbo = \Database::getInstance()->prepare("SELECT * FROM tl_abo WHERE id = ?")->execute($args[1]);
     $args[1] = '<a class="abos" title="' . $objAbo->title . '" href="contao/main.php?do=member&key=abos&id=' . $args[2] . '&rt=' . $_SESSION['REQUEST_TOKEN'] . '">' . (strlen($objAbo->title) >= 10 ? substr($objAbo->title, 0, 10) . '...' : $objAbo->title) . '</a>';
     // member
     $objMember = \Database::getInstance()->prepare("SELECT * FROM tl_member WHERE id = ?")->execute($args[2]);
     $args[2] = '<a href="/contao/main.php?do=member&act=edit&id=' . $objMember->id . '&rt=' . $_SESSION['REQUEST_TOKEN'] . '" title="' . $objMember->email . '">' . (strlen($objMember->firstname . ' ' . $objMember->lastname) >= 25 ? substr($objMember->firstname . ' ' . $objMember->lastname, 0, 25) . '...' : $objMember->firstname . ' ' . $objMember->lastname) . '</a>';
     // item
     $objItem = \Database::getInstance()->prepare("SELECT * FROM tl_abo_item WHERE id = ?")->execute($args[4]);
     $args[4] = '<a href="' . Environment::getInstance()->request . '" title="' . $objItem->title . '">' . (strlen($objItem->title) >= 10 ? substr($objItem->title, 0, 10) . '...' : $objItem->title) . '</a>';
     return $args;
 }
 public function createRecipientSource(RecipientSource $recipientSourceEntity)
 {
     $recipientSource = new RecipientsRecipientSourceSalutations();
     if ($recipientSourceEntity->getFilter()) {
         if ($recipientSourceEntity->getFilterByMailingLists()) {
             $recipientSource->setFilteredMailingLists($recipientSourceEntity->getMailingLists()->toArray());
         }
         if ($recipientSourceEntity->getRecipientsUsePropertyFilter()) {
             $recipientSource->setFilteredProperties($recipientSourceEntity->getRecipientsPropertyFilter());
         }
     }
     /** @var EventDispatcherInterface $eventDispatcher */
     $eventDispatcher = $GLOBALS['container']['event-dispatcher'];
     if ($recipientSourceEntity->getRecipientsManageSubscriptionPage()) {
         $getPageDetailsEvent = new GetPageDetailsEvent($recipientSourceEntity->getRecipientsManageSubscriptionPage());
         $eventDispatcher->dispatch(ContaoEvents::CONTROLLER_GET_PAGE_DETAILS, $getPageDetailsEvent);
         $generateFrontendUrlEvent = new GenerateFrontendUrlEvent($getPageDetailsEvent->getPageDetails());
         $eventDispatcher->dispatch(ContaoEvents::CONTROLLER_GENERATE_FRONTEND_URL, $generateFrontendUrlEvent);
         $url = $generateFrontendUrlEvent->getUrl();
         $url .= (strpos($url, '?') !== false ? '&' : '?') . 'avisota_subscription_email=##email##';
         if (!preg_match('~^\\w+:~', $url)) {
             $environment = \Environment::getInstance();
             $url = rtrim($environment->base, '/') . '/' . ltrim($url, '/');
         }
         $recipientSource->setManageSubscriptionUrlPattern($url);
     }
     if ($recipientSourceEntity->getRecipientsUnsubscribePage()) {
         $getPageDetailsEvent = new GetPageDetailsEvent($recipientSourceEntity->getRecipientsUnsubscribePage());
         $eventDispatcher->dispatch(ContaoEvents::CONTROLLER_GET_PAGE_DETAILS, $getPageDetailsEvent);
         $generateFrontendUrlEvent = new GenerateFrontendUrlEvent($getPageDetailsEvent->getPageDetails());
         $eventDispatcher->dispatch(ContaoEvents::CONTROLLER_GENERATE_FRONTEND_URL, $generateFrontendUrlEvent);
         $url = $generateFrontendUrlEvent->getUrl();
         $url .= (strpos($url, '?') !== false ? '&' : '?') . 'avisota_subscription_email=##email##';
         if (!preg_match('~^\\w+:~', $url)) {
             $environment = \Environment::getInstance();
             $url = rtrim($environment->base, '/') . '/' . ltrim($url, '/');
         }
         $recipientSource->setUnsubscribeUrlPattern($url);
     }
     $event = new CreateRecipientSourceEvent($recipientSourceEntity, $recipientSource);
     $eventDispatcher->dispatch(CoreEvents::CREATE_RECIPIENT_SOURCE, $event);
     return $event->getRecipientSource();
 }
Example #19
0
 public function getClasses()
 {
     // only in backend
     if (TL_MODE == 'BE') {
         // order is important
         \BackendUser::getInstance();
         \Database::getInstance();
         \Config::getInstance();
         \Environment::getInstance();
         \Input::getInstance();
         // init language files and start f module
         if (\Database::getInstance()->tableExists('tl_fmodules')) {
             $saveLanguage = $_SESSION['fm_language'] ? $_SESSION['fm_language'] : 'de';
             \Backend::loadLanguageFile('tl_fmodules_language_pack', $saveLanguage);
             $dcaCreator = new DCACreator();
             $dcaCreator->loadModules();
             $dcaCreator->createLabels();
         }
     }
 }
    protected function getExpirationTime() {
        if (!isset($this->expirationTime)) {
            // preparing value for cache entry expiration time
            $cacheConfig = Environment::getInstance()->getConfigurationSection('Cache');
            $cacheExpirationConfig = isset($cacheConfig['Entry Expiration']) ? $cacheConfig['Entry Expiration'] : NULL;
            // at first trying to use provided policy
            if (isset($this->expirationTimePolicyName) && isset($cacheExpirationConfig[$this->expirationTimePolicyName])) {
                $this->expirationTime = $cacheExpirationConfig[$this->expirationTimePolicyName];
            }
            // falling back to default policy
            if (!isset($this->expirationTime) && isset($cacheExpirationConfig['default'])) {
                $this->expirationTime = $cacheExpirationConfig['default'];
            }

            if (!isset($this->expirationTime)) {
                $this->expirationTime = FALSE;
            }
        }

        return ($this->expirationTime === FALSE) ? NULL : $this->expirationTime;
    }
 /**
  * {@inheritdoc}
  */
 public function handle(\Input $input)
 {
     $outFile = new \File(self::OUT_FILE_PATHNAME);
     $pidFile = new \File(self::PID_FILE_PATHNAME);
     $output = $outFile->getContent();
     $pid = $pidFile->getContent();
     // We send special signal 0 to test for existance of the process which is much more bullet proof than
     // using anything like shell_exec() wrapped ps/pgrep magic (which is not available on all systems).
     $isRunning = (bool) posix_kill($pid, 0);
     $startTime = new \DateTime();
     $startTime->setTimestamp(filectime(TL_ROOT . '/' . self::PID_FILE_PATHNAME));
     $endTime = new \DateTime();
     $endTime->setTimestamp($isRunning ? time() : filemtime(TL_ROOT . '/' . self::OUT_FILE_PATHNAME));
     $uptime = $endTime->diff($startTime);
     $uptime = $uptime->format('%h h %I m %S s');
     if (!$isRunning && \Input::getInstance()->post('close')) {
         $outFile->renameTo(UpdatePackagesController::OUTPUT_FILE_PATHNAME);
         $pidFile->delete();
         $this->redirect('contao/main.php?do=composer&amp;update=database');
     } else {
         if ($isRunning && \Input::getInstance()->post('terminate')) {
             posix_kill($pid, SIGTERM);
             $this->reload();
         }
     }
     $converter = new ConsoleColorConverter();
     $output = $converter->parse($output);
     if (\Environment::getInstance()->isAjaxRequest) {
         header('Content-Type: application/json; charset=utf-8');
         echo json_encode(array('output' => $output, 'isRunning' => $isRunning, 'uptime' => $uptime));
         exit;
     } else {
         $template = new \BackendTemplate('be_composer_client_detached');
         $template->output = $output;
         $template->isRunning = $isRunning;
         $template->uptime = $uptime;
         return $template->parse();
     }
 }
 public function load(AbstractMetaModelFactory $factory, AbstractMetaModel $environment_metamodel, array $filters = NULL, $finalAttempt)
 {
     LogHelper::log_notice(t('Loading Environment Meta Model from settings.php ...'));
     $datasourceCount = 0;
     $configurationDataSources = Environment::getInstance()->getConfigurationSection('Data Sources');
     if (isset($configurationDataSources)) {
         foreach ($configurationDataSources as $namespace => $sourceDataSources) {
             foreach ($sourceDataSources as $datasourceName => $sourceDataSource) {
                 $datasourceName = NameSpaceHelper::resolveNameSpace($namespace, $datasourceName);
                 $datasource = new DataSourceMetaData();
                 $datasource->name = $datasourceName;
                 $datasource->system = TRUE;
                 $datasource->readonly = TRUE;
                 $datasource->initializeFrom($sourceDataSource);
                 $environment_metamodel->registerDataSource($datasource);
                 $datasourceCount++;
             }
         }
     }
     LogHelper::log_info(t('Processed @datasourceCount data sources', array('@datasourceCount' => $datasourceCount)));
     return self::LOAD_STATE__SUCCESSFUL;
 }
Example #23
0
 /**
  * Generate the pagination menu and return it as HTML string
  *
  * @param string
  *
  * @return string
  *
  * @SuppressWarnings(PHPMD.Superglobals)
  * @SuppressWarnings(PHPMD.CamelCaseVariableName)
  */
 public function generate($strSeparator = '')
 {
     if ($this->intRowsPerPage < 1) {
         return '';
     }
     $this->strUrl = preg_replace(array('#\\?page=\\d+&#i', '#\\?page=\\d+$#i', '#&(amp;)?page=\\d+#i'), array('?', '', ''), \Environment::getInstance()->request);
     $this->strVarConnector = strpos($this->strUrl, '?') !== false ? '&amp;' : '?';
     $this->intTotalPages = ceil($this->intRows / $this->intRowsPerPage);
     // Return if there is only one page
     if ($this->intTotalPages < 2 || $this->intRows < 1) {
         return '';
     }
     if ($this->intPage > $this->intTotalPages) {
         $this->intPage = $this->intTotalPages;
     }
     $this->Template = new TwigFrontendTemplate('pagination');
     $this->Template->hasFirst = $this->hasFirst();
     $this->Template->hasPrevious = $this->hasPrevious();
     $this->Template->hasNext = $this->hasNext();
     $this->Template->hasLast = $this->hasLast();
     $this->Template->items = $this->getItems();
     $this->Template->page = $this->intPage;
     $this->Template->total = $this->intTotalPages;
     $this->Template->first = array('page' => 1, 'link' => $this->lblFirst, 'href' => $this->linkToPage(1));
     $this->Template->previous = array('page' => $this->intPage - 1, 'link' => $this->lblPrevious, 'href' => $this->linkToPage($this->intPage - 1));
     $this->Template->next = array('page' => $this->intPage + 1, 'link' => $this->lblNext, 'href' => $this->linkToPage($this->intPage + 1));
     $this->Template->last = array('page' => $this->intTotalPages, 'link' => $this->lblLast, 'href' => $this->linkToPage($this->intTotalPages));
     global $objPage;
     $strTagClose = $objPage->outputFormat == 'xhtml' ? ' />' : '>';
     // Add rel="prev" and rel="next" links (see #3515)
     if ($this->hasPrevious()) {
         $GLOBALS['TL_HEAD'][] = '<link rel="prev" href="' . $this->linkToPage($this->intPage - 1) . '"' . $strTagClose;
     }
     if ($this->hasNext()) {
         $GLOBALS['TL_HEAD'][] = '<link rel="next" href="' . $this->linkToPage($this->intPage + 1) . '"' . $strTagClose;
     }
     return $this->Template->parse();
 }
Example #24
0
 public function run()
 {
     global $container;
     /** @var \Symfony\Component\EventDispatcher\EventDispatcher $eventDispatcher */
     $eventDispatcher = $GLOBALS['container']['event-dispatcher'];
     $input = \Input::getInstance();
     $messageRepository = \Contao\Doctrine\ORM\EntityHelper::getRepository('Avisota\\Contao:Message');
     $messageId = $input->get('id');
     /** @var \Avisota\Contao\Entity\Message $message */
     $message = $messageRepository->find($messageId);
     if (!$message) {
         header("HTTP/1.0 404 Not Found");
         echo '<h1>404 Not Found</h1>';
         exit;
     }
     $user = BackendUser::getInstance();
     $user->authenticate();
     $event = new \Avisota\Contao\Core\Event\CreateFakeRecipientEvent($message);
     $eventDispatcher->dispatch(\Avisota\Contao\Core\CoreEvents::CREATE_FAKE_RECIPIENT, $event);
     $recipient = $event->getRecipient();
     if ($message->getCategory()->getViewOnlinePage()) {
         $event = new LoadLanguageFileEvent('avisota_message');
         $eventDispatcher->dispatch(ContaoEvents::SYSTEM_LOAD_LANGUAGE_FILE, $event);
         $environment = \Environment::getInstance();
         $url = sprintf($GLOBALS['TL_LANG']['avisota_message']['viewOnline'], sprintf('%ssystem/modules/avisota-message/web/preview.php?id=%s', $environment->base, $message->getId()));
     } else {
         $url = false;
     }
     $additionalData = array('view_online_link' => $url);
     /** @var \Avisota\Contao\Message\Core\Renderer\MessageRendererInterface $renderer */
     $renderer = $container['avisota.message.renderer'];
     $messageTemplate = $renderer->renderMessage($message);
     $messagePreview = $messageTemplate->renderPreview($recipient, $additionalData);
     header('Content-Type: ' . $messageTemplate->getContentType() . '; charset=' . $messageTemplate->getContentEncoding());
     header('Content-Disposition: inline; filename="' . $messageTemplate->getContentName() . '"');
     echo $messagePreview;
     exit;
 }
 /**
  * {@inheritdoc}
  */
 public function handle(\Input $input)
 {
     $outFile = new \File(self::OUT_FILE_PATHNAME);
     $pidFile = new \File(self::PID_FILE_PATHNAME);
     $output = $outFile->getContent();
     $pid = $pidFile->getContent();
     $isRunning = $this->isPidStillRunning($pid);
     $startTime = new \DateTime();
     $startTime->setTimestamp(filectime(TL_ROOT . '/' . self::PID_FILE_PATHNAME));
     $endTime = new \DateTime();
     $endTime->setTimestamp($isRunning ? time() : filemtime(TL_ROOT . '/' . self::OUT_FILE_PATHNAME));
     $uptime = $endTime->diff($startTime);
     $uptime = $uptime->format('%h h %I m %S s');
     if (!$isRunning && \Input::getInstance()->post('close')) {
         $outFile->renameTo(UpdatePackagesController::OUTPUT_FILE_PATHNAME);
         $pidFile->delete();
         $this->redirect('contao/main.php?do=composer&amp;update=database');
     } else {
         if ($isRunning && \Input::getInstance()->post('terminate')) {
             $this->killPid($pid);
             $this->reload();
         }
     }
     $converter = new ConsoleColorConverter();
     $output = $converter->parse($output);
     if (\Environment::getInstance()->isAjaxRequest) {
         header('Content-Type: application/json; charset=utf-8');
         echo json_encode(array('output' => $output, 'isRunning' => $isRunning, 'uptime' => $uptime));
         exit;
     } else {
         $template = new \BackendTemplate('be_composer_client_detached');
         $template->output = $output;
         $template->isRunning = $isRunning;
         $template->uptime = $uptime;
         return $template->parse();
     }
 }
Example #26
0
 /**
  * setCookie
  * 
  * Set cookie headers to be sent with the response. Follows the standard PHP setcookie interface, but automatically works out
  * if secure and httponly are require or not. The default value for $path is '/'.
  * 
  * @param $name string 
  * @param $value string
  * @param $expire int
  * @param $path string
  * @param $domain string
  */
 public function setCookie($name, $value, $expire = 0, $path = '/', $domain = null)
 {
     $https = Environment::getInstance()->getServer('HTTPS');
     $secure = $https && $https !== 'off' ? true : false;
     $httponly = $secure ? true : false;
     if (!$expire || $expire > time()) {
         Request::getInstance()->setCookie($name, $value);
     }
     $this->_cookies[$name] = array('value' => $value, 'expire' => $expire, 'path' => $path, 'domain' => $domain, 'secure' => $secure, 'httponly' => $httponly);
 }
 public function __construct()
 {
     $this->environment = Environment::getInstance();
 }
    public function __construct($datasourceType, $extensionConfigurations) {
        parent::__construct($datasourceType, $extensionConfigurations);

        $serverConfig = Environment::getInstance()->getConfigurationSection('Server');
        $this->callbackServerName = isset($serverConfig['Name']) ? $serverConfig['Name'] : self::CALLBACK_SERVER_NAME__DEFAULT;
    }
 /**
  * Generate the module
  *
  * @return string
  */
 public function run()
 {
     $objTemplate = new TwigBackendTemplate('be_purge_images');
     $objTemplate->isActive = $this->isActive();
     // Confirmation message
     if ($_SESSION['CLEAR_TWIG_CACHE_CONFIRM'] != '') {
         $objTemplate->cacheMessage = $_SESSION['CLEAR_TWIG_CACHE_CONFIRM'];
         $_SESSION['CLEAR_TWIG_CACHE_CONFIRM'] = '';
     }
     // Purge the resources
     if ($this->isActive()) {
         $this->import('Files');
         $intCount = $this->purge();
         $_SESSION['CLEAR_TWIG_CACHE_CONFIRM'] = sprintf($GLOBALS['TL_LANG']['tl_maintenance']['purgedTwigCache'], $intCount);
         $this->reload();
     }
     // count existing files
     $count = 0;
     $size = 0;
     $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(TL_ROOT . '/system/cache/twig'), RecursiveIteratorIterator::CHILD_FIRST);
     /** @var SplFileInfo $path */
     foreach ($iterator as $path) {
         if ($path->isFile() && $path->getFilename() != '.keep') {
             $count++;
             $size += $path->getSize();
         }
     }
     $objTemplate->count = sprintf($GLOBALS['TL_LANG']['tl_maintenance']['twigCacheCount'], $count, $this->getReadableSize($size));
     $objTemplate->action = ampersand(\Environment::getInstance()->request);
     return $objTemplate->parse();
 }
Example #30
0
 /**
  * {@inheritDoc}
  */
 public function getRequestUrl()
 {
     return \Environment::getInstance()->request;
 }