dolibarr 21.0.0-alpha
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 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 * or see https://www.gnu.org/
20 */
21
22// Variable $upload_dir must be defined when entering here.
23// Variable $upload_dirold may also exists.
24// Variable $confirm must be defined.
25// 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.
26
27//var_dump($upload_dir);
28//var_dump($upload_dirold);
29
30
31// Protection to understand what happen when submitting files larger than post_max_size
32if (GETPOSTINT('uploadform') && empty($_POST) && empty($_FILES)) {
33 dol_syslog("The PHP parameter 'post_max_size' is too low. All POST parameters and FILES were set to empty.");
34 $langs->loadLangs(array("errors", "install"));
35 print $langs->trans("ErrorFileSizeTooLarge").' ';
36 print $langs->trans("ErrorGoBackAndCorrectParameters");
37 die;
38}
39
40if ((GETPOST('sendit', 'alpha')
41 || GETPOST('linkit', 'restricthtml')
42 || ($action == 'confirm_deletefile' && $confirm == 'yes')
43 || ($action == 'confirm_updateline' && GETPOST('save', 'alpha') && GETPOST('link', 'alpha'))
44 || ($action == 'renamefile' && GETPOST('renamefilesave', 'alpha'))) && empty($permissiontoadd)) {
45 dol_syslog('The file actions_linkedfiles.inc.php was included but parameter $permissiontoadd was not set before.');
46 print 'The file actions_linkedfiles.inc.php was included but parameter $permissiontoadd was not set before.';
47 die;
48}
49
50
51// Submit file/link
52if (GETPOST('sendit', 'alpha') && getDolGlobalString('MAIN_UPLOAD_DOC') && !empty($permissiontoadd)) {
53 if (!empty($_FILES) && is_array($_FILES['userfile'])) {
54 if (is_array($_FILES['userfile']['tmp_name'])) {
55 $userfiles = $_FILES['userfile']['tmp_name'];
56 } else {
57 $userfiles = array($_FILES['userfile']['tmp_name']);
58 }
59
60 foreach ($userfiles as $key => $userfile) {
61 if (empty($_FILES['userfile']['tmp_name'][$key])) {
62 $error++;
63 if ($_FILES['userfile']['error'][$key] == 1 || $_FILES['userfile']['error'][$key] == 2) {
64 setEventMessages($langs->trans('ErrorFileSizeTooLarge'), null, 'errors');
65 } else {
66 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("File")), null, 'errors');
67 }
68 }
69 if (preg_match('/__.*__/', $_FILES['userfile']['name'][$key])) {
70 $error++;
71 setEventMessages($langs->trans('ErrorWrongFileName'), null, 'errors');
72 }
73 }
74
75 if (!$error) {
76 // Define if we have to generate thumbs or not
77 $generatethumbs = 1;
78 if (GETPOST('section_dir', 'alpha')) {
79 $generatethumbs = 0;
80 }
81 $allowoverwrite = (GETPOSTINT('overwritefile') ? 1 : 0);
82
83 if (!empty($upload_dirold) && getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
84 $result = dol_add_file_process($upload_dirold, $allowoverwrite, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs, $object);
85 } elseif (!empty($upload_dir)) {
86 $result = dol_add_file_process($upload_dir, $allowoverwrite, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs, $object);
87 }
88 }
89 }
90} elseif (GETPOST('linkit', 'restricthtml') && getDolGlobalString('MAIN_UPLOAD_DOC') && !empty($permissiontoadd)) {
91 $link = GETPOST('link', 'alpha');
92 if ($link) {
93 if (substr($link, 0, 7) != 'http://' && substr($link, 0, 8) != 'https://' && substr($link, 0, 7) != 'file://' && substr($link, 0, 7) != 'davs://') {
94 $link = 'http://'.$link;
95 }
96
97 // Parse $newUrl
98 $newUrlArray = parse_url($link);
99
100 // Allow external links to svg ?
101 if (!getDolGlobalString('MAIN_ALLOW_SVG_FILES_AS_EXTERNAL_LINKS')) {
102 if (!empty($newUrlArray['path']) && preg_match('/\.svg$/i', $newUrlArray['path'])) {
103 $error++;
104 $langs->load("errors");
105 setEventMessages($langs->trans('ErrorSVGFilesNotAllowedAsLinksWithout', 'MAIN_ALLOW_SVG_FILES_AS_EXTERNAL_LINKS'), null, 'errors');
106 }
107 }
108 // Check URL is external (must refuse local link by default)
109 if (!getDolGlobalString('MAIN_ALLOW_LOCAL_LINKS_AS_EXTERNAL_LINKS')) {
110 // Test $newUrlAray['host'] to check link is external using isIPAllowed() and if not refuse the local link
111 // TODO
112 }
113
114 if (!$error) {
115 dol_add_file_process($upload_dir, 0, 1, 'userfile', '', $link, '', 0);
116 }
117 }
118}
119
120// Delete file/link
121if ($action == 'confirm_deletefile' && $confirm == 'yes' && !empty($permissiontoadd)) {
122 $urlfile = GETPOST('urlfile', 'alpha', 0, null, null, 1);
123 if (GETPOST('section', 'alpha')) {
124 // For a delete from the ECM module, upload_dir is ECM root dir and urlfile contains relative path from upload_dir
125 $file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile;
126 } 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.
127 $urlfile = basename($urlfile);
128 $file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile;
129 if (!empty($upload_dirold)) {
130 $fileold = $upload_dirold."/".$urlfile;
131 }
132 }
133 $linkid = GETPOSTINT('linkid');
134
135 if ($urlfile) {
136 // delete of a file
137 $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
138 $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette (if file is an image)
139
140 $ret = dol_delete_file($file, 0, 0, 0, (is_object($object) ? $object : null));
141 if (!empty($fileold)) {
142 dol_delete_file($fileold, 0, 0, 0, (is_object($object) ? $object : null)); // Delete file using old path
143 }
144
145 if ($ret) {
146 // If it exists, remove thumb.
147 $regs = array();
148 if (preg_match('/(\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff)$/i', $file, $regs)) {
149 $photo_vignette = basename(preg_replace('/'.$regs[0].'/i', '', $file).'_small'.$regs[0]);
150 if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
151 dol_delete_file($dirthumb.$photo_vignette);
152 }
153
154 $photo_vignette = basename(preg_replace('/'.$regs[0].'/i', '', $file).'_mini'.$regs[0]);
155 if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
156 dol_delete_file($dirthumb.$photo_vignette);
157 }
158 }
159 setEventMessages($langs->trans("FileWasRemoved", $urlfile), null, 'mesgs');
160 } else {
161 setEventMessages($langs->trans("ErrorFailToDeleteFile", $urlfile), null, 'errors');
162 }
163 } elseif ($linkid) { // delete of external link
164 require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
165 $link = new Link($db);
166 $link->fetch($linkid);
167 $res = $link->delete($user);
168
169 $langs->load('link');
170 if ($res > 0) {
171 setEventMessages($langs->trans("LinkRemoved", $link->label), null, 'mesgs');
172 } else {
173 if (count($link->errors)) {
174 setEventMessages('', $link->errors, 'errors');
175 } else {
176 setEventMessages($langs->trans("ErrorFailedToDeleteLink", $link->label), null, 'errors');
177 }
178 }
179 }
180
181 if (is_object($object) && $object->id > 0) {
182 if (!empty($backtopage)) {
183 header('Location: '.$backtopage);
184 exit;
185 } else {
186 $tmpurl = $_SERVER["PHP_SELF"].'?id='.$object->id.(GETPOST('section_dir', 'alpha') ? '&section_dir='.urlencode(GETPOST('section_dir', 'alpha')) : '').(!empty($withproject) ? '&withproject=1' : '');
187 header('Location: '.$tmpurl);
188 exit;
189 }
190 }
191} elseif ($action == 'confirm_updateline' && GETPOST('save', 'alpha') && GETPOST('link', 'alpha') && !empty($permissiontoadd)) {
192 require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
193
194 $link = new Link($db);
195 $f = $link->fetch(GETPOSTINT('linkid'));
196 if ($f) {
197 $link->url = GETPOST('link', 'alpha');
198 if (substr($link->url, 0, 7) != 'http://' && substr($link->url, 0, 8) != 'https://' && substr($link->url, 0, 7) != 'file://') {
199 $link->url = 'http://'.$link->url;
200 }
201 $link->label = GETPOST('label', 'alphanohtml');
202 $res = $link->update($user);
203 if (!$res) {
204 setEventMessages($langs->trans("ErrorFailedToUpdateLink", $link->label), null, 'mesgs');
205 }
206 } else {
207 //error fetching
208 }
209} elseif ($action == 'renamefile' && GETPOST('renamefilesave', 'alpha') && !empty($permissiontoadd)) {
210 // For documents pages, upload_dir contains already the path to the file from module dir
211 if (!empty($upload_dir)) {
212 $filenamefrom = dol_sanitizeFileName(GETPOST('renamefilefrom', 'alpha'), '_', 0); // Do not remove accents
213 $filenameto = dol_sanitizeFileName(GETPOST('renamefileto', 'alpha'), '_', 0); // Do not remove accents
214
215 // We apply dol_string_nohtmltag also to clean file names (this remove duplicate spaces) because
216 // this function is also applied when we upload and when we make try to download file (by the GETPOST(filename, 'alphanohtml') call).
217 $filenameto = dol_string_nohtmltag($filenameto);
218 if (preg_match('/__.*__/', $filenameto)) {
219 $error++;
220 setEventMessages($langs->trans('ErrorWrongFileName'), null, 'errors');
221 }
222
223 // Check that filename is not the one of a reserved allowed CLI command
224 if (empty($error)) {
225 global $dolibarr_main_restrict_os_commands;
226 if (!empty($dolibarr_main_restrict_os_commands)) {
227 $arrayofallowedcommand = explode(',', $dolibarr_main_restrict_os_commands);
228 $arrayofallowedcommand = array_map('trim', $arrayofallowedcommand);
229 if (in_array(basename($filenameto), $arrayofallowedcommand)) {
230 $error++;
231 $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
232 setEventMessages($langs->trans("ErrorFilenameReserved", basename($filenameto)), null, 'errors');
233 }
234 }
235 }
236
237 if (empty($error) && $filenamefrom != $filenameto) {
238 // Security:
239 // Disallow file with some extensions. We rename them.
240 // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code.
241 if (isAFileWithExecutableContent($filenameto) && !getDolGlobalString('MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED')) {
242 // $upload_dir ends with a slash, so be must be sure the medias dir to compare to ends with slash too.
243 $publicmediasdirwithslash = $conf->medias->multidir_output[$conf->entity];
244 if (!preg_match('/\/$/', $publicmediasdirwithslash)) {
245 $publicmediasdirwithslash .= '/';
246 }
247
248 if (strpos($upload_dir, $publicmediasdirwithslash) !== 0) { // We never add .noexe on files into media directory
249 $filenameto .= '.noexe';
250 }
251 }
252
253 if ($filenamefrom && $filenameto) {
254 $srcpath = $upload_dir.'/'.$filenamefrom;
255 $destpath = $upload_dir.'/'.$filenameto;
256 /* 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.
257 if ($modulepart == "ticket" && !dol_is_file($srcpath)) {
258 $srcbis = $conf->agenda->dir_output.'/'.GETPOST('section_dir').$filenamefrom;
259 if (dol_is_file($srcbis)) {
260 $srcpath = $srcbis;
261 $destpath = $conf->agenda->dir_output.'/'.GETPOST('section_dir').$filenameto;
262 }
263 }*/
264
265 $reshook = $hookmanager->initHooks(array('actionlinkedfiles'));
266 $parameters = array('filenamefrom' => $filenamefrom, 'filenameto' => $filenameto, 'upload_dir' => $upload_dir);
267 $reshook = $hookmanager->executeHooks('renameUploadedFile', $parameters, $object);
268
269 if (empty($reshook)) {
270 if (preg_match('/^\./', $filenameto)) {
271 $langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now.
272 setEventMessages($langs->trans("ErrorFilenameCantStartWithDot", $filenameto), null, 'errors');
273 } elseif (!file_exists($destpath)) {
274 $result = dol_move($srcpath, $destpath);
275 if ($result) {
276 // Define if we have to generate thumbs or not
277 $generatethumbs = 1;
278 // When we rename a file from the file manager in ecm, we must not regenerate thumbs (not a problem, we do pass here)
279 // When we rename a file from the website module, we must not regenerate thumbs (module = medias in such a case)
280 // but when we rename from a tab "Documents", we must regenerate thumbs
281 if (GETPOST('modulepart', 'aZ09') == 'medias') {
282 $generatethumbs = 0;
283 }
284
285 if ($generatethumbs) {
286 if ($object->id > 0) {
287 // Create thumbs for the new file
288 $object->addThumbs($destpath);
289
290 // Delete thumb files with old name
291 $object->delThumbs($srcpath);
292 }
293 }
294
295 setEventMessages($langs->trans("FileRenamed"), null);
296 } else {
297 $langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now.
298 setEventMessages($langs->trans("ErrorFailToRenameFile", $filenamefrom, $filenameto), null, 'errors');
299 }
300 } else {
301 $langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now.
302 setEventMessages($langs->trans("ErrorDestinationAlreadyExists", $filenameto), null, 'errors');
303 }
304 }
305 }
306 }
307 }
308
309 // Update properties in ECM table
310 if (GETPOSTINT('ecmfileid') > 0) {
311 $shareenabled = GETPOST('shareenabled', 'alpha');
312
313 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
314 $ecmfile = new EcmFiles($db);
315 $result = $ecmfile->fetch(GETPOSTINT('ecmfileid'));
316 if ($result > 0) {
317 if ($shareenabled) {
318 if (empty($ecmfile->share)) {
319 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
320 $ecmfile->share = getRandomPassword(true);
321 }
322 } else {
323 $ecmfile->share = '';
324 }
325 $result = $ecmfile->update($user);
326 if ($result < 0) {
327 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
328 }
329 }
330 }
331}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
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_add_file_process($upload_dir, $allowoverwrite=0, $updatesessionordb=0, $varfiles='addedfile', $savingdocmask='', $link=null, $trackid='', $generatethumbs=1, $object=null)
Get and save an upload file (for example after submitting a new file a mail form).
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array())
Move a file into another name.
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.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
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.