action.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. <?php
  2. require_once __DIR__.DIRECTORY_SEPARATOR."common.php";
  3. if(!isset($_['action'])) throw new Exception('Action inexistante');
  4. //Execution du code en fonction de l'action
  5. switch ($_['action']){
  6. case 'login':
  7. global $myUser;
  8. try{
  9. $myUser = User::check($_['login'],$_['password']);
  10. if(!$myUser->connected()) throw new Exception('Utilisateur inexistant');
  11. $_SESSION['currentUser'] = serialize($myUser);
  12. }catch(Exception $e){
  13. $_SESSION['error'] = $e->getMessage();
  14. }
  15. header('location: index.php');
  16. break;
  17. case 'logout':
  18. unset($_SESSION['currentUser']);
  19. session_destroy();
  20. header('location: index.php');
  21. break;
  22. case 'save_user':
  23. try{
  24. global $myUser;
  25. if(!$myUser->connected()) throw new Exception("Permission refusée, seul un connecté peux faire ça");
  26. if($myUser->id!=$_['id']) throw new Exception("Permission refusée, seul le propriétaire du compte peux faire ça");
  27. if(!empty($_['password']) && $_['password']!=$_['confirmPassword']) throw new Exception("Les deux mot de passe ne correspondent pas");
  28. if(!empty($_['password'])) $myUser->password = User::password_encrypt($_['password']);
  29. $myUser->login = $_['login'];
  30. $myUser->save();
  31. $_SESSION['currentUser'] = serialize($myUser);
  32. $_SESSION['success'] = "Compte modifié avec succès";
  33. }catch(Exception $e){
  34. $_SESSION['error'] = $e->getMessage();
  35. }
  36. header('location: account.php');
  37. break;
  38. // SKETCH
  39. case 'create_sketch':
  40. Action::write(function($_,&$response){
  41. global $myUser;
  42. if(!$myUser->connected()) throw new Exception("Permission refusée, seul un connecté peux faire ça");
  43. $sketch = new Sketch();
  44. $sketch->fromArray($_);
  45. $sketch->owner = $myUser->id;
  46. $sketch->save();
  47. $resource = new Resource();
  48. $resource->label = 'README';
  49. $resource->type = 'readme';
  50. $resource->sketch = $sketch->id;
  51. $resource->content = 'Décrivez votre projet ici...';
  52. $resource->sort = 0;
  53. $resource->save();
  54. $response = $sketch->toArray();
  55. });
  56. break;
  57. case 'export_sketch':
  58. global $myUser;
  59. $response = array();
  60. try{
  61. $sketch = Sketch::getById($_['id']);
  62. if(!$sketch->public && $myUser->id!=$sketch->owner)throw new Exception('Ce sketch est privé');
  63. $response['sketch'] = $sketch->toArray();
  64. $response['resources'] = array();
  65. $types = ResourceType::all();
  66. foreach(Resource::loadAll(array('sketch'=>$_['id'])) as $resource){
  67. $type = $types[$resource->type];
  68. $response['resources'][] = $type['class']::toJson($resource);
  69. }
  70. }catch(Exception $e){
  71. $response['error'] = $e->getMessage();
  72. }
  73. $response = gzdeflate(json_encode($response));
  74. if(!isset($_['api'])){
  75. $filename = slugify($sketch->label).('.export.').date('d-m-Y_H-i').'.json';
  76. ob_end_clean();
  77. header("Content-Type: application/json");
  78. header("Content-Length: " . strlen($response));
  79. header('Expires: Sun, 01 Jan 2014 00:00:00 GMT');
  80. header('Cache-Control: no-store, no-cache, must-revalidate');
  81. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  82. header('Cache-Control: post-check=0, pre-check=0', FALSE);
  83. header('Pragma: no-cache');
  84. header("Content-Disposition: attachment; filename=\"".$filename."\"");
  85. }
  86. echo $response;
  87. break;
  88. case 'import_sketch':
  89. Action::write(function($_,&$response){
  90. global $myUser;
  91. if(!$myUser->connected()) throw new Exception("Permission refusée, seul un connecté peux faire ça");
  92. if($_['from'] == 'url'){
  93. if(!isset($_['url']) || empty($_['url'])) throw new Exception("Adresse du sketch invalide");
  94. $url = parse_url($_['url']);
  95. parse_str($url['query'], $parameters);
  96. if(!isset($parameters['id']) || empty($parameters['id']) || !is_numeric($parameters['id'])) throw new Exception("ID du sketch invalide");
  97. $contentPath = $url['scheme'].'://'.$url['host'].'/'.substr($url['path'],0,-11).'/action.php?action=export_sketch&id='.$parameters['id'].'&api=true';
  98. }else{
  99. $ext = getExt($_FILES['file']['name']);
  100. if($ext!='json') throw new Exception('Extension JSON autorisée uniquement');
  101. $contentPath = $_FILES['file']['tmp_name'];
  102. }
  103. $stream = false;
  104. try{ $stream = @file_get_contents($contentPath); }catch(Exception $a){}
  105. if($stream === false) throw new Exception("Impossible d'atteindre le contenu hackpoint : $contentPath ");
  106. $stream = gzinflate($stream);
  107. if($stream === false) throw new Exception('Impossible de décompresser le sketch...');
  108. $json = json_decode($stream,true);
  109. if($json == false) throw new Exception('Impossible de parser la réponse du hackpoint, json invalide :'.$stream);
  110. if(isset($json['error'])) throw new Exception($json['error']);
  111. $sketch = new Sketch();
  112. $sketch->fromArray($json['sketch']);
  113. $sketch->id = null;
  114. $sketch->owner = $myUser->id;
  115. $sketch->public = 0;
  116. $sketch->label = $sketch->label .='-import-'.date('d/m/Y H:i');
  117. $sketch->save();
  118. $types = ResourceType::all();
  119. foreach($json['resources'] as $res){
  120. $resource = new Resource();
  121. $resource->fromArray($res);
  122. $resource->id = null;
  123. $resource->sketch = $sketch->id;
  124. $type = $types[$resource->type];
  125. $resource = $type['class']::fromJson($resource);
  126. $resource->save();
  127. }
  128. });
  129. break;
  130. case 'search_sketch':
  131. Action::write(function($_,&$response){
  132. global $myUser;
  133. $filters = array('public'=>1);
  134. if($myUser->connected()){
  135. $filters = array('owner'=>$myUser->id);
  136. }
  137. $sketchs = Sketch::loadAll($filters, "label ASC");
  138. foreach($sketchs as $sketch){
  139. $sketch->label = html_entity_decode($sketch->label);
  140. $sketch->owner = User::getById($sketch->owner)->login;
  141. $sketch->public = $sketch->public==1?true:false;
  142. $response['rows'][] = $sketch->toArray();
  143. }
  144. });
  145. break;
  146. case 'delete_sketch':
  147. Action::write(function($_,&$response){
  148. global $myUser;
  149. $sketch = Sketch::getById($_['id']);
  150. if($myUser->id != $sketch->owner) throw new Exception("Permission refusée, seul l'auteur du sketch peux faire ça");
  151. Part::staticQuery("delete FROM ".ResourcePart::tableName()." WHERE resource IN(SELECT id FROM ".Resource::tableName()." WHERE sketch=".$_['id'].") ");
  152. foreach(Resource::loadAll(array('sketch'=>$_['id'])) as $resource):
  153. $resource->remove();
  154. endforeach;
  155. Sketch::deleteById($_['id']);
  156. });
  157. break;
  158. case 'save_sketch_title':
  159. Action::write(function($_,&$response){
  160. global $myUser;
  161. $sketch = Sketch::getById($_['id']);
  162. if($myUser->id != $sketch->owner) return;
  163. $sketch->fromArray($_);
  164. $sketch->save();
  165. });
  166. break;
  167. case 'toggle_share_sketch':
  168. Action::write(function($_,&$response){
  169. global $myUser;
  170. $sketch = Sketch::getById($_['id']);
  171. if($myUser->id != $sketch->owner) throw new Exception("Permission refusée, seul l'auteur du sketch peux faire ça");
  172. $sketch->public = $_['state'];
  173. $sketch->save();
  174. });
  175. break;
  176. case 'download_sketch':
  177. $sketch = Sketch::getByid($_['id']);
  178. $resources = Resource::loadAll(array('sketch'=>$sketch->id),'sort');
  179. $filename = $sketch->slug.'-'.time().'.zip';
  180. $filepath = sys_get_temp_dir().DIRECTORY_SEPARATOR.$filename;
  181. $zip = new ZipArchive;
  182. $res = $zip->open($filepath, ZipArchive::CREATE);
  183. if ($res === TRUE) {
  184. foreach($resources as $resource){
  185. $type = ResourceType::all($resource->type);
  186. $file = $type['class']::toFile($resource);
  187. $zip->addFromString($file['name'], $file['content']);
  188. }
  189. $zip->close();
  190. }
  191. ob_end_clean();
  192. header("Content-Type: application/zip");
  193. header("Content-Length: " . filesize($filepath));
  194. header('Expires: Sun, 01 Jan 2014 00:00:00 GMT');
  195. header('Cache-Control: no-store, no-cache, must-revalidate');
  196. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  197. header('Cache-Control: post-check=0, pre-check=0', FALSE);
  198. header('Pragma: no-cache');
  199. header("Content-Disposition: attachment; filename=\"".$filename."\"");
  200. readfile($filepath);
  201. unlink($filepath);
  202. break;
  203. // RESOURCES
  204. case 'upload_resource':
  205. Action::write(function($_,&$response){
  206. global $myUser;
  207. $resource = Resource::getByid($_['id']);
  208. $sketch = Sketch::getById($resource->sketch);
  209. $ext = getExt($_FILES['file']['name']);
  210. if($myUser->id != $sketch->owner) throw new Exception("Seul le propriétaire du sketch peux faire ça");
  211. if(!in_array($ext,explode(',',ALLOWED_RESOURCE_IMAGE))) throw new Exception('Extensions autorisées '.ALLOWED_RESOURCE_IMAGE);
  212. if($_FILES['file']['size']>ALLOWED_RESOURCE_SIZE) throw new Exception('Taille maximum autorisée '.ALLOWED_RESOURCE_SIZE.' o');
  213. $name = $resource->id.'.'.$ext;
  214. $path = SKETCH_PATH.$name;
  215. move_uploaded_file($_FILES['file']['tmp_name'], $path);
  216. $resource->content = $name;
  217. $resource->save();
  218. $response = array_merge(ResourceType::all($resource->type));
  219. $response['url'] ="action.php?action=get_resource_image&id=".$resource->id."&v=".time();
  220. });
  221. break;
  222. case 'upload_resource_file':
  223. Action::write(function($_,&$response){
  224. global $myUser;
  225. $resource = Resource::getByid($_['id']);
  226. $sketch = Sketch::getById($resource->sketch);
  227. $ext = getExt($_FILES['file']['name']);
  228. if($myUser->id != $sketch->owner) throw new Exception("Seul le propriétaire du sketch peux faire ça");
  229. if(ALLOWED_RESOURCE_FILE!='' && !in_array($ext,explode(',',ALLOWED_RESOURCE_FILE))) throw new Exception('Extensions autorisées '.ALLOWED_RESOURCE_FILE);
  230. if($_FILES['file']['size']>ALLOWED_RESOURCE_SIZE) throw new Exception('Taille maximum autorisée '.ALLOWED_RESOURCE_SIZE.' o');
  231. $name = $resource->id;
  232. $folder = SKETCH_PATH.$name;
  233. if(!file_exists($folder)) mkdir($folder);
  234. $path = $folder.'/'.$_FILES['file']['name'];
  235. move_uploaded_file($_FILES['file']['tmp_name'], $path);
  236. $response = array_merge(ResourceType::all($resource->type));
  237. $response['url'] = $path.'?v='.time();
  238. });
  239. break;
  240. case 'search_resources':
  241. Action::write(function($_,&$response){
  242. if(!isset($_['id']) || !is_numeric($_['id'])) throw new Exception("Sketch non spécifié");
  243. $resources = Resource::loadAll(array('sketch'=>$_['id']),'sort ASC, label ASC');
  244. foreach($resources as $resource){
  245. $resource->label = html_entity_decode($resource->label);
  246. $resource->content = null;
  247. $resource = $resource->toArray();
  248. $response['rows'][] = $resource;
  249. }
  250. });
  251. break;
  252. case 'import_resource':
  253. global $myUser;
  254. $sketch = Sketch::getByid($_['id']);
  255. if($myUser->id != $sketch->owner) return;
  256. $ext = explode('.',$_FILES['file']['name']);
  257. $ext = strtolower(array_pop($ext));
  258. $types = ResourceType::all();
  259. $type = ResourceType::all('readme');
  260. foreach($types as $uid=>$tp){
  261. if(!isset($tp['fromExtension'])) continue;
  262. if(in_array($ext, $tp['fromExtension'])) $type = $tp;
  263. }
  264. $resource = new Resource();
  265. $resource->sketch = $sketch->id;
  266. $stream = file_get_contents($_FILES['file']['tmp_name']);
  267. $resource->label = $_FILES['file']['name'];
  268. $resource->type = $type['uid'];
  269. $resource->content = $stream;
  270. $resource = $type['class']::fromFile($resource,$sketch);
  271. $resource->save();
  272. break;
  273. // PLUGINS
  274. case 'search_plugin':
  275. Action::write(function($_,&$response){
  276. global $myUser;
  277. if( $myUser->rank != 'ADMIN' ) throw new Exception("Permissions insuffisantes");
  278. foreach(Plugin::getAll() as $plugin){
  279. $plugin->folder = array('name'=>$plugin->folder,'path'=>$plugin->path());
  280. $response['rows'][] = $plugin;
  281. }
  282. });
  283. break;
  284. case 'change_plugin_state':
  285. Action::write(function($_,&$response){
  286. global $myUser;
  287. if( $myUser->rank != 'ADMIN' ) throw new Exception("Permissions insuffisantes");
  288. $plugin = Plugin::getById($_['plugin']);
  289. if($_['state']){
  290. $states = Plugin::states();
  291. $missingRequire = array();
  292. foreach($plugin->require as $require=>$version):
  293. $req = Plugin::getById($require);
  294. if($req == null || $req==false || !$req->state || $req->version!=$version)
  295. $missingRequire[]= $require.' - '.$version;
  296. endforeach;
  297. if(count($missingRequire)!=0) throw new Exception("Plugins pré-requis non installés : ".implode(',',$missingRequire));
  298. }
  299. Plugin::state($_['plugin'],$_['state']);
  300. });
  301. break;
  302. //COMPONENT
  303. case 'upload_component_image':
  304. global $myUser;
  305. $response = array();
  306. try{
  307. if(!isset($_FILES['file'])) throw new Exception("Le fichier est trop gros pour votre configuration php (php.ini), taille max :".max_upload_size(array(ALLOWED_RESOURCE_SIZE)));
  308. $ext = explode('.',$_FILES['file']['name']);
  309. $ext = strtolower(array_pop($ext));
  310. if(!in_array($ext,explode(',',ALLOWED_RESOURCE_IMAGE))) throw new Exception("Format d'image interdit, autorisé : ".ALLOWED_RESOURCE_IMAGE);
  311. if($_FILES['file']['size']>ALLOWED_RESOURCE_SIZE) throw new Exception("Le fichier est trop gros pour votre configuration programme, taille max: ".max_upload_size(array(ALLOWED_RESOURCE_SIZE)));
  312. imageResize($_FILES['file']['tmp_name'],100,100);
  313. $response['thumb'] = 'data:image/png;base64,'.base64_encode(file_get_contents($_FILES['file']['tmp_name']));
  314. }catch(Exception $e){
  315. $response['error'] = $e->getMessage();
  316. }
  317. header('Content-Type:application/json');
  318. echo json_encode($response);
  319. break;
  320. case 'search_component':
  321. Action::write(function($_,&$response){
  322. global $myUser;
  323. $parts = Part::populate();
  324. foreach($parts as $part){
  325. $part->label = html_entity_decode($part->label);
  326. $part->link = html_entity_decode($part->link);
  327. if($part->image==''){
  328. $part->image = 'img/default_image.png';
  329. }else{
  330. $part->image = PART_PATH.html_entity_decode($part->image).'?t='.time();
  331. }
  332. $response['rows'][] = $part->toArray();
  333. }
  334. });
  335. break;
  336. case 'delete_component':
  337. Action::write(function($_,&$response){
  338. global $myUser;
  339. $part = Part::getById($_['id']);
  340. if($myUser->id!=$part->owner) throw new Exception('Seul le propriétaire du composant peux faire ça');
  341. $part->remove();
  342. });
  343. break;
  344. case 'save_component':
  345. Action::write(function($_,&$response){
  346. global $myUser;
  347. if(!$myUser->connected()) throw new Exception("Permission refusée, seul un connecté peux faire ça");
  348. $part = isset($_['id']) && is_numeric($_['id'])?Part::getById($_['id']):new Part();
  349. $part->fromArray($_);
  350. $part->owner = $myUser->id;
  351. $part->save();
  352. if(substr($part->image,0,10) == 'data:image'){
  353. $imageName = $part->id.'.png';
  354. base64_to_image($part->image,PART_PATH.$imageName);
  355. $part->image = $imageName;
  356. $part->save();
  357. }
  358. $response = $part->toArray();
  359. });
  360. break;
  361. case 'edit_component':
  362. Action::write(function($_,&$response){
  363. $part = isset($_['id'])? Part::getById($_['id']):new Part;
  364. $part->label = html_entity_decode($part->label);
  365. $part->link = html_entity_decode($part->link);
  366. $part->brand = html_entity_decode($part->brand);
  367. if($part->image==''){
  368. $part->image = 'img/default_image.png';
  369. }else{
  370. $part->image = PART_PATH.html_entity_decode($part->image);
  371. }
  372. $part->image.='?t='.time();
  373. $response = $part->toArray();
  374. });
  375. break;
  376. //RESOURCE
  377. case 'save_resource':
  378. Action::write(function($_,&$response){
  379. global $myUser;
  380. $sketch = Sketch::getById($_['sketch']);
  381. if($myUser->id != $sketch->owner) throw new Exception("Permission refusée, seul l'auteur du sketch peux faire ça");
  382. $resource = isset($_['id']) && is_numeric($_['id']) && !empty($_['id']) ? Resource::getByid($_['id']) : new Resource();
  383. $resource->fromArray($_);
  384. $resource->sort = 10;
  385. if($resource->type=='readme' && $resource->id==0) $resource->sort = 0;
  386. $resource->label = $resource->label == ''?'Sans titre '.date('d-m-Y H:i'):$resource->label;
  387. $resource->save();
  388. $response = $resource->toArray();
  389. });
  390. break;
  391. case 'save_resource_content':
  392. Action::write(function($_,&$response){
  393. global $myUser;
  394. $resource = Resource::getByid($_['id']);
  395. $sketch = Sketch::getById($resource->sketch);
  396. if($myUser->id != $sketch->owner) return;
  397. $resource->fromArray($_);
  398. $resource->save();
  399. });
  400. break;
  401. case 'get_resource_file':
  402. global $myUser;
  403. ob_end_clean();
  404. $resource = Resource::getById($_['id']);
  405. $sketch =$resource->sketch_object;
  406. if($myUser->id != $sketch->owner && !$sketch->public){
  407. echo 'Désolé, vous n\'avez pas d\'accès à cette ressource...';
  408. return;
  409. }
  410. $filepath = SKETCH_PATH.$resource->id.'/'.$_['file'];
  411. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  412. $mime = finfo_file($finfo, $filepath);
  413. header('Content-Type: '.$mime);
  414. header("Content-Length: " . filesize($filepath));
  415. header('Expires: Sun, 01 Jan 2014 00:00:00 GMT');
  416. header('Cache-Control: no-store, no-cache, must-revalidate');
  417. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  418. header('Cache-Control: post-check=0, pre-check=0', FALSE);
  419. header('Pragma: no-cache');
  420. header("Content-Disposition: attachment; filename=\"".basename($filepath)."\"");
  421. echo file_get_contents($filepath);
  422. finfo_close($finfo);
  423. break;
  424. case 'get_resource_image':
  425. global $myUser;
  426. ob_end_clean();
  427. $resource = Resource::getById($_['id']);
  428. $sketch =$resource->sketch_object;
  429. if($myUser->id != $sketch->owner && !$sketch->public){
  430. readfile('img/default_image.png');
  431. return;
  432. }
  433. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  434. $filepath = SKETCH_PATH.$resource->content;
  435. $mime = finfo_file($finfo, $filepath);
  436. header('Content-Type: '.$mime);
  437. echo file_get_contents($filepath);
  438. finfo_close($finfo);
  439. exit();
  440. break;
  441. case 'edit_resource':
  442. Action::write(function($_,&$response){
  443. if(!isset($_['id']) || empty($_['id']) || $_['id']==0) return;
  444. $resource = Resource::getById($_['id']);
  445. if(!$resource) return;
  446. global $myUser;
  447. $sketch = Sketch::getById($resource->sketch);
  448. $resource->label = html_entity_decode($resource->label);
  449. $response = $resource->toArray();
  450. $type = ResourceType::all($resource->type);
  451. $response = array_merge($response,$type['class']::toHtml($resource,$sketch));
  452. if(isset($response['codemirror'])) $response['code'] = $response['codemirror'];
  453. if($myUser->id != $sketch->owner) $response['code']['readOnly'] = true;
  454. });
  455. break;
  456. case 'delete_resource':
  457. Action::write(function($_,&$response){
  458. global $myUser;
  459. $resource = Resource::getById($_['id']);
  460. $sketch = Sketch::getById($resource->sketch);
  461. if($myUser->id != $sketch->owner) throw new Exception("Permission refusée, seul l'auteur du sketch peux faire ça");
  462. Resource::getById($_['id']);
  463. $resource->remove();
  464. });
  465. break;
  466. /*FILES*/
  467. case 'search_file':
  468. Action::write(function($_,&$response){
  469. global $myUser;
  470. if(!isset($_['id']) || !is_numeric($_['id'])) throw new Exception("Ressource non spécifiée");
  471. $resource = Resource::getById($_['id']);
  472. $sketch = $resource->sketch_object;
  473. if($myUser->id != $sketch->owner && !$sketch->public) throw new Exception("Désolé, le sketch est privé");
  474. foreach(glob(SKETCH_PATH.'/'.$_['id'].'/*') as $file):
  475. $icon = getExtIcon(getExt($file));
  476. $response['rows'][] = array('id'=>basename($file),'icon'=>$icon,'label'=>basename($file),'resource'=>$resource->id);
  477. endforeach;
  478. });
  479. break;
  480. case 'download_file':
  481. global $myUser;
  482. $path = SKETCH_PATH.'/'.$_['resource'];
  483. $resource = Resource::getById($_['resource']);
  484. $sketch = $resource->sketch_object;
  485. if($myUser->id != $sketch->owner && !$sketch->public) throw new Exception("Permission refusée, le sketch est privé");
  486. $filename = $resource->label.'-'.time().'.zip';
  487. $filepath = sys_get_temp_dir().DIRECTORY_SEPARATOR.$filename;
  488. $zip = new ZipArchive;
  489. if(file_exists($filepath))unlink($filepath);
  490. $res = $zip->open($filepath, ZipArchive::CREATE);
  491. if ($res === TRUE) {
  492. foreach(glob($path.'/*') as $file)
  493. $zip->addFile($file,basename($file));
  494. $zip->close();
  495. }
  496. ob_end_clean();
  497. header("Content-Type: application/zip");
  498. header("Content-Length: " . filesize($filepath));
  499. header('Expires: Sun, 01 Jan 2014 00:00:00 GMT');
  500. header('Cache-Control: no-store, no-cache, must-revalidate');
  501. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  502. header('Cache-Control: post-check=0, pre-check=0', FALSE);
  503. header('Pragma: no-cache');
  504. header("Content-Disposition: attachment; filename=\"".$filename."\"");
  505. readfile($filepath);
  506. unlink($filepath);
  507. break;
  508. case 'delete_file':
  509. Action::write(function($_,&$response){
  510. global $myUser;
  511. $path = SKETCH_PATH.'/'.$_['resource'].'/'.$_['id'];
  512. $resource = Resource::getById($_['resource']);
  513. $sketch = $resource->sketch_object;
  514. if($myUser->id != $sketch->owner) throw new Exception("Permission refusée, seul l'auteur du sketch peux faire ça");
  515. if(file_exists($path)) unlink($path);
  516. });
  517. break;
  518. /*PART*/
  519. case 'search_part':
  520. Action::write(function($_,&$response){
  521. if(!isset($_['id']) || !is_numeric($_['id'])) throw new Exception("Ressource non spécifiée");
  522. $resourceParts = ResourcePart::loadAll(array('resource'=>$_['id']),'sort');
  523. foreach($resourceParts as $resourcePart):
  524. $part = $resourcePart->part_object;
  525. $part->label = html_entity_decode($part->label);
  526. $part->link = html_entity_decode($part->link);
  527. if($part->image == '') {
  528. $part->image = 'img/default_image.png';
  529. }else{
  530. $part->image = PART_PATH.$part->image;
  531. }
  532. $line = $part->toArray();
  533. $line['id'] = $resourcePart->id;
  534. $response['rows'][] = $line;
  535. endforeach;
  536. });
  537. break;
  538. case 'delete_part':
  539. Action::write(function($_,&$response){
  540. global $myUser;
  541. $part = ResourcePart::getById($_['id']);
  542. $resource = $part->resource_object;
  543. $sketch = $resource->sketch_object;
  544. if($myUser->id != $sketch->owner) throw new Exception("Permission refusée, seul l'auteur du sketch peux faire ça");
  545. ResourcePart::deleteById($_['id']);
  546. });
  547. break;
  548. case 'save_part':
  549. Action::write(function($_,&$response){
  550. global $myUser;
  551. $model = isset($_['model']) && is_numeric($_['model']) && !empty($_['model']) ? Part::getByid($_['model']) : new Part();
  552. if($model->id==0){
  553. $model->fromArray($_);
  554. $model->save();
  555. }
  556. $resourcePart = new ResourcePart();
  557. $resourcePart->fromArray($_);
  558. $resourcePart->part = $model->id;
  559. $resourcePart->save();
  560. });
  561. break;
  562. case 'autocomplete_part':
  563. global $myUser;
  564. $parts = Part::staticQuery("SELECT DISTINCT label,* FROM ".Part::tableName()." WHERE label LIKE ? GROUP BY label ORDER BY price ASC ",array('%'.$_['term'].'%'),true);
  565. $rows = array();
  566. levenshtein_deduplication($parts);
  567. foreach($parts as $part):
  568. $part->image = PART_PATH.$part->image;
  569. $rows[] = array('label'=>$part->label.' ('.$part->price.'€)','value'=>$part->toArray());
  570. endforeach;
  571. echo json_encode($rows);
  572. break;
  573. default:
  574. Plugin::callHook("action");
  575. break;
  576. }
  577. function levenshtein_deduplication(&$objs){
  578. foreach($objs as $obj1):
  579. foreach($objs as $u=>$obj2):
  580. if($obj1->id==$obj2->id) continue;
  581. if(levenshtein($obj1->label,$obj2->label) < 5 )
  582. unset($objs[$u]);
  583. endforeach;
  584. endforeach;
  585. }
  586. ?>