How do I parse a Typoscript file? - typo3

I am writing a unit test and want to check if the data in a certain typoscript file satisfies my requirements. How do I convert the text file to an array? The Typo3-Framework is available.
My google research points to using the class \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser but I don't find usage examples ...
(Using Typo3 7.6)

This is working (but possibly there are nicer ways to do this):
<?php
use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
class TyposcriptTest extends \TYPO3\CMS\Core\Tests\UnitTestCase {
public function setUp() {
parent::setUp();
$this->objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
}
protected function loadTSFile($filename) {
$content = file_get_contents($filename);
$parser = $this->objectManager->get(TypoScriptParser::class);
$parser->parse($content);
return $parser->setup;
}
public function testTS() {
$array = $this->loadTSFile('...');
$this->assertTrue(isset($array['tx_extension.']['flexForm.']['andsoon.']]), 'Assertion failed. TS content: ' . var_export($array, true));
}
}

Here is the working example for TYPO3 v - 10.4.x
$tsString = 'colors {
backgroundColor = red
fontColor = blue
}
[ip("123.45.*")]
headerImage = fileadmin/img1.jpg
[ELSE]
headerImage = fileadmin/img2.jpg
[GLOBAL]
// Wonder if this works... :-)
wakeMeUp = 7:00';
$TSparserObject = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
\TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::class
);
$TSparserObject->parse($tsString);
echo '<pre>';
print_r($TSparserObject->setup);
echo '</pre>';

Related

output records in the form of html table from moodle database , custom block development

Please check this code for the custom block to be placed in the dashboard. We want to display an HTML table for the records. But it does not add up to the custom block, rather it appears on the top page.
enter image description here
class block_scorecard extends block_base {
function init() {
$this->title = get_string('pluginname', 'block_scorecard');
}
function get_content() {
global $DB;
if ($this->content !== NULL) {
return $this->content;
}
$content = '';
$courses = $DB->get_records('scorm_scoes_track', ['element' => 'cmi.core.total_time']);
$table=new html_table();
$table->head=array('No of attempts','Time modified','status');
foreach ($courses as $course) {
$attempt=$course->attempt;
$timemodified=userdate($course->timemodified, get_string('strftimerecentfull'));
$status=$course->value;
$table->data[]=array($attempt, $timemodified, $status);
}
echo html_writer::table($table);
$this->content = new stdClass;
$this->content->text = $content;
}}
echo html_writer::table($table);
Should be
$content .= html_writer::table($table);

How to extend date picker viewhelper of EXT:powermail?

I need to add a custom validator to the datepicker field. By default, this field comes without any validators.
I've already made the validator settings visible in the TCA of tx_powermail_domain_model_field and added my custom validator as usual.
Now I need the attributes data-parsley-customXXX and data-parsley-error-message added to the HTML input field which is usually done via the the viewhelper in ValidationDataAttributeViewHelper.php:
https://github.com/einpraegsam/powermail/blob/develop/Classes/ViewHelpers/Validation/ValidationDataAttributeViewHelper.php#L342
https://github.com/einpraegsam/powermail/blob/develop/Classes/ViewHelpers/Validation/ValidationDataAttributeViewHelper.php#L348
This is the code I need to extend:
https://github.com/einpraegsam/powermail/blob/develop/Classes/ViewHelpers/Validation/DatepickerDataAttributeViewHelper.php#L32
I found a solution for my problem. As suggested in the comment it's possible to extend the Viewhelper:
ext_localconf.php:
$GLOBALS['TYPO3_CONF_VARS']['SYS']['Objects'][\In2code\Powermail\ViewHelpers\Validation\DatepickerDataAttributeViewHelper::class] = [
'className' => \Vendor\MyExt\Powermail\ViewHelpers\Validation\DatepickerDataAttributeViewHelper::class
];
myext/Classes/Powermail/ViewHelpers/Validation/DatepickerDataAttributeViewHelper.php
<?php
declare(strict_types=1);
namespace Vendor\MyExt\Powermail\ViewHelpers\Validation;
use In2code\Powermail\Domain\Model\Field;
use In2code\Powermail\Utility\LocalizationUtility;
class DatepickerDataAttributeViewHelper extends \In2code\Powermail\ViewHelpers\Validation\DatepickerDataAttributeViewHelper
{
/**
* Returns Data Attribute Array Datepicker settings (FE + BE)
*
* #return array for data attributes
*/
public function render(): array
{
/** #var Field $field */
$field = $this->arguments['field'];
$additionalAttributes = $this->arguments['additionalAttributes'];
$value = $this->arguments['value'];
$additionalAttributes['data-datepicker-force'] =
$this->settings['misc']['datepicker']['forceJavaScriptDatePicker'];
$additionalAttributes['data-datepicker-settings'] = $this->getDatepickerSettings($field);
$additionalAttributes['data-datepicker-months'] = $this->getMonthNames();
$additionalAttributes['data-datepicker-days'] = $this->getDayNames();
$additionalAttributes['data-datepicker-format'] = $this->getFormat($field);
if ($value) {
$additionalAttributes['data-date-value'] = $value;
}
if ($field->getValidation() && $this->isClientValidationEnabled()) {
$value = 1;
if ($field->getValidationConfiguration()) {
$value = $field->getValidationConfiguration();
}
$additionalAttributes['data-parsley-custom' . $field->getValidation()] = $value;
$additionalAttributes['data-parsley-error-message'] =
LocalizationUtility::translate('validationerror_validation.' . $field->getValidation());
}
$this->addMandatoryAttributes($additionalAttributes, $field);
return $additionalAttributes;
}
}

How do I send variables to an error layout in ZF3?

What is right way to send variables to the layout templete for it be approachable in error pages?
I have AppFrontController above all my frontend controllers. It have code (code is near) in onDispatch() method:
$assocArrayOfVars = $this->MyPlugin()->getDbVariablesArray();
foreach($assocArrayOfVars as $name => $value){
$this->layout()->$name = $value;
}
list($catalog, $count_goods) = $this->MyPlugin()->getStandardCatalogDataForLayout();
$this->layout()->catalog = $catalog;
$this->layout()->count_goods = $count_goods;
As the result, I have my local variables in every frontend page. But I have’nt it in an error page. How I can to deside this problem? I very need your advices! Thank you!
Thank you for your advices! Problem is solved. Code of final version Module.php file below. I use listener instead of a “parent controller” by froschdesign advice.
public function onBootstrap(MvcEvent $event)
{
$application = $event->getApplication();
$eventManager = $application->getEventManager();
$eventManager->attach('dispatch', array($this, 'loadConfiguration'), 2);
$eventManager->attach('dispatch.error', array($this, 'loadConfiguration'), 2);
}
public function loadConfiguration(MvcEvent $e)
{
$application = $e->getApplication();
$sm = $application->getServiceManager();
$sharedManager = $application->getEventManager()->getSharedManager();
$router = $sm->get('router');
$request = $sm->get('request');
$zendCart = $sm->get('ControllerPluginManager')->get('ZendCart');
$myPlugin = $sm->get('ControllerPluginManager')->get('MyPlugin');
$viewModel = $e->getViewModel();
$viewModel->setVariable('total', $zendCart->total());
$viewModel->setVariable('total_items', $zendCart->total_items());
$viewModel->setVariable('rusmonth', $rusmonth);
/* Layout variables */
$assocArrayOfVars = $myPlugin->getDbVariablesArray();
foreach ($assocArrayOfVars as $name => $value) {
$viewModel->setVariable($name, $value);
}
list($catalog, $count_goods) = $myPlugin->getStandardCatalogDataForLayout();
$viewModel->setVariable('catalog', $catalog);
$viewModel->setVariable('count_goods', $count_goods);
}
More listener examples here.

Prevent render template in fuelphp

In fuelphp, we can render template from controller. But I want prevent render template from package.
Example:
Step 1: fuelphp run controlelr -> render template
Step 2: run package -> have a command to clear all data in step 1. and
render blank page.
Result with a blank page
$this->template->content = ...
\Package::removeTemplate();
I tried with
\Event::forge(array('shutdown'));
\Fuel::finish();
But it is not success. How can I do it?
You can always modify your template, inside the controller in every function just use
$this->template
Example
class Controller_lorem extends Controller_Main {
public $template = 'template_default';
public function action_ipsum()
{
//use customize template other than default
$this->template = View::forge('template_custom');
}
I found a solution. Rewrite \Fuel::finish()
public static function finishS()
{
if (\Config::get('caching', false))
{
\Finder::instance()->write_cache('FuelFileFinder');
}
if (static::$profiling and ! static::$is_cli)
{
// Grab the output buffer and flush it, we will rebuffer later
$output = ob_get_clean();
$headers = headers_list();
$show = true;
foreach ($headers as $header)
{
if (stripos($header, 'content-type') === 0 and stripos($header, 'text/html') === false)
{
$show = false;
}
}
if ($show)
{
\Profiler::mark('End of Fuel Execution');
if (preg_match("|</body>.*?</html>|is", $output))
{
$output = preg_replace("|</body>.*?</html>|is", '', $output);
$output .= \Profiler::output();
$output .= '</body></html>';
}
else
{
$output .= \Profiler::output();
}
}
// Restart the output buffer and send the new output
ob_start();
**/// Remove this line echo $output;**
}
}

How to get typoscript setup in a scheduler/cron script?

I need to get the extension typoscript setup in schedular script.
I am using typo3 v 4.5.
My schedular script looks like this.
class tx_myext_scheduler extends tx_scheduler_Task {
public function execute() {
//here i need to get typoscript setup
}
}
and my extension setup looks like this.
plugin.tx_myext_pi1{
listView{
file.height = 216c
}
}
In schedualr script I need to get the file.height value.
How to do that ?
Currently i tried this without success
$pObj = $GLOBALS['TSFE'];
$conf = $pObj->tmpl->setup['plugin.']['tx_myext_pi1.'];
Thank you.
The TSFE is only available in the frontend, so have to initialize it yourself (that consumes some resources!). You can create it like that in scheduler: (source)
$GLOBALS['TT'] = new t3lib_timeTrackNull;
$GLOBALS['TSFE'] = t3lib_div::makeInstance('tslib_fe', $GLOBALS['TYPO3_CONF_VARS'], 2, 0);
$GLOBALS['TSFE']->sys_page = t3lib_div::makeInstance('t3lib_pageSelect');
$GLOBALS['TSFE']->sys_page->init(TRUE);
$GLOBALS['TSFE']->initTemplate();
$GLOBALS['TSFE']->rootLine = '';
$GLOBALS['TSFE']->sys_page->getRootLine(1, '');
$GLOBALS['TSFE']->getConfigArray();
or in an eID script: (source)
require_once(PATH_tslib.'class.tslib_fe.php');
require_once(PATH_t3lib.'class.t3lib_page.php');
$temp_TSFEclassName = t3lib_div::makeInstanceClassName('tslib_fe');
$GLOBALS['TSFE'] = new $temp_TSFEclassName($TYPO3_CONF_VARS, $pid, 0, true);
$GLOBALS['TSFE']->connectToDB();
$GLOBALS['TSFE']->initFEuser();
$GLOBALS['TSFE']->determineId();
$GLOBALS['TSFE']->getCompressedTCarray();
$GLOBALS['TSFE']->initTemplate();
$GLOBALS['TSFE']->getConfigArray();
or in a backend module: (source)
function loadTypoScriptForBEModule($extKey) {
require_once(PATH_t3lib . 'class.t3lib_page.php');
require_once(PATH_t3lib . 'class.t3lib_tstemplate.php');
require_once(PATH_t3lib . 'class.t3lib_tsparser_ext.php');
list($page) = t3lib_BEfunc::getRecordsByField('pages', 'pid', 0);
$pageUid = intval($page['uid']);
$sysPageObj = t3lib_div::makeInstance('t3lib_pageSelect');
$rootLine = $sysPageObj->getRootLine($pageUid);
$TSObj = t3lib_div::makeInstance('t3lib_tsparser_ext');
$TSObj->tt_track = 0;
$TSObj->init();
$TSObj->runThroughTemplates($rootLine);
$TSObj->generateConfig();
return $TSObj->setup['plugin.'][$extKey . '.'];
}
If you have missing class errors somewhere, maybe you have to add some requires.
This solution is perfect if the page is in standard mode, but doesn't work if the page is a Draft:
function loadTypoScriptForBEModule($extKey) {
require_once(PATH_t3lib . 'class.t3lib_page.php');
require_once(PATH_t3lib . 'class.t3lib_tstemplate.php');
require_once(PATH_t3lib . 'class.t3lib_tsparser_ext.php');
list($page) = t3lib_BEfunc::getRecordsByField('pages', 'pid', 0);
$pageUid = intval($page['uid']);
$sysPageObj = t3lib_div::makeInstance('t3lib_pageSelect');
$rootLine = $sysPageObj->getRootLine($pageUid);
$TSObj = t3lib_div::makeInstance('t3lib_tsparser_ext');
$TSObj->tt_track = 0;
$TSObj->init();
$TSObj->runThroughTemplates($rootLine);
$TSObj->generateConfig();
return $TSObj->setup['plugin.'][$extKey . '.'];
}