protected function addAsset()
{
$success = false;
if (array_key_exists("Filedata", $_FILES)) {
$filename = $_FILES["Filedata"]["name"];
$sourcePath = $_FILES["Filedata"]["tmp_name"];
} elseif ($this->getParam("type") == "base64") {
$filename = $this->getParam("filename");
$sourcePath = PIMCORE_SYSTEM_TEMP_DIRECTORY . "/upload-base64" . uniqid() . ".tmp";
$data = preg_replace("@^data:[^,]+;base64,@", "", $this->getParam("data"));
File::put($sourcePath, base64_decode($data));
}
if ($this->getParam("dir") && $this->getParam("parentId")) {
// this is for uploading folders with Drag&Drop
// param "dir" contains the relative path of the file
$parent = Asset::getById($this->getParam("parentId"));
$newPath = $parent->getRealFullPath() . "/" . trim($this->getParam("dir"), "/ ");
// check if the path is outside of the asset directory
$newRealPath = PIMCORE_ASSET_DIRECTORY . $newPath;
$newRealPath = resolvePath($newRealPath);
if (strpos($newRealPath, PIMCORE_ASSET_DIRECTORY) !== 0) {
throw new \Exception("not allowed");
}
$maxRetries = 5;
for ($retries = 0; $retries < $maxRetries; $retries++) {
try {
$newParent = Asset\Service::createFolderByPath($newPath);
break;
} catch (\Exception $e) {
if ($retries < $maxRetries - 1) {
$waitTime = rand(100000, 900000);
// microseconds
usleep($waitTime);
// wait specified time until we restart the transaction
} else {
// if the transaction still fail after $maxRetries retries, we throw out the exception
throw $e;
}
}
}
$this->setParam("parentId", $newParent->getId());
} elseif (!$this->getParam("parentId") && $this->getParam("parentPath")) {
$parent = Asset::getByPath($this->getParam("parentPath"));
if ($parent instanceof Asset\Folder) {
$this->setParam("parentId", $parent->getId());
} else {
$this->setParam("parentId", 1);
}
} elseif (!$this->getParam("parentId")) {
// set the parent to the root folder
$this->setParam("parentId", 1);
}
$filename = Element\Service::getValidKey($filename, "asset");
if (empty($filename)) {
throw new \Exception("The filename of the asset is empty");
}
$parentAsset = Asset::getById(intval($this->getParam("parentId")));
// check for duplicate filename
$filename = $this->getSafeFilename($parentAsset->getRealFullPath(), $filename);
if ($parentAsset->isAllowed("create")) {
if (!is_file($sourcePath) || filesize($sourcePath) < 1) {
throw new \Exception("Something went wrong, please check upload_max_filesize and post_max_size in your php.ini and write permissions of /website/var/");
}
$asset = Asset::create($this->getParam("parentId"), ["filename" => $filename, "sourcePath" => $sourcePath, "userOwner" => $this->user->getId(), "userModification" => $this->user->getId()]);
$success = true;
@unlink($sourcePath);
} else {
Logger::debug("prevented creating asset because of missing permissions, parent asset is " . $parentAsset->getRealFullPath());
}
return ["success" => $success, "asset" => $asset];
}