dolibarr 25.0.0-alpha
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-2026 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';
38require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
39require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php';
40require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
41require_once DOL_DOCUMENT_ROOT.'/ecm/class/htmlecm.form.class.php';
42require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
43require_once DOL_DOCUMENT_ROOT.'/core/lib/ecm.lib.php';
44require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
45
46// Load translation files required by page
47$langs->loadLangs(array('ecm', 'companies', 'other', 'users', 'orders', 'propal', 'bills', 'contracts', 'categories'));
48
49$action = GETPOST('action', 'aZ09');
50$cancel = GETPOST('cancel', 'alpha');
51$backtopage = GETPOST('backtopage', 'alpha');
52$module = GETPOST('module', 'aZ09arobase');
53
54// Get parameters
55$socid = GETPOSTINT("socid");
56
57// Security check
58if ($user->socid > 0) {
59 $action = '';
60 $socid = $user->socid;
61}
62
63$limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit;
64$sortfield = GETPOST('sortfield', 'aZ09comma');
65$sortorder = GETPOST('sortorder', 'aZ09comma');
66$page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page");
67if (empty($page) || $page == -1) {
68 $page = 0;
69} // If $page is not defined, or '' or -1
70$offset = $limit * $page;
71$pageprev = $page - 1;
72$pagenext = $page + 1;
73if (!$sortorder) {
74 $sortorder = "ASC";
75}
76if (!$sortfield) {
77 $sortfield = "label";
78}
79
80$section = GETPOST("section", 'alpha');
81if (!$section) {
82 dol_print_error(null, 'Error, section parameter missing');
83 exit;
84}
85$urlfile = (string) dol_sanitizePathName(GETPOST("urlfile"), '_', 0);
86if (!$urlfile) {
87 dol_print_error(null, "ErrorParamNotDefined");
88 exit;
89}
90
91// Load ecm object
92$ecmdir = new EcmDirectory($db);
93$result = $ecmdir->fetch(GETPOSTINT("section"));
94if (!($result > 0)) {
95 dol_print_error($db, $ecmdir->error);
96 exit;
97}
98$relativepath = $ecmdir->getRelativePath();
99$upload_dir = $conf->ecm->dir_output.'/'.$relativepath;
100
101$fullpath = $conf->ecm->dir_output.'/'.$relativepath.$urlfile;
102
103$relativetodocument = 'ecm/'.$relativepath; // $relativepath is relative to ECM dir, we need relative to document
104$filepath = $relativepath.$urlfile;
105$filepathtodocument = $relativetodocument.$urlfile;
106
107// Try to load object from index
108$object = new EcmFiles($db);
109
110// fetch optionals attributes and labels
111$extrafields->fetch_name_optionals_label($object->table_element);
112
113$result = $object->fetch(0, '', $filepathtodocument);
114if ($result < 0) {
115 dol_print_error($db, $object->error, $object->errors);
116 exit;
117}
118
119// Permissions
120$permissiontoread = $user->hasRight('ecm', 'read');
121$permissiontoadd = $user->hasRight('ecm', 'setup');
122$permissiontoupload = $user->hasRight('ecm', 'upload');
123
124if (!$permissiontoread) {
126}
127
128
129/*
130 * Actions
131 */
132
133if ($cancel) {
134 $action = '';
135 if ($backtopage) {
136 header("Location: ".$backtopage);
137 exit;
138 } else {
139 $paramscancel = array('urlfile' => $urlfile, 'section' => $section);
140 if ($module) {
141 $paramscancel['module'] = $module;
142 }
143 header('Location: '.dolBuildUrl($_SERVER["PHP_SELF"], $paramscancel));
144 exit;
145 }
146}
147
148// Rename and/or move file
149if ($action == 'update' && $permissiontoadd) {
150 $error = 0;
151
152 $oldlabel = GETPOST('urlfile', 'alpha');
153 $newlabel = dol_sanitizeFileName(GETPOST('label', 'alpha'), '_', 0);
154 $shareenabled = GETPOST('shareenabled', 'alpha');
155
156 // Target directory, the current one if not changed
157 $newecmdir = $ecmdir;
158 $newsection = GETPOSTINT('newsection');
159 if ($newsection > 0 && $newsection != $ecmdir->id) {
160 $newecmdir = new EcmDirectory($db);
161 $result = $newecmdir->fetch($newsection);
162 if (!($result > 0)) {
163 dol_print_error($db, $newecmdir->error);
164 exit;
165 }
166 }
167
168 //$db->begin();
169
170 $olddir = $ecmdir->getRelativePath(0); // Relative to ecm
171 $newdir = $newecmdir->getRelativePath(0); // Relative to ecm
172 $olddirrelativetodocument = 'ecm/'.$olddir; // Relative to document
173 $newdirrelativetodocument = 'ecm/'.$newdir;
174 $olddir = $conf->ecm->dir_output.'/'.$olddir;
175 $newdir = $conf->ecm->dir_output.'/'.$newdir;
176
177 $oldfile = $olddir.$oldlabel;
178 $newfile = $newdir.$newlabel;
179 $newfileformove = $newfile;
180 // If old file end with .noexe, new file must also end with .noexe
181 if (preg_match('/\.noexe$/', $oldfile) && !preg_match('/\.noexe$/', $newfileformove)) {
182 $newfileformove .= '.noexe';
183 }
184 //var_dump($oldfile);var_dump($newfile);exit;
185
186 // Now we update index of file
187 $db->begin();
188 //print $oldfile.' - '.$newfile;
189 // Compare full paths, so a move into another directory is detected even if the name is unchanged
190 if ($newfileformove != $oldfile && dol_is_file($newfileformove)) {
191 // Do not overwrite another file of the target directory
192 $langs->load('errors');
193 setEventMessages($langs->trans('ErrorDestinationAlreadyExists', $newlabel), null, 'errors');
194 $error++;
195 }
196 if (!$error && $newdir != $olddir && dol_mkdir($newdir) < 0) {
197 $langs->load('errors');
198 setEventMessages($langs->trans('ErrorFailToCreateDir', $newdir), null, 'errors');
199 $error++;
200 }
201 if (!$error && $newfileformove != $oldfile) {
202 $result = dol_move($oldfile, $newfileformove); // This include update of database
203 if (!$result) {
204 $langs->load('errors');
205 setEventMessages($langs->trans('ErrorFailToRenameFile', $oldfile, $newfile), null, 'errors');
206 $error++;
207 }
208
209 // Update cached number of files of both directories
210 if (!$error && $newecmdir->id != $ecmdir->id) {
211 $ecmdir->changeNbOfFiles('-');
212 $newecmdir->changeNbOfFiles('+');
213 }
214
215 // Reload object after the move
216 $result = $object->fetch(0, '', $newdirrelativetodocument.basename($newfileformove));
217 if ($result < 0) {
218 dol_print_error($db, $object->error, $object->errors);
219 exit;
220 }
221 }
222
223 if (!$error) {
224 if ($shareenabled) {
225 // Keep the current key: a new one would break the links already sent
226 if (empty($object->share)) {
227 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
228 $object->share = getRandomPassword(true);
229 }
230 } else {
231 $object->share = '';
232 }
233
234 if ($object->id > 0) {
235 $ret = $extrafields->setOptionalsFromPost(null, $object);
236 if ($ret < 0) {
237 $error++;
238 }
239 if (!$error) {
240 // Actions on extra fields
241 $result = $object->insertExtraFields();
242 if ($result < 0) {
243 setEventMessages($object->error, $object->errors, 'errors');
244 $error++;
245 }
246 }
247 // Call update to set the share key
248 $result = $object->update($user);
249 if ($result < 0) {
250 setEventMessages($object->error, $object->errors, 'warnings');
251 }
252 } else {
253 // Call create to insert record
254 $object->entity = $conf->entity;
255 $object->filepath = preg_replace('/[\\/]+$/', '', $newdirrelativetodocument);
256 $object->filename = $newlabel;
257 $object->label = md5_file(dol_osencode($newfileformove)); // hash of file content
258 $object->fullpath_orig = '';
259 $object->gen_or_uploaded = 'unknown';
260 $object->description = ''; // indexed content
261 $object->keywords = ''; // keyword content
262 $result = $object->create($user);
263 if ($result < 0) {
264 setEventMessages($object->error, $object->errors, 'warnings');
265 }
266 }
267 }
268
269 if (!$error) {
270 $db->commit();
271
272 $urlfile = $newlabel;
273 // If old file end with .noexe, new file must also end with .noexe
274 if (preg_match('/\.noexe$/', $newfileformove)) {
275 $urlfile .= '.noexe';
276 }
277
278 header('Location: '.dolBuildUrl($_SERVER["PHP_SELF"], array('urlfile' => $urlfile, 'section' => $newecmdir->id)));
279 exit;
280 } else {
281 $db->rollback();
282 }
283}
284
285
286
287/*
288 * View
289 */
290
291$form = new Form($db);
292
293llxHeader('', '', '', '', 0, 0, '', '', '', 'mod-ecm page-file_card');
294
295$object->section_id = $ecmdir->id;
296$object->label = $urlfile;
297$head = ecm_file_prepare_head($object);
298
299if ($action == 'edit') {
300 print '<form name="update" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
301 print '<input type="hidden" name="token" value="'.newToken().'">';
302 print '<input type="hidden" name="section" value="'.$section.'">';
303 print '<input type="hidden" name="urlfile" value="'.$urlfile.'">';
304 print '<input type="hidden" name="module" value="'.$module.'">';
305 print '<input type="hidden" name="action" value="update">';
306 print '<input type="hidden" name="id" value="'.$object->id.'">';
307}
308
309print dol_get_fiche_head($head, 'card', $langs->trans("File"), -1, 'generic');
310
311
312$s = '';
313$tmpecmdir = new EcmDirectory($db); // Need to create a new one
314$tmpecmdir->fetch($ecmdir->id);
315$result = 1;
316$i = 0;
317while ($tmpecmdir && $result > 0) {
318 $tmpecmdir->ref = $tmpecmdir->label;
319 $s = $tmpecmdir->getNomUrl(1).$s;
320 if ($tmpecmdir->fk_parent) {
321 $s = ' -> '.$s;
322 $result = $tmpecmdir->fetch($tmpecmdir->fk_parent);
323 } else {
324 $tmpecmdir = 0;
325 }
326 $i++;
327}
328
329$urlfiletoshow = preg_replace('/\.noexe$/', '', $urlfile);
330
331$s = img_picto('', 'object_dir').' <a href="'.DOL_URL_ROOT.'/ecm/index.php">'.$langs->trans("ECMRoot").'</a> -> '.$s.' -> ';
332if ($action == 'edit') {
333 $s .= '<input type="text" name="label" class="quatrevingtpercent" value="'.$urlfiletoshow.'">';
334} else {
335 $s .= $urlfiletoshow;
336}
337
338$linkback = '';
339if ($backtopage) {
340 $linkback = '<a href="'.$backtopage.'">'.$langs->trans("BackToTree").'</a>';
341}
342
343$object->ref = ''; // Force to hide ref
344dol_banner_tab($object, '', $linkback, 0, '', '', $s);
345
346print '<div class="fichecenter">';
347
348print '<div class="underbanner clearboth"></div>';
349print '<table class="border centpercent tableforfield">';
350print '<tr><td class="titlefieldcreate">'.$langs->trans("ECMCreationDate").'</td><td>';
351print dol_print_date(dol_filemtime($fullpath), 'dayhour');
352print '</td></tr>';
353
354// Directory, to move the file into another one
355if ($action == 'edit') {
356 $formecm = new FormEcm($db);
357 print '<tr><td>'.$langs->trans("ECMSection").'</td><td>';
358 print img_picto('', 'object_dir', 'class="pictofixedwidth"').$formecm->selectAllSections($ecmdir->id, 'newsection', 'ecm');
359 print '</td></tr>';
360}
361/*print '<tr><td>'.$langs->trans("ECMDirectoryForFiles").'</td><td>';
362print '/ecm/'.$relativepath;
363print '</td></tr>';
364print '<tr><td>'.$langs->trans("ECMNbOfDocs").'</td><td>';
365print count($filearray);
366print '</td></tr>';
367print '<tr><td>'.$langs->trans("TotalSizeOfAttachedFiles").'</td><td>';
368print dol_print_size($totalsize);
369print '</td></tr>';
370*/
371
372// Hash of file content
373print '<tr><td>'.$langs->trans("HashOfFileContent").'</td><td>';
374$object = new EcmFiles($db);
375$object->fetch(0, '', $filepathtodocument);
376if (!empty($object->label)) {
377 print $object->label;
378} else {
379 print img_warning().' '.$langs->trans("FileNotYetIndexedInDatabase");
380}
381print '</td></tr>';
382
383// Define $urlwithroot
384$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
385$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
386//$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
387
388// Link for internal download
389print '<tr><td>';
390print $form->textwithpicto($langs->trans("DirectDownloadInternalLink"), $langs->trans("PrivateDownloadLinkDesc"));
391print '</td><td>';
392$modulepart = 'ecm';
393$paramsrellink = array('modulepart' => $modulepart, 'attachment' => 1);
394if (!empty($object->entity)) {
395 $paramsrellink['entity'] = $object->entity;
396}
397$paramsrellink['file'] = $filepath;
398$rellink = dolBuildUrl('/document.php', $paramsrellink);
399$fulllink = $urlwithroot.$rellink;
400print img_picto('', 'globe').' ';
401if ($action != 'edit') {
402 print '<input type="text" class="maxquatrevingtpercent widthcentpercentminusxx small" id="downloadinternallink" name="downloadinternellink" value="'.dol_escape_htmltag($fulllink).'">';
403} else {
404 print $fulllink;
405}
406if ($action != 'edit') {
407 print ' <a href="'.$fulllink.'">'.img_picto($langs->trans("Download"), 'download', 'class="opacitymedium paddingrightonly"').'</a>'; // No target here.
408}
409print '</td></tr>';
410
411// Link for direct external download
412print '<tr><td>';
413if ($action != 'edit') {
414 print $form->textwithpicto($langs->trans("DirectDownloadLink"), $langs->trans("PublicDownloadLinkDesc"));
415} else {
416 print $form->textwithpicto($langs->trans("FileSharedViaALink"), $langs->trans("PublicDownloadLinkDesc"));
417}
418print '</td><td>';
419if (!empty($object->share)) {
420 if ($action != 'edit') {
421 $fulllink = $urlwithroot.'/document.php?hashp='.$object->share; // Hash for public share
422 //if (!empty($object->ref)) $fulllink.='&hashn='.$object->ref; // Hash of file path
423 //elseif (!empty($object->label)) $fulllink.='&hashc='.$object->label; // Hash of file content
424
425 print img_picto('', 'globe').' ';
426 if ($action != 'edit') {
427 print '<input type="text" class="maxquatrevingtpercent widthcentpercentminusxx nopadding small downloadexternallink" id="downloadlink" name="downloadexternallink" value="'.dol_escape_htmltag($fulllink).'" spellcheck="false">';
428 } else {
429 print $fulllink;
430 }
431 if ($action != 'edit') {
432 print ' <a href="'.$fulllink.'">'.img_picto($langs->trans("Download"), 'download', 'class="opacitymedium paddingrightonly"').'</a>'; // No target here
433 }
434 } else {
435 print '<input type="checkbox" name="shareenabled" checked="checked" /> ';
436 }
437} else {
438 if ($action != 'edit') {
439 print '<span class="opacitymedium">'.$langs->trans("FileNotShared").'</span>';
440 } else {
441 print '<input type="checkbox" name="shareenabled" /> ';
442 }
443}
444print '</td>';
445print '</tr>';
446print $object->showOptionals($extrafields, ($action == 'edit' ? 'edit' : 'view'));
447print '</table>';
448print '</div>';
449
450print ajax_autoselect('downloadinternallink');
451print ajax_autoselect('downloadlink');
452
453print dol_get_fiche_end();
454
455if ($action == 'edit') {
456 print $form->buttonsSaveCancel();
457
458 print '</form>';
459}
460
461
462// Confirm deletion of a file
463if ($action == 'deletefile') {
464 print $form->formconfirm(dolBuildUrl($_SERVER["PHP_SELF"], array('section' => $section)), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile', $urlfile), 'confirm_deletefile', '', 1, 1);
465}
466
467if ($action != 'edit') {
468 // Actions buttons
469 print '<div class="tabsAction">';
470
471 if ($user->hasRight('ecm', 'setup')) {
472 print '<a class="butAction" href="'.dolBuildUrl($_SERVER['PHP_SELF'], array('action' => 'edit', 'section' => $section, 'urlfile' => $urlfile)).'">'.$langs->trans('Edit').'</a>';
473 }
474
475 print '</div>';
476}
477
478
479// End of page
480llxFooter();
481$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
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage ECM directories.
Class to manage ECM files.
Class to manage HTML component for ECM and generic filemanager.
Class to manage generation of HTML components Only common components must be here.
if(! $sortfield) if(! $sortorder) $module
Definition list.php:193
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.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
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.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
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).
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
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.
Definition html.lib.php:542
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Definition html.lib.php:740
ajax_autoselect($htmlname, $addlink='', $textonlink='Link')
Make content of an input box selected when we click into input field.
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.