summaryrefslogtreecommitdiff
path: root/src/controller/PageManagementController.php
blob: f84c528725df7a9108acc2e89ea84248f8232dc5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
<?php
// src/controller/PageManagementController.php

declare(strict_types=1);

use App\Entity\Page;
use App\Entity\Node;
use App\Entity\NodeData;
//use App\Entity\Image;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManager;

class PageManagementController
{
	/* -- partie page -- */
	static public function setPageTitle(EntityManager $entityManager, array $json): void
	{
		$page = $entityManager->find('App\Entity\Page', $json['page_id']);
		$page->setPageName(htmlspecialchars($json['title']));
		$entityManager->flush();
		echo json_encode(['success' => true, 'title' => $page->getPageName()]);
		die;
	}

	static public function updatePageMenuPath(EntityManager $entityManager): void
	{
	    Director::$menu_data = new Menu($entityManager);
	    Director::$page_path = new Path();
	    $page = Director::$page_path->getLast();
	    $path = htmlspecialchars($_POST['page_menu_path']);

	    // mise en snake_case: filtre caractères non-alphanumériques, minuscule, doublons d'underscore, trim des underscores
	    $path = trim(preg_replace('/_+/', '_', strtolower(preg_replace('/[^a-zA-Z0-9]/', '_', $path))), '_');
	    $page->setEndOfPath($path);
	    foreach(Director::$menu_data->getChildren() as $child){
	        if($child->getEndOfPath() === Director::$page_path->getArray()[0]->getEndOfPath()){
	            $child->fillChildrenPagePath(); // MAJ de $page_path
	        }
	    }
	    $entityManager->flush();
	    header("Location: " . new URL(['page' => $page->getPagePath(), 'action' => 'modif_page']));
	    die;
	}

	static public function setPageDescription(EntityManager $entityManager, array $json): void
	{
		$node_data = $entityManager->find('App\Entity\NodeData', $json['node_data_id']);
		$node_data->updateData('description', htmlspecialchars($json['description']));
		$entityManager->flush();
		echo json_encode(['success' => true, 'description' => $node_data->getData()['description']]);
		die;
	}

	static public function newPage(EntityManager $entityManager): void
	{
	    // titre et chemin
	    $director = new Director($entityManager, true);
	    //Director::$menu_data = new Menu($entityManager);
	    $previous_page = Director::$menu_data->findPageById((int)$_POST["page_location"]); // (int) à cause de declare(strict_types=1);
	    $parent = $previous_page->getParent();

	    $page = new Page(
	        trim(htmlspecialchars($_POST["page_name"])),
	        trim(htmlspecialchars($_POST["page_name_path"])),
	        true, true, false,
	        $previous_page->getPosition(),
	        $parent); // peut et DOIT être null si on est au 1er niveau

	    // on a donné à la nouvelle entrée la même position qu'à la précédente,
	    // addChild l'ajoute à la fin du tableau "children" puis on trie
	    // exemple avec 2 comme position demandée: 1 2 3 4 2 devient 1 2 3 4 5 et la nouvelle entrée sera en 3è position
	    if($parent == null){
	        $parent = Director::$menu_data;
	    }
	    $parent->addChild($page);
	    $parent->reindexPositions();

	    $page->setPagePath(ltrim($parent->getPagePath() . '/' . $page->getEndOfPath(), '/'));

	    // noeud "head"
	    $node = new Node(
	        'head',
	        null, [],
	        1, // position d'un head = 1
	        null, // pas de parent
	        $page);
	    $node->useDefaultAttributes(); // fichiers CSS et JS

	    $data = new NodeData([
	        // pas de titre, il est dans $page
	        'description' => trim(htmlspecialchars($_POST["page_description"]))],
	        $node);

	    $bulk_data = $entityManager
	        ->createQuery('SELECT n FROM App\Entity\Image n WHERE n.file_name LIKE :name')
	        ->setParameter('name', '%favicon%')
	        ->getResult();
	    $data->setImages(new ArrayCollection($bulk_data));
	    
	    $entityManager->persist($page);
	    $entityManager->persist($node);
	    $entityManager->persist($data);
	    $entityManager->flush();

	    // page créée, direction la page en mode modification pour ajouter des blocs
	    header("Location: " . new URL(['page' => $page->getPagePath(), 'action' => 'modif_page']));
	    die;
	}

	static public function deletePage(EntityManager $entityManager): void
	{
	    $page = $entityManager->find('App\Entity\Page', (int)$_POST['page_id']);
	    $nodes = $entityManager->getRepository('App\Entity\Node')->findBy(['page' => $page]);
	    $data = [];
	    foreach($nodes as $node){
	        $data[] = $entityManager->getRepository('App\Entity\NodeData')->findOneBy(['node' => $node]);
	        $entityManager->remove($node);
	    }
	    foreach($data as $one_data){
	        $entityManager->remove($one_data);
	    }
	    $entityManager->remove($page); // suppression en BDD
	    
	    $entityManager->flush();
	    header("Location: " . new URL);
	    die;
	}

	/* partie "blocs" */
	static public function addBloc(EntityManager $entityManager): void
	{
	    $director = new Director($entityManager, true); // on a besoin de page_path qui dépend de menu_data
	    $page = Director::$page_path->getLast();
	    $director->findUniqueNodeByName('main');
	    $director->findItsChildren();
	    $main = $director->getNode();
	    $position = count($main->getChildren()) + 1; // position dans la fraterie

	    $blocks = ['blog', 'grid', 'calendar', 'galery', 'form']; // même liste dans FormBuilder.php
	    if(!in_array($_POST["bloc_select"], $blocks, true)) // 3è param: contrôle du type
	    {
	        header("Location: " . new URL(['page' => $_GET['page'], 'error' => 'bad_bloc_type']));
	        die;
	    }

	    if($_POST["bloc_select"] === 'calendar' || $_POST["bloc_select"] === 'form'){
	        $dql = 'SELECT n FROM App\Entity\Node n WHERE n.page = :page AND n.name_node = :name'; // noeud 'head' de la page
	        $bulk_data = $entityManager
	        ->createQuery($dql)
	        ->setParameter('page', $page)
	        ->setParameter('name', 'head')
	        ->getResult();

	        if(count($bulk_data) != 1){ // 1 head par page
	            header("Location: " . new URL(['page' => $_GET['page'], 'error' => 'head_node_not_found']));
	            die;
	        }

	        $bulk_data[0]->addAttribute('css_array', $_POST["bloc_select"]);
	        if($_POST["bloc_select"] === 'form'){
	            $bulk_data[0]->addAttribute('js_array', $_POST["bloc_select"]);
	        }
	        $entityManager->persist($bulk_data[0]);
	    }

	    $bloc = new Node(
	        $_POST["bloc_select"],
	        null, [],
	        $position,
	        $main,
	        $page);
	    $data = new NodeData(
	        ['title' => trim(htmlspecialchars($_POST["bloc_title"]))],
	        $bloc);

	    $entityManager->persist($bloc);
	    $entityManager->persist($data);
	    $entityManager->flush();
	    header("Location: " . new URL(['page' => $_GET['page'], 'action' => 'modif_page']));
	    die;
	}

	static public function deleteBloc(EntityManager $entityManager): void
	{
	    $director = new Director($entityManager, true);
	    $director->findUniqueNodeByName('main');
	    $director->findItsChildren();
	    //$director->findNodeById((int)$_POST['delete_bloc_id']);
	    $main = $director->getNode();
	    $bloc = null;
	    foreach($main->getChildren() as $child){
	        if($child->getId() === (int)$_POST['delete_bloc_id']){
	            $bloc = $child;
	            break;
	        }
	    }
	    if(!empty($bloc)){ // si $bloc est null c'est que le HTML a été modifié volontairement
	        $main->removeChild($bloc); // réindex le tableau $children au passage
	        $main->reindexPositions();
	        $entityManager->remove($bloc); // suppression en BDD
	        $entityManager->flush();
	    }
	    header("Location: " . new URL(['page' => $_GET['page'], 'action' => 'modif_page']));
	    die;
	}
	
	static public function renameBloc(EntityManager $entityManager, array $json): void
	{
		if(isset($json['bloc_title']) && $json['bloc_title'] !== null && isset($json['bloc_id']) && is_int($json['bloc_id'])){
            $director = new Director($entityManager);
            $director->findNodeById($json['bloc_id']);

            // le titre (du JSON en BDD) est récupéré sous forme de tableau, modifié et renvoyé
            $data = $director->getNode()->getNodeData()->getData();
            $data['title'] = htmlspecialchars($json['bloc_title']);
            $director->getNode()->getNodeData()->updateData('title', htmlspecialchars($json['bloc_title']));

            $entityManager->flush();
            echo json_encode(['success' => true, 'title' => $data['title']]);
        }
        else{
			echo json_encode(['success' => false]);
		}
		die;
	}

	static public function SwitchBlocsPositions(EntityManager $entityManager, array $json): void
	{
		if(isset($json['id1']) && is_int($json['id1']) && isset($json['id2']) && is_int($json['id2']) && isset($_GET['page'])){
    		$director = new Director($entityManager, true);
    		$director->findUniqueNodeByName('main');
            $director->findItsChildren();
            $main = $director->getNode();
            $main->sortChildren(true); // régénère les positions avant inversion

            $bloc1 = null;
            $bloc2 = null;
            foreach($main->getChildren() as $child){
            	if($child->getId() === $json['id1']){
            		$bloc1 = $child;
            		break;
            	}
            }
            foreach($main->getChildren() as $child){
            	if($child->getId() === $json['id2']){
            		$bloc2 = $child;
            		break;
            	}
            }

	        // inversion
	        $tmp = $bloc1->getPosition();
	        $bloc1->setPosition($bloc2->getPosition());
	        $bloc2->setPosition($tmp);

    		$entityManager->flush();
            echo json_encode(['success' => true]);
    	}
    	else{
			echo json_encode(['success' => false]);
		}
		die;
	}
}