ajax.render.php 91 KB

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