customreports.php 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  1. <?php
  2. /* Copyright (C) 2020 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 <http://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('label' => 'ThirdParties', 'ObjectClassName' => 'Societe', 'enabled' => $conf->societe->enabled, 'ClassPath' => "/societe/class/societe.class.php"),
  82. 'contact' => array('label' => 'Contacts', 'ObjectClassName' => 'Contact', 'enabled' => $conf->societe->enabled, 'ClassPath' => "/contact/class/contact.class.php"),
  83. 'proposal' => array('label' => 'Proposals', 'ObjectClassName' => 'Propal', 'enabled' => $conf->propal->enabled, 'ClassPath' => "/comm/propal/class/propal.class.php"),
  84. 'order' => array('label' => 'Orders', 'ObjectClassName' => 'Commande', 'enabled' => $conf->commande->enabled, 'ClassPath' => "/commande/class/commande.class.php"),
  85. 'invoice' => array('label' => 'Invoices', 'ObjectClassName' => 'Facture', 'enabled' => $conf->facture->enabled, 'ClassPath' => "/compta/facture/class/facture.class.php"),
  86. 'invoice_template'=>array('label' => 'PredefinedInvoices', 'ObjectClassName' => 'FactureRec', 'enabled' => $conf->facture->enabled, 'ClassPath' => "/compta/class/facturerec.class.php", 'langs'=>'bills'),
  87. 'contract' => array('label' => 'Contracts', 'ObjectClassName' => 'Contrat', 'enabled' => $conf->contrat->enabled, 'ClassPath' => "/contrat/class/contrat.class.php", 'langs'=>'contracts'),
  88. 'contractdet' => array('label' => 'ContractLines', 'ObjectClassName' => 'ContratLigne', 'enabled' => $conf->contrat->enabled, 'ClassPath' => "/contrat/class/contrat.class.php", 'langs'=>'contracts'),
  89. 'bom' => array('label' => 'BOM', 'ObjectClassName' => 'Bom', 'enabled' => $conf->bom->enabled),
  90. 'mo' => array('label' => 'MO', 'ObjectClassName' => 'Mo', 'enabled' => $conf->mrp->enabled, 'ClassPath' => "/mrp/class/mo.class.php"),
  91. 'ticket' => array('label' => 'Ticket', 'ObjectClassName' => 'Ticket', 'enabled' => $conf->ticket->enabled),
  92. 'member' => array('label' => 'Adherent', 'ObjectClassName' => 'Adherent', 'enabled' => $conf->adherent->enabled, 'ClassPath' => "/adherents/class/adherent.class.php", 'langs'=>'members'),
  93. 'cotisation' => array('label' => 'Subscriptions', 'ObjectClassName' => 'Subscription', 'enabled' => $conf->adherent->enabled, '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($object->table_element);
  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 ($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. $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element."_extrafields as te";
  235. } else {
  236. $tabletouse = $object->table_element;
  237. $tablealiastouse = 't';
  238. if (!empty($arrayofgroupby[$gval])) {
  239. $tmpval = explode('.', $gval);
  240. $tabletouse = $arrayofgroupby[$gval]['table'];
  241. $tablealiastouse = $tmpval[0];
  242. }
  243. $sql .= " FROM ".MAIN_DB_PREFIX.$tabletouse." as ".$tablealiastouse;
  244. }
  245. // Add the where here
  246. /*
  247. $sqlfilters = GETPOST('search_component_params_hidden', 'alphanohtml');
  248. if ($sqlfilters) {
  249. $errormessage = '';
  250. if (dolCheckFilters($sqlfilters, $errormessage)) {
  251. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  252. $sql .= " WHERE (".preg_replace_callback('/'.$regexstring.'/', 'dolForgeCriteriaCallback', $sqlfilters).")";
  253. } else {
  254. print $errormessage;
  255. }
  256. }*/
  257. $sql .= " LIMIT ".((int) ($MAXUNIQUEVALFORGROUP + 1));
  258. //print $sql;
  259. $resql = $db->query($sql);
  260. if (!$resql) {
  261. dol_print_error($db);
  262. }
  263. while ($obj = $db->fetch_object($resql)) {
  264. if (is_null($obj->val)) {
  265. $keytouse = '__NULL__';
  266. $valuetranslated = $langs->transnoentitiesnoconv("NotDefined");
  267. } elseif ($obj->val === '') {
  268. $keytouse = '';
  269. $valuetranslated = $langs->transnoentitiesnoconv("Empty");
  270. } else {
  271. $keytouse = (string) $obj->val;
  272. $valuetranslated = $obj->val;
  273. }
  274. $regs = array();
  275. if (!empty($object->fields[$gvalwithoutprefix]['arrayofkeyval'])) {
  276. $valuetranslated = $object->fields[$gvalwithoutprefix]['arrayofkeyval'][$obj->val];
  277. if (is_null($valuetranslated)) {
  278. $valuetranslated = $langs->transnoentitiesnoconv("UndefinedKey");
  279. }
  280. $valuetranslated = $langs->trans($valuetranslated);
  281. } elseif (preg_match('/integer:([^:]+):([^:]+)$/', $object->fields[$gvalwithoutprefix]['type'], $regs)) {
  282. $classname = $regs[1];
  283. $classpath = $regs[2];
  284. dol_include_once($classpath);
  285. if (class_exists($classname)) {
  286. $tmpobject = new $classname($db);
  287. $tmpobject->fetch($obj->val);
  288. foreach ($tmpobject->fields as $fieldkey => $field) {
  289. if ($field['showoncombobox']) {
  290. $valuetranslated = $tmpobject->$fieldkey;
  291. //if ($valuetranslated == '-') $valuetranslated = $langs->transnoentitiesnoconv("Unknown")
  292. break;
  293. }
  294. }
  295. //$valuetranslated = $tmpobject->ref.'eee';
  296. }
  297. }
  298. $arrayofvaluesforgroupby['g_'.$gkey][$keytouse] = $valuetranslated;
  299. }
  300. // Add also the possible NULL value if field is a parent field that is not a strict join
  301. $tmpfield = explode('.', $gval);
  302. if ($tmpfield[0] != 't' || (is_array($object->fields[$tmpfield[1]]) && empty($object->fields[$tmpfield[1]]['notnull']))) {
  303. 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");
  304. //var_dump($gval); var_dump($object->fields);
  305. $arrayofvaluesforgroupby['g_'.$gkey]['__NULL__'] = $langs->transnoentitiesnoconv("NotDefined");
  306. }
  307. asort($arrayofvaluesforgroupby['g_'.$gkey]);
  308. // Add a protection/error to refuse the request if number of differentr values for the group by is higher than $MAXUNIQUEVALFORGROUP
  309. if (count($arrayofvaluesforgroupby['g_'.$gkey]) > $MAXUNIQUEVALFORGROUP) {
  310. $langs->load("errors");
  311. if (strpos($fieldtocount, 'te.') === 0) {
  312. //if (!empty($extrafields->attributes[$object->table_element]['langfile'][$gvalwithoutprefix])) {
  313. // $langs->load($extrafields->attributes[$object->table_element]['langfile'][$gvalwithoutprefix]);
  314. //}
  315. $keyforlabeloffield = $extrafields->attributes[$object->table_element]['label'][$gvalwithoutprefix];
  316. } else {
  317. $keyforlabeloffield = $object->fields[$gvalwithoutprefix]['label'];
  318. }
  319. //var_dump($gkey.' '.$gval.' '.$gvalwithoutprefix);
  320. $gvalwithoutprefix = preg_replace('/\-(year|month|day)/', '', $gvalwithoutprefix);
  321. $labeloffield = $langs->transnoentitiesnoconv($keyforlabeloffield);
  322. setEventMessages($langs->trans("ErrorTooManyDifferentValueForSelectedGroupBy", $MAXUNIQUEVALFORGROUP, $labeloffield), null, 'warnings');
  323. $search_groupby = array();
  324. }
  325. $db->free($resql);
  326. }
  327. }
  328. //var_dump($arrayofvaluesforgroupby);exit;
  329. $tmparray = dol_getdate(dol_now());
  330. $endyear = $tmparray['year'];
  331. $endmonth = $tmparray['mon'];
  332. $datelastday = dol_get_last_day($endyear, $endmonth, 1);
  333. $startyear = $endyear - 2;
  334. $param = '';
  335. print '<form method="post" action="'.$_SERVER['PHP_SELF'].'">';
  336. print '<input type="hidden" name="token" value="'.newToken().'">';
  337. print '<input type="hidden" name="action" value="viewgraph">';
  338. print '<input type="hidden" name="tabfamily" value="'.$tabfamily.'">';
  339. $viewmode = '';
  340. $viewmode .= '<div class="divadvancedsearchfield">';
  341. $arrayofgraphs = array('bars' => 'Bars', 'lines' => 'Lines'); // also 'pies'
  342. $viewmode .= '<div class="inline-block opacitymedium"><span class="fas fa-chart-area paddingright" title="'.$langs->trans("Graph").'"></span>'.$langs->trans("Graph").'</div> ';
  343. $viewmode .= $form->selectarray('search_graph', $arrayofgraphs, $search_graph, 0, 0, 0, 'minwidth100', 1);
  344. $viewmode .= '</div>';
  345. $num = 0;
  346. $massactionbutton = '';
  347. $nav = '';
  348. $newcardbutton = '';
  349. $limit = 0;
  350. 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);
  351. print '<div class="liste_titre liste_titre_bydiv centpercent">';
  352. // Select object
  353. print '<div class="divadvancedsearchfield center floatnone">';
  354. print '<div class="inline-block"><span class="opacitymedium">'.$langs->trans("StatisticsOn").'</span></div> ';
  355. print $form->selectarray('objecttype', $newarrayoftype, $objecttype, 0, 0, 0, '', 1, 0, 0, '', 'minwidth200', 1);
  356. if (empty($conf->use_javascript_ajax)) {
  357. print '<input type="submit" class="button buttongen button-save nomargintop" name="changeobjecttype" value="'.$langs->trans("Refresh").'">';
  358. } else {
  359. print '<!-- js code to reload page with good object type -->
  360. <script type="text/javascript">
  361. jQuery(document).ready(function() {
  362. jQuery("#objecttype").change(function() {
  363. console.log("Reload for "+jQuery("#objecttype").val());
  364. 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')) : '').'";
  365. });
  366. });
  367. </script>';
  368. }
  369. print '</div><div class="clearboth"></div>';
  370. // Add Filter (you can use param &show_search_component_params_hidden=1 for debug)
  371. print '<div class="divadvancedsearchfield quatrevingtpercent">';
  372. print $form->searchComponent(array($object->element => $object->fields), $search_component_params, array(), $search_component_params_hidden);
  373. print '</div>';
  374. // Add measures into array
  375. $count = 0;
  376. //var_dump($arrayofmesures);
  377. print '<div class="divadvancedsearchfield clearboth">';
  378. 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>';
  379. $simplearrayofmesures = array();
  380. foreach ($arrayofmesures as $key => $val) {
  381. $simplearrayofmesures[$key] = $arrayofmesures[$key]['label'];
  382. }
  383. print $form->multiselectarray('search_measures', $simplearrayofmesures, $search_measures, 0, 0, 'minwidth400', 1, 0, '', '', $langs->trans("Measures")); // Fill the array $arrayofmeasures with possible fields
  384. print '</div>';
  385. // XAxis
  386. $count = 0;
  387. print '<div class="divadvancedsearchfield">';
  388. 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>';
  389. //var_dump($arrayofxaxis);
  390. print $formother->selectXAxisField($object, $search_xaxis, $arrayofxaxis, $langs->trans("XAxis")); // Fill the array $arrayofxaxis with possible fields
  391. print '</div>';
  392. // Group by
  393. $count = 0;
  394. print '<div class="divadvancedsearchfield">';
  395. print '<div class="inline-block opacitymedium"><span class="fas fa-ruler-horizontal paddingright pictofixedwidth" title="'.dol_escape_htmltag($langs->trans("GroupBy")).'"></span></div>';
  396. print $formother->selectGroupByField($object, $search_groupby, $arrayofgroupby, 'minwidth200 maxwidth250', $langs->trans("GroupBy")); // Fill the array $arrayofgroupby with possible fields
  397. print '</div>';
  398. if ($mode == 'grid') {
  399. // YAxis
  400. print '<div class="divadvancedsearchfield">';
  401. foreach ($object->fields as $key => $val) {
  402. if (empty($val['measure']) && (!isset($val['enabled']) || dol_eval($val['enabled'], 1, 1, '1'))) {
  403. if (in_array($key, array('id', 'rowid', 'entity', 'last_main_doc', 'extraparams'))) {
  404. continue;
  405. }
  406. if (preg_match('/^fk_/', $key)) {
  407. continue;
  408. }
  409. if (in_array($val['type'], array('html', 'text'))) {
  410. continue;
  411. }
  412. if (in_array($val['type'], array('timestamp', 'date', 'datetime'))) {
  413. $arrayofyaxis['t.'.$key.'-year'] = array(
  414. 'label' => $langs->trans($val['label']).' ('.$YYYY.')',
  415. 'position' => $val['position'],
  416. 'table' => $object->table_element
  417. );
  418. $arrayofyaxis['t.'.$key.'-month'] = array(
  419. 'label' => $langs->trans($val['label']).' ('.$YYYY.'-'.$MM.')',
  420. 'position' => $val['position'],
  421. 'table' => $object->table_element
  422. );
  423. $arrayofyaxis['t.'.$key.'-day'] = array(
  424. 'label' => $langs->trans($val['label']).' ('.$YYYY.'-'.$MM.'-'.$DD.')',
  425. 'position' => $val['position'],
  426. 'table' => $object->table_element
  427. );
  428. } else {
  429. $arrayofyaxis['t.'.$key] = array(
  430. 'label' => $val['label'],
  431. 'position' => (int) $val['position'],
  432. 'table' => $object->table_element
  433. );
  434. }
  435. }
  436. // Add measure from extrafields
  437. if ($object->isextrafieldmanaged) {
  438. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
  439. 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'))) {
  440. $arrayofyaxis['te.'.$key] = array(
  441. 'label' => $extrafields->attributes[$object->table_element]['label'][$key],
  442. 'position' => (int) $extrafields->attributes[$object->table_element]['pos'][$key],
  443. 'table' => $object->table_element
  444. );
  445. }
  446. }
  447. }
  448. }
  449. $arrayofyaxis = dol_sort_array($arrayofyaxis, 'position');
  450. $arrayofyaxislabel = array();
  451. foreach ($arrayofyaxis as $key => $val) {
  452. $arrayofyaxislabel[$key] = $val['label'];
  453. }
  454. print '<div class="inline-block opacitymedium"><span class="fas fa-ruler-vertical paddingright" title="'.$langs->trans("YAxis").'"></span>'.$langs->trans("YAxis").'</div> ';
  455. print $form->multiselectarray('search_yaxis', $arrayofyaxislabel, $search_yaxis, 0, 0, 'minwidth100', 1);
  456. print '</div>';
  457. }
  458. if ($mode == 'graph') {
  459. //
  460. }
  461. print '<div class="divadvancedsearchfield">';
  462. print '<input type="submit" class="button buttongen button-save nomargintop" value="'.$langs->trans("Refresh").'">';
  463. print '</div>';
  464. print '</div>';
  465. print '</form>';
  466. // Generate the SQL request
  467. $sql = '';
  468. if (!empty($search_measures) && !empty($search_xaxis)) {
  469. $fieldid = 'rowid';
  470. $sql = "SELECT ";
  471. foreach ($search_xaxis as $key => $val) {
  472. if (preg_match('/\-year$/', $val)) {
  473. $tmpval = preg_replace('/\-year$/', '', $val);
  474. $sql .= "DATE_FORMAT(".$tmpval.", '%Y') as x_".$key.', ';
  475. } elseif (preg_match('/\-month$/', $val)) {
  476. $tmpval = preg_replace('/\-month$/', '', $val);
  477. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m') as x_".$key.', ';
  478. } elseif (preg_match('/\-day$/', $val)) {
  479. $tmpval = preg_replace('/\-day$/', '', $val);
  480. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m-%d') as x_".$key.', ';
  481. } else {
  482. $sql .= $val." as x_".$key.", ";
  483. }
  484. }
  485. foreach ($search_groupby as $key => $val) {
  486. if (preg_match('/\-year$/', $val)) {
  487. $tmpval = preg_replace('/\-year$/', '', $val);
  488. $sql .= "DATE_FORMAT(".$tmpval.", '%Y') as g_".$key.', ';
  489. } elseif (preg_match('/\-month$/', $val)) {
  490. $tmpval = preg_replace('/\-month$/', '', $val);
  491. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m') as g_".$key.', ';
  492. } elseif (preg_match('/\-day$/', $val)) {
  493. $tmpval = preg_replace('/\-day$/', '', $val);
  494. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m-%d') as g_".$key.', ';
  495. } else {
  496. $sql .= $val." as g_".$key.", ";
  497. }
  498. }
  499. foreach ($search_measures as $key => $val) {
  500. if ($val == 't.count') {
  501. $sql .= "COUNT(t.".$fieldid.") as y_".$key.', ';
  502. } elseif (preg_match('/\-sum$/', $val)) {
  503. $tmpval = preg_replace('/\-sum$/', '', $val);
  504. $sql .= "SUM(".$db->ifsql($tmpval.' IS NULL', '0', $tmpval).") as y_".$key.", ";
  505. } elseif (preg_match('/\-average$/', $val)) {
  506. $tmpval = preg_replace('/\-average$/', '', $val);
  507. $sql .= "AVG(".$db->ifsql($tmpval.' IS NULL', '0', $tmpval).") as y_".$key.", ";
  508. } elseif (preg_match('/\-min$/', $val)) {
  509. $tmpval = preg_replace('/\-min$/', '', $val);
  510. $sql .= "MIN(".$db->ifsql($tmpval.' IS NULL', '0', $tmpval).") as y_".$key.", ";
  511. } elseif (preg_match('/\-max$/', $val)) {
  512. $tmpval = preg_replace('/\-max$/', '', $val);
  513. $sql .= "MAX(".$db->ifsql($tmpval.' IS NULL', '0', $tmpval).") as y_".$key.", ";
  514. }
  515. }
  516. $sql = preg_replace('/,\s*$/', '', $sql);
  517. $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t";
  518. // Add measure from extrafields
  519. if ($object->isextrafieldmanaged) {
  520. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as te ON te.fk_object = t.".$fieldid;
  521. }
  522. // Add table for link for multientity
  523. if ($object->ismultientitymanaged) { // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  524. if ($object->ismultientitymanaged == 1) {
  525. // No table to add here
  526. } else {
  527. $tmparray = explode('@', $object->ismultientitymanaged);
  528. $sql .= " INNER JOIN ".MAIN_DB_PREFIX.$tmparray[1]." as parenttableforentity ON t.".$tmparray[0]." = parenttableforentity.rowid";
  529. $sql .= " AND parenttableforentity.entity IN (".getEntity($tmparray[1]).")";
  530. }
  531. }
  532. $listoftablesalreadyadded = array($object->table_element => $object->table_element);
  533. // Add LEFT JOIN for all parent tables mentionned into the Xaxis
  534. //var_dump($arrayofxaxis); var_dump($search_xaxis);
  535. foreach ($search_xaxis as $key => $val) {
  536. if (!empty($arrayofxaxis[$val])) {
  537. $tmpval = explode('.', $val);
  538. //var_dump($arrayofxaxis[$val]['table']);
  539. if (! in_array($arrayofxaxis[$val]['table'], $listoftablesalreadyadded)) { // We do not add join for main table already added
  540. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$arrayofxaxis[$val]['table']." as ".$db->sanitize($tmpval[0])." ON t.".str_replace('t__', '', $db->sanitize($tmpval[0]))." = ".$db->sanitize($tmpval[0]).".rowid";
  541. $listoftablesalreadyadded[$arrayofxaxis[$val]['table']] = $arrayofxaxis[$val]['table'];
  542. }
  543. } else {
  544. dol_print_error($db, 'Found a key into search_xaxis not found into arrayofxaxis');
  545. }
  546. }
  547. // Add LEFT JOIN for all parent tables mentionned into the Group by
  548. //var_dump($arrayofgroupby); var_dump($search_groupby);
  549. foreach ($search_groupby as $key => $val) {
  550. if (!empty($arrayofgroupby[$val])) {
  551. $tmpval = explode('.', $val);
  552. //var_dump($arrayofxaxis[$val]['table']);
  553. if (! in_array($arrayofgroupby[$val]['table'], $listoftablesalreadyadded)) { // We do not add join for main table already added
  554. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$arrayofgroupby[$val]['table']." as ".$tmpval[0]." ON t.".str_replace('t__', '', $tmpval[0])." = ".$tmpval[0].".rowid";
  555. $listoftablesalreadyadded[$arrayofgroupby[$val]['table']] = $arrayofgroupby[$val]['table'];
  556. }
  557. } else {
  558. dol_print_error($db, 'Found a key into search_groupby not found into arrayofgroupby');
  559. }
  560. }
  561. // Add LEFT JOIN for all parent tables mentionned into the Yaxis
  562. //var_dump($arrayofgroupby); var_dump($search_groupby);
  563. foreach ($search_measures as $key => $val) {
  564. if (!empty($arrayofmesures[$val])) {
  565. $tmpval = explode('.', $val);
  566. //var_dump($arrayofxaxis[$val]['table']);
  567. if (! in_array($arrayofmesures[$val]['table'], $listoftablesalreadyadded)) { // We do not add join for main table already added
  568. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$arrayofmesures[$val]['table']." as ".$tmpval[0]." ON t.".str_replace('t__', '', $tmpval[0])." = ".$tmpval[0].".rowid";
  569. $listoftablesalreadyadded[$arrayofmesures[$val]['table']] = $arrayofmesures[$val]['table'];
  570. }
  571. } else {
  572. dol_print_error($db, 'Found a key into search_measures not found into arrayofmesures');
  573. }
  574. }
  575. $sql .= " WHERE 1 = 1";
  576. if ($object->ismultientitymanaged == 1) { // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  577. $sql .= " AND t.entity IN (".getEntity($object->element).")";
  578. }
  579. // Add the where here
  580. $sqlfilters = $search_component_params_hidden;
  581. if ($sqlfilters) {
  582. $errormessage = '';
  583. if (dolCheckFilters($sqlfilters, $errormessage)) {
  584. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  585. $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'dolForgeCriteriaCallback', $sqlfilters).")";
  586. } else {
  587. print $errormessage;
  588. }
  589. }
  590. $sql .= " GROUP BY ";
  591. foreach ($search_xaxis as $key => $val) {
  592. if (preg_match('/\-year$/', $val)) {
  593. $tmpval = preg_replace('/\-year$/', '', $val);
  594. $sql .= "DATE_FORMAT(".$tmpval.", '%Y'), ";
  595. } elseif (preg_match('/\-month$/', $val)) {
  596. $tmpval = preg_replace('/\-month$/', '', $val);
  597. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m'), ";
  598. } elseif (preg_match('/\-day$/', $val)) {
  599. $tmpval = preg_replace('/\-day$/', '', $val);
  600. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m-%d'), ";
  601. } else {
  602. $sql .= $val.", ";
  603. }
  604. }
  605. foreach ($search_groupby as $key => $val) {
  606. if (preg_match('/\-year$/', $val)) {
  607. $tmpval = preg_replace('/\-year$/', '', $val);
  608. $sql .= "DATE_FORMAT(".$tmpval.", '%Y'), ";
  609. } elseif (preg_match('/\-month$/', $val)) {
  610. $tmpval = preg_replace('/\-month$/', '', $val);
  611. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m'), ";
  612. } elseif (preg_match('/\-day$/', $val)) {
  613. $tmpval = preg_replace('/\-day$/', '', $val);
  614. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m-%d'), ";
  615. } else {
  616. $sql .= $val.', ';
  617. }
  618. }
  619. $sql = preg_replace('/,\s*$/', '', $sql);
  620. $sql .= ' ORDER BY ';
  621. foreach ($search_xaxis as $key => $val) {
  622. if (preg_match('/\-year$/', $val)) {
  623. $tmpval = preg_replace('/\-year$/', '', $val);
  624. $sql .= "DATE_FORMAT(".$tmpval.", '%Y'), ";
  625. } elseif (preg_match('/\-month$/', $val)) {
  626. $tmpval = preg_replace('/\-month$/', '', $val);
  627. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m'), ";
  628. } elseif (preg_match('/\-day$/', $val)) {
  629. $tmpval = preg_replace('/\-day$/', '', $val);
  630. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m-%d'), ";
  631. } else {
  632. $sql .= $val.', ';
  633. }
  634. }
  635. foreach ($search_groupby as $key => $val) {
  636. if (preg_match('/\-year$/', $val)) {
  637. $tmpval = preg_replace('/\-year$/', '', $val);
  638. $sql .= "DATE_FORMAT(".$tmpval.", '%Y'), ";
  639. } elseif (preg_match('/\-month$/', $val)) {
  640. $tmpval = preg_replace('/\-month$/', '', $val);
  641. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m'), ";
  642. } elseif (preg_match('/\-day$/', $val)) {
  643. $tmpval = preg_replace('/\-day$/', '', $val);
  644. $sql .= "DATE_FORMAT(".$tmpval.", '%Y-%m-%d'), ";
  645. } else {
  646. $sql .= $val.', ';
  647. }
  648. }
  649. $sql = preg_replace('/,\s*$/', '', $sql);
  650. }
  651. //print $sql;
  652. $legend = array();
  653. foreach ($search_measures as $key => $val) {
  654. $legend[] = $langs->trans($arrayofmesures[$val]['label']);
  655. }
  656. $useagroupby = (is_array($search_groupby) && count($search_groupby));
  657. //var_dump($useagroupby);
  658. //var_dump($arrayofvaluesforgroupby);
  659. // Execute the SQL request
  660. $totalnbofrecord = 0;
  661. $data = array();
  662. if ($sql) {
  663. $resql = $db->query($sql);
  664. if (!$resql) {
  665. dol_print_error($db);
  666. }
  667. $ifetch = 0;
  668. $xi = 0;
  669. $oldlabeltouse = '';
  670. while ($obj = $db->fetch_object($resql)) {
  671. $ifetch++;
  672. if ($useagroupby) {
  673. $xval = $search_xaxis[0];
  674. $fieldforxkey = 'x_0';
  675. $xlabel = $obj->$fieldforxkey;
  676. $xvalwithoutprefix = preg_replace('/^[a-z]+\./', '', $xval);
  677. // Define $xlabel
  678. if (!empty($object->fields[$xvalwithoutprefix]['arrayofkeyval'])) {
  679. $xlabel = $object->fields[$xvalwithoutprefix]['arrayofkeyval'][$obj->$fieldforxkey];
  680. }
  681. $labeltouse = (($xlabel || $xlabel == '0') ? dol_trunc($xlabel, 20, 'middle') : ($xlabel === '' ? $langs->transnoentitiesnoconv("Empty") : $langs->transnoentitiesnoconv("NotDefined")));
  682. if ($oldlabeltouse && ($labeltouse != $oldlabeltouse)) {
  683. $xi++; // Increase $xi
  684. }
  685. //var_dump($labeltouse.' '.$oldlabeltouse.' '.$xi);
  686. $oldlabeltouse = $labeltouse;
  687. /* Example of value for $arrayofvaluesforgroupby
  688. * array (size=1)
  689. * 'g_0' =>
  690. * array (size=6)
  691. * 0 => string '0' (length=1)
  692. * '' => string 'Empty' (length=5)
  693. * '__NULL__' => string 'Not defined' (length=11)
  694. * 'done' => string 'done' (length=4)
  695. * 'processing' => string 'processing' (length=10)
  696. * 'undeployed' => string 'undeployed' (length=10)
  697. */
  698. foreach ($search_measures as $key => $val) {
  699. $gi = 0;
  700. foreach ($search_groupby as $gkey) {
  701. //var_dump('*** Fetch #'.$ifetch.' for labeltouse='.$labeltouse.' measure number '.$key.' and group g_'.$gi);
  702. //var_dump($arrayofvaluesforgroupby);
  703. foreach ($arrayofvaluesforgroupby['g_'.$gi] as $gvaluepossiblekey => $gvaluepossiblelabel) {
  704. $ykeysuffix = $gvaluepossiblelabel;
  705. $gvalwithoutprefix = preg_replace('/^[a-z]+\./', '', $gval);
  706. $fieldfory = 'y_'.$key;
  707. $fieldforg = 'g_'.$gi;
  708. $fieldforybis = 'y_'.$key.'_'.$ykeysuffix;
  709. //var_dump('gvaluepossiblekey='.$gvaluepossiblekey.' gvaluepossiblelabel='.$gvaluepossiblelabel.' ykeysuffix='.$ykeysuffix.' gval='.$gval.' gvalwithoutsuffix='.$gvalwithoutprefix);
  710. //var_dump('fieldforg='.$fieldforg.' obj->$fieldforg='.$obj->$fieldforg.' fieldfory='.$fieldfory.' obj->$fieldfory='.$obj->$fieldfory.' fieldforybis='.$fieldforybis);
  711. if (!is_array($data[$xi])) {
  712. $data[$xi] = array();
  713. }
  714. if (!array_key_exists('label', $data[$xi])) {
  715. $data[$xi] = array();
  716. $data[$xi]['label'] = $labeltouse;
  717. }
  718. $objfieldforg = $obj->$fieldforg;
  719. if (is_null($objfieldforg)) {
  720. $objfieldforg = '__NULL__';
  721. }
  722. if ($gvaluepossiblekey == '0') { // $gvaluepossiblekey can have type int or string. So we create a special if, used when value is '0'
  723. //var_dump($objfieldforg.' == \'0\' -> '.($objfieldforg == '0'));
  724. if ($objfieldforg == '0') {
  725. // The record we fetch is for this group
  726. $data[$xi][$fieldforybis] = $obj->$fieldfory;
  727. } elseif (!isset($data[$xi][$fieldforybis])) {
  728. // The record we fetch is not for this group
  729. $data[$xi][$fieldforybis] = '0';
  730. }
  731. } else {
  732. //var_dump((string) $objfieldforg.' === '.(string) $gvaluepossiblekey.' -> '.((string) $objfieldforg === (string) $gvaluepossiblekey));
  733. if ((string) $objfieldforg === (string) $gvaluepossiblekey) {
  734. // The record we fetch is for this group
  735. $data[$xi][$fieldforybis] = $obj->$fieldfory;
  736. } elseif (!isset($data[$xi][$fieldforybis])) {
  737. // The record we fetch is not for this group
  738. $data[$xi][$fieldforybis] = '0';
  739. }
  740. }
  741. }
  742. //var_dump($data[$xi]);
  743. $gi++;
  744. }
  745. }
  746. } else { // No group by
  747. $xval = $search_xaxis[0];
  748. $fieldforxkey = 'x_0';
  749. $xlabel = $obj->$fieldforxkey;
  750. $xvalwithoutprefix = preg_replace('/^[a-z]+\./', '', $xval);
  751. // Define $xlabel
  752. if (!empty($object->fields[$xvalwithoutprefix]['arrayofkeyval'])) {
  753. $xlabel = $object->fields[$xvalwithoutprefix]['arrayofkeyval'][$obj->$fieldforxkey];
  754. }
  755. $labeltouse = (($xlabel || $xlabel == '0') ? dol_trunc($xlabel, 20, 'middle') : ($xlabel === '' ? $langs->trans("Empty") : $langs->trans("NotDefined")));
  756. $xarrayforallseries = array('label' => $labeltouse);
  757. foreach ($search_measures as $key => $val) {
  758. $fieldfory = 'y_'.$key;
  759. $xarrayforallseries[$fieldfory] = $obj->$fieldfory;
  760. }
  761. $data[$xi] = $xarrayforallseries;
  762. $xi++;
  763. }
  764. }
  765. $totalnbofrecord = count($data);
  766. }
  767. //var_dump($data);
  768. print '<div class="customreportsoutput'.($totalnbofrecord ? '' : ' customreportsoutputnotdata').'">';
  769. if ($mode == 'grid') {
  770. // TODO
  771. }
  772. if ($mode == 'graph') {
  773. $WIDTH = '80%';
  774. $HEIGHT = 200;
  775. // Show graph
  776. $px1 = new DolGraph();
  777. $mesg = $px1->isGraphKo();
  778. if (!$mesg) {
  779. //var_dump($legend);
  780. //var_dump($data);
  781. $px1->SetData($data);
  782. unset($data);
  783. $arrayoftypes = array();
  784. foreach ($search_measures as $key => $val) {
  785. $arrayoftypes[] = $search_graph;
  786. }
  787. $px1->SetLegend($legend);
  788. $px1->SetMinValue($px1->GetFloorMinValue());
  789. $px1->SetMaxValue($px1->GetCeilMaxValue());
  790. $px1->SetWidth($WIDTH);
  791. $px1->SetHeight($HEIGHT);
  792. $px1->SetYLabel($langs->trans("Y"));
  793. $px1->SetShading(3);
  794. $px1->SetHorizTickIncrement(1);
  795. $px1->SetCssPrefix("cssboxes");
  796. $px1->SetType($arrayoftypes);
  797. $px1->mode = 'depth';
  798. $px1->SetTitle('');
  799. $dir = $conf->user->dir_temp;
  800. dol_mkdir($dir);
  801. $filenamenb = $dir.'/customreport_'.$object->element.'.png';
  802. $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=user&file=customreport_'.$object->element.'.png';
  803. $px1->draw($filenamenb, $fileurlnb);
  804. $texttoshow = $langs->trans("NoRecordFound");
  805. if (!GETPOSTISSET('search_measures') || !GETPOSTISSET('search_xaxis')) {
  806. $texttoshow = $langs->trans("SelectYourGraphOptionsFirst");
  807. }
  808. print $px1->show($totalnbofrecord ? 0 : $texttoshow);
  809. }
  810. }
  811. if ($sql) {
  812. // Show admin info
  813. print '<br>'.info_admin($langs->trans("SQLUsedForExport").':<br> '.$sql, 0, 0, 1, '', 'TechnicalInformation');
  814. }
  815. print '<div>';
  816. if (!defined('USE_CUSTOM_REPORT_AS_INCLUDE')) {
  817. print dol_get_fiche_end();
  818. }
  819. // End of page
  820. llxFooter();
  821. $db->close();
  822. /**
  823. * Fill arrayofmesures for an object
  824. *
  825. * @param mixed $object Any object
  826. * @param string $tablealias Alias of table
  827. * @param string $labelofobject Label of object
  828. * @param array $arrayofmesures Array of mesures already filled
  829. * @param int $level Level
  830. * @param int $count Count
  831. * @return array Array of mesures
  832. */
  833. function fillArrayOfMeasures($object, $tablealias, $labelofobject, &$arrayofmesures, $level = 0, &$count = 0)
  834. {
  835. global $langs, $extrafields, $db;
  836. if ($level > 10) { // Protection against infinite loop
  837. return $arrayofmesures;
  838. }
  839. if ($level == 0) {
  840. // Add the count of record only for the main/first level object. Parents are necessarly unique for each record.
  841. $arrayofmesures[$tablealias.'.count'] = array(
  842. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': Count',
  843. 'position' => 0,
  844. 'table' => $object->table_element
  845. );
  846. }
  847. // Add main fields of object
  848. foreach ($object->fields as $key => $val) {
  849. if (!empty($val['isameasure']) && (!isset($val['enabled']) || dol_eval($val['enabled'], 1, 1, '1'))) {
  850. $position = (!empty($val['position']) ? $val['position'] : 0);
  851. $arrayofmesures[$tablealias.'.'.$key.'-sum'] = array(
  852. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']).' <span class="opacitymedium">('.$langs->trans("Sum").')</span>',
  853. 'position' => ($position+($count * 100000)).'.1',
  854. 'table' => $object->table_element
  855. );
  856. $arrayofmesures[$tablealias.'.'.$key.'-average'] = array(
  857. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']).' <span class="opacitymedium">('.$langs->trans("Average").')</span>',
  858. 'position' => ($position+($count * 100000)).'.2',
  859. 'table' => $object->table_element
  860. );
  861. $arrayofmesures[$tablealias.'.'.$key.'-min'] = array(
  862. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']).' <span class="opacitymedium">('.$langs->trans("Minimum").')</span>',
  863. 'position' => ($position+($count * 100000)).'.3',
  864. 'table' => $object->table_element
  865. );
  866. $arrayofmesures[$tablealias.'.'.$key.'-max'] = array(
  867. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']).' <span class="opacitymedium">('.$langs->trans("Maximum").')</span>',
  868. 'position' => ($position+($count * 100000)).'.4',
  869. 'table' => $object->table_element
  870. );
  871. }
  872. }
  873. // Add extrafields to Measures
  874. if ($object->isextrafieldmanaged) {
  875. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
  876. 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'))) {
  877. $position = (!empty($val['position']) ? $val['position'] : 0);
  878. $arrayofmesures[$tablealias.'e.'.$key.'-sum'] = array(
  879. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($extrafields->attributes[$object->table_element]['label'][$key]).' <span class="opacitymedium">('.$langs->trans("Sum").')</span>',
  880. 'position' => ($position+($count * 100000)).'.1',
  881. 'table' => $object->table_element
  882. );
  883. $arrayofmesures[$tablealias.'e.'.$key.'-average'] = array(
  884. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($extrafields->attributes[$object->table_element]['label'][$key]).' <span class="opacitymedium">('.$langs->trans("Average").')</span>',
  885. 'position' => ($position+($count * 100000)).'.2',
  886. 'table' => $object->table_element
  887. );
  888. $arrayofmesures[$tablealias.'e.'.$key.'-min'] = array(
  889. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($extrafields->attributes[$object->table_element]['label'][$key]).' <span class="opacitymedium">('.$langs->trans("Minimum").')</span>',
  890. 'position' => ($position+($count * 100000)).'.3',
  891. 'table' => $object->table_element
  892. );
  893. $arrayofmesures[$tablealias.'e.'.$key.'-max'] = array(
  894. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($extrafields->attributes[$object->table_element]['label'][$key]).' <span class="opacitymedium">('.$langs->trans("Maximum").')</span>',
  895. 'position' => ($position+($count * 100000)).'.4',
  896. 'table' => $object->table_element
  897. );
  898. }
  899. }
  900. }
  901. // Add fields for parent objects
  902. foreach ($object->fields as $key => $val) {
  903. if (preg_match('/^[^:]+:[^:]+:/', $val['type'])) {
  904. $tmptype = explode(':', $val['type'], 4);
  905. if ($tmptype[0] == 'integer' && $tmptype[1] && $tmptype[2]) {
  906. $newobject = $tmptype[1];
  907. dol_include_once($tmptype[2]);
  908. if (class_exists($newobject)) {
  909. $tmpobject = new $newobject($db);
  910. //var_dump($key); var_dump($tmpobject->element); var_dump($val['label']); var_dump($tmptype); var_dump('t-'.$key);
  911. $count++;
  912. $arrayofmesures = fillArrayOfMeasures($tmpobject, $tablealias.'__'.$key, $langs->trans($val['label']), $arrayofmesures, $level + 1, $count);
  913. } else {
  914. print 'For property '.$object->element.'->'.$key.', type="'.$val['type'].'": Failed to find class '.$newobject." in file ".$tmptype[2]."<br>\n";
  915. }
  916. }
  917. }
  918. }
  919. return $arrayofmesures;
  920. }
  921. /**
  922. * Fill arrayofmesures for an object
  923. *
  924. * @param mixed $object Any object
  925. * @param string $tablealias Alias of table ('t' for example)
  926. * @param string $labelofobject Label of object
  927. * @param array $arrayofxaxis Array of xaxis already filled
  928. * @param int $level Level
  929. * @param int $count Count
  930. * @return array Array of xaxis
  931. */
  932. function fillArrayOfXAxis($object, $tablealias, $labelofobject, &$arrayofxaxis, $level = 0, &$count = 0)
  933. {
  934. global $langs, $extrafields, $db;
  935. if ($level > 10) { // Protection against infinite loop
  936. return $arrayofxaxis;
  937. }
  938. if ($level >= 2) {
  939. return $arrayofxaxis;
  940. }
  941. $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);
  942. $MM = substr($langs->trans("Month"), 0, 1).substr($langs->trans("Month"), 0, 1);
  943. $DD = substr($langs->trans("Day"), 0, 1).substr($langs->trans("Day"), 0, 1);
  944. $HH = substr($langs->trans("Hour"), 0, 1).substr($langs->trans("Hour"), 0, 1);
  945. $MI = substr($langs->trans("Minute"), 0, 1).substr($langs->trans("Minute"), 0, 1);
  946. $SS = substr($langs->trans("Second"), 0, 1).substr($langs->trans("Second"), 0, 1);
  947. // Add main fields of object
  948. foreach ($object->fields as $key => $val) {
  949. if (empty($val['measure'])) {
  950. if (in_array($key, array(
  951. 'id', 'ref_int', 'ref_ext', 'rowid', 'entity', 'last_main_doc', 'logo', 'logo_squarred', 'extraparams',
  952. 'parent', 'photo', 'socialnetworks', 'webservices_url', 'webservices_key'))) {
  953. continue;
  954. }
  955. if (isset($val['enabled']) && !dol_eval($val['enabled'], 1, 1, '1')) {
  956. continue;
  957. }
  958. if (isset($val['visible']) && !dol_eval($val['visible'], 1, 1, '1')) {
  959. continue;
  960. }
  961. if (preg_match('/^fk_/', $key) && !preg_match('/^fk_statu/', $key)) {
  962. continue;
  963. }
  964. if (preg_match('/^pass/', $key)) {
  965. continue;
  966. }
  967. if (in_array($val['type'], array('html', 'text'))) {
  968. continue;
  969. }
  970. if (in_array($val['type'], array('timestamp', 'date', 'datetime'))) {
  971. $position = (!empty($val['position']) ? $val['position'] : 0);
  972. $arrayofxaxis[$tablealias.'.'.$key.'-year'] = array(
  973. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']).' <span class="opacitymedium">('.$YYYY.')</span>',
  974. 'position' => ($position+($count * 100000)).'.1',
  975. 'table' => $object->table_element
  976. );
  977. $arrayofxaxis[$tablealias.'.'.$key.'-month'] = array(
  978. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']).' <span class="opacitymedium">('.$YYYY.'-'.$MM.')</span>',
  979. 'position' => ($position+($count * 100000)).'.2',
  980. 'table' => $object->table_element
  981. );
  982. $arrayofxaxis[$tablealias.'.'.$key.'-day'] = array(
  983. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']).' <span class="opacitymedium">('.$YYYY.'-'.$MM.'-'.$DD.')</span>',
  984. 'position' => ($position+($count * 100000)).'.3',
  985. 'table' => $object->table_element
  986. );
  987. } else {
  988. $arrayofxaxis[$tablealias.'.'.$key] = array(
  989. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']),
  990. 'position' => ($position+($count * 100000)),
  991. 'table' => $object->table_element
  992. );
  993. }
  994. }
  995. }
  996. // Add extrafields to X-Axis
  997. if ($object->isextrafieldmanaged) {
  998. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
  999. if ($extrafields->attributes[$object->table_element]['type'][$key] == 'separate') {
  1000. continue;
  1001. }
  1002. if (!empty($extrafields->attributes[$object->table_element]['totalizable'][$key])) {
  1003. continue;
  1004. }
  1005. $arrayofxaxis[$tablealias.'e.'.$key] = array(
  1006. 'label' => img_picto('', $object->picto, 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($extrafields->attributes[$object->table_element]['label'][$key]),
  1007. 'position' => 1000 + (int) $extrafields->attributes[$object->table_element]['pos'][$key] + ($count * 100000),
  1008. 'table' => $object->table_element
  1009. );
  1010. }
  1011. }
  1012. // Add fields for parent objects
  1013. foreach ($object->fields as $key => $val) {
  1014. if (preg_match('/^[^:]+:[^:]+:/', $val['type'])) {
  1015. $tmptype = explode(':', $val['type'], 4);
  1016. if ($tmptype[0] == 'integer' && $tmptype[1] && $tmptype[2]) {
  1017. $newobject = $tmptype[1];
  1018. dol_include_once($tmptype[2]);
  1019. if (class_exists($newobject)) {
  1020. $tmpobject = new $newobject($db);
  1021. //var_dump($key); var_dump($tmpobject->element); var_dump($val['label']); var_dump($tmptype); var_dump('t-'.$key);
  1022. $count++;
  1023. $arrayofxaxis = fillArrayOfXAxis($tmpobject, $tablealias.'__'.$key, $langs->trans($val['label']), $arrayofxaxis, $level + 1, $count);
  1024. } else {
  1025. print 'For property '.$object->element.'->'.$key.', type="'.$val['type'].'": Failed to find class '.$newobject." in file ".$tmptype[2]."<br>\n";
  1026. }
  1027. }
  1028. }
  1029. }
  1030. return $arrayofxaxis;
  1031. }
  1032. /**
  1033. * Fill arrayofgrupby for an object
  1034. *
  1035. * @param mixed $object Any object
  1036. * @param string $tablealias Alias of table
  1037. * @param string $labelofobject Label of object
  1038. * @param array $arrayofgroupby Array of groupby already filled
  1039. * @param int $level Level
  1040. * @param int $count Count
  1041. * @return array Array of groupby
  1042. */
  1043. function fillArrayOfGroupBy($object, $tablealias, $labelofobject, &$arrayofgroupby, $level = 0, &$count = 0)
  1044. {
  1045. global $langs, $extrafields, $db;
  1046. if ($level > 10) { // Protection against infinite loop
  1047. return $arrayofgroupby;
  1048. }
  1049. if ($level >= 2) {
  1050. return $arrayofgroupby;
  1051. }
  1052. $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);
  1053. $MM = substr($langs->trans("Month"), 0, 1).substr($langs->trans("Month"), 0, 1);
  1054. $DD = substr($langs->trans("Day"), 0, 1).substr($langs->trans("Day"), 0, 1);
  1055. $HH = substr($langs->trans("Hour"), 0, 1).substr($langs->trans("Hour"), 0, 1);
  1056. $MI = substr($langs->trans("Minute"), 0, 1).substr($langs->trans("Minute"), 0, 1);
  1057. $SS = substr($langs->trans("Second"), 0, 1).substr($langs->trans("Second"), 0, 1);
  1058. // Add main fields of object
  1059. foreach ($object->fields as $key => $val) {
  1060. if (!$val['isameasure']) {
  1061. if (in_array($key, array(
  1062. 'id', 'ref_int', 'ref_ext', 'rowid', 'entity', 'last_main_doc', 'logo', 'logo_squarred', 'extraparams',
  1063. 'parent', 'photo', 'socialnetworks', 'webservices_url', 'webservices_key'))) {
  1064. continue;
  1065. }
  1066. if (isset($val['enabled']) && !dol_eval($val['enabled'], 1, 1, '1')) {
  1067. continue;
  1068. }
  1069. if (isset($val['visible']) && !dol_eval($val['visible'], 1, 1, '1')) {
  1070. continue;
  1071. }
  1072. if (preg_match('/^fk_/', $key) && !preg_match('/^fk_statu/', $key)) {
  1073. continue;
  1074. }
  1075. if (preg_match('/^pass/', $key)) {
  1076. continue;
  1077. }
  1078. if (in_array($val['type'], array('html', 'text'))) {
  1079. continue;
  1080. }
  1081. if (in_array($val['type'], array('timestamp', 'date', 'datetime'))) {
  1082. $position = (!empty($val['position']) ? $val['position'] : 0);
  1083. $arrayofgroupby[$tablealias.'.'.$key.'-year'] = array(
  1084. 'label' => img_picto('', $object->picto,
  1085. 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']).' <span class="opacitymedium">('.$YYYY.')</span>', 'position' => ($position+($count * 100000)).'.1',
  1086. 'table' => $object->table_element
  1087. );
  1088. $arrayofgroupby[$tablealias.'.'.$key.'-month'] = array(
  1089. 'label' => img_picto('', $object->picto,
  1090. 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']).' <span class="opacitymedium">('.$YYYY.'-'.$MM.')</span>', 'position' => ($position+($count * 100000)).'.2',
  1091. 'table' => $object->table_element
  1092. );
  1093. $arrayofgroupby[$tablealias.'.'.$key.'-day'] = array(
  1094. 'label' => img_picto('', $object->picto,
  1095. 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']).' <span class="opacitymedium">('.$YYYY.'-'.$MM.'-'.$DD.')</span>', 'position' => ($position+($count * 100000)).'.3',
  1096. 'table' => $object->table_element
  1097. );
  1098. } else {
  1099. $arrayofgroupby[$tablealias.'.'.$key] = array(
  1100. 'label' => img_picto('', $object->picto,
  1101. 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($val['label']), 'position' => ($position+($count * 100000)),
  1102. 'table' => $object->table_element
  1103. );
  1104. }
  1105. }
  1106. }
  1107. // Add extrafields to Group by
  1108. if ($object->isextrafieldmanaged) {
  1109. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
  1110. if ($extrafields->attributes[$object->table_element]['type'][$key] == 'separate') {
  1111. continue;
  1112. }
  1113. if (!empty($extrafields->attributes[$object->table_element]['totalizable'][$key])) {
  1114. continue;
  1115. }
  1116. $arrayofgroupby[$tablealias.'e.'.$key] = array(
  1117. 'label' => img_picto('', $object->picto,
  1118. 'class="pictofixedwidth"').' '.$labelofobject.': '.$langs->trans($extrafields->attributes[$object->table_element]['label'][$key]), 'position' => 1000 + (int) $extrafields->attributes[$object->table_element]['pos'][$key] + ($count * 100000),
  1119. 'table' => $object->table_element
  1120. );
  1121. }
  1122. }
  1123. // Add fields for parent objects
  1124. foreach ($object->fields as $key => $val) {
  1125. if (preg_match('/^[^:]+:[^:]+:/', $val['type'])) {
  1126. $tmptype = explode(':', $val['type'], 4);
  1127. if ($tmptype[0] == 'integer' && $tmptype[1] && $tmptype[2]) {
  1128. $newobject = $tmptype[1];
  1129. dol_include_once($tmptype[2]);
  1130. if (class_exists($newobject)) {
  1131. $tmpobject = new $newobject($db);
  1132. //var_dump($key); var_dump($tmpobject->element); var_dump($val['label']); var_dump($tmptype); var_dump('t-'.$key);
  1133. $count++;
  1134. $arrayofgroupby = fillArrayOfGroupBy($tmpobject, $tablealias.'__'.$key, $langs->trans($val['label']), $arrayofgroupby, $level + 1, $count);
  1135. } else {
  1136. print 'For property '.$object->element.'->'.$key.', type="'.$val['type'].'": Failed to find class '.$newobject." in file ".$tmptype[2]."<br>\n";
  1137. }
  1138. }
  1139. }
  1140. }
  1141. return $arrayofgroupby;
  1142. }