ajax.render.php 91 KB

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