ajax.render.php 65 KB

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