run_query.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. <?php
  2. // Copyright (C) 2010-2016 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Tools to design OQL queries and test them
  20. *
  21. * @copyright Copyright (C) 2010-2016 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. require_once('../approot.inc.php');
  25. require_once(APPROOT.'/application/application.inc.php');
  26. require_once(APPROOT.'/application/itopwebpage.class.inc.php');
  27. require_once(APPROOT.'/application/startup.inc.php');
  28. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  29. LoginWebPage::DoLogin(true); // Check user rights and prompt if needed (must be admin)
  30. function ShowExamples($oP, $sExpression)
  31. {
  32. $bUsingExample = false;
  33. $aExamples = array(
  34. 'Pedagogic examples' => array(
  35. "Web applications" => "SELECT WebApplication",
  36. "Person having an 'A' in their name" => "SELECT Person AS B WHERE B.name LIKE '%A%'",
  37. "Servers having a name like dbserver1.demo.com or dbserver023.foo.fr" => "SELECT Server WHERE name REGEXP '^dbserver[0-9]+\\\\..+\\\\.[a-z]{2,3}$'",
  38. "Changes planned on new year's day" => "SELECT Change AS ch WHERE ch.start_date >= '2009-12-31' AND ch.end_date <= '2010-01-01'",
  39. "IPs in a range" => "SELECT DatacenterDevice AS dev WHERE INET_ATON(dev.managementip) > INET_ATON('10.22.32.224') AND INET_ATON(dev.managementip) < INET_ATON('10.22.32.255')",
  40. "Persons below a given root organization" => "SELECT Person AS P JOIN Organization AS Node ON P.org_id = Node.id JOIN Organization AS Root ON Node.parent_id BELOW Root.id WHERE Root.id=1",
  41. ),
  42. 'Usefull examples' => array(
  43. "NW interfaces of equipment in production for customer 'Demo'" => "SELECT PhysicalInterface AS if JOIN DatacenterDevice AS dev ON if.connectableci_id = dev.id WHERE dev.status = 'production' AND dev.organization_name = 'Demo'",
  44. "My tickets" => "SELECT Ticket AS t WHERE t.agent_id = :current_contact_id",
  45. "People being owner of an active ticket" => "SELECT Person AS p JOIN UserRequest AS u ON u.agent_id = p.id WHERE u.status != 'closed'",
  46. "Contracts terminating in the next thirty days" => "SELECT Contract AS c WHERE c.end_date > NOW() AND c.end_date < DATE_ADD(NOW(), INTERVAL 30 DAY)",
  47. "Orphan tickets (opened one hour ago, still not assigned)" => "SELECT UserRequest AS u WHERE u.start_date < DATE_SUB(NOW(), INTERVAL 60 MINUTE) AND u.status = 'new'",
  48. "Long lasting incidents (duration > 8 hours)" => "SELECT UserRequest AS u WHERE u.close_date > DATE_ADD(u.start_date, INTERVAL 8 HOUR)",
  49. ),
  50. );
  51. $aDisplayData = array();
  52. $oAppContext = new ApplicationContext();
  53. $sContext = $oAppContext->GetForForm();
  54. foreach($aExamples as $sTopic => $aQueries)
  55. {
  56. foreach($aQueries as $sDescription => $sOql)
  57. {
  58. $sHighlight = '';
  59. $sDisable = '';
  60. if ($sOql == $sExpression)
  61. {
  62. // this one is currently being tested, highlight it
  63. $sHighlight = "background-color:yellow;";
  64. $sDisable = 'disabled';
  65. // and remember we are testing a query of the list
  66. $bUsingExample = true;
  67. }
  68. //$aDisplayData[$sTopic][] = array(
  69. $aDisplayData[Dict::S('UI:RunQuery:QueryExamples')][] = array(
  70. 'desc' => "<div style=\"$sHighlight\">".htmlentities($sDescription, ENT_QUOTES, 'UTF-8')."</div>",
  71. 'oql' => "<div style=\"$sHighlight\">".htmlentities($sOql, ENT_QUOTES, 'UTF-8')."</div>",
  72. 'go' => "<form method=\"get\"><input type=\"hidden\" name=\"expression\" value=\"$sOql\"><input type=\"submit\" value=\"".Dict::S('UI:Button:Test')."\" $sDisable>$sContext</form>\n",
  73. );
  74. }
  75. }
  76. $aDisplayConfig = array();
  77. $aDisplayConfig['desc'] = array('label' => Dict::S('UI:RunQuery:HeaderPurpose'), 'description' => Dict::S('UI:RunQuery:HeaderPurpose+'));
  78. $aDisplayConfig['oql'] = array('label' => Dict::S('UI:RunQuery:HeaderOQLExpression'), 'description' => Dict::S('UI:RunQuery:HeaderOQLExpression+'));
  79. $aDisplayConfig['go'] = array('label' => '', 'description' => '');
  80. foreach ($aDisplayData as $sTopic => $aQueriesDisplayData)
  81. {
  82. $bShowOpened = $bUsingExample;
  83. $oP->StartCollapsibleSection($sTopic, $bShowOpened);
  84. $oP->table($aDisplayConfig, $aQueriesDisplayData);
  85. $oP->EndCollapsibleSection();
  86. }
  87. }
  88. $sOperation = utils::ReadParam('operation', 'menu');
  89. $oAppContext = new ApplicationContext();
  90. $oP = new iTopWebPage(Dict::S('UI:RunQuery:Title'));
  91. $oP->SetBreadCrumbEntry('ui-tool-runquery', Dict::S('Menu:RunQueriesMenu'), Dict::S('Menu:RunQueriesMenu+'), '', utils::GetAbsoluteUrlAppRoot().'images/wrench.png');
  92. // Main program
  93. $sExpression = utils::ReadParam('expression', '', false, 'raw_data');
  94. $sEncoding = utils::ReadParam('encoding', 'oql');
  95. ShowExamples($oP, $sExpression);
  96. try
  97. {
  98. if ($sEncoding == 'crypted')
  99. {
  100. // Translate $sExpression into a oql expression
  101. $sClearText = base64_decode($sExpression);
  102. echo "<strong>FYI: '$sClearText'</strong><br/>\n";
  103. $oFilter = DBObjectSearch::unserialize($sExpression);
  104. $sExpression = $oFilter->ToOQL();
  105. }
  106. else
  107. {
  108. // leave $sExpression as is
  109. }
  110. $oFilter = null;
  111. $aArgs = array();
  112. $sSyntaxError = null;
  113. if (!empty($sExpression))
  114. {
  115. try
  116. {
  117. $oFilter = DBObjectSearch::FromOQL($sExpression);
  118. }
  119. catch(Exception $e)
  120. {
  121. if ($e instanceof OqlException)
  122. {
  123. $sSyntaxError = $e->getHtmlDesc();
  124. }
  125. else
  126. {
  127. $sSyntaxError = $e->getMessage();
  128. }
  129. }
  130. if ($oFilter)
  131. {
  132. $aArgs = array();
  133. foreach($oFilter->GetQueryParams() as $sParam => $foo)
  134. {
  135. $value = utils::ReadParam('arg_'.$sParam, null, true, 'raw_data');
  136. if (!is_null($value))
  137. {
  138. $aArgs[$sParam] = $value;
  139. }
  140. else
  141. {
  142. $aArgs[$sParam] = '';
  143. }
  144. }
  145. $oFilter->SetInternalParams($aArgs);
  146. }
  147. elseif ($sSyntaxError)
  148. {
  149. // Query arguments taken from the page args
  150. }
  151. }
  152. $oP->add("<form method=\"post\">\n");
  153. $oP->add(Dict::S('UI:RunQuery:ExpressionToEvaluate')."<br/>\n");
  154. $oP->add("<textarea cols=\"120\" rows=\"8\" name=\"expression\">".htmlentities($sExpression, ENT_QUOTES, 'UTF-8')."</textarea>\n");
  155. if (count($aArgs) > 0)
  156. {
  157. $oP->add("<div class=\"wizContainer\">\n");
  158. $oP->add("<h3>Query arguments</h3>\n");
  159. foreach($aArgs as $sParam => $sValue)
  160. {
  161. $oP->p("$sParam: <input type=\"string\" name=\"arg_$sParam\" value=\"$sValue\">\n");
  162. }
  163. $oP->add("</div>\n");
  164. }
  165. $oP->add("<input type=\"submit\" value=\"".Dict::S('UI:Button:Evaluate')."\">\n");
  166. $oP->add($oAppContext->GetForForm());
  167. $oP->add("</form>\n");
  168. if ($oFilter)
  169. {
  170. $oP->add("<h3>Query results</h3>\n");
  171. $oResultBlock = new DisplayBlock($oFilter, 'list', false);
  172. $oResultBlock->Display($oP, 'runquery');
  173. // Breadcrumb
  174. //$iCount = $oResultBlock->GetDisplayedCount();
  175. $sPageId = "ui-search-".$oFilter->GetClass();
  176. $sLabel = MetaModel::GetName($oFilter->GetClass());
  177. $aArgs = array();
  178. foreach (array_merge($_POST, $_GET) as $sKey => $value)
  179. {
  180. if (is_array($value))
  181. {
  182. $aItems = array();
  183. foreach($value as $sItemKey => $sItemValue)
  184. {
  185. $aArgs[] = $sKey.'['.$sItemKey.']='.urlencode($sItemValue);
  186. }
  187. }
  188. else
  189. {
  190. $aArgs[] = $sKey.'='.urlencode($value);
  191. }
  192. }
  193. $sUrl = utils::GetAbsoluteUrlAppRoot().'pages/run_query.php?'.implode('&', $aArgs);
  194. $oP->SetBreadCrumbEntry($sPageId, $sLabel, $oFilter->ToOQL(true), $sUrl, '../images/breadcrumb-search.png');
  195. $oP->p('');
  196. $oP->StartCollapsibleSection(Dict::S('UI:RunQuery:MoreInfo'), false);
  197. $oP->p(Dict::S('UI:RunQuery:DevelopedQuery').htmlentities($oFilter->ToOQL(), ENT_QUOTES, 'UTF-8'));
  198. $oP->p(Dict::S('UI:RunQuery:SerializedFilter').$oFilter->serialize());
  199. $oP->EndCollapsibleSection();
  200. }
  201. elseif ($sSyntaxError)
  202. {
  203. if ($e instanceof OqlException)
  204. {
  205. $sWrongWord = $e->GetWrongWord();
  206. $aSuggestedWords = $e->GetSuggestions();
  207. if (count($aSuggestedWords) > 0)
  208. {
  209. $sSuggestedWord = OqlException::FindClosestString($sWrongWord, $aSuggestedWords);
  210. if (strlen($sSuggestedWord) > 0)
  211. {
  212. $oP->p('<b>'.Dict::Format('UI:RunQuery:Error', $e->GetIssue().' <em>'.$sWrongWord).'</em></b>');
  213. $sBefore = substr($sExpression, 0, $e->GetColumn());
  214. $sAfter = substr($sExpression, $e->GetColumn() + strlen($sWrongWord));
  215. $sFixedExpression = $sBefore.$sSuggestedWord.$sAfter;
  216. $sFixedExpressionHtml = $sBefore.'<span style="background-color:yellow">'.$sSuggestedWord.'</span>'.$sAfter;
  217. $oP->p("Suggesting: $sFixedExpressionHtml");
  218. $oP->add('<button onClick="$(\'textarea[name=expression]\').val(\''.htmlentities(addslashes($sFixedExpression)).'\');">Use this query</button>');
  219. }
  220. else
  221. {
  222. $oP->p('<b>'.Dict::Format('UI:RunQuery:Error', $e->getHtmlDesc()).'</b>');
  223. }
  224. }
  225. else
  226. {
  227. $oP->p('<b>'.Dict::Format('UI:RunQuery:Error', $e->getHtmlDesc()).'</b>');
  228. }
  229. }
  230. else
  231. {
  232. $oP->p('<b>'.Dict::Format('UI:RunQuery:Error', $e->getMessage()).'</b>');
  233. }
  234. }
  235. }
  236. catch(Exception $e)
  237. {
  238. $oP->p('<b>'.Dict::Format('UI:RunQuery:Error', $e->getMessage()).'</b>');
  239. }
  240. $oP->output();
  241. ?>