myobject_list.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  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. $id = GETPOST('id', 'int');
  84. $ref = GETPOST('ref', 'alpha');
  85. $action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ...
  86. $massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
  87. $show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ?
  88. $confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation
  89. $cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button
  90. $toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list
  91. $contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'myobjectlist'; // To manage different context of search
  92. $backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page
  93. $optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
  94. $mode = GETPOST('mode', 'aZ');
  95. // Load variable for pagination
  96. $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
  97. $sortfield = GETPOST('sortfield', 'aZ09comma');
  98. $sortorder = GETPOST('sortorder', 'aZ09comma');
  99. $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
  100. if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) {
  101. // If $page is not defined, or '' or -1 or if we click on clear filters
  102. $page = 0;
  103. }
  104. $offset = $limit * $page;
  105. $pageprev = $page - 1;
  106. $pagenext = $page + 1;
  107. // Initialize technical objects
  108. $object = new MyObject($db);
  109. $extrafields = new ExtraFields($db);
  110. $diroutputmassaction = $conf->mymodule->dir_output.'/temp/massgeneration/'.$user->id;
  111. $hookmanager->initHooks(array('myobjectlist')); // Note that conf->hooks_modules contains array
  112. // Fetch optionals attributes and labels
  113. $extrafields->fetch_name_optionals_label($object->table_element);
  114. //$extrafields->fetch_name_optionals_label($object->table_element_line);
  115. $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
  116. // Default sort order (if not yet defined by previous GETPOST)
  117. if (!$sortfield) {
  118. reset($object->fields); // Reset is required to avoid key() to return null.
  119. $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition.
  120. }
  121. if (!$sortorder) {
  122. $sortorder = "ASC";
  123. }
  124. // Initialize array of search criterias
  125. $search_all = GETPOST('search_all', 'alphanohtml');
  126. $search = array();
  127. foreach ($object->fields as $key => $val) {
  128. if (GETPOST('search_'.$key, 'alpha') !== '') {
  129. $search[$key] = GETPOST('search_'.$key, 'alpha');
  130. }
  131. if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
  132. $search[$key.'_dtstart'] = dol_mktime(0, 0, 0, GETPOST('search_'.$key.'_dtstartmonth', 'int'), GETPOST('search_'.$key.'_dtstartday', 'int'), GETPOST('search_'.$key.'_dtstartyear', 'int'));
  133. $search[$key.'_dtend'] = dol_mktime(23, 59, 59, GETPOST('search_'.$key.'_dtendmonth', 'int'), GETPOST('search_'.$key.'_dtendday', 'int'), GETPOST('search_'.$key.'_dtendyear', 'int'));
  134. }
  135. }
  136. // List of fields to search into when doing a "search in all"
  137. $fieldstosearchall = array();
  138. foreach ($object->fields as $key => $val) {
  139. if (!empty($val['searchall'])) {
  140. $fieldstosearchall['t.'.$key] = $val['label'];
  141. }
  142. }
  143. // Definition of array of fields for columns
  144. $arrayfields = array();
  145. foreach ($object->fields as $key => $val) {
  146. // If $val['visible']==0, then we never show the field
  147. if (!empty($val['visible'])) {
  148. $visible = (int) dol_eval($val['visible'], 1);
  149. $arrayfields['t.'.$key] = array(
  150. 'label'=>$val['label'],
  151. 'checked'=>(($visible < 0) ? 0 : 1),
  152. 'enabled'=>(abs($visible) != 3 && dol_eval($val['enabled'], 1)),
  153. 'position'=>$val['position'],
  154. 'help'=> isset($val['help']) ? $val['help'] : ''
  155. );
  156. }
  157. }
  158. // Extra fields
  159. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php';
  160. $object->fields = dol_sort_array($object->fields, 'position');
  161. //$arrayfields['anotherfield'] = array('type'=>'integer', 'label'=>'AnotherField', 'checked'=>1, 'enabled'=>1, 'position'=>90, 'csslist'=>'right');
  162. $arrayfields = dol_sort_array($arrayfields, 'position');
  163. // There is several ways to check permission.
  164. // Set $enablepermissioncheck to 1 to enable a minimum low level of checks
  165. $enablepermissioncheck = 0;
  166. if ($enablepermissioncheck) {
  167. $permissiontoread = $user->rights->mymodule->myobject->read;
  168. $permissiontoadd = $user->rights->mymodule->myobject->write;
  169. $permissiontodelete = $user->rights->mymodule->myobject->delete;
  170. } else {
  171. $permissiontoread = 1;
  172. $permissiontoadd = 1;
  173. $permissiontodelete = 1;
  174. }
  175. // Security check (enable the most restrictive one)
  176. if ($user->socid > 0) accessforbidden();
  177. //if ($user->socid > 0) accessforbidden();
  178. //$socid = 0; if ($user->socid > 0) $socid = $user->socid;
  179. //$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0);
  180. //restrictedArea($user, $object->element, 0, $object->table_element, '', 'fk_soc', 'rowid', $isdraft);
  181. if (empty($conf->mymodule->enabled)) accessforbidden('Module not enabled');
  182. if (!$permissiontoread) accessforbidden();
  183. /*
  184. * Actions
  185. */
  186. if (GETPOST('cancel', 'alpha')) {
  187. $action = 'list';
  188. $massaction = '';
  189. }
  190. if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
  191. $massaction = '';
  192. }
  193. $parameters = array();
  194. $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  195. if ($reshook < 0) {
  196. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  197. }
  198. if (empty($reshook)) {
  199. // Selection of new fields
  200. include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
  201. // Purge search criteria
  202. 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
  203. foreach ($object->fields as $key => $val) {
  204. $search[$key] = '';
  205. if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
  206. $search[$key.'_dtstart'] = '';
  207. $search[$key.'_dtend'] = '';
  208. }
  209. }
  210. $toselect = array();
  211. $search_array_options = array();
  212. }
  213. if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
  214. || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) {
  215. $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
  216. }
  217. // Mass actions
  218. $objectclass = 'MyObject';
  219. $objectlabel = 'MyObject';
  220. $uploaddir = $conf->mymodule->dir_output;
  221. include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
  222. }
  223. /*
  224. * View
  225. */
  226. $form = new Form($db);
  227. $now = dol_now();
  228. //$help_url = "EN:Module_MyObject|FR:Module_MyObject_FR|ES:Módulo_MyObject";
  229. $help_url = '';
  230. $title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("MyObjects"));
  231. $morejs = array();
  232. $morecss = array();
  233. // Build and execute select
  234. // --------------------------------------------------------------------
  235. $sql = 'SELECT ';
  236. $sql .= $object->getFieldList('t');
  237. // Add fields from extrafields
  238. if (!empty($extrafields->attributes[$object->table_element]['label'])) {
  239. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
  240. $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key." as options_".$key : '');
  241. }
  242. }
  243. // Add fields from hooks
  244. $parameters = array();
  245. $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook
  246. $sql .= preg_replace('/^,/', '', $hookmanager->resPrint);
  247. $sql = preg_replace('/,\s*$/', '', $sql);
  248. //$sql .= ", COUNT(rc.rowid) as anotherfield";
  249. $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t";
  250. //$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."anothertable as rc ON rc.parent = t.rowid";
  251. if (isset($extrafields->attributes[$object->table_element]['label']) && is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) {
  252. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)";
  253. }
  254. // Add table from hooks
  255. $parameters = array();
  256. $reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object); // Note that $action and $object may have been modified by hook
  257. $sql .= $hookmanager->resPrint;
  258. if ($object->ismultientitymanaged == 1) {
  259. $sql .= " WHERE t.entity IN (".getEntity($object->element).")";
  260. } else {
  261. $sql .= " WHERE 1 = 1";
  262. }
  263. foreach ($search as $key => $val) {
  264. if (array_key_exists($key, $object->fields)) {
  265. if ($key == 'status' && $search[$key] == -1) {
  266. continue;
  267. }
  268. $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0);
  269. if ((strpos($object->fields[$key]['type'], 'integer:') === 0) || (strpos($object->fields[$key]['type'], 'sellist:') === 0) || !empty($object->fields[$key]['arrayofkeyval'])) {
  270. if ($search[$key] == '-1' || ($search[$key] === '0' && (empty($object->fields[$key]['arrayofkeyval']) || !array_key_exists('0', $object->fields[$key]['arrayofkeyval'])))) {
  271. $search[$key] = '';
  272. }
  273. $mode_search = 2;
  274. }
  275. if ($search[$key] != '') {
  276. $sql .= natural_search("t.".$db->escape($key), $search[$key], (($key == 'status') ? 2 : $mode_search));
  277. }
  278. } else {
  279. if (preg_match('/(_dtstart|_dtend)$/', $key) && $search[$key] != '') {
  280. $columnName = preg_replace('/(_dtstart|_dtend)$/', '', $key);
  281. if (preg_match('/^(date|timestamp|datetime)/', $object->fields[$columnName]['type'])) {
  282. if (preg_match('/_dtstart$/', $key)) {
  283. $sql .= " AND t.".$db->escape($columnName)." >= '".$db->idate($search[$key])."'";
  284. }
  285. if (preg_match('/_dtend$/', $key)) {
  286. $sql .= " AND t.".$db->escape($columnName)." <= '".$db->idate($search[$key])."'";
  287. }
  288. }
  289. }
  290. }
  291. }
  292. if ($search_all) {
  293. $sql .= natural_search(array_keys($fieldstosearchall), $search_all);
  294. }
  295. //$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear);
  296. // Add where from extra fields
  297. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
  298. // Add where from hooks
  299. $parameters = array();
  300. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
  301. $sql .= $hookmanager->resPrint;
  302. /* If a group by is required
  303. $sql .= " GROUP BY ";
  304. foreach($object->fields as $key => $val) {
  305. $sql .= "t.".$db->escape($key).", ";
  306. }
  307. // Add fields from extrafields
  308. if (!empty($extrafields->attributes[$object->table_element]['label'])) {
  309. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
  310. $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.', ' : '');
  311. }
  312. }
  313. // Add where from hooks
  314. $parameters = array();
  315. $reshook = $hookmanager->executeHooks('printFieldListGroupBy', $parameters, $object); // Note that $action and $object may have been modified by hook
  316. $sql .= $hookmanager->resPrint;
  317. $sql = preg_replace('/,\s*$/', '', $sql);
  318. */
  319. // Add HAVING from hooks
  320. /*
  321. $parameters = array();
  322. $reshook = $hookmanager->executeHooks('printFieldListHaving', $parameters, $object); // Note that $action and $object may have been modified by hook
  323. $sql .= empty($hookmanager->resPrint) ? "" : " HAVING 1=1 ".$hookmanager->resPrint;
  324. */
  325. // Count total nb of records
  326. $nbtotalofrecords = '';
  327. if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
  328. /* This old and fast method to get and count full list returns all record so use a high amount of memory.
  329. $resql = $db->query($sql);
  330. $nbtotalofrecords = $db->num_rows($resql);
  331. */
  332. /* The slow method does not consume memory on mysql (not tested on pgsql) */
  333. /*$resql = $db->query($sql, 0, 'auto', 1);
  334. while ($db->fetch_object($resql)) {
  335. if (empty($nbtotalofrecords)) {
  336. $nbtotalofrecords = 1; // We can't make +1 because init value is ''
  337. } else {
  338. $nbtotalofrecords++;
  339. }
  340. }*/
  341. /* The fast and low memory method to get and count full list converts the sql into a sql count */
  342. $sqlforcount = preg_replace('/^SELECT[a-zA-Z0-9\._\s\(\),=<>\:\-\']+\sFROM/', 'SELECT COUNT(*) as nbtotalofrecords FROM', $sql);
  343. $resql = $db->query($sqlforcount);
  344. if ($resql) {
  345. $objforcount = $db->fetch_object($resql);
  346. $nbtotalofrecords = $objforcount->nbtotalofrecords;
  347. } else {
  348. dol_print_error($db);
  349. }
  350. if (($page * $limit) > $nbtotalofrecords) { // if total of record found is smaller than page * limit, goto and load page 0
  351. $page = 0;
  352. $offset = 0;
  353. }
  354. $db->free($resql);
  355. }
  356. // Complete request and execute it with limit
  357. $sql .= $db->order($sortfield, $sortorder);
  358. if ($limit) {
  359. $sql .= $db->plimit($limit + 1, $offset);
  360. }
  361. $resql = $db->query($sql);
  362. if (!$resql) {
  363. dol_print_error($db);
  364. exit;
  365. }
  366. $num = $db->num_rows($resql);
  367. // Direct jump if only one record found
  368. if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) {
  369. $obj = $db->fetch_object($resql);
  370. $id = $obj->rowid;
  371. header("Location: ".dol_buildpath('/mymodule/myobject_card.php', 1).'?id='.$id);
  372. exit;
  373. }
  374. // Output page
  375. // --------------------------------------------------------------------
  376. llxHeader('', $title, $help_url, '', 0, 0, $morejs, $morecss, '', '');
  377. // Example : Adding jquery code
  378. // print '<script type="text/javascript">
  379. // jQuery(document).ready(function() {
  380. // function init_myfunc()
  381. // {
  382. // jQuery("#myid").removeAttr(\'disabled\');
  383. // jQuery("#myid").attr(\'disabled\',\'disabled\');
  384. // }
  385. // init_myfunc();
  386. // jQuery("#mybutton").click(function() {
  387. // init_myfunc();
  388. // });
  389. // });
  390. // </script>';
  391. $arrayofselected = is_array($toselect) ? $toselect : array();
  392. $param = '';
  393. if (!empty($mode)) {
  394. $param .= '&mode='.urlencode($mode);
  395. }
  396. if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
  397. $param .= '&contextpage='.urlencode($contextpage);
  398. }
  399. if ($limit > 0 && $limit != $conf->liste_limit) {
  400. $param .= '&limit='.urlencode($limit);
  401. }
  402. foreach ($search as $key => $val) {
  403. if (is_array($search[$key]) && count($search[$key])) {
  404. foreach ($search[$key] as $skey) {
  405. if ($skey != '') {
  406. $param .= '&search_'.$key.'[]='.urlencode($skey);
  407. }
  408. }
  409. } elseif ($search[$key] != '') {
  410. $param .= '&search_'.$key.'='.urlencode($search[$key]);
  411. }
  412. }
  413. if ($optioncss != '') {
  414. $param .= '&optioncss='.urlencode($optioncss);
  415. }
  416. // Add $param from extra fields
  417. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
  418. // Add $param from hooks
  419. $parameters = array();
  420. $reshook = $hookmanager->executeHooks('printFieldListSearchParam', $parameters, $object); // Note that $action and $object may have been modified by hook
  421. $param .= $hookmanager->resPrint;
  422. // List of mass actions available
  423. $arrayofmassactions = array(
  424. //'validate'=>img_picto('', 'check', 'class="pictofixedwidth"').$langs->trans("Validate"),
  425. //'generate_doc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("ReGeneratePDF"),
  426. //'builddoc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("PDFMerge"),
  427. //'presend'=>img_picto('', 'email', 'class="pictofixedwidth"').$langs->trans("SendByMail"),
  428. );
  429. if ($permissiontodelete) {
  430. $arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"').$langs->trans("Delete");
  431. }
  432. if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) {
  433. $arrayofmassactions = array();
  434. }
  435. $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
  436. print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n";
  437. if ($optioncss != '') {
  438. print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
  439. }
  440. print '<input type="hidden" name="token" value="'.newToken().'">';
  441. print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
  442. print '<input type="hidden" name="action" value="list">';
  443. print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
  444. print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
  445. print '<input type="hidden" name="page" value="'.$page.'">';
  446. print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
  447. print '<input type="hidden" name="mode" value="'.$mode.'">';
  448. $newcardbutton = '';
  449. $newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanban'), '', 'fa fa-th-list imgforviewmode', $_SERVER["PHP_SELF"].'?mode=kanban'.preg_replace('/^&mode=[^&]+/', '', $param), '', ($mode == 'kanban' ? 2 : 1), array('morecss'=>'reposition'));
  450. $newcardbutton .= dolGetButtonTitle($langs->trans('ViewList'), '', 'fa fa-list-alt imgforviewmode', $_SERVER["PHP_SELF"].'?mode=common'.preg_replace('/^&mode=[^&]+/', '', $param), '', ((empty($mode) || $mode == 'common') ? 2 : 1), array('morecss'=>'reposition'));
  451. $newcardbutton .= dolGetButtonTitleSeparator();
  452. $newcardbutton .= dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', dol_buildpath('/mymodule/myobject_card.php', 1).'?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']), '', $permissiontoadd);
  453. print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'object_'.$object->picto, 0, $newcardbutton, '', $limit, 0, 0, 1);
  454. // Add code for pre mass action (confirmation or email presend form)
  455. $topicmail = "SendMyObjectRef";
  456. $modelmail = "myobject";
  457. $objecttmp = new MyObject($db);
  458. $trackid = 'xxxx'.$object->id;
  459. include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
  460. if ($search_all) {
  461. $setupstring = '';
  462. foreach ($fieldstosearchall as $key => $val) {
  463. $fieldstosearchall[$key] = $langs->trans($val);
  464. $setupstring .= $key."=".$val.";";
  465. }
  466. print '<!-- Search done like if PRODUCT_QUICKSEARCH_ON_FIELDS = '.$setupstring.' -->'."\n";
  467. print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>'."\n";
  468. }
  469. $moreforfilter = '';
  470. /*$moreforfilter.='<div class="divsearchfield">';
  471. $moreforfilter.= $langs->trans('MyFilter') . ': <input type="text" name="search_myfield" value="'.dol_escape_htmltag($search_myfield).'">';
  472. $moreforfilter.= '</div>';*/
  473. $parameters = array();
  474. $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
  475. if (empty($reshook)) {
  476. $moreforfilter .= $hookmanager->resPrint;
  477. } else {
  478. $moreforfilter = $hookmanager->resPrint;
  479. }
  480. if (!empty($moreforfilter)) {
  481. print '<div class="liste_titre liste_titre_bydiv centpercent">';
  482. print $moreforfilter;
  483. print '</div>';
  484. }
  485. $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
  486. if (!empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) {
  487. $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage, 'left'); // This also change content of $arrayfields
  488. } else {
  489. $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
  490. }
  491. $selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : '');
  492. print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
  493. print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
  494. // Fields title search
  495. // --------------------------------------------------------------------
  496. print '<tr class="liste_titre">';
  497. // Action column
  498. if (!empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) {
  499. print '<td class="liste_titre maxwidthsearch">';
  500. $searchpicto = $form->showFilterButtons('left');
  501. print $searchpicto;
  502. print '</td>';
  503. }
  504. foreach ($object->fields as $key => $val) {
  505. $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']);
  506. if ($key == 'status') {
  507. $cssforfield .= ($cssforfield ? ' ' : '').'center';
  508. } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
  509. $cssforfield .= ($cssforfield ? ' ' : '').'center';
  510. } elseif (in_array($val['type'], array('timestamp'))) {
  511. $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
  512. } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID' && empty($val['arrayofkeyval'])) {
  513. $cssforfield .= ($cssforfield ? ' ' : '').'right';
  514. }
  515. if (!empty($arrayfields['t.'.$key]['checked'])) {
  516. print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">';
  517. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  518. print $form->selectarray('search_'.$key, $val['arrayofkeyval'], (isset($search[$key]) ? $search[$key] : ''), $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1);
  519. } elseif ((strpos($val['type'], 'integer:') === 0) || (strpos($val['type'], 'sellist:') === 0)) {
  520. print $object->showInputField($val, $key, (isset($search[$key]) ? $search[$key] : ''), '', '', 'search_', $cssforfield.' maxwidth250', 1);
  521. } elseif (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
  522. print '<div class="nowrap">';
  523. print $form->selectDate($search[$key.'_dtstart'] ? $search[$key.'_dtstart'] : '', "search_".$key."_dtstart", 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'));
  524. print '</div>';
  525. print '<div class="nowrap">';
  526. print $form->selectDate($search[$key.'_dtend'] ? $search[$key.'_dtend'] : '', "search_".$key."_dtend", 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'));
  527. print '</div>';
  528. } elseif ($key == 'lang') {
  529. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
  530. $formadmin = new FormAdmin($db);
  531. print $formadmin->select_language($search[$key], 'search_lang', 0, null, 1, 0, 0, 'minwidth150 maxwidth200', 2);
  532. } else {
  533. print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag(isset($search[$key]) ? $search[$key] : '').'">';
  534. }
  535. print '</td>';
  536. }
  537. }
  538. // Extra fields
  539. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
  540. // Fields from hook
  541. $parameters = array('arrayfields'=>$arrayfields);
  542. $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook
  543. print $hookmanager->resPrint;
  544. /*if (!empty($arrayfields['anotherfield']['checked'])) {
  545. print '<td class="liste_titre"></td>';
  546. }*/
  547. // Action column
  548. if (empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) {
  549. print '<td class="liste_titre maxwidthsearch">';
  550. $searchpicto = $form->showFilterButtons();
  551. print $searchpicto;
  552. print '</td>';
  553. }
  554. print '</tr>'."\n";
  555. $totalarray = array();
  556. $totalarray['nbfield'] = 0;
  557. // Fields title label
  558. // --------------------------------------------------------------------
  559. print '<tr class="liste_titre">';
  560. if (!empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) {
  561. print getTitleFieldOfList(($mode != 'kanban' ? $selectedfields : ''), 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n";
  562. }
  563. foreach ($object->fields as $key => $val) {
  564. $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']);
  565. if ($key == 'status') {
  566. $cssforfield .= ($cssforfield ? ' ' : '').'center';
  567. } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
  568. $cssforfield .= ($cssforfield ? ' ' : '').'center';
  569. } elseif (in_array($val['type'], array('timestamp'))) {
  570. $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
  571. } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID' && empty($val['arrayofkeyval'])) {
  572. $cssforfield .= ($cssforfield ? ' ' : '').'right';
  573. }
  574. $cssforfield = preg_replace('/small\s*/', '', $cssforfield); // the 'small' css must not be used for the title label
  575. if (!empty($arrayfields['t.'.$key]['checked'])) {
  576. print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n";
  577. $totalarray['nbfield']++;
  578. }
  579. }
  580. // Extra fields
  581. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
  582. // Hook fields
  583. $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder, 'totalarray'=>&$totalarray);
  584. $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
  585. print $hookmanager->resPrint;
  586. /*if (!empty($arrayfields['anotherfield']['checked'])) {
  587. print '<th class="liste_titre right">'.$langs->trans("AnotherField").'</th>';
  588. $totalarray['nbfield']++;
  589. }*/
  590. // Action column
  591. if (empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) {
  592. print getTitleFieldOfList(($mode != 'kanban' ? $selectedfields : ''), 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n";
  593. }
  594. $totalarray['nbfield']++;
  595. print '</tr>'."\n";
  596. // Detect if we need a fetch on each output line
  597. $needToFetchEachLine = 0;
  598. if (isset($extrafields->attributes[$object->table_element]['computed']) && is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) {
  599. foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) {
  600. if (preg_match('/\$object/', $val)) {
  601. $needToFetchEachLine++; // There is at least one compute field that use $object
  602. }
  603. }
  604. }
  605. // Loop on record
  606. // --------------------------------------------------------------------
  607. $i = 0;
  608. $savnbfield = $totalarray['nbfield'];
  609. $totalarray['nbfield'] = 0;
  610. $imaxinloop = ($limit ? min($num, $limit) : $num);
  611. while ($i < $imaxinloop) {
  612. $obj = $db->fetch_object($resql);
  613. if (empty($obj)) {
  614. break; // Should not happen
  615. }
  616. // Store properties in $object
  617. $object->setVarsFromFetchObj($obj);
  618. if ($mode == 'kanban') {
  619. if ($i == 0) {
  620. print '<tr><td colspan="'.$savnbfield.'">';
  621. print '<div class="box-flex-container">';
  622. }
  623. // Output Kanban
  624. print $object->getKanbanView('');
  625. if ($i == ($imaxinloop - 1)) {
  626. print '</div>';
  627. print '</td></tr>';
  628. }
  629. } else {
  630. // Show here line of result
  631. $j = 0;
  632. print '<tr data-rowid="'.$object->id.'" class="oddeven">';
  633. // Action column
  634. if (!empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) {
  635. print '<td class="nowrap center">';
  636. if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
  637. $selected = 0;
  638. if (in_array($object->id, $arrayofselected)) {
  639. $selected = 1;
  640. }
  641. print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>';
  642. }
  643. print '</td>';
  644. }
  645. foreach ($object->fields as $key => $val) {
  646. $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']);
  647. if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
  648. $cssforfield .= ($cssforfield ? ' ' : '').'center';
  649. } elseif ($key == 'status') {
  650. $cssforfield .= ($cssforfield ? ' ' : '').'center';
  651. }
  652. if (in_array($val['type'], array('timestamp'))) {
  653. $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
  654. } elseif ($key == 'ref') {
  655. $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
  656. }
  657. if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('rowid', 'status')) && empty($val['arrayofkeyval'])) {
  658. $cssforfield .= ($cssforfield ? ' ' : '').'right';
  659. }
  660. //if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100';
  661. if (!empty($arrayfields['t.'.$key]['checked'])) {
  662. print '<td'.($cssforfield ? ' class="'.$cssforfield.'"' : '');
  663. if (preg_match('/tdoverflow/', $cssforfield)) {
  664. print ' title="'.dol_escape_htmltag($object->$key).'"';
  665. }
  666. print '>';
  667. if ($key == 'status') {
  668. print $object->getLibStatut(5);
  669. } elseif ($key == 'rowid') {
  670. print $object->showOutputField($val, $key, $object->id, '');
  671. } else {
  672. print $object->showOutputField($val, $key, $object->$key, '');
  673. }
  674. print '</td>';
  675. if (!$i) {
  676. $totalarray['nbfield']++;
  677. }
  678. if (!empty($val['isameasure']) && $val['isameasure'] == 1) {
  679. if (!$i) {
  680. $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key;
  681. }
  682. if (!isset($totalarray['val'])) {
  683. $totalarray['val'] = array();
  684. }
  685. if (!isset($totalarray['val']['t.'.$key])) {
  686. $totalarray['val']['t.'.$key] = 0;
  687. }
  688. $totalarray['val']['t.'.$key] += $object->$key;
  689. }
  690. }
  691. }
  692. // Extra fields
  693. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
  694. // Fields from hook
  695. $parameters = array('arrayfields'=>$arrayfields, 'object'=>$object, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray);
  696. $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook
  697. print $hookmanager->resPrint;
  698. /*if (!empty($arrayfields['anotherfield']['checked'])) {
  699. print '<td class="right">'.$obj->anotherfield.'</td>';
  700. }*/
  701. // Action column
  702. if (empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) {
  703. print '<td class="nowrap center">';
  704. if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
  705. $selected = 0;
  706. if (in_array($object->id, $arrayofselected)) {
  707. $selected = 1;
  708. }
  709. print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>';
  710. }
  711. print '</td>';
  712. }
  713. if (!$i) {
  714. $totalarray['nbfield']++;
  715. }
  716. print '</tr>'."\n";
  717. }
  718. $i++;
  719. }
  720. // Show total line
  721. include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
  722. // If no record found
  723. if ($num == 0) {
  724. $colspan = 1;
  725. foreach ($arrayfields as $key => $val) {
  726. if (!empty($val['checked'])) {
  727. $colspan++;
  728. }
  729. }
  730. print '<tr><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span></td></tr>';
  731. }
  732. $db->free($resql);
  733. $parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql);
  734. $reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  735. print $hookmanager->resPrint;
  736. print '</table>'."\n";
  737. print '</div>'."\n";
  738. print '</form>'."\n";
  739. if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) {
  740. $hidegeneratedfilelistifempty = 1;
  741. if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) {
  742. $hidegeneratedfilelistifempty = 0;
  743. }
  744. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
  745. $formfile = new FormFile($db);
  746. // Show list of available documents
  747. $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
  748. $urlsource .= str_replace('&amp;', '&', $param);
  749. $filedir = $diroutputmassaction;
  750. $genallowed = $permissiontoread;
  751. $delallowed = $permissiontoadd;
  752. print $formfile->showdocuments('massfilesarea_mymodule', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty);
  753. }
  754. // End of page
  755. llxFooter();
  756. $db->close();