dolibarr 25.0.0-alpha
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-2026 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
39'
40@phan-var-force CommonObject $object
41@phan-var-force string $upload_dir
42@phan-var-force string $upload_dirold
43@phan-var-force string $confirm
44@phan-var-force string $forceFullTextIndexation
45';
46
47// Protection to understand what happen when submitting files larger than post_max_size
48if (GETPOSTINT('uploadform') && empty($_POST) && empty($_FILES)) {
49 dol_syslog("The PHP parameter 'post_max_size' is too low. All POST parameters and FILES were set to empty.");
50 $langs->loadLangs(array("errors", "install"));
51 print $langs->trans("ErrorFileSizeTooLarge").' ';
52 print $langs->trans("ErrorGoBackAndCorrectParameters");
53 die;
54}
55
56if ((GETPOST('sendit', 'alpha')
57 || GETPOST('linkit', 'restricthtml')
58 || ($action == 'confirm_deletefile' && $confirm == 'yes')
59 || ($action == 'confirm_updateline' && GETPOST('save', 'alpha') && GETPOST('link', 'alpha'))
60 || ($action == 'renamefile' && GETPOST('renamefilesave', 'alpha'))) && empty($permissiontoadd)) {
61 dol_syslog('The file actions_linkedfiles.inc.php was included but parameter $permissiontoadd was not set before or is set to false.');
62 print 'The file actions_linkedfiles.inc.php was included but parameter $permissiontoadd was not set before or is set to false.';
63 die;
64}
65
66$error = 0;
67
68// Submit file/link
69if (GETPOST('sendit', 'alpha') && getDolGlobalString('MAIN_UPLOAD_DOC') && !empty($permissiontoadd)) {
70 if (!empty($_FILES) && is_array($_FILES['userfile'])) {
71 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
72
73 if (is_array($_FILES['userfile']['tmp_name'])) { // When form has a input type="file" field with name="userfile[]"
74 $userfiles = $_FILES['userfile']['tmp_name'];
75 $filearrayis = 'array';
76 } else {
77 $userfiles = array(0 => $_FILES['userfile']['tmp_name']);
78 $filearrayis = 'string';
79 }
80
81 foreach ($userfiles as $key => $userfile) {
82 if ($filearrayis == 'array') {
83 $fileerror = $_FILES['userfile']['error'][$key];
84 $fileoriginname = $_FILES['userfile']['name'][$key];
85 } else {
86 $fileerror = $_FILES['userfile']['error'];
87 $fileoriginname = $_FILES['userfile']['name'];
88 }
89
90 if (empty($userfile)) {
91 $error++;
92 if ($fileerror == 1 || $fileerror == 2) {
93 setEventMessages($langs->trans('ErrorFileSizeTooLarge'), null, 'errors');
94 } else {
95 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("File")), null, 'errors');
96 }
97 }
98 if (preg_match('/__.*__/', $fileoriginname)) {
99 $error++;
100 setEventMessages($langs->trans('ErrorWrongFileName'), null, 'errors');
101 }
102 }
103
104 if (!$error) {
105 // Define if we have to generate thumbs or not
106 $generatethumbs = 1;
107 if (GETPOST('section_dir', 'alpha')) {
108 $generatethumbs = 0;
109 }
110 $allowoverwrite = (GETPOSTINT('overwritefile') ? 1 : 0);
111 $forceFullTextIndexation = (!empty($forceFullTextIndexation) ? $forceFullTextIndexation : '');
112
113 if (!empty($upload_dirold) && getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
114 $result = dol_add_file_process($upload_dirold, $allowoverwrite, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs, $object, empty($forceFullTextIndexation) ? 0 : $forceFullTextIndexation);
115 } elseif (!empty($upload_dir)) {
116 $result = dol_add_file_process($upload_dir, $allowoverwrite, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs, $object, empty($forceFullTextIndexation) ? 0 : $forceFullTextIndexation);
117 }
118 }
119 }
120} elseif (GETPOST('linkit', 'restricthtml') && getDolGlobalString('MAIN_UPLOAD_DOC') && !empty($permissiontoadd)) {
121 $link = GETPOST('link', 'alpha');
122 if ($link) {
123 if (substr($link, 0, 7) != 'http://'
124 && substr($link, 0, 8) != 'https://'
125 && substr($link, 0, 7) != 'davs://'
126 && (substr($link, 0, 7) != 'file://' || !getDolGlobalString('MAIN_ALLOW_LINK_STARTING_WITH_FILE'))) {
127 $link = 'http://'.$link;
128 }
129
130 // Parse $newUrl
131 $newUrlArray = parse_url($link);
132
133 // Allow external links to svg ?
134 if (!getDolGlobalString('MAIN_ALLOW_SVG_FILES_AS_EXTERNAL_LINKS')) {
135 if (!empty($newUrlArray['path']) && preg_match('/\.svg$/i', $newUrlArray['path'])) {
136 $error++;
137 $langs->load("errors");
138 setEventMessages($langs->trans('ErrorSVGFilesNotAllowedAsLinksWithout', 'MAIN_ALLOW_SVG_FILES_AS_EXTERNAL_LINKS'), null, 'errors');
139 }
140 }
141 // Check URL is external (must refuse local link by default)
142 if (!getDolGlobalString('MAIN_ALLOW_LOCAL_LINKS_AS_EXTERNAL_LINKS')) {
143 // Test $newUrlAray['host'] to check link is external using isIPAllowed() and if not refuse the local link
144 // TODO
145 }
146
147 if (!$error) {
148 dol_add_file_process($upload_dir, 0, 1, 'userfile', '', $link, '', 0);
149 }
150 }
151}
152
153// Delete file/link
154if ($action == 'confirm_deletefile' && $confirm == 'yes' && !empty($permissiontoadd)) {
155 $urlfile = GETPOST('urlfile', 'alpha', 0, null, null, 1);
156 if (GETPOST('section', 'alpha')) {
157 // For a delete from the ECM module, upload_dir is ECM root dir and urlfile contains relative path from upload_dir
158 $file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile;
159 } 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.
160 $urlfile = basename($urlfile);
161 $file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile;
162 if (!empty($upload_dirold)) {
163 $fileold = $upload_dirold."/".$urlfile;
164 }
165 }
166 $linkid = GETPOSTINT('linkid');
167 if ($urlfile) {
168 // delete of a file
169 $dir = dirname($file).'/'; // Path to the folder containing the original image
170 $dirthumb = $dir.'/thumbs/'; // Path to the folder containing the thumbnail (if file is an image)
171
172 $ret = dol_delete_file($file, 1, 0, 0, (is_object($object) ? $object : null));
173 if (!empty($fileold)) {
174 dol_delete_file($fileold, 1, 0, 0, (is_object($object) ? $object : null)); // Delete file using old path
175 }
176
177 if ($ret) {
178 // If it exists, remove thumb.
179 $regs = array();
180 if (preg_match('/(\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff|\.webp|\.xpm|\.xbm|\.avif)$/i', $file, $regs)) {
181 $photo_vignette = basename(preg_replace('/'.$regs[0].'/i', '', $file).'_small'.$regs[0]);
182 if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
183 dol_delete_file($dirthumb.$photo_vignette);
184 }
185
186 $photo_vignette = basename(preg_replace('/'.$regs[0].'/i', '', $file).'_mini'.$regs[0]);
187 if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
188 dol_delete_file($dirthumb.$photo_vignette);
189 }
190 }
191 setEventMessages($langs->trans("FileWasRemoved", $urlfile), null, 'mesgs');
192 } else {
193 setEventMessages($langs->trans("ErrorFailToDeleteFile", $urlfile), null, 'errors');
194 }
195 } elseif ($linkid) { // delete of external link
196 require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
197 $link = new Link($db);
198 $link->fetch($linkid);
199 // Verify the link belongs to the current object to prevent IDOR
200 if (!is_object($object) || $link->objecttype != $object->element || $link->objectid != $object->id) {
202 }
203 $res = $link->delete($user);
204
205 $langs->load('link');
206 if ($res > 0) {
207 setEventMessages($langs->trans("LinkRemoved", $link->label), null, 'mesgs');
208 } else {
209 if (count($link->errors)) {
210 setEventMessages('', $link->errors, 'errors');
211 } else {
212 setEventMessages($langs->trans("ErrorFailedToDeleteLink", $link->label), null, 'errors');
213 }
214 }
215 }
216
217 if (is_object($object) && $object->id > 0) {
218 if (!empty($backtopage)) {
219 header('Location: '.$backtopage);
220 exit;
221 } else {
222 $tmpurl = $_SERVER["PHP_SELF"].'?id='.$object->id.(GETPOST('section_dir', 'alpha') ? '&section_dir='.urlencode(GETPOST('section_dir', 'alpha')) : '').(!empty($withproject) ? '&withproject=1' : '');
223 header('Location: '.$tmpurl);
224 exit;
225 }
226 }
227} elseif ($action == 'confirm_updateline' && GETPOST('save', 'alpha') && GETPOST('link', 'alpha') && !empty($permissiontoadd)) {
228 require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
229
230 $link = new Link($db);
231 $f = $link->fetch(GETPOSTINT('linkid'));
232
233 if ($f > 0) {
234 // Verify the link belongs to the current object to prevent IDOR
235 if (!is_object($object) || $link->objecttype != $object->element || $link->objectid != $object->id) {
237 }
238 $link->url = GETPOST('link', 'alpha');
239 if (substr($link->url, 0, 7) != 'http://'
240 && substr($link->url, 0, 8) != 'https://'
241 && substr($link->url, 0, 7) != 'davs://'
242 && (substr($link->url, 0, 7) != 'file://' || !getDolGlobalString('MAIN_ALLOW_LINK_STARTING_WITH_FILE'))) {
243 $link->url = 'http://'.$link->url;
244 }
245 $link->label = GETPOST('label', 'alphanohtml');
246
247 $shareenabled = GETPOST('shareenabled', 'alpha');
248 if ($shareenabled) {
249 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
250 $link->share = getRandomPassword(true);
251 } else {
252 $link->share = '';
253 }
254 $res = $link->update($user);
255 if ($res <= 0) {
256 setEventMessages($langs->trans("ErrorFailedToUpdateLink", $link->label), $link->errors, 'errors');
257 }
258 } else {
259 //error fetching
260 }
261} elseif ($action == 'renamefile' && GETPOST('renamefilesave', 'alpha') && !empty($permissiontoadd)) {
262 // For documents pages, upload_dir contains already the path to the file from module dir
263 if (!empty($upload_dir)) {
264 $filenamefrom = dol_sanitizeFileName(GETPOST('renamefilefrom', 'alpha'), '_', 0); // Do not remove accents
265 $filenameto = dol_sanitizeFileName(GETPOST('renamefileto', 'alpha'), '_', 0); // Do not remove accents
266
267 // We apply dol_string_nohtmltag also to clean file names (this remove duplicate spaces) because
268 // this function is also applied when we upload and when we make try to download file (by the GETPOST(filename, 'alphanohtml') call).
269 $filenameto = dol_string_nohtmltag($filenameto);
270 if (preg_match('/__.*__/', $filenameto)) {
271 $error++;
272 setEventMessages($langs->trans('ErrorWrongFileName'), null, 'errors');
273 }
274
275 // Check that filename is not the one of a reserved allowed CLI command
276 if (empty($error)) {
277 global $dolibarr_main_restrict_os_commands;
278 if (!empty($dolibarr_main_restrict_os_commands)) {
279 $arrayofallowedcommand = explode(',', $dolibarr_main_restrict_os_commands);
280 $arrayofallowedcommand = array_map('trim', $arrayofallowedcommand);
281 if (in_array(basename($filenameto), $arrayofallowedcommand)) {
282 $error++;
283 $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
284 setEventMessages($langs->trans("ErrorFilenameReserved", basename($filenameto)), null, 'errors');
285 }
286 }
287 }
288
289 if (empty($error) && $filenamefrom != $filenameto) {
290 // For backward compatibility, the file to rename may be stored into an old path (see PRODUCT_USE_OLD_PATH_FOR_PHOTO).
291 // Upload and delete actions already fall back on $upload_dirold, so the rename action must do the same.
292 $dirforfile = $upload_dir;
293 if (!empty($upload_dirold) && !dol_is_file($upload_dir.'/'.$filenamefrom) && dol_is_file($upload_dirold.'/'.$filenamefrom)) {
294 $dirforfile = $upload_dirold;
295 }
296
297 // Security:
298 // Disallow file with some extensions. We rename them.
299 // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code.
300 if (isAFileWithExecutableContent($filenameto) && !getDolGlobalString('MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED')) {
301 // $dirforfile ends with a slash, so be must be sure the medias dir to compare to ends with slash too.
302 $publicmediasdirwithslash = $conf->medias->multidir_output[$conf->entity];
303 if (!preg_match('/\/$/', $publicmediasdirwithslash)) {
304 $publicmediasdirwithslash .= '/';
305 }
306
307 if (strpos($dirforfile, $publicmediasdirwithslash) !== 0) { // We never add .noexe on files into media directory
308 $filenameto .= '.noexe';
309 }
310 }
311
312 if ($filenamefrom && $filenameto) {
313 $srcpath = $dirforfile.'/'.$filenamefrom;
314 $destpath = $dirforfile.'/'.$filenameto;
315 /* 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.
316 if ($modulepart == "ticket" && !dol_is_file($srcpath)) {
317 $srcbis = $conf->agenda->dir_output.'/'.GETPOST('section_dir').$filenamefrom;
318 if (dol_is_file($srcbis)) {
319 $srcpath = $srcbis;
320 $destpath = $conf->agenda->dir_output.'/'.GETPOST('section_dir').$filenameto;
321 }
322 }*/
323
324 $reshook = $hookmanager->initHooks(array('actionlinkedfiles'));
325 $parameters = array('filenamefrom' => $filenamefrom, 'filenameto' => $filenameto, 'upload_dir' => $dirforfile);
326 $reshook = $hookmanager->executeHooks('renameUploadedFile', $parameters, $object);
327
328 if (empty($reshook)) {
329 if (preg_match('/^\./', $filenameto)) {
330 $langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now.
331 setEventMessages($langs->trans("ErrorFilenameCantStartWithDot", $filenameto), null, 'errors');
332 } elseif (!file_exists($destpath)) {
333 $result = dol_move($srcpath, $destpath, '0', 1, 0, 1, [], $object->entity ?? $conf->entity);
334 if ($result) {
335 // Define if we have to generate thumbs or not
336 $generatethumbs = 1;
337 // When we rename a file from the file manager in ecm, we must not regenerate thumbs (not a problem, we do pass here)
338 // When we rename a file from the website module, we must not regenerate thumbs (module = medias in such a case)
339 // but when we rename from a tab "Documents", we must regenerate thumbs
340 if (GETPOST('modulepart', 'aZ09') == 'medias') {
341 $generatethumbs = 0;
342 }
343
344 if ($generatethumbs) {
345 if ($object->id > 0) {
346 // Create thumbs for the new file
347 $object->addThumbs($destpath);
348
349 // Delete thumb files with old name
350 $object->delThumbs($srcpath);
351 }
352 }
353
354 setEventMessages($langs->trans("FileRenamed"), null);
355 } else {
356 $langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now.
357 setEventMessages($langs->trans("ErrorFailToRenameFile", $filenamefrom, $filenameto), null, 'errors');
358 }
359 } else {
360 $langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now.
361 setEventMessages($langs->trans("ErrorDestinationAlreadyExists", $filenameto), null, 'errors');
362 }
363 }
364 }
365 }
366 }
367
368 // Update properties in ECM table
369 if (GETPOSTINT('ecmfileid') > 0) {
370 $shareenabled = GETPOST('shareenabled', 'alpha');
371
372 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
373 $ecmfile = new EcmFiles($db);
374 $result = $ecmfile->fetch(GETPOSTINT('ecmfileid'));
375 if ($result > 0) {
376 if ($shareenabled) {
377 if (empty($ecmfile->share)) {
378 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
379 $ecmfile->share = getRandomPassword(true);
380 }
381 } else {
382 $ecmfile->share = '';
383 }
384 $result = $ecmfile->update($user);
385 if ($result < 0) {
386 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
387 }
388 }
389 }
390}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
Class to manage ECM files.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
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.
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, $nodefault=0)
Return value of a param into GET or POST supervariable.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
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.