1<?php
2/* Copyright (C) 2008-2016 Laurent Destailleur  <eldy@users.sourceforge.net>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18
19/**
20 *  \file       htdocs/ecm/dir_card.php
21 *	\ingroup    ecm
22 *	\brief     	Card of a directory for ECM module
23 */
24
25require '../main.inc.php';
26require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
27require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php';
28require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
29require_once DOL_DOCUMENT_ROOT.'/core/lib/ecm.lib.php';
30require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
31
32// Load translation files required by page
33$langs->loadLangs(array('ecm', 'companies', 'other'));
34
35$action     = GETPOST('action', 'alpha');
36$cancel     = GETPOST('cancel', 'aZ09');
37$backtopage = GETPOST('backtopage', 'alpha');
38$confirm    = GETPOST('confirm', 'alpha');
39
40$module  = GETPOST('module', 'alpha');
41$website = GETPOST('website', 'alpha');
42$pageid  = GETPOST('pageid', 'int');
43if (empty($module)) {
44	$module = 'ecm';
45}
46
47// Get parameters
48$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
49$sortfield = GETPOST("sortfield", 'alpha');
50$sortorder = GETPOST("sortorder", 'alpha');
51$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
52if (empty($page) || $page == -1) {
53	$page = 0;
54}     // If $page is not defined, or '' or -1
55$offset = $limit * $page;
56$pageprev = $page - 1;
57$pagenext = $page + 1;
58if (!$sortorder) {
59	$sortorder = "ASC";
60}
61if (!$sortfield) {
62	$sortfield = "name";
63}
64
65$section = GETPOST("section", 'alpha') ? GETPOST("section", 'alpha') : GETPOST("relativedir", 'alpha');
66if (!$section) {
67	dol_print_error('', "ErrorSectionParamNotDefined");
68	exit;
69}
70
71// Load ecm object
72$ecmdir = new EcmDirectory($db);
73
74if ($module == 'ecm') {
75	// $section should be an int except if it is dir not yet created into EcmDirectory
76	$result = $ecmdir->fetch($section);
77	if ($result > 0) {
78		$relativepath = $ecmdir->getRelativePath();
79		$upload_dir = $conf->ecm->dir_output.'/'.$relativepath;
80	} else {
81		$relativepath = $section;
82		$upload_dir = $conf->ecm->dir_output.'/'.$relativepath;
83	}
84} else // For example $module == 'medias'
85{
86	$relativepath = $section;
87	$upload_dir = $conf->medias->multidir_output[$conf->entity].'/'.$relativepath;
88}
89
90// Permissions
91$permtoread = 0;
92$permtoadd = 0;
93$permtoupload = 0;
94if ($module == 'ecm') {
95	$permtoread = $user->rights->ecm->read;
96	$permtoadd = $user->rights->ecm->setup;
97	$permtoupload = $user->rights->ecm->upload;
98}
99if ($module == 'medias') {
100	$permtoread = ($user->rights->mailing->lire || $user->rights->website->read);
101	$permtoadd = ($user->rights->mailing->creer || $user->rights->website->write);
102	$permtoupload = ($user->rights->mailing->creer || $user->rights->website->write);
103}
104
105if (!$permtoread) {
106	accessforbidden();
107}
108
109
110/*
111 * Actions
112 */
113
114// Upload file
115if (GETPOST("sendit") && !empty($conf->global->MAIN_UPLOAD_DOC) && $permtoupload) {
116	if (dol_mkdir($upload_dir) >= 0) {
117		$resupload = dol_move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_dir."/".dol_unescapefile($_FILES['userfile']['name']), 0, 0, $_FILES['userfile']['error']);
118		if (is_numeric($resupload) && $resupload > 0) {
119			$result = $ecmdir->changeNbOfFiles('+');
120		} else {
121			$langs->load("errors");
122			if ($resupload < 0) {	// Unknown error
123				setEventMessages($langs->trans("ErrorFileNotUploaded"), null, 'errors');
124			} elseif (preg_match('/ErrorFileIsInfectedWithAVirus/', $resupload)) {
125				// Files infected by a virus
126				setEventMessages($langs->trans("ErrorFileIsInfectedWithAVirus"), null, 'errors');
127			} else // Known error
128			{
129				setEventMessages($langs->trans($resupload), null, 'errors');
130			}
131		}
132	} else {
133		// Failed transfer (exceeding the limit file?)
134		$langs->load("errors");
135		setEventMessages($langs->trans("ErrorFailToCreateDir", $upload_dir), null, 'errors');
136	}
137}
138
139// Remove file
140if ($action == 'confirm_deletefile' && $confirm == 'yes' && $permtoupload) {
141	$langs->load("other");
142	$file = $upload_dir."/".GETPOST('urlfile'); // Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP).
143	$ret = dol_delete_file($file);
144	if ($ret) {
145		setEventMessages($langs->trans("FileWasRemoved", GETPOST('urlfile')), null, 'mesgs');
146	} else {
147		setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), null, 'errors');
148	}
149
150	$result = $ecmdir->changeNbOfFiles('-');
151}
152
153// Remove dir
154if ($action == 'confirm_deletedir' && $confirm == 'yes' && $permtoupload) {
155	$backtourl = DOL_URL_ROOT."/ecm/index.php";
156	if ($module == 'medias') {
157		$backtourl = DOL_URL_ROOT."/website/index.php?file_manager=1";
158	}
159
160	$deletedirrecursive = (GETPOST('deletedirrecursive', 'alpha') == 'on' ? 1 : 0);
161
162	if ($module == 'ecm' && $ecmdir->id > 0) {	// If manual ECM and directory is indexed into database
163		// Fetch was already done
164		$result = $ecmdir->delete($user, 'all', $deletedirrecursive);
165		if ($result <= 0) {
166			$langs->load('errors');
167			setEventMessages($langs->trans($ecmdir->error, $ecmdir->label), null, 'errors');
168		}
169	} else {
170		if ($deletedirrecursive) {
171			$resbool = dol_delete_dir_recursive($upload_dir, 0, 1);
172		} else {
173			$resbool = dol_delete_dir($upload_dir, 1);
174		}
175		if ($resbool) {
176			$result = 1;
177		} else {
178			$langs->load('errors');
179			setEventMessages($langs->trans("ErrorFailToDeleteDir", $upload_dir), null, 'errors');
180			$result = 0;
181		}
182	}
183	if ($result > 0) {
184		header("Location: ".$backtourl);
185		exit;
186	}
187}
188
189// Update dirname or description
190if ($action == 'update' && !GETPOST('cancel', 'alpha') && $permtoadd) {
191	$error = 0;
192
193	if ($module == 'ecm') {
194		$oldlabel = $ecmdir->label;
195		$olddir = $ecmdir->getRelativePath(0);
196		$olddir = $conf->ecm->dir_output.'/'.$olddir;
197	} else {
198		$olddir = GETPOST('section', 'alpha');
199		$olddir = $conf->medias->multidir_output[$conf->entity].'/'.$relativepath;
200	}
201
202	if ($module == 'ecm') {
203		$db->begin();
204
205		// Fetch was already done
206		$ecmdir->label = dol_sanitizeFileName(GETPOST("label"));
207		$ecmdir->description = GETPOST("description");
208		$ret = $extrafields->setOptionalsFromPost(null, $ecmdir);
209		if ($ret < 0) {
210			$error++;
211		}
212		if (!$error) {
213			// Actions on extra fields
214			$result = $ecmdir->insertExtraFields();
215			if ($result < 0) {
216				setEventMessages($ecmdir->error, $ecmdir->errors, 'errors');
217				$error++;
218			}
219		}
220		$result = $ecmdir->update($user);
221		if ($result > 0) {
222			// Try to rename file if changed
223			if ($oldlabel != $ecmdir->label && file_exists($olddir)) {
224				$newdir = $ecmdir->getRelativePath(1); // return "xxx/zzz/" from ecm directory
225				$newdir = $conf->ecm->dir_output.'/'.$newdir;
226				//print $olddir.'-'.$newdir;
227				$result = @rename($olddir, $newdir);
228				if (!$result) {
229					$langs->load('errors');
230					setEventMessages($langs->trans('ErrorFailToRenameDir', $olddir, $newdir), null, 'errors');
231					$error++;
232				}
233			}
234
235			if (!$error) {
236				$db->commit();
237
238				// Set new value after renaming
239				$relativepath = $ecmdir->getRelativePath();
240				$upload_dir = $conf->ecm->dir_output.'/'.$relativepath;
241			} else {
242				$db->rollback();
243			}
244		} else {
245			$db->rollback();
246			setEventMessages($ecmdir->error, $ecmdir->errors, 'errors');
247		}
248	} else {
249		$newdir = $conf->medias->multidir_output[$conf->entity].'/'.GETPOST('oldrelparentdir', 'alpha').'/'.GETPOST('label', 'alpha');
250
251		$result = @rename($olddir, $newdir);
252		if (!$result) {
253			$langs->load('errors');
254			setEventMessages($langs->trans('ErrorFailToRenameDir', $olddir, $newdir), null, 'errors');
255			$error++;
256		}
257
258		if (!$error) {
259			// Set new value after renaming
260			$relativepath = GETPOST('oldrelparentdir', 'alpha').'/'.GETPOST('label', 'alpha');
261			$upload_dir = $conf->medias->multidir_output[$conf->entity].'/'.$relativepath;
262			$section = $relativepath;
263		}
264	}
265}
266
267
268/*
269 * View
270 */
271
272$form = new Form($db);
273
274$object = new EcmDirectory($db); // Need to create a new one instance
275$extrafields = new ExtraFields($db);
276// fetch optionals attributes and labels
277$extrafields->fetch_name_optionals_label($object->table_element);
278
279if ($module == 'ecm' && $ecmdir->id > 0) {
280	$object->fetch($ecmdir->id);
281}
282
283llxHeader();
284
285// Built the file List
286$filearrayall = dol_dir_list($upload_dir, "all", 0, '', '', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
287$filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
288$totalsize = 0;
289foreach ($filearray as $key => $file) {
290	$totalsize += $file['size'];
291}
292
293
294$head = ecm_prepare_head($ecmdir, $module, $section);
295print dol_get_fiche_head($head, 'card', $langs->trans("ECMSectionManual"), -1, 'dir');
296
297
298if ($action == 'edit') {
299	print '<form name="update" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
300	print '<input type="hidden" name="token" value="'.newToken().'">';
301	print '<input type="hidden" name="section" value="'.$section.'">';
302	print '<input type="hidden" name="module" value="'.$module.'">';
303	print '<input type="hidden" name="action" value="update">';
304}
305
306
307$morehtml = '';
308
309$morehtmlref = '/'.$module.'/'.$relativepath;
310
311if ($module == 'ecm') {
312	$s = '';
313	$result = 1;
314	$i = 0;
315	$tmpecmdir = new EcmDirectory($db); // Need to create a new one
316	if ($ecmdir->id > 0) {
317		$tmpecmdir->fetch($ecmdir->id);
318		while ($tmpecmdir && $result > 0) {
319			$tmpecmdir->ref = $tmpecmdir->label;
320			if ($i == 0 && $action == 'edit') {
321				$s = '<input type="text" name="label" class="minwidth300" maxlength="32" value="'.$tmpecmdir->label.'">';
322			} else {
323				$s = $tmpecmdir->getNomUrl(1).$s;
324			}
325			if ($tmpecmdir->fk_parent) {
326				$s = ' -> '.$s;
327				$result = $tmpecmdir->fetch($tmpecmdir->fk_parent);
328			} else {
329				$tmpecmdir = 0;
330			}
331			$i++;
332		}
333	} else {
334		$s .= join(' -> ', explode('/', $section));
335	}
336	$morehtmlref = '<a href="'.DOL_URL_ROOT.'/ecm/index.php">'.$langs->trans("ECMRoot").'</a> -> '.$s;
337}
338if ($module == 'medias') {
339	$s = 'medias -> ';
340	$result = 1;
341	$subdirs = explode('/', $section);
342	$i = 0;
343	foreach ($subdirs as $subdir) {
344		if ($i == (count($subdirs) - 1)) {
345			if ($action == 'edit') {
346				$s .= '<input type="text" name="label" class="minwidth300" maxlength="32" value="'.$subdir.'">';
347				$s .= '<input type="hidden" name="oldrelparentdir" value="'.dirname($section).'">';
348				$s .= '<input type="hidden" name="oldreldir" value="'.basename($section).'">';
349			} else {
350				$s .= $subdir;
351			}
352		}
353		if ($i < (count($subdirs) - 1)) {
354			$s .= $subdir.' -> ';
355		}
356		$i++;
357	}
358
359	$morehtmlref = $s;
360}
361
362
363dol_banner_tab($object, '', $morehtml, 0, '', '', $morehtmlref);
364
365print '<div class="fichecenter">';
366
367print '<div class="underbanner clearboth"></div>';
368print '<table class="border centpercent tableforfield">';
369/*print '<tr><td class="titlefield">'.$langs->trans("Ref").'</td><td>';
370print img_picto('','object_dir').' <a href="'.DOL_URL_ROOT.'/ecm/index.php">'.$langs->trans("ECMRoot").'</a> -> ';
371print $s;
372print '</td></tr>';*/
373if ($module == 'ecm') {
374	print '<tr><td class="titlefield tdtop">'.$langs->trans("Description").'</td><td>';
375	if ($action == 'edit') {
376		print '<textarea class="flat quatrevingtpercent" name="description">';
377		print $ecmdir->description;
378		print '</textarea>';
379	} else {
380		print dol_nl2br($ecmdir->description);
381	}
382	print '</td></tr>';
383
384	print '<tr><td class="titlefield">'.$langs->trans("ECMCreationUser").'</td><td>';
385	if ($ecmdir->fk_user_c > 0) {
386		$userecm = new User($db);
387		$userecm->fetch($ecmdir->fk_user_c);
388		print $userecm->getNomUrl(1);
389	}
390	print '</td></tr>';
391}
392print '<tr><td class="titlefield">'.$langs->trans("ECMCreationDate").'</td><td>';
393if ($module == 'ecm') {
394	print dol_print_date($ecmdir->date_c, 'dayhour');
395} else {
396	//var_dump($upload_dir);
397	print dol_print_date(dol_filemtime($upload_dir), 'dayhour');
398}
399print '</td></tr>';
400print '<tr><td>'.$langs->trans("ECMDirectoryForFiles").'</td><td>';
401if ($module == 'ecm') {
402	print '/ecm/'.$relativepath;
403} else {
404	print '/'.$module.'/'.$relativepath;
405}
406print '</td></tr>';
407print '<tr><td>'.$langs->trans("ECMNbOfDocs").'</td><td>';
408$nbofiles = count($filearray);
409print $nbofiles;
410if ($ecmdir->id > 0) {
411	// Test if nb is same than in cache
412	if ($nbofiles != $ecmdir->cachenbofdoc) {
413		$ecmdir->changeNbOfFiles((string) $nbofiles);
414	}
415}
416print '</td></tr>';
417print '<tr><td>'.$langs->trans("TotalSizeOfAttachedFiles").'</td><td>';
418print dol_print_size($totalsize);
419print '</td></tr>';
420print $object->showOptionals($extrafields, ($action == 'edit' ? 'edit' : 'view'));
421print '</table>';
422
423if ($action == 'edit') {
424	print '<br><div align="center">';
425	print '<input type="submit" class="button button-save" name="submit" value="'.$langs->trans("Save").'">';
426	print ' &nbsp; &nbsp; ';
427	print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
428	print '</div>';
429}
430
431print '</div>';
432if ($action == 'edit') {
433	print '</form>';
434}
435
436print dol_get_fiche_end();
437
438
439
440// Actions buttons
441if ($action != 'edit' && $action != 'delete') {
442	print '<div class="tabsAction">';
443
444	if ($permtoadd) {
445		print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=edit'.($module ? '&module='.$module : '').'&section='.$section.'">'.$langs->trans('Edit').'</a>';
446	}
447
448	if ($permtoadd) {
449		print '<a class="butAction" href="'.DOL_URL_ROOT.'/ecm/dir_add_card.php?action=create'.($module ? '&module='.$module : '').'&catParent='.$section.'">'.$langs->trans('ECMAddSection').'</a>';
450	} else {
451		print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotAllowed").'">'.$langs->trans('ECMAddSection').'</a>';
452	}
453
454	//if (count($filearrayall) == 0)
455	//{
456	if ($permtoadd) {
457		print '<a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?action=delete_dir&token='.newToken().($module ? '&module='.$module : '').'&section='.$section.($backtopage ? '&backtopage='.urlencode($backtopage) : '').'">'.$langs->trans('Delete').'</a>';
458	} else {
459		print '<a class="butActionDeleteRefused" href="#" title="'.$langs->trans("NotAllowed").'">'.$langs->trans('Delete').'</a>';
460	}
461	/*}
462	else
463	{
464		if (count($filearray) > 0)
465			print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("CannotRemoveDirectoryContainsFiles").'">'.$langs->trans('Delete').'</a>';
466		else
467			print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("CannotRemoveDirectoryContainsFilesOrDirs").'">'.$langs->trans('Delete').'</a>';
468	}*/
469	print '</div>';
470}
471
472// Confirm remove file
473if ($action == 'delete') {
474	print $form->formconfirm($_SERVER["PHP_SELF"].'?section='.GETPOST("section", 'alpha').'&urlfile='.urlencode($_GET["urlfile"]).($backtopage ? '&backtopage='.urlencode($backtopage) : ''), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile');
475}
476
477// Confirm remove file
478if ($action == 'delete_dir') {
479	$relativepathwithoutslash = preg_replace('/[\/]$/', '', $relativepath);
480
481	//Form to close proposal (signed or not)
482	if (count($filearrayall) > 0) {
483		$langs->load("other");
484		$formquestion = array(
485			array('type' => 'checkbox', 'name' => 'deletedirrecursive', 'label' => $langs->trans("ContentOfDirectoryIsNotEmpty").'<br>'.$langs->trans("DeleteAlsoContentRecursively"), 'value' => '0')				// Field to complete private note (not replace)
486		);
487	}
488
489	print $form->formconfirm($_SERVER["PHP_SELF"].'?section='.GETPOST('section', 'alpha').($module ? '&module='.$module : '').($backtopage ? '&backtopage='.urlencode($backtopage) : ''), $langs->trans('DeleteSection'), $langs->trans('ConfirmDeleteSection', $relativepathwithoutslash), 'confirm_deletedir', $formquestion, 1, 1);
490}
491
492
493/*
494$formfile=new FormFile($db);
495
496// Display upload form
497if ($user->rights->ecm->upload)
498{
499	$formfile->form_attach_new_file(DOL_URL_ROOT.'/ecm/dir_card.php','',0,$section);
500}
501
502// List of document
503if ($user->rights->ecm->read)
504{
505	$param='&amp;section='.$section;
506	$formfile->list_of_documents($filearray,'','ecm',$param,1,$relativepath,$user->rights->ecm->upload);
507}
508*/
509
510// End of page
511llxFooter();
512$db->close();
513