<?php
namespace Webkul\UVDesk\SupportCenterBundle\Controller;
use Doctrine\Common\Collections\Criteria;
use Webkul\UVDesk\SupportCenterBundle\Form;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ParameterBag;
use Webkul\UVDesk\SupportCenterBundle\Entity\Article;
use Webkul\UVDesk\SupportCenterBundle\Entity\Solutions;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Webkul\UVDesk\SupportCenterBundle\Entity\ArticleViewLog;
use Webkul\UVDesk\SupportCenterBundle\Entity\SolutionCategory;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Webkul\UVDesk\SupportCenterBundle\Entity\KnowledgebaseWebsite;
use Webkul\UVDesk\CoreFrameworkBundle\Entity\Website as CoreWebsite;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Security;
use Webkul\UVDesk\CoreFrameworkBundle\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Webkul\UVDesk\CoreFrameworkBundle\Entity\SupportRole;
use Webkul\UVDesk\CoreFrameworkBundle\Entity\UserInstance;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\EventDispatcher\GenericEvent;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Webkul\UVDesk\CoreFrameworkBundle\Workflow\Events as CoreWorkflowEvents;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
class Website extends Controller
{
private $visibility = ['public'];
private $limit = 5;
private $company;
private function isKnowledgebaseActive()
{
$entityManager = $this->getDoctrine()->getManager();
$website = $entityManager->getRepository(CoreWebsite::class)->findOneByCode('knowledgebase');
if (!empty($website)) {
$knowledgebaseWebsite = $entityManager->getRepository(KnowledgebaseWebsite::class)->findOneBy(['website' => $website->getId(), 'status' => true]);
if (!empty($knowledgebaseWebsite) && true == $knowledgebaseWebsite->getIsActive()) {
return true;
}
}
throw new NotFoundHttpException('Page Not Found');
}
public function home(Request $request)
{
$user=$this->get('user.service')->getSessionUser();
if(!$user){
return new Response($this->container->get('twig')->render('@UVDeskSupportCenter//Knowledgebase//login.html.twig', [
]));
}
$this->isKnowledgebaseActive();
// Usar vista moderna unificada por defecto (puedes cambiar 'classic' para usar la vieja)
if ($request->query->get('view') != 'classic') {
return $this->modernUnifiedView($request);
}
$parameterBag = [
'visibility' => 'public',
'sort' => 'id',
'direction' => 'desc'
];
$articleRepository = $this->getDoctrine()->getRepository('UVDeskSupportCenterBundle:Article');
$solutionRepository = $this->getDoctrine()->getRepository('UVDeskSupportCenterBundle:Solutions');
$twigResponse = [
'searchDisable' => false,
'popArticles' => $articleRepository->getPopularTranslatedArticles($request->getLocale()),
'solutions' => $solutionRepository->getAllSolutions(new ParameterBag($parameterBag), $this->container, 'a', [1]),
];
$newResult = [];
foreach ($twigResponse['solutions'] as $key => $result) {
$newResult[] = [
'id' => $result->getId(),
'name' => $result->getName(),
'description' => $result->getDescription(),
'visibility' => $result->getVisibility(),
'solutionImage' => ($result->getSolutionImage() == null) ? '' : $result->getSolutionImage(),
'categoriesCount' => $solutionRepository->getCategoriesCountBySolution($result->getId()),
'categories' => $solutionRepository->getCategoriesWithCountBySolution($result->getId()),
'articleCount' => $solutionRepository->getArticlesCountBySolution($result->getId()),
];
}
$twigResponse['solutions']['results'] = $newResult;
$twigResponse['solutions']['categories'] = array_map(function($category) use ($articleRepository) {
$parameterBag = [
'categoryId' => $category['id'],
'status' => 1,
'sort' => 'id',
'limit'=>10,
'direction' => 'desc'
];
$article = $articleRepository->getAllArticles(new ParameterBag($parameterBag), $this->container, 'a.id, a.name, a.slug, a.stared');
return [
'id' => $category['id'],
'name' => $category['name'],
'description' => $category['description'],
'articles' => $article
];
}, $solutionRepository->getAllCategories(10, 2));
$filterArray = ['id' => 5];
$solution = $this->getDoctrine()
->getRepository('UVDeskSupportCenterBundle:Solutions')
->findOneBy($filterArray);
$parameterBag = [
'solutionId' => $solution->getId(),
'status' => 1,
'sort' => 'id',
'direction' => 'desc'
];
$articles = $this->getDoctrine()
->getRepository('UVDeskSupportCenterBundle:Article')
->getAllArticles(new ParameterBag($parameterBag), $this->container, 'a.id, a.name, a.slug, a.stared');
$twigResponse['articles'] = array_reverse($articles);
return $this->render('@UVDeskSupportCenter//Knowledgebase//index.html.twig', $twigResponse);
}
/**
* Vista moderna unificada con navegación tipo Ajax Systems
*/
public function modernUnifiedView(Request $request)
{
$em = $this->getDoctrine()->getManager();
$articleRepository = $this->getDoctrine()->getRepository('UVDeskSupportCenterBundle:Article');
$solutionRepository = $this->getDoctrine()->getRepository('UVDeskSupportCenterBundle:Solutions');
// Obtener TODAS las soluciones activas con visibilidad pública
$parameterBag = [
'visibility' => 'public',
'sort' => 'id',
'direction' => 'asc'
];
$solutions = $solutionRepository->getAllSolutions(new ParameterBag($parameterBag), $this->container, 'a', [1]);
// Obtener TODOS los artículos activos directamente de la base de datos
$qb = $em->createQueryBuilder();
$qb->select('a')
->from('UVDeskSupportCenterBundle:Article', 'a')
->where('a.status = :status')
->setParameter('status', 1)
->orderBy('a.id', 'ASC');
$allArticles = $qb->getQuery()->getResult();
error_log('Total articles found in database: ' . count($allArticles));
$completeStructure = [];
foreach ($solutions as $solution) {
error_log('Processing solution: ' . $solution->getId() . ' - ' . $solution->getName());
$categoriesData = $solutionRepository->getCategoriesWithCountBySolution($solution->getId());
$categories = [];
$allCategorizedArticleIds = [];
$solutionArticleIds = [];
// Obtener artículos de esta solución a través de las categorías
// Solution → SolutionCategoryMapping → Category → ArticleCategory → Article
$qb2 = $em->createQueryBuilder();
$qb2->select('DISTINCT a')
->from('UVDeskSupportCenterBundle:Article', 'a')
->join('UVDeskSupportCenterBundle:ArticleCategory', 'ac', 'WITH', 'a.id = ac.articleId')
->join('UVDeskSupportCenterBundle:SolutionCategoryMapping', 'scm', 'WITH', 'ac.categoryId = scm.categoryId')
->where('a.status = :status')
->andWhere('scm.solutionId = :solutionId')
->setParameter('status', 1)
->setParameter('solutionId', $solution->getId())
->orderBy('a.id', 'ASC');
$solutionArticles = $qb2->getQuery()->getResult();
foreach ($solutionArticles as $article) {
$articleId = $article->getId();
$solutionArticleIds[] = $articleId;
}
error_log('Solution ' . $solution->getId() . ' has ' . count($solutionArticles) . ' articles');
// Procesar categorías
foreach ($categoriesData as $categoryData) {
$qb3 = $em->createQueryBuilder();
$qb3->select('a')
->from('UVDeskSupportCenterBundle:Article', 'a')
->join('UVDeskSupportCenterBundle:ArticleCategory', 'ac', 'WITH', 'a.id = ac.articleId')
->where('a.status = :status')
->andWhere('ac.categoryId = :categoryId')
->setParameter('status', 1)
->setParameter('categoryId', $categoryData['id'])
->orderBy('a.id', 'ASC');
$categoryArticles = $qb3->getQuery()->getResult();
// Formatear artículos para el template
$formattedArticles = [];
foreach ($categoryArticles as $article) {
$allCategorizedArticleIds[] = $article->getId();
$dateAdded = $article->getDateAdded();
$dateAddedFormatted = '';
if ($dateAdded instanceof \DateTime) {
$dateAddedFormatted = $dateAdded->format('d/m/Y');
}
$formattedArticles[] = [
'id' => $article->getId(),
'name' => $article->getName(),
'slug' => $article->getSlug(),
'stared' => $article->getStared(),
'content' => $article->getContent(),
'dateAdded' => $dateAddedFormatted
];
}
error_log('Category ' . $categoryData['id'] . ' (' . $categoryData['name'] . ') has ' . count($formattedArticles) . ' articles');
$categories[] = [
'id' => $categoryData['id'],
'name' => $categoryData['name'],
'description' => $categoryData['description'] ?? '',
'articleCount' => count($formattedArticles),
'articles' => $formattedArticles
];
}
// Obtener artículos directos (sin categoría) de esta solución
$directArticles = [];
foreach ($solutionArticles as $article) {
$articleId = $article->getId();
// Si no está en ninguna categoría y pertenece a esta solución
if (!in_array($articleId, $allCategorizedArticleIds)) {
$dateAdded = $article->getDateAdded();
$dateAddedFormatted = '';
if ($dateAdded instanceof \DateTime) {
$dateAddedFormatted = $dateAdded->format('d/m/Y');
}
$directArticles[] = [
'id' => $article->getId(),
'name' => $article->getName(),
'slug' => $article->getSlug(),
'stared' => $article->getStared(),
'content' => $article->getContent(),
'dateAdded' => $dateAddedFormatted
];
}
}
error_log('Solution ' . $solution->getId() . ' has ' . count($directArticles) . ' direct articles');
$completeStructure[] = [
'id' => $solution->getId(),
'name' => $solution->getName(),
'description' => $solution->getDescription(),
'solutionImage' => $solution->getSolutionImage(),
'categories' => $categories,
'directArticles' => $directArticles,
'totalArticles' => count($solutionArticles)
];
}
// Si se solicita un artículo específico
$selectedArticle = null;
$articleSlug = $request->query->get('article');
if ($articleSlug) {
$article = $articleRepository->findOneBy(['status' => 1, 'slug' => $articleSlug]);
if ($article) {
$selectedArticle = [
'id' => $article->getId(),
'name' => $article->getName(),
'content' => $article->getContent(),
'slug' => $article->getSlug(),
'dateAdded' => $this->get('user.service')->convertToTimezone($article->getDateAdded()),
'articleAuthor' => $articleRepository->getArticleAuthorDetails($article->getId()),
];
}
}
// Obtener artículos para el header (similar a la vista original)
$filterArray = ['id' => 5];
$solutionForArticles = $this->getDoctrine()
->getRepository('UVDeskSupportCenterBundle:Solutions')
->findOneBy($filterArray);
$articles = [];
if ($solutionForArticles) {
$parameterBag = [
'solutionId' => $solutionForArticles->getId(),
'status' => 1,
'sort' => 'id',
'direction' => 'desc'
];
$articles = $this->getDoctrine()
->getRepository('UVDeskSupportCenterBundle:Article')
->getAllArticles(new ParameterBag($parameterBag), $this->container, 'a.id, a.name, a.slug, a.stared');
$articles = array_reverse($articles);
}
// Debug: Log structure count
error_log('Total solutions (folders) found: ' . count($completeStructure));
foreach ($completeStructure as $folder) {
error_log('Folder: ' . $folder['name'] . ' - Categories: ' . count($folder['categories']) . ' - Direct Articles: ' . count($folder['directArticles']));
}
return $this->render('@UVDeskSupportCenter/Knowledgebase/modern-unified.html.twig', [
'structure' => $completeStructure,
'selectedArticle' => $selectedArticle,
'searchDisable' => false,
'articles' => $articles, // Para el header
]);
}
/**
* Cargar artículo vía AJAX para la vista moderna
*/
public function loadArticleAjax(Request $request)
{
$this->isKnowledgebaseActive();
$articleSlug = $request->query->get('slug');
if (!$articleSlug) {
return new JsonResponse(['error' => 'Article slug required'], 400);
}
$articleRepository = $this->getDoctrine()->getRepository('UVDeskSupportCenterBundle:Article');
$article = $articleRepository->findOneBy(['status' => 1, 'slug' => $articleSlug]);
if (!$article) {
return new JsonResponse(['error' => 'Article not found'], 404);
}
$articleAuthor = $articleRepository->getArticleAuthorDetails($article->getId());
// Formatear fecha correctamente
$dateAdded = $article->getDateAdded();
$dateAddedFormatted = '';
if ($dateAdded) {
if ($dateAdded instanceof \DateTime) {
$dateAddedFormatted = $dateAdded->format('d/m/Y');
} else {
// Si es string, intentar convertirlo
try {
$dateObj = new \DateTime($dateAdded);
$dateAddedFormatted = $dateObj->format('d/m/Y');
} catch (\Exception $e) {
$dateAddedFormatted = '';
}
}
}
return new JsonResponse([
'id' => $article->getId(),
'name' => $article->getName(),
'content' => $article->getContent(),
'slug' => $article->getSlug(),
'dateAdded' => $dateAddedFormatted,
'author' => $articleAuthor ? [
'firstName' => $articleAuthor->firstName ?? '',
'lastName' => $articleAuthor->lastName ?? '',
] : null,
]);
}
public function listCategories(Request $request)
{
$this->isKnowledgebaseActive();
$solutionRepository = $this->getDoctrine()->getRepository('UVDeskSupportCenterBundle:Solutions');
$categoryCollection = $solutionRepository->getAllCategories(10, 4);
return $this->render('@UVDeskSupportCenter/Knowledgebase/categoryListing.html.twig', [
'categories' => $categoryCollection,
'categoryCount' => count($categoryCollection),
]);
}
public function changePass($email,$pass)
{
try{
$entityManager = $this->getDoctrine()->getManager();
$user = $entityManager->getRepository('UVDeskCoreFrameworkBundle:User')->findOneByEmail($email) ?: new User();
$encodedPassword = $this->container->get('security.password_encoder')->encodePassword($user, $pass);
$user->setPassword($encodedPassword);
$entityManager->persist($user);
$entityManager->flush();
return $this->render('@UVDeskSupportCenter/Knowledgebase/json.html.twig', ['return'=>'ok']);
}catch(Exception $e){
return $this->render('@UVDeskSupportCenter/Knowledgebase/json.html.twig', ['return'=>$es]);
}
}
public function viewFolder(Request $request)
{
//////////////
//colocar sesion
/////////////
$this->isKnowledgebaseActive();
if(!$request->attributes->get('solution'))
return $this->redirect($this->generateUrl('helpdesk_knowledgebase'));
$filterArray = ['id' => $request->attributes->get('solution')];
$solution = $this->getDoctrine()
->getRepository('UVDeskSupportCenterBundle:Solutions')
->findOneBy($filterArray);
if(!$solution)
$this->noResultFound();
$sesion=null;
if($this->get('user.service')->getSessionUser()!=null)
$sesion=true;
$breadcrumbs = [
[
'label' => $this->get('translator')->trans('Support Center'),
'url' => $this->generateUrl('helpdesk_knowledgebase'),
'sesion'=> $sesion
],
[
'label' => $solution->getName(),
'url' => '#',
'sesion'=> $sesion
],
];
$testArray = [1, 2, 3, 4];
foreach ($testArray as $test) {
$categories[] = [
'id' => $test,
'name' => $test . " name",
'articleCount' => $test . " articleCount",
];
}
return $this->render('@UVDeskSupportCenter//Knowledgebase//folder.html.twig', [
'folder' => $solution,
'categoryCount' => $this->getDoctrine()
->getRepository('UVDeskSupportCenterBundle:Solutions')
->getCategoriesCountBySolution($solution->getId()),
'categories' => $this->getDoctrine()
->getRepository('UVDeskSupportCenterBundle:Solutions')
->getCategoriesWithCountBySolution($solution->getId()),
'breadcrumbs' => $breadcrumbs
]);
}
//////////aca////
public function viewFolderArticle(Request $request)
{
$this->isKnowledgebaseActive();
if(!$request->attributes->get('solution'))
return $this->redirect($this->generateUrl('helpdesk_knowledgebase'));
$filterArray = ['id' => $request->attributes->get('solution')];
$solution = $this->getDoctrine()
->getRepository('UVDeskSupportCenterBundle:Solutions')
->findOneBy($filterArray);
if(!$solution)
$this->noResultFound();
$sesion=null;
if($this->get('user.service')->getSessionUser()!=null)
$sesion=true;
$breadcrumbs = [
[
'label' => $this->get('translator')->trans('Support Center'),
'url' => $this->generateUrl('helpdesk_knowledgebase'),
'sesion'=>$sesion
],
[
'label' => $solution->getName(),
'url' => '#',
'sesion'=>$sesion
],
];
$parameterBag = [
'solutionId' => $solution->getId(),
'status' => 1,
'sort' => 'id',
'direction' => 'desc'
];
$article_data = [
'folder' => $solution,
'articlesCount' => $this->getDoctrine()
->getRepository('UVDeskSupportCenterBundle:Solutions')
->getArticlesCountBySolution($solution->getId(), [1]),
'articles' => $this->getDoctrine()
->getRepository('UVDeskSupportCenterBundle:Article')
->getAllArticles(new ParameterBag($parameterBag), $this->container, 'a.id, a.name, a.slug, a.stared'),
'breadcrumbs' => $breadcrumbs,
];
return $this->render('@UVDeskSupportCenter/Knowledgebase/folderArticle.html.twig', $article_data);
}
public function viewCategory(Request $request)
{
$this->isKnowledgebaseActive();
if(!$request->attributes->get('category'))
return $this->redirect($this->generateUrl('helpdesk_knowledgebase'));
$filterArray = array(
'id' => $request->attributes->get('category'),
'status' => 1,
);
$category = $this->getDoctrine()
->getRepository('UVDeskSupportCenterBundle:SolutionCategory')
->findOneBy($filterArray);
if(!$category)
$this->noResultFound();
$sesion=null;
if($this->get('user.service')->getSessionUser()!=null)
$sesion=true;
$breadcrumbs = [
[ 'label' => $this->get('translator')->trans('Support Center'),'url' => $this->generateUrl('helpdesk_knowledgebase'),'sesion'=>$sesion ],
[ 'label' => $category->getName(),'url' => '#','sesion'=>$sesion ],
];
$parameterBag = [
'categoryId' => $category->getId(),
'status' => 1,
'sort' => 'id',
'direction' => 'desc'
];
$category_data= array(
'category' => $category,
'articlesCount' => $this->getDoctrine()
->getRepository('UVDeskSupportCenterBundle:SolutionCategory')
->getArticlesCountByCategory($category->getId(), [1]),
'articles' => $this->getDoctrine()
->getRepository('UVDeskSupportCenterBundle:Article')
->getAllArticles(new ParameterBag($parameterBag), $this->container, 'a.id, a.name, a.slug, a.stared'),
'breadcrumbs' => $breadcrumbs
);
return $this->render('@UVDeskSupportCenter/Knowledgebase/category.html.twig',$category_data);
}
public function viewArticle(Request $request)
{
$this->isKnowledgebaseActive();
if (!$request->attributes->get('article') && !$request->attributes->get('slug')) {
return $this->redirect($this->generateUrl('helpdesk_knowledgebase'));
}
$entityManager = $this->getDoctrine()->getManager();
$user = $this->get('user.service')->getCurrentUser();
$articleRepository = $entityManager->getRepository('UVDeskSupportCenterBundle:Article');
if ($request->attributes->get('article')) {
$article = $articleRepository->findOneBy(['status' => 1, 'id' => $request->attributes->get('article')]);
} else {
$article = $articleRepository->findOneBy(['status' => 1,'slug' => $request->attributes->get('slug')]);
}
if (empty($article)) {
$this->noResultFound();
}
$article->setViewed((int) $article->getViewed() + 1);
// Log article view
$articleViewLog = new ArticleViewLog();
$articleViewLog->setUser(($user != null && $user != 'anon.') ? $user : null);
$articleViewLog->setArticle($article);
$articleViewLog->setViewedAt(new \DateTime('now'));
$entityManager->persist($article);
$entityManager->persist($articleViewLog);
$entityManager->flush();
// Get article feedbacks
$feedbacks = ['enabled' => false, 'submitted' => false, 'article' => $articleRepository->getArticleFeedbacks($article)];
if (!empty($user) && $user != 'anon.') {
$feedbacks['enabled'] = true;
if (!empty($feedbacks['article']['collection']) && in_array($user->getId(), array_column($feedbacks['article']['collection'], 'user'))) {
$feedbacks['submitted'] = true;
}
}
$sesion=null;
if($this->get('user.service')->getSessionUser()!=null)
$sesion=true;
// @TODO: App popular articles
$article_details = [
'article' => $article,
'breadcrumbs' => [
['label' => $this->get('translator')->trans('Support Center'), 'url' => $this->generateUrl('helpdesk_knowledgebase'),'sesion'=>$sesion],
['label' => $article->getName(), 'url' => '#','sesion'=>$sesion]
],
'dateAdded' => $this->get('user.service')->convertToTimezone($article->getDateAdded()),
'articleTags' => $articleRepository->getTagsByArticle($article->getId()),
'articleAuthor' => $articleRepository->getArticleAuthorDetails($article->getId()),
'relatedArticles' => $articleRepository->getAllRelatedyByArticle(['locale' => $request->getLocale(), 'articleId' => $article->getId()], [1]),
'popArticles' => $articleRepository->getPopularTranslatedArticles($request->getLocale())
];
return $this->render('@UVDeskSupportCenter/Knowledgebase/article.html.twig',$article_details);
}
public function searchKnowledgebase(Request $request)
{
$this->isKnowledgebaseActive();
$searchQuery = $request->query->get('s');
if (empty($searchQuery)) {
return $this->redirect($this->generateUrl('helpdesk_knowledgebase'));
}
$articleCollection = $this->getDoctrine()->getRepository('UVDeskSupportCenterBundle:Article')->getArticleBySearch($request);
return $this->render('@UVDeskSupportCenter/Knowledgebase/search.html.twig', [
'search' => $searchQuery,
'articles' => $articleCollection,
]);
}
public function viewTaggedResources(Request $request)
{
$this->isKnowledgebaseActive();
$tagQuery = $request->attributes->get('tag');
if (empty($tagQuery)) {
return $this->redirect($this->generateUrl('helpdesk_knowledgebase'));
}
$tagLabel = $request->attributes->get('name');
$articleCollection = $this->getDoctrine()->getRepository('UVDeskSupportCenterBundle:Article')->getArticleByTags([$tagLabel]);
$sesion=null;
if($this->get('user.service')->getSessionUser()!=null)
$sesion=true;
return $this->render('@UVDeskSupportCenter/Knowledgebase/search.html.twig', [
'articles' => $articleCollection,
'search' => $tagLabel,
'breadcrumbs' => [
['label' => $this->get('translator')->trans('Support Center'), 'url' => $this->generateUrl('helpdesk_knowledgebase'),'sesion'=>$sesion],
['label' => $tagLabel, 'url' => '#','sesion'=>$sesion],
],
]);
}
public function rateArticle($articleId, Request $request)
{
$this->isKnowledgebaseActive();
// @TODO: Refactor
// if ($request->getMethod() != 'POST') {
// return $this->redirect($this->generateUrl('helpdesk_knowledgebase'));
// }
// $company = $this->getCompany();
// $user = $this->container->get('user.service')->getCurrentUser();
$response = ['code' => 404, 'content' => ['alertClass' => 'danger', 'alertMessage' => 'An unexpected error occurred. Please try again later.']];
// if (!empty($user) && $user != 'anon.') {
// $entityManager = $this->getDoctrine()->getEntityManager();
// $article = $entityManager->getRepository('WebkulSupportCenterBundle:Article')->findOneBy(['id' => $articleId, 'companyId' => $company->getId()]);
// if (!empty($article)) {
// $providedFeedback = $request->request->get('feedback');
// if (!empty($providedFeedback) && in_array(strtolower($providedFeedback), ['positive', 'neagtive'])) {
// $isArticleHelpful = ('positive' == strtolower($providedFeedback)) ? true : false;
// $articleFeedback = $entityManager->getRepository('WebkulSupportCenterBundle:ArticleFeedback')->findOneBy(['article' => $article, 'ratedCustomer' => $user]);
// $response = ['code' => 200, 'content' => ['alertClass' => 'success', 'alertMessage' => 'Feedback saved successfully.']];
// if (empty($articleFeedback)) {
// $articleFeedback = new \Webkul\SupportCenterBundle\Entity\ArticleFeedback();
// // $articleBadge->setDescription('');
// $articleFeedback->setIsHelpful($isArticleHelpful);
// $articleFeedback->setArticle($article);
// $articleFeedback->setRatedCustomer($user);
// $articleFeedback->setCreatedAt(new \DateTime('now'));
// } else {
// $articleFeedback->setIsHelpful($isArticleHelpful);
// $response['content']['alertMessage'] = 'Feedback updated successfully.';
// }
// $entityManager->persist($articleFeedback);
// $entityManager->flush();
// } else {
// $response['content']['alertMessage'] = 'Invalid feedback provided.';
// }
// } else {
// $response['content']['alertMessage'] = 'Article not found.';
// }
// } else {
// $response['content']['alertMessage'] = 'You need to login to your account before can perform this action.';
// }
return new Response(json_encode($response['content']), $response['code'], ['Content-Type: application/json']);
}
/**
* @Route("/api/knowledgebase/documents", name="helpdesk_knowledgebase_documents_api", methods={"GET", "OPTIONS"})
*/
public function getKnowledgebaseDocuments(Request $request)
{
$this->isKnowledgebaseActive();
$entityManager = $this->getDoctrine()->getManager();
$articleRepository = $entityManager->getRepository('UVDeskSupportCenterBundle:Article');
// Obtener todos los artículos activos
$query = $entityManager->createQueryBuilder()
->select('a')
->from('UVDeskSupportCenterBundle:Article', 'a')
->where('a.status = :status')
->setParameter('status', 1);
// Ejecutar la consulta para obtener todos los artículos
$articles = $query->getQuery()->getResult();
// Formatear los resultados
$documents = [];
$searchQuery = $request->query->get('search');
$searchPerformed = !empty($searchQuery);
foreach ($articles as $article) {
// Obtener el contenido del artículo
$content = $article->getContent();
// Inicializar variables
$documentName = 'TEC' . $article->getId() . ' - ' . $article->getName();
$documentUrl = null;
$linkText = '';
$includeDocument = true;
// Información de depuración
$contentDebug = [
'articleId' => $article->getId(),
'hasContent' => !empty($content),
'contentLength' => !empty($content) ? strlen($content) : 0,
];
// Buscar enlaces .pdf en el contenido
if (!empty($content)) {
// Vista previa del contenido
$contentPreview = substr($content, 0, 300) . (strlen($content) > 300 ? '...' : '');
$contentDebug['contentPreview'] = $contentPreview;
// Contar menciones de PDF y enlaces
$contentDebug['pdfMentions'] = substr_count(strtolower($content), '.pdf');
$contentDebug['linkMentions'] = substr_count(strtolower($content), 'href=');
// Buscar enlaces dentro de etiquetas <a href>
preg_match_all('/<a\s+[^>]*href=["\']([^"\']+)["\'][^>]*>([^<]+)<\/a>/i', $content, $matches);
if (!empty($matches[1])) {
// Filtrar solo los enlaces relevantes (PDF o softguardtv.com o otros recursos)
$relevantLinks = [];
$relevantTexts = [];
foreach ($matches[1] as $index => $link) {
// Aceptar si es un PDF o contiene softguardtv.com o knowledge
if (preg_match('/\.pdf$/i', $link) ||
strpos($link, 'softguardtv.com') !== false ||
strpos($link, 'knowledge') !== false ||
strpos($link, 'courses') !== false ||
strpos($link, 'lectures') !== false) {
$relevantLinks[] = $link;
$relevantTexts[] = $matches[2][$index] ?? '';
}
}
// Guardar enlaces y textos relevantes
if (!empty($relevantLinks)) {
$contentDebug['foundLinks'] = $relevantLinks;
$contentDebug['linkTexts'] = $relevantTexts;
// Usar el primer enlace encontrado
$documentUrl = $relevantLinks[0];
$linkText = !empty($relevantTexts[0]) ? trim($relevantTexts[0]) : '';
// Usar texto del enlace como nombre
if (!empty($linkText)) {
$documentName = $linkText;
}
}
} else {
// Búsqueda alternativa para URLs
preg_match_all('/(https?:\/\/[^\s"\'<>]+)/i', $content, $altMatches);
if (!empty($altMatches[0])) {
// Filtrar enlaces relevantes
$relevantLinks = [];
foreach ($altMatches[0] as $link) {
if (preg_match('/\.pdf$/i', $link) ||
strpos($link, 'softguardtv.com') !== false ||
strpos($link, 'knowledge') !== false ||
strpos($link, 'courses') !== false ||
strpos($link, 'lectures') !== false) {
$relevantLinks[] = $link;
}
}
if (!empty($relevantLinks)) {
$contentDebug['foundLinks'] = $relevantLinks;
$documentUrl = $relevantLinks[0];
}
}
}
// Si se está realizando una búsqueda, verificar si el término está en el contenido
if ($searchPerformed) {
// Buscar en el contenido completo (incluye texto y enlaces)
$includeDocument = (
stripos($content, $searchQuery) !== false ||
stripos($documentName, $searchQuery) !== false ||
(!empty($documentUrl) && stripos($documentUrl, $searchQuery) !== false) ||
(!empty($linkText) && stripos($linkText, $searchQuery) !== false)
);
$contentDebug['searchPerformed'] = true;
$contentDebug['searchTerm'] = $searchQuery;
$contentDebug['matchFound'] = $includeDocument;
}
}
// Si no se encontró URL, usar formato estándar
if (empty($documentUrl)) {
$baseDocumentName = $article->getName();
$documentUrl = 'https://softguard.com/knowledge/TEC' . $article->getId() . '_' . $baseDocumentName . '.pdf';
$contentDebug['usingFallbackUrl'] = true;
}
// Solo incluir el documento si pasa los filtros de búsqueda
if ($includeDocument) {
$documents[] = [
'id' => $article->getId(),
'name' => $documentName,
'url' => $documentUrl,
'views' => $article->getViewed(),
'dateAdded' => $article->getDateAdded() ? $article->getDateAdded()->format('Y-m-d H:i:s') : null,
'contentDebug' => $contentDebug
];
}
}
// Ordenar por popularidad (vistas)
usort($documents, function($a, $b) {
return $b['views'] - $a['views'];
});
// Devolver respuesta JSON
return new JsonResponse([
'success' => true,
'documents' => $documents,
'totalFound' => count($documents),
'searchQuery' => $searchQuery
]);
}
/**
* Función auxiliar para convertir texto en un slug
*/
private function slugify($text)
{
// Reemplazar espacios con guiones bajos
$text = str_replace(' ', '_', $text);
// Eliminar caracteres especiales
$text = preg_replace('/[^A-Za-z0-9\-_]/', '', $text);
// Convertir a minúsculas
return strtolower($text);
}
}