Get file listing

@param string $encodedpath
@return mixed
547320
public function get_listing($encodedpath = '', $page = '') {
        global $CFG, $USER, $OUTPUT;
        $ret = array();
        $ret['dynload'] = true;
        $ret['nosearch'] = true;
        $ret['nologin'] = true;
        $manageurl = new moodle_url('/user/files.php');
        $ret['manage'] = $manageurl->out();
        $list = array();

        if (!empty($encodedpath)) {
            $params = json_decode(base64_decode($encodedpath), true);
            if (is_array($params)) {
                $filepath = clean_param($params['filepath'], PARAM_PATH);
                $filename = clean_param($params['filename'], PARAM_FILE);
            }
        } else {
            $itemid   = 0;
            $filepath = '/';
            $filename = null;
        }
        $filearea = 'private';
        $component = 'user';
        $itemid  = 0;
        $context = context_user::instance($USER->id);

        try {
            $browser = get_file_browser();

            if ($fileinfo = $browser->get_file_info($context, $component, $filearea, $itemid, $filepath, $filename)) {
                $pathnodes = array();
                $level = $fileinfo;
                $params = $fileinfo->get_params();
                while ($level && $params['component'] == 'user' && $params['filearea'] == 'private') {
                    $encodedpath = base64_encode(json_encode($level->get_params()));
                    $pathnodes[] = array('name'=>$level->get_visible_name(), 'path'=>$encodedpath);
                    $level = $level->get_parent();
                    $params = $level->get_params();
                }
                $ret['path'] = array_reverse($pathnodes);

                // build file tree
                $children = $fileinfo->get_children();
                foreach ($children as $child) {
                    if ($child->is_directory()) {
                        $encodedpath = base64_encode(json_encode($child->get_params()));
                        $node = array(
                            'title' => $child->get_visible_name(),
                            'datemodified' => $child->get_timemodified(),
                            'datecreated' => $child->get_timecreated(),
                            'path' => $encodedpath,
                            'children'=>array(),
                            'thumbnail' => $OUTPUT->image_url(file_folder_icon(90))->out(false)
                        );
                        $list[] = $node;
                    } else {
                        $encodedpath = base64_encode(json_encode($child->get_params()));
                        $node = array(
                            'title' => $child->get_visible_name(),
                            'size' => $child->get_filesize(),
                            'datemodified' => $child->get_timemodified(),
                            'datecreated' => $child->get_timecreated(),
                            'author' => $child->get_author(),
                            'license' => $child->get_license(),
                            'isref' => $child->is_external_file(),
                            'source'=> $encodedpath,
                            'icon' => $OUTPUT->image_url(file_file_icon($child, 24))->out(false),
                            'thumbnail' => $OUTPUT->image_url(file_file_icon($child, 90))->out(false)
                        );
                        if ($child->get_status() == 666) {
                            $node['originalmissing'] = true;
                        }
                        if ($imageinfo = $child->get_imageinfo()) {
                            $fileurl = new moodle_url($child->get_url());
                            $node['realthumbnail'] = $fileurl->out(false, array('preview' => 'thumb', 'oid' => $child->get_timemodified()));
                            $node['realicon'] = $fileurl->out(false, array('preview' => 'tinyicon', 'oid' => $child->get_timemodified()));
                            $node['image_width'] = $imageinfo['width'];
                            $node['image_height'] = $imageinfo['height'];
                        }
                        $list[] = $node;
                    }
                }
            }
        } catch (Exception $e) {
            throw new repository_exception('emptyfilelist', 'repository_user');
        }
        $ret['list'] = $list;
        $ret['list'] = array_filter($list, array($this, 'filter'));
        return $ret;
    }
697582
protected function getFileFunctions($filePath)
    {
        $source = file_get_contents($filePath);
        $tokens = token_get_all($source);

        $functions = [];
        $nextStringIsFunc = false;
        foreach($tokens as $token) {
            switch($token[0]) {
                case T_FUNCTION:
                    $nextStringIsFunc = true;
                    break;

                case T_STRING:
                    if ($nextStringIsFunc) {
                        $nextStringIsFunc = false;
                        $functions[] = $token[1];
                    }
                    break;
            }
        }

        return $functions;
    }
944265
public function get_file_list($path = '') {
        global $OUTPUT;

        $precedingpath = '';
        if (empty($path)) {
            $url = self::API."/me/skydrive/files/";
        } else {
            $parts = explode('/', $path);
            $currentfolder = array_pop($parts);
            $url = self::API."/{$currentfolder}/files/";
        }

        $ret = json_decode($this->get($url));

        if (isset($ret->error)) {
            $this->log_out();
            return false;
        }

        $files = array();

        foreach ($ret->data as $file) {
            switch($file->type) {
                case 'folder':
                case 'album':
                    // Cache the foldername for future requests.
                    $cachekey = $this->folder_cache_key($file->id);
                    $this->foldernamecache->set($cachekey, $file->name);

                    $files[] = array(
                        'title' => $file->name,
                        'path' => $path.'/'.$file->id,
                        'size' => 0,
                        'date' => strtotime($file->updated_time),
                        'thumbnail' => $OUTPUT->image_url(file_folder_icon(90))->out(false),
                        'children' => array(),
                    );
                    break;
                case 'photo':
                    $files[] = array(
                        'title' => $file->name,
                        'size' => $file->size,
                        'date' => strtotime($file->updated_time),
                        'thumbnail' => $OUTPUT->image_url(file_extension_icon($file->name, 90))->out(false),
                        'realthumbnail' => $file->picture,
                        'source' => $file->id,
                        'url' => $file->link,
                        'image_height' => $file->height,
                        'image_width' => $file->width,
                        'author' => $file->from->name,
                    );
                    break;
                case 'video':
                    $files[] = array(
                        'title' => $file->name,
                        'size' => $file->size,
                        'date' => strtotime($file->updated_time),
                        'thumbnail' => $OUTPUT->image_url(file_extension_icon($file->name, 90))->out(false),
                        'realthumbnail' => $file->picture,
                        'source' => $file->id,
                        'url' => $file->link,
                        'author' => $file->from->name,
                    );
                    break;
                case 'audio':
                    $files[] = array(
                        'title' => $file->name,
                        'size' => $file->size,
                        'date' => strtotime($file->updated_time),
                        'thumbnail' => $OUTPUT->image_url(file_extension_icon($file->name, 90))->out(false),
                        'source' => $file->id,
                        'url' => $file->link,
                        'author' => $file->from->name,
                    );
                    break;
                case 'file':
                    $files[] = array(
                        'title' => $file->name,
                        'size' => $file->size,
                        'date' => strtotime($file->updated_time),
                        'thumbnail' => $OUTPUT->image_url(file_extension_icon($file->name, 90))->out(false),
                        'source' => $file->id,
                        'url' => $file->link,
                        'author' => $file->from->name,
                    );
                    break;
            }
        }
        return $files;
    }
1238473
public function listDirectory($path, $recursive = false, $withHidden = true)
    {
        if ($recursive) {
            return $this->listDirectoryRecursive($path);
        }

        $all = $withHidden ? glob($path.'/{,.}[!.,!..]*', GLOB_MARK | GLOB_BRACE) : glob("$path/*");

        $all = array_map(function ($path) {
            return rtrim($path, '/\\');
        }, $all);

        sort($all);

        return $all;
    }
178267
public static function decode($encodedPath) {
        
        $len = strlen( $encodedPath ) -1;
        // For speed we preallocate to an upper bound on the final length, then
        // truncate the array before returning.
        $path = [];
        $index = 0;
        $lat = 0;
        $lng = 0;

        while( $index < $len) {
            $result = 1;
            $shift = 0;
            $b;
            do {
                $b = ord($encodedPath{$index++}) - 63 - 1;
                $result += $b << $shift;
                $shift += 5;
            } while ($b >= hexdec("0x1f"));
            
            $lat += ($result & 1) != 0 ? ~($result >> 1) : ($result >> 1);

            $result = 1;
            $shift = 0;
            do {
                $b = ord($encodedPath{$index++}) - 63 - 1;
                $result += $b << $shift;
                $shift += 5;
            } while ($b >= hexdec("0x1f"));
            $lng += ($result & 1) != 0 ? ~($result >> 1) : ($result >> 1);
            
            array_push($path, ['lat' => $lat * 1e-5, 'lng' => $lng * 1e-5]);
        }

        return $path;
    }
756515
public function findFile($filePath)
    {
        if (file_exists($filePath)) {
            return $filePath;
        }
        foreach ($this->supportedExtensions as $extension)
        {
            $extendedFilePath = $filePath.'.'.$extension;
            if (file_exists($extendedFilePath)) {
                return $extendedFilePath;
            }
            $extendedFilePath = $filePath.'.'.strtoupper($extension);
            if (file_exists($extendedFilePath)) {
                return $extendedFilePath;
            }
            $extendedFilePath = $filePath.'.'.ucfirst($extension);
            if (file_exists($extendedFilePath)) {
                return $extendedFilePath;
            }
        }
        return null;
    }
913185
protected function getModuleId($filePath)
    {
        preg_match(
            '/.*(protected|public|private)\s\$id\s=\s(\'|\")(?P<id>.*)(\'|\")\;.*/',
            file_get_contents($filePath),
            $matches
        );

        if (array_key_exists('id', $matches) && isset($matches['id']{0})) {
            return $matches['id'];
        } else {
            return false;
        }
    }
236066
public function get_listing($path = '', $page = '') {
        global $USER, $OUTPUT;
        $itemid = optional_param('itemid', 0, PARAM_INT);
        $env = optional_param('env', 'filepicker', PARAM_ALPHA);
        $ret = array(
            'dynload' => true,
            'nosearch' => true,
            'nologin' => true,
            'list' => array(),
        );
        if (empty($itemid) || $env !== 'editor') {
            return $ret;
        }

        // In the most cases files embedded in textarea do not have subfolders. Do not show path by default.
        $retpath = array(array('name' => get_string('files'), 'path' => ''));
        if (!empty($path)) {
            $pathchunks = preg_split('|/|', trim($path, '/'));
            foreach ($pathchunks as $i => $chunk) {
                $retpath[] = array(
                    'name' => $chunk,
                    'path' => '/'. join('/', array_slice($pathchunks, 0, $i + 1)). '/'
                );
            }
            $ret['path'] = $retpath; // Show path if already inside subfolder.
        }

        $context = context_user::instance($USER->id);
        $fs = get_file_storage();
        $files = $fs->get_directory_files($context->id, 'user', 'draft', $itemid,
                empty($path) ? '/' : $path, false, true);
        foreach ($files as $file) {
            if ($file->is_directory()) {
                $node = array(
                    'title' => basename($file->get_filepath()),
                    'path' => $file->get_filepath(),
                    'children' => array(),
                    'datemodified' => $file->get_timemodified(),
                    'datecreated' => $file->get_timecreated(),
                    'icon' => $OUTPUT->image_url(file_folder_icon(24))->out(false),
                    'thumbnail' => $OUTPUT->image_url(file_folder_icon(90))->out(false)
                );
                $ret['list'][] = $node;
                $ret['path'] = $retpath; // Show path if subfolders exist.
                continue;
            }
            $fileurl = moodle_url::make_draftfile_url($itemid, $file->get_filepath(), $file->get_filename());
            $node = array(
                'title' => $file->get_filename(),
                'size' => $file->get_filesize(),
                'source' => $fileurl->out(),
                'datemodified' => $file->get_timemodified(),
                'datecreated' => $file->get_timecreated(),
                'author' => $file->get_author(),
                'license' => $file->get_license(),
                'isref' => $file->is_external_file(),
                'iscontrolledlink' => $file->is_controlled_link(),
                'icon' => $OUTPUT->image_url(file_file_icon($file, 24))->out(false),
                'thumbnail' => $OUTPUT->image_url(file_file_icon($file, 90))->out(false)
            );
            if ($file->get_status() == 666) {
                $node['originalmissing'] = true;
            }
            if ($imageinfo = $file->get_imageinfo()) {
                $node['realthumbnail'] = $fileurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
                $node['realicon'] = $fileurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
                $node['image_width'] = $imageinfo['width'];
                $node['image_height'] = $imageinfo['height'];
            }
            $ret['list'][] = $node;
        }
        $ret['list'] = array_filter($ret['list'], array($this, 'filter'));
        return $ret;
    }
1049940
public function getFiles($sDirectory, $sExt = '')
	{
	    $aFiles = array();
	    
	    if(!is_dir($sDirectory)){
			return null;
		}
	    
	    foreach(new \DirectoryIterator($sDirectory) as $oFileInfo){
	        if($oFileInfo->isFile()){
	            if(empty($sExt) || $sExt == $oFileInfo->getExtension()){
	                $aFiles[] = $oFileInfo->getPathname();
	            }
	        }	            
	    }
	    
	    return $aFiles;
	}
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();
	}
1370590
public function listFolder(string $path, bool $recursive = false) : array
	{
		$path = $this->normalizePath($path);
			
		$requestUrl = $this->siteUrl.'/sites/'.$this->siteName.'/_api/Web/GetFolderByServerRelativeUrl(\''.$this->folderPath.$path.'\')/Folders';
		
		$options = [
			'headers' => $this->requestHeaders,
		];
			
		$response = $this->send('GET', $requestUrl, $options);
			
		$folders = json_decode($response->getBody())->d ?? ['results' => []];
			
		// Making sure we convert the object to an array
		if (!is_array($folders)) {
			$folders = json_decode(json_encode($folders), true);
		}
			
		return $folders['results'];
	}
764998
public function getFileList($order = 'desc')
    {
        if (! is_null($this->itemsOrderCache) && isset($this->itemsOrderCache[$order])) {
            return $this->itemsOrderCache[$order];
        }

        // Order Files by date newer to older
        $this->items->sort(function ($a, $b) use ($order) {
            if ($a == $b) {
                return 0;
            }
            if ($order === 'asc') {
                return ($a < $b) ? -1 : 1;
            }

            return ($a > $b) ? -1 : 1;
        });

        $this->itemsOrderCache[$order] = $this->items->all();

        return $this->itemsOrderCache[$order];
    }
655941
public function get_listing($path='', $page = '') {
        if (empty($path)) {
            $path = $this->build_node_path('root', get_string('pluginname', 'repository_googledocs'));
        }
        if (!$this->issuer->get('enabled')) {
            // Empty list of files for disabled repository.
            return ['dynload' => false, 'list' => [], 'nologin' => true];
        }

        // We analyse the path to extract what to browse.
        $trail = explode('/', $path);
        $uri = array_pop($trail);
        list($id, $name) = $this->explode_node_path($uri);

        // Handle the special keyword 'search', which we defined in self::search() so that
        // we could set up a breadcrumb in the search results. In any other case ID would be
        // 'root' which is a special keyword set up by Google, or a parent (folder) ID.
        if ($id === 'search') {
            return $this->search($name);
        }

        // Query the Drive.
        $q = "'" . str_replace("'", "\'", $id) . "' in parents";
        $q .= ' AND trashed = false';
        $results = $this->query($q, $path);

        $ret = array();
        $ret['dynload'] = true;
        $ret['defaultreturntype'] = $this->default_returntype();
        $ret['path'] = $this->build_breadcrumb($path);
        $ret['list'] = $results;
        $ret['manage'] = 'https://drive.google.com/';

        return $ret;
    }
1332275
public function readFile($filePath)
    {
        if (false === $fileContent = @file_get_contents($filePath)) {
            throw new RuntimeException(
                sprintf('unable to read file "%s"', $filePath)
            );
        }

        return $fileContent;
    }
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;
    }
994512
public function getFileContents($filePath, $showError = true)
    {
        $filePath = realpath($filePath);

        if ($this->fileIsReadable($filePath) === false) {
            if ($showError === true) {
                // This file was not readable! We need to tell the user!
                $this->pool->messages->addMessage('fileserviceAccess', array($this->filterFilePath($filePath)));
            }
            // Return empty string.
            return '';
        }

        // Is it readable and does it have any content?
        $size = filesize($filePath);
        if ($size > 0) {
            $file = fopen($filePath, 'r');
            $result = fread($file, $size);
            fclose($file);
            return $result;
        }

        // Empty file returns an empty string.
        return '';
    }
746316
public static function getListItems($filepath,$ext = "json") {

		// set-up the dispatcher
		$dispatcherInstance = Dispatcher::getInstance();

		// dispatch that the data gather has started
		$dispatcherInstance->dispatch("data.getListItemsStart");

		// default vars
		$sourceDir     = Config::getOption("sourceDir");
		$listItems     = array();
		$listItemsData = array();

		// add list item data, makes 'listItems' a reserved word
		if (file_exists($sourceDir."/".$filepath)) {

			$file = file_get_contents($sourceDir."/".$filepath);

			if ($ext == "json") {
				$listItemsData = json_decode($file, true);
				if ($jsonErrorMessage = JSON::hasError()) {
					JSON::lastErrorMsg($filepath,$jsonErrorMessage,$listItems);
				}
			} else {

				try {
					$listItemsData = YAML::parse($file);
				} catch (ParseException $e) {
					printf("unable to parse ".$pathNameClean.": %s..\n", $e->getMessage());
				}

				// single line of text won't throw a YAML error. returns as string
				if (gettype($listItemsData) == "string") {
					$listItemsData = array();
				}

			}


			$numbers = array("one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve");

			$i = 0;
			$k = 1;
			$c = count($listItemsData)+1;

			while ($k < $c) {

				shuffle($listItemsData);
				$itemsArray = array();

				while ($i < $k) {
					$itemsArray[] = $listItemsData[$i];
					$i++;
				}

				$listItems[$numbers[$k-1]] = $itemsArray;

				$i = 0;
				$k++;

			}

		}

		$dispatcherInstance->dispatch("data.getListItemsEnd");

		return $listItems;

	}