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