I am uploading file to tmp folder from external file using php code(not from user post request), then fill $_FILES with information for that file and pass it to code that uses $_FILES variable. But inside that code, it uses move_uploaded_file, that has is_uploaded_file check. File uploaded manually by code(not by user form posted) fails this check because it was not uploaded using POST. Can I make it pass that check?
Code that fails:
//$url contains url of image from another site
function upload_from_url($url)
{
global $modx;
// we load temporary file to /tmp and then add it to $_FILES
$img = '/tmp/'.uniqid("", true); // no extension here since we can't trust it
$res = file_put_contents($img, file_get_contents($url)); // UPLOAD is made here, it works
$mimeType = mime_content_type($img);
$allowedMimeTypes = ["image/jpeg","image/gif","image/png"];
if (!in_array($mimeType, $allowedMimeTypes))
{
logError("!!!ATTENTION!!! got file $img with forbidden mime type $mimeType");
throw new RuntimeException("Forbidden file mime type!");
die; // just to be sure; shouldn't get here
}
$_FILES['file']['name'] = uniqid("img", true)."."
.(explode("/", $mimeType)[1]); // get jpg part of image/jpg
$_FILES['file']['type'] = $mimeType;
$_FILES['file']['tmp_name'] = $img;
$_FILES['file']['error'] = 0; // = UPLOAD_ERR_OK
$_FILES['file']['size'] = filesize($img);
$response = $modx-> runProcessor('browser/file/upload', ['path' => 'assets/images']); // <= here it fails
}
Inside $modx-> runProcessor('browser/file/upload'...
code, there is part that fails:
if (!move_uploaded_file($file['tmp_name'],$newPath)) {
$this->addError('path',$this->xpdo->lexicon('file_err_upload'));
continue;
}
It gets $file from $files from $_FILES variable, and I don't want to modify framework code to workaround it.
I don't think you'll be able of convincing the php core that it is indeed an uploaded file, but you can try using the MODX Media Sources instead of the upload processor.
Get an instance of a media source, initialize it, and use createObject
to create a file:
$source = $modx->getObject('sources.modMediaSource', $idOfSource);
if ($source && $source->initialize()) {
$source->createObject($objectPath, $name, $content)
}