TODO

@param $name
@param null $folder
@return Upload
328252
public function allocate($name, $folder = null)
    {
        return new Upload($this, isset($_FILES[$name])?$_FILES[$name]:array(), $folder);
    }
1177840
function getFiles($folder, $name)
    {
        $filesArray = array();
        $files = Folder::files($folder, null, false, true);

	    $path = JFusionFramework::getPluginPath($name);

        foreach ($files as $file) {
            $file = str_replace($path . '/', '', $file);
	        $file = str_replace($path . '\\', '', $file);
            $data = file_get_contents($file);
            $filesArray[] = array('name' => $file, 'data' => $data);
        }
        $folders = Folder::folders($folder, null, false, true);
        if (!empty($folders)) {
            foreach ($folders as $f) {
                $filesArray = array_merge($filesArray, $this->getFiles($f, $name));
            }
        }
        return $filesArray;
    }
268244
public function createFolder($folder)
    {
        if ($this->exists($folder)) {
            return true;
        }

        $metadata = $this->dropbox->createFolder($this->pathRoot.$folder);
        return !is_null($metadata);
    }
1339899
public function upload($name)
    {
        $instance = $this->_getInstance($name);
        require_once Plugin::classPath('Field') . 'Lib/class.upload.php';
        $uploader = new \upload($this->request->data['Filedata']);

        if (!empty($instance->settings['extensions'])) {
            $exts = explode(',', $instance->settings['extensions']);
            $exts = array_map('trim', $exts);
            $exts = array_map('strtolower', $exts);

            if (!in_array(strtolower($uploader->file_src_name_ext), $exts)) {
                $this->_error(__d('field', 'Invalid file extension.'), 501);
            }
        }

        $response = '';
        $uploader->file_overwrite = false;
        $folder = normalizePath(WWW_ROOT . "/files/{$instance->settings['upload_folder']}/");
        $url = normalizePath("/files/{$instance->settings['upload_folder']}/", '/');

        $uploader->process($folder);
        if ($uploader->processed) {
            $response = json_encode([
                'file_url' => Router::url($url . $uploader->file_dst_name, true),
                'file_size' => FileToolbox::bytesToSize($uploader->file_src_size),
                'file_name' => $uploader->file_dst_name,
                'mime_icon' => FileToolbox::fileIcon($uploader->file_src_mime),
            ]);
        } else {
            $this->_error(__d('field', 'File upload error, details: {0}', $uploader->error), 502);
        }

        $this->viewBuilder()->layout('ajax');
        $this->title(__d('field', 'Upload File'));
        $this->set(compact('response'));
    }
161957
public static function updateFolder($bucket, $folder, $bizAttr = null) {
        $folder = self::normalizerPath($folder, True);

        return self::updateBase($bucket, $folder, $bizAttr);
    }
1063021
public function getUploadPath($name = null)
    {
        if (is_null($name)) {
            return '';
        } else {
            if (!isset($this->cache[$name])) {
                $this->cache[$name] = Yii::$app->pathManager->getPath($this->namespace);
            }
        }
        return $this->cache[$name]->getFullPath($name);
    }
883014
public function renamePluginEntry($folder, $element, $name)
	{
		if ($this->baseDb->tableExists('#__plugins'))
		{
			$table = '#__plugins';
			$pk    = 'id';
		}
		else if ($this->baseDb->tableExists('#__extensions'))
		{
			$table = '#__extensions';
			$pk    = 'extension_id';
		}
		else
		{
			$this->log(sprintf('Required table not found for renaming plugin plg_%s_%s', $folder, $element), 'warning');
			return false;
		}

		$folder  = strtolower($folder);
		$element = strtolower($element);

		// First, make sure the plugin exists
		$query = "SELECT `{$pk}` FROM `{$table}` WHERE `folder` = '{$folder}' AND `element` = '{$element}'";
		$this->baseDb->setQuery($query);
		if ($id = $this->baseDb->loadResult())
		{
			$query = "UPDATE `{$table}` SET `name` = " . $this->baseDb->quote($name) . " WHERE `{$pk}` = " . $this->baseDb->quote($id);
			$this->baseDb->setQuery($query);
			$this->baseDb->query();

			$this->log(sprintf('Renamed plugin plg_%s_%s to "%s"', $folder, $element, $name));
		}

		return true;
	}
523685
public function get($name, $path, $controller = null)
    {
        $this->add('GET', $name, $path, $controller);
        return $this;
    }
1038076
public function setRelativeUploadsFolderPath($folder) {
        $this->relativeUploadsFolderPath = $folder instanceof \Closure ? $folder : static::normalizeFolderPath($folder);
        return $this;
    }
601277
public function createFolder($folder = null)
    {
        $folder = $this->paths->getFolder($folder);
        $this->modulable->toHistory('mkdir '.$folder);

        return $this->modulable->getConnection()->createDir($folder);
    }
165049
public static function getParams($name, $folder)
	{
		$database = \App::get('db');

		// load the params from databse
		$sql = "SELECT params FROM `#__extensions` WHERE folder=" . $database->quote($folder) . " AND element=" . $database->quote($name) . " AND enabled=1";
		$database->setQuery($sql);
		$result = $database->loadResult();

		// params object
		$params = new Registry($result);
		return $params;
	}
988474
public function getUploadDir($name)
    {
        if (array_key_exists($name, $this->paths)) {
            return $this->paths[$name];
        } else {
            throw new \InvalidArgumentException(sprintf('Upload path "%s" is not defined.', $name));
        }
    }
1077331
public static function getUploadedFile($name)
    {

        // for large file, the $_FILES may be empty so see this before checking for other updates
        $limit = SystemHelper::getFileUploadLimit();
        $contentLength = intval($_SERVER['CONTENT_LENGTH']);
        if( $limit > 0 && $contentLength > $limit && count(self::getFiles())===0){
            throw new FileUploadException('Exceeded filesize limit of ' . $limit);
        }

        $files = self::getFiles();
        $fileData = $files[$name];
        if (isset($files[$name])) {

            //check for upload errors
            if (isset($fileData['error']) && $fileData['error'] != UPLOAD_ERR_OK) {
                switch ($fileData['error']) {
                    case UPLOAD_ERR_NO_FILE:
                        throw new FileUploadException('No file sent.');
                    case UPLOAD_ERR_INI_SIZE:
                    case UPLOAD_ERR_FORM_SIZE:
                        throw new FileUploadException('Exceeded filesize limit of ' . $limit);
                    default:
                        throw new common_exception_Error('Upload fails, check errors');
                }
            }
        }
        if (!is_uploaded_file($fileData['tmp_name'])) {
            throw new common_exception_Error('Non uploaded file in filedata, potential attack');
        }
        return $fileData;
    }
955668
public static function files($name = null)
    {
        $files = app()->request->getUploadedFiles();

        if (is_null($name)) {
            return $files;
        }

        if (isset($files[$name])) {
            return $files[$name];
        }

        return null;
    }
200159
public function handleUpload($uploadDirectory, $name = null){

        if (is_writable($this->chunksFolder) &&
            1 == mt_rand(1, 1/$this->chunksCleanupProbability)){

            // Run garbage collection
            $this->cleanupChunks();
        }

        // Check that the max upload size specified in class configuration does not
        // exceed size allowed by server config
        if ($this->toBytes($this->iniGet('post_max_size')) < $this->sizeLimit ||
            $this->toBytes($this->iniGet('upload_max_filesize')) < $this->sizeLimit){
            $size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';
            return array('error'=>"Server error. Increase post_max_size and upload_max_filesize to ".$size);
        }

        if ($this->isInaccessible($uploadDirectory)){
            return array('error' => "Server error. Uploads directory isn't writable");
        }

        if(!isset($_SERVER['CONTENT_TYPE'])) {
            return array('error' => "No files were uploaded.");
        } else if (strpos(strtolower($_SERVER['CONTENT_TYPE']), 'multipart/') !== 0){
            return array('error' => "Server error. Not a multipart request. Please set forceMultipart to default value (true).");
        }

        // Get size and name
        $file = $_FILES[$this->inputName];
        $size = $file['size'];

        if ($name === null){
            $name = $this->getName();
        }

        // Validate name
        if ($name === null || $name === ''){
            return array('error' => 'File name empty.');
        }

        // Validate file size
        if ($size == 0){
            return array('error' => 'File is empty.');
        }

        if ($size > $this->sizeLimit){
            return array('error' => 'File is too large.');
        }

        // Validate file extension
        $pathinfo = pathinfo($name);
        $ext = isset($pathinfo['extension']) ? $pathinfo['extension'] : '';

        if($this->allowedExtensions && !in_array(strtolower($ext), array_map("strtolower", $this->allowedExtensions))){
            $these = implode(', ', $this->allowedExtensions);
            return array('error' => 'File has an invalid extension, it should be one of '. $these . '.');
        }

        // Save a chunk
        $totalParts = isset($_REQUEST['qqtotalparts']) ? (int)$_REQUEST['qqtotalparts'] : 1;

        $uuid = $_REQUEST['qquuid'];
        if ($totalParts > 1){
        # chunked upload

            $chunksFolder = $this->chunksFolder;
            $partIndex = (int)$_REQUEST['qqpartindex'];

            if (!is_writable($chunksFolder) && !is_executable($uploadDirectory)){
                return array('error' => "Server error. Chunks directory isn't writable or executable.");
            }

            $targetFolder = $this->chunksFolder.DIRECTORY_SEPARATOR.$uuid;

            if (!file_exists($targetFolder)){
                mkdir($targetFolder);
            }

            $target = $targetFolder.'/'.$partIndex;
            $success = move_uploaded_file($_FILES[$this->inputName]['tmp_name'], $target);

            // Last chunk saved successfully
            if ($success AND ($totalParts-1 == $partIndex)){

                $target = join(DIRECTORY_SEPARATOR, array($uploadDirectory, $uuid, $name));
                //$target = $this->getUniqueTargetPath($uploadDirectory, $name);
                $this->uploadName = $uuid.DIRECTORY_SEPARATOR.$name;

                if (!file_exists($target)){
                    mkdir(dirname($target));
                }
                $target = fopen($target, 'wb');

                for ($i=0; $i<$totalParts; $i++){
                    $chunk = fopen($targetFolder.DIRECTORY_SEPARATOR.$i, "rb");
                    stream_copy_to_stream($chunk, $target);
                    fclose($chunk);
                }

                // Success
                fclose($target);

                for ($i=0; $i<$totalParts; $i++){
                    unlink($targetFolder.DIRECTORY_SEPARATOR.$i);
                }

                rmdir($targetFolder);

                return array("success" => true, "uuid" => $uuid);
            }

            return array("success" => true, "uuid" => $uuid);

        }
        else {
        # non-chunked upload

            $target = join(DIRECTORY_SEPARATOR, array($uploadDirectory, $uuid, $name));
            //$target = $this->getUniqueTargetPath($uploadDirectory, $name);

            if ($target){
                $this->uploadName = basename($target);

                if (!is_dir(dirname($target))){
                    mkdir(dirname($target));
                }
                if (move_uploaded_file($file['tmp_name'], $target)){
                    return array('success'=> true, "uuid" => $uuid);
                }
            }

            return array('error'=> 'Could not save uploaded file.' .
                'The upload was cancelled, or server error encountered');
        }
    }
423630
public function uploadAction(Request $request)
    {
        $folderId = $request->get('folder_id', null);

        try {
            $volumeManager = $this->get('phlexible_media_manager.volume_manager');
            $volume = $volumeManager->getByFolderId($folderId);
            $folder = $volume->findFolder($folderId);

            if (empty($folder)) {
                return new ResultResponse(
                    false,
                    'Target folder not found.',
                    [
                        'params' => $request->request->all(),
                        'files' => $request->files->all(),
                    ]
                );
            }

            if (!$request->files->count()) {
                return new ResultResponse(
                    false,
                    'No files received.',
                    [
                        'params' => $request->request->all(),
                        'files' => $request->files->all(),
                    ]
                );
            }

            $uploadHandler = $this->get('phlexible_media_manager.upload.handler');

            $cnt = 0;
            foreach ($request->files->all() as $uploadedFile) {
                /* @var $uploadedFile UploadedFile */

                $file = $uploadHandler->handle($uploadedFile, $folderId, $this->getUser()->getId());

                if ($file) {
                    ++$cnt;

                    $body = 'Filename: '.$uploadedFile->getClientOriginalName().PHP_EOL
                        .'Folder:   '.$folder->getName().PHP_EOL
                        .'Filesize: '.$file->getSize().PHP_EOL
                        .'Filetype: '.$file->getMimeType().PHP_EOL;

                    $message = MediaManagerMessage::create('File "'.$file->getName().'" uploaded.', $body);
                    $this->get('phlexible_message.message_poster')->post($message);
                }
            }

            return new ResultResponse(
                true,
                $cnt.' file(s) uploaded.',
                [
                    'params' => $request->request->all(),
                    'files' => $request->files->all(),
                ]
            );
        } catch (\Exception $e) {
            return new ResultResponse(
                false,
                $e->getMessage(),
                [
                    'params' => $request->request->all(),
                    'files' => $request->files->all(),
                    'trace' => $e->getTraceAsString(),
                    'traceArray' => $e->getTrace(),
                ]
            );
        }
    }
653128
public function uploadOne(UploadedFile $file, $folder = null, $disk = 'public')
    {
        return $file->store($folder, ['disk' => $disk]);
    }