dolibarr  16.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  *
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
31 if (GETPOST('uploadform', 'int') && 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 
39 if ((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 paramater $permissiontoadd as not set before.');
45  print 'The file actions_linkedfiles.inc.php was included but paramater $permissiontoadd as not set before.';
46  die;
47 }
48 
49 
50 // Submit file/link
51 if (GETPOST('sendit', 'alpha') && !empty($conf->global->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 = (GETPOST('overwritefile', 'int') ? 1 : 0);
81 
82  if (!empty($upload_dirold) && !empty($conf->global->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') && !empty($conf->global->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  dol_add_file_process($upload_dir, 0, 1, 'userfile', null, $link, '', 0);
96  }
97 }
98 
99 
100 // Delete file/link
101 if ($action == 'confirm_deletefile' && $confirm == 'yes' && !empty($permissiontoadd)) {
102  $urlfile = GETPOST('urlfile', 'alpha', 0, null, null, 1); // Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP).
103  if (GETPOST('section', 'alpha')) {
104  // For a delete from the ECM module, upload_dir is ECM root dir and urlfile contains relative path from upload_dir
105  $file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile;
106  } 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.
107  {
108  $urlfile = basename($urlfile);
109  $file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile;
110  if (!empty($upload_dirold)) {
111  $fileold = $upload_dirold."/".$urlfile;
112  }
113  }
114  $linkid = GETPOST('linkid', 'int');
115 
116  if ($urlfile) {
117  // delete of a file
118  $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
119  $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette (if file is an image)
120 
121  $ret = dol_delete_file($file, 0, 0, 0, (is_object($object) ? $object : null));
122  if (!empty($fileold)) {
123  dol_delete_file($fileold, 0, 0, 0, (is_object($object) ? $object : null)); // Delete file using old path
124  }
125 
126  if ($ret) {
127  // If it exists, remove thumb.
128  $regs = array();
129  if (preg_match('/(\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff)$/i', $file, $regs)) {
130  $photo_vignette = basename(preg_replace('/'.$regs[0].'/i', '', $file).'_small'.$regs[0]);
131  if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
132  dol_delete_file($dirthumb.$photo_vignette);
133  }
134 
135  $photo_vignette = basename(preg_replace('/'.$regs[0].'/i', '', $file).'_mini'.$regs[0]);
136  if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
137  dol_delete_file($dirthumb.$photo_vignette);
138  }
139  }
140  setEventMessages($langs->trans("FileWasRemoved", $urlfile), null, 'mesgs');
141  } else {
142  setEventMessages($langs->trans("ErrorFailToDeleteFile", $urlfile), null, 'errors');
143  }
144  } elseif ($linkid) { // delete of external link
145  require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
146  $link = new Link($db);
147  $link->fetch($linkid);
148  $res = $link->delete($user);
149 
150  $langs->load('link');
151  if ($res > 0) {
152  setEventMessages($langs->trans("LinkRemoved", $link->label), null, 'mesgs');
153  } else {
154  if (count($link->errors)) {
155  setEventMessages('', $link->errors, 'errors');
156  } else {
157  setEventMessages($langs->trans("ErrorFailedToDeleteLink", $link->label), null, 'errors');
158  }
159  }
160  }
161 
162  if (is_object($object) && $object->id > 0) {
163  if ($backtopage) {
164  header('Location: '.$backtopage);
165  exit;
166  } else {
167  $tmpurl = $_SERVER["PHP_SELF"].'?id='.$object->id.(GETPOST('section_dir', 'alpha') ? '&section_dir='.urlencode(GETPOST('section_dir', 'alpha')) : '').(!empty($withproject) ? '&withproject=1' : '');
168  header('Location: '.$tmpurl);
169  exit;
170  }
171  }
172 } elseif ($action == 'confirm_updateline' && GETPOST('save', 'alpha') && GETPOST('link', 'alpha') && !empty($permissiontoadd)) {
173  require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
174  $langs->load('link');
175  $link = new Link($db);
176  $f = $link->fetch(GETPOST('linkid', 'int'));
177  if ($f) {
178  $link->url = GETPOST('link', 'alpha');
179  if (substr($link->url, 0, 7) != 'http://' && substr($link->url, 0, 8) != 'https://' && substr($link->url, 0, 7) != 'file://') {
180  $link->url = 'http://'.$link->url;
181  }
182  $link->label = GETPOST('label', 'alphanohtml');
183  $res = $link->update($user);
184  if (!$res) {
185  setEventMessages($langs->trans("ErrorFailedToUpdateLink", $link->label), null, 'mesgs');
186  }
187  } else {
188  //error fetching
189  }
190 } elseif ($action == 'renamefile' && GETPOST('renamefilesave', 'alpha') && !empty($permissiontoadd)) {
191  // For documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile.
192  if (!empty($upload_dir)) {
193  $filenamefrom = dol_sanitizeFileName(GETPOST('renamefilefrom', 'alpha'), '_', 0); // Do not remove accents
194  $filenameto = dol_sanitizeFileName(GETPOST('renamefileto', 'alpha'), '_', 0); // Do not remove accents
195 
196  // We apply dol_string_nohtmltag also to clean file names (this remove duplicate spaces) because
197  // this function is also applied when we upload and when we make try to download file (by the GETPOST(filename, 'alphanohtml') call).
198  $filenameto = dol_string_nohtmltag($filenameto);
199  if (preg_match('/__.*__/', $filenameto)) {
200  $error++;
201  setEventMessages($langs->trans('ErrorWrongFileName'), null, 'errors');
202  }
203  if (!$error && $filenamefrom != $filenameto) {
204  // Security:
205  // Disallow file with some extensions. We rename them.
206  // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code.
207  if (isAFileWithExecutableContent($filenameto) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED)) {
208  // $upload_dir ends with a slash, so be must be sure the medias dir to compare to ends with slash too.
209  $publicmediasdirwithslash = $conf->medias->multidir_output[$conf->entity];
210  if (!preg_match('/\/$/', $publicmediasdirwithslash)) {
211  $publicmediasdirwithslash .= '/';
212  }
213 
214  if (strpos($upload_dir, $publicmediasdirwithslash) !== 0) { // We never add .noexe on files into media directory
215  $filenameto .= '.noexe';
216  }
217  }
218 
219  if ($filenamefrom && $filenameto) {
220  $srcpath = $upload_dir.'/'.$filenamefrom;
221  $destpath = $upload_dir.'/'.$filenameto;
222 
223  $reshook = $hookmanager->initHooks(array('actionlinkedfiles'));
224  $parameters = array('filenamefrom' => $filenamefrom, 'filenameto' => $filenameto, 'upload_dir' => $upload_dir);
225  $reshook = $hookmanager->executeHooks('renameUploadedFile', $parameters, $object);
226 
227  if (empty($reshook)) {
228  if (preg_match('/^\./', $filenameto)) {
229  $langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now.
230  setEventMessages($langs->trans("ErrorFilenameCantStartWithDot", $filenameto), null, 'errors');
231  } elseif (!file_exists($destpath)) {
232  $result = dol_move($srcpath, $destpath);
233  if ($result) {
234  // Define if we have to generate thumbs or not
235  $generatethumbs = 1;
236  // When we rename a file from the file manager in ecm, we must not regenerate thumbs (not a problem, we do pass here)
237  // When we rename a file from the website module, we must not regenerate thumbs (module = medias in such a case)
238  // but when we rename from a tab "Documents", we must regenerate thumbs
239  if (GETPOST('modulepart') == 'medias') {
240  $generatethumbs = 0;
241  }
242 
243  if ($generatethumbs) {
244  if ($object->id) {
245  $object->addThumbs($destpath);
246  }
247 
248  // TODO Add revert function of addThumbs to remove thumbs with old name
249  //$object->delThumbs($srcpath);
250  }
251 
252  setEventMessages($langs->trans("FileRenamed"), null);
253  } else {
254  $langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now.
255  setEventMessages($langs->trans("ErrorFailToRenameFile", $filenamefrom, $filenameto), null, 'errors');
256  }
257  } else {
258  $langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now.
259  setEventMessages($langs->trans("ErrorDestinationAlreadyExists", $filenameto), null, 'errors');
260  }
261  }
262  }
263  }
264  }
265 
266  // Update properties in ECM table
267  if (GETPOST('ecmfileid', 'int') > 0) {
268  $shareenabled = GETPOST('shareenabled', 'alpha');
269 
270  include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
271  $ecmfile = new EcmFiles($db);
272  $result = $ecmfile->fetch(GETPOST('ecmfileid', 'int'));
273  if ($result > 0) {
274  if ($shareenabled) {
275  if (empty($ecmfile->share)) {
276  require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
277  $ecmfile->share = getRandomPassword(true);
278  }
279  } else {
280  $ecmfile->share = '';
281  }
282  $result = $ecmfile->update($user);
283  if ($result < 0) {
284  setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
285  }
286  }
287  }
288 }
dol_sanitizeFileName
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
Definition: functions.lib.php:1226
dol_osencode
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
Definition: functions.lib.php:8499
GETPOST
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
Definition: functions.lib.php:484
dol_add_file_process
dol_add_file_process($upload_dir, $allowoverwrite=0, $donotupdatesession=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).
Definition: files.lib.php:1634
getRandomPassword
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
Definition: security2.lib.php:454
dol_delete_file
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.
Definition: files.lib.php:1231
dol_string_nohtmltag
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
Definition: functions.lib.php:6694
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1603
EcmFiles
Class to manage ECM files.
Definition: ecmfiles.class.php:35
isAFileWithExecutableContent
isAFileWithExecutableContent($filename)
Return if a file can contains executable content.
Definition: functions.lib.php:10863
setEventMessages
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
Definition: functions.lib.php:8137
dol_move
dol_move($srcfile, $destfile, $newmask=0, $overwriteifexists=1, $testvirus=0, $indexdatabase=1)
Move a file into another name.
Definition: files.lib.php:855