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