cmdbabstract.class.inc.php 99 KB

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