Get the whole tree of a part of the tree via an AJAX request.

@param HTTPRequest $request
@return HTTPResponse
@throws Exception
7086
public function tree(HTTPRequest $request)
    {
        // Regular source specification
        $isSubTree = false;

        $this->search = $request->requestVar('search');
        $id = (is_numeric($request->latestParam('ID')))
            ? (int)$request->latestParam('ID')
            : (int)$request->requestVar('ID');

        // pre-process the tree - search needs to operate globally, not locally as marking filter does
        if ($this->search) {
            $this->populateIDs();
        }

        /** @var DataObject|Hierarchy $obj */
        $obj = null;
        $sourceObject = $this->getSourceObject();

        // Precache numChildren count if possible.
        if ($this->getNumChildrenMethod() == 'numChildren') {
            // We're not calling `Hierarchy::prepopulateTreeDataCache()` because we're not customising results based
            // on version or Fluent locales. So there would be no performance gain from additional caching.
            Hierarchy::prepopulate_numchildren_cache($sourceObject);
        }

        if ($id && !$request->requestVar('forceFullTree')) {
            $obj = DataObject::get_by_id($sourceObject, $id);
            $isSubTree = true;
            if (!$obj) {
                throw new Exception(
                    "TreeDropdownField->tree(): the object #$id of type $sourceObject could not be found"
                );
            }
        } else {
            if ($this->getTreeBaseID()) {
                $obj = DataObject::get_by_id($sourceObject, $this->getTreeBaseID());
            }

            if (!$this->getTreeBaseID() || !$obj) {
                $obj = DataObject::singleton($sourceObject);
            }
        }

        // Create marking set
        $markingSet = MarkedSet::create(
            $obj,
            $this->getChildrenMethod(),
            $this->getNumChildrenMethod(),
            $this->config()->get('node_threshold_total')
        );

        // Set filter on searched nodes
        if ($this->getFilterFunction() || $this->search) {
            // Rely on filtering to limit tree
            $markingSet->setMarkingFilterFunction(function ($node) {
                return $this->filterMarking($node);
            });
            $markingSet->setLimitingEnabled(false);
        }

        // Begin marking
        $markingSet->markPartialTree();

        // Explicitely mark our search results if necessary
        foreach ($this->searchIds as $id => $marked) {
            if ($marked) {
                $object = $this->objectForKey($id);
                if (!$object) {
                    continue;
                }
                $markingSet->markToExpose($object);
            }
        }

        // Allow to pass values to be selected within the ajax request
        $value = $request->requestVar('forceValue') ?: $this->value;
        if ($value && ($values = preg_split('/,\s*/', $value))) {
            foreach ($values as $value) {
                if (!$value || $value == 'unchanged') {
                    continue;
                }

                $object = $this->objectForKey($value);
                if (!$object) {
                    continue;
                }
                $markingSet->markToExpose($object);
            }
        }

        // Set title formatter
        $customised = function (DataObject $child) use ($isSubTree) {
            return [
                'name' => $this->getName(),
                'id' => $child->obj($this->getKeyField()),
                'title' => $child->obj($this->getTitleField()),
                'treetitle' => $child->obj($this->getLabelField()),
                'disabled' => $this->nodeIsDisabled($child),
                'isSubTree' => $isSubTree
            ];
        };

        // Determine output format
        if ($request->requestVar('format') === 'json') {
            // Format JSON output
            $json = $markingSet
                ->getChildrenAsArray($customised);

            if ($request->requestVar('flatList')) {
                // format and filter $json here
                $json['children'] = $this->flattenChildrenArray($json['children']);
            }
            return HTTPResponse::create()
                ->addHeader('Content-Type', 'application/json')
                ->setBody(json_encode($json));
        } else {
            // Return basic html
            $html = $markingSet->renderChildren(
                [self::class . '_HTML', 'type' => 'Includes'],
                $customised
            );
            return HTTPResponse::create()
                ->addHeader('Content-Type', 'text/html')
                ->setBody($html);
        }
    }
31487
public function treeAction(Request $request)
    {
        $categoryManager = $this->get('sonata.classification.manager.category');
        $currentContext = false;
        if ($context = $request->get('context')) {
            $currentContext = $this->get('sonata.classification.manager.context')->find($context);
        }

        // all root categories.
        $rootCategoriesSplitByContexts = $categoryManager->getRootCategoriesSplitByContexts(false);

        // root categories inside the current context
        $currentCategories = [];

        if (!$currentContext && !empty($rootCategoriesSplitByContexts)) {
            $currentCategories = current($rootCategoriesSplitByContexts);
            $currentContext = current($currentCategories)->getContext();
        } else {
            foreach ($rootCategoriesSplitByContexts as $contextId => $contextCategories) {
                if ($currentContext->getId() !== $contextId) {
                    continue;
                }

                foreach ($contextCategories as $category) {
                    if ($currentContext->getId() !== $category->getContext()->getId()) {
                        continue;
                    }

                    $currentCategories[] = $category;
                }
            }
        }

        $datagrid = $this->admin->getDatagrid();

        if ($this->admin->getPersistentParameter('context')) {
            $datagrid->setValue('context', null, $this->admin->getPersistentParameter('context'));
        }

        $formView = $datagrid->getForm()->createView();

        $this->setFormTheme($formView, $this->admin->getFilterTheme());

        return $this->renderWithExtraParams($this->admin->getTemplate('tree'), [
            'action' => 'tree',
            'current_categories' => $currentCategories,
            'root_categories' => $rootCategoriesSplitByContexts,
            'current_context' => $currentContext,
            'form' => $formView,
            'csrf_token' => $this->getCsrfToken('sonata.batch'),
        ]);
    }
722184
public static function getFromRequest(Request $request)
    {
        // if something has already set a page object, we return it
        $c = $request->getCurrentPage();
        if (is_object($c)) {
            return $c;
        }
        if ($request->getPath() != '') {
            $path = $request->getPath();
            $db = Database::connection();
            $cID = false;
            $ppIsCanonical = false;
            $site = \Core::make('site')->getSite();
            $treeIDs = [0];
            foreach($site->getLocales() as $locale) {
                $tree = $locale->getSiteTree();
                if (is_object($tree)) {
                    $treeIDs[] = $tree->getSiteTreeID();
                }
            }

            $treeIDs = implode(',', $treeIDs);

            while ((!$cID) && $path) {
                $row = $db->fetchAssoc('select pp.cID, ppIsCanonical from PagePaths pp inner join Pages p on pp.cID = p.cID where cPath = ? and siteTreeID in (' . $treeIDs . ')', [$path]);
                if (!empty($row)) {
                    $cID = $row['cID'];
                    if ($cID) {
                        $cPath = $path;
                        $ppIsCanonical = (bool) $row['ppIsCanonical'];
                        break;
                    }
                }
                $path = substr($path, 0, strrpos($path, '/'));
            }
            if ($cID && $cPath) {
                $c = self::getByID($cID, 'ACTIVE');
                $c->cPathFetchIsCanonical = $ppIsCanonical;
            } else {
                $c = new self();
                $c->loadError(COLLECTION_NOT_FOUND);
            }

            return $c;
        } else {
            $cID = $request->query->get('cID');
            if (!$cID) {
                $cID = $request->request->get('cID');
            }
            $cID = Core::make('helper/security')->sanitizeInt($cID);
            if ($cID) {
                $c = self::getByID($cID, 'ACTIVE');
            } else {
                $site = \Core::make('site')->getSite();
                $c = $site->getSiteHomePageObject('ACTIVE');
            }
            $c->cPathFetchIsCanonical = true;
        }

        return $c;
    }
1038466
public function treeAction(Request $request)
    {
        $language = $request->get('language');
        $treeId = (int) $request->get('tid');

        if (!$treeId || !$language) {
            return new Response('', 500);
        }

        $translator = $this->get('translator');
        $treeManager = $this->get('phlexible_tree.tree_manager');
        $teaserService = $this->get('phlexible_teaser.teaser_service');
        $elementService = $this->get('phlexible_element.element_service');
        $elementSourceManager = $this->get('phlexible_element.element_source_manager');
        $iconResolver = $this->get('phlexible_element.icon_resolver');

        $tree = $treeManager->getByNodeId($treeId);
        $treeNode = $tree->get($treeId);
        $element = $elementService->findElement($treeNode->getTypeId());
        $elementMasterLanguage = $element->getMasterLanguage();
        $elementtype = $elementService->findElementtype($element);

        $treeNodePath = $tree->getPath($treeNode);

        $layouts = [];
        $layoutareas = [];
        // TODO: repair
        foreach ($elementSourceManager->findElementtypesByType('layout') as $layoutarea) {
            if (in_array($elementtype, $elementService->findAllowedParents($layoutarea))) {
                $layoutareas[] = $layoutarea;
            }
        }

        foreach ($layoutareas as $layoutarea) {
            $teasers = $teaserService->findForLayoutAreaAndTreeNodePath($layoutarea, $treeNodePath);
            $areaRoot = [
                'id' => 'area_'.$layoutarea->getId(),
                'area_id' => $layoutarea->getId(),
                'parent_tid' => $treeId,
                'parent_eid' => $element->getEid(),
                'text' => $layoutarea->getTitle(),
                'icon' => $iconResolver->resolveElementtype($layoutarea),
                'type' => $layoutarea->getType(),
                'inherited' => null, //true,
                'cls' => 'siteroot-node',
                'leaf' => true,
                'expanded' => true,
                'allowDrag' => true,
                'allowDrop' => false,
                'children' => [],
                'qtip' => $translator->trans('elements.doubleclick_to_sort', [], 'gui'),
            ];

            foreach ($teasers as $teaser) {
                /* @var $teaser Teaser */
                $teaserData = [
                    'id' => $teaser->getId(),
                    'layoutarea_id' => $layoutarea->getId(),
                    'parent_tid' => $treeId,
                    'parent_eid' => $element->getEid(),
                    'type' => $teaser->getType(),
                    'sort' => $teaser->getInheritSort($treeId),
                    'inherited' => false,
                    'inherit' => false,
                    'leaf' => true,
                    'hide' => false,
                    'expanded' => false,
                    'cls' => '',
                    'children' => [],
                    'allowDrag' => false,
                    'allowDrop' => false,
                ];

                switch ($teaser->getType()) {
                    case 'inherited':
                    case 'teaser':
                    case 'element':
                        $teaserElement = $elementService->findElement($teaser->getTypeId());
                        $teaserElementVersion = $elementService->findLatestElementVersion($teaserElement);

                        $cls = '';
                        if (!$teaser->isStopped()) {
                            $cls .= 'inherit ';
                        }
                        if ($teaser->isHidden()) {
                            $cls .= 'dont-show ';
                        }
                        if ($teaser->getTreeId() !== $treeId) {
                            $cls .= 'inherited ';
                        }

                        $teaserData = array_merge(
                            $teaserData,
                            [
                                'text' => $teaserElementVersion->getBackendTitle($language),
                                'icon' => $iconResolver->resolveTeaser($teaser, $language),
                                'eid' => $teaserElement->getEid(),
                                'inherited' => $teaser->getTreeId() !== $treeId,
                                'inherit' => !$teaser->isStopped(),
                                'cls' => trim($cls),
                                'hide' => $teaser->isHidden(),
                            ]
                        );
                        break;

                    default:
                        continue;
                }

                $areaRoot['children'][] = $teaserData;
            }

            if (count($areaRoot['children'])) {
                $areaRoot['leaf'] = false;
            }

            $layouts[] = $areaRoot;
        }

        return new JsonResponse($layouts);
    }
1012060
protected function getRequestOrigin(HTTPRequest $request)
    {
        // Prefer Origin header
        $origin = $request->getHeader('Origin');
        if ($origin) {
            return $origin;
        }

        // Check referer
        $referer = $request->getHeader('Referer');
        if ($referer) {
            // Extract protocol, hostname, and port
            $refererParts = parse_url($referer);
            if (!$refererParts) {
                return null;
            }
            // Rebuild
            $origin = $refererParts['scheme'] . '://' . $refererParts['host'];
            if (isset($refererParts['port'])) {
                $origin .= ':' . $refererParts['port'];
            }
            return $origin;
        }

        return null;
    }
1055017
public function cgetAction(Request $request)
    {
        if (null !== $request->get('fields')) {
            return $this->cgetContent($request);
        }

        return $this->cgetNodes($request);
    }
220681
public function treePageBlock(ServerRequestInterface $request, Tree $tree): ResponseInterface
    {
        $block_id = $request->get('block_id');

        $block_id = (int) DB::table('block')
            ->where('block_id', '=', $block_id)
            ->where('gedcom_id', '=', $tree->id())
            ->value('block_id');

        $module = $this->getBlockModule($tree, $block_id);

        $html = view('layouts/ajax', [
            'content' => $module->getBlock($tree, $block_id, 'gedcom'),
        ]);

        return response($html);
    }
694147
protected function backURLToken(HTTPRequest $request)
    {
        $backURL = $request->getVar('BackURL');
        if (!strstr($backURL, '?')) {
            return null;
        }

        // Filter backURL if it contains the given request parameter
        list(,$query) = explode('?', $backURL);
        parse_str($query, $queryArgs);
        $name = $this->getName();
        if (isset($queryArgs[$name])) {
            return $queryArgs[$name];
        }
        return null;
    }
1098636
public function handle(GetTreeRequest $request)
	{
		if(!tao_helpers_Request::isAjax()){
			throw new common_exception_IsAjaxAction(__FUNCTION__);
		}

		$factory = new GenerisTreeFactory(
			$request->isShowInstance(),
			$request->getOpenNodes(),
			$request->getLimit(),
			$request->getOffset(),
			$request->getResourceUrisToShow(),
			$request->getFilters(),
			$request->getFiltersOptions(),
			[]
		);

		$treeWrapper = new TreeWrapper($factory->buildTree($request->getClass()));

		if ($request->isHideNode()) {
			$treeWrapper = $treeWrapper->getDefaultChildren();
		}

		return $treeWrapper;
	}
901276
public function treeListAction(Request $request)
    {
        if (!$this->getMenuAccess()->canAccessMenuAdmin($this->getCurrentUser())) {
            throw $this->createAccessDeniedException();
        }

        return $this->renderPage('ucms_tree.list_all', $request);
    }
1076717
public function getsubtree($request)
    {
        $html = $this->getSiteTreeFor(
            $this->config()->get('tree_class'),
            $request->getVar('ID'),
            null,
            null,
            null,
            $request->getVar('minNodeCount')
        );

        // Trim off the outer tag
        $html = preg_replace('/^[\s\t\r\n]*<ul[^>]*>/', '', $html);
        $html = preg_replace('/<\/ul[^>]*>[\s\t\r\n]*$/', '', $html);

        return $html;
    }
760238
public function page(ServerRequestInterface $request, Tree $tree): ResponseInterface
    {
        $query = $request->get('query', '');
        $xref  = $request->get('extra', '');

        $source = Source::getInstance($xref, $tree);

        Auth::checkSourceAccess($source);

        $regex_query = preg_quote(strtr($query, [' ' => '.+']), '/');

        // Fetch all records with a link to this source
        $individuals = DB::table('individuals')
            ->join('link', static function (JoinClause $join): void {
                $join
                    ->on('l_file', '=', 'i_file')
                    ->on('l_from', '=', 'i_id');
            })
            ->where('i_file', '=', $tree->id())
            ->where('l_to', '=', $xref)
            ->where('l_type', '=', 'SOUR')
            ->distinct()
            ->select(['individuals.*'])
            ->get()
            ->map(Individual::rowMapper())
            ->filter(GedcomRecord::accessFilter());

        $families = DB::table('families')
            ->join('link', static function (JoinClause $join): void {
                $join
                    ->on('l_file', '=', 'f_file')
                    ->on('l_from', '=', 'f_id')
                    ->where('l_type', '=', 'SOUR');
            })
            ->where('f_file', '=', $tree->id())
            ->where('l_to', '=', $xref)
            ->where('l_type', '=', 'SOUR')
            ->distinct()
            ->select(['families.*'])
            ->get()
            ->map(Family::rowMapper())
            ->filter(GedcomRecord::accessFilter());

        $pages = [];

        foreach ($individuals->merge($families) as $record) {
            if (preg_match_all('/\n1 SOUR @' . $xref . '@(?:\n[2-9].*)*\n2 PAGE (.*' . $regex_query . '.*)/i', $record->gedcom(), $matches)) {
                $pages = array_merge($pages, $matches[1]);
            }

            if (preg_match_all('/\n2 SOUR @' . $xref . '@(?:\n[3-9].*)*\n3 PAGE (.*' . $regex_query . '.*)/i', $record->gedcom(), $matches)) {
                $pages = array_merge($pages, $matches[1]);
            }
        }

        $pages = array_unique($pages);

        $pages = array_map(static function (string $page): array {
            return ['value' => $page];
        }, $pages);

        return response($pages);
    }
997407
protected function getFile(WebRequest $request)
    {
        $path = realpath($this->dirRoot . DIRECTORY_SEPARATOR . $request->getPath());
        if (false === $path) {
            throw new Exceptions\HttpStatusError(
                "File not found.",
                404
            );
        }
        if (is_dir($path)) {
            $path .= DIRECTORY_SEPARATOR . $this->index;
        }
        
        $contents = null;
        $info     = pathinfo($path);
        if ($info["extension"] == "php") {
            ob_start();
            /** @noinspection PhpIncludeInspection */
            include($path);
            $contents = ob_get_contents();
            ob_end_clean();
        } else {
            $contents = file_get_contents($path);
        }
        
        return $contents;
    }
414485
public static function route(Http\Request $request)
    {
        $path = $request->REQUEST_URI;
        $key = $request->getMethod().'@'.$path;
        $keyAny = 'ANY@'.$path;

        $matchedRoute = null;
        $matchedScore = 0;

        if (isset(self::$routes[$key])) {
            $matchedRoute = self::$routes[$key];
        } elseif (isset(self::$routes[$keyAny])) {
            $matchedRoute = self::$routes[$keyAny];
        } else {
            foreach (self::$routes as $key2 => $route) {
                if ($route->getMethod() != 'ANY' && $route->getMethod() != $request->getMethod()) {
                    continue;
                }

                $score = $route->getScore($path, $request->getMethod());
                if ($score > $matchedScore) {
                    $matchedRoute = $route;
                    $matchedScore = $score;
                }
            }
        }

        if ($matchedRoute) {
            $matchedRoute->setUrl($path);
        } elseif (self::$_404route) {
            $matchedRoute = self::$_404route;
        } else {
            throw new Exceptions\RouteException('Route not found');
        }
        return $matchedRoute;
    }
882169
public function run(HTTPRequest $request) {
		$options = $request->getRoute()->getOptions();
		if( empty($options['render']) ) {
			throw new Exception('The StaticPageController requires a render option, add it to your routes configuration.');
		}
		return HTMLHTTPResponse::render($options['render']);
	}
280165
public function get(Request $request)
    {
        $this->collect($request);

        return implode(PHP_EOL, $this->parts);
    }
84909
public function cgetAction(Request $request)
    {
        $locale = $this->getUser()->getLocale();

        if ('true' == $request->get('flat')) {
            /** @var RestHelperInterface $restHelper */
            $restHelper = $this->get('sulu_core.doctrine_rest_helper');

            $fieldDescriptors = $this->getFieldDescriptors();
            $listBuilder = $this->generateFlatListBuilder();
            $restHelper->initializeListBuilder($listBuilder, $fieldDescriptors);
            $this->applyRequestParameters($request, $listBuilder);

            $listResponse = $listBuilder->execute();
            $listResponse = $this->addLogos($listResponse, $locale);

            $list = new ListRepresentation(
                $listResponse,
                self::$entityKey,
                'get_accounts',
                $request->query->all(),
                $listBuilder->getCurrentPage(),
                $listBuilder->getLimit(),
                $listBuilder->count()
            );
            $view = $this->view($list, 200);
        } else {
            $filter = $this->retrieveFilter($request);
            $accountManager = $this->getAccountManager();
            $accounts = $accountManager->findAll($locale, $filter);
            $list = new CollectionRepresentation($accounts, self::$entityKey);
            $view = $this->view($list, 200);
        }

        $context = new Context();
        $context->setGroups(['fullAccount', 'partialContact', 'Default']);
        $view->setContext($context);

        return $this->handleView($view);
    }