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