ajax.render.php 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624
  1. <?php
  2. // Copyright (C) 2010-2013 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. * Handles various ajax requests
  20. *
  21. * @copyright Copyright (C) 2010-2012 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. require_once('../approot.inc.php');
  25. require_once(APPROOT.'/application/application.inc.php');
  26. require_once(APPROOT.'/application/webpage.class.inc.php');
  27. require_once(APPROOT.'/application/ajaxwebpage.class.inc.php');
  28. require_once(APPROOT.'/application/wizardhelper.class.inc.php');
  29. require_once(APPROOT.'/application/ui.linkswidget.class.inc.php');
  30. require_once(APPROOT.'/application/ui.extkeywidget.class.inc.php');
  31. require_once(APPROOT.'/application/datatable.class.inc.php');
  32. try
  33. {
  34. require_once(APPROOT.'/application/startup.inc.php');
  35. require_once(APPROOT.'/application/user.preferences.class.inc.php');
  36. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  37. LoginWebPage::DoLogin(false /* bMustBeAdmin */, true /* IsAllowedToPortalUsers */); // Check user rights and prompt if needed
  38. $oPage = new ajax_page("");
  39. $oPage->no_cache();
  40. $operation = utils::ReadParam('operation', '');
  41. $sFilter = stripslashes(utils::ReadParam('filter', '', false, 'raw_data'));
  42. $sEncoding = utils::ReadParam('encoding', 'serialize');
  43. $sClass = utils::ReadParam('class', 'MissingAjaxParam', false, 'class');
  44. $sStyle = utils::ReadParam('style', 'list');
  45. switch($operation)
  46. {
  47. case 'datatable':
  48. case 'pagination':
  49. $oPage->SetContentType('text/html');
  50. $extraParams = utils::ReadParam('extra_param', '', false, 'raw_data');
  51. $aExtraParams = array();
  52. if (is_array($extraParams))
  53. {
  54. $aExtraParams = $extraParams;
  55. }
  56. else
  57. {
  58. $sExtraParams = stripslashes($extraParams);
  59. if (!empty($sExtraParams))
  60. {
  61. $val = json_decode(str_replace("'", '"', $sExtraParams), true /* associative array */);
  62. if ($val !== null)
  63. {
  64. $aExtraParams = $val;
  65. }
  66. }
  67. }
  68. if ($sEncoding == 'oql')
  69. {
  70. $oFilter = CMDBSearchFilter::FromOQL($sFilter);
  71. }
  72. else
  73. {
  74. $oFilter = CMDBSearchFilter::unserialize($sFilter);
  75. }
  76. $iStart = utils::ReadParam('start',0);
  77. $iEnd = utils::ReadParam('end',1);
  78. $iSortCol = utils::ReadParam('sort_col','null');
  79. $sSelectMode = utils::ReadParam('select_mode', '');
  80. if (!empty($sSelectMode) && ($sSelectMode != 'none'))
  81. {
  82. // The first column is used for the selection (radio / checkbox) and is not sortable
  83. $iSortCol--;
  84. }
  85. $bDisplayKey = utils::ReadParam('display_key', 'true') == 'true';
  86. $aColumns = utils::ReadParam('columns', array(), false, 'raw_data');
  87. $aClassAliases = utils::ReadParam('class_aliases', array());
  88. $iListId = utils::ReadParam('list_id', 0);
  89. //$aList = cmdbAbstractObject::FlattenZList(MetaModel::GetZListItems($sClassName, 'list'));
  90. // Filter the list to removed linked set since we are not able to display them here
  91. $aOrderBy = array();
  92. $iSortIndex = 0;
  93. $aColumnsLoad = array();
  94. foreach($aClassAliases as $sAlias => $sClassName)
  95. {
  96. $aColumnsLoad[$sAlias] = array();
  97. foreach($aColumns[$sAlias] as $sAttCode => $aData)
  98. {
  99. if ($aData['checked'] == 'true')
  100. {
  101. $aColumns[$sAlias][$sAttCode]['checked'] = true;
  102. if ($sAttCode == '_key_')
  103. {
  104. if ($iSortCol == $iSortIndex)
  105. {
  106. if (!MetaModel::HasChildrenClasses($oFilter->GetClass()))
  107. {
  108. $aNameSpec = MetaModel::GetNameSpec($oFilter->GetClass());
  109. if ($aNameSpec[0] == '%1$s')
  110. {
  111. // The name is made of a single column, let's sort according to the sort algorithm for this column
  112. $aOrderBy[$aNameSpec[1][0]] = (utils::ReadParam('sort_order', 'asc') == 'asc');
  113. }
  114. else
  115. {
  116. $aOrderBy['friendlyname'] = (utils::ReadParam('sort_order', 'asc') == 'asc');
  117. }
  118. }
  119. else
  120. {
  121. $aOrderBy['friendlyname'] = (utils::ReadParam('sort_order', 'asc') == 'asc');
  122. }
  123. }
  124. }
  125. else
  126. {
  127. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  128. if ($oAttDef instanceof AttributeLinkedSet)
  129. {
  130. // Removed from the display list
  131. unset($aColumns[$sAlias][$sAttCode]);
  132. }
  133. else
  134. {
  135. $aColumnsLoad[$sAlias][] = $sAttCode;
  136. }
  137. if ($iSortCol == $iSortIndex)
  138. {
  139. if ($oAttDef->IsExternalKey())
  140. {
  141. $sSortCol = $sAttCode.'_friendlyname';
  142. }
  143. else
  144. {
  145. $sSortCol = $sAttCode;
  146. }
  147. $aOrderBy[$sSortCol] = (utils::ReadParam('sort_order', 'asc') == 'asc');
  148. }
  149. }
  150. $iSortIndex++;
  151. }
  152. else
  153. {
  154. $aColumns[$sAlias][$sAttCode]['checked'] = false;
  155. }
  156. }
  157. }
  158. // Load only the requested columns
  159. $oSet = new DBObjectSet($oFilter, $aOrderBy, $aExtraParams, null, $iEnd-$iStart, $iStart);
  160. $oSet->OptimizeColumnLoad($aColumnsLoad);
  161. $oDataTable = new DataTable($iListId, $oSet, $oSet->GetSelectedClasses());
  162. if ($operation == 'datatable')
  163. {
  164. // Redraw the whole table
  165. $sHtml = $oDataTable->UpdatePager($oPage, $iEnd-$iStart, $iStart); // Set the default page size
  166. $sHtml .= $oDataTable->GetHTMLTable($oPage, $aColumns, $sSelectMode, $iEnd-$iStart, $bDisplayKey, $aExtraParams);
  167. }
  168. else
  169. {
  170. // redraw just the needed rows
  171. $sHtml = $oDataTable->GetAsHTMLTableRows($oPage, $iEnd-$iStart, $aColumns, $sSelectMode, $bDisplayKey, $aExtraParams);
  172. }
  173. $oPage->add($sHtml);
  174. break;
  175. case 'datatable_save_settings':
  176. $oPage->SetContentType('text/plain');
  177. $iPageSize = utils::ReadParam('page_size', 10);
  178. $sTableId = utils::ReadParam('table_id', null, false, 'raw_data');
  179. $bSaveAsDefaults = (utils::ReadParam('defaults', 'true') == 'true');
  180. $aClassAliases = utils::ReadParam('class_aliases', array(), false, 'raw_data');
  181. $aColumns = utils::ReadParam('columns', array(), false, 'raw_data');
  182. foreach($aColumns as $sAlias => $aList)
  183. {
  184. foreach($aList as $sAttCode => $aData)
  185. {
  186. $aColumns[$sAlias][$sAttCode]['checked'] = ($aData['checked'] == 'true');
  187. $aColumns[$sAlias][$sAttCode]['disabled'] = ($aData['disabled'] == 'true');
  188. $aColumns[$sAlias][$sAttCode]['sort'] = ($aData['sort']);
  189. }
  190. }
  191. $oSettings = new DataTableSettings($aClassAliases, $sTableId);
  192. $oSettings->iDefaultPageSize = $iPageSize;
  193. $oSettings->aColumns = $aColumns;
  194. if ($bSaveAsDefaults)
  195. {
  196. if ($sTableId != null)
  197. {
  198. $oCurrSettings = DataTableSettings::GetTableSettings($aClassAliases, $sTableId, true /* bOnlyTable */ );
  199. if ($oCurrSettings)
  200. {
  201. $oCurrSettings->ResetToDefault(false); // Reset this table to the defaults
  202. }
  203. }
  204. $bRet = $oSettings->SaveAsDefault();
  205. }
  206. else
  207. {
  208. $bRet = $oSettings->Save();
  209. }
  210. $oPage->add($bRet ? 'Ok' : 'KO');
  211. break;
  212. case 'datatable_reset_settings':
  213. $oPage->SetContentType('text/plain');
  214. $sTableId = utils::ReadParam('table_id', null, false, 'raw_data');
  215. $aClassAliases = utils::ReadParam('class_aliases', array(), false, 'raw_data');
  216. $bResetAll = (utils::ReadParam('defaults', 'true') == 'true');
  217. $oSettings = new DataTableSettings($aClassAliases, $sTableId);
  218. $bRet = $oSettings->ResetToDefault($bResetAll);
  219. $oPage->add($bRet ? 'Ok' : 'KO');
  220. break;
  221. // ui.linkswidget
  222. case 'addObjects':
  223. $oPage->SetContentType('text/html');
  224. $sAttCode = utils::ReadParam('sAttCode', '');
  225. $iInputId = utils::ReadParam('iInputId', '');
  226. $sSuffix = utils::ReadParam('sSuffix', '');
  227. $bDuplicates = (utils::ReadParam('bDuplicates', 'false') == 'false') ? false : true;
  228. $sJson = utils::ReadParam('json', '', false, 'raw_data');
  229. if (!empty($sJson))
  230. {
  231. $oWizardHelper = WizardHelper::FromJSON($sJson);
  232. $oObj = $oWizardHelper->GetTargetObject();
  233. }
  234. else
  235. {
  236. // Search form: no current object
  237. $oObj = null;
  238. }
  239. $oWidget = new UILinksWidget($sClass, $sAttCode, $iInputId, $sSuffix, $bDuplicates);
  240. $oWidget->GetObjectPickerDialog($oPage, $oObj);
  241. break;
  242. // ui.linkswidget
  243. case 'searchObjectsToAdd':
  244. $oPage->SetContentType('text/html');
  245. $sRemoteClass = utils::ReadParam('sRemoteClass', '', false, 'class');
  246. $sAttCode = utils::ReadParam('sAttCode', '');
  247. $iInputId = utils::ReadParam('iInputId', '');
  248. $sSuffix = utils::ReadParam('sSuffix', '');
  249. $bDuplicates = (utils::ReadParam('bDuplicates', 'false') == 'false') ? false : true;
  250. $aAlreadyLinked = utils::ReadParam('aAlreadyLinked', array());
  251. $oWidget = new UILinksWidget($sClass, $sAttCode, $iInputId, $sSuffix, $bDuplicates);
  252. $oWidget->SearchObjectsToAdd($oPage, $sRemoteClass, $aAlreadyLinked);
  253. break;
  254. //ui.linksdirectwidget
  255. case 'createObject':
  256. $oPage->SetContentType('text/html');
  257. $sClass = utils::ReadParam('class', '', false, 'class');
  258. $sRealClass = utils::ReadParam('real_class', '', false, 'class');
  259. $sAttCode = utils::ReadParam('att_code', '');
  260. $iInputId = utils::ReadParam('iInputId', '');
  261. $oPage->SetContentType('text/html');
  262. $oWidget = new UILinksWidgetDirect($sClass, $sAttCode, $iInputId);
  263. $oWidget->GetObjectCreationDlg($oPage, $sRealClass);
  264. break;
  265. // ui.linksdirectwidget
  266. case 'getLinksetRow':
  267. $oPage->SetContentType('text/html');
  268. $sClass = utils::ReadParam('class', '', false, 'class');
  269. $sRealClass = utils::ReadParam('real_class', '', false, 'class');
  270. $sAttCode = utils::ReadParam('att_code', '');
  271. $iInputId = utils::ReadParam('iInputId', '');
  272. $iTempId = utils::ReadParam('tempId', '');
  273. $aValues = utils::ReadParam('values', array(), false, 'raw_data');
  274. $oPage->SetContentType('text/html');
  275. $oWidget = new UILinksWidgetDirect($sClass, $sAttCode, $iInputId);
  276. $oPage->add($oWidget->GetRow($oPage, $sRealClass, $aValues, -$iTempId));
  277. break;
  278. // ui.linksdirectwidget
  279. case 'selectObjectsToAdd':
  280. $oPage->SetContentType('text/html');
  281. $sClass = utils::ReadParam('class', '', false, 'class');
  282. $sJson = utils::ReadParam('json', '', false, 'raw_data');
  283. $oObj = null;
  284. if ($sJson != '')
  285. {
  286. $oWizardHelper = WizardHelper::FromJSON($sJson);
  287. $oObj = $oWizardHelper->GetTargetObject();
  288. }
  289. $sRealClass = utils::ReadParam('real_class', '', false, 'class');
  290. $sAttCode = utils::ReadParam('att_code', '');
  291. $iInputId = utils::ReadParam('iInputId', '');
  292. $iCurrObjectId = utils::ReadParam('iObjId', 0);
  293. $oPage->SetContentType('text/html');
  294. $oWidget = new UILinksWidgetDirect($sClass, $sAttCode, $iInputId);
  295. $oWidget->GetObjectsSelectionDlg($oPage, $oObj);
  296. break;
  297. // ui.linksdirectwidget
  298. case 'searchObjectsToAdd2':
  299. $oPage->SetContentType('text/html');
  300. $sClass = utils::ReadParam('class', '', false, 'class');
  301. $sRealClass = utils::ReadParam('real_class', '', false, 'class');
  302. $sAttCode = utils::ReadParam('att_code', '');
  303. $iInputId = utils::ReadParam('iInputId', '');
  304. $aAlreadyLinked = utils::ReadParam('aAlreadyLinked', array());
  305. $sJson = utils::ReadParam('json', '', false, 'raw_data');
  306. $oObj = null;
  307. if ($sJson != '')
  308. {
  309. $oWizardHelper = WizardHelper::FromJSON($sJson);
  310. $oObj = $oWizardHelper->GetTargetObject();
  311. }
  312. $oWidget = new UILinksWidgetDirect($sClass, $sAttCode, $iInputId);
  313. $oWidget->SearchObjectsToAdd($oPage, $sRealClass, $aAlreadyLinked, $oObj);
  314. break;
  315. // ui.linksdirectwidget
  316. case 'doAddObjects2':
  317. $oPage->SetContentType('text/html');
  318. $oPage->SetContentType('text/html');
  319. $sClass = utils::ReadParam('class', '', false, 'class');
  320. $sRealClass = utils::ReadParam('real_class', '', false, 'class');
  321. $sAttCode = utils::ReadParam('att_code', '');
  322. $iInputId = utils::ReadParam('iInputId', '');
  323. $iCurrObjectId = utils::ReadParam('iObjId', 0);
  324. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  325. if ($sFilter != '')
  326. {
  327. $oFullSetFilter = DBObjectSearch::unserialize($sFilter);
  328. }
  329. else
  330. {
  331. $oLinksetDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  332. $valuesDef = $oLinksetDef->GetValuesDef();
  333. if ($valuesDef === null)
  334. {
  335. $oFullSetFilter = new DBObjectSearch($oLinksetDef->GetLinkedClass());
  336. }
  337. else
  338. {
  339. if (!$valuesDef instanceof ValueSetObjects)
  340. {
  341. throw new Exception('Error: only ValueSetObjects are supported for "allowed_values" in AttributeLinkedSet ('.$this->sClass.'/'.$this->sAttCode.').');
  342. }
  343. $oFullSetFilter = DBObjectSearch::FromOQL($valuesDef->GetFilterExpression());
  344. }
  345. }
  346. $oWidget = new UILinksWidgetDirect($sClass, $sAttCode, $iInputId);
  347. $oWidget->DoAddObjects($oPage, $oFullSetFilter);
  348. break;
  349. ////////////////////////////////////////////////////////////
  350. // ui.extkeywidget
  351. case 'searchObjectsToSelect':
  352. $oPage->SetContentType('text/html');
  353. $sTargetClass = utils::ReadParam('sTargetClass', '', false, 'class');
  354. $iInputId = utils::ReadParam('iInputId', '');
  355. $sRemoteClass = utils::ReadParam('sRemoteClass', '', false, 'class');
  356. $sFilter = utils::ReadParam('sFilter', '', false, 'raw_data');
  357. $sJson = utils::ReadParam('json', '', false, 'raw_data');
  358. $sAttCode = utils::ReadParam('sAttCode', '');
  359. $bSearchMode = (utils::ReadParam('bSearchMode', 'false') == 'true');
  360. if (!empty($sJson))
  361. {
  362. $oWizardHelper = WizardHelper::FromJSON($sJson);
  363. $oObj = $oWizardHelper->GetTargetObject();
  364. }
  365. else
  366. {
  367. // Search form: no current object
  368. $oObj = null;
  369. }
  370. $oWidget = new UIExtKeyWidget($sTargetClass, $iInputId, $sAttCode, $bSearchMode);
  371. $oWidget->SearchObjectsToSelect($oPage, $sFilter, $sRemoteClass, $oObj);
  372. break;
  373. // ui.extkeywidget: autocomplete
  374. case 'ac_extkey':
  375. $oPage->SetContentType('text/plain');
  376. $sTargetClass = utils::ReadParam('sTargetClass', '', false, 'class');
  377. $iInputId = utils::ReadParam('iInputId', '');
  378. $sFilter = utils::ReadParam('sFilter', '', false, 'raw_data');
  379. $sJson = utils::ReadParam('json', '', false, 'raw_data');
  380. $sContains = utils::ReadParam('q', '', false, 'raw_data');
  381. $bSearchMode = (utils::ReadParam('bSearchMode', 'false') == 'true');
  382. if ($sContains !='')
  383. {
  384. if (!empty($sJson))
  385. {
  386. $oWizardHelper = WizardHelper::FromJSON($sJson);
  387. $oObj = $oWizardHelper->GetTargetObject();
  388. }
  389. else
  390. {
  391. // Search form: no current object
  392. $oObj = null;
  393. }
  394. $oWidget = new UIExtKeyWidget($sTargetClass, $iInputId, '', $bSearchMode);
  395. $oWidget->AutoComplete($oPage, $sFilter, $oObj, $sContains);
  396. }
  397. break;
  398. // ui.extkeywidget
  399. case 'objectSearchForm':
  400. $oPage->SetContentType('text/html');
  401. $sTargetClass = utils::ReadParam('sTargetClass', '', false, 'class');
  402. $iInputId = utils::ReadParam('iInputId', '');
  403. $sTitle = utils::ReadParam('sTitle', '', false, 'raw_data');
  404. $sAttCode = utils::ReadParam('sAttCode', '');
  405. $bSearchMode = (utils::ReadParam('bSearchMode', 'false') == 'true');
  406. $oWidget = new UIExtKeyWidget($sTargetClass, $iInputId, $sAttCode, $bSearchMode);
  407. $sJson = utils::ReadParam('json', '', false, 'raw_data');
  408. if (!empty($sJson))
  409. {
  410. $oWizardHelper = WizardHelper::FromJSON($sJson);
  411. $oObj = $oWizardHelper->GetTargetObject();
  412. }
  413. else
  414. {
  415. // Search form: no current object
  416. $oObj = null;
  417. }
  418. $oWidget->GetSearchDialog($oPage, $sTitle, $oObj);
  419. break;
  420. // ui.extkeywidget
  421. case 'objectCreationForm':
  422. $oPage->SetContentType('text/html');
  423. $sTargetClass = utils::ReadParam('sTargetClass', '', false, 'class');
  424. $iInputId = utils::ReadParam('iInputId', '');
  425. $sAttCode = utils::ReadParam('sAttCode', '');
  426. $oWidget = new UIExtKeyWidget($sTargetClass, $iInputId, $sAttCode, false);
  427. $sJson = utils::ReadParam('json', '', false, 'raw_data');
  428. if (!empty($sJson))
  429. {
  430. $oWizardHelper = WizardHelper::FromJSON($sJson);
  431. $oObj = $oWizardHelper->GetTargetObject();
  432. }
  433. else
  434. {
  435. // Search form: no current object
  436. $oObj = null;
  437. }
  438. $oWidget->GetObjectCreationForm($oPage, $oObj);
  439. break;
  440. // ui.extkeywidget
  441. case 'doCreateObject':
  442. $oPage->SetContentType('application/json');
  443. $sTargetClass = utils::ReadParam('sTargetClass', '', false, 'class');
  444. $iInputId = utils::ReadParam('iInputId', '');
  445. $sFormPrefix = utils::ReadParam('sFormPrefix', '');
  446. $sAttCode = utils::ReadParam('sAttCode', '');
  447. $oWidget = new UIExtKeyWidget($sTargetClass, $iInputId, $sAttCode, false);
  448. $aResult = $oWidget->DoCreateObject($oPage);
  449. echo json_encode($aResult);
  450. break;
  451. // ui.extkeywidget
  452. case 'getObjectName':
  453. $oPage->SetContentType('application/json');
  454. $sTargetClass = utils::ReadParam('sTargetClass', '', false, 'class');
  455. $iInputId = utils::ReadParam('iInputId', '');
  456. $iObjectId = utils::ReadParam('iObjectId', '');
  457. $bSearchMode = (utils::ReadParam('bSearchMode', 'false') == 'true');
  458. $oWidget = new UIExtKeyWidget($sTargetClass, $iInputId, '', $bSearchMode);
  459. $sName = $oWidget->GetObjectName($iObjectId);
  460. echo json_encode(array('name' => $sName));
  461. break;
  462. // ui.extkeywidget
  463. case 'displayHierarchy':
  464. $oPage->SetContentType('text/html');
  465. $sTargetClass = utils::ReadParam('sTargetClass', '', false, 'class');
  466. $sInputId = utils::ReadParam('sInputId', '');
  467. $sFilter = utils::ReadParam('sFilter', '', false, 'raw_data');
  468. $sJson = utils::ReadParam('json', '', false, 'raw_data');
  469. $currValue = utils::ReadParam('value', '');
  470. $bSearchMode = (utils::ReadParam('bSearchMode', 'false') == 'true');
  471. if (!empty($sJson))
  472. {
  473. $oWizardHelper = WizardHelper::FromJSON($sJson);
  474. $oObj = $oWizardHelper->GetTargetObject();
  475. }
  476. else
  477. {
  478. // Search form: no current object
  479. $oObj = null;
  480. }
  481. $oWidget = new UIExtKeyWidget($sTargetClass, $sInputId, '', $bSearchMode);
  482. $oWidget->DisplayHierarchy($oPage, $sFilter, $currValue, $oObj);
  483. break;
  484. ////////////////////////////////////////////////////
  485. // ui.linkswidget
  486. case 'doAddObjects':
  487. $oPage->SetContentType('text/html');
  488. $sAttCode = utils::ReadParam('sAttCode', '');
  489. $iInputId = utils::ReadParam('iInputId', '');
  490. $sSuffix = utils::ReadParam('sSuffix', '');
  491. $sRemoteClass = utils::ReadParam('sRemoteClass', $sClass, false, 'class');
  492. $bDuplicates = (utils::ReadParam('bDuplicates', 'false') == 'false') ? false : true;
  493. $sJson = utils::ReadParam('json', '', false, 'raw_data');
  494. $oWizardHelper = WizardHelper::FromJSON($sJson);
  495. $oObj = $oWizardHelper->GetTargetObject();
  496. $oWidget = new UILinksWidget($sClass, $sAttCode, $iInputId, $sSuffix, $bDuplicates);
  497. if ($sFilter != '')
  498. {
  499. $oFullSetFilter = DBObjectSearch::unserialize($sFilter);
  500. }
  501. else
  502. {
  503. $oFullSetFilter = new DBObjectSearch($sRemoteClass);
  504. }
  505. $oWidget->DoAddObjects($oPage, $oFullSetFilter, $oObj);
  506. break;
  507. ////////////////////////////////////////////////////////////
  508. case 'wizard_helper_preview':
  509. $oPage->SetContentType('text/html');
  510. $sJson = utils::ReadParam('json_obj', '', false, 'raw_data');
  511. $oWizardHelper = WizardHelper::FromJSON($sJson);
  512. $oObj = $oWizardHelper->GetTargetObject();
  513. $oObj->DisplayBareProperties($oPage);
  514. break;
  515. case 'wizard_helper':
  516. $oPage->SetContentType('text/html');
  517. $sJson = utils::ReadParam('json_obj', '', false, 'raw_data');
  518. $oWizardHelper = WizardHelper::FromJSON($sJson);
  519. $oObj = $oWizardHelper->GetTargetObject();
  520. $sClass = $oWizardHelper->GetTargetClass();
  521. foreach($oWizardHelper->GetFieldsForDefaultValue() as $sAttCode)
  522. {
  523. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  524. $defaultValue = $oAttDef->GetDefaultValue();
  525. $oWizardHelper->SetDefaultValue($sAttCode, $defaultValue);
  526. $oObj->Set($sAttCode, $defaultValue);
  527. }
  528. $sFormPrefix = $oWizardHelper->GetFormPrefix();
  529. foreach($oWizardHelper->GetFieldsForAllowedValues() as $sAttCode)
  530. {
  531. $sId = $oWizardHelper->GetIdForField($sAttCode);
  532. if ($sId != '')
  533. {
  534. if ($oObj->IsNew())
  535. {
  536. $iFlags = $oObj->GetInitialStateAttributeFlags($sAttCode);
  537. }
  538. else
  539. {
  540. $iFlags = $oObj->GetAttributeFlags($sAttCode);
  541. }
  542. if ($iFlags & OPT_ATT_READONLY)
  543. {
  544. $sHTMLValue = "<span id=\"field_{$sId}\">".$oObj->GetAsHTML($sAttCode);
  545. $sHTMLValue .= '<input type="hidden" id="'.$sId.'" name="attr_'.$sFormPrefix.$sAttCode.'" value="'.htmlentities($oObj->Get($sAttCode), ENT_QUOTES, 'UTF-8').'"/></span>';
  546. $oWizardHelper->SetAllowedValuesHtml($sAttCode, $sHTMLValue);
  547. }
  548. else
  549. {
  550. // It may happen that the field we'd like to update does not
  551. // exist in the form. For example, if the field should be hidden/read-only
  552. // in the current state of the object
  553. $value = $oObj->Get($sAttCode);
  554. $displayValue = $oObj->GetEditValue($sAttCode);
  555. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  556. if (!$oAttDef->IsWritable())
  557. {
  558. // Even non-writable fields (like AttributeExternal) can be refreshed
  559. $sHTMLValue = $oObj->GetAsHTML($sAttCode);
  560. }
  561. else
  562. {
  563. $iFlags = MetaModel::GetAttributeFlags($sClass, $oObj->GetState(), $sAttCode);
  564. $sHTMLValue = cmdbAbstractObject::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $value, $displayValue, $sId, '', $iFlags, array('this' => $oObj, 'formPrefix' => $sFormPrefix));
  565. // Make sure that we immediately validate the field when we reload it
  566. $oPage->add_ready_script("$('#$sId').trigger('validate');");
  567. }
  568. $oWizardHelper->SetAllowedValuesHtml($sAttCode, $sHTMLValue);
  569. }
  570. }
  571. }
  572. $oPage->add_script("oWizardHelper{$sFormPrefix}.m_oData=".$oWizardHelper->ToJSON().";\noWizardHelper{$sFormPrefix}.UpdateFields();\n");
  573. break;
  574. case 'obj_creation_form':
  575. $oPage->SetContentType('text/html');
  576. $sJson = utils::ReadParam('json_obj', '', false, 'raw_data');
  577. $oWizardHelper = WizardHelper::FromJSON($sJson);
  578. $oObj = $oWizardHelper->GetTargetObject();
  579. $sClass = $oWizardHelper->GetTargetClass();
  580. $sTargetState = utils::ReadParam('target_state', '');
  581. $iTransactionId = utils::ReadParam('transaction_id', '');
  582. $oObj->Set(MetaModel::GetStateAttributeCode($sClass), $sTargetState);
  583. cmdbAbstractObject::DisplayCreationForm($oPage, $sClass, $oObj, array(), array('action' => utils::GetAbsoluteUrlAppRoot().'pages/UI.php', 'transaction_id' => $iTransactionId));
  584. break;
  585. // DisplayBlock
  586. case 'ajax':
  587. $oPage->SetContentType('text/html');
  588. if ($sFilter != "")
  589. {
  590. $sExtraParams = stripslashes(utils::ReadParam('extra_params', '', false, 'raw_data'));
  591. $aExtraParams = array();
  592. if (!empty($sExtraParams))
  593. {
  594. $aExtraParams = json_decode(str_replace("'", '"', $sExtraParams), true /* associative array */);
  595. }
  596. // Restore the app context from the ExtraParams
  597. $oAppContext = new ApplicationContext(false); // false => don't read the context yet !
  598. $aContext = array();
  599. foreach($oAppContext->GetNames() as $sName)
  600. {
  601. $sParamName = 'c['.$sName.']';
  602. if (isset($aExtraParams[$sParamName]))
  603. {
  604. $aContext[$sName] = $aExtraParams[$sParamName];
  605. }
  606. }
  607. $_REQUEST['c'] = $aContext;
  608. if ($sEncoding == 'oql')
  609. {
  610. $oFilter = CMDBSearchFilter::FromOQL($sFilter);
  611. }
  612. else
  613. {
  614. $oFilter = CMDBSearchFilter::unserialize($sFilter);
  615. }
  616. $oDisplayBlock = new DisplayBlock($oFilter, $sStyle, false);
  617. $aExtraParams['display_limit'] = true;
  618. $aExtraParams['truncated'] = true;
  619. $oDisplayBlock->RenderContent($oPage, $aExtraParams);
  620. }
  621. else
  622. {
  623. $oPage->p("Invalid query (empty filter).");
  624. }
  625. break;
  626. case 'displayCSVHistory':
  627. $oPage->SetContentType('text/html');
  628. $bShowAll = (utils::ReadParam('showall', 'false') == 'true');
  629. BulkChange::DisplayImportHistory($oPage, true, $bShowAll);
  630. break;
  631. case 'details':
  632. $oPage->SetContentType('text/html');
  633. $key = utils::ReadParam('id', 0);
  634. $oFilter = new DBObjectSearch($sClass);
  635. $oFilter->AddCondition('id', $key, '=');
  636. $oDisplayBlock = new DisplayBlock($oFilter, 'details', false);
  637. $oDisplayBlock->RenderContent($oPage);
  638. break;
  639. case 'pie_chart':
  640. $oPage->SetContentType('application/json');
  641. $sGroupBy = utils::ReadParam('group_by', '');
  642. if ($sFilter != '')
  643. {
  644. if ($sEncoding == 'oql')
  645. {
  646. $oFilter = CMDBSearchFilter::FromOQL($sFilter);
  647. }
  648. else
  649. {
  650. $oFilter = CMDBSearchFilter::unserialize($sFilter);
  651. }
  652. $oDisplayBlock = new DisplayBlock($oFilter, 'pie_chart_ajax', false);
  653. $oDisplayBlock->RenderContent($oPage, array('group_by' => $sGroupBy));
  654. }
  655. else
  656. {
  657. $oPage->add("<chart>\n<chart_type>3d pie</chart_type><!-- empty filter '$sFilter' --></chart>\n.");
  658. }
  659. break;
  660. case 'open_flash_chart':
  661. // Workaround for IE8 + IIS + HTTPS
  662. // See TRAC #363, fix described here: http://forums.codecharge.com/posts.php?post_id=97771
  663. $oPage->add_header("Expires: Fri, 17 Jul 1970 05:00:00 GMT");
  664. $oPage->add_header("Cache-Control: cache, must-revalidate");
  665. $oPage->add_header("Pragma: public");
  666. $oPage->SetContentType('application/json');
  667. $aParams = utils::ReadParam('params', array(), false, 'raw_data');
  668. if ($sFilter != '')
  669. {
  670. $oFilter = CMDBSearchFilter::unserialize($sFilter);
  671. $oDisplayBlock = new DisplayBlock($oFilter, 'open_flash_chart_ajax', false);
  672. $oDisplayBlock->RenderContent($oPage, $aParams);
  673. }
  674. else
  675. {
  676. $oPage->add("<chart>\n<chart_type>3d pie</chart_type><!-- empty filter '$sFilter' --></chart>\n.");
  677. }
  678. break;
  679. case 'modal_details':
  680. $oPage->SetContentType('text/html');
  681. $key = utils::ReadParam('id', 0);
  682. $oFilter = new DBObjectSearch($sClass);
  683. $oFilter->AddCondition('id', $key, '=');
  684. $oPage->Add("<p style=\"width:100%; margin-top:-5px;padding:3px; background-color:#33f; color:#fff;\">Object Details</p>\n");
  685. $oDisplayBlock = new DisplayBlock($oFilter, 'details', false);
  686. $oDisplayBlock->RenderContent($oPage);
  687. $oPage->Add("<input type=\"button\" class=\"jqmClose\" value=\" Close \" />\n");
  688. break;
  689. case 'link':
  690. $oPage->SetContentType('text/html');
  691. $sClass = utils::ReadParam('sclass', 'logInfra', false, 'class');
  692. $sAttCode = utils::ReadParam('attCode', 'name');
  693. //$sOrg = utils::ReadParam('org_id', '');
  694. $sName = utils::ReadParam('q', '');
  695. $iMaxCount = utils::ReadParam('max', 30);
  696. $iCount = 0;
  697. $oFilter = new DBObjectSearch($sClass);
  698. $oFilter->AddCondition($sAttCode, $sName, 'Begins with');
  699. //$oFilter->AddCondition('org_id', $sOrg, '=');
  700. $oSet = new CMDBObjectSet($oFilter, array($sAttCode => true));
  701. while( ($iCount < $iMaxCount) && ($oObj = $oSet->fetch()) )
  702. {
  703. $oPage->add($oObj->GetAsHTML($sAttCode)."|".$oObj->GetKey()."\n");
  704. $iCount++;
  705. }
  706. break;
  707. case 'combo_options':
  708. $oPage->SetContentType('text/html');
  709. $oFilter = CMDBSearchFilter::FromOQL($sFilter);
  710. $oSet = new CMDBObjectSet($oFilter);
  711. while( $oObj = $oSet->fetch())
  712. {
  713. $oPage->add('<option title="Here is more information..." value="'.$oObj->GetKey().'">'.$oObj->GetName().'</option>');
  714. }
  715. break;
  716. case 'display_document':
  717. $id = utils::ReadParam('id', '');
  718. $sField = utils::ReadParam('field', '');
  719. if (!empty($sClass) && !empty($id) && !empty($sField))
  720. {
  721. DownloadDocument($oPage, $sClass, $id, $sField, 'inline');
  722. }
  723. break;
  724. case 'download_document':
  725. $id = utils::ReadParam('id', '');
  726. $sField = utils::ReadParam('field', '');
  727. $iCacheSec = (int) utils::ReadParam('cache', 0);
  728. if (!empty($sClass) && !empty($id) && !empty($sField))
  729. {
  730. DownloadDocument($oPage, $sClass, $id, $sField, 'attachment');
  731. if ($iCacheSec > 0)
  732. {
  733. $oPage->add_header("Expires: "); // Reset the value set in ajax_page
  734. $oPage->add_header("Cache-Control: no-transform,public,max-age=$iCacheSec,s-maxage=$iCacheSec");
  735. }
  736. }
  737. break;
  738. case 'search_form':
  739. $oPage->SetContentType('text/html');
  740. $sClass = utils::ReadParam('className', '', false, 'class');
  741. $sRootClass = utils::ReadParam('baseClass', '', false, 'class');
  742. $currentId = utils::ReadParam('currentId', '');
  743. $sTableId = utils::ReadParam('_table_id_', null, false, 'raw_data');
  744. $sAction = utils::ReadParam('action', '');
  745. $oFilter = new DBObjectSearch($sClass);
  746. $oSet = new CMDBObjectSet($oFilter);
  747. $sHtml = cmdbAbstractObject::GetSearchForm($oPage, $oSet, array('currentId' => $currentId, 'baseClass' => $sRootClass, 'action' => $sAction, 'table_id' => $sTableId));
  748. $oPage->add($sHtml);
  749. break;
  750. case 'set_pref':
  751. $sCode = utils::ReadPostedParam('code', '');
  752. $sValue = utils::ReadPostedParam('value', '', 'raw_data');
  753. appUserPreferences::SetPref($sCode, $sValue);
  754. break;
  755. case 'erase_all_pref':
  756. // Can be useful in case a user got some corrupted prefs...
  757. appUserPreferences::ClearPreferences();
  758. break;
  759. case 'on_form_cancel':
  760. // Called when a creation/modification form is cancelled by the end-user
  761. // Let's take this opportunity to inform the plug-ins so that they can perform some cleanup
  762. $iTransactionId = utils::ReadParam('transaction_id', 0);
  763. $sTempId = session_id().'_'.$iTransactionId;
  764. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  765. {
  766. $oExtensionInstance->OnFormCancel($sTempId);
  767. }
  768. break;
  769. case 'reload_dashboard':
  770. $oPage->SetContentType('text/html');
  771. $sDashboardId = utils::ReadParam('dashboard_id', '', false, 'raw_data');
  772. $aExtraParams = utils::ReadParam('extra_params', '', false, 'raw_data');
  773. ApplicationMenu::LoadAdditionalMenus();
  774. $idx = ApplicationMenu::GetMenuIndexById($sDashboardId);
  775. $oMenu = ApplicationMenu::GetMenuNode($idx);
  776. $oDashboard = $oMenu->GetDashboard();
  777. $oDashboard->Render($oPage, false, $aExtraParams);
  778. break;
  779. case 'dashboard_editor':
  780. $sId = utils::ReadParam('id', '', false, 'raw_data');
  781. ApplicationMenu::LoadAdditionalMenus();
  782. $idx = ApplicationMenu::GetMenuIndexById($sId);
  783. $oMenu = ApplicationMenu::GetMenuNode($idx);
  784. $oMenu->RenderEditor($oPage);
  785. break;
  786. case 'new_dashlet':
  787. require_once(APPROOT.'application/forms.class.inc.php');
  788. require_once(APPROOT.'application/dashlet.class.inc.php');
  789. $sDashletClass = utils::ReadParam('dashlet_class', '');
  790. $sDashletId = utils::ReadParam('dashlet_id', '', false, 'raw_data');
  791. if (is_subclass_of($sDashletClass, 'Dashlet'))
  792. {
  793. $oDashlet = new $sDashletClass(new ModelReflectionRuntime(), $sDashletId);
  794. $offset = $oPage->start_capture();
  795. $oDashlet->DoRender($oPage, true /* bEditMode */, false /* bEnclosingDiv */);
  796. $sHtml = addslashes($oPage->end_capture($offset));
  797. $sHtml = str_replace("\n", '', $sHtml);
  798. $sHtml = str_replace("\r", '', $sHtml);
  799. $oPage->add_script("$('#dashlet_$sDashletId').html('$sHtml');"); // in ajax web page add_script has the same effect as add_ready_script
  800. // but is executed BEFORE all 'ready_scripts'
  801. $oForm = $oDashlet->GetForm(); // Rebuild the form since the values/content changed
  802. $oForm->SetSubmitParams(utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php', array('operation' => 'update_dashlet_property'));
  803. $sHtml = addslashes($oForm->RenderAsPropertySheet($oPage, true /* bReturnHtml */, '.itop-dashboard'));
  804. $sHtml = str_replace("\n", '', $sHtml);
  805. $sHtml = str_replace("\r", '', $sHtml);
  806. $oPage->add_script("$('#dashlet_properties_$sDashletId').html('$sHtml')"); // in ajax web page add_script has the same effect as add_ready_script // but is executed BEFORE all 'ready_scripts'
  807. }
  808. break;
  809. case 'update_dashlet_property':
  810. require_once(APPROOT.'application/forms.class.inc.php');
  811. require_once(APPROOT.'application/dashlet.class.inc.php');
  812. $aParams = utils::ReadParam('params', '', false, 'raw_data');
  813. $sDashletClass = $aParams['attr_dashlet_class'];
  814. $sDashletId = $aParams['attr_dashlet_id'];
  815. $aUpdatedProperties = $aParams['updated']; // Code of the changed properties as an array: 'attr_xxx', 'attr_xxy', etc...
  816. $aPreviousValues = $aParams['previous_values']; // hash array: 'attr_xxx' => 'old_value'
  817. if (is_subclass_of($sDashletClass, 'Dashlet'))
  818. {
  819. $oDashlet = new $sDashletClass(new ModelReflectionRuntime(), $sDashletId);
  820. $oForm = $oDashlet->GetForm();
  821. $aValues = $oForm->ReadParams(); // hash array: 'xxx' => 'new_value'
  822. $aCurrentValues = $aValues;
  823. $aUpdatedDecoded = array();
  824. foreach($aUpdatedProperties as $sProp)
  825. {
  826. $sDecodedProp = str_replace('attr_', '', $sProp); // Remove the attr_ prefix
  827. $aCurrentValues[$sDecodedProp] = $aPreviousValues[$sProp]; // Set the previous value
  828. $aUpdatedDecoded[] = $sDecodedProp;
  829. }
  830. $oDashlet->FromParams($aCurrentValues);
  831. $sPrevClass = get_class($oDashlet);
  832. $oDashlet = $oDashlet->Update($aValues, $aUpdatedDecoded);
  833. $sNewClass = get_class($oDashlet);
  834. if ($sNewClass != $sPrevClass)
  835. {
  836. $oPage->add_ready_script("$('#dashlet_$sDashletId').dashlet('option', {dashlet_class: '$sNewClass'});");
  837. }
  838. if ($oDashlet->IsRedrawNeeded())
  839. {
  840. $offset = $oPage->start_capture();
  841. $oDashlet->DoRender($oPage, true /* bEditMode */, false /* bEnclosingDiv */);
  842. $sHtml = addslashes($oPage->end_capture($offset));
  843. $sHtml = str_replace("\n", '', $sHtml);
  844. $sHtml = str_replace("\r", '', $sHtml);
  845. $oPage->add_script("$('#dashlet_$sDashletId').html('$sHtml');"); // in ajax web page add_script has the same effect as add_ready_script
  846. // but is executed BEFORE all 'ready_scripts'
  847. }
  848. if ($oDashlet->IsFormRedrawNeeded())
  849. {
  850. $oForm = $oDashlet->GetForm(); // Rebuild the form since the values/content changed
  851. $oForm->SetSubmitParams(utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php', array('operation' => 'update_dashlet_property'));
  852. $sHtml = addslashes($oForm->RenderAsPropertySheet($oPage, true /* bReturnHtml */, '.itop-dashboard'));
  853. $sHtml = str_replace("\n", '', $sHtml);
  854. $sHtml = str_replace("\r", '', $sHtml);
  855. $oPage->add_script("$('#dashlet_properties_$sDashletId').html('$sHtml')"); // in ajax web page add_script has the same effect as add_ready_script // but is executed BEFORE all 'ready_scripts'
  856. // but is executed BEFORE all 'ready_scripts'
  857. }
  858. }
  859. break;
  860. case 'save_dashboard':
  861. $sDashboardId = utils::ReadParam('dashboard_id', '', false, 'raw_data');
  862. $aParams = array();
  863. $aParams['layout_class'] = utils::ReadParam('layout_class', '');
  864. $aParams['title'] = utils::ReadParam('title', '', false, 'raw_data');
  865. $aParams['auto_reload'] = utils::ReadParam('auto_reload', false);
  866. $aParams['auto_reload_sec'] = utils::ReadParam('auto_reload_sec', 300);
  867. $aParams['cells'] = utils::ReadParam('cells', array(), false, 'raw_data');
  868. $oDashboard = new RuntimeDashboard($sDashboardId);
  869. $oDashboard->FromParams($aParams);
  870. $oDashboard->Save();
  871. // trigger a reload of the current page since the dashboard just changed
  872. $oPage->add_ready_script(
  873. <<<EOF
  874. var sLocation = new String(window.location.href);
  875. var sNewLocation = sLocation.replace('&edit=1', '');
  876. sNewLocation = sLocation.replace(/#(.?)$/, ''); // Strips everything after the hash, since IF the URL does not change AND contains a hash, then Chrome does not reload the page
  877. window.location.href = sNewLocation;
  878. EOF
  879. );
  880. $oPage->add_ready_script("sLocation = new String(window.location.href); window.location.href=sLocation.replace('&edit=1', '');"); // reloads the page, doing a GET even if we arrived via a POST
  881. break;
  882. case 'revert_dashboard':
  883. $sDashboardId = utils::ReadParam('dashboard_id', '', false, 'raw_data');
  884. $oDashboard = new RuntimeDashboard($sDashboardId);
  885. $oDashboard->Revert();
  886. // trigger a reload of the current page since the dashboard just changed
  887. $oPage->add_ready_script("window.location.href=window.location.href;"); // reloads the page, doing a GET even if we arrived via a POST
  888. break;
  889. case 'render_dashboard':
  890. $sDashboardId = utils::ReadParam('dashboard_id', '', false, 'raw_data');
  891. $aParams = array();
  892. $aParams['layout_class'] = utils::ReadParam('layout_class', '');
  893. $aParams['title'] = utils::ReadParam('title', '', false, 'raw_data');
  894. $aParams['cells'] = utils::ReadParam('cells', array(), false, 'raw_data');
  895. $aParams['auto_reload'] = utils::ReadParam('auto_reload', false);
  896. $aParams['auto_reload_sec'] = utils::ReadParam('auto_reload_sec', 300);
  897. $oDashboard = new RuntimeDashboard($sDashboardId);
  898. $oDashboard->FromParams($aParams);
  899. $oDashboard->Render($oPage, true /* bEditMode */);
  900. break;
  901. case 'dashlet_creation_dlg':
  902. $sOQL = utils::ReadParam('oql', '', false, 'raw_data');
  903. RuntimeDashboard::GetDashletCreationDlgFromOQL($oPage, $sOQL);
  904. break;
  905. case 'add_dashlet':
  906. $oForm = RuntimeDashboard::GetDashletCreationForm();
  907. $aValues = $oForm->ReadParams();
  908. $sDashletClass = $aValues['dashlet_class'];
  909. $sMenuId = $aValues['menu_id'];
  910. if (is_subclass_of($sDashletClass, 'Dashlet'))
  911. {
  912. $oDashlet = new $sDashletClass(new ModelReflectionRuntime(), 0);
  913. $oDashlet->FromParams($aValues);
  914. ApplicationMenu::LoadAdditionalMenus();
  915. $index = ApplicationMenu::GetMenuIndexById($sMenuId);
  916. $oMenu = ApplicationMenu::GetMenuNode($index);
  917. $oMenu->AddDashlet($oDashlet);
  918. // navigate to the dashboard page
  919. if ($aValues['open_editor'])
  920. {
  921. $oPage->add_ready_script("window.location.href='".addslashes(utils::GetAbsoluteUrlAppRoot().'pages/UI.php?c[menu]='.urlencode($sMenuId))."&edit=1';"); // reloads the page, doing a GET even if we arrived via a POST
  922. }
  923. }
  924. break;
  925. case 'shortcut_list_dlg':
  926. $sOQL = utils::ReadParam('oql', '', false, 'raw_data');
  927. $sTableSettings = utils::ReadParam('table_settings', '', false, 'raw_data');
  928. ShortcutOQL::GetCreationDlgFromOQL($oPage, $sOQL, $sTableSettings);
  929. break;
  930. case 'shortcut_list_create':
  931. $oForm = ShortcutOQL::GetCreationForm();
  932. $aValues = $oForm->ReadParams();
  933. $oAppContext = new ApplicationContext();
  934. $aContext = $oAppContext->GetAsHash();
  935. $sContext = serialize($aContext);
  936. $oShortcut = MetaModel::NewObject("ShortcutOQL");
  937. $oShortcut->Set('user_id', UserRights::GetUserId());
  938. $oShortcut->Set("context", $sContext);
  939. $oShortcut->Set("name", $aValues['name']);
  940. $oShortcut->Set("oql", $aValues['oql']);
  941. $iAutoReload = (int)$aValues['auto_reload_sec'];
  942. if (($aValues['auto_reload']) && ($iAutoReload > 0))
  943. {
  944. $oShortcut->Set("auto_reload_sec", max(5, $iAutoReload));
  945. $oShortcut->Set("auto_reload", 'custom');
  946. }
  947. $iId = $oShortcut->DBInsertNoReload();
  948. $oShortcut->CloneTableSettings($aValues['table_settings']);
  949. // Add the menu node in the right place
  950. //
  951. // Mmmm... already done because the newly created menu is read from the DB
  952. // as soon as we invoke DisplayMenu
  953. // Refresh the menu pane
  954. $aExtraParams = array();
  955. ApplicationMenu::DisplayMenu($oPage, $aExtraParams);
  956. break;
  957. case 'shortcut_rename_dlg':
  958. $oSearch = new DBObjectSearch('Shortcut');
  959. $aShortcuts = utils::ReadMultipleSelection($oSearch);
  960. $iShortcut = $aShortcuts[0];
  961. $oShortcut = MetaModel::GetObject('Shortcut', $iShortcut);
  962. $oShortcut->StartRenameDialog($oPage);
  963. break;
  964. case 'shortcut_rename_go':
  965. $iShortcut = utils::ReadParam('id', 0);
  966. $oShortcut = MetaModel::GetObject('Shortcut', $iShortcut);
  967. $sName = utils::ReadParam('attr_name', '', false, 'raw_data');
  968. if (strlen($sName) > 0)
  969. {
  970. $oShortcut->Set('name', $sName);
  971. $oShortcut->DBUpdate();
  972. $oPage->add_ready_script('window.location.reload();');
  973. }
  974. break;
  975. case 'shortcut_delete_go':
  976. $oSearch = new DBObjectSearch('Shortcut');
  977. $oSearch->AddCondition('user_id', UserRights::GetUserId(), '=');
  978. $aShortcuts = utils::ReadMultipleSelection($oSearch);
  979. foreach ($aShortcuts as $iShortcut)
  980. {
  981. $oShortcut = MetaModel::GetObject('Shortcut', $iShortcut);
  982. $oShortcut->DBDelete();
  983. $oPage->add_ready_script('window.location.reload();');
  984. }
  985. break;
  986. case 'export_dashboard':
  987. $sMenuId = utils::ReadParam('id', '', false, 'raw_data');
  988. ApplicationMenu::LoadAdditionalMenus();
  989. $index = ApplicationMenu::GetMenuIndexById($sMenuId);
  990. $oMenu = ApplicationMenu::GetMenuNode($index);
  991. if ($oMenu instanceof DashboardMenuNode)
  992. {
  993. $oDashboard = $oMenu->GetDashboard();
  994. $oPage->TrashUnexpectedOutput();
  995. $oPage->SetContentType('text/xml');
  996. $oPage->SetContentDisposition('attachment', $oMenu->GetLabel().'.xml');
  997. $oPage->add($oDashboard->ToXml());
  998. }
  999. break;
  1000. case 'import_dashboard':
  1001. $sMenuId = utils::ReadParam('id', '', false, 'raw_data');
  1002. ApplicationMenu::LoadAdditionalMenus();
  1003. $index = ApplicationMenu::GetMenuIndexById($sMenuId);
  1004. $oMenu = ApplicationMenu::GetMenuNode($index);
  1005. $aResult = array('error' => '');
  1006. try
  1007. {
  1008. if ($oMenu instanceof DashboardMenuNode)
  1009. {
  1010. $oDoc = utils::ReadPostedDocument('dashboard_upload_file');
  1011. $oDashboard = $oMenu->GetDashboard();
  1012. $oDashboard->FromXml($oDoc->GetData());
  1013. $oDashboard->Save();
  1014. }
  1015. else
  1016. {
  1017. $aResult['error'] = 'Dashboard id="'.$sMenuId.'" not found.';
  1018. }
  1019. }
  1020. catch(DOMException $e)
  1021. {
  1022. $aResult = array('error' => Dict::S('UI:Error:InvalidDashboardFile'));
  1023. }
  1024. catch(Exception $e)
  1025. {
  1026. $aResult = array('error' => $e->getMessage());
  1027. }
  1028. $oPage->add(json_encode($aResult));
  1029. break;
  1030. case 'about_box':
  1031. $oPage->SetContentType('text/html');
  1032. $sDialogTitle = addslashes(Dict::S('UI:About:Title'));
  1033. $oPage->add_ready_script(
  1034. <<<EOF
  1035. $('#about_box').dialog({
  1036. width: 700,
  1037. modal: true,
  1038. title: '$sDialogTitle',
  1039. close: function() { $(this).remove(); }
  1040. });
  1041. $("#collapse_support_details").click(function() {
  1042. $("#support_details").slideToggle('normal');
  1043. $("#collapse_support_details").toggleClass('open');
  1044. });
  1045. $('#support_details').toggle();
  1046. EOF
  1047. );
  1048. $sVersionString = Dict::Format('UI:iTopVersion:Long', ITOP_VERSION, ITOP_REVISION, ITOP_BUILD_DATE);
  1049. $sMySQLVersion = CMDBSource::GetDBVersion();
  1050. $sPHPVersion = phpversion();
  1051. $sOSVersion = PHP_OS;
  1052. $sWebServerVersion = $_SERVER["SERVER_SOFTWARE"];
  1053. $sModules = implode(', ', get_loaded_extensions());
  1054. // Get the datamodel directory
  1055. $oFilter = DBObjectSearch::FromOQL('SELECT ModuleInstallation WHERE name="datamodel"');
  1056. $oSet = new DBObjectSet($oFilter, array('installed' => false)); // Most recent first
  1057. $oLastInstall = $oSet->Fetch();
  1058. $sLastInstallDate = $oLastInstall->Get('installed');
  1059. $sDataModelVersion = $oLastInstall->Get('version');
  1060. $aDataModelInfo = json_decode($oLastInstall->Get('comment'), true);
  1061. $sDataModelSourceDir = $aDataModelInfo['source_dir'];
  1062. require_once(APPROOT.'setup/runtimeenv.class.inc.php');
  1063. $sCurrEnv = utils::GetCurrentEnvironment();
  1064. $oRuntimeEnv = new RunTimeEnvironment($sCurrEnv);
  1065. $aAvailableModules = $oRuntimeEnv->AnalyzeInstallation(MetaModel::GetConfig(), array(APPROOT.$sDataModelSourceDir, APPROOT.'extensions'));
  1066. require_once(APPROOT.'setup/setuputils.class.inc.php');
  1067. $aLicenses = SetupUtils::GetLicenses();
  1068. $aItopSettings = array('cron_max_execution_time', 'timezone');
  1069. $aPHPSettings = array('memory_limit', 'max_execution_time', 'upload_max_filesize', 'post_max_size');
  1070. $aMySQLSettings = array('max_allowed_packet', 'key_buffer_size', 'query_cache_size');
  1071. $aMySQLStatuses = array('Key_read_requests', 'Key_reads');
  1072. if (extension_loaded('suhosin'))
  1073. {
  1074. $aPHPSettings[] = 'suhosin.post.max_vars';
  1075. $aPHPSettings[] = 'suhosin.get.max_value_length';
  1076. }
  1077. $aMySQLVars = array();
  1078. foreach (CMDBSource::QueryToArray('SHOW VARIABLES') as $aRow)
  1079. {
  1080. $aMySQLVars[$aRow['Variable_name']] = $aRow['Value'];
  1081. }
  1082. $aMySQLStats = array();
  1083. foreach (CMDBSource::QueryToArray('SHOW GLOBAL STATUS') as $aRow)
  1084. {
  1085. $aMySQLStats[$aRow['Variable_name']] = $aRow['Value'];
  1086. }
  1087. // Display
  1088. //
  1089. $oPage->add("<div id=\"about_box\">");
  1090. $oPage->add('<div style="margin-left: 120px;">');
  1091. $oPage->add('<table>');
  1092. $oPage->add('<tr>');
  1093. $oPage->add('<td><a href="http://www.combodo.com" title="www.combodo.com" target="_blank" style="background: none;"><img src="../images/logo-combodo.png" style="float: right;"/></a></td>');
  1094. $oPage->add('<td style="padding-left: 20px;">');
  1095. $oPage->add($sVersionString.'<br/>');
  1096. $oPage->add(Dict::S('UI:About:DataModel').': '.$sDataModelVersion.'<br/>');
  1097. $oPage->add('MySQL: '.$sMySQLVersion.'<br/>');
  1098. $oPage->add('PHP: '.$sPHPVersion.'<br/>');
  1099. $oPage->add('</td>');
  1100. $oPage->add('</tr>');
  1101. $oPage->add('</table>');
  1102. $oPage->add("</div>");
  1103. $oPage->add("<div>");
  1104. $oPage->add('<fieldset>');
  1105. $oPage->add('<legend>'.Dict::S('UI:About:Licenses').'</legend>');
  1106. $oPage->add('<ul style="margin: 0; font-size: smaller;">');
  1107. foreach($aLicenses as $index => $oLicense)
  1108. {
  1109. $oPage->add('<li><b>'.$oLicense->product.'</b>, &copy; '.$oLicense->author.' is licensed under the <b>'.$oLicense->license_type.' license</b>. (<a id="toggle_'.$index.'" class="CollapsibleLabel" style="cursor:pointer;">Details</a>)');
  1110. $oPage->add('<div id="license_'.$index.'" class="license_text" style="display:none;overflow:auto;max-height:10em;font-size:small;border:1px #696969 solid;margin-bottom:1em; margin-top:0.5em;padding:0.5em;">'.$oLicense->text.'</div>');
  1111. $oPage->add_ready_script('$("#toggle_'.$index.'").click( function() { $("#license_'.$index.'").slideToggle("normal"); } );');
  1112. }
  1113. $oPage->add('</ul>');
  1114. $oPage->add('</fieldset>');
  1115. $oPage->add("</div>");
  1116. $oPage->add('<fieldset>');
  1117. $oPage->add('<legend>'.Dict::S('UI:About:Modules').'</legend>');
  1118. //$oPage->add(print_r($aAvailableModules, true));
  1119. $oPage->add("<div style=\"height: 150px; overflow: auto; font-size: smaller;\">");
  1120. $oPage->add('<ul style="margin: 0;">');
  1121. foreach ($aAvailableModules as $sModuleId => $aModuleData)
  1122. {
  1123. if ($sModuleId == '_Root_') continue;
  1124. if (!$aModuleData['visible']) continue;
  1125. if ($aModuleData['version_db'] == '') continue;
  1126. $oPage->add('<li>'.$aModuleData['label'].' ('.$aModuleData['version_db'].')</li>');
  1127. }
  1128. $oPage->add('</ul>');
  1129. $oPage->add("</div>");
  1130. $oPage->add('</fieldset>');
  1131. // MUST NOT be localized, as the information given here will be sent to the support
  1132. $oPage->add("<a id=\"collapse_support_details\" class=\"CollapsibleLabel\" href=\"#\">".Dict::S('UI:About:Support')."</a></br>\n");
  1133. $oPage->add("<div id=\"support_details\">");
  1134. $oPage->add('<textarea readonly style="width: 660px; height: 150px; font-size: smaller;">');
  1135. $oPage->add("===== begin =====\n");
  1136. $oPage->add('iTopVersion: '.ITOP_VERSION."\n");
  1137. $oPage->add('iTopBuild: '.ITOP_REVISION."\n");
  1138. $oPage->add('iTopBuildDate: '.ITOP_BUILD_DATE."\n");
  1139. $oPage->add('DataModelVersion: '.$sDataModelVersion."\n");
  1140. $oPage->add('MySQLVersion: '.$sMySQLVersion."\n");
  1141. $oPage->add('PHPVersion: '. $sPHPVersion."\n");
  1142. $oPage->add('OSVersion: '.$sOSVersion."\n");
  1143. $oPage->add('WebServerVersion: '.$sWebServerVersion."\n");
  1144. $oPage->add('PHPModules: '.$sModules."\n");
  1145. foreach ($aItopSettings as $siTopVar)
  1146. {
  1147. $oPage->add('ItopSetting/'.$siTopVar.': '.MetaModel::GetConfig()->Get($siTopVar)."\n");
  1148. }
  1149. foreach ($aPHPSettings as $sPHPVar)
  1150. {
  1151. $oPage->add('PHPSetting/'.$sPHPVar.': '.ini_get($sPHPVar)."\n");
  1152. }
  1153. foreach ($aMySQLSettings as $sMySQLVar)
  1154. {
  1155. $oPage->add('MySQLSetting/'.$sMySQLVar.': '.$aMySQLVars[$sMySQLVar]."\n");
  1156. }
  1157. foreach ($aMySQLStatuses as $sMySQLStatus)
  1158. {
  1159. $oPage->add('MySQLStatus/'.$sMySQLStatus.': '.$aMySQLStats[$sMySQLStatus]."\n");
  1160. }
  1161. $oPage->add('InstallDate: '.$sLastInstallDate."\n");
  1162. $oPage->add('InstallPath: '.APPROOT."\n");
  1163. foreach ($aAvailableModules as $sModuleId => $aModuleData)
  1164. {
  1165. if ($sModuleId == '_Root_') continue;
  1166. if ($aModuleData['version_db'] == '') continue;
  1167. $oPage->add('InstalledModule/'.$sModuleId.': '.$aModuleData['version_db']."\n");
  1168. }
  1169. $oPage->add('===== end =====');
  1170. $oPage->add('</textarea>');
  1171. $oPage->add("</div>");
  1172. $oPage->add("</div>");
  1173. break;
  1174. case 'history':
  1175. $oPage->SetContentType('text/html');
  1176. $id = (int)utils::ReadParam('id', 0);
  1177. $iStart = (int)utils::ReadParam('start', 0);
  1178. $iCount = (int)utils::ReadParam('count', MetaModel::GetConfig()->Get('max_history_length', '50'));
  1179. $oObj = MetaModel::GetObject($sClass, $id);
  1180. $oObj->DisplayBareHistory($oPage, false, $iCount, $iStart);
  1181. $oPage->add_ready_script("$('#history table.listResults').tableHover(); $('#history table.listResults').tablesorter( { widgets: ['myZebra', 'truncatedList']} );");
  1182. break;
  1183. case 'history_from_filter':
  1184. $oPage->SetContentType('text/html');
  1185. $oHistoryFilter = CMDBSearchFilter::unserialize($sFilter);
  1186. $iStart = (int)utils::ReadParam('start', 0);
  1187. $iCount = (int)utils::ReadParam('count', MetaModel::GetConfig()->Get('max_history_length', '50'));
  1188. $oBlock = new HistoryBlock($oHistoryFilter, 'table', false);
  1189. $oBlock->SetLimit($iCount, $iStart);
  1190. $oBlock->Display($oPage, 'history');
  1191. $oPage->add_ready_script("$('#history table.listResults').tableHover(); $('#history table.listResults').tablesorter( { widgets: ['myZebra', 'truncatedList']} );");
  1192. break;
  1193. case 'full_text_search':
  1194. $aFullTextNeedles = utils::ReadParam('needles', array(), false, 'raw_data');
  1195. $sFullText = trim(implode(' ', $aFullTextNeedles));
  1196. $sClassName = utils::ReadParam('class', '');
  1197. $iCount = utils::ReadParam('count', 0);
  1198. $iCurrentPos = utils::ReadParam('position', 0);
  1199. $iTune = utils::ReadParam('tune', 0);
  1200. if (empty($sFullText))
  1201. {
  1202. $oPage->p(Dict::S('UI:Search:NoSearch'));
  1203. break;
  1204. }
  1205. // Search in full text mode in all the classes
  1206. $aMatches = array();
  1207. // Build the ordered list of classes to search into
  1208. //
  1209. if (empty($sClassName))
  1210. {
  1211. $aSearchClasses = MetaModel::GetClasses('searchable');
  1212. }
  1213. else
  1214. {
  1215. // Search is limited to a given class and its subclasses
  1216. $aSearchClasses = MetaModel::EnumChildClasses($sClassName, ENUM_CHILD_CLASSES_ALL);
  1217. }
  1218. $sMaxChunkDuration = MetaModel::GetConfig()->Get('full_text_chunk_duration');
  1219. $aAccelerators = MetaModel::GetConfig()->Get('full_text_accelerators');
  1220. foreach (array_reverse($aAccelerators) as $sClass => $aRestriction)
  1221. {
  1222. $iPos = array_search($sClass, $aSearchClasses);
  1223. if ($iPos !== false)
  1224. {
  1225. unset($aSearchClasses[$iPos]);
  1226. }
  1227. $bSkip = array_key_exists('skip', $aRestriction) ? $aRestriction['skip'] : false ;
  1228. if (!$bSkip)
  1229. {
  1230. // NOT skipped, add the class to the list of classes to search into
  1231. array_unshift($aSearchClasses, $aRestriction['query']);
  1232. }
  1233. }
  1234. $aSearchClasses = array_values($aSearchClasses); // renumbers the array starting from zero, removing the missing indexes
  1235. $fStarted = microtime(true);
  1236. $iFoundInThisRound = 0;
  1237. for($iPos = $iCurrentPos; $iPos < count($aSearchClasses) ; $iPos++)
  1238. {
  1239. if ($iFoundInThisRound && (microtime(true) - $fStarted >= $sMaxChunkDuration))
  1240. {
  1241. break;
  1242. }
  1243. $sClassSpec = $aSearchClasses[$iPos];
  1244. if (substr($sClassSpec, 0, 7) == 'SELECT ')
  1245. {
  1246. $oFilter = DBObjectSearch::FromOQL($sClassSpec);
  1247. $sClassName = $oFilter->GetClass();
  1248. $sNeedleFormat = isset($aAccelerators[$sClassName]['needle']) ? $aAccelerators[$sClassName]['needle'] : '%$needle$%';
  1249. $sNeedle = str_replace('$needle$', $sFullText, $sNeedleFormat);
  1250. $aParams = array('needle' => $sNeedle);
  1251. }
  1252. else
  1253. {
  1254. $sClassName = $sClassSpec;
  1255. $oFilter = new DBObjectSearch($sClassName);
  1256. $aParams = array();
  1257. foreach($aFullTextNeedles as $sSearchText)
  1258. {
  1259. $oFilter->AddCondition_FullText($sSearchText);
  1260. }
  1261. }
  1262. // Skip abstract classes
  1263. if (MetaModel::IsAbstract($sClassName)) continue;
  1264. if ($iTune > 0)
  1265. {
  1266. $fStartedClass = microtime(true);
  1267. }
  1268. $oSet = new DBObjectSet($oFilter, array(), $aParams);
  1269. if (array_key_exists($sClassName, $aAccelerators) && array_key_exists('attributes', $aAccelerators[$sClassName]))
  1270. {
  1271. $oSet->OptimizeColumnLoad(array($oFilter->GetClassAlias() => $aAccelerators[$sClassName]['attributes']));
  1272. }
  1273. $sFullTextJS = addslashes($sFullText);
  1274. $bEnableEnlarge = true;
  1275. if (array_key_exists($sClassName, $aAccelerators) && array_key_exists('enable_enlarge', $aAccelerators[$sClassName]))
  1276. {
  1277. $bEnableEnlarge = $aAccelerators[$sClassName]['enable_enlarge'];
  1278. }
  1279. $sEnlargeTheSearch =
  1280. <<<EOF
  1281. $('.search-class-$sClassName button').attr('disabled', 'disabled');
  1282. $('.search-class-$sClassName h2').append('&nbsp;<img id="indicator" src="../images/indicator.gif">');
  1283. var oParams = {operation: 'full_text_search_enlarge', class: '$sClassName', text: '$sFullTextJS'};
  1284. $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', oParams, function(data) {
  1285. $('.search-class-$sClassName').html(data);
  1286. });
  1287. EOF
  1288. ;
  1289. $sEnlargeButton = '';
  1290. if ($bEnableEnlarge)
  1291. {
  1292. $sEnlargeButton = "&nbsp;<button onclick=\"".htmlentities($sEnlargeTheSearch, ENT_QUOTES, 'UTF-8')."\">".Dict::S('UI:Search:Enlarge')."</button>";
  1293. }
  1294. if ($oSet->Count() > 0)
  1295. {
  1296. $aLeafs = array();
  1297. while($oObj = $oSet->Fetch())
  1298. {
  1299. if (get_class($oObj) == $sClassName)
  1300. {
  1301. $aLeafs[] = $oObj->GetKey();
  1302. $iFoundInThisRound ++;
  1303. }
  1304. }
  1305. $oLeafsFilter = new DBObjectSearch($sClassName);
  1306. if (count($aLeafs) > 0)
  1307. {
  1308. $iCount += count($aLeafs);
  1309. $oPage->add("<div class=\"search-class-result search-class-$sClassName\">\n");
  1310. $oPage->add("<div class=\"page_header\">\n");
  1311. if (array_key_exists($sClassName, $aAccelerators))
  1312. {
  1313. $oPage->add("<h2>".MetaModel::GetClassIcon($sClassName)."&nbsp;<span class=\"hilite\">".Dict::Format('UI:Search:Count_ObjectsOf_Class_Found', count($aLeafs), Metamodel::GetName($sClassName)).$sEnlargeButton."</h2>\n");
  1314. }
  1315. else
  1316. {
  1317. $oPage->add("<h2>".MetaModel::GetClassIcon($sClassName)."&nbsp;<span class=\"hilite\">".Dict::Format('UI:Search:Count_ObjectsOf_Class_Found', count($aLeafs), Metamodel::GetName($sClassName))."</h2>\n");
  1318. }
  1319. $oPage->add("</div>\n");
  1320. $oLeafsFilter->AddCondition('id', $aLeafs, 'IN');
  1321. $oBlock = new DisplayBlock($oLeafsFilter, 'list', false);
  1322. $sBlockId = 'global_search_'.$sClassName;
  1323. $oPage->add('<div id="'.$sBlockId.'">');
  1324. $oBlock->RenderContent($oPage, array('table_id' => $sBlockId, 'currentId' => $sBlockId));
  1325. $oPage->add("</div>\n");
  1326. $oPage->add("</div>\n");
  1327. $oPage->p('&nbsp;'); // Some space ?
  1328. }
  1329. }
  1330. else if (array_key_exists($sClassName, $aAccelerators))
  1331. {
  1332. $oPage->add("<div class=\"search-class-result search-class-$sClassName\">\n");
  1333. $oPage->add("<div class=\"page_header\">\n");
  1334. $oPage->add("<h2>".MetaModel::GetClassIcon($sClassName)."&nbsp;<span class=\"hilite\">".Dict::Format('UI:Search:Count_ObjectsOf_Class_Found', 0, Metamodel::GetName($sClassName)).$sEnlargeButton."</h2>\n");
  1335. $oPage->add("</div>\n");
  1336. $oPage->add("</div>\n");
  1337. $oPage->p('&nbsp;'); // Some space ?
  1338. }
  1339. if ($iTune > 0)
  1340. {
  1341. $fDurationClass = microtime(true) - $fStartedClass;
  1342. $oPage->add_script("oTimeStatistics.$sClassName = $fDurationClass;");
  1343. }
  1344. }
  1345. if ($iPos < count($aSearchClasses))
  1346. {
  1347. $sJSNeedle = json_encode($aFullTextNeedles);
  1348. $oPage->add_ready_script(
  1349. <<<EOF
  1350. var oParams = {operation: 'full_text_search', position: $iPos, needles: $sJSNeedle, count: $iCount, tune: $iTune};
  1351. $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', oParams, function(data) {
  1352. $('#full_text_results').append(data);
  1353. });
  1354. EOF
  1355. );
  1356. }
  1357. else
  1358. {
  1359. // We're done
  1360. $oPage->add_ready_script(
  1361. <<<EOF
  1362. $('#full_text_indicator').hide();
  1363. $('#full_text_progress,#full_text_progress_placeholder').hide(500);
  1364. EOF
  1365. );
  1366. if ($iTune > 0)
  1367. {
  1368. $oPage->add_ready_script(
  1369. <<<EOF
  1370. var sRes = '<h4>Search statistics (tune = 1)</h4><table>';
  1371. sRes += '<thead><tr><th>Class</th><th>Time</th></tr></thead>';
  1372. sRes += '<tbody>';
  1373. var fTotal = 0;
  1374. for (var sClass in oTimeStatistics)
  1375. {
  1376. fTotal = fTotal + oTimeStatistics[sClass];
  1377. fRounded = Math.round(oTimeStatistics[sClass] * 1000) / 1000;
  1378. sRes += '<tr><td>' + sClass + '</td><td>' + fRounded + '</td></tr>';
  1379. }
  1380. fRoundedTotal = Math.round(fTotal * 1000) / 1000;
  1381. sRes += '<tr><td><b>Total</b></td><td><b>' + fRoundedTotal + '</b></td></tr>';
  1382. sRes += '</tbody>';
  1383. sRes += '</table>';
  1384. $('#full_text_results').append(sRes);
  1385. EOF
  1386. );
  1387. }
  1388. if ($iCount == 0)
  1389. {
  1390. $sFullTextSummary = addslashes(Dict::S('UI:Search:NoObjectFound'));
  1391. $oPage->add_ready_script("$('#full_text_results').append('$sFullTextSummary');");
  1392. }
  1393. }
  1394. break;
  1395. case 'full_text_search_enlarge':
  1396. $sFullText = trim(utils::ReadParam('text', '', false, 'raw_data'));
  1397. $sClass = trim(utils::ReadParam('class', ''));
  1398. $iTune = utils::ReadParam('tune', 0);
  1399. if (preg_match('/^"(.*)"$/', $sFullText, $aMatches))
  1400. {
  1401. // The text is surrounded by double-quotes, remove the quotes and treat it as one single expression
  1402. $aFullTextNeedles = array($aMatches[1]);
  1403. }
  1404. else
  1405. {
  1406. // Split the text on the blanks and treat this as a search for <word1> AND <word2> AND <word3>
  1407. $aFullTextNeedles = explode(' ', $sFullText);
  1408. }
  1409. $oFilter = new DBObjectSearch($sClass);
  1410. foreach($aFullTextNeedles as $sSearchText)
  1411. {
  1412. $oFilter->AddCondition_FullText($sSearchText);
  1413. }
  1414. $oSet = new DBObjectSet($oFilter);
  1415. $oPage->add("<div class=\"page_header\">\n");
  1416. $oPage->add("<h2>".MetaModel::GetClassIcon($sClass)."&nbsp;<span class=\"hilite\">".Dict::Format('UI:Search:Count_ObjectsOf_Class_Found', $oSet->Count(), Metamodel::GetName($sClass))."</h2>\n");
  1417. $oPage->add("</div>\n");
  1418. if ($oSet->Count() > 0)
  1419. {
  1420. $aLeafs = array();
  1421. while($oObj = $oSet->Fetch())
  1422. {
  1423. if (get_class($oObj) == $sClass)
  1424. {
  1425. $aLeafs[] = $oObj->GetKey();
  1426. }
  1427. }
  1428. $oLeafsFilter = new DBObjectSearch($sClass);
  1429. if (count($aLeafs) > 0)
  1430. {
  1431. $oLeafsFilter->AddCondition('id', $aLeafs, 'IN');
  1432. $oBlock = new DisplayBlock($oLeafsFilter, 'list', false);
  1433. $sBlockId = 'global_search_'.$sClass;
  1434. $oPage->add('<div id="'.$sBlockId.'">');
  1435. $oBlock->RenderContent($oPage, array('table_id' => $sBlockId, 'currentId' => $sBlockId));
  1436. $oPage->add('</div>');
  1437. $oPage->P('&nbsp;'); // Some space ?
  1438. }
  1439. }
  1440. $oPage->add_ready_script(
  1441. <<<EOF
  1442. $('#full_text_indicator').hide();
  1443. $('#full_text_progress,#full_text_progress_placeholder').hide(500);
  1444. EOF
  1445. );
  1446. break;
  1447. default:
  1448. $oPage->p("Invalid query.");
  1449. }
  1450. $oPage->output();
  1451. }
  1452. catch (Exception $e)
  1453. {
  1454. // note: transform to cope with XSS attacks
  1455. echo htmlentities($e->GetMessage(), ENT_QUOTES, 'utf-8');
  1456. echo "<p>Debug trace: <pre>".$e->getTraceAsString()."</pre></p>\n";
  1457. IssueLog::Error($e->getMessage());
  1458. }
  1459. /**
  1460. * Downloads a document to the browser, either as 'inline' or 'attachment'
  1461. *
  1462. * @param WebPage $oPage The web page for the output
  1463. * @param string $sClass Class name of the object
  1464. * @param mixed $id Identifier of the object
  1465. * @param string $sAttCode Name of the attribute containing the document to download
  1466. * @param string $sContentDisposition Either 'inline' or 'attachment'
  1467. * @return none
  1468. */
  1469. function DownloadDocument(WebPage $oPage, $sClass, $id, $sAttCode, $sContentDisposition = 'attachment')
  1470. {
  1471. try
  1472. {
  1473. $oObj = MetaModel::GetObject($sClass, $id, false, false);
  1474. if (!is_object($oObj))
  1475. {
  1476. throw new Exception("Invalid id ($id) for class '$sClass' - the object does not exist or you are not allowed to view it");
  1477. }
  1478. $oDocument = $oObj->Get($sAttCode);
  1479. if (is_object($oDocument))
  1480. {
  1481. $oPage->TrashUnexpectedOutput();
  1482. $oPage->SetContentType($oDocument->GetMimeType());
  1483. $oPage->SetContentDisposition($sContentDisposition,$oDocument->GetFileName());
  1484. $oPage->add($oDocument->GetData());
  1485. }
  1486. }
  1487. catch(Exception $e)
  1488. {
  1489. $oPage->p($e->getMessage());
  1490. }
  1491. }
  1492. ?>