ajax.render.php 89 KB

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