dolibarr 24.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-2026 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'; form-action 'none'; frame-ancestors 'self'");
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$needlogin = 1;
54// For direct external download link, we don't need to load/check we are into a login session
55if (isset($_GET["hashp"]) && !defined("NOLOGIN")) {
56 $needlogin = 0;
57 if (!defined("NOLOGIN")) {
58 define("NOLOGIN", 1);
59 }
60 if (!defined("NOCSRFCHECK")) {
61 define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
62 }
63 if (!defined("NOIPCHECK")) {
64 define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip
65 }
66}
67// Some value of modulepart can be used to get resources that are public so no login are required.
68// Keep $_GET here, GETPOST is not available yet
69if ((isset($_GET["modulepart"]) && $_GET["modulepart"] == 'medias')) {
70 $needlogin = 0;
71 if (!defined("NOLOGIN")) {
72 define("NOLOGIN", 1);
73 }
74 if (!defined("NOCSRFCHECK")) {
75 define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
76 }
77 if (!defined("NOIPCHECK")) {
78 define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip
79 }
80}
81
82// For MultiCompany modules, if an entity is set in query parameters (required to point an object because a ref can exists
83// in 2 entities), then if user is not already into a session, the user must be loaded on this entity, so permission will
84// be the one of this entity.
85// Do not use GETPOST here, function is not defined and define must be done before including main.inc.php
86$entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 0));
87if ($entity > 0) {
88 // An entity was forced on param, so we force the constant to allow master.inc.php to use this entity if not already logged.
89 // It has no effect if already logged.
90 define("DOLENTITY", $entity);
91}
92
116function llxHeader($head = '', $title = '', $help_url = '', $target = '', $disablejs = 0, $disablehead = 0, $arrayofjs = '', $arrayofcss = '', $morequerystring = '', $morecssonbody = '', $replacemainareaby = '', $disablenofollow = 0, $disablenoindex = 0)
117{
118}
131function llxFooter($comment = '', $zone = 'private', $disabledoutputofmessages = 0)
132{
133}
134
135require 'main.inc.php'; // Load $user and permissions
143require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
144require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
145
146$encoding = '';
147$action = GETPOST('action', 'aZ09');
148$original_file = GETPOST('file', 'alphanohtml');
149$hashp = GETPOST('hashp', 'aZ09');
150$modulepart = GETPOST('modulepart', 'alpha');
151$urlsource = GETPOST('urlsource', 'alpha');
152$entity = ($entity > 0 ? $entity : $conf->entity);
153
154// Security check
155if (empty($modulepart) && empty($hashp)) {
156 httponly_accessforbidden('Bad link. Bad value for parameter modulepart', 400);
157}
158if (empty($original_file) && empty($hashp)) {
159 httponly_accessforbidden('Bad link. Missing identification to find file (original_file or hashp)', 400);
160}
161if ($hashp == 'shared') {
162 httponly_accessforbidden('Bad link. Bad value for parameter hashp', 400);
163}
164if ($modulepart == 'fckeditor') {
165 $modulepart = 'medias'; // For backward compatibility
166}
167
168$socid = 0;
169if ($user->socid > 0) {
170 $socid = $user->socid;
171}
172
173// For some module part, dir may be privates
174if (in_array($modulepart, array('facture_paiement', 'unpaid'))) {
175 if (!$user->hasRight('societe', 'client', 'voir')) {
176 $original_file = 'private/'.$user->id.'/'.$original_file; // If user has no permission to see all, output dir is specific to user
177 }
178}
179
180
181/*
182 * Actions
183 */
184
185// None
186
187
188
189/*
190 * View
191 */
192
193// If we have a hash public (hashp), we guess the original_file.
194$ecmfile = '';
195if (!empty($hashp) && $hashp != 'shared') {
196 if (GETPOST('type', 'alpha') == 'link') {
197 // If we request a link
198 require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
199 $link = new Link($db);
200 $result = $link->fetch(0, $hashp);
201 if ($result > 0 && !empty($link->url)) {
202 if (preg_match('/^(http|dav)/', $link->url)) {
203 header('Location: '.$link->url); // Return the shared link we found in db
204 exit;
205 }
206 } else {
207 $langs->load("errors");
208 httponly_accessforbidden($langs->trans("ErrorLinkNotFoundWithSharedLink"), 403, 1);
209 }
210 } else {
211 // If we request a file
212 include_once DOL_DOCUMENT_ROOT . '/ecm/class/ecmfiles.class.php';
213 $ecmfile = new EcmFiles($db);
214 $result = $ecmfile->fetch(0, '', '', '', $hashp);
215 if ($result > 0) {
216 $tmp = explode('/', $ecmfile->filepath, 2); // $ecmfile->filepath is relative to document directory
217 // filepath can be 'users/X' or 'X/propale/PR11111'
218 if (is_numeric($tmp[0])) { // If first tmp is numeric, it is subdir of company for multicompany, we take next part.
219 $tmp = explode('/', $tmp[1], 2);
220 }
221 $moduleparttocheck = $tmp[0]; // moduleparttocheck is first part of path
222
223 if ($modulepart) { // Not required, so often not defined, for link using public hashp parameter.
224 if ($moduleparttocheck == $modulepart) {
225 // We remove first level of directory
226 $original_file = (($tmp[1] ? $tmp[1] . '/' : '') . $ecmfile->filename); // this is relative to module dir
227 //var_dump($original_file); exit;
228 } else {
229 httponly_accessforbidden('Bad entry found. File has a path from another module part.', 403);
230 }
231 } else {
232 $modulepart = $moduleparttocheck;
233 $original_file = (($tmp[1] ? $tmp[1] . '/' : '') . $ecmfile->filename); // this is relative to module dir
234 }
235
236 $entity = $ecmfile->entity;
237 if (isModEnabled('multicompany') && !empty($ecmfile->src_object_type) && $ecmfile->src_object_id > 0) {
238 $object = fetchObjectByElement($ecmfile->src_object_id, $ecmfile->src_object_type);
239 if (is_object($object) && $object->id > 0) {
240 $entity = $object->entity;
241 }
242 }
243
244 if ($entity != $conf->entity) {
245 $conf->entity = $entity;
246 $conf->setValues($db);
247 // Multicompany: Here we are switching entity and later we will check the requested object is in this entity but may be that user is not allowed to log/see entity
248 // but we don't mind, we are using the public hash to get file.
249 }
250 } else {
251 $langs->load("errors");
252 httponly_accessforbidden($langs->trans("ErrorFileNotFoundWithSharedLink"), 403, 1);
253 }
254 }
255}
256
257// Define attachment (attachment=true to force choice popup 'open'/'save as')
258$attachment = true;
259if (preg_match('/\.(html|htm)$/i', $original_file)) {
260 $attachment = false;
261}
262if (isset($_GET["attachment"])) {
263 $attachment = GETPOST("attachment", 'alpha') ? true : false;
264}
265if (getDolGlobalString('MAIN_DISABLE_FORCE_SAVEAS')) {
266 $attachment = false;
267}
268
269// Define mime type
270$type = 'application/octet-stream'; // By default
271if (GETPOST('type', 'alpha')) {
272 $type = GETPOST('type', 'alpha');
273} else {
274 $type = dol_mimetype($original_file);
275}
276// Security: Force to octet-stream if file is a dangerous file. For example when it is a .noexe file
277// We do not force if file is a javascript to be able to get js from website module with <script src="
278// Note: Force whatever is $modulepart seems ok.
279if (!in_array($type, array('text/x-javascript')) && !dolIsAllowedForPreview($original_file)) {
280 $type = 'application/octet-stream';
281}
282
283// Security: Delete string ../ or ..\ into $original_file
284$original_file = preg_replace('/\.\.+/', '..', $original_file); // Replace '... or more' with '..'
285$original_file = str_replace('../', '/', $original_file);
286$original_file = str_replace('..\\', '/', $original_file);
287
288// Security check
289if (empty($modulepart)) {
290 accessforbidden('Bad value for parameter modulepart');
291}
292
293// Check security and set return info with full path of file
294$hookmanager->initHooks(array('document'));
295$check_access = dol_check_secure_access_document($modulepart, $original_file, (int) $entity, $user, '', 'read');
296$accessallowed = $check_access['accessallowed'];
297$sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
298$fullpath_original_file = $check_access['original_file']; // $fullpath_original_file is now a full path name
299//var_dump($modulepart.' '.$entity.' '.$fullpath_original_file.' '.$original_file.' '.$accessallowed);exit;
300
301if (!empty($hashp) && $hashp != 'shared') {
302 $accessallowed = 1; // When using hashp, link is public so we force $accessallowed
303 $sqlprotectagainstexternals = '';
304} else {
305 // Basic protection (against external users only)
306 if ($user->socid > 0) {
307 if ($sqlprotectagainstexternals) {
308 $resql = $db->query($sqlprotectagainstexternals);
309 if ($resql) {
310 $num = $db->num_rows($resql);
311 $i = 0;
312 while ($i < $num) {
313 $obj = $db->fetch_object($resql);
314 if ($user->socid != $obj->fk_soc) {
315 $accessallowed = 0;
316 break;
317 }
318 $i++;
319 }
320 }
321 }
322 } /*
323 TODO Why this else ? Which use case does it cover ?
324 TICKET_EMAIL_MUST_EXISTS means a visitor can create a ticket from public interface even if email does not exists yet as a contact.
325 Public interface means no login and unknown user (ticket are found by email submiter / id).
326 Disabled as this looks a security bypass
327 elseif ($modulepart == 'ticket' && !getDolGlobalString('TICKET_EMAIL_MUST_EXISTS')) {
328 if ($sqlprotectagainstexternals) {
329 $resql = $db->query($sqlprotectagainstexternals);
330 if ($resql) {
331 $num = $db->num_rows($resql);
332 if ($num > 0) {
333 $accessallowed = 1;
334 }
335 }
336 }
337 }
338 */
339}
340
341// Check permission on per object basis
342if ($accessallowed && (empty($hashp) || $hashp == 'shared') && $needlogin) {
343 // If $modulepart is not an object type (userphoto, companylogo, memberphoto, apercuxxx, systemtools...), there is no object to check
344 // a permission on: we keep the result of dol_check_secure_access_document(), that has checked the permission for this modulepart.
345 $accessallowed = checkUserAccessToDocumentObject($user, $modulepart, $original_file, 'read');
346}
347
348// Security:
349// Limit access if permissions are wrong
350if (!$accessallowed) {
352}
353
354// Security:
355// We refuse directory transversal change and pipes in file names
356if (preg_match('/\.\./', $fullpath_original_file) || preg_match('/[<>|]/', $fullpath_original_file)) {
357 dol_syslog("Refused to deliver file ".$fullpath_original_file);
358 print "ErrorFileNameInvalid: ".dol_escape_htmltag($original_file);
359 exit;
360}
361
362
363clearstatcache();
364
365$filename = basename($fullpath_original_file);
366$filename = preg_replace('/\.noexe$/i', '', $filename);
367
368// Output file on browser
369dol_syslog("document.php download $fullpath_original_file filename=$filename content-type=$type");
370$fullpath_original_file_osencoded = dol_osencode($fullpath_original_file); // New file name encoded in OS encoding charset
371
372// This test if file exists should be useless. We keep it to find bug more easily
373if (!file_exists($fullpath_original_file_osencoded)) {
374 dol_syslog("ErrorFileDoesNotExists: ".$fullpath_original_file);
375 print $langs->trans("ErrorFileDoesNotExists") . ' : ' . dol_escape_htmltag($original_file);
376 exit;
377}
378
379// Hooks
380$parameters = array('ecmfile' => $ecmfile, 'modulepart' => $modulepart, 'original_file' => $original_file,
381 'entity' => $entity, 'fullpath_original_file' => $fullpath_original_file,
382 'filename' => $filename, 'fullpath_original_file_osencoded' => $fullpath_original_file_osencoded);
383$object = new stdClass();
384$reshook = $hookmanager->executeHooks('downloadDocument', $parameters, $object, $action); // Note that $action and $object may have been
385if ($reshook < 0) {
386 $errors = $hookmanager->error.(is_array($hookmanager->errors) ? (!empty($hookmanager->error) ? ', ' : '').implode(', ', $hookmanager->errors) : '');
387 dol_syslog("document.php - Errors when executing the hook 'downloadDocument' : ".$errors);
388 print "ErrorDownloadDocumentHooks: ".$errors;
389 exit;
390}
391
392// Set this for test
393//$type = 'text/html'; $attachment = -1;
394
395
396// If we show an invoice, we test if we must regenerate the PDF
397if ($modulepart == 'facture') {
398 $refname = basename(dirname($original_file)."/");
399 if ($refname == 'thumbs' || $refname == 'temp') {
400 // If we get the thumbs directory, we must go one step higher. For example original_file='10/thumbs/myfile_small.jpg' -> refname='10'
401 $refname = basename(dirname(dirname($original_file))."/");
402 }
403
404 $invoice = fetchObjectByElement(0, $modulepart, $refname);
405
406 if ($original_file == preg_replace('/facture\//', '', $invoice->last_main_doc)) {
407 // We are on the download or print of the main document
408 if ($invoice instanceOf Facture && $invoice->status > Facture::STATUS_DRAFT) {
409 $action = 'DOC_DOWNLOAD';
410 if (GETPOSTISSET('attachement') || GETPOST('preview')) {
411 $action = 'DOC_PREVIEW';
412 }
413
414 dol_syslog("Print for action=".$action.". Current counter of this non draft invoice is already ".$invoice->id.", so file was already printed, so we regenerate the PDF to add mention DUPLICATA", LOG_DEBUG);
415
416 // $object->pos_print_counter is current value. We increase it here.
417 if ($invoice->status == Facture::STATUS_CLOSED) {
418 // Increase counter by 1
419 $sql = "UPDATE ".MAIN_DB_PREFIX."facture SET pos_print_counter = pos_print_counter + 1";
420 $sql .= " WHERE rowid = ".((int) $invoice->id);
421 $db->query($sql);
422
423 $invoice->pos_print_counter += 1;
424 //$invoice->update($user, 1); // disabled update, we already did a direct sql update before. We disable trigger here because we already call the trigger $action = DOC_PREVIEW or DOC_DOWNLOAD just after.
425 }
426
427 // When we reach the second print, we must regenerate the document to have the mention duplicata on PDF)
428 // No need if we are at print 3, 4 or more. The PDF was regenerated when counter was 2,
429 if ($invoice->pos_print_counter == 2) {
430 $outputlangs = new Translate('', $conf);
431 $outputlangs->setDefaultLang(GETPOST('lang'));
432 $outputlangs->loadLangs(array("admin", "blockedlog"));
433
434 $hidedetails = 0;
435 $hidedesc = 0;
436 $hideref = 0;
437 $moreparams = '';
438 $hidedetails = isset($hidedetails) ? $hidedetails : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0); // @phpstan-ignore-line as variable $hidedetails is forced
439 $hidedesc = isset($hidedesc) ? $hidedesc : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0); // @phpstan-ignore-line as variable $hidedesc is forced
440 $hideref = isset($hideref) ? $hideref : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0); // @phpstan-ignore-line as variable $hideref is forced
441 $moreparams = isset($moreparams) ? $moreparams : null; // @phpstan-ignore-line as variable $moreparams is forced
442
443 $result = $invoice->generateDocument($invoice->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
444 if ($result < 0) {
445 dol_syslog("Failed to regenerate PDF", LOG_WARNING);
446 }
447 }
448
449 // Call trigger
450 $result = $invoice->call_trigger($action, $user);
451 if ($result < 0) {
452 top_httphead();
453
454 http_response_code(500);
455 print 'Error in trigger: '.$invoice->errorsToString();
456 exit;
457 }
458 }
459 }
460}
461
462
463
464// Permissions are ok and file found, so we return it
465top_httphead($type);
466
467header('Content-Description: File Transfer');
468if ($encoding) {
469 header('Content-Encoding: '.$encoding);
470}
471// Add MIME Content-Disposition from RFC 2183 (inline=automatically displayed, attachment=need user action to open)
472
473if ($attachment > 0) {
474 header('Content-Disposition: attachment; filename="'.$filename.'"');
475} elseif (empty($attachment)) {
476 header('Content-Disposition: inline; filename="'.$filename.'"');
477}
478// Ajout directives pour resoudre bug IE
479header('Cache-Control: Public, must-revalidate');
480header('Pragma: public');
481$readfile = true;
482
483// on view document, can output images with good orientation according to exif infos
484// TODO Why this on document.php and not in viewimage.php ?
485if (!$attachment && getDolGlobalString('MAIN_USE_EXIF_ROTATION') && image_format_supported($fullpath_original_file_osencoded) == 1) {
486 $imgres = correctExifImageOrientation($fullpath_original_file_osencoded, null);
487 $readfile = !$imgres;
488}
489
490if (is_object($db)) {
491 $db->close();
492}
493
494// Send file now
495if ($readfile) {
496 header('Content-Length: '.dol_filesize($fullpath_original_file));
497
498 readfileLowMemory($fullpath_original_file_osencoded);
499}
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.
Class to manage invoices.
const STATUS_DRAFT
Draft status.
const STATUS_CLOSED
Classified paid.
Class to manage translations.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
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.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=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.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
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.
checkUserAccessToDocumentObject(User $user, $modulepart, $original_file, $mode='read')
Check that a user can access the object a document is attached to.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.