cmdbabstract.class.inc.php 93 KB

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