Execute a phing target when a file has been modified - phing

I have a filelist of about 25 files. I need to execute a certain phing target when the modification time of one of these files has changed. What is the best way to do this?

If you're after cross-platform then I guess you could try something like the Node.js beholder or hound to spawn a command line exec for Phing. Alternatively there are a few C++ cross-platform watcher libraries around if you want to roll your own.

Extend phing by writing your own task. Something like this one which uses filesets.
Limited to watching files for changes only.
<?php
/**
Example target:
<target name="mytarget">
<react refresh="1.7" cmd="dosomething.sh">
<fileset dir=".">
<include name="*.txt" />
</fileset>
</react>
</target>
Will call dosomething.sh script when a txt file has changed in the current
directory every 1.7 seconds.
$Id: ReactTask.php 123 2013-07-22 08:16:26Z gregory.vincic $
*/
require_once "phing/Task.php";
class ReactTask extends Task {
/** Command to execute */
private $cmd = null;
public function setCmd($str) {
$this->cmd = $str;
}
/** Refresh time in microseconds, defaults to 1 second. */
private $refresh = 1000000;
public function setRefresh($str) {
if($str != null && is_numeric($str)) {
$this->refresh = $str*1000000;
}
}
/** Any filesets of files that should be appended. */
private $filesets = array();
function createFileSet() {
$num = array_push($this->filesets, new FileSet());
return $this->filesets[$num-1];
}
/** Uses phps passthru to execute the configured command every X seconds */
public function main() {
$lastmtime = null;
$this->log("Refreshing every " . $this->refresh/1000000 . " seconds.\n", Project::MSG_WARN);
while(1) {
$mtimes = $this->rlist();
if(count($mtimes) > 0 && max($mtimes) > $lastmtime) {
passthru($this->cmd);
$lastmtime = max($mtimes);
}
usleep($this->refresh);
}
}
/** Lists modification times of all the files defined by your filesets. */
private function rlist() {
$res = array();
foreach($this->filesets as $fs) {
try {
$files = $fs->getDirectoryScanner($this->project)->getIncludedFiles();
foreach ($files as $file) {
$path = $fs->dir . "/" . $file;
$res[] = filemtime($path);
}
} catch (BuildException $be) {
$this->log($be->getMessage(), Project::MSG_WARN);
}
}
return $res;
}
}
?>

Related

Codeigniter 3 | Copy zip file and extract

I've function for demo import database:
/**
* Demo importer post [Template 01 - Fashion / Clothing]
*/
public function demo_importer_post_template01()
{
$folder_name = 'template01';
$file_name = 'template01.sql';
$path = 'assets/backup_db/'; // Codeigniter application /assets
$file_restore = $this->load->file($path . $folder_name . '/' . $file_name, true);
$file_array = explode(';', $file_restore);
foreach ($file_array as $query)
{
$this->db->query("SET FOREIGN_KEY_CHECKS = 0");
$this->db->query($query);
$this->db->query("SET FOREIGN_KEY_CHECKS = 1");
}
$this->session->set_flashdata('success', trans("msg_updated"));
redirect($this->agent->referrer());
}
This function insert database from /assets/backup_db/template01/template01.sql
This working fine. Now I need with this function extract some static files from: /assets/backup_db/template01/template01.zip
Can anyone help me How to copy template01.zip to root public_html and then unzip files from template01.zip

Upgrade from TYPO3 9 to 10 - Fatal Error in Upgrade Wizard with no extensions enabled

I just upgraded my TYPO3 v9 to v10.04.27 and now i get an error in the Upgrade Wizard
(1/1) Error
Class 'TYPO3\CMS\Core\Cache\Frontend\StringFrontend' not found in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Cache/CacheManager.php line 351
As you can see in the path i also tried already with an older TYPO3 10 Version.
I disabled all extensions before the upgrade. Except the ones that cant be disabled.
So this should be a completely clean TYPO3 10 install (except the Config Files).
I dont know what i can do about this.
Here is the Full Trace:
Something went wrong. Please use Check for broken extensions to see if a loaded extension breaks this part of the install tool and unload it.
The box below may additionally reveal further details on what went wrong depending on your debug settings. It may help to temporarily switch to debug mode using Settings > Configuration Presets > Debug settings.
If this error happens at an early state and no full exception back trace is shown, it may also help to manually increase debugging output in typo3conf/LocalConfiguration.php:['BE']['debug'] => true, ['SYS']['devIPmask'] => '*', ['SYS']['displayErrors'] => 1,['SYS']['exceptionalErrors'] => 12290
Ajax error
Whoops, looks like something went wrong.
(1/1) Error
Class 'TYPO3\CMS\Core\Cache\Frontend\StringFrontend' not found
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Cache/CacheManager.php line 351
$backendInstance->initializeObject();
}
// New used on purpose, see comment above
$frontendInstance = new $frontend($identifier, $backendInstance);
if (!$frontendInstance instanceof FrontendInterface) {
throw new InvalidCacheException('"' . $frontend . '" is not a valid cache frontend object.', 1464550984);
}
if (is_callable([$frontendInstance, 'initializeObject'])) {
at TYPO3\CMS\Core\Cache\CacheManager->createCache()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Cache/CacheManager.php line 157
if ($this->hasCache($identifier) === false) {
throw new NoSuchCacheException('A cache with identifier "' . $identifier . '" does not exist.', 1203699034);
}
if (!isset($this->caches[$identifier])) {
$this->createCache($identifier);
}
return $this->caches[$identifier];
}
at TYPO3\CMS\Core\Cache\CacheManager->getCache()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Cache/DatabaseSchemaService.php line 51
$cacheManager->setCacheConfigurations($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']);
$tableDefinitions = '';
foreach ($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations'] as $cacheName => $_) {
$backend = $cacheManager->getCache($cacheName)->getBackend();
if (method_exists($backend, 'getTableDefinitions')) {
$tableDefinitions .= LF . $backend->getTableDefinitions();
}
}
at TYPO3\CMS\Core\Cache\DatabaseSchemaService->getCachingFrameworkRequiredDatabaseSchema()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Cache/DatabaseSchemaService.php line 33
* #param AlterTableDefinitionStatementsEvent $event
*/
public function addCachingFrameworkDatabaseSchema(AlterTableDefinitionStatementsEvent $event): void
{
$event->addSqlData($this->getCachingFrameworkRequiredDatabaseSchema());
}
/**
* Get schema SQL of required cache framework tables.
at TYPO3\CMS\Core\Cache\DatabaseSchemaService->addCachingFrameworkDatabaseSchema()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/EventDispatcher/EventDispatcher.php line 51
if ($event instanceof StoppableEventInterface && $event->isPropagationStopped()) {
return $event;
}
foreach ($this->listenerProvider->getListenersForEvent($event) as $listener) {
$listener($event);
if ($event instanceof StoppableEventInterface && $event->isPropagationStopped()) {
break;
}
}
at TYPO3\CMS\Core\EventDispatcher\EventDispatcher->dispatch()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Database/Schema/SqlReader.php line 75
}
}
/** #var AlterTableDefinitionStatementsEvent $event */
$event = $this->eventDispatcher->dispatch(new AlterTableDefinitionStatementsEvent($sqlString));
$sqlString = $event->getSqlData();
return implode(LF . LF, $sqlString);
}
at TYPO3\CMS\Core\Database\Schema\SqlReader->getTablesDefinitionString()
in /srv/typo3_src-10.4.20/typo3/sysext/install/Classes/Service/UpgradeWizardsService.php line 156
*/
public function getBlockingDatabaseAdds(): array
{
$sqlReader = GeneralUtility::makeInstance(SqlReader::class);
$databaseDefinitions = $sqlReader->getCreateTableStatementArray($sqlReader->getTablesDefinitionString());
$schemaMigrator = GeneralUtility::makeInstance(SchemaMigrator::class);
$databaseDifferences = $schemaMigrator->getSchemaDiffs($databaseDefinitions);
at TYPO3\CMS\Install\Service\UpgradeWizardsService->getBlockingDatabaseAdds()
in /srv/typo3_src-10.4.20/typo3/sysext/install/Classes/Controller/UpgradeController.php line 1042
$this->lateBootService->loadExtLocalconfDatabaseAndExtTables(false);
$adds = [];
$needsUpdate = false;
try {
$adds = $this->upgradeWizardsService->getBlockingDatabaseAdds();
$this->lateBootService->resetGlobalContainer();
if (!empty($adds)) {
$needsUpdate = true;
}
at TYPO3\CMS\Install\Controller\UpgradeController->upgradeWizardsBlockingDatabaseAddsAction()
in /srv/typo3_src-10.4.20/typo3/sysext/install/Classes/Middleware/Maintenance.php line 246
'Unknown action method ' . $action . ' in controller ' . $controllerName,
1505216027
);
}
$response = $controller->$action($request);
}
return $response;
}
at TYPO3\CMS\Install\Middleware\Maintenance->process()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Http/MiddlewareDispatcher.php line 121
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->middleware->process($request, $this->next);
}
};
}
at class#anonymous/srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Http/MiddlewareDispatcher.php:103$bc->handle()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Middleware/NormalizedParamsAttribute.php line 45
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$request = $request->withAttribute('normalizedParams', NormalizedParams::createFromRequest($request));
return $handler->handle($request);
}
}
at TYPO3\CMS\Core\Middleware\NormalizedParamsAttribute->process()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Http/MiddlewareDispatcher.php line 172
if (!$middleware instanceof MiddlewareInterface) {
throw new \InvalidArgumentException(get_class($middleware) . ' does not implement ' . MiddlewareInterface::class, 1516821342);
}
return $middleware->process($request, $this->next);
}
};
}
}
at class#anonymous/srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Http/MiddlewareDispatcher.php:138$bd->handle()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Http/MiddlewareDispatcher.php line 78
* #return ResponseInterface
*/
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->tip->handle($request);
}
/**
* Seed the middleware stack with the inner request handler
at TYPO3\CMS\Core\Http\MiddlewareDispatcher->handle()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Http/AbstractApplication.php line 85
* #return ResponseInterface
*/
protected function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->requestHandler->handle($request);
}
/**
* Set up the application and shut it down afterwards
at TYPO3\CMS\Core\Http\AbstractApplication->handle()
in /srv/typo3_src-10.4.20/typo3/sysext/install/Classes/Http/Application.php line 52
protected function handle(ServerRequestInterface $request): ResponseInterface
{
$this->initializeContext();
$request = $request->withAttribute('applicationType', SystemEnvironmentBuilder::REQUESTTYPE_INSTALL);
return parent::handle($request)
->withHeader('X-Frame-Options', 'SAMEORIGIN');
}
/**
at TYPO3\CMS\Install\Http\Application->handle()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Http/AbstractApplication.php line 97
final public function run(callable $execute = null)
{
try {
$response = $this->handle(
ServerRequestFactory::fromGlobals()
);
if ($execute !== null) {
call_user_func($execute);
}
at TYPO3\CMS\Core\Http\AbstractApplication->run()
in /srv/typo3_src-10.4.20/typo3/install.php line 105
call_user_func(function () {
$classLoader = require dirname(__DIR__).'/vendor/autoload.php';
\TYPO3\CMS\Core\Core\SystemEnvironmentBuilder::run(1, \TYPO3\CMS\Core\Core\SystemEnvironmentBuilder::REQUESTTYPE_INSTALL);
\TYPO3\CMS\Core\Core\Bootstrap::init($classLoader, true)->get(\TYPO3\CMS\Install\Http\Application::class)->run();
});
at {closure}()
in /srv/typo3_src-10.4.20/typo3/install.php line 106
call_user_func(function () {
$classLoader = require dirname(__DIR__).'/vendor/autoload.php';
\TYPO3\CMS\Core\Core\SystemEnvironmentBuilder::run(1, \TYPO3\CMS\Core\Core\SystemEnvironmentBuilder::REQUESTTYPE_INSTALL);
\TYPO3\CMS\Core\Core\Bootstrap::init($classLoader, true)->get(\TYPO3\CMS\Install\Http\Application::class)->run();
});
Any ideas?
Thank you in advance
Delete all extensions except the ones from TYPO3 core. Then cache will be rebuild without not needed classes.
I had some errors in my installations if extension are only deactivated but not deleted.
My guess is that you're using the StringFrontend somewhere, which was deprecated in TYPO3 9.2.
Can you check your LocalConfiguration.php and AdditionalConfiguration.php if you find "StringFrontend" anywhere and replace it with VariableFrontend or remove it completely? (as suggested in the migration path)

How do I parse a Typoscript file?

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>';

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;**
}
}

Zend Enable SQL Query logging

I am using this to retrieve the database connection atm.
$db = Zend_Db_Table::getDefaultAdapter();
I do set this up in my config like this:
resources.db.adapter = pdo_mysql
resources.db.isDefaultTableAdapter = true
resources.db.params.host = localhost
resources.db.params.username = root
resources.db.params.password = password
resources.db.params.dbname = db
resources.db.params.profiler.enabled = true
resources.db.params.profiler.class = Zend_Db_Profiler
I would like to output everything to a sql.log for example. Is this possible to apply on the default adapter? for example through the settings, so I can ignore it in production environment?
Much appriciated.
I did look at: How to enable SQL output to log file with Zend_Db? but it didn't seem to cover my issue.
/Marcus
There is an example of extending Zend_Db_Profiler so you can write the queries to /logs/db-queries.log file.
So you have to do the following:
Create My_Db_Profiler_Log class in the library folder
Add the following lines to the application.ini
resources.db.params.profiler.enabled = true
resources.db.params.profiler.class = My_Db_Profiler_Log
Note: be aware, that the log file will become very big, very soon! So it is a good idea to log only the queries you are interested in. And this example should be considered only as a starting point in implementation of such a logging system.
Here is the code for the custom profiler class:
<?php
class My_Db_Profiler_Log extends Zend_Db_Profiler {
/**
* Zend_Log instance
* #var Zend_Log
*/
protected $_log;
/**
* counter of the total elapsed time
* #var double
*/
protected $_totalElapsedTime;
public function __construct($enabled = false) {
parent::__construct($enabled);
$this->_log = new Zend_Log();
$writer = new Zend_Log_Writer_Stream(APPLICATION_PATH . '/logs/db-queries.log');
$this->_log->addWriter($writer);
}
/**
* Intercept the query end and log the profiling data.
*
* #param integer $queryId
* #throws Zend_Db_Profiler_Exception
* #return void
*/
public function queryEnd($queryId) {
$state = parent::queryEnd($queryId);
if (!$this->getEnabled() || $state == self::IGNORED) {
return;
}
// get profile of the current query
$profile = $this->getQueryProfile($queryId);
// update totalElapsedTime counter
$this->_totalElapsedTime += $profile->getElapsedSecs();
// create the message to be logged
$message = "\r\nElapsed Secs: " . round($profile->getElapsedSecs(), 5) . "\r\n";
$message .= "Query: " . $profile->getQuery() . "\r\n";
// log the message as INFO message
$this->_log->info($message);
}
}
?>
Extend the Zend_Db_Profiler to write to an SQL.log and attach the profiler to your db adapter
<?php
class File_Profiler extends Zend_Db_Profiler {
/**
* The filename to save the queries
*
* #var string
*/
protected $_filename;
/**
* The file handle
*
* #var resource
*/
protected $_handle = null;
/**
* Class constructor
*
* #param string $filename
*/
public function __construct( $filename ) {
$this->_filename = $filename;
}
/**
* Change the profiler status. If the profiler is not enabled no
* query will be written to the destination file
*
* #param boolean $enabled
*/
public function setEnabled( $enabled ) {
parent::setEnabled($enabled);
if( $this->getEnabled() ) {
if( !$this->_handle ) {
if( !($this->_handle = #fopen($this->_filename, "a")) ) {
throw new Exception("Unable to open filename {$this->_filename} for query profiling");
}
}
}
else {
if( $this->_handle ) {
#fclose($this->_handle);
}
}
}
/**
* Intercept parent::queryEnd to catch the query and write it to a file
*
* #param int $queryId
*/
public function queryEnd($queryId) {
$state = parent::queryEnd($queryId);
if(!$this->getEnabled() || $state == self::IGNORED) {
return;
}
$profile = $this->getQueryProfile($queryId);
#fwrite($this->_handle, round($profile->getElapsedSecs(),5) . " " . $profile->getQuery() . " " . ($params=$profile->getQueryParams())?$params:null);
}
}
Haven't test it, but it should do the trick. Give it a try and let me know.
Btw you do know that you can log all queries on the mysql as well?
this will let you see sql queries to the web page , IT MIGHT BE OFF TOPIC but it helpful
I am highly recommend you to use ZF debug bar , it will give you very handy information
i am using it to see my doctrine queries , and it had support for zend db too
https://github.com/jokkedk/ZFDebug