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