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