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