<?php
namespace VcaBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use VcaBundle\Entity\Doc;
use VcaBundle\Entity\DossierUser;
use VcaBundle\Entity\Thematique;
use \ZipArchive;
use Symfony\Component\HttpFoundation\Session\Session;
ini_set("memory_limit", "-1");
class DossierUserController extends Controller
{
public function preExecute()
{
@UsersController::securityAction();
}
/**
* Displays all the files (DossierUser entities) owned by a user and processes the add of a new DossierUser
*
* @Route("/admin/monedp", name="admin_monedp")
*/
public function monedpAction(Request $request)
{
$thematique = NULL;
if ($request->isMethod('POST')) {
$this->createDossier();
return $this->redirect($this->getParameter('baseDir').'admin/monedp');
}
$em = $this->getDoctrine()->getManager();
$session = new Session();
$userId = $session->get('userIdFairdoc');
$user = $em->getRepository('VcaBundle:Users')->findOneBy(array('id' => $userId));
if (!isset($user)){
return $this->redirect($this->getParameter('baseDir'));
}
$lecteur = $em->getRepository('VcaBundle:Users')->findOneBy(array('userLecteur' => true));
$allKey = array();
if ($user->getUserChefdoc()){
$nodess = trim($user->getUserThemes());
$nodesss = substr($nodess, 0, -1);
$nodesId = substr($nodesss, 1);
$exp = explode(";", $nodesId);
$list = "";
$i = 0;
foreach ($exp as $n) {
if ($n != null && $n !== "" && $n != " ") {
if ($i == 0) {
$list .= $this->getTree($n);
} else {
$list .= ','.$this->getTree($n);
}
}
$i++;
}
$allKey = explode(',', $list);
}
$dossiers = $em->getRepository('VcaBundle:DossierUser')->findBy(array('dosPhoto' => false), array('id' => 'DESC'));
$index = $user->getUserTheme();
//$thematiques = $em->getRepository('VcaBundle:Thematique')->findAll(array(), array('theme_value' => 'ASC'));
$req = " ";
if (!$session->get('isRealAdminFairdoc')) {
$nodess = trim($user->getUserLisible());
$nodesss = substr($nodess, 0, -1);
$nodesId = substr($nodesss, 1);
$exp = explode(";", $nodesId);
$list = "";
$i = 0;
foreach ($exp as $n) {
if ($n != null && $n !== "" && $n != " ") {
if ($i == 0) {
$list .= $this->getTree($n);
} else {
$list .= ','.$this->getTree($n);
}
}
$i++;
}
$req = " AND theme_id IN ($list) ";
}
$query = "SELECT theme_id, theme_value, theme_parent FROM thematique WHERE 1=1 $req ORDER BY theme_value ASC ";
$db = $this->get('doctrine.dbal.default_connection');//on récupére un objet Doctrine\DBAL\Connection
$thematiques = $db->fetchAll($query);
$query = "select distinct mc.motcle_id, mc.motcle_value,
(select count(dmc.dos_id) from dossier_motcle WHERE motcle_id = mc.motcle_id group by motcle_id) as count
from motcle mc
LEFT join dossier_motcle dmc ON dmc.motcle_id = mc.motcle_id
group by mc.motcle_id";
$db = $this->get('doctrine.dbal.default_connection');//on récupére un objet Doctrine\DBAL\Connection
$mots = $db->fetchAll($query);
//$mots = $em->getRepository('VcaBundle:Motcle')->findBy(array(), array('motcleValue' => 'ASC'));
if ($session->get('isRealAdminFairdoc')){
$index = null;
}
$query = "select distinct(doc_type) from document_user du
JOIN dossier_document dd ON dd.doc_id = du.doc_id
JOIN dossier_user dou ON dou.dos_id = dd.dos_id
WHERE dou.dos_photo is false Order by doc_type asc";
$db = $this->get('doctrine.dbal.default_connection');//on récupére un objet Doctrine\DBAL\Connection
$extensions = $db->fetchAll($query);
$docs = array();
$nbDocs = array();
foreach ($dossiers as $key => $dos){
$docs[] = $dos->getDosDocs();
$nbDocs[] = count(end($docs));
}
$dossiers = array_values($dossiers);
$types = $em->getRepository('VcaBundle:DataUserType')->findAll();
$year = array();
for ($i = date("Y"); $i >= 1970; $i--) {
$year[] = $i;
}
$arbre = $this->buildTree($thematiques);
usort($arbre, function($a, $b) {
return $a['text'] <=> $b['text'];
});
$debut=array();
$debut["text"] = "Tous les répertoires";
$debut["id"] = 0;
array_unshift($arbre, $debut);
//var_dump($arbre);exit;
return $this->render('document/myedp.html.twig', array(
'dossiers' => $dossiers,
'nbDocs' => $nbDocs,
'docs' => $docs,
'types' => $types,
'user' => $user,
'year' => $year,
'index' => $index,
'arbre' => $arbre,
'allKey' => $allKey,
'lecteur' => $lecteur,
'mots' => $mots,
'extensions' => $extensions,
'node' => null,
'thematique' => $thematique,
'thematiques' => $thematiques,
'base_dir' => realpath($this->getParameter('kernel.root_dir') . '/..') . DIRECTORY_SEPARATOR,
));
}
/**
*
* @Route("/admin/monedploadajax", name="edp_loadajax")
*/
public function monedploadajaxAction(Request $request)
{
$session = new Session();
$userId = $session->get('userIdFairdoc');
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('VcaBundle:Users')->findOneBy(array('id' => $userId));
$lecture = " AND du.dos_hidden = false";
if ($user->getUserHidden() || $user->getUserAdmin()){
$lecture = " ";
}
$repId=$motReq=$motleft=null;
$em = $this->getDoctrine()->getManager();
$lecteur = $em->getRepository('VcaBundle:Users')->findOneBy(array('userLecteur' => true));
if (isset($_GET["id"]) && $_GET["id"] != 0){
$repId = $this->getTree($_GET["id"]);
$repId = ' AND dt.theme_id IN ('.$repId.') ';
if (isset($_GET["check"]) && $_GET["check"] != 1){
$repId = ' AND dt.theme_id = '.$_GET["id"].' ';
}
} else {
if (isset($_GET["check"]) && $_GET["check"] != 1){
$repId = ' AND dt.theme_id = 0 ';
}
}
$req = " ";
if (!$session->get('isRealAdminFairdoc')) {
$nodess = trim($user->getUserLisible());
$nodesss = substr($nodess, 0, -1);
$nodesId = substr($nodesss, 1);
$exp = explode(";", $nodesId);
$list = "";
$i = 0;
foreach ($exp as $n) {
if ($n != null && $n !== "" && $n != " ") {
if ($i == 0) {
$list .= $this->getTree($n);
} else {
$list .= ','.$this->getTree($n);
}
}
$i++;
}
$req = " AND (dt.theme_id IN ($list) OR dt.theme_id is null)";
}
if (isset($_GET["motcle"]) && $_GET["motcle"] != 0){
$motleft = " LEFT JOIN dossier_motcle dm ON dm.dos_id=du.dos_id ";
//$motReq = ' AND dm.motcle_id IN ('.$_GET["motcle"].') ';
$motsSearch = explode(',', $_GET["motcle"]);
if (count($motsSearch) == 1) {
$motReq = " HAVING '".$_GET["motcle"]."' = ANY(ARRAY_AGG((select motcle_id from dossier_motcle dm WHERE dm.dos_id=du.dos_id AND dm.motcle_id = ".$_GET["motcle"]." ))) ";
} else {
$motReq .= " HAVING '".$_GET["motcle"]."' = ANY(ARRAY_AGG(";
foreach ($motsSearch as $key => $motSearch) {
if ($key == 0){
$motReq .= "(select motcle_id from dossier_motcle dm WHERE dm.dos_id=du.dos_id AND dm.motcle_id = ".$motSearch." )";
} else {
$motReq .= " || ',' ||(select motcle_id from dossier_motcle dm WHERE dm.dos_id=du.dos_id AND dm.motcle_id = ".$motSearch." )";
}
}
$motReq .= "))";
}
}
//var_dump($_GET["extension"]);exit;
if (isset($_GET["extension"]) && $_GET["extension"] != ""){
//echo 'ooooo';exit;
$motsSearch = explode(',', $_GET["extension"]);
//var_dump($_GET["extension"]);exit;
if (count($motsSearch) == 1) {
$req .= " AND doc_type = '".$_GET["extension"]."' ";
} else {
$req .= " AND ( ";
foreach ($motsSearch as $key => $motSearch) {
if ($key == 0){
$req .= " doc_type = '$motSearch' ";
} else {
$req .= " OR doc_type = '$motSearch' ";
}
}
$req .= " ) ";
}
}
if (isset($_GET["search"]) ) {
$search = $_GET["search"];
$value = $search["value"];
$req .= " AND lower(translate(dos_name,'éèàçù','eeacu')) like '%".pg_escape_string(strtolower($this->str_to_noaccent($value)))."%' ";
}
//order[0][column]=1&order[0][dir]=des
//if (isset($_GET[order[0][column]]))
$order = " ORDER BY TO_DATE(du.dos_date, 'DD/MM/YYYY') DESC, du.dos_id DESC ";
if (isset($_GET["order"])) {
$value = $_GET["order"];
if ($value[0]["column"] == 1) {
$order = " ORDER BY du.dos_name ".$value[0]["dir"];
}
if ($value[0]["column"] == 2) {
$order = " ORDER BY du.dos_description ".$value[0]["dir"];
}
if ($value[0]["column"] == 2) {
$order = " ORDER BY TO_DATE(du.dos_date, 'DD/MM/YYYY') ".$value[0]["dir"]." , du.dos_id DESC ";
}
if ($value[0]["column"] == 3) {
$order = " ORDER BY t.theme_value ".$value[0]["dir"];
}
if ($value[0]["column"] == 4) {
$order = " ORDER BY doc.doc_type ".$value[0]["dir"];
}
if ($value[0]["column"] == 5) {
$order = " ORDER BY doc.doc_size ".$value[0]["dir"];
}
}
//var_dump($_GET["order"]);exit;
$page = $_GET["start"];
$db = $this->get('doctrine.dbal.default_connection');//on récupére un objet Doctrine\DBAL\Connection
$query = "select distinct du.dos_id, du.dos_name, du.dos_description, t.theme_value, t.theme_id, dd.doc_id, du.dos_date, doc.doc_type , doc.doc_filename, doc.doc_indb , TO_DATE(du.dos_date, 'DD/MM/YYYY') as test, du.dos_lien, du.dos_islien, doc.doc_size , doc.doc_type
from dossier_user du
LEFT JOIN dossier_thematique dt ON dt.dos_id = du.dos_id
LEFT JOIN thematique t ON t.theme_id = dt.theme_id
LEFT JOIN dossier_document dd ON dd.dos_id=du.dos_id
LEFT JOIN document_user doc ON dd.doc_id=doc.doc_id
$motleft
where 1=1 $repId $req AND dos_photo = false $lecture GROUP BY du.dos_id, t.theme_value, t.theme_id , dd.doc_id, doc.doc_id $motReq $order LIMIT 20 OFFSET $page ";
$dossiers = $db->fetchAll($query);
$retour = array();
if (isset($_GET["motcle"]) && $_GET["motcle"] != 0){
$query = "select distinct du.dos_id, du.dos_name, du.dos_description, t.theme_value, t.theme_id, dd.doc_id, du.dos_date, doc.doc_type , doc.doc_filename , TO_DATE(du.dos_date, 'DD/MM/YYYY') as test
from dossier_user du
LEFT JOIN dossier_thematique dt ON dt.dos_id = du.dos_id
LEFT JOIN thematique t ON t.theme_id = dt.theme_id
LEFT JOIN dossier_document dd ON dd.dos_id=du.dos_id
LEFT JOIN document_user doc ON dd.doc_id=doc.doc_id
$motleft
where 1=1 $repId $req AND dos_photo = false $lecture GROUP BY du.dos_id, t.theme_value, t.theme_id , dd.doc_id, doc.doc_id $motReq ";
$count = $db->fetchAll($query);
$tot[0]["total"] = count($count);
} else {
$query = "select count(distinct du.dos_id) as total from dossier_user du
LEFT JOIN dossier_thematique dt ON dt.dos_id = du.dos_id
LEFT JOIN thematique t ON t.theme_id = dt.theme_id
LEFT JOIN dossier_document dd ON dd.dos_id=du.dos_id
LEFT JOIN document_user doc ON dd.doc_id=doc.doc_id
$motleft
where 1=1 $repId $req AND dos_photo = false $lecture ";
//echo $query;exit;
$tot = $db->fetchAll($query);
}
$retour = array();
$retour["draw"] = $_GET["draw"];
if (!isset($tot[0])) {
$retour["recordsTotal"] = 0;
$retour["recordsFiltered"] = 0;
} else {
$retour["recordsTotal"] = $tot[0]["total"];
$retour["recordsFiltered"] = $tot[0]["total"];
}
$i = 0;
foreach ($dossiers as $row) {
$query = "select motcle_value FROM motcle mc
LEFT JOIN dossier_motcle dmc ON mc.motcle_id = dmc.motcle_id
WHERE dos_id = ".$row["dos_id"]."";
$mots = $db->fetchAll($query);
$motcles = '<div class="form-group keywords"><ul class="holder" style="width: 426px;">';
//var_dump($row->getDosThematique());exit;
foreach ($mots as $mot) {
$motcles .= '<li class="bit-box" rel="8" id="pt_RRBwwVRaTRVuBfdKgmzUZbqtA5a09wRx" style="font-size: 0.6em;">'.strtoupper($mot["motcle_value"]).'</li><br />';
}
$motcles .= '</ul></div>';
$retour["data"][$i][0] = '';
if ($row["dos_islien"]) {
$retour["data"][$i][0] = '<a href="'.$row["dos_lien"].'" target="_blank"><img src="../img/link.png" style="width: 45px;" /></a>';
} else {
if ($row["doc_id"] != null) {
if ($row["doc_type"] == "doc" || $row["doc_type"] == "docx") {
$parts = explode('.', $row["doc_filename"]);
$last = array_pop($parts);
$parts = array(implode('.', $parts), $last);
$filename = $parts[0]; // outputs "one_two_three"
$retour["data"][$i][0] = '<a href="#" data-toggle="modal" data-target="#exampleModal" title="Prévisualiser le Document" alt="Prévisualiser le Document" onclick="changDoc(\''.$row["dos_id"].'/'.$filename.'.pdf\');return false;"><img src="../img/word.png" style="width: 30px;" /></a>';
}
if ($row["doc_type"] == "xls" || $row["doc_type"] == "xlsx") {
$retour["data"][$i][0] = '<img src="../img/excel.png" style="width: 30px;" />';
}
if ($row["doc_type"] == "ppt" || $row["doc_type"] == "pptx") {
$retour["data"][$i][0] = '<a href="#" data-toggle="modal" data-target="#exampleModal" title="Prévisualiser le Document" alt="Prévisualiser le Document" onclick="changeppt(\''.$row["dos_id"].'/'.$row["doc_filename"].'\');return false;"><img src="../img/ppt.png" style="width: 30px;" /></a>';
}
if ($row["doc_type"] == "mp3" || $row["doc_type"] == "m4a") {
$retour["data"][$i][0] = '<a href="#" data-toggle="modal" data-target="#exampleModal" title="Prévisualiser le Document" alt="Prévisualiser le Document" onclick="changemp3(\''.$row["dos_id"].'/'.$row["doc_filename"].'\');return false;"><img src="../img/audio.png" style="width: 30px;" /></a>';
}
if ($row["doc_type"] == "mp4") {
$retour["data"][$i][0] = '<a href="#" data-toggle="modal" data-target="#exampleModal" title="Prévisualiser le Document" alt="Prévisualiser le Document" onclick="changevideo(\''.$row["dos_id"].'/'.$row["doc_filename"].'\');return false;"><img src="../img/film.png" style="width: 30px;" /></a>';
}
if ($row["doc_type"] == "pdf") {
$retour["data"][$i][0] = '<a href="#" data-toggle="modal" data-target="#exampleModal" title="Prévisualiser le Document" alt="Prévisualiser le Document" onclick="changDoc(\''.$row["dos_id"].'/'.$row["doc_filename"].'\');return false;"><img src="../img/pdf.png" style="width: 30px;" /></a>';
}
if ($row["doc_type"] == "zip" || $row["doc_type"] == "rar") {
$retour["data"][$i][0] = '<img src="../img/zip.png" style="width: 45px;" />';
}
}
}
$retour["data"][$i][1] = (string) $row["dos_name"];
//$retour["data"][$i][2] = (string) $row["dos_description"];
$retour["data"][$i][2] = (string) $row["dos_date"];
$retour["data"][$i][3] = (string) strtoupper($row["theme_value"]);
$retour["data"][$i][4] = (string) strtoupper($row["doc_type"]);
$retour["data"][$i][5] = (string) round($row["doc_size"]/(1024*1024),2).' Mo';
//$retour["data"][$i][5] = (string) $motcles;
$retour["data"][$i][6] = '';
if (!$row["dos_islien"]) {
if ($row["doc_id"] != null) {
$retour["data"][$i][6] = (string) '<a href="'.$this->container->getParameter('baseDir').'admin/downloadDoc/'.$row["doc_id"].'"target="_blank">
<button type="button" class="btn btn-success btn-xs" title="Télécharger le Fichier ">
<i class="fa fa-download"></i>
</button>
</a> ';
}
}
if ($session->get('isRealAdminFairdoc')) {
$retour["data"][$i][6] .= '<a href="'.$this->container->getParameter('baseDir').'admin/deleteDos/'.$row["dos_id"].'" onClick="deleteDossier('.$row["dos_id"].'); return false;">
<button type="button" class="btn btn-danger btn-xs" alt="Supprimer le Fichier" title="Supprimer le Fichier">
<i class="fa fa-times"></i>
</button>
</a>
<a href="'.$this->container->getParameter('baseDir').'admin/editFolder/'.$row["dos_id"].'">
<button type="button" class="btn btn-secondary btn-xs" alt="Modifier le Fichier" title="Modifier le Fichier">
<i class="fa fa-pencil-square-o"></i>
</button>
</a>
<input type="checkbox" name="supp['.$row["dos_id"].']" class="myCheck" onclick="suppCheck()" value="'.$row["dos_id"].'">
';
}
if ($user->getUserChefdoc() && !$session->get('isRealAdminFairdoc')){
$nodess = trim($user->getUserThemes());
$nodesss = substr($nodess, 0, -1);
$nodesId = substr($nodesss, 1);
$exp = explode(";", $nodesId);
$list = "";
$j = 0;
foreach ($exp as $n) {
if ($n != null && $n !== "" && $n != " ") {
if ($j == 0) {
$list .= $this->getTree($n);
} else {
$list .= ','.$this->getTree($n);
}
}
$j++;
}
$allKey = explode(',', $list);
if (in_array($row["theme_id"], $allKey)) {
$retour["data"][$i][6] .= '<a href="'.$this->container->getParameter('baseDir').'/admin/deleteDos/'.$row["dos_id"].'" onClick="deleteDossier('.$row["dos_id"].'); return false;">
<button type="button" class="btn btn-danger btn-xs" alt="Supprimer le Fichier" title="Supprimer le Fichier">
<i class="fa fa-times"></i>
</button>
</a>
<a href="'.$this->container->getParameter('baseDir').'/admin/editFolder/'.$row["dos_id"].'">
<button type="button" class="btn btn-secondary btn-xs" alt="Modifier le Fichier" title="Modifier le Fichier">
<i class="fa fa-pencil-square-o"></i>
</button>
</a>
<input type="checkbox" name="supp['.$row["dos_id"].']" class="myCheck" onclick="suppCheck()" value="'.$row["dos_id"].'">
';
}
}
if ($row["doc_type"] == "csv" && !$row["doc_indb"] && $this->getParameter('myTitle') != 'FairDoc') {
$retour["data"][$i][6] .= '<a href="'.$this->container->getParameter('baseDir').'admin/addToDb/'.$row["doc_id"].'">
<button type="button" class="btn btn-warning btn-xs" alt="Mettre en BDD" title="Mettre en BDD">
<i class="fa fa-database"></i>
</button>
</a>';
}
if ($row["doc_type"] == "csv" && $row["doc_indb"]) {
$retour["data"][$i][6] .= '<a href="'.$this->container->getParameter('baseDir').'admin/seeDoc/'.$row["doc_id"].'">
<button type="button" class="btn btn-info btn-xs" alt="Voir en BDD" title="Voir en BDD">
<i class="fa fa-database"></i>
</button>
</a>';
}
if (!$row["dos_islien"]) {
$retour["data"][$i][6] .= ' <a href="#" data-toggle="modal" data-target="#exampleModalDirect" title="Lien Direct" alt="Lien Direct" onclick="changLien(\''.$lecteur->getUserLogin().'\', \''.str_pad($row["doc_id"], 6, "0", STR_PAD_LEFT).'\');return false;" style="text-decoration: none;color: black;"><i class="fa fa-link mypopover"></i></a>';
}
$i++;
}
if (!isset($tot[0])) {
$retour["data"] = array();
} else {
if ($tot[0]["total"] == 0) {
$retour["data"] = array();
}
}
echo json_encode($retour);exit;
}
public function str_to_noaccent($str)
{
$url = $str;
$url = preg_replace('#Ç#', 'C', $url);
$url = preg_replace('#ç#', 'c', $url);
$url = preg_replace('#è|é|ê|ë#', 'e', $url);
$url = preg_replace('#È|É|Ê|Ë#', 'E', $url);
$url = preg_replace('#à|á|â|ã|ä|å#', 'a', $url);
$url = preg_replace('#@|À|Á|Â|Ã|Ä|Å#', 'A', $url);
$url = preg_replace('#ì|í|î|ï#', 'i', $url);
$url = preg_replace('#Ì|Í|Î|Ï#', 'I', $url);
$url = preg_replace('#ð|ò|ó|ô|õ|ö#', 'o', $url);
$url = preg_replace('#Ò|Ó|Ô|Õ|Ö#', 'O', $url);
$url = preg_replace('#ù|ú|û|ü#', 'u', $url);
$url = preg_replace('#Ù|Ú|Û|Ü#', 'U', $url);
$url = preg_replace('#ý|ÿ#', 'y', $url);
$url = preg_replace('#Ý#', 'Y', $url);
return ($url);
}
/**
* Create theme entities.
*
* @Route("/addThemeGroupe", name="addThemeGroupe")
* @Method("POST")
*/
public function createAction(Request $request)
{
if (!$request->isMethod('POST')) {
return NULL;
}
$pays = new Thematique();
$pays->setThemeValue($_POST["nameTheme"]);
if (isset($_POST["parentTheme"]) && $_POST["parentTheme"] != "") {
$pays->setThemeParent($_POST["parentTheme"]);
} else {
$pays->setThemeParent(null);
}
$em = $this->getDoctrine()->getManager();
$em->persist($pays);
$em->flush($pays);
$id=$pays->getThemeId();
if (isset($_POST["visibletous"]) && $_POST["visibletous"]) {
$query = "update users set user_lisible = user_lisible || '$id;'";
$db = $this->get('doctrine.dbal.default_connection');
$retour = $db->fetchAll($query);
}
return $this->redirect($this->getParameter('baseDir').'admin/monedp');
}
/**
* Create theme entities.
*
* @Route("/editThemeGroupe", name="editThemeGroupe")
* @Method("POST")
*/
public function editThemeGroupeAction(Request $request)
{
if (!$request->isMethod('POST')) {
return NULL;
}
$id = $_POST["parenteditTheme"];
$em = $this->getDoctrine()->getManager();
$pays = $em->getRepository('VcaBundle:Thematique')->find($id);
$pays->setThemeValue($_POST["editthemename"]);
$em = $this->getDoctrine()->getManager();
$em->persist($pays);
$em->flush($pays);
return $this->redirect($this->getParameter('baseDir').'admin/monedp');
}
private function buildTree(array $elements, $parentId = null) {
$branch = array();
foreach ($elements as $i=>$element) {
$test = array();
$test["text"] = $element["theme_value"];
$test["id"] = $element["theme_id"];
if ($element["theme_parent"] == $parentId) {
$children = $this->buildTree($elements, $element["theme_id"]);
if ($children) {
$test['nodes'] = $children;
}
$branch[$i] = $test;
}
}
return $branch;
}
private function getTree($rootid)
{
$arr = array();
$retour = $rootid;
$db = $this->get('doctrine.dbal.default_connection');//on récupére un objet Doctrine\DBAL\Connection
$query = "select theme_id from thematique where theme_parent = $rootid";
$rows = $db->fetchAll($query);
foreach ($rows as $row){
$retour .= ','.$row["theme_id"];
$retour .= ','.$this->getTree($row["theme_id"]);
}
return $retour;
}
/**
* Creates a zip that contains all the Doc entities of a DossierUser and downloads it
*
* @Route("/admin/downloadFolder/{id}/{check}", name="admin_download")
*/
public function downloadDossierAction(Request $request, $id, $check){
$session = new Session();
$userId = $session->get('userIdFairdoc');
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('VcaBundle:Users')->findOneBy(array('id' => $userId));
$lecture = " AND du.dos_hidden = false";
if ($user->getUserHidden() || $user->getUserAdmin()){
$lecture = " ";
}
$repId=$motReq=$motleft=null;
$em = $this->getDoctrine()->getManager();
$lecteur = $em->getRepository('VcaBundle:Users')->findOneBy(array('userLecteur' => true));
if (isset($id) && $id != 0){
$repId = $this->getTree($id);
$repId = ' AND dt.theme_id IN ('.$repId.') ';
if (isset($check) && $check != 1){
$repId = ' AND dt.theme_id = '.$id.' ';
}
} else {
if (isset($check) && $check != 1){
$repId = ' AND dt.theme_id = '.$id.' ';
}
}
$req = " ";
if (!$session->get('isRealAdminFairdoc')) {
$nodess = trim($user->getUserLisible());
$nodesss = substr($nodess, 0, -1);
$nodesId = substr($nodesss, 1);
$exp = explode(";", $nodesId);
$list = "";
$i = 0;
foreach ($exp as $n) {
if ($n != null && $n !== "" && $n != " ") {
if ($i == 0) {
$list .= $this->getTree($n);
} else {
$list .= ','.$this->getTree($n);
}
}
$i++;
}
$req = " AND (dt.theme_id IN ($list) OR dt.theme_id is null)";
}
$order = " ORDER BY TO_DATE(du.dos_date, 'DD/MM/YYYY') DESC ";
$db = $this->get('doctrine.dbal.default_connection');//on récupére un objet Doctrine\DBAL\Connection
$query = "select distinct du.dos_id, du.dos_name, du.dos_description, t.theme_value, t.theme_id, dd.doc_id, du.dos_date, doc.doc_type , doc.doc_filename, doc.doc_indb , TO_DATE(du.dos_date, 'DD/MM/YYYY') as test, du.dos_lien, du.dos_islien
from dossier_user du
LEFT JOIN dossier_thematique dt ON dt.dos_id = du.dos_id
LEFT JOIN thematique t ON t.theme_id = dt.theme_id
LEFT JOIN dossier_document dd ON dd.dos_id=du.dos_id
LEFT JOIN document_user doc ON dd.doc_id=doc.doc_id
$motleft
where 1=1 $repId $req AND dos_photo = false $lecture GROUP BY du.dos_id, t.theme_value, t.theme_id , dd.doc_id, doc.doc_id $motReq $order ";
$dossiers = $db->fetchAll($query);
exec("rm -f ".realpath($this->getParameter('kernel.root_dir') . '/..') . "/public/files/Archive.zip");
$zip = new ZipArchive();
$archive_filename = realpath($this->getParameter('kernel.root_dir') . '/..') . "/public/files/Archive.zip";
if ($zip->open($archive_filename, ZipArchive::CREATE) == TRUE){
foreach ($dossiers as $row) {
//$fichiers = scandir(realpath($this->getParameter('kernel.root_dir') . '/..') . "/public/files/".$row["dos_id"]);
//foreach ($fichiers as $fichier) {
$fichier = realpath($this->getParameter('kernel.root_dir') . '/..') . "/public/files/".$row["dos_id"]."/".$row["doc_filename"];
if (file_exists($fichier) && is_file($fichier)) {
$myname = str_replace('.'.$row["doc_type"], "", $row["dos_name"]);
$myname .= '.'.$row["doc_type"];
if(!$zip->addFile($fichier, $myname))
{
throw new Exception("Echec de l'ajout du fichier à l'archive");
}
}
//}
}
$zip->close();
ob_clean();
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=Archive.zip");
header("Pragma: no-cache");
header("Expires: 0");
readfile("$archive_filename");
unlink($archive_filename);
}
exit();
}
/**
* Show folder content
*
* @Route("/admin/showFolder/{id}", name="admin_showfolder")
*/
public function showFolderAction(Request $request, $id)
{
$session = new Session();
$thematique = NULL;
$em = $this->getDoctrine()->getManager();
$userId = $session->get('userIdFairdoc');
$user = $em->getRepository('VcaBundle:Users')->findOneBy(array('id' => $userId));
$dossier = $em->getRepository('VcaBundle:DossierUser')->find($id);
$index = $user->getUserTheme();
if($index){
$thematique = $em->getRepository('VcaBundle:Thematique')->findOneBy(["id" => $index]);
}
return $this->render('document/showDoc.html.twig', array(
'user' => $user,
'thematique' => $thematique,
'index' => $index,
'dossier' => $dossier,
));
}
/**
* Creates a form to edit the data of a DossierUser entity and to add new Doc entities to it
*
* @Route("/admin/editFolder/{id}", name="admin_editfolder")
*/
public function editFolderAction(Request $request, DossierUser $dos)
{
$session = new Session();
$thematique = NULL;
$em = $this->getDoctrine()->getManager();
$userId = $session->get('userIdFairdoc');
$user = $em->getRepository('VcaBundle:Users')->findOneBy(array('id' => $userId));
$dossiers = $em->getRepository('VcaBundle:DossierUser')->findBy(array(), array('id' => 'DESC'));
$index = $user->getUserTheme();
if($index){
$thematique = $em->getRepository('VcaBundle:Thematique')->findOneBy(["id" => $index]);
}
$query = "select distinct t.theme_id, t.theme_value,
(select th.theme_value from thematique th where th.theme_id = t.theme_parent AND t.theme_parent != 0 AND t.theme_parent is not null ) as parent
from thematique t
LEFT join dossier_thematique dt ON dt.theme_id = t.theme_id
group by t.theme_id order by parent asc";
$db = $this->get('doctrine.dbal.default_connection');//on récupére un objet Doctrine\DBAL\Connection
$thematiques = $db->fetchAll($query);
if ($session->get('isRealAdminFairdoc')){
$index = null;
}
if (!$this->isDossierOwner($dos)){
return $this->redirect($this->getParameter('baseDir').'admin/monedp');
}
$id = $dos->getDosId();
if ($request->isMethod('POST')) {
$dos = $em->getRepository('VcaBundle:DossierUser')->find($id);
if ($session->get('isRealAdminFairdoc')){
$liste = $dos->getDosThematique();
foreach ($liste as $docaut) {
$dos->getDosThematique()->removeElement($docaut);
}
if ( $_POST["theme"] != 0 && $_POST["theme"] != null) {
$thematique = $em->getRepository('VcaBundle:Thematique')->findOneBy(["id" => $_POST["theme"]]);
$dos->getDosThematique()->add($thematique);
}
}
//var_dump($_POST);exit;
$hidden = false;
if (isset($_POST["cache"])) {
$hidden = $_POST["cache"];
}
$dos->setDosHidden($hidden);
if (isset($_POST["lien"])) {
$dos->setDosLien($_POST["lien"]);
}
if (isset($_POST["name"]))
$dos->setDosName(substr($_POST["name"], 0, 255));
/*
if (isset($_POST["lat"])) {
$dos->setDosLatitude(substr($_POST["lat"], 0, 255));
}
if (isset($_POST["lng"])) {
$dos->setDosLongitude(substr($_POST["lng"],0,255));
}
*/
$dos->setDosDescription(substr($_POST["description"], 0, 255));
$dos->setDosDate(substr($_POST["datepicker"], 0,255));
//$dos->setDosSite(substr($_POST["execution"],0,255));
// suppression des themes en cours
/*
$liste = $dos->getDosThematique();
foreach ($liste as $docaut) {
$dos->getDosThematique()->removeElement($docaut);
}*/
// suppression des mot en cours
$liste = $dos->getDosMotcle();
foreach ($liste as $docaut) {
$dos->getDosMotcle()->removeElement($docaut);
}
// edition image de couverture
if(isset($_FILES['imageCover']) && $_FILES['imageCover'] != ""){
$imageCover = $_FILES['imageCover'];
$tmpName = $imageCover['tmp_name'];
$filename = "";
if (isset($imageCover['name'])) {
$basename = substr($imageCover['name'], 0, strrpos($imageCover['name'], "."));
$filename = BlogController::sublimyFile($basename);
}
$extension = substr($imageCover["name"], strrpos($imageCover["name"], '.')+1);
if($filename){
$old_image = $dos->getImage();
if($old_image){
exec("rm ".realpath($this->getParameter('kernel.root_dir').'/..')."/public/files/".$dos->getDosId()."/".$dos->getImage()." ");
}
$fileImNameBig = "cover_".$filename.'.'.$extension;
$dos->setImage(substr($fileImNameBig, 0, 255));
exec("cp ".$tmpName." ".realpath($this->getParameter('kernel.root_dir').'/..')."/public/files/".$dos->getDosId()."/".$fileImNameBig." ");
}
}
//Ajout des fichiers au dossier
if (isset($_FILES['fileToUpload']) && $_FILES['fileToUpload']["name"][0] != "") {
$liste = $dos->getDosDocs();
foreach ($liste as $docaut) {
$dos->getDosDocs()->removeElement($docaut);
}
$dos = $this->addFiles($_FILES['fileToUpload'], 0, $dos);
}
$docs = $dos->getDosDocs();
if (isset($_POST["docDescription"])) {
//Un fichier n'a pas été chargé correctement
if (count($docs) != count($_POST["docDescription"])) {
$nbNewDocs = count($_FILES['fileToUpload']['name']);
$nbDescriptions = count($_POST["docDescription"]);
if (count($docs) == $nbNewDocs) {
for ($i = 0; $i < $nbNewDocs; $i++) {
if ($_FILES["fileToUpload"]["error"][$i] !== UPLOAD_ERR_OK) {
//On supprime la description des fichiers non chargés
unset($_POST["docDescription"][$i + $nbDescriptions - $nbNewDocs]);
}
}
}
}
$_POST["docDescription"] = array_values($_POST["docDescription"]);
//Ajout de la description de chaque document
foreach ($docs as $key => $doc) {
$doc->setDocDescription(substr($_POST["docDescription"][$key], 0, 255));
}
}
$dos = $this->saveList($dos);
return $this->redirect($this->getParameter('baseDir').'admin/monedp');
}
$year = array();
for ($i = date("Y"); $i >=1970 ; $i--) {
$year[] = $i;
}
//on recupere les auteurs
$list_aut = array();
foreach ($dos->getDosCorrespondant() as $i => $auteur) {
$list_aut[$i]['id'] = $auteur->getAutId();
$list_aut[$i]['value'] = strtoupper($auteur->getAutNom()) . " " . strtolower($auteur->getAutPrenom());
}
//on recupere les pays
$list_pays = array();
foreach ($dos->getDosPays() as $i => $pays) {
$list_pays[$i]['id'] = $pays->getPaysId();
$list_pays[$i]['value'] = strtoupper($pays->getPaysNomFr());
}
//on recupere les mots
$list_mot = array();
foreach ($dos->getDosMotcle() as $i => $motcle) {
$list_mot[$i]['id'] = $motcle->getMotcleId();
$list_mot[$i]['value'] = strtoupper($motcle->getMotcleValue());
}
//on recupere les themes
$list_theme = array();
foreach ($dos->getDosThematique() as $i => $theme) {
$list_theme[$i]['id'] = $theme->getThemeId();
$list_theme[$i]['value'] = strtoupper($theme->getThemeValue());
}
//on recupere les fichiers
$docs = $dos->getDosDocs();
$dataHead = $em->getRepository('VcaBundle:DataUserHead')->findBy(array('vcadocId' => $dos->getDosId(), 'affiche' => true), array("id" => "asc"));
$nbOnglets = count($dataHead);
$upload = $em->getRepository('VcaBundle:Upload')->findBy(array('dosId' => $dos->getDosId()));
$retourUpload = array();
foreach ($upload as $up) {
if ($up->getUserId() != null) {
$user = $em->getRepository('VcaBundle:Users')->findOneBy(array('id' => $up->getUserId()));
$retourUpload[] = $user->getUserNom()." ".$user->getUserPrenom()." le ".$up->getDate();
}
}
//$session->set("ongletDoc", $doc->getId());
return $this->render('document/editDoc.html.twig', array(
'user' => $user,
'thematique' => $thematique,
'thematiques' => $thematiques,
'index' => $index,
'dos' => $dos,
'docs' => $docs,
'year' => $year,
'list_aut' => $list_aut,
'list_pays' => $list_pays,
'list_mot' => $list_mot,
'list_theme' => $list_theme,
'nbOnglets' => $nbOnglets,
'retourUpload' => $retourUpload,
'base_dir' => realpath($this->getParameter('kernel.root_dir') . '/..') . DIRECTORY_SEPARATOR,
));
}
/**
* List of shared DossierUser entities
*
* @Route("/admin/documentation", name="admin documentation")
*/
public function documentationAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$list_theme = $em->getRepository('VcaBundle:Thematique')->findAll();
$doss = $em->getRepository('VcaBundle:DossierUser')->findBy(array('dosShare'=>true), array('id'=>'DESC'));
$docs = array();
$nbDocs = array();
foreach ($doss as $key => $dos) {
$docs[] = $dos->getDosDocs();
$nbDocs[] = sizeof(end($docs));
}
// replace this example code with whatever you need
return $this->render('document/documentation.html.twig', array(
'dossiers' => $doss,
'nbDocs' => $nbDocs,
'docs' => $docs,
'list_theme' => $list_theme,
'base_dir' => realpath($this->getParameter('kernel.root_dir') . '/..') . DIRECTORY_SEPARATOR,
));
}
/**
* Fetches the DossierUser entities which match the filter
*
* @Route("/admin/rechargeDoc", name="admin rechargeDoc")
*/
public function rechargeDocAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
//Fetch only the shared DossierUser entities
$dossByShare = $em->getRepository('VcaBundle:DossierUser')->findSharedDos();
$dosIdArray = array();
foreach ($dossByShare as $dossArray){
$dosIdArray = array_merge_recursive($dosIdArray, $dossArray);
}
$dosIdArray = array_unique($dosIdArray["dos_id"]);
//Fetch the id of the DossierUser entities which match $_POST["text"] and keep the shared ones
if (isset($_POST["text"])){
$dossText = array();
$dossByText = $em->getRepository('VcaBundle:DossierUser')->findDosByText($_POST["text"]);
foreach ($dossByText as $textItem){
$dossText = array_merge_recursive($dossText, $textItem);
}
if (sizeof($dossText) > 0) {
if (! is_int($dossText["dos_id"])) {
$dossText = array_unique($dossText["dos_id"]);
}
$dosIdArray = array_intersect($dosIdArray, $dossText);
} else {
$dosIdArray = array();
}
}
//Fetch the id of the DossierUser entities which are linked to at least one of the chosen MotCle and keep the ones which match the previous requirements
if (isset($_POST["mot"])) {
$dossMots = array();
$dossByMot = array();
foreach ($_POST["mot"] as $mot_item) {
$dossByMot[] = $em->getRepository('VcaBundle:DossierUser')->findDosByMot($mot_item);
}
foreach ($dossByMot as $dossArray){
foreach ($dossArray as $dossItem){
$dossMots = array_merge_recursive($dossMots, $dossItem);
}
}
if (sizeof($dossMots) > 0) {
if (! is_int($dossMots["dos_id"])) {
$dossMots = array_unique($dossMots["dos_id"]);
}
$dosIdArray = array_intersect($dosIdArray, $dossMots);
} else {
$dosIdArray = array();
}
}
//Fetch the id of the DossierUser entities which are linked to at least one of the chosen Thematique and keep the ones which match the previous requirements
if (isset($_POST["theme"])) {
$dossThemes = array();
$dossByTheme = array();
foreach ($_POST["theme"] as $theme_item) {
$dossByTheme[] = $em->getRepository('VcaBundle:DossierUser')->findDosByTheme($theme_item);
}
foreach ($dossByTheme as $dossArray){
foreach ($dossArray as $dossItem){
$dossThemes = array_merge_recursive($dossThemes, $dossItem);
}
}
if (sizeof($dossByTheme[0])>0) {
if (! is_int($dossThemes["dos_id"])) {
$dossThemes = array_unique($dossThemes["dos_id"]);
}
$dosIdArray = array_intersect($dosIdArray, $dossThemes);
} else {
$dosIdArray = array();
}
}
//Fetch the id of the DossierUser entities which are linked to at least one of the chosen Pays and keep the ones which match the previous requirements
if (isset($_POST["pays"])) {
$dossPays = array();
$dossByPays = array();
foreach ($_POST["pays"] as $pays_item) {
$dossByPays[] = $em->getRepository('VcaBundle:DossierUser')->findDosByPays($pays_item);
}
foreach ($dossByPays as $dossArray){
foreach ($dossArray as $dossItem){
$dossPays = array_merge_recursive($dossPays, $dossItem);
}
}
if (sizeof($dossByPays[0])>0) {
if (! is_int($dossPays["dos_id"])) {
$dossPays = array_unique($dossPays["dos_id"]);
}
$dosIdArray = array_intersect($dosIdArray, $dossPays);
} else {
$dosIdArray = array();
}
}
$doss = array();
foreach ($dosIdArray as $dos) {
$i = count($doss);
//Retrieve all the information necessary to display each DossierUser entity
$dossier = $em->getRepository('VcaBundle:DossierUser')->find($dos);
$doss[$i]["dos"]["id"] = $dossier->getDosId();
$doss[$i]["dos"]["dosName"] = $dossier->getDosName();
$doss[$i]["dos"]["dosDescription"] = $dossier->getDosName();
$doss[$i]["docs"] = count($dossier->getDosDocs());
//Search for the information about the User who owns each DossierUser
$user = $em->getRepository('VcaBundle:DossierUser')->find($dos)->getDosUser();
$user = $em->getRepository('VcaBundle:Users')->find($user);
$doss[$i]["user"]["user_nom"] = $user->getUserNom();
$doss[$i]["user"]["user_prenom"] = $user->getUserPrenom();
$doss[$i]["user"]["user_email"] = $user->getUserEmail();
//Search for the Motcle entities linked with each DossierUser
$motcles = $em->getRepository('VcaBundle:DossierUser')->findMotInDos($dos);
$doss[$i]["motcles"] = array();
foreach ($motcles as $j=>$mot){
$doss[$i]["motcles"][$j]["motcle_value"] = $em->getRepository('VcaBundle:Motcle')->find($mot["motcle_id"])->getMotcleValue();
}
//Search for the Thematique entities linked with each DossierUser
$thematiques = $em->getRepository('VcaBundle:DossierUser')->findThemeInDos($dos);
$doss[$i]["thematiques"] = array();
foreach ($thematiques as $j=>$theme){
$doss[$i]["thematiques"][$j]["theme_value"] = $em->getRepository('VcaBundle:Thematique')->find($theme["theme_id"])->getThemeValue();
}
}
echo json_encode($doss);
exit;
}
/**
* @Route("/admin/rechercheDocs", name="rechercheDocs")
*/
public function rechercheDocs()
{
$em = $this->getDoctrine()->getManager();
$docs = $em->getRepository('VcaBundle:DossierUser')->find(["id" => $_POST["id"]]);
$ds = [];
foreach ($docs->getDosDocs() as $doc) {
$ds[] = $doc->serialize();
}
echo json_encode($ds);
exit;
}
/**
* Deletes a dossierUser entity.
*
* @Route("/admin/deleteDos/{id}", name="dos_delete")
*/
public function deleteDosAction(Request $request, DossierUser $dos)
{
if (!$this->isDossierOwner($dos)){
return $this->redirect($this->getParameter('baseDir').'admin/monedp');
}
//Suppression physique du dossier
exec("rm -R ".realpath($this->getParameter('kernel.root_dir').'/..')."/public/files/".$dos->getDosId());
$em = $this->getDoctrine()->getManager();
$em->remove($dos);
//Suppression physique du dossier
//$this->rrmdir(realpath($this->getParameter('kernel.root_dir') . '/..') . "/public/files/" .$dos->getDosId()."/");
$em->flush();
return $this->redirect($this->getParameter('baseDir').'admin/monedp');
}
/**
* Deletes a dossierUser entity.
*
* @Route("/admin/deleteAllDos/{id}", name="dos_alldelete")
*/
public function deleteAllDosAction(Request $request, $id=null)
{
if ($id == null) {
return $this->redirect($this->getParameter('baseDir').'admin/monedp');
}
$myDos = explode(";;", $id);
$em = $this->getDoctrine()->getManager();
foreach ($myDos as $doss) {
$dos = $em->getRepository('VcaBundle:DossierUser')->findOneBy(array('id' => $doss));
if (!$this->isDossierOwner($dos)){
return $this->redirect($this->getParameter('baseDir').'admin/monedp');
}
//Suppression physique du dossier
exec("rm -R ".realpath($this->getParameter('kernel.root_dir').'/..')."/public/files/".$dos->getDosId());
$em->remove($dos);
//Suppression physique du dossier
//$this->rrmdir(realpath($this->getParameter('kernel.root_dir') . '/..') . "/public/files/" .$dos->getDosId()."/");
$em->flush();
}
return $this->redirect($this->getParameter('baseDir').'admin/monedp');
}
/**
* Shares a DossierUser entity.
*
* @Route("/admin/shareDos/{id}/{share}", name="dos_share")
*/
public function shareDosAction(Request $request, DossierUser $dos, $share)
{
if (!$this->isDossierOwner($dos)){
return $this->redirect($this->getParameter('baseDir').'admin/monedp');
}
$dos->setDosShare($share);
$em = $this->getDoctrine()->getManager();
$em->persist($dos);
$em->flush();
return $this->redirect($this->getParameter('baseDir').'admin/monedp');
}
/**
* Creates a DossierUser and persists it in the database.
*/
private function createDossier()
{
$session = new Session();
//var_dump($_FILES['fileToUpload']);exit;
$em = $this->getDoctrine()->getManager();
foreach ($_FILES['fileToUpload']["name"] as $key=>$fichier) {
$dos = new DossierUser();
//$dos->setDosName(substr($fichier, 0, 255));
$dos->setDosName(substr($_POST["name"], 0, 255));
$dos->setDosDescription(substr($_POST["description"], 0, 255));
$dos->setDosDate(substr($_POST["datepicker"], 0, 255));
//$dos->setDosSite(substr($_POST["execution"], 0, 255));
$dos->setDosShare(true);
$dos->setDosPhoto(false);
$hidden = false;
if (isset($_POST["cache"])) {
$hidden = $_POST["cache"];
}
$dos->setDosHidden($hidden);
$hidden = false;
if (isset($_POST["islien"])) {
$hidden = $_POST["islien"];
}
$dos->setDosIslien($hidden);
$dos->setDosLien($_POST["lien"]);
$userId =$session->get('userIdFairdoc');
$user = $em->getRepository("VcaBundle:Users")->find($userId);
$dos->setDosUser($user);
if ( $_POST["theme"] != 0 && $_POST["theme"] != null) {
$thematique = $em->getRepository('VcaBundle:Thematique')->findOneBy(["id" => $_POST["theme"]]);
$dos->getDosThematique()->add($thematique);
}
if (isset($_POST["lat"])) {
$dos->setDosLatitude(substr($_POST["lat"], 0, 100));
}
if (isset($_POST["lng"])) {
$dos->setDosLongitude(substr($_POST["lng"], 0, 100));
}
$em->persist($dos);
$em->flush();
$dosId = $dos->getDosId();
//Création d'un répertoire dosId dans web/files
mkdir(realpath($this->getParameter('kernel.root_dir') . '/..') . "/public/files/" . $dosId);
//Ajout des fichiers au dossier
$dos = $this->addFiles($_FILES['fileToUpload'],$key, $dos);
$docs = $dos->getDosDocs();
if (isset($_POST["docDescription"])) {
//Un fichier n'a pas été chargé correctement
if (count($docs) != count($_POST["docDescription"])) {
$nbNewDocs = count($_FILES['fileToUpload']['name']);
$nbDescriptions = count($_POST["docDescription"]);
for ($i = 0; $i < $nbDescriptions; $i++) {
if ($_FILES["fileToUpload"]["error"][$i] !== UPLOAD_ERR_OK) {
unset($_POST["docDescription"][$i]);
}
}
}
$_POST["docDescription"] = array_values($_POST["docDescription"]);
foreach ($docs as $key => $doc) {
$doc->setDocDescription(substr($_POST["docDescription"][$key], 0, 100));
}
}
$dos = $this->saveList($dos);
// edition image de couverture
if(isset($_FILES['imageCover']) && $_FILES['imageCover']){
$imageCover = $_FILES['imageCover'];
$tmpName = $imageCover['tmp_name'];
$filename = "";
if (isset($imageCover['name'])) {
$basename = substr($imageCover['name'], 0, strrpos($imageCover['name'], "."));
$filename = BlogController::sublimyFile($basename);
}
$extension = substr($imageCover["name"], strrpos($imageCover["name"], '.')+1);
$fileImNameBig = "cover_".$filename.'.'.$extension;
$dos->setImage(substr($fileImNameBig, 0, 255));
exec("cp ".$tmpName." ".realpath($this->getParameter('kernel.root_dir').'/..')."/public/files/".$dos->getDosId()."/".$fileImNameBig." ");
}
$em->flush();
}
return;
}
/**
* Creates the Doc entities and updates the DossierUser entity
*
* @param $files : array of files
* @param DossierUser $dos : dossier auquel appartiennent les fichiers
* @return DossierUser
*/
private function addFiles($files, $cle , DossierUser $dos)
{
$em = $this->getDoctrine()->getManager();
//Transformation de l'array $_FILES pour faciliter la lecture
$file_array = $this->reArrayFiles($files);
$docList = new ArrayCollection();
$dosId = $dos->getDosId();
foreach ($file_array as $key => $file){
if ($key == $cle ) {
if ($file['error'] === UPLOAD_ERR_OK) {
$tmpName = $file['tmp_name'];
$filename = "";
if (isset($file['name'])) {
$basename = substr($file['name'], 0, strrpos($file['name'], "."));
$filename = $this->sublimyFile($basename);
}
$extension = substr($file["name"], strrpos($file["name"], '.') + 1);
$inDbb = false;
$doc = new Doc();
$doc->setDocName(substr($filename, 0, 255));
$doc->setDocType(substr($extension, 0, 255));
$doc->setDocIndb($inDbb);
$doc->setDocCreation(date("Y-m-d H:i:s"));
$doc->setDocShare(false);
$doc->setDocSize($file['size']);
$em->persist($doc);
$docList[] = $doc;
$DocIdData = $doc->getDocId();
$fileImNameBig = $DocIdData . '_' . $filename . '.' . $extension;
$doc->setDocFilename(substr($fileImNameBig, 0, 255));
exec("cp " . $tmpName . " " . realpath($this->getParameter('kernel.root_dir') . '/..') . "/public/files/" . $dosId . "/" . $fileImNameBig . " ");
//Sauvegarde du document
$em->flush();
}
}
}
//Mise a jour du dossier avec les tables de jointure
if (!$docList->isEmpty()) {
foreach ($docList as $doc) {
$docItem = $em->getRepository('VcaBundle:Doc')->find($doc->getDocId());
$dos->addDoc($docItem);
}
$em->flush();
}
//on convertit les docs en PDF lowriter ou soffice
exec("export HOME=/tmp && /usr/bin/soffice --convert-to pdf " . realpath($this->getParameter('kernel.root_dir') . '/..') . "/public/files/" . $dosId . "/*.doc --outdir " . realpath($this->getParameter('kernel.root_dir') . '/..') . "/public/files/" . $dosId . " ");
exec("export HOME=/tmp && /usr/bin/soffice --convert-to pdf " . realpath($this->getParameter('kernel.root_dir') . '/..') . "/public/files/" . $dosId . "/*.docx --outdir " . realpath($this->getParameter('kernel.root_dir') . '/..') . "/public/files/" . $dosId . " ");
return $dos;
}
private function saveList(DossierUser $dos)
{
$em = $this->getDoctrine()->getManager();
$correspondants = new ArrayCollection();
if (isset($_POST["aut_list"])) {
foreach ($_POST["aut_list"] as $aut) {
$correspondants[] = $em->getRepository('VcaBundle:Auteur')->find($aut);
}
$dos->setDosCorrespondant($correspondants);
}
$payss = new ArrayCollection();
if (isset($_POST["pays_list"])) {
foreach ($_POST["pays_list"] as $pays) {
$payss[] = $em->getRepository('VcaBundle:Pays')->find($pays);
}
$dos->setDosPays($payss);
}
/*
$region = new \Doctrine\Common\Collections\ArrayCollection();
if (isset($_POST["region_list"])) {
foreach ($_POST["region_list"] as $aut) {
$region[] = $em->getRepository('VcaBundle:Region')->findOneBy(array('regionId' => $aut));
}
$doc->setDocRegion($region);
}
$type = new \Doctrine\Common\Collections\ArrayCollection();
if (isset($_POST["type_list"])) {
foreach ($_POST["type_list"] as $aut) {
$type[] = $em->getRepository('VcaBundle:Type')->findOneBy(array('typeId' => $aut));
}
$doc->setDocTypedata($type);
}
*/
$motcles = new ArrayCollection();
if (isset($_POST["mot_list"])) {
foreach ($_POST["mot_list"] as $motcle) {
$motcles[] = $em->getRepository('VcaBundle:Motcle')->find($motcle);
}
$dos->setDosMotcle($motcles);
}
$thematiques = new ArrayCollection();
if (isset($_POST["theme_list"])) {
foreach ($_POST["theme_list"] as $thematique) {
$thematiques[] = $em->getRepository('VcaBundle:Thematique')->find($thematique);
}
$dos->setDosThematique($thematiques);
}
//$dos->setDosDocs($docs);
$em->flush();
return $dos;
}
/**
* Deletes recursively a directory
*
* @param $dir directory we want to delete
*/
private function rrmdir($dir){
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (is_dir($dir."/".$object))
$this->rrmdir($dir."/".$object);
else
unlink($dir."/".$object);
}
}
rmdir($dir);
}
}
/**
* Rearranges the array file_post to make it easier to use (I often use it for $_FILES when uploading files)
*
* @param $file_post
* @return array
*/
private function reArrayFiles($file_post)
{
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
/**
* Checks if the current User is the owner of a DossierUser entity
*
* @param DossierUser $dos
* @return bool
*/
private function isDossierOwner(DossierUser $dos){
$session = new Session();
if ($session->get('isRealAdminFairdoc')){
return true;
}
$userId = $session->get('userIdFairdoc');
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('VcaBundle:Users')->findOneBy(array('id' => $userId));
if ($user->getUserChefdoc()){
$nodess = trim($user->getUserThemes());
$nodesss = substr($nodess, 0, -1);
$nodesId = substr($nodesss, 1);
$exp = explode(";", $nodesId);
$list = "";
$i = 0;
foreach ($exp as $n) {
if ($n != null && $n !== "" && $n != " ") {
if ($i == 0) {
$list .= $this->getTree($n);
} else {
$list .= ','.$this->getTree($n);
}
}
$i++;
}
$allKey = explode(',', $list);
$thematiques = $dos->getDosThematique();
foreach($thematiques as $themes) {
$theme = $themes->getThemeId();
}
if (in_array($theme, $allKey)) {
return true;
}
}
return false;
}
/**
* Standardizes a string : converts it to lowercase and deletes all special chars
*
* @param $path string
* @return string
*/
public function sublimyFile($path)
{
// everything to lower and no spaces begin or end
$path = strtolower(trim($path));
// adding - for spaces and union characters
$find = array(' ', '&', '\r\n', '\n', '+', ',');
$path = str_replace($find, '_', $path);
//replaces diacritical e by e
$find = array('é', 'è', 'ê', 'ë');
$path = str_replace($find, 'e', $path);
//delete and replace rest of special chars
$find = array('/[^a-z0-9\-<>]/', '/[\-]+/', '/<[^>]*>/');
$repl = array('', '-', '');
$path = preg_replace($find, $repl, $path);
return $path;
}
/**
* Lists all user entities.
*
* @Route("/admin/gestionrep", name="gestionrep")
* @Method("GET")
*/
public function gestionrepAction()
{
$session = new Session();
if ($session->get('isRealAdminFairdoc') == false)
{
return $this->render('users/error.html.twig');
}
else
{
$query = "select distinct t.theme_id, t.theme_value,
(select count(dt.dos_id) from dossier_thematique WHERE theme_id = t.theme_id group by t.theme_id) as count,
(select th.theme_value from thematique th where th.theme_id = t.theme_parent) as parent
from thematique t
LEFT join dossier_thematique dt ON dt.theme_id = t.theme_id where 1=1
group by t.theme_id";
$db = $this->get('doctrine.dbal.default_connection');//on récupére un objet Doctrine\DBAL\Connection
$themes = $db->fetchAll($query);
return $this->render('document/gestion.html.twig', array(
'themes' => $themes
));
}
}
/**
* Deletes a dossierUser entity.
*
* @Route("/admin/deletemyrep/{id}", name="deletemyrep")
*/
public function deletemyrepAction(Request $request, $id)
{
$session = new Session();
if ($session->get('isRealAdminFairdoc') == false)
{
return $this->render('users/error.html.twig');
}
else
{
$db = $this->get('doctrine.dbal.default_connection');//on récupére un objet Doctrine\DBAL\Connection
$query = "select theme_parent from thematique where theme_id = $id";
$themeParent = $db->fetchAll($query);
$query = "select theme_id from thematique where theme_parent = $id";
$themesFils = $db->fetchAll($query);
$query = "select dos_id from dossier_thematique where theme_id = $id";
$files = $db->fetchAll($query);
if (isset($themeParent[0]["theme_parent"]) && $themeParent[0]["theme_parent"] != 0) {
foreach($themesFils as $themeFils) {
$query = 'update thematique SET theme_parent = '.$themeParent[0]["theme_parent"].' where theme_id = '.$themeFils["theme_id"];
$db->fetchAll($query);
}
foreach($files as $file) {
$query = 'update dossier_thematique SET theme_id = '.$themeParent[0]["theme_parent"].' where dos_id = '.$file["dos_id"];
$db->fetchAll($query);
}
} else {
foreach($themesFils as $themeFils) {
$query = 'update thematique SET theme_parent = null where theme_id = '.$themeFils["theme_id"];
$db->fetchAll($query);
}
foreach($files as $file) {
$query = 'delete from dossier_thematique where dos_id = '.$file["dos_id"];
$db->fetchAll($query);
}
}
$query = "delete from thematique where theme_id = ".$id." ";
$db->fetchAll($query);
}
return $this->redirect($this->getParameter('baseDir').'admin/gestionrep');
}
/**
* Deletes a dossierUser entity.
*
* @Route("/admin/deletesmyrep/{id}", name="deletesmyrep")
*/
public function deletesmyrepAction(Request $request, $id)
{
$session = new Session();
if ($session->get('isRealAdminFairdoc') == false)
{
return $this->render('users/error.html.twig');
}
else
{
$db = $this->get('doctrine.dbal.default_connection');//on récupére un objet Doctrine\DBAL\Connection
$query = "select theme_parent from thematique where theme_id = $id";
$themeParent = $db->fetchAll($query);
$query = "select theme_id from thematique where theme_parent = $id";
$themesFils = $db->fetchAll($query);
$query = "select dos_id from dossier_thematique where theme_id = $id";
$files = $db->fetchAll($query);
if (isset($themeParent[0]["theme_parent"]) && $themeParent[0]["theme_parent"] != 0) {
foreach($themesFils as $themeFils) {
$query = 'update thematique SET theme_parent = '.$themeParent[0]["theme_parent"].' where theme_id = '.$themeFils["theme_id"];
$db->fetchAll($query);
}
foreach($files as $file) {
$query = 'update dossier_thematique SET theme_id = '.$themeParent[0]["theme_parent"].' where dos_id = '.$file["dos_id"];
$db->fetchAll($query);
}
} else {
foreach($themesFils as $themeFils) {
$query = 'update thematique SET theme_parent = null where theme_id = '.$themeFils["theme_id"];
$db->fetchAll($query);
}
foreach($files as $file) {
$query = 'delete from dossier_thematique where dos_id = '.$file["dos_id"];
$db->fetchAll($query);
}
}
$query = "delete from thematique where theme_id = ".$id." ";
$db->fetchAll($query);
}
return $this->redirect($this->getParameter('baseDir').'admin/monedp');
}
}