Image Upload with $_FILES array:

Post values:
+ file
+ folderId
+ isHidden

@return array
@since 1.2.3
9043
public function actionImagesUpload()
    {
        $result = $this->actionFilesUpload();

        if ($result['upload'] && $result['file']) {
            $fileId = $result['file']->id;

            $image = Yii::$app->storage->createImage($fileId, 0);

            if ($image) {
                // create system thumbnails
                $tinyCrop = Yii::$app->storage->createImage($fileId, Yii::$app->storage->getFilterId(TinyCrop::identifier()));
                $mediumThumbnail = Yii::$app->storage->createImage($fileId, Yii::$app->storage->getFilterId(MediumThumbnail::identifier()));
            }

            return [
                'image' => $image,
                'tinyCrop' => $tinyCrop,
                'mediumThumbnail' => $mediumThumbnail,
            ];
        }

        return $this->sendArrayError(['image' => 'Unable to create the given with and the corresponding filters.']);
    }
308721
public function uploadedFiles()
    {
        if (!$this->files) {
            $this->files = new UploadedFiles($_FILES);
        }
        return $this->files->files();
    }
1258851
public function actionIndex()
    {
        $this->requirePostRequest();
        $request = Craft::$app->getRequest();
        $plugin = Plugin::getInstance();
        $settings = $plugin->getSettings();

        $submission = new Submission();
        $submission->fromEmail = $request->getBodyParam('fromEmail');
        $submission->fromName = $request->getBodyParam('fromName');
        $submission->subject = $request->getBodyParam('subject');

        $message = $request->getBodyParam('message');
        if (is_array($message)) {
            $submission->message = array_filter($message, function($value) {
                return $value !== '';
            });
        } else {
            $submission->message = $message;
        }

        if ($settings->allowAttachments && isset($_FILES['attachment']) && isset($_FILES['attachment']['name'])) {
            if (is_array($_FILES['attachment']['name'])) {
                $submission->attachment = UploadedFile::getInstancesByName('attachment');
            } else {
                $submission->attachment = [UploadedFile::getInstanceByName('attachment')];
            }
        }

        if (!$plugin->getMailer()->send($submission)) {
            if ($request->getAcceptsJson()) {
                return $this->asJson(['errors' => $submission->getErrors()]);
            }

            Craft::$app->getSession()->setError(Craft::t('contact-form', 'There was a problem with your submission, please check the form and try again!'));
            Craft::$app->getUrlManager()->setRouteParams([
                'variables' => ['message' => $submission]
            ]);

            return null;
        }

        if ($request->getAcceptsJson()) {
            return $this->asJson(['success' => true]);
        }

        Craft::$app->getSession()->setNotice($settings->successFlashMessage);
        return $this->redirectToPostedUrl($submission);
    }
486023
public function get_files() {
        // The files array can contain stored file ids, so we need to get instances if asked.
        foreach ($this->files as $id => $listfile) {
            if (is_numeric($listfile)) {
                $fs = get_file_storage();

                if ($file = $fs->get_file_by_id($id)) {
                    $this->files[$id] = $file;
                } else {
                    unset($this->files[$id]); // Index is out of date and referencing a file that does not exist.
                }
            }
        }

        return $this->files;
    }
784329
protected function uploadArchive()
    {

        if ($_FILES['content']['error'] !== UPLOAD_ERR_OK) {

            \common_Logger::w('File upload failed with error ' . $_FILES['content']['error']);
            switch ($_FILES['content']['error']) {
                case UPLOAD_ERR_INI_SIZE:
                case UPLOAD_ERR_FORM_SIZE:
                    $error = __('Archive size must be lesser than : ') . ini_get('post_max_size');
                    break;
                case UPLOAD_ERR_NO_FILE:
                    $error = __('No file uploaded');
                    break;
                default:
                    $error = __('File upload failed');
                    break;
            }
            return array('error' => $error);
        }

        $filePath = $this->tmpDir . '/' . $_FILES['content']['name'];
        if (!move_uploaded_file($_FILES['content']['tmp_name'], $filePath)) {
            return array('error' => __('Unable to move uploaded file'));
        }

        return $filePath;
    }
325919
protected function parsePost()
    {
        $ret = $_POST ?: [];
        if (isset($_FILES)) {
            foreach ($_FILES as $name => $info) {
                if (is_array($info["name"])) {
                    $len = count($info["name"]);
                    for ($i = 0; $i < $len; $i++) {
                        $file = $this->createUploadedFile([
                            "name" => $info["name"][$i] ?? "",
                            "type" => $info["type"][$i] ?? "",
                            "tmp_name" => $info["tmp_name"][$i] ?? "",
                            "error" => $info["error"][$i] ?? 0,
                            "size" => $info["size"][$i] ?? 0,
                        ]);
                        \sndsgd\Arr::addValue($ret, $name, $file);
                    }
                } else {
                    $file = $this->createUploadedFile($info);
                    \sndsgd\Arr::addValue($ret, $name, $file);
                }
            }
        }
        return $ret;
    }
1356589
protected function uploadSingleFile()
    {
        // check if there is error while uploading from error array key.
        if (is_array($this->files[$this->input_file_name]) && array_key_exists('error', $this->files[$this->input_file_name]) && $this->files[$this->input_file_name]['error'] != 0) {
            switch ($this->files[$this->input_file_name]['error']) {
                case 1:
                    $this->setErrorMessage(
                        sprintf(static::__('The uploaded file exceeds the max file size directive. (%s &gt; %s).'), $this->files[$this->input_file_name]['size'], ini_get('upload_max_filesize')),
                        'RDU_' . $this->files[$this->input_file_name]['error'],
                        $this->files[$this->input_file_name]['size'] . ' &gt; ' . ini_get('upload_max_filesize'),
                        $this->files[$this->input_file_name]['name'],
                        $this->files[$this->input_file_name]['size'],
                        $this->files[$this->input_file_name]['type']
                    );
                    return false;
                case 2:
                    $this->setErrorMessage(
                        static::__('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.'),
                        'RDU_' . $this->files[$this->input_file_name]['error'],
                        '',
                        $this->files[$this->input_file_name]['name'],
                        $this->files[$this->input_file_name]['size'],
                        $this->files[$this->input_file_name]['type']
                    );
                    return false;
                case 3:
                    $this->setErrorMessage(
                        static::__('The uploaded file was only partially uploaded.'),
                        'RDU_' . $this->files[$this->input_file_name]['error'],
                        '',
                        $this->files[$this->input_file_name]['name'],
                        $this->files[$this->input_file_name]['size'],
                        $this->files[$this->input_file_name]['type']
                    );
                    return false;
                case 4:
                    $this->setErrorMessage(
                        static::__('You did not upload the file.'),
                        'RDU_' . $this->files[$this->input_file_name]['error'],
                        '',
                        $this->files[$this->input_file_name]['name'],
                        $this->files[$this->input_file_name]['size'],
                        $this->files[$this->input_file_name]['type']
                    );
                    return false;
                case 6:
                    $this->setErrorMessage(
                        static::__('Missing a temporary folder.'),
                        'RDU_' . $this->files[$this->input_file_name]['error'],
                        '',
                        $this->files[$this->input_file_name]['name'],
                        $this->files[$this->input_file_name]['size'],
                        $this->files[$this->input_file_name]['type']
                    );
                    return false;
                case 7:
                    $this->setErrorMessage(
                        static::__('Failed to write file to disk.'),
                        'RDU_' . $this->files[$this->input_file_name]['error'],
                        '',
                        $this->files[$this->input_file_name]['name'],
                        $this->files[$this->input_file_name]['size'],
                        $this->files[$this->input_file_name]['type']
                    );
                    return false;
                case 8:
                    $this->setErrorMessage(
                        static::__('A PHP extension stopped the file upload.'),
                        'RDU_' . $this->files[$this->input_file_name]['error'],
                        '',
                        $this->files[$this->input_file_name]['name'],
                        $this->files[$this->input_file_name]['size'],
                        $this->files[$this->input_file_name]['type']
                    );
                    return false;
            }
        }

        // validate that there is file upload.
        if (
            empty($this->files[$this->input_file_name]) || 
            (
                is_array($this->files[$this->input_file_name]) && 
                array_key_exists('name', $this->files[$this->input_file_name]) && 
                $this->files[$this->input_file_name]['name'] == null
            ) ||
            (
                is_array($this->files[$this->input_file_name]) && 
                array_key_exists('tmp_name', $this->files[$this->input_file_name]) && 
                $this->files[$this->input_file_name]['tmp_name'] == null
            )
        ) {
            $this->setErrorMessage(
                static::__('You did not upload the file.'),
                'RDU_4',
                '',
                $this->files[$this->input_file_name]['name'],
                $this->files[$this->input_file_name]['size'],
                $this->files[$this->input_file_name]['type']
            );
            return false;
        }

        // validate allowed extension and its mime types.
        $result = $this->validateExtensionAndMimeType();
        if ($result !== true) {
            return false;
        }
        unset($result);

        // validate max file size.
        $result = $this->validateFileSize();
        if ($result !== true) {
            return false;
        }
        unset($result);

        // validate max image dimension.
        $result = $this->validateImageDimension();
        if ($result !== true) {
            return false;
        }
        unset($result);

        // security scan.
        if ($this->security_scan === true) {
            $result = $this->securityScan();
            if ($result !== true) {
                return false;
            }
            unset($result);
        }

        // set new file name (in case that it was not set) and check for reserved file name.
        $tmp_new_file_name = $this->new_file_name;
        $this->setNewFileName();

        // check for safe web file name if this option was set to true.
        if ($this->web_safe_file_name === true) {
            $this->setWebSafeFileName();
        }

        // now, it should all passed validation. add the uploaded file to move uploaded queue in case that it is upload multiple file and has option to stop on error.
        // get the uploaded file extension.
        $file_name_explode = explode('.', $this->files[$this->input_file_name]['name']);
        $file_extension = null;
        if (is_array($file_name_explode)) {
            $file_extension = '.'.$file_name_explode[count($file_name_explode)-1];
        }
        unset($file_name_explode);
        // add to queue.
        $this->move_uploaded_queue = array_merge(
            $this->move_uploaded_queue, 
            array(
                $this->files[$this->input_file_name]['input_file_key'] => array(
                    'name' => $this->files[$this->input_file_name]['name'],
                    'tmp_name' => $this->files[$this->input_file_name]['tmp_name'],
                    'new_name' => $this->new_file_name.$file_extension,
                )
            )
        );
        // restore temp of new file name to ready for next loop of upload multiple.
        $this->new_file_name = $tmp_new_file_name;
        unset($file_extension, $tmp_new_file_name);

        // done.
        return true;
    }
1090249
protected function defaultUploadedFiles()
    {
        $files = [];
        foreach ($_FILES as $class => $info) {
            $files[$class] = [];
            $this->populateUploadedFileRecursive($files[$class], $info['name'], $info['tmp_name'], $info['type'], $info['size'], $info['error']);
        }

        return $files;
    }
647830
function reArrayFiles(&$file_post) {

        $file_ary = array();
        $file_count = count($file_post['name']);
        $file_keys = array_keys($file_post);

        for ($i=0; $i<$file_count; $i++) {
            foreach ($file_keys as $key) {
                $file_ary[$i][$key] = $file_post[$key][$i];
            }
        }

        return $file_ary;
    }
1314013
private static function areFileUploadsEnabled() {
		if (self::parseIniBoolean(\ini_get('file_uploads')) === false) {
			return false;
		}

		if (((int) \ini_get('max_file_uploads')) <= 0) {
			return false;
		}

		return true;
	}
978367
public function definition() {
        $mform =& $this->_form;

        $types = (FILE_INTERNAL | FILE_REFERENCE | FILE_CONTROLLED_LINK);
        $options = array('subdirs' => 0, 'maxfiles' => -1, 'accepted_types' => '*', 'return_types' => $types);

        $mform->addElement('filemanager', 'files_filemanager', get_string('files'), null, $options);

        $mform->addElement('hidden', 'contextid', $this->_customdata['contextid']);
        $mform->setType('contextid', PARAM_INT);

        $mform->addElement('hidden', 'currentcontext', $this->_customdata['currentcontext']);
        $mform->setType('currentcontext', PARAM_INT);

        $mform->addElement('hidden', 'filearea', $this->_customdata['filearea']);
        $mform->setType('filearea', PARAM_AREA);

        $mform->addElement('hidden', 'component', $this->_customdata['component']);
        $mform->setType('component', PARAM_COMPONENT);

        $mform->addElement('hidden', 'returnurl', $this->_customdata['returnurl']);
        $mform->setType('returnurl', PARAM_URL);

        $this->add_action_buttons(true, get_string('savechanges'));
        $this->set_data($this->_customdata['data']);
    }
355618
public function getFilesArray()
    {
        if ($this->_filesArray === null) {
            $this->_filesArray = $this->getQueryCacheHelper((new Query())->from('{{%admin_storage_file}}')->select(['id', 'is_hidden', 'is_deleted', 'folder_id', 'name_original', 'name_new', 'name_new_compound', 'mime_type', 'extension', 'hash_name', 'hash_file', 'upload_timestamp', 'file_size', 'upload_user_id', 'caption'])->indexBy('id'), self::CACHE_KEY_FILE);
        }

        return $this->_filesArray;
    }
1296816
public function actionFilesUpload()
    {
        $this->checkRouteAccess(self::PERMISSION_ROUTE);
        
        foreach ($_FILES as $k => $file) {
            if ($file['error'] !== UPLOAD_ERR_OK) {
                Yii::$app->response->setStatusCode(422, 'Data Validation Failed.');
                return ['upload' => false, 'message' => Storage::getUploadErrorMessage($file['error']), 'file' => null];
            }
            try {
                $response = Yii::$app->storage->addFile($file['tmp_name'], $file['name'], Yii::$app->request->post('folderId', 0), Yii::$app->request->post('isHidden', false));
                if ($response) {
                    return ['upload' => true, 'message' => Module::t('api_storage_file_upload_succes'), 'file' => $response];
                } else {
                    Yii::$app->response->setStatusCode(422, 'Data Validation Failed.');
                    return ['upload' => false, 'message' => Module::t('api_storage_file_upload_folder_error'), 'file' => null];
                }
            } catch (Exception $err) {
                Yii::$app->response->setStatusCode(422, 'Data Validation Failed.');
                return ['upload' => false, 'message' => Module::t('api_sotrage_file_upload_error', ['error' => $err->getMessage()]), 'file' => null];
            }
        }
    
        // If the files array is empty, this is an indicator for exceeding the upload_max_filesize from php ini or a wrong upload defintion.
        Yii::$app->response->setStatusCode(422, 'Data Validation Failed.');
        return ['upload' => false, 'message' => Storage::getUploadErrorMessage(UPLOAD_ERR_NO_FILE), 'file' => null];
    }
1349953
protected static function getPostData()
    {
        $post_data = '-';
        if(!empty($_POST))
        {
            /*
             * Clean posted data to hide passwords
            */
            $password_subtexts = ['password', 'pwd'];

            $post = $_POST;

            foreach($post as $field => $value)
            {
                if(is_string($value))
                {
                    foreach($password_subtexts as $password_subtext){
                        if(stripos($field, $password_subtext) !== false){
                            $post[$field] = '*****';
                        }
                    }
                }
                elseif(is_array($value))
                {
                    foreach($value as $f => $v)
                    {
                        if(is_string($v))
                        {
                            foreach($password_subtexts as $password_subtext){
                                if(stripos($f, $password_subtext) !== false){
                                    $post[$field][$f] = '*****';
                                }
                            }
                        }
                    }
                }
            }

            $post_data = json_encode($post);

            return $post_data;
        }
    }
513590
public function getDataAsArray()
    {
        $fields = $this->getFields();

        if (!$fields) {
            return [];
        }

        $result = [];

        foreach ($fields as $field) {
            //ignore non-fields
            if (!$field instanceof AbstractFormField) {
                continue;
            }

            // if a field is disabled, we will ignore the field and only set an empty string as value
            if ($field->isDisabled()) {
                if (!array_key_exists($field->getName(), $result)) {
                    $result[$field->getName()] = '';
                }
                continue;
            }


            if ($field instanceof CheckBox) {
                $result[$field->getName()] = $field->isChecked() ? $field->getValue() : '';
            } elseif ($field instanceof RadioButton) {
                // if the field is not checked...
                if (!$field->isChecked()) {
                    // there was no other field with the same name yet
                    if (!array_key_exists($field->getName(), $result)) {
                        // then set the field with an empty value
                        $result[$field->getName()] = '';
                    }
                } // the field is checked
                else {
                    $result[$field->getName()] = $field->getValue();
                }
            } elseif ($field instanceof UploadField) {
                $value = $field->getValue();
                if (!$value ||
                    !isset($value['error']) ||
                    $value['error'] == UPLOAD_ERR_NO_FILE ||
                    empty($value['name'])
                ) {
                    continue;
                }
                $result[$field->getName()] = $value['name'];
            } elseif ($field instanceof AbstractFormField) {
                $result[$field->getName()] = $field->getValue();
            }
        }
        return $result;
    }
694747
public function getFiles()
    {

        // initialize the array with the files
        $files = array();

        // iterate over the file keys and read the configuration values
        foreach (FileKeys::getServerFileKeys() as $fileKey) {
            $files[$fileKey] = $this->getSystemConfiguration()->getParam($fileKey);
        }

        // return the array with the files
        return $files;
    }
298601
public function getFileArray()
    {
        if (!$this->FileArray) {
            $user = $this->getConfig('user');
            is_true_or_fail(is_positive($user), __d('me_cms', 'You have to set a valid user id'), InvalidArgumentException::class);
            $this->FileArray = new FileArray(LOGIN_RECORDS . 'user_' . $user . '.log');
        }

        return $this->FileArray;
    }