aboutsummaryrefslogtreecommitdiff
path: root/src/controller/MaintenanceController.php
blob: 98f2e600347d406dea3f7bb5c7a444c90b341655 (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
<?php
// src/controller/MaintenanceController.php

declare(strict_types=1);

use Doctrine\ORM\EntityManager;
use App\Entity\log;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\RedirectResponse;

class MaintenanceController
{
	static public function getLogs(EntityManager $entityManager): void
	{
		$data = $entityManager->getRepository(Log::class)->findAll();
		if(empty($data)){
			echo json_encode(['success' => false]);
		}
		else{
			$view = '<h4>Table ' . TABLE_PREFIX . 'log de la base de données</h4>
				<table>
					<thead>
						<tr>
	                        <th>date et heure (Greenwich)</th>
	                        <th>connexion réussie</th>
	                    </tr>
	                </thead>
	                <tbody>';
            foreach($data as $entry){
            	$view .= '<tr>
            		<td>' . $entry->getFormatedDate() . '</td>
            		<td>' . ($entry->getSuccess() ? 'oui' : 'non') . '</td>
            	</tr>';
            }
            $view .= '</tbody></table>';
			echo json_encode(['success' => true, 'view' => $view]);
		}
		die;
	}
	static public function eraseLogs(EntityManager $entityManager): void
	{
		try{
			$table = $entityManager->getClassMetadata(Log::class)->getTableName();
			$entityManager->getConnection()->executeStatement("TRUNCATE TABLE {$table}"); // SQL donné à DBAL
			echo json_encode(['success' => true]);
		}
		catch(Exception $e){
			echo json_encode(['success' => false]);
		}
		die;
	}

	static public function getLastDump(EntityManager $entityManager): void
	{
		try{
			$backup_list = Backup::getBackupList();
			$nb = count($backup_list);

			if($nb <= 0){ // se produit à la première connexion en mode admin pour une raison algorithimque
				Backup::mySQLdump($entityManager, 'auto');
				$backup_list = Backup::getBackupList();
				$nb = count($backup_list);
				if($nb <= 0){ // improbable, les dossiers devraient déjà avoir été créés
					throw new RuntimeException("Le serveur a rencontré une erreur: aucun backup n'est disponible et ce n'est pas normal.");
				}
			}

			$file_path = Backup::$backup_dir . '/' . $backup_list[$nb - 1];
			$response = new BinaryFileResponse($file_path);
			$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT); // ne pas essayer de l'afficher dans le navigateur
		}
		catch(RuntimeException $e){
			$_SESSION['flash_message'] = $e->getMessage();
			$response = new RedirectResponse((string) new URL(['page' => 'maintenance']));
		}
		$response->send();
		die;
	}
	static public function getAllMedia(): void
	{
		try{
			$file_path = '../var/' . UserDataService::createZip('all_media.zip', ['user_data/assets', 'user_data/images', 'user_data/media']);
			$response = new BinaryFileResponse($file_path);
			$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT); // ne pas essayer de l'afficher dans le navigateur
		}
		catch(RuntimeException $e){
			$_SESSION['flash_message'] = $e->getMessage();
			$response = new RedirectResponse((string) new URL(['page' => 'maintenance']));
		}
		$response->send();
		die;
	}

	// parce qu'il faut un contrôleur
	static public function handleBackupSelection(EntityManager $entityManager, Request $request): void
	{
		$selected_file = $request->request->get('selected_sql');
		$url = new URL;
        if($request->query->has('from')){
            $url->addParams(['page' => $request->query->get('from')]);
        }

        try{
			if(pathinfo($selected_file)['extension'] !== 'sql'){ // pas censé se produire en fait
	        	throw new Exception("charger un fichier au format SQL");
	        }
	        Backup::restoreDatabase($entityManager, $selected_file);

	        $_SESSION['flash_message'] = "La base de données a été restaurée avec succès !!";
	    }
	    catch(Exception $e){
	    	$_SESSION['flash_message'] = "Une erreur s'est produite: " . $e->getMessage();
	    }

	    $response = new RedirectResponse((string)$url);
	    $response->send();
	    die;
	}

	static public function downloadSQL(EntityManager $entityManager, Request $request): void
	{
        $uploaded_file = $request->files->get('uploaded_sql');
        $date = new DateTime;
        $server_place = Config::$database . '_' . $date->format('Y-m-d') . '_uploaded.sql';
        $url = new URL;
        if($request->query->has('from')){
            $url->addParams(['page' => $request->query->get('from')]);
        }

        try{
	        if(pathinfo($uploaded_file->getClientOriginalName())['extension'] !== 'sql'){
	        	throw new Exception("Charger un fichier au format SQL");
	        }
	        //echo $uploaded_file->getSize(); // à garder de côté au cas où

        	// enregistrer le fichier
	        $uploaded_file->move(Backup::$backup_dir, $server_place);

	        // s'en servir
	        Backup::restoreDatabase($entityManager, $server_place);

	        $_SESSION['flash_message'] = "La base de données a été restaurée avec succès !!";
	    }
	    catch(Exception $e){
	    	$_SESSION['flash_message'] = "Une erreur s'est produite: " . $e->getMessage();
	    }

	    $response = new RedirectResponse((string)$url);
	    $response->send();
	    die;
	}
}