dolibarr 24.0.3
viewimage.controller.class.php
Go to the documentation of this file.
1<?php
2/*
3 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
4 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.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 */
19
26require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
27
28
33{
37 public $action;
38
42 public $entity;
43
47 public $filename;
48
52 public $fullpath_original_file;
53
57 public $fullpath_original_file_osencoded;
58
62 public $modulepart;
63
67 public $original_file;
68
72 public $type;
73
74
80 public function init()
81 {
82 global $conf, $hookmanager, $user;
83
84 define('MAIN_SECURITY_FORCECSP', "default-src 'none'");
85
86 if (!defined('NOREQUIRESOC')) {
87 define('NOREQUIRESOC', '1');
88 }
89 if (!defined('NOREQUIRETRAN')) {
90 define('NOREQUIRETRAN', '1');
91 }
92 if (!defined('NOCSRFCHECK')) {
93 define('NOCSRFCHECK', '1');
94 }
95 if (!defined('NOTOKENRENEWAL')) {
96 define('NOTOKENRENEWAL', '1');
97 }
98 if (!defined('NOREQUIREMENU')) {
99 define('NOREQUIREMENU', '1');
100 }
101 if (!defined('NOREQUIREHTML')) {
102 define('NOREQUIREHTML', '1');
103 }
104 if (!defined('NOREQUIREAJAX')) {
105 define('NOREQUIREAJAX', '1');
106 }
107
108 // For MultiCompany module.
109 // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php
110 // Because 2 entities can have the same ref.
111 $entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1));
112 define("DOLENTITY", $entity);
113
115
116 $action = GETPOST('action', 'aZ09');
117 $original_file = GETPOST('file', 'alphanohtml');
118 $hashp = GETPOST('hashp', 'aZ09', 1);
119 $extname = GETPOST('extname', 'alpha', 1);
120 $modulepart = GETPOST('modulepart', 'alpha', 1);
121 $urlsource = GETPOST('urlsource', 'alpha');
122 $entity = (GETPOSTINT('entity') ? GETPOSTINT('entity') : $conf->entity);
123
124 // Security check
125 if (empty($modulepart) && empty($hashp)) {
126 httponly_accessforbidden('Bad link. Bad value for parameter modulepart', 400);
127 }
128 if (empty($original_file) && empty($hashp) && $modulepart != 'barcode') {
129 httponly_accessforbidden('Bad link. Missing identification to find file (param file or hashp)', 400);
130 }
131 if ($modulepart == 'fckeditor') {
132 $modulepart = 'medias'; // For backward compatibility
133 }
134
135 $cachestring = GETPOST("cache", 'aZ09'); // May be 1, or an int, or a hash
136 if ($cachestring) {
137 // Important: The following code is to avoid a page request by the browser and PHP CPU at each Dolibarr page access.
138 // We are here when param cache=xxx to force a cache policy:
139 // xxx=1 means cache of 3600s
140 // xxx=abcdef or 123456789 means a cache of 1 week (the key will be modified to get break cache use)
141 $delaycache = ((is_numeric($cachestring) && (int) $cachestring > 1 && (int) $cachestring < 999999) ? $cachestring : '3600');
142 header('Cache-Control: max-age=' . $delaycache . ', public, must-revalidate');
143 header('Pragma: cache'); // This is to avoid to have Pragma: no-cache set by proxy or web server
144 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
145 }
146
147 // If we have a hash public (hashp), we guess the original_file from the shared file record (never trust param file).
148 if (!empty($hashp) && $hashp != 'shared') {
149 include_once DOL_DOCUMENT_ROOT . '/ecm/class/ecmfiles.class.php';
150 include_once DOL_DOCUMENT_ROOT . '/core/lib/images.lib.php';
151 $ecmfile = new EcmFiles($this->db);
152 $result = $ecmfile->fetch(0, '', '', '', $hashp);
153 if ($result > 0) {
154 $tmp = explode('/', $ecmfile->filepath, 2); // $ecmfile->filepath is relative to document directory
155 // filepath can be 'users/X' or 'X/propale/PR11111'
156 if (is_numeric($tmp[0])) { // If first tmp is numeric, it is subdir of company for multicompany, we take next part.
157 $tmp = explode('/', $tmp[1], 2);
158 }
159 $moduleparttocheck = $tmp[0]; // moduleparttocheck is first part of path
160
161 if ($modulepart) { // Not required, so often not defined, for link using public hashp parameter.
162 if ($moduleparttocheck != $modulepart) {
163 httponly_accessforbidden('Bad link. File is from another module part.', 403);
164 }
165 } else {
166 $modulepart = $moduleparttocheck;
167 }
168 $original_file = ((!empty($tmp[1]) ? $tmp[1] . '/' : '') . $ecmfile->filename); // this is relative to module dir
169
170 if ($extname) {
171 $original_file = getImageFileNameForSize($original_file, $extname);
172 }
173 } else {
174 httponly_accessforbidden("ErrorFileNotFoundWithSharedLink", 403, 1);
175 }
176 }
177
178 // Define mime type
179 $type = 'application/octet-stream';
180 if (GETPOST('type', 'alpha')) {
181 $type = GETPOST('type', 'alpha');
182 } else {
183 $type = dol_mimetype($original_file);
184 }
185
186 // Security: This wrapper is for images. We do not allow type/html
187 if (preg_match('/html/i', $type)) {
188 httponly_accessforbidden('Error: Using the image wrapper to output a file with a mime type HTML is not possible.');
189 }
190 // Security: This wrapper is for images. We do not allow files ending with .noexe
191 if (preg_match('/\.noexe$/i', $original_file)) {
192 httponly_accessforbidden('Error: Using the image wrapper to output a file ending with .noexe is not allowed.');
193 }
194
195 // Security: Delete string ../ or ..\ into $original_file
196 $original_file = preg_replace('/\.\.+/', '..', $original_file); // Replace '... or more' with '..'
197 $original_file = str_replace('../', '/', $original_file);
198 $original_file = str_replace('..\\', '/', $original_file);
199
200 // Find the subdirectory name as the reference
201 $refname = basename(dirname($original_file) . "/");
202 if ($refname == 'thumbs') {
203 // If we get the thumbs directory, we must go one step higher. For example original_file='10/thumbs/myfile_small.jpg' -> refname='10'
204 $refname = basename(dirname(dirname($original_file)) . "/");
205 }
206
207 // Check that file is allowed for view with viewimage.php
208 if (!empty($original_file) && !dolIsAllowedForPreview($original_file)) {
209 httponly_accessforbidden('This file extension is not qualified for preview', 403);
210 }
211
212 // Security check
213 if (empty($modulepart)) {
214 httponly_accessforbidden('Bad value for parameter modulepart', 400);
215 }
216
217 // When logged in a different entity, medias cannot be accessed because $conf->$module->multidir_output
218 // is not set on the requested entity, but they are public documents, so reset entity
219 if ($modulepart === 'medias' && $entity != $conf->entity) {
220 $conf->entity = $entity;
221 $conf->setValues($this->db);
222 }
223
224 $sqlprotectagainstexternals = '';
225 $fullpath_original_file = '';
226 $accessallowed = 0;
227
228 // Hooks
229 $hookmanager->initHooks(array('viewimage'));
230 $parameters = array('modulepart' => $modulepart, 'original_file' => &$original_file,
231 'sqlprotectagainstexternals' => &$sqlprotectagainstexternals, 'fullpath_original_file' => &$fullpath_original_file,
232 'entity' => $entity, 'accessallowed' => &$accessallowed);
233 $object = new stdClass();
234 $reshook = $hookmanager->executeHooks('accessViewImage', $parameters, $object, $action); // Note that $action and $object may have been
235 if ($reshook < 0) {
236 $errors = $hookmanager->error . (is_array($hookmanager->errors) ? (!empty($hookmanager->error) ? ', ' : '') . implode(', ', $hookmanager->errors) : '');
237 dol_syslog("document.php - Errors when executing the hook 'accessViewImage' : " . $errors);
238 print "ErrorViewImageHooks: " . $errors;
239 exit;
240 } elseif (empty($reshook)) {
241 $check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, $user, $refname);
242 $accessallowed = $check_access['accessallowed'];
243 $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
244 $fullpath_original_file = $check_access['original_file']; // $fullpath_original_file is now a full path name
245 }
246
247 if (!empty($hashp) && $hashp != 'shared') {
248 $accessallowed = 1; // When using hashp, link is public so we force $accessallowed
249 $sqlprotectagainstexternals = '';
250 } else {
251 // Basic protection (against external users only)
252 if ($user->socid > 0) {
253 if ($sqlprotectagainstexternals) {
254 $resql = $this->db->query($sqlprotectagainstexternals);
255 if ($resql) {
256 $num = $this->db->num_rows($resql);
257 $i = 0;
258 while ($i < $num) {
259 $obj = $this->db->fetch_object($resql);
260 if ($user->socid != $obj->fk_soc) {
261 $accessallowed = 0;
262 break;
263 }
264 $i++;
265 }
266 }
267 }
268 }
269 }
270
271 // Security:
272 // Limit access if permissions are wrong
273 if (!$accessallowed) {
275 }
276
277 // Security:
278 // On interdit les remontees de repertoire ainsi que les pipe dans les noms de fichiers.
279 if (preg_match('/\.\./', $fullpath_original_file) || preg_match('/[<>|]/', $fullpath_original_file)) {
280 dol_syslog("Refused to deliver file " . $fullpath_original_file);
281 print "ErrorFileNameInvalid: " . dol_escape_htmltag($original_file);
282 exit;
283 }
284
285 // Find the subdirectory name as the reference
286 $refname = basename(dirname($original_file) . "/");
287
288 $filename = basename($fullpath_original_file);
289 $filename = preg_replace('/\.noexe$/i', '', $filename);
290
291 // Output file on browser
292 dol_syslog("document controller download $fullpath_original_file filename=$filename content-type=$type");
293 $fullpath_original_file_osencoded = dol_osencode($fullpath_original_file); // New file name encoded in OS encoding charset
294
295 // This test if file exists should be useless. We keep it to find bug more easily
296 if (!file_exists($fullpath_original_file_osencoded)) {
297 dol_syslog("ErrorFileDoesNotExists: " . $fullpath_original_file);
298 print "ErrorFileDoesNotExists: " . $original_file;
299 exit;
300 }
301
302 $fileSize = dol_filesize($fullpath_original_file);
303 $fileSizeMax = getDolGlobalInt('MAIN_SECURITY_MAXFILESIZE_DOWNLOADED');
304 if ($fileSizeMax && $fileSize > $fileSizeMax) {
305 dol_syslog('ErrorFileSizeTooLarge: ' . $fileSize);
306 print 'ErrorFileSizeTooLarge: ' . $fileSize . ' (max ' . $fileSizeMax . ' Kb)';
307 exit;
308 }
309
310 // Hooks
311 $hookmanager->initHooks(array('document'));
312 $parameters = array('modulepart' => $modulepart, 'original_file' => $original_file,
313 'entity' => $entity, 'refname' => $refname, 'fullpath_original_file' => $fullpath_original_file,
314 'filename' => $filename, 'fullpath_original_file_osencoded' => $fullpath_original_file_osencoded);
315 $object = new stdClass();
316 $reshook = $hookmanager->executeHooks('viewImage', $parameters, $object, $action); // Note that $action and $object may have been
317 if ($reshook < 0) {
318 $errors = $hookmanager->error . (is_array($hookmanager->errors) ? (!empty($hookmanager->error) ? ', ' : '') . implode(', ', $hookmanager->errors) : '');
319 dol_syslog("document.php - Errors when executing the hook 'viewImage' : " . $errors);
320 print "ErrorViewImageHooks: " . $errors;
321 exit;
322 }
323
324 $this->action = $action;
325 $this->entity = $entity;
326 $this->filename = $filename;
327 $this->fullpath_original_file = $fullpath_original_file;
328 $this->fullpath_original_file_osencoded = $fullpath_original_file_osencoded;
329 $this->modulepart = $modulepart;
330 $this->original_file = $original_file;
331 $this->type = $type;
332 }
333
339 public function checkAccess()
340 {
341 $this->accessRight = true;
342
343 return parent::checkAccess();
344 }
345
352 public function action()
353 {
355 if (!$context->controllerInstance->checkAccess()) {
356 return -1;
357 }
358
359 //$context = Context::getInstance();
360 //$context->title = $langs->trans('WebPortalDocumentTitle');
361 //$context->desc = $langs->trans('WebPortalDocumentDesc');
362 //$context->doNotDisplayHeaderBar=1;// hide default header
363
364 $this->init();
365
366 return 1;
367 }
368
374 public function display()
375 {
376 global $conf;
377
379 if (!$context->controllerInstance->checkAccess()) {
380 $this->display404();
381 return;
382 }
383
384 // initialize
385 $modulepart = $this->modulepart;
386 $fullpath_original_file = $this->fullpath_original_file;
387 $fullpath_original_file_osencoded = $this->fullpath_original_file_osencoded;
388 $type = $this->type;
389
390 if ($modulepart == 'barcode') {
391 $generator = GETPOST("generator", "aZ09");
392 $encoding = GETPOST("encoding", "aZ09");
393 $readable = GETPOST("readable", 'aZ09') ? GETPOST("readable", "aZ09") : "Y";
394 if (in_array($encoding, array('EAN8', 'EAN13'))) {
395 $code = GETPOST("code", 'alphanohtml');
396 } else {
397 $code = GETPOST("code", 'restricthtml'); // This can be rich content (qrcode, datamatrix, ...)
398 }
399
400 // If $code is virtualcard_xxx_999.vcf, it is a file to read to get code
401 $reg = array();
402 if (preg_match('/^virtualcard_([^_]+)_(\d+)\.vcf$/', $code, $reg)) {
403 $vcffile = '';
404 $id = 0;
405 $login = '';
406 if ($reg[1] == 'user' && (int) $reg[2] > 0) {
407 $vcffile = $conf->user->dir_temp . '/' . $code;
408 $id = (int) $reg[2];
409 $tmpuser = new User($this->db);
410 $tmpuser->fetch($id);
411 $login = $tmpuser->login;
412 } elseif ($reg[1] == 'contact' && (int) $reg[2] > 0) {
413 $vcffile = $conf->contact->dir_temp . '/' . $code;
414 $id = (int) $reg[2];
415 }
416
417 $code = '';
418 if ($vcffile && $id) {
419 // Case of use of viewimage to get the barcode for user pubic profile,
420 // we must check the securekey that protet against forging url
421 if ($reg[1] == 'user' && (int) $reg[2] > 0) {
422 $encodedsecurekey = dol_hash($conf->file->instance_unique_id . 'uservirtualcard' . $id . '-' . $login, 'md5');
423 if ($encodedsecurekey != GETPOST('securekey')) {
424 $code = 'badvalueforsecurekey';
425 }
426 }
427 if (empty($code)) {
428 $code = file_get_contents($vcffile);
429 }
430 }
431 }
432
433
434 if (empty($generator) || empty($encoding)) {
435 print 'Error: Parameter "generator" or "encoding" not defined';
436 exit;
437 }
438
439 $dirbarcode = array_merge(array("/core/modules/barcode/doc/"), $conf->modules_parts['barcode']);
440
441 $result = 0;
442
443 foreach ($dirbarcode as $reldir) {
444 $dir = dol_buildpath($reldir, 0);
445 $newdir = dol_osencode($dir);
446
447 // Check if directory exists (we do not use dol_is_dir to avoid loading files.lib.php)
448 if (!is_dir($newdir)) {
449 continue;
450 }
451
452 $result = @include_once $newdir . $generator . '.modules.php';
453 if ($result) {
454 break;
455 }
456 }
457
458 // Load barcode class
459 $classname = "mod" . ucfirst($generator);
460
461 $module = new $classname($this->db);
462 '@phan-var-force ModeleBarCode $module';
464 if ($module->encodingIsSupported($encoding)) {
465 $result = $module->buildBarCode($code, $encoding, $readable);
466 }
467 } else {
468 // Open and return file
469 clearstatcache();
470
471 $filename = basename($fullpath_original_file);
472
473 // Output files on browser
474 dol_syslog("viewimage.php return file $fullpath_original_file filename=$filename content-type=$type");
475
476 if (!dol_is_file($fullpath_original_file) && !GETPOSTINT("noalt", 1)) {
477 // This test is to replace error images with a nice "notfound image" when image is not available (for example when thumbs not yet generated).
478 $fullpath_original_file = Context::getRootConfigUrl() . 'img/nophoto.png';
479 /*$error='Error: File '.$_GET["file"].' does not exists or filesystems permissions are not allowed';
480 print $error;
481 exit;*/
482 }
483
484 // Permissions are ok and file found, so we return it
485 if ($type) {
486 top_httphead($type);
487 header('Content-Disposition: inline; filename="' . basename($fullpath_original_file) . '"');
488 } else {
489 top_httphead('image/png');
490 header('Content-Disposition: inline; filename="' . basename($fullpath_original_file) . '"');
491 }
492
493 $fullpath_original_file_osencoded = dol_osencode($fullpath_original_file);
494
495 readfile($fullpath_original_file_osencoded);
496 }
497 }
498}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
static getInstance()
Singleton method to create one instance of this object.
static getRootConfigUrl()
Get WebPortal root url.
Class to manage pages.
display()
Display.
display404()
Display error template.
Class to manage ECM files.
Class to manage Dolibarr users.
Class for ViewImageController.
checkAccess()
Check current access to controller.
action()
Action method is called before html output can be used to manage security and change context.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
dol_filesize($pathoffile)
Return size of a file.
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.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
getImageFileNameForSize($file, $extName, $extImgTarget='')
Return the filename of file to get the thumbs.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dolIsAllowedForPreview($file)
Return if a file is qualified for preview.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
if(!defined( 'NOREQUIREMENU')) if(!empty(GETPOST('seteventmessages', 'alpha'))) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
$context
@method int call_trigger(string $triggerName, ?User $user)
Definition logout.php:42
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition repair.php:137
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.