document.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. <?php
  2. /* Copyright (C) 2004-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2013 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2005 Simon Tosser <simon@kornog-computing.com>
  5. * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
  6. * Copyright (C) 2010 Pierre Morin <pierre.morin@auguria.net>
  7. * Copyright (C) 2010 Juanjo Menent <jmenent@2byte.es>
  8. * Copyright (C) 2022 Ferran Marcet <fmarcet@2byte.es>
  9. *
  10. * This program is free software; you can redistribute it and/or modify
  11. * it under the terms of the GNU General Public License as published by
  12. * the Free Software Foundation; either version 3 of the License, or
  13. * (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  22. * or see https://www.gnu.org/
  23. */
  24. /**
  25. * \file htdocs/document.php
  26. * \brief Wrapper to download data files
  27. * \remarks Call of this wrapper is made with URL:
  28. * DOL_URL_ROOT.'/document.php?modulepart=repfichierconcerne&file=relativepathoffile'
  29. * DOL_URL_ROOT.'/document.php?modulepart=logs&file=dolibarr.log'
  30. * DOL_URL_ROOT.'/document.php?hashp=sharekey'
  31. */
  32. define('MAIN_SECURITY_FORCECSP', "default-src: 'none'");
  33. //if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled cause need to load personalized language
  34. //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled cause need to load personalized language
  35. if (!defined('NOTOKENRENEWAL')) {
  36. define('NOTOKENRENEWAL', '1');
  37. }
  38. if (!defined('NOREQUIREMENU')) {
  39. define('NOREQUIREMENU', '1');
  40. }
  41. if (!defined('NOREQUIREHTML')) {
  42. define('NOREQUIREHTML', '1');
  43. }
  44. if (!defined('NOREQUIREAJAX')) {
  45. define('NOREQUIREAJAX', '1');
  46. }
  47. // For direct external download link, we don't need to load/check we are into a login session
  48. if (isset($_GET["hashp"]) && !defined("NOLOGIN")) {
  49. if (!defined("NOLOGIN")) {
  50. define("NOLOGIN", 1);
  51. }
  52. if (!defined("NOCSRFCHECK")) {
  53. define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
  54. }
  55. if (!defined("NOIPCHECK")) {
  56. define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip
  57. }
  58. }
  59. // Some value of modulepart can be used to get resources that are public so no login are required.
  60. if ((isset($_GET["modulepart"]) && $_GET["modulepart"] == 'medias')) {
  61. if (!defined("NOLOGIN")) {
  62. define("NOLOGIN", 1);
  63. }
  64. if (!defined("NOCSRFCHECK")) {
  65. define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
  66. }
  67. if (!defined("NOIPCHECK")) {
  68. define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip
  69. }
  70. }
  71. /**
  72. * Header empty
  73. *
  74. * @ignore
  75. * @return void
  76. */
  77. function llxHeader()
  78. {
  79. }
  80. /**
  81. * Footer empty
  82. *
  83. * @ignore
  84. * @return void
  85. */
  86. function llxFooter()
  87. {
  88. }
  89. require 'main.inc.php'; // Load $user and permissions
  90. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  91. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  92. $encoding = '';
  93. $action = GETPOST('action', 'aZ09');
  94. $original_file = GETPOST('file', 'alphanohtml'); // Do not use urldecode here ($_GET are already decoded by PHP).
  95. $hashp = GETPOST('hashp', 'aZ09');
  96. $modulepart = GETPOST('modulepart', 'alpha');
  97. $urlsource = GETPOST('urlsource', 'alpha');
  98. $entity = GETPOST('entity', 'int') ?GETPOST('entity', 'int') : $conf->entity;
  99. // Security check
  100. if (empty($modulepart) && empty($hashp)) {
  101. httponly_accessforbidden('Bad link. Bad value for parameter modulepart', 400);
  102. }
  103. if (empty($original_file) && empty($hashp)) {
  104. httponly_accessforbidden('Bad link. Missing identification to find file (original_file or hashp)', 400);
  105. }
  106. if ($modulepart == 'fckeditor') {
  107. $modulepart = 'medias'; // For backward compatibility
  108. }
  109. $socid = 0;
  110. if ($user->socid > 0) {
  111. $socid = $user->socid;
  112. }
  113. // For some module part, dir may be privates
  114. if (in_array($modulepart, array('facture_paiement', 'unpaid'))) {
  115. if (!$user->hasRight('societe', 'client', 'voir') || $socid) {
  116. $original_file = 'private/'.$user->id.'/'.$original_file; // If user has no permission to see all, output dir is specific to user
  117. }
  118. }
  119. /*
  120. * Actions
  121. */
  122. // None
  123. /*
  124. * View
  125. */
  126. // If we have a hash public (hashp), we guess the original_file.
  127. $ecmfile='';
  128. if (!empty($hashp)) {
  129. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  130. $ecmfile = new EcmFiles($db);
  131. $result = $ecmfile->fetch(0, '', '', '', $hashp);
  132. if ($result > 0) {
  133. $tmp = explode('/', $ecmfile->filepath, 2); // $ecmfile->filepath is relative to document directory
  134. // filepath can be 'users/X' or 'X/propale/PR11111'
  135. if (is_numeric($tmp[0])) { // If first tmp is numeric, it is subdir of company for multicompany, we take next part.
  136. $tmp = explode('/', $tmp[1], 2);
  137. }
  138. $moduleparttocheck = $tmp[0]; // moduleparttocheck is first part of path
  139. if ($modulepart) { // Not required, so often not defined, for link using public hashp parameter.
  140. if ($moduleparttocheck == $modulepart) {
  141. // We remove first level of directory
  142. $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir
  143. //var_dump($original_file); exit;
  144. } else {
  145. httponly_accessforbidden('Bad link. File is from another module part.', 403);
  146. }
  147. } else {
  148. $modulepart = $moduleparttocheck;
  149. $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir
  150. }
  151. $entity = $ecmfile->entity;
  152. if ($entity != $conf->entity) {
  153. $conf->entity = $entity;
  154. $conf->setValues($db);
  155. }
  156. } else {
  157. $langs->load("errors");
  158. httponly_accessforbidden($langs->trans("ErrorFileNotFoundWithSharedLink"), 403, 1);
  159. }
  160. }
  161. // Define attachment (attachment=true to force choice popup 'open'/'save as')
  162. $attachment = true;
  163. if (preg_match('/\.(html|htm)$/i', $original_file)) {
  164. $attachment = false;
  165. }
  166. if (isset($_GET["attachment"])) {
  167. $attachment = GETPOST("attachment", 'alpha') ?true:false;
  168. }
  169. if (!empty($conf->global->MAIN_DISABLE_FORCE_SAVEAS)) {
  170. $attachment = false;
  171. }
  172. // Define mime type
  173. $type = 'application/octet-stream'; // By default
  174. if (GETPOST('type', 'alpha')) {
  175. $type = GETPOST('type', 'alpha');
  176. } else {
  177. $type = dol_mimetype($original_file);
  178. }
  179. // Security: Force to octet-stream if file is a dangerous file. For example when it is a .noexe file
  180. // We do not force if file is a javascript to be able to get js from website module with <script src="
  181. // Note: Force whatever is $modulepart seems ok.
  182. if (!in_array($type, array('text/x-javascript')) && !dolIsAllowedForPreview($original_file)) {
  183. $type = 'application/octet-stream';
  184. }
  185. // Security: Delete string ../ or ..\ into $original_file
  186. $original_file = preg_replace('/\.\.+/', '..', $original_file); // Replace '... or more' with '..'
  187. $original_file = str_replace('../', '/', $original_file);
  188. $original_file = str_replace('..\\', '/', $original_file);
  189. // Find the subdirectory name as the reference
  190. $refname = basename(dirname($original_file)."/");
  191. // Security check
  192. if (empty($modulepart)) {
  193. accessforbidden('Bad value for parameter modulepart');
  194. }
  195. // Check security and set return info with full path of file
  196. $check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, $user, $refname);
  197. $accessallowed = $check_access['accessallowed'];
  198. $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
  199. $fullpath_original_file = $check_access['original_file']; // $fullpath_original_file is now a full path name
  200. //var_dump($fullpath_original_file.' '.$original_file.' '.$refname.' '.$accessallowed);exit;
  201. if (!empty($hashp)) {
  202. $accessallowed = 1; // When using hashp, link is public so we force $accessallowed
  203. $sqlprotectagainstexternals = '';
  204. } else {
  205. // Basic protection (against external users only)
  206. if ($user->socid > 0) {
  207. if ($sqlprotectagainstexternals) {
  208. $resql = $db->query($sqlprotectagainstexternals);
  209. if ($resql) {
  210. $num = $db->num_rows($resql);
  211. $i = 0;
  212. while ($i < $num) {
  213. $obj = $db->fetch_object($resql);
  214. if ($user->socid != $obj->fk_soc) {
  215. $accessallowed = 0;
  216. break;
  217. }
  218. $i++;
  219. }
  220. }
  221. }
  222. }
  223. }
  224. // Security:
  225. // Limit access if permissions are wrong
  226. if (!$accessallowed) {
  227. accessforbidden();
  228. }
  229. // Security:
  230. // We refuse directory transversal change and pipes in file names
  231. if (preg_match('/\.\./', $fullpath_original_file) || preg_match('/[<>|]/', $fullpath_original_file)) {
  232. dol_syslog("Refused to deliver file ".$fullpath_original_file);
  233. print "ErrorFileNameInvalid: ".dol_escape_htmltag($original_file);
  234. exit;
  235. }
  236. clearstatcache();
  237. $filename = basename($fullpath_original_file);
  238. $filename = preg_replace('/\.noexe$/i', '', $filename);
  239. // Output file on browser
  240. dol_syslog("document.php download $fullpath_original_file filename=$filename content-type=$type");
  241. $fullpath_original_file_osencoded = dol_osencode($fullpath_original_file); // New file name encoded in OS encoding charset
  242. // This test if file exists should be useless. We keep it to find bug more easily
  243. if (!file_exists($fullpath_original_file_osencoded)) {
  244. dol_syslog("ErrorFileDoesNotExists: ".$fullpath_original_file);
  245. print "ErrorFileDoesNotExists: ".$original_file;
  246. exit;
  247. }
  248. // Hooks
  249. $hookmanager->initHooks(array('document'));
  250. $parameters = array('ecmfile' => $ecmfile, 'modulepart' => $modulepart, 'original_file' => $original_file,
  251. 'entity' => $entity, 'refname' => $refname, 'fullpath_original_file' => $fullpath_original_file,
  252. 'filename' => $filename, 'fullpath_original_file_osencoded' => $fullpath_original_file_osencoded);
  253. $object = new stdClass();
  254. $reshook = $hookmanager->executeHooks('downloadDocument', $parameters, $object, $action); // Note that $action and $object may have been
  255. if ($reshook < 0) {
  256. $errors = $hookmanager->error.(is_array($hookmanager->errors) ? (!empty($hookmanager->error) ? ', ' : '').join(', ', $hookmanager->errors) : '');
  257. dol_syslog("document.php - Errors when executing the hook 'downloadDocument' : ".$errors);
  258. print "ErrorDownloadDocumentHooks: ".$errors;
  259. exit;
  260. }
  261. // Permissions are ok and file found, so we return it
  262. top_httphead($type);
  263. header('Content-Description: File Transfer');
  264. if ($encoding) {
  265. header('Content-Encoding: '.$encoding);
  266. }
  267. // Add MIME Content-Disposition from RFC 2183 (inline=automatically displayed, attachment=need user action to open)
  268. if ($attachment) {
  269. header('Content-Disposition: attachment; filename="'.$filename.'"');
  270. } else {
  271. header('Content-Disposition: inline; filename="'.$filename.'"');
  272. }
  273. // Ajout directives pour resoudre bug IE
  274. header('Cache-Control: Public, must-revalidate');
  275. header('Pragma: public');
  276. $readfile = true;
  277. // on view document, can output images with good orientation according to exif infos
  278. if (!$attachment && !empty($conf->global->MAIN_USE_EXIF_ROTATION) && image_format_supported($fullpath_original_file_osencoded) == 1) {
  279. $imgres = correctExifImageOrientation($fullpath_original_file_osencoded, null);
  280. $readfile = !$imgres;
  281. }
  282. if (is_object($db)) {
  283. $db->close();
  284. }
  285. // Send file now
  286. if ($readfile) {
  287. header('Content-Length: '.dol_filesize($fullpath_original_file));
  288. readfileLowMemory($fullpath_original_file_osencoded);
  289. }