1<?php
2/* Copyright (C) 2013-2017 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2014      Marcos García       <marcosgdf@gmail.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
18
19/**
20 *	\file       htdocs/opensurvey/list.php
21 *	\ingroup    opensurvey
22 *	\brief      Page to list surveys
23 */
24
25require '../main.inc.php';
26require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php";
27require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php";
28require_once DOL_DOCUMENT_ROOT."/opensurvey/class/opensurveysondage.class.php";
29
30// Load translation files required by the page
31$langs->load("opensurvey");
32
33$action     = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ...
34$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
35$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ?
36$confirm    = GETPOST('confirm', 'alpha'); // Result of a confirmation
37$cancel     = GETPOST('cancel', 'alpha'); // We click on a Cancel button
38$toselect   = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list
39$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'opensurveylist'; // To manage different context of search
40$backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page
41$optioncss  = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
42
43$id = GETPOST('id', 'alpha');
44$search_ref = GETPOST('search_ref', 'alpha');
45$search_title = GETPOST('search_title', 'alpha');
46$search_status = GETPOST('search_status', 'alpha');
47
48// Load variable for pagination
49$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
50$sortfield = GETPOST('sortfield', 'aZ09comma');
51$sortorder = GETPOST('sortorder', 'aZ09comma');
52$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
53if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; }     // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action
54$offset = $limit * $page;
55$pageprev = $page - 1;
56$pagenext = $page + 1;
57
58// Initialize technical objects
59$object = new Opensurveysondage($db);
60$opensurvey_static = new Opensurveysondage($db);
61
62$extrafields = new ExtraFields($db);
63$diroutputmassaction = $conf->opensurvey->dir_output.'/temp/massgeneration/'.$user->id;
64$hookmanager->initHooks(array('surveylist')); // Note that conf->hooks_modules contains array
65// Fetch optionals attributes and labels
66$extrafields->fetch_name_optionals_label($object->table_element);
67$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
68
69// Default sort order (if not yet defined by previous GETPOST)
70if (!$sortfield) $sortfield = "p.date_fin";
71if (!$sortorder) $sortorder = "DESC";
72
73// Security check
74if (!$user->rights->opensurvey->read) accessforbidden();
75
76// Definition of fields for list
77$arrayfields = array();
78foreach ($arrayfields as $key => $val)
79{
80	// If $val['visible']==0, then we never show the field
81	if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>$val['enabled'], 'position'=>$val['position']);
82}
83// Extra fields
84if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0)
85{
86	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val)
87	{
88		if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) {
89			$arrayfields["ef.".$key] = array(
90				'label'=>$extrafields->attributes[$object->table_element]['label'][$key],
91				'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1),
92				'position'=>$extrafields->attributes[$object->table_element]['pos'][$key],
93				'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])
94			);
95		}
96	}
97}
98$object->fields = dol_sort_array($object->fields, 'position');
99$arrayfields = dol_sort_array($arrayfields, 'position');
100
101$permissiontoread = $user->rights->opensurvey->read;
102$permissiontoadd = $user->rights->opensurvey->write;
103$permissiontodelete = $user->rights->opensurvey->delete;
104
105
106/*
107 * Actions
108 */
109
110if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; }
111if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; }
112
113$parameters = array();
114$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
115if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
116
117if (empty($reshook))
118{
119	// Selection of new fields
120	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
121
122	// Purge search criteria
123	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
124	{
125		$search_status = '';
126		$search_title = '';
127		$search_ref = '';
128		$toselect = '';
129		$search_array_options = array();
130	}
131	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
132		|| GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha'))
133	{
134		$massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
135	}
136
137	// Mass actions
138	$objectclass = 'Opensurveysondage';
139	$objectlabel = 'Opensurveysondage';
140	$uploaddir = $conf->opensurvey->dir_output;
141	include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
142}
143
144
145/*
146 * View
147 */
148
149$form = new Form($db);
150
151$now = dol_now();
152
153//$help_url="EN:Module_MyObject|FR:Module_MyObject_FR|ES:Módulo_MyObject";
154$help_url = '';
155$title = $langs->trans('OpenSurveyArea');
156
157
158$sql = "SELECT p.id_sondage as rowid, p.fk_user_creat, p.format, p.date_fin, p.status, p.titre as title, p.nom_admin, p.tms,";
159$sql .= " u.login, u.firstname, u.lastname";
160$sql .= " FROM ".MAIN_DB_PREFIX."opensurvey_sondage as p";
161$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user u ON u.rowid = p.fk_user_creat";
162$sql .= " WHERE p.entity IN (".getEntity('survey').")";
163if ($search_status != '-1' && $search_status != '') $sql .= natural_search("p.status", $search_status, 2);
164if ($search_expired == 'expired') $sql .= " AND p.date_fin < '".$db->idate($now)."'";
165if ($search_expired == 'opened')  $sql .= " AND p.date_fin >= '".$db->idate($now)."'";
166if ($search_ref) $sql .= natural_search("p.id_sondage", $search_ref);
167if ($search_title) $sql .= natural_search("p.titre", $search_title);
168// Add where from extra fields
169include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
170// Add where from hooks
171$parameters = array();
172$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
173$sql .= $hookmanager->resPrint;
174
175$sql .= $db->order($sortfield, $sortorder);
176
177// Count total nb of records
178$nbtotalofrecords = '';
179if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
180{
181	$resql = $db->query($sql);
182	$nbtotalofrecords = $db->num_rows($resql);
183	if (($page * $limit) > $nbtotalofrecords)	// if total of record found is smaller than page * limit, goto and load page 0
184	{
185		$page = 0;
186		$offset = 0;
187	}
188}
189// if total of record found is smaller than limit, no need to do paging and to restart another select with limits set.
190if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords)
191{
192	$num = $nbtotalofrecords;
193} else {
194	$sql .= $db->plimit($limit + 1, $offset);
195
196	$resql = $db->query($sql);
197	if (!$resql)
198	{
199		dol_print_error($db);
200		exit;
201	}
202
203	$num = $db->num_rows($resql);
204}
205
206// Direct jump if only one record found
207if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all)
208{
209	$obj = $db->fetch_object($resql);
210	$id = $obj->rowid;
211	header("Location: ".dol_buildpath('/opensurvey/card.php', 1).'?id='.$id);
212	exit;
213}
214
215
216// Output page
217// --------------------------------------------------------------------
218
219llxHeader('', $title, $help_url);
220
221$arrayofselected = is_array($toselect) ? $toselect : array();
222
223$param = '';
224if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
225if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
226$fieldtosortuser = empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 'firstname' : 'lastname';
227
228if ($optioncss != '')     $param .= '&optioncss='.urlencode($optioncss);
229// Add $param from extra fields
230include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
231
232// List of mass actions available
233$arrayofmassactions = array(
234	//'presend'=>$langs->trans("SendByMail"),
235	//'builddoc'=>$langs->trans("PDFMerge"),
236);
237if ($permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
238if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array();
239$massactionbutton = $form->selectMassAction('', $arrayofmassactions);
240
241
242// List of surveys into database
243
244print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
245if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
246print '<input type="hidden" name="token" value="'.newToken().'">';
247print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
248print '<input type="hidden" name="action" value="list">';
249print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
250print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
251print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
252
253$newcardbutton = dolGetButtonTitle($langs->trans('NewSurvey'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/opensurvey/wizard/index.php', '', $user->rights->opensurvey->write);
254
255print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'poll', 0, $newcardbutton, '', $limit, 0, 0, 1);
256
257// Add code for pre mass action (confirmation or email presend form)
258$topicmail = "SendOpenSurveyRef";
259$modelmail = "opensurvey";
260$objecttmp = new Opensurveysondage($db);
261$trackid = 'surv'.$object->id;
262include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
263
264if ($sall)
265{
266	foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val);
267	print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>';
268}
269
270$moreforfilter = '';
271/*$moreforfilter.='<div class="divsearchfield">';
272$moreforfilter.= $langs->trans('MyFilter') . ': <input type="text" name="search_myfield" value="'.dol_escape_htmltag($search_myfield).'">';
273$moreforfilter.= '</div>';*/
274
275$parameters = array();
276$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
277if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint;
278else $moreforfilter = $hookmanager->resPrint;
279
280if (!empty($moreforfilter))
281{
282	print '<div class="liste_titre liste_titre_bydiv centpercent">';
283	print $moreforfilter;
284	print '</div>';
285}
286
287$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
288//$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage);	// This also change content of $arrayfields
289$selectedfields = '';
290$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : '');
291
292print '<div class="div-table-responsive">';
293print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
294
295// Fields title search
296// --------------------------------------------------------------------
297print '<tr class="liste_titre_filter">';
298print '<td class="liste_titre"><input type="text" class="maxwidth100" name="search_ref" value="'.dol_escape_htmltag($search_ref).'"></td>';
299print '<td class="liste_titre"><input type="text" class="maxwidth100onsmartphone" name="search_title" value="'.dol_escape_htmltag($search_title).'"></td>';
300print '<td class="liste_titre"></td>';
301print '<td class="liste_titre"></td>';
302print '<td class="liste_titre"></td>';
303print '<td class="liste_titre"></td>';
304print '<td class="liste_titre"></td>';
305$arraystatus = array('-1'=>'&nbsp;', '0'=>$langs->trans("Draft"), '1'=>$langs->trans("Opened"), '2'=>$langs->trans("Closed"));
306print '<td class="liste_titre" align="center">'.$form->selectarray('search_status', $arraystatus, $search_status).'</td>';
307// Extra fields
308include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
309
310// Fields from hook
311$parameters = array('arrayfields'=>$arrayfields);
312$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook
313print $hookmanager->resPrint;
314// Action column
315print '<td class="liste_titre maxwidthsearch">';
316$searchpicto = $form->showFilterButtons();
317print $searchpicto;
318print '</td>';
319print '</tr>'."\n";
320
321
322// Fields title label
323// --------------------------------------------------------------------
324print '<tr class="liste_titre">';
325print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "p.id_sondage", $param, "", "", $sortfield, $sortorder);
326print_liste_field_titre("Title", $_SERVER["PHP_SELF"], "p.titre", $param, "", "", $sortfield, $sortorder);
327print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "p.format", $param, "", "", $sortfield, $sortorder);
328print_liste_field_titre("Author", $_SERVER["PHP_SELF"], "u.".$fieldtosortuser, $param, "", "", $sortfield, $sortorder);
329print_liste_field_titre("NbOfVoters", $_SERVER["PHP_SELF"], "", $param, "", 'align="right"', $sortfield, $sortorder);
330print_liste_field_titre("ExpireDate", $_SERVER["PHP_SELF"], "p.date_fin", $param, "", 'align="center"', $sortfield, $sortorder);
331print_liste_field_titre("DateLastModification", $_SERVER["PHP_SELF"], "p.tms", $param, "", 'align="center"', $sortfield, $sortorder);
332print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "p.status", $param, "", 'align="center"', $sortfield, $sortorder);
333// Extra fields
334include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
335// Hook fields
336$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder);
337$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
338print $hookmanager->resPrint;
339// Action column
340print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch ')."\n";
341print '</tr>'."\n";
342
343
344
345// Loop on record
346// --------------------------------------------------------------------
347$i = 0;
348$totalarray = array();
349while ($i < min($num, $limit))
350{
351	$obj = $db->fetch_object($resql);
352	if (empty($obj)) break; // Should not happen
353
354	$sql2 = 'select COUNT(*) as nb from '.MAIN_DB_PREFIX."opensurvey_user_studs where id_sondage='".$db->escape($obj->rowid)."'";
355	$resql2 = $db->query($sql2);
356	if ($resql2)
357	{
358		$obj2 = $db->fetch_object($resql2);
359		$nbuser = $obj2->nb;
360	} else dol_print_error($db);
361
362	$opensurvey_static->id = $obj->rowid;
363	$opensurvey_static->ref = $obj->rowid;
364	$opensurvey_static->title = $obj->title;
365	$opensurvey_static->status = $obj->status;
366	$opensurvey_static->date_fin = $db->jdate($obj->date_fin);
367
368	// Show here line of result
369	print '<tr class="oddeven">';
370
371	// Ref
372	print '<td>';
373	print $opensurvey_static->getNomUrl(1);
374	print '</td>';
375	if (!$i) $totalarray['nbfield']++;
376
377	// Title
378	print '<td>'.dol_htmlentities($obj->title).'</td>';
379	if (!$i) $totalarray['nbfield']++;
380
381	// Type
382	print '<td>';
383	$type = ($obj->format == 'A') ? 'classic' : 'date';
384	print img_picto('', dol_buildpath('/opensurvey/img/'.($type == 'classic' ? 'chart-32.png' : 'calendar-32.png'), 1), 'width="16"', 1);
385	print ' '.$langs->trans($type == 'classic' ? "TypeClassic" : "TypeDate");
386	print '</td>';
387	if (!$i) $totalarray['nbfield']++;
388
389	print '<td>';
390	// Author
391	if ($obj->fk_user_creat) {
392		$userstatic = new User($db);
393		$userstatic->id = $obj->fk_user_creat;
394		$userstatic->firstname = $obj->firstname;
395		$userstatic->lastname = $obj->lastname;
396		$userstatic->login = $userstatic->getFullName($langs, 0, -1, 48);
397
398		print $userstatic->getLoginUrl(1);
399	} else {
400		print dol_htmlentities($obj->nom_admin);
401	}
402	print '</td>';
403	if (!$i) $totalarray['nbfield']++;
404
405	// Nb of voters
406	print'<td class="right">'.$nbuser.'</td>'."\n";
407	if (!$i) $totalarray['nbfield']++;
408
409	print '<td class="center">'.dol_print_date($db->jdate($obj->date_fin), 'day');
410	if ($db->jdate($obj->date_fin) < $now && $obj->status == Opensurveysondage::STATUS_VALIDATED) { print img_warning($langs->trans("Expired")); }
411	print '</td>';
412	if (!$i) $totalarray['nbfield']++;
413
414	print '<td class="center">'.dol_print_date($db->jdate($obj->tms), 'dayhour');
415	print '</td>';
416	if (!$i) $totalarray['nbfield']++;
417
418	print '<td class="center">'.$opensurvey_static->getLibStatut(5).'</td>'."\n";
419	if (!$i) $totalarray['nbfield']++;
420
421	// Extra fields
422	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
423	// Fields from hook
424	$parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray);
425	$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook
426	print $hookmanager->resPrint;
427	// Action column
428	print '<td class="nowrap center">';
429	if ($massactionbutton || $massaction)   // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
430	{
431		$selected = 0;
432		if (in_array($obj->rowid, $arrayofselected)) $selected = 1;
433		print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
434	}
435	print '</td>';
436	if (!$i) $totalarray['nbfield']++;
437
438	print '</tr>'."\n";
439	$i++;
440}
441
442// Show total line
443include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
444
445
446// If no record found
447if ($num == 0)
448{
449	$colspan = 8;
450	foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; }
451	print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
452}
453
454
455$db->free($resql);
456
457$parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql);
458$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook
459print $hookmanager->resPrint;
460
461print '</table>'."\n";
462print '</div>'."\n";
463
464print '</form>'."\n";
465
466if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords))
467{
468	$hidegeneratedfilelistifempty = 1;
469	if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0;
470
471	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
472	$formfile = new FormFile($db);
473
474	// Show list of available documents
475	$urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
476	$urlsource .= str_replace('&amp;', '&', $param);
477
478	$filedir = $diroutputmassaction;
479	$genallowed = $permissiontoread;
480	$delallowed = $permissiontoadd;
481
482	print $formfile->showdocuments('massfilesarea_mymodule', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty);
483}
484
485// End of page
486llxFooter();
487$db->close();
488