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