ajax.render.php 77 KB

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