sqlblock.class.inc.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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>');
  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']))
  165. {
  166. }
  167. }
  168. if (strlen($this->m_sTitle) > 0)
  169. {
  170. $oPage->add("<h2>".Dict::S($this->m_sTitle)."</h2>\n");
  171. }
  172. switch ($this->m_sType)
  173. {
  174. case 'bars':
  175. case 'pie':
  176. $aColNames = array_keys($this->m_aColumns);
  177. $sXColName = $aColNames[0];
  178. $sYColName = $aColNames[1];
  179. $aData = array();
  180. while($aRow = CMDBSource::FetchArray($res))
  181. {
  182. $aData[$aRow[$sXColName]] = $aRow[$sYColName];
  183. }
  184. $this->RenderChart($oPage, $sId, $aData);
  185. break;
  186. default:
  187. case 'table':
  188. $aDisplayConfig = array();
  189. foreach($this->m_aColumns as $sName => $aColumnData)
  190. {
  191. $aDisplayConfig[$sName] = array('label' => $aColumnData['label'], 'description' => '');
  192. }
  193. $aDisplayData = array();
  194. while($aRow = CMDBSource::FetchArray($res))
  195. {
  196. $aDisplayRow = array();
  197. foreach($this->m_aColumns as $sName => $aColumnData)
  198. {
  199. $aDisplayRow[$sName] = $aRow[$sName];
  200. }
  201. $aDisplayData[] = $aRow;
  202. }
  203. $oPage->table($aDisplayConfig, $aDisplayData);
  204. break;
  205. }
  206. }
  207. public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId)
  208. {
  209. $sHtml = '';
  210. return $sHtml;
  211. }
  212. protected function RenderChart($oPage, $sId, $aValues)
  213. {
  214. // 1- Compute Open Flash Chart data
  215. //
  216. $aValueKeys = array();
  217. foreach($aValues as $key => $value)
  218. {
  219. // Make sure that values are integers (so that max() will work....)
  220. // and build an array of STRING with the keys (numeric keys are transformed into string by PHP :-(
  221. $aValues[$key] = (int)$value;
  222. $aValueKeys[] = (string)$key;
  223. }
  224. $oChart = new open_flash_chart();
  225. if ($this->m_sType == 'bars')
  226. {
  227. $oChartElement = new bar_glass();
  228. $maxValue = max($aValues);
  229. $oYAxis = new y_axis();
  230. $aMagicValues = array(1,2,5,10);
  231. $iMultiplier = 1;
  232. $index = 0;
  233. $iTop = $aMagicValues[$index % count($aMagicValues)]*$iMultiplier;
  234. while($maxValue > $iTop)
  235. {
  236. $index++;
  237. $iTop = $aMagicValues[$index % count($aMagicValues)]*$iMultiplier;
  238. if (($index % count($aMagicValues)) == 0)
  239. {
  240. $iMultiplier = $iMultiplier * 10;
  241. }
  242. }
  243. //echo "oYAxis->set_range(0, $iTop, $iMultiplier);\n";
  244. $oYAxis->set_range(0, $iTop, $iMultiplier);
  245. $oChart->set_y_axis( $oYAxis );
  246. $oChartElement->set_values(array_values($aValues));
  247. $oXAxis = new x_axis();
  248. $oXLabels = new x_axis_labels();
  249. // set them vertical
  250. $oXLabels->set_vertical();
  251. // set the label text
  252. $oXLabels->set_labels($aValueKeys);
  253. // Add the X Axis Labels to the X Axis
  254. $oXAxis->set_labels( $oXLabels );
  255. $oChart->set_x_axis( $oXAxis );
  256. }
  257. else
  258. {
  259. $oChartElement = new pie();
  260. $oChartElement->set_start_angle( 35 );
  261. $oChartElement->set_animate( true );
  262. $oChartElement->set_tooltip( '#label# - #val# (#percent#)' );
  263. $oChartElement->set_colours( array('#FF8A00', '#909980', '#2C2B33', '#CCC08D', '#596664') );
  264. $aData = array();
  265. foreach($aValues as $sValue => $iValue)
  266. {
  267. $aData[] = new pie_value($iValue, $sValue); //@@ BUG: not passed via ajax !!!
  268. }
  269. $oChartElement->set_values( $aData );
  270. $oChart->x_axis = null;
  271. }
  272. // Title given in HTML
  273. //$oTitle = new title($this->m_sTitle);
  274. //$oChart->set_title($oTitle);
  275. $oChart->set_bg_colour('#FFFFFF');
  276. $oChart->add_element( $oChartElement );
  277. $sData = $oChart->toPrettyString();
  278. $sData = json_encode($sData);
  279. // 2- Declare the Javascript function that will render the chart data\
  280. //
  281. $oPage->add_script(
  282. <<< EOF
  283. function ofc_get_data_{$sId}()
  284. {
  285. return $sData;
  286. }
  287. EOF
  288. );
  289. // 3- Insert the Open Flash chart
  290. //
  291. $oPage->add("<div id=\"$sId\">If blah blah cd romain<div>\n");
  292. $oPage->add_ready_script(
  293. <<<EOF
  294. swfobject.embedSWF( "../images/open-flash-chart.swf",
  295. "{$sId}",
  296. "100%", "300","9.0.0",
  297. "expressInstall.swf",
  298. {"get-data":"ofc_get_data_{$sId}", "id":"{$sId}"},
  299. {'wmode': 'transparent'}
  300. );
  301. EOF
  302. );
  303. }
  304. }
  305. ?>