cmdbabstract.class.inc.php 98 KB

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