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