action.php 20 KB

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