action.php 21 KB

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