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