action.php 20 KB

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