action.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  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);
  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');
  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']) && $ext == $tp['extension']) $type = $uid;
  250. Type::fromFileImport($_FILES['file'],$sketch,$type);
  251. break;
  252. //COMPONENT
  253. case 'upload_component_image':
  254. global $myUser;
  255. $response = array();
  256. try{
  257. 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)));
  258. $ext = explode('.',$_FILES['file']['name']);
  259. $ext = strtolower(array_pop($ext));
  260. if(!in_array($ext,explode(',',ALLOWED_RESOURCE_IMAGE))) throw new Exception("Format d'image interdit, autorisé : ".ALLOWED_RESOURCE_IMAGE);
  261. 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)));
  262. imageResize($_FILES['file']['tmp_name'],100,100);
  263. $response['thumb'] = 'data:image/png;base64,'.base64_encode(file_get_contents($_FILES['file']['tmp_name']));
  264. }catch(Exception $e){
  265. $response['error'] = $e->getMessage();
  266. }
  267. header('Content-Type:application/json');
  268. echo json_encode($response);
  269. break;
  270. case 'search_component':
  271. Action::write(function($_,&$response){
  272. global $myUser;
  273. $parts = Part::populate();
  274. foreach($parts as $part){
  275. $part->label = html_entity_decode($part->label);
  276. $part->link = html_entity_decode($part->link);
  277. if($part->image==''){
  278. $part->image = 'img/default_image.png';
  279. }else{
  280. $part->image = PART_PATH.html_entity_decode($part->image).'?t='.time();
  281. }
  282. $response['rows'][] = $part->toArray();
  283. }
  284. });
  285. break;
  286. case 'delete_component':
  287. Action::write(function($_,&$response){
  288. global $myUser;
  289. $part = Part::getById($_['id']);
  290. if($myUser->id!=$part->owner) throw new Exception('Seul le propriétaire du composant peux faire ça');
  291. $part->remove();
  292. });
  293. break;
  294. case 'save_component':
  295. Action::write(function($_,&$response){
  296. global $myUser;
  297. if(!$myUser->connected()) throw new Exception("Permission refusée, seul un connecté peux faire ça");
  298. $part = isset($_['id']) && is_numeric($_['id'])?Part::getById($_['id']):new Part();
  299. $part->fromArray($_);
  300. $part->owner = $myUser->id;
  301. $part->save();
  302. if(substr($part->image,0,10) == 'data:image'){
  303. $imageName = $part->id.'.png';
  304. base64_to_image($part->image,PART_PATH.$imageName);
  305. $part->image = $imageName;
  306. $part->save();
  307. }
  308. $response = $part->toArray();
  309. });
  310. break;
  311. case 'edit_component':
  312. Action::write(function($_,&$response){
  313. $part = isset($_['id'])? Part::getById($_['id']):new Part;
  314. $part->label = html_entity_decode($part->label);
  315. $part->link = html_entity_decode($part->link);
  316. $part->brand = html_entity_decode($part->brand);
  317. if($part->image==''){
  318. $part->image = 'img/default_image.png';
  319. }else{
  320. $part->image = PART_PATH.html_entity_decode($part->image);
  321. }
  322. $part->image.='?t='.time();
  323. $response = $part->toArray();
  324. });
  325. break;
  326. //RESOURCE
  327. case 'save_resource':
  328. Action::write(function($_,&$response){
  329. global $myUser;
  330. $sketch = Sketch::getById($_['sketch']);
  331. if($myUser->id != $sketch->owner) throw new Exception("Permission refusée, seul l'auteur du sketch peux faire ça");
  332. $resource = isset($_['id']) && is_numeric($_['id']) && !empty($_['id']) ? Resource::getByid($_['id']) : new Resource();
  333. $resource->fromArray($_);
  334. $resource->sort = 10;
  335. if($resource->type=='readme' && $resource->id==0) $resource->sort = 0;
  336. $resource->label = $resource->label == ''?'Sans titre '.date('d-m-Y H:i'):$resource->label;
  337. $resource->save();
  338. $response = $resource->toArray();
  339. });
  340. break;
  341. case 'save_resource_content':
  342. Action::write(function($_,&$response){
  343. global $myUser;
  344. $resource = Resource::getByid($_['id']);
  345. $sketch = Sketch::getById($resource->sketch);
  346. if($myUser->id != $sketch->owner) return;
  347. $resource->fromArray($_);
  348. $resource->save();
  349. });
  350. break;
  351. case 'get_resource_file':
  352. global $myUser;
  353. $resource = Resource::getById($_['id']);
  354. $sketch =$resource->sketch_object;
  355. if($myUser->id != $sketch->owner && !$sketch->public){
  356. echo 'Désolé, vous n\'avez pas d\'accès à cette ressource...';
  357. return;
  358. }
  359. $filepath = SKETCH_PATH.$resource->id.'/'.$_['file'];
  360. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  361. $mime = finfo_file($finfo, $filepath);
  362. header('Content-Type: '.$mime);
  363. header("Content-Length: " . filesize($filepath));
  364. header('Expires: Sun, 01 Jan 2014 00:00:00 GMT');
  365. header('Cache-Control: no-store, no-cache, must-revalidate');
  366. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  367. header('Cache-Control: post-check=0, pre-check=0', FALSE);
  368. header('Pragma: no-cache');
  369. header("Content-Disposition: attachment; filename=\"".basename($filepath)."\"");
  370. echo file_get_contents($filepath);
  371. finfo_close($finfo);
  372. break;
  373. case 'get_resource_image':
  374. global $myUser;
  375. $resource = Resource::getById($_['id']);
  376. $sketch =$resource->sketch_object;
  377. if($myUser->id != $sketch->owner && !$sketch->public){
  378. readfile('img/default_image.png');
  379. return;
  380. }
  381. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  382. $filepath = SKETCH_PATH.$resource->content;
  383. $mime = finfo_file($finfo, $filepath);
  384. header('Content-Type: '.$mime);
  385. readfile($filepath);
  386. break;
  387. case 'edit_resource':
  388. Action::write(function($_,&$response){
  389. $resource = Resource::getById($_['id']);
  390. global $myUser;
  391. $sketch = Sketch::getById($resource->sketch);
  392. $resource->label = html_entity_decode($resource->label);
  393. $response = Type::toHtml($resource,$sketch);
  394. });
  395. break;
  396. case 'delete_resource':
  397. Action::write(function($_,&$response){
  398. global $myUser;
  399. $resource = Resource::getById($_['id']);
  400. $sketch = Sketch::getById($resource->sketch);
  401. if($myUser->id != $sketch->owner) throw new Exception("Permission refusée, seul l'auteur du sketch peux faire ça");
  402. Resource::getById($_['id']);
  403. $resource->remove();
  404. });
  405. break;
  406. /*FILES*/
  407. case 'search_file':
  408. Action::write(function($_,&$response){
  409. global $myUser;
  410. if(!isset($_['id']) || !is_numeric($_['id'])) throw new Exception("Ressource non spécifiée");
  411. $resource = Resource::getById($_['id']);
  412. $sketch = $resource->sketch_object;
  413. if($myUser->id != $sketch->owner && !$sketch->public) throw new Exception("Désolé, le sketch est privé");
  414. foreach(glob(SKETCH_PATH.'/'.$_['id'].'/*') as $file):
  415. $icon = getExtIcon(getExt($file));
  416. $response['rows'][] = array('id'=>basename($file),'icon'=>$icon,'label'=>basename($file),'resource'=>$resource->id);
  417. endforeach;
  418. });
  419. break;
  420. case 'download_file':
  421. global $myUser;
  422. $path = SKETCH_PATH.'/'.$_['resource'];
  423. $resource = Resource::getById($_['resource']);
  424. $sketch = $resource->sketch_object;
  425. if($myUser->id != $sketch->owner && !$sketch->public) throw new Exception("Permission refusée, le sketch est privé");
  426. $filename = $resource->label.'-'.time().'.zip';
  427. $filepath = sys_get_temp_dir().DIRECTORY_SEPARATOR.$filename;
  428. $zip = new ZipArchive;
  429. if(file_exists($filepath))unlink($filepath);
  430. $res = $zip->open($filepath, ZipArchive::CREATE);
  431. if ($res === TRUE) {
  432. foreach(glob($path.'/*') as $file)
  433. $zip->addFile($file,basename($file));
  434. $zip->close();
  435. }
  436. header("Content-Type: application/zip");
  437. header("Content-Length: " . filesize($filepath));
  438. header('Expires: Sun, 01 Jan 2014 00:00:00 GMT');
  439. header('Cache-Control: no-store, no-cache, must-revalidate');
  440. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  441. header('Cache-Control: post-check=0, pre-check=0', FALSE);
  442. header('Pragma: no-cache');
  443. header("Content-Disposition: attachment; filename=\"".$filename."\"");
  444. readfile($filepath);
  445. unlink($filepath);
  446. break;
  447. case 'delete_file':
  448. Action::write(function($_,&$response){
  449. global $myUser;
  450. $path = SKETCH_PATH.'/'.$_['resource'].'/'.$_['id'];
  451. $resource = Resource::getById($_['resource']);
  452. $sketch = $resource->sketch_object;
  453. if($myUser->id != $sketch->owner) throw new Exception("Permission refusée, seul l'auteur du sketch peux faire ça");
  454. if(file_exists($path)) unlink($path);
  455. });
  456. break;
  457. /*PART*/
  458. case 'search_part':
  459. Action::write(function($_,&$response){
  460. if(!isset($_['id']) || !is_numeric($_['id'])) throw new Exception("Ressource non spécifiée");
  461. $resourceParts = ResourcePart::loadAll(array('resource'=>$_['id']),'sort');
  462. foreach($resourceParts as $resourcePart):
  463. $part = $resourcePart->part_object;
  464. $part->label = html_entity_decode($part->label);
  465. $part->link = html_entity_decode($part->link);
  466. if($part->image == '') {
  467. $part->image = 'img/default_image.png';
  468. }else{
  469. $part->image = PART_PATH.$part->image;
  470. }
  471. $line = $part->toArray();
  472. $line['id'] = $resourcePart->id;
  473. $response['rows'][] = $line;
  474. endforeach;
  475. });
  476. break;
  477. case 'delete_part':
  478. Action::write(function($_,&$response){
  479. global $myUser;
  480. $part = ResourcePart::getById($_['id']);
  481. $resource = $part->resource_object;
  482. $sketch = $resource->sketch_object;
  483. if($myUser->id != $sketch->owner) throw new Exception("Permission refusée, seul l'auteur du sketch peux faire ça");
  484. ResourcePart::deleteById($_['id']);
  485. });
  486. break;
  487. case 'save_part':
  488. Action::write(function($_,&$response){
  489. global $myUser;
  490. $model = isset($_['model']) && is_numeric($_['model']) && !empty($_['model']) ? Part::getByid($_['model']) : new Part();
  491. if($model->id==0){
  492. $model->fromArray($_);
  493. $model->save();
  494. }
  495. $resourcePart = new ResourcePart();
  496. $resourcePart->fromArray($_);
  497. $resourcePart->part = $model->id;
  498. $resourcePart->save();
  499. });
  500. break;
  501. case 'autocomplete_part':
  502. global $myUser;
  503. $parts = Part::staticQuery("SELECT DISTINCT label,* FROM ".Part::tableName()." WHERE label LIKE ? GROUP BY label ORDER BY price ASC ",array('%'.$_['term'].'%'),true);
  504. $rows = array();
  505. levenshtein_deduplication($parts);
  506. foreach($parts as $part):
  507. $part->image = PART_PATH.$part->image;
  508. $rows[] = array('label'=>$part->label.' ('.$part->price.'€)','value'=>$part->toArray());
  509. endforeach;
  510. echo json_encode($rows);
  511. break;
  512. default:
  513. break;
  514. }
  515. function levenshtein_deduplication(&$objs){
  516. foreach($objs as $obj1):
  517. foreach($objs as $u=>$obj2):
  518. if($obj1->id==$obj2->id) continue;
  519. if(levenshtein($obj1->label,$obj2->label) < 5 )
  520. unset($objs[$u]);
  521. endforeach;
  522. endforeach;
  523. }
  524. ?>