action.php 20 KB

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