Controller/WikiTagController.php
author cavaliet
Tue, 25 Oct 2011 12:20:47 +0200
changeset 13 c288952a089f
parent 12 81cc9274c20a
child 14 673b2766024e
permissions -rwxr-xr-x
Remove WP link from tag list now works.

<?php
/*
 * This file is part of the WikiTagBundle package.
*
* (c) IRI <http://www.iri.centrepompidou.fr/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace IRI\Bundle\WikiTagBundle\Controller;

use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\DBAL\DriverManager;

use IRI\Bundle\WikiTagBundle\Entity\DocumentTag;
use IRI\Bundle\WikiTagBundle\Entity\Tag;
use IRI\Bundle\WikiTagBundle\Utils\WikiTagUtils;
use Pagerfanta\Pagerfanta;
use Pagerfanta\Adapter\ArrayAdapter;
use Pagerfanta\Adapter\DoctrineORMAdapter;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;


class WikiTagController extends Controller
{
    private static $SEARCH_STAR_CHARACTER = "*";
    
    /**
     * Fake index action
     */
    public function indexAction()
    {
        return new Response('<html><body>Nothing to see here.</body></html>');
    }

    /**
     * Renders the little html to add the css
     */
    public function addCssAction()
    {
        return $this->render('WikiTagBundle:WikiTag:css.html.twig');
    }

    /**
     * Renders the little html to add the javascript
     * TODO: review why this injection in javascript, t10n?
     */
    public function addJavascriptAction()
    {
        $cats = $this->getDoctrine()->getRepository('WikiTagBundle:Category')->findOrderedCategories();
        // $cats is {"Label":"Créateur"},{"Label":"Datation"},...
        $nbCats = count($cats);
        $ar = array('' => '');
        for($i=0;$i<$nbCats;$i++){
            $temp = array($cats[$i]["label"] => $cats[$i]["label"]);
            $ar = array_merge($ar, $temp);
        }
        // ... so we create is json like {"":""},{"Créateur":"Créateur"},{"Datation":"Datation"},...
        $categories = json_encode($ar);
        return $this->render('WikiTagBundle:WikiTag:javascript.html.twig', array('categories' => $categories));
    }

    /**
     * Display a list of ordered tag for a document
     * @param integer $id_doc
     */
    public function documentTagsAction($id_doc)
    {
        $ordered_tags = $this->getDoctrine()->getRepository('WikiTagBundle:DocumentTag')->findOrderedTagsForDoc($id_doc);
        return $this->render('WikiTagBundle:WikiTag:documentTags.html.twig', array('ordered_tags' => $ordered_tags, 'doc_id' => $id_doc));
    }

    /**
     *
     * TODO : Enter description here ...
     * @return \Symfony\Bundle\FrameworkBundle\Controller\Response
     */
    public function tagUpDownAction()
    {

        $req = $this->getRequest()->request;
        $id_doc = $req->get('wikitag_document_id');
        // post vars new_order and old_order indicate the position (from 1) of the tag in the list.
        // NB : it is different from the DocumentTag.order in the database.
        $new_order = intval($req->get('new_order')) - 1;
        $old_order = intval($req->get('old_order')) - 1;
        // First we get the DocumentTags
        $em = $this->getDoctrine()->getEntityManager();
        $ordered_tags = $this->getDoctrine()->getRepository('WikiTagBundle:DocumentTag')->findOrderedTagsForDoc($id_doc);
        // We change the moved DocumentTag's order
        $new_dt_order = $ordered_tags[$new_order]->getTagOrder();
        $moved_dt = $ordered_tags[$old_order];
        $moved_dt->setTagOrder($new_dt_order);
        // We move the TaggedSheets's order
        if($new_order > $old_order){
            // And we decrease the other ones
            for ($i=($old_order+1); $i <= ($new_order); $i++){
                $dt = $ordered_tags[$i];
                $dt->setTagOrder($dt->getTagOrder() - 1);
            }
        }
        else{
            // And we increase the other ones
            for ($i=$new_order; $i <= ($old_order-1); $i++){
                $dt = $ordered_tags[$i];
                $dt->setTagOrder($dt->getTagOrder() + 1);
            }
        }
        // Save datas.
        $em->flush();

        return $this->renderDocTags($id_doc);
    }

    /**
     *
     * TODO: Enter description here ...
     * @return \Symfony\Bundle\FrameworkBundle\Controller\Response
     */
    public function removeTagFromListAction()
    {
        $id_doc = $this->getRequest()->request->get('wikitag_document_id');
        $id_tag = $this->getRequest()->request->get('tag_id');
        // We get the DocumentTag meant to be deleted, and remove it.
        $em = $this->getDoctrine()->getEntityManager();
        $dt = $this->getDoctrine()->getRepository('WikiTagBundle:DocumentTag')->findOneBy(array('tag' => $id_tag, 'document' => $id_doc));
        $em->remove($dt);
        $em->flush();

        return $this->renderDocTags($id_doc);
    }

    /**
     *
     * TODO: Enter description here ...
     */
    public function modifyDocumentTagAction()
    {
        $id_doc = $this->getRequest()->request->get('wikitag_document_id');
        $tag_label = $this->getRequest()->request->get('value');
        $id_moved_tag = $this->getRequest()->request->get('id');
        $moved_tag = $this->getDoctrine()->getRepository('WikiTagBundle:Tag')->findOneBy(array('id' => $id_moved_tag));
        if($tag_label!=$moved_tag->getLabel()){
            // We get the DocumentTags
            $em = $this->getDoctrine()->getEntityManager();
            $tags = $this->getDoctrine()->getRepository('WikiTagBundle:DocumentTag')->findBy(array('document' => $id_doc));
            $nb_tags = count($tags);
            $found = false;
            $i = 0;
            while($i<$nb_tags && $found==false){
                $dt = $tags[$i];
                if(strtolower($dt->getTag()->getLabel())==strtolower($tag_label)){
                    $found = true;
                }
                $i++;
            }
            // If the label was found, we sent a bad request
            if($found==true){
                return new Response(json_encode(array('error' => 'duplicate_tag', 'message' => sprintf("Le tag %s existe déjà pour cette fiche.", $tag_label))),400);
            }
            // We create the new tag or get the already existing tag. $tag, $revision_id, $created
            $ar = WikiTagUtils::getOrCreateTag($tag_label, $this->getDoctrine());// tag, revision_id, created = get_or_create_tag(tag_label)
            $tag = $ar[0];
            $revision_id = $ar[1];
            $created = $ar[2];
            // We get the DocumentTag and change its tag
            $dt = $this->getDoctrine()->getRepository('WikiTagBundle:DocumentTag')->findOneBy(array('document' => $id_doc, 'tag' => $id_moved_tag));
            $dt->setTag($tag);
            $dt->setWikipediaRevisionId($revision_id);
            //
            // HERE QUERY TO GET A INDEX_NOTE/SCORE for the tag. Here is python code :
            //kwargs = {DJANGO_ID + "__exact": unicode(ds_id)}
            //results = SearchQuerySet().filter(title=tag_label).filter_or(description=tag_label).filter(**kwargs)
            //if len(results) > 0:
            //    ts.index_note = results[0].score
            //
            // We save the datas
            $doc = $this->getDoctrine()->getRepository('WikiTagBundle:Document')->findOneBy(array('id' => $id_doc));
            $doc->setManualOrder(true);
            $em->flush();
        }

        return $this->renderDocTags($id_doc);
    }

    /**
     *
     * @Route("/wtrtd")
     * TODO : Enter description here ...
     * TODO : implement
     */
    public function reorderTagDocumentAction()
    {
        $id_Doc = $this->getRequest()->request->get('wikitag_document_id');
        return $this->renderDocTags($id_doc);
    }

    /**
     *
     * TODO: Enter description here ...
     */
    public function addTagAction()
    {
        $id_doc = $this->getRequest()->request->get('wikitag_document_id');
        $tag_label = $this->getRequest()->request->get('value');
        // We get the DocumentTags
        $em = $this->getDoctrine()->getEntityManager();
        $tags = $this->getDoctrine()->getRepository('WikiTagBundle:DocumentTag')->findByDocumentExternalId($id_doc);
        $nb_tags = count($tags);
        $found = false;
        $i = 0;
        while($i<$nb_tags && $found==false){
            $dt = $tags[$i];
            if(strtolower($dt->getTag()->getLabel())==strtolower($tag_label)){
                $found = true;
            }
            $i++;
        }
        // If the label was found, we sent a bad request
        if($found==true){
            //TODO : translation
            return new Response(json_encode(array('error' => 'duplicate_tag', 'message' => sprintf("Le tag %s existe déjà pour cette fiche.", $tag_label))),400);
        }
        // returns array($tag, $revision_id, $created)
        $ar = WikiTagUtils::getOrCreateTag($tag_label, $this->getDoctrine());// tag, revision_id, created = get_or_create_tag(tag_label)
        $tag = $ar[0];
        $revision_id = $ar[1];
        $created = $ar[2];
        
        $tags = $this->getDoctrine()->getRepository('WikiTagBundle:DocumentTag')->findByDocumentExternalId($id_doc, array('tag'=>$tag->getId()));
        $nb_tags = count($tags);

        if($created==true || $nb_tags==0){
            $new_order_ar = $this->getDoctrine()->getRepository('WikiTagBundle:DocumentTag')->getMaxOrder($id_doc);
            // The result is a double array. And reset(reset($newOrderAr)) is not allowed. And a string is returned.
            $a1 = reset($new_order_ar);
            $new_order = intval(reset($a1)) + 1;
            // TODO: use a factory that returns an DocumentTagInterface
            $new_DT = new DocumentTag();
            $new_DT->setDocument($this->getDoctrine()->getRepository('WikiTagBundle:Document')->findOneByExternalId($id_doc));
            $new_DT->setTag($tag);
            $new_DT->setOriginalOrder($new_order);
            $new_DT->setTagOrder($new_order);
            $new_DT->setWikipediaRevisionId($revision_id);
            $em->persist($new_DT);
            $em->flush();
        }

        return $this->renderDocTags($id_doc);
    }


    /**
     *
     * TODO: Enter description here ...
     * @return \Symfony\Bundle\FrameworkBundle\Controller\Response
     */
    public function removeWpLinkAction()
    {
        $id_doc = $this->getRequest()->request->get('wikitag_document_id');
        $id_tag = $this->getRequest()->request->get('tag_id');
        $tag = $this->getDoctrine()->getRepository('WikiTagBundle:Tag')->find($id_tag);
        //return new Response(var_dump(array($tag)));
        // We search if the unsemantized version of the tag already exist.
        $un_tag = $this->getDoctrine()->getRepository('WikiTagBundle:Tag')->findOneBy(array('label'=>$tag->getLabel(), 'urlStatus'=>Tag::$TAG_URL_STATUS_DICT['null_result']));
        $em = $this->getDoctrine()->getEntityManager();
        $un_tag_created = FALSE;
        if(!$un_tag){
            // Create another tag almost identical, without the W info
            // TODO: use a factory that return a TagInterface
            $un_tag = new Tag();
            $un_tag->setLabel($tag->getLabel());
            $un_tag->setOriginalLabel($tag->getOriginalLabel());
            $un_tag->setUrlStatus(Tag::$TAG_URL_STATUS_DICT['null_result']);
            $un_tag->setWikipediaUrl(null);
            $un_tag->setWikipediaPageId(null);
            $un_tag->setDbpediaUri(null);
            $un_tag->setCategory($tag->getCategory());
            $un_tag->setAlias($tag->getAlias());
            $un_tag->setPopularity($tag->getPopularity());
            $em->persist($un_tag);
            $un_tag_created = TRUE;
        }
        
        if($id_doc && $id_doc!=""){
            // We associate the unsemantized tag to the DocumentTag and save datas
            // TODO: do the request on external id of document
            $dt = $this->getDoctrine()->getRepository('WikiTagBundle:DocumentTag')->findOneBy(array('document' => $id_doc, 'tag' => $id_tag));
            $dt->setTag($un_tag);
            $em->flush();
            return $this->renderDocTags($id_doc);
        }
        else{
            // Here we are in the context of tag list.
            if($un_tag_created==TRUE){
                $em->flush();
                $num_page = $this->getRequest()->request->get('num_page');
                $nb_by_page = $this->getRequest()->request->get('nb_by_page');
                $sort = $this->getRequest()->request->get('sort');
                $searched = $this->getRequest()->request->get('searched');
                return $this->renderAllTags($num_page, $nb_by_page, $sort, $searched);
            }
            else{
                // The unsemantized version of the tag already exist, so we send an error.
                return new Response(json_encode(array('error' => 'duplicate_tag', 'message' => sprintf("La version désémantisée du tag %s (%s) existe déjà.", $un_tag->getLabel(), $un_tag->getOriginalLabel()))),400);
            }
        }
    }


    /**
     *
     * TODO: Enter description here ...
     */
    public function updateTagCategoryAction()
    {
        $id_doc = $this->getRequest()->request->get('wikitag_document_id');
        $id_tag = $this->getRequest()->request->get('id');
        $cat_label = $this->getRequest()->request->get('value');
        // We get the Tag and update its category.
        $em = $this->getDoctrine()->getEntityManager();
        $tag = $this->getDoctrine()->getRepository('WikiTagBundle:Tag')->find($id_tag);
        if($cat_label==''){
            $cat = null;
            $tag->nullCategory();
        }
        else{
            $cat = $this->getDoctrine()->getRepository('WikiTagBundle:Category')->findOneBy(array('label' => $cat_label));
            $tag->setCategory($cat);
        }
        $em->flush();

        if($id_doc && $id_doc!=""){
            return $this->renderDocTags($id_doc);
        }
        else{
            $num_page = $this->getRequest()->request->get('num_page');
            $nb_by_page = $this->getRequest()->request->get('nb_by_page');
            $sort = $this->getRequest()->request->get('sort');
            $searched = $this->getRequest()->request->get('searched');
            return $this->renderAllTags($num_page, $nb_by_page, $sort, $searched);
        }
    }


    /**
     *
     * Generic render partial template
     * @param unknown_type $id_doc
     */
    public function renderDocTags($id_doc)
    {
        $ordered_tags = $this->getDoctrine()->getRepository('WikiTagBundle:DocumentTag')->findOrderedTagsForDoc($id_doc);
        return $this->render('WikiTagBundle:WikiTag:tagTable.html.twig', array('ordered_tags' => $ordered_tags, 'doc_id' => $id_doc));
    }
    
    /**
     * 
     * TODO: Enter description here ...
     * TODO : implement
     */
    public function resetWpInfoAction()
    {
        $id_doc = $this->getRequest()->request->get('wikitag_document_id');
        return $this->renderDocTags($id_doc);
    }


    /**
     *
     * TODO : Enter description here ...
     * TODO : implement
     * @return \Symfony\Bundle\FrameworkBundle\Controller\Response
     */
    public function updateTagAliasAction()
    {
        $id_tag = $this->getRequest()->request->get('id');
        $alias = $this->getRequest()->request->get('value');
        // We get the Tag and update its category.
        $em = $this->getDoctrine()->getEntityManager();
        $tag = $this->getDoctrine()->getRepository('WikiTagBundle:Tag')->find($id_tag);
        $tag->setAlias($alias);
        $em->flush();
        
        $id_doc = $this->getRequest()->request->get('wikitag_document_id');
        if($id_doc && $id_doc!=""){
            // In case we changed the alias from the document view
            return $this->renderDocTags($id_doc);
        }
        else{
            // In case we changed the alias from the tag list.
            $num_page = $this->getRequest()->request->get('num_page');
            $nb_by_page = $this->getRequest()->request->get('nb_by_page');
            $sort = $this->getRequest()->request->get('sort');
            $searched = $this->getRequest()->request->get('searched');
            return $this->renderAllTags($num_page, $nb_by_page, $sort, $searched);
        }
    }
    
    /**
     * List of all tags
     * TODO: Enter description here ...
     */
    public function allTagsAction()
    {
        // $this->getRequest()->query->get('foo') does not work "because" we are a second controller. So we have to use $_GET.
        // Searched string
        $searched = NULL;
        if(array_key_exists('searched', $_GET)){
            $searched = $_GET['searched'];
        }
        // Number of tags per page
        $nb_by_page = 50;
        if(array_key_exists('nb_by_page', $_GET)){
            $nb_by_page = intval($_GET['nb_by_page']);
        }
        // Current page number
        $num_page = 1;
        if(array_key_exists('num_page', $_GET)){
            $num_page = intval($_GET['num_page']);
        }
        // Sorting criteria
        $sort = NULL;
        if(array_key_exists('sort', $_GET)){
            $sort = $_GET['sort'];
        }
        
        // We get the needed datas in an array($tags, $num_page, $nb_by_page, $searched, $sort, $reverse_sort, $pagerfanta);
        $ar = $this->getAllTags($num_page, $nb_by_page, $sort, $searched);
        $tags = $ar[0];
        $num_page = $ar[1];
        $nb_by_page = $ar[2];
        $searched = $ar[3];
        $sort = $ar[4];
        $reverse_sort = $ar[5];
        $pagerfanta = $ar[6];
        
        // We get the needed vars : number totals of tags, previous and next page number
        $last_page = $pagerfanta->getNbPages();
        $nb_total = $pagerfanta->getNbResults();
        $prev_page = 1;
        if($pagerfanta->hasPreviousPage()){
            $prev_page = $pagerfanta->getPreviousPage();
        }
        $next_page = $last_page;
        if($pagerfanta->hasNextPage()){
            $next_page = $pagerfanta->getNextPage();
        }
        // We calculate start_index and end_index (number of tags in the whole list)
        $start_index = 1 + (($num_page - 1) * $nb_by_page);
        $end_index = min($nb_total, $start_index + $nb_by_page - 1);
        
        // We build the list of tags's first letters to make quick search.
        $conn = $this->getDoctrine()->getEntityManager()->getConnection();
        $sql = "SELECT UPPER(SUBSTRING(normalized_label,1,1)) as fl FROM wikitag_tag GROUP BY fl ORDER BY fl";
        $letters = $conn->query($sql)->fetchAll();
        $search_def = array();
        foreach ($letters as $l){
            $search_def[$l[0]] = $l[0].WikiTagController::$SEARCH_STAR_CHARACTER;
        }
        
        return $this->render('WikiTagBundle:WikiTag:TagList.html.twig', 
            array('tags' => $tags, 'searched' => $searched, 'search_def' => $search_def, 'nb_by_page' => $nb_by_page, 'sort' => $sort, 
            'start_index' => $start_index, 'end_index' => $end_index, 'nb_total' => $nb_total, 'num_page' => $num_page, 'last_page' => $last_page, 
        	'prev_page' => $prev_page, 'next_page' => $next_page, 'reverse_sort' => $reverse_sort));
    }


    /**
     * Generic render partial template for tag list
     */
    public function renderAllTags($num_page=NULL, $nb_by_page=NULL, $sort=NULL, $searched=NULL)
    {
        // We get the needed datas in an array($tags, $num_page, $nb_by_page, $searched, $sort, $reverse_sort, $pagerfanta);
        $ar = $this->getAllTags($num_page, $nb_by_page, $sort, $searched);
        $tags = $ar[0];
        $num_page = $ar[1];
        $nb_by_page = $ar[2];
        $searched = $ar[3];
        $sort = $ar[4];
        $reverse_sort = $ar[5];
        
        return $this->render('WikiTagBundle:WikiTag:TagListTable.html.twig', 
            array('tags' => $tags, 'searched' => $searched, 'nb_by_page' => $nb_by_page, 'sort' => $sort, 'num_page' => $num_page, 'reverse_sort' => $reverse_sort));
    }


    /**
     * Generic to get all tags with the context (pagination number, nb by page, searched string, sort)
     */
    private function getAllTags($num_page=NULL, $nb_by_page=NULL, $sort=NULL, $searched=NULL)
    {
        // We get/set all the parameters for the search and pagination.
        // Searched string
        if($searched==NULL){
            $searched = "";
        }
        // Number of tags per page
        if($nb_by_page==NULL){
            $nb_by_page = 50;
        }
        // Current page number
        if($num_page==NULL){
            $num_page = 1;
        }
        
        // We build the query.
        $qb = $this->getDoctrine()->getEntityManager()->createQueryBuilder();
        $qb->select('t')->from('WikiTagBundle:Tag','t');
        // We add the search string if necessary ('* bugs)
        if($searched!="" && $searched!="'*"){
            // We replace "*" by "%".
            $qb->where($qb->expr()->orx($qb->expr()->like('t.normalizedLabel', "'".str_replace("*", "%", $searched)."'")));
        }
        // We add the sorting criteria
        if($sort==NULL){
            $sort = "popd"; // sort by descendent popularity by default.
            $reverse_sort = "popa";
        }
        $sort_query = "t.popularity DESC t.normalizedLabel ASC t.label ASC";
        switch($sort){
            case "popd":
                $qb->addOrderBy('t.popularity','DESC');
                $qb->addOrderBy('t.normalizedLabel','ASC');
                $qb->addOrderBy('t.label','ASC');
                $reverse_sort = "popa";
                break;
            case "popa":
                $qb->addOrderBy('t.popularity','ASC');
                $qb->addOrderBy('t.normalizedLabel','ASC');
                $qb->addOrderBy('t.label','ASC');
                $reverse_sort = "popd";
                break;
            case "labd":
                $qb->addOrderBy('t.normalizedLabel','DESC');
                $qb->addOrderBy('t.label','DESC');
                $reverse_sort = "laba";
                break;
            case "laba":
                $qb->addOrderBy('t.normalizedLabel','ASC');
                $qb->addOrderBy('t.label','ASC');
                $reverse_sort = "labd";
                break;
        }
        
        // We paginate
        $adapter = new DoctrineORMAdapter($qb);
        $pagerfanta = new Pagerfanta($adapter);
        $pagerfanta->setMaxPerPage($nb_by_page); // 10 by default
        //$last_page = $pagerfanta->getNbPages();
        $pagerfanta->setCurrentPage($num_page); // 1 by default
        $nb_total = $pagerfanta->getNbResults();
        $tags = $pagerfanta->getCurrentPageResults();
        $pagerfanta->haveToPaginate(); // whether the number of results if higher than the max per page
        
        return array($tags, $num_page, $nb_by_page, $searched, $sort, $reverse_sort, $pagerfanta);
    }


}