cmdbabstract.class.inc.php 101 KB

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