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