actions_linkedfiles.inc.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. <?php
  2. /* Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  3. * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
  4. * Copyright (C) 2015 Ferran Marcet <fmarcet@2byte.es>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. * or see https://www.gnu.org/
  19. */
  20. // Variable $upload_dir must be defined when entering here.
  21. // Variable $upload_dirold may also exists.
  22. // Variable $confirm must be defined.
  23. // If variable $permissiontoadd is defined, we check it is true. Note: A test on permission should already have been done into the restrictedArea() method called by parent page.
  24. //var_dump($upload_dir);
  25. //var_dump($upload_dirold);
  26. // Protection to understand what happen when submitting files larger than post_max_size
  27. if (GETPOST('uploadform', 'int') && empty($_POST) && empty($_FILES)) {
  28. dol_syslog("The PHP parameter 'post_max_size' is too low. All POST parameters and FILES were set to empty.");
  29. $langs->loadLangs(array("errors", "install"));
  30. print $langs->trans("ErrorFileSizeTooLarge").' ';
  31. print $langs->trans("ErrorGoBackAndCorrectParameters");
  32. die;
  33. }
  34. if ((GETPOST('sendit', 'alpha')
  35. || GETPOST('linkit', 'restricthtml')
  36. || ($action == 'confirm_deletefile' && $confirm == 'yes')
  37. || ($action == 'confirm_updateline' && GETPOST('save', 'alpha') && GETPOST('link', 'alpha'))
  38. || ($action == 'renamefile' && GETPOST('renamefilesave', 'alpha'))) && empty($permissiontoadd)) {
  39. dol_syslog('The file actions_linkedfiles.inc.php was included but parameter $permissiontoadd was not set before.');
  40. print 'The file actions_linkedfiles.inc.php was included but parameter $permissiontoadd was not set before.';
  41. die;
  42. }
  43. // Submit file/link
  44. if (GETPOST('sendit', 'alpha') && getDolGlobalString('MAIN_UPLOAD_DOC') && !empty($permissiontoadd)) {
  45. if (!empty($_FILES) && is_array($_FILES['userfile'])) {
  46. if (is_array($_FILES['userfile']['tmp_name'])) {
  47. $userfiles = $_FILES['userfile']['tmp_name'];
  48. } else {
  49. $userfiles = array($_FILES['userfile']['tmp_name']);
  50. }
  51. foreach ($userfiles as $key => $userfile) {
  52. if (empty($_FILES['userfile']['tmp_name'][$key])) {
  53. $error++;
  54. if ($_FILES['userfile']['error'][$key] == 1 || $_FILES['userfile']['error'][$key] == 2) {
  55. setEventMessages($langs->trans('ErrorFileSizeTooLarge'), null, 'errors');
  56. } else {
  57. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("File")), null, 'errors');
  58. }
  59. }
  60. if (preg_match('/__.*__/', $_FILES['userfile']['name'][$key])) {
  61. $error++;
  62. setEventMessages($langs->trans('ErrorWrongFileName'), null, 'errors');
  63. }
  64. }
  65. if (!$error) {
  66. // Define if we have to generate thumbs or not
  67. $generatethumbs = 1;
  68. if (GETPOST('section_dir', 'alpha')) {
  69. $generatethumbs = 0;
  70. }
  71. $allowoverwrite = (GETPOST('overwritefile', 'int') ? 1 : 0);
  72. if (!empty($upload_dirold) && getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
  73. $result = dol_add_file_process($upload_dirold, $allowoverwrite, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs, $object);
  74. } elseif (!empty($upload_dir)) {
  75. $result = dol_add_file_process($upload_dir, $allowoverwrite, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs, $object);
  76. }
  77. }
  78. }
  79. } elseif (GETPOST('linkit', 'restricthtml') && getDolGlobalString('MAIN_UPLOAD_DOC') && !empty($permissiontoadd)) {
  80. $link = GETPOST('link', 'alpha');
  81. if ($link) {
  82. if (substr($link, 0, 7) != 'http://' && substr($link, 0, 8) != 'https://' && substr($link, 0, 7) != 'file://' && substr($link, 0, 7) != 'davs://') {
  83. $link = 'http://'.$link;
  84. }
  85. // Parse $newUrl
  86. $newUrlArray = parse_url($link);
  87. // Allow external links to svg ?
  88. if (!getDolGlobalString('MAIN_ALLOW_SVG_FILES_AS_EXTERNAL_LINKS')) {
  89. if (!empty($newUrlArray['path']) && preg_match('/\.svg$/i', $newUrlArray['path'])) {
  90. $error++;
  91. $langs->load("errors");
  92. setEventMessages($langs->trans('ErrorSVGFilesNotAllowedAsLinksWithout', 'MAIN_ALLOW_SVG_FILES_AS_EXTERNAL_LINKS'), null, 'errors');
  93. }
  94. }
  95. // Check URL is external (must refuse local link by default)
  96. if (!getDolGlobalString('MAIN_ALLOW_LOCAL_LINKS_AS_EXTERNAL_LINKS')) {
  97. // Test $newUrlAray['host'] to check link is external using isIPAllowed() and if not refuse the local link
  98. // TODO
  99. }
  100. if (!$error) {
  101. dol_add_file_process($upload_dir, 0, 1, 'userfile', null, $link, '', 0);
  102. }
  103. }
  104. }
  105. // Delete file/link
  106. if ($action == 'confirm_deletefile' && $confirm == 'yes' && !empty($permissiontoadd)) {
  107. $urlfile = GETPOST('urlfile', 'alpha', 0, null, null, 1); // Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP).
  108. if (GETPOST('section', 'alpha')) {
  109. // For a delete from the ECM module, upload_dir is ECM root dir and urlfile contains relative path from upload_dir
  110. $file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile;
  111. } else { // For a delete from the file manager into another module, or from documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile.
  112. $urlfile = basename($urlfile);
  113. $file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile;
  114. if (!empty($upload_dirold)) {
  115. $fileold = $upload_dirold."/".$urlfile;
  116. }
  117. }
  118. $linkid = GETPOST('linkid', 'int');
  119. if ($urlfile) {
  120. // delete of a file
  121. $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
  122. $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette (if file is an image)
  123. $ret = dol_delete_file($file, 0, 0, 0, (is_object($object) ? $object : null));
  124. if (!empty($fileold)) {
  125. dol_delete_file($fileold, 0, 0, 0, (is_object($object) ? $object : null)); // Delete file using old path
  126. }
  127. if ($ret) {
  128. // If it exists, remove thumb.
  129. $regs = array();
  130. if (preg_match('/(\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff)$/i', $file, $regs)) {
  131. $photo_vignette = basename(preg_replace('/'.$regs[0].'/i', '', $file).'_small'.$regs[0]);
  132. if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
  133. dol_delete_file($dirthumb.$photo_vignette);
  134. }
  135. $photo_vignette = basename(preg_replace('/'.$regs[0].'/i', '', $file).'_mini'.$regs[0]);
  136. if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
  137. dol_delete_file($dirthumb.$photo_vignette);
  138. }
  139. }
  140. setEventMessages($langs->trans("FileWasRemoved", $urlfile), null, 'mesgs');
  141. } else {
  142. setEventMessages($langs->trans("ErrorFailToDeleteFile", $urlfile), null, 'errors');
  143. }
  144. } elseif ($linkid) { // delete of external link
  145. require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
  146. $link = new Link($db);
  147. $link->fetch($linkid);
  148. $res = $link->delete($user);
  149. $langs->load('link');
  150. if ($res > 0) {
  151. setEventMessages($langs->trans("LinkRemoved", $link->label), null, 'mesgs');
  152. } else {
  153. if (count($link->errors)) {
  154. setEventMessages('', $link->errors, 'errors');
  155. } else {
  156. setEventMessages($langs->trans("ErrorFailedToDeleteLink", $link->label), null, 'errors');
  157. }
  158. }
  159. }
  160. if (is_object($object) && $object->id > 0) {
  161. if (!empty($backtopage)) {
  162. header('Location: '.$backtopage);
  163. exit;
  164. } else {
  165. $tmpurl = $_SERVER["PHP_SELF"].'?id='.$object->id.(GETPOST('section_dir', 'alpha') ? '&section_dir='.urlencode(GETPOST('section_dir', 'alpha')) : '').(!empty($withproject) ? '&withproject=1' : '');
  166. header('Location: '.$tmpurl);
  167. exit;
  168. }
  169. }
  170. } elseif ($action == 'confirm_updateline' && GETPOST('save', 'alpha') && GETPOST('link', 'alpha') && !empty($permissiontoadd)) {
  171. require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
  172. $link = new Link($db);
  173. $f = $link->fetch(GETPOST('linkid', 'int'));
  174. if ($f) {
  175. $link->url = GETPOST('link', 'alpha');
  176. if (substr($link->url, 0, 7) != 'http://' && substr($link->url, 0, 8) != 'https://' && substr($link->url, 0, 7) != 'file://') {
  177. $link->url = 'http://'.$link->url;
  178. }
  179. $link->label = GETPOST('label', 'alphanohtml');
  180. $res = $link->update($user);
  181. if (!$res) {
  182. setEventMessages($langs->trans("ErrorFailedToUpdateLink", $link->label), null, 'mesgs');
  183. }
  184. } else {
  185. //error fetching
  186. }
  187. } elseif ($action == 'renamefile' && GETPOST('renamefilesave', 'alpha') && !empty($permissiontoadd)) {
  188. // For documents pages, upload_dir contains already the path to the file from module dir
  189. if (!empty($upload_dir)) {
  190. $filenamefrom = dol_sanitizeFileName(GETPOST('renamefilefrom', 'alpha'), '_', 0); // Do not remove accents
  191. $filenameto = dol_sanitizeFileName(GETPOST('renamefileto', 'alpha'), '_', 0); // Do not remove accents
  192. // We apply dol_string_nohtmltag also to clean file names (this remove duplicate spaces) because
  193. // this function is also applied when we upload and when we make try to download file (by the GETPOST(filename, 'alphanohtml') call).
  194. $filenameto = dol_string_nohtmltag($filenameto);
  195. if (preg_match('/__.*__/', $filenameto)) {
  196. $error++;
  197. setEventMessages($langs->trans('ErrorWrongFileName'), null, 'errors');
  198. }
  199. // Check that filename is not the one of a reserved allowed CLI command
  200. if (empty($error)) {
  201. global $dolibarr_main_restrict_os_commands;
  202. if (!empty($dolibarr_main_restrict_os_commands)) {
  203. $arrayofallowedcommand = explode(',', $dolibarr_main_restrict_os_commands);
  204. $arrayofallowedcommand = array_map('trim', $arrayofallowedcommand);
  205. if (in_array(basename($filenameto), $arrayofallowedcommand)) {
  206. $error++;
  207. $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
  208. setEventMessages($langs->trans("ErrorFilenameReserved", basename($filenameto)), null, 'errors');
  209. }
  210. }
  211. }
  212. if (empty($error) && $filenamefrom != $filenameto) {
  213. // Security:
  214. // Disallow file with some extensions. We rename them.
  215. // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code.
  216. if (isAFileWithExecutableContent($filenameto) && !getDolGlobalString('MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED')) {
  217. // $upload_dir ends with a slash, so be must be sure the medias dir to compare to ends with slash too.
  218. $publicmediasdirwithslash = $conf->medias->multidir_output[$conf->entity];
  219. if (!preg_match('/\/$/', $publicmediasdirwithslash)) {
  220. $publicmediasdirwithslash .= '/';
  221. }
  222. if (strpos($upload_dir, $publicmediasdirwithslash) !== 0) { // We never add .noexe on files into media directory
  223. $filenameto .= '.noexe';
  224. }
  225. }
  226. if ($filenamefrom && $filenameto) {
  227. $srcpath = $upload_dir.'/'.$filenamefrom;
  228. $destpath = $upload_dir.'/'.$filenameto;
  229. $reshook = $hookmanager->initHooks(array('actionlinkedfiles'));
  230. $parameters = array('filenamefrom' => $filenamefrom, 'filenameto' => $filenameto, 'upload_dir' => $upload_dir);
  231. $reshook = $hookmanager->executeHooks('renameUploadedFile', $parameters, $object);
  232. if (empty($reshook)) {
  233. if (preg_match('/^\./', $filenameto)) {
  234. $langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now.
  235. setEventMessages($langs->trans("ErrorFilenameCantStartWithDot", $filenameto), null, 'errors');
  236. } elseif (!file_exists($destpath)) {
  237. $result = dol_move($srcpath, $destpath);
  238. if ($result) {
  239. // Define if we have to generate thumbs or not
  240. $generatethumbs = 1;
  241. // When we rename a file from the file manager in ecm, we must not regenerate thumbs (not a problem, we do pass here)
  242. // When we rename a file from the website module, we must not regenerate thumbs (module = medias in such a case)
  243. // but when we rename from a tab "Documents", we must regenerate thumbs
  244. if (GETPOST('modulepart', 'aZ09') == 'medias') {
  245. $generatethumbs = 0;
  246. }
  247. if ($generatethumbs) {
  248. if ($object->id > 0) {
  249. // Create thumbs for the new file
  250. $object->addThumbs($destpath);
  251. // Delete thumb files with old name
  252. $object->delThumbs($srcpath);
  253. }
  254. }
  255. setEventMessages($langs->trans("FileRenamed"), null);
  256. } else {
  257. $langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now.
  258. setEventMessages($langs->trans("ErrorFailToRenameFile", $filenamefrom, $filenameto), null, 'errors');
  259. }
  260. } else {
  261. $langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now.
  262. setEventMessages($langs->trans("ErrorDestinationAlreadyExists", $filenameto), null, 'errors');
  263. }
  264. }
  265. }
  266. }
  267. }
  268. // Update properties in ECM table
  269. if (GETPOST('ecmfileid', 'int') > 0) {
  270. $shareenabled = GETPOST('shareenabled', 'alpha');
  271. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  272. $ecmfile = new EcmFiles($db);
  273. $result = $ecmfile->fetch(GETPOST('ecmfileid', 'int'));
  274. if ($result > 0) {
  275. if ($shareenabled) {
  276. if (empty($ecmfile->share)) {
  277. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  278. $ecmfile->share = getRandomPassword(true);
  279. }
  280. } else {
  281. $ecmfile->share = '';
  282. }
  283. $result = $ecmfile->update($user);
  284. if ($result < 0) {
  285. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  286. }
  287. }
  288. }
  289. }