customreports.php 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465
  1. <?php
  2. /* Copyright (C) 2020-2023 Laurent Destailleur <eldy@users.sourceforge.net>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. *
  17. * Note: This tool can be included into a list page with :
  18. * define('USE_CUSTOM_REPORT_AS_INCLUDE', 1);
  19. * include DOL_DOCUMENT_ROOT.'/core/customreports.php';
  20. */
  21. /**
  22. * \file htdocs/core/customreports.php
  23. * \ingroup core
  24. * \brief Page to make custom reports
  25. */
  26. if (!defined('USE_CUSTOM_REPORT_AS_INCLUDE')) {
  27. require '../main.inc.php';
  28. // Get parameters
  29. $action = GETPOST('action', 'aZ09') ? GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ...
  30. $massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
  31. $mode = GETPOST('mode', 'alpha') ? GETPOST('mode', 'alpha') : 'graph';
  32. $objecttype = GETPOST('objecttype', 'aZ09');
  33. $tabfamily = GETPOST('tabfamily', 'aZ09');
  34. if (empty($objecttype)) {
  35. $objecttype = 'thirdparty';
  36. }
  37. $search_measures = GETPOST('search_measures', 'array');
  38. //$search_xaxis = GETPOST('search_xaxis', 'array');
  39. if (GETPOST('search_xaxis', 'alpha') && GETPOST('search_xaxis', 'alpha') != '-1') {
  40. $search_xaxis = array(GETPOST('search_xaxis', 'alpha'));
  41. } else {
  42. $search_xaxis = array();
  43. }
  44. //$search_groupby = GETPOST('search_groupby', 'array');
  45. if (GETPOST('search_groupby', 'alpha') && GETPOST('search_groupby', 'alpha') != '-1') {
  46. $search_groupby = array(GETPOST('search_groupby', 'alpha'));
  47. } else {
  48. $search_groupby = array();
  49. }
  50. $search_yaxis = GETPOST('search_yaxis', 'array');
  51. $search_graph = GETPOST('search_graph', 'restricthtml');
  52. // Load variable for pagination
  53. $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
  54. $sortfield = GETPOST('sortfield', 'aZ09comma');
  55. $sortorder = GETPOST('sortorder', 'aZ09comma');
  56. $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
  57. if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) {
  58. $page = 0;
  59. } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action
  60. $offset = $limit * $page;
  61. $pageprev = $page - 1;
  62. $pagenext = $page + 1;
  63. $diroutputmassaction = $conf->user->dir_temp.'/'.$user->id.'/customreport';
  64. }
  65. require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php";
  66. require_once DOL_DOCUMENT_ROOT."/core/lib/company.lib.php";
  67. require_once DOL_DOCUMENT_ROOT."/core/class/dolgraph.class.php";
  68. require_once DOL_DOCUMENT_ROOT."/core/class/doleditor.class.php";
  69. require_once DOL_DOCUMENT_ROOT."/core/class/html.formother.class.php";
  70. // Load traductions files requiredby by page
  71. $langs->loadLangs(array("companies", "other", "exports", "sendings"));
  72. $extrafields = new ExtraFields($db);
  73. $hookmanager->initHooks(array('customreport')); // Note that conf->hooks_modules contains array
  74. $title = '';
  75. $picto = '';
  76. $head = array();
  77. $object = null;
  78. $ObjectClassName = '';
  79. // Objects available by default
  80. $arrayoftype = array(
  81. 'thirdparty' => array('langs'=>'companies', 'label' => 'ThirdParties', 'picto'=>'company', 'ObjectClassName' => 'Societe', 'enabled' => isModEnabled('societe'), 'ClassPath' => "/societe/class/societe.class.php"),
  82. 'contact' => array('label' => 'Contacts', 'picto'=>'contact', 'ObjectClassName' => 'Contact', 'enabled' => isModEnabled('societe'), 'ClassPath' => "/contact/class/contact.class.php"),
  83. 'proposal' => array('label' => 'Proposals', 'picto'=>'proposal', 'ObjectClassName' => 'Propal', 'enabled' => isModEnabled('propal'), 'ClassPath' => "/comm/propal/class/propal.class.php"),
  84. 'order' => array('label' => 'Orders', 'picto'=>'order', 'ObjectClassName' => 'Commande', 'enabled' => isModEnabled('commande'), 'ClassPath' => "/commande/class/commande.class.php"),
  85. 'invoice' => array('langs'=>'facture', 'label' => 'Invoices', 'picto'=>'bill', 'ObjectClassName' => 'Facture', 'enabled' => isModEnabled('facture'), 'ClassPath' => "/compta/facture/class/facture.class.php"),
  86. 'invoice_template'=>array('label' => 'PredefinedInvoices', 'picto'=>'bill', 'ObjectClassName' => 'FactureRec', 'enabled' => isModEnabled('facture'), 'ClassPath' => "/compta/class/facturerec.class.php", 'langs'=>'bills'),
  87. 'contract' => array('label' => 'Contracts', 'picto'=>'contract', 'ObjectClassName' => 'Contrat', 'enabled' => isModEnabled('contrat'), 'ClassPath' => "/contrat/class/contrat.class.php", 'langs'=>'contracts'),
  88. 'contractdet' => array('label' => 'ContractLines', 'picto'=>'contract', 'ObjectClassName' => 'ContratLigne', 'enabled' => isModEnabled('contrat'), 'ClassPath' => "/contrat/class/contrat.class.php", 'langs'=>'contracts'),
  89. 'bom' => array('label' => 'BOM', 'picto'=>'bom', 'ObjectClassName' => 'Bom', 'enabled' => isModEnabled('bom')),
  90. 'mo' => array('label' => 'MO', 'picto'=>'mrp', 'ObjectClassName' => 'Mo', 'enabled' => isModEnabled('mrp'), 'ClassPath' => "/mrp/class/mo.class.php"),
  91. 'ticket' => array('label' => 'Ticket', 'picto'=>'ticket', 'ObjectClassName' => 'Ticket', 'enabled' => isModEnabled('ticket')),
  92. 'member' => array('label' => 'Adherent', 'picto'=>'member', 'ObjectClassName' => 'Adherent', 'enabled' => isModEnabled('adherent'), 'ClassPath' => "/adherents/class/adherent.class.php", 'langs'=>'members'),
  93. 'cotisation' => array('label' => 'Subscriptions', 'picto'=>'member', 'ObjectClassName' => 'Subscription', 'enabled' => isModEnabled('adherent'), 'ClassPath' => "/adherents/class/subscription.class.php", 'langs'=>'members'),
  94. );
  95. // Complete $arrayoftype by external modules
  96. $parameters = array('objecttype'=>$objecttype, 'tabfamily'=>$tabfamily);
  97. $reshook = $hookmanager->executeHooks('loadDataForCustomReports', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  98. if ($reshook < 0) {
  99. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  100. } elseif (is_array($hookmanager->resArray)) {
  101. if (!empty($hookmanager->resArray['title'])) { // Add entries for tabs
  102. $title = $hookmanager->resArray['title'];
  103. }
  104. if (!empty($hookmanager->resArray['picto'])) { // Add entries for tabs
  105. $picto = $hookmanager->resArray['picto'];
  106. }
  107. if (!empty($hookmanager->resArray['head'])) { // Add entries for tabs
  108. $head = array_merge($head, $hookmanager->resArray['head']);
  109. }
  110. if (!empty($hookmanager->resArray['arrayoftype'])) { // Add entries from hook
  111. foreach ($hookmanager->resArray['arrayoftype'] as $key => $val) {
  112. $arrayoftype[$key] = $val;
  113. }
  114. }
  115. }
  116. if ($objecttype) {
  117. try {
  118. if (!empty($arrayoftype[$objecttype]['ClassPath'])) {
  119. dol_include_once($arrayoftype[$objecttype]['ClassPath']);
  120. } else {
  121. dol_include_once("/".$objecttype."/class/".$objecttype.".class.php");
  122. }
  123. $ObjectClassName = $arrayoftype[$objecttype]['ObjectClassName'];
  124. $object = new $ObjectClassName($db);
  125. } catch (Exception $e) {
  126. print 'Failed to load class for type '.$objecttype;
  127. }
  128. }
  129. // Security check
  130. $socid = 0;
  131. if ($user->socid > 0) { // Protection if external user
  132. //$socid = $user->socid;
  133. accessforbidden();
  134. }
  135. // Fetch optionals attributes and labels
  136. $extrafields->fetch_name_optionals_label('all'); // We load all extrafields definitions for all objects
  137. //$extrafields->fetch_name_optionals_label($object->table_element_line);
  138. $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
  139. $search_component_params = array('');
  140. $search_component_params_hidden = GETPOST('search_component_params_hidden', 'alphanohtml');
  141. // For the case we enter a criteria manually, the search_component_params_input will be defined and must be used in priority
  142. if (GETPOST('search_component_params_input', 'alphanohtml')) {
  143. $search_component_params_hidden = GETPOST('search_component_params_input', 'alphanohtml');
  144. }
  145. $MAXUNIQUEVALFORGROUP = 20;
  146. $MAXMEASURESINBARGRAPH = 20;
  147. $YYYY = substr($langs->trans("Year"), 0, 1).substr($langs->trans("Year"), 0, 1).substr($langs->trans("Year"), 0, 1).substr($langs->trans("Year"), 0, 1);
  148. $MM = substr($langs->trans("Month"), 0, 1).substr($langs->trans("Month"), 0, 1);
  149. $DD = substr($langs->trans("Day"), 0, 1).substr($langs->trans("Day"), 0, 1);
  150. $HH = substr($langs->trans("Hour"), 0, 1).substr($langs->trans("Hour"), 0, 1);
  151. $MI = substr($langs->trans("Minute"), 0, 1).substr($langs->trans("Minute"), 0, 1);
  152. $SS = substr($langs->trans("Second"), 0, 1).substr($langs->trans("Second"), 0, 1);
  153. $arrayofmesures = array();
  154. $arrayofxaxis = array();
  155. $arrayofgroupby = array();
  156. $arrayofyaxis = array();
  157. $arrayofvaluesforgroupby = array();
  158. $features = $object->element;
  159. if (!empty($object->element_for_permission)) {
  160. $features = $object->element_for_permission;
  161. }
  162. restrictedArea($user, $features, 0, '');
  163. $error = 0;
  164. /*
  165. * Actions
  166. */
  167. // None
  168. /*
  169. * View
  170. */
  171. $form = new Form($db);
  172. $formother = new FormOther($db);
  173. if (!defined('USE_CUSTOM_REPORT_AS_INCLUDE')) {
  174. llxHeader('', $langs->transnoentitiesnoconv('CustomReports'), '');
  175. print dol_get_fiche_head($head, 'customreports', $title, -1, $picto);
  176. }
  177. $newarrayoftype = array();
  178. foreach ($arrayoftype as $key => $val) {
  179. if (dol_eval($val['enabled'], 1, 1, '1')) {
  180. $newarrayoftype[$key] = $arrayoftype[$key];
  181. }
  182. if (!empty($val['langs'])) {
  183. $langs->load($val['langs']);
  184. }
  185. }
  186. $count = 0;
  187. $arrayofmesures = fillArrayOfMeasures($object, 't', $langs->trans($newarrayoftype[$objecttype]['label']), $arrayofmesures, 0, $count);
  188. $arrayofmesures = dol_sort_array($arrayofmesures, 'position', 'asc', 0, 0, 1);
  189. $count = 0;
  190. $arrayofxaxis = fillArrayOfXAxis($object, 't', $langs->trans($newarrayoftype[$objecttype]['label']), $arrayofxaxis, 0, $count);
  191. $arrayofxaxis = dol_sort_array($arrayofxaxis, 'position', 'asc', 0, 0, 1);
  192. $count = 0;
  193. $arrayofgroupby = fillArrayOfGroupBy($object, 't', $langs->trans($newarrayoftype[$objecttype]['label']), $arrayofgroupby, 0, $count);
  194. $arrayofgroupby = dol_sort_array($arrayofgroupby, 'position', 'asc', 0, 0, 1);
  195. // Check parameters
  196. if ($action == 'viewgraph') {
  197. if (!count($search_measures)) {
  198. setEventMessages($langs->trans("AtLeastOneMeasureIsRequired"), null, 'warnings');
  199. } elseif ($mode == 'graph' && count($search_xaxis) > 1) {
  200. setEventMessages($langs->trans("OnlyOneFieldForXAxisIsPossible"), null, 'warnings');
  201. $search_xaxis = array(0 => $search_xaxis[0]);
  202. }
  203. if (count($search_groupby) >= 2) {
  204. setEventMessages($langs->trans("ErrorOnlyOneFieldForGroupByIsPossible"), null, 'warnings');
  205. $search_groupby = array(0 => $search_groupby[0]);
  206. }
  207. if (!count($search_xaxis)) {
  208. setEventMessages($langs->trans("AtLeastOneXAxisIsRequired"), null, 'warnings');
  209. } elseif ($mode == 'graph' && $search_graph == 'bars' && count($search_measures) > $MAXMEASURESINBARGRAPH) {
  210. $langs->load("errors");
  211. setEventMessages($langs->trans("GraphInBarsAreLimitedToNMeasures", $MAXMEASURESINBARGRAPH), null, 'warnings');
  212. $search_graph = 'lines';
  213. }
  214. }
  215. // Get all possible values of fields when a 'group by' is set, and save this into $arrayofvaluesforgroupby
  216. // $arrayofvaluesforgroupby will be used to forge lael of each grouped series
  217. if (is_array($search_groupby) && count($search_groupby)) {
  218. foreach ($search_groupby as $gkey => $gval) {
  219. $gvalwithoutprefix = preg_replace('/^[a-z]+\./', '', $gval);
  220. if (preg_match('/\-year$/', $search_groupby[$gkey])) {
  221. $tmpval = preg_replace('/\-year$/', '', $search_groupby[$gkey]);
  222. $fieldtocount .= 'DATE_FORMAT('.$tmpval.", '%Y')";
  223. } elseif (preg_match('/\-month$/', $search_groupby[$gkey])) {
  224. $tmpval = preg_replace('/\-month$/', '', $search_groupby[$gkey]);
  225. $fieldtocount .= 'DATE_FORMAT('.$tmpval.", '%Y-%m')";
  226. } elseif (preg_match('/\-day$/', $search_groupby[$gkey])) {
  227. $tmpval = preg_replace('/\-day$/', '', $search_groupby[$gkey]);
  228. $fieldtocount .= 'DATE_FORMAT('.$tmpval.", '%Y-%m-%d')";
  229. } else {
  230. $fieldtocount = $search_groupby[$gkey];
  231. }
  232. $sql = "SELECT DISTINCT ".$fieldtocount." as val";
  233. if (strpos($fieldtocount, 'te') === 0) {
  234. $tabletouse = $object->table_element;
  235. $tablealiastouse = 'te';
  236. if (!empty($arrayofgroupby[$gval])) {
  237. $tmpval = explode('.', $gval);
  238. $tabletouse = $arrayofgroupby[$gval]['table'];
  239. $tablealiastouse = $tmpval[0];
  240. }
  241. //var_dump($tablealiastouse);exit;
  242. //$sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element."_extrafields as te";
  243. $sql .= " FROM ".MAIN_DB_PREFIX.$tabletouse."_extrafields as ".$tablealiastouse;
  244. } else {
  245. $tabletouse = $object->table_element;
  246. $tablealiastouse = 't';
  247. if (!empty($arrayofgroupby[$gval])) {
  248. $tmpval = explode('.', $gval);
  249. $tabletouse = $arrayofgroupby[$gval]['table'];
  250. $tablealiastouse = $tmpval[0];
  251. }
  252. $sql .= " FROM ".MAIN_DB_PREFIX.$tabletouse." as ".$tablealiastouse;
  253. }
  254. // Add a where here keeping only the citeria on $tabletouse
  255. // TODO
  256. /*$sqlfilters = ... GETPOST('search_component_params_hidden', 'alphanohtml');
  257. if ($sqlfilters) {
  258. $errormessage = '';
  259. $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
  260. }*/
  261. $sql .= " LIMIT ".((int) ($MAXUNIQUEVALFORGROUP + 1));
  262. //print $sql;
  263. $resql = $db->query($sql);
  264. if (!$resql) {
  265. dol_print_error($db);
  266. }
  267. while ($obj = $db->fetch_object($resql)) {
  268. if (is_null($obj->val)) {
  269. $keytouse = '__NULL__';
  270. $valuetranslated = $langs->transnoentitiesnoconv("NotDefined");
  271. } elseif ($obj->val === '') {
  272. $keytouse = '';
  273. $valuetranslated = $langs->transnoentitiesnoconv("Empty");
  274. } else {
  275. $keytouse = (string) $obj->val;
  276. $valuetranslated = $obj->val;
  277. }
  278. $regs = array();
  279. if (!empty($object->fields[$gvalwithoutprefix]['arrayofkeyval'])) {
  280. $valuetranslated = $object->fields[$gvalwithoutprefix]['arrayofkeyval'][$obj->val];
  281. if (is_null($valuetranslated)) {
  282. $valuetranslated = $langs->transnoentitiesnoconv("UndefinedKey");
  283. }
  284. $valuetranslated = $langs->trans($valuetranslated);
  285. } elseif (preg_match('/integer:([^:]+):([^:]+)$/', $object->fields[$gvalwithoutprefix]['type'], $regs)) {
  286. $classname = $regs[1];
  287. $classpath = $regs[2];
  288. dol_include_once($classpath);
  289. if (class_exists($classname)) {
  290. $tmpobject = new $classname($db);
  291. $tmpobject->fetch($obj->val);
  292. foreach ($tmpobject->fields as $fieldkey => $field) {
  293. if ($field['showoncombobox']) {
  294. $valuetranslated = $tmpobject->$fieldkey;
  295. //if ($valuetranslated == '-') $valuetranslated = $langs->transnoentitiesnoconv("Unknown")
  296. break;
  297. }
  298. }
  299. //$valuetranslated = $tmpobject->ref.'eee';
  300. }
  301. }
  302. $arrayofvaluesforgroupby['g_'.$gkey][$keytouse] = $valuetranslated;
  303. }
  304. // Add also the possible NULL value if field is a parent field that is not a strict join
  305. $tmpfield = explode('.', $gval);
  306. if ($tmpfield[0] != 't' || (is_array($object->fields[$tmpfield[1]]) && empty($object->fields[$tmpfield[1]]['notnull']))) {
  307. dol_syslog("The group by field ".$gval." may be null (because field is null or it is a left join), so we add __NULL__ entry in list of possible values");
  308. //var_dump($gval); var_dump($object->fields);
  309. $arrayofvaluesforgroupby['g_'.$gkey]['__NULL__'] = $langs->transnoentitiesnoconv("NotDefined");
  310. }
  311. asort($arrayofvaluesforgroupby['g_'.$gkey]);
  312. // Add a protection/error to refuse the request if number of differentr values for the group by is higher than $MAXUNIQUEVALFORGROUP
  313. if (count($arrayofvaluesforgroupby['g_'.$gkey]) > $MAXUNIQUEVALFORGROUP) {
  314. $langs->load("errors");
  315. if (strpos($fieldtocount, 'te') === 0) { // This is a field of an extrafield
  316. //if (!empty($extrafields->attributes[$object->table_element]['langfile'][$gvalwithoutprefix])) {
  317. // $langs->load($extrafields->attributes[$object->table_element]['langfile'][$gvalwithoutprefix]);
  318. //}
  319. $keyforlabeloffield = $extrafields->attributes[$object->table_element]['label'][$gvalwithoutprefix];
  320. $labeloffield = $langs->transnoentitiesnoconv($keyforlabeloffield);
  321. } elseif (strpos($fieldtocount, 't__') === 0) { // This is a field of a foreign key
  322. $reg = array();
  323. if (preg_match('/^(.*)\.(.*)/', $gvalwithoutprefix, $reg)) {
  324. /*
  325. $gvalwithoutprefix = preg_replace('/\..*$/', '', $gvalwithoutprefix);
  326. $gvalwithoutprefix = preg_replace('/^t__/', '', $gvalwithoutprefix);
  327. $keyforlabeloffield = $object->fields[$gvalwithoutprefix]['label'];
  328. $labeloffield = $langs->transnoentitiesnoconv($keyforlabeloffield).'-'.$reg[2];
  329. */
  330. $labeloffield = $arrayofgroupby[$fieldtocount]['labelnohtml'];
  331. } else {
  332. $labeloffield = $langs->transnoentitiesnoconv($keyforlabeloffield);
  333. }
  334. } else { // This is a common field
  335. $reg = array();
  336. if (preg_match('/^(.*)\-(year|month|day)/', $gvalwithoutprefix, $reg)) {
  337. $gvalwithoutprefix = preg_replace('/\-(year|month|day)/', '', $gvalwithoutprefix);
  338. $keyforlabeloffield = $object->fields[$gvalwithoutprefix]['label'];
  339. $labeloffield = $langs->transnoentitiesnoconv($keyforlabeloffield).'-'.$reg[2];
  340. } else {
  341. $keyforlabeloffield = $object->fields[$gvalwithoutprefix]['label'];
  342. $labeloffield = $langs->transnoentitiesnoconv($keyforlabeloffield);
  343. }
  344. }
  345. //var_dump($object->fields);
  346. setEventMessages($langs->trans("ErrorTooManyDifferentValueForSelectedGroupBy", $MAXUNIQUEVALFORGROUP, $labeloffield), null, 'warnings');
  347. $search_groupby = array();
  348. }
  349. $db->free($resql);
  350. }
  351. }
  352. //var_dump($arrayofvaluesforgroupby);exit;
  353. $tmparray = dol_getdate(dol_now());
  354. $endyear = $tmparray['year'];
  355. $endmonth = $tmparray['mon'];
  356. $datelastday = dol_get_last_day($endyear, $endmonth, 1);
  357. $startyear = $endyear - 2;
  358. $param = '';
  359. print '<form method="post" action="'.$_SERVER['PHP_SELF'].'" autocomplete="off">';
  360. print '<input type="hidden" name="token" value="'.newToken().'">';
  361. print '<input type="hidden" name="action" value="viewgraph">';
  362. print '<input type="hidden" name="tabfamily" value="'.$tabfamily.'">';
  363. $viewmode = '';
  364. $viewmode .= '<div class="divadvancedsearchfield">';
  365. $arrayofgraphs = array('bars' => 'Bars', 'lines' => 'Lines'); // also 'pies'
  366. $viewmode .= '<div class="inline-block opacitymedium"><span class="fas fa-chart-area paddingright" title="'.$langs->trans("Graph").'"></span>'.$langs->trans("Graph").'</div> ';
  367. $viewmode .= $form->selectarray('search_graph', $arrayofgraphs, $search_graph, 0, 0, 0, '', 1, 0, 0, '', 'graphtype width100');
  368. $viewmode .= '</div>';
  369. $num = 0;
  370. $massactionbutton = '';
  371. $nav = '';
  372. $newcardbutton = '';
  373. $limit = 0;
  374. print_barre_liste('', $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, -1, 'object_action', 0, $nav.'<span class="marginleftonly"></span>'.$newcardbutton, '', $limit, 1, 0, 1, $viewmode);
  375. foreach ($newarrayoftype as $tmpkey => $tmpval) {
  376. $newarrayoftype[$tmpkey]['label'] = img_picto('', $tmpval['picto'], 'class="pictofixedwidth"').$langs->trans($tmpval['label']);
  377. }
  378. print '<div class="liste_titre liste_titre_bydiv liste_titre_bydiv_inlineblock centpercent">';
  379. // Select object
  380. print '<div class="divadvancedsearchfield center floatnone">';
  381. print '<div class="inline-block"><span class="opacitymedium">'.$langs->trans("StatisticsOn").'</span></div> ';
  382. print $form->selectarray('objecttype', $newarrayoftype, $objecttype, 0, 0, 0, '', 1, 0, 0, '', 'minwidth200', 1, '', 0, 1);
  383. if (empty($conf->use_javascript_ajax)) {
  384. print '<input type="submit" class="button buttongen button-save nomargintop" name="changeobjecttype" value="'.$langs->trans("Refresh").'">';
  385. } else {
  386. print '<!-- js code to reload page with good object type -->
  387. <script nonce="'.getNonce().'" type="text/javascript">
  388. jQuery(document).ready(function() {
  389. jQuery("#objecttype").change(function() {
  390. console.log("Reload for "+jQuery("#objecttype").val());
  391. location.href = "'.$_SERVER["PHP_SELF"].'?objecttype="+jQuery("#objecttype").val()+"'.($tabfamily ? '&tabfamily='.urlencode($tabfamily) : '').(GETPOST('show_search_component_params_hidden', 'int') ? '&show_search_component_params_hidden='.((int) GETPOST('show_search_component_params_hidden', 'int')) : '').'";
  392. });
  393. });
  394. </script>';
  395. }
  396. print '</div><div class="clearboth"></div>';
  397. // Filter (you can use param &show_search_component_params_hidden=1 for debug)
  398. print '<div class="divadvancedsearchfield quatrevingtpercent">';
  399. print $form->searchComponent(array($object->element => $object->fields), $search_component_params, array(), $search_component_params_hidden);
  400. print '</div>';
  401. // YAxis (add measures into array)
  402. $count = 0;
  403. //var_dump($arrayofmesures);
  404. print '<div class="divadvancedsearchfield clearboth">';
  405. print '<div class="inline-block"><span class="fas fa-ruler-combined paddingright pictofixedwidth" title="'.dol_escape_htmltag($langs->trans("Measures")).'"></span><span class="fas fa-caret-left caretleftaxis" title="'.dol_escape_htmltag($langs->trans("Measures")).'"></span></div>';
  406. $simplearrayofmesures = array();
  407. foreach ($arrayofmesures as $key => $val) {
  408. $simplearrayofmesures[$key] = $arrayofmesures[$key]['label'];
  409. }
  410. print $form->multiselectarray('search_measures', $simplearrayofmesures, $search_measures, 0, 0, 'minwidth300', 1, 0, '', '', $langs->trans("Measures")); // Fill the array $arrayofmeasures with possible fields
  411. print '</div>';
  412. // XAxis
  413. $count = 0;
  414. print '<div class="divadvancedsearchfield">';
  415. print '<div class="inline-block"><span class="fas fa-ruler-combined paddingright pictofixedwidth" title="'.dol_escape_htmltag($langs->trans("XAxis")).'"></span><span class="fas fa-caret-down caretdownaxis" title="'.dol_escape_htmltag($langs->trans("XAxis")).'"></span></div>';
  416. //var_dump($arrayofxaxis);
  417. print $formother->selectXAxisField($object, $search_xaxis, $arrayofxaxis, $langs->trans("XAxis"), 'minwidth300 maxwidth400'); // Fill the array $arrayofxaxis with possible fields
  418. print '</div>';
  419. // Group by
  420. $count = 0;
  421. print '<div class="divadvancedsearchfield">';
  422. print '<div class="inline-block opacitymedium"><span class="fas fa-ruler-horizontal paddingright pictofixedwidth" title="'.dol_escape_htmltag($langs->trans("GroupBy")).'"></span></div>';
  423. print $formother->selectGroupByField($object, $search_groupby, $arrayofgroupby, 'minwidth250 maxwidth300', $langs->trans("GroupBy")); // Fill the array $arrayofgroupby with possible fields
  424. print '</div>';
  425. if ($mode == 'grid') {
  426. // YAxis
  427. print '<div class="divadvancedsearchfield">';
  428. foreach ($object->fields as $key => $val) {
  429. if (empty($val['measure']) && (!isset($val['enabled']) || dol_eval($val['enabled'], 1, 1, '1'))) {
  430. if (in_array($key, array('id', 'rowid', 'entity', 'last_main_doc', 'extraparams'))) {
  431. continue;
  432. }
  433. if (preg_match('/^fk_/', $key)) {
  434. continue;
  435. }
  436. if (in_array($val['type'], array('html', 'text'))) {
  437. continue;
  438. }
  439. if (in_array($val['type'], array('timestamp', 'date', 'datetime'))) {
  440. $arrayofyaxis['t.'.$key.'-year'] = array(
  441. 'label' => $langs->trans($val['label']).' ('.$YYYY.')',
  442. 'position' => $val['position'],
  443. 'table' => $object->table_element
  444. );
  445. $arrayofyaxis['t.'.$key.'-month'] = array(
  446. 'label' => $langs->trans($val['label']).' ('.$YYYY.'-'.$MM.')',
  447. 'position' => $val['position'],
  448. 'table' => $object->table_element
  449. );
  450. $arrayofyaxis['t.'.$key.'-day'] = array(
  451. 'label' => $langs->trans($val['label']).' ('.$YYYY.'-'.$MM.'-'.$DD.')',
  452. 'position' => $val['position'],
  453. 'table' => $object->table_element
  454. );
  455. } else {
  456. $arrayofyaxis['t.'.$key] = array(
  457. 'label' => $val['label'],
  458. 'position' => (int) $val['position'],
  459. 'table' => $object->table_element
  460. );
  461. }
  462. }
  463. }
  464. // Add measure from extrafields
  465. if ($object->isextrafieldmanaged) {
  466. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
  467. if (!empty($extrafields->attributes[$object->table_element]['totalizable'][$key]) && (!isset($extrafields->attributes[$object->table_element]['enabled'][$key]) || dol_eval($extrafields->attributes[$object->table_element]['enabled'][$key], 1, 1, '1'))) {
  468. $arrayofyaxis['te.'.$key] = array(
  469. 'label' => $extrafields->attributes[$object->table_element]['label'][$key],
  470. 'position' => (int) $extrafields->attributes[$object->table_element]['pos'][$key],
  471. 'table' => $object->table_element
  472. );
  473. }
  474. }
  475. }
  476. $arrayofyaxis = dol_sort_array($arrayofyaxis, 'position');
  477. $arrayofyaxislabel = array();
  478. foreach ($arrayofyaxis as $key => $val) {
  479. $arrayofyaxislabel[$key] = $val['label'];
  480. }
  481. print '<div class="inline-block opacitymedium"><span class="fas fa-ruler-vertical paddingright" title="'.$langs->trans("YAxis").'"></span>'.$langs->trans("YAxis").'</div> ';
  482. print $form->multiselectarray('search_yaxis', $arrayofyaxislabel, $search_yaxis, 0, 0, 'minwidth100', 1);
  483. print '</div>';
  484. }
  485. if ($mode == 'graph') {
  486. //
  487. }
  488. print '<div class="divadvancedsearchfield">';
  489. print '<input type="submit" class="button buttongen button-save nomargintop" value="'.$langs->trans("Refresh").'">';
  490. print '</div>';
  491. print '</div>';
  492. print '</form>';
  493. // Generate the SQL request
  494. $sql = '';
  495. if (!empty($search_measures) && !empty($search_xaxis)) {
  496. $errormessage = '';
  497. $fieldid = 'rowid';
  498. $sql = "SELECT ";
  499. foreach ($search_xaxis as $key => $val) {
  500. if (preg_match('/\-year$/', $val)) {
  501. $tmpval = preg_replace('/\-year$/', '', $val);
  502. $sql .= "DATE_FORMAT(".$tmpval.", '%Y') as x_".$key.', ';
  503. } elseif (preg_match('/\-month$/', $val)) {
  504. $tmpval = preg_replace('/\-month$/', '', $val);
  505. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m') as x_".$key.', ';
  506. } elseif (preg_match('/\-day$/', $val)) {
  507. $tmpval = preg_replace('/\-day$/', '', $val);
  508. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m-%d') as x_".$key.', ';
  509. } else {
  510. $sql .= $val." as x_".$key.", ";
  511. }
  512. }
  513. foreach ($search_groupby as $key => $val) {
  514. if (preg_match('/\-year$/', $val)) {
  515. $tmpval = preg_replace('/\-year$/', '', $val);
  516. $sql .= "DATE_FORMAT(".$tmpval.", '%Y') as g_".$key.', ';
  517. } elseif (preg_match('/\-month$/', $val)) {
  518. $tmpval = preg_replace('/\-month$/', '', $val);
  519. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m') as g_".$key.', ';
  520. } elseif (preg_match('/\-day$/', $val)) {
  521. $tmpval = preg_replace('/\-day$/', '', $val);
  522. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m-%d') as g_".$key.', ';
  523. } else {
  524. $sql .= $val." as g_".$key.", ";
  525. }
  526. }
  527. foreach ($search_measures as $key => $val) {
  528. if ($val == 't.count') {
  529. $sql .= "COUNT(t.".$fieldid.") as y_".$key.', ';
  530. } elseif (preg_match('/\-sum$/', $val)) {
  531. $tmpval = preg_replace('/\-sum$/', '', $val);
  532. $sql .= "SUM(".$db->ifsql($tmpval.' IS NULL', '0', $tmpval).") as y_".$key.", ";
  533. } elseif (preg_match('/\-average$/', $val)) {
  534. $tmpval = preg_replace('/\-average$/', '', $val);
  535. $sql .= "AVG(".$db->ifsql($tmpval.' IS NULL', '0', $tmpval).") as y_".$key.", ";
  536. } elseif (preg_match('/\-min$/', $val)) {
  537. $tmpval = preg_replace('/\-min$/', '', $val);
  538. $sql .= "MIN(".$db->ifsql($tmpval.' IS NULL', '0', $tmpval).") as y_".$key.", ";
  539. } elseif (preg_match('/\-max$/', $val)) {
  540. $tmpval = preg_replace('/\-max$/', '', $val);
  541. $sql .= "MAX(".$db->ifsql($tmpval.' IS NULL', '0', $tmpval).") as y_".$key.", ";
  542. }
  543. }
  544. $sql = preg_replace('/,\s*$/', '', $sql);
  545. $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t";
  546. // Add measure from extrafields
  547. if ($object->isextrafieldmanaged) {
  548. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as te ON te.fk_object = t.".$fieldid;
  549. }
  550. // Add table for link on multientity
  551. if ($object->ismultientitymanaged) { // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  552. if ($object->ismultientitymanaged == 1) {
  553. // No table to add here
  554. } else {
  555. $tmparray = explode('@', $object->ismultientitymanaged);
  556. $sql .= " INNER JOIN ".MAIN_DB_PREFIX.$tmparray[1]." as parenttableforentity ON t.".$tmparray[0]." = parenttableforentity.rowid";
  557. $sql .= " AND parenttableforentity.entity IN (".getEntity($tmparray[1]).")";
  558. }
  559. }
  560. // Init the list of tables added. We include by default always the main table.
  561. $listoftablesalreadyadded = array($object->table_element => $object->table_element);
  562. // Add LEFT JOIN for all parent tables mentionned into the Xaxis
  563. //var_dump($arrayofxaxis); var_dump($search_xaxis);
  564. foreach ($search_xaxis as $key => $val) {
  565. if (!empty($arrayofxaxis[$val])) {
  566. $tmpval = explode('.', $val);
  567. //var_dump($arrayofgroupby);
  568. $tmpforloop = dolExplodeIntoArray($arrayofxaxis[$val]['tablefromt'], ',');
  569. foreach ($tmpforloop as $tmptable => $tmptablealias) {
  570. if (! in_array($tmptable, $listoftablesalreadyadded)) { // We do not add join for main table and tables already added
  571. $tmpforexplode = explode('__', $tmptablealias);
  572. $endpart = end($tmpforexplode);
  573. $parenttableandfield = preg_replace('/__'.$endpart.'$/', '', $tmptablealias).'.'.$endpart;
  574. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$tmptable." as ".$db->sanitize($tmptablealias)." ON ".$db->sanitize($parenttableandfield)." = ".$db->sanitize($tmptablealias).".rowid";
  575. $listoftablesalreadyadded[$tmptable] = $tmptable;
  576. if (preg_match('/^te/', $tmpval[0]) && preg_replace('/^t_/', 'te_', $tmptablealias) == $tmpval[0]) {
  577. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$tmptable."_extrafields as ".$db->sanitize($tmpval[0])." ON ".$db->sanitize($tmpval[0]).".fk_object = ".$db->sanitize($tmptablealias).".rowid";
  578. $listoftablesalreadyadded[$tmptable] = $tmptable;
  579. }
  580. }
  581. }
  582. } else {
  583. $errormessage = 'Found a key into search_xaxis not found into arrayofxaxis';
  584. }
  585. }
  586. // Add LEFT JOIN for all parent tables mentionned into the Group by
  587. //var_dump($arrayofgroupby); var_dump($search_groupby);
  588. foreach ($search_groupby as $key => $val) {
  589. if (!empty($arrayofgroupby[$val])) {
  590. $tmpval = explode('.', $val);
  591. //var_dump($arrayofgroupby[$val]); var_dump($tmpval);
  592. $tmpforloop = dolExplodeIntoArray($arrayofgroupby[$val]['tablefromt'], ',');
  593. foreach ($tmpforloop as $tmptable => $tmptablealias) {
  594. if (! in_array($tmptable, $listoftablesalreadyadded)) { // We do not add join for main table and tables already added
  595. $tmpforexplode = explode('__', $tmptablealias);
  596. $endpart = end($tmpforexplode);
  597. $parenttableandfield = preg_replace('/__'.$endpart.'$/', '', $tmptablealias).'.'.$endpart;
  598. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$tmptable." as ".$db->sanitize($tmptablealias)." ON ".$db->sanitize($parenttableandfield)." = ".$db->sanitize($tmptablealias).".rowid";
  599. $listoftablesalreadyadded[$tmptable] = $tmptable;
  600. if (preg_match('/^te/', $tmpval[0]) && preg_replace('/^t_/', 'te_', $tmptablealias) == $tmpval[0]) {
  601. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$tmptable."_extrafields as ".$db->sanitize($tmpval[0])." ON ".$db->sanitize($tmpval[0]).".fk_object = ".$db->sanitize($tmptablealias).".rowid";
  602. $listoftablesalreadyadded[$tmptable] = $tmptable;
  603. }
  604. }
  605. }
  606. } else {
  607. $errormessage = 'Found a key into search_groupby not found into arrayofgroupby';
  608. }
  609. }
  610. // Add LEFT JOIN for all parent tables mentionned into the Yaxis
  611. //var_dump($arrayofgroupby); var_dump($search_groupby);
  612. foreach ($search_measures as $key => $val) {
  613. if (!empty($arrayofmesures[$val])) {
  614. $tmpval = explode('.', $val);
  615. //var_dump($arrayofgroupby);
  616. $tmpforloop = dolExplodeIntoArray($arrayofmesures[$val]['tablefromt'], ',');
  617. foreach ($tmpforloop as $tmptable => $tmptablealias) {
  618. if (! in_array($tmptable, $listoftablesalreadyadded)) { // We do not add join for main table and tables already added
  619. $tmpforexplode = explode('__', $tmptablealias);
  620. $endpart = end($tmpforexplode);
  621. $parenttableandfield = preg_replace('/__'.$endpart.'$/', '', $tmptablealias).'.'.$endpart;
  622. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$tmptable." as ".$db->sanitize($tmptablealias)." ON ".$db->sanitize($parenttableandfield)." = ".$db->sanitize($tmptablealias).".rowid";
  623. $listoftablesalreadyadded[$tmptable] = $tmptable;
  624. if (preg_match('/^te/', $tmpval[0]) && preg_replace('/^t_/', 'te_', $tmptablealias) == $tmpval[0]) {
  625. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$tmptable."_extrafields as ".$db->sanitize($tmpval[0])." ON ".$db->sanitize($tmpval[0]).".fk_object = ".$db->sanitize($tmptablealias).".rowid";
  626. $listoftablesalreadyadded[$tmptable] = $tmptable;
  627. }
  628. }
  629. }
  630. } else {
  631. $errormessage = 'Found a key into search_measures not found into arrayofmesures';
  632. }
  633. }
  634. $sql .= " WHERE 1 = 1";
  635. if ($object->ismultientitymanaged == 1) { // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  636. $sql .= " AND t.entity IN (".getEntity($object->element).")";
  637. }
  638. // Add the where here
  639. $sqlfilters = $search_component_params_hidden;
  640. if ($sqlfilters) {
  641. $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage, 0, 0, 1);
  642. }
  643. $sql .= " GROUP BY ";
  644. foreach ($search_xaxis as $key => $val) {
  645. if (preg_match('/\-year$/', $val)) {
  646. $tmpval = preg_replace('/\-year$/', '', $val);
  647. $sql .= "DATE_FORMAT(".$tmpval.", '%Y'), ";
  648. } elseif (preg_match('/\-month$/', $val)) {
  649. $tmpval = preg_replace('/\-month$/', '', $val);
  650. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m'), ";
  651. } elseif (preg_match('/\-day$/', $val)) {
  652. $tmpval = preg_replace('/\-day$/', '', $val);
  653. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m-%d'), ";
  654. } else {
  655. $sql .= $val.", ";
  656. }
  657. }
  658. foreach ($search_groupby as $key => $val) {
  659. if (preg_match('/\-year$/', $val)) {
  660. $tmpval = preg_replace('/\-year$/', '', $val);
  661. $sql .= "DATE_FORMAT(".$tmpval.", '%Y'), ";
  662. } elseif (preg_match('/\-month$/', $val)) {
  663. $tmpval = preg_replace('/\-month$/', '', $val);
  664. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m'), ";
  665. } elseif (preg_match('/\-day$/', $val)) {
  666. $tmpval = preg_replace('/\-day$/', '', $val);
  667. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m-%d'), ";
  668. } else {
  669. $sql .= $val.', ';
  670. }
  671. }
  672. $sql = preg_replace('/,\s*$/', '', $sql);
  673. $sql .= ' ORDER BY ';
  674. foreach ($search_xaxis as $key => $val) {
  675. if (preg_match('/\-year$/', $val)) {
  676. $tmpval = preg_replace('/\-year$/', '', $val);
  677. $sql .= "DATE_FORMAT(".$tmpval.", '%Y'), ";
  678. } elseif (preg_match('/\-month$/', $val)) {
  679. $tmpval = preg_replace('/\-month$/', '', $val);
  680. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m'), ";
  681. } elseif (preg_match('/\-day$/', $val)) {
  682. $tmpval = preg_replace('/\-day$/', '', $val);
  683. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m-%d'), ";
  684. } else {
  685. $sql .= $val.', ';
  686. }
  687. }
  688. foreach ($search_groupby as $key => $val) {
  689. if (preg_match('/\-year$/', $val)) {
  690. $tmpval = preg_replace('/\-year$/', '', $val);
  691. $sql .= "DATE_FORMAT(".$tmpval.", '%Y'), ";
  692. } elseif (preg_match('/\-month$/', $val)) {
  693. $tmpval = preg_replace('/\-month$/', '', $val);
  694. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m'), ";
  695. } elseif (preg_match('/\-day$/', $val)) {
  696. $tmpval = preg_replace('/\-day$/', '', $val);
  697. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m-%d'), ";
  698. } else {
  699. $sql .= $val.', ';
  700. }
  701. }
  702. $sql = preg_replace('/,\s*$/', '', $sql);
  703. }
  704. //print $sql;
  705. if ($errormessage) {
  706. print dol_escape_htmltag($errormessage);
  707. $sql = '';
  708. }
  709. $legend = array();
  710. foreach ($search_measures as $key => $val) {
  711. $legend[] = $langs->trans($arrayofmesures[$val]['label']);
  712. }
  713. $useagroupby = (is_array($search_groupby) && count($search_groupby));
  714. //var_dump($useagroupby);
  715. //var_dump($arrayofvaluesforgroupby);
  716. // Execute the SQL request
  717. $totalnbofrecord = 0;
  718. $data = array();
  719. if ($sql) {
  720. $resql = $db->query($sql);
  721. if (!$resql) {
  722. dol_print_error($db);
  723. }
  724. $ifetch = 0;
  725. $xi = 0;
  726. $oldlabeltouse = '';
  727. while ($obj = $db->fetch_object($resql)) {
  728. $ifetch++;
  729. if ($useagroupby) {
  730. $xval = $search_xaxis[0];
  731. $fieldforxkey = 'x_0';
  732. $xlabel = $obj->$fieldforxkey;
  733. $xvalwithoutprefix = preg_replace('/^[a-z]+\./', '', $xval);
  734. // Define $xlabel
  735. if (!empty($object->fields[$xvalwithoutprefix]['arrayofkeyval'])) {
  736. $xlabel = $object->fields[$xvalwithoutprefix]['arrayofkeyval'][$obj->$fieldforxkey];
  737. }
  738. $labeltouse = (($xlabel || $xlabel == '0') ? dol_trunc($xlabel, 20, 'middle') : ($xlabel === '' ? $langs->transnoentitiesnoconv("Empty") : $langs->transnoentitiesnoconv("NotDefined")));
  739. if ($oldlabeltouse && ($labeltouse != $oldlabeltouse)) {
  740. $xi++; // Increase $xi
  741. }
  742. //var_dump($labeltouse.' '.$oldlabeltouse.' '.$xi);
  743. $oldlabeltouse = $labeltouse;
  744. /* Example of value for $arrayofvaluesforgroupby
  745. * array (size=1)
  746. * 'g_0' =>
  747. * array (size=6)
  748. * 0 => string '0' (length=1)
  749. * '' => string 'Empty' (length=5)
  750. * '__NULL__' => string 'Not defined' (length=11)
  751. * 'done' => string 'done' (length=4)
  752. * 'processing' => string 'processing' (length=10)
  753. * 'undeployed' => string 'undeployed' (length=10)
  754. */
  755. foreach ($search_measures as $key => $val) {
  756. $gi = 0;
  757. foreach ($search_groupby as $gkey) {
  758. //var_dump('*** Fetch #'.$ifetch.' for labeltouse='.$labeltouse.' measure number '.$key.' and group g_'.$gi);
  759. //var_dump($arrayofvaluesforgroupby);
  760. foreach ($arrayofvaluesforgroupby['g_'.$gi] as $gvaluepossiblekey => $gvaluepossiblelabel) {
  761. $ykeysuffix = $gvaluepossiblelabel;
  762. $gvalwithoutprefix = preg_replace('/^[a-z]+\./', '', $gval);
  763. $fieldfory = 'y_'.$key;
  764. $fieldforg = 'g_'.$gi;
  765. $fieldforybis = 'y_'.$key.'_'.$ykeysuffix;
  766. //var_dump('gvaluepossiblekey='.$gvaluepossiblekey.' gvaluepossiblelabel='.$gvaluepossiblelabel.' ykeysuffix='.$ykeysuffix.' gval='.$gval.' gvalwithoutsuffix='.$gvalwithoutprefix);
  767. //var_dump('fieldforg='.$fieldforg.' obj->$fieldforg='.$obj->$fieldforg.' fieldfory='.$fieldfory.' obj->$fieldfory='.$obj->$fieldfory.' fieldforybis='.$fieldforybis);
  768. if (!is_array($data[$xi])) {
  769. $data[$xi] = array();
  770. }
  771. if (!array_key_exists('label', $data[$xi])) {
  772. $data[$xi] = array();
  773. $data[$xi]['label'] = $labeltouse;
  774. }
  775. $objfieldforg = $obj->$fieldforg;
  776. if (is_null($objfieldforg)) {
  777. $objfieldforg = '__NULL__';
  778. }
  779. if ($gvaluepossiblekey == '0') { // $gvaluepossiblekey can have type int or string. So we create a special if, used when value is '0'
  780. //var_dump($objfieldforg.' == \'0\' -> '.($objfieldforg == '0'));
  781. if ($objfieldforg == '0') {
  782. // The record we fetch is for this group
  783. $data[$xi][$fieldforybis] = $obj->$fieldfory;
  784. } elseif (!isset($data[$xi][$fieldforybis])) {
  785. // The record we fetch is not for this group
  786. $data[$xi][$fieldforybis] = '0';
  787. }
  788. } else {
  789. //var_dump((string) $objfieldforg.' === '.(string) $gvaluepossiblekey.' -> '.((string) $objfieldforg === (string) $gvaluepossiblekey));
  790. if ((string) $objfieldforg === (string) $gvaluepossiblekey) {
  791. // The record we fetch is for this group
  792. $data[$xi][$fieldforybis] = $obj->$fieldfory;
  793. } elseif (!isset($data[$xi][$fieldforybis])) {
  794. // The record we fetch is not for this group
  795. $data[$xi][$fieldforybis] = '0';
  796. }
  797. }
  798. }
  799. //var_dump($data[$xi]);
  800. $gi++;
  801. }
  802. }
  803. } else { // No group by
  804. $xval = $search_xaxis[0];
  805. $fieldforxkey = 'x_0';
  806. $xlabel = $obj->$fieldforxkey;
  807. $xvalwithoutprefix = preg_replace('/^[a-z]+\./', '', $xval);
  808. // Define $xlabel
  809. if (!empty($object->fields[$xvalwithoutprefix]['arrayofkeyval'])) {
  810. $xlabel = $object->fields[$xvalwithoutprefix]['arrayofkeyval'][$obj->$fieldforxkey];
  811. }
  812. $labeltouse = (($xlabel || $xlabel == '0') ? dol_trunc($xlabel, 20, 'middle') : ($xlabel === '' ? $langs->transnoentitiesnoconv("Empty") : $langs->transnoentitiesnoconv("NotDefined")));
  813. $xarrayforallseries = array('label' => $labeltouse);
  814. foreach ($search_measures as $key => $val) {
  815. $fieldfory = 'y_'.$key;
  816. $xarrayforallseries[$fieldfory] = $obj->$fieldfory;
  817. }
  818. $data[$xi] = $xarrayforallseries;
  819. $xi++;
  820. }
  821. }
  822. $totalnbofrecord = count($data);
  823. }
  824. //var_dump($data);
  825. print '<div class="customreportsoutput'.($totalnbofrecord ? '' : ' customreportsoutputnotdata').'">';
  826. if ($mode == 'grid') {
  827. // TODO
  828. }
  829. if ($mode == 'graph') {
  830. $WIDTH = '80%';
  831. $HEIGHT = (empty($_SESSION['dol_screenheight']) ? 400 : $_SESSION['dol_screenheight'] - 500);
  832. // Show graph
  833. $px1 = new DolGraph();
  834. $mesg = $px1->isGraphKo();
  835. if (!$mesg) {
  836. //var_dump($legend);
  837. //var_dump($data);
  838. $px1->SetData($data);
  839. unset($data);
  840. $arrayoftypes = array();
  841. foreach ($search_measures as $key => $val) {
  842. $arrayoftypes[] = $search_graph;
  843. }
  844. $px1->SetLegend($legend);
  845. $px1->SetMinValue($px1->GetFloorMinValue());
  846. $px1->SetMaxValue($px1->GetCeilMaxValue());
  847. $px1->SetWidth($WIDTH);
  848. $px1->SetHeight($HEIGHT);
  849. $px1->SetYLabel($langs->trans("Y"));
  850. $px1->SetShading(3);
  851. $px1->SetHorizTickIncrement(1);
  852. $px1->SetCssPrefix("cssboxes");
  853. $px1->SetType($arrayoftypes);
  854. $px1->mode = 'depth';
  855. $px1->SetTitle('');
  856. $dir = $conf->user->dir_temp;
  857. dol_mkdir($dir);
  858. $filenamenb = $dir.'/customreport_'.$object->element.'.png';
  859. $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=user&file=customreport_'.$object->element.'.png';
  860. $px1->draw($filenamenb, $fileurlnb);
  861. $texttoshow = $langs->trans("NoRecordFound");
  862. if (!GETPOSTISSET('search_measures') || !GETPOSTISSET('search_xaxis')) {
  863. $texttoshow = $langs->trans("SelectYourGraphOptionsFirst");
  864. }
  865. print $px1->show($totalnbofrecord ? 0 : $texttoshow);
  866. }
  867. }
  868. if ($sql) {
  869. // Show admin info
  870. print '<br>'.info_admin($langs->trans("SQLUsedForExport").':<br> '.$sql, 0, 0, 1, '', 'TechnicalInformation');
  871. }
  872. print '<div>';
  873. if (!defined('USE_CUSTOM_REPORT_AS_INCLUDE')) {
  874. print dol_get_fiche_end();
  875. }
  876. // End of page
  877. llxFooter();
  878. $db->close();
  879. /**
  880. * Fill arrayofmesures for an object
  881. *
  882. * @param mixed $object Any object
  883. * @param string $tablealias Alias of table
  884. * @param string $labelofobject Label of object
  885. * @param array $arrayofmesures Array of mesures already filled
  886. * @param int $level Level
  887. * @param int $count Count
  888. * @param string $tablepath Path of all tables ('t' or 't,contract' or 't,contract,societe'...)
  889. * @return array Array of mesures
  890. */
  891. function fillArrayOfMeasures($object, $tablealias, $labelofobject, &$arrayofmesures, $level = 0, &$count = 0, &$tablepath = '')
  892. {
  893. global $langs, $extrafields, $db;
  894. if ($level > 10) { // Protection against infinite loop
  895. return $arrayofmesures;
  896. }
  897. if (empty($tablepath)) {
  898. $tablepath = $object->table_element.'='.$tablealias;
  899. } else {
  900. $tablepath .= ','.$object->table_element.'='.$tablealias;
  901. }
  902. if ($level == 0) {
  903. // Add the count of record only for the main/first level object. Parents are necessarly unique for each record.
  904. $arrayofmesures[$tablealias.'.count'] = array(
  905. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': Count',
  906. 'labelnohtml' => $labelofobject.': Count',
  907. 'position' => 0,
  908. 'table' => $object->table_element,
  909. 'tablefromt' => $tablepath
  910. );
  911. }
  912. // Note: here $tablealias can be 't' or 't__fk_contract' or 't_fk_contract_fk_soc'
  913. // Add main fields of object
  914. foreach ($object->fields as $key => $val) {
  915. if (!empty($val['isameasure']) && (!isset($val['enabled']) || dol_eval($val['enabled'], 1, 1, '1'))) {
  916. $position = (empty($val['position']) ? 0 : intVal($val['position']));
  917. $arrayofmesures[$tablealias.'.'.$key.'-sum'] = array(
  918. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']).' <span class="opacitymedium">('.$langs->trans("Sum").')</span>',
  919. 'labelnohtml' => $labelofobject.': '.$langs->trans($val['label']),
  920. 'position' => ($position + ($count * 100000)).'.1',
  921. 'table' => $object->table_element,
  922. 'tablefromt' => $tablepath
  923. );
  924. $arrayofmesures[$tablealias.'.'.$key.'-average'] = array(
  925. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']).' <span class="opacitymedium">('.$langs->trans("Average").')</span>',
  926. 'labelnohtml' => $labelofobject.': '.$langs->trans($val['label']),
  927. 'position' => ($position + ($count * 100000)).'.2',
  928. 'table' => $object->table_element,
  929. 'tablefromt' => $tablepath
  930. );
  931. $arrayofmesures[$tablealias.'.'.$key.'-min'] = array(
  932. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']).' <span class="opacitymedium">('.$langs->trans("Minimum").')</span>',
  933. 'labelnohtml' => $labelofobject.': '.$langs->trans($val['label']),
  934. 'position' => ($position + ($count * 100000)).'.3',
  935. 'table' => $object->table_element,
  936. 'tablefromt' => $tablepath
  937. );
  938. $arrayofmesures[$tablealias.'.'.$key.'-max'] = array(
  939. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']).' <span class="opacitymedium">('.$langs->trans("Maximum").')</span>',
  940. 'labelnohtml' => $labelofobject.': '.$langs->trans($val['label']),
  941. 'position' => ($position + ($count * 100000)).'.4',
  942. 'table' => $object->table_element,
  943. 'tablefromt' => $tablepath
  944. );
  945. }
  946. }
  947. // Add extrafields to Measures
  948. if (!empty($object->isextrafieldmanaged) && isset($extrafields->attributes[$object->table_element]['label'])) {
  949. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
  950. if (!empty($extrafields->attributes[$object->table_element]['totalizable'][$key]) && (!isset($extrafields->attributes[$object->table_element]['enabled'][$key]) || dol_eval($extrafields->attributes[$object->table_element]['enabled'][$key], 1, 1, '1'))) {
  951. $position = (!empty($val['position']) ? $val['position'] : 0);
  952. $arrayofmesures[preg_replace('/^t/', 'te', $tablealias).'.'.$key.'-sum'] = array(
  953. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($extrafields->attributes[$object->table_element]['label'][$key]).' <span class="opacitymedium">('.$langs->trans("Sum").')</span>',
  954. 'labelnohtml' => $labelofobject.': '.$langs->trans($val),
  955. 'position' => ($position+($count * 100000)).'.1',
  956. 'table' => $object->table_element,
  957. 'tablefromt' => $tablepath
  958. );
  959. $arrayofmesures[preg_replace('/^t/', 'te', $tablealias).'.'.$key.'-average'] = array(
  960. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($extrafields->attributes[$object->table_element]['label'][$key]).' <span class="opacitymedium">('.$langs->trans("Average").')</span>',
  961. 'labelnohtml' => $labelofobject.': '.$langs->trans($val),
  962. 'position' => ($position+($count * 100000)).'.2',
  963. 'table' => $object->table_element,
  964. 'tablefromt' => $tablepath
  965. );
  966. $arrayofmesures[preg_replace('/^t/', 'te', $tablealias).'.'.$key.'-min'] = array(
  967. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($extrafields->attributes[$object->table_element]['label'][$key]).' <span class="opacitymedium">('.$langs->trans("Minimum").')</span>',
  968. 'labelnohtml' => $labelofobject.': '.$langs->trans($val),
  969. 'position' => ($position+($count * 100000)).'.3',
  970. 'table' => $object->table_element,
  971. 'tablefromt' => $tablepath
  972. );
  973. $arrayofmesures[preg_replace('/^t/', 'te', $tablealias).'.'.$key.'-max'] = array(
  974. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($extrafields->attributes[$object->table_element]['label'][$key]).' <span class="opacitymedium">('.$langs->trans("Maximum").')</span>',
  975. 'labelnohtml' => $labelofobject.': '.$langs->trans($val),
  976. 'position' => ($position+($count * 100000)).'.4',
  977. 'table' => $object->table_element,
  978. 'tablefromt' => $tablepath
  979. );
  980. }
  981. }
  982. }
  983. // Add fields for parent objects
  984. foreach ($object->fields as $key => $val) {
  985. if (preg_match('/^[^:]+:[^:]+:/', $val['type'])) {
  986. $tmptype = explode(':', $val['type'], 4);
  987. if ($tmptype[0] == 'integer' && !empty($tmptype[1]) && !empty($tmptype[2])) {
  988. $newobject = $tmptype[1];
  989. dol_include_once($tmptype[2]);
  990. if (class_exists($newobject)) {
  991. $tmpobject = new $newobject($db);
  992. //var_dump($key); var_dump($tmpobject->element); var_dump($val['label']); var_dump($tmptype); var_dump('t-'.$key);
  993. $count++;
  994. $arrayofmesures = fillArrayOfMeasures($tmpobject, $tablealias.'__'.$key, $langs->trans($val['label']), $arrayofmesures, $level + 1, $count, $tablepath);
  995. } else {
  996. print 'For property '.$object->element.'->'.$key.', type="'.$val['type'].'": Failed to find class '.$newobject." in file ".$tmptype[2]."<br>\n";
  997. }
  998. }
  999. }
  1000. }
  1001. return $arrayofmesures;
  1002. }
  1003. /**
  1004. * Fill arrayofmesures for an object
  1005. *
  1006. * @param mixed $object Any object
  1007. * @param string $tablealias Alias of table ('t' for example)
  1008. * @param string $labelofobject Label of object
  1009. * @param array $arrayofxaxis Array of xaxis already filled
  1010. * @param int $level Level
  1011. * @param int $count Count
  1012. * @param string $tablepath Path of all tables ('t' or 't,contract' or 't,contract,societe'...)
  1013. * @return array Array of xaxis
  1014. */
  1015. function fillArrayOfXAxis($object, $tablealias, $labelofobject, &$arrayofxaxis, $level = 0, &$count = 0, &$tablepath = '')
  1016. {
  1017. global $langs, $extrafields, $db;
  1018. if ($level >= 3) { // Limit scan on 2 levels max
  1019. return $arrayofxaxis;
  1020. }
  1021. if (empty($tablepath)) {
  1022. $tablepath = $object->table_element.'='.$tablealias;
  1023. } else {
  1024. $tablepath .= ','.$object->table_element.'='.$tablealias;
  1025. }
  1026. $YYYY = substr($langs->trans("Year"), 0, 1).substr($langs->trans("Year"), 0, 1).substr($langs->trans("Year"), 0, 1).substr($langs->trans("Year"), 0, 1);
  1027. $MM = substr($langs->trans("Month"), 0, 1).substr($langs->trans("Month"), 0, 1);
  1028. $DD = substr($langs->trans("Day"), 0, 1).substr($langs->trans("Day"), 0, 1);
  1029. $HH = substr($langs->trans("Hour"), 0, 1).substr($langs->trans("Hour"), 0, 1);
  1030. $MI = substr($langs->trans("Minute"), 0, 1).substr($langs->trans("Minute"), 0, 1);
  1031. $SS = substr($langs->trans("Second"), 0, 1).substr($langs->trans("Second"), 0, 1);
  1032. /*if ($level > 0) {
  1033. var_dump($object->element.' '.$object->isextrafieldmanaged);
  1034. }*/
  1035. // Note: here $tablealias can be 't' or 't__fk_contract' or 't_fk_contract_fk_soc'
  1036. // Add main fields of object
  1037. foreach ($object->fields as $key => $val) {
  1038. if (empty($val['measure'])) {
  1039. if (in_array($key, array(
  1040. 'id', 'ref_ext', 'rowid', 'entity', 'last_main_doc', 'logo', 'logo_squarred', 'extraparams',
  1041. 'parent', 'photo', 'socialnetworks', 'webservices_url', 'webservices_key'))) {
  1042. continue;
  1043. }
  1044. if (isset($val['enabled']) && !dol_eval($val['enabled'], 1, 1, '1')) {
  1045. continue;
  1046. }
  1047. if (isset($val['visible']) && !dol_eval($val['visible'], 1, 1, '1')) {
  1048. continue;
  1049. }
  1050. if (preg_match('/^fk_/', $key) && !preg_match('/^fk_statu/', $key)) {
  1051. continue;
  1052. }
  1053. if (preg_match('/^pass/', $key)) {
  1054. continue;
  1055. }
  1056. if (in_array($val['type'], array('html', 'text'))) {
  1057. continue;
  1058. }
  1059. if (in_array($val['type'], array('timestamp', 'date', 'datetime'))) {
  1060. $position = (empty($val['position']) ? 0 : intVal($val['position']));
  1061. $arrayofxaxis[$tablealias.'.'.$key.'-year'] = array(
  1062. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']).' <span class="opacitymedium">('.$YYYY.')</span>',
  1063. 'labelnohtml' => $labelofobject.': '.$langs->trans($val['label']),
  1064. 'position' => ($position + ($count * 100000)).'.1',
  1065. 'table' => $object->table_element,
  1066. 'tablefromt' => $tablepath
  1067. );
  1068. $arrayofxaxis[$tablealias.'.'.$key.'-month'] = array(
  1069. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']).' <span class="opacitymedium">('.$YYYY.'-'.$MM.')</span>',
  1070. 'labelnohtml' => $labelofobject.': '.$langs->trans($val['label']),
  1071. 'position' => ($position + ($count * 100000)).'.2',
  1072. 'table' => $object->table_element,
  1073. 'tablefromt' => $tablepath
  1074. );
  1075. $arrayofxaxis[$tablealias.'.'.$key.'-day'] = array(
  1076. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']).' <span class="opacitymedium">('.$YYYY.'-'.$MM.'-'.$DD.')</span>',
  1077. 'labelnohtml' => $labelofobject.': '.$langs->trans($val['label']),
  1078. 'position' => ($position + ($count * 100000)).'.3',
  1079. 'table' => $object->table_element,
  1080. 'tablefromt' => $tablepath
  1081. );
  1082. } else {
  1083. $position = (empty($val['position']) ? 0 : intVal($val['position']));
  1084. $arrayofxaxis[$tablealias.'.'.$key] = array(
  1085. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']),
  1086. 'labelnohtml' => $labelofobject.': '.$langs->trans($val['label']),
  1087. 'position' => ($position + ($count * 100000)),
  1088. 'table' => $object->table_element,
  1089. 'tablefromt' => $tablepath
  1090. );
  1091. }
  1092. }
  1093. }
  1094. // Add extrafields to X-Axis
  1095. if (!empty($object->isextrafieldmanaged) && isset($extrafields->attributes[$object->table_element]['label'])) {
  1096. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
  1097. if ($extrafields->attributes[$object->table_element]['type'][$key] == 'separate') {
  1098. continue;
  1099. }
  1100. if (!empty($extrafields->attributes[$object->table_element]['totalizable'][$key])) {
  1101. continue;
  1102. }
  1103. if (in_array($extrafields->attributes[$object->table_element]['type'][$key], array('timestamp', 'date', 'datetime'))) {
  1104. $position = (empty($extrafields->attributes[$object->table_element]['pos'][$key]) ? 0 : intVal($extrafields->attributes[$object->table_element]['pos'][$key]));
  1105. $arrayofxaxis[preg_replace('/^t/', 'te', $tablealias).'.'.$key.'-year'] = array(
  1106. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val).' <span class="opacitymedium">('.$YYYY.')</span>',
  1107. 'labelnohtml' => $labelofobject.': '.$langs->trans($val),
  1108. 'position' => ($position + ($count * 100000)).'.1',
  1109. 'table' => $object->table_element,
  1110. 'tablefromt' => $tablepath
  1111. );
  1112. $arrayofxaxis[preg_replace('/^t/', 'te', $tablealias).'.'.$key.'-month'] = array(
  1113. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val).' <span class="opacitymedium">('.$YYYY.'-'.$MM.')</span>',
  1114. 'labelnohtml' => $labelofobject.': '.$langs->trans($val),
  1115. 'position' => ($position + ($count * 100000)).'.2',
  1116. 'table' => $object->table_element,
  1117. 'tablefromt' => $tablepath
  1118. );
  1119. $arrayofxaxis[preg_replace('/^t/', 'te', $tablealias).'.'.$key.'-day'] = array(
  1120. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val).' <span class="opacitymedium">('.$YYYY.'-'.$MM.'-'.$DD.')</span>',
  1121. 'labelnohtml' => $labelofobject.': '.$langs->trans($val),
  1122. 'position' => ($position + ($count * 100000)).'.3',
  1123. 'table' => $object->table_element,
  1124. 'tablefromt' => $tablepath
  1125. );
  1126. } else {
  1127. $arrayofxaxis[preg_replace('/^t/', 'te', $tablealias).'.'.$key] = array(
  1128. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val),
  1129. 'labelnohtml' => $labelofobject.': '.$langs->trans($val),
  1130. 'position' => 1000 + (int) $extrafields->attributes[$object->table_element]['pos'][$key] + ($count * 100000),
  1131. 'table' => $object->table_element,
  1132. 'tablefromt' => $tablepath
  1133. );
  1134. }
  1135. }
  1136. }
  1137. // Add fields for parent objects
  1138. foreach ($object->fields as $key => $val) {
  1139. if (preg_match('/^[^:]+:[^:]+:/', $val['type'])) {
  1140. $tmptype = explode(':', $val['type'], 4);
  1141. if ($tmptype[0] == 'integer' && $tmptype[1] && $tmptype[2]) {
  1142. $newobject = $tmptype[1];
  1143. dol_include_once($tmptype[2]);
  1144. if (class_exists($newobject)) {
  1145. $tmpobject = new $newobject($db);
  1146. //var_dump($key); var_dump($tmpobject->element); var_dump($val['label']); var_dump($tmptype); var_dump('t-'.$key);
  1147. $count++;
  1148. $arrayofxaxis = fillArrayOfXAxis($tmpobject, $tablealias.'__'.$key, $langs->trans($val['label']), $arrayofxaxis, $level + 1, $count, $tablepath);
  1149. } else {
  1150. print 'For property '.$object->element.'->'.$key.', type="'.$val['type'].'": Failed to find class '.$newobject." in file ".$tmptype[2]."<br>\n";
  1151. }
  1152. }
  1153. }
  1154. }
  1155. return $arrayofxaxis;
  1156. }
  1157. /**
  1158. * Fill arrayofgrupby for an object
  1159. *
  1160. * @param mixed $object Any object
  1161. * @param string $tablealias Alias of table
  1162. * @param string $labelofobject Label of object
  1163. * @param array $arrayofgroupby Array of groupby already filled
  1164. * @param int $level Level
  1165. * @param int $count Count
  1166. * @param string $tablepath Path of all tables ('t' or 't,contract' or 't,contract,societe'...)
  1167. * @return array Array of groupby
  1168. */
  1169. function fillArrayOfGroupBy($object, $tablealias, $labelofobject, &$arrayofgroupby, $level = 0, &$count = 0, &$tablepath = '')
  1170. {
  1171. global $langs, $extrafields, $db;
  1172. if ($level >= 3) {
  1173. return $arrayofgroupby;
  1174. }
  1175. if (empty($tablepath)) {
  1176. $tablepath = $object->table_element.'='.$tablealias;
  1177. } else {
  1178. $tablepath .= ','.$object->table_element.'='.$tablealias;
  1179. }
  1180. $YYYY = substr($langs->trans("Year"), 0, 1).substr($langs->trans("Year"), 0, 1).substr($langs->trans("Year"), 0, 1).substr($langs->trans("Year"), 0, 1);
  1181. $MM = substr($langs->trans("Month"), 0, 1).substr($langs->trans("Month"), 0, 1);
  1182. $DD = substr($langs->trans("Day"), 0, 1).substr($langs->trans("Day"), 0, 1);
  1183. $HH = substr($langs->trans("Hour"), 0, 1).substr($langs->trans("Hour"), 0, 1);
  1184. $MI = substr($langs->trans("Minute"), 0, 1).substr($langs->trans("Minute"), 0, 1);
  1185. $SS = substr($langs->trans("Second"), 0, 1).substr($langs->trans("Second"), 0, 1);
  1186. // Note: here $tablealias can be 't' or 't__fk_contract' or 't_fk_contract_fk_soc'
  1187. // Add main fields of object
  1188. foreach ($object->fields as $key => $val) {
  1189. if (empty($val['isameasure'])) {
  1190. if (in_array($key, array(
  1191. 'id', 'ref_ext', 'rowid', 'entity', 'last_main_doc', 'logo', 'logo_squarred', 'extraparams',
  1192. 'parent', 'photo', 'socialnetworks', 'webservices_url', 'webservices_key'))) {
  1193. continue;
  1194. }
  1195. if (isset($val['enabled']) && !dol_eval($val['enabled'], 1, 1, '1')) {
  1196. continue;
  1197. }
  1198. if (isset($val['visible']) && !dol_eval($val['visible'], 1, 1, '1')) {
  1199. continue;
  1200. }
  1201. if (preg_match('/^fk_/', $key) && !preg_match('/^fk_statu/', $key)) {
  1202. continue;
  1203. }
  1204. if (preg_match('/^pass/', $key)) {
  1205. continue;
  1206. }
  1207. if (in_array($val['type'], array('html', 'text'))) {
  1208. continue;
  1209. }
  1210. if (in_array($val['type'], array('timestamp', 'date', 'datetime'))) {
  1211. $position = (empty($val['position']) ? 0 : intVal($val['position']));
  1212. $arrayofgroupby[$tablealias.'.'.$key.'-year'] = array(
  1213. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']).' <span class="opacitymedium">('.$YYYY.')</span>',
  1214. 'labelnohtml' => $labelofobject.': '.$langs->trans($val['label']),
  1215. 'position' => ($position + ($count * 100000)).'.1',
  1216. 'table' => $object->table_element,
  1217. 'tablefromt' => $tablepath
  1218. );
  1219. $arrayofgroupby[$tablealias.'.'.$key.'-month'] = array(
  1220. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']).' <span class="opacitymedium">('.$YYYY.'-'.$MM.')</span>',
  1221. 'labelnohtml' => $labelofobject.': '.$langs->trans($val['label']),
  1222. 'position' => ($position + ($count * 100000)).'.2',
  1223. 'table' => $object->table_element,
  1224. 'tablefromt' => $tablepath
  1225. );
  1226. $arrayofgroupby[$tablealias.'.'.$key.'-day'] = array(
  1227. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']).' <span class="opacitymedium">('.$YYYY.'-'.$MM.'-'.$DD.')</span>',
  1228. 'labelnohtml' => $labelofobject.': '.$langs->trans($val['label']),
  1229. 'position' => ($position + ($count * 100000)).'.3',
  1230. 'table' => $object->table_element,
  1231. 'tablefromt' => $tablepath
  1232. );
  1233. } else {
  1234. $position = (empty($val['position']) ? 0 : intVal($val['position']));
  1235. $arrayofgroupby[$tablealias.'.'.$key] = array(
  1236. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']),
  1237. 'labelnohtml' => $labelofobject.': '.$langs->trans($val['label']),
  1238. 'position' => ($position + ($count * 100000)),
  1239. 'table' => $object->table_element,
  1240. 'tablefromt' => $tablepath
  1241. );
  1242. }
  1243. }
  1244. }
  1245. // Add extrafields to Group by
  1246. if (!empty($object->isextrafieldmanaged) && isset($extrafields->attributes[$object->table_element]['label'])) {
  1247. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
  1248. if ($extrafields->attributes[$object->table_element]['type'][$key] == 'separate') {
  1249. continue;
  1250. }
  1251. if (!empty($extrafields->attributes[$object->table_element]['totalizable'][$key])) {
  1252. continue;
  1253. }
  1254. if (in_array($extrafields->attributes[$object->table_element]['type'][$key], array('timestamp', 'date', 'datetime'))) {
  1255. $position = (empty($extrafields->attributes[$object->table_element]['pos'][$key]) ? 0 : intVal($extrafields->attributes[$object->table_element]['pos'][$key]));
  1256. $arrayofgroupby[preg_replace('/^t/', 'te', $tablealias).'.'.$key.'-year'] = array(
  1257. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val).' <span class="opacitymedium">('.$YYYY.')</span>',
  1258. 'labelnohtml' => $labelofobject.': '.$langs->trans($val),
  1259. 'position' => ($position + ($count * 100000)).'.1',
  1260. 'table' => $object->table_element,
  1261. 'tablefromt' => $tablepath
  1262. );
  1263. $arrayofgroupby[preg_replace('/^t/', 'te', $tablealias).'.'.$key.'-month'] = array(
  1264. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val).' <span class="opacitymedium">('.$YYYY.'-'.$MM.')</span>',
  1265. 'labelnohtml' => $labelofobject.': '.$langs->trans($val),
  1266. 'position' => ($position + ($count * 100000)).'.2',
  1267. 'table' => $object->table_element,
  1268. 'tablefromt' => $tablepath
  1269. );
  1270. $arrayofgroupby[preg_replace('/^t/', 'te', $tablealias).'.'.$key.'-day'] = array(
  1271. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val).' <span class="opacitymedium">('.$YYYY.'-'.$MM.'-'.$DD.')</span>',
  1272. 'labelnohtml' => $labelofobject.': '.$langs->trans($val),
  1273. 'position' => ($position + ($count * 100000)).'.3',
  1274. 'table' => $object->table_element,
  1275. 'tablefromt' => $tablepath
  1276. );
  1277. } else {
  1278. $arrayofgroupby[preg_replace('/^t/', 'te', $tablealias).'.'.$key] = array(
  1279. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val),
  1280. 'labelnohtml' => $labelofobject.': '.$langs->trans($val),
  1281. 'position' => 1000 + (int) $extrafields->attributes[$object->table_element]['pos'][$key] + ($count * 100000),
  1282. 'table' => $object->table_element,
  1283. 'tablefromt' => $tablepath
  1284. );
  1285. }
  1286. }
  1287. }
  1288. // Add fields for parent objects
  1289. foreach ($object->fields as $key => $val) {
  1290. if (preg_match('/^[^:]+:[^:]+:/', $val['type'])) {
  1291. $tmptype = explode(':', $val['type'], 4);
  1292. if ($tmptype[0] == 'integer' && $tmptype[1] && $tmptype[2]) {
  1293. $newobject = $tmptype[1];
  1294. dol_include_once($tmptype[2]);
  1295. if (class_exists($newobject)) {
  1296. $tmpobject = new $newobject($db);
  1297. //var_dump($key); var_dump($tmpobject->element); var_dump($val['label']); var_dump($tmptype); var_dump('t-'.$key);
  1298. $count++;
  1299. $arrayofgroupby = fillArrayOfGroupBy($tmpobject, $tablealias.'__'.$key, $langs->trans($val['label']), $arrayofgroupby, $level + 1, $count, $tablepath);
  1300. } else {
  1301. print 'For property '.$object->element.'->'.$key.', type="'.$val['type'].'": Failed to find class '.$newobject." in file ".$tmptype[2]."<br>\n";
  1302. }
  1303. }
  1304. }
  1305. }
  1306. return $arrayofgroupby;
  1307. }