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