install.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. <?php
  2. if(isset($_GET['action']) && $_GET['action'] =='check_connection'){
  3. $response = array();
  4. require_once(__DIR__.'/connector/'.$_GET['connector'].'.class.php');
  5. $connector = $_GET['connector'];
  6. $connectionString = $connector::connection;
  7. foreach ($_GET as $key => $value) {
  8. $connectionString = str_replace('{{'.$key.'}}',$value,$connectionString);
  9. }
  10. $connectionString = str_replace('{{ROOT}}',dirname(__FILE__).DIRECTORY_SEPARATOR,$connectionString);
  11. try{
  12. $connection = new PDO($connectionString, $_GET['login'], $_GET['password'],$connector::pdo_attributes());
  13. }catch(Exception $e){
  14. $response['error'] = 'Connexion impossible : '.$e->getMessage();
  15. }
  16. echo json_encode($response);
  17. exit();
  18. }
  19. try {
  20. /*
  21. Page customizable depuis n'importe quel app.json de plugin via la mention :
  22. "install": "Install.class.php",
  23. cette classe située au sein du plugin peut contenir les méthodes suivantes
  24. css : chemin relatif au plugin d'un fichier css custom d'install
  25. js : chemin relatif au plugin d'un fichier js custom d'install
  26. post_install : méthode contenant le code qui doit s'executer en fin d'installation.
  27. pre_install : méthode en début d'installation.
  28. */
  29. date_default_timezone_set('Europe/Paris');
  30. mb_internal_encoding('UTF-8');
  31. require_once(__DIR__.'/function.php');
  32. spl_autoload_register('app_autoloader');
  33. $_ = array_map('secure_user_vars', array_merge($_POST, $_GET));
  34. require_once('class/Plugin.class.php');
  35. $entityFolder = __DIR__.'/class/';
  36. if(file_exists(__DIR__.DIRECTORY_SEPARATOR.'.git') && !file_exists(__DIR__.DIRECTORY_SEPARATOR.'.git'.DIRECTORY_SEPARATOR.'.htaccess')){
  37. file_put_contents(__DIR__.DIRECTORY_SEPARATOR.'.git'.DIRECTORY_SEPARATOR.'.htaccess', 'Require all denied');
  38. }
  39. $custom = null;
  40. //Recherche de custom install dans les plugins
  41. foreach(glob(__DIR__.DIRECTORY_SEPARATOR.'plugin'.DIRECTORY_SEPARATOR.'*'.DIRECTORY_SEPARATOR.'app.json') as $app){
  42. $manifest = json_decode(file_get_contents($app),true);
  43. if(!$manifest || !isset($manifest['install'])) continue;
  44. $custom = array();
  45. $custom['plugin'] = 'plugin/'.basename(dirname($app)).'/';
  46. $custom['pluginPath'] = __DIR__.DIRECTORY_SEPARATOR.'plugin'.DIRECTORY_SEPARATOR.basename(dirname($app)).DIRECTORY_SEPARATOR;
  47. $custom['class'] = basename(str_replace('.class.php', '', $manifest['install']));
  48. $custom['classPath'] = $custom['pluginPath'].$custom['class'].'.class.php';
  49. require_once($custom['classPath']);
  50. }
  51. /*
  52. Installation en mode cli, exemple :
  53. php install.php "{\"connector\":\"Mysql\",\"host\":\"mysql-host\",\"login\":\"root\",\"password\":\"root\",\"name\":\"hackpoint\",\"root\":\"http:\/\/127.0.0.1\/hackpoint\"}"
  54. */
  55. if(php_sapi_name() == 'cli'){
  56. echo 'Headless install...'.PHP_EOL;
  57. $parameters = json_decode($argv[1],true);
  58. echo 'Parameters: '.PHP_EOL;
  59. print_r($parameters);
  60. echo 'Installing... '.PHP_EOL;
  61. install_core($parameters,$custom);
  62. echo 'Installation done. '.PHP_EOL;
  63. exit();
  64. }
  65. ?>
  66. <!DOCTYPE html>
  67. <html lang="fr">
  68. <head>
  69. <meta charset="utf-8">
  70. <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  71. <meta name="description" content="">
  72. <meta name="author" content="">
  73. <link rel="icon" type="image/png" href="favicon.png" />
  74. <title>Installateur</title>
  75. <!-- Bootstrap core CSS -->
  76. <link href="css/bootstrap.min.css" rel="stylesheet">
  77. <!-- Font awesome -->
  78. <link rel="stylesheet" href="css/fontawesome-all.min.css">
  79. <!-- Custom styles for this template -->
  80. <link href="css/main.css" rel="stylesheet">
  81. <?php
  82. if(method_exists($custom['class'], 'css')): ?>
  83. <link href="<?php echo $custom['plugin'].$custom['class']::css(); ?>" rel="stylesheet">
  84. <?php endif; ?>
  85. <style>
  86. body{
  87. background: #f5f5f5;
  88. }
  89. </style>
  90. </head>
  91. <body>
  92. <!-- Fixed navbar -->
  93. <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
  94. <a class="navbar-brand" href="index.php"><img style="max-height: 40px;" src="img/logo/default-logo.png"> Installation</a>
  95. <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
  96. <span class="navbar-toggler-icon"></span>
  97. </button>
  98. </nav>
  99. <!-- Begin page content -->
  100. <div class="container">
  101. <?php
  102. $entities = array();
  103. foreach(glob(__DIR__.'/connector/*.class.php') as $classFile){
  104. require_once($classFile);
  105. $className = str_replace('.class.php','',basename($classFile));
  106. $entities[$className] = $className::label.' - '.$className::description;
  107. }
  108. //check prerequisite
  109. if(file_exists(__DIR__.'/constant.php')) throw new Exception('Le script est déja installé, pour recommencer l\'installation, supprimez le fichier constant.php');
  110. if(!is_writable (__DIR__)) throw new Exception('Le dossier '.__DIR__.' doit être accessible en ecriture, merci de taper la commande linux <br/><code>sudo chown -R www-data:www-data '.__ROOT__.'</code><br/> ou de régler le dossier en écriture via votre client ftp');
  111. if(!file_exists(__DIR__.'/file')) mkdir(__DIR__.'/file',0755,true);
  112. if(!file_exists(__DIR__.'/file/avatar')) mkdir(__DIR__.'/file/avatar',0755,true);
  113. //if(!extension_loaded('gd') || !function_exists('gd_info')) throw new Exception('L\'extension php GD2 est requise, veuillez installer GD2 (sous linux : <code>sudo apt-get install php5-gd && service apache2 restart</code>)');
  114. //if(!in_array('sqlite',PDO::getAvailableDrivers())) throw new Exception('Le driver SQLITE est requis, veuillez installer sqlite3 (sous linux : <code>sudo apt-get install php5-sqlite && service apache2 restart</code>)');
  115. if(isset($_['connector'])){
  116. install_core($_,$custom);
  117. ?>
  118. <div class="alert alert-success alert-dismissable">
  119. <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
  120. <strong>Succès!</strong> La base est bien installée, l'utilisateur par défaut est <code>admin:admin</code>, pensez à changer le mot de passe rapidemment. <br>
  121. </div>
  122. <a class="btn btn-primary" href="index.php">Revenir à l'index</a>
  123. <?php
  124. } else {
  125. $root = 'http'.((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')|| $_SERVER['SERVER_PORT'] == 443?'s':'').'://'.$_SERVER['HTTP_HOST'].($_SERVER['SERVER_PORT']==80?'':':'.$_SERVER['SERVER_PORT']).$_SERVER['REQUEST_URI'];
  126. $root = str_replace("/install.php", "", $root );
  127. $parts = explode('?',$root);
  128. $root = array_shift($parts);
  129. if( method_exists($custom['class'], 'pre_form') ) $custom['class']::pre_form();
  130. ?>
  131. <div class="row justify-content-md-center">
  132. <form class="col-md-6 mt-3" action="install.php" method="POST">
  133. <h3>Installation</h3>
  134. <p class="text-muted">Merci de bien vouloir remplir les champs ci-dessous</p>
  135. <div class="input-group mb-3">
  136. <div class="input-group-prepend">
  137. <label class="input-group-text" for="connector">Type de base</label>
  138. </div>
  139. <select class="form-control" id="connector" name="connector" onchange="window.location='install.php?sgbd='+$(this).val()">
  140. <option value="">-</option>
  141. <?php foreach($entities as $class=>$label): ?>
  142. <option <?php echo (isset($_['sgbd']) && $_['sgbd']==$class ? 'selected="selected"': '') ?> value="<?php echo $class ?>"><?php echo $label; ?></option>
  143. <?php endforeach; ?>
  144. </select>
  145. </div>
  146. <?php if(isset($_['sgbd']) && $_['sgbd']!=''):
  147. require_once(__DIR__.'/connector/'.$_['sgbd'].'.class.php');
  148. foreach($_['sgbd']::fields() as $field): ?>
  149. <div class="input-group mb-3">
  150. <div class="input-group-prepend">
  151. <label class="input-group-text" for="<?php echo $field['id']; ?>"><?php echo $field['label']; ?></label>
  152. </div>
  153. <?php if(!isset($field['comment'])): ?><small><?php echo $field['comment']; ?></small><br/><?php endif; ?>
  154. <input type="text" class="form-control" value="<?php echo $field['default']; ?>" name="<?php echo $field['id']; ?>" id="<?php echo $field['id']; ?>"/></div>
  155. <?php endforeach; ?>
  156. <div class="input-group mb-3">
  157. <div class="input-group-prepend">
  158. <label class="input-group-text" for="root">Adresse web</label>
  159. </div>
  160. <input type="text" class="form-control " name="root" id="root" value="<?php echo $root; ?>"/><br/>
  161. </div>
  162. <div class="btn btn-primary right" onclick="$(this).addClass('btn-preloader');$(this).parent().get(0).submit()"><i class="far fa-check-circle"></i> Installer</div>
  163. <div class="btn btn-dark right mr-2 btn-test" onclick="check_connection()"><i class="far fa-check-circle"></i> Tester la connexion</div>
  164. </div>
  165. <?php endif; ?>
  166. </form>
  167. </div>
  168. <?php
  169. if( method_exists($custom['class'], 'post_form') ) $custom['class']::post_form();
  170. }
  171. } catch (Exception $e) { ?>
  172. <div class="alert alert-danger">
  173. <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
  174. <strong>Oops!</strong> <?php echo $e->getMessage().' - '.$e->getFile().' L'.$e->getLine().'<hr/><pre>'.$e->getTraceAsString().'</pre>';
  175. ?>
  176. </div>
  177. <?php
  178. } ?>
  179. </div>
  180. <!-- Bootstrap core JavaScript -->
  181. <!-- Placed at the end of the document so the pages load faster -->
  182. <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
  183. <script>window.jQuery || document.write('<script src="js/vendor/jquery.min.js"><\/script>')</script>
  184. <script src="js/vendor/popper.min.js"></script>
  185. <script src="js/bootstrap.min.js"></script>
  186. <script src="js/vendor/mustache.min.js"></script>
  187. <script src="js/plugins.js"></script>
  188. <script src="js/main.js"></script>
  189. <?php if( method_exists($custom['class'], 'js') ): ?>
  190. <link href="<?php echo $custom['plugin'].$custom['class']::js(); ?>" rel="stylesheet">
  191. <?php endif; ?>
  192. <script type="text/javascript">
  193. function check_connection(){
  194. var data = $('form').toJson();
  195. data.action = 'check_connection';
  196. $('.btn-test').addClass('btn-preloader');
  197. $.getJSON({
  198. url :'install.php',
  199. data : data,
  200. success:function(response){
  201. setTimeout(function(){
  202. $('.btn-test').removeClass('btn-preloader');
  203. },500);
  204. if(response.error){
  205. $.message('error',response.error);
  206. }else{
  207. $.message('success','Connecté à la base avec succès');
  208. }
  209. }
  210. });
  211. }
  212. </script>
  213. </body>
  214. </html>
  215. <?php
  216. function install_core($parameters,$custom){
  217. $constantStream = file_get_contents(__DIR__.'/constant-sample.php');
  218. $enablePlugins = array('fr.core.factory','fr.core.dashboard','fr.core.notification','fr.core.navigation');
  219. if(!isset($parameters['host'])) $parameters['host'] = '';
  220. if(!isset($parameters['login'])) $parameters['login'] = '';
  221. if(!isset($parameters['password'])) $parameters['password'] = '';
  222. if(!isset($parameters['database'])) $parameters['database'] = '';
  223. $cryptKey = base64_encode(time().$parameters['login'].mt_rand(0,1000));
  224. $tags = array_merge($parameters,array(
  225. 'cryptKey' => $cryptKey
  226. ));
  227. foreach ($tags as $key => $value) {
  228. $constantStream = str_replace("{{".$key."}}",$value,$constantStream);
  229. }
  230. file_put_contents(__DIR__.DIRECTORY_SEPARATOR.'constant.php',$constantStream);
  231. require_once(__DIR__.DIRECTORY_SEPARATOR.'constant.php');
  232. if(!file_exists(File::core())) mkdir(File::core(),0755,true);
  233. require_once(__ROOT__.'class'.SLASH.'Entity.class.php');
  234. if( method_exists($custom['class'], 'pre_install') ) $custom['class']::pre_install();
  235. //install entities
  236. Entity::install(__ROOT__.'class');
  237. global $conf,$myUser;
  238. $conf = new Configuration();
  239. $conf->getAll();
  240. //create firm
  241. $firm = new Firm();
  242. $firm->label = 'Établissement';
  243. $firm->description = 'Établissement par défaut';
  244. $firm->save();
  245. /* RANKS */
  246. //create admin rank
  247. $superAdmin = new Rank();
  248. $superAdmin->label = 'Super Admin';
  249. $superAdmin->description = 'Dispose de tous les accès';
  250. $superAdmin->superadmin = true;
  251. $superAdmin->save();
  252. //create all anonymous rank
  253. $anonymous = new Rank();
  254. $anonymous->label = 'Tout le monde - Anonyme';
  255. $anonymous->description = 'Utilisateur non connecté à la plateforme';
  256. $anonymous->superadmin = false;
  257. $anonymous->save();
  258. //create all connected rank
  259. $connected = new Rank();
  260. $connected->label = 'Tout le monde - Connecté';
  261. $connected->description = 'Utilisateur connecté à la plateforme';
  262. $connected->superadmin = false;
  263. $connected->save();
  264. //create default user
  265. $admin = new User();
  266. $admin->login = 'admin';
  267. $admin->password = User::password_encrypt('admin');
  268. $admin->firstname = 'Administrateur';
  269. $admin->name = 'Principal';
  270. $admin->superadmin = 1;
  271. $admin->state = User::ACTIVE;
  272. $admin->save();
  273. //create ufr
  274. $userfirmrank = new UserFirmRank();
  275. $userfirmrank->user = $admin->login;
  276. $userfirmrank->firm = $firm->id;
  277. $userfirmrank->rank = $superAdmin->id;
  278. $userfirmrank->save();
  279. $admin->loadRanks();
  280. $_SESSION['currentUser'] = serialize($admin);
  281. $myUser = $admin;
  282. $scopes = array();
  283. Plugin::callHook('section',array(&$scopes));
  284. foreach($scopes as $scope=>$description){
  285. $right = new Right();
  286. $right->targetUid = $superAdmin->id;
  287. $right->targetScope = 'rank';
  288. $right->scope = $scope;
  289. $right->read = true;
  290. $right->edit = true;
  291. $right->delete = true;
  292. $right->configure = true;
  293. $right->save();
  294. }
  295. //droits sur les rangs créés only par superadmin
  296. foreach (array($superAdmin->id,$anonymous->id,$connected->id) as $rankId) {
  297. $right = new Right();
  298. $right->scope = 'rank';
  299. $right->uid = $rankId;
  300. $right->read = 1;
  301. $right->edit = 1;
  302. $right->delete = 1;
  303. $right->configure = 1;
  304. $right->recursive = 1;
  305. $right->targetScope = 'rank';
  306. $right->targetUid = $superAdmin->id;
  307. $right->save();
  308. }
  309. //Activation des plugins par défaut
  310. foreach ($enablePlugins as $plugin) {
  311. if(!Plugin::exist($plugin)) continue;
  312. Plugin::state($plugin,true);
  313. }
  314. $states = Plugin::states();
  315. //Activation des plugins pour les établissements
  316. foreach(Firm::loadAll() as $firm){
  317. foreach ($enablePlugins as $plugin) {
  318. if(!Plugin::exist($plugin)) continue;
  319. $firms = $states[$plugin];
  320. $key = array_search($firm->id, $firms);
  321. $firms[] = $firm->id;
  322. $states[$plugin] = array_values($firms);
  323. Plugin::states($states);
  324. }
  325. }
  326. if( method_exists($custom['class'], 'post_install') ) $custom['class']::post_install();
  327. }
  328. ?>