Upload files and send them to multiple users.

@param array $users - An array of user ids
@return string - The response html
163495
public function view_batch_upload_files($users) {
        global $CFG, $DB, $USER;

        require_capability('mod/assign:grade', $this->assignment->get_context());
        require_once($CFG->dirroot . '/mod/assign/feedback/file/batchuploadfilesform.php');
        require_once($CFG->dirroot . '/mod/assign/renderable.php');

        $formparams = array('cm'=>$this->assignment->get_course_module()->id,
                            'users'=>$users,
                            'context'=>$this->assignment->get_context());

        $usershtml = '';

        $usercount = 0;
        foreach ($users as $userid) {
            if ($usercount >= ASSIGNFEEDBACK_FILE_MAXSUMMARYUSERS) {
                $moreuserscount = count($users) - ASSIGNFEEDBACK_FILE_MAXSUMMARYUSERS;
                $usershtml .= get_string('moreusers', 'assignfeedback_file', $moreuserscount);
                break;
            }
            $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);

            $usersummary = new assign_user_summary($user,
                                                   $this->assignment->get_course()->id,
                                                   has_capability('moodle/site:viewfullnames',
                                                   $this->assignment->get_course_context()),
                                                   $this->assignment->is_blind_marking(),
                                                   $this->assignment->get_uniqueid_for_user($user->id),
                                                   get_extra_user_fields($this->assignment->get_context()));
            $usershtml .= $this->assignment->get_renderer()->render($usersummary);
            $usercount += 1;
        }

        $formparams['usershtml'] = $usershtml;

        $mform = new assignfeedback_file_batch_upload_files_form(null, $formparams);

        if ($mform->is_cancelled()) {
            redirect(new moodle_url('view.php',
                                    array('id'=>$this->assignment->get_course_module()->id,
                                          'action'=>'grading')));
            return;
        } else if ($data = $mform->get_data()) {
            // Copy the files from the draft area to a temporary import area.
            $data = file_postupdate_standard_filemanager($data,
                                                         'files',
                                                         $this->get_file_options(),
                                                         $this->assignment->get_context(),
                                                         'assignfeedback_file',
                                                         ASSIGNFEEDBACK_FILE_BATCH_FILEAREA,
                                                         $USER->id);
            $fs = get_file_storage();

            // Now copy each of these files to the users feedback file area.
            foreach ($users as $userid) {
                $grade = $this->assignment->get_user_grade($userid, true);
                $this->assignment->notify_grade_modified($grade);

                $this->copy_area_files($fs,
                                       $this->assignment->get_context()->id,
                                       'assignfeedback_file',
                                       ASSIGNFEEDBACK_FILE_BATCH_FILEAREA,
                                       $USER->id,
                                       $this->assignment->get_context()->id,
                                       'assignfeedback_file',
                                       ASSIGNFEEDBACK_FILE_FILEAREA,
                                       $grade->id);

                $filefeedback = $this->get_file_feedback($grade->id);
                if ($filefeedback) {
                    $filefeedback->numfiles = $this->count_files($grade->id,
                                                                 ASSIGNFEEDBACK_FILE_FILEAREA);
                    $DB->update_record('assignfeedback_file', $filefeedback);
                } else {
                    $filefeedback = new stdClass();
                    $filefeedback->numfiles = $this->count_files($grade->id,
                                                                 ASSIGNFEEDBACK_FILE_FILEAREA);
                    $filefeedback->grade = $grade->id;
                    $filefeedback->assignment = $this->assignment->get_instance()->id;
                    $DB->insert_record('assignfeedback_file', $filefeedback);
                }
            }

            // Now delete the temporary import area.
            $fs->delete_area_files($this->assignment->get_context()->id,
                                   'assignfeedback_file',
                                   ASSIGNFEEDBACK_FILE_BATCH_FILEAREA,
                                   $USER->id);

            redirect(new moodle_url('view.php',
                                    array('id'=>$this->assignment->get_course_module()->id,
                                          'action'=>'grading')));
            return;
        } else {

            $header = new assign_header($this->assignment->get_instance(),
                                        $this->assignment->get_context(),
                                        false,
                                        $this->assignment->get_course_module()->id,
                                        get_string('batchuploadfiles', 'assignfeedback_file'));
            $o = '';
            $o .= $this->assignment->get_renderer()->render($header);
            $o .= $this->assignment->get_renderer()->render(new assign_form('batchuploadfiles', $mform));
            $o .= $this->assignment->get_renderer()->render_footer();
        }

        return $o;
    }
531734
public function withUploadedFiles(array $uploadedFiles)
    {
        $this->assertUploadedFilesStructure($uploadedFiles);
        
        $request = $this->copy();
        $request->uploadedFiles = $uploadedFiles;
        
        if (isset($this->files)) {
            $this->ungroupUploadedFiles($uploadedFiles);
        }
        
        return $request;
    }
1158164
public function upload()
        {
            $files = $this->getFiles();
            $response = [];
            $types = new ImageUploadTypes();
            foreach($files as $file){

                if(!$file instanceof ImageUpload)
                {
                    $file = new ImageUpload($file);
                    $file->setAllowedMimeTypes($types->getImageMimeTypes());
                    $file->setAllowedExt($types->getImageTypeExt(), ['.php']);
                }

                $response[] = $file->upload();
            }

            return $response;
        }
690585
protected function convertUploadedFiles(array $files)
    {
        $fileObjects = [];
        
        foreach ($files as $fieldName => $file) {
            if ($file instanceof UploadedFileInterface) {
                $fileObjects[$fieldName] = $file;
            } elseif (!isset($file['tmp_name']) && !isset($file['error'])) {
                $fileObjects[$fieldName] = $this->convertUploadedFiles($file);
            } else {
                $fileObjects[$fieldName] = new UploadedFile($file);
            }
        }
        
        return $fileObjects;
    }
1096870
public function uploadLargeFile(array $options)
    {
        if (substr($options['FileName'], 0, 1) === '/') {
            $options['FileName'] = ltrim($options['FileName'], '/');
        }

        //if last char of path is not a "/" then add a "/"
        if (substr($options['FilePath'], -1) != '/') {
            $options['FilePath'] = $options['FilePath'].'/';
        }

        if (!isset($options['BucketId']) && isset($options['BucketName'])) {
            $options['BucketId'] = $this->getBucketIdFromName($options['BucketName']);
        }

        if (!isset($options['FileContentType'])) {
            $options['FileContentType'] = 'b2/x-auto';
        }

        $this->authorizeAccount();

        // 1) b2_start_large_file, (returns fileId)
        $start = $this->startLargeFile($options['FileName'], $options['FileContentType'], $options['BucketId']);

        // 2) b2_get_upload_part_url for each thread uploading (takes fileId)
        $url = $this->getUploadPartUrl($start['fileId']);

        // 3) b2_upload_part for each part of the file
        $parts = $this->uploadParts($options['FilePath'].$options['FileName'], $url['uploadUrl'], $url['authorizationToken']);

        $sha1s = [];

        foreach ($parts as $part) {
            $sha1s[] = $part['contentSha1'];
        }

        // 4) b2_finish_large_file.
        return $this->finishLargeFile($start['fileId'], $sha1s);
    }
216386
public static function getGroupIdName($users)
	{
		$users = explode(",", $users);
		$usersArray = array();
		foreach ($users as $user)
		{
			$user = User::find($user);
			if ($user)
				$usersArray[] = array('name' => $user->name, 'user_id' => $user->user_id);
		}
		return $usersArray;
	}
625534
protected function prepareUploadedFiles($files)
    {
        $fileKeys = ['error', 'name', 'size', 'tmp_name', 'type'];
        $reformatFiles = new ReformatUploadedFiles($files);

        $output = [];
        foreach ($reformatFiles as $key => $value) {
            $keys = array_keys($value);
            sort($keys);

            if ($fileKeys == $keys && is_array($value['tmp_name'])) {
                $output[$key] = $this->prepareUploadedFiles($reformatFiles[$key]);
                continue;
            }

            $output[$key] = new UploadedFile(
                $value['tmp_name'],
                $value['error'],
                $value['name'],
                $value['type'],
                $value['size']
            );
        }

        return $output;
    }
907679
public function upload($id, $files)
    {
        if (!is_array($files)) {
            $files = array($files);
        }

        return $this->getUploader()->upload($id, $files);
    }
311378
public function post($uri, array $headers = [], $datas = [], array $files = [])
    {
        return $this->send($uri, InternalRequestInterface::METHOD_POST, $headers, $datas, $files);
    }
863426
public function set_users(array $users) {
        $this->users = $users;
        $hasbulkops = !empty($this->bulkoperations);
        foreach ($users as $userid=>$user) {
            $user = (array)$user;
            $row = new html_table_row();
            $row->attributes = array('class' => 'userinforow');
            $row->id = 'user_'.$userid;
            $row->cells = array();
            if ($hasbulkops) {
                // Add a checkbox into the first column.
                $input = html_writer::empty_tag('input', array('type' => 'checkbox', 'name' => 'bulkuser[]', 'value' => $userid));
                $row->cells[] = new html_table_cell($input);
            }
            foreach ($this->fields as $field => $label) {
                if (is_array($label)) {
                    $bits = array();
                    foreach (array_keys($label) as $subfield) {
                        if (array_key_exists($subfield, $user)) {
                            $bits[] = html_writer::tag('div', $user[$subfield], array('class'=>'subfield subfield_'.$subfield));
                        }
                    }
                    if (empty($bits)) {
                        $bits[] = '&nbsp;';
                    }
                    $row->cells[] = new html_table_cell(join(' ', $bits));
                } else {
                    if (!array_key_exists($field, $user)) {
                        $user[$field] = '&nbsp;';
                    }
                    $row->cells[] = new html_table_cell($user[$field]);
                }
            }
            $this->data[] = $row;
        }
    }
1193336
public function doUpload() {
        $result = false;
        
        if(is_array($this->fileArray['tmp_name'])) {
        	error_log('file array is in multi upload format, use doMultiUpload()');
        	return false;
        }
        
        $errno = $this->fileArray['error']; 
		if($errno == UPLOAD_ERR_OK) {

			if(!File::createFolder($this->uploadDir,true)) {
	        	error_log('Failed to create directory ' . $this->uploadDir);
	        	return false;
	        }
			
			if(is_uploaded_file($this->fileArray['tmp_name'])) {
				$result = move_uploaded_file($this->fileArray['tmp_name'], $this->uploadDir.$this->fileArray['name']);
			} else {
				$result = copy($this->fileArray['tmp_name'], $this->uploadDir.$this->fileArray['name']);
			}
			
			if($result) {
				$this->uploaded[] = $this->fileArray;
			
				//can't rely on browser to determine mime type, so do our own check.
				$this->setMimeType($this->uploadDir.$this->fileArray['name']);
			}
		} else {
			error_log($this->getErrMsg($errno));    
			$result = false;
		}
        
        return $result;
    }
999080
public function put($uri, array $headers = [], $datas = [], array $files = [])
    {
        return $this->send($uri, InternalRequestInterface::METHOD_PUT, $headers, $datas, $files);
    }
1047349
public function upload(Request $request)
    {
        $json = [];
        foreach ($request->file('file') as $file) {
            $this->storage->putFile($request->get('directory'), $file);
        }

        $json['success'] = trans('admin::image.success.upload');

        return response()
            ->json($json);
    }
910706
public function upload()
        {
            $files = $this->getFiles();
            $response = [];

            foreach($files as $file){

                if(!$file instanceof Upload)
                {
                    $file = new FileUpload($file);
                }

                $response[] = $file->upload();
            }

            return $response;
        }
953179
public function set(array $files)
    {
        if (!empty($files)) {
            foreach ($files as $_file) {
                if (is_array($_file) && isset($_file['file'])) {
                    $this->add(
                        $_file['file'],
                        isset($_file['media']) ? $_file['media'] : '',
                        isset($_file['condition']) ? $_file['condition'] : null
                    );
                } elseif (is_string($_file)) {
                    $this->add($_file);
                }
            }
        }
        return $this;
    }
327655
public static function update_users($users) {
        global $CFG, $DB, $USER;
        require_once($CFG->dirroot."/user/lib.php");
        require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
        require_once($CFG->dirroot.'/user/editlib.php');

        // Ensure the current user is allowed to run this function.
        $context = context_system::instance();
        require_capability('moodle/user:update', $context);
        self::validate_context($context);

        $params = self::validate_parameters(self::update_users_parameters(), array('users' => $users));

        $filemanageroptions = array('maxbytes' => $CFG->maxbytes,
                'subdirs'        => 0,
                'maxfiles'       => 1,
                'accepted_types' => 'web_image');

        $transaction = $DB->start_delegated_transaction();

        foreach ($params['users'] as $user) {
            // First check the user exists.
            if (!$existinguser = core_user::get_user($user['id'])) {
                continue;
            }
            // Check if we are trying to update an admin.
            if ($existinguser->id != $USER->id and is_siteadmin($existinguser) and !is_siteadmin($USER)) {
                continue;
            }
            // Other checks (deleted, remote or guest users).
            if ($existinguser->deleted or is_mnet_remote_user($existinguser) or isguestuser($existinguser->id)) {
                continue;
            }
            // Check duplicated emails.
            if (isset($user['email']) && $user['email'] !== $existinguser->email) {
                if (!validate_email($user['email'])) {
                    continue;
                } else if (empty($CFG->allowaccountssameemail)) {
                    // Make a case-insensitive query for the given email address and make sure to exclude the user being updated.
                    $select = $DB->sql_equal('email', ':email', false) . ' AND mnethostid = :mnethostid AND id <> :userid';
                    $params = array(
                        'email' => $user['email'],
                        'mnethostid' => $CFG->mnet_localhost_id,
                        'userid' => $user['id']
                    );
                    // Skip if there are other user(s) that already have the same email.
                    if ($DB->record_exists_select('user', $select, $params)) {
                        continue;
                    }
                }
            }

            user_update_user($user, true, false);

            $userobject = (object)$user;

            // Update user picture if it was specified for this user.
            if (empty($CFG->disableuserimages) && isset($user['userpicture'])) {
                $userobject->deletepicture = null;

                if ($user['userpicture'] == 0) {
                    $userobject->deletepicture = true;
                } else {
                    $userobject->imagefile = $user['userpicture'];
                }

                core_user::update_picture($userobject, $filemanageroptions);
            }

            // Update user interests.
            if (!empty($user['interests'])) {
                $trimmedinterests = array_map('trim', explode(',', $user['interests']));
                $interests = array_filter($trimmedinterests, function($value) {
                    return !empty($value);
                });
                useredit_update_interests($userobject, $interests);
            }

            // Update user custom fields.
            if (!empty($user['customfields'])) {

                foreach ($user['customfields'] as $customfield) {
                    // Profile_save_data() saves profile file it's expecting a user with the correct id,
                    // and custom field to be named profile_field_"shortname".
                    $user["profile_field_".$customfield['type']] = $customfield['value'];
                }
                profile_save_data((object) $user);
            }

            // Trigger event.
            \core\event\user_updated::create_from_userid($user['id'])->trigger();

            // Preferences.
            if (!empty($user['preferences'])) {
                $userpref = clone($existinguser);
                foreach ($user['preferences'] as $preference) {
                    $userpref->{'preference_'.$preference['type']} = $preference['value'];
                }
                useredit_update_user_preference($userpref);
            }
            if (isset($user['suspended']) and $user['suspended']) {
                \core\session\manager::kill_user_sessions($user['id']);
            }
        }

        $transaction->allow_commit();

        return null;
    }
1332478
public function upload($files)
    {
        $exception = null;

        //for each client
        foreach ($this->children as $child) {
            $this->logger->info(sprintf('[dizda-backup] Uploading to %s', $child->getName()));

            try {
                //try to upload every file, one at a time
                foreach ($files as $file) {
                    $child->upload($file);
                }
            } catch (\Exception $e) {
                //save the exception for later, there might be other children that are working
                $exception = $e;
            }
        }

        if ($exception) {
            throw $exception;
        }
    }