ajax.render.php 90 KB

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