cmdbabstract.class.inc.php 106 KB

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