dolibarr  20.0.0-beta
viewimage.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2004-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2005-2016 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2005-2016 Regis Houssin <regis.houssin@inodbox.com>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program. If not, see <https://www.gnu.org/licenses/>.
18  * or see https://www.gnu.org/
19  */
20 
29 define('MAIN_SECURITY_FORCECSP', "default-src: 'none'");
30 
31 //if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled cause need to load personalized language
32 //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled cause need to load personalized language
33 if (!defined('NOREQUIRESOC')) {
34  define('NOREQUIRESOC', '1');
35 }
36 if (!defined('NOREQUIRETRAN')) {
37  define('NOREQUIRETRAN', '1');
38 }
39 if (!defined('NOCSRFCHECK')) {
40  define('NOCSRFCHECK', '1');
41 }
42 if (!defined('NOTOKENRENEWAL')) {
43  define('NOTOKENRENEWAL', '1');
44 }
45 if (!defined('NOREQUIREMENU')) {
46  define('NOREQUIREMENU', '1');
47 }
48 if (!defined('NOREQUIREHTML')) {
49  define('NOREQUIREHTML', '1');
50 }
51 if (!defined('NOREQUIREAJAX')) {
52  define('NOREQUIREAJAX', '1');
53 }
54 
55 // Some value of modulepart can be used to get resources that are public so no login are required.
56 // Note that only directory logo is free to access without login.
57 $needlogin = 1;
58 // Keep $_GET here, GETPOST is not available yet
59 if (isset($_GET["modulepart"])) {
60  // Some value of modulepart can be used to get resources that are public so no login are required.
61 
62  // For logo of company
63  if ($_GET["modulepart"] == 'mycompany' && preg_match('/^\/?logos\//', $_GET['file'])) {
64  $needlogin = 0;
65  }
66  // For barcode live generation
67  if ($_GET["modulepart"] == 'barcode') {
68  $needlogin = 0;
69  }
70  // Medias files
71  if ($_GET["modulepart"] == 'medias') {
72  $needlogin = 0;
73  }
74  // Common files (files into /public/theme/common)
75  if ($_GET["modulepart"] == 'common') {
76  $needlogin = 0;
77  }
78  // User photo when user has made its profile public (for virtual credi card)
79  if ($_GET["modulepart"] == 'userphotopublic') {
80  $needlogin = 0;
81  }
82  // Used by TakePOS Auto Order
83  if ($_GET["modulepart"] == 'product' && isset($_GET["publictakepos"])) {
84  $needlogin = 0;
85  }
86 }
87 // For direct external download link, we don't need to load/check we are into a login session
88 if (isset($_GET["hashp"])) {
89  $needlogin = 0;
90 }
91 // If nologin required
92 if (!$needlogin) {
93  if (!defined("NOLOGIN")) {
94  define("NOLOGIN", 1);
95  }
96  if (!defined("NOCSRFCHECK")) {
97  define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
98  }
99  if (!defined("NOIPCHECK")) {
100  define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip
101  }
102 }
103 
104 // For MultiCompany module.
105 // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php
106 // Because 2 entities can have the same ref.
107 $entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1));
108 if (is_numeric($entity)) {
109  define("DOLENTITY", $entity);
110 }
111 
118 function llxHeader()
119 {
120 }
127 function llxFooter()
128 {
129 }
130 
131 require 'main.inc.php'; // Load $user and permissions
132 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
133 
134 $action = GETPOST('action', 'aZ09');
135 $original_file = GETPOST('file', 'alphanohtml');
136 $hashp = GETPOST('hashp', 'aZ09', 1);
137 $modulepart = GETPOST('modulepart', 'alpha', 1);
138 $urlsource = GETPOST('urlsource', 'alpha');
139 $entity = (GETPOSTINT('entity') ? GETPOSTINT('entity') : $conf->entity);
140 
141 // Security check
142 if (empty($modulepart) && empty($hashp)) {
143  httponly_accessforbidden('Bad link. Bad value for parameter modulepart', 400);
144 }
145 if (empty($original_file) && empty($hashp) && $modulepart != 'barcode') {
146  httponly_accessforbidden('Bad link. Missing identification to find file (param file or hashp)', 400);
147 }
148 if ($modulepart == 'fckeditor') {
149  $modulepart = 'medias'; // For backward compatibility
150 }
151 
152 
153 /*
154  * Actions
155  */
156 
157 // None
158 
159 
160 
161 /*
162  * View
163  */
164 
165 if (GETPOST("cache", 'alpha')) {
166  // Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access.
167  // Add param cache=abcdef
168  if (empty($dolibarr_nocache)) {
169  header('Cache-Control: max-age=3600, public, must-revalidate');
170  header('Pragma: cache'); // This is to avoid to have Pragma: no-cache set by proxy or web server
171  header('Expires: '.gmdate('D, d M Y H:i:s', time() + 3600).' GMT'); // This is to avoid to have Expires set by proxy or web server
172  //header('Expires: '.strtotime('+1 hour');
173  } else {
174  header('Cache-Control: no-cache');
175  }
176  //print $dolibarr_nocache; exit;
177 }
178 
179 // If we have a hash public (hashp), we guess the original_file.
180 if (!empty($hashp)) {
181  include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
182  $ecmfile = new EcmFiles($db);
183  $result = $ecmfile->fetch(0, '', '', '', $hashp);
184  if ($result > 0) {
185  $tmp = explode('/', $ecmfile->filepath, 2); // $ecmfile->filepath is relative to document directory
186  // filepath can be 'users/X' or 'X/propale/PR11111'
187  if (is_numeric($tmp[0])) { // If first tmp is numeric, it is subdir of company for multicompany, we take next part.
188  $tmp = explode('/', $tmp[1], 2);
189  }
190  $moduleparttocheck = $tmp[0]; // moduleparttocheck is first part of path
191 
192  if ($modulepart) { // Not required, so often not defined, for link using public hashp parameter.
193  if ($moduleparttocheck == $modulepart) {
194  // We remove first level of directory
195  $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir
196  //var_dump($original_file); exit;
197  } else {
198  httponly_accessforbidden('Bad link. File is from another module part.', 403);
199  }
200  } else {
201  $modulepart = $moduleparttocheck;
202  $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir
203  }
204  } else {
205  httponly_accessforbidden("ErrorFileNotFoundWithSharedLink", 403, 1);
206  }
207 }
208 
209 // Define mime type
210 $type = 'application/octet-stream';
211 if (GETPOST('type', 'alpha')) {
212  $type = GETPOST('type', 'alpha');
213 } else {
214  $type = dol_mimetype($original_file);
215 }
216 
217 // Security: This wrapper is for images. We do not allow type/html
218 if (preg_match('/html/i', $type)) {
219  httponly_accessforbidden('Error: Using the image wrapper to output a file with a mime type HTML is not possible.');
220 }
221 // Security: This wrapper is for images. We do not allow files ending with .noexe
222 if (preg_match('/\.noexe$/i', $original_file)) {
223  httponly_accessforbidden('Error: Using the image wrapper to output a file ending with .noexe is not allowed.');
224 }
225 
226 // Security: Delete string ../ or ..\ into $original_file
227 $original_file = preg_replace('/\.\.+/', '..', $original_file); // Replace '... or more' with '..'
228 $original_file = str_replace('../', '/', $original_file);
229 $original_file = str_replace('..\\', '/', $original_file);
230 
231 // Find the subdirectory name as the reference
232 $refname = basename(dirname($original_file)."/");
233 if ($refname == 'thumbs') {
234  // If we get the thumbs directory, we must go one step higher. For example original_file='10/thumbs/myfile_small.jpg' -> refname='10'
235  $refname = basename(dirname(dirname($original_file))."/");
236 }
237 
238 // Check that file is allowed for view with viewimage.php
239 if (!empty($original_file) && !dolIsAllowedForPreview($original_file)) {
240  httponly_accessforbidden('This file extension is not qualified for preview', 403);
241 }
242 
243 // Security check
244 if (empty($modulepart)) {
245  httponly_accessforbidden('Bad value for parameter modulepart', 400);
246 }
247 
248 // When logged in a different entity, medias cannot be accessed because $conf->$module->multidir_output
249 // is not set on the requested entity, but they are public documents, so reset entity
250 if ($modulepart === 'medias' && $entity != $conf->entity) {
251  $conf->entity = $entity;
252  $conf->setValues($db);
253 }
254 
255 $check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, $user, $refname);
256 $accessallowed = $check_access['accessallowed'];
257 $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
258 $fullpath_original_file = $check_access['original_file']; // $fullpath_original_file is now a full path name
259 
260 if (!empty($hashp)) {
261  $accessallowed = 1; // When using hashp, link is public so we force $accessallowed
262  $sqlprotectagainstexternals = '';
263 } elseif (GETPOSTINT("publictakepos")) {
264  if (getDolGlobalString('TAKEPOS_AUTO_ORDER') && in_array($modulepart, array('product', 'category'))) {
265  $accessallowed = 1; // When TakePOS Public Auto Order is enabled, we accept to see all images of product and categories with no login
266  // TODO Replace this with a call of getPublicImageOfObject like used by website so
267  // only shared images are visible
268  }
269 } else {
270  // Basic protection (against external users only)
271  if ($user->socid > 0) {
272  if ($sqlprotectagainstexternals) {
273  $resql = $db->query($sqlprotectagainstexternals);
274  if ($resql) {
275  $num = $db->num_rows($resql);
276  $i = 0;
277  while ($i < $num) {
278  $obj = $db->fetch_object($resql);
279  if ($user->socid != $obj->fk_soc) {
280  $accessallowed = 0;
281  break;
282  }
283  $i++;
284  }
285  }
286  }
287  }
288 }
289 
290 // Security:
291 // Limit access if permissions are wrong
292 if (!$accessallowed) {
293  accessforbidden();
294 }
295 
296 // Security:
297 // On interdit les remontees de repertoire ainsi que les pipe dans les noms de fichiers.
298 if (preg_match('/\.\./', $fullpath_original_file) || preg_match('/[<>|]/', $fullpath_original_file)) {
299  dol_syslog("Refused to deliver file ".$fullpath_original_file);
300  print "ErrorFileNameInvalid: ".dol_escape_htmltag($original_file);
301  exit;
302 }
303 
304 
305 
306 if ($modulepart == 'barcode') {
307  $generator = GETPOST("generator", "aZ09");
308  $encoding = GETPOST("encoding", "aZ09");
309  $readable = GETPOST("readable", 'aZ09') ? GETPOST("readable", "aZ09") : "Y";
310  if (in_array($encoding, array('EAN8', 'EAN13'))) {
311  $code = GETPOST("code", 'alphanohtml');
312  } else {
313  $code = GETPOST("code", 'restricthtml'); // This can be rich content (qrcode, datamatrix, ...)
314  }
315 
316  if (empty($generator) || empty($encoding)) {
317  print 'Error: Parameter "generator" or "encoding" not defined';
318  exit;
319  }
320 
321  $dirbarcode = array_merge(array("/core/modules/barcode/doc/"), $conf->modules_parts['barcode']);
322 
323  $result = 0;
324 
325  foreach ($dirbarcode as $reldir) {
326  $dir = dol_buildpath($reldir, 0);
327  $newdir = dol_osencode($dir);
328 
329  // Check if directory exists (we do not use dol_is_dir to avoid loading files.lib.php)
330  if (!is_dir($newdir)) {
331  continue;
332  }
333 
334  $result = @include_once $newdir.$generator.'.modules.php';
335  if ($result) {
336  break;
337  }
338  }
339 
340  // Load barcode class
341  $classname = "mod".ucfirst($generator);
342 
343  $module = new $classname($db);
344  if ($module->encodingIsSupported($encoding)) {
345  $result = $module->buildBarCode($code, $encoding, $readable);
346  }
347 } else {
348  // Open and return file
349  clearstatcache();
350 
351  $filename = basename($fullpath_original_file);
352 
353  // Output files on browser
354  dol_syslog("viewimage.php return file $fullpath_original_file filename=$filename content-type=$type");
355 
356  if (!dol_is_file($fullpath_original_file) && !GETPOSTINT("noalt", 1)) {
357  // This test is to replace error images with a nice "notfound image" when image is not available (for example when thumbs not yet generated).
358  $fullpath_original_file = DOL_DOCUMENT_ROOT.'/public/theme/common/nophoto.png';
359  /*$error='Error: File '.$_GET["file"].' does not exists or filesystems permissions are not allowed';
360  print $error;
361  exit;*/
362  }
363 
364  // Permissions are ok and file found, so we return it
365  if ($type) {
366  top_httphead($type);
367  header('Content-Disposition: inline; filename="'.basename($fullpath_original_file).'"');
368  } else {
369  top_httphead('image/png');
370  header('Content-Disposition: inline; filename="'.basename($fullpath_original_file).'"');
371  }
372 
373  $fullpath_original_file_osencoded = dol_osencode($fullpath_original_file);
374 
375  readfile($fullpath_original_file_osencoded);
376 }
377 
378 
379 if (is_object($db)) {
380  $db->close();
381 }
Class to manage ECM files.
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...
Definition: files.lib.php:2725
dol_is_file($pathoffile)
Return if path is a file.
Definition: files.lib.php:519
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.
dolIsAllowedForPreview($file)
Return if a file is qualified for preview.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
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.
if(!defined('NOREQUIREMENU')) if(!empty(GETPOST('seteventmessages', 'alpha'))) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
Definition: main.inc.php:1648
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.
if(is_numeric($entity)) llxHeader()
Header empty.
Definition: viewimage.php:118
llxFooter()
Footer empty.
Definition: viewimage.php:127