myobject_list.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  1. <?php
  2. /* Copyright (C) 2007-2017 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) ---Put here your own copyright and developer email---
  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. * \file htdocs/modulebuilder/template/myobject_list.php
  20. * \ingroup mymodule
  21. * \brief List page for myobject
  22. */
  23. //if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db
  24. //if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user
  25. //if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc
  26. //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs
  27. //if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters
  28. //if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters
  29. //if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on).
  30. //if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
  31. //if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data
  32. //if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu
  33. //if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php
  34. //if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library
  35. //if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too.
  36. //if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip
  37. //if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT', 'auto'); // Force lang to a particular value
  38. //if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler
  39. //if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', 1); // The main.inc.php does not make a redirect if not logged, instead show simple error message
  40. //if (! defined("FORCECSP")) define('FORCECSP', 'none'); // Disable all Content Security Policies
  41. //if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET
  42. //if (! defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); // Disable browser notification
  43. //if (! defined('NOSESSION')) define('NOSESSION', '1'); // On CLI mode, no need to use web sessions
  44. // Load Dolibarr environment
  45. $res = 0;
  46. // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
  47. if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) {
  48. $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
  49. }
  50. // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
  51. $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
  52. while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) {
  53. $i--; $j--;
  54. }
  55. if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) {
  56. $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
  57. }
  58. if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) {
  59. $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
  60. }
  61. // Try main.inc.php using relative path
  62. if (!$res && file_exists("../main.inc.php")) {
  63. $res = @include "../main.inc.php";
  64. }
  65. if (!$res && file_exists("../../main.inc.php")) {
  66. $res = @include "../../main.inc.php";
  67. }
  68. if (!$res && file_exists("../../../main.inc.php")) {
  69. $res = @include "../../../main.inc.php";
  70. }
  71. if (!$res) {
  72. die("Include of main fails");
  73. }
  74. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
  75. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  76. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  77. // load mymodule libraries
  78. require_once __DIR__.'/class/myobject.class.php';
  79. // for other modules
  80. //dol_include_once('/othermodule/class/otherobject.class.php');
  81. // Load translation files required by the page
  82. $langs->loadLangs(array("mymodule@mymodule", "other"));
  83. $action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ...
  84. $massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
  85. $show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ?
  86. $confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation
  87. $cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button
  88. $toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list
  89. $contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'myobjectlist'; // To manage different context of search
  90. $backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page
  91. $optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
  92. $id = GETPOST('id', 'int');
  93. // Load variable for pagination
  94. $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
  95. $sortfield = GETPOST('sortfield', 'aZ09comma');
  96. $sortorder = GETPOST('sortorder', 'aZ09comma');
  97. $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
  98. if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) {
  99. // If $page is not defined, or '' or -1 or if we click on clear filters
  100. $page = 0;
  101. }
  102. $offset = $limit * $page;
  103. $pageprev = $page - 1;
  104. $pagenext = $page + 1;
  105. // Initialize technical objects
  106. $object = new MyObject($db);
  107. $extrafields = new ExtraFields($db);
  108. $diroutputmassaction = $conf->mymodule->dir_output.'/temp/massgeneration/'.$user->id;
  109. $hookmanager->initHooks(array('myobjectlist')); // Note that conf->hooks_modules contains array
  110. // Fetch optionals attributes and labels
  111. $extrafields->fetch_name_optionals_label($object->table_element);
  112. //$extrafields->fetch_name_optionals_label($object->table_element_line);
  113. $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
  114. // Default sort order (if not yet defined by previous GETPOST)
  115. if (!$sortfield) {
  116. reset($object->fields); // Reset is required to avoid key() to return null.
  117. $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition.
  118. }
  119. if (!$sortorder) {
  120. $sortorder = "ASC";
  121. }
  122. // Initialize array of search criterias
  123. $search_all = GETPOST('search_all', 'alphanohtml');
  124. $search = array();
  125. foreach ($object->fields as $key => $val) {
  126. if (GETPOST('search_'.$key, 'alpha') !== '') {
  127. $search[$key] = GETPOST('search_'.$key, 'alpha');
  128. }
  129. if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
  130. $search[$key.'_dtstart'] = dol_mktime(0, 0, 0, GETPOST('search_'.$key.'_dtstartmonth', 'int'), GETPOST('search_'.$key.'_dtstartday', 'int'), GETPOST('search_'.$key.'_dtstartyear', 'int'));
  131. $search[$key.'_dtend'] = dol_mktime(23, 59, 59, GETPOST('search_'.$key.'_dtendmonth', 'int'), GETPOST('search_'.$key.'_dtendday', 'int'), GETPOST('search_'.$key.'_dtendyear', 'int'));
  132. }
  133. }
  134. // List of fields to search into when doing a "search in all"
  135. $fieldstosearchall = array();
  136. foreach ($object->fields as $key => $val) {
  137. if (!empty($val['searchall'])) {
  138. $fieldstosearchall['t.'.$key] = $val['label'];
  139. }
  140. }
  141. // Definition of array of fields for columns
  142. $arrayfields = array();
  143. foreach ($object->fields as $key => $val) {
  144. // If $val['visible']==0, then we never show the field
  145. if (!empty($val['visible'])) {
  146. $visible = (int) dol_eval($val['visible'], 1);
  147. $arrayfields['t.'.$key] = array(
  148. 'label'=>$val['label'],
  149. 'checked'=>(($visible < 0) ? 0 : 1),
  150. 'enabled'=>($visible != 3 && dol_eval($val['enabled'], 1)),
  151. 'position'=>$val['position'],
  152. 'help'=> isset($val['help']) ? $val['help'] : ''
  153. );
  154. }
  155. }
  156. // Extra fields
  157. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php';
  158. $object->fields = dol_sort_array($object->fields, 'position');
  159. $arrayfields = dol_sort_array($arrayfields, 'position');
  160. $permissiontoread = $user->rights->mymodule->myobject->read;
  161. $permissiontoadd = $user->rights->mymodule->myobject->write;
  162. $permissiontodelete = $user->rights->mymodule->myobject->delete;
  163. // Security check
  164. if (empty($conf->mymodule->enabled)) {
  165. accessforbidden('Module not enabled');
  166. }
  167. // Security check (enable the most restrictive one)
  168. if ($user->socid > 0) accessforbidden();
  169. //if ($user->socid > 0) accessforbidden();
  170. //$socid = 0; if ($user->socid > 0) $socid = $user->socid;
  171. //$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0);
  172. //restrictedArea($user, $object->element, $object->id, $object->table_element, '', 'fk_soc', 'rowid', $isdraft);
  173. //if (empty($conf->mymodule->enabled)) accessforbidden();
  174. //if (!$permissiontoread) accessforbidden();
  175. /*
  176. * Actions
  177. */
  178. if (GETPOST('cancel', 'alpha')) {
  179. $action = 'list';
  180. $massaction = '';
  181. }
  182. if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
  183. $massaction = '';
  184. }
  185. $parameters = array();
  186. $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  187. if ($reshook < 0) {
  188. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  189. }
  190. if (empty($reshook)) {
  191. // Selection of new fields
  192. include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
  193. // Purge search criteria
  194. 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
  195. foreach ($object->fields as $key => $val) {
  196. $search[$key] = '';
  197. if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
  198. $search[$key.'_dtstart'] = '';
  199. $search[$key.'_dtend'] = '';
  200. }
  201. }
  202. $toselect = array();
  203. $search_array_options = array();
  204. }
  205. if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
  206. || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) {
  207. $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
  208. }
  209. // Mass actions
  210. $objectclass = 'MyObject';
  211. $objectlabel = 'MyObject';
  212. $uploaddir = $conf->mymodule->dir_output;
  213. include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
  214. }
  215. /*
  216. * View
  217. */
  218. $form = new Form($db);
  219. $now = dol_now();
  220. //$help_url="EN:Module_MyObject|FR:Module_MyObject_FR|ES:Módulo_MyObject";
  221. $help_url = '';
  222. $title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("MyObjects"));
  223. $morejs = array();
  224. $morecss = array();
  225. // Build and execute select
  226. // --------------------------------------------------------------------
  227. $sql = 'SELECT ';
  228. $sql .= $object->getFieldList('t');
  229. // Add fields from extrafields
  230. if (!empty($extrafields->attributes[$object->table_element]['label'])) {
  231. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
  232. $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key." as options_".$key : '');
  233. }
  234. }
  235. // Add fields from hooks
  236. $parameters = array();
  237. $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook
  238. $sql .= preg_replace('/^,/', '', $hookmanager->resPrint);
  239. $sql = preg_replace('/,\s*$/', '', $sql);
  240. $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t";
  241. if (isset($extrafields->attributes[$object->table_element]['label']) && is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) {
  242. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)";
  243. }
  244. // Add table from hooks
  245. $parameters = array();
  246. $reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object); // Note that $action and $object may have been modified by hook
  247. $sql .= $hookmanager->resPrint;
  248. if ($object->ismultientitymanaged == 1) {
  249. $sql .= " WHERE t.entity IN (".getEntity($object->element).")";
  250. } else {
  251. $sql .= " WHERE 1 = 1";
  252. }
  253. foreach ($search as $key => $val) {
  254. if (array_key_exists($key, $object->fields)) {
  255. if ($key == 'status' && $search[$key] == -1) {
  256. continue;
  257. }
  258. $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0);
  259. if ((strpos($object->fields[$key]['type'], 'integer:') === 0) || (strpos($object->fields[$key]['type'], 'sellist:') === 0) || !empty($object->fields[$key]['arrayofkeyval'])) {
  260. if ($search[$key] == '-1' || ($search[$key] === '0' && (empty($object->fields[$key]['arrayofkeyval']) || !array_key_exists('0', $object->fields[$key]['arrayofkeyval'])))) {
  261. $search[$key] = '';
  262. }
  263. $mode_search = 2;
  264. }
  265. if ($search[$key] != '') {
  266. $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search));
  267. }
  268. } else {
  269. if (preg_match('/(_dtstart|_dtend)$/', $key) && $search[$key] != '') {
  270. $columnName = preg_replace('/(_dtstart|_dtend)$/', '', $key);
  271. if (preg_match('/^(date|timestamp|datetime)/', $object->fields[$columnName]['type'])) {
  272. if (preg_match('/_dtstart$/', $key)) {
  273. $sql .= " AND t.".$columnName." >= '".$db->idate($search[$key])."'";
  274. }
  275. if (preg_match('/_dtend$/', $key)) {
  276. $sql .= " AND t." . $columnName . " <= '" . $db->idate($search[$key]) . "'";
  277. }
  278. }
  279. }
  280. }
  281. }
  282. if ($search_all) {
  283. $sql .= natural_search(array_keys($fieldstosearchall), $search_all);
  284. }
  285. //$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear);
  286. // Add where from extra fields
  287. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
  288. // Add where from hooks
  289. $parameters = array();
  290. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
  291. $sql .= $hookmanager->resPrint;
  292. /* If a group by is required
  293. $sql .= " GROUP BY ";
  294. foreach($object->fields as $key => $val) {
  295. $sql .= "t.".$key.", ";
  296. }
  297. // Add fields from extrafields
  298. if (!empty($extrafields->attributes[$object->table_element]['label'])) {
  299. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
  300. $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.', ' : '');
  301. }
  302. }
  303. // Add where from hooks
  304. $parameters = array();
  305. $reshook = $hookmanager->executeHooks('printFieldListGroupBy', $parameters, $object); // Note that $action and $object may have been modified by hook
  306. $sql .= $hookmanager->resPrint;
  307. $sql = preg_replace('/,\s*$/', '', $sql);
  308. */
  309. // Add HAVING from hooks
  310. /*
  311. $parameters = array();
  312. $reshook = $hookmanager->executeHooks('printFieldListHaving', $parameters, $object); // Note that $action and $object may have been modified by hook
  313. $sql .= !empty($hookmanager->resPrint) ? (" HAVING 1=1 " . $hookmanager->resPrint) : "";
  314. */
  315. // Count total nb of records
  316. $nbtotalofrecords = '';
  317. if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
  318. /* This old and fast method to get and count full list returns all record so use a high amount of memory.
  319. $resql = $db->query($sql);
  320. $nbtotalofrecords = $db->num_rows($resql);
  321. */
  322. /* The slow method does not consume memory on mysql (not tested on pgsql) */
  323. /*$resql = $db->query($sql, 0, 'auto', 1);
  324. while ($db->fetch_object($resql)) {
  325. $nbtotalofrecords++;
  326. }*/
  327. /* The fast and low memory method to get and count full list converts the sql into a sql count */
  328. $sqlforcount = preg_replace('/^SELECT[a-z0-9\._\s\(\),]+FROM/i', 'SELECT COUNT(*) as nbtotalofrecords FROM', $sql);
  329. $resql = $db->query($sqlforcount);
  330. $objforcount = $db->fetch_object($resql);
  331. $nbtotalofrecords = $objforcount->nbtotalofrecords;
  332. if (($page * $limit) > $nbtotalofrecords) { // if total of record found is smaller than page * limit, goto and load page 0
  333. $page = 0;
  334. $offset = 0;
  335. }
  336. $db->free($resql);
  337. }
  338. // Complete request and execute it with limit
  339. $sql .= $db->order($sortfield, $sortorder);
  340. if ($limit) {
  341. $sql .= $db->plimit($limit + 1, $offset);
  342. }
  343. $resql = $db->query($sql);
  344. if (!$resql) {
  345. dol_print_error($db);
  346. exit;
  347. }
  348. $num = $db->num_rows($resql);
  349. // Direct jump if only one record found
  350. if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) {
  351. $obj = $db->fetch_object($resql);
  352. $id = $obj->rowid;
  353. header("Location: ".dol_buildpath('/mymodule/myobject_card.php', 1).'?id='.$id);
  354. exit;
  355. }
  356. // Output page
  357. // --------------------------------------------------------------------
  358. llxHeader('', $title, $help_url, '', 0, 0, $morejs, $morecss, '', '');
  359. // Example : Adding jquery code
  360. // print '<script type="text/javascript">
  361. // jQuery(document).ready(function() {
  362. // function init_myfunc()
  363. // {
  364. // jQuery("#myid").removeAttr(\'disabled\');
  365. // jQuery("#myid").attr(\'disabled\',\'disabled\');
  366. // }
  367. // init_myfunc();
  368. // jQuery("#mybutton").click(function() {
  369. // init_myfunc();
  370. // });
  371. // });
  372. // </script>';
  373. $arrayofselected = is_array($toselect) ? $toselect : array();
  374. $param = '';
  375. if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
  376. $param .= '&contextpage='.urlencode($contextpage);
  377. }
  378. if ($limit > 0 && $limit != $conf->liste_limit) {
  379. $param .= '&limit='.urlencode($limit);
  380. }
  381. foreach ($search as $key => $val) {
  382. if (is_array($search[$key]) && count($search[$key])) {
  383. foreach ($search[$key] as $skey) {
  384. if ($skey != '') {
  385. $param .= '&search_'.$key.'[]='.urlencode($skey);
  386. }
  387. }
  388. } elseif ($search[$key] != '') {
  389. $param .= '&search_'.$key.'='.urlencode($search[$key]);
  390. }
  391. }
  392. if ($optioncss != '') {
  393. $param .= '&optioncss='.urlencode($optioncss);
  394. }
  395. // Add $param from extra fields
  396. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
  397. // Add $param from hooks
  398. $parameters = array();
  399. $reshook = $hookmanager->executeHooks('printFieldListSearchParam', $parameters, $object); // Note that $action and $object may have been modified by hook
  400. $param .= $hookmanager->resPrint;
  401. // List of mass actions available
  402. $arrayofmassactions = array(
  403. //'validate'=>img_picto('', 'check', 'class="pictofixedwidth"').$langs->trans("Validate"),
  404. //'generate_doc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("ReGeneratePDF"),
  405. //'builddoc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("PDFMerge"),
  406. //'presend'=>img_picto('', 'email', 'class="pictofixedwidth"').$langs->trans("SendByMail"),
  407. );
  408. if ($permissiontodelete) {
  409. $arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"').$langs->trans("Delete");
  410. }
  411. if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) {
  412. $arrayofmassactions = array();
  413. }
  414. $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
  415. print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n";
  416. if ($optioncss != '') {
  417. print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
  418. }
  419. print '<input type="hidden" name="token" value="'.newToken().'">';
  420. print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
  421. print '<input type="hidden" name="action" value="list">';
  422. print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
  423. print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
  424. print '<input type="hidden" name="page" value="'.$page.'">';
  425. print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
  426. $newcardbutton = dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', dol_buildpath('/mymodule/myobject_card.php', 1).'?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']), '', $permissiontoadd);
  427. print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'object_'.$object->picto, 0, $newcardbutton, '', $limit, 0, 0, 1);
  428. // Add code for pre mass action (confirmation or email presend form)
  429. $topicmail = "SendMyObjectRef";
  430. $modelmail = "myobject";
  431. $objecttmp = new MyObject($db);
  432. $trackid = 'xxxx'.$object->id;
  433. include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
  434. if ($search_all) {
  435. foreach ($fieldstosearchall as $key => $val) {
  436. $fieldstosearchall[$key] = $langs->trans($val);
  437. }
  438. print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>';
  439. }
  440. $moreforfilter = '';
  441. /*$moreforfilter.='<div class="divsearchfield">';
  442. $moreforfilter.= $langs->trans('MyFilter') . ': <input type="text" name="search_myfield" value="'.dol_escape_htmltag($search_myfield).'">';
  443. $moreforfilter.= '</div>';*/
  444. $parameters = array();
  445. $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
  446. if (empty($reshook)) {
  447. $moreforfilter .= $hookmanager->resPrint;
  448. } else {
  449. $moreforfilter = $hookmanager->resPrint;
  450. }
  451. if (!empty($moreforfilter)) {
  452. print '<div class="liste_titre liste_titre_bydiv centpercent">';
  453. print $moreforfilter;
  454. print '</div>';
  455. }
  456. $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
  457. $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
  458. $selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : '');
  459. print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
  460. print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
  461. // Fields title search
  462. // --------------------------------------------------------------------
  463. print '<tr class="liste_titre">';
  464. foreach ($object->fields as $key => $val) {
  465. $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']);
  466. if ($key == 'status') {
  467. $cssforfield .= ($cssforfield ? ' ' : '').'center';
  468. } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
  469. $cssforfield .= ($cssforfield ? ' ' : '').'center';
  470. } elseif (in_array($val['type'], array('timestamp'))) {
  471. $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
  472. } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID' && empty($val['arrayofkeyval'])) {
  473. $cssforfield .= ($cssforfield ? ' ' : '').'right';
  474. }
  475. if (!empty($arrayfields['t.'.$key]['checked'])) {
  476. print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">';
  477. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  478. print $form->selectarray('search_'.$key, $val['arrayofkeyval'], (isset($search[$key]) ? $search[$key] : ''), $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1);
  479. } elseif ((strpos($val['type'], 'integer:') === 0) || (strpos($val['type'], 'sellist:') === 0)) {
  480. print $object->showInputField($val, $key, (isset($search[$key]) ? $search[$key] : ''), '', '', 'search_', 'maxwidth125', 1);
  481. } elseif (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
  482. print '<div class="nowrap">';
  483. print $form->selectDate($search[$key.'_dtstart'] ? $search[$key.'_dtstart'] : '', "search_".$key."_dtstart", 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'));
  484. print '</div>';
  485. print '<div class="nowrap">';
  486. print $form->selectDate($search[$key.'_dtend'] ? $search[$key.'_dtend'] : '', "search_".$key."_dtend", 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'));
  487. print '</div>';
  488. } elseif ($key == 'lang') {
  489. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
  490. $formadmin = new FormAdmin($db);
  491. print $formadmin->select_language($search[$key], 'search_lang', 0, null, 1, 0, 0, 'minwidth150 maxwidth200', 2);
  492. } else {
  493. print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag(isset($search[$key]) ? $search[$key] : '').'">';
  494. }
  495. print '</td>';
  496. }
  497. }
  498. // Extra fields
  499. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
  500. // Fields from hook
  501. $parameters = array('arrayfields'=>$arrayfields);
  502. $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook
  503. print $hookmanager->resPrint;
  504. // Action column
  505. print '<td class="liste_titre maxwidthsearch">';
  506. $searchpicto = $form->showFilterButtons();
  507. print $searchpicto;
  508. print '</td>';
  509. print '</tr>'."\n";
  510. // Fields title label
  511. // --------------------------------------------------------------------
  512. print '<tr class="liste_titre">';
  513. foreach ($object->fields as $key => $val) {
  514. $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']);
  515. if ($key == 'status') {
  516. $cssforfield .= ($cssforfield ? ' ' : '').'center';
  517. } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
  518. $cssforfield .= ($cssforfield ? ' ' : '').'center';
  519. } elseif (in_array($val['type'], array('timestamp'))) {
  520. $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
  521. } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID' && empty($val['arrayofkeyval'])) {
  522. $cssforfield .= ($cssforfield ? ' ' : '').'right';
  523. }
  524. if (!empty($arrayfields['t.'.$key]['checked'])) {
  525. print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n";
  526. }
  527. }
  528. // Extra fields
  529. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
  530. // Hook fields
  531. $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder);
  532. $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
  533. print $hookmanager->resPrint;
  534. // Action column
  535. print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n";
  536. print '</tr>'."\n";
  537. // Detect if we need a fetch on each output line
  538. $needToFetchEachLine = 0;
  539. if (isset($extrafields->attributes[$object->table_element]['computed']) && is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) {
  540. foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) {
  541. if (preg_match('/\$object/', $val)) {
  542. $needToFetchEachLine++; // There is at least one compute field that use $object
  543. }
  544. }
  545. }
  546. // Loop on record
  547. // --------------------------------------------------------------------
  548. $i = 0;
  549. $totalarray = array();
  550. $totalarray['nbfield'] = 0;
  551. while ($i < ($limit ? min($num, $limit) : $num)) {
  552. $obj = $db->fetch_object($resql);
  553. if (empty($obj)) {
  554. break; // Should not happen
  555. }
  556. // Store properties in $object
  557. $object->setVarsFromFetchObj($obj);
  558. // Show here line of result
  559. print '<tr class="oddeven">';
  560. foreach ($object->fields as $key => $val) {
  561. $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']);
  562. if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
  563. $cssforfield .= ($cssforfield ? ' ' : '').'center';
  564. } elseif ($key == 'status') {
  565. $cssforfield .= ($cssforfield ? ' ' : '').'center';
  566. }
  567. if (in_array($val['type'], array('timestamp'))) {
  568. $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
  569. } elseif ($key == 'ref') {
  570. $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
  571. }
  572. if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('rowid', 'status')) && empty($val['arrayofkeyval'])) {
  573. $cssforfield .= ($cssforfield ? ' ' : '').'right';
  574. }
  575. //if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100';
  576. if (!empty($arrayfields['t.'.$key]['checked'])) {
  577. print '<td'.($cssforfield ? ' class="'.$cssforfield.'"' : '').'>';
  578. if ($key == 'status') {
  579. print $object->getLibStatut(5);
  580. } elseif ($key == 'rowid') {
  581. print $object->showOutputField($val, $key, $object->id, '');
  582. } else {
  583. print $object->showOutputField($val, $key, $object->$key, '');
  584. }
  585. print '</td>';
  586. if (!$i) {
  587. $totalarray['nbfield']++;
  588. }
  589. if (!empty($val['isameasure']) && $val['isameasure'] == 1) {
  590. if (!$i) {
  591. $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key;
  592. }
  593. if (!isset($totalarray['val'])) {
  594. $totalarray['val'] = array();
  595. }
  596. if (!isset($totalarray['val']['t.'.$key])) {
  597. $totalarray['val']['t.'.$key] = 0;
  598. }
  599. $totalarray['val']['t.'.$key] += $object->$key;
  600. }
  601. }
  602. }
  603. // Extra fields
  604. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
  605. // Fields from hook
  606. $parameters = array('arrayfields'=>$arrayfields, 'object'=>$object, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray);
  607. $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook
  608. print $hookmanager->resPrint;
  609. // Action column
  610. print '<td class="nowrap center">';
  611. if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
  612. $selected = 0;
  613. if (in_array($object->id, $arrayofselected)) {
  614. $selected = 1;
  615. }
  616. print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>';
  617. }
  618. print '</td>';
  619. if (!$i) {
  620. $totalarray['nbfield']++;
  621. }
  622. print '</tr>'."\n";
  623. $i++;
  624. }
  625. // Show total line
  626. include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
  627. // If no record found
  628. if ($num == 0) {
  629. $colspan = 1;
  630. foreach ($arrayfields as $key => $val) {
  631. if (!empty($val['checked'])) {
  632. $colspan++;
  633. }
  634. }
  635. print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
  636. }
  637. $db->free($resql);
  638. $parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql);
  639. $reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook
  640. print $hookmanager->resPrint;
  641. print '</table>'."\n";
  642. print '</div>'."\n";
  643. print '</form>'."\n";
  644. if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) {
  645. $hidegeneratedfilelistifempty = 1;
  646. if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) {
  647. $hidegeneratedfilelistifempty = 0;
  648. }
  649. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
  650. $formfile = new FormFile($db);
  651. // Show list of available documents
  652. $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
  653. $urlsource .= str_replace('&amp;', '&', $param);
  654. $filedir = $diroutputmassaction;
  655. $genallowed = $permissiontoread;
  656. $delallowed = $permissiontoadd;
  657. print $formfile->showdocuments('massfilesarea_mymodule', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty);
  658. }
  659. // End of page
  660. llxFooter();
  661. $db->close();