audit.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. <?php
  2. // Copyright (C) 2010-2015 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-2015 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. // Big result sets cause long OQL that cannot be passed (serialized) as a GET parameter
  152. // Therefore we don't use the standard "search_oql" operation of UI.php to display the CSV
  153. $iCategory = utils::ReadParam('category', '');
  154. $iRuleIndex = utils::ReadParam('rule', 0);
  155. $oAuditCategory = MetaModel::GetObject('AuditCategory', $iCategory);
  156. $oDefinitionFilter = DBObjectSearch::FromOQL($oAuditCategory->Get('definition_set'));
  157. FilterByContext($oDefinitionFilter, $oAppContext);
  158. $oDefinitionSet = new CMDBObjectSet($oDefinitionFilter);
  159. $oFilter = GetRuleResultFilter($iRuleIndex, $oDefinitionFilter, $oAppContext);
  160. $oErrorObjectSet = new CMDBObjectSet($oFilter);
  161. $oAuditRule = MetaModel::GetObject('AuditRule', $iRuleIndex);
  162. $sFileName = utils::ReadParam('filename', null, true, 'string');
  163. $bAdvanced = utils::ReadParam('advanced', false);
  164. $sAdvanced = $bAdvanced ? '&advanced=1' : '';
  165. if ($sFileName != null)
  166. {
  167. $oP = new CSVPage("iTop - Export");
  168. $sCharset = MetaModel::GetConfig()->Get('csv_file_default_charset');
  169. $sCSVData = cmdbAbstractObject::GetSetAsCSV($oErrorObjectSet, array('localize_values' => true, 'fields_advanced' => $bAdvanced), $sCharset);
  170. if ($sCharset == 'UTF-8')
  171. {
  172. $sOutputData = UTF8_BOM.$sCSVData;
  173. }
  174. else
  175. {
  176. $sOutputData = $sCSVData;
  177. }
  178. if ($sFileName == '')
  179. {
  180. // Plain text => Firefox will NOT propose to download the file
  181. $oP->add_header("Content-type: text/plain; charset=$sCharset");
  182. }
  183. else
  184. {
  185. $oP->add_header("Content-type: text/csv; charset=$sCharset");
  186. }
  187. $oP->add($sOutputData);
  188. $oP->TrashUnexpectedOutput();
  189. $oP->output();
  190. exit;
  191. }
  192. else
  193. {
  194. $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>');
  195. $oP->p('<a href="./audit.php?'.$oAppContext->GetForLink().'">[Back to audit results]</a>');
  196. $sBlockId = 'audit_errors';
  197. $oP->p("<div id=\"$sBlockId\" style=\"clear:both\">\n");
  198. $oBlock = DisplayBlock::FromObjectSet($oErrorObjectSet, 'csv');
  199. $oBlock->Display($oP, 1);
  200. $oP->p("</div>\n");
  201. // Adjust the size of the Textarea containing the CSV to fit almost all the remaining space
  202. $oP->add_ready_script(" $('#1>textarea').height(400);"); // adjust the size of the block
  203. $sExportUrl = utils::GetAbsoluteUrlAppRoot()."pages/audit.php?operation=csv&category=".$oAuditCategory->GetKey()."&rule=".$oAuditRule->GetKey();
  204. $oP->add_ready_script("$('a[href*=\"webservices/export.php?expression=\"]').attr('href', '".$sExportUrl."&filename=audit.csv".$sAdvanced."');");
  205. $oP->add_ready_script("$('#1 :checkbox').removeAttr('onclick').click( function() { var sAdvanced = ''; if (this.checked) sAdvanced = '&advanced=1'; window.location.href='$sExportUrl'+sAdvanced; } );");
  206. }
  207. break;
  208. case 'errors':
  209. $iCategory = utils::ReadParam('category', '');
  210. $iRuleIndex = utils::ReadParam('rule', 0);
  211. $oAuditCategory = MetaModel::GetObject('AuditCategory', $iCategory);
  212. $oDefinitionFilter = DBObjectSearch::FromOQL($oAuditCategory->Get('definition_set'));
  213. FilterByContext($oDefinitionFilter, $oAppContext);
  214. $oDefinitionSet = new CMDBObjectSet($oDefinitionFilter);
  215. $oFilter = GetRuleResultFilter($iRuleIndex, $oDefinitionFilter, $oAppContext);
  216. $oErrorObjectSet = new CMDBObjectSet($oFilter);
  217. $oAuditRule = MetaModel::GetObject('AuditRule', $iRuleIndex);
  218. $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>');
  219. $oP->p('<a href="./audit.php?'.$oAppContext->GetForLink().'">[Back to audit results]</a>');
  220. $sBlockId = 'audit_errors';
  221. $oP->p("<div id=\"$sBlockId\" style=\"clear:both\">\n");
  222. $oBlock = DisplayBlock::FromObjectSet($oErrorObjectSet, 'list');
  223. $oBlock->Display($oP, 1);
  224. $oP->p("</div>\n");
  225. $sExportUrl = utils::GetAbsoluteUrlAppRoot()."pages/audit.php?operation=csv&category=".$oAuditCategory->GetKey()."&rule=".$oAuditRule->GetKey();
  226. $oP->add_ready_script("$('a[href*=\"pages/UI.php?operation=search\"]').attr('href', '".$sExportUrl."')");
  227. break;
  228. case 'audit':
  229. default:
  230. $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>');
  231. $oAuditFilter = new DBObjectSearch('AuditCategory');
  232. $oCategoriesSet = new DBObjectSet($oAuditFilter);
  233. $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");
  234. $oP->add("<tr><td>\n");
  235. $oP->add("<table>\n");
  236. $oP->add("<tr>\n");
  237. $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");
  238. $oP->add("</tr>\n");
  239. while($oAuditCategory = $oCategoriesSet->fetch())
  240. {
  241. try
  242. {
  243. $oDefinitionFilter = DBObjectSearch::FromOQL($oAuditCategory->Get('definition_set'));
  244. FilterByContext($oDefinitionFilter, $oAppContext);
  245. $aObjectsWithErrors = array();
  246. if (!empty($currentOrganization))
  247. {
  248. if (MetaModel::IsValidFilterCode($oDefinitionFilter->GetClass(), 'org_id'))
  249. {
  250. $oDefinitionFilter->AddCondition('org_id', $currentOrganization, '=');
  251. }
  252. }
  253. $aResults = array();
  254. $oDefinitionSet = new CMDBObjectSet($oDefinitionFilter);
  255. $iCount = $oDefinitionSet->Count();
  256. $oRulesFilter = new DBObjectSearch('AuditRule');
  257. $oRulesFilter->AddCondition('category_id', $oAuditCategory->GetKey(), '=');
  258. $oRulesSet = new DBObjectSet($oRulesFilter);
  259. while($oAuditRule = $oRulesSet->fetch() )
  260. {
  261. $aRow = array();
  262. $aRow['description'] = $oAuditRule->GetName();
  263. if ($iCount == 0)
  264. {
  265. // nothing to check, really !
  266. $aRow['nb_errors'] = "<a href=\"audit.php?operation=errors&category=".$oAuditCategory->GetKey()."&rule=".$oAuditRule->GetKey()."\">0</a>";
  267. $aRow['percent_ok'] = '100.00';
  268. $aRow['class'] = GetReportColor($iCount, 0);
  269. }
  270. else
  271. {
  272. try
  273. {
  274. $oFilter = GetRuleResultFilter($oAuditRule->GetKey(), $oDefinitionFilter, $oAppContext);
  275. $aErrors = $oFilter->ToDataArray(array('id'));
  276. $iErrorsCount = count($aErrors);
  277. foreach($aErrors as $aErrorRow)
  278. {
  279. $aObjectsWithErrors[$aErrorRow['id']] = true;
  280. }
  281. $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>";
  282. $aRow['percent_ok'] = sprintf('%.2f', 100.0 * (($iCount - $iErrorsCount) / $iCount));
  283. $aRow['class'] = GetReportColor($iCount, $iErrorsCount);
  284. }
  285. catch(Exception $e)
  286. {
  287. $aRow['nb_errors'] = "OQL Error";
  288. $aRow['percent_ok'] = 'n/a';
  289. $aRow['class'] = 'red';
  290. $sMessage = Dict::Format('UI:Audit:ErrorIn_Rule_Reason', $oAuditRule->GetHyperlink(), $e->getMessage());
  291. $oP->p("<img style=\"vertical-align:middle\" src=\"../images/stop-mid.png\"/>&nbsp;".$sMessage);
  292. }
  293. }
  294. $aResults[] = $aRow;
  295. }
  296. $iTotalErrors = count($aObjectsWithErrors);
  297. $sOverallPercentOk = ($iCount == 0) ? '100.00' : sprintf('%.2f', 100.0 * (($iCount - $iTotalErrors) / $iCount));
  298. $sClass = GetReportColor($iCount, $iTotalErrors);
  299. }
  300. catch(Exception $e)
  301. {
  302. $aRow = array();
  303. $aRow['description'] = "OQL error";
  304. $aRow['nb_errors'] = "n/a";
  305. $aRow['percent_ok'] = '';
  306. $aRow['class'] = 'red';
  307. $sMessage = Dict::Format('UI:Audit:ErrorIn_Category_Reason', $oAuditCategory->GetHyperlink(), $e->getMessage());
  308. $oP->p("<img style=\"vertical-align:middle\" src=\"../images/stop-mid.png\"/>&nbsp;".$sMessage);
  309. $aResults[] = $aRow;
  310. $sClass = 'red';
  311. $iTotalErrors = 'n/a';
  312. $sOverallPercentOk = '';
  313. }
  314. $oP->add("<tr>\n");
  315. $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");
  316. $oP->add("</tr>\n");
  317. foreach($aResults as $aRow)
  318. {
  319. $oP->add("<tr>\n");
  320. $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");
  321. $oP->add("</tr>\n");
  322. }
  323. }
  324. $oP->add("</table>\n");
  325. $oP->add("</td></tr>\n");
  326. $oP->add("</table>\n");
  327. }
  328. $oP->output();
  329. }
  330. catch(CoreException $e)
  331. {
  332. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  333. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  334. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  335. $oP->error(Dict::Format('UI:Error_Details', $e->getHtmlDesc()));
  336. $oP->output();
  337. if (MetaModel::IsLogEnabledIssue())
  338. {
  339. if (MetaModel::IsValidClass('EventIssue'))
  340. {
  341. $oLog = new EventIssue();
  342. $oLog->Set('message', $e->getMessage());
  343. $oLog->Set('userinfo', '');
  344. $oLog->Set('issue', $e->GetIssue());
  345. $oLog->Set('impact', 'Page could not be displayed');
  346. $oLog->Set('callstack', $e->getTrace());
  347. $oLog->Set('data', $e->getContextData());
  348. $oLog->DBInsertNoReload();
  349. }
  350. IssueLog::Error($e->getMessage());
  351. }
  352. // For debugging only
  353. //throw $e;
  354. }
  355. catch(Exception $e)
  356. {
  357. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  358. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  359. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  360. $oP->error(Dict::Format('UI:Error_Details', $e->getMessage()));
  361. $oP->output();
  362. if (MetaModel::IsLogEnabledIssue())
  363. {
  364. if (MetaModel::IsValidClass('EventIssue'))
  365. {
  366. $oLog = new EventIssue();
  367. $oLog->Set('message', $e->getMessage());
  368. $oLog->Set('userinfo', '');
  369. $oLog->Set('issue', 'PHP Exception');
  370. $oLog->Set('impact', 'Page could not be displayed');
  371. $oLog->Set('callstack', $e->getTrace());
  372. $oLog->Set('data', array());
  373. $oLog->DBInsertNoReload();
  374. }
  375. IssueLog::Error($e->getMessage());
  376. }
  377. }
  378. ?>