Typo3 : add file to FAL when it is not presente in sys_file - typo3

I have this situation
I have a table in my db containing some file names in a field1 (eg field1: "my file.ext")
NOTE: the filename does not necessarily pass a Typo3 "sanitizeFilename" check -> it may contain spaces " " or other characters that would be removed by the sanitizeFilename () method
I have the file mentioned above, stored on the server that host typo3
In the sys_file table, the file is not present
the "update storage index" scheduler cannot process all the files, and if i launch it, it "destroy" the file name (my file.ext -> my_file.ext), so the name stored in the field of my table doensn't have much sense anymore.
I would need to absorb the above mentioned files in the FAL, in order to use them in an ext typo3.
I had thought of such a solution
<?php
// read from "field1" of my table
// $filename = the name extracted from my table (e.g. : "my file.ext")
// %path = the path of the file : e.g. "/fileadmin/user_upload")
if (file_exists($_SERVER['DOCUMENT_ROOT'] . "/" . $defaultStorage->getConfiguration()['basePath'] . $path . $filename)) {
// check the folder
if ($defaultStorage->hasFolder($path)) {
$folder = $defaultStorage->getFolder($path);
} else {
throw new \ Exception ($path . "path not found in AbstractImportCommand in method extractFile");
}
// CHECK IF FILE IS IN FAL
$file = $folder->getStorage()->getFileInFolder($filename, $folder);
if ($file) {
// the file already exists in the FAL
} else {
// create new sys_file
$file = $defaultStorage->addFile(
$_SERVER['DOCUMENT_ROOT'] . "/" . $defaultStorage->getConfiguration()['basePath'] . $path . $filename,
$folder,
DuplicationBehavior::REPLACE
);
}
}
Any suggestion?

Put your code into a command.
(optional) create a sys_file_metadata record for your file if you have information that needs to be stored there
create a sys_file_reference to your content record (before that you should adjust TCA accordingly)
For creating the sys_file_reference there is no api. A function doing so could look like this:
/**
* #param $fileUid
* #param $recordUid
* #param $table
*/
private function createSysFileReference($record, $fileUid, $tableName, $fieldName){
$data['sys_file_reference']['NEW_' . uniqid()] = [
'table_local' => 'sys_file',
'uid_local' => $fileUid,
'tablenames' => $tableName,
'uid_foreign' => $record['uid'],
'fieldname' => $fieldName,
'pid' => $record['pid']
];
$dataHandler = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\DataHandling\DataHandler::class);
$dataHandler->start($data, []);
$dataHandler->process_datamap();
}

What you consider as "destroying the filename" is indeed preserving file functionality, so sanitizing the filenames is required.
As example consider a file with white space like "My Pdf.pdf". It will be shown eventually like "My%20Pdf.pdf" in the URL and also saved like this. If you link to it, at least the link text won't show the "%20" and the expectation that links and the name of the file are always synchronized (no matter how it's stored) isn't reliable as it probably depends on several parameters like operating system or browser too. The same problem might occur for many different signs too.
Consider that the problems occur not only when a user is downloading a file but also when a file is uploaded, where the wrong url-encoded name is saved in the database, this name might be saved differently in the filesystem or not be found even if the saved value is the same as in the filesystem, due to the url-encoded signs. Your file references are broken on the server then and according links might not work and images not displayed.
So circumventing FAL beside tables is a bad decision and while it's likely possible to write an own sanitizer, I would refrain from dropping it completely.

Related

Concrete5.7.5.2 - Where to put form file attachment headers?

I build my email headers like this:
$txt_message .= $this->txt_message;
$html_message .= $this->html_message;
$mh = Core::make('helper/mail');
$mh->to($this->email_to, $this->site_name);
$mh->from($this->email, $this->name);
$mh->replyto($this->email, $this->name);
$mh->setSubject($this->subject);
$mh->setBody($txt_message);
$mh->setBodyHtml($html_message);
#$mh->sendMail();
Some posts say an attachment can be added with
$mh->addAttachment($file);
but $file must be a file object. How can I make the uploaded file a file object?
I also found this post:http://www.adrikodde.nl/blog/2012/mail-attachments-concrete5/
But I get errors for all Zend stuff. Is Zend Mail still available in C5.7?
Where do I put headers for a file attachment? Where can I find out more about what really sends the message (is it still a Zend Mail?) and what methods are available?
Thank you.
[SOLVED]
Thanks to Nicolai, here's a working example for attaching files:
$file = $_FILES['image']['tmp_name'];
$filename = $_FILES['image']['name'];
$importer = new \Concrete\Core\File\Importer();
$file_version = $importer->import($file, $filename);
$attachment = $file_version->getFile();
$mh->addAttachment($attachment);
//Delete the file if not wanted on server
$attachment->delete();
PS. Don't forget to check the file really selected/exists/uploaded before you try to send it!
if (!empty($this->image)) {
$importer = new \Concrete\Core\File\Importer();
$image_version = $importer->import($this->image, $file_name);
if ($image_version instanceof \Concrete\Core\File\Version) {
$attachment = $image_version->getFile();
$mh->addAttachment($attachment);
}
}
#$mh->sendMail();
To add the file to your filesystem, you should take a look at this
http://concrete5.org/api/class-Concrete.Core.File.Importer.html.
On the returned object (which is a FileVersion on success), you should be able to call getFile( ) to get the actual Concrete5 File object

Perl OpenOffice::OODoc - accessing header/footer elements

How do you get elements in a header/footer of a odt doc?
for example I have:
use OpenOffice::OODoc;
my $doc = odfDocument(file => 'whatever.odt');
my $t=0;
while (my $table = $doc->getTable($t))
{
print "Table $t exists\n";
$t++;
}
When I check the tables they are all from the body. I can't seem to find elements for anything in the header or footer?
I found sample code here which led me to the answer:
#! /usr/local/bin/perl
use OpenOffice::OODoc;
my $file='asdf.odt';
# odfContainer is a representation of the zipped odf file
# and all of its parts.
my $container = odfContainer("$file");
# We're going to look at the 'style' part of the container,
# because that's where the header is located.
my $style = odfDocument
(
container => $container,
part => 'styles'
);
# masterPageHeader takes the style name as its argument.
# This is not at all clear from the documentation.
my $masterPageHeader = $style->masterPageHeader('Standard');
my $headerText = $style->getText( $masterPageHeader );
print "$headerText\n"
The master page style defines the look and feel of the document -- think CSS. Apparently 'Standard' is the default name for the master page style of a document created by OpenOffice... that was the toughest nut to crack... once I found the example code, that fell out in my lap.

addFilter Rename ZendFramework

i need to Rename a file with Zend_File_Transfer() only if new file match with old one in the server using some convention like newfile-1.ext where the -1 is the string that is added but Rename filter is strange, i really dont understand so good.
For example, is necesary some like this:
if(file_exists($file)){
$upload->addFilter('Rename', $file);
}
or Rename does it?
thanks
Here is an example from one of my apps. File is recvieved by an Zend_Form
$upload->receive();
$name = $upload->getFileName();
$newFile = 'mynewfile.xyz'
$filterFileRename = new Zend_Filter_File_Rename(array(
'target' => $this->path . $newFile, // path to file
'overwrite' => true
));
$file = $filterFileRename->filter($name);

Zend_Form_Element_File multiple file upload and mysql

Does anybody knows a working example to receive multiple files, store them in a folder and the names in a mysql table? Some days already with no luck at all, something always missing, and before putting those questions, well , maybe i can find the right one!
maybe?
i am learning using zend 1.11
thanks
pablo
EDIT:
i add the code for clearness:
in the form:
$element = new Zend_Form_Element_File('images');
$element->setLabel('Upload bis 3 Bilder (máx. 200kb each):')
->setMultiFile(3)
->setValueDisabled(true)
->addValidator(new Zend_Validate_File_Size('2MB'))
->addValidator('Count', false, array('min'=>0,'max' => 3));
in the controller:
$adapter = $form->images->getTransferAdapter();
//create directory where files would be hold
if (!file_exists(UPLOADDIR))
mkdir(UPLOADDIR, 0777, 1);
$i=0;
$images="";
//loop uploaded files
foreach ($adapter->getFileInfo() as $info)
{
//rename file how you like and move it to given destination
$fileName = time().$i.'.'.$this->getExtension($info['name']);
$adapter->addFilter('Rename', array('target'=>UPLOADDIR.$fileName, 'overwrite'=>true));
//if something goes wrong print errors in screen
if (!$adapter->receive($info['name']))
{
die(print_r($adapter->getMessages(),1));
}else{
if ($info['name']!==""){
$images .= $fileName.",";
}
}
$i++;
}
I think you should use setFilters() instead of addFilter on the adapter, because the current code will add a new Rename filter on each iteration of the foreach loop.
Try replacing:
$adapter->addFilter('Rename', array('target'=>UPLOADDIR.$fileName, 'overwrite'=>true));
with
$adapter->setFilters(array(new Zend_Filter_File_Rename(array('target'=>UPLOADDIR.$fileName, 'overwrite'=>true))));

ZendFramework Zend_Form_Element_File setDestination vs rename filter

The code says Zend_Form_element_File::setDestination() is deprecated and to use the rename filter. However the rename filter is currently codes such that when path is set, only temporary name is given. Original filename is lost.
<?php
$file = new Zend_Form_Element_File();
$file->setDestination('/var/www/project/public');
?>
vs
<?php
$file = new Zend_Form_Element_File();
$file->addFilter('Rename', array('target' => '/var/www/project/public'));
?>
Any solution to upload files so that it preserves original filename structure but checks for existing file and appends _1.ext or _2.ext?
You need to query the name of the file after upload and then add the Rename filter then. Eg:
if ($form->file->isUploaded()) {
$fileinfo = $form->file->getFileInfo();
$filename = $fileinfo['file']['name'];
$extn = pathinfo($filename,PATHINFO_EXTENSION);
$uploadname = $this->_makeFilename($formData, $extn);
$uploadfilepath = UPLOADED_FILES_PATH . '/' . $uploadname;
$form->file->addFilter('Rename', $uploadfilepath);
$receiveStatus = $form->file->receive();
}
After submitting the form you can inspect the $_FILES['file_element']['name'] check for existing files and then set the rename filter on your form element before calling the :
$form->getValues()/isValid() or $form->file_element->receive().