list all files and directories inside a directory

@throws PageException
558851
public static Object actionList(PageContext pageContext, Resource directory, String serverPassword, int type, ResourceFilter filter, int listInfo, boolean recurse, String sort)
	    throws PageException {
	// check directory
	SecurityManager securityManager = pageContext.getConfig().getSecurityManager();
	securityManager.checkFileLocation(pageContext.getConfig(), directory, serverPassword);

	if (type != TYPE_ALL) {
	    ResourceFilter typeFilter = (type == TYPE_DIR) ? DIRECTORY_FILTER : FILE_FILTER;
	    if (filter == null) filter = typeFilter;
	    else filter = new AndResourceFilter(new ResourceFilter[] { typeFilter, filter });
	}

	// create query Object
	String[] names = new String[] { "name", "size", "type", "dateLastModified", "attributes", "mode", "directory" };
	String[] types = new String[] { "VARCHAR", "DOUBLE", "VARCHAR", "DATE", "VARCHAR", "VARCHAR", "VARCHAR" };

	boolean hasMeta = directory instanceof ResourceMetaData;
	if (hasMeta) {
	    names = new String[] { "name", "size", "type", "dateLastModified", "attributes", "mode", "directory", "meta" };
	    types = new String[] { "VARCHAR", "DOUBLE", "VARCHAR", "DATE", "VARCHAR", "VARCHAR", "VARCHAR", "OBJECT" };
	}
	Array array = null;
	Query query = null;
	Object rtn;
	if (listInfo == LIST_INFO_QUERY_ALL || listInfo == LIST_INFO_QUERY_NAME) {
	    boolean listOnlyNames = listInfo == LIST_INFO_QUERY_NAME;
	    rtn = query = new QueryImpl(listOnlyNames ? new String[] { "name" } : names, listOnlyNames ? new String[] { "VARCHAR" } : types, 0, "query");
	}
	else rtn = array = new ArrayImpl();

	if (!directory.exists()) {
	    if (directory instanceof FileResource) return rtn;
	    throw new ApplicationException("directory [" + directory.toString() + "] doesn't exist");
	}
	if (!directory.isDirectory()) {
	    if (directory instanceof FileResource) return rtn;
	    throw new ApplicationException("file [" + directory.toString() + "] exists, but isn't a directory");
	}
	if (!directory.isReadable()) {
	    if (directory instanceof FileResource) return rtn;
	    throw new ApplicationException("no access to read directory [" + directory.toString() + "]");
	}

	long startNS = System.nanoTime();

	try {
	    // Query All
	    if (listInfo == LIST_INFO_QUERY_ALL) _fillQueryAll(query, directory, filter, 0, hasMeta, recurse);

	    // Query Name
	    else if (listInfo == LIST_INFO_QUERY_NAME) {
		if (recurse || type != TYPE_ALL) _fillQueryNamesRec("", query, directory, filter, 0, recurse);
		else _fillQueryNames(query, directory, filter, 0);
	    }

	    // Array Name/Path
	    else if (listInfo == LIST_INFO_ARRAY_NAME || listInfo == LIST_INFO_ARRAY_PATH) {
		boolean onlyName = listInfo == LIST_INFO_ARRAY_NAME;
		if (!onlyName || recurse || type != TYPE_ALL) _fillArrayPathOrName(array, directory, filter, 0, recurse, onlyName);// QueryNamesRec("",query, directory, filter,
																   // 0,recurse);
		else _fillArrayName(array, directory, filter, 0);
	    }

	}
	catch (IOException e) {
	    throw Caster.toPageException(e);
	}

	// sort
	if (sort != null && query != null) {
	    String[] arr = sort.toLowerCase().split(",");
	    for (int i = arr.length - 1; i >= 0; i--) {
		try {
		    String[] col = arr[i].trim().split("\\s+");
		    if (col.length == 1) query.sort(col[0].trim());
		    else if (col.length == 2) {
			String order = col[1].toLowerCase().trim();
			if (order.equals("asc")) query.sort(col[0], lucee.runtime.type.Query.ORDER_ASC);
			else if (order.equals("desc")) query.sort(col[0], lucee.runtime.type.Query.ORDER_DESC);
			else throw new ApplicationException("invalid order type [" + col[1] + "]");
		    }
		}
		catch (Throwable t) {
		    ExceptionUtil.rethrowIfNecessary(t);
		}
	    }
	}
	if (query != null) query.setExecutionTime(System.nanoTime() - startNS);
	return rtn;
    }
72751
public function get_listing($fullpath = '', $page = ''){
        global $OUTPUT;

        $ret = array();
        $ret['list'] = array();
        $ret['manage'] = self::MANAGE_URL;
        $ret['dynload'] = true;

        $crumbs = explode('/', $fullpath);
        $path = array_pop($crumbs);

        if (empty($path)) {
            $type = 'folder';
            $pathid = 0;
            $pathname = get_string('pluginname', 'repository_boxnet');
        } else {
            list($type, $pathid, $pathname) = $this->split_part($path);
        }

        $ret['path'] = $this->build_breadcrumb($fullpath);
        $folders = array();
        $files = array();

        if ($type == 'search') {
            $result = $this->boxnetclient->search($pathname);
        } else {
            $result = $this->boxnetclient->get_folder_items($pathid);
        }
        foreach ($result->entries as $item) {
            if ($item->type == 'folder') {
                $folders[$item->name . ':' . $item->id] = array(
                    'title' => $item->name,
                    'path' => $fullpath . '/' . $this->build_part('folder', $item->id, $item->name),
                    'date' => strtotime($item->modified_at),
                    'thumbnail' => $OUTPUT->image_url(file_folder_icon(64))->out(false),
                    'thumbnail_height' => 64,
                    'thumbnail_width' => 64,
                    'children' => array(),
                    'size' => $item->size,
                );
            } else {
                $files[$item->name . ':' . $item->id] = array(
                    'title' => $item->name,
                    'source' => $this->build_part('file', $item->id, $item->name),
                    'size' => $item->size,
                    'date' => strtotime($item->modified_at),
                    'thumbnail' => $OUTPUT->image_url(file_extension_icon($item->name, 64))->out(false),
                    'thumbnail_height' => 64,
                    'thumbnail_width' => 64,
                    'author' => $item->owned_by->name,
                );
            }
        }

        core_collator::ksort($folders, core_collator::SORT_NATURAL);
        core_collator::ksort($files, core_collator::SORT_NATURAL);
        $ret['list'] = array_merge($folders, $files);
        $ret['list'] = array_filter($ret['list'], array($this, 'filter'));

        return $ret;
    }
660535
private void doGetDatasources() throws PageException {

	Map ds = config.getDataSourcesAsMap();
	Iterator it = ds.keySet().iterator();
	lucee.runtime.type.Query qry = new QueryImpl(new String[] { "name", "host", "classname", "bundleName", "bundleVersion", "dsn", "DsnTranslated", "database", "port",
		"timezone", "username", "password", "passwordEncrypted", "readonly", "grant", "drop", "create", "revoke", "alter", "select", "delete", "update", "insert",
		"connectionLimit", "openConnections", "connectionTimeout", "clob", "blob", "validate", "storage", "customSettings", "metaCacheTimeout" }, ds.size(), "query");

	int row = 0;

	while (it.hasNext()) {
	    Object key = it.next();
	    DataSource d = (DataSource) ds.get(key);
	    row++;

	    qry.setAt(KeyConstants._name, row, key);
	    qry.setAt(KeyConstants._host, row, d.getHost());
	    qry.setAt("classname", row, d.getClassDefinition().getClassName());
	    qry.setAt("bundleName", row, d.getClassDefinition().getName());
	    qry.setAt("bundleVersion", row, d.getClassDefinition().getVersionAsString());
	    qry.setAt("dsn", row, d.getDsnOriginal());
	    qry.setAt("database", row, d.getDatabase());
	    qry.setAt(KeyConstants._port, row, d.getPort() < 1 ? "" : Caster.toString(d.getPort()));
	    qry.setAt("dsnTranslated", row, d.getDsnTranslated());
	    qry.setAt("timezone", row, toStringTimeZone(d.getTimeZone()));
	    qry.setAt(KeyConstants._password, row, d.getPassword());

	    qry.setAt("passwordEncrypted", row, ConfigWebUtil.encrypt(d.getPassword()));
	    qry.setAt(KeyConstants._username, row, d.getUsername());
	    qry.setAt(KeyConstants._readonly, row, Caster.toBoolean(d.isReadOnly()));
	    qry.setAt(KeyConstants._select, row, Boolean.valueOf(d.hasAllow(DataSource.ALLOW_SELECT)));
	    qry.setAt(KeyConstants._delete, row, Boolean.valueOf(d.hasAllow(DataSource.ALLOW_DELETE)));
	    qry.setAt(KeyConstants._update, row, Boolean.valueOf(d.hasAllow(DataSource.ALLOW_UPDATE)));
	    qry.setAt(KeyConstants._create, row, Boolean.valueOf(d.hasAllow(DataSource.ALLOW_CREATE)));
	    qry.setAt(KeyConstants._insert, row, Boolean.valueOf(d.hasAllow(DataSource.ALLOW_INSERT)));
	    qry.setAt(KeyConstants._drop, row, Boolean.valueOf(d.hasAllow(DataSource.ALLOW_DROP)));
	    qry.setAt(KeyConstants._grant, row, Boolean.valueOf(d.hasAllow(DataSource.ALLOW_GRANT)));
	    qry.setAt(KeyConstants._revoke, row, Boolean.valueOf(d.hasAllow(DataSource.ALLOW_REVOKE)));
	    qry.setAt(KeyConstants._alter, row, Boolean.valueOf(d.hasAllow(DataSource.ALLOW_ALTER)));
	    int oc = config.getDatasourceConnectionPool().openConnections(key.toString());
	    qry.setAt("openConnections", row, oc < 0 ? 0 : oc);
	    qry.setAt("connectionLimit", row, d.getConnectionLimit() < 1 ? "" : Caster.toString(d.getConnectionLimit()));
	    qry.setAt("connectionTimeout", row, d.getConnectionTimeout() < 1 ? "" : Caster.toString(d.getConnectionTimeout()));
	    qry.setAt("customSettings", row, d.getCustoms());
	    qry.setAt("blob", row, Boolean.valueOf(d.isBlob()));
	    qry.setAt("clob", row, Boolean.valueOf(d.isClob()));
	    qry.setAt("validate", row, Boolean.valueOf(d.validate()));
	    qry.setAt("storage", row, Boolean.valueOf(d.isStorage()));
	    qry.setAt("metaCacheTimeout", row, Caster.toDouble(d.getMetaCacheTimeout()));

	}
	pageContext.setVariable(getString("admin", action, "returnVariable"), qry);
    }
163312
private void listFolder(final StructrShellCommand parent, final Iterable<AbstractFile> folder) throws FrameworkException, IOException {

		boolean hasContents = false;

		for (final AbstractFile child : folder) {

			if (parent.isAllowed(child, Permission.read, false)) {

				hasContents = true;

				if (child instanceof Folder) {

					term.setBold(true);
					term.setTextColor(4);
					term.print(child.getName() + "  ");
					term.setTextColor(7);
					term.setBold(false);

				} else {

					term.print(child.getName() + "  ");
				}
			}
		}

		if (hasContents) {
			term.println();
		}
	}
135134
public String getFileList() {

        // if mode is "listonly", only the list will be shown
        boolean galleryView = VIEW_GALLERY.equals(getSettings().getExplorerMode());
        // if mode is "listview", all file in the set collector will be shown
        boolean listView = VIEW_LIST.equals(getSettings().getExplorerMode());

        String currentFolder = getSettings().getExplorerResource();
        try {
            getCms().readResource(currentFolder, CmsResourceFilter.ALL);
        } catch (CmsException e) {
            // file was not readable
            currentFolder = "/";
        }

        // start creating content
        StringBuffer content = new StringBuffer(2048);
        content.append(getInitializationHeader());

        // now get the entries for the file list
        List<CmsResource> resources = getResources(getSettings().getExplorerResource());

        // if a folder contains to much entries we split them to pages of C_ENTRYS_PER_PAGE length
        int startat = 0;
        int stopat = resources.size();
        int selectedPage = 1;
        int numberOfPages = 0;
        int maxEntrys = getSettings().getUserSettings().getExplorerFileEntries();

        if (!galleryView) {
            selectedPage = getSettings().getExplorerPage();
            if (stopat > maxEntrys) {
                // we have to split
                numberOfPages = ((stopat - 1) / maxEntrys) + 1;
                if (selectedPage > numberOfPages) {
                    // the user has changed the folder and then selected a page for the old folder
                    selectedPage = 1;
                }
                startat = (selectedPage - 1) * maxEntrys;
                if ((startat + maxEntrys) < stopat) {
                    stopat = startat + maxEntrys;
                }
            }
        }
        // now check which file list columns we want to show
        int preferences = getUserPreferences();

        boolean showTitle = (preferences & CmsUserSettings.FILELIST_TITLE) > 0;
        boolean showNavText = (preferences & CmsUserSettings.FILELIST_NAVTEXT) > 0;
        boolean showPermissions = (preferences & CmsUserSettings.FILELIST_PERMISSIONS) > 0;
        boolean showDateLastModified = (preferences & CmsUserSettings.FILELIST_DATE_LASTMODIFIED) > 0;
        boolean showUserWhoLastModified = (preferences & CmsUserSettings.FILELIST_USER_LASTMODIFIED) > 0;
        boolean showDateCreated = (preferences & CmsUserSettings.FILELIST_DATE_CREATED) > 0;
        boolean showUserWhoCreated = (preferences & CmsUserSettings.FILELIST_USER_CREATED) > 0;
        boolean showDateReleased = (preferences & CmsUserSettings.FILELIST_DATE_RELEASED) > 0;
        boolean showDateExpired = (preferences & CmsUserSettings.FILELIST_DATE_EXPIRED) > 0;

        boolean fullPath = galleryView || listView;

        // set the right reference project
        CmsProject referenceProject;
        try {
            if (!listView) {
                referenceProject = getCms().readProject(getSettings().getProject());
            } else {
                referenceProject = getCms().readProject(getSettings().getExplorerProjectId());
            }
        } catch (CmsException ex) {
            referenceProject = getCms().getRequestContext().getCurrentProject();
        }

        CmsResourceUtil resUtil = new CmsResourceUtil(getCms());
        resUtil.setReferenceProject(referenceProject);

        for (int i = startat; i < stopat; i++) {
            CmsResource res = resources.get(i);
            resUtil.setResource(res);
            content.append(
                getInitializationEntry(
                    resUtil,
                    fullPath,
                    showTitle,
                    showNavText,
                    showPermissions,
                    showDateLastModified,
                    showUserWhoLastModified,
                    showDateCreated,
                    showUserWhoCreated,
                    showDateReleased,
                    showDateExpired));
        }

        content.append(getInitializationFooter(numberOfPages, selectedPage));
        return content.toString();
    }
1170529
def list_files_in_directory(dir, options)
      files = Dir.glob File.join(dir, "*")

      normalized_file_list options, files, false, options.exclude
    end
1098216
def respond_list_directory(self, dir_path, query=None):
		
		del query
		try:
			dir_contents = os.listdir(dir_path)
		except os.error:
			self.respond_not_found()
			return
		if os.path.normpath(dir_path) != self.__config['serve_files_root']:
			dir_contents.append('..')
		dir_contents.sort(key=lambda a: a.lower())
		displaypath = html.escape(urllib.parse.unquote(self.path), quote=True)

		f = io.BytesIO()
		encoding = sys.getfilesystemencoding()
		f.write(b'<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n')
		f.write(b'<html>\n<title>Directory listing for ' + displaypath.encode(encoding) + b'</title>\n')
		f.write(b'<body>\n<h2>Directory listing for ' + displaypath.encode(encoding) + b'</h2>\n')
		f.write(b'<hr>\n<ul>\n')
		for name in dir_contents:
			fullname = os.path.join(dir_path, name)
			displayname = linkname = name
			# Append / for directories or @ for symbolic links
			if os.path.isdir(fullname):
				displayname = name + "/"
				linkname = name + "/"
			if os.path.islink(fullname):
				displayname = name + "@"
				# Note: a link to a directory displays with @ and links with /
			f.write(('<li><a href="' + urllib.parse.quote(linkname) + '">' + html.escape(displayname, quote=True) + '</a>\n').encode(encoding))
		f.write(b'</ul>\n<hr>\n</body>\n</html>\n')
		length = f.tell()
		f.seek(0)

		self.send_response(200)
		self.send_header('Content-Type', 'text/html; charset=' + encoding)
		self.send_header('Content-Length', length)
		self.end_headers()
		shutil.copyfileobj(f, self.wfile)
		f.close()
		return
123228
public function listContents($directory)
    {
        $files = $this->modulable->getConnection()->listContents($directory);
        $files = array_pluck($files, 'path');
        $files = array_map('basename', $files);

        return $files;
    }
81586
private function nList($dir)
    {
        $dirList = ftp_nlist($this->session, $dir);
        if ($dirList === false) {
            throw new \RuntimeException('List error');
        }
        return $dirList;
    }
986443
def list_dir_all(cookie, tokens, path):
    ''''''
    pcs_files = []
    page = 1
    while True:
        content = list_dir(cookie, tokens, path, page)
        if not content:
            return (path, None)
        if not content['list']:
            return (path, pcs_files)
        pcs_files.extend(content['list'])
        page = page + 1
791376
void displayInheritedPermissions() {

        // store all parent folder ids together with path in a map
        m_parents = new HashMap<CmsUUID, String>();
        String sitePath = m_cms.getSitePath(m_resource);
        String path = CmsResource.getParentFolder(sitePath);
        List<CmsResource> parentResources = new ArrayList<CmsResource>();
        try {
            // get all parent folders of the current file
            parentResources = m_cms.readPath(path, CmsResourceFilter.IGNORE_EXPIRATION);
        } catch (CmsException e) {
            // can usually be ignored
            if (LOG.isInfoEnabled()) {
                LOG.info(e.getLocalizedMessage());
            }
        }
        Iterator<CmsResource> k = parentResources.iterator();
        while (k.hasNext()) {
            // add the current folder to the map
            CmsResource curRes = k.next();
            m_parents.put(curRes.getResourceId(), curRes.getRootPath());
        }

        ArrayList<CmsAccessControlEntry> inheritedEntries = new ArrayList<CmsAccessControlEntry>();
        try {
            Iterator<CmsAccessControlEntry> itAces = m_cms.getAccessControlEntries(path, true).iterator();
            while (itAces.hasNext()) {
                CmsAccessControlEntry curEntry = itAces.next();
                inheritedEntries.add(curEntry);
            }
        } catch (CmsException e) {
            // can usually be ignored
            if (LOG.isInfoEnabled()) {
                LOG.info(e.getLocalizedMessage());
            }
        }
        addEntryTableToLayout(inheritedEntries, m_inheritedPermissions, false, true);

        //        buildInheritedList(inheritedEntries, parents);
    }
695423
public function setDir($dir)
    {
        if (empty($dir) || !@is_dir($dir)) {
            throw new PageCacheException(__METHOD__ . ': ' . (string)$dir . ' in constructor is not a directory');
        }

        // Check for trailing slash and add it if not exists
        if (mb_substr($dir, -1, 1) !== DIRECTORY_SEPARATOR) {
            $dir .= DIRECTORY_SEPARATOR;
        }

        $this->dir = $dir;
    }
805304
public function output() {
        $parts = explode('/', $this->output_path);
        // get rid of the filename
        array_pop($parts);

        $path = implode('/', $parts);
        if ($path && !file_exists($path)) {
            if (!mkdir($path, 0777, true)) {
                throw new \Exception("could not make directory $path");
            }
        }

        if (!file_put_contents($this->output_path, $this->render())) {
            throw new \Exception("could not write $filename");
        }
    }
1365341
protected function getData()
    {
        $assetsPath = $this->getAssetsPath();

        if (!file_exists($assetsPath) || !is_dir($assetsPath)) {
            if (!File::makeDirectory($assetsPath)) {
                throw new ApplicationException(Lang::get(
                    'cms::lang.cms_object.error_creating_directory',
                    ['name' => $assetsPath]
                ));
            }
        }

        $searchTerm = Str::lower($this->getSearchTerm());

        if (!strlen($searchTerm)) {
            $currentPath = $this->getCurrentPath();
            return $this->getDirectoryContents(
                new DirectoryIterator($currentPath)
            );
        }

        return $this->findFiles();
    }
126476
protected function listDirectoryContents($directory = '.')
    {
        if ($directory && strpos($directory, '.') !== 0) {
            ftp_chdir($this->getConnection(), $directory);
        }

        $listing = @ftp_rawlist($this->getConnection(), '.') ?: [];

        $this->setConnectionRoot();

        return  $this->normalizeDirectoryListing($listing);
    }
1081271
public function listFile()
    {
        $this->downloadFile();
        $this->actionListFile();
        $this->setTitleListFile();
        $this->setBreadcrumbListFile();
        $this->setFilterListFile();
        $this->setPagerListFile();

        $this->setData('files', $this->getListFile());
        $this->setData('entities', $this->file->getEntities());

        $this->outputListFile();
    }
29253
private static List<Path> file_listing_(Path dir) throws IOException {
        try (Stream<Path> files = Files.list(dir)) {
            return files.collect(Collectors.toList());
        }
    }