ajax.render.php 91 KB

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