dolibarr 23.0.4
actions_linkedfiles.inc.php
1<?php
2/* Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
3 * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
4 * Copyright (C) 2015 Ferran Marcet <fmarcet@2byte.es>
5 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 * or see https://www.gnu.org/
21 */
22
38'
39@phan-var-force string $upload_dir
40@phan-var-force string $forceFullTextIndexation
41';
42
43// Protection to understand what happen when submitting files larger than post_max_size
44if (GETPOSTINT('uploadform') && empty($_POST) && empty($_FILES)) {
45 dol_syslog("The PHP parameter 'post_max_size' is too low. All POST parameters and FILES were set to empty.");
46 $langs->loadLangs(array("errors", "install"));
47 print $langs->trans("ErrorFileSizeTooLarge").' ';
48 print $langs->trans("ErrorGoBackAndCorrectParameters");
49 die;
50}
51
52if ((GETPOST('sendit', 'alpha')
53 || GETPOST('linkit', 'restricthtml')
54 || ($action == 'confirm_deletefile' && $confirm == 'yes')
55 || ($action == 'confirm_updateline' && GETPOST('save', 'alpha') && GETPOST('link', 'alpha'))
56 || ($action == 'renamefile' && GETPOST('renamefilesave', 'alpha'))) && empty($permissiontoadd)) {
57 dol_syslog('The file actions_linkedfiles.inc.php was included but parameter $permissiontoadd was not set before.');
58 print 'The file actions_linkedfiles.inc.php was included but parameter $permissiontoadd was not set before.';
59 die;
60}
61
62$error = 0;
63
64// Submit file/link
65if (GETPOST('sendit', 'alpha') && getDolGlobalString('MAIN_UPLOAD_DOC') && !empty($permissiontoadd)) {
66 if (!empty($_FILES) && is_array($_FILES['userfile'])) {
67 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
68
69 if (is_array($_FILES['userfile']['tmp_name'])) { // When form has a input type="file" field with name="userfile[]"
70 $userfiles = $_FILES['userfile']['tmp_name'];
71 $filearrayis = 'array';
72 } else {
73 $userfiles = array(0 => $_FILES['userfile']['tmp_name']);
74 $filearrayis = 'string';
75 }
76
77 foreach ($userfiles as $key => $userfile) {
78 if ($filearrayis == 'array') {
79 $fileerror = $_FILES['userfile']['error'][$key];
80 $fileoriginname = $_FILES['userfile']['name'][$key];
81 } else {
82 $fileerror = $_FILES['userfile']['error'];
83 $fileoriginname = $_FILES['userfile']['name'];
84 }
85
86 if (empty($userfile)) {
87 $error++;
88 if ($fileerror == 1 || $fileerror == 2) {
89 setEventMessages($langs->trans('ErrorFileSizeTooLarge'), null, 'errors');
90 } else {
91 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("File")), null, 'errors');
92 }
93 }
94 if (preg_match('/__.*__/', $fileoriginname)) {
95 $error++;
96 setEventMessages($langs->trans('ErrorWrongFileName'), null, 'errors');
97 }
98 }
99
100 if (!$error) {
101 // Define if we have to generate thumbs or not
102 $generatethumbs = 1;
103 if (GETPOST('section_dir', 'alpha')) {
104 $generatethumbs = 0;
105 }
106 $allowoverwrite = (GETPOSTINT('overwritefile') ? 1 : 0);
107 $forceFullTextIndexation = (!empty($forceFullTextIndexation) ? $forceFullTextIndexation : '');
108
109 if (!empty($upload_dirold) && getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
110 $result = dol_add_file_process($upload_dirold, $allowoverwrite, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs, $object, empty($forceFullTextIndexation) ? 0 : $forceFullTextIndexation);
111 } elseif (!empty($upload_dir)) {
112 $result = dol_add_file_process($upload_dir, $allowoverwrite, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs, $object, empty($forceFullTextIndexation) ? 0 : $forceFullTextIndexation);
113 }
114 }
115 }
116} elseif (GETPOST('linkit', 'restricthtml') && getDolGlobalString('MAIN_UPLOAD_DOC') && !empty($permissiontoadd)) {
117 $link = GETPOST('link', 'alpha');
118 if ($link) {
119 if (substr($link, 0, 7) != 'http://' && substr($link, 0, 8) != 'https://' && substr($link, 0, 7) != 'file://' && substr($link, 0, 7) != 'davs://') {
120 $link = 'http://'.$link;
121 }
122
123 // Parse $newUrl
124 $newUrlArray = parse_url($link);
125
126 // Allow external links to svg ?
127 if (!getDolGlobalString('MAIN_ALLOW_SVG_FILES_AS_EXTERNAL_LINKS')) {
128 if (!empty($newUrlArray['path']) && preg_match('/\.svg$/i', $newUrlArray['path'])) {
129 $error++;
130 $langs->load("errors");
131 setEventMessages($langs->trans('ErrorSVGFilesNotAllowedAsLinksWithout', 'MAIN_ALLOW_SVG_FILES_AS_EXTERNAL_LINKS'), null, 'errors');
132 }
133 }
134 // Check URL is external (must refuse local link by default)
135 if (!getDolGlobalString('MAIN_ALLOW_LOCAL_LINKS_AS_EXTERNAL_LINKS')) {
136 // Test $newUrlAray['host'] to check link is external using isIPAllowed() and if not refuse the local link
137 // TODO
138 }
139
140 if (!$error) {
141 dol_add_file_process($upload_dir, 0, 1, 'userfile', '', $link, '', 0);
142 }
143 }
144}
145
146// Delete file/link
147if ($action == 'confirm_deletefile' && $confirm == 'yes' && !empty($permissiontoadd)) {
148 $urlfile = GETPOST('urlfile', 'alpha', 0, null, null, 1);
149 if (GETPOST('section', 'alpha')) {
150 // For a delete from the ECM module, upload_dir is ECM root dir and urlfile contains relative path from upload_dir
151 $file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile;
152 } else { // For a delete from the file manager into another module, or from documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile.
153 $urlfile = basename($urlfile);
154 $file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile;
155 if (!empty($upload_dirold)) {
156 $fileold = $upload_dirold."/".$urlfile;
157 }
158 }
159 $linkid = GETPOSTINT('linkid');
160 if ($urlfile) {
161 // delete of a file
162 $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
163 $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette (if file is an image)
164
165 $ret = dol_delete_file($file, 0, 0, 0, (is_object($object) ? $object : null));
166 if (!empty($fileold)) {
167 dol_delete_file($fileold, 0, 0, 0, (is_object($object) ? $object : null)); // Delete file using old path
168 }
169
170 if ($ret) {
171 // If it exists, remove thumb.
172 $regs = array();
173 if (preg_match('/(\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff)$/i', $file, $regs)) {
174 $photo_vignette = basename(preg_replace('/'.$regs[0].'/i', '', $file).'_small'.$regs[0]);
175 if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
176 dol_delete_file($dirthumb.$photo_vignette);
177 }
178
179 $photo_vignette = basename(preg_replace('/'.$regs[0].'/i', '', $file).'_mini'.$regs[0]);
180 if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
181 dol_delete_file($dirthumb.$photo_vignette);
182 }
183 }
184 setEventMessages($langs->trans("FileWasRemoved", $urlfile), null, 'mesgs');
185 } else {
186 setEventMessages($langs->trans("ErrorFailToDeleteFile", $urlfile), null, 'errors');
187 }
188 } elseif ($linkid) { // delete of external link
189 require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
190 $link = new Link($db);
191 $link->fetch($linkid);
192 // Verify the link belongs to the current object to prevent IDOR
193 if (!is_object($object) || $link->objecttype != $object->element || $link->objectid != $object->id) {
195 }
196 $res = $link->delete($user);
197
198 $langs->load('link');
199 if ($res > 0) {
200 setEventMessages($langs->trans("LinkRemoved", $link->label), null, 'mesgs');
201 } else {
202 if (count($link->errors)) {
203 setEventMessages('', $link->errors, 'errors');
204 } else {
205 setEventMessages($langs->trans("ErrorFailedToDeleteLink", $link->label), null, 'errors');
206 }
207 }
208 }
209
210 if (is_object($object) && $object->id > 0) {
211 if (!empty($backtopage)) {
212 header('Location: '.$backtopage);
213 exit;
214 } else {
215 $tmpurl = $_SERVER["PHP_SELF"].'?id='.$object->id.(GETPOST('section_dir', 'alpha') ? '&section_dir='.urlencode(GETPOST('section_dir', 'alpha')) : '').(!empty($withproject) ? '&withproject=1' : '');
216 header('Location: '.$tmpurl);
217 exit;
218 }
219 }
220} elseif ($action == 'confirm_updateline' && GETPOST('save', 'alpha') && GETPOST('link', 'alpha') && !empty($permissiontoadd)) {
221 require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
222
223 $link = new Link($db);
224 $f = $link->fetch(GETPOSTINT('linkid'));
225 if ($f) {
226 // Verify the link belongs to the current object to prevent IDOR
227 if (!is_object($object) || $link->objecttype != $object->element || $link->objectid != $object->id) {
229 }
230 $link->url = GETPOST('link', 'alpha');
231 if (substr($link->url, 0, 7) != 'http://' && substr($link->url, 0, 8) != 'https://' && substr($link->url, 0, 7) != 'file://') {
232 $link->url = 'http://'.$link->url;
233 }
234 $link->label = GETPOST('label', 'alphanohtml');
235
236 $shareenabled = GETPOST('shareenabled', 'alpha');
237 if ($shareenabled) {
238 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
239 $link->share = getRandomPassword(true);
240 } else {
241 $link->share = '';
242 }
243 $res = $link->update($user);
244 if (!$res) {
245 setEventMessages($langs->trans("ErrorFailedToUpdateLink", $link->label), null, 'mesgs');
246 }
247 } else {
248 //error fetching
249 }
250} elseif ($action == 'renamefile' && GETPOST('renamefilesave', 'alpha') && !empty($permissiontoadd)) {
251 // For documents pages, upload_dir contains already the path to the file from module dir
252 if (!empty($upload_dir)) {
253 $filenamefrom = dol_sanitizeFileName(GETPOST('renamefilefrom', 'alpha'), '_', 0); // Do not remove accents
254 $filenameto = dol_sanitizeFileName(GETPOST('renamefileto', 'alpha'), '_', 0); // Do not remove accents
255
256 // We apply dol_string_nohtmltag also to clean file names (this remove duplicate spaces) because
257 // this function is also applied when we upload and when we make try to download file (by the GETPOST(filename, 'alphanohtml') call).
258 $filenameto = dol_string_nohtmltag($filenameto);
259 if (preg_match('/__.*__/', $filenameto)) {
260 $error++;
261 setEventMessages($langs->trans('ErrorWrongFileName'), null, 'errors');
262 }
263
264 // Check that filename is not the one of a reserved allowed CLI command
265 if (empty($error)) {
266 global $dolibarr_main_restrict_os_commands;
267 if (!empty($dolibarr_main_restrict_os_commands)) {
268 $arrayofallowedcommand = explode(',', $dolibarr_main_restrict_os_commands);
269 $arrayofallowedcommand = array_map('trim', $arrayofallowedcommand);
270 if (in_array(basename($filenameto), $arrayofallowedcommand)) {
271 $error++;
272 $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
273 setEventMessages($langs->trans("ErrorFilenameReserved", basename($filenameto)), null, 'errors');
274 }
275 }
276 }
277
278 if (empty($error) && $filenamefrom != $filenameto) {
279 // For backward compatibility, the file to rename may be stored into an old path (see PRODUCT_USE_OLD_PATH_FOR_PHOTO).
280 // Upload and delete actions already fall back on $upload_dirold, so the rename action must do the same.
281 $dirforfile = $upload_dir;
282 if (!empty($upload_dirold) && !dol_is_file($upload_dir.'/'.$filenamefrom) && dol_is_file($upload_dirold.'/'.$filenamefrom)) {
283 $dirforfile = $upload_dirold;
284 }
285
286 // Security:
287 // Disallow file with some extensions. We rename them.
288 // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code.
289 if (isAFileWithExecutableContent($filenameto) && !getDolGlobalString('MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED')) {
290 // $dirforfile ends with a slash, so be must be sure the medias dir to compare to ends with slash too.
291 $publicmediasdirwithslash = $conf->medias->multidir_output[$conf->entity];
292 if (!preg_match('/\/$/', $publicmediasdirwithslash)) {
293 $publicmediasdirwithslash .= '/';
294 }
295
296 if (strpos($dirforfile, $publicmediasdirwithslash) !== 0) { // We never add .noexe on files into media directory
297 $filenameto .= '.noexe';
298 }
299 }
300
301 if ($filenamefrom && $filenameto) {
302 $srcpath = $dirforfile.'/'.$filenamefrom;
303 $destpath = $dirforfile.'/'.$filenameto;
304 /* disabled. Too many bugs. All files of an object must remain into directory of object. link with event should be done in llx_ecm_files with column agenda_id.
305 if ($modulepart == "ticket" && !dol_is_file($srcpath)) {
306 $srcbis = $conf->agenda->dir_output.'/'.GETPOST('section_dir').$filenamefrom;
307 if (dol_is_file($srcbis)) {
308 $srcpath = $srcbis;
309 $destpath = $conf->agenda->dir_output.'/'.GETPOST('section_dir').$filenameto;
310 }
311 }*/
312
313 $reshook = $hookmanager->initHooks(array('actionlinkedfiles'));
314 $parameters = array('filenamefrom' => $filenamefrom, 'filenameto' => $filenameto, 'upload_dir' => $dirforfile);
315 $reshook = $hookmanager->executeHooks('renameUploadedFile', $parameters, $object);
316
317 if (empty($reshook)) {
318 if (preg_match('/^\./', $filenameto)) {
319 $langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now.
320 setEventMessages($langs->trans("ErrorFilenameCantStartWithDot", $filenameto), null, 'errors');
321 } elseif (!file_exists($destpath)) {
322 $result = dol_move($srcpath, $destpath, '0', 1, 0, 1, [], $object->entity ?? $conf->entity);
323 if ($result) {
324 // Define if we have to generate thumbs or not
325 $generatethumbs = 1;
326 // When we rename a file from the file manager in ecm, we must not regenerate thumbs (not a problem, we do pass here)
327 // When we rename a file from the website module, we must not regenerate thumbs (module = medias in such a case)
328 // but when we rename from a tab "Documents", we must regenerate thumbs
329 if (GETPOST('modulepart', 'aZ09') == 'medias') {
330 $generatethumbs = 0;
331 }
332
333 if ($generatethumbs) {
334 if ($object->id > 0) {
335 // Create thumbs for the new file
336 $object->addThumbs($destpath);
337
338 // Delete thumb files with old name
339 $object->delThumbs($srcpath);
340 }
341 }
342
343 setEventMessages($langs->trans("FileRenamed"), null);
344 } else {
345 $langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now.
346 setEventMessages($langs->trans("ErrorFailToRenameFile", $filenamefrom, $filenameto), null, 'errors');
347 }
348 } else {
349 $langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now.
350 setEventMessages($langs->trans("ErrorDestinationAlreadyExists", $filenameto), null, 'errors');
351 }
352 }
353 }
354 }
355 }
356
357 // Update properties in ECM table
358 if (GETPOSTINT('ecmfileid') > 0) {
359 $shareenabled = GETPOST('shareenabled', 'alpha');
360
361 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
362 $ecmfile = new EcmFiles($db);
363 $result = $ecmfile->fetch(GETPOSTINT('ecmfileid'));
364 if ($result > 0) {
365 if ($shareenabled) {
366 if (empty($ecmfile->share)) {
367 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
368 $ecmfile->share = getRandomPassword(true);
369 }
370 } else {
371 $ecmfile->share = '';
372 }
373 $result = $ecmfile->update($user);
374 if ($result < 0) {
375 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
376 }
377 }
378 }
379}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
Class to manage ECM files.
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=null)
Move a file into another name.
dol_add_file_process($upload_dir, $allowoverwrite=0, $updatesessionordb=0, $keyforsourcefile='addedfile', $savingdocmask='', $link=null, $trackid='', $generatethumbs=1, $object=null, $forceFullTextIndexation='', $mode=0)
Get and save an upload file (for example after submitting a new file in a mail form).
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_is_file($pathoffile)
Return if path is a file.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
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.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
isAFileWithExecutableContent($filename)
Return if a file can contains executable content.
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.
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.