sqlblock.class.inc.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  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; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * SqlBlock - display tables or charts, given an SQL query - use cautiously!
  18. *
  19. *
  20. * @author Erwan Taloc <erwan.taloc@combodo.com>
  21. * @author Romain Quetiez <romain.quetiez@combodo.com>
  22. * @author Denis Flaven <denis.flaven@combodo.com>
  23. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  24. */
  25. require_once(APPROOT.'/application/webpage.class.inc.php');
  26. require_once(APPROOT.'/application/utils.inc.php');
  27. require_once(APPROOT.'/pages/php-ofc-library/open-flash-chart.php');
  28. /**
  29. * Helper class to design optimized dashboards, based on an SQL query
  30. *
  31. */
  32. class SqlBlock
  33. {
  34. protected $m_sQuery;
  35. protected $m_aColumns;
  36. protected $m_sTitle;
  37. protected $m_sType;
  38. public function __construct($sQuery, $aColumns, $sTitle, $sType)
  39. {
  40. $this->m_sQuery = $sQuery;
  41. $this->m_aColumns = $aColumns;
  42. $this->m_sTitle = $sTitle;
  43. $this->m_sType = $sType;
  44. }
  45. /**
  46. * Constructs a SqlBlock object from an XML template
  47. /*
  48. *
  49. * <sqlblock>
  50. * <sql>SELECT date_format(start_date, '%d') AS Date, count(*) AS Count FROM ticket WHERE DATE_SUB(NOW(), INTERVAL 15 DAY) &lt; start_date AND finalclass = 'UserIssue' GROUP BY date_format(start_date, '%d')</sql>
  51. * <type>table</type>
  52. * <title>UserRequest:Overview-Title</title>
  53. * <column>
  54. * <name>Date</name>
  55. * <label>UserRequest:Overview-Date</label>
  56. * <drilldown></drilldown>
  57. * </column>
  58. * <column>
  59. * <name>Count</name>
  60. * <label>UserRequest:Overview-Count</label>
  61. * <drilldown>SELECT UserIssue WHERE date_format(start_date, '%d') = :Date</drilldown>
  62. * </column>
  63. * </sqlblock>
  64. *
  65. * Tags
  66. * - sql: a (My)SQL query. Do not forget to use html entities (e.g. &lt; for <)
  67. * - type: table (default), bars or pie. If bars or pie is selected only the two first columns are taken into account.
  68. * - title: optional title, typed in clear or given as a dictionnary entry
  69. * - column: specification of a column (not displayed if omitted)
  70. * - column / name: name of the column in the SQL query (use aliases)
  71. * - column / label: label, typed in clear or given as a dictionnary entry
  72. * - column / drilldown: NOT IMPLEMENTED YET - OQL with parameters corresponding to column names (in the query)
  73. *
  74. * @param $sTemplate string The XML template
  75. * @return DisplayBlock The DisplayBlock object, or null if the template is invalid
  76. */
  77. public static function FromTemplate($sTemplate)
  78. {
  79. $oXml = simplexml_load_string('<root>'.$sTemplate.'</root>', 'SimpleXMLElement', LIBXML_NOCDATA);
  80. if (false)
  81. {
  82. // Debug
  83. echo "<pre>\n";
  84. print_r($oXml);
  85. echo "</pre>\n";
  86. }
  87. if (isset($oXml->title))
  88. {
  89. $sTitle = (string)$oXml->title;
  90. }
  91. if (isset($oXml->type))
  92. {
  93. $sType = (string)$oXml->type;
  94. }
  95. else
  96. {
  97. $sType = 'table';
  98. }
  99. if (!isset($oXml->sql))
  100. {
  101. throw new Exception('Missing tag "sql" in sqlblock');
  102. }
  103. $sQuery = (string)$oXml->sql;
  104. $aColumns = array();
  105. if (isset($oXml->column))
  106. {
  107. foreach ($oXml->column AS $oColumnData)
  108. {
  109. if (!isset($oColumnData->name))
  110. {
  111. throw new Exception("Missing tag 'name' in sqlblock/column");
  112. }
  113. $sName = (string) $oColumnData->name;
  114. if (strlen($sName) == 0)
  115. {
  116. throw new Exception("Empty tag 'name' in sqlblock/column");
  117. }
  118. $aColumns[$sName] = array();
  119. if (isset($oColumnData->label))
  120. {
  121. $sLabel = (string)$oColumnData->label;
  122. if (strlen($sLabel) > 0)
  123. {
  124. $aColumns[$sName]['label'] = Dict::S($sLabel);
  125. }
  126. }
  127. if (isset($oColumnData->drilldown))
  128. {
  129. $sDrillDown = (string)$oColumnData->drilldown;
  130. if (strlen($sDrillDown) > 0)
  131. {
  132. $aColumns[$sName]['drilldown'] = $sDrillDown;
  133. }
  134. }
  135. }
  136. }
  137. return new SqlBlock($sQuery, $aColumns, $sTitle, $sType);
  138. }
  139. public function RenderContent(WebPage $oPage, $aExtraParams = array())
  140. {
  141. if (empty($aExtraParams['currentId']))
  142. {
  143. $sId = 'sqlblock_'.$oPage->GetUniqueId(); // Works only if the page is not an Ajax one !
  144. }
  145. else
  146. {
  147. $sId = $aExtraParams['currentId'];
  148. }
  149. // $oPage->add($this->GetRenderContent($oPage, $aExtraParams, $sId));
  150. $res = CMDBSource::Query($this->m_sQuery);
  151. $aQueryCols = CMDBSource::GetColumns($res);
  152. // Prepare column definitions (check + give default values)
  153. //
  154. foreach($this->m_aColumns as $sName => $aColumnData)
  155. {
  156. if (!in_array($sName, $aQueryCols))
  157. {
  158. throw new Exception("Unknown column name '$sName' in sqlblock column");
  159. }
  160. if (!isset($aColumnData['label']))
  161. {
  162. $this->m_aColumns[$sName]['label'] = $sName;
  163. }
  164. if (isset($aColumnData['drilldown']) && !empty($aColumnData['drilldown']))
  165. {
  166. // Check if the OQL is valid
  167. try
  168. {
  169. $this->m_aColumns[$sName]['filter'] = DBObjectSearch::FromOQL($aColumnData['drilldown']);
  170. }
  171. catch(OQLException $e)
  172. {
  173. unset($aColumnData['drilldown']);
  174. }
  175. }
  176. }
  177. if (strlen($this->m_sTitle) > 0)
  178. {
  179. $oPage->add("<h2>".Dict::S($this->m_sTitle)."</h2>\n");
  180. }
  181. switch ($this->m_sType)
  182. {
  183. case 'bars':
  184. case 'pie':
  185. $aColNames = array_keys($this->m_aColumns);
  186. $sXColName = $aColNames[0];
  187. $sYColName = $aColNames[1];
  188. $aData = array();
  189. $aRows = array();
  190. while($aRow = CMDBSource::FetchArray($res))
  191. {
  192. $aData[$aRow[$sXColName]] = $aRow[$sYColName];
  193. $aRows[$aRow[$sXColName]] = $aRow;
  194. }
  195. $this->RenderChart($oPage, $sId, $aData, $this->m_aColumns[$sYColName]['drilldown'], $aRows);
  196. break;
  197. default:
  198. case 'table':
  199. $oAppContext = new ApplicationContext();
  200. $aDisplayConfig = array();
  201. foreach($this->m_aColumns as $sName => $aColumnData)
  202. {
  203. $aDisplayConfig[$sName] = array('label' => $aColumnData['label'], 'description' => '');
  204. }
  205. $aDisplayData = array();
  206. while($aRow = CMDBSource::FetchArray($res))
  207. {
  208. $aSQLColNames = array_keys($aRow);
  209. $aDisplayRow = array();
  210. foreach($this->m_aColumns as $sName => $aColumnData)
  211. {
  212. if (isset($aColumnData['filter']))
  213. {
  214. $sFilter = $aColumnData['drilldown'];
  215. $sClass = $aColumnData['filter']->GetClass();
  216. $sFilter = str_replace('SELECT '.$sClass, '', $sFilter);
  217. foreach($aSQLColNames as $sColName)
  218. {
  219. $sFilter = str_replace(':'.$sColName, "'".addslashes( $aRow[$sColName] )."'", $sFilter);
  220. }
  221. $sURL = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=search_oql&search_form=0&oql_class='.$sClass.'&oql_clause='.urlencode($sFilter).'&format=html?'.$oAppContext->GetForLink();
  222. $aDisplayRow[$sName] = '<a href="'.$sURL.'">'.$aRow[$sName]."</a>";
  223. }
  224. else
  225. {
  226. $aDisplayRow[$sName] = $aRow[$sName];
  227. }
  228. }
  229. $aDisplayData[] = $aDisplayRow;
  230. }
  231. $oPage->table($aDisplayConfig, $aDisplayData);
  232. break;
  233. }
  234. }
  235. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  236. {
  237. $sHtml = '';
  238. return $sHtml;
  239. }
  240. protected function RenderChart($oPage, $sId, $aValues, $sDrillDown = '', $aRows = array())
  241. {
  242. // 1- Compute Open Flash Chart data
  243. //
  244. $aValueKeys = array();
  245. $index = 0;
  246. if ($sDrillDown != '')
  247. {
  248. $oFilter = DBObjectSearch::FromOQL($sDrillDown);
  249. $sClass = $oFilter->GetClass();
  250. $sOQLClause = str_replace('SELECT '.$sClass, '', $sDrillDown);
  251. $aSQLColNames = array_keys(current($aRows)); // Read the list of columns from the current (i.e. first) element of the array
  252. $oAppContext = new ApplicationContext();
  253. $sURL = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=search_oql&search_form=0&oql_class='.$sClass.'&format=html&'.$oAppContext->GetForLink().'&oql_clause=';
  254. $aURLs = array();
  255. }
  256. foreach($aValues as $key => $value)
  257. {
  258. // Make sure that values are integers (so that max() will work....)
  259. // and build an array of STRING with the keys (numeric keys are transformed into string by PHP :-(
  260. $aValues[$key] = (int)$value;
  261. $aValueKeys[] = (string)$key;
  262. // Build the custom query for the 'drill down' on each element
  263. if ($sDrillDown != '')
  264. {
  265. $sFilter = $sOQLClause;
  266. foreach($aSQLColNames as $sColName)
  267. {
  268. $sFilter = str_replace(':'.$sColName, "'".addslashes( $aRows[$key][$sColName] )."'", $sFilter);
  269. $aURLs[$index] = $sURL.urlencode($sFilter);
  270. }
  271. }
  272. $index++;
  273. }
  274. $oChart = new open_flash_chart();
  275. if ($this->m_sType == 'bars')
  276. {
  277. $oChartElement = new bar_glass();
  278. $maxValue = max($aValues);
  279. $oYAxis = new y_axis();
  280. $aMagicValues = array(1,2,5,10);
  281. $iMultiplier = 1;
  282. $index = 0;
  283. $iTop = $aMagicValues[$index % count($aMagicValues)]*$iMultiplier;
  284. while($maxValue > $iTop)
  285. {
  286. $index++;
  287. $iTop = $aMagicValues[$index % count($aMagicValues)]*$iMultiplier;
  288. if (($index % count($aMagicValues)) == 0)
  289. {
  290. $iMultiplier = $iMultiplier * 10;
  291. }
  292. }
  293. //echo "oYAxis->set_range(0, $iTop, $iMultiplier);\n";
  294. $oYAxis->set_range(0, $iTop, $iMultiplier);
  295. $oChart->set_y_axis( $oYAxis );
  296. $aBarValues = array();
  297. foreach($aValues as $iValue)
  298. {
  299. $oBarValue = new bar_value($iValue);
  300. $oBarValue->on_click("ofc_drilldown_{$sId}");
  301. $aBarValues[] = $oBarValue;
  302. }
  303. $oChartElement->set_values($aBarValues);
  304. //$oChartElement->set_values(array_values($aValues));
  305. $oXAxis = new x_axis();
  306. $oXLabels = new x_axis_labels();
  307. // set them vertical
  308. $oXLabels->set_vertical();
  309. // set the label text
  310. $oXLabels->set_labels($aValueKeys);
  311. // Add the X Axis Labels to the X Axis
  312. $oXAxis->set_labels( $oXLabels );
  313. $oChart->set_x_axis( $oXAxis );
  314. }
  315. else
  316. {
  317. $oChartElement = new pie();
  318. $oChartElement->set_start_angle( 35 );
  319. $oChartElement->set_animate( true );
  320. $oChartElement->set_tooltip( '#label# - #val# (#percent#)' );
  321. $oChartElement->set_colours( array('#FF8A00', '#909980', '#2C2B33', '#CCC08D', '#596664') );
  322. $aData = array();
  323. foreach($aValues as $sValue => $iValue)
  324. {
  325. $oPieValue = new pie_value($iValue, $sValue); //@@ BUG: not passed via ajax !!!
  326. $oPieValue->on_click("ofc_drilldown_{$sId}");
  327. $aData[] = $oPieValue;
  328. }
  329. $oChartElement->set_values( $aData );
  330. $oChart->x_axis = null;
  331. }
  332. // Title given in HTML
  333. //$oTitle = new title($this->m_sTitle);
  334. //$oChart->set_title($oTitle);
  335. $oChart->set_bg_colour('#FFFFFF');
  336. $oChart->add_element( $oChartElement );
  337. $sData = $oChart->toPrettyString();
  338. $sData = json_encode($sData);
  339. $sURLList = '';
  340. foreach($aURLs as $index => $sURL)
  341. {
  342. $sURLList .= "\taURLs[$index] = '".addslashes($sURL)."';\n";
  343. }
  344. // 2- Declare the Javascript function that will render the chart data\
  345. //
  346. $oPage->add_script(
  347. <<< EOF
  348. function ofc_get_data_{$sId}()
  349. {
  350. return $sData;
  351. }
  352. function ofc_drilldown_{$sId}(index)
  353. {
  354. var aURLs = new Array();
  355. {$sURLList}
  356. var sURL = aURLs[index];
  357. window.location.href = sURL; // Navigate !
  358. }
  359. EOF
  360. );
  361. // 3- Insert the Open Flash chart
  362. //
  363. $oPage->add("<div id=\"$sId\"><div>\n");
  364. $oPage->add_ready_script(
  365. <<<EOF
  366. swfobject.embedSWF( "../images/open-flash-chart.swf",
  367. "{$sId}",
  368. "100%", "300","9.0.0",
  369. "expressInstall.swf",
  370. {"get-data":"ofc_get_data_{$sId}", "id":"{$sId}"},
  371. {'wmode': 'transparent'}
  372. );
  373. EOF
  374. );
  375. }
  376. }
  377. ?>