ajax.render.php 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660
  1. <?php
  2. // Copyright (C) 2010-2014 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[$sAlias.'.'.$aNameSpec[1][0]] = (utils::ReadParam('sort_order', 'asc') == 'asc');
  113. }
  114. else
  115. {
  116. $aOrderBy[$sAlias.'.'.'friendlyname'] = (utils::ReadParam('sort_order', 'asc') == 'asc');
  117. }
  118. }
  119. else
  120. {
  121. $aOrderBy[$sAlias.'.'.'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[$sAlias.'.'.$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. $oPage->add_ready_script("$('.dashboard_contents table.listResults').tableHover(); $('.dashboard_contents table.listResults').tablesorter( { widgets: ['myZebra', 'truncatedList']} );");
  779. break;
  780. case 'dashboard_editor':
  781. $sId = utils::ReadParam('id', '', false, 'raw_data');
  782. ApplicationMenu::LoadAdditionalMenus();
  783. $idx = ApplicationMenu::GetMenuIndexById($sId);
  784. $oMenu = ApplicationMenu::GetMenuNode($idx);
  785. $oMenu->RenderEditor($oPage);
  786. break;
  787. case 'new_dashlet':
  788. require_once(APPROOT.'application/forms.class.inc.php');
  789. require_once(APPROOT.'application/dashlet.class.inc.php');
  790. $sDashletClass = utils::ReadParam('dashlet_class', '');
  791. $sDashletId = utils::ReadParam('dashlet_id', '', false, 'raw_data');
  792. if (is_subclass_of($sDashletClass, 'Dashlet'))
  793. {
  794. $oDashlet = new $sDashletClass(new ModelReflectionRuntime(), $sDashletId);
  795. $offset = $oPage->start_capture();
  796. $oDashlet->DoRender($oPage, true /* bEditMode */, false /* bEnclosingDiv */);
  797. $sHtml = addslashes($oPage->end_capture($offset));
  798. $sHtml = str_replace("\n", '', $sHtml);
  799. $sHtml = str_replace("\r", '', $sHtml);
  800. $oPage->add_script("$('#dashlet_$sDashletId').html('$sHtml');"); // in ajax web page add_script has the same effect as add_ready_script
  801. // but is executed BEFORE all 'ready_scripts'
  802. $oForm = $oDashlet->GetForm(); // Rebuild the form since the values/content changed
  803. $oForm->SetSubmitParams(utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php', array('operation' => 'update_dashlet_property'));
  804. $sHtml = addslashes($oForm->RenderAsPropertySheet($oPage, true /* bReturnHtml */, '.itop-dashboard'));
  805. $sHtml = str_replace("\n", '', $sHtml);
  806. $sHtml = str_replace("\r", '', $sHtml);
  807. $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'
  808. }
  809. break;
  810. case 'update_dashlet_property':
  811. require_once(APPROOT.'application/forms.class.inc.php');
  812. require_once(APPROOT.'application/dashlet.class.inc.php');
  813. $aParams = utils::ReadParam('params', '', false, 'raw_data');
  814. $sDashletClass = $aParams['attr_dashlet_class'];
  815. $sDashletId = $aParams['attr_dashlet_id'];
  816. $aUpdatedProperties = $aParams['updated']; // Code of the changed properties as an array: 'attr_xxx', 'attr_xxy', etc...
  817. $aPreviousValues = $aParams['previous_values']; // hash array: 'attr_xxx' => 'old_value'
  818. if (is_subclass_of($sDashletClass, 'Dashlet'))
  819. {
  820. $oDashlet = new $sDashletClass(new ModelReflectionRuntime(), $sDashletId);
  821. $oForm = $oDashlet->GetForm();
  822. $aValues = $oForm->ReadParams(); // hash array: 'xxx' => 'new_value'
  823. $aCurrentValues = $aValues;
  824. $aUpdatedDecoded = array();
  825. foreach($aUpdatedProperties as $sProp)
  826. {
  827. $sDecodedProp = str_replace('attr_', '', $sProp); // Remove the attr_ prefix
  828. $aCurrentValues[$sDecodedProp] = $aPreviousValues[$sProp]; // Set the previous value
  829. $aUpdatedDecoded[] = $sDecodedProp;
  830. }
  831. $oDashlet->FromParams($aCurrentValues);
  832. $sPrevClass = get_class($oDashlet);
  833. $oDashlet = $oDashlet->Update($aValues, $aUpdatedDecoded);
  834. $sNewClass = get_class($oDashlet);
  835. if ($sNewClass != $sPrevClass)
  836. {
  837. $oPage->add_ready_script("$('#dashlet_$sDashletId').dashlet('option', {dashlet_class: '$sNewClass'});");
  838. }
  839. if ($oDashlet->IsRedrawNeeded())
  840. {
  841. $offset = $oPage->start_capture();
  842. $oDashlet->DoRender($oPage, true /* bEditMode */, false /* bEnclosingDiv */);
  843. $sHtml = addslashes($oPage->end_capture($offset));
  844. $sHtml = str_replace("\n", '', $sHtml);
  845. $sHtml = str_replace("\r", '', $sHtml);
  846. $oPage->add_script("$('#dashlet_$sDashletId').html('$sHtml');"); // in ajax web page add_script has the same effect as add_ready_script
  847. // but is executed BEFORE all 'ready_scripts'
  848. }
  849. if ($oDashlet->IsFormRedrawNeeded())
  850. {
  851. $oForm = $oDashlet->GetForm(); // Rebuild the form since the values/content changed
  852. $oForm->SetSubmitParams(utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php', array('operation' => 'update_dashlet_property'));
  853. $sHtml = addslashes($oForm->RenderAsPropertySheet($oPage, true /* bReturnHtml */, '.itop-dashboard'));
  854. $sHtml = str_replace("\n", '', $sHtml);
  855. $sHtml = str_replace("\r", '', $sHtml);
  856. $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'
  857. // but is executed BEFORE all 'ready_scripts'
  858. }
  859. }
  860. break;
  861. case 'save_dashboard':
  862. $sDashboardId = utils::ReadParam('dashboard_id', '', false, 'raw_data');
  863. $aParams = array();
  864. $aParams['layout_class'] = utils::ReadParam('layout_class', '');
  865. $aParams['title'] = utils::ReadParam('title', '', false, 'raw_data');
  866. $aParams['auto_reload'] = utils::ReadParam('auto_reload', false);
  867. $aParams['auto_reload_sec'] = utils::ReadParam('auto_reload_sec', 300);
  868. $aParams['cells'] = utils::ReadParam('cells', array(), false, 'raw_data');
  869. $oDashboard = new RuntimeDashboard($sDashboardId);
  870. $oDashboard->FromParams($aParams);
  871. $oDashboard->Save();
  872. // trigger a reload of the current page since the dashboard just changed
  873. $oPage->add_ready_script(
  874. <<<EOF
  875. var sLocation = new String(window.location.href);
  876. var sNewLocation = sLocation.replace('&edit=1', '');
  877. 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
  878. window.location.href = sNewLocation;
  879. EOF
  880. );
  881. $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
  882. break;
  883. case 'revert_dashboard':
  884. $sDashboardId = utils::ReadParam('dashboard_id', '', false, 'raw_data');
  885. $oDashboard = new RuntimeDashboard($sDashboardId);
  886. $oDashboard->Revert();
  887. // trigger a reload of the current page since the dashboard just changed
  888. $oPage->add_ready_script("window.location.href=window.location.href;"); // reloads the page, doing a GET even if we arrived via a POST
  889. break;
  890. case 'render_dashboard':
  891. $sDashboardId = utils::ReadParam('dashboard_id', '', false, 'raw_data');
  892. $aParams = array();
  893. $aParams['layout_class'] = utils::ReadParam('layout_class', '');
  894. $aParams['title'] = utils::ReadParam('title', '', false, 'raw_data');
  895. $aParams['cells'] = utils::ReadParam('cells', array(), false, 'raw_data');
  896. $aParams['auto_reload'] = utils::ReadParam('auto_reload', false);
  897. $aParams['auto_reload_sec'] = utils::ReadParam('auto_reload_sec', 300);
  898. $oDashboard = new RuntimeDashboard($sDashboardId);
  899. $oDashboard->FromParams($aParams);
  900. $oDashboard->Render($oPage, true /* bEditMode */);
  901. break;
  902. case 'dashlet_creation_dlg':
  903. $sOQL = utils::ReadParam('oql', '', false, 'raw_data');
  904. RuntimeDashboard::GetDashletCreationDlgFromOQL($oPage, $sOQL);
  905. break;
  906. case 'add_dashlet':
  907. $oForm = RuntimeDashboard::GetDashletCreationForm();
  908. $aValues = $oForm->ReadParams();
  909. $sDashletClass = $aValues['dashlet_class'];
  910. $sMenuId = $aValues['menu_id'];
  911. if (is_subclass_of($sDashletClass, 'Dashlet'))
  912. {
  913. $oDashlet = new $sDashletClass(new ModelReflectionRuntime(), 0);
  914. $oDashlet->FromParams($aValues);
  915. ApplicationMenu::LoadAdditionalMenus();
  916. $index = ApplicationMenu::GetMenuIndexById($sMenuId);
  917. $oMenu = ApplicationMenu::GetMenuNode($index);
  918. $oMenu->AddDashlet($oDashlet);
  919. // navigate to the dashboard page
  920. if ($aValues['open_editor'])
  921. {
  922. $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
  923. }
  924. }
  925. break;
  926. case 'shortcut_list_dlg':
  927. $sOQL = utils::ReadParam('oql', '', false, 'raw_data');
  928. $sTableSettings = utils::ReadParam('table_settings', '', false, 'raw_data');
  929. ShortcutOQL::GetCreationDlgFromOQL($oPage, $sOQL, $sTableSettings);
  930. break;
  931. case 'shortcut_list_create':
  932. $oForm = ShortcutOQL::GetCreationForm();
  933. $aValues = $oForm->ReadParams();
  934. $oAppContext = new ApplicationContext();
  935. $aContext = $oAppContext->GetAsHash();
  936. $sContext = serialize($aContext);
  937. $oShortcut = MetaModel::NewObject("ShortcutOQL");
  938. $oShortcut->Set('user_id', UserRights::GetUserId());
  939. $oShortcut->Set("context", $sContext);
  940. $oShortcut->Set("name", $aValues['name']);
  941. $oShortcut->Set("oql", $aValues['oql']);
  942. $iAutoReload = (int)$aValues['auto_reload_sec'];
  943. if (($aValues['auto_reload']) && ($iAutoReload > 0))
  944. {
  945. $oShortcut->Set("auto_reload_sec", max(5, $iAutoReload));
  946. $oShortcut->Set("auto_reload", 'custom');
  947. }
  948. $iId = $oShortcut->DBInsertNoReload();
  949. $oShortcut->CloneTableSettings($aValues['table_settings']);
  950. // Add the menu node in the right place
  951. //
  952. // Mmmm... already done because the newly created menu is read from the DB
  953. // as soon as we invoke DisplayMenu
  954. // Refresh the menu pane
  955. $aExtraParams = array();
  956. ApplicationMenu::DisplayMenu($oPage, $aExtraParams);
  957. break;
  958. case 'shortcut_rename_dlg':
  959. $oSearch = new DBObjectSearch('Shortcut');
  960. $aShortcuts = utils::ReadMultipleSelection($oSearch);
  961. $iShortcut = $aShortcuts[0];
  962. $oShortcut = MetaModel::GetObject('Shortcut', $iShortcut);
  963. $oShortcut->StartRenameDialog($oPage);
  964. break;
  965. case 'shortcut_rename_go':
  966. $iShortcut = utils::ReadParam('id', 0);
  967. $oShortcut = MetaModel::GetObject('Shortcut', $iShortcut);
  968. $sName = utils::ReadParam('attr_name', '', false, 'raw_data');
  969. if (strlen($sName) > 0)
  970. {
  971. $oShortcut->Set('name', $sName);
  972. $oShortcut->DBUpdate();
  973. $oPage->add_ready_script('window.location.reload();');
  974. }
  975. break;
  976. case 'shortcut_delete_go':
  977. $oSearch = new DBObjectSearch('Shortcut');
  978. $oSearch->AddCondition('user_id', UserRights::GetUserId(), '=');
  979. $aShortcuts = utils::ReadMultipleSelection($oSearch);
  980. foreach ($aShortcuts as $iShortcut)
  981. {
  982. $oShortcut = MetaModel::GetObject('Shortcut', $iShortcut);
  983. $oShortcut->DBDelete();
  984. $oPage->add_ready_script('window.location.reload();');
  985. }
  986. break;
  987. case 'export_dashboard':
  988. $sMenuId = utils::ReadParam('id', '', false, 'raw_data');
  989. ApplicationMenu::LoadAdditionalMenus();
  990. $index = ApplicationMenu::GetMenuIndexById($sMenuId);
  991. $oMenu = ApplicationMenu::GetMenuNode($index);
  992. if ($oMenu instanceof DashboardMenuNode)
  993. {
  994. $oDashboard = $oMenu->GetDashboard();
  995. $oPage->TrashUnexpectedOutput();
  996. $oPage->SetContentType('text/xml');
  997. $oPage->SetContentDisposition('attachment', $oMenu->GetLabel().'.xml');
  998. $oPage->add($oDashboard->ToXml());
  999. }
  1000. break;
  1001. case 'import_dashboard':
  1002. $sMenuId = utils::ReadParam('id', '', false, 'raw_data');
  1003. ApplicationMenu::LoadAdditionalMenus();
  1004. $index = ApplicationMenu::GetMenuIndexById($sMenuId);
  1005. $oMenu = ApplicationMenu::GetMenuNode($index);
  1006. $aResult = array('error' => '');
  1007. try
  1008. {
  1009. if ($oMenu instanceof DashboardMenuNode)
  1010. {
  1011. $oDoc = utils::ReadPostedDocument('dashboard_upload_file');
  1012. $oDashboard = $oMenu->GetDashboard();
  1013. $oDashboard->FromXml($oDoc->GetData());
  1014. $oDashboard->Save();
  1015. }
  1016. else
  1017. {
  1018. $aResult['error'] = 'Dashboard id="'.$sMenuId.'" not found.';
  1019. }
  1020. }
  1021. catch(DOMException $e)
  1022. {
  1023. $aResult = array('error' => Dict::S('UI:Error:InvalidDashboardFile'));
  1024. }
  1025. catch(Exception $e)
  1026. {
  1027. $aResult = array('error' => $e->getMessage());
  1028. }
  1029. $oPage->add(json_encode($aResult));
  1030. break;
  1031. case 'about_box':
  1032. $oPage->SetContentType('text/html');
  1033. $sDialogTitle = addslashes(Dict::S('UI:About:Title'));
  1034. $oPage->add_ready_script(
  1035. <<<EOF
  1036. $('#about_box').dialog({
  1037. width: 700,
  1038. modal: true,
  1039. title: '$sDialogTitle',
  1040. close: function() { $(this).remove(); }
  1041. });
  1042. $("#collapse_support_details").click(function() {
  1043. $("#support_details").slideToggle('normal');
  1044. $("#collapse_support_details").toggleClass('open');
  1045. });
  1046. $('#support_details').toggle();
  1047. EOF
  1048. );
  1049. $sVersionString = Dict::Format('UI:iTopVersion:Long', ITOP_VERSION, ITOP_REVISION, ITOP_BUILD_DATE);
  1050. $sMySQLVersion = CMDBSource::GetDBVersion();
  1051. $sPHPVersion = phpversion();
  1052. $sOSVersion = PHP_OS;
  1053. $sWebServerVersion = $_SERVER["SERVER_SOFTWARE"];
  1054. $sModules = implode(', ', get_loaded_extensions());
  1055. // Get the datamodel directory
  1056. $oFilter = DBObjectSearch::FromOQL('SELECT ModuleInstallation WHERE name="datamodel"');
  1057. $oSet = new DBObjectSet($oFilter, array('installed' => false)); // Most recent first
  1058. $oLastInstall = $oSet->Fetch();
  1059. $sLastInstallDate = $oLastInstall->Get('installed');
  1060. $sDataModelVersion = $oLastInstall->Get('version');
  1061. $aDataModelInfo = json_decode($oLastInstall->Get('comment'), true);
  1062. $sDataModelSourceDir = $aDataModelInfo['source_dir'];
  1063. require_once(APPROOT.'setup/runtimeenv.class.inc.php');
  1064. $sCurrEnv = utils::GetCurrentEnvironment();
  1065. $oRuntimeEnv = new RunTimeEnvironment($sCurrEnv);
  1066. $aSearchDirs = array(APPROOT.$sDataModelSourceDir);
  1067. if (file_exists(APPROOT.'extensions'))
  1068. {
  1069. $aSearchDirs[] = APPROOT.'extensions';
  1070. }
  1071. $aAvailableModules = $oRuntimeEnv->AnalyzeInstallation(MetaModel::GetConfig(), $aSearchDirs);
  1072. require_once(APPROOT.'setup/setuputils.class.inc.php');
  1073. $aLicenses = SetupUtils::GetLicenses();
  1074. $aItopSettings = array('cron_max_execution_time', 'timezone');
  1075. $aPHPSettings = array('memory_limit', 'max_execution_time', 'upload_max_filesize', 'post_max_size');
  1076. $aMySQLSettings = array('max_allowed_packet', 'key_buffer_size', 'query_cache_size');
  1077. $aMySQLStatuses = array('Key_read_requests', 'Key_reads');
  1078. if (extension_loaded('suhosin'))
  1079. {
  1080. $aPHPSettings[] = 'suhosin.post.max_vars';
  1081. $aPHPSettings[] = 'suhosin.get.max_value_length';
  1082. }
  1083. $aMySQLVars = array();
  1084. foreach (CMDBSource::QueryToArray('SHOW VARIABLES') as $aRow)
  1085. {
  1086. $aMySQLVars[$aRow['Variable_name']] = $aRow['Value'];
  1087. }
  1088. $aMySQLStats = array();
  1089. foreach (CMDBSource::QueryToArray('SHOW GLOBAL STATUS') as $aRow)
  1090. {
  1091. $aMySQLStats[$aRow['Variable_name']] = $aRow['Value'];
  1092. }
  1093. // Display
  1094. //
  1095. $oPage->add("<div id=\"about_box\">");
  1096. $oPage->add('<div style="margin-left: 120px;">');
  1097. $oPage->add('<table>');
  1098. $oPage->add('<tr>');
  1099. $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>');
  1100. $oPage->add('<td style="padding-left: 20px;">');
  1101. $oPage->add($sVersionString.'<br/>');
  1102. $oPage->add(Dict::S('UI:About:DataModel').': '.$sDataModelVersion.'<br/>');
  1103. $oPage->add('MySQL: '.$sMySQLVersion.'<br/>');
  1104. $oPage->add('PHP: '.$sPHPVersion.'<br/>');
  1105. $oPage->add('</td>');
  1106. $oPage->add('</tr>');
  1107. $oPage->add('</table>');
  1108. $oPage->add("</div>");
  1109. $oPage->add("<div>");
  1110. $oPage->add('<fieldset>');
  1111. $oPage->add('<legend>'.Dict::S('UI:About:Licenses').'</legend>');
  1112. $oPage->add('<ul style="margin: 0; font-size: smaller;">');
  1113. foreach($aLicenses as $index => $oLicense)
  1114. {
  1115. $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>)');
  1116. $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>');
  1117. $oPage->add_ready_script('$("#toggle_'.$index.'").click( function() { $("#license_'.$index.'").slideToggle("normal"); } );');
  1118. }
  1119. $oPage->add('</ul>');
  1120. $oPage->add('</fieldset>');
  1121. $oPage->add("</div>");
  1122. $oPage->add('<fieldset>');
  1123. $oPage->add('<legend>'.Dict::S('UI:About:Modules').'</legend>');
  1124. //$oPage->add(print_r($aAvailableModules, true));
  1125. $oPage->add("<div style=\"height: 150px; overflow: auto; font-size: smaller;\">");
  1126. $oPage->add('<ul style="margin: 0;">');
  1127. foreach ($aAvailableModules as $sModuleId => $aModuleData)
  1128. {
  1129. if ($sModuleId == '_Root_') continue;
  1130. if (!$aModuleData['visible']) continue;
  1131. if ($aModuleData['version_db'] == '') continue;
  1132. $oPage->add('<li>'.$aModuleData['label'].' ('.$aModuleData['version_db'].')</li>');
  1133. }
  1134. $oPage->add('</ul>');
  1135. $oPage->add("</div>");
  1136. $oPage->add('</fieldset>');
  1137. // MUST NOT be localized, as the information given here will be sent to the support
  1138. $oPage->add("<a id=\"collapse_support_details\" class=\"CollapsibleLabel\" href=\"#\">".Dict::S('UI:About:Support')."</a></br>\n");
  1139. $oPage->add("<div id=\"support_details\">");
  1140. $oPage->add('<textarea readonly style="width: 660px; height: 150px; font-size: smaller;">');
  1141. $oPage->add("===== begin =====\n");
  1142. $oPage->add('iTopVersion: '.ITOP_VERSION."\n");
  1143. $oPage->add('iTopBuild: '.ITOP_REVISION."\n");
  1144. $oPage->add('iTopBuildDate: '.ITOP_BUILD_DATE."\n");
  1145. $oPage->add('DataModelVersion: '.$sDataModelVersion."\n");
  1146. $oPage->add('MySQLVersion: '.$sMySQLVersion."\n");
  1147. $oPage->add('PHPVersion: '. $sPHPVersion."\n");
  1148. $oPage->add('OSVersion: '.$sOSVersion."\n");
  1149. $oPage->add('WebServerVersion: '.$sWebServerVersion."\n");
  1150. $oPage->add('PHPModules: '.$sModules."\n");
  1151. foreach ($aItopSettings as $siTopVar)
  1152. {
  1153. $oPage->add('ItopSetting/'.$siTopVar.': '.MetaModel::GetConfig()->Get($siTopVar)."\n");
  1154. }
  1155. foreach ($aPHPSettings as $sPHPVar)
  1156. {
  1157. $oPage->add('PHPSetting/'.$sPHPVar.': '.ini_get($sPHPVar)."\n");
  1158. }
  1159. foreach ($aMySQLSettings as $sMySQLVar)
  1160. {
  1161. $oPage->add('MySQLSetting/'.$sMySQLVar.': '.$aMySQLVars[$sMySQLVar]."\n");
  1162. }
  1163. foreach ($aMySQLStatuses as $sMySQLStatus)
  1164. {
  1165. $oPage->add('MySQLStatus/'.$sMySQLStatus.': '.$aMySQLStats[$sMySQLStatus]."\n");
  1166. }
  1167. $oPage->add('InstallDate: '.$sLastInstallDate."\n");
  1168. $oPage->add('InstallPath: '.APPROOT."\n");
  1169. foreach ($aAvailableModules as $sModuleId => $aModuleData)
  1170. {
  1171. if ($sModuleId == '_Root_') continue;
  1172. if ($aModuleData['version_db'] == '') continue;
  1173. $oPage->add('InstalledModule/'.$sModuleId.': '.$aModuleData['version_db']."\n");
  1174. }
  1175. $oPage->add('===== end =====');
  1176. $oPage->add('</textarea>');
  1177. $oPage->add("</div>");
  1178. $oPage->add("</div>");
  1179. break;
  1180. case 'history':
  1181. $oPage->SetContentType('text/html');
  1182. $id = (int)utils::ReadParam('id', 0);
  1183. $iStart = (int)utils::ReadParam('start', 0);
  1184. $iCount = (int)utils::ReadParam('count', MetaModel::GetConfig()->Get('max_history_length', '50'));
  1185. $oObj = MetaModel::GetObject($sClass, $id);
  1186. $oObj->DisplayBareHistory($oPage, false, $iCount, $iStart);
  1187. $oPage->add_ready_script("$('#history table.listResults').tableHover(); $('#history table.listResults').tablesorter( { widgets: ['myZebra', 'truncatedList']} );");
  1188. break;
  1189. case 'history_from_filter':
  1190. $oPage->SetContentType('text/html');
  1191. $oHistoryFilter = CMDBSearchFilter::unserialize($sFilter);
  1192. $iStart = (int)utils::ReadParam('start', 0);
  1193. $iCount = (int)utils::ReadParam('count', MetaModel::GetConfig()->Get('max_history_length', '50'));
  1194. $oBlock = new HistoryBlock($oHistoryFilter, 'table', false);
  1195. $oBlock->SetLimit($iCount, $iStart);
  1196. $oBlock->Display($oPage, 'history');
  1197. $oPage->add_ready_script("$('#history table.listResults').tableHover(); $('#history table.listResults').tablesorter( { widgets: ['myZebra', 'truncatedList']} );");
  1198. break;
  1199. case 'full_text_search':
  1200. $aFullTextNeedles = utils::ReadParam('needles', array(), false, 'raw_data');
  1201. $sFullText = trim(implode(' ', $aFullTextNeedles));
  1202. $sClassName = utils::ReadParam('class', '');
  1203. $iCount = utils::ReadParam('count', 0);
  1204. $iCurrentPos = utils::ReadParam('position', 0);
  1205. $iTune = utils::ReadParam('tune', 0);
  1206. if (empty($sFullText))
  1207. {
  1208. $oPage->p(Dict::S('UI:Search:NoSearch'));
  1209. break;
  1210. }
  1211. // Search in full text mode in all the classes
  1212. $aMatches = array();
  1213. // Build the ordered list of classes to search into
  1214. //
  1215. if (empty($sClassName))
  1216. {
  1217. $aSearchClasses = MetaModel::GetClasses('searchable');
  1218. }
  1219. else
  1220. {
  1221. // Search is limited to a given class and its subclasses
  1222. $aSearchClasses = MetaModel::EnumChildClasses($sClassName, ENUM_CHILD_CLASSES_ALL);
  1223. }
  1224. // Skip abstract classes, since we search in all the child classes anyway
  1225. foreach($aSearchClasses as $idx => $sClass)
  1226. {
  1227. if (MetaModel::IsAbstract($sClass))
  1228. {
  1229. unset($aSearchClasses[$idx]);
  1230. }
  1231. }
  1232. $sMaxChunkDuration = MetaModel::GetConfig()->Get('full_text_chunk_duration');
  1233. $aAccelerators = MetaModel::GetConfig()->Get('full_text_accelerators');
  1234. foreach (array_reverse($aAccelerators) as $sClass => $aRestriction)
  1235. {
  1236. $bSkip = false;
  1237. $iPos = array_search($sClass, $aSearchClasses);
  1238. if ($iPos !== false)
  1239. {
  1240. unset($aSearchClasses[$iPos]);
  1241. }
  1242. else
  1243. {
  1244. $bSkip = true;
  1245. }
  1246. $bSkip |= array_key_exists('skip', $aRestriction) ? $aRestriction['skip'] : false ;
  1247. if (!in_array($sClass, $aSearchClasses))
  1248. if ($sClass == $sClassName)
  1249. {
  1250. // Class explicitely requested, do NOT skip it
  1251. // beware: there may not be a 'query' defined for a skipped class !
  1252. $bSkip = false;
  1253. }
  1254. if (!$bSkip)
  1255. {
  1256. // NOT skipped, add the class to the list of classes to search into
  1257. if (array_key_exists('query', $aRestriction))
  1258. {
  1259. array_unshift($aSearchClasses, $aRestriction['query']);
  1260. }
  1261. else
  1262. {
  1263. // No accelerator query
  1264. array_unshift($aSearchClasses, $sClassName);
  1265. }
  1266. }
  1267. }
  1268. $aSearchClasses = array_values($aSearchClasses); // renumbers the array starting from zero, removing the missing indexes
  1269. $fStarted = microtime(true);
  1270. $iFoundInThisRound = 0;
  1271. for($iPos = $iCurrentPos; $iPos < count($aSearchClasses) ; $iPos++)
  1272. {
  1273. if ($iFoundInThisRound && (microtime(true) - $fStarted >= $sMaxChunkDuration))
  1274. {
  1275. break;
  1276. }
  1277. $sClassSpec = $aSearchClasses[$iPos];
  1278. if (substr($sClassSpec, 0, 7) == 'SELECT ')
  1279. {
  1280. $oFilter = DBObjectSearch::FromOQL($sClassSpec);
  1281. $sClassName = $oFilter->GetClass();
  1282. $sNeedleFormat = isset($aAccelerators[$sClassName]['needle']) ? $aAccelerators[$sClassName]['needle'] : '%$needle$%';
  1283. $sNeedle = str_replace('$needle$', $sFullText, $sNeedleFormat);
  1284. $aParams = array('needle' => $sNeedle);
  1285. }
  1286. else
  1287. {
  1288. $sClassName = $sClassSpec;
  1289. $oFilter = new DBObjectSearch($sClassName);
  1290. $aParams = array();
  1291. foreach($aFullTextNeedles as $sSearchText)
  1292. {
  1293. $oFilter->AddCondition_FullText($sSearchText);
  1294. }
  1295. }
  1296. // Skip abstract classes
  1297. if (MetaModel::IsAbstract($sClassName)) continue;
  1298. if ($iTune > 0)
  1299. {
  1300. $fStartedClass = microtime(true);
  1301. }
  1302. $oSet = new DBObjectSet($oFilter, array(), $aParams);
  1303. if (array_key_exists($sClassName, $aAccelerators) && array_key_exists('attributes', $aAccelerators[$sClassName]))
  1304. {
  1305. $oSet->OptimizeColumnLoad(array($oFilter->GetClassAlias() => $aAccelerators[$sClassName]['attributes']));
  1306. }
  1307. $sFullTextJS = addslashes($sFullText);
  1308. $bEnableEnlarge = array_key_exists($sClassName, $aAccelerators) && array_key_exists('query', $aAccelerators[$sClassName]);
  1309. if (array_key_exists($sClassName, $aAccelerators) && array_key_exists('enable_enlarge', $aAccelerators[$sClassName]))
  1310. {
  1311. $bEnableEnlarge &= $aAccelerators[$sClassName]['enable_enlarge'];
  1312. }
  1313. $sEnlargeTheSearch =
  1314. <<<EOF
  1315. $('.search-class-$sClassName button').attr('disabled', 'disabled');
  1316. $('.search-class-$sClassName h2').append('&nbsp;<img id="indicator" src="../images/indicator.gif">');
  1317. var oParams = {operation: 'full_text_search_enlarge', class: '$sClassName', text: '$sFullTextJS'};
  1318. $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', oParams, function(data) {
  1319. $('.search-class-$sClassName').html(data);
  1320. });
  1321. EOF
  1322. ;
  1323. $sEnlargeButton = '';
  1324. if ($bEnableEnlarge)
  1325. {
  1326. $sEnlargeButton = "&nbsp;<button onclick=\"".htmlentities($sEnlargeTheSearch, ENT_QUOTES, 'UTF-8')."\">".Dict::S('UI:Search:Enlarge')."</button>";
  1327. }
  1328. if ($oSet->Count() > 0)
  1329. {
  1330. $aLeafs = array();
  1331. while($oObj = $oSet->Fetch())
  1332. {
  1333. if (get_class($oObj) == $sClassName)
  1334. {
  1335. $aLeafs[] = $oObj->GetKey();
  1336. $iFoundInThisRound ++;
  1337. }
  1338. }
  1339. $oLeafsFilter = new DBObjectSearch($sClassName);
  1340. if (count($aLeafs) > 0)
  1341. {
  1342. $iCount += count($aLeafs);
  1343. $oPage->add("<div class=\"search-class-result search-class-$sClassName\">\n");
  1344. $oPage->add("<div class=\"page_header\">\n");
  1345. if (array_key_exists($sClassName, $aAccelerators))
  1346. {
  1347. $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");
  1348. }
  1349. else
  1350. {
  1351. $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");
  1352. }
  1353. $oPage->add("</div>\n");
  1354. $oLeafsFilter->AddCondition('id', $aLeafs, 'IN');
  1355. $oBlock = new DisplayBlock($oLeafsFilter, 'list', false);
  1356. $sBlockId = 'global_search_'.$sClassName;
  1357. $oPage->add('<div id="'.$sBlockId.'">');
  1358. $oBlock->RenderContent($oPage, array('table_id' => $sBlockId, 'currentId' => $sBlockId));
  1359. $oPage->add("</div>\n");
  1360. $oPage->add("</div>\n");
  1361. $oPage->p('&nbsp;'); // Some space ?
  1362. }
  1363. }
  1364. else if (array_key_exists($sClassName, $aAccelerators))
  1365. {
  1366. $oPage->add("<div class=\"search-class-result search-class-$sClassName\">\n");
  1367. $oPage->add("<div class=\"page_header\">\n");
  1368. $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");
  1369. $oPage->add("</div>\n");
  1370. $oPage->add("</div>\n");
  1371. $oPage->p('&nbsp;'); // Some space ?
  1372. }
  1373. if ($iTune > 0)
  1374. {
  1375. $fDurationClass = microtime(true) - $fStartedClass;
  1376. $oPage->add_script("oTimeStatistics.$sClassName = $fDurationClass;");
  1377. }
  1378. }
  1379. if ($iPos < count($aSearchClasses))
  1380. {
  1381. $sJSNeedle = json_encode($aFullTextNeedles);
  1382. $oPage->add_ready_script(
  1383. <<<EOF
  1384. var oParams = {operation: 'full_text_search', position: $iPos, needles: $sJSNeedle, count: $iCount, tune: $iTune};
  1385. $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', oParams, function(data) {
  1386. $('#full_text_results').append(data);
  1387. });
  1388. EOF
  1389. );
  1390. }
  1391. else
  1392. {
  1393. // We're done
  1394. $oPage->add_ready_script(
  1395. <<<EOF
  1396. $('#full_text_indicator').hide();
  1397. $('#full_text_progress,#full_text_progress_placeholder').hide(500);
  1398. EOF
  1399. );
  1400. if ($iTune > 0)
  1401. {
  1402. $oPage->add_ready_script(
  1403. <<<EOF
  1404. var sRes = '<h4>Search statistics (tune = 1)</h4><table>';
  1405. sRes += '<thead><tr><th>Class</th><th>Time</th></tr></thead>';
  1406. sRes += '<tbody>';
  1407. var fTotal = 0;
  1408. for (var sClass in oTimeStatistics)
  1409. {
  1410. fTotal = fTotal + oTimeStatistics[sClass];
  1411. fRounded = Math.round(oTimeStatistics[sClass] * 1000) / 1000;
  1412. sRes += '<tr><td>' + sClass + '</td><td>' + fRounded + '</td></tr>';
  1413. }
  1414. fRoundedTotal = Math.round(fTotal * 1000) / 1000;
  1415. sRes += '<tr><td><b>Total</b></td><td><b>' + fRoundedTotal + '</b></td></tr>';
  1416. sRes += '</tbody>';
  1417. sRes += '</table>';
  1418. $('#full_text_results').append(sRes);
  1419. EOF
  1420. );
  1421. }
  1422. if ($iCount == 0)
  1423. {
  1424. $sFullTextSummary = addslashes(Dict::S('UI:Search:NoObjectFound'));
  1425. $oPage->add_ready_script("$('#full_text_results').append('<div id=\"no_object_found\">$sFullTextSummary</div>');");
  1426. }
  1427. }
  1428. break;
  1429. case 'full_text_search_enlarge':
  1430. $sFullText = trim(utils::ReadParam('text', '', false, 'raw_data'));
  1431. $sClass = trim(utils::ReadParam('class', ''));
  1432. $iTune = utils::ReadParam('tune', 0);
  1433. if (preg_match('/^"(.*)"$/', $sFullText, $aMatches))
  1434. {
  1435. // The text is surrounded by double-quotes, remove the quotes and treat it as one single expression
  1436. $aFullTextNeedles = array($aMatches[1]);
  1437. }
  1438. else
  1439. {
  1440. // Split the text on the blanks and treat this as a search for <word1> AND <word2> AND <word3>
  1441. $aFullTextNeedles = explode(' ', $sFullText);
  1442. }
  1443. $oFilter = new DBObjectSearch($sClass);
  1444. foreach($aFullTextNeedles as $sSearchText)
  1445. {
  1446. $oFilter->AddCondition_FullText($sSearchText);
  1447. }
  1448. $oSet = new DBObjectSet($oFilter);
  1449. $oPage->add("<div class=\"page_header\">\n");
  1450. $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");
  1451. $oPage->add("</div>\n");
  1452. if ($oSet->Count() > 0)
  1453. {
  1454. $aLeafs = array();
  1455. while($oObj = $oSet->Fetch())
  1456. {
  1457. if (get_class($oObj) == $sClass)
  1458. {
  1459. $aLeafs[] = $oObj->GetKey();
  1460. }
  1461. }
  1462. $oLeafsFilter = new DBObjectSearch($sClass);
  1463. if (count($aLeafs) > 0)
  1464. {
  1465. $oLeafsFilter->AddCondition('id', $aLeafs, 'IN');
  1466. $oBlock = new DisplayBlock($oLeafsFilter, 'list', false);
  1467. $sBlockId = 'global_search_'.$sClass;
  1468. $oPage->add('<div id="'.$sBlockId.'">');
  1469. $oBlock->RenderContent($oPage, array('table_id' => $sBlockId, 'currentId' => $sBlockId));
  1470. $oPage->add('</div>');
  1471. $oPage->P('&nbsp;'); // Some space ?
  1472. // Hide "no object found"
  1473. $oPage->add_ready_script('$("#no_object_found").hide();');
  1474. }
  1475. }
  1476. $oPage->add_ready_script(
  1477. <<<EOF
  1478. $('#full_text_indicator').hide();
  1479. $('#full_text_progress,#full_text_progress_placeholder').hide(500);
  1480. EOF
  1481. );
  1482. break;
  1483. default:
  1484. $oPage->p("Invalid query.");
  1485. }
  1486. $oPage->output();
  1487. }
  1488. catch (Exception $e)
  1489. {
  1490. // note: transform to cope with XSS attacks
  1491. echo htmlentities($e->GetMessage(), ENT_QUOTES, 'utf-8');
  1492. echo "<p>Debug trace: <pre>".$e->getTraceAsString()."</pre></p>\n";
  1493. IssueLog::Error($e->getMessage());
  1494. }
  1495. /**
  1496. * Downloads a document to the browser, either as 'inline' or 'attachment'
  1497. *
  1498. * @param WebPage $oPage The web page for the output
  1499. * @param string $sClass Class name of the object
  1500. * @param mixed $id Identifier of the object
  1501. * @param string $sAttCode Name of the attribute containing the document to download
  1502. * @param string $sContentDisposition Either 'inline' or 'attachment'
  1503. * @return none
  1504. */
  1505. function DownloadDocument(WebPage $oPage, $sClass, $id, $sAttCode, $sContentDisposition = 'attachment')
  1506. {
  1507. try
  1508. {
  1509. $oObj = MetaModel::GetObject($sClass, $id, false, false);
  1510. if (!is_object($oObj))
  1511. {
  1512. throw new Exception("Invalid id ($id) for class '$sClass' - the object does not exist or you are not allowed to view it");
  1513. }
  1514. $oDocument = $oObj->Get($sAttCode);
  1515. if (is_object($oDocument))
  1516. {
  1517. $oPage->TrashUnexpectedOutput();
  1518. $oPage->SetContentType($oDocument->GetMimeType());
  1519. $oPage->SetContentDisposition($sContentDisposition,$oDocument->GetFileName());
  1520. $oPage->add($oDocument->GetData());
  1521. }
  1522. }
  1523. catch(Exception $e)
  1524. {
  1525. $oPage->p($e->getMessage());
  1526. }
  1527. }
  1528. ?>