dolibarr 21.0.4
ajaxdirpreview.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2004-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2005 Simon Tosser <simon@kornog-computing.com>
5 * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
6 * Copyright (C) 2010 Pierre Morin <pierre.morin@auguria.net>
7 * Copyright (C) 2013 Marcos García <marcosgdf@gmail.com>
8 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
9 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
10 * Copyright (C) 2025 Joachim Kueter <git-jk@bloxera.com>
11 *
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 3 of the License, or
15 * (at your option) any later version.
16 *
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program. If not, see <https://www.gnu.org/licenses/>.
24 */
25
33if (!defined('NOTOKENRENEWAL')) {
34 define('NOTOKENRENEWAL', 1); // Disables token renewal
35}
36if (!defined('NOREQUIREMENU')) {
37 define('NOREQUIREMENU', '1');
38}
39if (!defined('NOREQUIREHTML')) {
40 define('NOREQUIREHTML', '1');
41}
42if (!defined('NOREQUIREAJAX')) {
43 define('NOREQUIREAJAX', '1');
44}
45
54if (!isset($mode) || $mode != 'noajax') { // For ajax call
55 require_once '../../main.inc.php';
56 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
57 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
58 require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php';
59
60 $action = GETPOST('action', 'aZ09');
61 $file = urldecode(GETPOST('file', 'alpha'));
62 $section = GETPOST("section", 'alpha');
63 $module = GETPOST("module", 'alpha');
64 $urlsource = GETPOST("urlsource", 'alpha');
65 $search_doc_ref = GETPOST('search_doc_ref', 'alpha');
66
67 $limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit;
68 $sortfield = GETPOST("sortfield", 'aZ09comma');
69 $sortorder = GETPOST("sortorder", 'aZ09comma');
70 $page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page");
71 $showonrightsize = '';
72
73 if (empty($page) || $page == -1) {
74 $page = 0;
75 } // If $page is not defined, or '' or -1
76 $offset = $limit * $page;
77 $pageprev = $page - 1;
78 $pagenext = $page + 1;
79 if (!$sortorder) {
80 $sortorder = "ASC";
81 }
82 if (!$sortfield) {
83 $sortfield = "name";
84 }
85
86 $rootdirfordoc = $conf->ecm->dir_output;
87
88 $upload_dir = dirname(str_replace("../", "/", $rootdirfordoc.'/'.$file));
89
90 $ecmdir = new EcmDirectory($db);
91 if ($section > 0) {
92 $result = $ecmdir->fetch($section);
93 //if (!($result > 0)) {
94 //dol_print_error($db,$ecmdir->error);
95 //exit;
96 //}
97 }
98} else {
99 // When no an ajax call (include from other file)
100 '
101 @phan-var-force int $section
102 @phan-var-force string $module
103 @phan-var-force string $showonrightsize
104 ';
105 $rootdirfordoc = $conf->ecm->dir_output;
106
107 $ecmdir = new EcmDirectory($db);
108 $relativepath = '';
109 if ($section > 0) {
110 $result = $ecmdir->fetch($section);
111 if (!($result > 0)) {
112 dol_print_error($db, $ecmdir->error);
113 exit;
114 }
115
116 $relativepath = $ecmdir->getRelativePath(); // Example 'mydir/'
117 } elseif (GETPOST('section_dir')) {
118 $relativepath = GETPOST('section_dir');
119 }
120 //var_dump($section.'-'.GETPOST('section_dir').'-'.$relativepath);
121
122 $upload_dir = $rootdirfordoc.'/'.$relativepath;
123}
124
125if (empty($url)) { // autoset $url but it is better to have it defined before into filemanager.tpl.php (not possible when in auto tree)
126 if (!empty($module) && $module == 'medias' && !GETPOST('website')) {
127 $url = DOL_URL_ROOT.'/ecm/index_medias.php';
128 } elseif (GETPOSTISSET('website')) {
129 $url = DOL_URL_ROOT.'/website/index.php';
130 } else {
131 $url = DOL_URL_ROOT.'/ecm/index.php';
132 }
133}
134
135// Load translation files required by the page
136$langs->loadLangs(array("ecm", "companies", "other"));
137
138if (empty($modulepart)) {
139 $modulepart = $module;
140}
141
142// Security check
143if ($user->socid > 0) {
144 $socid = $user->socid;
145}
146// On interdit les remontees de repertoire ainsi que les pipe dans les noms de fichiers.
147if (preg_match('/\.\./', $upload_dir) || preg_match('/[<>|]/', $upload_dir)) {
148 dol_syslog("Refused to deliver file ".$upload_dir);
149 // Do no show plain path in shown error message
150 dol_print_error(null, $langs->trans("ErrorFileNameInvalid", $upload_dir));
151 exit;
152}
153// Check permissions
154if ($modulepart == 'ecm') {
155 if (!$user->hasRight('ecm', 'read')) {
157 }
158} elseif ($modulepart == 'medias' || $modulepart == 'website') {
159 // Always allowed
160} else {
162}
163
164
165/*
166 * Action
167 */
168
169// None
170
171
172
173/*
174 * View
175 */
176
177if (!isset($mode) || $mode != 'noajax') {
178 // Ajout directives pour resoudre bug IE
179 header('Cache-Control: Public, must-revalidate');
180 header('Pragma: public');
181
182 top_httphead();
183}
184
185$type = 'directory';
186
187// This test if file exists should be useless. We keep it to find bug more easily
188if (!dol_is_dir($upload_dir)) {
189 //dol_mkdir($upload_dir);
190 /*$langs->load("install");
191 dol_print_error(0,$langs->trans("ErrorDirDoesNotExists",$upload_dir));
192 exit;*/
193}
194
195print '<!-- ajaxdirpreview type='.$type.' module='.$module.' modulepart='.$modulepart.'-->'."\n";
196//print '<!-- Page called with mode='.dol_escape_htmltag(isset($mode)?$mode:'').' type='.dol_escape_htmltag($type).' module='.dol_escape_htmltag($module).' url='.dol_escape_htmltag($url).' '.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.dol_escape_htmltag($_SERVER["QUERY_STRING"]).' -->'."\n";
197
198$param = ($sortfield ? '&sortfield='.urlencode($sortfield) : '').($sortorder ? '&sortorder='.urlencode($sortorder) : '');
199if (!empty($websitekey)) {
200 $param .= '&website='.urlencode($websitekey);
201}
202if (!empty($pageid)) {
203 $param .= '&pageid='.((int) $pageid);
204}
205
206
207// Dir scan
208if ($type == 'directory') {
209 $formfile = new FormFile($db);
210
211 $maxlengthname = 40;
212 $excludefiles = array('^SPECIMEN\.pdf$', '^\.', '(\.meta|_preview.*\.png)$', '^temp$', '^payments$', '^CVS$', '^thumbs$');
213 $sorting = (strtolower($sortorder) == 'desc' ? SORT_DESC : SORT_ASC);
214
215 // Right area. If module is defined here, we are in automatic ecm.
216 $automodules = array(
217 'company',
218 'invoice',
219 'invoice_supplier',
220 'propal',
221 'supplier_proposal',
222 'order',
223 'order_supplier',
224 'contract',
225 'product',
226 'tax',
227 'tax-vat',
228 'salaries',
229 'project',
230 'project_task',
231 'fichinter',
232 'user',
233 'expensereport',
234 'holiday',
235 'recruitment-recruitmentcandidature',
236 'banque',
237 'chequereceipt',
238 'mrp-mo'
239 );
240
241 $parameters = array('modulepart' => $module);
242 $reshook = $hookmanager->executeHooks('addSectionECMAuto', $parameters);
243 if ($reshook > 0 && is_array($hookmanager->resArray) && count($hookmanager->resArray) > 0) {
244 if (is_array($hookmanager->resArray['module'])) {
245 $automodules = array_merge($automodules, $hookmanager->resArray['module']);
246 } else {
247 $automodules[] = $hookmanager->resArray['module'];
248 }
249 }
250
251 // TODO change for multicompany sharing
252 if ($module == 'company') {
253 $upload_dir = $conf->societe->dir_output;
254 $excludefiles[] = '^contact$'; // The subdir 'contact' contains files of contacts.
255 } elseif ($module == 'invoice') {
256 $upload_dir = $conf->facture->dir_output;
257 } elseif ($module == 'invoice_supplier') {
258 $upload_dir = $conf->fournisseur->facture->dir_output;
259 } elseif ($module == 'propal') {
260 $upload_dir = $conf->propal->dir_output;
261 } elseif ($module == 'supplier_proposal') {
262 $upload_dir = $conf->supplier_proposal->dir_output;
263 } elseif ($module == 'order') {
264 $upload_dir = $conf->commande->dir_output;
265 } elseif ($module == 'order_supplier') {
266 $upload_dir = $conf->fournisseur->commande->dir_output;
267 } elseif ($module == 'contract') {
268 $upload_dir = $conf->contrat->dir_output;
269 } elseif ($module == 'product') {
270 $upload_dir = $conf->product->dir_output;
271 } elseif ($module == 'tax') {
272 $upload_dir = $conf->tax->dir_output;
273 $excludefiles[] = '^vat$'; // The subdir 'vat' contains files of vats.
274 } elseif ($module == 'tax-vat') {
275 $upload_dir = $conf->tax->dir_output.'/vat';
276 } elseif ($module == 'salaries') {
277 $upload_dir = $conf->salaries->dir_output;
278 } elseif ($module == 'project') {
279 $upload_dir = $conf->project->dir_output;
280 } elseif ($module == 'project_task') {
281 $upload_dir = $conf->project->dir_output;
282 } elseif ($module == 'fichinter') {
283 $upload_dir = $conf->ficheinter->dir_output;
284 } elseif ($module == 'user') {
285 $upload_dir = $conf->user->dir_output;
286 } elseif ($module == 'expensereport') {
287 $upload_dir = $conf->expensereport->dir_output;
288 } elseif ($module == 'holiday') {
289 $upload_dir = $conf->holiday->dir_output;
290 } elseif ($module == 'recruitment-recruitmentcandidature') {
291 $upload_dir = $conf->recruitment->dir_output.'/recruitmentcandidature';
292 } elseif ($module == 'banque') {
293 $upload_dir = $conf->bank->dir_output;
294 } elseif ($module == 'chequereceipt') {
295 $upload_dir = $conf->bank->dir_output.'/checkdeposits';
296 } elseif ($module == 'mrp-mo') {
297 $upload_dir = $conf->mrp->dir_output;
298 } else {
299 $parameters = array('modulepart' => $module);
300 $reshook = $hookmanager->executeHooks('addSectionECMAuto', $parameters);
301 if ($reshook > 0 && is_array($hookmanager->resArray) && count($hookmanager->resArray) > 0) {
302 $upload_dir = $hookmanager->resArray['directory'];
303 }
304 }
305
306 // Automatic list
307 if (in_array($module, $automodules)) {
308 $param .= '&module='.urlencode($module);
309 if (isset($search_doc_ref) && $search_doc_ref != '') {
310 $param .= '&search_doc_ref='.urlencode($search_doc_ref);
311 }
312
313 $textifempty = ($section ? $langs->trans("NoFileFound") : ($showonrightsize == 'featurenotyetavailable' ? $langs->trans("FeatureNotYetAvailable") : $langs->trans("NoFileFound")));
314
315 $filter = preg_quote((string) $search_doc_ref, '/');
316 $filearray = dol_dir_list($upload_dir, "files", 1, $filter, $excludefiles, $sortfield, $sorting, 1);
317
318 // To allow external users,we must restrict $filearray to entries the user is a thirdparty.
319 // This can be done by filtering on entries found into llx_ecm
320 if ($user->socid > 0) {
321 $filearrayallowedtoexternal = array(); // 'fullpath' => array(...)
322
323 // Search files in ECM with select filepath.filename where src_object_type = $module and src_object_type EXISTS in (select rowid from $objecttablename WERE fk_soc = '.$user->socid.' and entity in getEntity($objecttbalename)
324 // TODO
325
326 // Now clean $filearray to keep only record also found into $filearrayallowedtoexternal.
327 foreach ($filearray as $key => $val) {
328 if (!in_array($upload_dir.'/'.$val['relativename'], $filearrayallowedtoexternal)) {
329 unset($filearray[$key]);
330 }
331 }
332 }
333
334 $perm = $user->hasRight('ecm', 'upload');
335
336 $formfile->list_of_autoecmfiles($upload_dir, $filearray, $module, $param, 1, '', $perm, 1, $textifempty, $maxlengthname, $url, 1);
337 } else {
338 // Manual list
339 if ($module == 'medias') {
340 /*
341 $_POST is array like
342 'token' => string '062380e11b7dcd009d07318b57b71750' (length=32)
343 'action' => string 'file_manager' (length=12)
344 'website' => string 'template' (length=8)
345 'pageid' => string '124' (length=3)
346 'section_dir' => string 'mydir/' (length=3)
347 'section_id' => string '0' (length=1)
348 'max_file_size' => string '2097152' (length=7)
349 'sendit' => string 'Envoyer fichier' (length=15)
350 */
351 $relativepath = GETPOST('file', 'alpha') ? GETPOST('file', 'alpha') : GETPOST('section_dir', 'alpha');
352 if ($relativepath && $relativepath != '/') {
353 $relativepath .= '/';
354 }
355 $upload_dir = $dolibarr_main_data_root.'/'.$module.'/'.$relativepath;
356 if (GETPOSTISSET('website') || GETPOSTISSET('file_manager')) {
357 $param .= '&file_manager=1';
358 if (!preg_match('/website=/', $param) && GETPOST('website', 'alpha')) {
359 $param .= '&website='.urlencode(GETPOST('website', 'alpha'));
360 }
361 if (!preg_match('/pageid=/', $param)) {
362 $param .= '&pageid='.GETPOSTINT('pageid');
363 }
364 //if (!preg_match('/backtopage=/',$param)) $param.='&backtopage='.urlencode($_SERVER["PHP_SELF"].'?file_manager=1&website='.$websitekey.'&pageid='.$pageid);
365 }
366 } else {
367 $relativepath = $ecmdir->getRelativePath();
368 $upload_dir = $conf->ecm->dir_output.'/'.$relativepath;
369 }
370
371 // If $section defined with value 0
372 if (($section === '0' || empty($section)) && ($module != 'medias')) {
373 $filearray = array();
374 } else {
375 $filearray = dol_dir_list($upload_dir, "files", 0, '', array('^\.', '(\.meta|_preview.*\.png)$', '^temp$', '^CVS$'), $sortfield, $sorting, 1);
376 }
377
378 if ($section) {
379 $param .= '&section='.$section;
380 if (isset($search_doc_ref) && $search_doc_ref != '') {
381 $param .= '&search_doc_ref='.urlencode($search_doc_ref);
382 }
383
384 $textifempty = $langs->trans('NoFileFound');
385 } elseif ($section === '0') {
386 if ($module == 'ecm') {
387 $textifempty = '<br><div class="center"><span class="warning">'.$langs->trans("DirNotSynchronizedSyncFirst").'</span></div><br>';
388 } else {
389 $textifempty = $langs->trans('NoFileFound');
390 }
391 } else {
392 $textifempty = ($showonrightsize == 'featurenotyetavailable' ? $langs->trans("FeatureNotYetAvailable") : $langs->trans("ECMSelectASection"));
393 }
394
395 $useinecm = null;
396 if ($module == 'medias') {
397 $useinecm = 6;
398 $modulepart = 'medias';
399 $perm = ($user->hasRight("website", "write") || $user->hasRight("emailing", "creer"));
400 $title = 'none';
401 } elseif ($module == 'ecm') { // DMS/ECM -> manual structure
402 if ($user->hasRight("ecm", "read")) {
403 // Buttons: Preview
404 $useinecm = 2;
405 }
406
407 if ($user->hasRight("ecm", "upload")) {
408 // Buttons: Preview + Delete
409 $useinecm = 4;
410 }
411
412 if ($user->hasRight("ecm", "setup")) {
413 // Buttons: Preview + Delete + Edit
414 $useinecm = 5;
415 }
416
417 $perm = $user->hasRight("ecm", "upload");
418 $modulepart = 'ecm';
419 $title = ''; // Use default
420 } else {
421 $useinecm = 5;
422 $modulepart = 'ecm';
423 $perm = $user->hasRight("ecm", "upload");
424 $title = ''; // Use default
425 }
426
427 // When we show list of files for ECM files, $filearray contains file list, and directory is defined with modulepart + section into $param
428 // When we show list of files for a directory, $filearray ciontains file list, and directory is defined with modulepart + $relativepath
429 // var_dump("section=".$section." title=".$title." modulepart=".$modulepart." useinecm=".$useinecm." perm(permtoeditline)=".$perm." relativepath=".$relativepath." param=".$param." url=".$url);
430 $formfile->list_of_documents($filearray, null, $modulepart, $param, 1, $relativepath, $perm, $useinecm, $textifempty, $maxlengthname, $title, $url, 0, $perm, '', $sortfield, $sortorder);
431 }
432}
433
434
435
436// Bottom of page
437$useajax = 1;
438if (!empty($conf->dol_use_jmobile)) {
439 $useajax = 0;
440}
441if (empty($conf->use_javascript_ajax)) {
442 $useajax = 0;
443}
444if (getDolGlobalString('MAIN_ECM_DISABLE_JS')) {
445 $useajax = 0;
446}
447
448//$param.=($param?'?':'').(preg_replace('/^&/','',$param));
449
450if ($useajax || $action == 'deletefile') {
451 $urlfile = '';
452 if ($action == 'deletefile') {
453 $urlfile = GETPOST('urlfile', 'alpha');
454 }
455
456 if (empty($section_dir)) {
457 $section_dir = GETPOST("file", "alpha");
458 }
459 $section_id = $section;
460
461 require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
462
463 $form = new Form($db);
464 $formquestion = array();
465 $formquestion['urlfile'] = array('type' => 'hidden', 'value' => $urlfile, 'name' => 'urlfile'); // We must always put field, even if empty because it is filled by javascript later
466 $formquestion['section'] = array('type' => 'hidden', 'value' => $section, 'name' => 'section'); // We must always put field, even if empty because it is filled by javascript later
467 $formquestion['section_id'] = array('type' => 'hidden', 'value' => $section_id, 'name' => 'section_id'); // We must always put field, even if empty because it is filled by javascript later
468 $formquestion['section_dir'] = array('type' => 'hidden', 'value' => $section_dir, 'name' => 'section_dir'); // We must always put field, even if empty because it is filled by javascript later
469 $formquestion['sortfield'] = array('type' => 'hidden', 'value' => $sortfield, 'name' => 'sortfield'); // We must always put field, even if empty because it is filled by javascript later
470 $formquestion['sortorder'] = array('type' => 'hidden', 'value' => $sortorder, 'name' => 'sortorder'); // We must always put field, even if empty because it is filled by javascript later
471 if (!empty($action) && $action == 'file_manager') {
472 $formquestion['file_manager'] = array('type' => 'hidden', 'value' => 1, 'name' => 'file_manager');
473 }
474 if (!empty($websitekey)) {
475 $formquestion['website'] = array('type' => 'hidden', 'value' => $websitekey, 'name' => 'website');
476 }
477 if (!empty($pageid) && $pageid > 0) {
478 $formquestion['pageid'] = array('type' => 'hidden', 'value' => $pageid, 'name' => 'pageid');
479 }
480
481 print $form->formconfirm($url, $langs->trans("DeleteFile"), $langs->trans("ConfirmDeleteFile"), 'confirm_deletefile', $formquestion, "no", ($useajax ? 'deletefile' : 0));
482}
483
484if ($useajax) {
485 print '<!-- ajaxdirpreview.php: js to manage preview of doc -->'."\n";
486 print '<script nonce="'.getNonce().'" type="text/javascript">';
487
488 // Enable jquery handlers on new generated HTML objects (same code than into lib_footer.js.php)
489 // Because the content is reloaded by ajax call, we must also reenable some jquery hooks
490 // Wrapper to manage document_preview
491 if ($conf->browser->layout != 'phone') {
492 print "\n/* JS CODE TO ENABLE document_preview */\n";
493 print '
494 jQuery(document).ready(function () {
495 jQuery(".documentpreview").click(function () {
496 console.log("We click on preview for element with href="+$(this).attr(\'href\')+" mime="+$(this).attr(\'mime\'));
497 document_preview($(this).attr(\'href\'), $(this).attr(\'mime\'), \''.dol_escape_js($langs->transnoentities("Preview")).'\');
498 return false;
499 });
500 });
501 ' . "\n";
502 }
503
504 // Enable jquery handlers button to delete files
505 print 'jQuery(document).ready(function() {'."\n";
506 print ' jQuery(".deletefilelink").click(function(e) { '."\n";
507 print ' console.log("We click on button with class deletefilelink, param='.$param.', we set urlfile to "+jQuery(this).attr("rel"));'."\n";
508 print ' jQuery("#urlfile").val(jQuery(this).attr("rel"));'."\n";
509 //print ' jQuery("#section_dir").val(\'aaa\');'."\n";
510 print ' jQuery("#dialog-confirm-deletefile").dialog("open");'."\n";
511 print ' return false;'."\n";
512 print ' });'."\n";
513 print '});'."\n";
514 print '</script>'."\n";
515}
516
517// Close db if mode is not noajax
518if ((!isset($mode) || $mode != 'noajax') && is_object($db)) {
519 $db->close();
520}
Class to manage ECM directories.
Class to offer components to list and upload files.
Class to manage generation of HTML components Only common components must be here.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:63
dol_is_dir($folder)
Test if filename is a directory.
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
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...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
if(!defined( 'NOREQUIREMENU')) if(!empty(GETPOST('seteventmessages', 'alpha'))) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.