Find a page with matching path.

To be compatible with older versions, fallback to name-only lookup.

@param securityContext
@param pages
@param path
@param edit
@return page
@throws FrameworkException
555275
private Page findPage(final SecurityContext securityContext, List<Page> pages, final String path, final EditMode edit) throws FrameworkException {

		if (pages == null) {

			pages = StructrApp.getInstance(securityContext).nodeQuery(Page.class).getAsList();
			Collections.sort(pages, new GraphObjectComparator(StructrApp.key(Page.class, "position"), GraphObjectComparator.ASCENDING));
		}

		for (final Page page : pages) {

			final String pagePath = page.getPath();
			if (pagePath != null && pagePath.equals(path) && (EditMode.CONTENT.equals(edit) || isVisibleForSite(securityContext.getRequest(), page))) {

				return page;
			}
		}

		final String name     = PathHelper.getName(path);

		for (final Page page : pages) {

			final String pageName = page.getName();
			if (pageName != null && pageName.equals(name) && (EditMode.CONTENT.equals(edit) || isVisibleForSite(securityContext.getRequest(), page))) {

				return page;
			}
		}

		for (final Page page : pages) {

			final String pageUuid = page.getUuid();
			if (pageUuid != null && pageUuid.equals(name) && (EditMode.CONTENT.equals(edit) || isVisibleForSite(securityContext.getRequest(), page))) {

				return page;
			}
		}

		return null;
	}
678285
function findPage(pages, path) {
  const p = path.shift();
  const page = pages.find(page => page.path === p);

  if (!page) {
    return {redirect: getDefaultPath(pages)};
  }
  if (page.children) {
    const result = findPage(page.children, path);
    if (result.page) {
      return result;
    }
    return {redirect: [p].concat(result.redirect)};
  }
  if (path.length) {
    return {redirect: []};
  }
  return {page};
}
1232377
@SuppressWarnings("unused")
    public Template getTemplate(String path) {
        ActContext.Base ctx = ActContext.Base.currentContext();
        if (null != ctx) {
            String curPath = ctx.templatePath();
            ctx.templateLiteral(path);
            try {
                return load(ctx);
            } finally {
                ctx.templatePath(curPath);
            }
        }
        final String templatePath = S.ensureStartsWith(path, '/');
        Template template = null;

        View defView = Act.appConfig().defaultView();

        if (null != defView) {
            template = !isTemplatePath(path) ? defView.loadInlineTemplate(path) : defView.loadTemplate(templatePath);
        }
        if (null == template && multiViews) {
            for (View view : viewList) {
                if (view == defView) continue;
                template = view.loadTemplate(templatePath);
                if (null != template) {
                    break;
                }
            }
        }
        if (null != template) {
            cache(path, template);
        }
        return template;
    }
1342136
private Set<String> findExclusionPaths(ServletContext servletContext) {
        Set<String> exclusions = new TreeSet<String>();
        
        // Let other handlers deal with folders that do not reside in the WEB-INF or META-INF
        Set<String> resourcePaths = servletContext.getResourcePaths("/");
        
        // This most certainly should not be null!
        // It means that the server cannot read files at all
        if (resourcePaths == null) throw new InitException("ServletContext cannot read files. Reason is unknown");
        
        resourcePaths.removeIf( path -> path.contains("-INF") || path.contains("-inf"));
    
        // We still need to also remove the views folder from being processed by other handlers
        resourcePaths.removeIf( path -> path.contains(TemplateEngine.TEMPLATES_FOLDER));
        
        // Add the remaining paths to exclusions
        for (String path : resourcePaths) {
            // add leading slash
            if (path.charAt(0) != '/')
                path = '/' + path;
            
            // remove the last slash
            if (path.charAt(path.length()-1) == '/')
                path = path.substring(0, path.length()-1);
            exclusions.add(path);
        }
        
        return exclusions;
    }
1254503
private SecurityContext securityContext() {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex(swaggerProperties().getAuthorization().getAuthRegex()))
                .build();
    }
620604
public function editAction(Page $page, Request $request)
    {
        $form = $this->container->get('form.factory')->createNamed(
            'page',
            EditionType::class,
            $page,
            array(
                'action' => $this->container->get('router')->generate(
                    'synapse_admin_page_edition',
                    array('id' => $page->getId())
                ),
                'synapse_theme' => $request->get('synapse_theme'),
                'method' => 'POST',
                'csrf_protection' => false,
            )
        );

        if ($request->request->has('page')) {
            $form->handleRequest($request);
            if ($form->isValid()) {
                $form->getData()->resolve();

                return $this->redirect(// refresh to rebuild dynamic form
                    $this->container->get('router')->generate(
                        $request->attributes->get('_route'),
                        $request->attributes->get('_route_params')
                    )
                );
            }
        }

        return $this->render('SynapsePageBundle:Admin/Page:edit.html.twig', array(
            'form' => $form->createView(),
            'page' => $page,
        ));
    }
213393
public function findByRequest(Request $request): ?PageInterface
    {
        if (null !== $route = $request->attributes->get('_route', null)) {
            return $this->findByRoute($route);
        }

        return null;
    }
1248961
public static void actionRename(PageContext pc, Resource directory, String strNewdirectory, String serverPassword, boolean createPath, Object acl, String storage)
	    throws PageException {
	// check directory
	SecurityManager securityManager = pc.getConfig().getSecurityManager();
	securityManager.checkFileLocation(pc.getConfig(), directory, serverPassword);

	if (!directory.exists()) throw new ApplicationException("the directory [" + directory.toString() + "] doesn't exist");
	if (!directory.isDirectory()) throw new ApplicationException("the file [" + directory.toString() + "] exists, but it isn't a directory");
	if (!directory.canRead()) throw new ApplicationException("no access to read directory [" + directory.toString() + "]");

	if (strNewdirectory == null) throw new ApplicationException("the attribute [newDirectory] is not defined");

	// real to source
	Resource newdirectory = toDestination(pc, strNewdirectory, directory);

	securityManager.checkFileLocation(pc.getConfig(), newdirectory, serverPassword);
	if (newdirectory.exists()) throw new ApplicationException("new directory [" + newdirectory.toString() + "] already exists");
	if (createPath) {
	    newdirectory.getParentResource().mkdirs();

	}
	try {
	    directory.moveTo(newdirectory);
	}
	catch (Throwable t) {
	    ExceptionUtil.rethrowIfNecessary(t);
	    throw Caster.toPageException(t);
	}

	// set S3 stuff
	setS3Attrs(pc, directory, acl, storage);

    }
1042501
public void redirectToContextPath(String path) {
        if ("".equals(contextPath)) {
            // context path is the root
            redirect(path);
        } else {
            redirect(contextPath + StringUtils.addStart(path, "/"));
        }
    }
478944
private void doSecurityManager() throws PageException {
	String rtnVar = getString("admin", action, "returnVariable");
	String secType = getString("admin", action, "sectype");
	String secValue = getString("secvalue", null);
	boolean isServer = config instanceof ConfigServer;

	if (secValue == null) {
	    if (isServer) {
		pageContext.setVariable(rtnVar, SecurityManagerImpl.toStringAccessValue(SecurityManager.VALUE_YES));
	    }
	    else {
		pageContext.setVariable(rtnVar, SecurityManagerImpl.toStringAccessValue(config.getSecurityManager().getAccess(secType)));
	    }
	    return;
	}
	pageContext.setVariable(rtnVar, Caster.toBoolean(isServer || config.getSecurityManager().getAccess(secType) == SecurityManagerImpl.toShortAccessValue(secValue)));
    }
946929
public void doInclude(String realPath, boolean runOnce, Object cachedWithin) throws PageException {
	if (cachedWithin == null) cachedWithin = getCachedWithin(ConfigWeb.CACHEDWITHIN_INCLUDE);
	_doInclude(getRelativePageSources(realPath), runOnce, cachedWithin);
    }
251334
public String getRootPath(Page page) {
    if (page == null) {
      return null;
    }
    return getRootPath(page.adaptTo(Resource.class));
  }
219030
public void setLoginPage(String path)
    {
        if (!path.startsWith("/"))
        {
            log.warn("form-login-page must start with /");
            path="/"+path;
        }
        _formLoginPage=path;
        _formLoginPath=path;
        if (_formLoginPath.indexOf('?')>0)
            _formLoginPath=_formLoginPath.substring(0,_formLoginPath.indexOf('?'));
    }
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;
    }
1093059
def from_path(self, complete_path, lang, exclude_drafts=True):
        """"""
        if complete_path.endswith("/"):
            complete_path = complete_path[:-1]
        # just return the root page
        if complete_path == '':
            root_pages = self.root()
            if root_pages:
                return root_pages[0]
            else:
                return None

        slug = get_slug(complete_path)
        from pages.models import Content
        page_ids = Content.objects.get_page_ids_by_slug(slug)
        pages_list = self.on_site().filter(id__in=page_ids)
        if exclude_drafts:
            pages_list = pages_list.exclude(status=self.model.DRAFT)
        if len(pages_list) == 1:
            if(settings.PAGE_USE_STRICT_URL and
                    pages_list[0].get_complete_slug(lang) != complete_path):
                return None
            return pages_list[0]
        # if more than one page is matching the slug,
        # we need to use the full URL
        if len(pages_list) > 1:
            for page in pages_list:
                if page.get_complete_slug(lang) == complete_path:
                    return page
        return None
903836
@GET
  @Path(WEBUI_BROWSE)
  @ReturnType("alluxio.wire.MasterWebUIBrowse")
  public Response getWebUIBrowse(@DefaultValue("/") @QueryParam("path") String requestPath,
      @DefaultValue("0") @QueryParam("offset") String requestOffset,
      @DefaultValue("") @QueryParam("end") String requestEnd,
      @DefaultValue("20") @QueryParam("limit") String requestLimit) {
    return RestUtils.call(() -> {
      MasterWebUIBrowse response = new MasterWebUIBrowse();

      if (!ServerConfiguration.getBoolean(PropertyKey.WEB_FILE_INFO_ENABLED)) {
        return response;
      }

      if (SecurityUtils.isSecurityEnabled(ServerConfiguration.global())
          && AuthenticatedClientUser.get(ServerConfiguration.global()) == null) {
        AuthenticatedClientUser.set(LoginUser.get(ServerConfiguration.global()).getName());
      }
      response.setDebug(ServerConfiguration.getBoolean(PropertyKey.DEBUG)).setShowPermissions(
          ServerConfiguration.getBoolean(PropertyKey.SECURITY_AUTHORIZATION_PERMISSION_ENABLED))
          .setMasterNodeAddress(mMasterProcess.getRpcAddress().toString()).setInvalidPathError("");
      List<FileInfo> filesInfo;
      String path = requestPath;
      if (path == null || path.isEmpty()) {
        path = AlluxioURI.SEPARATOR;
      }
      AlluxioURI currentPath = new AlluxioURI(path);
      response.setCurrentPath(currentPath.toString()).setViewingOffset(0);

      try {
        long fileId = mFileSystemMaster.getFileId(currentPath);
        FileInfo fileInfo = mFileSystemMaster.getFileInfo(fileId);
        UIFileInfo currentFileInfo = new UIFileInfo(fileInfo, ServerConfiguration.global(),
            new MasterStorageTierAssoc().getOrderedStorageAliases());
        if (currentFileInfo.getAbsolutePath() == null) {
          throw new FileDoesNotExistException(currentPath.toString());
        }
        response.setCurrentDirectory(currentFileInfo)
            .setBlockSizeBytes(currentFileInfo.getBlockSizeBytes());
        if (!currentFileInfo.getIsDirectory()) {
          long relativeOffset = 0;
          long offset;
          try {
            if (requestOffset != null) {
              relativeOffset = Long.parseLong(requestOffset);
            }
          } catch (NumberFormatException e) {
            relativeOffset = 0;
          }
          // If no param "end" presents, the offset is relative to the beginning; otherwise, it is
          // relative to the end of the file.
          if (requestEnd.equals("")) {
            offset = relativeOffset;
          } else {
            offset = fileInfo.getLength() - relativeOffset;
          }
          if (offset < 0) {
            offset = 0;
          } else if (offset > fileInfo.getLength()) {
            offset = fileInfo.getLength();
          }
          try {
            AlluxioURI absolutePath = new AlluxioURI(currentFileInfo.getAbsolutePath());
            FileSystem fs = mFsClient;
            String fileData;
            URIStatus status = fs.getStatus(absolutePath);
            if (status.isCompleted()) {
              OpenFilePOptions options =
                  OpenFilePOptions.newBuilder().setReadType(ReadPType.NO_CACHE).build();
              try (FileInStream is = fs.openFile(absolutePath, options)) {
                int len = (int) Math.min(5 * Constants.KB, status.getLength() - offset);
                byte[] data = new byte[len];
                long skipped = is.skip(offset);
                if (skipped < 0) {
                  // nothing was skipped
                  fileData = "Unable to traverse to offset; is file empty?";
                } else if (skipped < offset) {
                  // couldn't skip all the way to offset
                  fileData = "Unable to traverse to offset; is offset larger than the file?";
                } else {
                  // read may not read up to len, so only convert what was read
                  int read = is.read(data, 0, len);
                  if (read < 0) {
                    // stream couldn't read anything, skip went to EOF?
                    fileData = "Unable to read file";
                  } else {
                    fileData = WebUtils.convertByteArrayToStringWithoutEscape(data, 0, read);
                  }
                }
              }
            } else {
              fileData = "The requested file is not complete yet.";
            }
            List<UIFileBlockInfo> uiBlockInfo = new ArrayList<>();
            for (FileBlockInfo fileBlockInfo : mFileSystemMaster
                .getFileBlockInfoList(absolutePath)) {
              uiBlockInfo.add(new UIFileBlockInfo(fileBlockInfo, ServerConfiguration.global()));
            }
            response.setFileBlocks(uiBlockInfo).setFileData(fileData)
                .setHighestTierAlias(mBlockMaster.getGlobalStorageTierAssoc().getAlias(0));
          } catch (AlluxioException e) {
            throw new IOException(e);
          }
          response.setViewingOffset(offset);
          return response;
        }

        if (currentPath.isRoot()) {
          response.setPathInfos(new UIFileInfo[0]);
        } else {
          String[] splitPath = PathUtils.getPathComponents(currentPath.toString());
          UIFileInfo[] pathInfos = new UIFileInfo[splitPath.length - 1];
          fileId = mFileSystemMaster.getFileId(currentPath);
          pathInfos[0] =
              new UIFileInfo(mFileSystemMaster.getFileInfo(fileId), ServerConfiguration.global(),
                  new MasterStorageTierAssoc().getOrderedStorageAliases());
          AlluxioURI breadcrumb = new AlluxioURI(AlluxioURI.SEPARATOR);
          for (int i = 1; i < splitPath.length - 1; i++) {
            breadcrumb = breadcrumb.join(splitPath[i]);
            fileId = mFileSystemMaster.getFileId(breadcrumb);
            pathInfos[i] =
                new UIFileInfo(mFileSystemMaster.getFileInfo(fileId), ServerConfiguration.global(),
                    new MasterStorageTierAssoc().getOrderedStorageAliases());
          }
          response.setPathInfos(pathInfos);
        }

        filesInfo = mFileSystemMaster.listStatus(currentPath, ListStatusContext.mergeFrom(
            ListStatusPOptions.newBuilder().setLoadMetadataType(LoadMetadataPType.ALWAYS)));
      } catch (FileDoesNotExistException e) {
        response.setInvalidPathError("Error: Invalid Path " + e.getMessage());
        return response;
      } catch (InvalidPathException e) {
        response.setInvalidPathError("Error: Invalid Path " + e.getLocalizedMessage());
        return response;
      } catch (UnavailableException e) {
        response.setInvalidPathError("The service is temporarily unavailable. " + e.getMessage());
        return response;
      } catch (IOException e) {
        response.setInvalidPathError(
            "Error: File " + currentPath + " is not available " + e.getMessage());
        return response;
      } catch (AccessControlException e) {
        response.setInvalidPathError(
            "Error: File " + currentPath + " cannot be accessed " + e.getMessage());
        return response;
      }

      List<UIFileInfo> fileInfos = new ArrayList<>(filesInfo.size());
      for (FileInfo fileInfo : filesInfo) {
        UIFileInfo toAdd = new UIFileInfo(fileInfo, ServerConfiguration.global(),
            new MasterStorageTierAssoc().getOrderedStorageAliases());
        try {
          if (!toAdd.getIsDirectory() && fileInfo.getLength() > 0) {
            FileBlockInfo blockInfo =
                mFileSystemMaster.getFileBlockInfoList(new AlluxioURI(toAdd.getAbsolutePath()))
                    .get(0);
            List<String> locations = new ArrayList<>();
            // add the in-Alluxio block locations
            for (BlockLocation location : blockInfo.getBlockInfo().getLocations()) {
              WorkerNetAddress address = location.getWorkerAddress();
              locations.add(address.getHost() + ":" + address.getDataPort());
            }
            // add underFS locations
            locations.addAll(blockInfo.getUfsLocations());
            toAdd.setFileLocations(locations);
          }
        } catch (FileDoesNotExistException e) {
          response.setFileDoesNotExistException("Error: non-existing file " + e.getMessage());
          return response;
        } catch (InvalidPathException e) {
          response.setInvalidPathException("Error: invalid path " + e.getMessage());
          return response;
        } catch (AccessControlException e) {
          response.setAccessControlException(
              "Error: File " + currentPath + " cannot be accessed " + e.getMessage());
          return response;
        }
        fileInfos.add(toAdd);
      }
      Collections.sort(fileInfos, UIFileInfo.PATH_STRING_COMPARE);

      response.setNTotalFile(fileInfos.size());

      try {
        int offset = Integer.parseInt(requestOffset);
        int limit = Integer.parseInt(requestLimit);
        limit = offset == 0 && limit > fileInfos.size() ? fileInfos.size() : limit;
        limit = offset + limit > fileInfos.size() ? fileInfos.size() - offset : limit;
        int sum = Math.addExact(offset, limit);
        fileInfos = fileInfos.subList(offset, sum);
        response.setFileInfos(fileInfos);
      } catch (NumberFormatException e) {
        response.setFatalError("Error: offset or limit parse error, " + e.getLocalizedMessage());
        return response;
      } catch (ArithmeticException e) {
        response.setFatalError(
            "Error: offset or offset + limit is out of bound, " + e.getLocalizedMessage());
        return response;
      } catch (IllegalArgumentException e) {
        response.setFatalError(e.getLocalizedMessage());
        return response;
      }

      return response;
    }, ServerConfiguration.global());
  }
1226939
public function find(PageDocument $page)
    {
        $request = $this->requestStack->getCurrentRequest();

        $template = $page->getDefault(AbstractPhpcrDocument::DEFAULT_TEMPLATE_KEY);
        if ($template === null) {
            $defaults = [];

            /** @var RouteEnhancerInterface $enhancer */
            foreach ($this->dynamicRouter->getRouteEnhancers() as $enhancer) {
                $defaults = array_merge($defaults, $enhancer->enhance(['_content' => $page], $request));
            }

            if (array_key_exists(AbstractPhpcrDocument::DEFAULT_TEMPLATE_KEY, $defaults)) {
                $template = $defaults[AbstractPhpcrDocument::DEFAULT_TEMPLATE_KEY];
            }
        }

        return $template;
    }