dolibarr 24.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-2025 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2024-2025 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'; form-action 'none'; frame-ancestors 'self'");
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 (by definition, the company logo is public)
65 if ($_GET["modulepart"] == 'mycompany' && isset($_GET['file']) && preg_match('/^\/?logos\//', $_GET['file'])) {
66 $needlogin = 0;
67 }
68 // For barcode live generation (barcode are just a graph of a value, so can be public)
69 if ($_GET["modulepart"] == 'barcode') {
70 $needlogin = 0;
71 }
72 // Medias files (by definition medias files are for website so are public)
73 if ($_GET["modulepart"] == 'medias') {
74 $needlogin = 0;
75 }
76 // Common files (public files embedded 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 credit card)
81 if ($_GET["modulepart"] == 'userphotopublic') {
82 $needlogin = 0;
83 }
84 // Used by TakePOS Auto Order. TODO Image product may became public in this case. A security check to check that product is in takepos tree must be done later.
85 // isModEnabled is not defined, DOL_DOCUMENT_ROOT is not defined
86 if ($_GET["modulepart"] == 'product' /* && isModEnabled('takepos') */ && isset($_GET["publictakepos"])) {
87 $needlogin = 0;
88 }
89}
90// For direct external download link (when files was shared for download using a hash link), we don't need to load/check we are into a login session
91if (isset($_GET["hashp"])) {
92 $needlogin = 0;
93}
94// If nologin required
95if (!$needlogin) {
96 if (!defined("NOLOGIN")) {
97 define("NOLOGIN", 1);
98 }
99 if (!defined("NOCSRFCHECK")) {
100 define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
101 }
102 if (!defined("NOIPCHECK")) {
103 define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip
104 }
105}
106
107// For MultiCompany module.
108// Do not use GETPOST here, function is not defined and define must be done before including main.inc.php
109// Because 2 entities can have the same ref.
110$entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1));
111if (is_numeric($entity)) {
112 define("DOLENTITY", $entity);
113}
114
137function llxHeader($head = '', $title = '', $help_url = '', $target = '', $disablejs = 0, $disablehead = 0, $arrayofjs = '', $arrayofcss = '', $morequerystring = '', $morecssonbody = '', $replacemainareaby = '', $disablenofollow = 0, $disablenoindex = 0) // @phan-suppress-current-line PhanRedefineFunction
138{
139}
150function llxFooter($comment = '', $zone = 'private', $disabledoutputofmessages = 0) // @phan-suppress-current-line PhanRedefineFunction
151{
152}
153
154require 'main.inc.php'; // Load $user and permissions
155require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
156
165$action = GETPOST('action', 'aZ09');
166$original_file = GETPOST('file', 'alphanohtml');
167$hashp = GETPOST('hashp', 'aZ09', 1);
168$extname = GETPOST('extname', 'alpha', 1);
169$modulepart = GETPOST('modulepart', 'alpha', 1);
170$urlsource = GETPOST('urlsource', 'alpha');
171$entity = (GETPOSTINT('entity') ? GETPOSTINT('entity') : $conf->entity);
172
173// Security check
174if (empty($modulepart) && empty($hashp)) {
175 httponly_accessforbidden('Bad link. Bad value for parameter modulepart', 400);
176}
177if (empty($original_file) && empty($hashp) && $modulepart != 'barcode') {
178 httponly_accessforbidden('Bad link. Missing identification to find file (param file or hashp)', 400);
179}
180if ($modulepart == 'fckeditor') {
181 $modulepart = 'medias'; // For backward compatibility
182}
183
184
185/*
186 * Actions
187 */
188
189// None
190
191
192
193/*
194 * View
195 */
196
197$cachestring = GETPOST("cache", 'aZ09'); // May be 1, or an int, or a hash
198if ($cachestring) {
199 // Important: The following code is to avoid a page request by the browser and PHP CPU at each Dolibarr page access.
200 // We are here when param cache=xxx to force a cache policy:
201 // xxx=1 means cache of 3600s
202 // xxx=abcdef or 123456789 means a cache of 1 week (the key will be modified to get break cache use)
203 $delaycache = ((is_numeric($cachestring) && (int) $cachestring > 1 && (int) $cachestring < 999999) ? $cachestring : '3600');
204 header('Cache-Control: max-age='.$delaycache.', public, must-revalidate');
205 header('Pragma: cache'); // This is to avoid to have Pragma: no-cache set by proxy or web server
206 header('Expires: '.gmdate('D, d M Y H:i:s', time() + (int) $delaycache).' GMT'); // This is to avoid to have Expires set by proxy or web server
207}
208
209// If we have a hash public (hashp), we guess the original_file.
210if (!empty($hashp)) {
211 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
212 include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
213 $ecmfile = new EcmFiles($db);
214 $result = $ecmfile->fetch(0, '', '', '', $hashp);
215 if ($result > 0) {
216 $tmp = explode('/', $ecmfile->filepath, 2); // $ecmfile->filepath is relative to document directory
217 // filepath can be 'users/X' or 'X/propale/PR11111'
218 if (is_numeric($tmp[0])) { // If first tmp is numeric, it is subdir of company for multicompany, we take next part.
219 $tmp = explode('/', $tmp[1], 2);
220 }
221 $moduleparttocheck = $tmp[0]; // moduleparttocheck is first part of path
222
223 if ($modulepart) { // Not required, so often not defined, for link using public hashp parameter.
224 if ($moduleparttocheck == $modulepart) {
225 // We remove first level of directory
226 $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir
227 //var_dump($original_file); exit;
228 } else {
229 httponly_accessforbidden('Bad link. File is from another module part.', 403);
230 }
231 } else {
232 $modulepart = $moduleparttocheck;
233 $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir
234 }
235
236 if ($extname) {
237 $original_file = getImageFileNameForSize($original_file, $extname);
238 }
239 } else {
240 httponly_accessforbidden("ErrorFileNotFoundWithSharedLink", 403, 1);
241 }
242}
243
244// Define mime type
245$type = 'application/octet-stream';
246if (GETPOST('type', 'alpha')) {
247 $type = GETPOST('type', 'alpha');
248} else {
249 $type = dol_mimetype($original_file);
250}
251
252// Security: This wrapper is for images. We do not allow type/html
253if (preg_match('/html/i', $type)) {
254 httponly_accessforbidden('Error: Using the image wrapper to output a file with a mime type HTML is not possible.');
255}
256// Security: This wrapper is for images. We do not allow files ending with .noexe
257if (preg_match('/\.noexe$/i', $original_file)) {
258 httponly_accessforbidden('Error: Using the image wrapper to output a file ending with .noexe is not allowed.');
259}
260
261// Security: Delete string ../ or ..\ into $original_file
262$original_file = preg_replace('/\.\.+/', '..', $original_file); // Replace '... or more' with '..'
263$original_file = str_replace('../', '/', $original_file);
264$original_file = str_replace('..\\', '/', $original_file);
265
266// Find the subdirectory name as the reference
267$refname = basename(dirname($original_file)."/");
268if ($refname == 'thumbs') {
269 // If we get the thumbs directory, we must go one step higher. For example original_file='10/thumbs/myfile_small.jpg' -> refname='10'
270 $refname = basename(dirname(dirname($original_file))."/");
271}
272
273// Check that file is allowed for view with viewimage.php
274if (!empty($original_file) && !dolIsAllowedForPreview($original_file)) {
275 httponly_accessforbidden('This file extension is not qualified for preview', 403);
276}
277
278// Security check
279if (empty($modulepart)) {
280 httponly_accessforbidden('Bad value for parameter modulepart', 400);
281}
282
283// When logged in a different entity, medias cannot be accessed because $conf->$module->multidir_output
284// is not set on the requested entity, but they are public documents, so reset entity
285if ($modulepart === 'medias' && $entity != $conf->entity) {
286 $conf->entity = $entity;
287 $conf->setValues($db);
288}
289
290$check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, $user, $refname);
291$accessallowed = $check_access['accessallowed'];
292$sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
293$fullpath_original_file = $check_access['original_file']; // $fullpath_original_file is now a full path name
294
295if (!empty($hashp)) {
296 $accessallowed = 1; // When using hashp, link is public so we force $accessallowed
297 $sqlprotectagainstexternals = '';
298} elseif (GETPOSTINT("publictakepos")) {
299 if (getDolGlobalString('TAKEPOS_AUTO_ORDER') && in_array($modulepart, array('product', 'category'))) {
300 $accessallowed = 1; // When TakePOS Public Auto Order is enabled, we accept to see all images of product and categories with no login
301 // TODO Replace the use of link to viewimage with a call to get link by getPublicImageOfObject, like done by website templates so
302 // only shared images are visible
303 }
304} else {
305 // Basic protection (against external users only)
306 if ($user->socid > 0) {
307 if ($sqlprotectagainstexternals) {
308 $resql = $db->query($sqlprotectagainstexternals);
309 if ($resql) {
310 $num = $db->num_rows($resql);
311 $i = 0;
312 while ($i < $num) {
313 $obj = $db->fetch_object($resql);
314 if ($user->socid != $obj->fk_soc) {
315 $accessallowed = 0;
316 break;
317 }
318 $i++;
319 }
320 }
321 }
322 }
323}
324
325// Security:
326// Limit access if permissions are wrong
327if (!$accessallowed) {
329}
330
331// Security:
332// On interdit les remontees de repertoire ainsi que les pipe dans les noms de fichiers.
333if (preg_match('/\.\./', $fullpath_original_file) || preg_match('/[<>|]/', $fullpath_original_file)) {
334 dol_syslog("Refused to deliver file ".$fullpath_original_file);
335 print "ErrorFileNameInvalid: ".dol_escape_htmltag($original_file);
336 exit;
337}
338
339
340if ($modulepart == 'barcode') {
341 $generator = GETPOST("generator", "aZ09");
342 $encoding = GETPOST("encoding", "aZ09");
343 $readable = GETPOST("readable", 'aZ09') ? GETPOST("readable", "aZ09") : "Y";
344 if (in_array($encoding, array('EAN8', 'EAN13'))) {
345 $code = GETPOST("code", 'alphanohtml');
346 } else {
347 $code = GETPOST("code", 'restricthtml'); // This can be rich content (qrcode, datamatrix, ...)
348 }
349
350 // If $code is virtualcard_xxx_999.vcf, it is a file to read to get code
351 $reg = array();
352 if (preg_match('/^virtualcard_([^_]+)_(\d+)\.vcf$/', $code, $reg)) {
353 $vcffile = '';
354 $id = 0;
355 $login = '';
356 if ($reg[1] == 'user' && (int) $reg[2] > 0) {
357 $vcffile = $conf->user->dir_temp.'/'.$code;
358 $id = (int) $reg[2];
359 $tmpuser = new User($db);
360 $tmpuser->fetch($id);
361 $login = $tmpuser->login;
362 } elseif ($reg[1] == 'contact' && (int) $reg[2] > 0) {
363 $vcffile = $conf->contact->dir_temp.'/'.$code;
364 $id = (int) $reg[2];
365 }
366
367 $code = '';
368 if ($vcffile && $id) {
369 // Case of use of viewimage to get the barcode for user pubic profile,
370 // we must check the securekey that protet against forging url
371 if ($reg[1] == 'user' && (int) $reg[2] > 0) {
372 $encodedsecurekey = dol_hash($conf->file->instance_unique_id.'uservirtualcard'.$id.'-'.$login, 'md5');
373 if ($encodedsecurekey != GETPOST('securekey')) {
374 $code = 'badvalueforsecurekey';
375 }
376 }
377 if (empty($code)) {
378 $code = file_get_contents($vcffile);
379 }
380 }
381 }
382
383
384 if (empty($generator) || empty($encoding)) {
385 print 'Error: Parameter "generator" or "encoding" not defined';
386 exit;
387 }
388
389 $dirbarcode = array_merge(array("/core/modules/barcode/doc/"), $conf->modules_parts['barcode']);
390
391 $result = 0;
392
393 foreach ($dirbarcode as $reldir) {
394 $dir = dol_buildpath($reldir, 0);
395 $newdir = dol_osencode($dir);
396
397 // Check if directory exists (we do not use dol_is_dir to avoid loading files.lib.php)
398 if (!is_dir($newdir)) {
399 continue;
400 }
401
402 $result = @include_once $newdir.$generator.'.modules.php';
403 if ($result) {
404 break;
405 }
406 }
407
408 // Load barcode class
409 $classname = "mod".ucfirst($generator);
410
411 $module = new $classname($db);
412 '@phan-var-force ModeleBarCode $module';
414 if ($module->encodingIsSupported($encoding)) {
415 top_httphead('none'); // This add header like the Content-Security-Policy. We set content-type to 'none' so the content-type will be added by the $module->buildBarCode.
416 // Note that link to image can be shown as a direct link due to the MAIN_SECURITY_FORCECSP directive. Link must be into an img of a page in same domain.
417
418 $result = $module->buildBarCode($code, $encoding, $readable);
419 }
420} else {
421 // Open and return file
422 clearstatcache();
423
424 $filename = basename($fullpath_original_file);
425
426 // Output files on browser
427 dol_syslog("viewimage.php return file $fullpath_original_file filename=$filename content-type=$type");
428
429 if (!dol_is_file($fullpath_original_file) && !GETPOSTINT("noalt", 1)) {
430 // This test is to replace error images with a nice "notfound image" when image is not available (for example when thumbs not yet generated).
431 $fullpath_original_file = DOL_DOCUMENT_ROOT.'/public/theme/common/nophoto.png';
432 /*$error='Error: File '.$_GET["file"].' does not exists or filesystems permissions are not allowed';
433 print $error;
434 exit;*/
435 }
436
437 // Permissions are ok and file found, so we return it
438 if ($type) {
439 top_httphead($type);
440 header('Content-Disposition: inline; filename="'.basename($fullpath_original_file).'"');
441 } else {
442 top_httphead('image/png');
443 header('Content-Disposition: inline; filename="'.basename($fullpath_original_file).'"');
444 }
445
446 $fullpath_original_file_osencoded = dol_osencode($fullpath_original_file);
447
448 readfile($fullpath_original_file_osencoded);
449}
450
451
452if (is_object($db)) {
453 $db->close();
454}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
Class to manage ECM files.
Class to manage Dolibarr users.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
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.
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.
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.
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.
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Footer empty.
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.