Get All files in a File area
@param int|\assign $assignment Assignment
@param int $userid User ID
@param int $attemptnumber Attempt Number
@param string $filearea File Area
@param string $filepath File Path
@return array
430509
private static function get_files($assignment, $userid, $attemptnumber, $filearea, $filepath = '/') {
        $grade = $assignment->get_user_grade($userid, true, $attemptnumber);
        $itemid = $grade->id;
        $contextid = $assignment->get_context()->id;
        $component = self::COMPONENT;
        $fs = get_file_storage();
        $files = $fs->get_directory_files($contextid, $component, $filearea, $itemid, $filepath);
        return $files;
    }
1256569
public function get_file_info($component, $filearea, $itemid, $filepath, $filename) {
        global $DB;

        if (!core_course_category::can_view_category($this->category)) {
            if (empty($component)) {
                // we can not list the category contents, so try parent, or top system
                if ($this->category->parent and $pc = $DB->get_record('course_categories', array('id'=>$this->category->parent))) {
                    $parent = context_coursecat::instance($pc->id, IGNORE_MISSING);
                    return $this->browser->get_file_info($parent);
                } else {
                    return $this->browser->get_file_info();
                }
            }
            return null;
        }

        if (empty($component)) {
            return $this;
        }

        $methodname = "get_area_{$component}_{$filearea}";
        if (method_exists($this, $methodname)) {
            return $this->$methodname($itemid, $filepath, $filename);
        }

        return null;
    }
615954
public byte[] getFileBytes(String filePath)
		throws IOException {
	    
		byte[] out = null;
		String path = (String) Utils.intern(filePath);
		RandomAccessFile raf = null;
		synchronized (path) {
			File file = null;
			try {
				file = new File(path);
				boolean exists = file.exists();
				if (exists) {
					byte[] fileBytes = new byte[(int)file.length()];
					raf = new RandomAccessFile(file,"r");
					raf.readFully(fileBytes);
					out = fileBytes;
				} else {
				    String msg = 
				        "File does not exist. (" + filePath + ")";
					mLog.error(msg);
					throw new IOException(msg);
				}
			} catch (IOException e) {
				mLog.error("Error writing: " + filePath);
				mLog.error(e);
				throw e;
			} finally {
				if (raf != null) {
					raf.close();
				}
			}
		}
		return out;
    }
529497
public static function getImageResolution($filePath, $throwException = false)
    {
        $dimensions = @getimagesize(Yii::getAlias($filePath));
        
        $width = 0;
        $height = 0;
        
        if (isset($dimensions[0]) && isset($dimensions[1])) {
            $width = (int)$dimensions[0];
            $height = (int)$dimensions[1];
        } elseif ($throwException) {
            throw new Exception("Unable to determine the resoltuions of the file $filePath.");
        }
        
        return [
            'width' => $width,
            'height' => $height,
        ];
    }
792884
public function get_file_info($component, $filearea, $itemid, $filepath, $filename) {
        // try to emulate require_login() tests here
        if (!isloggedin()) {
            return null;
        }

        $coursecontext = $this->context->get_course_context(true);
        if (!$this->course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
            return null;
        }

        if (!is_viewing($this->context) and !$this->browser->is_enrolled($this->course->id)) {
            // no peaking here if not enrolled or inspector
            return null;
        }

        if (!$this->cm->uservisible) {
            // activity hidden sorry
            return null;
        }

        if (empty($component)) {
            return $this;
        }

        if ($component == 'mod_'.$this->modname and $filearea === 'intro') {
            return $this->get_area_intro($itemid, $filepath, $filename);
        } else if ($component == 'backup' and $filearea === 'activity') {
            return $this->get_area_backup($itemid, $filepath, $filename);
        }

        if ($functionname = component_callback_exists('mod_'.$this->modname, 'get_file_info')) {
            $cm = $this->cm->get_course_module_record();
            return $functionname($this->browser, $this->areas, $this->course, $cm,
                $this->context, $filearea, $itemid, $filepath, $filename);
        }

        return null;
    }
1019865
public static function upload_data($userid,$file_data,$session,$offset){
		$expired = time() + self::EXPIRED_SECONDS;
		$url = self::generateResUrl($userid);
		$sign = Auth::appSign($url, $expired);

		$data = array(
            'FileContent' => $file_data,
			'op' => 'upload_slice',
			'session' => $session,
			'offset' => $offset,
        );

        $req = array(
            'url' => $url,
            'method' => 'post',
            'timeout' => 10,
            'data' => $data,
            'header' => array(
                'Authorization:'.$sign,
            ),
        );

		$rsp = Http::send($req);
		$info = Http::info();
		$ret = json_decode($rsp, true);
		if ($ret) {
			if (0 === $ret['code']) {
				$ret['httpcode'] = $info['http_code'];
				return $ret;
			} else {
				return array(
					'httpcode' => $info['http_code'],
					'code' => $ret['code'],
					'message' => $ret['message'],
					'data' => array()
				);
			}
		} else {
			return array(
					'httpcode' => $info['http_code'],
					'code' => self::VIDEO_NETWORK_ERROR,
					'message' => 'network error', 'data' => array()
				);
		}
	}
1002197
public static function get_user_mappings($assignmentids) {
        global $DB;
        $params = self::validate_parameters(self::get_user_mappings_parameters(),
                        array('assignmentids' => $assignmentids));

        $assignments = array();
        $warnings = array();
        $requestedassignmentids = $params['assignmentids'];

        // Check the user is allowed to get the mappings for the assignments requested.
        $placeholders = array();
        list($sqlassignmentids, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);
        $sql = "SELECT cm.id, cm.instance FROM {course_modules} cm JOIN {modules} md ON md.id = cm.module ".
               "WHERE md.name = :modname AND cm.instance ".$sqlassignmentids;
        $placeholders['modname'] = 'assign';
        $cms = $DB->get_records_sql($sql, $placeholders);
        foreach ($cms as $cm) {
            try {
                $context = context_module::instance($cm->id);
                self::validate_context($context);
                require_capability('mod/assign:revealidentities', $context);
            } catch (Exception $e) {
                $requestedassignmentids = array_diff($requestedassignmentids, array($cm->instance));
                $warning = array();
                $warning['item'] = 'assignment';
                $warning['itemid'] = $cm->instance;
                $warning['warningcode'] = '1';
                $warning['message'] = 'No access rights in module context';
                $warnings[] = $warning;
            }
        }

        // Create the query and populate an array of assign_user_mapping records from the recordset results.
        if (count ($requestedassignmentids) > 0) {
            $placeholders = array();
            list($inorequalsql, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);

            $sql = "SELECT aum.id,aum.assignment,aum.userid ".
                   "FROM {assign_user_mapping} aum ".
                   "WHERE aum.assignment ".$inorequalsql.
                   " ORDER BY aum.assignment, aum.id";

            $rs = $DB->get_recordset_sql($sql, $placeholders);
            $currentassignmentid = null;
            $assignment = null;
            foreach ($rs as $rd) {
                $mapping = array();
                $mapping['id'] = $rd->id;
                $mapping['userid'] = $rd->userid;

                if (is_null($currentassignmentid) || ($rd->assignment != $currentassignmentid )) {
                    if (!is_null($assignment)) {
                        $assignments[] = $assignment;
                    }
                    $assignment = array();
                    $assignment['assignmentid'] = $rd->assignment;
                    $assignment['mappings'] = array();
                    $requestedassignmentids = array_diff($requestedassignmentids, array($rd->assignment));
                }
                $assignment['mappings'][] = $mapping;

                $currentassignmentid = $rd->assignment;
            }
            if (!is_null($assignment)) {
                $assignments[] = $assignment;
            }
            $rs->close();

        }

        foreach ($requestedassignmentids as $assignmentid) {
            $warning = array();
            $warning['item'] = 'assignment';
            $warning['itemid'] = $assignmentid;
            $warning['warningcode'] = '3';
            $warning['message'] = 'No mappings found';
            $warnings[] = $warning;
        }

        $result = array();
        $result['assignments'] = $assignments;
        $result['warnings'] = $warnings;
        return $result;
    }
186758
protected function get_area_backup_section($itemid, $filepath, $filename) {
        global $CFG, $DB;

        if (!has_capability('moodle/backup:backupcourse', $this->context) and !has_capability('moodle/restore:restorecourse', $this->context)) {
            return null;
        }

        if (empty($itemid)) {
            // list all sections
            return new file_info_area_backup_section($this->browser, $this->context, $this->course, $this);
        }

        if (!$section = $DB->get_record('course_sections', array('course'=>$this->course->id, 'id'=>$itemid))) {
            return null; // does not exist
        }

        $fs = get_file_storage();

        $filepath = is_null($filepath) ? '/' : $filepath;
        $filename = is_null($filename) ? '.' : $filename;
        if (!$storedfile = $fs->get_file($this->context->id, 'backup', 'section', $itemid, $filepath, $filename)) {
            if ($filepath === '/' and $filename === '.') {
                $storedfile = new virtual_root_file($this->context->id, 'backup', 'section', $itemid);
            } else {
                // not found
                return null;
            }
        }

        $downloadable = has_capability('moodle/backup:downloadfile', $this->context);
        $uploadable   = has_capability('moodle/restore:uploadfile', $this->context);

        $urlbase = $CFG->wwwroot.'/pluginfile.php';
        return new file_info_stored($this->browser, $this->context, $storedfile, $urlbase, $section->id, true, $downloadable, $uploadable, false);
    }
675024
public static function open_file($path, $lock = true, $area = null)
	{
		if (is_string($path))
		{
			$path = static::instance($area)->get_path($path);
			$resource = fopen($path, 'r+');
		}
		else
		{
			$resource = $path;
		}

		// Make sure the parameter is a valid resource
		if ( ! is_resource($resource))
		{
			return false;
		}

		// If locks aren't used, don't lock
		if ( ! static::instance($area)->use_locks())
		{
			return $resource;
		}

		// Accept valid lock constant or set to LOCK_EX
		$lock = in_array($lock, array(LOCK_SH, LOCK_EX, LOCK_NB)) ? $lock : LOCK_EX;

		// Try to get a lock, timeout after 5 seconds
		$lock_mtime = microtime(true);
		while ( ! flock($resource, $lock))
		{
			if (microtime(true) - $lock_mtime > 5)
			{
				throw new \FileAccessException('Could not secure file lock, timed out after 5 seconds.');
			}
		}

		return $resource;
	}
314331
function filePersister(filepath) {

	var self = this;
	this.initialized = false;
	this.filepath = filepath;

	/**
	 * Check to see if the specified file path is available.
	 * @returns A promise appropriately resolving or rejecting.
	 */
	this.start = function() {
		if (!this.initialized) {
			return fsp.emptyDir(this.filepath)
			.then(function() {
				self.initialized = true;
				return Promise.resolve('User has permissions to write to that file.');
			})
			.catch(function(err) {
				return Promise.reject('User does not have permissions to write to that folder.');
			});
		}
		return Promise.reject('Error: Persister already initialized.');
	};

	/**
	 * Save the passed state to the file.
	 * @param {Object} passedState - State to be saved in the file.
	 * @returns A promise resolving to an appropriate success message or an error message.
	 */
	this.save = function(brain, package) {
		var filepath = this.filepath;
		if (this.initialized) {
			return fsp.remove(filepath + '/' + package + '.txt')
			.then(function(){
				return fsp.writeFile(filepath + '/' + package + '.txt', JSON.stringify(brain));				
			})
			.then(function(){
				return Promise.resolve('Saved.');
			})
		} 
		return Promise.reject('Error: Persister not initialized.');
	};

	/**
	 * Retrieve data from the file.
	 * @returns The most recent entry to the file, as a JavaScript object.
	 */
	this.recover = function(package) {
		if (this.initialized) {
			var filepath = this.filepath
			return fsp.ensureFile(filepath +'/' + package + '.txt')
			.then(function(){
				return fsp.readFile(filepath + '/' + package + '.txt', 'utf8')
			})
			.then(function(data) {
				if (data === ''){
					return Promise.resolve({});
				} else {
					return Promise.resolve(JSON.parse(data));
				}
			});
		}
		return Promise.reject('Error: Persister not initialized.');
	};

}
344511
public function render_area_files($component, $area, $submissionid) {
        global $USER;

        return $this->get_renderer()->assign_files($this->context, $submissionid, $area, $component);

    }
992900
public List<UploadFile> getFiles(String uploadPath, Integer maxPostSize, String encoding) {
		if (request instanceof MultipartRequest == false)
			request = new MultipartRequest(request, uploadPath, maxPostSize, encoding);
		return ((MultipartRequest)request).getFiles();
	}
373836
public function attachFile(string $filePath, string $name = null)
    {
        $this->attachedFiles[] = [
          'path' => $filePath,
          'name' => $name
        ];

        return $this;
    }
58463
protected static function get_graded_users(int $userid, \assign $assign) {
        $params = ['grader' => $userid, 'assignid' => $assign->get_instance()->id];

        $sql = "SELECT DISTINCT userid AS id
                  FROM {assign_grades}
                 WHERE grader = :grader AND assignment = :assignid";

        $useridlist = new useridlist($userid, $assign->get_instance()->id);
        $useridlist->add_from_sql($sql, $params);

        // Call sub-plugins to see if they have information not already collected.
        manager::plugintype_class_callback('assignsubmission', self::ASSIGNSUBMISSION_INTERFACE, 'get_student_user_ids',
                [$useridlist]);
        manager::plugintype_class_callback('assignfeedback', self::ASSIGNFEEDBACK_INTERFACE, 'get_student_user_ids', [$useridlist]);

        $userids = $useridlist->get_userids();
        return ($userids) ? $userids : false;
    }
1040813
public function get_files() {
        global $USER;

        $fs = get_file_storage();
        $usercontext = context_user::instance($USER->id);

        return $fs->get_area_files($usercontext->id, 'user', 'draft',
                $this->draftitemid, 'sortorder, filepath, filename', false);
    }
478376
public function get_files(stdClass $submission, stdClass $user) {
        $result = array();
        $fs = get_file_storage();

        $files = $fs->get_area_files($this->assignment->get_context()->id,
                                     'assignsubmission_file',
                                     ASSIGNSUBMISSION_FILE_FILEAREA,
                                     $submission->id,
                                     'timemodified',
                                     false);

        foreach ($files as $file) {
            // Do we return the full folder path or just the file name?
            if (isset($submission->exportfullpath) && $submission->exportfullpath == false) {
                $result[$file->get_filename()] = $file;
            } else {
                $result[$file->get_filepath().$file->get_filename()] = $file;
            }
        }
        return $result;
    }
1072666
public function checkCreateFile($filePath)
    {
        $defaultPermissions = $this->getPermissionUtils()->getDefaultPermissions();

        if (file_exists($filePath)) {
            if (!is_writable($filePath) && !in_array($this->getPermissionUtils()->getCurrentPermission($filePath), array($defaultPermissions['file'], $defaultPermissions['dir']))) {
                return $this->getPermissionUtils()->setDefaultPermissions($filePath, true);
            }
            return true;
        }

        $pathParts = pathinfo($filePath);
        if (!file_exists($pathParts['dirname'])) {
            $dirPermission = $defaultPermissions['dir'];
            $dirPermission = is_string($dirPermission) ? base_convert($dirPermission,8,10) : $dirPermission;

            if (!$this->mkdir($pathParts['dirname'], $dirPermission, true)) {
                throw new Error('Permission denied: unable to create a folder on the server - ' . $pathParts['dirname']);
            }
        }

        if (touch($filePath)) {
            return $this->getPermissionUtils()->setDefaultPermissions($filePath, true);
        }

        return false;
    }