audit.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. * Execute and shows the data quality audit
  20. *
  21. * @copyright Copyright (C) 2010-2016 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(DBSearch &$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->Intersect($oDefinitionFilter);
  92. }
  93. else
  94. {
  95. // The query returns only the valid elements, all the others are invalid
  96. $aValidRows = $oRuleFilter->ToDataArray(array('id'));
  97. $aValidIds = array();
  98. foreach($aValidRows as $aRow)
  99. {
  100. $aValidIds[] = $aRow['id'];
  101. }
  102. $oFilter = $oDefinitionFilter->DeepClone();
  103. if (count($aValidIds) > 0)
  104. {
  105. $aInDefSet = array();
  106. foreach($oDefinitionFilter->ToDataArray(array('id')) as $aRow)
  107. {
  108. $aInDefSet[] = $aRow['id'];
  109. }
  110. $aInvalids = array_diff($aInDefSet, $aValidIds);
  111. if (count($aInvalids) > 0)
  112. {
  113. $oFilter->AddCondition('id', $aInvalids, 'IN');
  114. }
  115. else
  116. {
  117. $oFilter->AddCondition('id', 0, '=');
  118. }
  119. }
  120. }
  121. return $oFilter;
  122. }
  123. function GetReportColor($iTotal, $iErrors)
  124. {
  125. $sResult = 'red';
  126. if ( ($iTotal == 0) || ($iErrors / $iTotal) <= 0.05 )
  127. {
  128. $sResult = 'green';
  129. }
  130. else if ( ($iErrors / $iTotal) <= 0.25 )
  131. {
  132. $sResult = 'orange';
  133. }
  134. return $sResult;
  135. }
  136. try
  137. {
  138. require_once('../approot.inc.php');
  139. require_once(APPROOT.'/application/application.inc.php');
  140. require_once(APPROOT.'/application/itopwebpage.class.inc.php');
  141. require_once(APPROOT.'/application/csvpage.class.inc.php');
  142. require_once(APPROOT.'/application/startup.inc.php');
  143. $operation = utils::ReadParam('operation', '');
  144. $oAppContext = new ApplicationContext();
  145. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  146. LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  147. $oP = new iTopWebPage(Dict::S('UI:Audit:Title'));
  148. switch($operation)
  149. {
  150. case 'csv':
  151. $oP->DisableBreadCrumb();
  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. $sTitle = 'Audit Errors';
  211. $oP->SetBreadCrumbEntry('ui-tool-auditerrors', $sTitle, '', '', utils::GetAbsoluteUrlAppRoot().'images/wrench.png');
  212. $iCategory = utils::ReadParam('category', '');
  213. $iRuleIndex = utils::ReadParam('rule', 0);
  214. $oAuditCategory = MetaModel::GetObject('AuditCategory', $iCategory);
  215. $oDefinitionFilter = DBObjectSearch::FromOQL($oAuditCategory->Get('definition_set'));
  216. FilterByContext($oDefinitionFilter, $oAppContext);
  217. $oDefinitionSet = new CMDBObjectSet($oDefinitionFilter);
  218. $oFilter = GetRuleResultFilter($iRuleIndex, $oDefinitionFilter, $oAppContext);
  219. $oErrorObjectSet = new CMDBObjectSet($oFilter);
  220. $oAuditRule = MetaModel::GetObject('AuditRule', $iRuleIndex);
  221. $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>');
  222. $oP->p('<a href="./audit.php?'.$oAppContext->GetForLink().'">[Back to audit results]</a>');
  223. $sBlockId = 'audit_errors';
  224. $oP->p("<div id=\"$sBlockId\" style=\"clear:both\">\n");
  225. $oBlock = DisplayBlock::FromObjectSet($oErrorObjectSet, 'list');
  226. $oBlock->Display($oP, 1);
  227. $oP->p("</div>\n");
  228. $sExportUrl = utils::GetAbsoluteUrlAppRoot()."pages/audit.php?operation=csv&category=".$oAuditCategory->GetKey()."&rule=".$oAuditRule->GetKey();
  229. $oP->add_ready_script("$('a[href*=\"pages/UI.php?operation=search\"]').attr('href', '".$sExportUrl."')");
  230. break;
  231. case 'audit':
  232. default:
  233. $oP->SetBreadCrumbEntry('ui-tool-audit', Dict::S('Menu:Audit'), Dict::S('UI:Audit:InteractiveAudit'), '', utils::GetAbsoluteUrlAppRoot().'images/wrench.png');
  234. $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>');
  235. $oAuditFilter = new DBObjectSearch('AuditCategory');
  236. $oCategoriesSet = new DBObjectSet($oAuditFilter);
  237. $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");
  238. $oP->add("<tr><td>\n");
  239. $oP->add("<table>\n");
  240. $oP->add("<tr>\n");
  241. $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");
  242. $oP->add("</tr>\n");
  243. while($oAuditCategory = $oCategoriesSet->fetch())
  244. {
  245. try
  246. {
  247. $oDefinitionFilter = DBObjectSearch::FromOQL($oAuditCategory->Get('definition_set'));
  248. FilterByContext($oDefinitionFilter, $oAppContext);
  249. $aObjectsWithErrors = array();
  250. if (!empty($currentOrganization))
  251. {
  252. if (MetaModel::IsValidFilterCode($oDefinitionFilter->GetClass(), 'org_id'))
  253. {
  254. $oDefinitionFilter->AddCondition('org_id', $currentOrganization, '=');
  255. }
  256. }
  257. $aResults = array();
  258. $oDefinitionSet = new CMDBObjectSet($oDefinitionFilter);
  259. $iCount = $oDefinitionSet->Count();
  260. $oRulesFilter = new DBObjectSearch('AuditRule');
  261. $oRulesFilter->AddCondition('category_id', $oAuditCategory->GetKey(), '=');
  262. $oRulesSet = new DBObjectSet($oRulesFilter);
  263. while($oAuditRule = $oRulesSet->fetch() )
  264. {
  265. $aRow = array();
  266. $aRow['description'] = $oAuditRule->GetName();
  267. if ($iCount == 0)
  268. {
  269. // nothing to check, really !
  270. $aRow['nb_errors'] = "<a href=\"audit.php?operation=errors&category=".$oAuditCategory->GetKey()."&rule=".$oAuditRule->GetKey()."\">0</a>";
  271. $aRow['percent_ok'] = '100.00';
  272. $aRow['class'] = GetReportColor($iCount, 0);
  273. }
  274. else
  275. {
  276. try
  277. {
  278. $oFilter = GetRuleResultFilter($oAuditRule->GetKey(), $oDefinitionFilter, $oAppContext);
  279. $aErrors = $oFilter->ToDataArray(array('id'));
  280. $iErrorsCount = count($aErrors);
  281. foreach($aErrors as $aErrorRow)
  282. {
  283. $aObjectsWithErrors[$aErrorRow['id']] = true;
  284. }
  285. $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>";
  286. $aRow['percent_ok'] = sprintf('%.2f', 100.0 * (($iCount - $iErrorsCount) / $iCount));
  287. $aRow['class'] = GetReportColor($iCount, $iErrorsCount);
  288. }
  289. catch(Exception $e)
  290. {
  291. $aRow['nb_errors'] = "OQL Error";
  292. $aRow['percent_ok'] = 'n/a';
  293. $aRow['class'] = 'red';
  294. $sMessage = Dict::Format('UI:Audit:ErrorIn_Rule_Reason', $oAuditRule->GetHyperlink(), $e->getMessage());
  295. $oP->p("<img style=\"vertical-align:middle\" src=\"../images/stop-mid.png\"/>&nbsp;".$sMessage);
  296. }
  297. }
  298. $aResults[] = $aRow;
  299. }
  300. $iTotalErrors = count($aObjectsWithErrors);
  301. $sOverallPercentOk = ($iCount == 0) ? '100.00' : sprintf('%.2f', 100.0 * (($iCount - $iTotalErrors) / $iCount));
  302. $sClass = GetReportColor($iCount, $iTotalErrors);
  303. }
  304. catch(Exception $e)
  305. {
  306. $aRow = array();
  307. $aRow['description'] = "OQL error";
  308. $aRow['nb_errors'] = "n/a";
  309. $aRow['percent_ok'] = '';
  310. $aRow['class'] = 'red';
  311. $sMessage = Dict::Format('UI:Audit:ErrorIn_Category_Reason', $oAuditCategory->GetHyperlink(), $e->getMessage());
  312. $oP->p("<img style=\"vertical-align:middle\" src=\"../images/stop-mid.png\"/>&nbsp;".$sMessage);
  313. $aResults[] = $aRow;
  314. $sClass = 'red';
  315. $iTotalErrors = 'n/a';
  316. $sOverallPercentOk = '';
  317. }
  318. $oP->add("<tr>\n");
  319. $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");
  320. $oP->add("</tr>\n");
  321. foreach($aResults as $aRow)
  322. {
  323. $oP->add("<tr>\n");
  324. $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");
  325. $oP->add("</tr>\n");
  326. }
  327. }
  328. $oP->add("</table>\n");
  329. $oP->add("</td></tr>\n");
  330. $oP->add("</table>\n");
  331. }
  332. $oP->output();
  333. }
  334. catch(CoreException $e)
  335. {
  336. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  337. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  338. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  339. $oP->error(Dict::Format('UI:Error_Details', $e->getHtmlDesc()));
  340. $oP->output();
  341. if (MetaModel::IsLogEnabledIssue())
  342. {
  343. if (MetaModel::IsValidClass('EventIssue'))
  344. {
  345. $oLog = new EventIssue();
  346. $oLog->Set('message', $e->getMessage());
  347. $oLog->Set('userinfo', '');
  348. $oLog->Set('issue', $e->GetIssue());
  349. $oLog->Set('impact', 'Page could not be displayed');
  350. $oLog->Set('callstack', $e->getTrace());
  351. $oLog->Set('data', $e->getContextData());
  352. $oLog->DBInsertNoReload();
  353. }
  354. IssueLog::Error($e->getMessage());
  355. }
  356. // For debugging only
  357. //throw $e;
  358. }
  359. catch(Exception $e)
  360. {
  361. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  362. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  363. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  364. $oP->error(Dict::Format('UI:Error_Details', $e->getMessage()));
  365. $oP->output();
  366. if (MetaModel::IsLogEnabledIssue())
  367. {
  368. if (MetaModel::IsValidClass('EventIssue'))
  369. {
  370. $oLog = new EventIssue();
  371. $oLog->Set('message', $e->getMessage());
  372. $oLog->Set('userinfo', '');
  373. $oLog->Set('issue', 'PHP Exception');
  374. $oLog->Set('impact', 'Page could not be displayed');
  375. $oLog->Set('callstack', $e->getTrace());
  376. $oLog->Set('data', array());
  377. $oLog->DBInsertNoReload();
  378. }
  379. IssueLog::Error($e->getMessage());
  380. }
  381. }
  382. ?>