run_query.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. // Main program
  92. $sExpression = utils::ReadParam('expression', '', false, 'raw_data');
  93. $sEncoding = utils::ReadParam('encoding', 'oql');
  94. ShowExamples($oP, $sExpression);
  95. try
  96. {
  97. if ($sEncoding == 'crypted')
  98. {
  99. // Translate $sExpression into a oql expression
  100. $sClearText = base64_decode($sExpression);
  101. echo "<strong>FYI: '$sClearText'</strong><br/>\n";
  102. $oFilter = DBObjectSearch::unserialize($sExpression);
  103. $sExpression = $oFilter->ToOQL();
  104. }
  105. else
  106. {
  107. // leave $sExpression as is
  108. }
  109. $oFilter = null;
  110. $aArgs = array();
  111. $sSyntaxError = null;
  112. if (!empty($sExpression))
  113. {
  114. try
  115. {
  116. $oFilter = DBObjectSearch::FromOQL($sExpression);
  117. }
  118. catch(Exception $e)
  119. {
  120. if ($e instanceof OqlException)
  121. {
  122. $sSyntaxError = $e->getHtmlDesc();
  123. }
  124. else
  125. {
  126. $sSyntaxError = $e->getMessage();
  127. }
  128. }
  129. $aNakedMagicArguments = array();
  130. foreach (MetaModel::PrepareQueryArguments(array()) as $sArgName => $value)
  131. {
  132. $iPos = strpos($sArgName, '->object()');
  133. if ($iPos === false)
  134. {
  135. $aNakedMagicArguments[$sArgName] = $value;
  136. }
  137. else
  138. {
  139. $aNakedMagicArguments[substr($sArgName, 0, $iPos)] = true;
  140. }
  141. }
  142. if ($oFilter)
  143. {
  144. $aArgs = array();
  145. foreach($oFilter->GetQueryParams() as $sParam => $foo)
  146. {
  147. // Skip magic parameters
  148. $iPos = strpos($sParam, '->');
  149. if ($iPos === false)
  150. {
  151. $sRefName = $sParam;
  152. }
  153. else
  154. {
  155. $sRefName = substr($sParam, 0, $iPos);
  156. }
  157. if (array_key_exists($sRefName, $aNakedMagicArguments)) continue;
  158. $value = utils::ReadParam('arg_'.$sParam, null, true, 'raw_data');
  159. if (!is_null($value))
  160. {
  161. $aArgs[$sParam] = $value;
  162. }
  163. else
  164. {
  165. $aArgs[$sParam] = '';
  166. }
  167. }
  168. $oFilter->SetInternalParams($aArgs);
  169. }
  170. elseif ($sSyntaxError)
  171. {
  172. // Query arguments taken from the page args
  173. }
  174. }
  175. $oP->add("<form method=\"post\">\n");
  176. $oP->add(Dict::S('UI:RunQuery:ExpressionToEvaluate')."<br/>\n");
  177. $oP->add("<textarea cols=\"120\" rows=\"8\" name=\"expression\">".htmlentities($sExpression, ENT_QUOTES, 'UTF-8')."</textarea>\n");
  178. if (count($aArgs) > 0)
  179. {
  180. $oP->add("<div class=\"wizContainer\">\n");
  181. $oP->add("<h3>Query arguments</h3>\n");
  182. foreach($aArgs as $sParam => $sValue)
  183. {
  184. $oP->p("$sParam: <input type=\"string\" name=\"arg_$sParam\" value=\"$sValue\">\n");
  185. }
  186. $oP->add("</div>\n");
  187. }
  188. $oP->add("<input type=\"submit\" value=\"".Dict::S('UI:Button:Evaluate')."\">\n");
  189. $oP->add($oAppContext->GetForForm());
  190. $oP->add("</form>\n");
  191. if ($oFilter)
  192. {
  193. $oP->add("<h3>Query results</h3>\n");
  194. $oResultBlock = new DisplayBlock($oFilter, 'list', false);
  195. $oResultBlock->Display($oP, 'runquery');
  196. $oP->p('');
  197. $oP->StartCollapsibleSection(Dict::S('UI:RunQuery:MoreInfo'), false);
  198. $oP->p(Dict::S('UI:RunQuery:DevelopedQuery').htmlentities($oFilter->ToOQL(), ENT_QUOTES, 'UTF-8'));
  199. $oP->p(Dict::S('UI:RunQuery:SerializedFilter').$oFilter->serialize());
  200. $oP->EndCollapsibleSection();
  201. }
  202. elseif ($sSyntaxError)
  203. {
  204. if ($e instanceof OqlException)
  205. {
  206. $sWrongWord = $e->GetWrongWord();
  207. $aSuggestedWords = $e->GetSuggestions();
  208. if (count($aSuggestedWords) > 0)
  209. {
  210. $sSuggestedWord = OqlException::FindClosestString($sWrongWord, $aSuggestedWords);
  211. if (strlen($sSuggestedWord) > 0)
  212. {
  213. $oP->p('<b>'.Dict::Format('UI:RunQuery:Error', $e->GetIssue().' <em>'.$sWrongWord).'</em></b>');
  214. $sBefore = substr($sExpression, 0, $e->GetColumn());
  215. $sAfter = substr($sExpression, $e->GetColumn() + strlen($sWrongWord));
  216. $sFixedExpression = $sBefore.$sSuggestedWord.$sAfter;
  217. $sFixedExpressionHtml = $sBefore.'<span style="background-color:yellow">'.$sSuggestedWord.'</span>'.$sAfter;
  218. $oP->p("Suggesting: $sFixedExpressionHtml");
  219. $oP->add('<button onClick="$(\'textarea[name=expression]\').val(\''.htmlentities(addslashes($sFixedExpression)).'\');">Use this query</button>');
  220. }
  221. else
  222. {
  223. $oP->p('<b>'.Dict::Format('UI:RunQuery:Error', $e->getHtmlDesc()).'</b>');
  224. }
  225. }
  226. else
  227. {
  228. $oP->p('<b>'.Dict::Format('UI:RunQuery:Error', $e->getHtmlDesc()).'</b>');
  229. }
  230. }
  231. else
  232. {
  233. $oP->p('<b>'.Dict::Format('UI:RunQuery:Error', $e->getMessage()).'</b>');
  234. }
  235. }
  236. }
  237. catch(Exception $e)
  238. {
  239. $oP->p('<b>'.Dict::Format('UI:RunQuery:Error', $e->getMessage()).'</b>');
  240. }
  241. $oP->output();
  242. ?>