ajax.render.php 59 KB

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