dolibarr 22.0.5
file_card.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2008-2020 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
4 * Copyright (C) 2025 MDW <mdeweerd@users.noreply.github.com>
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 */
19
26// Load Dolibarr environment
27require '../main.inc.php';
28require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
29require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php';
30require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
31require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
32require_once DOL_DOCUMENT_ROOT.'/core/lib/ecm.lib.php';
33require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
34
45// Load translation files required by page
46$langs->loadLangs(array('ecm', 'companies', 'other', 'users', 'orders', 'propal', 'bills', 'contracts', 'categories'));
47
48$action = GETPOST('action', 'aZ09');
49$cancel = GETPOST('cancel', 'alpha');
50$backtopage = GETPOST('backtopage', 'alpha');
51
52// Get parameters
53$socid = GETPOSTINT("socid");
54
55// Security check
56if ($user->socid > 0) {
57 $action = '';
58 $socid = $user->socid;
59}
60
61$limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit;
62$sortfield = GETPOST('sortfield', 'aZ09comma');
63$sortorder = GETPOST('sortorder', 'aZ09comma');
64$page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page");
65if (empty($page) || $page == -1) {
66 $page = 0;
67} // If $page is not defined, or '' or -1
68$offset = $limit * $page;
69$pageprev = $page - 1;
70$pagenext = $page + 1;
71if (!$sortorder) {
72 $sortorder = "ASC";
73}
74if (!$sortfield) {
75 $sortfield = "label";
76}
77
78$section = GETPOST("section", 'alpha');
79if (!$section) {
80 dol_print_error(null, 'Error, section parameter missing');
81 exit;
82}
83$urlfile = (string) dol_sanitizePathName(GETPOST("urlfile"), '_', 0);
84if (!$urlfile) {
85 dol_print_error(null, "ErrorParamNotDefined");
86 exit;
87}
88
89// Load ecm object
90$ecmdir = new EcmDirectory($db);
91$result = $ecmdir->fetch(GETPOSTINT("section"));
92if (!($result > 0)) {
93 dol_print_error($db, $ecmdir->error);
94 exit;
95}
96$relativepath = $ecmdir->getRelativePath();
97$upload_dir = $conf->ecm->dir_output.'/'.$relativepath;
98
99$fullpath = $conf->ecm->dir_output.'/'.$relativepath.$urlfile;
100
101$relativetodocument = 'ecm/'.$relativepath; // $relativepath is relative to ECM dir, we need relative to document
102$filepath = $relativepath.$urlfile;
103$filepathtodocument = $relativetodocument.$urlfile;
104
105// Try to load object from index
106$object = new EcmFiles($db);
107$extrafields = new ExtraFields($db);
108// fetch optionals attributes and labels
109$extrafields->fetch_name_optionals_label($object->table_element);
110
111$result = $object->fetch(0, '', $filepathtodocument);
112if ($result < 0) {
113 dol_print_error($db, $object->error, $object->errors);
114 exit;
115}
116
117// Permissions
118$permissiontoread = $user->hasRight('ecm', 'read');
119$permissiontoadd = $user->hasRight('ecm', 'setup');
120$permissiontoupload = $user->hasRight('ecm', 'upload');
121
122if (!$permissiontoread) {
124}
125
126
127/*
128 * Actions
129 */
130
131if ($cancel) {
132 $action = '';
133 if ($backtopage) {
134 header("Location: ".$backtopage);
135 exit;
136 } else {
137 header('Location: '.$_SERVER["PHP_SELF"].'?urlfile='.urlencode($urlfile).'&section='.urlencode($section).($module ? '&module='.urlencode($module) : ''));
138 exit;
139 }
140}
141
142// Rename file
143if ($action == 'update' && $permissiontoadd) {
144 $error = 0;
145
146 $oldlabel = GETPOST('urlfile', 'alpha');
147 $newlabel = dol_sanitizeFileName(GETPOST('label', 'alpha'), '_', 0);
148 $shareenabled = GETPOST('shareenabled', 'alpha');
149
150 //$db->begin();
151
152 $olddir = $ecmdir->getRelativePath(0); // Relative to ecm
153 $olddirrelativetodocument = 'ecm/'.$olddir; // Relative to document
154 $newdirrelativetodocument = 'ecm/'.$olddir;
155 $olddir = $conf->ecm->dir_output.'/'.$olddir;
156 $newdir = $olddir;
157
158 $oldfile = $olddir.$oldlabel;
159 $newfile = $newdir.$newlabel;
160 $newfileformove = $newfile;
161 // If old file end with .noexe, new file must also end with .noexe
162 if (preg_match('/\.noexe$/', $oldfile) && !preg_match('/\.noexe$/', $newfileformove)) {
163 $newfileformove .= '.noexe';
164 }
165 //var_dump($oldfile);var_dump($newfile);exit;
166
167 // Now we update index of file
168 $db->begin();
169 //print $oldfile.' - '.$newfile;
170 if ($newlabel != $oldlabel && dol_is_file($newfileformove)) {
171 // Do not overwrite another file of the directory
172 $langs->load('errors');
173 setEventMessages($langs->trans('ErrorDestinationAlreadyExists', $newlabel), null, 'errors');
174 $error++;
175 }
176 if (!$error && $newlabel != $oldlabel) {
177 $result = dol_move($oldfile, $newfileformove); // This include update of database
178 if (!$result) {
179 $langs->load('errors');
180 setEventMessages($langs->trans('ErrorFailToRenameFile', $oldfile, $newfile), null, 'errors');
181 $error++;
182 }
183
184 // Reload object after the move
185 $result = $object->fetch(0, '', $newdirrelativetodocument.$newlabel);
186 if ($result < 0) {
187 dol_print_error($db, $object->error, $object->errors);
188 exit;
189 }
190 }
191
192 if (!$error) {
193 if ($shareenabled) {
194 // Keep the current key: a new one would break the links already sent
195 if (empty($object->share)) {
196 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
197 $object->share = getRandomPassword(true);
198 }
199 } else {
200 $object->share = '';
201 }
202
203 if ($object->id > 0) {
204 $ret = $extrafields->setOptionalsFromPost(null, $object);
205 if ($ret < 0) {
206 $error++;
207 }
208 if (!$error) {
209 // Actions on extra fields
210 $result = $object->insertExtraFields();
211 if ($result < 0) {
212 setEventMessages($object->error, $object->errors, 'errors');
213 $error++;
214 }
215 }
216 // Call update to set the share key
217 $result = $object->update($user);
218 if ($result < 0) {
219 setEventMessages($object->error, $object->errors, 'warnings');
220 }
221 } else {
222 // Call create to insert record
223 $object->entity = $conf->entity;
224 $object->filepath = preg_replace('/[\\/]+$/', '', $newdirrelativetodocument);
225 $object->filename = $newlabel;
226 $object->label = md5_file(dol_osencode($newfileformove)); // hash of file content
227 $object->fullpath_orig = '';
228 $object->gen_or_uploaded = 'unknown';
229 $object->description = ''; // indexed content
230 $object->keywords = ''; // keyword content
231 $result = $object->create($user);
232 if ($result < 0) {
233 setEventMessages($object->error, $object->errors, 'warnings');
234 }
235 }
236 }
237
238 if (!$error) {
239 $db->commit();
240
241 $urlfile = $newlabel;
242 // If old file end with .noexe, new file must also end with .noexe
243 if (preg_match('/\.noexe$/', $newfileformove)) {
244 $urlfile .= '.noexe';
245 }
246
247 header('Location: '.$_SERVER["PHP_SELF"].'?urlfile='.urlencode($urlfile).'&section='.urlencode($section));
248 exit;
249 } else {
250 $db->rollback();
251 }
252}
253
254
255
256/*
257 * View
258 */
259
260$form = new Form($db);
261
262llxHeader('', '', '', '', 0, 0, '', '', '', 'mod-ecm page-file_card');
263
264$object->section_id = $ecmdir->id;
265$object->label = $urlfile;
266$head = ecm_file_prepare_head($object);
267
268if ($action == 'edit') {
269 print '<form name="update" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
270 print '<input type="hidden" name="token" value="'.newToken().'">';
271 print '<input type="hidden" name="section" value="'.$section.'">';
272 print '<input type="hidden" name="urlfile" value="'.$urlfile.'">';
273 print '<input type="hidden" name="module" value="'.$module.'">';
274 print '<input type="hidden" name="action" value="update">';
275 print '<input type="hidden" name="id" value="'.$object->id.'">';
276}
277
278print dol_get_fiche_head($head, 'card', $langs->trans("File"), -1, 'generic');
279
280
281$s = '';
282$tmpecmdir = new EcmDirectory($db); // Need to create a new one
283$tmpecmdir->fetch($ecmdir->id);
284$result = 1;
285$i = 0;
286while ($tmpecmdir && $result > 0) {
287 $tmpecmdir->ref = $tmpecmdir->label;
288 $s = $tmpecmdir->getNomUrl(1).$s;
289 if ($tmpecmdir->fk_parent) {
290 $s = ' -> '.$s;
291 $result = $tmpecmdir->fetch($tmpecmdir->fk_parent);
292 } else {
293 $tmpecmdir = 0;
294 }
295 $i++;
296}
297
298$urlfiletoshow = preg_replace('/\.noexe$/', '', $urlfile);
299
300$s = img_picto('', 'object_dir').' <a href="'.DOL_URL_ROOT.'/ecm/index.php">'.$langs->trans("ECMRoot").'</a> -> '.$s.' -> ';
301if ($action == 'edit') {
302 $s .= '<input type="text" name="label" class="quatrevingtpercent" value="'.$urlfiletoshow.'">';
303} else {
304 $s .= $urlfiletoshow;
305}
306
307$linkback = '';
308if ($backtopage) {
309 $linkback = '<a href="'.$backtopage.'">'.$langs->trans("BackToTree").'</a>';
310}
311
312$object->ref = ''; // Force to hide ref
313dol_banner_tab($object, '', $linkback, 0, '', '', $s);
314
315print '<div class="fichecenter">';
316
317print '<div class="underbanner clearboth"></div>';
318print '<table class="border centpercent tableforfield">';
319print '<tr><td class="titlefieldcreate">'.$langs->trans("ECMCreationDate").'</td><td>';
320print dol_print_date(dol_filemtime($fullpath), 'dayhour');
321print '</td></tr>';
322/*print '<tr><td>'.$langs->trans("ECMDirectoryForFiles").'</td><td>';
323print '/ecm/'.$relativepath;
324print '</td></tr>';
325print '<tr><td>'.$langs->trans("ECMNbOfDocs").'</td><td>';
326print count($filearray);
327print '</td></tr>';
328print '<tr><td>'.$langs->trans("TotalSizeOfAttachedFiles").'</td><td>';
329print dol_print_size($totalsize);
330print '</td></tr>';
331*/
332
333// Hash of file content
334print '<tr><td>'.$langs->trans("HashOfFileContent").'</td><td>';
335$object = new EcmFiles($db);
336$object->fetch(0, '', $filepathtodocument);
337if (!empty($object->label)) {
338 print $object->label;
339} else {
340 print img_warning().' '.$langs->trans("FileNotYetIndexedInDatabase");
341}
342print '</td></tr>';
343
344// Define $urlwithroot
345$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
346$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
347//$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
348
349// Link for internal download
350print '<tr><td>';
351print $form->textwithpicto($langs->trans("DirectDownloadInternalLink"), $langs->trans("PrivateDownloadLinkDesc"));
352print '</td><td>';
353$modulepart = 'ecm';
354$forcedownload = 1;
355$rellink = '/document.php?modulepart='.$modulepart;
356if ($forcedownload) {
357 $rellink .= '&attachment=1';
358}
359if (!empty($object->entity)) {
360 $rellink .= '&entity='.$object->entity;
361}
362$rellink .= '&file='.urlencode($filepath);
363$fulllink = $urlwithroot.$rellink;
364print img_picto('', 'globe').' ';
365if ($action != 'edit') {
366 print '<input type="text" class="maxquatrevingtpercent widthcentpercentminusxx small" id="downloadinternallink" name="downloadinternellink" value="'.dol_escape_htmltag($fulllink).'">';
367} else {
368 print $fulllink;
369}
370if ($action != 'edit') {
371 print ' <a href="'.$fulllink.'">'.img_picto($langs->trans("Download"), 'download', 'class="opacitymedium paddingrightonly"').'</a>'; // No target here.
372}
373print '</td></tr>';
374
375// Link for direct external download
376print '<tr><td>';
377if ($action != 'edit') {
378 print $form->textwithpicto($langs->trans("DirectDownloadLink"), $langs->trans("PublicDownloadLinkDesc"));
379} else {
380 print $form->textwithpicto($langs->trans("FileSharedViaALink"), $langs->trans("PublicDownloadLinkDesc"));
381}
382print '</td><td>';
383if (!empty($object->share)) {
384 if ($action != 'edit') {
385 $forcedownload = 0;
386
387 $paramlink = '';
388 if (!empty($object->share)) {
389 $paramlink .= ($paramlink ? '&' : '').'hashp='.$object->share; // Hash for public share
390 }
391 if ($forcedownload) {
392 $paramlink .= ($paramlink ? '&' : '').'attachment=1';
393 }
394
395 $fulllink = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
396 //if (!empty($object->ref)) $fulllink.='&hashn='.$object->ref; // Hash of file path
397 //elseif (!empty($object->label)) $fulllink.='&hashc='.$object->label; // Hash of file content
398
399 print img_picto('', 'globe').' ';
400 if ($action != 'edit') {
401 print '<input type="text" class="maxquatrevingtpercent widthcentpercentminusxx nopadding small" id="downloadlink" name="downloadexternallink" value="'.dol_escape_htmltag($fulllink).'">';
402 } else {
403 print $fulllink;
404 }
405 if ($action != 'edit') {
406 print ' <a href="'.$fulllink.'">'.img_picto($langs->trans("Download"), 'download', 'class="opacitymedium paddingrightonly"').'</a>'; // No target here
407 }
408 } else {
409 print '<input type="checkbox" name="shareenabled"'.($object->share ? ' checked="checked"' : '').' /> ';
410 }
411} else {
412 if ($action != 'edit') {
413 print '<span class="opacitymedium">'.$langs->trans("FileNotShared").'</span>';
414 } else {
415 print '<input type="checkbox" name="shareenabled"'.($object->share ? ' checked="checked"' : '').' /> ';
416 }
417}
418print '</td>';
419print '</tr>';
420print $object->showOptionals($extrafields, ($action == 'edit' ? 'edit' : 'view'));
421print '</table>';
422print '</div>';
423
424print ajax_autoselect('downloadinternallink');
425print ajax_autoselect('downloadlink');
426
427print dol_get_fiche_end();
428
429if ($action == 'edit') {
430 print $form->buttonsSaveCancel();
431
432 print '</form>';
433}
434
435
436// Confirm deletion of a file
437if ($action == 'deletefile') {
438 print $form->formconfirm($_SERVER["PHP_SELF"].'?section='.urlencode($section), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile', $urlfile), 'confirm_deletefile', '', 1, 1);
439}
440
441if ($action != 'edit') {
442 // Actions buttons
443 print '<div class="tabsAction">';
444
445 if ($user->hasRight('ecm', 'setup')) {
446 print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=edit&section='.urlencode($section).'&urlfile='.urlencode($urlfile).'">'.$langs->trans('Edit').'</a>';
447 }
448
449 print '</div>';
450}
451
452
453// End of page
454llxFooter();
455$db->close();
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:67
global $dolibarr_main_url_root
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
Class to manage ECM directories.
Class to manage ECM files.
Class to manage standard extra fields.
Class to manage generation of HTML components Only common components must be here.
ecm_file_prepare_head($object)
Prepare array with list of tabs.
Definition ecm.lib.php:118
dol_filemtime($pathoffile)
Return time of a file.
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=0)
Move a file into another name.
dol_is_file($pathoffile)
Return if path is a file.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_warning($titlealt='default', $moreatt='', $morecss='pictowarning')
Show warning logo.
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_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0, $morecssdiv='')
Show tabs of a record.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
ajax_autoselect($htmlname, $addlink='', $textonlink='Link')
Make content of an input box selected when we click into input field.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0)
Clean a string to use it as a file name.
dol_sanitizePathName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a path name.
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.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.