ajax.render.php 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461
  1. <?php
  2. // Copyright (C) 2010-2016 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-2016 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 = DBSearch::FromOQL($sFilter);
  73. }
  74. else
  75. {
  76. $oFilter = DBSearch::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($oObj);
  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 = DBSearch::FromOQL($sFilter);
  613. }
  614. else
  615. {
  616. $oFilter = DBSearch::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 = DBSearch::FromOQL($sFilter);
  649. }
  650. else
  651. {
  652. $oFilter = DBSearch::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 '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. $aParams = utils::ReadParam('params', array(), false, 'raw_data');
  669. if ($sFilter != '')
  670. {
  671. $oFilter = DBSearch::unserialize($sFilter);
  672. $oDisplayBlock = new DisplayBlock($oFilter, 'chart_ajax', false);
  673. $oDisplayBlock->RenderContent($oPage, $aParams);
  674. }
  675. else
  676. {
  677. $oPage->add("<chart>\n<chart_type>3d pie</chart_type><!-- empty filter '$sFilter' --></chart>\n.");
  678. }
  679. break;
  680. case 'modal_details':
  681. $oPage->SetContentType('text/html');
  682. $key = utils::ReadParam('id', 0);
  683. $oFilter = new DBObjectSearch($sClass);
  684. $oFilter->AddCondition('id', $key, '=');
  685. $oPage->Add("<p style=\"width:100%; margin-top:-5px;padding:3px; background-color:#33f; color:#fff;\">Object Details</p>\n");
  686. $oDisplayBlock = new DisplayBlock($oFilter, 'details', false);
  687. $oDisplayBlock->RenderContent($oPage);
  688. $oPage->Add("<input type=\"button\" class=\"jqmClose\" value=\" Close \" />\n");
  689. break;
  690. case 'link':
  691. $oPage->SetContentType('text/html');
  692. $sClass = utils::ReadParam('sclass', 'logInfra', false, 'class');
  693. $sAttCode = utils::ReadParam('attCode', 'name');
  694. //$sOrg = utils::ReadParam('org_id', '');
  695. $sName = utils::ReadParam('q', '');
  696. $iMaxCount = utils::ReadParam('max', 30);
  697. $iCount = 0;
  698. $oFilter = new DBObjectSearch($sClass);
  699. $oFilter->AddCondition($sAttCode, $sName, 'Begins with');
  700. //$oFilter->AddCondition('org_id', $sOrg, '=');
  701. $oSet = new CMDBObjectSet($oFilter, array($sAttCode => true));
  702. while( ($iCount < $iMaxCount) && ($oObj = $oSet->fetch()) )
  703. {
  704. $oPage->add($oObj->GetAsHTML($sAttCode)."|".$oObj->GetKey()."\n");
  705. $iCount++;
  706. }
  707. break;
  708. case 'combo_options':
  709. $oPage->SetContentType('text/html');
  710. $oFilter = DBSearch::FromOQL($sFilter);
  711. $oSet = new CMDBObjectSet($oFilter);
  712. while( $oObj = $oSet->fetch())
  713. {
  714. $oPage->add('<option title="Here is more information..." value="'.$oObj->GetKey().'">'.$oObj->GetName().'</option>');
  715. }
  716. break;
  717. case 'display_document':
  718. $id = utils::ReadParam('id', '');
  719. $sField = utils::ReadParam('field', '');
  720. if (!empty($sClass) && ($sClass != 'InlineImage') && !empty($id) && !empty($sField))
  721. {
  722. ormDocument::DownloadDocument($oPage, $sClass, $id, $sField, 'inline');
  723. }
  724. break;
  725. case 'search_form':
  726. $oPage->SetContentType('text/html');
  727. $sClass = utils::ReadParam('className', '', false, 'class');
  728. $sRootClass = utils::ReadParam('baseClass', '', false, 'class');
  729. $currentId = utils::ReadParam('currentId', '');
  730. $sTableId = utils::ReadParam('_table_id_', null, false, 'raw_data');
  731. $sAction = utils::ReadParam('action', '');
  732. $oFilter = new DBObjectSearch($sClass);
  733. $oSet = new CMDBObjectSet($oFilter);
  734. $sHtml = cmdbAbstractObject::GetSearchForm($oPage, $oSet, array('currentId' => $currentId, 'baseClass' => $sRootClass, 'action' => $sAction, 'table_id' => $sTableId));
  735. $oPage->add($sHtml);
  736. break;
  737. case 'set_pref':
  738. $sCode = utils::ReadPostedParam('code', '');
  739. $sValue = utils::ReadPostedParam('value', '', 'raw_data');
  740. appUserPreferences::SetPref($sCode, $sValue);
  741. break;
  742. case 'erase_all_pref':
  743. // Can be useful in case a user got some corrupted prefs...
  744. appUserPreferences::ClearPreferences();
  745. break;
  746. case 'on_form_cancel':
  747. // Called when a creation/modification form is cancelled by the end-user
  748. // Let's take this opportunity to inform the plug-ins so that they can perform some cleanup
  749. $iTransactionId = utils::ReadParam('transaction_id', 0);
  750. $sTempId = session_id().'_'.$iTransactionId;
  751. InlineImage::OnFormCancel($sTempId);
  752. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  753. {
  754. $oExtensionInstance->OnFormCancel($sTempId);
  755. }
  756. $sObjClass = utils::ReadParam('obj_class', '', false, 'class');
  757. $iObjKey = (int)utils::ReadParam('obj_key', 0, false, 'integer');
  758. $sToken = utils::ReadParam('token', 0, false, 'raw_data');
  759. if (($sObjClass != '') && ($iObjKey != 0) && ($sToken != ''))
  760. {
  761. $bReleaseLock = iTopOwnershipLock::ReleaseLock($sObjClass, $iObjKey, $sToken);
  762. }
  763. break;
  764. case 'reload_dashboard':
  765. $oPage->SetContentType('text/html');
  766. $sDashboardId = utils::ReadParam('dashboard_id', '', false, 'raw_data');
  767. $aExtraParams = utils::ReadParam('extra_params', '', false, 'raw_data');
  768. ApplicationMenu::LoadAdditionalMenus();
  769. $idx = ApplicationMenu::GetMenuIndexById($sDashboardId);
  770. $oMenu = ApplicationMenu::GetMenuNode($idx);
  771. $oDashboard = $oMenu->GetDashboard();
  772. $oDashboard->Render($oPage, false, $aExtraParams);
  773. $oPage->add_ready_script("$('.dashboard_contents table.listResults').tableHover(); $('.dashboard_contents table.listResults').tablesorter( { widgets: ['myZebra', 'truncatedList']} );");
  774. break;
  775. case 'dashboard_editor':
  776. $sId = utils::ReadParam('id', '', false, 'raw_data');
  777. ApplicationMenu::LoadAdditionalMenus();
  778. $idx = ApplicationMenu::GetMenuIndexById($sId);
  779. $oMenu = ApplicationMenu::GetMenuNode($idx);
  780. $oMenu->RenderEditor($oPage);
  781. break;
  782. case 'new_dashlet':
  783. require_once(APPROOT.'application/forms.class.inc.php');
  784. require_once(APPROOT.'application/dashlet.class.inc.php');
  785. $sDashletClass = utils::ReadParam('dashlet_class', '');
  786. $sDashletId = utils::ReadParam('dashlet_id', '', false, 'raw_data');
  787. if (is_subclass_of($sDashletClass, 'Dashlet'))
  788. {
  789. $oDashlet = new $sDashletClass(new ModelReflectionRuntime(), $sDashletId);
  790. $offset = $oPage->start_capture();
  791. $oDashlet->DoRender($oPage, true /* bEditMode */, false /* bEnclosingDiv */);
  792. $sHtml = addslashes($oPage->end_capture($offset));
  793. $sHtml = str_replace("\n", '', $sHtml);
  794. $sHtml = str_replace("\r", '', $sHtml);
  795. $oPage->add_script("$('#dashlet_$sDashletId').html('$sHtml');"); // in ajax web page add_script has the same effect as add_ready_script
  796. // but is executed BEFORE all 'ready_scripts'
  797. $oForm = $oDashlet->GetForm(); // Rebuild the form since the values/content changed
  798. $oForm->SetSubmitParams(utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php', array('operation' => 'update_dashlet_property'));
  799. $sHtml = addslashes($oForm->RenderAsPropertySheet($oPage, true /* bReturnHtml */, '.itop-dashboard'));
  800. $sHtml = str_replace("\n", '', $sHtml);
  801. $sHtml = str_replace("\r", '', $sHtml);
  802. $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'
  803. }
  804. break;
  805. case 'update_dashlet_property':
  806. require_once(APPROOT.'application/forms.class.inc.php');
  807. require_once(APPROOT.'application/dashlet.class.inc.php');
  808. $aParams = utils::ReadParam('params', '', false, 'raw_data');
  809. $sDashletClass = $aParams['attr_dashlet_class'];
  810. $sDashletId = $aParams['attr_dashlet_id'];
  811. $aUpdatedProperties = $aParams['updated']; // Code of the changed properties as an array: 'attr_xxx', 'attr_xxy', etc...
  812. $aPreviousValues = $aParams['previous_values']; // hash array: 'attr_xxx' => 'old_value'
  813. if (is_subclass_of($sDashletClass, 'Dashlet'))
  814. {
  815. $oDashlet = new $sDashletClass(new ModelReflectionRuntime(), $sDashletId);
  816. $oForm = $oDashlet->GetForm();
  817. $aValues = $oForm->ReadParams(); // hash array: 'xxx' => 'new_value'
  818. $aCurrentValues = $aValues;
  819. $aUpdatedDecoded = array();
  820. foreach($aUpdatedProperties as $sProp)
  821. {
  822. $sDecodedProp = str_replace('attr_', '', $sProp); // Remove the attr_ prefix
  823. $aCurrentValues[$sDecodedProp] = $aPreviousValues[$sProp]; // Set the previous value
  824. $aUpdatedDecoded[] = $sDecodedProp;
  825. }
  826. $oDashlet->FromParams($aCurrentValues);
  827. $sPrevClass = get_class($oDashlet);
  828. $oDashlet = $oDashlet->Update($aValues, $aUpdatedDecoded);
  829. $sNewClass = get_class($oDashlet);
  830. if ($sNewClass != $sPrevClass)
  831. {
  832. $oPage->add_ready_script("$('#dashlet_$sDashletId').dashlet('option', {dashlet_class: '$sNewClass'});");
  833. }
  834. if ($oDashlet->IsRedrawNeeded())
  835. {
  836. $offset = $oPage->start_capture();
  837. $oDashlet->DoRender($oPage, true /* bEditMode */, false /* bEnclosingDiv */);
  838. $sHtml = addslashes($oPage->end_capture($offset));
  839. $sHtml = str_replace("\n", '', $sHtml);
  840. $sHtml = str_replace("\r", '', $sHtml);
  841. $oPage->add_script("$('#dashlet_$sDashletId').html('$sHtml');"); // in ajax web page add_script has the same effect as add_ready_script
  842. // but is executed BEFORE all 'ready_scripts'
  843. }
  844. if ($oDashlet->IsFormRedrawNeeded())
  845. {
  846. $oForm = $oDashlet->GetForm(); // Rebuild the form since the values/content changed
  847. $oForm->SetSubmitParams(utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php', array('operation' => 'update_dashlet_property'));
  848. $sHtml = addslashes($oForm->RenderAsPropertySheet($oPage, true /* bReturnHtml */, '.itop-dashboard'));
  849. $sHtml = str_replace("\n", '', $sHtml);
  850. $sHtml = str_replace("\r", '', $sHtml);
  851. $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'
  852. // but is executed BEFORE all 'ready_scripts'
  853. }
  854. }
  855. break;
  856. case 'save_dashboard':
  857. $sDashboardId = utils::ReadParam('dashboard_id', '', false, 'raw_data');
  858. $aParams = array();
  859. $aParams['layout_class'] = utils::ReadParam('layout_class', '');
  860. $aParams['title'] = utils::ReadParam('title', '', false, 'raw_data');
  861. $aParams['auto_reload'] = utils::ReadParam('auto_reload', false);
  862. $aParams['auto_reload_sec'] = utils::ReadParam('auto_reload_sec', 300);
  863. $aParams['cells'] = utils::ReadParam('cells', array(), false, 'raw_data');
  864. $oDashboard = new RuntimeDashboard($sDashboardId);
  865. $oDashboard->FromParams($aParams);
  866. $oDashboard->Save();
  867. // trigger a reload of the current page since the dashboard just changed
  868. $oPage->add_ready_script(
  869. <<<EOF
  870. var sLocation = new String(window.location.href);
  871. var sNewLocation = sLocation.replace('&edit=1', '');
  872. 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
  873. window.location.href = sNewLocation;
  874. EOF
  875. );
  876. $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
  877. break;
  878. case 'revert_dashboard':
  879. $sDashboardId = utils::ReadParam('dashboard_id', '', false, 'raw_data');
  880. $oDashboard = new RuntimeDashboard($sDashboardId);
  881. $oDashboard->Revert();
  882. // trigger a reload of the current page since the dashboard just changed
  883. $oPage->add_ready_script("window.location.href=window.location.href;"); // reloads the page, doing a GET even if we arrived via a POST
  884. break;
  885. case 'render_dashboard':
  886. $sDashboardId = utils::ReadParam('dashboard_id', '', false, 'raw_data');
  887. $aParams = array();
  888. $aParams['layout_class'] = utils::ReadParam('layout_class', '');
  889. $aParams['title'] = utils::ReadParam('title', '', false, 'raw_data');
  890. $aParams['cells'] = utils::ReadParam('cells', array(), false, 'raw_data');
  891. $aParams['auto_reload'] = utils::ReadParam('auto_reload', false);
  892. $aParams['auto_reload_sec'] = utils::ReadParam('auto_reload_sec', 300);
  893. $oDashboard = new RuntimeDashboard($sDashboardId);
  894. $oDashboard->FromParams($aParams);
  895. $oDashboard->Render($oPage, true /* bEditMode */);
  896. break;
  897. case 'dashlet_creation_dlg':
  898. $sOQL = utils::ReadParam('oql', '', false, 'raw_data');
  899. RuntimeDashboard::GetDashletCreationDlgFromOQL($oPage, $sOQL);
  900. break;
  901. case 'add_dashlet':
  902. $oForm = RuntimeDashboard::GetDashletCreationForm();
  903. $aValues = $oForm->ReadParams();
  904. $sDashletClass = $aValues['dashlet_class'];
  905. $sMenuId = $aValues['menu_id'];
  906. if (is_subclass_of($sDashletClass, 'Dashlet'))
  907. {
  908. $oDashlet = new $sDashletClass(new ModelReflectionRuntime(), 0);
  909. $oDashlet->FromParams($aValues);
  910. ApplicationMenu::LoadAdditionalMenus();
  911. $index = ApplicationMenu::GetMenuIndexById($sMenuId);
  912. $oMenu = ApplicationMenu::GetMenuNode($index);
  913. $oMenu->AddDashlet($oDashlet);
  914. // navigate to the dashboard page
  915. if ($aValues['open_editor'])
  916. {
  917. $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
  918. }
  919. }
  920. break;
  921. case 'shortcut_list_dlg':
  922. $sOQL = utils::ReadParam('oql', '', false, 'raw_data');
  923. $sTableSettings = utils::ReadParam('table_settings', '', false, 'raw_data');
  924. ShortcutOQL::GetCreationDlgFromOQL($oPage, $sOQL, $sTableSettings);
  925. break;
  926. case 'shortcut_list_create':
  927. $oForm = ShortcutOQL::GetCreationForm();
  928. $aValues = $oForm->ReadParams();
  929. $oAppContext = new ApplicationContext();
  930. $aContext = $oAppContext->GetAsHash();
  931. $sContext = serialize($aContext);
  932. $oShortcut = MetaModel::NewObject("ShortcutOQL");
  933. $oShortcut->Set('user_id', UserRights::GetUserId());
  934. $oShortcut->Set("context", $sContext);
  935. $oShortcut->Set("name", $aValues['name']);
  936. $oShortcut->Set("oql", $aValues['oql']);
  937. $iAutoReload = (int)$aValues['auto_reload_sec'];
  938. if (($aValues['auto_reload']) && ($iAutoReload > 0))
  939. {
  940. $oShortcut->Set("auto_reload_sec", max(MetaModel::GetConfig()->Get('min_reload_interval'), $iAutoReload));
  941. $oShortcut->Set("auto_reload", 'custom');
  942. }
  943. $iId = $oShortcut->DBInsertNoReload();
  944. $oShortcut->CloneTableSettings($aValues['table_settings']);
  945. // Add the menu node in the right place
  946. //
  947. // Mmmm... already done because the newly created menu is read from the DB
  948. // as soon as we invoke DisplayMenu
  949. // Refresh the menu pane
  950. $aExtraParams = array();
  951. ApplicationMenu::DisplayMenu($oPage, $aExtraParams);
  952. break;
  953. case 'shortcut_rename_dlg':
  954. $oSearch = new DBObjectSearch('Shortcut');
  955. $aShortcuts = utils::ReadMultipleSelection($oSearch);
  956. $iShortcut = $aShortcuts[0];
  957. $oShortcut = MetaModel::GetObject('Shortcut', $iShortcut);
  958. $oShortcut->StartRenameDialog($oPage);
  959. break;
  960. case 'shortcut_rename_go':
  961. $iShortcut = utils::ReadParam('id', 0);
  962. $oShortcut = MetaModel::GetObject('Shortcut', $iShortcut);
  963. $sName = utils::ReadParam('attr_name', '', false, 'raw_data');
  964. if (strlen($sName) > 0)
  965. {
  966. $oShortcut->Set('name', $sName);
  967. $oShortcut->DBUpdate();
  968. $oPage->add_ready_script('window.location.reload();');
  969. }
  970. break;
  971. case 'shortcut_delete_go':
  972. $oSearch = new DBObjectSearch('Shortcut');
  973. $oSearch->AddCondition('user_id', UserRights::GetUserId(), '=');
  974. $aShortcuts = utils::ReadMultipleSelection($oSearch);
  975. foreach ($aShortcuts as $iShortcut)
  976. {
  977. $oShortcut = MetaModel::GetObject('Shortcut', $iShortcut);
  978. $oShortcut->DBDelete();
  979. $oPage->add_ready_script('window.location.reload();');
  980. }
  981. break;
  982. case 'export_dashboard':
  983. $sMenuId = utils::ReadParam('id', '', false, 'raw_data');
  984. ApplicationMenu::LoadAdditionalMenus();
  985. $index = ApplicationMenu::GetMenuIndexById($sMenuId);
  986. $oMenu = ApplicationMenu::GetMenuNode($index);
  987. if ($oMenu instanceof DashboardMenuNode)
  988. {
  989. $oDashboard = $oMenu->GetDashboard();
  990. $oPage->TrashUnexpectedOutput();
  991. $oPage->SetContentType('text/xml');
  992. $oPage->SetContentDisposition('attachment', $oMenu->GetLabel().'.xml');
  993. $oPage->add($oDashboard->ToXml());
  994. }
  995. break;
  996. case 'import_dashboard':
  997. $sMenuId = utils::ReadParam('id', '', false, 'raw_data');
  998. ApplicationMenu::LoadAdditionalMenus();
  999. $index = ApplicationMenu::GetMenuIndexById($sMenuId);
  1000. $oMenu = ApplicationMenu::GetMenuNode($index);
  1001. $aResult = array('error' => '');
  1002. try
  1003. {
  1004. if ($oMenu instanceof DashboardMenuNode)
  1005. {
  1006. $oDoc = utils::ReadPostedDocument('dashboard_upload_file');
  1007. $oDashboard = $oMenu->GetDashboard();
  1008. $oDashboard->FromXml($oDoc->GetData());
  1009. $oDashboard->Save();
  1010. }
  1011. else
  1012. {
  1013. $aResult['error'] = 'Dashboard id="'.$sMenuId.'" not found.';
  1014. }
  1015. }
  1016. catch(DOMException $e)
  1017. {
  1018. $aResult = array('error' => Dict::S('UI:Error:InvalidDashboardFile'));
  1019. }
  1020. catch(Exception $e)
  1021. {
  1022. $aResult = array('error' => $e->getMessage());
  1023. }
  1024. $oPage->add(json_encode($aResult));
  1025. break;
  1026. case 'about_box':
  1027. $oPage->SetContentType('text/html');
  1028. $sDialogTitle = addslashes(Dict::S('UI:About:Title'));
  1029. $oPage->add_ready_script(
  1030. <<<EOF
  1031. $('#about_box').dialog({
  1032. width: 700,
  1033. modal: true,
  1034. title: '$sDialogTitle',
  1035. close: function() { $(this).remove(); }
  1036. });
  1037. $("#collapse_support_details").click(function() {
  1038. $("#support_details").slideToggle('normal');
  1039. $("#collapse_support_details").toggleClass('open');
  1040. });
  1041. $('#support_details').toggle();
  1042. EOF
  1043. );
  1044. $sVersionString = Dict::Format('UI:iTopVersion:Long', ITOP_VERSION, ITOP_REVISION, ITOP_BUILD_DATE);
  1045. $sMySQLVersion = CMDBSource::GetDBVersion();
  1046. $sPHPVersion = phpversion();
  1047. $sOSVersion = PHP_OS;
  1048. $sWebServerVersion = $_SERVER["SERVER_SOFTWARE"];
  1049. $sModules = implode(', ', get_loaded_extensions());
  1050. // Get the datamodel directory
  1051. $oFilter = DBObjectSearch::FromOQL('SELECT ModuleInstallation WHERE name="datamodel"');
  1052. $oSet = new DBObjectSet($oFilter, array('installed' => false)); // Most recent first
  1053. $oLastInstall = $oSet->Fetch();
  1054. $sLastInstallDate = $oLastInstall->Get('installed');
  1055. $sDataModelVersion = $oLastInstall->Get('version');
  1056. $aDataModelInfo = json_decode($oLastInstall->Get('comment'), true);
  1057. $sDataModelSourceDir = $aDataModelInfo['source_dir'];
  1058. require_once(APPROOT.'setup/runtimeenv.class.inc.php');
  1059. $sCurrEnv = utils::GetCurrentEnvironment();
  1060. $oRuntimeEnv = new RunTimeEnvironment($sCurrEnv);
  1061. $aSearchDirs = array(APPROOT.$sDataModelSourceDir);
  1062. if (file_exists(APPROOT.'extensions'))
  1063. {
  1064. $aSearchDirs[] = APPROOT.'extensions';
  1065. }
  1066. $sExtraDir = APPROOT.'data/'.$sCurrEnv.'-modules/';
  1067. if (file_exists($sExtraDir))
  1068. {
  1069. $aSearchDirs[] = $sExtraDir;
  1070. }
  1071. $aAvailableModules = $oRuntimeEnv->AnalyzeInstallation(MetaModel::GetConfig(), $aSearchDirs);
  1072. require_once(APPROOT.'setup/setuputils.class.inc.php');
  1073. $aLicenses = SetupUtils::GetLicenses();
  1074. $aItopSettings = array('cron_max_execution_time', 'timezone');
  1075. $aPHPSettings = array('memory_limit', 'max_execution_time', 'upload_max_filesize', 'post_max_size');
  1076. $aMySQLSettings = array('max_allowed_packet', 'key_buffer_size', 'query_cache_size');
  1077. $aMySQLStatuses = array('Key_read_requests', 'Key_reads');
  1078. if (extension_loaded('suhosin'))
  1079. {
  1080. $aPHPSettings[] = 'suhosin.post.max_vars';
  1081. $aPHPSettings[] = 'suhosin.get.max_value_length';
  1082. }
  1083. $aMySQLVars = array();
  1084. foreach (CMDBSource::QueryToArray('SHOW VARIABLES') as $aRow)
  1085. {
  1086. $aMySQLVars[$aRow['Variable_name']] = $aRow['Value'];
  1087. }
  1088. $aMySQLStats = array();
  1089. foreach (CMDBSource::QueryToArray('SHOW GLOBAL STATUS') as $aRow)
  1090. {
  1091. $aMySQLStats[$aRow['Variable_name']] = $aRow['Value'];
  1092. }
  1093. // Display
  1094. //
  1095. $oPage->add("<div id=\"about_box\">");
  1096. $oPage->add('<div style="margin-left: 120px;">');
  1097. $oPage->add('<table>');
  1098. $oPage->add('<tr>');
  1099. $oPage->add('<td><a href="http://www.combodo.com" title="www.combodo.com" target="_blank" style="background: none;"><img src="../images/logo-combodo.png?itopversion='.ITOP_VERSION.'" style="float: right;"/></a></td>');
  1100. $oPage->add('<td style="padding-left: 20px;">');
  1101. $oPage->add($sVersionString.'<br/>');
  1102. $oPage->add(Dict::S('UI:About:DataModel').': '.$sDataModelVersion.'<br/>');
  1103. $oPage->add('MySQL: '.$sMySQLVersion.'<br/>');
  1104. $oPage->add('PHP: '.$sPHPVersion.'<br/>');
  1105. $oPage->add('</td>');
  1106. $oPage->add('</tr>');
  1107. $oPage->add('</table>');
  1108. $oPage->add("</div>");
  1109. $oPage->add("<div>");
  1110. $oPage->add('<fieldset>');
  1111. $oPage->add('<legend>'.Dict::S('UI:About:Licenses').'</legend>');
  1112. $oPage->add('<ul style="margin: 0; font-size: smaller;">');
  1113. foreach($aLicenses as $index => $oLicense)
  1114. {
  1115. $oPage->add('<li><b>'.$oLicense->product.'</b>, &copy; '.$oLicense->author.' is licensed under the <b>'.$oLicense->license_type.' license</b>. (<a id="toggle_'.$index.'" class="CollapsibleLabel" style="cursor:pointer;">Details</a>)');
  1116. $oPage->add('<div id="license_'.$index.'" class="license_text" style="display:none;overflow:auto;max-height:10em;font-size:small;border:1px #696969 solid;margin-bottom:1em; margin-top:0.5em;padding:0.5em;">'.$oLicense->text.'</div>');
  1117. $oPage->add_ready_script('$("#toggle_'.$index.'").click( function() { $("#license_'.$index.'").slideToggle("normal"); } );');
  1118. }
  1119. $oPage->add('</ul>');
  1120. $oPage->add('</fieldset>');
  1121. $oPage->add("</div>");
  1122. $oPage->add('<fieldset>');
  1123. $oPage->add('<legend>'.Dict::S('UI:About:Modules').'</legend>');
  1124. //$oPage->add(print_r($aAvailableModules, true));
  1125. $oPage->add("<div style=\"height: 150px; overflow: auto; font-size: smaller;\">");
  1126. $oPage->add('<ul style="margin: 0;">');
  1127. foreach ($aAvailableModules as $sModuleId => $aModuleData)
  1128. {
  1129. if ($sModuleId == '_Root_') continue;
  1130. if (!$aModuleData['visible']) continue;
  1131. if ($aModuleData['version_db'] == '') continue;
  1132. $oPage->add('<li>'.$aModuleData['label'].' ('.$aModuleData['version_db'].')</li>');
  1133. }
  1134. $oPage->add('</ul>');
  1135. $oPage->add("</div>");
  1136. $oPage->add('</fieldset>');
  1137. // MUST NOT be localized, as the information given here will be sent to the support
  1138. $oPage->add("<a id=\"collapse_support_details\" class=\"CollapsibleLabel\" href=\"#\">".Dict::S('UI:About:Support')."</a></br>\n");
  1139. $oPage->add("<div id=\"support_details\">");
  1140. $oPage->add('<textarea readonly style="width: 660px; height: 150px; font-size: smaller;">');
  1141. $oPage->add("===== begin =====\n");
  1142. $oPage->add('iTopVersion: '.ITOP_VERSION."\n");
  1143. $oPage->add('iTopBuild: '.ITOP_REVISION."\n");
  1144. $oPage->add('iTopBuildDate: '.ITOP_BUILD_DATE."\n");
  1145. $oPage->add('DataModelVersion: '.$sDataModelVersion."\n");
  1146. $oPage->add('MySQLVersion: '.$sMySQLVersion."\n");
  1147. $oPage->add('PHPVersion: '. $sPHPVersion."\n");
  1148. $oPage->add('OSVersion: '.$sOSVersion."\n");
  1149. $oPage->add('WebServerVersion: '.$sWebServerVersion."\n");
  1150. $oPage->add('PHPModules: '.$sModules."\n");
  1151. foreach ($aItopSettings as $siTopVar)
  1152. {
  1153. $oPage->add('ItopSetting/'.$siTopVar.': '.MetaModel::GetConfig()->Get($siTopVar)."\n");
  1154. }
  1155. foreach ($aPHPSettings as $sPHPVar)
  1156. {
  1157. $oPage->add('PHPSetting/'.$sPHPVar.': '.ini_get($sPHPVar)."\n");
  1158. }
  1159. foreach ($aMySQLSettings as $sMySQLVar)
  1160. {
  1161. $oPage->add('MySQLSetting/'.$sMySQLVar.': '.$aMySQLVars[$sMySQLVar]."\n");
  1162. }
  1163. foreach ($aMySQLStatuses as $sMySQLStatus)
  1164. {
  1165. $oPage->add('MySQLStatus/'.$sMySQLStatus.': '.$aMySQLStats[$sMySQLStatus]."\n");
  1166. }
  1167. $oPage->add('InstallDate: '.$sLastInstallDate."\n");
  1168. $oPage->add('InstallPath: '.APPROOT."\n");
  1169. foreach ($aAvailableModules as $sModuleId => $aModuleData)
  1170. {
  1171. if ($sModuleId == '_Root_') continue;
  1172. if ($aModuleData['version_db'] == '') continue;
  1173. $oPage->add('InstalledModule/'.$sModuleId.': '.$aModuleData['version_db']."\n");
  1174. }
  1175. $oPage->add('===== end =====');
  1176. $oPage->add('</textarea>');
  1177. $oPage->add("</div>");
  1178. $oPage->add("</div>");
  1179. break;
  1180. case 'history':
  1181. $oPage->SetContentType('text/html');
  1182. $id = (int)utils::ReadParam('id', 0);
  1183. $iStart = (int)utils::ReadParam('start', 0);
  1184. $iCount = (int)utils::ReadParam('count', MetaModel::GetConfig()->Get('max_history_length', '50'));
  1185. $oObj = MetaModel::GetObject($sClass, $id);
  1186. $oObj->DisplayBareHistory($oPage, false, $iCount, $iStart);
  1187. $oPage->add_ready_script("$('#history table.listResults').tableHover(); $('#history table.listResults').tablesorter( { widgets: ['myZebra', 'truncatedList']} );");
  1188. break;
  1189. case 'history_from_filter':
  1190. $oPage->SetContentType('text/html');
  1191. $oHistoryFilter = DBSearch::unserialize($sFilter);
  1192. $iStart = (int)utils::ReadParam('start', 0);
  1193. $iCount = (int)utils::ReadParam('count', MetaModel::GetConfig()->Get('max_history_length', '50'));
  1194. $oBlock = new HistoryBlock($oHistoryFilter, 'table', false);
  1195. $oBlock->SetLimit($iCount, $iStart);
  1196. $oBlock->Display($oPage, 'history');
  1197. $oPage->add_ready_script("$('#history table.listResults').tableHover(); $('#history table.listResults').tablesorter( { widgets: ['myZebra', 'truncatedList']} );");
  1198. break;
  1199. case 'full_text_search':
  1200. $aFullTextNeedles = utils::ReadParam('needles', array(), false, 'raw_data');
  1201. $sFullText = trim(implode(' ', $aFullTextNeedles));
  1202. $sClassName = utils::ReadParam('class', '');
  1203. $iCount = utils::ReadParam('count', 0);
  1204. $iCurrentPos = utils::ReadParam('position', 0);
  1205. $iTune = utils::ReadParam('tune', 0);
  1206. if (empty($sFullText))
  1207. {
  1208. $oPage->p(Dict::S('UI:Search:NoSearch'));
  1209. break;
  1210. }
  1211. // Search in full text mode in all the classes
  1212. $aMatches = array();
  1213. // Build the ordered list of classes to search into
  1214. //
  1215. if (empty($sClassName))
  1216. {
  1217. $aSearchClasses = MetaModel::GetClasses('searchable');
  1218. }
  1219. else
  1220. {
  1221. // Search is limited to a given class and its subclasses
  1222. $aSearchClasses = MetaModel::EnumChildClasses($sClassName, ENUM_CHILD_CLASSES_ALL);
  1223. }
  1224. // Skip abstract classes, since we search in all the child classes anyway
  1225. foreach($aSearchClasses as $idx => $sClass)
  1226. {
  1227. if (MetaModel::IsAbstract($sClass))
  1228. {
  1229. unset($aSearchClasses[$idx]);
  1230. }
  1231. }
  1232. $sMaxChunkDuration = MetaModel::GetConfig()->Get('full_text_chunk_duration');
  1233. $aAccelerators = MetaModel::GetConfig()->Get('full_text_accelerators');
  1234. foreach (array_reverse($aAccelerators) as $sClass => $aRestriction)
  1235. {
  1236. $bSkip = false;
  1237. $iPos = array_search($sClass, $aSearchClasses);
  1238. if ($iPos !== false)
  1239. {
  1240. unset($aSearchClasses[$iPos]);
  1241. }
  1242. else
  1243. {
  1244. $bSkip = true;
  1245. }
  1246. $bSkip |= array_key_exists('skip', $aRestriction) ? $aRestriction['skip'] : false ;
  1247. if (!in_array($sClass, $aSearchClasses))
  1248. if ($sClass == $sClassName)
  1249. {
  1250. // Class explicitely requested, do NOT skip it
  1251. // beware: there may not be a 'query' defined for a skipped class !
  1252. $bSkip = false;
  1253. }
  1254. if (!$bSkip)
  1255. {
  1256. // NOT skipped, add the class to the list of classes to search into
  1257. if (array_key_exists('query', $aRestriction))
  1258. {
  1259. array_unshift($aSearchClasses, $aRestriction['query']);
  1260. }
  1261. else
  1262. {
  1263. // No accelerator query
  1264. array_unshift($aSearchClasses, $sClassName);
  1265. }
  1266. }
  1267. }
  1268. $aSearchClasses = array_values($aSearchClasses); // renumbers the array starting from zero, removing the missing indexes
  1269. $fStarted = microtime(true);
  1270. $iFoundInThisRound = 0;
  1271. for($iPos = $iCurrentPos; $iPos < count($aSearchClasses) ; $iPos++)
  1272. {
  1273. if ($iFoundInThisRound && (microtime(true) - $fStarted >= $sMaxChunkDuration))
  1274. {
  1275. break;
  1276. }
  1277. $sClassSpec = $aSearchClasses[$iPos];
  1278. if (substr($sClassSpec, 0, 7) == 'SELECT ')
  1279. {
  1280. $oFilter = DBObjectSearch::FromOQL($sClassSpec);
  1281. $sClassName = $oFilter->GetClass();
  1282. $sNeedleFormat = isset($aAccelerators[$sClassName]['needle']) ? $aAccelerators[$sClassName]['needle'] : '%$needle$%';
  1283. $sNeedle = str_replace('$needle$', $sFullText, $sNeedleFormat);
  1284. $aParams = array('needle' => $sNeedle);
  1285. }
  1286. else
  1287. {
  1288. $sClassName = $sClassSpec;
  1289. $oFilter = new DBObjectSearch($sClassName);
  1290. $aParams = array();
  1291. foreach($aFullTextNeedles as $sSearchText)
  1292. {
  1293. $oFilter->AddCondition_FullText($sSearchText);
  1294. }
  1295. }
  1296. // Skip abstract classes
  1297. if (MetaModel::IsAbstract($sClassName)) continue;
  1298. if ($iTune > 0)
  1299. {
  1300. $fStartedClass = microtime(true);
  1301. }
  1302. $oSet = new DBObjectSet($oFilter, array(), $aParams);
  1303. if (array_key_exists($sClassName, $aAccelerators) && array_key_exists('attributes', $aAccelerators[$sClassName]))
  1304. {
  1305. $oSet->OptimizeColumnLoad(array($oFilter->GetClassAlias() => $aAccelerators[$sClassName]['attributes']));
  1306. }
  1307. $sFullTextJS = addslashes($sFullText);
  1308. $bEnableEnlarge = array_key_exists($sClassName, $aAccelerators) && array_key_exists('query', $aAccelerators[$sClassName]);
  1309. if (array_key_exists($sClassName, $aAccelerators) && array_key_exists('enable_enlarge', $aAccelerators[$sClassName]))
  1310. {
  1311. $bEnableEnlarge &= $aAccelerators[$sClassName]['enable_enlarge'];
  1312. }
  1313. $sEnlargeTheSearch =
  1314. <<<EOF
  1315. $('.search-class-$sClassName button').attr('disabled', 'disabled');
  1316. $('.search-class-$sClassName h2').append('&nbsp;<img id="indicator" src="../images/indicator.gif">');
  1317. var oParams = {operation: 'full_text_search_enlarge', class: '$sClassName', text: '$sFullTextJS'};
  1318. $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', oParams, function(data) {
  1319. $('.search-class-$sClassName').html(data);
  1320. });
  1321. EOF
  1322. ;
  1323. $sEnlargeButton = '';
  1324. if ($bEnableEnlarge)
  1325. {
  1326. $sEnlargeButton = "&nbsp;<button onclick=\"".htmlentities($sEnlargeTheSearch, ENT_QUOTES, 'UTF-8')."\">".Dict::S('UI:Search:Enlarge')."</button>";
  1327. }
  1328. if ($oSet->Count() > 0)
  1329. {
  1330. $aLeafs = array();
  1331. while($oObj = $oSet->Fetch())
  1332. {
  1333. if (get_class($oObj) == $sClassName)
  1334. {
  1335. $aLeafs[] = $oObj->GetKey();
  1336. $iFoundInThisRound ++;
  1337. }
  1338. }
  1339. $oLeafsFilter = new DBObjectSearch($sClassName);
  1340. if (count($aLeafs) > 0)
  1341. {
  1342. $iCount += count($aLeafs);
  1343. $oPage->add("<div class=\"search-class-result search-class-$sClassName\">\n");
  1344. $oPage->add("<div class=\"page_header\">\n");
  1345. if (array_key_exists($sClassName, $aAccelerators))
  1346. {
  1347. $oPage->add("<h2>".MetaModel::GetClassIcon($sClassName)."&nbsp;<span class=\"hilite\">".Dict::Format('UI:Search:Count_ObjectsOf_Class_Found', count($aLeafs), Metamodel::GetName($sClassName)).$sEnlargeButton."</h2>\n");
  1348. }
  1349. else
  1350. {
  1351. $oPage->add("<h2>".MetaModel::GetClassIcon($sClassName)."&nbsp;<span class=\"hilite\">".Dict::Format('UI:Search:Count_ObjectsOf_Class_Found', count($aLeafs), Metamodel::GetName($sClassName))."</h2>\n");
  1352. }
  1353. $oPage->add("</div>\n");
  1354. $oLeafsFilter->AddCondition('id', $aLeafs, 'IN');
  1355. $oBlock = new DisplayBlock($oLeafsFilter, 'list', false);
  1356. $sBlockId = 'global_search_'.$sClassName;
  1357. $oPage->add('<div id="'.$sBlockId.'">');
  1358. $oBlock->RenderContent($oPage, array('table_id' => $sBlockId, 'currentId' => $sBlockId));
  1359. $oPage->add("</div>\n");
  1360. $oPage->add("</div>\n");
  1361. $oPage->p('&nbsp;'); // Some space ?
  1362. }
  1363. }
  1364. else if (array_key_exists($sClassName, $aAccelerators))
  1365. {
  1366. $oPage->add("<div class=\"search-class-result search-class-$sClassName\">\n");
  1367. $oPage->add("<div class=\"page_header\">\n");
  1368. $oPage->add("<h2>".MetaModel::GetClassIcon($sClassName)."&nbsp;<span class=\"hilite\">".Dict::Format('UI:Search:Count_ObjectsOf_Class_Found', 0, Metamodel::GetName($sClassName)).$sEnlargeButton."</h2>\n");
  1369. $oPage->add("</div>\n");
  1370. $oPage->add("</div>\n");
  1371. $oPage->p('&nbsp;'); // Some space ?
  1372. }
  1373. if ($iTune > 0)
  1374. {
  1375. $fDurationClass = microtime(true) - $fStartedClass;
  1376. $oPage->add_script("oTimeStatistics.$sClassName = $fDurationClass;");
  1377. }
  1378. }
  1379. if ($iPos < count($aSearchClasses))
  1380. {
  1381. $sJSNeedle = json_encode($aFullTextNeedles);
  1382. $oPage->add_ready_script(
  1383. <<<EOF
  1384. var oParams = {operation: 'full_text_search', position: $iPos, needles: $sJSNeedle, count: $iCount, tune: $iTune};
  1385. $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', oParams, function(data) {
  1386. $('#full_text_results').append(data);
  1387. });
  1388. EOF
  1389. );
  1390. }
  1391. else
  1392. {
  1393. // We're done
  1394. $oPage->add_ready_script(
  1395. <<<EOF
  1396. $('#full_text_indicator').hide();
  1397. $('#full_text_progress,#full_text_progress_placeholder').hide(500);
  1398. EOF
  1399. );
  1400. if ($iTune > 0)
  1401. {
  1402. $oPage->add_ready_script(
  1403. <<<EOF
  1404. var sRes = '<h4>Search statistics (tune = 1)</h4><table>';
  1405. sRes += '<thead><tr><th>Class</th><th>Time</th></tr></thead>';
  1406. sRes += '<tbody>';
  1407. var fTotal = 0;
  1408. for (var sClass in oTimeStatistics)
  1409. {
  1410. fTotal = fTotal + oTimeStatistics[sClass];
  1411. fRounded = Math.round(oTimeStatistics[sClass] * 1000) / 1000;
  1412. sRes += '<tr><td>' + sClass + '</td><td>' + fRounded + '</td></tr>';
  1413. }
  1414. fRoundedTotal = Math.round(fTotal * 1000) / 1000;
  1415. sRes += '<tr><td><b>Total</b></td><td><b>' + fRoundedTotal + '</b></td></tr>';
  1416. sRes += '</tbody>';
  1417. sRes += '</table>';
  1418. $('#full_text_results').append(sRes);
  1419. EOF
  1420. );
  1421. }
  1422. if ($iCount == 0)
  1423. {
  1424. $sFullTextSummary = addslashes(Dict::S('UI:Search:NoObjectFound'));
  1425. $oPage->add_ready_script("$('#full_text_results').append('<div id=\"no_object_found\">$sFullTextSummary</div>');");
  1426. }
  1427. }
  1428. break;
  1429. case 'full_text_search_enlarge':
  1430. $sFullText = trim(utils::ReadParam('text', '', false, 'raw_data'));
  1431. $sClass = trim(utils::ReadParam('class', ''));
  1432. $iTune = utils::ReadParam('tune', 0);
  1433. if (preg_match('/^"(.*)"$/', $sFullText, $aMatches))
  1434. {
  1435. // The text is surrounded by double-quotes, remove the quotes and treat it as one single expression
  1436. $aFullTextNeedles = array($aMatches[1]);
  1437. }
  1438. else
  1439. {
  1440. // Split the text on the blanks and treat this as a search for <word1> AND <word2> AND <word3>
  1441. $aFullTextNeedles = explode(' ', $sFullText);
  1442. }
  1443. $oFilter = new DBObjectSearch($sClass);
  1444. foreach($aFullTextNeedles as $sSearchText)
  1445. {
  1446. $oFilter->AddCondition_FullText($sSearchText);
  1447. }
  1448. $oSet = new DBObjectSet($oFilter);
  1449. $oPage->add("<div class=\"page_header\">\n");
  1450. $oPage->add("<h2>".MetaModel::GetClassIcon($sClass)."&nbsp;<span class=\"hilite\">".Dict::Format('UI:Search:Count_ObjectsOf_Class_Found', $oSet->Count(), Metamodel::GetName($sClass))."</h2>\n");
  1451. $oPage->add("</div>\n");
  1452. if ($oSet->Count() > 0)
  1453. {
  1454. $aLeafs = array();
  1455. while($oObj = $oSet->Fetch())
  1456. {
  1457. if (get_class($oObj) == $sClass)
  1458. {
  1459. $aLeafs[] = $oObj->GetKey();
  1460. }
  1461. }
  1462. $oLeafsFilter = new DBObjectSearch($sClass);
  1463. if (count($aLeafs) > 0)
  1464. {
  1465. $oLeafsFilter->AddCondition('id', $aLeafs, 'IN');
  1466. $oBlock = new DisplayBlock($oLeafsFilter, 'list', false);
  1467. $sBlockId = 'global_search_'.$sClass;
  1468. $oPage->add('<div id="'.$sBlockId.'">');
  1469. $oBlock->RenderContent($oPage, array('table_id' => $sBlockId, 'currentId' => $sBlockId));
  1470. $oPage->add('</div>');
  1471. $oPage->P('&nbsp;'); // Some space ?
  1472. // Hide "no object found"
  1473. $oPage->add_ready_script('$("#no_object_found").hide();');
  1474. }
  1475. }
  1476. $oPage->add_ready_script(
  1477. <<<EOF
  1478. $('#full_text_indicator').hide();
  1479. $('#full_text_progress,#full_text_progress_placeholder').hide(500);
  1480. EOF
  1481. );
  1482. break;
  1483. case 'xlsx_export_dialog':
  1484. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  1485. $oPage->SetContentType('text/html');
  1486. $oPage->add(
  1487. <<<EOF
  1488. <style>
  1489. .ui-progressbar {
  1490. position: relative;
  1491. }
  1492. .progress-label {
  1493. position: absolute;
  1494. left: 50%;
  1495. top: 1px;
  1496. font-size: 11pt;
  1497. }
  1498. .download-form button {
  1499. display:block;
  1500. margin-left: auto;
  1501. margin-right: auto;
  1502. margin-top: 2em;
  1503. }
  1504. .ui-progressbar-value {
  1505. background: url(../setup/orange-progress.gif);
  1506. }
  1507. .progress-bar {
  1508. height: 20px;
  1509. }
  1510. .statistics > div {
  1511. padding-left: 16px;
  1512. cursor: pointer;
  1513. font-size: 10pt;
  1514. background: url(../images/minus.gif) 0 2px no-repeat;
  1515. }
  1516. .statistics > div.closed {
  1517. padding-left: 16px;
  1518. background: url(../images/plus.gif) 0 2px no-repeat;
  1519. }
  1520. .statistics .closed .stats-data {
  1521. display: none;
  1522. }
  1523. .stats-data td {
  1524. padding-right: 5px;
  1525. }
  1526. </style>
  1527. EOF
  1528. );
  1529. $oPage->add('<div id="XlsxExportDlg">');
  1530. $oPage->add('<div class="export-options">');
  1531. $oPage->add('<p><input type="checkbox" id="export-advanced-mode"/>&nbsp;<label for="export-advanced-mode">'.Dict::S('UI:CSVImport:AdvancedMode').'</label></p>');
  1532. $oPage->add('<p style="font-size:10pt;margin-left:2em;margin-top:-0.5em;padding-bottom:1em;">'.Dict::S('UI:CSVImport:AdvancedMode+').'</p>');
  1533. $oPage->add('<p><input type="checkbox" id="export-auto-download" checked="checked"/>&nbsp;<label for="export-auto-download">'.Dict::S('ExcelExport:AutoDownload').'</label></p>');
  1534. $oPage->add('</div>');
  1535. $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>');
  1536. $oPage->add('<div class="statistics"><div class="stats-toggle closed">'.Dict::S('ExcelExport:Statistics').'<div class="stats-data"></div></div></div>');
  1537. $oPage->add('</div>');
  1538. $aLabels = array(
  1539. 'dialog_title' => Dict::S('ExcelExporter:ExportDialogTitle'),
  1540. 'cancel_button' => Dict::S('UI:Button:Cancel'),
  1541. 'export_button' => Dict::S('ExcelExporter:ExportButton'),
  1542. 'download_button' => Dict::Format('ExcelExporter:DownloadButton', 'export.xlsx'), //TODO: better name for the file (based on the class of the filter??)
  1543. );
  1544. $sJSLabels = json_encode($aLabels);
  1545. $sFilter = addslashes($sFilter);
  1546. $sJSPageUrl = addslashes(utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php');
  1547. $oPage->add_ready_script("$('#XlsxExportDlg').xlsxexporter({filter: '$sFilter', labels: $sJSLabels, ajax_page_url: '$sJSPageUrl'});");
  1548. break;
  1549. case 'xlsx_start':
  1550. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  1551. $bAdvanced = (utils::ReadParam('advanced', 'false') == 'true');
  1552. $oSearch = DBObjectSearch::unserialize($sFilter);
  1553. $oExcelExporter = new ExcelExporter();
  1554. $oExcelExporter->SetObjectList($oSearch);
  1555. //$oExcelExporter->SetChunkSize(10); //Only for testing
  1556. $oExcelExporter->SetAdvancedMode($bAdvanced);
  1557. $sToken = $oExcelExporter->SaveState();
  1558. $oPage->add(json_encode(array('status' => 'ok', 'token' => $sToken)));
  1559. break;
  1560. case 'xlsx_run':
  1561. $sMemoryLimit = MetaModel::GetConfig()->Get('xlsx_exporter_memory_limit');
  1562. ini_set('memory_limit', $sMemoryLimit);
  1563. ini_set('max_execution_time', max(300, ini_get('max_execution_time'))); // At least 5 minutes
  1564. $sToken = utils::ReadParam('token', '', false, 'raw_data');
  1565. $oExcelExporter = new ExcelExporter($sToken);
  1566. $aStatus = $oExcelExporter->Run();
  1567. $aResults = array('status' => $aStatus['code'], 'percentage' => $aStatus['percentage'], 'message' => $aStatus['message']);
  1568. if ($aStatus['code'] == 'done')
  1569. {
  1570. $aResults['statistics'] = $oExcelExporter->GetStatistics('html');
  1571. }
  1572. $oPage->add(json_encode($aResults));
  1573. break;
  1574. case 'xlsx_download':
  1575. $sToken = utils::ReadParam('token', '', false, 'raw_data');
  1576. $oPage->SetContentType('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  1577. $oPage->SetContentDisposition('attachment', 'export.xlsx');
  1578. $sFileContent = ExcelExporter::GetExcelFileFromToken($sToken);
  1579. $oPage->add($sFileContent);
  1580. ExcelExporter::CleanupFromToken($sToken);
  1581. break;
  1582. case 'xlsx_abort':
  1583. // Stop & cleanup an export...
  1584. $sToken = utils::ReadParam('token', '', false, 'raw_data');
  1585. ExcelExporter::CleanupFromToken($sToken);
  1586. break;
  1587. case 'relation_pdf':
  1588. case 'relation_attachment':
  1589. require_once(APPROOT.'core/simplegraph.class.inc.php');
  1590. require_once(APPROOT.'core/relationgraph.class.inc.php');
  1591. require_once(APPROOT.'core/displayablegraph.class.inc.php');
  1592. $sRelation = utils::ReadParam('relation', 'impacts');
  1593. $sDirection = utils::ReadParam('direction', 'down');
  1594. $iGroupingThreshold = utils::ReadParam('g', 5, false, 'integer');
  1595. $sPageFormat = utils::ReadParam('p', 'A4');
  1596. $sPageOrientation = utils::ReadParam('o', 'L');
  1597. $sTitle = utils::ReadParam('title', '', false, 'raw_data');
  1598. $sPositions = utils::ReadParam('positions', null, false, 'raw_data');
  1599. $aExcludedClasses = utils::ReadParam('excluded_classes', array(), false, 'raw_data');
  1600. $bIncludeList = (bool)utils::ReadParam('include_list', false);
  1601. $sComments = utils::ReadParam('comments', '', false, 'raw_data');
  1602. $aContexts = utils::ReadParam('contexts', array(), false, 'raw_data');
  1603. $sContextKey = utils::ReadParam('context_key', '', false, 'raw_data');
  1604. $aPositions = null;
  1605. if ($sPositions != null)
  1606. {
  1607. $aPositions = json_decode($sPositions, true);
  1608. }
  1609. // Get the list of source objects
  1610. $aSources = utils::ReadParam('sources', array(), false, 'raw_data');
  1611. $aSourceObjects = array();
  1612. foreach($aSources as $sClass => $aIDs)
  1613. {
  1614. $oSearch = new DBObjectSearch($sClass);
  1615. $oSearch->AddCondition('id', $aIDs, 'IN');
  1616. $oSet = new DBObjectSet($oSearch);
  1617. while($oObj = $oSet->Fetch())
  1618. {
  1619. $aSourceObjects[] = $oObj;
  1620. }
  1621. }
  1622. $sSourceClass = '*';
  1623. if (count($aSourceObjects) == 1)
  1624. {
  1625. $sSourceClass = get_class($aSourceObjects[0]);
  1626. }
  1627. // Get the list of excluded objects
  1628. $aExcluded = utils::ReadParam('excluded', array(), false, 'raw_data');
  1629. $aExcludedObjects = array();
  1630. foreach($aExcluded as $sClass => $aIDs)
  1631. {
  1632. $oSearch = new DBObjectSearch($sClass);
  1633. $oSearch->AddCondition('id', $aIDs, 'IN');
  1634. $oSet = new DBObjectSet($oSearch);
  1635. while($oObj = $oSet->Fetch())
  1636. {
  1637. $aExcludedObjects[] = $oObj;
  1638. }
  1639. }
  1640. $iMaxRecursionDepth = MetaModel::GetConfig()->Get('relations_max_depth', 20);
  1641. if ($sDirection == 'up')
  1642. {
  1643. $oRelGraph = MetaModel::GetRelatedObjectsUp($sRelation, $aSourceObjects, $iMaxRecursionDepth, true, $aContexts);
  1644. }
  1645. else
  1646. {
  1647. $oRelGraph = MetaModel::GetRelatedObjectsDown($sRelation, $aSourceObjects, $iMaxRecursionDepth, true, $aExcludedObjects, $aContexts);
  1648. }
  1649. // Remove excluded classes from the graph
  1650. if (count($aExcludedClasses) > 0)
  1651. {
  1652. $oIterator = new RelationTypeIterator($oRelGraph, 'Node');
  1653. foreach($oIterator as $oNode)
  1654. {
  1655. $oObj = $oNode->GetProperty('object');
  1656. if ($oObj && in_array(get_class($oObj), $aExcludedClasses))
  1657. {
  1658. $oRelGraph->FilterNode($oNode);
  1659. }
  1660. }
  1661. }
  1662. $oPage = new PDFPage($sTitle, $sPageFormat, $sPageOrientation);
  1663. $oPage->SetContentDisposition('attachment', $sTitle.'.pdf');
  1664. $oGraph = DisplayableGraph::FromRelationGraph($oRelGraph, $iGroupingThreshold, ($sDirection == 'down'));
  1665. $oGraph->InitFromGraphviz();
  1666. if ($aPositions != null)
  1667. {
  1668. $oGraph->UpdatePositions($aPositions);
  1669. }
  1670. $aGroups = array();
  1671. $oIterator = new RelationTypeIterator($oGraph, 'Node');
  1672. foreach($oIterator as $oNode)
  1673. {
  1674. if ($oNode instanceof DisplayableGroupNode)
  1675. {
  1676. $aGroups[$oNode->GetProperty('group_index')] = $oNode->GetObjects();
  1677. }
  1678. }
  1679. // First page is the graph
  1680. $oGraph->RenderAsPDF($oPage, $sComments, $sContextKey);
  1681. if ($bIncludeList)
  1682. {
  1683. // Then the lists of objects (one table per finalclass)
  1684. $aResults = array();
  1685. $oIterator = new RelationTypeIterator($oRelGraph, 'Node');
  1686. foreach($oIterator as $oNode)
  1687. {
  1688. $oObj = $oNode->GetProperty('object'); // Some nodes (Redundancy Nodes and Group) do not contain an object
  1689. if ($oObj)
  1690. {
  1691. $sObjClass = get_class($oObj);
  1692. if (!array_key_exists($sObjClass, $aResults))
  1693. {
  1694. $aResults[$sObjClass] = array();
  1695. }
  1696. $aResults[$sObjClass][] = $oObj;
  1697. }
  1698. }
  1699. $oPage->get_tcpdf()->AddPage();
  1700. $oPage->get_tcpdf()->SetFont('dejavusans', '', 10, '', true); // Reset the font size to its default
  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*count($aObjects));
  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, array('table_id' => $sSourceClass.'_'.$sRelation.'_'.$sDirection.'_'.$sListClass));
  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*count($aObjects));
  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 'relation_groups':
  1828. $aGroups = utils::ReadParam('groups');
  1829. $iBlock = 1; // Zero is not a valid blockid
  1830. foreach($aGroups as $idx => $aDefinition)
  1831. {
  1832. $sListClass = $aDefinition['class'];
  1833. $oSearch = new DBObjectSearch($sListClass);
  1834. $oSearch->AddCondition('id', $aDefinition['keys'], 'IN');
  1835. $oPage->add("<h1>".Dict::Format('UI:RelationGroupNumber_N', (1+$idx))."</h1>\n");
  1836. $oPage->add("<div id=\"relation_group_$idx\" class=\"page_header\">\n");
  1837. $oPage->add("<h2>".MetaModel::GetClassIcon($sListClass)."&nbsp;<span class=\"hilite\">".Dict::Format('UI:Search:Count_ObjectsOf_Class_Found', count($aDefinition['keys']), Metamodel::GetName($sListClass))."</h2>\n");
  1838. $oPage->add("</div>\n");
  1839. $oBlock = new DisplayBlock($oSearch, 'list');
  1840. $oBlock->Display($oPage, 'group_'.$iBlock++);
  1841. $oPage->p('&nbsp;'); // Some space ?
  1842. }
  1843. break;
  1844. case 'relation_lists':
  1845. $aLists = utils::ReadParam('lists');
  1846. $iBlock = 1; // Zero is not a valid blockid
  1847. foreach($aLists as $sListClass => $aKeys)
  1848. {
  1849. $oSearch = new DBObjectSearch($sListClass);
  1850. $oSearch->AddCondition('id', $aKeys, 'IN');
  1851. $oPage->add("<div class=\"page_header\">\n");
  1852. $oPage->add("<h2>".MetaModel::GetClassIcon($sListClass)."&nbsp;<span class=\"hilite\">".Dict::Format('UI:Search:Count_ObjectsOf_Class_Found', count($aKeys), Metamodel::GetName($sListClass))."</h2>\n");
  1853. $oPage->add("</div>\n");
  1854. $oBlock = new DisplayBlock($oSearch, 'list');
  1855. $oBlock->Display($oPage, 'list_'.$iBlock++, array('table_id' => 'ImpactAnalysis_'.$sListClass));
  1856. $oPage->p('&nbsp;'); // Some space ?
  1857. }
  1858. break;
  1859. case 'ticket_impact':
  1860. require_once(APPROOT.'core/simplegraph.class.inc.php');
  1861. require_once(APPROOT.'core/relationgraph.class.inc.php');
  1862. require_once(APPROOT.'core/displayablegraph.class.inc.php');
  1863. $sRelation = utils::ReadParam('relation', 'impacts');
  1864. $sDirection = utils::ReadParam('direction', 'down');
  1865. $iGroupingThreshold = utils::ReadParam('g', 5);
  1866. $sClass = utils::ReadParam('class', '', false, 'class');
  1867. $sAttCode = utils::ReadParam('attcode', 'functionalcis_list');
  1868. $sImpactAttCode = utils::ReadParam('impact_attcode', 'impact_code');
  1869. $sImpactAttCodeValue = utils::ReadParam('impact_attcode_value', 'manual');
  1870. $iId = (int)utils::ReadParam('id', 0, false, 'integer');
  1871. // Get the list of source objects
  1872. $oTicket = MetaModel::GetObject($sClass, $iId);
  1873. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1874. $sExtKeyToRemote = $oAttDef->GetExtKeyToRemote();
  1875. $oExtKeyToRemote = MetaModel::GetAttributeDef($oAttDef->GetLinkedClass(), $sExtKeyToRemote);
  1876. $sRemoteClass = $oExtKeyToRemote->GetTargetClass();
  1877. $oSet = $oTicket->Get($sAttCode);
  1878. $aSourceObjects = array();
  1879. $aExcludedObjects = array();
  1880. while($oLnk = $oSet->Fetch())
  1881. {
  1882. if ($oLnk->Get($sImpactAttCode) == 'manual')
  1883. {
  1884. $aSourceObjects[] = MetaModel::GetObject($sRemoteClass, $oLnk->Get($sExtKeyToRemote));
  1885. }
  1886. if ($oLnk->Get($sImpactAttCode) == 'not_impacted')
  1887. {
  1888. $aExcludedObjects[] = MetaModel::GetObject($sRemoteClass, $oLnk->Get($sExtKeyToRemote));
  1889. }
  1890. }
  1891. // Compute the graph
  1892. $iMaxRecursionDepth = MetaModel::GetConfig()->Get('relations_max_depth', 20);
  1893. if ($sDirection == 'up')
  1894. {
  1895. $oRelGraph = MetaModel::GetRelatedObjectsUp($sRelation, $aSourceObjects, $iMaxRecursionDepth);
  1896. }
  1897. else
  1898. {
  1899. $oRelGraph = MetaModel::GetRelatedObjectsDown($sRelation, $aSourceObjects, $iMaxRecursionDepth, $aExcludedObjects);
  1900. }
  1901. $aResults = $oRelGraph->GetObjectsByClass();
  1902. $oGraph = DisplayableGraph::FromRelationGraph($oRelGraph, $iGroupingThreshold, ($sDirection == 'down'));
  1903. $sContextKey = 'itop-tickets/relation_context/'.$sClass.'/'.$sRelation.'/'.$sDirection;
  1904. $oAppContext = new ApplicationContext();
  1905. $oGraph->Display($oPage, $aResults, $sRelation, $oAppContext, $aExcludedObjects, $sClass, $iId, $sContextKey, array('this' => $oTicket));
  1906. break;
  1907. case 'export_build':
  1908. try
  1909. {
  1910. $token = utils::ReadParam('token', null);
  1911. $aResult = array('code' => 'error', 'percentage' => 100, 'message' => "Export not found for token: '$token'"); // Fallback error, just in case
  1912. $data = '';
  1913. if ($token === null)
  1914. {
  1915. $sFormat = utils::ReadParam('format', '');
  1916. $sExpression = utils::ReadParam('expression', null, false, 'raw_data');
  1917. $iQueryId = utils::ReadParam('query', null);
  1918. if ($sExpression === null)
  1919. {
  1920. $oQuerySearch = DBObjectSearch::FromOQL('SELECT QueryOQL WHERE id = :query_id', array('query_id' => $iQueryId));
  1921. $oQueries = new DBObjectSet($oQuerySearch);
  1922. if ($oQueries->Count() > 0)
  1923. {
  1924. $oQuery = $oQueries->Fetch();
  1925. $sExpression = $oQuery->Get('oql');
  1926. }
  1927. else
  1928. {
  1929. $aResult = array('code' => 'error', 'percentage' => 100, 'message' => "Invalid query phrasebook identifier: '$iQueryId'");
  1930. }
  1931. }
  1932. if($sExpression !== null)
  1933. {
  1934. $oSearch = DBObjectSearch::FromOQL($sExpression);
  1935. $oExporter = BulkExport::FindExporter($sFormat, $oSearch);
  1936. $oExporter->SetObjectList($oSearch);
  1937. $oExporter->SetFormat($sFormat);
  1938. $oExporter->SetChunkSize(EXPORTER_DEFAULT_CHUNK_SIZE);
  1939. $oExporter->ReadParameters();
  1940. }
  1941. // First pass, generate the headers
  1942. $data .= $oExporter->GetHeader();
  1943. }
  1944. else
  1945. {
  1946. $oExporter = BulkExport::FindExporterFromToken($token);
  1947. }
  1948. if ($oExporter)
  1949. {
  1950. $data .= $oExporter->GetNextChunk($aResult);
  1951. if ($aResult['code'] != 'done')
  1952. {
  1953. $oExporter->AppendToTmpFile($data);
  1954. $aResult['token'] = $oExporter->SaveState();
  1955. }
  1956. else
  1957. {
  1958. // Last pass
  1959. $data .= $oExporter->GetFooter();
  1960. $oExporter->AppendToTmpFile($data);
  1961. $aResult['token'] = $oExporter->SaveState();
  1962. if (substr($oExporter->GetMimeType(), 0, 5) == 'text/')
  1963. {
  1964. // Result must be encoded in UTF-8 to be passed as part of a JSON structure
  1965. $sCharset = $oExporter->GetCharacterSet();
  1966. if (strtoupper($sCharset) != 'UTF-8')
  1967. {
  1968. $aResult['text_result'] = iconv($sCharset, 'UTF-8', file_get_contents($oExporter->GetTmpFilePath()));
  1969. }
  1970. else
  1971. {
  1972. $aResult['text_result'] = file_get_contents($oExporter->GetTmpFilePath());
  1973. }
  1974. $aResult['mime_type'] = $oExporter->GetMimeType();
  1975. }
  1976. $aResult['message'] = Dict::Format('Core:BulkExport:ClickHereToDownload_FileName', $oExporter->GetDownloadFileName());
  1977. }
  1978. }
  1979. $oPage->add(json_encode($aResult));
  1980. }
  1981. catch(BulkExportException $e)
  1982. {
  1983. $aResult = array('code' => 'error', 'percentage' => 100, 'message' => $e->GetLocalizedMessage());
  1984. $oPage->add(json_encode($aResult));
  1985. }
  1986. catch(Exception $e)
  1987. {
  1988. $aResult = array('code' => 'error', 'percentage' => 100, 'message' => $e->getMessage());
  1989. $oPage->add(json_encode($aResult));
  1990. }
  1991. break;
  1992. case 'export_download':
  1993. $token = utils::ReadParam('token', null);
  1994. if ($token !== null)
  1995. {
  1996. $oExporter = BulkExport::FindExporterFromToken($token);
  1997. if ($oExporter)
  1998. {
  1999. $sMimeType = $oExporter->GetMimeType();
  2000. if (substr($sMimeType, 0, 5) == 'text/')
  2001. {
  2002. $sMimeType .= ';charset='.strtolower($oExporter->GetCharacterSet());
  2003. }
  2004. $oPage->SetContentType($sMimeType);
  2005. $oPage->SetContentDisposition('attachment', $oExporter->GetDownloadFileName());
  2006. $oPage->add(file_get_contents($oExporter->GetTmpFilePath()));
  2007. }
  2008. }
  2009. break;
  2010. case 'export_cancel':
  2011. $token = utils::ReadParam('token', null);
  2012. if ($token !== null)
  2013. {
  2014. $oExporter = BulkExport::FindExporterFromToken($token);
  2015. if ($oExporter)
  2016. {
  2017. $oExporter->Cleanup();
  2018. }
  2019. }
  2020. $aResult = array('code' => 'error', 'percentage' => 100, 'message' => Dict::S('Core:BulkExport:ExportCancelledByUser'));
  2021. $oPage->add(json_encode($aResult));
  2022. break;
  2023. case 'extend_lock':
  2024. $sObjClass = utils::ReadParam('obj_class', '', false, 'class');
  2025. $iObjKey = (int)utils::ReadParam('obj_key', 0, false, 'integer');
  2026. $sToken = utils::ReadParam('token', 0, false, 'raw_data');
  2027. $aResult = iTopOwnershipLock::ExtendLock($sObjClass, $iObjKey, $sToken);
  2028. if (!$aResult['status'])
  2029. {
  2030. if ($aResult['operation'] == 'lost')
  2031. {
  2032. $sName = $aResult['owner']->GetName();
  2033. if ($aResult['owner']->Get('contactid') != 0)
  2034. {
  2035. $sName .= ' ('.$aResult['owner']->Get('contactid_friendlyname').')';
  2036. }
  2037. $aResult['message'] = Dict::Format('UI:CurrentObjectIsLockedBy_User', $sName);
  2038. $aResult['popup_message'] = Dict::Format('UI:CurrentObjectIsLockedBy_User_Explanation', $sName);
  2039. }
  2040. else if ($aResult['operation'] == 'expired')
  2041. {
  2042. $aResult['message'] = Dict::S('UI:CurrentObjectLockExpired');
  2043. $aResult['popup_message'] = Dict::S('UI:CurrentObjectLockExpired_Explanation');
  2044. }
  2045. }
  2046. $oPage->add(json_encode($aResult));
  2047. break;
  2048. case 'watchdog':
  2049. $oPage->add('ok'); // Better for debugging...
  2050. break;
  2051. case 'cke_img_upload':
  2052. // Image uploaded via CKEditor
  2053. $aResult = array(
  2054. 'uploaded' => 0,
  2055. 'fileName' => '',
  2056. 'url' => '',
  2057. 'icon' => '',
  2058. 'msg' => '',
  2059. 'att_id' => 0,
  2060. 'preview' => 'false',
  2061. );
  2062. $sObjClass = stripslashes(utils::ReadParam('obj_class', '', false, 'class'));
  2063. $sTempId = utils::ReadParam('temp_id', '');
  2064. if (empty($sObjClass))
  2065. {
  2066. $aResult['error'] = "Missing argument 'obj_class'";
  2067. }
  2068. elseif (empty($sTempId))
  2069. {
  2070. $aResult['error'] = "Missing argument 'temp_id'";
  2071. }
  2072. else
  2073. {
  2074. try
  2075. {
  2076. $oDoc = utils::ReadPostedDocument('upload');
  2077. if (InlineImage::IsImage($oDoc->GetMimeType()))
  2078. {
  2079. $aDimensions = null;
  2080. $oDoc = InlineImage::ResizeImageToFit($oDoc, $aDimensions);
  2081. $oAttachment = MetaModel::NewObject('InlineImage');
  2082. $oAttachment->Set('expire', time() + 3600); // one hour...
  2083. $oAttachment->Set('temp_id', $sTempId);
  2084. $oAttachment->Set('item_class', $sObjClass);
  2085. $oAttachment->SetDefaultOrgId();
  2086. $oAttachment->Set('contents', $oDoc);
  2087. $oAttachment->Set('secret', sprintf ('%06x', mt_rand(0, 0xFFFFFF))); // something not easy to guess
  2088. $iAttId = $oAttachment->DBInsert();
  2089. $aResult['uploaded'] = 1;
  2090. $aResult['msg'] = htmlentities($oDoc->GetFileName(), ENT_QUOTES, 'UTF-8');
  2091. $aResult['fileName'] = $oDoc->GetFileName();
  2092. $aResult['url'] = utils::GetAbsoluteUrlAppRoot().INLINEIMAGE_DOWNLOAD_URL.$iAttId.'&s='.$oAttachment->Get('secret');
  2093. if (is_array($aDimensions))
  2094. {
  2095. $aResult['width'] = $aDimensions['width'];
  2096. $aResult['height'] = $aDimensions['height'];
  2097. }
  2098. }
  2099. else
  2100. {
  2101. $aResult['error'] = $oDoc->GetFileName().' is not a valid image format.';
  2102. }
  2103. }
  2104. catch (FileUploadException $e)
  2105. {
  2106. $aResult['error'] = $e->GetMessage();
  2107. }
  2108. }
  2109. $oPage->add(json_encode($aResult));
  2110. break;
  2111. case 'cke_upload_and_browse':
  2112. $sTempId = utils::ReadParam('temp_id');
  2113. $sObjClass = utils::ReadParam('obj_class', '', false, 'class');
  2114. try
  2115. {
  2116. $oDoc = utils::ReadPostedDocument('upload');
  2117. if (InlineImage::IsImage($oDoc->GetMimeType()))
  2118. {
  2119. $aDimensions = null;
  2120. $oDoc = InlineImage::ResizeImageToFit($oDoc, $aDimensions);
  2121. $oAttachment = MetaModel::NewObject('InlineImage');
  2122. $oAttachment->Set('expire', time() + 3600); // one hour...
  2123. $oAttachment->Set('temp_id', $sTempId);
  2124. $oAttachment->Set('item_class', $sObjClass);
  2125. $oAttachment->SetDefaultOrgId();
  2126. $oAttachment->Set('contents', $oDoc);
  2127. $oAttachment->Set('secret', sprintf ('%06x', mt_rand(0, 0xFFFFFF))); // something not easy to guess
  2128. $iAttId = $oAttachment->DBInsert();
  2129. }
  2130. }
  2131. catch (FileUploadException $e)
  2132. {
  2133. // fail silently ??
  2134. }
  2135. // Fall though !! => browse
  2136. case 'cke_browse':
  2137. $oPage = new NiceWebPage(Dict::S('UI:BrowseInlineImages'));
  2138. $oPage->add_linked_stylesheet(utils::GetAbsoluteUrlAppRoot().'css/magnific-popup.css');
  2139. $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/jquery.magnific-popup.min.js');
  2140. $sImgUrl = utils::GetAbsoluteUrlAppRoot().INLINEIMAGE_DOWNLOAD_URL;
  2141. $sTempId = utils::ReadParam('temp_id');
  2142. $sClass = utils::ReadParam('obj_class', '', false, 'class');
  2143. $iObjectId = utils::ReadParam('obj_key', 0, false, 'integer');
  2144. $sCKEditorFuncNum = utils::ReadParam('CKEditorFuncNum', '');
  2145. $sPostUrl = utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php?CKEditorFuncNum='.$sCKEditorFuncNum;
  2146. $oPage->add_style(
  2147. <<<EOF
  2148. body {
  2149. overflow: auto;
  2150. }
  2151. EOF
  2152. );
  2153. $sMaxUpload = InlineImage::GetMaxUpload();
  2154. $sUploadLegend = Dict::S('UI:UploadInlineImageLegend');
  2155. $sUploadLabel = Dict::S('UI:SelectInlineImageToUpload');
  2156. $sAvailableImagesLegend = Dict::S('UI:AvailableInlineImagesLegend');
  2157. $sInsertBtnLabel = Dict::S('UI:Button:Insert');
  2158. $sNoInlineImage = Dict::S('UI:NoInlineImage');
  2159. $oPage->add(
  2160. <<<EOF
  2161. <div>
  2162. <fieldset>
  2163. <legend>$sUploadLegend</legend>
  2164. <form method="post" id="upload_form" action="$sPostUrl" enctype="multipart/form-data">
  2165. <input type="hidden" name="operation" value="cke_upload_and_browse">
  2166. <input type="hidden" name="temp_id" value="$sTempId">
  2167. <input type="hidden" name="obj_class" value="$sClass">
  2168. <input type="hidden" name="obj_key" value="$iObjectId">
  2169. $sUploadLabel <input id="upload_button" type="file" name="upload"> <span id="upload_status"> $sMaxUpload</span>
  2170. </form>
  2171. </fieldset>
  2172. </div>
  2173. EOF
  2174. );
  2175. $oPage->add_script(
  2176. <<<EOF
  2177. // Helper function to get parameters from the query string.
  2178. function getUrlParam( paramName ) {
  2179. var reParam = new RegExp( '(?:[\?&]|&)' + paramName + '=([^&]+)', 'i' );
  2180. var match = window.location.search.match( reParam );
  2181. return ( match && match.length > 1 ) ? match[1] : null;
  2182. }
  2183. // Simulate user action of selecting a file to be returned to CKEditor.
  2184. function returnFileUrl(iAttId, sAltText, sSecret) {
  2185. var funcNum = getUrlParam( 'CKEditorFuncNum' );
  2186. var fileUrl = '$sImgUrl'+iAttId+'&s='+sSecret;
  2187. window.opener.CKEDITOR.tools.callFunction( funcNum, fileUrl, function() {
  2188. // Get the reference to a dialog window.
  2189. var dialog = this.getDialog();
  2190. // Check if this is the Image Properties dialog window.
  2191. if ( dialog.getName() == 'image' ) {
  2192. // Get the reference to a text field that stores the "alt" attribute.
  2193. var element = dialog.getContentElement( 'info', 'txtAlt' );
  2194. // Assign the new value.
  2195. if ( element )
  2196. element.setValue(sAltText);
  2197. }
  2198. // Return "false" to stop further execution. In such case CKEditor will ignore the second argument ("fileUrl")
  2199. // and the "onSelect" function assigned to the button that called the file manager (if defined).
  2200. // return false;
  2201. } );
  2202. window.close();
  2203. }
  2204. EOF
  2205. );
  2206. $oPage->add_ready_script(
  2207. <<<EOF
  2208. $('#upload_button').on('change', function() {
  2209. $('#upload_status').html('<img src="../images/indicator.gif">');
  2210. $('#upload_form').submit();
  2211. $(this).prop('disabled', true);
  2212. });
  2213. $('.img-picker').magnificPopup({type: 'image', closeOnContentClick: true });
  2214. EOF
  2215. );
  2216. $sOQL = "SELECT InlineImage WHERE ((temp_id = :temp_id) OR (item_class = :obj_class AND item_id = :obj_id))";
  2217. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array(), array('temp_id' => $sTempId, 'obj_class' => $sClass, 'obj_id' => $iObjectId));
  2218. $oPage->add("<div><fieldset><legend>$sAvailableImagesLegend</legend>");
  2219. if ($oSet->Count() == 0)
  2220. {
  2221. $oPage->add("<p style=\"text-align:center\">$sNoInlineImage</p>");
  2222. }
  2223. else
  2224. {
  2225. while($oAttachment = $oSet->Fetch())
  2226. {
  2227. $oDoc = $oAttachment->Get('contents');
  2228. if ($oDoc->GetMainMimeType() == 'image')
  2229. {
  2230. $sDocName = addslashes(htmlentities($oDoc->GetFileName(), ENT_QUOTES, 'UTF-8'));
  2231. $iAttId = $oAttachment->GetKey();
  2232. $sSecret = $oAttachment->Get('secret');
  2233. $oPage->add("<div style=\"float:left;margin:1em;text-align:center;\"><img class=\"img-picker\" style=\"max-width:300px;cursor:zoom-in\" href=\"{$sImgUrl}{$iAttId}&s={$sSecret}\" alt=\"$sDocName\" title=\"$sDocName\" src=\"{$sImgUrl}{$iAttId}&s={$sSecret}\"><br/><button onclick=\"returnFileUrl($iAttId, '$sDocName', '$sSecret')\">$sInsertBtnLabel</button></div>");
  2234. }
  2235. }
  2236. }
  2237. $oPage->add("</fieldset></div>");
  2238. break;
  2239. case 'custom_fields_update':
  2240. $oPage->SetContentType('application/json');
  2241. $sAttCode = utils::ReadParam('attcode', '');
  2242. $aRequestedFields = utils::ReadParam('requested_fields', array());
  2243. $sRequestedFieldsFormPath = utils::ReadParam('form_path', '');
  2244. $sJson = utils::ReadParam('json_obj', '', false, 'raw_data');
  2245. $aResult = array();
  2246. try
  2247. {
  2248. $oWizardHelper = WizardHelper::FromJSON($sJson);
  2249. $oObj = $oWizardHelper->GetTargetObject();
  2250. $oOrmCustomFieldValue = $oObj->Get($sAttCode);
  2251. $oForm = $oOrmCustomFieldValue->GetForm();
  2252. $oSubForm = $oForm->FindSubForm($sRequestedFieldsFormPath);
  2253. $oRenderer = new \Combodo\iTop\Renderer\Console\ConsoleFormRenderer($oSubForm);
  2254. $aRenderRes = $oRenderer->Render($aRequestedFields);
  2255. $aResult['form']['updated_fields'] = $aRenderRes;
  2256. }
  2257. catch (Exception $e)
  2258. {
  2259. $aResult['error'] = $e->getMessage();
  2260. }
  2261. $oPage->add(json_encode($aResult));
  2262. break;
  2263. default:
  2264. $oPage->p("Invalid query.");
  2265. }
  2266. $oPage->output();
  2267. }
  2268. catch (Exception $e)
  2269. {
  2270. // note: transform to cope with XSS attacks
  2271. echo htmlentities($e->GetMessage(), ENT_QUOTES, 'utf-8');
  2272. IssueLog::Error($e->getMessage()."\nDebug trace:\n".$e->getTraceAsString());
  2273. }