dolibarr 23.0.3
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 $res = $link->delete($user);
193
194 $langs->load('link');
195 if ($res > 0) {
196 setEventMessages($langs->trans("LinkRemoved", $link->label), null, 'mesgs');
197 } else {
198 if (count($link->errors)) {
199 setEventMessages('', $link->errors, 'errors');
200 } else {
201 setEventMessages($langs->trans("ErrorFailedToDeleteLink", $link->label), null, 'errors');
202 }
203 }
204 }
205
206 if (is_object($object) && $object->id > 0) {
207 if (!empty($backtopage)) {
208 header('Location: '.$backtopage);
209 exit;
210 } else {
211 $tmpurl = $_SERVER["PHP_SELF"].'?id='.$object->id.(GETPOST('section_dir', 'alpha') ? '&section_dir='.urlencode(GETPOST('section_dir', 'alpha')) : '').(!empty($withproject) ? '&withproject=1' : '');
212 header('Location: '.$tmpurl);
213 exit;
214 }
215 }
216} elseif ($action == 'confirm_updateline' && GETPOST('save', 'alpha') && GETPOST('link', 'alpha') && !empty($permissiontoadd)) {
217 require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
218
219 $link = new Link($db);
220 $f = $link->fetch(GETPOSTINT('linkid'));
221 if ($f) {
222 $link->url = GETPOST('link', 'alpha');
223 if (substr($link->url, 0, 7) != 'http://' && substr($link->url, 0, 8) != 'https://' && substr($link->url, 0, 7) != 'file://') {
224 $link->url = 'http://'.$link->url;
225 }
226 $link->label = GETPOST('label', 'alphanohtml');
227
228 $shareenabled = GETPOST('shareenabled', 'alpha');
229 if ($shareenabled) {
230 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
231 $link->share = getRandomPassword(true);
232 } else {
233 $link->share = '';
234 }
235 $res = $link->update($user);
236 if (!$res) {
237 setEventMessages($langs->trans("ErrorFailedToUpdateLink", $link->label), null, 'mesgs');
238 }
239 } else {
240 //error fetching
241 }
242} elseif ($action == 'renamefile' && GETPOST('renamefilesave', 'alpha') && !empty($permissiontoadd)) {
243 // For documents pages, upload_dir contains already the path to the file from module dir
244 if (!empty($upload_dir)) {
245 $filenamefrom = dol_sanitizeFileName(GETPOST('renamefilefrom', 'alpha'), '_', 0); // Do not remove accents
246 $filenameto = dol_sanitizeFileName(GETPOST('renamefileto', 'alpha'), '_', 0); // Do not remove accents
247
248 // We apply dol_string_nohtmltag also to clean file names (this remove duplicate spaces) because
249 // this function is also applied when we upload and when we make try to download file (by the GETPOST(filename, 'alphanohtml') call).
250 $filenameto = dol_string_nohtmltag($filenameto);
251 if (preg_match('/__.*__/', $filenameto)) {
252 $error++;
253 setEventMessages($langs->trans('ErrorWrongFileName'), null, 'errors');
254 }
255
256 // Check that filename is not the one of a reserved allowed CLI command
257 if (empty($error)) {
258 global $dolibarr_main_restrict_os_commands;
259 if (!empty($dolibarr_main_restrict_os_commands)) {
260 $arrayofallowedcommand = explode(',', $dolibarr_main_restrict_os_commands);
261 $arrayofallowedcommand = array_map('trim', $arrayofallowedcommand);
262 if (in_array(basename($filenameto), $arrayofallowedcommand)) {
263 $error++;
264 $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
265 setEventMessages($langs->trans("ErrorFilenameReserved", basename($filenameto)), null, 'errors');
266 }
267 }
268 }
269
270 if (empty($error) && $filenamefrom != $filenameto) {
271 // Security:
272 // Disallow file with some extensions. We rename them.
273 // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code.
274 if (isAFileWithExecutableContent($filenameto) && !getDolGlobalString('MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED')) {
275 // $upload_dir ends with a slash, so be must be sure the medias dir to compare to ends with slash too.
276 $publicmediasdirwithslash = $conf->medias->multidir_output[$conf->entity];
277 if (!preg_match('/\/$/', $publicmediasdirwithslash)) {
278 $publicmediasdirwithslash .= '/';
279 }
280
281 if (strpos($upload_dir, $publicmediasdirwithslash) !== 0) { // We never add .noexe on files into media directory
282 $filenameto .= '.noexe';
283 }
284 }
285
286 if ($filenamefrom && $filenameto) {
287 $srcpath = $upload_dir.'/'.$filenamefrom;
288 $destpath = $upload_dir.'/'.$filenameto;
289 /* 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.
290 if ($modulepart == "ticket" && !dol_is_file($srcpath)) {
291 $srcbis = $conf->agenda->dir_output.'/'.GETPOST('section_dir').$filenamefrom;
292 if (dol_is_file($srcbis)) {
293 $srcpath = $srcbis;
294 $destpath = $conf->agenda->dir_output.'/'.GETPOST('section_dir').$filenameto;
295 }
296 }*/
297
298 $reshook = $hookmanager->initHooks(array('actionlinkedfiles'));
299 $parameters = array('filenamefrom' => $filenamefrom, 'filenameto' => $filenameto, 'upload_dir' => $upload_dir);
300 $reshook = $hookmanager->executeHooks('renameUploadedFile', $parameters, $object);
301
302 if (empty($reshook)) {
303 if (preg_match('/^\./', $filenameto)) {
304 $langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now.
305 setEventMessages($langs->trans("ErrorFilenameCantStartWithDot", $filenameto), null, 'errors');
306 } elseif (!file_exists($destpath)) {
307 $result = dol_move($srcpath, $destpath, '0', 1, 0, 1, [], $object->entity ?? $conf->entity);
308 if ($result) {
309 // Define if we have to generate thumbs or not
310 $generatethumbs = 1;
311 // When we rename a file from the file manager in ecm, we must not regenerate thumbs (not a problem, we do pass here)
312 // When we rename a file from the website module, we must not regenerate thumbs (module = medias in such a case)
313 // but when we rename from a tab "Documents", we must regenerate thumbs
314 if (GETPOST('modulepart', 'aZ09') == 'medias') {
315 $generatethumbs = 0;
316 }
317
318 if ($generatethumbs) {
319 if ($object->id > 0) {
320 // Create thumbs for the new file
321 $object->addThumbs($destpath);
322
323 // Delete thumb files with old name
324 $object->delThumbs($srcpath);
325 }
326 }
327
328 setEventMessages($langs->trans("FileRenamed"), null);
329 } else {
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("ErrorFailToRenameFile", $filenamefrom, $filenameto), null, 'errors');
332 }
333 } else {
334 $langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now.
335 setEventMessages($langs->trans("ErrorDestinationAlreadyExists", $filenameto), null, 'errors');
336 }
337 }
338 }
339 }
340 }
341
342 // Update properties in ECM table
343 if (GETPOSTINT('ecmfileid') > 0) {
344 $shareenabled = GETPOST('shareenabled', 'alpha');
345
346 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
347 $ecmfile = new EcmFiles($db);
348 $result = $ecmfile->fetch(GETPOSTINT('ecmfileid'));
349 if ($result > 0) {
350 if ($shareenabled) {
351 if (empty($ecmfile->share)) {
352 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
353 $ecmfile->share = getRandomPassword(true);
354 }
355 } else {
356 $ecmfile->share = '';
357 }
358 $result = $ecmfile->update($user);
359 if ($result < 0) {
360 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
361 }
362 }
363 }
364}
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.
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.