dolibarr 18.0.6
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
29define('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
33if (!defined('NOREQUIRESOC')) {
34 define('NOREQUIRESOC', '1');
35}
36if (!defined('NOREQUIRETRAN')) {
37 define('NOREQUIRETRAN', '1');
38}
39if (!defined('NOCSRFCHECK')) {
40 define('NOCSRFCHECK', '1');
41}
42if (!defined('NOTOKENRENEWAL')) {
43 define('NOTOKENRENEWAL', '1');
44}
45if (!defined('NOREQUIREMENU')) {
46 define('NOREQUIREMENU', '1');
47}
48if (!defined('NOREQUIREHTML')) {
49 define('NOREQUIREHTML', '1');
50}
51if (!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;
58if (isset($_GET["modulepart"])) {
59 // For logo of company
60 if ($_GET["modulepart"] == 'mycompany' && preg_match('/^\/?logos\//', $_GET['file'])) {
61 $needlogin = 0;
62 }
63 // For barcode live generation
64 if ($_GET["modulepart"] == 'barcode') {
65 $needlogin = 0;
66 }
67 // Some value of modulepart can be used to get resources that are public so no login are required.
68 if ($_GET["modulepart"] == 'medias') {
69 $needlogin = 0;
70 }
71 if ($_GET["modulepart"] == 'userphotopublic') {
72 $needlogin = 0;
73 }
74 // Used by TakePOS Auto Order
75 if ($_GET["modulepart"] == 'product' && isset($_GET["publictakepos"])) {
76 $needlogin = 0;
77 }
78}
79// For direct external download link, we don't need to load/check we are into a login session
80if (isset($_GET["hashp"])) {
81 $needlogin = 0;
82}
83// If nologin required
84if (!$needlogin) {
85 if (!defined("NOLOGIN")) {
86 define("NOLOGIN", 1);
87 }
88 if (!defined("NOCSRFCHECK")) {
89 define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
90 }
91 if (!defined("NOIPCHECK")) {
92 define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip
93 }
94}
95
96// For multicompany
97$entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1));
98if (is_numeric($entity)) {
99 define("DOLENTITY", $entity);
100}
101
108function llxHeader()
109{
110}
117function llxFooter()
118{
119}
120
121require 'main.inc.php'; // Load $user and permissions
122require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
123
124$action = GETPOST('action', 'aZ09');
125$original_file = GETPOST('file', 'alphanohtml'); // Do not use urldecode here ($_GET are already decoded by PHP).
126$hashp = GETPOST('hashp', 'aZ09', 1); // Must be read only by GET
127$modulepart = GETPOST('modulepart', 'alpha', 1); // Must be read only by GET
128$urlsource = GETPOST('urlsource', 'alpha');
129$entity = (GETPOST('entity', 'int') ? GETPOST('entity', 'int') : $conf->entity);
130
131// Security check
132if (empty($modulepart) && empty($hashp)) {
133 httponly_accessforbidden('Bad link. Bad value for parameter modulepart', 400);
134}
135if (empty($original_file) && empty($hashp) && $modulepart != 'barcode') {
136 httponly_accessforbidden('Bad link. Missing identification to find file (param file or hashp)', 400);
137}
138if ($modulepart == 'fckeditor') {
139 $modulepart = 'medias'; // For backward compatibility
140}
141
142
143/*
144 * Actions
145 */
146
147// None
148
149
150
151/*
152 * View
153 */
154
155if (GETPOST("cache", 'alpha')) {
156 // Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access.
157 // Add param cache=abcdef
158 if (empty($dolibarr_nocache)) {
159 header('Cache-Control: max-age=3600, public, must-revalidate');
160 header('Pragma: cache'); // This is to avoid to have Pragma: no-cache set by proxy or web server
161 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
162 //header('Expires: '.strtotime('+1 hour');
163 } else {
164 header('Cache-Control: no-cache');
165 }
166 //print $dolibarr_nocache; exit;
167}
168
169// If we have a hash public (hashp), we guess the original_file.
170if (!empty($hashp)) {
171 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
172 $ecmfile = new EcmFiles($db);
173 $result = $ecmfile->fetch(0, '', '', '', $hashp);
174 if ($result > 0) {
175 $tmp = explode('/', $ecmfile->filepath, 2); // $ecmfile->filepath is relative to document directory
176 // filepath can be 'users/X' or 'X/propale/PR11111'
177 if (is_numeric($tmp[0])) { // If first tmp is numeric, it is subdir of company for multicompany, we take next part.
178 $tmp = explode('/', $tmp[1], 2);
179 }
180 $moduleparttocheck = $tmp[0]; // moduleparttocheck is first part of path
181
182 if ($modulepart) { // Not required, so often not defined, for link using public hashp parameter.
183 if ($moduleparttocheck == $modulepart) {
184 // We remove first level of directory
185 $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir
186 //var_dump($original_file); exit;
187 } else {
188 httponly_accessforbidden('Bad link. File is from another module part.', 403);
189 }
190 } else {
191 $modulepart = $moduleparttocheck;
192 $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir
193 }
194 } else {
195 $langs->load("errors");
196 httponly_accessforbidden($langs->trans("ErrorFileNotFoundWithSharedLink"), 403, 1);
197 }
198}
199
200// Define mime type
201$type = 'application/octet-stream';
202if (GETPOST('type', 'alpha')) {
203 $type = GETPOST('type', 'alpha');
204} else {
205 $type = dol_mimetype($original_file);
206}
207
208// Security: This wrapper is for images. We do not allow type/html
209if (preg_match('/html/i', $type)) {
210 httponly_accessforbidden('Error: Using the image wrapper to output a file with a mime type HTML is not possible.');
211}
212// Security: This wrapper is for images. We do not allow files ending with .noexe
213if (preg_match('/\.noexe$/i', $original_file)) {
214 httponly_accessforbidden('Error: Using the image wrapper to output a file ending with .noexe is not allowed.');
215}
216
217// Security: Delete string ../ or ..\ into $original_file
218$original_file = preg_replace('/\.\.+/', '..', $original_file); // Replace '... or more' with '..'
219$original_file = str_replace('../', '/', $original_file);
220$original_file = str_replace('..\\', '/', $original_file);
221
222// Find the subdirectory name as the reference
223$refname = basename(dirname($original_file)."/");
224if ($refname == 'thumbs') {
225 // If we get the thumbs directory, we must go one step higher. For example original_file='10/thumbs/myfile_small.jpg' -> refname='10'
226 $refname = basename(dirname(dirname($original_file))."/");
227}
228
229// Check that file is allowed for view with viewimage.php
230if (!empty($original_file) && !dolIsAllowedForPreview($original_file)) {
231 httponly_accessforbidden('This file is not qualified for preview', 403);
232}
233
234// Security check
235if (empty($modulepart)) {
236 httponly_accessforbidden('Bad value for parameter modulepart', 400);
237}
238
239// When logged in a different entity, medias cannot be accessed because $conf->$module->multidir_output
240// is not set on the requested entity, but they are public documents, so reset entity
241if ($modulepart === 'medias' && $entity != $conf->entity) {
242 $conf->entity = $entity;
243 $conf->setValues($db);
244}
245
246$check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, $user, $refname);
247$accessallowed = $check_access['accessallowed'];
248$sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
249$fullpath_original_file = $check_access['original_file']; // $fullpath_original_file is now a full path name
250
251if (!empty($hashp)) {
252 $accessallowed = 1; // When using hashp, link is public so we force $accessallowed
253 $sqlprotectagainstexternals = '';
254} elseif (isset($_GET["publictakepos"])) {
255 if (!empty($conf->global->TAKEPOS_AUTO_ORDER)) {
256 $accessallowed = 1; // Only if TakePOS Public Auto Order is enabled and received publictakepos variable
257 }
258} else {
259 // Basic protection (against external users only)
260 if ($user->socid > 0) {
261 if ($sqlprotectagainstexternals) {
262 $resql = $db->query($sqlprotectagainstexternals);
263 if ($resql) {
264 $num = $db->num_rows($resql);
265 $i = 0;
266 while ($i < $num) {
267 $obj = $db->fetch_object($resql);
268 if ($user->socid != $obj->fk_soc) {
269 $accessallowed = 0;
270 break;
271 }
272 $i++;
273 }
274 }
275 }
276 }
277}
278
279// Security:
280// Limit access if permissions are wrong
281if (!$accessallowed) {
283}
284
285// Security:
286// On interdit les remontees de repertoire ainsi que les pipe dans les noms de fichiers.
287if (preg_match('/\.\./', $fullpath_original_file) || preg_match('/[<>|]/', $fullpath_original_file)) {
288 dol_syslog("Refused to deliver file ".$fullpath_original_file);
289 print "ErrorFileNameInvalid: ".dol_escape_htmltag($original_file);
290 exit;
291}
292
293
294
295if ($modulepart == 'barcode') {
296 $generator = GETPOST("generator", "aZ09");
297 $encoding = GETPOST("encoding", "aZ09");
298 $readable = GETPOST("readable", 'aZ09') ? GETPOST("readable", "aZ09") : "Y";
299 if (in_array($encoding, array('EAN8', 'EAN13'))) {
300 $code = GETPOST("code", 'alphanohtml');
301 } else {
302 $code = GETPOST("code", 'restricthtml'); // This can be rich content (qrcode, datamatrix, ...)
303 }
304
305 if (empty($generator) || empty($encoding)) {
306 print 'Error: Parameter "generator" or "encoding" not defined';
307 exit;
308 }
309
310 $dirbarcode = array_merge(array("/core/modules/barcode/doc/"), $conf->modules_parts['barcode']);
311
312 $result = 0;
313
314 foreach ($dirbarcode as $reldir) {
315 $dir = dol_buildpath($reldir, 0);
316 $newdir = dol_osencode($dir);
317
318 // Check if directory exists (we do not use dol_is_dir to avoid loading files.lib.php)
319 if (!is_dir($newdir)) {
320 continue;
321 }
322
323 $result = @include_once $newdir.$generator.'.modules.php';
324 if ($result) {
325 break;
326 }
327 }
328
329 // Load barcode class
330 $classname = "mod".ucfirst($generator);
331 $module = new $classname($db);
332 if ($module->encodingIsSupported($encoding)) {
333 $result = $module->buildBarCode($code, $encoding, $readable);
334 }
335} else {
336 // Open and return file
337 clearstatcache();
338
339 $filename = basename($fullpath_original_file);
340
341 // Output files on browser
342 dol_syslog("viewimage.php return file $fullpath_original_file filename=$filename content-type=$type");
343
344 // This test is to avoid error images when image is not available (for example thumbs).
345 if (!dol_is_file($fullpath_original_file) && empty($_GET["noalt"])) {
346 $fullpath_original_file = DOL_DOCUMENT_ROOT.'/public/theme/common/nophoto.png';
347 /*$error='Error: File '.$_GET["file"].' does not exists or filesystems permissions are not allowed';
348 print $error;
349 exit;*/
350 }
351
352 // Permissions are ok and file found, so we return it
353 if ($type) {
354 top_httphead($type);
355 header('Content-Disposition: inline; filename="'.basename($fullpath_original_file).'"');
356 } else {
357 top_httphead('image/png');
358 header('Content-Disposition: inline; filename="'.basename($fullpath_original_file).'"');
359 }
360
361 $fullpath_original_file_osencoded = dol_osencode($fullpath_original_file);
362
363 readfile($fullpath_original_file_osencoded);
364}
365
366
367if (is_object($db)) {
368 $db->close();
369}
Class to manage ECM files.
dol_check_secure_access_document($modulepart, $original_file, $entity, $fuser='', $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.
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.
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()
Header empty.
llxFooter()
Footer empty.