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