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