cmdbabstract.class.inc.php 108 KB

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