myobject_list.php 37 KB

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