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