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