cmdbabstract.class.inc.php 95 KB

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