ajax.render.php 91 KB

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