document.plugin.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. <?php
  2. //Déclaration d'un item de menu dans le menu principal
  3. function document_menu(&$menuItems){
  4. global $_,$myUser;
  5. if(!$myUser->can('document','read')) return;
  6. $menuItems[] = array(
  7. 'sort'=>4,
  8. 'url'=>'index.php?module=document',
  9. 'label'=>'Documents',
  10. 'icon'=> 'far fa-copy',
  11. 'color'=> '#FFBA00'
  12. );
  13. }
  14. //Cette fonction va generer une page quand on clique sur document dans menu
  15. function document_page(){
  16. global $_,$myUser;
  17. if(!isset($_['module']) || $_['module'] !='document') return;
  18. $page = !isset($_['page']) ? 'list' : $_['page'];
  19. $file = __DIR__.SLASH.'page.'.$page.'.php';
  20. if(!file_exists($file)) throw new Exception("Page ".$page." inexistante");
  21. require_once($file);
  22. }
  23. //Fonction executée lors de l'activation du plugin
  24. function document_install($id){
  25. if($id != 'fr.sys1.document') return;
  26. Entity::install(__DIR__);
  27. if(!file_exists(Element::root()))
  28. mkdir(Element::root(),0755,true);
  29. if(!file_exists(__DIR__.SLASH.'logs'))
  30. mkdir(__DIR__.SLASH.'logs',0755,true);
  31. global $conf;
  32. $conf->put('document_allowed_extensions','csv,xls,xlsx,doc,docx,dotm,dotx,pdf,png,jpg,jpeg,gif,tif,svg,bmp,txt,zip,gzip,msg');
  33. $conf->put('document_allowed_size',10485760);
  34. }
  35. //Fonction executée lors de la désactivation du plugin
  36. function document_uninstall($id){
  37. if($id != 'fr.sys1.document') return;
  38. Entity::uninstall(__DIR__);
  39. }
  40. //Déclaration des sections de droits du plugin
  41. function document_section(&$sections){
  42. $sections['document'] = "Gestion des droits sur le plugin document";
  43. }
  44. //Cette fonction comprend toutes les actions du plugin qui ne nécessitent pas de vue html
  45. function document_action(){
  46. require_once(__DIR__.SLASH.'action.php');
  47. }
  48. //Déclaration du menu de réglages
  49. function document_menu_setting(&$settingMenu){
  50. global $_, $myUser;
  51. if($myUser->can('document','configure')) {
  52. $settingMenu[]= array(
  53. 'sort' =>4,
  54. 'url' => 'setting.php?section=document',
  55. 'icon' => 'fas fa-angle-right',
  56. 'label' => 'Documents'
  57. );
  58. }
  59. }
  60. //Déclaration des pages de réglages
  61. function document_content_setting(){
  62. global $_;
  63. if(file_exists(__DIR__.SLASH.'setting.'.$_['section'].'.php'))
  64. require_once(__DIR__.SLASH.'setting.'.$_['section'].'.php');
  65. }
  66. //Vérifie qu'un nom de fichier ou de dossier ne contient pas des caractères interdits par l'os (?:*|<>/\)
  67. function document_check_element_name($element){
  68. $pattern = "\/\\\:\*\?\"\<\>\|";
  69. preg_match('|['.$pattern.']|i', $element, $match);
  70. return !empty($match) ? $match[0] : '';
  71. }
  72. function document_dav_document($requested){
  73. global $conf,$myUser;
  74. $requested = trim($requested, '/');
  75. if(substr($requested, 0,13)!='dav/documents') return;
  76. if(empty($requested)) throw new Exception("Unspecified DAV path");
  77. if($conf->get('document_enable_dav') != "1"){
  78. header('HTTP/1.1 501 Method not implemented');
  79. header('Content-Type: text/html; charset=utf-8');
  80. throw new Exception('Mode Webdav désactivé, veuillez débloquer le Webdav dans les paramétrages pour accéder à cette fonctionnalité');
  81. }
  82. require_once(__ROOT__.'common.php');
  83. require_once(__DIR__.SLASH.'Element.class.php');
  84. require_once(__DIR__.SLASH.'WebDav.class.php');
  85. $projectPath = preg_replace('|https?\:\/\/'.$_SERVER['HTTP_HOST'].'|i', '', ROOT_URL);
  86. $server = new WebDav();
  87. $server->logs = WebDav::logPath().SLASH.'dav-logs.txt';
  88. $server->lockfile = WebDav::logPath().SLASH.'dav-lock.json';
  89. $server->root = str_replace('//','/',$projectPath.'/dav/documents/');
  90. $server->folder = Element::root();
  91. //Windows cherche desktop.ini a chaque ouverture de dossier pour le custom
  92. $server->ignoreFiles[] = 'desktop.ini';
  93. //Tortoise et autre client git d'explorer cherchent les .git a chaques ouverture
  94. $server->ignoreFiles[] = '.git';
  95. if($conf->get('document_enable_dav_logs') == "1"){
  96. $server->on['log'] = function($message){
  97. Log::put(nl2br($message),'DAV');
  98. };
  99. }
  100. $server->do['login'] = function($login,$password){
  101. global $myUser;
  102. if($myUser->login !=''){
  103. //file_put_contents(WebDav::logPath().SLASH.'dav-logs.txt', 'already connected with : '.$login.PHP_EOL,FILE_APPEND);
  104. return $myUser;
  105. }
  106. // file_put_contents(WebDav::logPath().SLASH.'dav-logs.txt', 'Connecting with : '.$login.PHP_EOL,FILE_APPEND);
  107. $myUser = User::check($login,$password);
  108. if(!$myUser)
  109. throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur",401);
  110. if(file_exists('enabled.maintenance') && $myUser->superadmin != 1)
  111. throw new Exception('Seul un compte Super Admin peut se connecter en mode maintenance',401);
  112. if(!$myUser->connected())
  113. throw new Exception('Identifiant ou mot de passe incorrect',401);
  114. if(is_numeric($myUser->preference('default_firm')) && $myUser->haveFirm($myUser->preference('default_firm'))){
  115. $_SESSION['firm'] = serialize(Firm::getById($myUser->preference('default_firm')));
  116. if(!$_SESSION['firm'])
  117. throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur",401);
  118. }else if(count($myUser->firms)!=0){
  119. $_SESSION['firm'] = serialize(reset($myUser->firms));
  120. if(!$_SESSION['firm'])
  121. throw new Exception(" Problème lors de la connexion, veuillez contacter l'administrateur",401);
  122. }else{
  123. throw new Exception('Ce compte n\'est actif sur aucune firm',401);
  124. }
  125. $myFirm = isset($_SESSION['firm']) ? unserialize($_SESSION['firm']) : new Firm();
  126. if(!$myFirm)
  127. throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur",401);
  128. $_SESSION['currentUser'] = serialize($myUser);
  129. if(!$_SESSION['currentUser'])
  130. throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur",401);
  131. };
  132. $server->do['delete'] = function($isoPath){
  133. global $myUser,$conf;
  134. $utf8Path = utf8_encode($isoPath);
  135. Element::remove($utf8Path);
  136. if($conf->get('document_enable_logs')) Log::put('Suppression de '.$utf8Path,'document');
  137. };
  138. $server->do['download'] = function($isoPath){
  139. global $myUser,$_,$conf;
  140. $utf8Path = utf8_encode($isoPath);
  141. //pour verfiier si le fichier existe, on récupere son chemin système avec le bon encodage
  142. $osPath = get_OS() === 'WIN' ? $isoPath: $utf8Path;
  143. if(!file_exists($osPath)) throw new Exception("Fichier inexistant",404);
  144. if(!is_file($osPath)) throw new Exception("Méthode non autorisée sur autre chose qu'un fichier",501);
  145. $stream = Element::download($utf8Path);
  146. if($conf->get('document_enable_logs_verbose')) Log::put('Téléchargement de '.$utf8Path,'document');
  147. return $stream;
  148. };
  149. $server->do['edit'] = function($isoPath,$body,$type){
  150. global $myUser,$conf;
  151. User::check_access('document','edit');
  152. $utf8Path = utf8_encode($isoPath);
  153. if($type=='file'){
  154. $maxSize = $conf->get('document_allowed_size');
  155. $extension = getExt($utf8Path);
  156. $extensions = explode(',',str_replace(' ', '', $conf->get('document_allowed_extensions')));
  157. if(strlen($body) > $maxSize) throw new Exception("Taille du fichier trop grande, taille maximum :".readable_size($maxSize).' ('.$maxSize.' octets)',406);
  158. if(!in_array($extension , $extensions)) throw new Exception("Extension '".$extension."' du fichier ".$path." non permise, autorisé :".implode(', ',$extensions),415);
  159. $element = Element::addFile($utf8Path, $body);
  160. if($conf->get('document_enable_logs') || $conf->get('document_enable_logs_verbose')) Log::put('Enregistrement fichier '.$utf8Path,'document');
  161. }else{
  162. Element::addFolder($utf8Path);
  163. if($conf->get('document_enable_logs') || $conf->get('document_enable_logs_verbose')) Log::put('Enregistrement dossier '.$utf8Path,'document');
  164. }
  165. $element = Element::fromPath($utf8Path);
  166. $baseElement = Element::load(array('path'=>$element->path));
  167. if(is_object($baseElement) && $baseElement->id!=0) $element->id = $baseElement->id;
  168. $element->save();
  169. };
  170. $server->do['move'] = function($isoPath,$isoTo){
  171. global $myUser,$conf;
  172. $utf8Path = utf8_encode($isoPath);
  173. $utf8To = utf8_encode($isoTo);
  174. User::check_access('document','edit');
  175. $char = document_check_element_name(mt_basename($utf8To));
  176. if(!empty($char)) throw new Exception("Caractères interdits : ".$char);
  177. Element::move($utf8Path,$utf8To);
  178. if($conf->get('document_enable_logs') || $conf->get('document_enable_logs_verbose')) Log::put('Déplacement de '.$utf8Path.' dans '.$utf8To,'document');
  179. };
  180. $server->do['copy'] = function($isoPath,$isoTo){
  181. global $myUser,$conf;
  182. $utf8Path = utf8_encode($isoPath);
  183. $utf8To = utf8_encode($isoTo);
  184. User::check_access('document','edit');
  185. $char = document_check_element_name(mt_basename($utf8To));
  186. if(!empty($char)) throw new Exception("Caractères interdits : ".$char);
  187. Element::copy($utf8Path,$utf8To);
  188. if($conf->get('document_enable_logs') || $conf->get('document_enable_logs_verbose')) Log::put('Copie de '.$utf8Path.' dans '.$utf8To,'document');
  189. };
  190. $server->do['list'] = function($isoPath,$depth =0){
  191. global $myUser,$conf;
  192. $utf8Path = utf8_encode($isoPath);
  193. User::check_access('document','read');
  194. //pour verfier si le fichier existe, on récupere son chemin système avec le bon encodage
  195. $osPath = get_OS() === 'WIN' ? $isoPath: $utf8Path;
  196. if(!file_exists($osPath)) throw new Exception("Not found", 404);
  197. $files = array();
  198. //Si la cible est la racine dav, on la retourne sous forme d'element fictif, sinon on utilise le systeme d'element standard
  199. if($utf8Path == Element::root()){
  200. $file = new Element();
  201. $file->label = '';
  202. $file->type = 'directory';
  203. $file->path = '';
  204. $toScan = array($file);
  205. }else{
  206. $toScan = array(Element::fromPath($utf8Path));
  207. }
  208. if($conf->get('document_enable_logs_verbose')) Logs::put('visualisation de '.$utf8Path,'document');
  209. //Si le dav demande un scan en profondeur du dossier, on scan les enfants du dossier ciblé
  210. if($depth>0)
  211. $toScan = array_merge($toScan,Element::browse($utf8Path.SLASH.'*'));
  212. foreach($toScan as $element){
  213. //on convertis l'utf8 de l'element pour passer en iso webdav windows si le serveur est sous windows
  214. $path = Element::root().(get_OS() === 'WIN' ? utf8_decode( $element->path) : $element->path );
  215. $file = array(
  216. 'type' => $element->type,
  217. 'label' => $element->label
  218. );
  219. if($element->type == 'directory'){
  220. $stat = stat($path);
  221. $file['create_time'] = $stat['ctime'];
  222. $file['update_time'] = $stat['mtime'];
  223. $file['length'] = $stat['size'];
  224. }else{
  225. $file['create_time'] = filectime($path);
  226. $file['update_time'] = filemtime($path);
  227. $file['length'] = filesize($path);
  228. }
  229. $files[] = $file;
  230. }
  231. return $files;
  232. };
  233. $server->start();
  234. }
  235. //Déclaration des settings de base
  236. //Types possibles : text,select ( + "values"=> array('1'=>'Val 1'),password,checkbox. Un simple string définit une catégorie.
  237. Configuration::setting('document',array(
  238. "Général",
  239. 'document_allowed_extensions' => array("label"=>"Extensions autorisées","type"=>"text","legend"=>"(séparés par virgules)","placeholder"=>"csv,pdf,jpg,..."),
  240. 'document_allowed_size' => array("label"=>"Taille maximum autorisée","type"=>"text","legend"=>"(en octets)","placeholder"=>"28060000","type"=>"number"),
  241. 'document_enable_logs' => array("label"=>"Activer les logs standards","legend"=>"(ajout, supression, modifification d'un fichier ou dossier)","type"=>"checkbox"),
  242. 'document_enable_logs_verbose' => array("label"=>"Activer les logs avancés","legend"=>"(lecture ou téléchargement d'un fichier ou dossier)","type"=>"checkbox"),
  243. "Options DAV <br><small style='font-size:65%;' class='text-muted'>Adresse WebDAV : <code>".
  244. ( substr(ROOT_URL,-1) == '/' ? substr(ROOT_URL,0,(strlen(ROOT_URL)-1)) : ROOT_URL )
  245. ."/dav/documents</code><br>
  246. Les Identifiants sont identiques à ceux de l'erp<br>
  247. Si vous souhaitez vous connecter avec un lecteur réseau windows, vous devez installer un certificat https</small>",
  248. 'document_enable_dav' => array("label"=>"Activer le WebDav","type"=>"checkbox"),
  249. 'document_enable_dav_logs' => array("label"=>"Activer les logs WebDav ","type"=>"checkbox"),
  250. ));
  251. function document_widget(&$widgets){
  252. global $myUser;
  253. require_once(__DIR__.SLASH.'..'.SLASH.'dashboard'.SLASH.'DashboardWidget.class.php');
  254. $modelWidget = new DashboardWidget();
  255. $modelWidget->model = 'document';
  256. $modelWidget->title = 'Documents';
  257. $modelWidget->icon = 'fas fa-file';
  258. $modelWidget->background = '#A3CB38';
  259. $modelWidget->callback = 'init_components';
  260. $modelWidget->load = 'action.php?action=document_widget_load';
  261. if($myUser->can('document','configure')){
  262. $modelWidget->configure = 'action.php?action=document_widget_configure';
  263. $modelWidget->configure_callback = 'document_widget_configure_save';
  264. }
  265. $modelWidget->js = [Plugin::url().'/js/widget.js?v='.time()];
  266. $modelWidget->css = [Plugin::url().'/css/widget.css?v=1'.time()];
  267. $modelWidget->description = "Affiche un espace document";
  268. $widgets[] = $modelWidget;
  269. }
  270. function document_client_menu(&$clientMenu,$client){
  271. $menu = new MenuItem();
  272. $menu->label = 'Documents';
  273. $menu->url = '#tab=document';
  274. $menu->slug = 'document';
  275. $menu->sort = 10;
  276. $clientMenu[] = $menu;
  277. }
  278. function document_client_page($slug){
  279. if($slug != 'document') return;
  280. require_once(__DIR__.SLASH.'tab.client.php');
  281. }
  282. //Déclation des assets
  283. Plugin::addCss("/css/main.css");
  284. Plugin::addCss("/css/document.api.css");
  285. Plugin::addJs("/js/component.js",true);
  286. Plugin::addJs("/js/document.api.js");
  287. Plugin::addJs("/js/main.js");
  288. //Mapping hook / fonctions
  289. Plugin::addHook("widget", "document_widget");
  290. Plugin::addHook("install", "document_install");
  291. Plugin::addHook("uninstall", "document_uninstall");
  292. Plugin::addHook("section", "document_section");
  293. Plugin::addHook("menu_main", "document_menu");
  294. Plugin::addHook("page", "document_page");
  295. Plugin::addHook("action", "document_action");
  296. Plugin::addHook("menu_setting", "document_menu_setting");
  297. Plugin::addHook("content_setting", "document_content_setting");
  298. Plugin::addHook("rewrite", "document_dav_document");
  299. Plugin::addHook("client_menu", "document_client_menu");
  300. Plugin::addHook("client_page", "document_client_page");
  301. ?>