audit.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. <?php
  2. // Copyright (C) 2010-2012 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. * Execute and shows the data quality audit
  20. *
  21. * @copyright Copyright (C) 2010-2012 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. /**
  25. * Adds the context parameters to the audit query
  26. */
  27. function FilterByContext(DBObjectSearch &$oFilter, ApplicationContext $oAppContext)
  28. {
  29. $sObjClass = $oFilter->GetClass();
  30. $aContextParams = $oAppContext->GetNames();
  31. $aCallSpec = array($sObjClass, 'MapContextParam');
  32. if (is_callable($aCallSpec))
  33. {
  34. foreach($aContextParams as $sParamName)
  35. {
  36. $sValue = $oAppContext->GetCurrentValue($sParamName, null);
  37. if ($sValue != null)
  38. {
  39. $sAttCode = call_user_func($aCallSpec, $sParamName); // Returns null when there is no mapping for this parameter
  40. if ( ($sAttCode != null) && MetaModel::IsValidAttCode($sObjClass, $sAttCode))
  41. {
  42. // Check if the condition points to a hierarchical key
  43. if ($sAttCode == 'id')
  44. {
  45. // Filtering on the objects themselves
  46. $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass($sObjClass);
  47. if ($sHierarchicalKeyCode !== false)
  48. {
  49. $oRootFilter = new DBObjectSearch($sObjClass);
  50. $oRootFilter->AddCondition($sAttCode, $sValue);
  51. $oFilter->AddCondition_PointingTo($oRootFilter, $sHierarchicalKeyCode, TREE_OPERATOR_BELOW); // Use the 'below' operator by default
  52. $bConditionAdded = true;
  53. }
  54. }
  55. else
  56. {
  57. $oAttDef = MetaModel::GetAttributeDef($sObjClass, $sAttCode);
  58. $bConditionAdded = false;
  59. if ($oAttDef->IsExternalKey())
  60. {
  61. $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass($oAttDef->GetTargetClass());
  62. if ($sHierarchicalKeyCode !== false)
  63. {
  64. $oRootFilter = new DBObjectSearch($oAttDef->GetTargetClass());
  65. $oRootFilter->AddCondition('id', $sValue);
  66. $oHKFilter = new DBObjectSearch($oAttDef->GetTargetClass());
  67. $oHKFilter->AddCondition_PointingTo($oRootFilter, $sHierarchicalKeyCode, TREE_OPERATOR_BELOW); // Use the 'below' operator by default
  68. $oFilter->AddCondition_PointingTo($oHKFilter, $sAttCode);
  69. $bConditionAdded = true;
  70. }
  71. }
  72. }
  73. if (!$bConditionAdded)
  74. {
  75. $oFilter->AddCondition($sAttCode, $sValue);
  76. }
  77. }
  78. }
  79. }
  80. }
  81. }
  82. function GetRuleResultFilter($iRuleId, $oDefinitionFilter, $oAppContext)
  83. {
  84. $oRule = MetaModel::GetObject('AuditRule', $iRuleId);
  85. $sOql = $oRule->Get('query');
  86. $oRuleFilter = DBObjectSearch::FromOQL($sOql);
  87. FilterByContext($oRuleFilter, $oAppContext); // Not needed since this filter is a subset of the definition filter, but may speedup things
  88. if ($oRule->Get('valid_flag') == 'false')
  89. {
  90. // The query returns directly the invalid elements
  91. $oFilter = $oRuleFilter;
  92. $oFilter->MergeWith($oDefinitionFilter);
  93. }
  94. else
  95. {
  96. // The query returns only the valid elements, all the others are invalid
  97. $aValidRows = $oRuleFilter->ToDataArray(array('id'));
  98. $aValidIds = array();
  99. foreach($aValidRows as $aRow)
  100. {
  101. $aValidIds[] = $aRow['id'];
  102. }
  103. $oFilter = $oDefinitionFilter->DeepClone();
  104. if (count($aValidIds) > 0)
  105. {
  106. $aInDefSet = array();
  107. foreach($oDefinitionFilter->ToDataArray(array('id')) as $aRow)
  108. {
  109. $aInDefSet[] = $aRow['id'];
  110. }
  111. $aInvalids = array_diff($aInDefSet, $aValidIds);
  112. if (count($aInvalids) > 0)
  113. {
  114. $oFilter->AddCondition('id', $aInvalids, 'IN');
  115. }
  116. else
  117. {
  118. $oFilter->AddCondition('id', 0, '=');
  119. }
  120. }
  121. }
  122. return $oFilter;
  123. }
  124. function GetReportColor($iTotal, $iErrors)
  125. {
  126. $sResult = 'red';
  127. if ( ($iTotal == 0) || ($iErrors / $iTotal) <= 0.05 )
  128. {
  129. $sResult = 'green';
  130. }
  131. else if ( ($iErrors / $iTotal) <= 0.25 )
  132. {
  133. $sResult = 'orange';
  134. }
  135. return $sResult;
  136. }
  137. try
  138. {
  139. require_once('../approot.inc.php');
  140. require_once(APPROOT.'/application/application.inc.php');
  141. require_once(APPROOT.'/application/itopwebpage.class.inc.php');
  142. require_once(APPROOT.'/application/csvpage.class.inc.php');
  143. require_once(APPROOT.'/application/startup.inc.php');
  144. $operation = utils::ReadParam('operation', '');
  145. $oAppContext = new ApplicationContext();
  146. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  147. LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  148. $oP = new iTopWebPage(Dict::S('UI:Audit:Title'));
  149. switch($operation)
  150. {
  151. case 'csv':
  152. // Big result sets cause long OQL that cannot be passed (serialized) as a GET parameter
  153. // Therefore we don't use the standard "search_oql" operation of UI.php to display the CSV
  154. $iCategory = utils::ReadParam('category', '');
  155. $iRuleIndex = utils::ReadParam('rule', 0);
  156. $oAuditCategory = MetaModel::GetObject('AuditCategory', $iCategory);
  157. $oDefinitionFilter = DBObjectSearch::FromOQL($oAuditCategory->Get('definition_set'));
  158. FilterByContext($oDefinitionFilter, $oAppContext);
  159. $oDefinitionSet = new CMDBObjectSet($oDefinitionFilter);
  160. $oFilter = GetRuleResultFilter($iRuleIndex, $oDefinitionFilter, $oAppContext);
  161. $oErrorObjectSet = new CMDBObjectSet($oFilter);
  162. $oAuditRule = MetaModel::GetObject('AuditRule', $iRuleIndex);
  163. $sFileName = utils::ReadParam('filename', null, true, 'string');
  164. $bAdvanced = utils::ReadParam('advanced', false);
  165. $sAdvanced = $bAdvanced ? '&advanced=1' : '';
  166. if ($sFileName != null)
  167. {
  168. $oP = new CSVPage("iTop - Export");
  169. $sCharset = MetaModel::GetConfig()->Get('csv_file_default_charset');
  170. $sCSVData = cmdbAbstractObject::GetSetAsCSV($oErrorObjectSet, array('localize_values' => true, 'fields_advanced' => $bAdvanced), $sCharset);
  171. if ($sCharset == 'UTF-8')
  172. {
  173. $sOutputData = UTF8_BOM.$sCSVData;
  174. }
  175. else
  176. {
  177. $sOutputData = $sCSVData;
  178. }
  179. if ($sFileName == '')
  180. {
  181. // Plain text => Firefox will NOT propose to download the file
  182. $oP->add_header("Content-type: text/plain; charset=$sCharset");
  183. }
  184. else
  185. {
  186. $oP->add_header("Content-type: text/csv; charset=$sCharset");
  187. }
  188. $oP->add($sOutputData);
  189. $oP->TrashUnexpectedOutput();
  190. $oP->output();
  191. exit;
  192. }
  193. else
  194. {
  195. $oP->add('<div class="page_header"><h1>Audit Errors: <span class="hilite">'.$oAuditRule->Get('description').'</span></h1><img style="margin-top: -20px; margin-right: 10px; float: right;" src="../images/stop.png"/></div>');
  196. $oP->p('<a href="./audit.php?'.$oAppContext->GetForLink().'">[Back to audit results]</a>');
  197. $sBlockId = 'audit_errors';
  198. $oP->p("<div id=\"$sBlockId\" style=\"clear:both\">\n");
  199. $oBlock = DisplayBlock::FromObjectSet($oErrorObjectSet, 'csv');
  200. $oBlock->Display($oP, 1);
  201. $oP->p("</div>\n");
  202. // Adjust the size of the Textarea containing the CSV to fit almost all the remaining space
  203. $oP->add_ready_script(" $('#1>textarea').height(400);"); // adjust the size of the block
  204. $sExportUrl = utils::GetAbsoluteUrlAppRoot()."pages/audit.php?operation=csv&category=".$oAuditCategory->GetKey()."&rule=".$oAuditRule->GetKey();
  205. $oP->add_ready_script("$('a[href*=\"webservices/export.php?expression=\"]').attr('href', '".$sExportUrl."&filename=audit.csv".$sAdvanced."');");
  206. $oP->add_ready_script("$('#1 :checkbox').removeAttr('onclick').click( function() { var sAdvanced = ''; if (this.checked) sAdvanced = '&advanced=1'; window.location.href='$sExportUrl'+sAdvanced; } );");
  207. }
  208. break;
  209. case 'errors':
  210. $iCategory = utils::ReadParam('category', '');
  211. $iRuleIndex = utils::ReadParam('rule', 0);
  212. $oAuditCategory = MetaModel::GetObject('AuditCategory', $iCategory);
  213. $oDefinitionFilter = DBObjectSearch::FromOQL($oAuditCategory->Get('definition_set'));
  214. FilterByContext($oDefinitionFilter, $oAppContext);
  215. $oDefinitionSet = new CMDBObjectSet($oDefinitionFilter);
  216. $oFilter = GetRuleResultFilter($iRuleIndex, $oDefinitionFilter, $oAppContext);
  217. $oErrorObjectSet = new CMDBObjectSet($oFilter);
  218. $oAuditRule = MetaModel::GetObject('AuditRule', $iRuleIndex);
  219. $oP->add('<div class="page_header"><h1>Audit Errors: <span class="hilite">'.$oAuditRule->Get('description').'</span></h1><img style="margin-top: -20px; margin-right: 10px; float: right;" src="../images/stop.png"/></div>');
  220. $oP->p('<a href="./audit.php?'.$oAppContext->GetForLink().'">[Back to audit results]</a>');
  221. $sBlockId = 'audit_errors';
  222. $oP->p("<div id=\"$sBlockId\" style=\"clear:both\">\n");
  223. $oBlock = DisplayBlock::FromObjectSet($oErrorObjectSet, 'list');
  224. $oBlock->Display($oP, 1);
  225. $oP->p("</div>\n");
  226. $sExportUrl = utils::GetAbsoluteUrlAppRoot()."pages/audit.php?operation=csv&category=".$oAuditCategory->GetKey()."&rule=".$oAuditRule->GetKey();
  227. $oP->add_ready_script("$('a[href*=\"pages/UI.php?operation=search\"]').attr('href', '".$sExportUrl."')");
  228. break;
  229. case 'audit':
  230. default:
  231. $oP->add('<div class="page_header"><h1>'.Dict::S('UI:Audit:InteractiveAudit').'</h1><img style="margin-top: -20px; margin-right: 10px; float: right;" src="../images/clean.png"/></div>');
  232. $oAuditFilter = new CMDBSearchFilter('AuditCategory');
  233. $oCategoriesSet = new DBObjectSet($oAuditFilter);
  234. $oP->add("<table style=\"margin-top: 1em; padding: 0px; border-top: 3px solid #f6f6f1; border-left: 3px solid #f6f6f1; border-bottom: 3px solid #e6e6e1; border-right: 3px solid #e6e6e1;\">\n");
  235. $oP->add("<tr><td>\n");
  236. $oP->add("<table>\n");
  237. $oP->add("<tr>\n");
  238. $oP->add("<th><img src=\"../images/minus.gif\"></th><th class=\"alignLeft\">".Dict::S('UI:Audit:HeaderAuditRule')."</th><th>".Dict::S('UI:Audit:HeaderNbObjects')."</th><th>".Dict::S('UI:Audit:HeaderNbErrors')."</th><th>".Dict::S('UI:Audit:PercentageOk')."</th>\n");
  239. $oP->add("</tr>\n");
  240. while($oAuditCategory = $oCategoriesSet->fetch())
  241. {
  242. try
  243. {
  244. $oDefinitionFilter = DBObjectSearch::FromOQL($oAuditCategory->Get('definition_set'));
  245. FilterByContext($oDefinitionFilter, $oAppContext);
  246. $aObjectsWithErrors = array();
  247. if (!empty($currentOrganization))
  248. {
  249. if (MetaModel::IsValidFilterCode($oDefinitionFilter->GetClass(), 'org_id'))
  250. {
  251. $oDefinitionFilter->AddCondition('org_id', $currentOrganization, '=');
  252. }
  253. }
  254. $aResults = array();
  255. $oDefinitionSet = new CMDBObjectSet($oDefinitionFilter);
  256. $iCount = $oDefinitionSet->Count();
  257. $oRulesFilter = new CMDBSearchFilter('AuditRule');
  258. $oRulesFilter->AddCondition('category_id', $oAuditCategory->GetKey(), '=');
  259. $oRulesSet = new DBObjectSet($oRulesFilter);
  260. while($oAuditRule = $oRulesSet->fetch() )
  261. {
  262. $aRow = array();
  263. $aRow['description'] = $oAuditRule->GetName();
  264. if ($iCount == 0)
  265. {
  266. // nothing to check, really !
  267. $aRow['nb_errors'] = "<a href=\"audit.php?operation=errors&category=".$oAuditCategory->GetKey()."&rule=".$oAuditRule->GetKey()."\">0</a>";
  268. $aRow['percent_ok'] = '100.00';
  269. $aRow['class'] = GetReportColor($iCount, 0);
  270. }
  271. else
  272. {
  273. try
  274. {
  275. $oFilter = GetRuleResultFilter($oAuditRule->GetKey(), $oDefinitionFilter, $oAppContext);
  276. $aErrors = $oFilter->ToDataArray(array('id'));
  277. $iErrorsCount = count($aErrors);
  278. foreach($aErrors as $aErrorRow)
  279. {
  280. $aObjectsWithErrors[$aErrorRow['id']] = true;
  281. }
  282. $aRow['nb_errors'] = ($iErrorsCount == 0) ? '0' : "<a href=\"?operation=errors&category=".$oAuditCategory->GetKey()."&rule=".$oAuditRule->GetKey()."&".$oAppContext->GetForLink()."\">$iErrorsCount</a> <a href=\"?operation=csv&category=".$oAuditCategory->GetKey()."&rule=".$oAuditRule->GetKey()."&".$oAppContext->GetForLink()."\">(CSV)</a>";
  283. $aRow['percent_ok'] = sprintf('%.2f', 100.0 * (($iCount - $iErrorsCount) / $iCount));
  284. $aRow['class'] = GetReportColor($iCount, $iErrorsCount);
  285. }
  286. catch(Exception $e)
  287. {
  288. $aRow['nb_errors'] = "OQL Error";
  289. $aRow['percent_ok'] = 'n/a';
  290. $aRow['class'] = 'red';
  291. $sMessage = Dict::Format('UI:Audit:ErrorIn_Rule_Reason', $oAuditRule->GetHyperlink(), $e->getMessage());
  292. $oP->p("<img style=\"vertical-align:middle\" src=\"../images/stop-mid.png\"/>&nbsp;".$sMessage);
  293. }
  294. }
  295. $aResults[] = $aRow;
  296. $iTotalErrors = count($aObjectsWithErrors);
  297. $sOverallPercentOk = ($iCount == 0) ? '100.00' : sprintf('%.2f', 100.0 * (($iCount - $iTotalErrors) / $iCount));
  298. $sClass = GetReportColor($iCount, $iTotalErrors);
  299. }
  300. }
  301. catch(Exception $e)
  302. {
  303. $aRow = array();
  304. $aRow['description'] = "OQL error";
  305. $aRow['nb_errors'] = "n/a";
  306. $aRow['percent_ok'] = '';
  307. $aRow['class'] = 'red';
  308. $sMessage = Dict::Format('UI:Audit:ErrorIn_Category_Reason', $oAuditCategory->GetHyperlink(), $e->getMessage());
  309. $oP->p("<img style=\"vertical-align:middle\" src=\"../images/stop-mid.png\"/>&nbsp;".$sMessage);
  310. $aResults[] = $aRow;
  311. }
  312. $oP->add("<tr>\n");
  313. $oP->add("<th><img src=\"../images/minus.gif\"></th><th class=\"alignLeft\">".$oAuditCategory->GetName()."</th><th class=\"alignRight\">$iCount</th><th class=\"alignRight\">$iTotalErrors</th><th class=\"alignRight $sClass\">$sOverallPercentOk %</th>\n");
  314. $oP->add("</tr>\n");
  315. foreach($aResults as $aRow)
  316. {
  317. $oP->add("<tr>\n");
  318. $oP->add("<td>&nbsp;</td><td colspan=\"2\">".$aRow['description']."</td><td class=\"alignRight\">".$aRow['nb_errors']."</td><td class=\"alignRight ".$aRow['class']."\">".$aRow['percent_ok']." %</td>\n");
  319. $oP->add("</tr>\n");
  320. }
  321. }
  322. $oP->add("</table>\n");
  323. $oP->add("</td></tr>\n");
  324. $oP->add("</table>\n");
  325. }
  326. $oP->output();
  327. }
  328. catch(CoreException $e)
  329. {
  330. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  331. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  332. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  333. $oP->error(Dict::Format('UI:Error_Details', $e->getHtmlDesc()));
  334. $oP->output();
  335. if (MetaModel::IsLogEnabledIssue())
  336. {
  337. if (MetaModel::IsValidClass('EventIssue'))
  338. {
  339. $oLog = new EventIssue();
  340. $oLog->Set('message', $e->getMessage());
  341. $oLog->Set('userinfo', '');
  342. $oLog->Set('issue', $e->GetIssue());
  343. $oLog->Set('impact', 'Page could not be displayed');
  344. $oLog->Set('callstack', $e->getTrace());
  345. $oLog->Set('data', $e->getContextData());
  346. $oLog->DBInsertNoReload();
  347. }
  348. IssueLog::Error($e->getMessage());
  349. }
  350. // For debugging only
  351. //throw $e;
  352. }
  353. catch(Exception $e)
  354. {
  355. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  356. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  357. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  358. $oP->error(Dict::Format('UI:Error_Details', $e->getMessage()));
  359. $oP->output();
  360. if (MetaModel::IsLogEnabledIssue())
  361. {
  362. if (MetaModel::IsValidClass('EventIssue'))
  363. {
  364. $oLog = new EventIssue();
  365. $oLog->Set('message', $e->getMessage());
  366. $oLog->Set('userinfo', '');
  367. $oLog->Set('issue', 'PHP Exception');
  368. $oLog->Set('impact', 'Page could not be displayed');
  369. $oLog->Set('callstack', $e->getTrace());
  370. $oLog->Set('data', array());
  371. $oLog->DBInsertNoReload();
  372. }
  373. IssueLog::Error($e->getMessage());
  374. }
  375. }
  376. ?>