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