cmdbabstract.class.inc.php 98 KB

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