dolibarr  13.0.2
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  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program. If not, see <https://www.gnu.org/licenses/>.
21  * or see https://www.gnu.org/
22  */
23 
33 //if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled cause need to load personalized language
34 //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled cause need to load personalized language
35 if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1');
36 if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1');
37 if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1');
38 if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1');
39 
40 // For direct external download link, we don't need to load/check we are into a login session
41 if (isset($_GET["hashp"]) && !defined("NOLOGIN"))
42 {
43  if (!defined("NOLOGIN")) define("NOLOGIN", 1);
44  if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
45  if (!defined("NOIPCHECK")) define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip
46 }
47 // Some value of modulepart can be used to get resources that are public so no login are required.
48 if ((isset($_GET["modulepart"]) && $_GET["modulepart"] == 'medias'))
49 {
50  if (!defined("NOLOGIN")) define("NOLOGIN", 1);
51  if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
52  if (!defined("NOIPCHECK")) define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip
53 }
54 
61 function llxHeader()
62 {
63 }
70 function llxFooter()
71 {
72 }
73 
74 require 'main.inc.php'; // Load $user and permissions
75 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
76 require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
77 
78 $encoding = '';
79 $action = GETPOST('action', 'aZ09');
80 $original_file = GETPOST('file', 'alphanohtml'); // Do not use urldecode here ($_GET are already decoded by PHP).
81 $hashp = GETPOST('hashp', 'aZ09');
82 $modulepart = GETPOST('modulepart', 'alpha');
83 $urlsource = GETPOST('urlsource', 'alpha');
84 $entity = GETPOST('entity', 'int') ?GETPOST('entity', 'int') : $conf->entity;
85 
86 // Security check
87 if (empty($modulepart) && empty($hashp)) accessforbidden('Bad link. Bad value for parameter modulepart', 0, 0, 1);
88 if (empty($original_file) && empty($hashp)) accessforbidden('Bad link. Missing identification to find file (original_file or hashp)', 0, 0, 1);
89 if ($modulepart == 'fckeditor') $modulepart = 'medias'; // For backward compatibility
90 
91 $socid = 0;
92 if ($user->socid > 0) $socid = $user->socid;
93 
94 // For some module part, dir may be privates
95 if (in_array($modulepart, array('facture_paiement', 'unpaid')))
96 {
97  if (!$user->rights->societe->client->voir || $socid) $original_file = 'private/'.$user->id.'/'.$original_file; // If user has no permission to see all, output dir is specific to user
98 }
99 
100 
101 /*
102  * Actions
103  */
104 
105 // None
106 
107 
108 
109 /*
110  * View
111  */
112 
113 // If we have a hash public (hashp), we guess the original_file.
114 if (!empty($hashp))
115 {
116  include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
117  $ecmfile = new EcmFiles($db);
118  $result = $ecmfile->fetch(0, '', '', '', $hashp);
119  if ($result > 0)
120  {
121  $tmp = explode('/', $ecmfile->filepath, 2); // $ecmfile->filepath is relative to document directory
122  // filepath can be 'users/X' or 'X/propale/PR11111'
123  if (is_numeric($tmp[0])) // If first tmp is numeric, it is subdir of company for multicompany, we take next part.
124  {
125  $tmp = explode('/', $tmp[1], 2);
126  }
127  $moduleparttocheck = $tmp[0]; // moduleparttocheck is first part of path
128 
129  if ($modulepart) // Not required, so often not defined, for link using public hashp parameter.
130  {
131  if ($moduleparttocheck == $modulepart)
132  {
133  // We remove first level of directory
134  $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir
135  //var_dump($original_file); exit;
136  } else {
137  accessforbidden('Bad link. File is from another module part.', 0, 0, 1);
138  }
139  } else {
140  $modulepart = $moduleparttocheck;
141  $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir
142  }
143  } else {
144  $langs->load("errors");
145  accessforbidden($langs->trans("ErrorFileNotFoundWithSharedLink"), 0, 0, 1);
146  }
147 }
148 
149 // Define attachment (attachment=true to force choice popup 'open'/'save as')
150 $attachment = true;
151 if (preg_match('/\.(html|htm)$/i', $original_file)) $attachment = false;
152 if (isset($_GET["attachment"])) $attachment = GETPOST("attachment", 'alpha') ?true:false;
153 if (!empty($conf->global->MAIN_DISABLE_FORCE_SAVEAS)) $attachment = false;
154 
155 // Define mime type
156 $type = 'application/octet-stream'; // By default
157 if (GETPOST('type', 'alpha')) $type = GETPOST('type', 'alpha');
158 else $type = dol_mimetype($original_file);
159 // Security: Force to octet-stream if file is a dangerous file. For example when it is a .noexe file
160 // We do not force if file is a javascript to be able to get js from website module with <script src="
161 // Note: Force whatever is $modulepart seems ok.
162 if (!in_array($type, array('text/x-javascript')) && !dolIsAllowedForPreview($original_file)) {
163  $type = 'application/octet-stream';
164 }
165 
166 // Security: Delete string ../ into $original_file
167 $original_file = str_replace("../", "/", $original_file);
168 
169 // Find the subdirectory name as the reference
170 $refname = basename(dirname($original_file)."/");
171 
172 // Security check
173 if (empty($modulepart)) accessforbidden('Bad value for parameter modulepart');
174 
175 // Check security and set return info with full path of file
176 $check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, $user, $refname);
177 $accessallowed = $check_access['accessallowed'];
178 $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
179 $fullpath_original_file = $check_access['original_file']; // $fullpath_original_file is now a full path name
180 //var_dump($fullpath_original_file);exit;
181 
182 if (!empty($hashp))
183 {
184  $accessallowed = 1; // When using hashp, link is public so we force $accessallowed
185  $sqlprotectagainstexternals = '';
186 } else {
187  // Basic protection (against external users only)
188  if ($user->socid > 0)
189  {
190  if ($sqlprotectagainstexternals)
191  {
192  $resql = $db->query($sqlprotectagainstexternals);
193  if ($resql)
194  {
195  $num = $db->num_rows($resql);
196  $i = 0;
197  while ($i < $num)
198  {
199  $obj = $db->fetch_object($resql);
200  if ($user->socid != $obj->fk_soc)
201  {
202  $accessallowed = 0;
203  break;
204  }
205  $i++;
206  }
207  }
208  }
209  }
210 }
211 
212 // Security:
213 // Limit access if permissions are wrong
214 if (!$accessallowed)
215 {
216  accessforbidden();
217 }
218 
219 // Security:
220 // We refuse directory transversal change and pipes in file names
221 if (preg_match('/\.\./', $fullpath_original_file) || preg_match('/[<>|]/', $fullpath_original_file))
222 {
223  dol_syslog("Refused to deliver file ".$fullpath_original_file);
224  print "ErrorFileNameInvalid: ".dol_escape_htmltag($original_file);
225  exit;
226 }
227 
228 
229 clearstatcache();
230 
231 $filename = basename($fullpath_original_file);
232 $filename = preg_replace('/\.noexe$/i', '', $filename);
233 
234 // Output file on browser
235 dol_syslog("document.php download $fullpath_original_file filename=$filename content-type=$type");
236 $fullpath_original_file_osencoded = dol_osencode($fullpath_original_file); // New file name encoded in OS encoding charset
237 
238 // This test if file exists should be useless. We keep it to find bug more easily
239 if (!file_exists($fullpath_original_file_osencoded))
240 {
241  dol_syslog("ErrorFileDoesNotExists: ".$fullpath_original_file);
242  print "ErrorFileDoesNotExists: ".$original_file;
243  exit;
244 }
245 
246 // Hooks
247 if (!is_object($hookmanager)) {
248  include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
249  $hookmanager = new HookManager($this->db);
250 }
251 $hookmanager->initHooks(array('document'));
252 $parameters = array('ecmfile' => $ecmfile, 'modulepart' => $modulepart, 'original_file' => $original_file,
253  'entity' => $entity, 'refname' => $refname, 'fullpath_original_file' => $fullpath_original_file,
254  'filename' => $filename, 'fullpath_original_file_osencoded' => $fullpath_original_file_osencoded);
255 $reshook = $hookmanager->executeHooks('downloadDocument', $parameters); // Note that $action and $object may have been
256 if ($reshook < 0) {
257  $errors = $hookmanager->error.(is_array($hookmanager->errors) ? (!empty($hookmanager->error) ? ', ' : '').join($separator, $hookmanager->errors) : '');
258  dol_syslog("document.php - Errors when executing the hook 'downloadDocument' : ".$errors);
259  print "ErrorDownloadDocumentHooks: ".$errors;
260  exit;
261 }
262 
263 // Permissions are ok and file found, so we return it
264 top_httphead($type);
265 header('Content-Description: File Transfer');
266 if ($encoding) header('Content-Encoding: '.$encoding);
267 // Add MIME Content-Disposition from RFC 2183 (inline=automatically displayed, attachment=need user action to open)
268 if ($attachment) header('Content-Disposition: attachment; filename="'.$filename.'"');
269 else header('Content-Disposition: inline; filename="'.$filename.'"');
270 // Ajout directives pour resoudre bug IE
271 header('Cache-Control: Public, must-revalidate');
272 header('Pragma: public');
273 $readfile = true;
274 
275 // on view document, can output images with good orientation according to exif infos
276 if (!$attachment && !empty($conf->global->MAIN_USE_EXIF_ROTATION) && image_format_supported($fullpath_original_file_osencoded) == 1) {
277  $imgres = correctExifImageOrientation($fullpath_original_file_osencoded, null);
278  $readfile = !$imgres;
279 }
280 
281 if (is_object($db)) $db->close();
282 
283 // Send file now
284 if ($readfile) {
285  header('Content-Length: '.dol_filesize($fullpath_original_file));
286 
287  readfileLowMemory($fullpath_original_file_osencoded);
288 }
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.
dolIsAllowedForPreview($file)
Return if a file is qualified for preview.
correctExifImageOrientation($fileSource, $fileDest, $quality=95)
Add exif orientation correction for image.
Definition: images.lib.php:339
dol_filesize($pathoffile)
Return size of a file.
Definition: files.lib.php:555
$conf db
API class for accounts.
Definition: inc.php:54
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
Definition: images.lib.php:39
if(!defined('NOREQUIREMENU')) if(!function_exists("llxHeader")) top_httphead($contenttype= 'text/html', $forcenocache=0)
Show HTTP header.
Definition: main.inc.php:1214
llxHeader()
Empty header.
Definition: wrapper.php:45
Class to manage hooks.
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) ...
Definition: files.lib.php:2230
dol_mimetype($file, $default= 'application/octet-stream', $mode=0)
Return mime type of a file.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
readfileLowMemory($fullpath_original_file_osencoded, $method=-1)
Return a file on output using a low memory.
accessforbidden($message= '', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program Calling this function terminate execution ...
print
Draft customers invoices.
Definition: index.php:89
if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) if(!empty($conf->don->enabled)&&$user->rights->don->lire) if(!empty($conf->tax->enabled)&&$user->rights->tax->charges->lire) if(!empty($conf->facture->enabled)&&!empty($conf->commande->enabled)&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
Definition: index.php:1232
llxFooter()
Empty footer.
Definition: wrapper.php:59
Class to manage ECM files.