ajax.render.php 61 KB

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