cmdbabstract.class.inc.php 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * Abstract class that implements some common and useful methods for displaying
  18. * the objects
  19. *
  20. * @author Erwan Taloc <erwan.taloc@combodo.com>
  21. * @author Romain Quetiez <romain.quetiez@combodo.com>
  22. * @author Denis Flaven <denis.flaven@combodo.com>
  23. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  24. */
  25. define('OBJECT_PROPERTIES_TAB', 'ObjectProperties');
  26. define('HILIGHT_CLASS_CRITICAL', 'red');
  27. define('HILIGHT_CLASS_WARNING', 'orange');
  28. define('HILIGHT_CLASS_OK', 'green');
  29. define('HILIGHT_CLASS_NONE', '');
  30. require_once(APPROOT.'/core/cmdbobject.class.inc.php');
  31. require_once(APPROOT.'/application/applicationextension.inc.php');
  32. require_once(APPROOT.'/application/utils.inc.php');
  33. require_once(APPROOT.'/application/applicationcontext.class.inc.php');
  34. require_once(APPROOT.'/application/ui.linkswidget.class.inc.php');
  35. require_once(APPROOT.'/application/ui.linksdirectwidget.class.inc.php');
  36. require_once(APPROOT.'/application/ui.passwordwidget.class.inc.php');
  37. require_once(APPROOT.'/application/ui.extkeywidget.class.inc.php');
  38. require_once(APPROOT.'/application/ui.htmleditorwidget.class.inc.php');
  39. require_once(APPROOT.'/application/datatable.class.inc.php');
  40. /**
  41. * All objects to be displayed in the application (either as a list or as details)
  42. * must implement this interface.
  43. */
  44. interface iDisplay
  45. {
  46. /**
  47. * Maps the given context parameter name to the appropriate filter/search code for this class
  48. * @param string $sContextParam Name of the context parameter, i.e. 'org_id'
  49. * @return string Filter code, i.e. 'customer_id'
  50. */
  51. public static function MapContextParam($sContextParam);
  52. /**
  53. * This function returns a 'hilight' CSS class, used to hilight a given row in a table
  54. * There are currently (i.e defined in the CSS) 4 possible values HILIGHT_CLASS_CRITICAL,
  55. * HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  56. * To Be overridden by derived classes
  57. * @param void
  58. * @return String The desired higlight class for the object/row
  59. */
  60. public function GetHilightClass();
  61. /**
  62. * Returns the relative path to the page that handles the display of the object
  63. * @return string
  64. */
  65. public static function GetUIPage();
  66. /**
  67. * Displays the details of the object
  68. */
  69. public function DisplayDetails(WebPage $oPage, $bEditMode = false);
  70. }
  71. abstract class cmdbAbstractObject extends CMDBObject implements iDisplay
  72. {
  73. protected $m_iFormId; // The ID of the form used to edit the object (when in edition mode !)
  74. static $iGlobalFormId = 1;
  75. /**
  76. * returns what will be the next ID for the forms
  77. */
  78. public static function GetNextFormId()
  79. {
  80. return 1 + self::$iGlobalFormId;
  81. }
  82. public static function GetUIPage()
  83. {
  84. return 'UI.php';
  85. }
  86. function DisplayBareHeader(WebPage $oPage, $bEditMode = false)
  87. {
  88. // Standard Header with name, actions menu and history block
  89. //
  90. // action menu
  91. $oSingletonFilter = new DBObjectSearch(get_class($this));
  92. $oSingletonFilter->AddCondition('id', $this->GetKey(), '=');
  93. $oBlock = new MenuBlock($oSingletonFilter, 'details', false);
  94. $oBlock->Display($oPage, -1);
  95. // Master data sources
  96. $sSynchroIcon = '';
  97. $oReplicaSet = $this->GetMasterReplica();
  98. $bSynchronized = false;
  99. $oCreatorTask = null;
  100. $bCanBeDeletedByTask = false;
  101. $bCanBeDeletedByUser = true;
  102. $aMasterSources = array();
  103. if ($oReplicaSet->Count() > 0)
  104. {
  105. $bSynchronized = true;
  106. while($aData = $oReplicaSet->FetchAssoc())
  107. {
  108. // Assumption: $aData['datasource'] will not be null because the data source id is always set...
  109. $sApplicationURL = $aData['datasource']->GetApplicationUrl($this, $aData['replica']);
  110. $sLink = $aData['datasource']->GetName();
  111. if (!empty($sApplicationURL))
  112. {
  113. $sLink = "<a href=\"$sApplicationURL\" target=\"_blank\">".$aData['datasource']->GetName()."</a>";
  114. }
  115. if ($aData['replica']->Get('status_dest_creator') == 1)
  116. {
  117. $oCreatorTask = $aData['datasource'];
  118. $bCreatedByTask = true;
  119. }
  120. else
  121. {
  122. $bCreatedByTask = false;
  123. }
  124. if ($bCreatedByTask)
  125. {
  126. $sDeletePolicy = $aData['datasource']->Get('delete_policy');
  127. if (($sDeletePolicy == 'delete') || ($sDeletePolicy == 'update_then_delete'))
  128. {
  129. $bCanBeDeletedByTask = true;
  130. }
  131. $sUserDeletePolicy = $aData['datasource']->Get('user_delete_policy');
  132. if ($sUserDeletePolicy == 'nobody')
  133. {
  134. $bCanBeDeletedByUser = false;
  135. }
  136. elseif (($sUserDeletePolicy == 'administrators') && !UserRights::IsAdministrator())
  137. {
  138. $bCanBeDeletedByUser = false;
  139. }
  140. else // everybody...
  141. {
  142. }
  143. }
  144. $aMasterSources[$aData['datasource']->GetKey()]['datasource'] = $aData['datasource'];
  145. $aMasterSources[$aData['datasource']->GetKey()]['url'] = $sLink;
  146. $aMasterSources[$aData['datasource']->GetKey()]['last_synchro'] = $aData['replica']->Get('status_last_seen');
  147. }
  148. if (is_object($oCreatorTask))
  149. {
  150. $sTaskUrl = $aMasterSources[$oCreatorTask->GetKey()]['url'];
  151. if (!$bCanBeDeletedByUser)
  152. {
  153. $sTip = "<p>".Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sTaskUrl)."</p>";
  154. }
  155. else
  156. {
  157. $sTip = "<p>".Dict::Format('Core:Synchro:TheObjectWasCreatedBy_Source', $sTaskUrl)."</p>";
  158. }
  159. if ($bCanBeDeletedByTask)
  160. {
  161. $sTip .= "<p>".Dict::Format('Core:Synchro:TheObjectCanBeDeletedBy_Source', $sTaskUrl)."</p>";
  162. }
  163. }
  164. else
  165. {
  166. $sTip = "<p>".Dict::S('Core:Synchro:ThisObjectIsSynchronized')."</p>";
  167. }
  168. $sTip .= "<p><b>".Dict::S('Core:Synchro:ListOfDataSources')."</b></p>";
  169. foreach($aMasterSources as $aStruct)
  170. {
  171. $oDataSource = $aStruct['datasource'];
  172. $sLink = $aStruct['url'];
  173. $sTip .= "<p style=\"white-space:nowrap\">".$oDataSource->GetIcon(true, 'style="vertical-align:middle"')."&nbsp;$sLink<br/>";
  174. $sTip .= Dict::S('Core:Synchro:LastSynchro').'<br/>'.$aStruct['last_synchro']."</p>";
  175. }
  176. $sSynchroIcon = '&nbsp;<img style="vertical-align:middle;" id="synchro_icon" src="../images/locked.png"/>';
  177. $oPage->add_ready_script("$('#synchro_icon').qtip( { content: '$sTip', show: 'mouseover', hide: { fixed: true }, style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );");
  178. }
  179. $oPage->add("<div class=\"page_header\"><h1>".$this->GetIcon()."&nbsp;\n");
  180. $oPage->add(MetaModel::GetName(get_class($this)).": <span class=\"hilite\">".$this->GetName()."</span>$sSynchroIcon</h1>\n");
  181. $oPage->add("</div>\n");
  182. }
  183. function DisplayBareHistory(WebPage $oPage, $bEditMode = false)
  184. {
  185. // history block (with as a tab)
  186. $oHistoryFilter = new DBObjectSearch('CMDBChangeOp');
  187. $oHistoryFilter->AddCondition('objkey', $this->GetKey(), '=');
  188. $oHistoryFilter->AddCondition('objclass', get_class($this), '=');
  189. $oBlock = new HistoryBlock($oHistoryFilter, 'table', false);
  190. $oBlock->Display($oPage, -1);
  191. }
  192. function DisplayBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix = '', $aExtraParams = array())
  193. {
  194. $aFieldsMap = $this->GetBareProperties($oPage, $bEditMode, $sPrefix, $aExtraParams);
  195. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  196. {
  197. $oExtensionInstance->OnDisplayProperties($this, $oPage, $bEditMode);
  198. }
  199. // Special case to display the case log, if any...
  200. // WARNING: if you modify the loop below, also check the corresponding code in UpdateObject and DisplayModifyForm
  201. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  202. {
  203. if ($oAttDef instanceof AttributeCaseLog)
  204. {
  205. $sComment = (isset($aExtraParams['fieldsComments'][$sAttCode])) ? $aExtraParams['fieldsComments'][$sAttCode] : '';
  206. $this->DisplayCaseLog($oPage, $sAttCode, $sComment, $sPrefix, $bEditMode);
  207. }
  208. }
  209. return $aFieldsMap;
  210. }
  211. function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
  212. {
  213. // Related objects: display all the linkset attributes, each as a separate tab
  214. // In the order described by the 'display' ZList
  215. $aList = $this->FlattenZList(MetaModel::GetZListItems(get_class($this), 'details'));
  216. if (count($aList) == 0)
  217. {
  218. // Empty ZList defined, display all the linkedset attributes defined
  219. $aList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
  220. }
  221. $sClass = get_class($this);
  222. foreach($aList as $sAttCode)
  223. {
  224. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  225. // Display mode
  226. if (!$oAttDef->IsLinkset()) continue; // Process only linkset attributes...
  227. // $oSet = new DBObjectSet($this->Get($sAttCode)->GetFilter()); // Why do something so useless ?
  228. $oSet = $this->Get($sAttCode);
  229. $iCount = $oSet->Count();
  230. $sCount = '';
  231. if ($iCount != 0)
  232. {
  233. $sCount = " ($iCount)";
  234. }
  235. $oPage->SetCurrentTab($oAttDef->GetLabel().$sCount);
  236. if ($this->IsNew())
  237. {
  238. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  239. }
  240. else
  241. {
  242. $iFlags = $this->GetAttributeFlags($sAttCode);
  243. }
  244. $bReadOnly = ($iFlags & (OPT_ATT_READONLY|OPT_ATT_SLAVE));
  245. if ($bEditMode && (!$bReadOnly))
  246. {
  247. $sInputId = $this->m_iFormId.'_'.$sAttCode;
  248. $sLinkedClass = $oAttDef->GetLinkedClass();
  249. if ($oAttDef->IsIndirect())
  250. {
  251. $oLinkingAttDef = MetaModel::GetAttributeDef($sLinkedClass, $oAttDef->GetExtKeyToRemote());
  252. $sTargetClass = $oLinkingAttDef->GetTargetClass();
  253. }
  254. else
  255. {
  256. $sTargetClass = $sLinkedClass;
  257. }
  258. $oPage->p(MetaModel::GetClassIcon($sTargetClass)."&nbsp;".$oAttDef->GetDescription().'<span id="busy_'.$sInputId.'"></span>');
  259. $oValue = $this->Get($sAttCode);
  260. $sDisplayValue = ''; // not used
  261. $aArgs = array('this' => $this);
  262. $sHTMLValue = "<span id=\"field_{$sInputId}\">".self::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $oValue, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).'</span>';
  263. $aFieldsMap[$sAttCode] = $sInputId;
  264. $oPage->add($sHTMLValue);
  265. }
  266. else
  267. {
  268. // Display mode
  269. if (!$oAttDef->IsIndirect())
  270. {
  271. // 1:n links
  272. $sTargetClass = $oAttDef->GetLinkedClass();
  273. $aDefaults = array($oAttDef->GetExtKeyToMe() => $this->GetKey());
  274. $oAppContext = new ApplicationContext();
  275. foreach($oAppContext->GetNames() as $sKey)
  276. {
  277. // The linked object inherits the parent's value for the context
  278. if (MetaModel::IsValidAttCode($sClass, $sKey))
  279. {
  280. $aDefaults[$sKey] = $this->Get($sKey);
  281. }
  282. }
  283. $aParams = array(
  284. 'target_attr' => $oAttDef->GetExtKeyToMe(),
  285. 'object_id' => $this->GetKey(),
  286. 'menu' => false,
  287. 'default' => $aDefaults,
  288. 'table_id' => $sClass.'_'.$sAttCode,
  289. );
  290. }
  291. else
  292. {
  293. // n:n links
  294. $sLinkedClass = $oAttDef->GetLinkedClass();
  295. $oLinkingAttDef = MetaModel::GetAttributeDef($sLinkedClass, $oAttDef->GetExtKeyToRemote());
  296. $sTargetClass = $oLinkingAttDef->GetTargetClass();
  297. $bMenu = ($this->Get($sAttCode)->Count() > 0); // The menu is enabled only if there are already some elements...
  298. $aParams = array(
  299. 'link_attr' => $oAttDef->GetExtKeyToMe(),
  300. 'object_id' => $this->GetKey(),
  301. 'target_attr' => $oAttDef->GetExtKeyToRemote(),
  302. 'view_link' => false,
  303. 'menu' => false,
  304. 'display_limit' => true, // By default limit the list to speed up the initial load & display
  305. 'table_id' => $sClass.'_'.$sAttCode,
  306. );
  307. }
  308. $oPage->p(MetaModel::GetClassIcon($sTargetClass)."&nbsp;".$oAttDef->GetDescription());
  309. $oBlock = new DisplayBlock($this->Get($sAttCode)->GetFilter(), 'list', false);
  310. $oBlock->Display($oPage, 'rel_'.$sAttCode, $aParams);
  311. }
  312. }
  313. $oPage->SetCurrentTab('');
  314. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  315. {
  316. $oExtensionInstance->OnDisplayRelations($this, $oPage, $bEditMode);
  317. }
  318. // Display Notifications after the other tabs since this tab disappears in edition
  319. if (!$bEditMode)
  320. {
  321. // Get the actual class of the current object
  322. // And look for triggers referring to it
  323. // If any trigger has been found then display a tab with notifications
  324. //
  325. $sClass = get_class($this);
  326. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  327. $oTriggerSet = new CMDBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnObject AS T WHERE T.target_class IN ('$sClassList')"));
  328. if ($oTriggerSet->Count() > 0)
  329. {
  330. // Display notifications regarding the object
  331. $iId = $this->GetKey();
  332. $oNotifSearch = DBObjectSearch::FromOQL("SELECT EventNotificationEmail AS Ev JOIN TriggerOnObject AS T ON Ev.trigger_id = T.id WHERE T.target_class IN ('$sClassList') AND Ev.object_id = $iId");
  333. $oNotifSet = new DBObjectSet($oNotifSearch);
  334. $sCount = ($oNotifSet->Count() > 0) ? ' ('.$oNotifSet->Count().')' : '';
  335. $oPage->SetCurrentTab(Dict::S('UI:NotificationsTab').$sCount);
  336. $oBlock = new DisplayBlock($oNotifSearch, 'list', false);
  337. $oBlock->Display($oPage, 'notifications', array('menu' => false));
  338. }
  339. }
  340. }
  341. function GetBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix, $aExtraParams = array())
  342. {
  343. $sHtml = '';
  344. $oAppContext = new ApplicationContext();
  345. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  346. $aDetails = array();
  347. $sClass = get_class($this);
  348. $aDetailsList = MetaModel::GetZListItems($sClass, 'details');
  349. $aDetailsStruct = self::ProcessZlist($aDetailsList, array('UI:PropertiesTab' => array()), 'UI:PropertiesTab', 'col1', '');
  350. // Compute the list of properties to display, first the attributes in the 'details' list, then
  351. // all the remaining attributes that are not external fields
  352. $sHtml = '';
  353. $aDetails = array();
  354. $iInputId = 0;
  355. $aFieldsMap = array();
  356. $aFieldsComments = (isset($aExtraParams['fieldsComments'])) ? $aExtraParams['fieldsComments'] : array();
  357. $aExtraFlags = (isset($aExtraParams['fieldsFlags'])) ? $aExtraParams['fieldsFlags'] : array();
  358. $bFieldComments = (count($aFieldsComments) > 0);
  359. foreach($aDetailsStruct as $sTab => $aCols )
  360. {
  361. $aDetails[$sTab] = array();
  362. ksort($aCols);
  363. $oPage->SetCurrentTab(Dict::S($sTab));
  364. $oPage->add('<table style="vertical-align:top"><tr>');
  365. foreach($aCols as $sColIndex => $aFieldsets)
  366. {
  367. $oPage->add('<td style="vertical-align:top">');
  368. //$aDetails[$sTab][$sColIndex] = array();
  369. $sLabel = '';
  370. $sPreviousLabel = '';
  371. $aDetails[$sTab][$sColIndex] = array();
  372. foreach($aFieldsets as $sFieldsetName => $aFields)
  373. {
  374. if (!empty($sFieldsetName) && ($sFieldsetName[0] != '_'))
  375. {
  376. $sLabel = $sFieldsetName;
  377. }
  378. else
  379. {
  380. $sLabel = '';
  381. }
  382. if ($sLabel != $sPreviousLabel)
  383. {
  384. if (!empty($sPreviousLabel))
  385. {
  386. $oPage->add('<fieldset>');
  387. $oPage->add('<legend>'.Dict::S($sPreviousLabel).'</legend>');
  388. }
  389. $oPage->Details($aDetails[$sTab][$sColIndex]);
  390. if (!empty($sPreviousLabel))
  391. {
  392. $oPage->add('</fieldset>');
  393. }
  394. $aDetails[$sTab][$sColIndex] = array();
  395. $sPreviousLabel = $sLabel;
  396. }
  397. foreach($aFields as $sAttCode)
  398. {
  399. if ($bEditMode)
  400. {
  401. $sComments = isset($aFieldsComments[$sAttCode]) ? $aFieldsComments[$sAttCode] : '&nbsp;';
  402. $sInfos = '&nbsp;';
  403. if ($this->IsNew())
  404. {
  405. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  406. }
  407. else
  408. {
  409. $iFlags = $this->GetAttributeFlags($sAttCode);
  410. }
  411. if (($iFlags & OPT_ATT_MANDATORY) && $this->IsNew())
  412. {
  413. $iFlags = $iFlags & ~OPT_ATT_READONLY; // Mandatory fields cannot be read-only when creating an object
  414. }
  415. if (array_key_exists($sAttCode, $aExtraFlags))
  416. {
  417. // the caller may override some flags if needed
  418. $iFlags = $iFlags | $aExtraFlags[$sAttCode];
  419. }
  420. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  421. if ( (!$oAttDef->IsLinkSet()) && (($iFlags & OPT_ATT_HIDDEN) == 0))
  422. {
  423. if ($oAttDef->IsWritable())
  424. {
  425. if ($sStateAttCode == $sAttCode)
  426. {
  427. // State attribute is always read-only from the UI
  428. $sHTMLValue = $this->GetStateLabel();
  429. $val = array('label' => '<span>'.$oAttDef->GetLabel().'</span>', 'value' => $sHTMLValue, 'comments' => $sComments, 'infos' => $sInfos);
  430. }
  431. else
  432. {
  433. $sInputId = $this->m_iFormId.'_'.$sAttCode;
  434. if ($iFlags & OPT_ATT_HIDDEN)
  435. {
  436. // Attribute is hidden, add a hidden input
  437. $oPage->add('<input type="hidden" id="'.$sInputId.'" name="attr_'.$sPrefix.$sAttCode.'" value="'.htmlentities($this->Get($sAttCode), ENT_QUOTES, 'UTF-8').'"/>');
  438. $aFieldsMap[$sAttCode] = $sInputId;
  439. }
  440. else
  441. {
  442. if ($iFlags & (OPT_ATT_READONLY|OPT_ATT_SLAVE))
  443. {
  444. // Check if the attribute is not read-only because of a synchro...
  445. $aReasons = array();
  446. $sSynchroIcon = '';
  447. if ($iFlags & OPT_ATT_SLAVE)
  448. {
  449. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  450. $sSynchroIcon = "&nbsp;<img id=\"synchro_$sInputId\" src=\"../images/transp-lock.png\" style=\"vertical-align:middle\"/>";
  451. $sTip = '';
  452. foreach($aReasons as $aRow)
  453. {
  454. $sTip .= "<p>Synchronized with {$aRow['name']} - {$aRow['description']}</p>";
  455. }
  456. $oPage->add_ready_script("$('#synchro_$sInputId').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );");
  457. }
  458. // Attribute is read-only
  459. $sHTMLValue = "<span id=\"field_{$sInputId}\">".$this->GetAsHTML($sAttCode);
  460. $sHTMLValue .= '<input type="hidden" id="'.$sInputId.'" name="attr_'.$sPrefix.$sAttCode.'" value="'.htmlentities($this->Get($sAttCode), ENT_QUOTES, 'UTF-8').'"/></span>';
  461. $aFieldsMap[$sAttCode] = $sInputId;
  462. $sComments = $sSynchroIcon;
  463. }
  464. else
  465. {
  466. $sValue = $this->Get($sAttCode);
  467. $sDisplayValue = $this->GetEditValue($sAttCode);
  468. $aArgs = array('this' => $this, 'formPrefix' => $sPrefix);
  469. $sHTMLValue = "<span id=\"field_{$sInputId}\">".self::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $sValue, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).'</span>';
  470. $aFieldsMap[$sAttCode] = $sInputId;
  471. }
  472. $val = array('label' => '<span title="'.$oAttDef->GetDescription().'">'.$oAttDef->GetLabel().'</span>', 'value' => $sHTMLValue, 'comments' => $sComments, 'infos' => $sInfos);
  473. }
  474. }
  475. }
  476. else
  477. {
  478. $val = array('label' => '<span title="'.$oAttDef->GetDescription().'">'.$oAttDef->GetLabel().'</span>', 'value' => $this->GetAsHTML($sAttCode), 'comments' => $sComments, 'infos' => $sInfos);
  479. }
  480. }
  481. else
  482. {
  483. $val = null; // Skip this field
  484. }
  485. }
  486. else
  487. {
  488. // !bEditMode
  489. $val = $this->GetFieldAsHtml($sClass, $sAttCode, $sStateAttCode);
  490. }
  491. if ($val != null)
  492. {
  493. // The field is visible, add it to the current column
  494. $aDetails[$sTab][$sColIndex][] = $val;
  495. $iInputId++;
  496. }
  497. }
  498. }
  499. if (!empty($sPreviousLabel))
  500. {
  501. $oPage->add('<fieldset>');
  502. $oPage->add('<legend>'.Dict::S($sFieldsetName).'</legend>');
  503. }
  504. $oPage->Details($aDetails[$sTab][$sColIndex]);
  505. if (!empty($sPreviousLabel))
  506. {
  507. $oPage->add('</fieldset>');
  508. }
  509. $oPage->add('</td>');
  510. }
  511. $oPage->add('</tr></table>');
  512. }
  513. return $aFieldsMap;
  514. }
  515. function DisplayDetails(WebPage $oPage, $bEditMode = false)
  516. {
  517. $sTemplate = Utils::ReadFromFile(MetaModel::GetDisplayTemplate(get_class($this)));
  518. if (!empty($sTemplate))
  519. {
  520. $oTemplate = new DisplayTemplate($sTemplate);
  521. // Note: to preserve backward compatibility with home-made templates, the placeholder '$pkey$' has been preserved
  522. // but the preferred method is to use '$id$'
  523. $oTemplate->Render($oPage, array('class_name'=> MetaModel::GetName(get_class($this)),'class'=> get_class($this), 'pkey'=> $this->GetKey(), 'id'=> $this->GetKey(), 'name' => $this->GetName()));
  524. }
  525. else
  526. {
  527. // Object's details
  528. // template not found display the object using the *old style*
  529. $this->DisplayBareHeader($oPage, $bEditMode);
  530. $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB);
  531. $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB);
  532. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  533. $this->DisplayBareProperties($oPage, $bEditMode);
  534. $this->DisplayBareRelations($oPage, $bEditMode);
  535. $oPage->SetCurrentTab(Dict::S('UI:HistoryTab'));
  536. $this->DisplayBareHistory($oPage, $bEditMode);
  537. }
  538. }
  539. function DisplayPreview(WebPage $oPage)
  540. {
  541. $aDetails = array();
  542. $sClass = get_class($this);
  543. $aList = MetaModel::GetZListItems($sClass, 'preview');
  544. foreach($aList as $sAttCode)
  545. {
  546. $aDetails[] = array('label' => MetaModel::GetLabel($sClass, $sAttCode), 'value' =>$this->GetAsHTML($sAttCode));
  547. }
  548. $oPage->details($aDetails);
  549. }
  550. public static function DisplaySet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  551. {
  552. $oPage->add(self::GetDisplaySet($oPage, $oSet, $aExtraParams));
  553. }
  554. /**
  555. * Get the HTML fragment corresponding to the display of a table representing a set of objects
  556. * @param WebPage $oPage The page object is used for out-of-band information (mostly scripts) output
  557. * @param CMDBObjectSet The set of objects to display
  558. * @param Hash $aExtraParams Some extra configuration parameters to tweak the behavior of the display
  559. * @return String The HTML fragment representing the table of objects
  560. */
  561. public static function GetDisplaySet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  562. {
  563. if (empty($aExtraParams['currentId']))
  564. {
  565. $iListId = $oPage->GetUniqueId(); // Works only if not in an Ajax page !!
  566. }
  567. else
  568. {
  569. $iListId = $aExtraParams['currentId'];
  570. }
  571. // Initialize and check the parameters
  572. $bViewLink = isset($aExtraParams['view_link']) ? $aExtraParams['view_link'] : true;
  573. $sLinkageAttribute = isset($aExtraParams['link_attr']) ? $aExtraParams['link_attr'] : '';
  574. $iLinkedObjectId = isset($aExtraParams['object_id']) ? $aExtraParams['object_id'] : 0;
  575. $sTargetAttr = isset($aExtraParams['target_attr']) ? $aExtraParams['target_attr'] : '';
  576. if (!empty($sLinkageAttribute))
  577. {
  578. if($iLinkedObjectId == 0)
  579. {
  580. // if 'links' mode is requested the id of the object to link to must be specified
  581. throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_object_id'));
  582. }
  583. if($sTargetAttr == '')
  584. {
  585. // if 'links' mode is requested the d of the object to link to must be specified
  586. throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_target_attr'));
  587. }
  588. }
  589. $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true;
  590. $bTruncated = isset($aExtraParams['truncated']) ? $aExtraParams['truncated'] == true : true;
  591. $bSelectMode = isset($aExtraParams['selection_mode']) ? $aExtraParams['selection_mode'] == true : false;
  592. $bSingleSelectMode = isset($aExtraParams['selection_type']) ? ($aExtraParams['selection_type'] == 'single') : false;
  593. $aExtraFieldsRaw = isset($aExtraParams['extra_fields']) ? explode(',', trim($aExtraParams['extra_fields'])) : array();
  594. $aExtraFields = array();
  595. foreach ($aExtraFieldsRaw as $sFieldName)
  596. {
  597. // Ignore attributes not of the main queried class
  598. if (preg_match('/^(.*)\.(.*)$/', $sFieldName, $aMatches))
  599. {
  600. $sClassAlias = $aMatches[1];
  601. $sAttCode = $aMatches[2];
  602. if ($sClassAlias == $oSet->GetFilter()->GetClassAlias())
  603. {
  604. $aExtraFields[] = $sAttCode;
  605. }
  606. }
  607. else
  608. {
  609. $aExtraFields[] = $sFieldName;
  610. }
  611. }
  612. $sHtml = '';
  613. $oAppContext = new ApplicationContext();
  614. $sClassName = $oSet->GetFilter()->GetClass();
  615. $sZListName = isset($aExtraParams['zlist']) ? ($aExtraParams['zlist']) : 'list';
  616. if ($sZListName !== false)
  617. {
  618. $aList = self::FlattenZList(MetaModel::GetZListItems($sClassName, $sZListName));
  619. $aList = array_merge($aList, $aExtraFields);
  620. }
  621. else
  622. {
  623. $aList = $aExtraFields;
  624. }
  625. // Filter the list to removed linked set since we are not able to display them here
  626. foreach($aList as $index => $sAttCode)
  627. {
  628. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  629. if ($oAttDef instanceof AttributeLinkedSet)
  630. {
  631. // Removed from the display list
  632. unset($aList[$index]);
  633. }
  634. }
  635. if (!empty($sLinkageAttribute))
  636. {
  637. // The set to display is in fact a set of links between the object specified in the $sLinkageAttribute
  638. // and other objects...
  639. // The display will then group all the attributes related to the link itself:
  640. // | Link_attr1 | link_attr2 | ... || Object_attr1 | Object_attr2 | Object_attr3 | .. | Object_attr_n |
  641. $aDisplayList = array();
  642. $aAttDefs = MetaModel::ListAttributeDefs($sClassName);
  643. assert(isset($aAttDefs[$sLinkageAttribute]));
  644. $oAttDef = $aAttDefs[$sLinkageAttribute];
  645. assert($oAttDef->IsExternalKey());
  646. // First display all the attributes specific to the link record
  647. foreach($aList as $sLinkAttCode)
  648. {
  649. $oLinkAttDef = $aAttDefs[$sLinkAttCode];
  650. if ( (!$oLinkAttDef->IsExternalKey()) && (!$oLinkAttDef->IsExternalField()) )
  651. {
  652. $aDisplayList[] = $sLinkAttCode;
  653. }
  654. }
  655. // Then display all the attributes neither specific to the link record nor to the 'linkage' object (because the latter are constant)
  656. foreach($aList as $sLinkAttCode)
  657. {
  658. $oLinkAttDef = $aAttDefs[$sLinkAttCode];
  659. if (($oLinkAttDef->IsExternalKey() && ($sLinkAttCode != $sLinkageAttribute))
  660. || ($oLinkAttDef->IsExternalField() && ($oLinkAttDef->GetKeyAttCode()!=$sLinkageAttribute)) )
  661. {
  662. $aDisplayList[] = $sLinkAttCode;
  663. }
  664. }
  665. // First display all the attributes specific to the link
  666. // Then display all the attributes linked to the other end of the relationship
  667. $aList = $aDisplayList;
  668. }
  669. $sSelectMode = 'none';
  670. if ($bSelectMode)
  671. {
  672. $sSelectMode = $bSingleSelectMode ? 'single' : 'multiple';
  673. }
  674. $sClassAlias = $oSet->GetClassAlias();
  675. $bDisplayLimit = isset($aExtraParams['display_limit']) ? $aExtraParams['display_limit'] : true;
  676. // Load only the requested columns
  677. $oSet->OptimizeColumnLoad(array($sClassAlias => $aList));
  678. $sTableId = isset($aExtraParams['table_id']) ? $aExtraParams['table_id'] : null;
  679. $aClassAliases = array( $sClassAlias => $sClassName);
  680. $oDataTable = new DataTable($iListId, $oSet, $aClassAliases, $sTableId);
  681. $oSettings = DataTableSettings::GetDataModelSettings($aClassAliases, $bViewLink, array($sClassAlias => $aList));
  682. if ($bDisplayLimit)
  683. {
  684. $iDefaultPageSize = appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit());
  685. $oSettings->iDefaultPageSize = $iDefaultPageSize;
  686. }
  687. $oSettings->aSortOrder = MetaModel::GetOrderByDefault($sClassName);
  688. return $oDataTable->Display($oPage, $oSettings, $bDisplayMenu, $sSelectMode, $bViewLink, $aExtraParams);
  689. }
  690. public static function GetDisplayExtendedSet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  691. {
  692. if (empty($aExtraParams['currentId']))
  693. {
  694. $iListId = $oPage->GetUniqueId(); // Works only if not in an Ajax page !!
  695. }
  696. else
  697. {
  698. $iListId = $aExtraParams['currentId'];
  699. }
  700. $aList = array();
  701. // Initialize and check the parameters
  702. $bViewLink = isset($aExtraParams['view_link']) ? $aExtraParams['view_link'] : true;
  703. $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true;
  704. // Check if there is a list of aliases to limit the display to...
  705. $aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']) : array();
  706. $sZListName = isset($aExtraParams['zlist']) ? ($aExtraParams['zlist']) : 'list';
  707. $aExtraFieldsRaw = isset($aExtraParams['extra_fields']) ? explode(',', trim($aExtraParams['extra_fields'])) : array();
  708. $aExtraFields = array();
  709. foreach ($aExtraFieldsRaw as $sFieldName)
  710. {
  711. // Ignore attributes not of the main queried class
  712. if (preg_match('/^(.*)\.(.*)$/', $sFieldName, $aMatches))
  713. {
  714. $sClassAlias = $aMatches[1];
  715. $sAttCode = $aMatches[2];
  716. if (array_key_exists($sClassAlias, $oSet->GetSelectedClasses()))
  717. {
  718. $aExtraFields[$sClassAlias][] = $sAttCode;
  719. }
  720. }
  721. else
  722. {
  723. $aExtraFields['*'] = $sAttCode;
  724. }
  725. }
  726. $sHtml = '';
  727. $oAppContext = new ApplicationContext();
  728. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  729. $aAuthorizedClasses = array();
  730. foreach($aClasses as $sAlias => $sClassName)
  731. {
  732. if ( (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS)) &&
  733. ( (count($aDisplayAliases) == 0) || (in_array($sAlias, $aDisplayAliases))) )
  734. {
  735. $aAuthorizedClasses[$sAlias] = $sClassName;
  736. }
  737. }
  738. $aAttribs = array();
  739. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  740. {
  741. if (array_key_exists($sAlias, $aExtraFields))
  742. {
  743. $aList[$sAlias] = $aExtraFields[$sAlias];
  744. }
  745. else
  746. {
  747. $aList[$sAlias] = array();
  748. }
  749. if ($sZListName !== false)
  750. {
  751. $aDefaultList = self::FlattenZList(MetaModel::GetZListItems($sClassName, $sZListName));
  752. $aList[$sAlias] = array_merge($aDefaultList, $aList[$sAlias]);
  753. }
  754. // Filter the list to removed linked set since we are not able to display them here
  755. foreach($aList[$sAlias] as $index => $sAttCode)
  756. {
  757. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  758. if ($oAttDef instanceof AttributeLinkedSet)
  759. {
  760. // Removed from the display list
  761. unset($aList[$sAlias][$index]);
  762. }
  763. }
  764. }
  765. // Load only the requested columns
  766. $aAttToLoad = array(); // attributes to load
  767. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  768. {
  769. foreach($aList[$sAlias] as $sAttCode)
  770. {
  771. $aAttToLoad[$sAlias][] = $sAttCode;
  772. }
  773. }
  774. $oSet->OptimizeColumnLoad($aAttToLoad);
  775. $sSelectMode = 'none';
  776. $sClassAlias = $oSet->GetClassAlias();
  777. $oDataTable = new DataTable($iListId, $oSet, $aAuthorizedClasses);
  778. $oSettings = DataTableSettings::GetDataModelSettings($aAuthorizedClasses, $bViewLink, $aList);
  779. $bDisplayLimit = isset($aExtraParams['display_limit']) ? $aExtraParams['display_limit'] : true;
  780. if ($bDisplayLimit)
  781. {
  782. $iDefaultPageSize = appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit());
  783. $oSettings->iDefaultPageSize = $iDefaultPageSize;
  784. }
  785. $oSettings->aSortOrder = MetaModel::GetOrderByDefault($sClassName);
  786. return $oDataTable->Display($oPage, $oSettings, $bDisplayMenu, $sSelectMode, $bViewLink, $aExtraParams);
  787. }
  788. static function DisplaySetAsCSV(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array())
  789. {
  790. $oPage->add(self::GetSetAsCSV($oSet, $aParams));
  791. }
  792. static function GetSetAsCSV(DBObjectSet $oSet, $aParams = array())
  793. {
  794. $sSeparator = isset($aParams['separator']) ? $aParams['separator'] : ','; // default separator is comma
  795. $sTextQualifier = isset($aParams['text_qualifier']) ? $aParams['text_qualifier'] : '"'; // default text qualifier is double quote
  796. $aFields = null;
  797. if (isset($aParams['fields']) && (strlen($aParams['fields']) > 0))
  798. {
  799. $aFields = explode(',', $aParams['fields']);
  800. }
  801. $bFieldsAdvanced = false;
  802. if (isset($aParams['fields_advanced']))
  803. {
  804. $bFieldsAdvanced = (bool) $aParams['fields_advanced'];
  805. }
  806. $bLocalize = true;
  807. if (isset($aParams['localize_values']))
  808. {
  809. $bLocalize = (bool) $aParams['localize_values'];
  810. }
  811. $aList = array();
  812. $oAppContext = new ApplicationContext();
  813. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  814. $aAuthorizedClasses = array();
  815. foreach($aClasses as $sAlias => $sClassName)
  816. {
  817. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  818. {
  819. $aAuthorizedClasses[$sAlias] = $sClassName;
  820. }
  821. }
  822. $aAttribs = array();
  823. $aHeader = array();
  824. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  825. {
  826. $aList[$sAlias] = array();
  827. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef)
  828. {
  829. if (is_null($aFields) || (count($aFields) == 0))
  830. {
  831. // Standard list of attributes (no link sets)
  832. if ($oAttDef->IsScalar() && ($oAttDef->IsWritable() || $oAttDef->IsExternalField()))
  833. {
  834. $sAttCodeEx = $oAttDef->IsExternalField() ? $oAttDef->GetKeyAttCode().'->'.$oAttDef->GetExtAttCode() : $sAttCode;
  835. if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
  836. {
  837. if ($bFieldsAdvanced)
  838. {
  839. $aList[$sAlias][$sAttCodeEx] = $oAttDef;
  840. if ($oAttDef->IsExternalKey(EXTKEY_RELATIVE))
  841. {
  842. $sRemoteClass = $oAttDef->GetTargetClass();
  843. foreach(MetaModel::GetReconcKeys($sRemoteClass) as $sRemoteAttCode)
  844. {
  845. $aList[$sAlias][$sAttCode.'->'.$sRemoteAttCode] = MetaModel::GetAttributeDef($sRemoteClass, $sRemoteAttCode);
  846. }
  847. }
  848. }
  849. }
  850. else
  851. {
  852. // Any other attribute
  853. $aList[$sAlias][$sAttCodeEx] = $oAttDef;
  854. }
  855. }
  856. }
  857. else
  858. {
  859. // User defined list of attributes
  860. if (in_array($sAttCode, $aFields) || in_array($sAlias.'.'.$sAttCode, $aFields))
  861. {
  862. $aList[$sAlias][$sAttCode] = $oAttDef;
  863. }
  864. }
  865. }
  866. if ($bFieldsAdvanced)
  867. {
  868. $aHeader[] = 'id';
  869. }
  870. foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef)
  871. {
  872. $sStar = '';
  873. if (!$oAttDef->IsNullAllowed() && isset($aParams['showMandatoryFields']))
  874. {
  875. $sStar = '*';
  876. }
  877. $aHeader[] = ($bLocalize ? MetaModel::GetLabel($sClassName, $sAttCodeEx) : $sAttCodeEx).$sStar;
  878. }
  879. }
  880. $sHtml = implode($sSeparator, $aHeader)."\n";
  881. $oSet->Seek(0);
  882. while ($aObjects = $oSet->FetchAssoc())
  883. {
  884. $aRow = array();
  885. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  886. {
  887. $oObj = $aObjects[$sAlias];
  888. if ($bFieldsAdvanced)
  889. {
  890. if (is_null($oObj))
  891. {
  892. $aRow[] = '';
  893. }
  894. else
  895. {
  896. $aRow[] = $oObj->GetKey();
  897. }
  898. }
  899. foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef)
  900. {
  901. if (is_null($oObj))
  902. {
  903. $aRow[] = '';
  904. }
  905. else
  906. {
  907. $value = $oObj->Get($sAttCodeEx);
  908. $aRow[] = $oAttDef->GetAsCSV($value, $sSeparator, $sTextQualifier, $oObj, $bLocalize);
  909. }
  910. }
  911. }
  912. $sHtml .= implode($sSeparator, $aRow)."\n";
  913. }
  914. return $sHtml;
  915. }
  916. static function DisplaySetAsHTMLSpreadsheet(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array())
  917. {
  918. $oPage->add(self::GetSetAsHTMLSpreadsheet($oSet, $aParams));
  919. }
  920. /**
  921. * Spreadsheet output: designed for end users doing some reporting
  922. * Then the ids are excluded and replaced by the corresponding friendlyname
  923. */
  924. static function GetSetAsHTMLSpreadsheet(DBObjectSet $oSet, $aParams = array())
  925. {
  926. $aFields = null;
  927. if (isset($aParams['fields']) && (strlen($aParams['fields']) > 0))
  928. {
  929. $aFields = explode(',', $aParams['fields']);
  930. }
  931. $bFieldsAdvanced = false;
  932. if (isset($aParams['fields_advanced']))
  933. {
  934. $bFieldsAdvanced = (bool) $aParams['fields_advanced'];
  935. }
  936. $bLocalize = true;
  937. if (isset($aParams['localize_values']))
  938. {
  939. $bLocalize = (bool) $aParams['localize_values'];
  940. }
  941. $aList = array();
  942. $oAppContext = new ApplicationContext();
  943. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  944. $aAuthorizedClasses = array();
  945. foreach($aClasses as $sAlias => $sClassName)
  946. {
  947. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  948. {
  949. $aAuthorizedClasses[$sAlias] = $sClassName;
  950. }
  951. }
  952. $aAttribs = array();
  953. $aHeader = array();
  954. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  955. {
  956. $aList[$sAlias] = array();
  957. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef)
  958. {
  959. if (is_null($aFields) || (count($aFields) == 0))
  960. {
  961. // Standard list of attributes (no link sets)
  962. if ($oAttDef->IsScalar() && ($oAttDef->IsWritable() || $oAttDef->IsExternalField()))
  963. {
  964. $sAttCodeEx = $oAttDef->IsExternalField() ? $oAttDef->GetKeyAttCode().'->'.$oAttDef->GetExtAttCode() : $sAttCode;
  965. $aList[$sAlias][$sAttCodeEx] = $oAttDef;
  966. if ($bFieldsAdvanced && $oAttDef->IsExternalKey(EXTKEY_RELATIVE))
  967. {
  968. $sRemoteClass = $oAttDef->GetTargetClass();
  969. foreach(MetaModel::GetReconcKeys($sRemoteClass) as $sRemoteAttCode)
  970. {
  971. $aList[$sAlias][$sAttCode.'->'.$sRemoteAttCode] = MetaModel::GetAttributeDef($sRemoteClass, $sRemoteAttCode);
  972. }
  973. }
  974. }
  975. }
  976. else
  977. {
  978. // User defined list of attributes
  979. if (in_array($sAttCode, $aFields) || in_array($sAlias.'.'.$sAttCode, $aFields))
  980. {
  981. $aList[$sAlias][$sAttCode] = $oAttDef;
  982. }
  983. }
  984. }
  985. // Replace external key by the corresponding friendly name (if not already in the list)
  986. foreach($aList[$sAlias] as $sAttCode => $oAttDef)
  987. {
  988. if ($oAttDef->IsExternalKey())
  989. {
  990. unset($aList[$sAlias][$sAttCode]);
  991. $sFriendlyNameAttCode = $sAttCode.'_friendlyname';
  992. if (!array_key_exists($sFriendlyNameAttCode, $aList[$sAlias]) && MetaModel::IsValidAttCode($sClassName, $sFriendlyNameAttCode))
  993. {
  994. $oFriendlyNameAtt = MetaModel::GetAttributeDef($sClassName, $sFriendlyNameAttCode);
  995. $aList[$sAlias][$sFriendlyNameAttCode] = $oFriendlyNameAtt;
  996. }
  997. }
  998. }
  999. foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef)
  1000. {
  1001. $sColLabel = $bLocalize ? MetaModel::GetLabel($sClassName, $sAttCodeEx) : $sAttCodeEx;
  1002. $oFinalAttDef = $oAttDef->GetFinalAttDef();
  1003. if (get_class($oFinalAttDef) == 'AttributeDateTime')
  1004. {
  1005. $aHeader[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Date').')';
  1006. $aHeader[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Time').')';
  1007. }
  1008. else
  1009. {
  1010. $aHeader[] = $sColLabel;
  1011. }
  1012. }
  1013. }
  1014. $sHtml = "<table border=\"1\">\n";
  1015. $sHtml .= "<tr>\n";
  1016. $sHtml .= "<td>".implode("</td><td>", $aHeader)."</td>\n";
  1017. $sHtml .= "</tr>\n";
  1018. $oSet->Seek(0);
  1019. while ($aObjects = $oSet->FetchAssoc())
  1020. {
  1021. $aRow = array();
  1022. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  1023. {
  1024. $oObj = $aObjects[$sAlias];
  1025. foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef)
  1026. {
  1027. if (is_null($oObj))
  1028. {
  1029. $aRow[] = '<td></td>';
  1030. }
  1031. else
  1032. {
  1033. $oFinalAttDef = $oAttDef->GetFinalAttDef();
  1034. if (get_class($oFinalAttDef) == 'AttributeDateTime')
  1035. {
  1036. $iDate = AttributeDateTime::GetAsUnixSeconds($oObj->Get($sAttCodeEx));
  1037. $aRow[] = '<td>'.date('Y-m-d', $iDate).'</td>';
  1038. $aRow[] = '<td>'.date('H:i:s', $iDate).'</td>';
  1039. }
  1040. else
  1041. {
  1042. $rawValue = $oObj->Get($sAttCodeEx);
  1043. if ($bLocalize)
  1044. {
  1045. $outputValue = htmlentities($oFinalAttDef->GetValueLabel($rawValue), ENT_QUOTES, 'UTF-8');
  1046. }
  1047. else
  1048. {
  1049. $outputValue = htmlentities($rawValue, ENT_QUOTES, 'UTF-8');
  1050. }
  1051. $aRow[] = '<td>'.$outputValue.'</td>';
  1052. }
  1053. }
  1054. }
  1055. }
  1056. $sHtml .= implode("\n", $aRow);
  1057. $sHtml .= "</tr>\n";
  1058. }
  1059. $sHtml .= "</table>\n";
  1060. return $sHtml;
  1061. }
  1062. static function DisplaySetAsXML(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array())
  1063. {
  1064. $bLocalize = true;
  1065. if (isset($aParams['localize_values']))
  1066. {
  1067. $bLocalize = (bool) $aParams['localize_values'];
  1068. }
  1069. $oAppContext = new ApplicationContext();
  1070. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  1071. $aAuthorizedClasses = array();
  1072. foreach($aClasses as $sAlias => $sClassName)
  1073. {
  1074. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  1075. {
  1076. $aAuthorizedClasses[$sAlias] = $sClassName;
  1077. }
  1078. }
  1079. $aAttribs = array();
  1080. $aList = array();
  1081. $aList[$sAlias] = MetaModel::GetZListItems($sClassName, 'details');
  1082. $oPage->add("<Set>\n");
  1083. $oSet->Seek(0);
  1084. while ($aObjects = $oSet->FetchAssoc())
  1085. {
  1086. if (count($aAuthorizedClasses) > 1)
  1087. {
  1088. $oPage->add("<Row>\n");
  1089. }
  1090. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  1091. {
  1092. $oObj = $aObjects[$sAlias];
  1093. if (is_null($oObj))
  1094. {
  1095. $oPage->add("<$sClassName alias=\"$sAlias\" id=\"null\">\n");
  1096. }
  1097. else
  1098. {
  1099. $sClassName = get_class($oObj);
  1100. $oPage->add("<$sClassName alias=\"$sAlias\" id=\"".$oObj->GetKey()."\">\n");
  1101. }
  1102. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode=>$oAttDef)
  1103. {
  1104. if (is_null($oObj))
  1105. {
  1106. $oPage->add("<$sAttCode>null</$sAttCode>\n");
  1107. }
  1108. else
  1109. {
  1110. if ($oAttDef->IsWritable())
  1111. {
  1112. if (!$oAttDef->IsLinkSet())
  1113. {
  1114. $sValue = $oObj->GetAsXML($sAttCode, $bLocalize);
  1115. $oPage->add("<$sAttCode>$sValue</$sAttCode>\n");
  1116. }
  1117. }
  1118. }
  1119. }
  1120. $oPage->add("</$sClassName>\n");
  1121. }
  1122. if (count($aAuthorizedClasses) > 1)
  1123. {
  1124. $oPage->add("</Row>\n");
  1125. }
  1126. }
  1127. $oPage->add("</Set>\n");
  1128. }
  1129. public static function DisplaySearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  1130. {
  1131. $oPage->add(self::GetSearchForm($oPage, $oSet, $aExtraParams));
  1132. }
  1133. public static function GetSearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  1134. {
  1135. static $iSearchFormId = 0;
  1136. $oAppContext = new ApplicationContext();
  1137. $sHtml = '';
  1138. $numCols=4;
  1139. $sClassName = $oSet->GetFilter()->GetClass();
  1140. // Romain: temporarily removed the tab "OQL query" because it was not finalized
  1141. // (especially when used to add a link)
  1142. /*
  1143. $sHtml .= "<div class=\"mini_tabs\" id=\"mini_tabs{$iSearchFormId}\"><ul>
  1144. <li><a href=\"#\" onClick=\"$('div.mini_tab{$iSearchFormId}').toggle();$('#mini_tabs{$iSearchFormId} ul li a').toggleClass('selected');\">".Dict::S('UI:OQLQueryTab')."</a></li>
  1145. <li><a class=\"selected\" href=\"#\" onClick=\"$('div.mini_tab{$iSearchFormId}').toggle();$('#mini_tabs{$iSearchFormId} ul li a').toggleClass('selected');\">".Dict::S('UI:SimpleSearchTab')."</a></li>
  1146. </ul></div>\n";
  1147. */
  1148. // Simple search form
  1149. if (isset($aExtraParams['currentId']))
  1150. {
  1151. $sSearchFormId = $aExtraParams['currentId'];
  1152. }
  1153. else
  1154. {
  1155. $iSearchFormId = $oPage->GetUniqueId();
  1156. $sSearchFormId = 'SimpleSearchForm'.$iSearchFormId;
  1157. $sHtml .= "<div id=\"ds_$sSearchFormId\" class=\"mini_tab{$iSearchFormId}\">\n";
  1158. }
  1159. // Check if the current class has some sub-classes
  1160. if (isset($aExtraParams['baseClass']))
  1161. {
  1162. $sRootClass = $aExtraParams['baseClass'];
  1163. }
  1164. else
  1165. {
  1166. $sRootClass = $sClassName;
  1167. }
  1168. $aSubClasses = MetaModel::GetSubclasses($sRootClass);
  1169. if (count($aSubClasses) > 0)
  1170. {
  1171. $aOptions = array();
  1172. $aOptions[MetaModel::GetName($sRootClass)] = "<option value=\"$sRootClass\">".MetaModel::GetName($sRootClass)."</options>\n";
  1173. foreach($aSubClasses as $sSubclassName)
  1174. {
  1175. $aOptions[MetaModel::GetName($sSubclassName)] = "<option value=\"$sSubclassName\">".MetaModel::GetName($sSubclassName)."</options>\n";
  1176. }
  1177. $aOptions[MetaModel::GetName($sClassName)] = "<option selected value=\"$sClassName\">".MetaModel::GetName($sClassName)."</options>\n";
  1178. ksort($aOptions);
  1179. $sContext = $oAppContext->GetForLink();
  1180. $sClassesCombo = "<select name=\"class\" onChange=\"ReloadSearchForm('$sSearchFormId', this.value, '$sRootClass', '$sContext')\">\n".implode('', $aOptions)."</select>\n";
  1181. }
  1182. else
  1183. {
  1184. $sClassesCombo = MetaModel::GetName($sClassName);
  1185. }
  1186. $oUnlimitedFilter = new DBObjectSearch($sClassName);
  1187. $sAction = (isset($aExtraParams['action'])) ? $aExtraParams['action'] : utils::GetAbsoluteUrlAppRoot().'pages/UI.php';
  1188. $sHtml .= "<form id=\"fs_{$sSearchFormId}\" action=\"{$sAction}\">\n"; // Don't use $_SERVER['SCRIPT_NAME'] since the form may be called asynchronously (from ajax.php)
  1189. $sHtml .= "<h2>".Dict::Format('UI:SearchFor_Class_Objects', $sClassesCombo)."</h2>\n";
  1190. $index = 0;
  1191. $sHtml .= "<p>\n";
  1192. $aFilterCriteria = $oSet->GetFilter()->GetCriteria();
  1193. $aMapCriteria = array();
  1194. foreach($aFilterCriteria as $aCriteria)
  1195. {
  1196. $aMapCriteria[$aCriteria['filtercode']][] = array('value' => $aCriteria['value'], 'opcode' => $aCriteria['opcode']);
  1197. }
  1198. $aList = MetaModel::GetZListItems($sClassName, 'standard_search');
  1199. $aConsts = $oSet->ListConstantFields(); // Some fields are constants based on the query/context
  1200. $sClassAlias = $oSet->GetFilter()->GetClassAlias();
  1201. foreach($aList as $sFilterCode)
  1202. {
  1203. //$oAppContext->Reset($sFilterCode); // Make sure the same parameter will not be passed twice
  1204. $sHtml .= '<span style="white-space: nowrap;padding:5px;display:inline-block;">';
  1205. $sFilterValue = isset($aConsts[$sClassAlias][$sFilterCode]) ? $aConsts[$sClassAlias][$sFilterCode] : '';
  1206. $sFilterValue = utils::ReadParam($sFilterCode, $sFilterValue, false, 'raw_data');
  1207. $sFilterOpCode = null; // Use the default 'loose' OpCode
  1208. if (empty($sFilterValue))
  1209. {
  1210. if (isset($aMapCriteria[$sFilterCode]))
  1211. {
  1212. if (count($aMapCriteria[$sFilterCode]) > 1)
  1213. {
  1214. $sFilterValue = Dict::S('UI:SearchValue:Mixed');
  1215. }
  1216. else
  1217. {
  1218. $sFilterValue = $aMapCriteria[$sFilterCode][0]['value'];
  1219. $sFilterOpCode = $aMapCriteria[$sFilterCode][0]['opcode'];
  1220. }
  1221. if ($sFilterCode != 'company')
  1222. {
  1223. $oUnlimitedFilter->AddCondition($sFilterCode, $sFilterValue, $sFilterOpCode);
  1224. }
  1225. }
  1226. }
  1227. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sFilterCode);
  1228. if ($oAttDef->IsExternalKey())
  1229. {
  1230. $sTargetClass = $oAttDef->GetTargetClass();
  1231. $oSearch = new DBObjectSearch($sTargetClass);
  1232. $oSearch->SetModifierProperty('UserRightsGetSelectFilter', 'bSearchMode', true);
  1233. $oAllowedValues = new DBObjectSet($oSearch);
  1234. $iFieldSize = $oAttDef->GetMaxSize();
  1235. $iMaxComboLength = $oAttDef->GetMaximumComboLength();
  1236. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;";
  1237. $aExtKeyParams = $aExtraParams;
  1238. $aExtKeyParams['iFieldSize'] = $oAttDef->GetMaxSize();
  1239. $aExtKeyParams['iMinChars'] = $oAttDef->GetMinAutoCompleteChars();
  1240. $sHtml .= UIExtKeyWidget::DisplayFromAttCode($oPage, $sFilterCode, $sClassName, $oAttDef->GetLabel(), $oAllowedValues, $sFilterValue, $sSearchFormId.'search_'.$sFilterCode, false, $sFilterCode, '', $aExtKeyParams, true);
  1241. }
  1242. else
  1243. {
  1244. $aAllowedValues = MetaModel::GetAllowedValues_flt($sClassName, $sFilterCode, $aExtraParams);
  1245. if (is_null($aAllowedValues))
  1246. {
  1247. // Any value is possible, display an input box
  1248. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;<input class=\"textSearch\" name=\"$sFilterCode\" value=\"".htmlentities($sFilterValue, ENT_QUOTES, 'utf-8')."\"/>\n";
  1249. }
  1250. else
  1251. {
  1252. //Enum field, display a combo
  1253. $sValue = "<select name=\"$sFilterCode\">\n";
  1254. $sValue .= "<option value=\"\">".Dict::S('UI:SearchValue:Any')."</option>\n";
  1255. foreach($aAllowedValues as $key => $value)
  1256. {
  1257. if ($sFilterValue == $key)
  1258. {
  1259. $sSelected = ' selected';
  1260. }
  1261. else
  1262. {
  1263. $sSelected = '';
  1264. }
  1265. $sValue .= "<option value=\"$key\"$sSelected>$value</option>\n";
  1266. }
  1267. $sValue .= "</select>\n";
  1268. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;$sValue\n";
  1269. }
  1270. }
  1271. unset($aExtraParams[$sFilterCode]);
  1272. // Finally, add a tooltip if one is defined for this attribute definition
  1273. $sTip = $oAttDef->GetHelpOnSmartSearch();
  1274. if (strlen($sTip) > 0)
  1275. {
  1276. $sTip = addslashes($sTip);
  1277. $sTip = str_replace(array("\n", "\r"), " ", $sTip);
  1278. // :input does represent in form visible input (INPUT, SELECT, TEXTAREA)
  1279. $oPage->add_ready_script("$('form#fs_$sSearchFormId :input[name={$sFilterCode}]').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );");
  1280. }
  1281. $index++;
  1282. $sHtml .= '</span> ';
  1283. }
  1284. $sHtml .= "</p>\n";
  1285. $sHtml .= "<p align=\"right\"><input type=\"submit\" value=\"".Dict::S('UI:Button:Search')."\"></p>\n";
  1286. if (isset($aExtraParams['table_id']))
  1287. {
  1288. // Rename to avoid collisions...
  1289. $aExtraParams['_table_id_'] = $aExtraParams['table_id'];
  1290. unset($aExtraParams['table_id']);
  1291. }
  1292. foreach($aExtraParams as $sName => $sValue)
  1293. {
  1294. $sHtml .= "<input type=\"hidden\" name=\"$sName\" value=\"$sValue\" />\n";
  1295. }
  1296. $sHtml .= "<input type=\"hidden\" name=\"class\" value=\"$sClassName\" />\n";
  1297. $sHtml .= "<input type=\"hidden\" name=\"dosearch\" value=\"1\" />\n";
  1298. $sHtml .= "<input type=\"hidden\" name=\"operation\" value=\"search_form\" />\n";
  1299. $sHtml .= $oAppContext->GetForForm();
  1300. $sHtml .= "</form>\n";
  1301. if (!isset($aExtraParams['currentId']))
  1302. {
  1303. $sHtml .= "</div><!-- Simple search form -->\n";
  1304. }
  1305. /*
  1306. // OQL query builder
  1307. $sHtml .= "<div id=\"OQLQuery{$iSearchFormId}\" style=\"display:none\" class=\"mini_tab{$iSearchFormId}\">\n";
  1308. $sHtml .= "<h1>".Dict::S('UI:OQLQueryBuilderTitle')."</h1>\n";
  1309. $sHtml .= "<form id=\"formOQL{$iSearchFormId}\"><table style=\"width:80%;\"><tr style=\"vertical-align:top\">\n";
  1310. $sHtml .= "<td style=\"text-align:right\"><label>SELECT&nbsp;</label><select name=\"oql_class\">";
  1311. $aClasses = MetaModel::EnumChildClasses($sClassName, ENUM_CHILD_CLASSES_ALL);
  1312. $sSelectedClass = utils::ReadParam('oql_class', $sClassName, false, 'class');
  1313. $sOQLClause = utils::ReadParam('oql_clause', '', false, 'raw_data');
  1314. asort($aClasses);
  1315. foreach($aClasses as $sChildClass)
  1316. {
  1317. $sSelected = ($sChildClass == $sSelectedClass) ? 'selected' : '';
  1318. $sHtml.= "<option value=\"$sChildClass\" $sSelected>".MetaModel::GetName($sChildClass)."</option>\n";
  1319. }
  1320. $sHtml .= "</select>&nbsp;</td><td>\n";
  1321. $sHtml .= "<textarea name=\"oql_clause\" style=\"width:100%\">$sOQLClause</textarea></td></tr>\n";
  1322. $sHtml .= "<tr><td colspan=\"2\" style=\"text-align:right\"><input type=\"submit\" value=\"".Dict::S('UI:Button:Query')."\"></td></tr>\n";
  1323. $sHtml .= "<input type=\"hidden\" name=\"dosearch\" value=\"1\" />\n";
  1324. foreach($aExtraParams as $sName => $sValue)
  1325. {
  1326. $sHtml .= "<input type=\"hidden\" name=\"$sName\" value=\"$sValue\" />\n";
  1327. }
  1328. $sHtml .= "<input type=\"hidden\" name=\"operation\" value=\"search_oql\" />\n";
  1329. $sHtml .= $oAppContext->GetForForm();
  1330. $sHtml .= "</table></form>\n";
  1331. $sHtml .= "</div><!-- OQL query form -->\n";
  1332. */
  1333. return $sHtml;
  1334. }
  1335. public static function GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $value = '', $sDisplayValue = '', $iId = '', $sNameSuffix = '', $iFlags = 0, $aArgs = array())
  1336. {
  1337. static $iInputId = 0;
  1338. $sFieldPrefix = '';
  1339. $sFormPrefix = isset($aArgs['formPrefix']) ? $aArgs['formPrefix'] : '';
  1340. $sFieldPrefix = isset($aArgs['prefix']) ? $sFormPrefix.$aArgs['prefix'] : $sFormPrefix;
  1341. if ($sDisplayValue == '')
  1342. {
  1343. $sDisplayValue = $value;
  1344. }
  1345. if (isset($aArgs[$sAttCode]) && empty($value))
  1346. {
  1347. // default value passed by the context (either the app context of the operation)
  1348. $value = $aArgs[$sAttCode];
  1349. }
  1350. if (!empty($iId))
  1351. {
  1352. $iInputId = $iId;
  1353. }
  1354. else
  1355. {
  1356. $iInputId = $oPage->GetUniqueId();
  1357. }
  1358. if (!$oAttDef->IsExternalField())
  1359. {
  1360. $bMandatory = 'false';
  1361. if ( (!$oAttDef->IsNullAllowed()) || ($iFlags & OPT_ATT_MANDATORY))
  1362. {
  1363. $bMandatory = 'true';
  1364. }
  1365. $sValidationField = "<span class=\"form_validation\" id=\"v_{$iId}\"></span>";
  1366. $sHelpText = $oAttDef->GetHelpOnEdition();
  1367. $aEventsList = array();
  1368. switch($oAttDef->GetEditClass())
  1369. {
  1370. case 'Date':
  1371. $aEventsList[] ='validate';
  1372. $aEventsList[] ='keyup';
  1373. $aEventsList[] ='change';
  1374. $sHTMLValue = "<input title=\"$sHelpText\" class=\"date-pick\" type=\"text\" size=\"12\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" value=\"".htmlentities($sDisplayValue, ENT_QUOTES, 'UTF-8')."\" id=\"$iId\"/>&nbsp;{$sValidationField}";
  1375. break;
  1376. case 'DateTime':
  1377. $aEventsList[] ='validate';
  1378. $aEventsList[] ='keyup';
  1379. $aEventsList[] ='change';
  1380. $sHTMLValue = "<input title=\"$sHelpText\" class=\"datetime-pick\" type=\"text\" size=\"20\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" value=\"".htmlentities($sDisplayValue, ENT_QUOTES, 'UTF-8')."\" id=\"$iId\"/>&nbsp;{$sValidationField}";
  1381. break;
  1382. case 'Duration':
  1383. $aEventsList[] ='validate';
  1384. $aEventsList[] ='change';
  1385. $oPage->add_ready_script("$('#{$iId}_d').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1386. $oPage->add_ready_script("$('#{$iId}_h').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1387. $oPage->add_ready_script("$('#{$iId}_m').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1388. $oPage->add_ready_script("$('#{$iId}_s').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1389. $aVal = AttributeDuration::SplitDuration($value);
  1390. $sDays = "<input title=\"$sHelpText\" type=\"text\" size=\"3\" name=\"attr_{$sFieldPrefix}{$sAttCode}[d]{$sNameSuffix}\" value=\"{$aVal['days']}\" id=\"{$iId}_d\"/>";
  1391. $sHours = "<input title=\"$sHelpText\" type=\"text\" size=\"2\" name=\"attr_{$sFieldPrefix}{$sAttCode}[h]{$sNameSuffix}\" value=\"{$aVal['hours']}\" id=\"{$iId}_h\"/>";
  1392. $sMinutes = "<input title=\"$sHelpText\" type=\"text\" size=\"2\" name=\"attr_{$sFieldPrefix}{$sAttCode}[m]{$sNameSuffix}\" value=\"{$aVal['minutes']}\" id=\"{$iId}_m\"/>";
  1393. $sSeconds = "<input title=\"$sHelpText\" type=\"text\" size=\"2\" name=\"attr_{$sFieldPrefix}{$sAttCode}[s]{$sNameSuffix}\" value=\"{$aVal['seconds']}\" id=\"{$iId}_s\"/>";
  1394. $sHidden = "<input type=\"hidden\" id=\"{$iId}\" value=\"".htmlentities($value, ENT_QUOTES, 'UTF-8')."\"/>";
  1395. $sHTMLValue = Dict::Format('UI:DurationForm_Days_Hours_Minutes_Seconds', $sDays, $sHours, $sMinutes, $sSeconds).$sHidden."&nbsp;".$sValidationField;
  1396. $oPage->add_ready_script("$('#{$iId}').bind('update', function(evt, sFormId) { return ToggleDurationField('$iId'); });");
  1397. break;
  1398. case 'Password':
  1399. $aEventsList[] ='validate';
  1400. $aEventsList[] ='keyup';
  1401. $aEventsList[] ='change';
  1402. $sHTMLValue = "<input title=\"$sHelpText\" type=\"password\" size=\"30\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" value=\"".htmlentities($value, ENT_QUOTES, 'UTF-8')."\" id=\"$iId\"/>&nbsp;{$sValidationField}";
  1403. break;
  1404. case 'OQLExpression':
  1405. case 'Text':
  1406. $aEventsList[] ='validate';
  1407. $aEventsList[] ='keyup';
  1408. $aEventsList[] ='change';
  1409. $sEditValue = $oAttDef->GetEditValue($value);
  1410. $aStyles = array();
  1411. $sStyle = '';
  1412. $sWidth = $oAttDef->GetWidth('width', '');
  1413. if (!empty($sWidth))
  1414. {
  1415. $aStyles[] = 'width:'.$sWidth;
  1416. }
  1417. $sHeight = $oAttDef->GetHeight('height', '');
  1418. if (!empty($sHeight))
  1419. {
  1420. $aStyles[] = 'height:'.$sHeight;
  1421. }
  1422. if (count($aStyles) > 0)
  1423. {
  1424. $sStyle = 'style="'.implode('; ', $aStyles).'"';
  1425. }
  1426. if ($oAttDef->GetEditClass() == 'OQLExpression')
  1427. {
  1428. $sTestResId = 'query_res_'.$sFieldPrefix.$sAttCode.$sNameSuffix; //$oPage->GetUniqueId();
  1429. $sBaseUrl = utils::GetAbsoluteUrlAppRoot().'pages/run_query.php?expression=';
  1430. $sInitialUrl = $sBaseUrl.urlencode($sEditValue);
  1431. $sAdditionalStuff = "<a id=\"$sTestResId\" target=\"_blank\" href=\"$sInitialUrl\">".Dict::S('UI:Edit:TestQuery')."</a>";
  1432. $oPage->add_ready_script("$('#$iId').bind('change keyup', function(evt, sFormId) { $('#$sTestResId').attr('href', '$sBaseUrl'+encodeURIComponent($(this).val())); } );");
  1433. }
  1434. else
  1435. {
  1436. $sAdditionalStuff = "";
  1437. }
  1438. // Ok, the text area is drawn here
  1439. $sHTMLValue = "<table><tr><td><textarea class=\"resizable\" title=\"$sHelpText\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" rows=\"8\" cols=\"40\" id=\"$iId\" $sStyle>".htmlentities($sEditValue, ENT_QUOTES, 'UTF-8')."</textarea>$sAdditionalStuff</td><td>{$sValidationField}</td></tr></table>";
  1440. break;
  1441. case 'CaseLog':
  1442. $aStyles = array();
  1443. $sStyle = '';
  1444. $sWidth = $oAttDef->GetWidth('width', '');
  1445. if (!empty($sWidth))
  1446. {
  1447. $aStyles[] = 'width:'.$sWidth;
  1448. }
  1449. $sHeight = $oAttDef->GetHeight('height', '');
  1450. if (!empty($sHeight))
  1451. {
  1452. $aStyles[] = 'height:'.$sHeight;
  1453. }
  1454. if (count($aStyles) > 0)
  1455. {
  1456. $sStyle = 'style="'.implode('; ', $aStyles).'"';
  1457. }
  1458. $sHeader = '<div class="caselog_input_header">&nbsp;'.Dict::S('UI:CaseLogTypeYourTextHere').'</div>';
  1459. $sEditValue = $oAttDef->GetEditValue($value);
  1460. $sPreviousLog = is_object($value) ? $value->GetAsHTML($oPage, true /* bEditMode */, array('AttributeText', 'RenderWikiHtml')) : '';
  1461. $iEntriesCount = is_object($value) ? count($value->GetIndex()) : 0;
  1462. $sHidden = "<input type=\"hidden\" id=\"{$iId}_count\" value=\"$iEntriesCount\"/>"; // To know how many entries the case log already contains
  1463. $sHTMLValue = "<div class=\"caselog\" $sStyle><table style=\"width:100%;\"><tr><td>$sHeader<textarea style=\"border:0;width:100%\" title=\"$sHelpText\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" rows=\"8\" cols=\"40\" id=\"$iId\">".htmlentities($sEditValue, ENT_QUOTES, 'UTF-8')."</textarea>$sPreviousLog</td><td>{$sValidationField}</td></tr></table>$sHidden</div>";
  1464. $oPage->add_ready_script("$('#$iId').bind('keyup change validate', function(evt, sFormId) { return ValidateCaseLogField('$iId', $bMandatory, sFormId) } );"); // Custom validation function
  1465. break;
  1466. case 'HTML':
  1467. $oWidget = new UIHTMLEditorWidget($iId, $sAttCode, $sNameSuffix, $sFieldPrefix, $sHelpText, $sValidationField, $value, $bMandatory);
  1468. $sHTMLValue = $oWidget->Display($oPage, $aArgs);
  1469. break;
  1470. case 'LinkedSet':
  1471. if ($oAttDef->IsIndirect())
  1472. {
  1473. $oWidget = new UILinksWidget($sClass, $sAttCode, $iId, $sNameSuffix, $oAttDef->DuplicatesAllowed(), $aArgs);
  1474. }
  1475. else
  1476. {
  1477. $oWidget = new UILinksWidgetDirect($sClass, $sAttCode, $iId, $sNameSuffix, $aArgs);
  1478. }
  1479. $aEventsList[] ='validate';
  1480. $aEventsList[] ='change';
  1481. $oObj = isset($aArgs['this']) ? $aArgs['this'] : null;
  1482. $sHTMLValue = $oWidget->Display($oPage, $value, array(), $sFormPrefix, $oObj);
  1483. break;
  1484. case 'Document':
  1485. $aEventsList[] ='validate';
  1486. $aEventsList[] ='change';
  1487. $oDocument = $value; // Value is an ormDocument object
  1488. $sFileName = '';
  1489. if (is_object($oDocument))
  1490. {
  1491. $sFileName = $oDocument->GetFileName();
  1492. }
  1493. $iMaxFileSize = utils::ConvertToBytes(ini_get('upload_max_filesize'));
  1494. $sHTMLValue = "<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"$iMaxFileSize\" />\n";
  1495. $sHTMLValue .= "<input name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}[filename]\" type=\"hidden\" id=\"$iId\" \" value=\"".htmlentities($sFileName, ENT_QUOTES, 'UTF-8')."\"/>\n";
  1496. $sHTMLValue .= "<span id=\"name_$iInputId\">$sFileName</span><br/>\n";
  1497. $sHTMLValue .= "<input title=\"$sHelpText\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}[fcontents]\" type=\"file\" id=\"file_$iId\" onChange=\"UpdateFileName('$iId', this.value)\"/>&nbsp;{$sValidationField}\n";
  1498. break;
  1499. case 'StopWatch':
  1500. $sHTMLValue = "The edition of a stopwatch is not allowed!!!";
  1501. break;
  1502. case 'List':
  1503. // Not editable for now...
  1504. $sHTMLValue = '';
  1505. break;
  1506. case 'One Way Password':
  1507. $aEventsList[] ='validate';
  1508. $oWidget = new UIPasswordWidget($sAttCode, $iId, $sNameSuffix);
  1509. $sHTMLValue = $oWidget->Display($oPage, $aArgs);
  1510. // Event list & validation is handled directly by the widget
  1511. break;
  1512. case 'ExtKey':
  1513. $aEventsList[] ='validate';
  1514. $aEventsList[] ='change';
  1515. $oAllowedValues = MetaModel::GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs);
  1516. $sFieldName = $sFieldPrefix.$sAttCode.$sNameSuffix;
  1517. $aExtKeyParams = $aArgs;
  1518. $aExtKeyParams['iFieldSize'] = $oAttDef->GetMaxSize();
  1519. $aExtKeyParams['iMinChars'] = $oAttDef->GetMinAutoCompleteChars();
  1520. $sHTMLValue = UIExtKeyWidget::DisplayFromAttCode($oPage, $sAttCode, $sClass, $oAttDef->GetLabel(), $oAllowedValues, $value, $iId, $bMandatory, $sFieldName, $sFormPrefix, $aExtKeyParams);
  1521. $sHTMLValue .= "<!-- iFlags: $iFlags bMandatory: $bMandatory -->\n";
  1522. break;
  1523. case 'String':
  1524. default:
  1525. $aEventsList[] ='validate';
  1526. // #@# todo - add context information (depending on dimensions)
  1527. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  1528. $iFieldSize = $oAttDef->GetMaxSize();
  1529. if ($aAllowedValues !== null)
  1530. {
  1531. // Discrete list of values, use a SELECT or RADIO buttons depending on the config
  1532. $sDisplayStyle = $oAttDef->GetDisplayStyle();
  1533. switch($sDisplayStyle)
  1534. {
  1535. case 'radio':
  1536. case 'radio_horizontal':
  1537. case 'radio_vertical':
  1538. $sHTMLValue = '';
  1539. $bVertical = ($sDisplayStyle != 'radio_horizontal');
  1540. $sHTMLValue = $oPage->GetRadioButtons($aAllowedValues, $value, $iId, "attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}", $bMandatory, $bVertical, $sValidationField);
  1541. $aEventsList[] ='change';
  1542. break;
  1543. case 'select':
  1544. default:
  1545. $sHTMLValue = "<select title=\"$sHelpText\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" id=\"$iId\">\n";
  1546. $sHTMLValue .= "<option value=\"\">".Dict::S('UI:SelectOne')."</option>\n";
  1547. foreach($aAllowedValues as $key => $display_value)
  1548. {
  1549. if ((count($aAllowedValues) == 1) && ($bMandatory == 'true') )
  1550. {
  1551. // When there is only once choice, select it by default
  1552. $sSelected = ' selected';
  1553. }
  1554. else
  1555. {
  1556. $sSelected = ($value == $key) ? ' selected' : '';
  1557. }
  1558. $sHTMLValue .= "<option value=\"$key\"$sSelected>$display_value</option>\n";
  1559. }
  1560. $sHTMLValue .= "</select>&nbsp;{$sValidationField}\n";
  1561. $aEventsList[] ='change';
  1562. }
  1563. }
  1564. else
  1565. {
  1566. $sHTMLValue = "<input title=\"$sHelpText\" type=\"text\" size=\"30\" maxlength=\"$iFieldSize\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" value=\"".htmlentities($sDisplayValue, ENT_QUOTES, 'UTF-8')."\" id=\"$iId\"/>&nbsp;{$sValidationField}";
  1567. $aEventsList[] ='keyup';
  1568. $aEventsList[] ='change';
  1569. }
  1570. break;
  1571. }
  1572. $sPattern = addslashes($oAttDef->GetValidationPattern()); //'^([0-9]+)$';
  1573. if (!empty($aEventsList))
  1574. {
  1575. $sNullValue = $oAttDef->GetNullValue();
  1576. if (!is_numeric($sNullValue))
  1577. {
  1578. $sNullValue = "'$sNullValue'"; // Add quotes to turn this into a JS string if it's not a number
  1579. }
  1580. $oPage->add_ready_script("$('#$iId').bind('".implode(' ', $aEventsList)."', function(evt, sFormId) { return ValidateField('$iId', '$sPattern', $bMandatory, sFormId, $sNullValue) } );\n"); // Bind to a custom event: validate
  1581. }
  1582. $aDependencies = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that depend on the current one
  1583. if (count($aDependencies) > 0)
  1584. {
  1585. $oPage->add_ready_script("$('#$iId').bind('change', function(evt, sFormId) { return oWizardHelper{$sFormPrefix}.UpdateDependentFields(['".implode("','", $aDependencies)."']) } );\n"); // Bind to a custom event: validate
  1586. }
  1587. }
  1588. return "<div>{$sHTMLValue}</div>";
  1589. }
  1590. public function DisplayModifyForm(WebPage $oPage, $aExtraParams = array())
  1591. {
  1592. self::$iGlobalFormId++;
  1593. $sPrefix = '';
  1594. if (isset($aExtraParams['formPrefix']))
  1595. {
  1596. $sPrefix = $aExtraParams['formPrefix'];
  1597. }
  1598. $aFieldsComments = (isset($aExtraParams['fieldsComments'])) ? $aExtraParams['fieldsComments'] : array();
  1599. $this->m_iFormId = $sPrefix.self::$iGlobalFormId;
  1600. $sClass = get_class($this);
  1601. $oAppContext = new ApplicationContext();
  1602. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1603. $iKey = $this->GetKey();
  1604. $aDetails = array();
  1605. $aFieldsMap = array();
  1606. if (!isset($aExtraParams['action']))
  1607. {
  1608. $sFormAction = $_SERVER['SCRIPT_NAME']; // No parameter in the URL, the only parameter will be the ones passed through the form
  1609. }
  1610. else
  1611. {
  1612. $sFormAction = $aExtraParams['action'];
  1613. }
  1614. // Custom label for the apply button ?
  1615. if (isset($aExtraParams['custom_button']))
  1616. {
  1617. $sApplyButton = $aExtraParams['custom_button'];
  1618. }
  1619. else if ($iKey > 0)
  1620. {
  1621. $sApplyButton = Dict::S('UI:Button:Apply');
  1622. }
  1623. else
  1624. {
  1625. $sApplyButton = Dict::S('UI:Button:Create');
  1626. }
  1627. // Custom operation for the form ?
  1628. if (isset($aExtraParams['custom_operation']))
  1629. {
  1630. $sOperation = $aExtraParams['custom_operation'];
  1631. }
  1632. else if ($iKey > 0)
  1633. {
  1634. $sOperation = 'apply_modify';
  1635. }
  1636. else
  1637. {
  1638. $sOperation = 'apply_new';
  1639. }
  1640. if ($iKey > 0)
  1641. {
  1642. // The object already exists in the database, it's a modification
  1643. $sButtons = "<input id=\"{$sPrefix}_id\" type=\"hidden\" name=\"id\" value=\"$iKey\">\n";
  1644. $sButtons .= "<input type=\"hidden\" name=\"operation\" value=\"{$sOperation}\">\n";
  1645. $sButtons .= "<button type=\"button\" class=\"action cancel\"><span>".Dict::S('UI:Button:Cancel')."</span></button>&nbsp;&nbsp;&nbsp;&nbsp;\n";
  1646. $sButtons .= "<button type=\"submit\" class=\"action\"><span>{$sApplyButton}</span></button>\n";
  1647. }
  1648. else
  1649. {
  1650. // The object does not exist in the database it's a creation
  1651. $sButtons = "<input type=\"hidden\" name=\"operation\" value=\"$sOperation\">\n";
  1652. $sButtons .= "<button type=\"button\" class=\"action cancel\">".Dict::S('UI:Button:Cancel')."</button>&nbsp;&nbsp;&nbsp;&nbsp;\n";
  1653. $sButtons .= "<button type=\"submit\" class=\"action\"><span>{$sApplyButton}</span></button>\n";
  1654. }
  1655. $aTransitions = $this->EnumTransitions();
  1656. if (!isset($aExtraParams['custom_operation']) && count($aTransitions))
  1657. {
  1658. // transitions are displayed only for the standard new/modify actions, not for modify_all or any other case...
  1659. $oSetToCheckRights = DBObjectSet::FromObject($this);
  1660. $aStimuli = Metamodel::EnumStimuli($sClass);
  1661. foreach($aTransitions as $sStimulusCode => $aTransitionDef)
  1662. {
  1663. $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? UserRights::IsStimulusAllowed($sClass, $sStimulusCode, $oSetToCheckRights) : UR_ALLOWED_NO;
  1664. switch($iActionAllowed)
  1665. {
  1666. case UR_ALLOWED_YES:
  1667. $sButtons .= "<button type=\"submit\" name=\"next_action\" value=\"{$sStimulusCode}\" class=\"action\"><span>".$aStimuli[$sStimulusCode]->GetLabel()."</span></button>\n";
  1668. break;
  1669. default:
  1670. // Do nothing
  1671. }
  1672. }
  1673. }
  1674. $sButtonsPosition = MetaModel::GetConfig()->Get('buttons_position');
  1675. $iTransactionId = isset($aExtraParams['transaction_id']) ? $aExtraParams['transaction_id'] : utils::GetNewTransactionId();
  1676. $oPage->SetTransactionId($iTransactionId);
  1677. $oPage->add("<form action=\"$sFormAction\" id=\"form_{$this->m_iFormId}\" enctype=\"multipart/form-data\" method=\"post\" onSubmit=\"return OnSubmit('form_{$this->m_iFormId}');\">\n");
  1678. $sStatesSelection = '';
  1679. if (!isset($aExtraParams['custom_operation']) && $this->IsNew())
  1680. {
  1681. $aInitialStates = MetaModel::EnumInitialStates($sClass);
  1682. //$aInitialStates = array('new' => 'foo', 'closed' => 'bar');
  1683. if (count($aInitialStates) > 1)
  1684. {
  1685. $sStatesSelection = Dict::Format('UI:Create_Class_InState', MetaModel::GetName($sClass)).'<select name="obj_state" class="state_select_'.$this->m_iFormId.'">';
  1686. foreach($aInitialStates as $sStateCode => $sStateData)
  1687. {
  1688. $sSelected = '';
  1689. if ($sStateCode == $this->GetState())
  1690. {
  1691. $sSelected = ' selected';
  1692. }
  1693. $sStatesSelection .= '<option value="'.$sStateCode.'"'.$sSelected.'>'.MetaModel::GetStateLabel($sClass, $sStateCode).'</option>';
  1694. }
  1695. $sStatesSelection .= '</select>';
  1696. $oPage->add_ready_script("$('.state_select_{$this->m_iFormId}').change( function() { oWizardHelper$sPrefix.ReloadObjectCreationForm('form_{$this->m_iFormId}', $(this).val()); } );");
  1697. }
  1698. }
  1699. $sConfirmationMessage = addslashes(Dict::S('UI:NavigateAwayConfirmationMessage'));
  1700. $oPage->add_ready_script(
  1701. <<<EOF
  1702. $(window).unload(function() { return OnUnload('$iTransactionId') } );
  1703. window.onbeforeunload = function() {
  1704. if (!window.bInSubmit && !window.bInCancel)
  1705. {
  1706. return '$sConfirmationMessage';
  1707. }
  1708. // return nothing ! safer for IE
  1709. };
  1710. EOF
  1711. );
  1712. if ($sButtonsPosition != 'bottom')
  1713. {
  1714. // top or both, display the buttons here
  1715. $oPage->p($sStatesSelection);
  1716. $oPage->add($sButtons);
  1717. }
  1718. $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB, $sPrefix);
  1719. $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB);
  1720. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  1721. $aFieldsMap = $this->DisplayBareProperties($oPage, true, $sPrefix, $aExtraParams);
  1722. if ($iKey > 0)
  1723. {
  1724. $aFieldsMap['id'] = $sPrefix.'_id';
  1725. }
  1726. // Now display the relations, one tab per relation
  1727. if (!isset($aExtraParams['noRelations']))
  1728. {
  1729. $this->DisplayBareRelations($oPage, true); // Edit mode
  1730. }
  1731. $oPage->SetCurrentTab('');
  1732. $oPage->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  1733. $oPage->add("<input type=\"hidden\" name=\"transaction_id\" value=\"$iTransactionId\">\n");
  1734. foreach($aExtraParams as $sName => $value)
  1735. {
  1736. $oPage->add("<input type=\"hidden\" name=\"$sName\" value=\"$value\">\n");
  1737. }
  1738. $oPage->add($oAppContext->GetForForm());
  1739. if ($sButtonsPosition != 'top')
  1740. {
  1741. // bottom or both: display the buttons here
  1742. $oPage->p($sStatesSelection);
  1743. $oPage->add($sButtons);
  1744. }
  1745. // Hook the cancel button via jQuery so that it can be unhooked easily as well if needed
  1746. $sDefaultUrl = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=cancel&'.$oAppContext->GetForLink();
  1747. $oPage->add_ready_script("$('#form_{$this->m_iFormId} button.cancel').click( function() { BackToDetails('$sClass', $iKey, '$sDefaultUrl')} );");
  1748. $oPage->add("</form>\n");
  1749. $iFieldsCount = count($aFieldsMap);
  1750. $sJsonFieldsMap = json_encode($aFieldsMap);
  1751. $sState = $this->GetState();
  1752. $oPage->add_script(
  1753. <<<EOF
  1754. // Create the object once at the beginning of the page...
  1755. var oWizardHelper$sPrefix = new WizardHelper('$sClass', '$sPrefix', '$sState');
  1756. oWizardHelper$sPrefix.SetFieldsMap($sJsonFieldsMap);
  1757. oWizardHelper$sPrefix.SetFieldsCount($iFieldsCount);
  1758. EOF
  1759. );
  1760. $oPage->add_ready_script(
  1761. <<<EOF
  1762. oWizardHelper$sPrefix.UpdateWizard();
  1763. // Starts the validation when the page is ready
  1764. CheckFields('form_{$this->m_iFormId}', false);
  1765. EOF
  1766. );
  1767. }
  1768. public static function DisplayCreationForm(WebPage $oPage, $sClass, $oObjectToClone = null, $aArgs = array(), $aExtraParams = array())
  1769. {
  1770. $oAppContext = new ApplicationContext();
  1771. $sClass = ($oObjectToClone == null) ? $sClass : get_class($oObjectToClone);
  1772. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1773. $aStates = MetaModel::EnumStates($sClass);
  1774. $sStatesSelection = '';
  1775. if ($oObjectToClone == null)
  1776. {
  1777. $oObj = MetaModel::NewObject($sClass);
  1778. if (!empty($sStateAttCode))
  1779. {
  1780. $sTargetState = MetaModel::GetDefaultState($sClass);
  1781. $oObj->Set($sStateAttCode, $sTargetState);
  1782. }
  1783. }
  1784. else
  1785. {
  1786. $oObj = clone $oObjectToClone;
  1787. }
  1788. // Pre-fill the object with default values, when there is only on possible choice
  1789. // AND the field is mandatory (otherwise there is always the possiblity to let it empty)
  1790. $aArgs['this'] = $oObj;
  1791. $aDetailsList = self::FLattenZList(MetaModel::GetZListItems($sClass, 'details'));
  1792. // Order the fields based on their dependencies
  1793. $aDeps = array();
  1794. foreach($aDetailsList as $sAttCode)
  1795. {
  1796. $aDeps[$sAttCode] = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode);
  1797. }
  1798. $aList = self::OrderDependentFields($aDeps);
  1799. // Now fill-in the fields with default/supplied values
  1800. foreach($aList as $sAttCode)
  1801. {
  1802. if (isset($aArgs['default'][$sAttCode]))
  1803. {
  1804. $oObj->Set($sAttCode, $aArgs['default'][$sAttCode]);
  1805. }
  1806. else
  1807. {
  1808. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1809. // If the field is mandatory, set it to the only possible value
  1810. $iFlags = $oObj->GetInitialStateAttributeFlags($sAttCode);
  1811. if ((!$oAttDef->IsNullAllowed()) || ($iFlags & OPT_ATT_MANDATORY))
  1812. {
  1813. if ($oAttDef->IsExternalKey())
  1814. {
  1815. $oAllowedValues = MetaModel::GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs);
  1816. if ($oAllowedValues->Count() == 1)
  1817. {
  1818. $oRemoteObj = $oAllowedValues->Fetch();
  1819. $oObj->Set($sAttCode, $oRemoteObj->GetKey());
  1820. }
  1821. }
  1822. else
  1823. {
  1824. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  1825. if (count($aAllowedValues) == 1)
  1826. {
  1827. $aValues = array_keys($aAllowedValues);
  1828. $oObj->Set($sAttCode, $aValues[0]);
  1829. }
  1830. }
  1831. }
  1832. }
  1833. }
  1834. return $oObj->DisplayModifyForm( $oPage, $aExtraParams);
  1835. }
  1836. public static function ProcessZlist($aList, $aDetails, $sCurrentTab, $sCurrentCol, $sCurrentSet)
  1837. {
  1838. //echo "<pre>ZList: ";
  1839. //print_r($aList);
  1840. //echo "</pre>\n";
  1841. $index = 0;
  1842. foreach($aList as $sKey => $value)
  1843. {
  1844. if (is_array($value))
  1845. {
  1846. if (preg_match('/^(.*):(.*)$/U', $sKey, $aMatches))
  1847. {
  1848. $sCode = $aMatches[1];
  1849. $sName = $aMatches[2];
  1850. switch($sCode)
  1851. {
  1852. case 'tab':
  1853. //echo "<p>Found a tab: $sName ($sKey)</p>\n";
  1854. if(!isset($aDetails[$sName]))
  1855. {
  1856. $aDetails[$sName] = array('col1' => array());
  1857. }
  1858. $aDetails = self::ProcessZlist($value, $aDetails, $sName, 'col1', '');
  1859. break;
  1860. case 'fieldset':
  1861. //echo "<p>Found a fieldset: $sName ($sKey)</p>\n";
  1862. if(!isset($aDetailsStruct[$sCurrentTab][$sCurrentCol][$sName]))
  1863. {
  1864. $aDetails[$sCurrentTab][$sCurrentCol][$sName] = array();
  1865. }
  1866. $aDetails = self::ProcessZlist($value, $aDetails, $sCurrentTab, $sCurrentCol, $sName);
  1867. break;
  1868. default:
  1869. case 'col':
  1870. //echo "<p>Found a column: $sName ($sKey)</p>\n";
  1871. if(!isset($aDetails[$sCurrentTab][$sName]))
  1872. {
  1873. $aDetails[$sCurrentTab][$sName] = array();
  1874. }
  1875. $aDetails = self::ProcessZlist($value, $aDetails, $sCurrentTab, $sName, '');
  1876. break;
  1877. }
  1878. }
  1879. }
  1880. else
  1881. {
  1882. //echo "<p>Scalar value: $value, in [$sCurrentTab][$sCurrentCol][$sCurrentSet][]</p>\n";
  1883. if (empty($sCurrentSet))
  1884. {
  1885. $aDetails[$sCurrentTab][$sCurrentCol]['_'.$index][] = $value;
  1886. }
  1887. else
  1888. {
  1889. $aDetails[$sCurrentTab][$sCurrentCol][$sCurrentSet][] = $value;
  1890. }
  1891. }
  1892. $index++;
  1893. }
  1894. return $aDetails;
  1895. }
  1896. static function FlattenZList($aList)
  1897. {
  1898. $aResult = array();
  1899. foreach($aList as $value)
  1900. {
  1901. if (!is_array($value))
  1902. {
  1903. $aResult[] = $value;
  1904. }
  1905. else
  1906. {
  1907. $aResult = array_merge($aResult,self::FlattenZList($value));
  1908. }
  1909. }
  1910. return $aResult;
  1911. }
  1912. protected function GetFieldAsHtml($sClass, $sAttCode, $sStateAttCode)
  1913. {
  1914. $retVal = null;
  1915. if ($this->IsNew())
  1916. {
  1917. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  1918. }
  1919. else
  1920. {
  1921. $iFlags = $this->GetAttributeFlags($sAttCode);
  1922. }
  1923. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1924. if ( (!$oAttDef->IsLinkSet()) && (($iFlags & OPT_ATT_HIDDEN) == 0) )
  1925. {
  1926. // The field is visible in the current state of the object
  1927. if ($sStateAttCode == $sAttCode)
  1928. {
  1929. // Special display for the 'state' attribute itself
  1930. $sDisplayValue = $this->GetStateLabel();
  1931. }
  1932. else if ($oAttDef->GetEditClass() == 'Document')
  1933. {
  1934. $oDocument = $this->Get($sAttCode);
  1935. $sDisplayValue = $this->GetAsHTML($sAttCode);
  1936. $sDisplayValue .= "<br/>".Dict::Format('UI:OpenDocumentInNewWindow_', $oDocument->GetDisplayLink(get_class($this), $this->GetKey(), $sAttCode)).", \n";
  1937. $sDisplayValue .= "<br/>".Dict::Format('UI:DownloadDocument_', $oDocument->GetDownloadLink(get_class($this), $this->GetKey(), $sAttCode)).", \n";
  1938. }
  1939. else
  1940. {
  1941. $sDisplayValue = $this->GetAsHTML($sAttCode);
  1942. }
  1943. $retVal = array('label' => '<span title="'.MetaModel::GetDescription($sClass, $sAttCode).'">'.MetaModel::GetLabel($sClass, $sAttCode).'</span>', 'value' => $sDisplayValue);
  1944. }
  1945. return $retVal;
  1946. }
  1947. /**
  1948. * Displays a blob document *inline* (if possible, depending on the type of the document)
  1949. * @return string
  1950. */
  1951. public function DisplayDocumentInline(WebPage $oPage, $sAttCode)
  1952. {
  1953. $oDoc = $this->Get($sAttCode);
  1954. $sClass = get_class($this);
  1955. $Id = $this->GetKey();
  1956. switch ($oDoc->GetMainMimeType())
  1957. {
  1958. case 'text':
  1959. case 'html':
  1960. $data = $oDoc->GetData();
  1961. switch($oDoc->GetMimeType())
  1962. {
  1963. case 'text/html':
  1964. case 'text/xml':
  1965. $oPage->add("<iframe id='preview_$sAttCode' src=\"".utils::GetAbsoluteUrlAppRoot()."pages/ajax.render.php?operation=display_document&class=$sClass&id=$Id&field=$sAttCode\" width=\"100%\" height=\"400\">Loading...</iframe>\n");
  1966. break;
  1967. default:
  1968. $oPage->add("<pre>".htmlentities(MyHelpers::beautifulstr($data, 1000, true), ENT_QUOTES, 'UTF-8')."</pre>\n");
  1969. }
  1970. break;
  1971. case 'application':
  1972. switch($oDoc->GetMimeType())
  1973. {
  1974. case 'application/pdf':
  1975. $oPage->add("<iframe id='preview_$sAttCode' src=\"".utils::GetAbsoluteUrlAppRoot()."pages/ajax.render.php?operation=display_document&class=$sClass&id=$Id&field=$sAttCode\" width=\"100%\" height=\"400\">Loading...</iframe>\n");
  1976. break;
  1977. default:
  1978. $oPage->add(Dict::S('UI:Document:NoPreview'));
  1979. }
  1980. break;
  1981. case 'image':
  1982. $oPage->add("<img src=\"".utils::GetAbsoluteUrlAppRoot()."pages/ajax.render.php?operation=display_document&class=$sClass&id=$Id&field=$sAttCode\" />\n");
  1983. break;
  1984. default:
  1985. $oPage->add(Dict::S('UI:Document:NoPreview'));
  1986. }
  1987. }
  1988. // $m_highlightComparison[previous][new] => next value
  1989. protected static $m_highlightComparison = array(
  1990. HILIGHT_CLASS_CRITICAL => array(
  1991. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  1992. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_CRITICAL,
  1993. HILIGHT_CLASS_OK => HILIGHT_CLASS_CRITICAL,
  1994. HILIGHT_CLASS_NONE => HILIGHT_CLASS_CRITICAL,
  1995. ),
  1996. HILIGHT_CLASS_WARNING => array(
  1997. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  1998. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING,
  1999. HILIGHT_CLASS_OK => HILIGHT_CLASS_WARNING,
  2000. HILIGHT_CLASS_NONE => HILIGHT_CLASS_WARNING,
  2001. ),
  2002. HILIGHT_CLASS_OK => array(
  2003. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  2004. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING,
  2005. HILIGHT_CLASS_OK => HILIGHT_CLASS_OK,
  2006. HILIGHT_CLASS_NONE => HILIGHT_CLASS_OK,
  2007. ),
  2008. HILIGHT_CLASS_NONE => array(
  2009. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  2010. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING,
  2011. HILIGHT_CLASS_OK => HILIGHT_CLASS_OK,
  2012. HILIGHT_CLASS_NONE => HILIGHT_CLASS_NONE,
  2013. ),
  2014. );
  2015. /**
  2016. * This function returns a 'hilight' CSS class, used to hilight a given row in a table
  2017. * There are currently (i.e defined in the CSS) 4 possible values HILIGHT_CLASS_CRITICAL,
  2018. * HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  2019. * To Be overridden by derived classes
  2020. * @param void
  2021. * @return String The desired higlight class for the object/row
  2022. */
  2023. public function GetHilightClass()
  2024. {
  2025. // Possible return values are:
  2026. // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  2027. $current = HILIGHT_CLASS_NONE; // Not hilighted by default
  2028. // Invoke extensions before the deletion (the deletion will do some cleanup and we might loose some information
  2029. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  2030. {
  2031. $new = $oExtensionInstance->GetHilightClass($this);
  2032. @$current = self::$m_highlightComparison[$current][$new];
  2033. }
  2034. return $current;
  2035. }
  2036. /**
  2037. * Re-order the fields based on their inter-dependencies
  2038. * @params hash @aFields field_code => array_of_depencies
  2039. * @return array Ordered array of fields or throws an exception
  2040. */
  2041. public static function OrderDependentFields($aFields)
  2042. {
  2043. $bCircular = false;
  2044. $aResult = array();
  2045. $iCount = 0;
  2046. do
  2047. {
  2048. $bSet = false;
  2049. $iCount++;
  2050. foreach($aFields as $sFieldCode => $aDeps)
  2051. {
  2052. foreach($aDeps as $key => $sDependency)
  2053. {
  2054. if (in_array($sDependency, $aResult))
  2055. {
  2056. // Dependency is resolved, remove it
  2057. unset($aFields[$sFieldCode][$key]);
  2058. }
  2059. }
  2060. if (count($aFields[$sFieldCode]) == 0)
  2061. {
  2062. // No more pending depencies for this field, add it to the list
  2063. $aResult[] = $sFieldCode;
  2064. unset($aFields[$sFieldCode]);
  2065. $bSet = true;
  2066. }
  2067. }
  2068. }
  2069. while($bSet && (count($aFields) > 0));
  2070. if (count($aFields) > 0)
  2071. {
  2072. $sMessage = "Error: Circular dependencies between the fields (or field missing in ZList) ! <pre>".print_r($aFields, true)."</pre>";
  2073. throw(new Exception($sMessage));
  2074. }
  2075. return $aResult;
  2076. }
  2077. /**
  2078. * Get the list of actions to be displayed as 'shortcuts' (i.e buttons) instead of inside the Actions popup menu
  2079. * @param $sFinalClass string The actual class of the objects for which to display the menu
  2080. * @return Array the list of menu codes (i.e dictionary entries) that can be displayed as shortcuts next to the actions menu
  2081. */
  2082. public static function GetShortcutActions($sFinalClass)
  2083. {
  2084. $sShortcutActions = MetaModel::GetConfig()->Get('shortcut_actions');
  2085. $aShortcutActions = explode(',', $sShortcutActions);
  2086. return $aShortcutActions;
  2087. }
  2088. /**
  2089. * Maps the given context parameter name to the appropriate filter/search code for this class
  2090. * @param string $sContextParam Name of the context parameter, i.e. 'org_id'
  2091. * @return string Filter code, i.e. 'customer_id'
  2092. */
  2093. public static function MapContextParam($sContextParam)
  2094. {
  2095. if ($sContextParam == 'menu')
  2096. {
  2097. return null;
  2098. }
  2099. else
  2100. {
  2101. return $sContextParam;
  2102. }
  2103. }
  2104. /**
  2105. * Updates the object from a flat array of values
  2106. * @param $aAttList array $aAttList array of attcode
  2107. * @param $aErrors array Returns information about slave attributes
  2108. * @param $sTargetState string Target state for which to evaluate the writeable attributes (=current state is empty)
  2109. * @return array of attcodes that can be used for writing on the current object
  2110. */
  2111. public function GetWriteableAttList($aAttList, &$aErrors, $sTargetState = '')
  2112. {
  2113. if (!is_array($aAttList))
  2114. {
  2115. $aAttList = $this->FlattenZList(MetaModel::GetZListItems(get_class($this), 'details'));
  2116. // Special case to process the case log, if any...
  2117. // WARNING: if you change this also check the functions DisplayModifyForm and DisplayCaseLog
  2118. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  2119. {
  2120. if ($this->IsNew())
  2121. {
  2122. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  2123. }
  2124. else
  2125. {
  2126. $aVoid = array();
  2127. $iFlags = $this->GetAttributeFlags($sAttCode, $aVoid, $sTargetState);
  2128. }
  2129. if ($oAttDef instanceof AttributeCaseLog)
  2130. {
  2131. if (!($iFlags & (OPT_ATT_HIDDEN|OPT_ATT_SLAVE|OPT_ATT_READONLY)))
  2132. {
  2133. // The case log is editable, append it to the list of fields to retrieve
  2134. $aAttList[] = $sAttCode;
  2135. }
  2136. }
  2137. }
  2138. }
  2139. $aWriteableAttList = array();
  2140. foreach($aAttList as $sAttCode)
  2141. {
  2142. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2143. if ($this->IsNew())
  2144. {
  2145. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  2146. }
  2147. else
  2148. {
  2149. $aVoid = array();
  2150. $iFlags = $this->GetAttributeFlags($sAttCode, $aVoid, $sTargetState);
  2151. }
  2152. if ($oAttDef->IsWritable())
  2153. {
  2154. if ( $iFlags & (OPT_ATT_HIDDEN | OPT_ATT_READONLY))
  2155. {
  2156. // Non-visible, or read-only attribute, do nothing
  2157. }
  2158. elseif($iFlags & OPT_ATT_SLAVE)
  2159. {
  2160. $aErrors[$sAttCode] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $oAttDef->GetLabel());
  2161. }
  2162. else
  2163. {
  2164. $aWriteableAttList[$sAttCode] = $oAttDef;
  2165. }
  2166. }
  2167. }
  2168. return $aWriteableAttList;
  2169. }
  2170. /**
  2171. * Updates the object from a flat array of values
  2172. * @param string $aValues array of attcode => scalar or array (N-N links)
  2173. * @return void
  2174. */
  2175. public function UpdateObjectFromArray($aValues)
  2176. {
  2177. foreach($aValues as $sAttCode => $value)
  2178. {
  2179. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2180. if ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect())
  2181. {
  2182. $aLinks = $value;
  2183. $sLinkedClass = $oAttDef->GetLinkedClass();
  2184. $sExtKeyToRemote = $oAttDef->GetExtKeyToRemote();
  2185. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  2186. $oLinkedSet = DBObjectSet::FromScratch($sLinkedClass);
  2187. if (is_array($aLinks))
  2188. {
  2189. foreach($aLinks as $id => $aData)
  2190. {
  2191. if (is_numeric($id))
  2192. {
  2193. if ($id < 0)
  2194. {
  2195. // New link to be created, the opposite of the id (-$id) is the ID of the remote object
  2196. $oLink = MetaModel::NewObject($sLinkedClass);
  2197. $oLink->Set($sExtKeyToRemote, -$id);
  2198. $oLink->Set($sExtKeyToMe, $this->GetKey());
  2199. }
  2200. else
  2201. {
  2202. // Existing link, potentially to be updated...
  2203. $oLink = MetaModel::GetObject($sLinkedClass, $id);
  2204. }
  2205. // Now populate the attributes
  2206. foreach($aData as $sName => $value)
  2207. {
  2208. if (MetaModel::IsValidAttCode($sLinkedClass, $sName))
  2209. {
  2210. $oLinkAttDef = MetaModel::GetAttributeDef($sLinkedClass, $sName);
  2211. if ($oLinkAttDef->IsWritable())
  2212. {
  2213. $oLink->Set($sName, $value);
  2214. }
  2215. }
  2216. }
  2217. $oLinkedSet->AddObject($oLink);
  2218. }
  2219. }
  2220. }
  2221. $this->Set($sAttCode, $oLinkedSet);
  2222. }
  2223. elseif ($oAttDef->GetEditClass() == 'Document')
  2224. {
  2225. // There should be an uploaded file with the named attr_<attCode>
  2226. $oDocument = $value['fcontents'];
  2227. if (!$oDocument->IsEmpty())
  2228. {
  2229. // A new file has been uploaded
  2230. $this->Set($sAttCode, $oDocument);
  2231. }
  2232. }
  2233. elseif ($oAttDef->GetEditClass() == 'One Way Password')
  2234. {
  2235. // Check if the password was typed/changed
  2236. $aPwdData = $value;
  2237. if (!is_null($aPwdData) && $aPwdData['changed'])
  2238. {
  2239. // The password has been changed or set
  2240. $this->Set($sAttCode, $aPwdData['value']);
  2241. }
  2242. }
  2243. elseif ($oAttDef->GetEditClass() == 'Duration')
  2244. {
  2245. $aDurationData = $value;
  2246. if (!is_array($aDurationData)) continue;
  2247. $iValue = (((24*$aDurationData['d'])+$aDurationData['h'])*60 +$aDurationData['m'])*60 + $aDurationData['s'];
  2248. $this->Set($sAttCode, $iValue);
  2249. $previousValue = $this->Get($sAttCode);
  2250. if ($previousValue !== $iValue)
  2251. {
  2252. $this->Set($sAttCode, $iValue);
  2253. }
  2254. }
  2255. else if (($oAttDef->GetEditClass() == 'LinkedSet') && !$oAttDef->IsIndirect() && ($oAttDef->GetEditMode() == LINKSET_EDITMODE_INPLACE))
  2256. {
  2257. $oLinkset = $this->Get($sAttCode);
  2258. $sLinkedClass = $oLinkset->GetClass();
  2259. $aObjSet = array();
  2260. $oLinkset->Rewind();
  2261. $bModified = false;
  2262. while($oLink = $oLinkset->Fetch())
  2263. {
  2264. if (in_array($oLink->GetKey(), $value['to_be_deleted']))
  2265. {
  2266. // The link is to be deleted, don't copy it in the array
  2267. $bModified = true;
  2268. }
  2269. else
  2270. {
  2271. $aObjSet[] = $oLink;
  2272. }
  2273. }
  2274. if (array_key_exists('to_be_created', $value) && (count($value['to_be_created']) > 0))
  2275. {
  2276. // Now handle the lniks to be created
  2277. foreach($value['to_be_created'] as $aData)
  2278. {
  2279. $sSubClass = $aData['class'];
  2280. if ( ($sLinkedClass == $sSubClass) || (is_subclass_of($sSubClass, $sLinkedClass)) )
  2281. {
  2282. $aObjData = $aData['data'];
  2283. $oLink = new $sSubClass;
  2284. $oLink->UpdateObjectFromArray($aObjData);
  2285. $aObjSet[] = $oLink;
  2286. $bModified = true;
  2287. }
  2288. }
  2289. }
  2290. if ($bModified)
  2291. {
  2292. $oNewSet = DBObjectSet::FromArray($oLinkset->GetClass(), $aObjSet);
  2293. $this->Set($sAttCode, $oNewSet);
  2294. }
  2295. }
  2296. else
  2297. {
  2298. if (!is_null($value))
  2299. {
  2300. $aAttributes[$sAttCode] = trim($value);
  2301. $previousValue = $this->Get($sAttCode);
  2302. if ($previousValue !== $aAttributes[$sAttCode])
  2303. {
  2304. $this->Set($sAttCode, $aAttributes[$sAttCode]);
  2305. }
  2306. }
  2307. }
  2308. }
  2309. }
  2310. /**
  2311. * Updates the object from the POSTed parameters (form)
  2312. */
  2313. public function UpdateObjectFromPostedForm($sFormPrefix = '', $aAttList = null, $sTargetState = '')
  2314. {
  2315. if (is_null($aAttList))
  2316. {
  2317. $aAttList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
  2318. }
  2319. $aValues = array();
  2320. foreach($aAttList as $sAttCode)
  2321. {
  2322. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2323. if ($oAttDef->GetEditClass() == 'Document')
  2324. {
  2325. $value = array('fcontents' => utils::ReadPostedDocument("attr_{$sFormPrefix}{$sAttCode}", 'fcontents'));
  2326. }
  2327. else if (($oAttDef->GetEditClass() == 'LinkedSet') && !$oAttDef->IsIndirect() && ($oAttDef->GetEditMode() == LINKSET_EDITMODE_INPLACE))
  2328. {
  2329. $aRawToBeCreated = json_decode(utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}_tbc", '{}', 'raw_data'), true);
  2330. $aToBeCreated = array();
  2331. foreach($aRawToBeCreated as $aData)
  2332. {
  2333. $sSubFormPrefix = $aData['formPrefix'];
  2334. $sObjClass = $aData['class'];
  2335. $aObjData = array();
  2336. foreach($aData as $sKey => $value)
  2337. {
  2338. if (preg_match("/^attr_$sSubFormPrefix(.*)$/", $sKey, $aMatches))
  2339. {
  2340. $aObjData[$aMatches[1]] = $value;
  2341. }
  2342. }
  2343. $aToBeCreated[] = array('class' => $sObjClass, 'data' => $aObjData);
  2344. }
  2345. $value = array('to_be_created' => $aToBeCreated,
  2346. 'to_be_deleted' => json_decode(utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}_tbd", '[]', 'raw_data'), true) );
  2347. }
  2348. else
  2349. {
  2350. $value = utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}", null, 'raw_data');
  2351. }
  2352. if (!is_null($value))
  2353. {
  2354. $aValues[$sAttCode] = $value;
  2355. }
  2356. }
  2357. $aErrors = array();
  2358. $aFinalValues = array();
  2359. foreach($this->GetWriteableAttList(array_keys($aValues), $aErrors, $sTargetState) as $sAttCode => $oAttDef)
  2360. {
  2361. $aFinalValues[$sAttCode] = $aValues[$sAttCode];
  2362. }
  2363. $this->UpdateObjectFromArray($aFinalValues);
  2364. // Invoke extensions after the update of the object from the form
  2365. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  2366. {
  2367. $oExtensionInstance->OnFormSubmit($this, $sFormPrefix);
  2368. }
  2369. return $aErrors;
  2370. }
  2371. /**
  2372. * Updates the object from a given page argument
  2373. */
  2374. public function UpdateObjectFromArg($sArgName, $aAttList = null, $sTargetState = '')
  2375. {
  2376. if (is_null($aAttList))
  2377. {
  2378. $aAttList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
  2379. }
  2380. $aRawValues = utils::ReadParam($sArgName, array(), '', 'raw_data');
  2381. $aValues = array();
  2382. foreach($aAttList as $sAttCode)
  2383. {
  2384. if (isset($aRawValues[$sAttCode]))
  2385. {
  2386. $aValues[$sAttCode] = $aRawValues[$sAttCode];
  2387. }
  2388. }
  2389. $aErrors = array();
  2390. $aFinalValues = array();
  2391. foreach($this->GetWriteableAttList(array_keys($aValues), $aErrors, $sTargetState) as $sAttCode => $oAttDef)
  2392. {
  2393. $aFinalValues[$sAttCode] = $aValues[$sAttCode];
  2394. }
  2395. $this->UpdateObjectFromArray($aFinalValues);
  2396. return $aErrors;
  2397. }
  2398. protected function DBInsertTracked_Internal($bDoNotReload = false)
  2399. {
  2400. $res = parent::DBInsertTracked_Internal($bDoNotReload);
  2401. // Invoke extensions after insertion (the object must exist, have an id, etc.)
  2402. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2403. {
  2404. $oExtensionInstance->OnDBInsert($this, self::GetCurrentChange());
  2405. }
  2406. return $res;
  2407. }
  2408. protected function DBCloneTracked_Internal($newKey = null)
  2409. {
  2410. $oNewObj = parent::DBCloneTracked_Internal($newKey);
  2411. // Invoke extensions after insertion (the object must exist, have an id, etc.)
  2412. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2413. {
  2414. $oExtensionInstance->OnDBInsert($oNewObj, self::GetCurrentChange());
  2415. }
  2416. return $oNewObj;
  2417. }
  2418. protected function DBUpdateTracked_Internal()
  2419. {
  2420. $res = parent::DBUpdateTracked_Internal();
  2421. // Invoke extensions after the update (could be before)
  2422. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2423. {
  2424. $oExtensionInstance->OnDBUpdate($this, self::GetCurrentChange());
  2425. }
  2426. return $res;
  2427. }
  2428. protected static function BulkUpdateTracked_Internal(DBObjectSearch $oFilter, array $aValues)
  2429. {
  2430. // Todo - invoke the extension
  2431. return parent::BulkUpdateTracked_Internal($oFilter, $aValues);
  2432. }
  2433. protected function DBDeleteTracked_Internal(&$oDeletionPlan = null)
  2434. {
  2435. // Invoke extensions before the deletion (the deletion will do some cleanup and we might loose some information
  2436. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2437. {
  2438. $oExtensionInstance->OnDBDelete($this, self::GetCurrentChange());
  2439. }
  2440. return parent::DBDeleteTracked_Internal($oDeletionPlan);
  2441. }
  2442. public function IsModified()
  2443. {
  2444. if (parent::IsModified())
  2445. {
  2446. return true;
  2447. }
  2448. // Plugins
  2449. //
  2450. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2451. {
  2452. if ($oExtensionInstance->OnIsModified($this))
  2453. {
  2454. return true;
  2455. }
  2456. }
  2457. }
  2458. public function DoCheckToWrite()
  2459. {
  2460. parent::DoCheckToWrite();
  2461. // Plugins
  2462. //
  2463. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2464. {
  2465. $aNewIssues = $oExtensionInstance->OnCheckToWrite($this);
  2466. if (count($aNewIssues) > 0)
  2467. {
  2468. $this->m_aCheckIssues = array_merge($this->m_aCheckIssues, $aNewIssues);
  2469. }
  2470. }
  2471. // User rights
  2472. //
  2473. $aChanges = $this->ListChanges();
  2474. if (count($aChanges) > 0)
  2475. {
  2476. $aForbiddenFields = array();
  2477. foreach ($this->ListChanges() as $sAttCode => $value)
  2478. {
  2479. $bUpdateAllowed = UserRights::IsActionAllowedOnAttribute(get_class($this), $sAttCode, UR_ACTION_MODIFY, DBObjectSet::FromObject($this));
  2480. if (!$bUpdateAllowed)
  2481. {
  2482. $oAttCode = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2483. $aForbiddenFields[] = $oAttCode->GetLabel();
  2484. }
  2485. }
  2486. if (count($aForbiddenFields) > 0)
  2487. {
  2488. // Security issue
  2489. $this->m_bSecurityIssue = true;
  2490. $this->m_aCheckIssues[] = Dict::Format('UI:Delete:NotAllowedToUpdate_Fields',implode(', ', $aForbiddenFields));
  2491. }
  2492. }
  2493. }
  2494. protected function DoCheckToDelete(&$oDeletionPlan)
  2495. {
  2496. parent::DoCheckToDelete($oDeletionPlan);
  2497. // Plugins
  2498. //
  2499. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2500. {
  2501. $aNewIssues = $oExtensionInstance->OnCheckToDelete($this);
  2502. if (count($aNewIssues) > 0)
  2503. {
  2504. $this->m_aDeleteIssues = array_merge($this->m_aDeleteIssues, $aNewIssues);
  2505. }
  2506. }
  2507. // User rights
  2508. //
  2509. $bDeleteAllowed = UserRights::IsActionAllowed(get_class($this), UR_ACTION_DELETE, DBObjectSet::FromObject($this));
  2510. if (!$bDeleteAllowed)
  2511. {
  2512. // Security issue
  2513. $this->m_bSecurityIssue = true;
  2514. $this->m_aDeleteIssues[] = Dict::S('UI:Delete:NotAllowedToDelete');
  2515. }
  2516. }
  2517. /**
  2518. * Special display where the case log uses the whole "screen" at the bottom of the "Properties" tab
  2519. */
  2520. public function DisplayCaseLog(WebPage $oPage, $sAttCode, $sComment = '', $sPrefix = '', $bEditMode = false)
  2521. {
  2522. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  2523. $sClass = get_class($this);
  2524. if ($this->IsNew())
  2525. {
  2526. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  2527. }
  2528. else
  2529. {
  2530. $iFlags = $this->GetAttributeFlags($sAttCode);
  2531. }
  2532. if ( $iFlags & OPT_ATT_HIDDEN)
  2533. {
  2534. // The case log is hidden do nothing
  2535. }
  2536. else
  2537. {
  2538. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2539. $sInputId = $this->m_iFormId.'_'.$sAttCode;
  2540. if ((!$bEditMode) || ($iFlags & (OPT_ATT_READONLY|OPT_ATT_SLAVE)))
  2541. {
  2542. // Check if the attribute is not read-only because of a synchro...
  2543. $aReasons = array();
  2544. $sSynchroIcon = '';
  2545. if ($iFlags & OPT_ATT_SLAVE)
  2546. {
  2547. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  2548. $sSynchroIcon = "&nbsp;<img id=\"synchro_$sInputId\" src=\"../images/transp-lock.png\" style=\"vertical-align:middle\"/>";
  2549. $sTip = '';
  2550. foreach($aReasons as $aRow)
  2551. {
  2552. $sTip .= "<p>Synchronized with {$aRow['name']} - {$aRow['description']}</p>";
  2553. }
  2554. $oPage->add_ready_script("$('#synchro_$sInputId').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );");
  2555. }
  2556. // Attribute is read-only
  2557. $sHTMLValue = $this->GetAsHTML($sAttCode);
  2558. $sHTMLValue .= '<input type="hidden" id="'.$sInputId.'" name="attr_'.$sPrefix.$sAttCode.'" value="'.htmlentities($this->Get($sAttCode), ENT_QUOTES, 'UTF-8').'"/>';
  2559. $aFieldsMap[$sAttCode] = $sInputId;
  2560. $sComment .= $sSynchroIcon;
  2561. }
  2562. else
  2563. {
  2564. $sValue = $this->Get($sAttCode);
  2565. $sDisplayValue = $this->GetEditValue($sAttCode);
  2566. $aArgs = array('this' => $this, 'formPrefix' => $sPrefix);
  2567. $sHTMLValue = '';
  2568. if ($sComment != '')
  2569. {
  2570. $sHTMLValue = '<span>'.$sComment.'</span><br/>';
  2571. }
  2572. $sHTMLValue .= "<span id=\"field_{$sInputId}\">".self::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $sValue, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).'</span>';
  2573. $aFieldsMap[$sAttCode] = $sInputId;
  2574. }
  2575. //$aVal = array('label' => '<span title="'.$oAttDef->GetDescription().'">'.$oAttDef->GetLabel().'</span>', 'value' => $sHTMLValue, 'comments' => $sComments, 'infos' => $sInfos);
  2576. $oPage->add('<fieldset><legend>'.$oAttDef->GetLabel().'</legend>');
  2577. $oPage->add($sHTMLValue);
  2578. $oPage->add('</fieldset>');
  2579. }
  2580. }
  2581. public function GetExpectedAttributes($sCurrentState, $sStimulus, $bOnlyNewOnes)
  2582. {
  2583. $aTransitions = $this->EnumTransitions();
  2584. $aStimuli = MetaModel::EnumStimuli(get_class($this));
  2585. if (!isset($aTransitions[$sStimulus]))
  2586. {
  2587. // Invalid stimulus
  2588. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  2589. }
  2590. $aTransition = $aTransitions[$sStimulus];
  2591. $sTargetState = $aTransition['target_state'];
  2592. $aTargetStates = MetaModel::EnumStates(get_class($this));
  2593. $aTargetState = $aTargetStates[$sTargetState];
  2594. $aCurrentState = $aTargetStates[$this->GetState()];
  2595. $aExpectedAttributes = $aTargetState['attribute_list'];
  2596. $aCurrentAttributes = $aCurrentState['attribute_list'];
  2597. $aComputedAttributes = array();
  2598. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  2599. {
  2600. if (!array_key_exists($sAttCode, $aCurrentAttributes))
  2601. {
  2602. $aComputedAttributes[$sAttCode] = $iExpectCode;
  2603. }
  2604. else
  2605. {
  2606. if ( !($aCurrentAttributes[$sAttCode] & (OPT_ATT_HIDDEN|OPT_ATT_READONLY)) )
  2607. {
  2608. $iExpectCode = $iExpectCode & ~(OPT_ATT_MUSTPROMPT|OPT_ATT_MUSTCHANGE); // Already prompted/changed, reset the flags
  2609. }
  2610. //TODO: better check if the attribute is not *null*
  2611. if ( ($iExpectCode & OPT_ATT_MANDATORY) && ($this->Get($sAttCode) != ''))
  2612. {
  2613. $iExpectCode = $iExpectCode & ~(OPT_ATT_MANDATORY); // If the attribute is present, then no need to request its presence
  2614. }
  2615. $aComputedAttributes[$sAttCode] = $iExpectCode;
  2616. }
  2617. $aComputedAttributes[$sAttCode] = $aComputedAttributes[$sAttCode] & ~(OPT_ATT_READONLY|OPT_ATT_HIDDEN); // Don't care about this form now
  2618. if ($aComputedAttributes[$sAttCode] == 0)
  2619. {
  2620. unset($aComputedAttributes[$sAttCode]);
  2621. }
  2622. }
  2623. return $aComputedAttributes;
  2624. }
  2625. }
  2626. ?>