dolibarr 23.0.3
wrapper.php
1<?php
2/* Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
3 * Copyright (C) 2025 MDW <mdeweerd@users.noreply.github.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
18
19// BEGIN PHP File wrapper.php used to download rss, logo, shared files - DO NOT MODIFY - It is just a copy of file website/samples/wrapper.php
20$websitekey = basename(__DIR__);
21if (strpos($_SERVER["PHP_SELF"], 'website/samples/wrapper.php')) {
22 die("Sample file for website module. Can't be called directly.");
23}
24if (!defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
25 require_once './master.inc.php';
26} // Load master if not already loaded
32include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
33
34$encoding = '';
35
36// Parameters to download files
37$hashp = GETPOST('hashp', 'aZ09');
38$extname = GETPOST('extname', 'alpha', 1);
39$modulepart = GETPOST('modulepart', 'aZ09');
40$entity = GETPOSTINT('entity') ? GETPOSTINT('entity') : $conf->entity;
41$original_file = GETPOST("file", "alpha");
42$l = GETPOST('l', 'aZ09');
43$limit = GETPOSTINT('limit');
44if ($limit <= 0 || $limit > 100) {
45 $limit = 20;
46}
47
48// Parameters for RSS
49$rss = GETPOST('rss', 'aZ09');
50if ($rss) {
51 $original_file = 'blog'.(($limit > 0 && $limit <= 100) ? '-'.$limit : '').(preg_match('/^[a-z][a-z](_[A-Z][A-Z])?$/', $l) ? '-'.$l : '').'-'.$websitekey.'.rss.cache';
52}
53
54// If we have a hash public (hashp), we guess the original_file.
55if (!empty($hashp)) {
56 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
57 include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
58 $ecmfile = new EcmFiles($db);
59 $result = $ecmfile->fetch(0, '', '', '', $hashp);
60 if ($result > 0) {
61 $tmp = explode('/', $ecmfile->filepath, 2); // $ecmfile->filepath is relative to document directory
62 // filepath can be 'users/X' or 'X/propale/PR11111'
63 if (is_numeric($tmp[0])) { // If first tmp is numeric, it is subdir of company for multicompany, we take next part.
64 $tmp = explode('/', $tmp[1], 2);
65 }
66 $moduleparttocheck = $tmp[0]; // moduleparttocheck is first part of path
67
68 if ($modulepart) { // Not required, so often not defined, for link using public hashp parameter.
69 if ($moduleparttocheck == $modulepart) {
70 // We remove first level of directory
71 $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir
72 //var_dump($original_file); exit(0);
73 } else {
74 // Security options
75
76 // X-Content-Type-Options
77 header("X-Content-Type-Options: nosniff");
78
79 // X-Frame-Options
80 if (!getDolGlobalString('WEBSITE_ALLOW_FRAMES_ON_ALL_PAGES')) {
81 header("X-Frame-Options: SAMEORIGIN");
82 }
83
84 http_response_code(401);
85 print 'Bad link. File is from another module part.';
86 exit(1);
87 }
88 } else {
89 $modulepart = $moduleparttocheck;
90 $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir
91 }
92
93 if ($extname) {
94 $original_file = getImageFileNameForSize($original_file, $extname);
95 }
96 } else {
97 // Security options
98
99 // X-Content-Type-Options
100 header("X-Content-Type-Options: nosniff");
101
102 // X-Frame-Options
103 if (!getDolGlobalString('WEBSITE_ALLOW_FRAMES_ON_ALL_PAGES')) {
104 header("X-Frame-Options: SAMEORIGIN");
105 }
106
107 http_response_code(404);
108 print "ErrorFileNotFoundWithSharedLink";
109 exit(2);
110 }
111}
112
113// Define attachment (attachment=true to force choice popup 'open'/'save as')
114$attachment = true;
115if (preg_match('/\.(html|htm)$/i', $original_file)) {
116 $attachment = false;
117}
118if (GETPOSTISSET("attachment")) {
119 $attachment = (GETPOST("attachment", 'alphanohtml') ? true : false);
120}
121if (getDolGlobalString('MAIN_DISABLE_FORCE_SAVEAS_WEBSITE')) {
122 $attachment = false;
123}
124
125// Define mime type
126$type = 'application/octet-stream';
127if (GETPOSTISSET('type')) {
128 $type = GETPOST('type', 'alpha');
129} else {
130 $type = dol_mimetype($original_file);
131}
132
133// Security: Delete string ../ into $original_file
134$original_file = str_replace("../", "/", $original_file);
135
136
137// Cache or not
138$cachestring = GETPOST("cache", 'aZ09'); // May be 1, or an int (delay in second of the cache if < 999999, or a timestamp), or a hash
139$cachedelay = GETPOSTINT('cachedelay') ? GETPOSTINT('cachedelay') : ((is_numeric($cachestring) && (int) $cachestring > 1 && (int) $cachestring < 999999) ? $cachestring : '3600');
140if ($cachestring || image_format_supported($original_file) >= 0) {
141 // Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access.
142 header('Cache-Control: max-age='.$cachedelay.', public, must-revalidate');
143 header('Pragma: cache'); // This is to avoid having Pragma: no-cache
144 header('Expires: '.gmdate('D, d M Y H:i:s', time() + (int) $cachedelay).' GMT'); // This is to avoid to have Expires set by proxy or web server
145}
146
147$refname = basename(dirname($original_file)."/");
148
149// Get RSS news
150if ($rss) {
151 $format = 'rss';
152 $type = '';
153 $filename = $original_file;
154 $dir_temp = (string) $conf->website->dir_temp;
155
156 include_once DOL_DOCUMENT_ROOT.'/website/class/website.class.php';
157 include_once DOL_DOCUMENT_ROOT.'/website/class/websitepage.class.php';
158 $website = new Website($db);
159 $websitepage = new WebsitePage($db);
160
161 $website->fetch(0, $websitekey);
162
163 $filters = array('type_container' => 'blogpost', 'status' => '1');
164 if ($l) {
165 $filters['lang'] = (string) $l;
166 }
167
168 $MAXNEWS = $limit;
169 $arrayofblogs = $websitepage->fetchAll($website->id, 'DESC', 'date_creation', $MAXNEWS, 0, $filters);
170 $eventarray = array();
171 if (is_array($arrayofblogs)) {
172 foreach ($arrayofblogs as $blog) {
173 $blog->fullpageurl = $website->virtualhost.'/'.$blog->pageurl.'.php';
174 $blog->image = preg_replace('/__WEBSITE_KEY__/', $websitekey, $blog->image);
175
176 $eventarray[] = $blog;
177 }
178 }
179
180 require_once DOL_DOCUMENT_ROOT."/core/lib/xcal.lib.php";
181 require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php";
182 require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php";
183
184 dol_syslog("build_exportfile Build export file format=".$format.", type=".$type.", cachestring=".$cachestring.", filename=".$filename.", filters size=".count($filters), LOG_DEBUG);
185
186 // Clean parameters
187 if (!$filename) {
188 $extension = 'rss';
189 $filename = $format.'.'.$extension;
190 }
191
192 // Create dir and define output file (definitive and temporary)
193 $result = dol_mkdir($dir_temp);
194 $outputfile = $dir_temp.'/'.$filename;
195
196 $result = 0;
197
198 $buildfile = true;
199
200 if ($cachedelay) {
201 $nowgmt = dol_now();
202 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
203 if (dol_filemtime($outputfile) > ($nowgmt - $cachedelay)) {
204 dol_syslog("build_exportfile file ".$outputfile." is not older than now - cachedelay (".$nowgmt." - ".$cachedelay."). Build is canceled");
205 $buildfile = false;
206 }
207 }
208
209 if ($buildfile) {
210 $outputlangs = new Translate('', $conf);
211 $outputlangs->setDefaultLang($l);
212 $outputlangs->loadLangs(array("main", "other"));
213 $title = $outputlangs->transnoentities('LatestBlogPosts').' - '.$website->virtualhost;
214 $desc = $title.($l ? ' ('.$l.')' : '');
215
216 // Create temp file
217 $outputfiletmp = tempnam($dir_temp, 'tmp'); // Temporary file (allow call of function by different threads
218 dolChmod($outputfiletmp);
219
220 // Write file
221 $result = build_rssfile($format, $title, $desc, $eventarray, $outputfiletmp, '', $website->virtualhost.'/wrapper.php?rss=1'.($l ? '&l='.$l : ''), $l);
222
223 if ($result >= 0) {
224 if (dol_move($outputfiletmp, $outputfile, '0', 1, 0, 0)) {
225 $result = 1;
226 } else {
227 $error = 'Failed to rename '.$outputfiletmp.' into '.$outputfile;
228 dol_syslog("build_exportfile ".$error, LOG_ERR);
229 dol_delete_file($outputfiletmp, 0, 1);
230
231 http_response_code(500);
232 print $error;
233 exit(3);
234 }
235 } else {
236 dol_syslog("build_exportfile build_xxxfile function fails to for format=".$format." outputfiletmp=".$outputfile, LOG_ERR);
237 dol_delete_file($outputfiletmp, 0, 1);
238 $langs->load("errors");
239
240 http_response_code(500);
241 print $langs->trans("ErrorFailToCreateFile", $outputfile);
242 exit(4);
243 }
244 }
245
246 $attachment = false;
247 if (GETPOSTISSET("attachment")) {
248 $attachment = GETPOST("attachment");
249 }
250 //$attachment = false;
251 $contenttype = 'application/rss+xml';
252 if (GETPOSTISSET("contenttype")) {
253 $contenttype = GETPOST("contenttype");
254 }
255 //$contenttype='text/plain';
256 $outputencoding = 'UTF-8';
257
258 if ($contenttype) {
259 header('Content-Type: '.$contenttype.($outputencoding ? '; charset='.$outputencoding : ''));
260 }
261 if ($attachment) {
262 header('Content-Disposition: attachment; filename="'.$filename.'"');
263 }
264
265 // Ajout directives pour resoudre bug IE
266 //header('Cache-Control: Public, must-revalidate');
267 //header('Pragma: public');
268 if ($cachedelay) {
269 header('Cache-Control: max-age='.$cachedelay.', private, must-revalidate');
270 } else {
271 header('Cache-Control: private, must-revalidate');
272 }
273
274 // Clean parameters
275 $outputfile = $dir_temp.'/'.$filename;
276 $result = readfile($outputfile);
277 if (!$result) {
278 print 'File '.$outputfile.' was empty.';
279 }
280
281 // header("Location: ".DOL_URL_ROOT.'/document.php?modulepart=agenda&file='.urlencode($filename));
282 exit(5);
283} elseif ($modulepart == "mycompany" && preg_match('/^\/?logos\//', $original_file)) {
284 // Get logos
285 readfile(dol_osencode($conf->mycompany->dir_output."/".$original_file));
286} else {
287 // Find the subdirectory name as the reference
288 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
289 $check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, null, $refname);
290 $accessallowed = empty($check_access['accessallowed']) ? '' : $check_access['accessallowed'];
291 $sqlprotectagainstexternals = empty($check_access['sqlprotectagainstexternals']) ? '' : $check_access['sqlprotectagainstexternals'];
292 $fullpath_original_file = empty($check_access['original_file']) ? '' : $check_access['original_file']; // $fullpath_original_file is now a full path name
293 if ($hashp) {
294 $accessallowed = 1; // When using hashp, link is public so we force $accessallowed
295 $sqlprotectagainstexternals = '';
296 }
297
298 // Security:
299 // Limit access if permissions are wrong
300 if (!$accessallowed) {
301 http_response_code(403);
302 print 'Access forbidden';
303 exit(6);
304 }
305
306 // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension
307 if (image_format_supported($fullpath_original_file) && !dol_is_file($fullpath_original_file)) {
308 $fullpath_original_file = getImageFileNameForSize($fullpath_original_file, '', '.png');
309 }
310
311 clearstatcache();
312
313 $filename = basename($fullpath_original_file);
314
315 // Output file on browser
316 dol_syslog("wrapper.php download $fullpath_original_file filename=$filename content-type=$type");
317 $fullpath_original_file_osencoded = dol_osencode($fullpath_original_file); // New file name encoded in OS encoding charset
318
319 // This test if file exists should be useless. We keep it to find bug more easily
320 if (!file_exists($fullpath_original_file_osencoded)) {
321 http_response_code(404);
322 print "ErrorFileDoesNotExists: ".dol_escape_htmltag($original_file);
323 exit(7);
324 }
325
326 // Permissions are ok and file found, so we return it
327 //top_httphead($type);
328 header('Content-Type: '.$type);
329 header('Content-Description: File Transfer');
330 if ($encoding) {
331 header('Content-Encoding: '.$encoding);
332 }
333 // Add MIME Content-Disposition from RFC 2183 (inline=automatically displayed, attachment=need user action to open)
334 if ($attachment) {
335 header('Content-Disposition: attachment; filename="'.$filename.'"');
336 } else {
337 header('Content-Disposition: inline; filename="'.$filename.'"');
338 }
339 header('Content-Length: '.dol_filesize($fullpath_original_file));
340
341 readfile($fullpath_original_file_osencoded);
342}
343if (is_object($db)) {
344 $db->close();
345}
346// END PHP
Class to manage ECM files.
Class to manage translations.
Class Website.
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=null)
Move a file into another name.
dol_filemtime($pathoffile)
Return time of a file.
dol_filesize($pathoffile)
Return size of a file.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
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_now($mode='gmt')
Return date for now.
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.
dolChmod($filepath, $newmask='')
Change mod of a file.
getImageFileNameForSize($file, $extName, $extImgTarget='')
Return the filename of file to get the thumbs.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
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.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
build_rssfile($format, $title, $desc, $events_array, $outputfile, $filter='', $url='', $langcode='')
Build a file from an array of events.
Definition xcal.lib.php:326