<?php
namespace App\Controller;
use Pimcore\Controller\FrontendController;
use Pimcore\Model\Element\Tag\Listing;
use Pimcore\Model\DataObject;
use Pimcore\Model\DataObject\RdResourceItem;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Website\LinkGenerator\RdResourceLinkGenerator;
use App\Website\Navigation\BreadcrumbHelperService;
use Knp\Component\Pager\PaginatorInterface;
use Pimcore\Twig\Extension\Templating\HeadTitle;
use Pimcore\Twig\Extension\Templating\Placeholder;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Elasticsearch\Client;
class RdResourceController extends BaseController
{
const RDRESOURCE_DEFAULT_DOCUMENT_PROPERTY_NAME = 'rdresource_default_document';
/**
* @param Request $request
*
* @return Response
*
* @throws \Exception
*/
public function listingAction(Request $request, PaginatorInterface $paginator)
{
$contributor = $request->query->get('contributor');
$project = $request->query->get('project');
$tree = $request->query->get('tree');
$rtag = $request->query->get('tag');
$filterquery = "";
$filters = [];
$contributorsquery = "";
$projectsquery = "";
$typesquery = "";
$stquery = "";
$valuequery = [];
$sort = $request->query->get('sort');
$st = $request->query->get('st');
$keywords = $request->query->get('keywords');
$type = $request->query->get('type');
parse_str($_SERVER['QUERY_STRING'], $qsarr);
$qslink = "";
if ($qsarr) {
foreach ($qsarr as $k => $v) {
if ($k != "tree" && $k != "page" && $k != "rtag") {
$qslink .= "&" . $k . "=" . $v;
}
}
}
// TAG LIST FOR STRUCTURE (TOPIC) BROWSING
// Get structure tags
$tagList = new \Pimcore\Model\Element\Tag\Listing();
//select parent node for tags or use all root tags.
$tagList->setCondition("parentId = 9");
$tagList->setOrderKey("name");
$tags = [];
$nodes = [];
$nodes[] = 9;
foreach ($tagList->load() as $tag) {
$tags[] = $this->convertTagToArray($tag, $nodes);
}
// STANDARD FILTER/SEARCH QUERIES
$rdResourceListing = new RdResourceItem\Listing();
if ($sort == "date ASC") {
$rdResourceListing->setOrderKey('registered_date');
$rdResourceListing->setOrder('ASC');
} elseif ($sort == "title") {
$rdResourceListing->setOrderKey('title');
$rdResourceListing->setOrder('ASC');
} else {
$rdResourceListing->setOrderKey('registered_date');
$rdResourceListing->setOrder('DESC');
}
if ($st) {
$valuequery[":st"] = "%" . $st . "%";
$stquery = "(contributors LIKE :st ";
$stquery .= " OR title LIKE :st";
$stquery .= " OR author LIKE :st";
$stquery .= " OR resource_format LIKE :st";
$stquery .= " OR user_institutions LIKE :st";
$stquery .= " OR contributors LIKE :st";
$stquery .= " OR other_contributors LIKE :st";
$stquery .= " OR project LIKE :st";
$stquery .= " OR licence LIKE :st";
$stquery .= " OR resource_usage LIKE :st";
$stquery .= " OR interoperability LIKE :st";
$stquery .= " OR standards LIKE :st";
$stquery .= " OR description LIKE :st";
$stquery .= ")";
$filters["st"] = $stquery;
}
if ($keywords) {
/*
$valuequery[":kw"] = "%;" . $keywords . ";%";
$kwquery = "(CONCAT(';',REPLACE(keywords, '; ', ';'),';') LIKE :kw)";
$filters["keywords"] = $kwquery;
*/
}
if ($contributor) {
$contributorsquery .= "(contributors LIKE :contributors)";
$valuequery[":contributors"] = "%" . $contributor . "%";
$filters["contributors"] = $contributorsquery;
}
if ($project) {
$projectsquery .= "(project LIKE :projects)";
$valuequery[":projects"] = "%" . $project . "%";
$filters["projects"] = $projectsquery;
}
if ($type) {
$typesquery .= "(resource_type LIKE :type)";
$valuequery[":type"] = "%" . $type . "%";
$filters["types"] = $typesquery;
}
$filterquery = implode(" AND ", $filters);
// print_r($filterquery);
//print_r($valuequery);
// print_r($stquery);
// $rdResourceListing->setCondition("topics LIKE :topics1 OR topics LIKE :topics2", ["topics1" => "%Data management%", "topics2" => "%Data discovery%"]);
if ($filterquery != "") {
$rdResourceListing->setCondition($filterquery, $valuequery);
}
// Filter by tags
$treevalues = $request->get('tree');
$treevalues = is_array($treevalues) ? $treevalues : explode(',', $treevalues);
$rtagname="";
if ($treevalues) {
$conditionParts = [];
foreach ($treevalues as $tagId) {
$tag = \Pimcore\Model\Element\Tag::getById($tagId);
if ($tag) {
//get ID path of tag or filtering the child tags
$tagPath = $tag->getFullIdPath();
$conditionParts[] = "o_id IN (
SELECT cid FROM tags_assignment INNER JOIN tags ON tags.id = tags_assignment.tagid
WHERE
ctype = 'object' AND
(tags.id = " . $tagId . " OR tags.idPath LIKE '" . $tagPath . "%'))";
}
}
}
$rtag = $request->get('rtag');
if ($rtag) {
$conditionParts = [];
$tag = \Pimcore\Model\Element\Tag::getById($rtag);
if ($tag) {
//get ID path of tag or filtering the child tags
$rtagid = $tag->getId();
$conditionParts[] = "o_id IN (
SELECT cid FROM tags_assignment INNER JOIN tags ON tags.id = tags_assignment.tagid
WHERE
ctype = 'object' AND
tags.id = " . $rtagid . ")";
}
$rtagname = $tag->getName();
}
if (count($conditionParts) > 0) {
$condition = implode(" AND ", $conditionParts);
$rdResourceListing->addConditionParam($condition);
}
$paginator = $paginator->paginate(
$rdResourceListing,
$request->get('page', 1),
10
);
// END STANDARD FILTER/SEARCH QUERIES
// FILTER OPTIONS
$sampleresource = new RdResourceItem();
$availableFilters = [];
$contributorsDef = $sampleresource->getClass()->getFieldDefinition("contributors");
$contributorsOptions = $contributorsDef->getOptions();
$projectsDef = $sampleresource->getClass()->getFieldDefinition("project");
$projectsOptions = $projectsDef->getOptions();
$typesDef = $sampleresource->getClass()->getFieldDefinition("resource_type");
$typesOptions = $typesDef->getOptions();
$pqListing = new RdResourceItem\Listing();
$contributorsFinalOptions = [];
$projectsFinalOptions = [];
$typesFinalOptions = [];
foreach ($contributorsOptions as $contributorsOption) {
$pqListing->setCondition("contributors LIKE :contribs", ["contribs" => "%" . $contributorsOption["value"] . "%"]);
if (count($pqListing)) {
$contributorsFinalOptions[] = $contributorsOption;
}
}
foreach ($projectsOptions as $projectsOption) {
$pqListing->setCondition("project LIKE :projects", ["projects" => "%" . $projectsOption["value"] . "%"]);
if (count($pqListing)) {
$projectsFinalOptions[] = $projectsOption;
}
}
foreach ($typesOptions as $typesOption) {
$pqListing->setCondition("resource_type LIKE :type", ["type" => "%" . $typesOption["value"] . "%"]);
if (count($pqListing)) {
$typesFinalOptions[] = $typesOption;
}
}
// END FILTER OPTIONS
// PREQUERIES FOR FACETTED SEARCH
//$qb = $entityManager->createQueryBuilder();
//$qb->select('count(account.id)');
//$qb->from('ZaysoCoreBundle:Account','account');
// END PREQUERIES FOR FACETTED SEARCH
return $this->render('rdresource/listing.html.twig', [
'rdResourceListing' => $paginator,
'paginationVariables' => $paginator->getPaginationData(),
'topics' => $request->query->get('topics'),
'keywords' => $request->query->get('keywords'),
'contributorsvalues' => $request->query->get('contributor'),
'typesvalues' => $request->query->get('type'),
'projectsvalues' => $request->query->get('project'),
'st' => $request->query->get('st'),
'sort' => $sort,
'rtag' => $rtag,
'rtagname' => $rtagname,
'contributors_options' => $contributorsFinalOptions,
'types_options' => $typesFinalOptions,
'projects_options' => $projectsFinalOptions,
'tags' => $tags,
'treevalues' => $request->query->get('tree'),
'qs' => $_SERVER['QUERY_STRING'],
'qslink' => $qslink
]);
// return $this->render('resource/listing.html.twig', ['rdResourceListing' => $rdResourceListing]);
}
/**
* @Route("{path}/{rdresourcetitle}-crdr-{rdresource}", name="rdresource-detail", defaults={"path"=""}, requirements={"path"=".*?", "rdresourcetitle"="[\w-]+", "rdresource"="\d+"})
*
* @param Request $request
* @param HeadTitle $headTitleHelper
* @param Placeholder $placeholderHelper
* @param RdResourceLinkGenerator $rdResourceLinkGenerator
* @param BreadcrumbHelperService $breadcrumbHelperService
*
* @return Response
*/
public function detailAction(Request $request, HeadTitle $headTitleHelper, Placeholder $placeholderHelper, RdResourceLinkGenerator $rdResourceLinkGenerator, BreadcrumbHelperService $breadcrumbHelperService)
{
$rdresource = RdResourceItem::getById($request->get('rdresource'));
if (!($rdresource instanceof RdResourceItem && ($rdresource->isPublished() || $this->verifyPreviewRequest($request, $rdresource)))) {
throw new NotFoundHttpException('Resource not found.');
}
$breadcrumbHelperService->enrichRdResourcePage($rdresource);
$resourcetags = \Pimcore\Model\Element\Tag::getTagsForElement('object', $rdresource->getId());
$rtags = array();
foreach ($resourcetags as $rtag) {
if ($rtag->getParentId() == 10) {
$rtags[] = $rtag;
}
}
$placeholderHelper('canonical')->set($rdResourceLinkGenerator->generate($rdresource, ['document' => $this->document->getProperty(self::RDRESOURCE_DEFAULT_DOCUMENT_PROPERTY_NAME)]));
$headTitleHelper($rdresource->getTitle());
$contributorOptions = DataObject\Service::getOptionsForMultiSelectField($rdresource, "contributors");
return $this->render('rdresource/detail.html.twig', [
'rdresource' => $rdresource,
'tags' => $rtags,
'qs' => $_SERVER['QUERY_STRING'],
'contributorOptions' => $contributorOptions
]);
}
/**
* Function to convert tags to an array that is expected by bootstrap tree view
*/
protected function convertTagToArray(\Pimcore\Model\Element\Tag $tag, $assignedTagIds)
{
$tagArray = [
"id" => $tag->getId(),
"path" => $tag->getIdPath(),
"fullpath" => $tag->getFullIdPath(),
"parentid" => $tag->getParentId(),
"text" => $tag->getName()
];
$state = [];
$state["checked"] = array_search($tag->getId(), $assignedTagIds) !== false;
$tagArray["state"] = $state;
$children = $tag->getChildren();
foreach ($children as $child) {
$childrenNodes = $this->convertTagToArray($child, $assignedTagIds);
if ($this->hasCheckedNodes($childrenNodes)) {
$tagArray["state"]["expanded"] = true;
}
$tagArray['nodes'][] = $childrenNodes;
}
return $tagArray;
}
protected function hasCheckedNodes($nodesArray)
{
$it = new \RecursiveIteratorIterator(
new \ParentIterator(new \RecursiveArrayIterator($nodesArray)),
\RecursiveIteratorIterator::SELF_FIRST
);
foreach ($it as $key => $value) {
if ($key == 'state' && $value['checked']) {
return true;
}
}
return false;
}
}