action.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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. ob_end_clean();
  358. $resource = Resource::getById($_['id']);
  359. $sketch =$resource->sketch_object;
  360. if($myUser->id != $sketch->owner && !$sketch->public){
  361. echo 'Désolé, vous n\'avez pas d\'accès à cette ressource...';
  362. return;
  363. }
  364. $filepath = SKETCH_PATH.$resource->id.'/'.$_['file'];
  365. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  366. $mime = finfo_file($finfo, $filepath);
  367. header('Content-Type: '.$mime);
  368. header("Content-Length: " . filesize($filepath));
  369. header('Expires: Sun, 01 Jan 2014 00:00:00 GMT');
  370. header('Cache-Control: no-store, no-cache, must-revalidate');
  371. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  372. header('Cache-Control: post-check=0, pre-check=0', FALSE);
  373. header('Pragma: no-cache');
  374. header("Content-Disposition: attachment; filename=\"".basename($filepath)."\"");
  375. echo file_get_contents($filepath);
  376. finfo_close($finfo);
  377. break;
  378. case 'get_resource_image':
  379. global $myUser;
  380. ob_end_clean();
  381. $resource = Resource::getById($_['id']);
  382. $sketch =$resource->sketch_object;
  383. if($myUser->id != $sketch->owner && !$sketch->public){
  384. readfile('img/default_image.png');
  385. return;
  386. }
  387. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  388. $filepath = SKETCH_PATH.$resource->content;
  389. $mime = finfo_file($finfo, $filepath);
  390. header('Content-Type: '.$mime);
  391. echo file_get_contents($filepath);
  392. finfo_close($finfo);
  393. exit();
  394. break;
  395. case 'edit_resource':
  396. Action::write(function($_,&$response){
  397. $resource = Resource::getById($_['id']);
  398. global $myUser;
  399. $sketch = Sketch::getById($resource->sketch);
  400. $resource->label = html_entity_decode($resource->label);
  401. $response = Type::toHtml($resource,$sketch);
  402. });
  403. break;
  404. case 'delete_resource':
  405. Action::write(function($_,&$response){
  406. global $myUser;
  407. $resource = Resource::getById($_['id']);
  408. $sketch = Sketch::getById($resource->sketch);
  409. if($myUser->id != $sketch->owner) throw new Exception("Permission refusée, seul l'auteur du sketch peux faire ça");
  410. Resource::getById($_['id']);
  411. $resource->remove();
  412. });
  413. break;
  414. /*FILES*/
  415. case 'search_file':
  416. Action::write(function($_,&$response){
  417. global $myUser;
  418. if(!isset($_['id']) || !is_numeric($_['id'])) throw new Exception("Ressource non spécifiée");
  419. $resource = Resource::getById($_['id']);
  420. $sketch = $resource->sketch_object;
  421. if($myUser->id != $sketch->owner && !$sketch->public) throw new Exception("Désolé, le sketch est privé");
  422. foreach(glob(SKETCH_PATH.'/'.$_['id'].'/*') as $file):
  423. $icon = getExtIcon(getExt($file));
  424. $response['rows'][] = array('id'=>basename($file),'icon'=>$icon,'label'=>basename($file),'resource'=>$resource->id);
  425. endforeach;
  426. });
  427. break;
  428. case 'download_file':
  429. global $myUser;
  430. $path = SKETCH_PATH.'/'.$_['resource'];
  431. $resource = Resource::getById($_['resource']);
  432. $sketch = $resource->sketch_object;
  433. if($myUser->id != $sketch->owner && !$sketch->public) throw new Exception("Permission refusée, le sketch est privé");
  434. $filename = $resource->label.'-'.time().'.zip';
  435. $filepath = sys_get_temp_dir().DIRECTORY_SEPARATOR.$filename;
  436. $zip = new ZipArchive;
  437. if(file_exists($filepath))unlink($filepath);
  438. $res = $zip->open($filepath, ZipArchive::CREATE);
  439. if ($res === TRUE) {
  440. foreach(glob($path.'/*') as $file)
  441. $zip->addFile($file,basename($file));
  442. $zip->close();
  443. }
  444. header("Content-Type: application/zip");
  445. header("Content-Length: " . filesize($filepath));
  446. header('Expires: Sun, 01 Jan 2014 00:00:00 GMT');
  447. header('Cache-Control: no-store, no-cache, must-revalidate');
  448. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  449. header('Cache-Control: post-check=0, pre-check=0', FALSE);
  450. header('Pragma: no-cache');
  451. header("Content-Disposition: attachment; filename=\"".$filename."\"");
  452. readfile($filepath);
  453. unlink($filepath);
  454. break;
  455. case 'delete_file':
  456. Action::write(function($_,&$response){
  457. global $myUser;
  458. $path = SKETCH_PATH.'/'.$_['resource'].'/'.$_['id'];
  459. $resource = Resource::getById($_['resource']);
  460. $sketch = $resource->sketch_object;
  461. if($myUser->id != $sketch->owner) throw new Exception("Permission refusée, seul l'auteur du sketch peux faire ça");
  462. if(file_exists($path)) unlink($path);
  463. });
  464. break;
  465. /*PART*/
  466. case 'search_part':
  467. Action::write(function($_,&$response){
  468. if(!isset($_['id']) || !is_numeric($_['id'])) throw new Exception("Ressource non spécifiée");
  469. $resourceParts = ResourcePart::loadAll(array('resource'=>$_['id']),'sort');
  470. foreach($resourceParts as $resourcePart):
  471. $part = $resourcePart->part_object;
  472. $part->label = html_entity_decode($part->label);
  473. $part->link = html_entity_decode($part->link);
  474. if($part->image == '') {
  475. $part->image = 'img/default_image.png';
  476. }else{
  477. $part->image = PART_PATH.$part->image;
  478. }
  479. $line = $part->toArray();
  480. $line['id'] = $resourcePart->id;
  481. $response['rows'][] = $line;
  482. endforeach;
  483. });
  484. break;
  485. case 'delete_part':
  486. Action::write(function($_,&$response){
  487. global $myUser;
  488. $part = ResourcePart::getById($_['id']);
  489. $resource = $part->resource_object;
  490. $sketch = $resource->sketch_object;
  491. if($myUser->id != $sketch->owner) throw new Exception("Permission refusée, seul l'auteur du sketch peux faire ça");
  492. ResourcePart::deleteById($_['id']);
  493. });
  494. break;
  495. case 'save_part':
  496. Action::write(function($_,&$response){
  497. global $myUser;
  498. $model = isset($_['model']) && is_numeric($_['model']) && !empty($_['model']) ? Part::getByid($_['model']) : new Part();
  499. if($model->id==0){
  500. $model->fromArray($_);
  501. $model->save();
  502. }
  503. $resourcePart = new ResourcePart();
  504. $resourcePart->fromArray($_);
  505. $resourcePart->part = $model->id;
  506. $resourcePart->save();
  507. });
  508. break;
  509. case 'autocomplete_part':
  510. global $myUser;
  511. $parts = Part::staticQuery("SELECT DISTINCT label,* FROM ".Part::tableName()." WHERE label LIKE ? GROUP BY label ORDER BY price ASC ",array('%'.$_['term'].'%'),true);
  512. $rows = array();
  513. levenshtein_deduplication($parts);
  514. foreach($parts as $part):
  515. $part->image = PART_PATH.$part->image;
  516. $rows[] = array('label'=>$part->label.' ('.$part->price.'€)','value'=>$part->toArray());
  517. endforeach;
  518. echo json_encode($rows);
  519. break;
  520. default:
  521. break;
  522. }
  523. function levenshtein_deduplication(&$objs){
  524. foreach($objs as $obj1):
  525. foreach($objs as $u=>$obj2):
  526. if($obj1->id==$obj2->id) continue;
  527. if(levenshtein($obj1->label,$obj2->label) < 5 )
  528. unset($objs[$u]);
  529. endforeach;
  530. endforeach;
  531. }
  532. ?>