audit.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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. $sCSVName = basename($sFileName); // pseudo sanitization, just in case
  187. // Force the name of the downloaded file, since windows gives precedence to the extension over of the mime type
  188. $oP->add_header("Content-disposition: attachment; filename=\"$sCSVName\"");
  189. $oP->add_header("Content-type: text/csv; charset=$sCharset");
  190. }
  191. $oP->add($sOutputData);
  192. $oP->TrashUnexpectedOutput();
  193. $oP->output();
  194. exit;
  195. }
  196. else
  197. {
  198. $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>');
  199. $oP->p('<a href="./audit.php?'.$oAppContext->GetForLink().'">[Back to audit results]</a>');
  200. $sBlockId = 'audit_errors';
  201. $oP->p("<div id=\"$sBlockId\" style=\"clear:both\">\n");
  202. $oBlock = DisplayBlock::FromObjectSet($oErrorObjectSet, 'csv');
  203. $oBlock->Display($oP, 1);
  204. $oP->p("</div>\n");
  205. // Adjust the size of the Textarea containing the CSV to fit almost all the remaining space
  206. $oP->add_ready_script(" $('#1>textarea').height(400);"); // adjust the size of the block
  207. $sExportUrl = utils::GetAbsoluteUrlAppRoot()."pages/audit.php?operation=csv&category=".$oAuditCategory->GetKey()."&rule=".$oAuditRule->GetKey();
  208. $oP->add_ready_script("$('a[href*=\"webservices/export.php?expression=\"]').attr('href', '".$sExportUrl."&filename=audit.csv".$sAdvanced."');");
  209. $oP->add_ready_script("$('#1 :checkbox').removeAttr('onclick').click( function() { var sAdvanced = ''; if (this.checked) sAdvanced = '&advanced=1'; window.location.href='$sExportUrl'+sAdvanced; } );");
  210. }
  211. break;
  212. case 'errors':
  213. $sTitle = 'Audit Errors';
  214. $oP->SetBreadCrumbEntry('ui-tool-auditerrors', $sTitle, '', '', utils::GetAbsoluteUrlAppRoot().'images/wrench.png');
  215. $iCategory = utils::ReadParam('category', '');
  216. $iRuleIndex = utils::ReadParam('rule', 0);
  217. $oAuditCategory = MetaModel::GetObject('AuditCategory', $iCategory);
  218. $oDefinitionFilter = DBObjectSearch::FromOQL($oAuditCategory->Get('definition_set'));
  219. FilterByContext($oDefinitionFilter, $oAppContext);
  220. $oDefinitionSet = new CMDBObjectSet($oDefinitionFilter);
  221. $oFilter = GetRuleResultFilter($iRuleIndex, $oDefinitionFilter, $oAppContext);
  222. $oErrorObjectSet = new CMDBObjectSet($oFilter);
  223. $oAuditRule = MetaModel::GetObject('AuditRule', $iRuleIndex);
  224. $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>');
  225. $oP->p('<a href="./audit.php?'.$oAppContext->GetForLink().'">[Back to audit results]</a>');
  226. $sBlockId = 'audit_errors';
  227. $oP->p("<div id=\"$sBlockId\" style=\"clear:both\">\n");
  228. $oBlock = DisplayBlock::FromObjectSet($oErrorObjectSet, 'list');
  229. $oBlock->Display($oP, 1);
  230. $oP->p("</div>\n");
  231. $sExportUrl = utils::GetAbsoluteUrlAppRoot()."pages/audit.php?operation=csv&category=".$oAuditCategory->GetKey()."&rule=".$oAuditRule->GetKey();
  232. $oP->add_ready_script("$('a[href*=\"pages/UI.php?operation=search\"]').attr('href', '".$sExportUrl."')");
  233. break;
  234. case 'audit':
  235. default:
  236. $oP->SetBreadCrumbEntry('ui-tool-audit', Dict::S('Menu:Audit'), Dict::S('UI:Audit:InteractiveAudit'), '', utils::GetAbsoluteUrlAppRoot().'images/wrench.png');
  237. $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>');
  238. $oAuditFilter = new DBObjectSearch('AuditCategory');
  239. $oCategoriesSet = new DBObjectSet($oAuditFilter);
  240. $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");
  241. $oP->add("<tr><td>\n");
  242. $oP->add("<table>\n");
  243. $oP->add("<tr>\n");
  244. $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");
  245. $oP->add("</tr>\n");
  246. while($oAuditCategory = $oCategoriesSet->fetch())
  247. {
  248. try
  249. {
  250. $oDefinitionFilter = DBObjectSearch::FromOQL($oAuditCategory->Get('definition_set'));
  251. FilterByContext($oDefinitionFilter, $oAppContext);
  252. $aObjectsWithErrors = array();
  253. if (!empty($currentOrganization))
  254. {
  255. if (MetaModel::IsValidFilterCode($oDefinitionFilter->GetClass(), 'org_id'))
  256. {
  257. $oDefinitionFilter->AddCondition('org_id', $currentOrganization, '=');
  258. }
  259. }
  260. $aResults = array();
  261. $oDefinitionSet = new CMDBObjectSet($oDefinitionFilter);
  262. $iCount = $oDefinitionSet->Count();
  263. $oRulesFilter = new DBObjectSearch('AuditRule');
  264. $oRulesFilter->AddCondition('category_id', $oAuditCategory->GetKey(), '=');
  265. $oRulesSet = new DBObjectSet($oRulesFilter);
  266. while($oAuditRule = $oRulesSet->fetch() )
  267. {
  268. $aRow = array();
  269. $aRow['description'] = $oAuditRule->GetName();
  270. if ($iCount == 0)
  271. {
  272. // nothing to check, really !
  273. $aRow['nb_errors'] = "<a href=\"audit.php?operation=errors&category=".$oAuditCategory->GetKey()."&rule=".$oAuditRule->GetKey()."\">0</a>";
  274. $aRow['percent_ok'] = '100.00';
  275. $aRow['class'] = GetReportColor($iCount, 0);
  276. }
  277. else
  278. {
  279. try
  280. {
  281. $oFilter = GetRuleResultFilter($oAuditRule->GetKey(), $oDefinitionFilter, $oAppContext);
  282. $aErrors = $oFilter->ToDataArray(array('id'));
  283. $iErrorsCount = count($aErrors);
  284. foreach($aErrors as $aErrorRow)
  285. {
  286. $aObjectsWithErrors[$aErrorRow['id']] = true;
  287. }
  288. $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>";
  289. $aRow['percent_ok'] = sprintf('%.2f', 100.0 * (($iCount - $iErrorsCount) / $iCount));
  290. $aRow['class'] = GetReportColor($iCount, $iErrorsCount);
  291. }
  292. catch(Exception $e)
  293. {
  294. $aRow['nb_errors'] = "OQL Error";
  295. $aRow['percent_ok'] = 'n/a';
  296. $aRow['class'] = 'red';
  297. $sMessage = Dict::Format('UI:Audit:ErrorIn_Rule_Reason', $oAuditRule->GetHyperlink(), $e->getMessage());
  298. $oP->p("<img style=\"vertical-align:middle\" src=\"../images/stop-mid.png\"/>&nbsp;".$sMessage);
  299. }
  300. }
  301. $aResults[] = $aRow;
  302. }
  303. $iTotalErrors = count($aObjectsWithErrors);
  304. $sOverallPercentOk = ($iCount == 0) ? '100.00' : sprintf('%.2f', 100.0 * (($iCount - $iTotalErrors) / $iCount));
  305. $sClass = GetReportColor($iCount, $iTotalErrors);
  306. }
  307. catch(Exception $e)
  308. {
  309. $aRow = array();
  310. $aRow['description'] = "OQL error";
  311. $aRow['nb_errors'] = "n/a";
  312. $aRow['percent_ok'] = '';
  313. $aRow['class'] = 'red';
  314. $sMessage = Dict::Format('UI:Audit:ErrorIn_Category_Reason', $oAuditCategory->GetHyperlink(), $e->getMessage());
  315. $oP->p("<img style=\"vertical-align:middle\" src=\"../images/stop-mid.png\"/>&nbsp;".$sMessage);
  316. $aResults[] = $aRow;
  317. $sClass = 'red';
  318. $iTotalErrors = 'n/a';
  319. $sOverallPercentOk = '';
  320. }
  321. $oP->add("<tr>\n");
  322. $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");
  323. $oP->add("</tr>\n");
  324. foreach($aResults as $aRow)
  325. {
  326. $oP->add("<tr>\n");
  327. $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");
  328. $oP->add("</tr>\n");
  329. }
  330. }
  331. $oP->add("</table>\n");
  332. $oP->add("</td></tr>\n");
  333. $oP->add("</table>\n");
  334. }
  335. $oP->output();
  336. }
  337. catch(CoreException $e)
  338. {
  339. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  340. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  341. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  342. $oP->error(Dict::Format('UI:Error_Details', $e->getHtmlDesc()));
  343. $oP->output();
  344. if (MetaModel::IsLogEnabledIssue())
  345. {
  346. if (MetaModel::IsValidClass('EventIssue'))
  347. {
  348. $oLog = new EventIssue();
  349. $oLog->Set('message', $e->getMessage());
  350. $oLog->Set('userinfo', '');
  351. $oLog->Set('issue', $e->GetIssue());
  352. $oLog->Set('impact', 'Page could not be displayed');
  353. $oLog->Set('callstack', $e->getTrace());
  354. $oLog->Set('data', $e->getContextData());
  355. $oLog->DBInsertNoReload();
  356. }
  357. IssueLog::Error($e->getMessage());
  358. }
  359. // For debugging only
  360. //throw $e;
  361. }
  362. catch(Exception $e)
  363. {
  364. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  365. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  366. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  367. $oP->error(Dict::Format('UI:Error_Details', $e->getMessage()));
  368. $oP->output();
  369. if (MetaModel::IsLogEnabledIssue())
  370. {
  371. if (MetaModel::IsValidClass('EventIssue'))
  372. {
  373. $oLog = new EventIssue();
  374. $oLog->Set('message', $e->getMessage());
  375. $oLog->Set('userinfo', '');
  376. $oLog->Set('issue', 'PHP Exception');
  377. $oLog->Set('impact', 'Page could not be displayed');
  378. $oLog->Set('callstack', $e->getTrace());
  379. $oLog->Set('data', array());
  380. $oLog->DBInsertNoReload();
  381. }
  382. IssueLog::Error($e->getMessage());
  383. }
  384. }
  385. ?>