action.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. <?php
  2. require_once __DIR__.DIRECTORY_SEPARATOR."common.php";
  3. if(!isset($_['action'])) throw new Exception('Action inexistante');
  4. //Execution du code en fonction de l'action
  5. switch ($_['action']){
  6. case 'login':
  7. global $myUser;
  8. try{
  9. $myUser = User::check($_['login'],$_['password']);
  10. if(!$myUser->connected()) throw new Exception('Utilisateur inexistant');
  11. $_SESSION['currentUser'] = serialize($myUser);
  12. }catch(Exception $e){
  13. $_SESSION['error'] = $e->getMessage();
  14. }
  15. header('location: index.php');
  16. break;
  17. case 'logout':
  18. unset($_SESSION['currentUser']);
  19. session_destroy();
  20. header('location: index.php');
  21. break;
  22. case 'save_user':
  23. try{
  24. global $myUser;
  25. if(!$myUser->connected()) throw new Exception("Permission refusée, seul un connecté peux faire ça");
  26. if($myUser->id!=$_['id']) throw new Exception("Permission refusée, seul le propriétaire du compte peux faire ça");
  27. if(!empty($_['password']) && $_['password']!=$_['confirmPassword']) throw new Exception("Les deux mot de passe ne correspondent pas");
  28. if(!empty($_['password'])) $myUser->password = User::password_encrypt($_['password']);
  29. $myUser->login = $_['login'];
  30. $myUser->save();
  31. $_SESSION['currentUser'] = serialize($myUser);
  32. $_SESSION['success'] = "Compte modifié avec succès";
  33. }catch(Exception $e){
  34. $_SESSION['error'] = $e->getMessage();
  35. }
  36. header('location: account.php');
  37. break;
  38. // SKETCH
  39. case 'create_sketch':
  40. Action::write(function($_,&$response){
  41. global $myUser;
  42. if(!$myUser->connected()) throw new Exception("Permission refusée, seul un connecté peux faire ça");
  43. $sketch = new Sketch();
  44. $sketch->fromArray($_);
  45. $sketch->owner = $myUser->id;
  46. $sketch->save();
  47. $resource = new Resource();
  48. $resource->label = 'README';
  49. $resource->type = 'readme';
  50. $resource->sketch = $sketch->id;
  51. $resource->content = 'Décrivez votre projet ici...';
  52. $resource->sort = 0;
  53. $resource->save();
  54. $response = $sketch->toArray();
  55. });
  56. break;
  57. case 'export_sketch':
  58. global $myUser;
  59. $response = array();
  60. try{
  61. $sketch = Sketch::getById($_['id']);
  62. if(!$sketch->public && $myUser->id!=$sketch->owner)throw new Exception('Ce sketch est privé');
  63. $response['sketch'] = $sketch->toArray();
  64. $response['resources'] = array();
  65. foreach(Resource::loadAll(array('sketch'=>$_['id'])) as $resource)
  66. $response['resources'][] = Type::toExport($resource);
  67. }catch(Exception $e){
  68. $response['error'] = $e->getMessage();
  69. }
  70. $response = gzdeflate(json_encode($response));
  71. if(!isset($_['api'])){
  72. $filename = slugify($sketch->label).('.export.').date('d-m-Y_H-i').'.json';
  73. header("Content-Type: application/json");
  74. header("Content-Length: " . strlen($response));
  75. header('Expires: Sun, 01 Jan 2014 00:00:00 GMT');
  76. header('Cache-Control: no-store, no-cache, must-revalidate');
  77. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  78. header('Cache-Control: post-check=0, pre-check=0', FALSE);
  79. header('Pragma: no-cache');
  80. header("Content-Disposition: attachment; filename=\"".$filename."\"");
  81. }
  82. echo $response;
  83. break;
  84. case 'import_sketch':
  85. Action::write(function($_,&$response){
  86. global $myUser;
  87. if(!$myUser->connected()) throw new Exception("Permission refusée, seul un connecté peux faire ça");
  88. if($_['from'] == 'url'){
  89. if(!isset($_['url']) || empty($_['url'])) throw new Exception("Adresse du sketch invalide");
  90. $url = parse_url($_['url']);
  91. parse_str($url['query'], $parameters);
  92. if(!isset($parameters['id']) || empty($parameters['id']) || !is_numeric($parameters['id'])) throw new Exception("ID du sketch invalide");
  93. $contentPath = $url['scheme'].'://'.$url['host'].'/'.substr($url['path'],0,-11).'/action.php?action=export_sketch&id='.$parameters['id'].'&api=true';
  94. }else{
  95. $ext = getExt($_FILES['file']['name']);
  96. if($ext!='json') throw new Exception('Extension JSON autorisée uniquement');
  97. $contentPath = $_FILES['file']['tmp_name'];
  98. }
  99. $stream = false;
  100. try{ $stream = @file_get_contents($contentPath); }catch(Exception $a){}
  101. if($stream === false) throw new Exception("Impossible d'atteindre le contenu hackpoint : $contentPath ");
  102. $stream = gzinflate($stream);
  103. if($stream === false) throw new Exception('Impossible de décompresser le sketch...');
  104. $json = json_decode($stream,true);
  105. if($json == false) throw new Exception('Impossible de parser la réponse du hackpoint, json invalide :'.$stream);
  106. if(isset($json['error'])) throw new Exception($json['error']);
  107. $sketch = new Sketch();
  108. $sketch->fromArray($json['sketch']);
  109. $sketch->id = null;
  110. $sketch->owner = $myUser->id;
  111. $sketch->public = 0;
  112. $sketch->label = $sketch->label .='-import-'.date('d/m/Y H:i');
  113. $sketch->save();
  114. foreach($json['resources'] as $res)
  115. Type::fromImport($res,$sketch);
  116. });
  117. break;
  118. case 'search_sketch':
  119. Action::write(function($_,&$response){
  120. global $myUser;
  121. $filters = array('public'=>1);
  122. if($myUser->connected()){
  123. $filters = array('owner'=>$myUser->id);
  124. }
  125. $sketchs = Sketch::loadAll($filters);
  126. foreach($sketchs as $sketch){
  127. $sketch->label = html_entity_decode($sketch->label);
  128. $response['rows'][] = $sketch->toArray();
  129. }
  130. });
  131. break;
  132. case 'delete_sketch':
  133. Action::write(function($_,&$response){
  134. global $myUser;
  135. $sketch = Sketch::getById($_['id']);
  136. if($myUser->id != $sketch->owner) throw new Exception("Permission refusée, seul l'auteur du sketch peux faire ça");
  137. Part::staticQuery("delete FROM ".ResourcePart::tableName()." WHERE resource IN(SELECT id FROM ".Resource::tableName()." WHERE sketch=".$_['id'].") ");
  138. foreach(Resource::loadAll(array('sketch'=>$_['id'])) as $resource):
  139. $resource->remove();
  140. endforeach;
  141. Sketch::deleteById($_['id']);
  142. });
  143. break;
  144. case 'save_sketch_title':
  145. Action::write(function($_,&$response){
  146. global $myUser;
  147. $sketch = Sketch::getById($_['id']);
  148. if($myUser->id != $sketch->owner) return;
  149. $sketch->fromArray($_);
  150. $sketch->save();
  151. });
  152. break;
  153. case 'toggle_share_sketch':
  154. Action::write(function($_,&$response){
  155. global $myUser;
  156. $sketch = Sketch::getById($_['id']);
  157. if($myUser->id != $sketch->owner) throw new Exception("Permission refusée, seul l'auteur du sketch peux faire ça");
  158. $sketch->public = $_['state'];
  159. $sketch->save();
  160. });
  161. break;
  162. case 'download_sketch':
  163. $sketch = Sketch::getByid($_['id']);
  164. $resources = Resource::loadAll(array('sketch'=>$sketch->id),'sort');
  165. $filename = $sketch->slug.'-'.time().'.zip';
  166. $filepath = sys_get_temp_dir().DIRECTORY_SEPARATOR.$filename;
  167. $zip = new ZipArchive;
  168. $res = $zip->open($filepath, ZipArchive::CREATE);
  169. if ($res === TRUE) {
  170. foreach($resources as $resource){
  171. $type = Type::get($resource->type);
  172. $file = Type::toFileStream($resource);
  173. $zip->addFromString($file->name, $file->content);
  174. }
  175. $zip->close();
  176. }
  177. header("Content-Type: application/zip");
  178. header("Content-Length: " . filesize($filepath));
  179. header('Expires: Sun, 01 Jan 2014 00:00:00 GMT');
  180. header('Cache-Control: no-store, no-cache, must-revalidate');
  181. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  182. header('Cache-Control: post-check=0, pre-check=0', FALSE);
  183. header('Pragma: no-cache');
  184. header("Content-Disposition: attachment; filename=\"".$filename."\"");
  185. readfile($filepath);
  186. unlink($filepath);
  187. break;
  188. // RESOURCES
  189. case 'upload_resource':
  190. Action::write(function($_,&$response){
  191. global $myUser;
  192. $resource = Resource::getByid($_['id']);
  193. $sketch = Sketch::getById($resource->sketch);
  194. $ext = getExt($_FILES['file']['name']);
  195. if($myUser->id != $sketch->owner) throw new Exception("Seul le propriétaire du sketch peux faire ça");
  196. if(!in_array($ext,explode(',',ALLOWED_RESOURCE_IMAGE))) throw new Exception('Extensions autorisées '.ALLOWED_RESOURCE_IMAGE);
  197. if($_FILES['file']['size']>ALLOWED_RESOURCE_SIZE) throw new Exception('Taille maximum autorisée '.ALLOWED_RESOURCE_SIZE.' o');
  198. $name = $resource->id.'.'.$ext;
  199. $path = SKETCH_PATH.$name;
  200. move_uploaded_file($_FILES['file']['tmp_name'], $path);
  201. $resource->content = $name;
  202. $resource->save();
  203. $response = array_merge(Type::get($resource->type));
  204. //$response['url'] = $path.'?v='.time();
  205. $response['url'] ="action.php?action=get_resource_image&id=".$resource->id."&v=".time();
  206. });
  207. break;
  208. case 'upload_resource_file':
  209. Action::write(function($_,&$response){
  210. global $myUser;
  211. $resource = Resource::getByid($_['id']);
  212. $sketch = Sketch::getById($resource->sketch);
  213. $ext = getExt($_FILES['file']['name']);
  214. if($myUser->id != $sketch->owner) throw new Exception("Seul le propriétaire du sketch peux faire ça");
  215. if(ALLOWED_RESOURCE_FILE!='' && !in_array($ext,explode(',',ALLOWED_RESOURCE_FILE))) throw new Exception('Extensions autorisées '.ALLOWED_RESOURCE_FILE);
  216. if($_FILES['file']['size']>ALLOWED_RESOURCE_SIZE) throw new Exception('Taille maximum autorisée '.ALLOWED_RESOURCE_SIZE.' o');
  217. $name = $resource->id;
  218. $folder = SKETCH_PATH.$name;
  219. if(!file_exists($folder)) mkdir($folder);
  220. $path = $folder.'/'.$_FILES['file']['name'];
  221. move_uploaded_file($_FILES['file']['tmp_name'], $path);
  222. $response = array_merge(Type::get($resource->type));
  223. $response['url'] = $path.'?v='.time();
  224. });
  225. break;
  226. case 'search_resources':
  227. Action::write(function($_,&$response){
  228. if(!isset($_['id']) || !is_numeric($_['id'])) throw new Exception("Sketch non spécifié");
  229. $resources = Resource::loadAll(array('sketch'=>$_['id']),'sort');
  230. foreach($resources as $resource){
  231. $resource->label = html_entity_decode($resource->label);
  232. $resource->content = null;
  233. $response['rows'][] = $resource->toArray();
  234. }
  235. });
  236. break;
  237. case 'import_resource':
  238. global $myUser;
  239. $sketch = Sketch::getByid($_['id']);
  240. if($myUser->id != $sketch->owner) return;
  241. $ext = explode('.',$_FILES['file']['name']);
  242. $ext = strtolower(array_pop($ext));
  243. $types = Type::all();
  244. $type = 'readme';
  245. foreach($types as $uid=>$tp)
  246. if(isset($tp['extension']) && $ext == $tp['extension']) $type = $uid;
  247. Type::fromFileImport($_FILES['file'],$sketch,$type);
  248. break;
  249. //COMPONENT
  250. case 'upload_component_image':
  251. global $myUser;
  252. $response = array();
  253. try{
  254. 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)));
  255. $ext = explode('.',$_FILES['file']['name']);
  256. $ext = strtolower(array_pop($ext));
  257. if(!in_array($ext,explode(',',ALLOWED_RESOURCE_IMAGE))) throw new Exception("Format d'image interdit, autorisé : ".ALLOWED_RESOURCE_IMAGE);
  258. 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)));
  259. imageResize($_FILES['file']['tmp_name'],100,100);
  260. $response['thumb'] = 'data:image/png;base64,'.base64_encode(file_get_contents($_FILES['file']['tmp_name']));
  261. }catch(Exception $e){
  262. $response['error'] = $e->getMessage();
  263. }
  264. header('Content-Type:application/json');
  265. echo json_encode($response);
  266. break;
  267. case 'search_component':
  268. Action::write(function($_,&$response){
  269. global $myUser;
  270. $parts = Part::populate();
  271. foreach($parts as $part){
  272. $part->label = html_entity_decode($part->label);
  273. $part->link = html_entity_decode($part->link);
  274. if($part->image==''){
  275. $part->image = 'img/default_image.png';
  276. }else{
  277. $part->image = PART_PATH.html_entity_decode($part->image).'?t='.time();
  278. }
  279. $response['rows'][] = $part->toArray();
  280. }
  281. });
  282. break;
  283. case 'delete_component':
  284. Action::write(function($_,&$response){
  285. global $myUser;
  286. $part = Part::getById($_['id']);
  287. if($myUser->id!=$part->owner) throw new Exception('Seul le propriétaire du composant peux faire ça');
  288. $part->remove();
  289. });
  290. break;
  291. case 'save_component':
  292. Action::write(function($_,&$response){
  293. global $myUser;
  294. if(!$myUser->connected()) throw new Exception("Permission refusée, seul un connecté peux faire ça");
  295. $part = isset($_['id']) && is_numeric($_['id'])?Part::getById($_['id']):new Part();
  296. $part->fromArray($_);
  297. $part->owner = $myUser->id;
  298. $part->save();
  299. if(substr($part->image,0,10) == 'data:image'){
  300. $imageName = $part->id.'.png';
  301. base64_to_image($part->image,PART_PATH.$imageName);
  302. $part->image = $imageName;
  303. $part->save();
  304. }
  305. $response = $part->toArray();
  306. });
  307. break;
  308. case 'edit_component':
  309. Action::write(function($_,&$response){
  310. $part = isset($_['id'])? Part::getById($_['id']):new Part;
  311. $part->label = html_entity_decode($part->label);
  312. $part->link = html_entity_decode($part->link);
  313. $part->brand = html_entity_decode($part->brand);
  314. if($part->image==''){
  315. $part->image = 'img/default_image.png';
  316. }else{
  317. $part->image = PART_PATH.html_entity_decode($part->image);
  318. }
  319. $part->image.='?t='.time();
  320. $response = $part->toArray();
  321. });
  322. break;
  323. //RESOURCE
  324. case 'save_resource':
  325. Action::write(function($_,&$response){
  326. global $myUser;
  327. $sketch = Sketch::getById($_['sketch']);
  328. if($myUser->id != $sketch->owner) throw new Exception("Permission refusée, seul l'auteur du sketch peux faire ça");
  329. $resource = isset($_['id']) && is_numeric($_['id']) && !empty($_['id']) ? Resource::getByid($_['id']) : new Resource();
  330. $resource->fromArray($_);
  331. $resource->sort = 10;
  332. if($resource->type=='readme' && $resource->id==0) $resource->sort = 0;
  333. $resource->label = $resource->label == ''?'Sans titre '.date('d-m-Y H:i'):$resource->label;
  334. $resource->save();
  335. $response = $resource->toArray();
  336. });
  337. break;
  338. case 'save_resource_content':
  339. Action::write(function($_,&$response){
  340. global $myUser;
  341. $resource = Resource::getByid($_['id']);
  342. $sketch = Sketch::getById($resource->sketch);
  343. if($myUser->id != $sketch->owner) return;
  344. $resource->fromArray($_);
  345. $resource->save();
  346. });
  347. break;
  348. case 'get_resource_file':
  349. global $myUser;
  350. $resource = Resource::getById($_['id']);
  351. $sketch =$resource->sketch_object;
  352. if($myUser->id != $sketch->owner && !$sketch->public){
  353. echo 'Désolé, vous n\'avez pas d\'accès à cette ressource...';
  354. return;
  355. }
  356. $filepath = SKETCH_PATH.$resource->id.'/'.$_['file'];
  357. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  358. $mime = finfo_file($finfo, $filepath);
  359. header('Content-Type: '.$mime);
  360. header("Content-Length: " . filesize($filepath));
  361. header('Expires: Sun, 01 Jan 2014 00:00:00 GMT');
  362. header('Cache-Control: no-store, no-cache, must-revalidate');
  363. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  364. header('Cache-Control: post-check=0, pre-check=0', FALSE);
  365. header('Pragma: no-cache');
  366. header("Content-Disposition: attachment; filename=\"".basename($filepath)."\"");
  367. echo file_get_contents($filepath);
  368. finfo_close($finfo);
  369. break;
  370. case 'get_resource_image':
  371. global $myUser;
  372. $resource = Resource::getById($_['id']);
  373. $sketch =$resource->sketch_object;
  374. if($myUser->id != $sketch->owner && !$sketch->public){
  375. readfile('img/default_image.png');
  376. return;
  377. }
  378. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  379. $filepath = SKETCH_PATH.$resource->content;
  380. $mime = finfo_file($finfo, $filepath);
  381. header('Content-Type: '.$mime);
  382. readfile($filepath);
  383. break;
  384. case 'edit_resource':
  385. Action::write(function($_,&$response){
  386. $resource = Resource::getById($_['id']);
  387. global $myUser;
  388. $sketch = Sketch::getById($resource->sketch);
  389. $resource->label = html_entity_decode($resource->label);
  390. $response = Type::toHtml($resource,$sketch);
  391. });
  392. break;
  393. case 'delete_resource':
  394. Action::write(function($_,&$response){
  395. global $myUser;
  396. $resource = Resource::getById($_['id']);
  397. $sketch = Sketch::getById($resource->sketch);
  398. if($myUser->id != $sketch->owner) throw new Exception("Permission refusée, seul l'auteur du sketch peux faire ça");
  399. Resource::getById($_['id']);
  400. $resource->remove();
  401. });
  402. break;
  403. /*FILES*/
  404. case 'search_file':
  405. Action::write(function($_,&$response){
  406. global $myUser;
  407. if(!isset($_['id']) || !is_numeric($_['id'])) throw new Exception("Ressource non spécifiée");
  408. $resource = Resource::getById($_['id']);
  409. $sketch = $resource->sketch_object;
  410. if($myUser->id != $sketch->owner && !$sketch->public) throw new Exception("Désolé, le sketch est privé");
  411. foreach(glob(SKETCH_PATH.'/'.$_['id'].'/*') as $file):
  412. $icon = getExtIcon(getExt($file));
  413. $response['rows'][] = array('id'=>basename($file),'icon'=>$icon,'label'=>basename($file),'resource'=>$resource->id);
  414. endforeach;
  415. });
  416. break;
  417. case 'download_file':
  418. global $myUser;
  419. $path = SKETCH_PATH.'/'.$_['resource'];
  420. $resource = Resource::getById($_['resource']);
  421. $sketch = $resource->sketch_object;
  422. if($myUser->id != $sketch->owner && !$sketch->public) throw new Exception("Permission refusée, le sketch est privé");
  423. $filename = $resource->label.'-'.time().'.zip';
  424. $filepath = sys_get_temp_dir().DIRECTORY_SEPARATOR.$filename;
  425. $zip = new ZipArchive;
  426. if(file_exists($filepath))unlink($filepath);
  427. $res = $zip->open($filepath, ZipArchive::CREATE);
  428. if ($res === TRUE) {
  429. foreach(glob($path.'/*') as $file)
  430. $zip->addFile($file,basename($file));
  431. $zip->close();
  432. }
  433. header("Content-Type: application/zip");
  434. header("Content-Length: " . filesize($filepath));
  435. header('Expires: Sun, 01 Jan 2014 00:00:00 GMT');
  436. header('Cache-Control: no-store, no-cache, must-revalidate');
  437. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  438. header('Cache-Control: post-check=0, pre-check=0', FALSE);
  439. header('Pragma: no-cache');
  440. header("Content-Disposition: attachment; filename=\"".$filename."\"");
  441. readfile($filepath);
  442. unlink($filepath);
  443. break;
  444. case 'delete_file':
  445. Action::write(function($_,&$response){
  446. global $myUser;
  447. $path = SKETCH_PATH.'/'.$_['resource'].'/'.$_['id'];
  448. $resource = Resource::getById($_['resource']);
  449. $sketch = $resource->sketch_object;
  450. if($myUser->id != $sketch->owner) throw new Exception("Permission refusée, seul l'auteur du sketch peux faire ça");
  451. if(file_exists($path)) unlink($path);
  452. });
  453. break;
  454. /*PART*/
  455. case 'search_part':
  456. Action::write(function($_,&$response){
  457. if(!isset($_['id']) || !is_numeric($_['id'])) throw new Exception("Ressource non spécifiée");
  458. $resourceParts = ResourcePart::loadAll(array('resource'=>$_['id']),'sort');
  459. foreach($resourceParts as $resourcePart):
  460. $part = $resourcePart->part_object;
  461. $part->label = html_entity_decode($part->label);
  462. $part->link = html_entity_decode($part->link);
  463. if($part->image == '') {
  464. $part->image = 'img/default_image.png';
  465. }else{
  466. $part->image = PART_PATH.$part->image;
  467. }
  468. $line = $part->toArray();
  469. $line['id'] = $resourcePart->id;
  470. $response['rows'][] = $line;
  471. endforeach;
  472. });
  473. break;
  474. case 'delete_part':
  475. Action::write(function($_,&$response){
  476. global $myUser;
  477. $part = ResourcePart::getById($_['id']);
  478. $resource = $part->resource_object;
  479. $sketch = $resource->sketch_object;
  480. if($myUser->id != $sketch->owner) throw new Exception("Permission refusée, seul l'auteur du sketch peux faire ça");
  481. ResourcePart::deleteById($_['id']);
  482. });
  483. break;
  484. case 'save_part':
  485. Action::write(function($_,&$response){
  486. global $myUser;
  487. $model = isset($_['model']) && is_numeric($_['model']) && !empty($_['model']) ? Part::getByid($_['model']) : new Part();
  488. if($model->id==0){
  489. $model->fromArray($_);
  490. $model->save();
  491. }
  492. $resourcePart = new ResourcePart();
  493. $resourcePart->fromArray($_);
  494. $resourcePart->part = $model->id;
  495. $resourcePart->save();
  496. });
  497. break;
  498. case 'autocomplete_part':
  499. global $myUser;
  500. $parts = Part::staticQuery("SELECT DISTINCT label,* FROM ".Part::tableName()." WHERE label LIKE ? GROUP BY label ORDER BY price ASC ",array('%'.$_['term'].'%'),true);
  501. $rows = array();
  502. levenshtein_deduplication($parts);
  503. foreach($parts as $part):
  504. $part->image = PART_PATH.$part->image;
  505. $rows[] = array('label'=>$part->label.' ('.$part->price.'€)','value'=>$part->toArray());
  506. endforeach;
  507. echo json_encode($rows);
  508. break;
  509. default:
  510. break;
  511. }
  512. function levenshtein_deduplication(&$objs){
  513. foreach($objs as $obj1):
  514. foreach($objs as $u=>$obj2):
  515. if($obj1->id==$obj2->id) continue;
  516. if(levenshtein($obj1->label,$obj2->label) < 5 )
  517. unset($objs[$u]);
  518. endforeach;
  519. endforeach;
  520. }
  521. ?>