action.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. <?php
  2. global $_,$conf;
  3. switch($_['action']){
  4. case 'document_load_template':
  5. global $myUser,$_;
  6. require_once(__DIR__.SLASH.'template.document.php');
  7. break;
  8. case 'document_widget_load':
  9. global $myUser;
  10. require_once(PLUGIN_PATH.'dashboard'.SLASH.'DashboardWidget.class.php');
  11. $widget = DashboardWidget::current();
  12. $root = $widget->data('widget-document-root');
  13. $root = !empty($root) ? ': <strong>'.$root.')</strong>':'';
  14. $widget->title = 'Mes documents'.$root;
  15. ob_start();
  16. require_once(__DIR__.SLASH.'widget.php');
  17. $widget->content = ob_get_clean();
  18. echo json_encode($widget);
  19. break;
  20. case 'document_widget_configure_save':
  21. Action::write(function(&$response){
  22. global $myUser,$_;
  23. require_once(PLUGIN_PATH.'dashboard'.SLASH.'DashboardWidget.class.php');
  24. User::check_access('document','configure');
  25. $widget = DashboardWidget::getById($_['id']);
  26. $widget->data('widget-document-tree',$_['widget-document-tree']);
  27. $widget->data('widget-document-detail',$_['widget-document-detail']);
  28. $widget->data('widget-document-search',$_['widget-document-search']);
  29. $root = str_replace(array('./','../'),'',$_['widget-document-root']);
  30. $widget->data('widget-document-root',$root);
  31. $widget->save();
  32. });
  33. break;
  34. case 'document_widget_configure':
  35. global $myUser;
  36. require_once(PLUGIN_PATH.'dashboard'.SLASH.'DashboardWidget.class.php');
  37. $widget = DashboardWidget::current();
  38. ob_start();
  39. require_once(__DIR__.SLASH.'widget.configure.php');
  40. $content = ob_get_clean();
  41. echo $content ;
  42. break;
  43. case 'document_embedded':
  44. Action::write(function(&$response){
  45. Plugin::addCss("/css/main.css");
  46. Plugin::addJs("/js/main.js");
  47. ob_start();
  48. global $myUser,$_;
  49. $embedded = true;
  50. //l'ui de la ged prend en entrée / quel que soit l'os
  51. if(isset($_['data']['root'])) $_['data']['root'] = str_replace('\\', '/', $_['data']['root']);
  52. require_once(__DIR__.SLASH.'page.list.php');
  53. $response['html'] = ob_get_clean();
  54. });
  55. break;
  56. case 'document_folder_create':
  57. Action::write(function(&$response){
  58. global $myUser,$_,$conf;
  59. User::check_access('document','edit');
  60. require_once(__DIR__.SLASH.'Element.class.php');
  61. $path = str_replace('/',SLASH,$_['path']);
  62. $path = Element::root().$path;
  63. if(!document_check_element_name(htmlspecialchars_decode(html_entity_decode($_['folder']), ENT_QUOTES))) throw new Exception("Caractères interdits : \\/:*?\"<>|");
  64. if(strlen($_['folder']) > 80) throw new Exception("Taille maximale autorisée de 80 caractères.");
  65. Element::addFolder($path);
  66. if($conf->get('document_enable_logs')) Log::put("Création d'un dossier : ".$path,'document');
  67. });
  68. break;
  69. /** ELEMENT **/
  70. //Récuperation d'une liste de element
  71. case 'document_element_search':
  72. Action::write(function(&$response){
  73. global $myUser,$_,$conf;
  74. User::check_access('document','read');
  75. require_once(__DIR__.SLASH.'Element.class.php');
  76. //recherche par libellé
  77. if(!empty($_['keyword'])){
  78. $query = 'SELECT * FROM {{table}} WHERE 1';
  79. $data = $elements = array();
  80. $query .= ' AND label LIKE ?';
  81. $data[] = '%'.$_['keyword'].'%';
  82. $folder = isset($_['folder']) && !empty($_['folder']) ? $_['folder'] : '.';
  83. if(isset($_['folder']) && !empty($_['folder']))
  84. $query .= ' AND `path` LIKE "'.$_['folder'].'%'.'"';
  85. //Tri des colonnes
  86. if(isset($_['sort'])) sort_secure_query($_['sort'],array('label','creator','size'),$query,$data);
  87. $response['qry'] = $query;
  88. foreach (Element::staticQuery($query,$data,true) as $element) {
  89. // Check pour ne pas faire ressortir le dossier lui même
  90. if ($element->path == $folder) continue;
  91. $elemPath =str_replace(SLASH.'.'.SLASH,SLASH,Element::root().$element->path) ;
  92. $line = Element::fromPath($elemPath);
  93. $line->path = rtrim($line->path, SLASH);
  94. $osPath = Element::root().str_replace('/',SLASH,$line->path);
  95. if(!file_exists($osPath)){
  96. Element::deleteById($line->id);
  97. continue;
  98. }
  99. $row = $line->toArray();
  100. $row['updatedRelative'] = relative_time($line->updated);
  101. $row['sizeReadable'] = $row['type'] == 'directory' ? $line->childNumber.' élements' : readable_size($line->size);
  102. $row['updatedReadable'] = day_name(date('N',$line->updated)).' '. date('d ',$line->updated).month_name(date('m',$line->updated)).date(' Y à H:i',$line->updated);
  103. $row['thumbnail'] = $line->thumbnail();
  104. $row['icon'] = $line->icon();
  105. $row['childNumber'] = $line->childNumber;
  106. $elements[] = $row;
  107. }
  108. $response['rows'] = $elements;
  109. //recherche par arborescence
  110. }else{
  111. if(isset($_['folder']) && !empty($_['folder'])){
  112. $folder = str_replace('/',SLASH,$_['folder']);
  113. }else {
  114. $folder = '.';
  115. if(isset($_['root'])) $folder = str_replace('/',SLASH,$_['root']);
  116. }
  117. $response['rows'] = array();
  118. $scanned = Element::root().$folder.SLASH.'*';
  119. //L'ui ne traite que les / quel que soit l'os
  120. foreach (Element::browse($scanned) as $line) {
  121. $line->path = str_replace('\\', '/', $line->path);
  122. $row = $line->toArray();
  123. $row['updatedRelative'] = relative_time($line->updated);
  124. $row['sizeReadable'] = $row['type'] == 'directory' ? $line->childNumber.' élements' : readable_size($line->size);
  125. $row['updatedReadable'] = day_name(date('N',$line->updated)).' '. date('d ',$line->updated).month_name(date('m',$line->updated)).date(' Y à H:i',$line->updated);
  126. $row['thumbnail'] = $line->thumbnail();
  127. $row['icon'] = $line->icon();
  128. $row['childNumber'] = $line->childNumber;
  129. $response['rows'][] = $row;
  130. }
  131. //tri du résultat si demandé
  132. if(isset($_['sort'])){
  133. $direction = $_['sort']['sort'] == 'asc' ? 1:-1 ;
  134. //le in_array permet de s'assurer qu'une colonne triable est spécifiée
  135. $attribute = in_array($_['sort']['column'],array('label','size','creator','updated'))? $_['sort']['column']: 'label';
  136. usort($response['rows'],function($a,$b) use($attribute,$direction){
  137. if($a[$attribute] > $b[$attribute]) return 1*$direction;
  138. if($a[$attribute] < $b[$attribute]) return -1*$direction;
  139. if($a[$attribute] == $b[$attribute]) return 0;
  140. });
  141. }
  142. if($conf->get('document_enable_logs_verbose')) Log::put('Ouverture du dossier '.str_replace(array('/','\\',SLASH.'.'.SLASH.'*'),array(SLASH,SLASH,''),$scanned).' ','document');
  143. }
  144. });
  145. break;
  146. case 'document_element_preview':
  147. Action::write(function(&$response){
  148. global $myUser,$_;
  149. User::check_access('document','read');
  150. require_once(__DIR__.SLASH.'Element.class.php');
  151. //l'ui ne renvois que les /, on les convertis par le separateur de l'os
  152. $_['path'] = str_replace('/', SLASH, $_['path']);
  153. $path = str_replace(SLASH.'.'.SLASH,SLASH,Element::root().$_['path']);
  154. $osPath = File::convert_decoding($path);
  155. if(!file_exists($osPath)) throw new Exception('Cet élément a peut-être été modifié ou déplacé par quelqu\'un d\'autre. Rafraîchissez la page et réessayez.');
  156. $element = Element::fromPath($path);
  157. //L'ui ne traite que les / quel que soit l'os
  158. $element->path = str_replace('\\', '/', $element->path);
  159. $row = $element->toArray();
  160. $row['updatedRelative'] = relative_time($element->updated);
  161. $row['sizeReadable'] = readable_size($element->size);
  162. $row['updatedReadable'] = day_name(date('N',$element->updated)).' '. date('d ',$element->updated).month_name(date('m',$element->updated)).date(' Y à H:i',$element->updated);
  163. $row['thumbnail'] = $element->thumbnail();
  164. $row['icon'] = $element->icon();
  165. $row['childNumber'] = $element->childNumber;
  166. $response['row'] = $row;
  167. });
  168. break;
  169. case 'document_properties_show':
  170. Action::write(function(&$response){
  171. global $myUser,$_;
  172. User::check_access('document','read');
  173. require_once(__DIR__.SLASH.'Element.class.php');
  174. $element = Element::provide();
  175. $element->path = str_replace('\\', '/', $element->path);
  176. $row = $element->toArray();
  177. $row['createdLabel'] = date('d/m/Y H:i',$element->updated);
  178. $row['updatedLabel'] = date('d/m/Y H:i',$element->updated);
  179. $bundle = base64_encode(json_encode(array(
  180. 'root' => $element->path,
  181. 'folder' => '',
  182. )));
  183. $row['rootUrl'] = ROOT_URL.'/index.php?module=document&data='.$bundle;
  184. $response['row'] = $row;
  185. });
  186. break;
  187. case 'document_element_execute':
  188. global $myUser,$_,$conf;
  189. User::check_access('document','read');
  190. require_once(__DIR__.SLASH.'Element.class.php');
  191. $isopath = Element::root().base64_decode(rawurldecode($_['path']));
  192. $utf8Path = utf8_encode($isopath);
  193. $osPath = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? $isopath : $utf8Path;
  194. $stream = Element::download($utf8Path);
  195. $name = mt_basename($utf8Path);
  196. $mime = 'application/octet-stream';
  197. if(is_dir($osPath)){
  198. $mime = 'application/zip';
  199. $name .= '.zip';
  200. }
  201. if($conf->get('document_enable_logs_verbose')) Log::put('Téléchargement de '.$utf8Path,'document');
  202. File::downloadStream($stream, $name, $mime);
  203. break;
  204. case 'document_element_move':
  205. Action::write(function(&$response){
  206. global $myUser,$_,$conf;
  207. User::check_access('document','edit');
  208. require_once(__DIR__.SLASH.'Element.class.php');
  209. //l'ui ne renvois que les /, on les convertis par le separateur de l'os
  210. $_['from'] = str_replace('/', SLASH, $_['from']);
  211. $_['to'] = str_replace('/', SLASH, $_['to']);
  212. $from = Element::root().$_['from'];
  213. $osFrom = File::convert_decoding($from);
  214. if(!file_exists($osFrom)) throw new Exception('Cet élément a peut-être été modifié ou déplacé par quelqu\'un d\'autre. Rafraîchissez la page et réessayez.');
  215. //if($_['to']=='.') $_['to'] = '';
  216. $to = Element::root().$_['to'];
  217. $osTo = File::convert_decoding($to);
  218. if(!is_dir($osTo)) return;
  219. if(!document_check_element_name(basename(htmlspecialchars_decode(html_entity_decode($to), ENT_QUOTES)))) throw new Exception("Caractères interdits : \\/:*?\"<>|");
  220. $to .= SLASH.basename($from);
  221. $element = Element::move($from,$to);
  222. $response['element'] = $element;
  223. if($conf->get('document_enable_logs')) Log::put('Déplacement de '.$from.' dans '.$to,'document');
  224. });
  225. break;
  226. case 'document_element_rename':
  227. Action::write(function(&$response){
  228. global $myUser,$_,$conf;
  229. User::check_access('document','edit');
  230. require_once(__DIR__.SLASH.'Element.class.php');
  231. //les exception vides reset le champ de l'ui sans afficher d'erreur
  232. if(!isset($_['label']) || empty($_['label'])) throw new Exception("Le nom ne dois pas être vide");
  233. if(strlen($_['label']) > 80) throw new Exception("Taille maximale autorisée de 80 caractères.");
  234. //l'ui ne renvois que les /, on les convertis par le separateur de l'os
  235. $_['path'] = str_replace('/', SLASH, $_['path']);
  236. $from = Element::root().$_['path'];
  237. $fromOs = File::convert_decoding($from);
  238. if(!file_exists($fromOs)) throw new Exception('Cet élément a peut-être été modifié ou déplacé par quelqu\'un d\'autre. Rafraîchissez la page et réessayez.');
  239. if(is_dir($fromOs) && substr($_['label'], -1,1)=='.') throw new Exception("Les dossiers ne peuvent pas terminer par un .");
  240. $to = dirname($from).SLASH.$_['label'];
  241. if(file_exists($to)) throw new Exception('Action impossible, un élément existe déjà avec ce nom.');
  242. if(!document_check_element_name(htmlspecialchars_decode(html_entity_decode($_['label']), ENT_QUOTES))) throw new Exception("Caractères interdits : \\/:*?\"<>|");
  243. $element = Element::move($from,$to);
  244. if(!$element) throw new Exception("Erreur lors de la récuperation de l'élement renommé", 500);
  245. $element->path = str_replace('\\', '/', $element->path);
  246. $response['element'] = $element;
  247. if($conf->get('document_enable_logs') ) Log::put('Renommage de l\'élément : '.$from.' en '.$to,'document');
  248. });
  249. break;
  250. case 'document_element_delete':
  251. Action::write(function(&$response){
  252. global $myUser,$_,$conf;
  253. User::check_access('document','delete');
  254. require_once(__DIR__.SLASH.'Element.class.php');
  255. //l'ui ne renvois que les /, on les convertis par le separateur de l'os
  256. $path = Element::root().str_replace('/', SLASH,$_['path']);
  257. $osPath = File::convert_decoding($path);
  258. if(!file_exists($osPath)) throw new Exception('Cet élément a peut-être été modifié ou déplacé par quelqu\'un d\'autre. Rafraîchissez la page et réessayez.');
  259. Element::remove($path);
  260. $extension = getExt($path);
  261. if( in_array($extension, array('jpg','jpeg','png','gif','bmp'))) {
  262. $thumbname = str_replace(array('\\'),array('/'),$_['path']);
  263. $thumbpath = Element::root().'.thumbnails'.SLASH.base64_encode($thumbname).'.'.$extension;
  264. if(file_exists($thumbpath)) unlink($thumbpath);
  265. }
  266. if($conf->get('document_enable_logs')) Log::put("Suppression d'un élément : ".$path,'document');
  267. });
  268. break;
  269. //edition d'un fichier (chargement)
  270. case 'document_element_edit':
  271. Action::write(function(&$response){
  272. global $myUser,$_,$conf;
  273. User::check_access('document','edit');
  274. require_once(__DIR__.SLASH.'Element.class.php');
  275. if(!isset($_['path'])) throw new Exception("Veuillez spécifier le chemin du fichier");
  276. $path = str_replace(array('..'),'',$_['path']);
  277. $path = Element::root().$path;
  278. $osPath = File::convert_decoding($path);
  279. if(!file_exists($osPath)) throw new Exception("Impossible de trouver le fichier, peut être a t-il été supprimé entree temps, veuillez recharger la page.");
  280. $response['path'] = $path;
  281. $response['label'] = mt_basename($path);
  282. $response['content'] = Element::download($path);
  283. });
  284. break;
  285. //edition d'un fichier (sauvegarde)
  286. case 'document_element_save':
  287. Action::write(function(&$response){
  288. global $myUser,$_,$conf;
  289. User::check_access('document','edit');
  290. require_once(__DIR__.SLASH.'Element.class.php');
  291. if(!isset($_['label'])) throw new Exception("Veuillez spécifier le nom du fichier");
  292. $label = str_replace(array('..','/','\\'),'',$_['label']);
  293. $path = Element::root().$_['path'].SLASH;
  294. $osPath = File::convert_decoding($path);
  295. $content = html_entity_decode($_['content']);
  296. $maxSize = $conf->get('document_allowed_size');
  297. $extensions = explode(',',str_replace(' ', '', $conf->get('document_allowed_extensions')));
  298. $extension = getExt($_['label']);
  299. if(strlen($content) > $maxSize) throw new Exception("Taille du fichier ".$_['label']." trop grande, taille maximum :".readable_size($maxSize).' ('.$maxSize.' octets)');
  300. if(!in_array($extension , $extensions)) throw new Exception("Extension '".$extension."' du fichier ".$_['label']." non permise, autorisé :".implode(', ',$extensions));
  301. $filePath = $path.$_['label'];
  302. Element::addFile($filePath,$content);
  303. });
  304. break;
  305. //upload d'un fichier
  306. case 'document_element_upload':
  307. Action::write(function(&$response){
  308. global $myUser,$_,$conf;
  309. User::check_access('document','edit');
  310. require_once(__DIR__.SLASH.'Element.class.php');
  311. $response['sort'] = $_['sort'];
  312. if(empty($_FILES)) throw new Exception("Aucun document à importer");
  313. $path = Element::root().$_['path'].SLASH;
  314. $osPath = File::convert_decoding($path);
  315. if(!file_exists($osPath)) throw new Exception("Dossier ".$osPath." introuvable");
  316. $maxSize = $conf->get('document_allowed_size');
  317. $extensions = explode(',',str_replace(' ', '', $conf->get('document_allowed_extensions')));
  318. $extension = getExt($_FILES['file']['name'][0]);
  319. if($_FILES['file']['size'][0] > $maxSize) throw new Exception("Taille du fichier ".$_FILES['file']['name'][0]." trop grande, taille maximum :".readable_size($maxSize).' ('.$maxSize.' octets)');
  320. if(!in_array($extension , $extensions)) throw new Exception("Extension '".$extension."' du fichier ".$_FILES['file']['name'][0]." non permise, autorisé :".implode(', ',$extensions));
  321. if($_['method'] == 'paste') $_FILES['file']['name'][0] = 'presse papier '.date('d-m-Y H-i-s').'.'.$extension;
  322. $filePath = $path.$_FILES['file']['name'][0];
  323. if(!file_exists($_FILES['file']['tmp_name'][0])) throw new Exception("Fichier temporaire n°".$_['sort']." inexistant, verifiez la clause upload_max_size de PHP.");
  324. Element::addFile($filePath,file_get_contents($_FILES['file']['tmp_name'][0]));
  325. if($conf->get('document_enable_logs')) Log::put("Upload d'un élément : ".$filePath,'document');
  326. });
  327. break;
  328. //Sauvegarde des configurations de document
  329. case 'document_setting_save':
  330. Action::write(function(&$response){
  331. global $myUser,$_,$conf;
  332. User::check_access('document','configure');
  333. foreach(Configuration::setting('document') as $key=>$value){
  334. if(!is_array($value)) continue;
  335. $allowed[] = $key;
  336. }
  337. foreach ($_['fields'] as $key => $value)
  338. if(in_array($key, $allowed)) $conf->put($key,$value);
  339. });
  340. break;
  341. /** ELEMENTRIGHT **/
  342. //Récuperation d'une liste de elementright
  343. case 'document_right_search':
  344. Action::write(function(&$response){
  345. global $myUser,$_;
  346. User::check_access('document','read');
  347. require_once(__DIR__.SLASH.'ElementRight.class.php');
  348. $rights = ElementRight::loadAll(array('element'=>$_['id']));
  349. foreach($rights as $right){
  350. if($right->entity =='rank'){
  351. $rank = Rank::getById($right->uid);
  352. if(!$rank) continue;
  353. $right->uid = $rank->label.' <small class="text-muted">(rang)</small>';
  354. }
  355. $row = $right->toArray();
  356. if($row['read'] == 0) unset($row['read']);
  357. if($row['edit'] == 0) unset($row['edit']);
  358. if($row['recursive'] == 0) unset($row['recursive']);
  359. $response['rows'][] = $row;
  360. }
  361. });
  362. break;
  363. //Ajout ou modification d'élément elementright
  364. case 'document_right_save':
  365. Action::write(function(&$response){
  366. global $myUser,$_;
  367. User::check_access('document','edit');
  368. require_once(__DIR__.SLASH.'ElementRight.class.php');
  369. require_once(__DIR__.SLASH.'Element.class.php');
  370. if(!isset($_['uid']) || empty($_['uid'])) throw new Exception("UID de partage non spécifié");
  371. $element = Element::provide('element');
  372. if(!$element) throw new Exception("Cet élément n'existe pas",404);
  373. if($element->creator != $myUser->login && !$myUser->can('document','configure') && !$myUser->superadmin) throw new Exception("Vous n'êtes pas propriétaire de cet élement",403);
  374. $item = ElementRight::provide();
  375. $item->element = $element->id;
  376. $item->recursive = isset($_['recursive']) ? $_['recursive'] : 0 ;
  377. $item->edit = isset($_['edit']) ? $_['edit'] : 0 ;
  378. $item->read = isset($_['read']) ? $_['read'] : 0 ;
  379. $item->uid = $_['uid'];
  380. $item->entity = is_numeric($_['uid']) ? 'rank' : 'user';
  381. //supression des anciens droits sur le même couple element / utilisateur si existants
  382. ElementRight::delete(array('element'=>$item->element,'entity'=>$item->entity,'uid'=>$item->uid));
  383. $item->save();
  384. });
  385. break;
  386. //Suppression d'élement elementright
  387. case 'document_right_delete':
  388. Action::write(function(&$response){
  389. global $myUser,$_;
  390. User::check_access('document','delete');
  391. require_once(__DIR__.SLASH.'ElementRight.class.php');
  392. require_once(__DIR__.SLASH.'Element.class.php');
  393. $right = ElementRight::provide('id',1);
  394. $element = $right->join('element');
  395. if(!$element) throw new Exception("Cet élément n'existe pas",404);
  396. if($element->creator != $myUser->login && !$myUser->can('document','configure') && !$myUser->superadmin) throw new Exception("Vous n'etes pas propriétaire de cet élement",403);
  397. ElementRight::deleteById($right->id);
  398. });
  399. break;
  400. }
  401. ?>