dolibarr 21.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 Frédéric France <frederic.france@free.fr>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <https://www.gnu.org/licenses/>.
23 * or see https://www.gnu.org/
24 */
25
35define('MAIN_SECURITY_FORCECSP', "default-src: 'none'");
36
37//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled cause need to load personalized language
38//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled cause need to load personalized language
39if (!defined('NOTOKENRENEWAL')) {
40 define('NOTOKENRENEWAL', '1');
41}
42if (!defined('NOREQUIREMENU')) {
43 define('NOREQUIREMENU', '1');
44}
45if (!defined('NOREQUIREHTML')) {
46 define('NOREQUIREHTML', '1');
47}
48if (!defined('NOREQUIREAJAX')) {
49 define('NOREQUIREAJAX', '1');
50}
51
52// For direct external download link, we don't need to load/check we are into a login session
53if (isset($_GET["hashp"]) && !defined("NOLOGIN")) {
54 if (!defined("NOLOGIN")) {
55 define("NOLOGIN", 1);
56 }
57 if (!defined("NOCSRFCHECK")) {
58 define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
59 }
60 if (!defined("NOIPCHECK")) {
61 define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip
62 }
63}
64// Some value of modulepart can be used to get resources that are public so no login are required.
65// Keep $_GET here, GETPOST is not available yet
66if ((isset($_GET["modulepart"]) && $_GET["modulepart"] == 'medias')) {
67 if (!defined("NOLOGIN")) {
68 define("NOLOGIN", 1);
69 }
70 if (!defined("NOCSRFCHECK")) {
71 define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
72 }
73 if (!defined("NOIPCHECK")) {
74 define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip
75 }
76}
77
98function llxHeader($head = '', $title = '', $help_url = '', $target = '', $disablejs = 0, $disablehead = 0, $arrayofjs = '', $arrayofcss = '', $morequerystring = '', $morecssonbody = '', $replacemainareaby = '', $disablenofollow = 0, $disablenoindex = 0)
99{
100}
107function llxFooter()
108{
109}
110
111require 'main.inc.php'; // Load $user and permissions
112require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
113require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
114
123$encoding = '';
124$action = GETPOST('action', 'aZ09');
125$original_file = GETPOST('file', 'alphanohtml');
126$hashp = GETPOST('hashp', 'aZ09');
127$modulepart = GETPOST('modulepart', 'alpha');
128$urlsource = GETPOST('urlsource', 'alpha');
129$entity = GETPOSTINT('entity', $conf->entity);
130
131// Security check
132if (empty($modulepart) && empty($hashp)) {
133 httponly_accessforbidden('Bad link. Bad value for parameter modulepart', 400);
134}
135if (empty($original_file) && empty($hashp)) {
136 httponly_accessforbidden('Bad link. Missing identification to find file (original_file or hashp)', 400);
137}
138if ($modulepart == 'fckeditor') {
139 $modulepart = 'medias'; // For backward compatibility
140}
141
142$socid = 0;
143if ($user->socid > 0) {
144 $socid = $user->socid;
145}
146
147// For some module part, dir may be privates
148if (in_array($modulepart, array('facture_paiement', 'unpaid'))) {
149 if (!$user->hasRight('societe', 'client', 'voir')) {
150 $original_file = 'private/'.$user->id.'/'.$original_file; // If user has no permission to see all, output dir is specific to user
151 }
152}
153
154
155/*
156 * Actions
157 */
158
159// None
160
161
162
163/*
164 * View
165 */
166
167// If we have a hash public (hashp), we guess the original_file.
168$ecmfile='';
169if (!empty($hashp)) {
170 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
171 $ecmfile = new EcmFiles($db);
172 $result = $ecmfile->fetch(0, '', '', '', $hashp);
173 if ($result > 0) {
174 $tmp = explode('/', $ecmfile->filepath, 2); // $ecmfile->filepath is relative to document directory
175 // filepath can be 'users/X' or 'X/propale/PR11111'
176 if (is_numeric($tmp[0])) { // If first tmp is numeric, it is subdir of company for multicompany, we take next part.
177 $tmp = explode('/', $tmp[1], 2);
178 }
179 $moduleparttocheck = $tmp[0]; // moduleparttocheck is first part of path
180
181 if ($modulepart) { // Not required, so often not defined, for link using public hashp parameter.
182 if ($moduleparttocheck == $modulepart) {
183 // We remove first level of directory
184 $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir
185 //var_dump($original_file); exit;
186 } else {
187 httponly_accessforbidden('Bad link. File is from another module part.', 403);
188 }
189 } else {
190 $modulepart = $moduleparttocheck;
191 $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir
192 }
193 $entity = $ecmfile->entity;
194 if ($entity != $conf->entity) {
195 $conf->entity = $entity;
196 $conf->setValues($db);
197 }
198 } else {
199 $langs->load("errors");
200 httponly_accessforbidden($langs->trans("ErrorFileNotFoundWithSharedLink"), 403, 1);
201 }
202}
203
204// Define attachment (attachment=true to force choice popup 'open'/'save as')
205$attachment = true;
206if (preg_match('/\.(html|htm)$/i', $original_file)) {
207 $attachment = false;
208}
209if (isset($_GET["attachment"])) {
210 $attachment = GETPOST("attachment", 'alpha') ?true:false;
211}
212if (getDolGlobalString('MAIN_DISABLE_FORCE_SAVEAS')) {
213 $attachment = false;
214}
215
216// Define mime type
217$type = 'application/octet-stream'; // By default
218if (GETPOST('type', 'alpha')) {
219 $type = GETPOST('type', 'alpha');
220} else {
221 $type = dol_mimetype($original_file);
222}
223// Security: Force to octet-stream if file is a dangerous file. For example when it is a .noexe file
224// We do not force if file is a javascript to be able to get js from website module with <script src="
225// Note: Force whatever is $modulepart seems ok.
226if (!in_array($type, array('text/x-javascript')) && !dolIsAllowedForPreview($original_file)) {
227 $type = 'application/octet-stream';
228}
229
230// Security: Delete string ../ or ..\ into $original_file
231$original_file = preg_replace('/\.\.+/', '..', $original_file); // Replace '... or more' with '..'
232$original_file = str_replace('../', '/', $original_file);
233$original_file = str_replace('..\\', '/', $original_file);
234
235
236// Security check
237if (empty($modulepart)) {
238 accessforbidden('Bad value for parameter modulepart');
239}
240
241// Check security and set return info with full path of file
242$check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, $user, '');
243$accessallowed = $check_access['accessallowed'];
244$sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
245$fullpath_original_file = $check_access['original_file']; // $fullpath_original_file is now a full path name
246//var_dump($modulepart.' '.$fullpath_original_file.' '.$original_file.' '.$accessallowed);exit;
247
248if (!empty($hashp)) {
249 $accessallowed = 1; // When using hashp, link is public so we force $accessallowed
250 $sqlprotectagainstexternals = '';
251} else {
252 // Basic protection (against external users only)
253 if ($user->socid > 0) {
254 if ($sqlprotectagainstexternals) {
255 $resql = $db->query($sqlprotectagainstexternals);
256 if ($resql) {
257 $num = $db->num_rows($resql);
258 $i = 0;
259 while ($i < $num) {
260 $obj = $db->fetch_object($resql);
261 if ($user->socid != $obj->fk_soc) {
262 $accessallowed = 0;
263 break;
264 }
265 $i++;
266 }
267 }
268 }
269 }
270}
271
272// Security:
273// Limit access if permissions are wrong
274if (!$accessallowed) {
276}
277
278// Security:
279// We refuse directory transversal change and pipes in file names
280if (preg_match('/\.\./', $fullpath_original_file) || preg_match('/[<>|]/', $fullpath_original_file)) {
281 dol_syslog("Refused to deliver file ".$fullpath_original_file);
282 print "ErrorFileNameInvalid: ".dol_escape_htmltag($original_file);
283 exit;
284}
285
286
287clearstatcache();
288
289$filename = basename($fullpath_original_file);
290$filename = preg_replace('/\.noexe$/i', '', $filename);
291
292// Output file on browser
293dol_syslog("document.php download $fullpath_original_file filename=$filename content-type=$type");
294$fullpath_original_file_osencoded = dol_osencode($fullpath_original_file); // New file name encoded in OS encoding charset
295
296// This test if file exists should be useless. We keep it to find bug more easily
297if (!file_exists($fullpath_original_file_osencoded)) {
298 dol_syslog("ErrorFileDoesNotExists: ".$fullpath_original_file);
299 print "ErrorFileDoesNotExists: ".dol_escape_htmltag($original_file);
300 exit;
301}
302
303// Hooks
304$hookmanager->initHooks(array('document'));
305$parameters = array('ecmfile' => $ecmfile, 'modulepart' => $modulepart, 'original_file' => $original_file,
306 'entity' => $entity, 'fullpath_original_file' => $fullpath_original_file,
307 'filename' => $filename, 'fullpath_original_file_osencoded' => $fullpath_original_file_osencoded);
308$object = new stdClass();
309$reshook = $hookmanager->executeHooks('downloadDocument', $parameters, $object, $action); // Note that $action and $object may have been
310if ($reshook < 0) {
311 $errors = $hookmanager->error.(is_array($hookmanager->errors) ? (!empty($hookmanager->error) ? ', ' : '').implode(', ', $hookmanager->errors) : '');
312 dol_syslog("document.php - Errors when executing the hook 'downloadDocument' : ".$errors);
313 print "ErrorDownloadDocumentHooks: ".$errors;
314 exit;
315}
316
317
318// Permissions are ok and file found, so we return it
319top_httphead($type);
320
321header('Content-Description: File Transfer');
322if ($encoding) {
323 header('Content-Encoding: '.$encoding);
324}
325// Add MIME Content-Disposition from RFC 2183 (inline=automatically displayed, attachment=need user action to open)
326
327if ($attachment) {
328 header('Content-Disposition: attachment; filename="'.$filename.'"');
329} else {
330 header('Content-Disposition: inline; filename="'.$filename.'"');
331}
332// Ajout directives pour resoudre bug IE
333header('Cache-Control: Public, must-revalidate');
334header('Pragma: public');
335$readfile = true;
336
337// on view document, can output images with good orientation according to exif infos
338// TODO Why this on document.php and not in viewimage.php ?
339if (!$attachment && getDolGlobalString('MAIN_USE_EXIF_ROTATION') && image_format_supported($fullpath_original_file_osencoded) == 1) {
340 $imgres = correctExifImageOrientation($fullpath_original_file_osencoded, null);
341 $readfile = !$imgres;
342}
343
344if (is_object($db)) {
345 $db->close();
346}
347
348// Send file now
349if ($readfile) {
350 header('Content-Length: '.dol_filesize($fullpath_original_file));
351
352 readfileLowMemory($fullpath_original_file_osencoded);
353}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:66
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:71
Class to manage ECM files.
llxFooter()
Footer empty.
Definition document.php:107
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.
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.
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.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
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.