audit.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * Execute and shows the data quality audit
  18. *
  19. * @author Erwan Taloc <erwan.taloc@combodo.com>
  20. * @author Romain Quetiez <romain.quetiez@combodo.com>
  21. * @author Denis Flaven <denis.flaven@combodo.com>
  22. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  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 = clone $oDefinitionFilter;
  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/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 'errors':
  151. $iCategory = utils::ReadParam('category', '');
  152. $iRuleIndex = utils::ReadParam('rule', 0);
  153. $oAuditCategory = MetaModel::GetObject('AuditCategory', $iCategory);
  154. $oDefinitionFilter = DBObjectSearch::FromOQL($oAuditCategory->Get('definition_set'));
  155. FilterByContext($oDefinitionFilter, $oAppContext);
  156. $oDefinitionSet = new CMDBObjectSet($oDefinitionFilter);
  157. $oFilter = GetRuleResultFilter($iRuleIndex, $oDefinitionFilter, $oAppContext);
  158. $oErrorObjectSet = new CMDBObjectSet($oFilter);
  159. $oAuditRule = MetaModel::GetObject('AuditRule', $iRuleIndex);
  160. $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>');
  161. $oP->p('<a href="./audit.php?'.$oAppContext->GetForLink().'">[Back to audit results]</a>');
  162. $sBlockId = 'audit_errors';
  163. $oP->p("<div id=\"$sBlockId\" style=\"clear:both\">\n");
  164. $oBlock = DisplayBlock::FromObjectSet($oErrorObjectSet, 'list');
  165. $oBlock->Display($oP, 1);
  166. $oP->p("</div>\n");
  167. break;
  168. case 'audit':
  169. default:
  170. $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>');
  171. $oAuditFilter = new CMDBSearchFilter('AuditCategory');
  172. $oCategoriesSet = new DBObjectSet($oAuditFilter);
  173. $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");
  174. $oP->add("<tr><td>\n");
  175. $oP->add("<table>\n");
  176. $oP->add("<tr>\n");
  177. $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");
  178. $oP->add("</tr>\n");
  179. while($oAuditCategory = $oCategoriesSet->fetch())
  180. {
  181. try
  182. {
  183. $oDefinitionFilter = DBObjectSearch::FromOQL($oAuditCategory->Get('definition_set'));
  184. FilterByContext($oDefinitionFilter, $oAppContext);
  185. $aObjectsWithErrors = array();
  186. if (!empty($currentOrganization))
  187. {
  188. if (MetaModel::IsValidFilterCode($oDefinitionFilter->GetClass(), 'org_id'))
  189. {
  190. $oDefinitionFilter->AddCondition('org_id', $currentOrganization, '=');
  191. }
  192. }
  193. $aResults = array();
  194. $oDefinitionSet = new CMDBObjectSet($oDefinitionFilter);
  195. $iCount = $oDefinitionSet->Count();
  196. $oRulesFilter = new CMDBSearchFilter('AuditRule');
  197. $oRulesFilter->AddCondition('category_id', $oAuditCategory->GetKey(), '=');
  198. $oRulesSet = new DBObjectSet($oRulesFilter);
  199. while($oAuditRule = $oRulesSet->fetch() )
  200. {
  201. $aRow = array();
  202. $aRow['description'] = $oAuditRule->GetName();
  203. if ($iCount == 0)
  204. {
  205. // nothing to check, really !
  206. $aRow['nb_errors'] = "<a href=\"audit.php?operation=errors&category=".$oAuditCategory->GetKey()."&rule=".$oAuditRule->GetKey()."\">0</a>";
  207. $aRow['percent_ok'] = '100.00';
  208. $aRow['class'] = GetReportColor($iCount, 0);
  209. }
  210. else
  211. {
  212. try
  213. {
  214. $oFilter = GetRuleResultFilter($oAuditRule->GetKey(), $oDefinitionFilter, $oAppContext);
  215. $aErrors = $oFilter->ToDataArray(array('id'));
  216. $iErrorsCount = count($aErrors);
  217. foreach($aErrors as $aErrorRow)
  218. {
  219. $aObjectsWithErrors[$aErrorRow['id']] = true;
  220. }
  221. $aRow['nb_errors'] = ($iErrorsCount == 0) ? '0' : "<a href=\"?operation=errors&category=".$oAuditCategory->GetKey()."&rule=".$oAuditRule->GetKey()."&".$oAppContext->GetForLink()."\">$iErrorsCount</a>";
  222. $aRow['percent_ok'] = sprintf('%.2f', 100.0 * (($iCount - $iErrorsCount) / $iCount));
  223. $aRow['class'] = GetReportColor($iCount, $iErrorsCount);
  224. }
  225. catch(Exception $e)
  226. {
  227. $aRow['nb_errors'] = "OQL Error";
  228. $aRow['percent_ok'] = 'n/a';
  229. $aRow['class'] = 'red';
  230. $sMessage = Dict::Format('UI:Audit:ErrorIn_Rule_Reason', $oAuditRule->GetHyperlink(), $e->getMessage());
  231. $oP->p("<img style=\"vertical-align:middle\" src=\"../images/stop-mid.png\"/>&nbsp;".$sMessage);
  232. }
  233. }
  234. $aResults[] = $aRow;
  235. $iTotalErrors = count($aObjectsWithErrors);
  236. $sOverallPercentOk = ($iCount == 0) ? '100.00' : sprintf('%.2f', 100.0 * (($iCount - $iTotalErrors) / $iCount));
  237. $sClass = GetReportColor($iCount, $iTotalErrors);
  238. }
  239. }
  240. catch(Exception $e)
  241. {
  242. $aRow = array();
  243. $aRow['description'] = "OQL error";
  244. $aRow['nb_errors'] = "n/a";
  245. $aRow['percent_ok'] = '';
  246. $aRow['class'] = 'red';
  247. $sMessage = Dict::Format('UI:Audit:ErrorIn_Category_Reason', $oAuditCategory->GetHyperlink(), $e->getMessage());
  248. $oP->p("<img style=\"vertical-align:middle\" src=\"../images/stop-mid.png\"/>&nbsp;".$sMessage);
  249. $aResults[] = $aRow;
  250. }
  251. $oP->add("<tr>\n");
  252. $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");
  253. $oP->add("</tr>\n");
  254. foreach($aResults as $aRow)
  255. {
  256. $oP->add("<tr>\n");
  257. $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");
  258. $oP->add("</tr>\n");
  259. }
  260. }
  261. $oP->add("</table>\n");
  262. $oP->add("</td></tr>\n");
  263. $oP->add("</table>\n");
  264. }
  265. $oP->output();
  266. }
  267. catch(CoreException $e)
  268. {
  269. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  270. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  271. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  272. $oP->error(Dict::Format('UI:Error_Details', $e->getHtmlDesc()));
  273. $oP->output();
  274. if (MetaModel::IsLogEnabledIssue())
  275. {
  276. if (MetaModel::IsValidClass('EventIssue'))
  277. {
  278. $oLog = new EventIssue();
  279. $oLog->Set('message', $e->getMessage());
  280. $oLog->Set('userinfo', '');
  281. $oLog->Set('issue', $e->GetIssue());
  282. $oLog->Set('impact', 'Page could not be displayed');
  283. $oLog->Set('callstack', $e->getTrace());
  284. $oLog->Set('data', $e->getContextData());
  285. $oLog->DBInsertNoReload();
  286. }
  287. IssueLog::Error($e->getMessage());
  288. }
  289. // For debugging only
  290. //throw $e;
  291. }
  292. catch(Exception $e)
  293. {
  294. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  295. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  296. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  297. $oP->error(Dict::Format('UI:Error_Details', $e->getMessage()));
  298. $oP->output();
  299. if (MetaModel::IsLogEnabledIssue())
  300. {
  301. if (MetaModel::IsValidClass('EventIssue'))
  302. {
  303. $oLog = new EventIssue();
  304. $oLog->Set('message', $e->getMessage());
  305. $oLog->Set('userinfo', '');
  306. $oLog->Set('issue', 'PHP Exception');
  307. $oLog->Set('impact', 'Page could not be displayed');
  308. $oLog->Set('callstack', $e->getTrace());
  309. $oLog->Set('data', array());
  310. $oLog->DBInsertNoReload();
  311. }
  312. IssueLog::Error($e->getMessage());
  313. }
  314. }
  315. ?>