dolibarr 23.0.3
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 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
10 * Copyright (C) 2025 MDW <mdeweerd@users.noreply.github.com>
11 *
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 3 of the License, or
15 * (at your option) any later version.
16 *
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program. If not, see <https://www.gnu.org/licenses/>.
24 * or see https://www.gnu.org/
25 */
26
36define('MAIN_SECURITY_FORCECSP', "default-src 'none'");
37
38//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled cause need to load personalized language
39//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled cause need to load personalized language
40if (!defined('NOTOKENRENEWAL')) {
41 define('NOTOKENRENEWAL', '1');
42}
43if (!defined('NOREQUIREMENU')) {
44 define('NOREQUIREMENU', '1');
45}
46if (!defined('NOREQUIREHTML')) {
47 define('NOREQUIREHTML', '1');
48}
49if (!defined('NOREQUIREAJAX')) {
50 define('NOREQUIREAJAX', '1');
51}
52
53// For direct external download link, we don't need to load/check we are into a login session
54if (isset($_GET["hashp"]) && !defined("NOLOGIN")) {
55 if (!defined("NOLOGIN")) {
56 define("NOLOGIN", 1);
57 }
58 if (!defined("NOCSRFCHECK")) {
59 define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
60 }
61 if (!defined("NOIPCHECK")) {
62 define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip
63 }
64}
65// Some value of modulepart can be used to get resources that are public so no login are required.
66// Keep $_GET here, GETPOST is not available yet
67if ((isset($_GET["modulepart"]) && $_GET["modulepart"] == 'medias')) {
68 if (!defined("NOLOGIN")) {
69 define("NOLOGIN", 1);
70 }
71 if (!defined("NOCSRFCHECK")) {
72 define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
73 }
74 if (!defined("NOIPCHECK")) {
75 define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip
76 }
77} elseif (isset($_GET["modulepart"]) && $_GET["modulepart"] == 'ticket' && strpos($_SERVER['HTTP_REFERER'], 'public/ticket') !== false) {
78 if (!defined("NOLOGIN")) {
79 define("NOLOGIN", 1);
80 }
81 if (!defined("NOCSRFCHECK")) {
82 define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
83 }
84 if (!defined("NOIPCHECK")) {
85 define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip
86 }
87}
88
112function llxHeader($head = '', $title = '', $help_url = '', $target = '', $disablejs = 0, $disablehead = 0, $arrayofjs = '', $arrayofcss = '', $morequerystring = '', $morecssonbody = '', $replacemainareaby = '', $disablenofollow = 0, $disablenoindex = 0)
113{
114}
127function llxFooter($comment = '', $zone = 'private', $disabledoutputofmessages = 0)
128{
129}
130
131require 'main.inc.php'; // Load $user and permissions
139require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
140require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
141
142$encoding = '';
143$action = GETPOST('action', 'aZ09');
144$original_file = GETPOST('file', 'alphanohtml');
145$hashp = GETPOST('hashp', 'aZ09');
146$modulepart = GETPOST('modulepart', 'alpha');
147$urlsource = GETPOST('urlsource', 'alpha');
148$entity = GETPOSTISSET('entity') ? GETPOSTINT('entity') : $conf->entity;
149
150// Security check
151if (empty($modulepart) && empty($hashp)) {
152 httponly_accessforbidden('Bad link. Bad value for parameter modulepart', 400);
153}
154if (empty($original_file) && empty($hashp)) {
155 httponly_accessforbidden('Bad link. Missing identification to find file (original_file or hashp)', 400);
156}
157if ($modulepart == 'fckeditor') {
158 $modulepart = 'medias'; // For backward compatibility
159}
160
161$socid = 0;
162if ($user->socid > 0) {
163 $socid = $user->socid;
164}
165
166// For some module part, dir may be privates
167if (in_array($modulepart, array('facture_paiement', 'unpaid'))) {
168 if (!$user->hasRight('societe', 'client', 'voir')) {
169 $original_file = 'private/'.$user->id.'/'.$original_file; // If user has no permission to see all, output dir is specific to user
170 }
171}
172
173
174/*
175 * Actions
176 */
177
178// None
179
180
181
182/*
183 * View
184 */
185
186// If we have a hash public (hashp), we guess the original_file.
187$ecmfile = '';
188if (!empty($hashp)) {
189 if (GETPOST('type', 'alpha')=='link') {
190 require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
191 $link = new Link($db);
192 $result = $link->fetch(0, $hashp);
193 if ($result > 0 && !empty($link->url)) {
194 header('Location: '.$link->url);
195 exit;
196 } else {
197 $langs->load("errors");
198 httponly_accessforbidden($langs->trans("ErrorLinkNotFoundWithSharedLink"), 403, 1);
199 }
200 } else {
201 include_once DOL_DOCUMENT_ROOT . '/ecm/class/ecmfiles.class.php';
202 $ecmfile = new EcmFiles($db);
203 $result = $ecmfile->fetch(0, '', '', '', $hashp);
204 if ($result > 0) {
205 $tmp = explode('/', $ecmfile->filepath, 2); // $ecmfile->filepath is relative to document directory
206 // filepath can be 'users/X' or 'X/propale/PR11111'
207 if (is_numeric($tmp[0])) { // If first tmp is numeric, it is subdir of company for multicompany, we take next part.
208 $tmp = explode('/', $tmp[1], 2);
209 }
210 $moduleparttocheck = $tmp[0]; // moduleparttocheck is first part of path
211
212 if ($modulepart) { // Not required, so often not defined, for link using public hashp parameter.
213 if ($moduleparttocheck == $modulepart) {
214 // We remove first level of directory
215 $original_file = (($tmp[1] ? $tmp[1] . '/' : '') . $ecmfile->filename); // this is relative to module dir
216 //var_dump($original_file); exit;
217 } else {
218 httponly_accessforbidden('Bad link. File is from another module part.', 403);
219 }
220 } else {
221 $modulepart = $moduleparttocheck;
222 $original_file = (($tmp[1] ? $tmp[1] . '/' : '') . $ecmfile->filename); // this is relative to module dir
223 }
224
225 $entity = $ecmfile->entity;
226 if (isModEnabled('multicompany') && !empty($ecmfile->src_object_type) && $ecmfile->src_object_id > 0) {
227 $object = fetchObjectByElement($ecmfile->src_object_id, $ecmfile->src_object_type);
228 if (is_object($object) && $object->id > 0) {
229 $entity = $object->entity;
230 }
231 }
232
233 if ($entity != $conf->entity) {
234 $conf->entity = $entity;
235 $conf->setValues($db);
236 }
237 } else {
238 $langs->load("errors");
239 httponly_accessforbidden($langs->trans("ErrorFileNotFoundWithSharedLink"), 403, 1);
240 }
241 }
242}
243
244// Define attachment (attachment=true to force choice popup 'open'/'save as')
245$attachment = true;
246if (preg_match('/\.(html|htm)$/i', $original_file)) {
247 $attachment = false;
248}
249if (isset($_GET["attachment"])) {
250 $attachment = GETPOST("attachment", 'alpha') ? true : false;
251}
252if (getDolGlobalString('MAIN_DISABLE_FORCE_SAVEAS')) {
253 $attachment = false;
254}
255
256// Define mime type
257$type = 'application/octet-stream'; // By default
258if (GETPOST('type', 'alpha')) {
259 $type = GETPOST('type', 'alpha');
260} else {
261 $type = dol_mimetype($original_file);
262}
263// Security: Force to octet-stream if file is a dangerous file. For example when it is a .noexe file
264// We do not force if file is a javascript to be able to get js from website module with <script src="
265// Note: Force whatever is $modulepart seems ok.
266if (!in_array($type, array('text/x-javascript')) && !dolIsAllowedForPreview($original_file)) {
267 $type = 'application/octet-stream';
268}
269
270// Security: Delete string ../ or ..\ into $original_file
271$original_file = preg_replace('/\.\.+/', '..', $original_file); // Replace '... or more' with '..'
272$original_file = str_replace('../', '/', $original_file);
273$original_file = str_replace('..\\', '/', $original_file);
274
275// Security check
276if (empty($modulepart)) {
277 accessforbidden('Bad value for parameter modulepart');
278}
279
280// Check security and set return info with full path of file
281$check_access = dol_check_secure_access_document($modulepart, $original_file, (int) $entity, $user, '', 'read');
282$accessallowed = $check_access['accessallowed'];
283$sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
284$fullpath_original_file = $check_access['original_file']; // $fullpath_original_file is now a full path name
285//var_dump($modulepart.' '.$entity.' '.$fullpath_original_file.' '.$original_file.' '.$accessallowed);exit;
286
287if (!empty($hashp)) {
288 $accessallowed = 1; // When using hashp, link is public so we force $accessallowed
289 $sqlprotectagainstexternals = '';
290} else {
291 // Basic protection (against external users only)
292 if ($user->socid > 0) {
293 if ($sqlprotectagainstexternals) {
294 $resql = $db->query($sqlprotectagainstexternals);
295 if ($resql) {
296 $num = $db->num_rows($resql);
297 $i = 0;
298 while ($i < $num) {
299 $obj = $db->fetch_object($resql);
300 if ($user->socid != $obj->fk_soc) {
301 $accessallowed = 0;
302 break;
303 }
304 $i++;
305 }
306 }
307 }
308 } elseif ($modulepart == 'ticket' && !getDolGlobalString('TICKET_EMAIL_MUST_EXISTS')) {
309 if ($sqlprotectagainstexternals) {
310 $resql = $db->query($sqlprotectagainstexternals);
311 if ($resql) {
312 $num = $db->num_rows($resql);
313 if ($num > 0) {
314 $accessallowed = 1;
315 }
316 }
317 }
318 }
319}
320
321// Security:
322// Limit access if permissions are wrong
323if (!$accessallowed) {
325}
326
327// Security:
328// We refuse directory transversal change and pipes in file names
329if (preg_match('/\.\./', $fullpath_original_file) || preg_match('/[<>|]/', $fullpath_original_file)) {
330 dol_syslog("Refused to deliver file ".$fullpath_original_file);
331 print "ErrorFileNameInvalid: ".dol_escape_htmltag($original_file);
332 exit;
333}
334
335
336clearstatcache();
337
338$filename = basename($fullpath_original_file);
339$filename = preg_replace('/\.noexe$/i', '', $filename);
340
341// Output file on browser
342dol_syslog("document.php download $fullpath_original_file filename=$filename content-type=$type");
343$fullpath_original_file_osencoded = dol_osencode($fullpath_original_file); // New file name encoded in OS encoding charset
344
345// This test if file exists should be useless. We keep it to find bug more easily
346if (!file_exists($fullpath_original_file_osencoded)) {
347 dol_syslog("ErrorFileDoesNotExists: ".$fullpath_original_file);
348 print $langs->trans("ErrorFileDoesNotExists") . ' : ' . dol_escape_htmltag($original_file);
349 exit;
350}
351
352// Hooks
353$hookmanager->initHooks(array('document'));
354$parameters = array('ecmfile' => $ecmfile, 'modulepart' => $modulepart, 'original_file' => $original_file,
355 'entity' => $entity, 'fullpath_original_file' => $fullpath_original_file,
356 'filename' => $filename, 'fullpath_original_file_osencoded' => $fullpath_original_file_osencoded);
357$object = new stdClass();
358$reshook = $hookmanager->executeHooks('downloadDocument', $parameters, $object, $action); // Note that $action and $object may have been
359if ($reshook < 0) {
360 $errors = $hookmanager->error.(is_array($hookmanager->errors) ? (!empty($hookmanager->error) ? ', ' : '').implode(', ', $hookmanager->errors) : '');
361 dol_syslog("document.php - Errors when executing the hook 'downloadDocument' : ".$errors);
362 print "ErrorDownloadDocumentHooks: ".$errors;
363 exit;
364}
365
366
367// Permissions are ok and file found, so we return it
368top_httphead($type);
369
370header('Content-Description: File Transfer');
371if ($encoding) {
372 header('Content-Encoding: '.$encoding);
373}
374// Add MIME Content-Disposition from RFC 2183 (inline=automatically displayed, attachment=need user action to open)
375
376if ($attachment) {
377 header('Content-Disposition: attachment; filename="'.$filename.'"');
378} else {
379 header('Content-Disposition: inline; filename="'.$filename.'"');
380}
381// Ajout directives pour resoudre bug IE
382header('Cache-Control: Public, must-revalidate');
383header('Pragma: public');
384$readfile = true;
385
386// on view document, can output images with good orientation according to exif infos
387// TODO Why this on document.php and not in viewimage.php ?
388if (!$attachment && getDolGlobalString('MAIN_USE_EXIF_ROTATION') && image_format_supported($fullpath_original_file_osencoded) == 1) {
389 $imgres = correctExifImageOrientation($fullpath_original_file_osencoded, null);
390 $readfile = !$imgres;
391}
392
393if (is_object($db)) {
394 $db->close();
395}
396
397// Send file now
398if ($readfile) {
399 header('Content-Length: '.dol_filesize($fullpath_original_file));
400
401 readfileLowMemory($fullpath_original_file_osencoded);
402}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
Class to manage ECM files.
dol_filesize($pathoffile)
Return size of a file.
dol_check_secure_access_document($modulepart, $original_file, $entity, $fuser=null, $refname='', $mode='read')
Security check when accessing to a document (used by document.php, viewimage.php and webservices to g...
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
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.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
correctExifImageOrientation($fileSource, $fileDest, $quality=95)
Add exif orientation correction for image.
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
if(!defined( 'NOREQUIREMENU')) if(!empty(GETPOST('seteventmessages', 'alpha'))) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
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.