action.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. <?php
  2. if (isset($_GET['action']) && $_GET['action'] == 'KNOCK_KNOCK_YANA') exit('1');
  3. if(!ini_get('safe_mode')) @set_time_limit(0);
  4. require_once(dirname(__FILE__).'/common.php');
  5. if(php_sapi_name() == 'cli'){
  6. $_['action'] = $_SERVER['argv'][1];
  7. }
  8. $response = array();
  9. Plugin::callHook("action_pre_case", array(&$_,$myUser));
  10. if(!$myUser && isset($_['token'])){
  11. $userManager = new User();
  12. $myUser = $userManager->load(array('token'=>$_['token']));
  13. if(isset($myUser) && $myUser!=false)
  14. $myUser->loadRight();
  15. }
  16. $myUser = (!$myUser?new User():$myUser);
  17. //Execution du code en fonction de l'action
  18. switch ($_['action']){
  19. case 'login':
  20. global $conf;
  21. $user = $userManager->exist($_['login'],$_['password']);
  22. $error = '?init=1';
  23. if($user==false){
  24. $error .= '&error='.urlencode('le compte spécifié est inexistant');
  25. }else{
  26. $_SESSION['currentUser'] = serialize($user);
  27. if(isset($_['rememberMe'])){
  28. $expire_time = time() + $conf->get('COOKIE_LIFETIME')*86400; //Jour en secondes
  29. //On crée un cookie dans la bd uniquement si aucun autre cookie n'existe sinon
  30. //On rend inutilisable le cookie utilisé par un autre navigateur
  31. //On ne veut que cela soit le cas uniquement si on clique sur déconnexion (et que l'on a demandé Se souvenir de moi)
  32. $actual_cookie = $user->getCookie();
  33. if ($actual_cookie == "")
  34. {
  35. $cookie_token = sha1(time().rand(0,1000));
  36. $user->setCookie($cookie_token);
  37. $user->save();
  38. }
  39. else
  40. {
  41. $cookie_token = $actual_cookie;
  42. }
  43. Functions::makeCookie($conf->get('COOKIE_NAME'),$cookie_token,$expire_time);
  44. }
  45. }
  46. header('location: ./index.php'.$error);
  47. break;
  48. case 'GET_TOKEN':
  49. $user = $userManager->load(array('login'=>$_['login'],'password'=>sha1(md5($_['password']))));
  50. $response['token'] = $user->getToken();
  51. echo json_encode($response);
  52. break;
  53. case 'user_add_user':
  54. $right_toverify = isset($_['id']) ? 'u' : 'c';
  55. if($myUser->can('user',$right_toverify)){
  56. $user = new User();
  57. //Si modification on charge la ligne au lieu de la créer
  58. if ($right_toverify == "u"){$user = $user->load(array("id"=>$_['id']));}
  59. $user->setMail($_['mailUser']);
  60. $user->setName($_['nameUser']);
  61. $user->setFirstName($_['firstNameUser']);
  62. $user->setPassword($_['passwordUser']);
  63. $user->setLogin($_['loginUser']);
  64. $user->setRank($_['rankUser']);
  65. $user->setState(1);
  66. $user->setToken(sha1(time().rand(0,1000)));
  67. $user->save();
  68. Functions::goback("setting","user");
  69. }
  70. else
  71. {
  72. Functions::goback("setting","user","&error=Vous n'avez pas le droit de faire ça!");
  73. }
  74. break;
  75. case 'delete_user':
  76. if(!$myUser->can('user','d')) exit('ERREUR: Permissions insuffisantes.');
  77. $userManager = new User();
  78. $NbUsers = $userManager->rowCount();
  79. if(isset($_['id']) && $NbUsers > 1){
  80. $userManager->delete(array('id'=>$_['id']));
  81. Functions::goback("setting","user");
  82. }
  83. else
  84. {
  85. Functions::goback("setting","user","&error=Impossible de supprimer le dernier utilisateur.");
  86. }
  87. break;
  88. case 'access_delete_rank':
  89. if(!$myUser->can('configuration','d')) exit('ERREUR: Permissions insuffisantes.');
  90. $rankManager = new Rank();
  91. $Nbrank = $rankManager->rowCount();
  92. if(isset($_['id']) && $Nbrank > 1){
  93. $rankManager->delete(array('id'=>$_['id']));
  94. Functions::goback("setting","access");
  95. header('location:setting.php?section=access');
  96. }
  97. else
  98. {
  99. Functions::goback("setting","access","&error=Impossible de supprimer le dernier rang.");
  100. }
  101. break;
  102. case 'access_add_rank':
  103. $right_toverify = isset($_['id']) ? 'u' : 'c';
  104. if(!$myUser->can('configuration',$right_toverify)) exit('ERREUR: Permissions insuffisantes.');
  105. $rank = new Rank();
  106. if ($right_toverify == "u"){$rank = $rank->load(array("id"=>$_['id']));}
  107. $rank->setLabel($_['labelRank']);
  108. $rank->setDescription($_['descriptionRank']);
  109. $rank->save();
  110. Functions::goback("setting","access");
  111. break;
  112. case 'set_rank_access':
  113. if(!$myUser->can('configuration','c')) exit('ERREUR: Permissions insuffisantes.');
  114. $right = new Right();
  115. $right = $right->load(array('section'=>$_['section'],'rank'=>$_['rank']));
  116. $right = (!$right?new Right():$right);
  117. $right->setSection($_['section']);
  118. $_['state'] = ($_['state']==1?true:false);
  119. switch($_['access']){
  120. case 'c':
  121. $right->setCreate($_['state']);
  122. break;
  123. case 'r':
  124. $right->setRead($_['state']);
  125. break;
  126. case 'u':
  127. $right->setUpdate($_['state']);
  128. break;
  129. case 'd':
  130. $right->setDelete($_['state']);
  131. break;
  132. }
  133. $right->setRank($_['rank']);
  134. $right->save();
  135. break;
  136. if(!$myUser->can('configuration','d')) exit('ERREUR: Permissions insuffisantes.');
  137. case 'access_delete_right':
  138. $rankManager = new Right();
  139. $rankManager->delete(array('id'=>$_['id']));
  140. Functions::goback("setting","right","&id=".$_['rank']);
  141. break;
  142. case 'logout':
  143. global $conf;
  144. //Détruire le cookie uniquement s'il existe sur cette ordinateur
  145. //Afin de le garder dans la BD pour les autres ordinateurs/navigateurs
  146. if(isset($_COOKIE[$conf->get('COOKIE_NAME')])){
  147. $user = new User();
  148. $user = $userManager->load(array("id"=>$myUser->getId()));
  149. $user->setCookie("");
  150. $user->save();
  151. Functions::destroyCookie($conf->get('COOKIE_NAME'));
  152. }
  153. $_SESSION = array();
  154. session_unset();
  155. session_destroy();
  156. Functions::goback(" ./index");
  157. break;
  158. case 'save_sentence':
  159. global $conf;
  160. $conf->put('last_sentence',$_['sentence']);
  161. break;
  162. case 'ENABLE_DASHBOARD':
  163. Plugin::enabled('dashboard-dashboard');
  164. Plugin::enabled('dashboard-monitoring-dashboard-monitoring');
  165. header('location: index.php');
  166. break;
  167. case 'changePluginState':
  168. if($myUser==false) exit('Vous devez vous connecter pour cette action.');
  169. if(!$myUser->can('plugin','u')) exit('ERREUR: Permissions insuffisantes.');
  170. if($_['state']=='0'){
  171. Plugin::enabled($_['plugin']);
  172. }else{
  173. Plugin::disabled($_['plugin']);
  174. }
  175. Functions::goback("setting","plugin","&block=".$_['block']);
  176. break;
  177. case 'crontab':
  178. Plugin::callHook("cron", array());
  179. break;
  180. case 'GET_SPEECH_COMMAND':
  181. if($myUser->getId()=='') exit('{"error":"invalid or missing token"}');
  182. if(!$myUser->can('vocal','r')) exit('{"error":"insufficient permissions for this account"}');
  183. list($host,$port) = explode(':',$_SERVER['HTTP_HOST']);
  184. $actionUrl = 'http://'.$host.':'.$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI'];
  185. $actionUrl = substr($actionUrl,0,strpos($actionUrl , '?'));
  186. Plugin::callHook("vocal_command", array(&$response,$actionUrl));
  187. $json = json_encode($response);
  188. echo ($json=='[]'?'{}':$json);
  189. break;
  190. case 'GET_EVENT':
  191. if($myUser->getId()=='') exit('{"error":"invalid or missing token"}');
  192. if(!$myUser->can('vocal','r')) exit('{"error":"insufficient permissions for this account"}');
  193. $response = array('responses'=>array());
  194. Plugin::callHook("get_event", array(&$response));
  195. $checker = (isset($_['checker'])?$_['checker']:'client');
  196. $eventManager = new Event();
  197. $events = $eventManager->loadAll(array(),'id');
  198. $time = date('i-H-d-m-Y');
  199. list($minut,$hour,$day,$month,$year) = explode('-',$time);
  200. foreach ($events as $event) {
  201. if(in_array($checker,$event->getRecipients()) && $event->getState()=='1'){
  202. if(
  203. ($event->getMinut() == '*' || in_array($minut,explode(',',$event->getMinut())) ) &&
  204. ($event->getHour() == '*' || in_array($hour,explode(',',$event->getHour())) ) &&
  205. ($event->getDay()== '*' || in_array($day,explode(',',$event->getDay())) ) &&
  206. ($event->getMonth() == '*' || in_array($month,explode(',',$event->getMonth())) ) &&
  207. ($event->getYear() == '*' || in_array($year,explode(',',$event->getYear())) )
  208. ){
  209. if($event->getRepeat()!=$time){
  210. if(in_array($checker, $event->getRecipients())){
  211. $event->setRepeat($time);
  212. $response['responses'][]= $event->getContent();
  213. //Le serveur ne peux qu'executer des commandes programme
  214. if($checker=='server'){
  215. $content = $event->getContent();
  216. switch($content['type']){
  217. case 'command':
  218. exec(htmlspecialchars_decode($content['program']));
  219. break;
  220. case 'gpio':
  221. foreach(explode(',',$content['gpios']) as $info){
  222. list($gpio,$state) = explode(':',$info);
  223. exec('gpio mode '.$gpio.' out');
  224. exec('gpio write '.$gpio.' '.$state);
  225. }
  226. break;
  227. }
  228. }
  229. $event->save();
  230. }
  231. }
  232. }
  233. }
  234. }
  235. $json = json_encode($response);
  236. echo ($json=='[]'?'{}':$json);
  237. break;
  238. case 'installPlugin':
  239. try{
  240. if($myUser==false) throw new Exception('Vous devez vous connecter pour cette action.');
  241. $tempZipName = 'plugins'.SLASH.md5(microtime());
  242. echo '<br/>Téléchargement du plugin...';
  243. file_put_contents($tempZipName,file_get_contents(urldecode($_['zip'])));
  244. if(!file_exists($tempZipName)) throw new Exception("Echec du téléchargement");
  245. echo '<br/>Plugin téléchargé <span class="label label-success">OK</span>';
  246. echo '<br/>Extraction du plugin...';
  247. $zip = new ZipArchive;
  248. $res = $zip->open($tempZipName);
  249. if ($res !== TRUE) throw new Exception("Echec de l\'extraction");
  250. $tempZipFolder = $tempZipName.'_';
  251. $zip->extractTo($tempZipFolder);
  252. $zip->close();
  253. echo '<br/>Plugin extrait '.$tempZipFolder.' <span class="label label-success">OK</span>';
  254. $i = 0;
  255. $pluginName = array();
  256. while(count($pluginName)==0 && $i<10){
  257. $pluginName = glob($tempZipFolder.SLASH.( str_repeat('*'.SLASH, $i) ).'*.plugin*.php');
  258. $i++;
  259. }
  260. if(count($pluginName)==0) throw new Exception("Plugin invalide, fichier principal manquant");
  261. $pluginName = str_replace(array($tempZipFolder.'/','.enabled','.disabled','.plugin','.php'),'',$pluginName[0]);
  262. $finalPath = __DIR__.SLASH.'plugins'.SLASH.basename(dirname($pluginName));
  263. if(file_exists($finalPath)){
  264. echo '<br/>Plugin déjà installé, il sera écrasé par la derniere version <span class="label label-info">OK</span>';
  265. Functions::rmFullDir($finalPath);
  266. }
  267. echo '<br/>Renommage...';
  268. if(rename(__DIR__.SLASH.dirname($pluginName),$finalPath )){
  269. echo '<br/>Plugin installé, <span class="label label-info">pensez à l\'activer</span>';
  270. }else{
  271. //Functions::rmFullDir(__DIR__.SLASH.$tempZipFolder);
  272. echo '<br/>Impossible de renommer le plugin '.__DIR__.SLASH.$tempZipFolder.' <span class="label label-error">Erreur</span>';
  273. }
  274. unlink($tempZipName);
  275. if(file_exists($tempZipFolder)) Functions::rmFullDir($tempZipFolder);
  276. }catch(Exception $e){
  277. if($tempZipFolder!=null && file_exists($tempZipFolder)) Functions::rmFullDir($tempZipFolder);
  278. if($tempZipName!=null && file_exists($tempZipName)) unlink($tempZipName);
  279. echo '<br/>'.$e->getMessage().' <span class="label label-error">Erreur</span>';
  280. }
  281. break;
  282. case 'CHANGE_GPIO_STATE':
  283. if($myUser==false) {
  284. exit('Vous devez vous connecter pour cette action.');
  285. }
  286. else {
  287. Gpio::write($_["pin"],$_["state"],true);
  288. }
  289. break;
  290. case 'GPIO_HAS_CHANGED':
  291. list($program,$action,$pin,$state) = $_SERVER['argv'];
  292. Gpio::emit($pin,$state);
  293. break;
  294. // Gestion des interfaces de seconde génération
  295. case 'ADD_CLIENT':
  296. Action::write(function($_,&$response){
  297. global $myUser,$conf,$client;
  298. if(!isset($_SERVER['argv'][2])) throw new Exception("Type client invalide");
  299. file_put_contents('filename', $_SERVER['argv'][2]);
  300. });
  301. break;
  302. default:
  303. Plugin::callHook("action_post_case", array());
  304. break;
  305. }
  306. ?>