dolibarr  19.0.0-dev
document.php
Go to the documentation of this file.
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 
34 define('MAIN_SECURITY_FORCECSP', "default-src: 'none'");
35 
36 //if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled cause need to load personalized language
37 //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled cause need to load personalized language
38 if (!defined('NOTOKENRENEWAL')) {
39  define('NOTOKENRENEWAL', '1');
40 }
41 if (!defined('NOREQUIREMENU')) {
42  define('NOREQUIREMENU', '1');
43 }
44 if (!defined('NOREQUIREHTML')) {
45  define('NOREQUIREHTML', '1');
46 }
47 if (!defined('NOREQUIREAJAX')) {
48  define('NOREQUIREAJAX', '1');
49 }
50 
51 // For direct external download link, we don't need to load/check we are into a login session
52 if (isset($_GET["hashp"]) && !defined("NOLOGIN")) {
53  if (!defined("NOLOGIN")) {
54  define("NOLOGIN", 1);
55  }
56  if (!defined("NOCSRFCHECK")) {
57  define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
58  }
59  if (!defined("NOIPCHECK")) {
60  define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip
61  }
62 }
63 // Some value of modulepart can be used to get resources that are public so no login are required.
64 if ((isset($_GET["modulepart"]) && $_GET["modulepart"] == 'medias')) {
65  if (!defined("NOLOGIN")) {
66  define("NOLOGIN", 1);
67  }
68  if (!defined("NOCSRFCHECK")) {
69  define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
70  }
71  if (!defined("NOIPCHECK")) {
72  define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip
73  }
74 }
75 
82 function llxHeader()
83 {
84 }
91 function llxFooter()
92 {
93 }
94 
95 require 'main.inc.php'; // Load $user and permissions
96 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
97 require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
98 
99 $encoding = '';
100 $action = GETPOST('action', 'aZ09');
101 $original_file = GETPOST('file', 'alphanohtml'); // Do not use urldecode here ($_GET are already decoded by PHP).
102 $hashp = GETPOST('hashp', 'aZ09');
103 $modulepart = GETPOST('modulepart', 'alpha');
104 $urlsource = GETPOST('urlsource', 'alpha');
105 $entity = GETPOST('entity', 'int') ?GETPOST('entity', 'int') : $conf->entity;
106 
107 // Security check
108 if (empty($modulepart) && empty($hashp)) {
109  httponly_accessforbidden('Bad link. Bad value for parameter modulepart', 400);
110 }
111 if (empty($original_file) && empty($hashp)) {
112  httponly_accessforbidden('Bad link. Missing identification to find file (original_file or hashp)', 400);
113 }
114 if ($modulepart == 'fckeditor') {
115  $modulepart = 'medias'; // For backward compatibility
116 }
117 
118 $socid = 0;
119 if ($user->socid > 0) {
120  $socid = $user->socid;
121 }
122 
123 // For some module part, dir may be privates
124 if (in_array($modulepart, array('facture_paiement', 'unpaid'))) {
125  if (!$user->hasRight('societe', 'client', 'voir') || $socid) {
126  $original_file = 'private/'.$user->id.'/'.$original_file; // If user has no permission to see all, output dir is specific to user
127  }
128 }
129 
130 
131 /*
132  * Actions
133  */
134 
135 // None
136 
137 
138 
139 /*
140  * View
141  */
142 
143 // If we have a hash public (hashp), we guess the original_file.
144 $ecmfile='';
145 if (!empty($hashp)) {
146  include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
147  $ecmfile = new EcmFiles($db);
148  $result = $ecmfile->fetch(0, '', '', '', $hashp);
149  if ($result > 0) {
150  $tmp = explode('/', $ecmfile->filepath, 2); // $ecmfile->filepath is relative to document directory
151  // filepath can be 'users/X' or 'X/propale/PR11111'
152  if (is_numeric($tmp[0])) { // If first tmp is numeric, it is subdir of company for multicompany, we take next part.
153  $tmp = explode('/', $tmp[1], 2);
154  }
155  $moduleparttocheck = $tmp[0]; // moduleparttocheck is first part of path
156 
157  if ($modulepart) { // Not required, so often not defined, for link using public hashp parameter.
158  if ($moduleparttocheck == $modulepart) {
159  // We remove first level of directory
160  $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir
161  //var_dump($original_file); exit;
162  } else {
163  httponly_accessforbidden('Bad link. File is from another module part.', 403);
164  }
165  } else {
166  $modulepart = $moduleparttocheck;
167  $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir
168  }
169  $entity = $ecmfile->entity;
170  if ($entity != $conf->entity) {
171  $conf->entity = $entity;
172  $conf->setValues($db);
173  }
174  } else {
175  $langs->load("errors");
176  httponly_accessforbidden($langs->trans("ErrorFileNotFoundWithSharedLink"), 403, 1);
177  }
178 }
179 
180 // Define attachment (attachment=true to force choice popup 'open'/'save as')
181 $attachment = true;
182 if (preg_match('/\.(html|htm)$/i', $original_file)) {
183  $attachment = false;
184 }
185 if (isset($_GET["attachment"])) {
186  $attachment = GETPOST("attachment", 'alpha') ?true:false;
187 }
188 if (!empty($conf->global->MAIN_DISABLE_FORCE_SAVEAS)) {
189  $attachment = false;
190 }
191 
192 // Define mime type
193 $type = 'application/octet-stream'; // By default
194 if (GETPOST('type', 'alpha')) {
195  $type = GETPOST('type', 'alpha');
196 } else {
197  $type = dol_mimetype($original_file);
198 }
199 // Security: Force to octet-stream if file is a dangerous file. For example when it is a .noexe file
200 // We do not force if file is a javascript to be able to get js from website module with <script src="
201 // Note: Force whatever is $modulepart seems ok.
202 if (!in_array($type, array('text/x-javascript')) && !dolIsAllowedForPreview($original_file)) {
203  $type = 'application/octet-stream';
204 }
205 
206 // Security: Delete string ../ or ..\ into $original_file
207 $original_file = preg_replace('/\.\.+/', '..', $original_file); // Replace '... or more' with '..'
208 $original_file = str_replace('../', '/', $original_file);
209 $original_file = str_replace('..\\', '/', $original_file);
210 
211 
212 // Find the subdirectory name as the reference
213 $refname = basename(dirname($original_file)."/");
214 
215 // Security check
216 if (empty($modulepart)) {
217  accessforbidden('Bad value for parameter modulepart');
218 }
219 
220 // Check security and set return info with full path of file
221 $check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, $user, $refname);
222 $accessallowed = $check_access['accessallowed'];
223 $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
224 $fullpath_original_file = $check_access['original_file']; // $fullpath_original_file is now a full path name
225 //var_dump($fullpath_original_file.' '.$original_file.' '.$refname.' '.$accessallowed);exit;
226 
227 if (!empty($hashp)) {
228  $accessallowed = 1; // When using hashp, link is public so we force $accessallowed
229  $sqlprotectagainstexternals = '';
230 } else {
231  // Basic protection (against external users only)
232  if ($user->socid > 0) {
233  if ($sqlprotectagainstexternals) {
234  $resql = $db->query($sqlprotectagainstexternals);
235  if ($resql) {
236  $num = $db->num_rows($resql);
237  $i = 0;
238  while ($i < $num) {
239  $obj = $db->fetch_object($resql);
240  if ($user->socid != $obj->fk_soc) {
241  $accessallowed = 0;
242  break;
243  }
244  $i++;
245  }
246  }
247  }
248  }
249 }
250 
251 // Security:
252 // Limit access if permissions are wrong
253 if (!$accessallowed) {
254  accessforbidden();
255 }
256 
257 // Security:
258 // We refuse directory transversal change and pipes in file names
259 if (preg_match('/\.\./', $fullpath_original_file) || preg_match('/[<>|]/', $fullpath_original_file)) {
260  dol_syslog("Refused to deliver file ".$fullpath_original_file);
261  print "ErrorFileNameInvalid: ".dol_escape_htmltag($original_file);
262  exit;
263 }
264 
265 
266 clearstatcache();
267 
268 $filename = basename($fullpath_original_file);
269 $filename = preg_replace('/\.noexe$/i', '', $filename);
270 
271 // Output file on browser
272 dol_syslog("document.php download $fullpath_original_file filename=$filename content-type=$type");
273 $fullpath_original_file_osencoded = dol_osencode($fullpath_original_file); // New file name encoded in OS encoding charset
274 
275 // This test if file exists should be useless. We keep it to find bug more easily
276 if (!file_exists($fullpath_original_file_osencoded)) {
277  dol_syslog("ErrorFileDoesNotExists: ".$fullpath_original_file);
278  print "ErrorFileDoesNotExists: ".$original_file;
279  exit;
280 }
281 
282 // Hooks
283 $hookmanager->initHooks(array('document'));
284 $parameters = array('ecmfile' => $ecmfile, 'modulepart' => $modulepart, 'original_file' => $original_file,
285  'entity' => $entity, 'refname' => $refname, 'fullpath_original_file' => $fullpath_original_file,
286  'filename' => $filename, 'fullpath_original_file_osencoded' => $fullpath_original_file_osencoded);
287 $object = new stdClass();
288 $reshook = $hookmanager->executeHooks('downloadDocument', $parameters, $object, $action); // Note that $action and $object may have been
289 if ($reshook < 0) {
290  $errors = $hookmanager->error.(is_array($hookmanager->errors) ? (!empty($hookmanager->error) ? ', ' : '').join(', ', $hookmanager->errors) : '');
291  dol_syslog("document.php - Errors when executing the hook 'downloadDocument' : ".$errors);
292  print "ErrorDownloadDocumentHooks: ".$errors;
293  exit;
294 }
295 
296 // Permissions are ok and file found, so we return it
297 top_httphead($type);
298 header('Content-Description: File Transfer');
299 if ($encoding) {
300  header('Content-Encoding: '.$encoding);
301 }
302 // Add MIME Content-Disposition from RFC 2183 (inline=automatically displayed, attachment=need user action to open)
303 if ($attachment) {
304  header('Content-Disposition: attachment; filename="'.$filename.'"');
305 } else {
306  header('Content-Disposition: inline; filename="'.$filename.'"');
307 }
308 // Ajout directives pour resoudre bug IE
309 header('Cache-Control: Public, must-revalidate');
310 header('Pragma: public');
311 $readfile = true;
312 
313 // on view document, can output images with good orientation according to exif infos
314 if (!$attachment && !empty($conf->global->MAIN_USE_EXIF_ROTATION) && image_format_supported($fullpath_original_file_osencoded) == 1) {
315  $imgres = correctExifImageOrientation($fullpath_original_file_osencoded, null);
316  $readfile = !$imgres;
317 }
318 
319 if (is_object($db)) {
320  $db->close();
321 }
322 
323 // Send file now
324 if ($readfile) {
325  header('Content-Length: '.dol_filesize($fullpath_original_file));
326 
327  readfileLowMemory($fullpath_original_file_osencoded);
328 }
Class to manage ECM files.
if(!defined('NOTOKENRENEWAL')) if(!defined('NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined('NOREQUIREAJAX')) if(isset($_GET["hashp"]) &&!defined("NOLOGIN")) if((isset($_GET["modulepart"]) && $_GET["modulepart"]=='medias')) llxHeader()
Header empty.
Definition: document.php:82
llxFooter()
Footer empty.
Definition: document.php:91
dol_filesize($pathoffile)
Return size of a file.
Definition: files.lib.php:587
dol_check_secure_access_document($modulepart, $original_file, $entity, $fuser='', $refname='', $mode='read')
Security check when accessing to a document (used by document.php, viewimage.php and webservices to g...
Definition: files.lib.php:2543
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
readfileLowMemory($fullpath_original_file_osencoded, $method=-1)
Return a file on output using a low memory.
dolIsAllowedForPreview($file)
Return if a file is qualified for preview.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
correctExifImageOrientation($fileSource, $fileDest, $quality=95)
Add exif orientation correction for image.
Definition: images.lib.php:425
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
Definition: images.lib.php:80
if(!defined('NOREQUIREMENU')) if(!empty(GETPOST('seteventmessages', 'alpha'))) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
Definition: main.inc.php:1494
httponly_accessforbidden($message=1, $http_response_code=403, $stringalreadysanitized=0)
Show a message to say access is forbidden and stop program.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.