action.php 22 KB

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