Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Replaces file paths like "files/lorem/ipsum/foo.jpg" in Contao text elements with {{file::…}} insert tags.
<?php
/**
* Contao Open Source CMS
*
* Copyright (c) 2005-2015 Leo Feyer
*
* @license LGPL-3.0+
*/
// inizialize the contao framework
define('TL_MODE', 'FE');
require('system/initialize.php');
/**
* Class FileTags
* Contains method to replace file paths like "files/lorem/ipsum/foo.jpg" with
* their file tags {{file::…}}
*/
class FileTags extends Controller
{
/**
* Call the parent constructor.
*
* @param void
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Runs the conversion process
*
* There is room for improvement in detecting the file paths via regex.
* Also the decode process might need some improvement.
*
* @param void
* @return void
*/
public function run()
{
// get all content elements with files/
$objContent = \ContentModel::findBy( array("text LIKE ?"), array("%files/%"), array('order' => 'id DESC') );
// go through each content element
while( $objContent->next() )
{
// match the files/ path
preg_match_all( '~"(files/[^"]*\..{3,4})"~', $objContent->text, $matches );
// go through each match
foreach( $matches[1] as $strFilePath )
{
// decode
$strFilePathReal = urldecode( $strFilePath );
$strFilePathReal = str_replace( '[&]', '&', $strFilePathReal );
// get the files object
if( ( $objFile = \FilesModel::findByPath( urldecode( $strFilePathReal ) ) ) !== null )
{
// construct file tag
$strFileTag = '{{file::' . \String::binToUuid( $objFile->uuid ) . '}}';
// replace file path with file tag
$objContent->text = str_replace( $strFilePath, $strFileTag, $objContent->text );
}
}
// save content element
$objContent->save();
}
}
}
// create a FileTags instance and run it
$objFileTags = new FileTags();
$objFileTags->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.