ajax.render.php 91 KB

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