run_query.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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. if ($oFilter)
  130. {
  131. $aArgs = array();
  132. foreach($oFilter->GetQueryParams() as $sParam => $foo)
  133. {
  134. $value = utils::ReadParam('arg_'.$sParam, null, true, 'raw_data');
  135. if (!is_null($value))
  136. {
  137. $aArgs[$sParam] = $value;
  138. }
  139. else
  140. {
  141. $aArgs[$sParam] = '';
  142. }
  143. }
  144. $oFilter->SetInternalParams($aArgs);
  145. }
  146. elseif ($sSyntaxError)
  147. {
  148. // Query arguments taken from the page args
  149. }
  150. }
  151. $oP->add("<form method=\"post\">\n");
  152. $oP->add(Dict::S('UI:RunQuery:ExpressionToEvaluate')."<br/>\n");
  153. $oP->add("<textarea cols=\"120\" rows=\"8\" name=\"expression\">".htmlentities($sExpression, ENT_QUOTES, 'UTF-8')."</textarea>\n");
  154. if (count($aArgs) > 0)
  155. {
  156. $oP->add("<div class=\"wizContainer\">\n");
  157. $oP->add("<h3>Query arguments</h3>\n");
  158. foreach($aArgs as $sParam => $sValue)
  159. {
  160. $oP->p("$sParam: <input type=\"string\" name=\"arg_$sParam\" value=\"$sValue\">\n");
  161. }
  162. $oP->add("</div>\n");
  163. }
  164. $oP->add("<input type=\"submit\" value=\"".Dict::S('UI:Button:Evaluate')."\">\n");
  165. $oP->add($oAppContext->GetForForm());
  166. $oP->add("</form>\n");
  167. if ($oFilter)
  168. {
  169. $oP->add("<h3>Query results</h3>\n");
  170. $oResultBlock = new DisplayBlock($oFilter, 'list', false);
  171. $oResultBlock->Display($oP, 'runquery');
  172. // Breadcrumb
  173. //$iCount = $oResultBlock->GetDisplayedCount();
  174. $sPageId = "ui-search-".$oFilter->GetClass();
  175. $sLabel = MetaModel::GetName($oFilter->GetClass());
  176. $aArgs = array();
  177. foreach (array_merge($_POST, $_GET) as $sKey => $value)
  178. {
  179. if (is_array($value))
  180. {
  181. $aItems = array();
  182. foreach($value as $sItemKey => $sItemValue)
  183. {
  184. $aArgs[] = $sKey.'['.$sItemKey.']='.urlencode($sItemValue);
  185. }
  186. }
  187. else
  188. {
  189. $aArgs[] = $sKey.'='.urlencode($value);
  190. }
  191. }
  192. $sUrl = utils::GetAbsoluteUrlAppRoot().'pages/run_query.php?'.implode('&', $aArgs);
  193. $oP->SetBreadCrumbEntry($sPageId, $sLabel, $oFilter->ToOQL(true), $sUrl, '../images/breadcrumb-search.png');
  194. $oP->p('');
  195. $oP->StartCollapsibleSection(Dict::S('UI:RunQuery:MoreInfo'), false);
  196. $oP->p(Dict::S('UI:RunQuery:DevelopedQuery').htmlentities($oFilter->ToOQL(), ENT_QUOTES, 'UTF-8'));
  197. $oP->p(Dict::S('UI:RunQuery:SerializedFilter').$oFilter->serialize());
  198. $oP->EndCollapsibleSection();
  199. }
  200. elseif ($sSyntaxError)
  201. {
  202. if ($e instanceof OqlException)
  203. {
  204. $sWrongWord = $e->GetWrongWord();
  205. $aSuggestedWords = $e->GetSuggestions();
  206. if (count($aSuggestedWords) > 0)
  207. {
  208. $sSuggestedWord = OqlException::FindClosestString($sWrongWord, $aSuggestedWords);
  209. if (strlen($sSuggestedWord) > 0)
  210. {
  211. $oP->p('<b>'.Dict::Format('UI:RunQuery:Error', $e->GetIssue().' <em>'.$sWrongWord).'</em></b>');
  212. $sBefore = substr($sExpression, 0, $e->GetColumn());
  213. $sAfter = substr($sExpression, $e->GetColumn() + strlen($sWrongWord));
  214. $sFixedExpression = $sBefore.$sSuggestedWord.$sAfter;
  215. $sFixedExpressionHtml = $sBefore.'<span style="background-color:yellow">'.$sSuggestedWord.'</span>'.$sAfter;
  216. $oP->p("Suggesting: $sFixedExpressionHtml");
  217. $oP->add('<button onClick="$(\'textarea[name=expression]\').val(\''.htmlentities(addslashes($sFixedExpression)).'\');">Use this query</button>');
  218. }
  219. else
  220. {
  221. $oP->p('<b>'.Dict::Format('UI:RunQuery:Error', $e->getHtmlDesc()).'</b>');
  222. }
  223. }
  224. else
  225. {
  226. $oP->p('<b>'.Dict::Format('UI:RunQuery:Error', $e->getHtmlDesc()).'</b>');
  227. }
  228. }
  229. else
  230. {
  231. $oP->p('<b>'.Dict::Format('UI:RunQuery:Error', $e->getMessage()).'</b>');
  232. }
  233. }
  234. }
  235. catch(Exception $e)
  236. {
  237. $oP->p('<b>'.Dict::Format('UI:RunQuery:Error', $e->getMessage()).'</b>');
  238. }
  239. $oP->output();
  240. ?>