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