ajax.render.php 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779
  1. <?php
  2. // Copyright (C) 2010-2014 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-2012 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/wizardhelper.class.inc.php');
  29. require_once(APPROOT.'/application/ui.linkswidget.class.inc.php');
  30. require_once(APPROOT.'/application/ui.extkeywidget.class.inc.php');
  31. require_once(APPROOT.'/application/datatable.class.inc.php');
  32. require_once(APPROOT.'/application/excelexporter.class.inc.php');
  33. try
  34. {
  35. require_once(APPROOT.'/application/startup.inc.php');
  36. require_once(APPROOT.'/application/user.preferences.class.inc.php');
  37. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  38. LoginWebPage::DoLoginEx(null /* any portal */, false);
  39. $oPage = new ajax_page("");
  40. $oPage->no_cache();
  41. $operation = utils::ReadParam('operation', '');
  42. $sFilter = stripslashes(utils::ReadParam('filter', '', false, 'raw_data'));
  43. $sEncoding = utils::ReadParam('encoding', 'serialize');
  44. $sClass = utils::ReadParam('class', 'MissingAjaxParam', false, 'class');
  45. $sStyle = utils::ReadParam('style', 'list');
  46. switch($operation)
  47. {
  48. case 'datatable':
  49. case 'pagination':
  50. $oPage->SetContentType('text/html');
  51. $extraParams = utils::ReadParam('extra_param', '', false, 'raw_data');
  52. $aExtraParams = array();
  53. if (is_array($extraParams))
  54. {
  55. $aExtraParams = $extraParams;
  56. }
  57. else
  58. {
  59. $sExtraParams = stripslashes($extraParams);
  60. if (!empty($sExtraParams))
  61. {
  62. $val = json_decode(str_replace("'", '"', $sExtraParams), true /* associative array */);
  63. if ($val !== null)
  64. {
  65. $aExtraParams = $val;
  66. }
  67. }
  68. }
  69. if ($sEncoding == 'oql')
  70. {
  71. $oFilter = CMDBSearchFilter::FromOQL($sFilter);
  72. }
  73. else
  74. {
  75. $oFilter = CMDBSearchFilter::unserialize($sFilter);
  76. }
  77. $iStart = utils::ReadParam('start',0);
  78. $iEnd = utils::ReadParam('end',1);
  79. $iSortCol = utils::ReadParam('sort_col','null');
  80. $sSelectMode = utils::ReadParam('select_mode', '');
  81. if (!empty($sSelectMode) && ($sSelectMode != 'none'))
  82. {
  83. // The first column is used for the selection (radio / checkbox) and is not sortable
  84. $iSortCol--;
  85. }
  86. $bDisplayKey = utils::ReadParam('display_key', 'true') == 'true';
  87. $aColumns = utils::ReadParam('columns', array(), false, 'raw_data');
  88. $aClassAliases = utils::ReadParam('class_aliases', array());
  89. $iListId = utils::ReadParam('list_id', 0);
  90. //$aList = cmdbAbstractObject::FlattenZList(MetaModel::GetZListItems($sClassName, 'list'));
  91. // Filter the list to removed linked set since we are not able to display them here
  92. $aOrderBy = array();
  93. $iSortIndex = 0;
  94. $aColumnsLoad = array();
  95. foreach($aClassAliases as $sAlias => $sClassName)
  96. {
  97. $aColumnsLoad[$sAlias] = array();
  98. foreach($aColumns[$sAlias] as $sAttCode => $aData)
  99. {
  100. if ($aData['checked'] == 'true')
  101. {
  102. $aColumns[$sAlias][$sAttCode]['checked'] = true;
  103. if ($sAttCode == '_key_')
  104. {
  105. if ($iSortCol == $iSortIndex)
  106. {
  107. if (!MetaModel::HasChildrenClasses($oFilter->GetClass()))
  108. {
  109. $aNameSpec = MetaModel::GetNameSpec($oFilter->GetClass());
  110. if ($aNameSpec[0] == '%1$s')
  111. {
  112. // The name is made of a single column, let's sort according to the sort algorithm for this column
  113. $aOrderBy[$sAlias.'.'.$aNameSpec[1][0]] = (utils::ReadParam('sort_order', 'asc') == 'asc');
  114. }
  115. else
  116. {
  117. $aOrderBy[$sAlias.'.'.'friendlyname'] = (utils::ReadParam('sort_order', 'asc') == 'asc');
  118. }
  119. }
  120. else
  121. {
  122. $aOrderBy[$sAlias.'.'.'friendlyname'] = (utils::ReadParam('sort_order', 'asc') == 'asc');
  123. }
  124. }
  125. }
  126. else
  127. {
  128. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  129. if ($oAttDef instanceof AttributeLinkedSet)
  130. {
  131. // Removed from the display list
  132. unset($aColumns[$sAlias][$sAttCode]);
  133. }
  134. else
  135. {
  136. $aColumnsLoad[$sAlias][] = $sAttCode;
  137. }
  138. if ($iSortCol == $iSortIndex)
  139. {
  140. if ($oAttDef->IsExternalKey())
  141. {
  142. $sSortCol = $sAttCode.'_friendlyname';
  143. }
  144. else
  145. {
  146. $sSortCol = $sAttCode;
  147. }
  148. $aOrderBy[$sAlias.'.'.$sSortCol] = (utils::ReadParam('sort_order', 'asc') == 'asc');
  149. }
  150. }
  151. $iSortIndex++;
  152. }
  153. else
  154. {
  155. $aColumns[$sAlias][$sAttCode]['checked'] = false;
  156. }
  157. }
  158. }
  159. // Load only the requested columns
  160. $oSet = new DBObjectSet($oFilter, $aOrderBy, $aExtraParams, null, $iEnd-$iStart, $iStart);
  161. $oSet->OptimizeColumnLoad($aColumnsLoad);
  162. $oDataTable = new DataTable($iListId, $oSet, $oSet->GetSelectedClasses());
  163. if ($operation == 'datatable')
  164. {
  165. // Redraw the whole table
  166. $sHtml = $oDataTable->UpdatePager($oPage, $iEnd-$iStart, $iStart); // Set the default page size
  167. $sHtml .= $oDataTable->GetHTMLTable($oPage, $aColumns, $sSelectMode, $iEnd-$iStart, $bDisplayKey, $aExtraParams);
  168. }
  169. else
  170. {
  171. // redraw just the needed rows
  172. $sHtml = $oDataTable->GetAsHTMLTableRows($oPage, $iEnd-$iStart, $aColumns, $sSelectMode, $bDisplayKey, $aExtraParams);
  173. }
  174. $oPage->add($sHtml);
  175. break;
  176. case 'datatable_save_settings':
  177. $oPage->SetContentType('text/plain');
  178. $iPageSize = utils::ReadParam('page_size', 10);
  179. $sTableId = utils::ReadParam('table_id', null, false, 'raw_data');
  180. $bSaveAsDefaults = (utils::ReadParam('defaults', 'true') == 'true');
  181. $aClassAliases = utils::ReadParam('class_aliases', array(), false, 'raw_data');
  182. $aColumns = utils::ReadParam('columns', array(), false, 'raw_data');
  183. foreach($aColumns as $sAlias => $aList)
  184. {
  185. foreach($aList as $sAttCode => $aData)
  186. {
  187. $aColumns[$sAlias][$sAttCode]['checked'] = ($aData['checked'] == 'true');
  188. $aColumns[$sAlias][$sAttCode]['disabled'] = ($aData['disabled'] == 'true');
  189. $aColumns[$sAlias][$sAttCode]['sort'] = ($aData['sort']);
  190. }
  191. }
  192. $oSettings = new DataTableSettings($aClassAliases, $sTableId);
  193. $oSettings->iDefaultPageSize = $iPageSize;
  194. $oSettings->aColumns = $aColumns;
  195. if ($bSaveAsDefaults)
  196. {
  197. if ($sTableId != null)
  198. {
  199. $oCurrSettings = DataTableSettings::GetTableSettings($aClassAliases, $sTableId, true /* bOnlyTable */ );
  200. if ($oCurrSettings)
  201. {
  202. $oCurrSettings->ResetToDefault(false); // Reset this table to the defaults
  203. }
  204. }
  205. $bRet = $oSettings->SaveAsDefault();
  206. }
  207. else
  208. {
  209. $bRet = $oSettings->Save();
  210. }
  211. $oPage->add($bRet ? 'Ok' : 'KO');
  212. break;
  213. case 'datatable_reset_settings':
  214. $oPage->SetContentType('text/plain');
  215. $sTableId = utils::ReadParam('table_id', null, false, 'raw_data');
  216. $aClassAliases = utils::ReadParam('class_aliases', array(), false, 'raw_data');
  217. $bResetAll = (utils::ReadParam('defaults', 'true') == 'true');
  218. $oSettings = new DataTableSettings($aClassAliases, $sTableId);
  219. $bRet = $oSettings->ResetToDefault($bResetAll);
  220. $oPage->add($bRet ? 'Ok' : 'KO');
  221. break;
  222. // ui.linkswidget
  223. case 'addObjects':
  224. $oPage->SetContentType('text/html');
  225. $sAttCode = utils::ReadParam('sAttCode', '');
  226. $iInputId = utils::ReadParam('iInputId', '');
  227. $sSuffix = utils::ReadParam('sSuffix', '');
  228. $bDuplicates = (utils::ReadParam('bDuplicates', 'false') == 'false') ? false : true;
  229. $sJson = utils::ReadParam('json', '', false, 'raw_data');
  230. if (!empty($sJson))
  231. {
  232. $oWizardHelper = WizardHelper::FromJSON($sJson);
  233. $oObj = $oWizardHelper->GetTargetObject();
  234. }
  235. else
  236. {
  237. // Search form: no current object
  238. $oObj = null;
  239. }
  240. $oWidget = new UILinksWidget($sClass, $sAttCode, $iInputId, $sSuffix, $bDuplicates);
  241. $oWidget->GetObjectPickerDialog($oPage, $oObj);
  242. break;
  243. // ui.linkswidget
  244. case 'searchObjectsToAdd':
  245. $oPage->SetContentType('text/html');
  246. $sRemoteClass = utils::ReadParam('sRemoteClass', '', false, 'class');
  247. $sAttCode = utils::ReadParam('sAttCode', '');
  248. $iInputId = utils::ReadParam('iInputId', '');
  249. $sSuffix = utils::ReadParam('sSuffix', '');
  250. $bDuplicates = (utils::ReadParam('bDuplicates', 'false') == 'false') ? false : true;
  251. $aAlreadyLinked = utils::ReadParam('aAlreadyLinked', array());
  252. $oWidget = new UILinksWidget($sClass, $sAttCode, $iInputId, $sSuffix, $bDuplicates);
  253. $oWidget->SearchObjectsToAdd($oPage, $sRemoteClass, $aAlreadyLinked);
  254. break;
  255. //ui.linksdirectwidget
  256. case 'createObject':
  257. $oPage->SetContentType('text/html');
  258. $sClass = utils::ReadParam('class', '', false, 'class');
  259. $sRealClass = utils::ReadParam('real_class', '', false, 'class');
  260. $sAttCode = utils::ReadParam('att_code', '');
  261. $iInputId = utils::ReadParam('iInputId', '');
  262. $oPage->SetContentType('text/html');
  263. $oWidget = new UILinksWidgetDirect($sClass, $sAttCode, $iInputId);
  264. $oWidget->GetObjectCreationDlg($oPage, $sRealClass);
  265. break;
  266. // ui.linksdirectwidget
  267. case 'getLinksetRow':
  268. $oPage->SetContentType('text/html');
  269. $sClass = utils::ReadParam('class', '', false, 'class');
  270. $sRealClass = utils::ReadParam('real_class', '', false, 'class');
  271. $sAttCode = utils::ReadParam('att_code', '');
  272. $iInputId = utils::ReadParam('iInputId', '');
  273. $iTempId = utils::ReadParam('tempId', '');
  274. $aValues = utils::ReadParam('values', array(), false, 'raw_data');
  275. $oPage->SetContentType('text/html');
  276. $oWidget = new UILinksWidgetDirect($sClass, $sAttCode, $iInputId);
  277. $oPage->add($oWidget->GetRow($oPage, $sRealClass, $aValues, -$iTempId));
  278. break;
  279. // ui.linksdirectwidget
  280. case 'selectObjectsToAdd':
  281. $oPage->SetContentType('text/html');
  282. $sClass = utils::ReadParam('class', '', false, 'class');
  283. $sJson = utils::ReadParam('json', '', false, 'raw_data');
  284. $oObj = null;
  285. if ($sJson != '')
  286. {
  287. $oWizardHelper = WizardHelper::FromJSON($sJson);
  288. $oObj = $oWizardHelper->GetTargetObject();
  289. }
  290. $sRealClass = utils::ReadParam('real_class', '', false, 'class');
  291. $sAttCode = utils::ReadParam('att_code', '');
  292. $iInputId = utils::ReadParam('iInputId', '');
  293. $iCurrObjectId = utils::ReadParam('iObjId', 0);
  294. $oPage->SetContentType('text/html');
  295. $oWidget = new UILinksWidgetDirect($sClass, $sAttCode, $iInputId);
  296. $oWidget->GetObjectsSelectionDlg($oPage, $oObj);
  297. break;
  298. // ui.linksdirectwidget
  299. case 'searchObjectsToAdd2':
  300. $oPage->SetContentType('text/html');
  301. $sClass = utils::ReadParam('class', '', false, 'class');
  302. $sRealClass = utils::ReadParam('real_class', '', false, 'class');
  303. $sAttCode = utils::ReadParam('att_code', '');
  304. $iInputId = utils::ReadParam('iInputId', '');
  305. $aAlreadyLinked = utils::ReadParam('aAlreadyLinked', array());
  306. $sJson = utils::ReadParam('json', '', false, 'raw_data');
  307. $oObj = null;
  308. if ($sJson != '')
  309. {
  310. $oWizardHelper = WizardHelper::FromJSON($sJson);
  311. $oObj = $oWizardHelper->GetTargetObject();
  312. }
  313. $oWidget = new UILinksWidgetDirect($sClass, $sAttCode, $iInputId);
  314. $oWidget->SearchObjectsToAdd($oPage, $sRealClass, $aAlreadyLinked, $oObj);
  315. break;
  316. // ui.linksdirectwidget
  317. case 'doAddObjects2':
  318. $oPage->SetContentType('text/html');
  319. $oPage->SetContentType('text/html');
  320. $sClass = utils::ReadParam('class', '', false, 'class');
  321. $sRealClass = utils::ReadParam('real_class', '', false, 'class');
  322. $sAttCode = utils::ReadParam('att_code', '');
  323. $iInputId = utils::ReadParam('iInputId', '');
  324. $iCurrObjectId = utils::ReadParam('iObjId', 0);
  325. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  326. if ($sFilter != '')
  327. {
  328. $oFullSetFilter = DBObjectSearch::unserialize($sFilter);
  329. }
  330. else
  331. {
  332. $oLinksetDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  333. $valuesDef = $oLinksetDef->GetValuesDef();
  334. if ($valuesDef === null)
  335. {
  336. $oFullSetFilter = new DBObjectSearch($oLinksetDef->GetLinkedClass());
  337. }
  338. else
  339. {
  340. if (!$valuesDef instanceof ValueSetObjects)
  341. {
  342. throw new Exception('Error: only ValueSetObjects are supported for "allowed_values" in AttributeLinkedSet ('.$this->sClass.'/'.$this->sAttCode.').');
  343. }
  344. $oFullSetFilter = DBObjectSearch::FromOQL($valuesDef->GetFilterExpression());
  345. }
  346. }
  347. $oWidget = new UILinksWidgetDirect($sClass, $sAttCode, $iInputId);
  348. $oWidget->DoAddObjects($oPage, $oFullSetFilter);
  349. break;
  350. ////////////////////////////////////////////////////////////
  351. // ui.extkeywidget
  352. case 'searchObjectsToSelect':
  353. $oPage->SetContentType('text/html');
  354. $sTargetClass = utils::ReadParam('sTargetClass', '', false, 'class');
  355. $iInputId = utils::ReadParam('iInputId', '');
  356. $sRemoteClass = utils::ReadParam('sRemoteClass', '', false, 'class');
  357. $sFilter = utils::ReadParam('sFilter', '', false, 'raw_data');
  358. $sJson = utils::ReadParam('json', '', false, 'raw_data');
  359. $sAttCode = utils::ReadParam('sAttCode', '');
  360. $bSearchMode = (utils::ReadParam('bSearchMode', 'false') == 'true');
  361. if (!empty($sJson))
  362. {
  363. $oWizardHelper = WizardHelper::FromJSON($sJson);
  364. $oObj = $oWizardHelper->GetTargetObject();
  365. }
  366. else
  367. {
  368. // Search form: no current object
  369. $oObj = null;
  370. }
  371. $oWidget = new UIExtKeyWidget($sTargetClass, $iInputId, $sAttCode, $bSearchMode);
  372. $oWidget->SearchObjectsToSelect($oPage, $sFilter, $sRemoteClass, $oObj);
  373. break;
  374. // ui.extkeywidget: autocomplete
  375. case 'ac_extkey':
  376. $oPage->SetContentType('text/plain');
  377. $sTargetClass = utils::ReadParam('sTargetClass', '', false, 'class');
  378. $iInputId = utils::ReadParam('iInputId', '');
  379. $sFilter = utils::ReadParam('sFilter', '', false, 'raw_data');
  380. $sJson = utils::ReadParam('json', '', false, 'raw_data');
  381. $sContains = utils::ReadParam('q', '', false, 'raw_data');
  382. $bSearchMode = (utils::ReadParam('bSearchMode', 'false') == 'true');
  383. if ($sContains !='')
  384. {
  385. if (!empty($sJson))
  386. {
  387. $oWizardHelper = WizardHelper::FromJSON($sJson);
  388. $oObj = $oWizardHelper->GetTargetObject();
  389. }
  390. else
  391. {
  392. // Search form: no current object
  393. $oObj = null;
  394. }
  395. $oWidget = new UIExtKeyWidget($sTargetClass, $iInputId, '', $bSearchMode);
  396. $oWidget->AutoComplete($oPage, $sFilter, $oObj, $sContains);
  397. }
  398. break;
  399. // ui.extkeywidget
  400. case 'objectSearchForm':
  401. $oPage->SetContentType('text/html');
  402. $sTargetClass = utils::ReadParam('sTargetClass', '', false, 'class');
  403. $iInputId = utils::ReadParam('iInputId', '');
  404. $sTitle = utils::ReadParam('sTitle', '', false, 'raw_data');
  405. $sAttCode = utils::ReadParam('sAttCode', '');
  406. $bSearchMode = (utils::ReadParam('bSearchMode', 'false') == 'true');
  407. $oWidget = new UIExtKeyWidget($sTargetClass, $iInputId, $sAttCode, $bSearchMode);
  408. $sJson = utils::ReadParam('json', '', false, 'raw_data');
  409. if (!empty($sJson))
  410. {
  411. $oWizardHelper = WizardHelper::FromJSON($sJson);
  412. $oObj = $oWizardHelper->GetTargetObject();
  413. }
  414. else
  415. {
  416. // Search form: no current object
  417. $oObj = null;
  418. }
  419. $oWidget->GetSearchDialog($oPage, $sTitle, $oObj);
  420. break;
  421. // ui.extkeywidget
  422. case 'objectCreationForm':
  423. $oPage->SetContentType('text/html');
  424. $sTargetClass = utils::ReadParam('sTargetClass', '', false, 'class');
  425. $iInputId = utils::ReadParam('iInputId', '');
  426. $sAttCode = utils::ReadParam('sAttCode', '');
  427. $oWidget = new UIExtKeyWidget($sTargetClass, $iInputId, $sAttCode, false);
  428. $sJson = utils::ReadParam('json', '', false, 'raw_data');
  429. if (!empty($sJson))
  430. {
  431. $oWizardHelper = WizardHelper::FromJSON($sJson);
  432. $oObj = $oWizardHelper->GetTargetObject();
  433. }
  434. else
  435. {
  436. // Search form: no current object
  437. $oObj = null;
  438. }
  439. $oWidget->GetObjectCreationForm($oPage, $oObj);
  440. break;
  441. // ui.extkeywidget
  442. case 'doCreateObject':
  443. $oPage->SetContentType('application/json');
  444. $sTargetClass = utils::ReadParam('sTargetClass', '', false, 'class');
  445. $iInputId = utils::ReadParam('iInputId', '');
  446. $sFormPrefix = utils::ReadParam('sFormPrefix', '');
  447. $sAttCode = utils::ReadParam('sAttCode', '');
  448. $oWidget = new UIExtKeyWidget($sTargetClass, $iInputId, $sAttCode, false);
  449. $aResult = $oWidget->DoCreateObject($oPage);
  450. echo json_encode($aResult);
  451. break;
  452. // ui.extkeywidget
  453. case 'getObjectName':
  454. $oPage->SetContentType('application/json');
  455. $sTargetClass = utils::ReadParam('sTargetClass', '', false, 'class');
  456. $iInputId = utils::ReadParam('iInputId', '');
  457. $iObjectId = utils::ReadParam('iObjectId', '');
  458. $bSearchMode = (utils::ReadParam('bSearchMode', 'false') == 'true');
  459. $oWidget = new UIExtKeyWidget($sTargetClass, $iInputId, '', $bSearchMode);
  460. $sName = $oWidget->GetObjectName($iObjectId);
  461. echo json_encode(array('name' => $sName));
  462. break;
  463. // ui.extkeywidget
  464. case 'displayHierarchy':
  465. $oPage->SetContentType('text/html');
  466. $sTargetClass = utils::ReadParam('sTargetClass', '', false, 'class');
  467. $sInputId = utils::ReadParam('sInputId', '');
  468. $sFilter = utils::ReadParam('sFilter', '', false, 'raw_data');
  469. $sJson = utils::ReadParam('json', '', false, 'raw_data');
  470. $currValue = utils::ReadParam('value', '');
  471. $bSearchMode = (utils::ReadParam('bSearchMode', 'false') == 'true');
  472. if (!empty($sJson))
  473. {
  474. $oWizardHelper = WizardHelper::FromJSON($sJson);
  475. $oObj = $oWizardHelper->GetTargetObject();
  476. }
  477. else
  478. {
  479. // Search form: no current object
  480. $oObj = null;
  481. }
  482. $oWidget = new UIExtKeyWidget($sTargetClass, $sInputId, '', $bSearchMode);
  483. $oWidget->DisplayHierarchy($oPage, $sFilter, $currValue, $oObj);
  484. break;
  485. ////////////////////////////////////////////////////
  486. // ui.linkswidget
  487. case 'doAddObjects':
  488. $oPage->SetContentType('text/html');
  489. $sAttCode = utils::ReadParam('sAttCode', '');
  490. $iInputId = utils::ReadParam('iInputId', '');
  491. $sSuffix = utils::ReadParam('sSuffix', '');
  492. $sRemoteClass = utils::ReadParam('sRemoteClass', $sClass, false, 'class');
  493. $bDuplicates = (utils::ReadParam('bDuplicates', 'false') == 'false') ? false : true;
  494. $sJson = utils::ReadParam('json', '', false, 'raw_data');
  495. $oWizardHelper = WizardHelper::FromJSON($sJson);
  496. $oObj = $oWizardHelper->GetTargetObject();
  497. $oWidget = new UILinksWidget($sClass, $sAttCode, $iInputId, $sSuffix, $bDuplicates);
  498. if ($sFilter != '')
  499. {
  500. $oFullSetFilter = DBObjectSearch::unserialize($sFilter);
  501. }
  502. else
  503. {
  504. $oFullSetFilter = new DBObjectSearch($sRemoteClass);
  505. }
  506. $oWidget->DoAddObjects($oPage, $oFullSetFilter, $oObj);
  507. break;
  508. ////////////////////////////////////////////////////////////
  509. case 'wizard_helper_preview':
  510. $oPage->SetContentType('text/html');
  511. $sJson = utils::ReadParam('json_obj', '', false, 'raw_data');
  512. $oWizardHelper = WizardHelper::FromJSON($sJson);
  513. $oObj = $oWizardHelper->GetTargetObject();
  514. $oObj->DisplayBareProperties($oPage);
  515. break;
  516. case 'wizard_helper':
  517. $oPage->SetContentType('text/html');
  518. $sJson = utils::ReadParam('json_obj', '', false, 'raw_data');
  519. $oWizardHelper = WizardHelper::FromJSON($sJson);
  520. $oObj = $oWizardHelper->GetTargetObject();
  521. $sClass = $oWizardHelper->GetTargetClass();
  522. foreach($oWizardHelper->GetFieldsForDefaultValue() as $sAttCode)
  523. {
  524. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  525. $defaultValue = $oAttDef->GetDefaultValue();
  526. $oWizardHelper->SetDefaultValue($sAttCode, $defaultValue);
  527. $oObj->Set($sAttCode, $defaultValue);
  528. }
  529. $sFormPrefix = $oWizardHelper->GetFormPrefix();
  530. foreach($oWizardHelper->GetFieldsForAllowedValues() as $sAttCode)
  531. {
  532. $sId = $oWizardHelper->GetIdForField($sAttCode);
  533. if ($sId != '')
  534. {
  535. if ($oObj->IsNew())
  536. {
  537. $iFlags = $oObj->GetInitialStateAttributeFlags($sAttCode);
  538. }
  539. else
  540. {
  541. $iFlags = $oObj->GetAttributeFlags($sAttCode);
  542. }
  543. if ($iFlags & OPT_ATT_READONLY)
  544. {
  545. $sHTMLValue = "<span id=\"field_{$sId}\">".$oObj->GetAsHTML($sAttCode);
  546. $sHTMLValue .= '<input type="hidden" id="'.$sId.'" name="attr_'.$sFormPrefix.$sAttCode.'" value="'.htmlentities($oObj->Get($sAttCode), ENT_QUOTES, 'UTF-8').'"/></span>';
  547. $oWizardHelper->SetAllowedValuesHtml($sAttCode, $sHTMLValue);
  548. }
  549. else
  550. {
  551. // It may happen that the field we'd like to update does not
  552. // exist in the form. For example, if the field should be hidden/read-only
  553. // in the current state of the object
  554. $value = $oObj->Get($sAttCode);
  555. $displayValue = $oObj->GetEditValue($sAttCode);
  556. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  557. if (!$oAttDef->IsWritable())
  558. {
  559. // Even non-writable fields (like AttributeExternal) can be refreshed
  560. $sHTMLValue = $oObj->GetAsHTML($sAttCode);
  561. }
  562. else
  563. {
  564. $iFlags = MetaModel::GetAttributeFlags($sClass, $oObj->GetState(), $sAttCode);
  565. $sHTMLValue = cmdbAbstractObject::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $value, $displayValue, $sId, '', $iFlags, array('this' => $oObj, 'formPrefix' => $sFormPrefix));
  566. // Make sure that we immediately validate the field when we reload it
  567. $oPage->add_ready_script("$('#$sId').trigger('validate');");
  568. }
  569. $oWizardHelper->SetAllowedValuesHtml($sAttCode, $sHTMLValue);
  570. }
  571. }
  572. }
  573. $oPage->add_script("oWizardHelper{$sFormPrefix}.m_oData=".$oWizardHelper->ToJSON().";\noWizardHelper{$sFormPrefix}.UpdateFields();\n");
  574. break;
  575. case 'obj_creation_form':
  576. $oPage->SetContentType('text/html');
  577. $sJson = utils::ReadParam('json_obj', '', false, 'raw_data');
  578. $oWizardHelper = WizardHelper::FromJSON($sJson);
  579. $oObj = $oWizardHelper->GetTargetObject();
  580. $sClass = $oWizardHelper->GetTargetClass();
  581. $sTargetState = utils::ReadParam('target_state', '');
  582. $iTransactionId = utils::ReadParam('transaction_id', '');
  583. $oObj->Set(MetaModel::GetStateAttributeCode($sClass), $sTargetState);
  584. cmdbAbstractObject::DisplayCreationForm($oPage, $sClass, $oObj, array(), array('action' => utils::GetAbsoluteUrlAppRoot().'pages/UI.php', 'transaction_id' => $iTransactionId));
  585. break;
  586. // DisplayBlock
  587. case 'ajax':
  588. $oPage->SetContentType('text/html');
  589. if ($sFilter != "")
  590. {
  591. $sExtraParams = stripslashes(utils::ReadParam('extra_params', '', false, 'raw_data'));
  592. $aExtraParams = array();
  593. if (!empty($sExtraParams))
  594. {
  595. $aExtraParams = json_decode(str_replace("'", '"', $sExtraParams), true /* associative array */);
  596. }
  597. // Restore the app context from the ExtraParams
  598. $oAppContext = new ApplicationContext(false); // false => don't read the context yet !
  599. $aContext = array();
  600. foreach($oAppContext->GetNames() as $sName)
  601. {
  602. $sParamName = 'c['.$sName.']';
  603. if (isset($aExtraParams[$sParamName]))
  604. {
  605. $aContext[$sName] = $aExtraParams[$sParamName];
  606. }
  607. }
  608. $_REQUEST['c'] = $aContext;
  609. if ($sEncoding == 'oql')
  610. {
  611. $oFilter = CMDBSearchFilter::FromOQL($sFilter);
  612. }
  613. else
  614. {
  615. $oFilter = CMDBSearchFilter::unserialize($sFilter);
  616. }
  617. $oDisplayBlock = new DisplayBlock($oFilter, $sStyle, false);
  618. $aExtraParams['display_limit'] = true;
  619. $aExtraParams['truncated'] = true;
  620. $oDisplayBlock->RenderContent($oPage, $aExtraParams);
  621. }
  622. else
  623. {
  624. $oPage->p("Invalid query (empty filter).");
  625. }
  626. break;
  627. case 'displayCSVHistory':
  628. $oPage->SetContentType('text/html');
  629. $bShowAll = (utils::ReadParam('showall', 'false') == 'true');
  630. BulkChange::DisplayImportHistory($oPage, true, $bShowAll);
  631. break;
  632. case 'details':
  633. $oPage->SetContentType('text/html');
  634. $key = utils::ReadParam('id', 0);
  635. $oFilter = new DBObjectSearch($sClass);
  636. $oFilter->AddCondition('id', $key, '=');
  637. $oDisplayBlock = new DisplayBlock($oFilter, 'details', false);
  638. $oDisplayBlock->RenderContent($oPage);
  639. break;
  640. case 'pie_chart':
  641. $oPage->SetContentType('application/json');
  642. $sGroupBy = utils::ReadParam('group_by', '');
  643. if ($sFilter != '')
  644. {
  645. if ($sEncoding == 'oql')
  646. {
  647. $oFilter = CMDBSearchFilter::FromOQL($sFilter);
  648. }
  649. else
  650. {
  651. $oFilter = CMDBSearchFilter::unserialize($sFilter);
  652. }
  653. $oDisplayBlock = new DisplayBlock($oFilter, 'pie_chart_ajax', false);
  654. $oDisplayBlock->RenderContent($oPage, array('group_by' => $sGroupBy));
  655. }
  656. else
  657. {
  658. $oPage->add("<chart>\n<chart_type>3d pie</chart_type><!-- empty filter '$sFilter' --></chart>\n.");
  659. }
  660. break;
  661. case 'open_flash_chart':
  662. // Workaround for IE8 + IIS + HTTPS
  663. // See TRAC #363, fix described here: http://forums.codecharge.com/posts.php?post_id=97771
  664. $oPage->add_header("Expires: Fri, 17 Jul 1970 05:00:00 GMT");
  665. $oPage->add_header("Cache-Control: cache, must-revalidate");
  666. $oPage->add_header("Pragma: public");
  667. $oPage->SetContentType('application/json');
  668. $aParams = utils::ReadParam('params', array(), false, 'raw_data');
  669. if ($sFilter != '')
  670. {
  671. $oFilter = CMDBSearchFilter::unserialize($sFilter);
  672. $oDisplayBlock = new DisplayBlock($oFilter, 'open_flash_chart_ajax', false);
  673. $oDisplayBlock->RenderContent($oPage, $aParams);
  674. }
  675. else
  676. {
  677. $oPage->add("<chart>\n<chart_type>3d pie</chart_type><!-- empty filter '$sFilter' --></chart>\n.");
  678. }
  679. break;
  680. case 'modal_details':
  681. $oPage->SetContentType('text/html');
  682. $key = utils::ReadParam('id', 0);
  683. $oFilter = new DBObjectSearch($sClass);
  684. $oFilter->AddCondition('id', $key, '=');
  685. $oPage->Add("<p style=\"width:100%; margin-top:-5px;padding:3px; background-color:#33f; color:#fff;\">Object Details</p>\n");
  686. $oDisplayBlock = new DisplayBlock($oFilter, 'details', false);
  687. $oDisplayBlock->RenderContent($oPage);
  688. $oPage->Add("<input type=\"button\" class=\"jqmClose\" value=\" Close \" />\n");
  689. break;
  690. case 'link':
  691. $oPage->SetContentType('text/html');
  692. $sClass = utils::ReadParam('sclass', 'logInfra', false, 'class');
  693. $sAttCode = utils::ReadParam('attCode', 'name');
  694. //$sOrg = utils::ReadParam('org_id', '');
  695. $sName = utils::ReadParam('q', '');
  696. $iMaxCount = utils::ReadParam('max', 30);
  697. $iCount = 0;
  698. $oFilter = new DBObjectSearch($sClass);
  699. $oFilter->AddCondition($sAttCode, $sName, 'Begins with');
  700. //$oFilter->AddCondition('org_id', $sOrg, '=');
  701. $oSet = new CMDBObjectSet($oFilter, array($sAttCode => true));
  702. while( ($iCount < $iMaxCount) && ($oObj = $oSet->fetch()) )
  703. {
  704. $oPage->add($oObj->GetAsHTML($sAttCode)."|".$oObj->GetKey()."\n");
  705. $iCount++;
  706. }
  707. break;
  708. case 'combo_options':
  709. $oPage->SetContentType('text/html');
  710. $oFilter = CMDBSearchFilter::FromOQL($sFilter);
  711. $oSet = new CMDBObjectSet($oFilter);
  712. while( $oObj = $oSet->fetch())
  713. {
  714. $oPage->add('<option title="Here is more information..." value="'.$oObj->GetKey().'">'.$oObj->GetName().'</option>');
  715. }
  716. break;
  717. case 'display_document':
  718. $id = utils::ReadParam('id', '');
  719. $sField = utils::ReadParam('field', '');
  720. if (!empty($sClass) && !empty($id) && !empty($sField))
  721. {
  722. DownloadDocument($oPage, $sClass, $id, $sField, 'inline');
  723. }
  724. break;
  725. case 'download_document':
  726. $id = utils::ReadParam('id', '');
  727. $sField = utils::ReadParam('field', '');
  728. $iCacheSec = (int) utils::ReadParam('cache', 0);
  729. if (!empty($sClass) && !empty($id) && !empty($sField))
  730. {
  731. DownloadDocument($oPage, $sClass, $id, $sField, 'attachment');
  732. if ($iCacheSec > 0)
  733. {
  734. $oPage->add_header("Expires: "); // Reset the value set in ajax_page
  735. $oPage->add_header("Cache-Control: no-transform,public,max-age=$iCacheSec,s-maxage=$iCacheSec");
  736. }
  737. }
  738. break;
  739. case 'search_form':
  740. $oPage->SetContentType('text/html');
  741. $sClass = utils::ReadParam('className', '', false, 'class');
  742. $sRootClass = utils::ReadParam('baseClass', '', false, 'class');
  743. $currentId = utils::ReadParam('currentId', '');
  744. $sTableId = utils::ReadParam('_table_id_', null, false, 'raw_data');
  745. $sAction = utils::ReadParam('action', '');
  746. $oFilter = new DBObjectSearch($sClass);
  747. $oSet = new CMDBObjectSet($oFilter);
  748. $sHtml = cmdbAbstractObject::GetSearchForm($oPage, $oSet, array('currentId' => $currentId, 'baseClass' => $sRootClass, 'action' => $sAction, 'table_id' => $sTableId));
  749. $oPage->add($sHtml);
  750. break;
  751. case 'set_pref':
  752. $sCode = utils::ReadPostedParam('code', '');
  753. $sValue = utils::ReadPostedParam('value', '', 'raw_data');
  754. appUserPreferences::SetPref($sCode, $sValue);
  755. break;
  756. case 'erase_all_pref':
  757. // Can be useful in case a user got some corrupted prefs...
  758. appUserPreferences::ClearPreferences();
  759. break;
  760. case 'on_form_cancel':
  761. // Called when a creation/modification form is cancelled by the end-user
  762. // Let's take this opportunity to inform the plug-ins so that they can perform some cleanup
  763. $iTransactionId = utils::ReadParam('transaction_id', 0);
  764. $sTempId = session_id().'_'.$iTransactionId;
  765. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  766. {
  767. $oExtensionInstance->OnFormCancel($sTempId);
  768. }
  769. break;
  770. case 'reload_dashboard':
  771. $oPage->SetContentType('text/html');
  772. $sDashboardId = utils::ReadParam('dashboard_id', '', false, 'raw_data');
  773. $aExtraParams = utils::ReadParam('extra_params', '', false, 'raw_data');
  774. ApplicationMenu::LoadAdditionalMenus();
  775. $idx = ApplicationMenu::GetMenuIndexById($sDashboardId);
  776. $oMenu = ApplicationMenu::GetMenuNode($idx);
  777. $oDashboard = $oMenu->GetDashboard();
  778. $oDashboard->Render($oPage, false, $aExtraParams);
  779. $oPage->add_ready_script("$('.dashboard_contents table.listResults').tableHover(); $('.dashboard_contents table.listResults').tablesorter( { widgets: ['myZebra', 'truncatedList']} );");
  780. break;
  781. case 'dashboard_editor':
  782. $sId = utils::ReadParam('id', '', false, 'raw_data');
  783. ApplicationMenu::LoadAdditionalMenus();
  784. $idx = ApplicationMenu::GetMenuIndexById($sId);
  785. $oMenu = ApplicationMenu::GetMenuNode($idx);
  786. $oMenu->RenderEditor($oPage);
  787. break;
  788. case 'new_dashlet':
  789. require_once(APPROOT.'application/forms.class.inc.php');
  790. require_once(APPROOT.'application/dashlet.class.inc.php');
  791. $sDashletClass = utils::ReadParam('dashlet_class', '');
  792. $sDashletId = utils::ReadParam('dashlet_id', '', false, 'raw_data');
  793. if (is_subclass_of($sDashletClass, 'Dashlet'))
  794. {
  795. $oDashlet = new $sDashletClass(new ModelReflectionRuntime(), $sDashletId);
  796. $offset = $oPage->start_capture();
  797. $oDashlet->DoRender($oPage, true /* bEditMode */, false /* bEnclosingDiv */);
  798. $sHtml = addslashes($oPage->end_capture($offset));
  799. $sHtml = str_replace("\n", '', $sHtml);
  800. $sHtml = str_replace("\r", '', $sHtml);
  801. $oPage->add_script("$('#dashlet_$sDashletId').html('$sHtml');"); // in ajax web page add_script has the same effect as add_ready_script
  802. // but is executed BEFORE all 'ready_scripts'
  803. $oForm = $oDashlet->GetForm(); // Rebuild the form since the values/content changed
  804. $oForm->SetSubmitParams(utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php', array('operation' => 'update_dashlet_property'));
  805. $sHtml = addslashes($oForm->RenderAsPropertySheet($oPage, true /* bReturnHtml */, '.itop-dashboard'));
  806. $sHtml = str_replace("\n", '', $sHtml);
  807. $sHtml = str_replace("\r", '', $sHtml);
  808. $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'
  809. }
  810. break;
  811. case 'update_dashlet_property':
  812. require_once(APPROOT.'application/forms.class.inc.php');
  813. require_once(APPROOT.'application/dashlet.class.inc.php');
  814. $aParams = utils::ReadParam('params', '', false, 'raw_data');
  815. $sDashletClass = $aParams['attr_dashlet_class'];
  816. $sDashletId = $aParams['attr_dashlet_id'];
  817. $aUpdatedProperties = $aParams['updated']; // Code of the changed properties as an array: 'attr_xxx', 'attr_xxy', etc...
  818. $aPreviousValues = $aParams['previous_values']; // hash array: 'attr_xxx' => 'old_value'
  819. if (is_subclass_of($sDashletClass, 'Dashlet'))
  820. {
  821. $oDashlet = new $sDashletClass(new ModelReflectionRuntime(), $sDashletId);
  822. $oForm = $oDashlet->GetForm();
  823. $aValues = $oForm->ReadParams(); // hash array: 'xxx' => 'new_value'
  824. $aCurrentValues = $aValues;
  825. $aUpdatedDecoded = array();
  826. foreach($aUpdatedProperties as $sProp)
  827. {
  828. $sDecodedProp = str_replace('attr_', '', $sProp); // Remove the attr_ prefix
  829. $aCurrentValues[$sDecodedProp] = $aPreviousValues[$sProp]; // Set the previous value
  830. $aUpdatedDecoded[] = $sDecodedProp;
  831. }
  832. $oDashlet->FromParams($aCurrentValues);
  833. $sPrevClass = get_class($oDashlet);
  834. $oDashlet = $oDashlet->Update($aValues, $aUpdatedDecoded);
  835. $sNewClass = get_class($oDashlet);
  836. if ($sNewClass != $sPrevClass)
  837. {
  838. $oPage->add_ready_script("$('#dashlet_$sDashletId').dashlet('option', {dashlet_class: '$sNewClass'});");
  839. }
  840. if ($oDashlet->IsRedrawNeeded())
  841. {
  842. $offset = $oPage->start_capture();
  843. $oDashlet->DoRender($oPage, true /* bEditMode */, false /* bEnclosingDiv */);
  844. $sHtml = addslashes($oPage->end_capture($offset));
  845. $sHtml = str_replace("\n", '', $sHtml);
  846. $sHtml = str_replace("\r", '', $sHtml);
  847. $oPage->add_script("$('#dashlet_$sDashletId').html('$sHtml');"); // in ajax web page add_script has the same effect as add_ready_script
  848. // but is executed BEFORE all 'ready_scripts'
  849. }
  850. if ($oDashlet->IsFormRedrawNeeded())
  851. {
  852. $oForm = $oDashlet->GetForm(); // Rebuild the form since the values/content changed
  853. $oForm->SetSubmitParams(utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php', array('operation' => 'update_dashlet_property'));
  854. $sHtml = addslashes($oForm->RenderAsPropertySheet($oPage, true /* bReturnHtml */, '.itop-dashboard'));
  855. $sHtml = str_replace("\n", '', $sHtml);
  856. $sHtml = str_replace("\r", '', $sHtml);
  857. $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'
  858. // but is executed BEFORE all 'ready_scripts'
  859. }
  860. }
  861. break;
  862. case 'save_dashboard':
  863. $sDashboardId = utils::ReadParam('dashboard_id', '', false, 'raw_data');
  864. $aParams = array();
  865. $aParams['layout_class'] = utils::ReadParam('layout_class', '');
  866. $aParams['title'] = utils::ReadParam('title', '', false, 'raw_data');
  867. $aParams['auto_reload'] = utils::ReadParam('auto_reload', false);
  868. $aParams['auto_reload_sec'] = utils::ReadParam('auto_reload_sec', 300);
  869. $aParams['cells'] = utils::ReadParam('cells', array(), false, 'raw_data');
  870. $oDashboard = new RuntimeDashboard($sDashboardId);
  871. $oDashboard->FromParams($aParams);
  872. $oDashboard->Save();
  873. // trigger a reload of the current page since the dashboard just changed
  874. $oPage->add_ready_script(
  875. <<<EOF
  876. var sLocation = new String(window.location.href);
  877. var sNewLocation = sLocation.replace('&edit=1', '');
  878. 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
  879. window.location.href = sNewLocation;
  880. EOF
  881. );
  882. $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
  883. break;
  884. case 'revert_dashboard':
  885. $sDashboardId = utils::ReadParam('dashboard_id', '', false, 'raw_data');
  886. $oDashboard = new RuntimeDashboard($sDashboardId);
  887. $oDashboard->Revert();
  888. // trigger a reload of the current page since the dashboard just changed
  889. $oPage->add_ready_script("window.location.href=window.location.href;"); // reloads the page, doing a GET even if we arrived via a POST
  890. break;
  891. case 'render_dashboard':
  892. $sDashboardId = utils::ReadParam('dashboard_id', '', false, 'raw_data');
  893. $aParams = array();
  894. $aParams['layout_class'] = utils::ReadParam('layout_class', '');
  895. $aParams['title'] = utils::ReadParam('title', '', false, 'raw_data');
  896. $aParams['cells'] = utils::ReadParam('cells', array(), false, 'raw_data');
  897. $aParams['auto_reload'] = utils::ReadParam('auto_reload', false);
  898. $aParams['auto_reload_sec'] = utils::ReadParam('auto_reload_sec', 300);
  899. $oDashboard = new RuntimeDashboard($sDashboardId);
  900. $oDashboard->FromParams($aParams);
  901. $oDashboard->Render($oPage, true /* bEditMode */);
  902. break;
  903. case 'dashlet_creation_dlg':
  904. $sOQL = utils::ReadParam('oql', '', false, 'raw_data');
  905. RuntimeDashboard::GetDashletCreationDlgFromOQL($oPage, $sOQL);
  906. break;
  907. case 'add_dashlet':
  908. $oForm = RuntimeDashboard::GetDashletCreationForm();
  909. $aValues = $oForm->ReadParams();
  910. $sDashletClass = $aValues['dashlet_class'];
  911. $sMenuId = $aValues['menu_id'];
  912. if (is_subclass_of($sDashletClass, 'Dashlet'))
  913. {
  914. $oDashlet = new $sDashletClass(new ModelReflectionRuntime(), 0);
  915. $oDashlet->FromParams($aValues);
  916. ApplicationMenu::LoadAdditionalMenus();
  917. $index = ApplicationMenu::GetMenuIndexById($sMenuId);
  918. $oMenu = ApplicationMenu::GetMenuNode($index);
  919. $oMenu->AddDashlet($oDashlet);
  920. // navigate to the dashboard page
  921. if ($aValues['open_editor'])
  922. {
  923. $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
  924. }
  925. }
  926. break;
  927. case 'shortcut_list_dlg':
  928. $sOQL = utils::ReadParam('oql', '', false, 'raw_data');
  929. $sTableSettings = utils::ReadParam('table_settings', '', false, 'raw_data');
  930. ShortcutOQL::GetCreationDlgFromOQL($oPage, $sOQL, $sTableSettings);
  931. break;
  932. case 'shortcut_list_create':
  933. $oForm = ShortcutOQL::GetCreationForm();
  934. $aValues = $oForm->ReadParams();
  935. $oAppContext = new ApplicationContext();
  936. $aContext = $oAppContext->GetAsHash();
  937. $sContext = serialize($aContext);
  938. $oShortcut = MetaModel::NewObject("ShortcutOQL");
  939. $oShortcut->Set('user_id', UserRights::GetUserId());
  940. $oShortcut->Set("context", $sContext);
  941. $oShortcut->Set("name", $aValues['name']);
  942. $oShortcut->Set("oql", $aValues['oql']);
  943. $iAutoReload = (int)$aValues['auto_reload_sec'];
  944. if (($aValues['auto_reload']) && ($iAutoReload > 0))
  945. {
  946. $oShortcut->Set("auto_reload_sec", max(MetaModel::GetConfig()->Get('min_reload_interval'), $iAutoReload));
  947. $oShortcut->Set("auto_reload", 'custom');
  948. }
  949. $iId = $oShortcut->DBInsertNoReload();
  950. $oShortcut->CloneTableSettings($aValues['table_settings']);
  951. // Add the menu node in the right place
  952. //
  953. // Mmmm... already done because the newly created menu is read from the DB
  954. // as soon as we invoke DisplayMenu
  955. // Refresh the menu pane
  956. $aExtraParams = array();
  957. ApplicationMenu::DisplayMenu($oPage, $aExtraParams);
  958. break;
  959. case 'shortcut_rename_dlg':
  960. $oSearch = new DBObjectSearch('Shortcut');
  961. $aShortcuts = utils::ReadMultipleSelection($oSearch);
  962. $iShortcut = $aShortcuts[0];
  963. $oShortcut = MetaModel::GetObject('Shortcut', $iShortcut);
  964. $oShortcut->StartRenameDialog($oPage);
  965. break;
  966. case 'shortcut_rename_go':
  967. $iShortcut = utils::ReadParam('id', 0);
  968. $oShortcut = MetaModel::GetObject('Shortcut', $iShortcut);
  969. $sName = utils::ReadParam('attr_name', '', false, 'raw_data');
  970. if (strlen($sName) > 0)
  971. {
  972. $oShortcut->Set('name', $sName);
  973. $oShortcut->DBUpdate();
  974. $oPage->add_ready_script('window.location.reload();');
  975. }
  976. break;
  977. case 'shortcut_delete_go':
  978. $oSearch = new DBObjectSearch('Shortcut');
  979. $oSearch->AddCondition('user_id', UserRights::GetUserId(), '=');
  980. $aShortcuts = utils::ReadMultipleSelection($oSearch);
  981. foreach ($aShortcuts as $iShortcut)
  982. {
  983. $oShortcut = MetaModel::GetObject('Shortcut', $iShortcut);
  984. $oShortcut->DBDelete();
  985. $oPage->add_ready_script('window.location.reload();');
  986. }
  987. break;
  988. case 'export_dashboard':
  989. $sMenuId = utils::ReadParam('id', '', false, 'raw_data');
  990. ApplicationMenu::LoadAdditionalMenus();
  991. $index = ApplicationMenu::GetMenuIndexById($sMenuId);
  992. $oMenu = ApplicationMenu::GetMenuNode($index);
  993. if ($oMenu instanceof DashboardMenuNode)
  994. {
  995. $oDashboard = $oMenu->GetDashboard();
  996. $oPage->TrashUnexpectedOutput();
  997. $oPage->SetContentType('text/xml');
  998. $oPage->SetContentDisposition('attachment', $oMenu->GetLabel().'.xml');
  999. $oPage->add($oDashboard->ToXml());
  1000. }
  1001. break;
  1002. case 'import_dashboard':
  1003. $sMenuId = utils::ReadParam('id', '', false, 'raw_data');
  1004. ApplicationMenu::LoadAdditionalMenus();
  1005. $index = ApplicationMenu::GetMenuIndexById($sMenuId);
  1006. $oMenu = ApplicationMenu::GetMenuNode($index);
  1007. $aResult = array('error' => '');
  1008. try
  1009. {
  1010. if ($oMenu instanceof DashboardMenuNode)
  1011. {
  1012. $oDoc = utils::ReadPostedDocument('dashboard_upload_file');
  1013. $oDashboard = $oMenu->GetDashboard();
  1014. $oDashboard->FromXml($oDoc->GetData());
  1015. $oDashboard->Save();
  1016. }
  1017. else
  1018. {
  1019. $aResult['error'] = 'Dashboard id="'.$sMenuId.'" not found.';
  1020. }
  1021. }
  1022. catch(DOMException $e)
  1023. {
  1024. $aResult = array('error' => Dict::S('UI:Error:InvalidDashboardFile'));
  1025. }
  1026. catch(Exception $e)
  1027. {
  1028. $aResult = array('error' => $e->getMessage());
  1029. }
  1030. $oPage->add(json_encode($aResult));
  1031. break;
  1032. case 'about_box':
  1033. $oPage->SetContentType('text/html');
  1034. $sDialogTitle = addslashes(Dict::S('UI:About:Title'));
  1035. $oPage->add_ready_script(
  1036. <<<EOF
  1037. $('#about_box').dialog({
  1038. width: 700,
  1039. modal: true,
  1040. title: '$sDialogTitle',
  1041. close: function() { $(this).remove(); }
  1042. });
  1043. $("#collapse_support_details").click(function() {
  1044. $("#support_details").slideToggle('normal');
  1045. $("#collapse_support_details").toggleClass('open');
  1046. });
  1047. $('#support_details').toggle();
  1048. EOF
  1049. );
  1050. $sVersionString = Dict::Format('UI:iTopVersion:Long', ITOP_VERSION, ITOP_REVISION, ITOP_BUILD_DATE);
  1051. $sMySQLVersion = CMDBSource::GetDBVersion();
  1052. $sPHPVersion = phpversion();
  1053. $sOSVersion = PHP_OS;
  1054. $sWebServerVersion = $_SERVER["SERVER_SOFTWARE"];
  1055. $sModules = implode(', ', get_loaded_extensions());
  1056. // Get the datamodel directory
  1057. $oFilter = DBObjectSearch::FromOQL('SELECT ModuleInstallation WHERE name="datamodel"');
  1058. $oSet = new DBObjectSet($oFilter, array('installed' => false)); // Most recent first
  1059. $oLastInstall = $oSet->Fetch();
  1060. $sLastInstallDate = $oLastInstall->Get('installed');
  1061. $sDataModelVersion = $oLastInstall->Get('version');
  1062. $aDataModelInfo = json_decode($oLastInstall->Get('comment'), true);
  1063. $sDataModelSourceDir = $aDataModelInfo['source_dir'];
  1064. require_once(APPROOT.'setup/runtimeenv.class.inc.php');
  1065. $sCurrEnv = utils::GetCurrentEnvironment();
  1066. $oRuntimeEnv = new RunTimeEnvironment($sCurrEnv);
  1067. $aSearchDirs = array(APPROOT.$sDataModelSourceDir);
  1068. if (file_exists(APPROOT.'extensions'))
  1069. {
  1070. $aSearchDirs[] = APPROOT.'extensions';
  1071. }
  1072. $sExtraDir = APPROOT.'data/'.$sCurrEnv.'-modules/';
  1073. if (file_exists($sExtraDir))
  1074. {
  1075. $aSearchDirs[] = $sExtraDir;
  1076. }
  1077. $aAvailableModules = $oRuntimeEnv->AnalyzeInstallation(MetaModel::GetConfig(), $aSearchDirs);
  1078. require_once(APPROOT.'setup/setuputils.class.inc.php');
  1079. $aLicenses = SetupUtils::GetLicenses();
  1080. $aItopSettings = array('cron_max_execution_time', 'timezone');
  1081. $aPHPSettings = array('memory_limit', 'max_execution_time', 'upload_max_filesize', 'post_max_size');
  1082. $aMySQLSettings = array('max_allowed_packet', 'key_buffer_size', 'query_cache_size');
  1083. $aMySQLStatuses = array('Key_read_requests', 'Key_reads');
  1084. if (extension_loaded('suhosin'))
  1085. {
  1086. $aPHPSettings[] = 'suhosin.post.max_vars';
  1087. $aPHPSettings[] = 'suhosin.get.max_value_length';
  1088. }
  1089. $aMySQLVars = array();
  1090. foreach (CMDBSource::QueryToArray('SHOW VARIABLES') as $aRow)
  1091. {
  1092. $aMySQLVars[$aRow['Variable_name']] = $aRow['Value'];
  1093. }
  1094. $aMySQLStats = array();
  1095. foreach (CMDBSource::QueryToArray('SHOW GLOBAL STATUS') as $aRow)
  1096. {
  1097. $aMySQLStats[$aRow['Variable_name']] = $aRow['Value'];
  1098. }
  1099. // Display
  1100. //
  1101. $oPage->add("<div id=\"about_box\">");
  1102. $oPage->add('<div style="margin-left: 120px;">');
  1103. $oPage->add('<table>');
  1104. $oPage->add('<tr>');
  1105. $oPage->add('<td><a href="http://www.combodo.com" title="www.combodo.com" target="_blank" style="background: none;"><img src="../images/logo-combodo.png" style="float: right;"/></a></td>');
  1106. $oPage->add('<td style="padding-left: 20px;">');
  1107. $oPage->add($sVersionString.'<br/>');
  1108. $oPage->add(Dict::S('UI:About:DataModel').': '.$sDataModelVersion.'<br/>');
  1109. $oPage->add('MySQL: '.$sMySQLVersion.'<br/>');
  1110. $oPage->add('PHP: '.$sPHPVersion.'<br/>');
  1111. $oPage->add('</td>');
  1112. $oPage->add('</tr>');
  1113. $oPage->add('</table>');
  1114. $oPage->add("</div>");
  1115. $oPage->add("<div>");
  1116. $oPage->add('<fieldset>');
  1117. $oPage->add('<legend>'.Dict::S('UI:About:Licenses').'</legend>');
  1118. $oPage->add('<ul style="margin: 0; font-size: smaller;">');
  1119. foreach($aLicenses as $index => $oLicense)
  1120. {
  1121. $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>)');
  1122. $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>');
  1123. $oPage->add_ready_script('$("#toggle_'.$index.'").click( function() { $("#license_'.$index.'").slideToggle("normal"); } );');
  1124. }
  1125. $oPage->add('</ul>');
  1126. $oPage->add('</fieldset>');
  1127. $oPage->add("</div>");
  1128. $oPage->add('<fieldset>');
  1129. $oPage->add('<legend>'.Dict::S('UI:About:Modules').'</legend>');
  1130. //$oPage->add(print_r($aAvailableModules, true));
  1131. $oPage->add("<div style=\"height: 150px; overflow: auto; font-size: smaller;\">");
  1132. $oPage->add('<ul style="margin: 0;">');
  1133. foreach ($aAvailableModules as $sModuleId => $aModuleData)
  1134. {
  1135. if ($sModuleId == '_Root_') continue;
  1136. if (!$aModuleData['visible']) continue;
  1137. if ($aModuleData['version_db'] == '') continue;
  1138. $oPage->add('<li>'.$aModuleData['label'].' ('.$aModuleData['version_db'].')</li>');
  1139. }
  1140. $oPage->add('</ul>');
  1141. $oPage->add("</div>");
  1142. $oPage->add('</fieldset>');
  1143. // MUST NOT be localized, as the information given here will be sent to the support
  1144. $oPage->add("<a id=\"collapse_support_details\" class=\"CollapsibleLabel\" href=\"#\">".Dict::S('UI:About:Support')."</a></br>\n");
  1145. $oPage->add("<div id=\"support_details\">");
  1146. $oPage->add('<textarea readonly style="width: 660px; height: 150px; font-size: smaller;">');
  1147. $oPage->add("===== begin =====\n");
  1148. $oPage->add('iTopVersion: '.ITOP_VERSION."\n");
  1149. $oPage->add('iTopBuild: '.ITOP_REVISION."\n");
  1150. $oPage->add('iTopBuildDate: '.ITOP_BUILD_DATE."\n");
  1151. $oPage->add('DataModelVersion: '.$sDataModelVersion."\n");
  1152. $oPage->add('MySQLVersion: '.$sMySQLVersion."\n");
  1153. $oPage->add('PHPVersion: '. $sPHPVersion."\n");
  1154. $oPage->add('OSVersion: '.$sOSVersion."\n");
  1155. $oPage->add('WebServerVersion: '.$sWebServerVersion."\n");
  1156. $oPage->add('PHPModules: '.$sModules."\n");
  1157. foreach ($aItopSettings as $siTopVar)
  1158. {
  1159. $oPage->add('ItopSetting/'.$siTopVar.': '.MetaModel::GetConfig()->Get($siTopVar)."\n");
  1160. }
  1161. foreach ($aPHPSettings as $sPHPVar)
  1162. {
  1163. $oPage->add('PHPSetting/'.$sPHPVar.': '.ini_get($sPHPVar)."\n");
  1164. }
  1165. foreach ($aMySQLSettings as $sMySQLVar)
  1166. {
  1167. $oPage->add('MySQLSetting/'.$sMySQLVar.': '.$aMySQLVars[$sMySQLVar]."\n");
  1168. }
  1169. foreach ($aMySQLStatuses as $sMySQLStatus)
  1170. {
  1171. $oPage->add('MySQLStatus/'.$sMySQLStatus.': '.$aMySQLStats[$sMySQLStatus]."\n");
  1172. }
  1173. $oPage->add('InstallDate: '.$sLastInstallDate."\n");
  1174. $oPage->add('InstallPath: '.APPROOT."\n");
  1175. foreach ($aAvailableModules as $sModuleId => $aModuleData)
  1176. {
  1177. if ($sModuleId == '_Root_') continue;
  1178. if ($aModuleData['version_db'] == '') continue;
  1179. $oPage->add('InstalledModule/'.$sModuleId.': '.$aModuleData['version_db']."\n");
  1180. }
  1181. $oPage->add('===== end =====');
  1182. $oPage->add('</textarea>');
  1183. $oPage->add("</div>");
  1184. $oPage->add("</div>");
  1185. break;
  1186. case 'history':
  1187. $oPage->SetContentType('text/html');
  1188. $id = (int)utils::ReadParam('id', 0);
  1189. $iStart = (int)utils::ReadParam('start', 0);
  1190. $iCount = (int)utils::ReadParam('count', MetaModel::GetConfig()->Get('max_history_length', '50'));
  1191. $oObj = MetaModel::GetObject($sClass, $id);
  1192. $oObj->DisplayBareHistory($oPage, false, $iCount, $iStart);
  1193. $oPage->add_ready_script("$('#history table.listResults').tableHover(); $('#history table.listResults').tablesorter( { widgets: ['myZebra', 'truncatedList']} );");
  1194. break;
  1195. case 'history_from_filter':
  1196. $oPage->SetContentType('text/html');
  1197. $oHistoryFilter = CMDBSearchFilter::unserialize($sFilter);
  1198. $iStart = (int)utils::ReadParam('start', 0);
  1199. $iCount = (int)utils::ReadParam('count', MetaModel::GetConfig()->Get('max_history_length', '50'));
  1200. $oBlock = new HistoryBlock($oHistoryFilter, 'table', false);
  1201. $oBlock->SetLimit($iCount, $iStart);
  1202. $oBlock->Display($oPage, 'history');
  1203. $oPage->add_ready_script("$('#history table.listResults').tableHover(); $('#history table.listResults').tablesorter( { widgets: ['myZebra', 'truncatedList']} );");
  1204. break;
  1205. case 'full_text_search':
  1206. $aFullTextNeedles = utils::ReadParam('needles', array(), false, 'raw_data');
  1207. $sFullText = trim(implode(' ', $aFullTextNeedles));
  1208. $sClassName = utils::ReadParam('class', '');
  1209. $iCount = utils::ReadParam('count', 0);
  1210. $iCurrentPos = utils::ReadParam('position', 0);
  1211. $iTune = utils::ReadParam('tune', 0);
  1212. if (empty($sFullText))
  1213. {
  1214. $oPage->p(Dict::S('UI:Search:NoSearch'));
  1215. break;
  1216. }
  1217. // Search in full text mode in all the classes
  1218. $aMatches = array();
  1219. // Build the ordered list of classes to search into
  1220. //
  1221. if (empty($sClassName))
  1222. {
  1223. $aSearchClasses = MetaModel::GetClasses('searchable');
  1224. }
  1225. else
  1226. {
  1227. // Search is limited to a given class and its subclasses
  1228. $aSearchClasses = MetaModel::EnumChildClasses($sClassName, ENUM_CHILD_CLASSES_ALL);
  1229. }
  1230. // Skip abstract classes, since we search in all the child classes anyway
  1231. foreach($aSearchClasses as $idx => $sClass)
  1232. {
  1233. if (MetaModel::IsAbstract($sClass))
  1234. {
  1235. unset($aSearchClasses[$idx]);
  1236. }
  1237. }
  1238. $sMaxChunkDuration = MetaModel::GetConfig()->Get('full_text_chunk_duration');
  1239. $aAccelerators = MetaModel::GetConfig()->Get('full_text_accelerators');
  1240. foreach (array_reverse($aAccelerators) as $sClass => $aRestriction)
  1241. {
  1242. $bSkip = false;
  1243. $iPos = array_search($sClass, $aSearchClasses);
  1244. if ($iPos !== false)
  1245. {
  1246. unset($aSearchClasses[$iPos]);
  1247. }
  1248. else
  1249. {
  1250. $bSkip = true;
  1251. }
  1252. $bSkip |= array_key_exists('skip', $aRestriction) ? $aRestriction['skip'] : false ;
  1253. if (!in_array($sClass, $aSearchClasses))
  1254. if ($sClass == $sClassName)
  1255. {
  1256. // Class explicitely requested, do NOT skip it
  1257. // beware: there may not be a 'query' defined for a skipped class !
  1258. $bSkip = false;
  1259. }
  1260. if (!$bSkip)
  1261. {
  1262. // NOT skipped, add the class to the list of classes to search into
  1263. if (array_key_exists('query', $aRestriction))
  1264. {
  1265. array_unshift($aSearchClasses, $aRestriction['query']);
  1266. }
  1267. else
  1268. {
  1269. // No accelerator query
  1270. array_unshift($aSearchClasses, $sClassName);
  1271. }
  1272. }
  1273. }
  1274. $aSearchClasses = array_values($aSearchClasses); // renumbers the array starting from zero, removing the missing indexes
  1275. $fStarted = microtime(true);
  1276. $iFoundInThisRound = 0;
  1277. for($iPos = $iCurrentPos; $iPos < count($aSearchClasses) ; $iPos++)
  1278. {
  1279. if ($iFoundInThisRound && (microtime(true) - $fStarted >= $sMaxChunkDuration))
  1280. {
  1281. break;
  1282. }
  1283. $sClassSpec = $aSearchClasses[$iPos];
  1284. if (substr($sClassSpec, 0, 7) == 'SELECT ')
  1285. {
  1286. $oFilter = DBObjectSearch::FromOQL($sClassSpec);
  1287. $sClassName = $oFilter->GetClass();
  1288. $sNeedleFormat = isset($aAccelerators[$sClassName]['needle']) ? $aAccelerators[$sClassName]['needle'] : '%$needle$%';
  1289. $sNeedle = str_replace('$needle$', $sFullText, $sNeedleFormat);
  1290. $aParams = array('needle' => $sNeedle);
  1291. }
  1292. else
  1293. {
  1294. $sClassName = $sClassSpec;
  1295. $oFilter = new DBObjectSearch($sClassName);
  1296. $aParams = array();
  1297. foreach($aFullTextNeedles as $sSearchText)
  1298. {
  1299. $oFilter->AddCondition_FullText($sSearchText);
  1300. }
  1301. }
  1302. // Skip abstract classes
  1303. if (MetaModel::IsAbstract($sClassName)) continue;
  1304. if ($iTune > 0)
  1305. {
  1306. $fStartedClass = microtime(true);
  1307. }
  1308. $oSet = new DBObjectSet($oFilter, array(), $aParams);
  1309. if (array_key_exists($sClassName, $aAccelerators) && array_key_exists('attributes', $aAccelerators[$sClassName]))
  1310. {
  1311. $oSet->OptimizeColumnLoad(array($oFilter->GetClassAlias() => $aAccelerators[$sClassName]['attributes']));
  1312. }
  1313. $sFullTextJS = addslashes($sFullText);
  1314. $bEnableEnlarge = array_key_exists($sClassName, $aAccelerators) && array_key_exists('query', $aAccelerators[$sClassName]);
  1315. if (array_key_exists($sClassName, $aAccelerators) && array_key_exists('enable_enlarge', $aAccelerators[$sClassName]))
  1316. {
  1317. $bEnableEnlarge &= $aAccelerators[$sClassName]['enable_enlarge'];
  1318. }
  1319. $sEnlargeTheSearch =
  1320. <<<EOF
  1321. $('.search-class-$sClassName button').attr('disabled', 'disabled');
  1322. $('.search-class-$sClassName h2').append('&nbsp;<img id="indicator" src="../images/indicator.gif">');
  1323. var oParams = {operation: 'full_text_search_enlarge', class: '$sClassName', text: '$sFullTextJS'};
  1324. $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', oParams, function(data) {
  1325. $('.search-class-$sClassName').html(data);
  1326. });
  1327. EOF
  1328. ;
  1329. $sEnlargeButton = '';
  1330. if ($bEnableEnlarge)
  1331. {
  1332. $sEnlargeButton = "&nbsp;<button onclick=\"".htmlentities($sEnlargeTheSearch, ENT_QUOTES, 'UTF-8')."\">".Dict::S('UI:Search:Enlarge')."</button>";
  1333. }
  1334. if ($oSet->Count() > 0)
  1335. {
  1336. $aLeafs = array();
  1337. while($oObj = $oSet->Fetch())
  1338. {
  1339. if (get_class($oObj) == $sClassName)
  1340. {
  1341. $aLeafs[] = $oObj->GetKey();
  1342. $iFoundInThisRound ++;
  1343. }
  1344. }
  1345. $oLeafsFilter = new DBObjectSearch($sClassName);
  1346. if (count($aLeafs) > 0)
  1347. {
  1348. $iCount += count($aLeafs);
  1349. $oPage->add("<div class=\"search-class-result search-class-$sClassName\">\n");
  1350. $oPage->add("<div class=\"page_header\">\n");
  1351. if (array_key_exists($sClassName, $aAccelerators))
  1352. {
  1353. $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");
  1354. }
  1355. else
  1356. {
  1357. $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");
  1358. }
  1359. $oPage->add("</div>\n");
  1360. $oLeafsFilter->AddCondition('id', $aLeafs, 'IN');
  1361. $oBlock = new DisplayBlock($oLeafsFilter, 'list', false);
  1362. $sBlockId = 'global_search_'.$sClassName;
  1363. $oPage->add('<div id="'.$sBlockId.'">');
  1364. $oBlock->RenderContent($oPage, array('table_id' => $sBlockId, 'currentId' => $sBlockId));
  1365. $oPage->add("</div>\n");
  1366. $oPage->add("</div>\n");
  1367. $oPage->p('&nbsp;'); // Some space ?
  1368. }
  1369. }
  1370. else if (array_key_exists($sClassName, $aAccelerators))
  1371. {
  1372. $oPage->add("<div class=\"search-class-result search-class-$sClassName\">\n");
  1373. $oPage->add("<div class=\"page_header\">\n");
  1374. $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");
  1375. $oPage->add("</div>\n");
  1376. $oPage->add("</div>\n");
  1377. $oPage->p('&nbsp;'); // Some space ?
  1378. }
  1379. if ($iTune > 0)
  1380. {
  1381. $fDurationClass = microtime(true) - $fStartedClass;
  1382. $oPage->add_script("oTimeStatistics.$sClassName = $fDurationClass;");
  1383. }
  1384. }
  1385. if ($iPos < count($aSearchClasses))
  1386. {
  1387. $sJSNeedle = json_encode($aFullTextNeedles);
  1388. $oPage->add_ready_script(
  1389. <<<EOF
  1390. var oParams = {operation: 'full_text_search', position: $iPos, needles: $sJSNeedle, count: $iCount, tune: $iTune};
  1391. $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', oParams, function(data) {
  1392. $('#full_text_results').append(data);
  1393. });
  1394. EOF
  1395. );
  1396. }
  1397. else
  1398. {
  1399. // We're done
  1400. $oPage->add_ready_script(
  1401. <<<EOF
  1402. $('#full_text_indicator').hide();
  1403. $('#full_text_progress,#full_text_progress_placeholder').hide(500);
  1404. EOF
  1405. );
  1406. if ($iTune > 0)
  1407. {
  1408. $oPage->add_ready_script(
  1409. <<<EOF
  1410. var sRes = '<h4>Search statistics (tune = 1)</h4><table>';
  1411. sRes += '<thead><tr><th>Class</th><th>Time</th></tr></thead>';
  1412. sRes += '<tbody>';
  1413. var fTotal = 0;
  1414. for (var sClass in oTimeStatistics)
  1415. {
  1416. fTotal = fTotal + oTimeStatistics[sClass];
  1417. fRounded = Math.round(oTimeStatistics[sClass] * 1000) / 1000;
  1418. sRes += '<tr><td>' + sClass + '</td><td>' + fRounded + '</td></tr>';
  1419. }
  1420. fRoundedTotal = Math.round(fTotal * 1000) / 1000;
  1421. sRes += '<tr><td><b>Total</b></td><td><b>' + fRoundedTotal + '</b></td></tr>';
  1422. sRes += '</tbody>';
  1423. sRes += '</table>';
  1424. $('#full_text_results').append(sRes);
  1425. EOF
  1426. );
  1427. }
  1428. if ($iCount == 0)
  1429. {
  1430. $sFullTextSummary = addslashes(Dict::S('UI:Search:NoObjectFound'));
  1431. $oPage->add_ready_script("$('#full_text_results').append('<div id=\"no_object_found\">$sFullTextSummary</div>');");
  1432. }
  1433. }
  1434. break;
  1435. case 'full_text_search_enlarge':
  1436. $sFullText = trim(utils::ReadParam('text', '', false, 'raw_data'));
  1437. $sClass = trim(utils::ReadParam('class', ''));
  1438. $iTune = utils::ReadParam('tune', 0);
  1439. if (preg_match('/^"(.*)"$/', $sFullText, $aMatches))
  1440. {
  1441. // The text is surrounded by double-quotes, remove the quotes and treat it as one single expression
  1442. $aFullTextNeedles = array($aMatches[1]);
  1443. }
  1444. else
  1445. {
  1446. // Split the text on the blanks and treat this as a search for <word1> AND <word2> AND <word3>
  1447. $aFullTextNeedles = explode(' ', $sFullText);
  1448. }
  1449. $oFilter = new DBObjectSearch($sClass);
  1450. foreach($aFullTextNeedles as $sSearchText)
  1451. {
  1452. $oFilter->AddCondition_FullText($sSearchText);
  1453. }
  1454. $oSet = new DBObjectSet($oFilter);
  1455. $oPage->add("<div class=\"page_header\">\n");
  1456. $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");
  1457. $oPage->add("</div>\n");
  1458. if ($oSet->Count() > 0)
  1459. {
  1460. $aLeafs = array();
  1461. while($oObj = $oSet->Fetch())
  1462. {
  1463. if (get_class($oObj) == $sClass)
  1464. {
  1465. $aLeafs[] = $oObj->GetKey();
  1466. }
  1467. }
  1468. $oLeafsFilter = new DBObjectSearch($sClass);
  1469. if (count($aLeafs) > 0)
  1470. {
  1471. $oLeafsFilter->AddCondition('id', $aLeafs, 'IN');
  1472. $oBlock = new DisplayBlock($oLeafsFilter, 'list', false);
  1473. $sBlockId = 'global_search_'.$sClass;
  1474. $oPage->add('<div id="'.$sBlockId.'">');
  1475. $oBlock->RenderContent($oPage, array('table_id' => $sBlockId, 'currentId' => $sBlockId));
  1476. $oPage->add('</div>');
  1477. $oPage->P('&nbsp;'); // Some space ?
  1478. // Hide "no object found"
  1479. $oPage->add_ready_script('$("#no_object_found").hide();');
  1480. }
  1481. }
  1482. $oPage->add_ready_script(
  1483. <<<EOF
  1484. $('#full_text_indicator').hide();
  1485. $('#full_text_progress,#full_text_progress_placeholder').hide(500);
  1486. EOF
  1487. );
  1488. break;
  1489. case 'xlsx_export_dialog':
  1490. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  1491. $oPage->SetContentType('text/html');
  1492. $oPage->add(
  1493. <<<EOF
  1494. <style>
  1495. .ui-progressbar {
  1496. position: relative;
  1497. }
  1498. .progress-label {
  1499. position: absolute;
  1500. left: 50%;
  1501. top: 1px;
  1502. font-size: 11pt;
  1503. }
  1504. .download-form button {
  1505. display:block;
  1506. margin-left: auto;
  1507. margin-right: auto;
  1508. margin-top: 2em;
  1509. }
  1510. .ui-progressbar-value {
  1511. background: url(../setup/orange-progress.gif);
  1512. }
  1513. .progress-bar {
  1514. height: 20px;
  1515. }
  1516. .statistics > div {
  1517. padding-left: 16px;
  1518. cursor: pointer;
  1519. font-size: 10pt;
  1520. background: url(../images/minus.gif) 0 2px no-repeat;
  1521. }
  1522. .statistics > div.closed {
  1523. padding-left: 16px;
  1524. background: url(../images/plus.gif) 0 2px no-repeat;
  1525. }
  1526. .statistics .closed .stats-data {
  1527. display: none;
  1528. }
  1529. .stats-data td {
  1530. padding-right: 5px;
  1531. }
  1532. </style>
  1533. EOF
  1534. );
  1535. $oPage->add('<div id="XlsxExportDlg">');
  1536. $oPage->add('<div class="export-options">');
  1537. $oPage->add('<p><input type="checkbox" id="export-advanced-mode"/>&nbsp;<label for="export-advanced-mode">'.Dict::S('UI:CSVImport:AdvancedMode').'</label></p>');
  1538. $oPage->add('<p style="font-size:10pt;margin-left:2em;margin-top:-0.5em;padding-bottom:1em;">'.Dict::S('UI:CSVImport:AdvancedMode+').'</p>');
  1539. $oPage->add('<p><input type="checkbox" id="export-auto-download" checked="checked"/>&nbsp;<label for="export-auto-download">'.Dict::S('ExcelExport:AutoDownload').'</label></p>');
  1540. $oPage->add('</div>');
  1541. $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>');
  1542. $oPage->add('<div class="statistics"><div class="stats-toggle closed">'.Dict::S('ExcelExport:Statistics').'<div class="stats-data"></div></div></div>');
  1543. $oPage->add('</div>');
  1544. $aLabels = array(
  1545. 'dialog_title' => Dict::S('ExcelExporter:ExportDialogTitle'),
  1546. 'cancel_button' => Dict::S('UI:Button:Cancel'),
  1547. 'export_button' => Dict::S('ExcelExporter:ExportButton'),
  1548. 'download_button' => Dict::Format('ExcelExporter:DownloadButton', 'export.xlsx'), //TODO: better name for the file (based on the class of the filter??)
  1549. );
  1550. $sJSLabels = json_encode($aLabels);
  1551. $sFilter = addslashes($sFilter);
  1552. $sJSPageUrl = addslashes(utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php');
  1553. $oPage->add_ready_script("$('#XlsxExportDlg').xlsxexporter({filter: '$sFilter', labels: $sJSLabels, ajax_page_url: '$sJSPageUrl'});");
  1554. break;
  1555. case 'xlsx_start':
  1556. $sFilter = utils::ReadParam('filter', '', false, 'raw_data');
  1557. $bAdvanced = (utils::ReadParam('advanced', 'false') == 'true');
  1558. $oSearch = DBObjectSearch::unserialize($sFilter);
  1559. $oExcelExporter = new ExcelExporter();
  1560. $oExcelExporter->SetObjectList($oSearch);
  1561. //$oExcelExporter->SetChunkSize(10); //Only for testing
  1562. $oExcelExporter->SetAdvancedMode($bAdvanced);
  1563. $sToken = $oExcelExporter->SaveState();
  1564. $oPage->add(json_encode(array('status' => 'ok', 'token' => $sToken)));
  1565. break;
  1566. case 'xlsx_run':
  1567. $sMemoryLimit = MetaModel::GetConfig()->Get('xlsx_exporter_memory_limit');
  1568. ini_set('memory_limit', $sMemoryLimit);
  1569. ini_set('max_execution_time', max(300, ini_get('max_execution_time'))); // At least 5 minutes
  1570. $sToken = utils::ReadParam('token', '', false, 'raw_data');
  1571. $oExcelExporter = new ExcelExporter($sToken);
  1572. $aStatus = $oExcelExporter->Run();
  1573. $aResults = array('status' => $aStatus['code'], 'percentage' => $aStatus['percentage'], 'message' => $aStatus['message']);
  1574. if ($aStatus['code'] == 'done')
  1575. {
  1576. $aResults['statistics'] = $oExcelExporter->GetStatistics('html');
  1577. }
  1578. $oPage->add(json_encode($aResults));
  1579. break;
  1580. case 'xlsx_download':
  1581. $sToken = utils::ReadParam('token', '', false, 'raw_data');
  1582. $oPage->SetContentType('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  1583. $oPage->SetContentDisposition('attachment', 'export.xlsx');
  1584. $sFileContent = ExcelExporter::GetExcelFileFromToken($sToken);
  1585. $oPage->add($sFileContent);
  1586. ExcelExporter::CleanupFromToken($sToken);
  1587. break;
  1588. case 'xlsx_abort':
  1589. // Stop & cleanup an export...
  1590. $sToken = utils::ReadParam('token', '', false, 'raw_data');
  1591. ExcelExporter::CleanupFromToken($sToken);
  1592. break;
  1593. default:
  1594. $oPage->p("Invalid query.");
  1595. }
  1596. $oPage->output();
  1597. }
  1598. catch (Exception $e)
  1599. {
  1600. // note: transform to cope with XSS attacks
  1601. echo htmlentities($e->GetMessage(), ENT_QUOTES, 'utf-8');
  1602. echo "<p>Debug trace: <pre>".$e->getTraceAsString()."</pre></p>\n";
  1603. IssueLog::Error($e->getMessage());
  1604. }
  1605. /**
  1606. * Downloads a document to the browser, either as 'inline' or 'attachment'
  1607. *
  1608. * @param WebPage $oPage The web page for the output
  1609. * @param string $sClass Class name of the object
  1610. * @param mixed $id Identifier of the object
  1611. * @param string $sAttCode Name of the attribute containing the document to download
  1612. * @param string $sContentDisposition Either 'inline' or 'attachment'
  1613. * @return none
  1614. */
  1615. function DownloadDocument(WebPage $oPage, $sClass, $id, $sAttCode, $sContentDisposition = 'attachment')
  1616. {
  1617. try
  1618. {
  1619. $oObj = MetaModel::GetObject($sClass, $id, false, false);
  1620. if (!is_object($oObj))
  1621. {
  1622. throw new Exception("Invalid id ($id) for class '$sClass' - the object does not exist or you are not allowed to view it");
  1623. }
  1624. $oDocument = $oObj->Get($sAttCode);
  1625. if (is_object($oDocument))
  1626. {
  1627. $oPage->TrashUnexpectedOutput();
  1628. $oPage->SetContentType($oDocument->GetMimeType());
  1629. $oPage->SetContentDisposition($sContentDisposition,$oDocument->GetFileName());
  1630. $oPage->add($oDocument->GetData());
  1631. }
  1632. }
  1633. catch(Exception $e)
  1634. {
  1635. $oPage->p($e->getMessage());
  1636. }
  1637. }
  1638. ?>